2021-05-12 06:35:00 +00:00
|
|
|
import React, { PureComponent } from 'react';
|
2021-02-02 22:23:42 +00:00
|
|
|
import { autoBindMethodsForReact } from 'class-autobind-decorator';
|
|
|
|
import { AUTOBIND_CFG } from '../../common/constants';
|
2017-08-10 22:26:06 +00:00
|
|
|
import moment from 'moment';
|
|
|
|
|
2021-05-12 06:35:00 +00:00
|
|
|
interface Props {
|
|
|
|
timestamp: number | Date | string;
|
|
|
|
intervalSeconds?: number;
|
|
|
|
className?: string;
|
|
|
|
capitalize?: boolean;
|
|
|
|
}
|
2017-08-10 22:26:06 +00:00
|
|
|
|
2021-05-12 06:35:00 +00:00
|
|
|
interface State {
|
|
|
|
text: string;
|
|
|
|
}
|
2017-08-10 22:26:06 +00:00
|
|
|
|
2021-02-02 22:23:42 +00:00
|
|
|
@autoBindMethodsForReact(AUTOBIND_CFG)
|
2021-05-12 06:35:00 +00:00
|
|
|
class TimeFromNow extends PureComponent<Props, State> {
|
|
|
|
_interval: NodeJS.Timeout | null = null;
|
2017-08-10 22:26:06 +00:00
|
|
|
|
2021-05-12 06:35:00 +00:00
|
|
|
state: State = {
|
|
|
|
text: '',
|
2017-08-10 22:26:06 +00:00
|
|
|
}
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
_update() {
|
2019-05-09 17:03:39 +00:00
|
|
|
const { timestamp, capitalize } = this.props;
|
|
|
|
let text = moment(timestamp).fromNow();
|
|
|
|
|
|
|
|
// Shorten default case
|
|
|
|
if (text === 'a few seconds ago') {
|
|
|
|
text = 'just now';
|
|
|
|
}
|
|
|
|
|
|
|
|
// Capitalize if needed
|
|
|
|
if (capitalize) {
|
|
|
|
text = text.replace(/\w\S*/g, function(txt) {
|
|
|
|
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-05-12 06:35:00 +00:00
|
|
|
this.setState({
|
|
|
|
text,
|
|
|
|
});
|
2017-08-10 22:26:06 +00:00
|
|
|
}
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
componentDidMount() {
|
2019-04-18 00:50:03 +00:00
|
|
|
const intervalSeconds = this.props.intervalSeconds || 5;
|
|
|
|
this._interval = setInterval(this._update, intervalSeconds * 1000);
|
2021-05-12 06:35:00 +00:00
|
|
|
|
2017-08-10 22:26:06 +00:00
|
|
|
this._update();
|
|
|
|
}
|
|
|
|
|
2020-02-18 17:44:08 +00:00
|
|
|
componentWillUnmount() {
|
2021-05-12 06:35:00 +00:00
|
|
|
if (this._interval !== null) {
|
|
|
|
clearInterval(this._interval);
|
|
|
|
}
|
2017-08-10 22:26:06 +00:00
|
|
|
}
|
|
|
|
|
2018-06-25 17:42:50 +00:00
|
|
|
render() {
|
2019-04-18 00:50:03 +00:00
|
|
|
const { className, timestamp } = this.props;
|
|
|
|
const { text } = this.state;
|
|
|
|
return (
|
|
|
|
<span title={moment(timestamp).toString()} className={className}>
|
|
|
|
{text}
|
|
|
|
</span>
|
|
|
|
);
|
2017-08-10 22:26:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default TimeFromNow;
|