Files
planka/client/src/components/Stopwatch/Stopwatch.jsx

92 lines
2.0 KiB
React
Raw Normal View History

import upperFirst from 'lodash/upperFirst';
2019-08-31 04:07:25 +05:00
import React, { useCallback, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { useForceUpdate, usePrevious } from '../../lib/hooks';
2019-08-31 04:07:25 +05:00
import { formatStopwatch } from '../../utils/stopwatch';
2019-08-31 04:07:25 +05:00
import styles from './Stopwatch.module.scss';
2019-08-31 04:07:25 +05:00
const SIZES = {
TINY: 'tiny',
SMALL: 'small',
MEDIUM: 'medium',
};
const Stopwatch = React.memo(({ as, startedAt, total, size, isDisabled, onClick }) => {
2019-08-31 04:07:25 +05:00
const prevStartedAt = usePrevious(startedAt);
const forceUpdate = useForceUpdate();
const interval = useRef(null);
const start = useCallback(() => {
interval.current = setInterval(() => {
forceUpdate();
}, 1000);
}, [forceUpdate]);
const stop = useCallback(() => {
clearInterval(interval.current);
}, []);
useEffect(() => {
2019-08-31 04:07:25 +05:00
if (prevStartedAt) {
if (!startedAt) {
stop();
}
} else if (startedAt) {
start();
}
}, [startedAt, prevStartedAt, start, stop]);
useEffect(
() => () => {
stop();
},
[stop],
);
const contentNode = (
<span
className={classNames(
styles.wrapper,
styles[`wrapper${upperFirst(size)}`],
startedAt && styles.wrapperActive,
onClick && styles.wrapperHoverable,
)}
>
{formatStopwatch({ startedAt, total })}
2019-08-31 04:07:25 +05:00
</span>
);
const ElementType = as;
2019-08-31 04:07:25 +05:00
return onClick ? (
<ElementType type="button" disabled={isDisabled} className={styles.button} onClick={onClick}>
2019-08-31 04:07:25 +05:00
{contentNode}
</ElementType>
2019-08-31 04:07:25 +05:00
) : (
contentNode
);
});
Stopwatch.propTypes = {
as: PropTypes.elementType,
2019-08-31 04:07:25 +05:00
startedAt: PropTypes.instanceOf(Date),
total: PropTypes.number.isRequired, // eslint-disable-line react/no-unused-prop-types
size: PropTypes.oneOf(Object.values(SIZES)),
isDisabled: PropTypes.bool,
onClick: PropTypes.func,
};
Stopwatch.defaultProps = {
as: 'button',
2019-08-31 04:07:25 +05:00
startedAt: undefined,
size: SIZES.MEDIUM,
isDisabled: false,
onClick: undefined,
};
export default Stopwatch;