forked from dzhurley/preact-timeago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeago.js
46 lines (35 loc) · 1.28 KB
/
timeago.js
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
const { h, Component } = require('preact');
const timeago = require('timeago.js');
class TimeAgo extends Component {
componentWillMount() {
this.instance = timeago();
}
componentDidMount() {
this.renderTimeAgo();
}
componentDidUpdate() {
this.renderTimeAgo();
}
componentWillUnmount() {
this.instance.cancel();
}
renderTimeAgo() {
const { datetime, live=false } = this.props;
this.instance.cancel();
if (!this.base || (live === false)) return;
// When used in combination with jsdom for headless testing, we need to ensure that
// `dataset` exists on the base until https://github.com/tmpvar/jsdom/issues/961 is
// resolved, as under the covers timeago.js checks `dataset` before `getAttribute`.
//
// TODO: pull request timeago.js to reorder checks on `getAttribute`/`dataset`.
if (typeof this.base.dataset == 'undefined') {
this.base.dataset = {};
}
this.base.setAttribute('datetime', datetime.getTime ? datetime.getTime() : datetime);
this.instance.render(this.base);
}
render(props) {
return h('time', { 'class': props.class }, this.instance.format(props.datetime));
}
}
module.exports = TimeAgo;