1 | "use strict";
|
2 |
|
3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4 | Object.defineProperty(exports, "__esModule", {
|
5 | value: true
|
6 | });
|
7 | exports["default"] = void 0;
|
8 | var _tslib = require("tslib");
|
9 | var _dayjs = _interopRequireDefault(require("dayjs"));
|
10 | var _react = require("react");
|
11 | var _useLatest = _interopRequireDefault(require("../useLatest"));
|
12 | var _index = require("../utils/index");
|
13 | var calcLeft = function calcLeft(target) {
|
14 | if (!target) {
|
15 | return 0;
|
16 | }
|
17 |
|
18 | var left = (0, _dayjs["default"])(target).valueOf() - Date.now();
|
19 | return left < 0 ? 0 : left;
|
20 | };
|
21 | var parseMs = function parseMs(milliseconds) {
|
22 | return {
|
23 | days: Math.floor(milliseconds / 86400000),
|
24 | hours: Math.floor(milliseconds / 3600000) % 24,
|
25 | minutes: Math.floor(milliseconds / 60000) % 60,
|
26 | seconds: Math.floor(milliseconds / 1000) % 60,
|
27 | milliseconds: Math.floor(milliseconds) % 1000
|
28 | };
|
29 | };
|
30 | var useCountdown = function useCountdown(options) {
|
31 | if (options === void 0) {
|
32 | options = {};
|
33 | }
|
34 | var _a = options || {},
|
35 | leftTime = _a.leftTime,
|
36 | targetDate = _a.targetDate,
|
37 | _b = _a.interval,
|
38 | interval = _b === void 0 ? 1000 : _b,
|
39 | onEnd = _a.onEnd;
|
40 | var target = (0, _react.useMemo)(function () {
|
41 | if ('leftTime' in options) {
|
42 | return (0, _index.isNumber)(leftTime) && leftTime > 0 ? Date.now() + leftTime : undefined;
|
43 | } else {
|
44 | return targetDate;
|
45 | }
|
46 | }, [leftTime, targetDate]);
|
47 | var _c = (0, _tslib.__read)((0, _react.useState)(function () {
|
48 | return calcLeft(target);
|
49 | }), 2),
|
50 | timeLeft = _c[0],
|
51 | setTimeLeft = _c[1];
|
52 | var onEndRef = (0, _useLatest["default"])(onEnd);
|
53 | (0, _react.useEffect)(function () {
|
54 | if (!target) {
|
55 |
|
56 | setTimeLeft(0);
|
57 | return;
|
58 | }
|
59 |
|
60 | setTimeLeft(calcLeft(target));
|
61 | var timer = setInterval(function () {
|
62 | var _a;
|
63 | var targetLeft = calcLeft(target);
|
64 | setTimeLeft(targetLeft);
|
65 | if (targetLeft === 0) {
|
66 | clearInterval(timer);
|
67 | (_a = onEndRef.current) === null || _a === void 0 ? void 0 : _a.call(onEndRef);
|
68 | }
|
69 | }, interval);
|
70 | return function () {
|
71 | return clearInterval(timer);
|
72 | };
|
73 | }, [target, interval]);
|
74 | var formattedRes = (0, _react.useMemo)(function () {
|
75 | return parseMs(timeLeft);
|
76 | }, [timeLeft]);
|
77 | return [timeLeft, formattedRes];
|
78 | };
|
79 | var _default = useCountdown;
|
80 | exports["default"] = _default; |
\ | No newline at end of file |