Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<div id="root"></div>
              
            
!

CSS

              
                

              
            
!

JS

              
                import React, {
  FC,
  useEffect,
  useRef,
  useState
} from "https://cdn.skypack.dev/react@latest";
import ReactDOM from "https://cdn.skypack.dev/react-dom@latest";
import styled from "https://cdn.skypack.dev/styled-components@latest";

// No styles yet while working on functionality
const Container = styled.div`
  margin-top: 250px;
  width: 100%;
`;

const Wrapper = styled.div`
  width: 50%;
  margin: auto;
`;
const Controls = styled.div``;
const BreakControls = styled.div``;
const SessionControls = styled.div``;
const Clock = styled.div``;
const StyledButton = styled.button``;

type DurationUpdateDirection = "increment" | "decrement";

interface IControlButtons {
  setDuration: (arg0: DurationUpdateDirection) => void;
  category: "session" | "break";
}

const ControlButtons = ({ setDuration, category }: IControlButtons) => {
  return (
    <>
      <StyledButton
        id={category === "session" ? "session-increment" : "break-increment"}
        onClick={() => {
          setDuration("increment");
        }}
      >
        UP
      </StyledButton>
      <StyledButton
        id={category === "session" ? "session-decrement" : "break-decrement"}
        onClick={() => {
          setDuration("decrement");
        }}
      >
        DOWN
      </StyledButton>
    </>
  );
};

// Convert milliseconds into MM:SS string format
const msToClock = (ms: number) => {
  const secondsRemaining = Math.floor(ms / 1000);
  const clockMinutes = Math.floor(secondsRemaining / 60);
  const clockSeconds = secondsRemaining % 60;
  return `${clockMinutes}:${
    clockSeconds > 9 ? clockSeconds : "0" + clockSeconds
  }`;
};

// Convert minutes into milliseconds
const minutesToMs = (minutes: number) => {
  return minutes * 60 * 1000;
};

// Convert milliseconds into minute units
const msToMinutes = (ms: number) => {
  return ms / 1000 / 60;
};

// Based on Dan Abramov's example here:
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/
const useInterval = (callback: () => void, delay: number | null) => {
  const savedCallback = useRef(callback);

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (!delay && delay !== 0) {
      return;
    }

    const id = setInterval(() => savedCallback.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
};

const App: FC = () => {
  const initialSession = minutesToMs(25);
  const initialBreak = minutesToMs(5);

  const [sessionLength, setSessionLength] = useState(initialSession);
  const [breakLength, setBreakLength] = useState(initialBreak);
  const [display, setDisplay] = useState(msToClock(initialSession));
  const [countdownMode, setCountdownMode] = useState<"Session" | "Break">(
    "Session"
  );
  const [activeCountdown, setActiveCountdown] = useState(false);

  const startTime = useRef(0);
  const timeRemaining = useRef<number>(initialSession);
  const audioRef = useRef<HTMLAudioElement>(null);

  const playBeep = () => audioRef.current?.play();

  const stopBeep = () => {
    audioRef.current?.pause();
    if (audioRef.current) audioRef.current.currentTime = 0;
  };

  const startCountdown = () => {
    setActiveCountdown(true);
    startTime.current = Date.now();
  };

  const pauseCountdown = () => {
    setActiveCountdown(false);
    timeRemaining.current =
      startTime.current + timeRemaining.current - Date.now();
  };

  const handleStartPause = () => {
    if (activeCountdown) pauseCountdown();
    else startCountdown();
  };

  const handleRefresh = () => {
    stopBeep();
    setActiveCountdown(false);
    setCountdownMode("Session");
    setSessionLength(initialSession);
    setBreakLength(initialBreak);
    timeRemaining.current = initialSession;
    setDisplay(msToClock(initialSession));
  };

  const handleCountdownEnd = () => {
    playBeep();
    if (countdownMode === "Session") {
      setCountdownMode("Break");
      timeRemaining.current = breakLength;
    } else {
      setCountdownMode("Session");
      timeRemaining.current = sessionLength;
    }
    startCountdown();
  };

  const updateClock = () => {
    const remainingTime =
      startTime.current + timeRemaining.current - Date.now();
    if (remainingTime >= 0) {
      setDisplay(msToClock(remainingTime));
    } else {
      // Attempt to pause for FCC tests
      pauseCountdown();
      setTimeout(handleCountdownEnd, 5000);
    }
  };

  const updateDuration = (
    prevDuration: number,
    direction: DurationUpdateDirection,
    sameMode: boolean
  ) => {
    const newDuration =
      direction === "increment"
        ? prevDuration + minutesToMs(1)
        : prevDuration - minutesToMs(1);

    if (newDuration <= minutesToMs(60) && newDuration > 0) {
      if (!activeCountdown && sameMode) {
        setDisplay(msToClock(newDuration));
        timeRemaining.current = newDuration;
      }
      return newDuration;
    } else return prevDuration;
  };

  const updateBreakDuration = (direction: DurationUpdateDirection) => {
    const sameMode = countdownMode === "Break";
    setBreakLength((prevDuration) =>
      updateDuration(prevDuration, direction, sameMode)
    );
  };

  const updateSessionDuration = (direction: DurationUpdateDirection) => {
    const sameMode = countdownMode === "Session";
    setSessionLength((prevDuration) =>
      updateDuration(prevDuration, direction, sameMode)
    );
  };

  useInterval(updateClock, activeCountdown ? 100 : null);

  return (
    <>
      <Container>
        <Wrapper>
          <h1>25 + 5 Clock</h1>
          <Controls>
            <BreakControls>
              <p id="break-label">
                Break Length:{" "}
                <span id="break-length">{msToMinutes(breakLength)}</span>
              </p>
              <ControlButtons
                category="break"
                setDuration={updateBreakDuration}
              />
            </BreakControls>
            <SessionControls>
              <p id="session-label">
                Session Length:{" "}
                <span id="session-length">{msToMinutes(sessionLength)}</span>
              </p>
              <ControlButtons
                category="session"
                setDuration={updateSessionDuration}
              />
            </SessionControls>
          </Controls>
          <Clock>
            <p id="timer-label">{countdownMode}</p>
            <p id="time-left">{display}</p>
          </Clock>
          <button id="start_stop" onClick={handleStartPause}>
            Start / Pause
          </button>
          <button id="reset" onClick={handleRefresh}>
            Refresh
          </button>
          <button onClick={() => playBeep()}>Play sound</button>
          <audio
            id="beep"
            ref={audioRef}
            preload="auto"
            src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/audio/BeepSound.wav"
          />
        </Wrapper>
      </Container>
    </>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

              
            
!
999px

Console