Timer.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use client";
  2. var __rest = this && this.__rest || function (s, e) {
  3. var t = {};
  4. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  5. if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  6. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  7. }
  8. return t;
  9. };
  10. import * as React from 'react';
  11. import { useEvent } from 'rc-util';
  12. import raf from "rc-util/es/raf";
  13. import { cloneElement } from '../_util/reactNode';
  14. import Statistic from './Statistic';
  15. import { formatCounter } from './utils';
  16. function getTime(value) {
  17. return new Date(value).getTime();
  18. }
  19. const StatisticTimer = props => {
  20. const {
  21. value,
  22. format = 'HH:mm:ss',
  23. onChange,
  24. onFinish,
  25. type
  26. } = props,
  27. rest = __rest(props, ["value", "format", "onChange", "onFinish", "type"]);
  28. const down = type === 'countdown';
  29. // We reuse state here to do same as `forceUpdate`
  30. const [showTime, setShowTime] = React.useState(null);
  31. // ======================== Update ========================
  32. const update = useEvent(() => {
  33. const now = Date.now();
  34. const timestamp = getTime(value);
  35. setShowTime({});
  36. const timeDiff = !down ? now - timestamp : timestamp - now;
  37. onChange === null || onChange === void 0 ? void 0 : onChange(timeDiff);
  38. // Only countdown will trigger `onFinish`
  39. if (down && timestamp < now) {
  40. onFinish === null || onFinish === void 0 ? void 0 : onFinish();
  41. return false;
  42. }
  43. return true;
  44. });
  45. // Effect trigger
  46. React.useEffect(() => {
  47. let rafId;
  48. const clear = () => raf.cancel(rafId);
  49. const rafUpdate = () => {
  50. rafId = raf(() => {
  51. if (update()) {
  52. rafUpdate();
  53. }
  54. });
  55. };
  56. rafUpdate();
  57. return clear;
  58. }, [value, down]);
  59. React.useEffect(() => {
  60. setShowTime({});
  61. }, []);
  62. // ======================== Format ========================
  63. const formatter = (formatValue, config) => showTime ? formatCounter(formatValue, Object.assign(Object.assign({}, config), {
  64. format
  65. }), down) : '-';
  66. const valueRender = node => cloneElement(node, {
  67. title: undefined
  68. });
  69. // ======================== Render ========================
  70. return /*#__PURE__*/React.createElement(Statistic, Object.assign({}, rest, {
  71. value: value,
  72. valueRender: valueRender,
  73. formatter: formatter
  74. }));
  75. };
  76. export default StatisticTimer;