51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { useEffect } from 'react';
|
|
import { useStopwatch } from 'react-timer-hook';
|
|
|
|
import FormatMillisecond, { FormatMilliSecondProps } from './FormatMilliSecond';
|
|
|
|
const setStopWatchOffset = (time: string) => {
|
|
const providedTime = new Date(time);
|
|
const currentTime = new Date();
|
|
const timeDifference = currentTime.getTime() - providedTime.getTime();
|
|
currentTime.setMilliseconds(currentTime.getMilliseconds() + timeDifference);
|
|
return currentTime;
|
|
};
|
|
|
|
/**
|
|
* Props for the Stopwatch component.
|
|
* @interface StopwatchProps
|
|
* @property {Date} offsetTimestamp - The initial timestamp for the stopwatch.
|
|
* @property {boolean} isPaused - Whether the stopwatch is paused.
|
|
*/
|
|
interface StopwatchProps extends Omit<FormatMilliSecondProps, 'time'> {
|
|
offsetTimestamp: Date;
|
|
isPaused: boolean;
|
|
}
|
|
|
|
/**
|
|
* A stopwatch component that tracks elapsed time.
|
|
*
|
|
* @component
|
|
* @param {StopwatchProps} props - The props for the Stopwatch component.
|
|
* @returns {React.ReactElement} A stopwatch element.
|
|
*
|
|
* @example
|
|
* ```tsx
|
|
* <Stopwatch offsetTimestamp={new Date()} isPaused={false} />
|
|
* ```
|
|
*/
|
|
const Stopwatch = ({ offsetTimestamp, isPaused, ...props }: StopwatchProps) => {
|
|
const { totalSeconds, pause, start } = useStopwatch({
|
|
autoStart: true,
|
|
offsetTimestamp: offsetTimestamp,
|
|
});
|
|
|
|
useEffect(() => {
|
|
isPaused ? pause() : start();
|
|
}, [isPaused]);
|
|
|
|
return <FormatMillisecond time={totalSeconds * 1000} {...props} />;
|
|
};
|
|
|
|
export { setStopWatchOffset, Stopwatch };
|