Countdown.js
2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import _extends from "@babel/runtime/helpers/extends";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import * as React from 'react';
import Statistic from './Statistic';
import { formatCountdown } from './utils';
import { cloneElement } from '../_util/reactNode';
var REFRESH_INTERVAL = 1000 / 30;
function getTime(value) {
return new Date(value).getTime();
}
var Countdown = /*#__PURE__*/function (_React$Component) {
_inherits(Countdown, _React$Component);
var _super = _createSuper(Countdown);
function Countdown() {
var _this;
_classCallCheck(this, Countdown);
_this = _super.apply(this, arguments);
_this.syncTimer = function () {
var value = _this.props.value;
var timestamp = getTime(value);
if (timestamp >= Date.now()) {
_this.startTimer();
} else {
_this.stopTimer();
}
};
_this.startTimer = function () {
if (_this.countdownId) return;
_this.countdownId = window.setInterval(function () {
_this.forceUpdate();
}, REFRESH_INTERVAL);
};
_this.stopTimer = function () {
var _this$props = _this.props,
onFinish = _this$props.onFinish,
value = _this$props.value;
if (_this.countdownId) {
clearInterval(_this.countdownId);
_this.countdownId = undefined;
var timestamp = getTime(value);
if (onFinish && timestamp < Date.now()) {
onFinish();
}
}
};
_this.formatCountdown = function (value, config) {
var format = _this.props.format;
return formatCountdown(value, _extends(_extends({}, config), {
format: format
}));
}; // Countdown do not need display the timestamp
_this.valueRender = function (node) {
return cloneElement(node, {
title: undefined
});
};
return _this;
}
_createClass(Countdown, [{
key: "componentDidMount",
value: function componentDidMount() {
this.syncTimer();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
this.syncTimer();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.stopTimer();
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement(Statistic, _extends({
valueRender: this.valueRender
}, this.props, {
formatter: this.formatCountdown
}));
}
}]);
return Countdown;
}(React.Component);
Countdown.defaultProps = {
format: 'HH:mm:ss'
};
export default Countdown;