chowa
Version:
UI component library based on React
93 lines (92 loc) • 3.17 kB
JavaScript
/**
* @license chowa v1.1.3
*
* Copyright (c) Chowa Techonlogies Co.,Ltd.(http://www.chowa.cn).
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
;
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const PropTypes = require("prop-types");
const base_statistic_1 = require("./base-statistic");
const moment = require("moment");
const utils_1 = require("../utils");
function countdownFormat(stamp) {
const cf = {
value: moment.duration(stamp),
format: (tpl) => {
const tokenDefs = {
years: /\*?[Yy]+/,
months: /\*?M+/,
weeks: /\*?[Ww]+/,
days: /\*?[Dd]+/,
hours: /\*?[Hh]+/,
minutes: /\*?m+/,
seconds: /\*?s+/,
milliseconds: /\*?S+/
};
let str = tpl;
for (const token in tokenDefs) {
if (str.match(tokenDefs[token])) {
str = str.replace(tokenDefs[token], utils_1.padZero(cf.value[token](), token === 'milliseconds' ? 3 : 2));
}
}
return str;
}
};
return cf;
}
class Countdown extends React.PureComponent {
constructor(props) {
super(props);
this.timer = null;
this.state = {
result: moment.isMoment(props.value)
? moment().valueOf() - props.value.valueOf()
: props.value - Date.now()
};
}
componentDidMount() {
const { refresInterval } = this.props;
if (this.state.result > 0) {
this.timer = window.setInterval(() => {
const { result } = this.state;
const finished = result <= refresInterval;
this.setState({
result: finished ? 0 : result - refresInterval
});
if (finished) {
clearInterval(this.timer);
this.timer = null;
if (this.props.onFinish) {
this.props.onFinish();
}
}
}, refresInterval);
}
}
componentWillUnmount() {
if (this.timer !== null) {
clearInterval(this.timer);
}
}
render() {
const { result } = this.state;
const { formatter } = this.props;
const valueNode = (React.createElement("span", { className: utils_1.preClass('statistic-value-moment') }, formatter(countdownFormat(result))));
return (React.createElement(base_statistic_1.default, Object.assign({ valueNode: valueNode }, utils_1.omitProps(this.props, ['value', 'formatter']))));
}
}
Countdown.propTypes = {
value: PropTypes.oneOfType([PropTypes.number, PropTypes.object]).isRequired,
formatter: PropTypes.func,
onFinish: PropTypes.func,
refresInterval: PropTypes.number
};
Countdown.defaultProps = {
formatter: (cf) => cf.format('HH : mm : ss . SS'),
refresInterval: 40
};
exports.default = Countdown;