-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
89 lines (70 loc) · 2.01 KB
/
index.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
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
'use strict';
var PropTypes = require('prop-types');
var createReactClass = require('create-react-class');
var timeAgo = require('damals');
var counterpart = require('counterpart');
var strftime = require('counterpart/strftime');
var assign = require('object-assign');
var DOM = require('react-dom-factories');
var toString = Object.prototype.toString;
function isString(value) {
return toString.call(value) === '[object String]';
}
function isNumber(value) {
return toString.call(value) === '[object Number]';
}
var Ago = createReactClass({
displayName: 'Ago',
ticker: null,
propTypes: {
date: PropTypes.oneOfType([
PropTypes.instanceOf(Date),
PropTypes.string,
PropTypes.number
]),
tooltipFormat: PropTypes.string,
autoUpdate: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.number
])
},
getDefaultProps: function() {
return {
date: new Date(),
tooltipFormat: 'default',
autoUpdate: 0
};
},
componentDidMount: function() {
if (this.props.autoUpdate) {
var delay = isNumber(this.props.autoUpdate) ? this.props.autoUpdate * 1000 : 2600;
this.ticker = setInterval(this.invalidate, delay);
}
counterpart.onLocaleChange(this.invalidate);
},
componentWillUnmount: function() {
if (this.ticker) {
clearInterval(this.ticker);
this.ticker = null;
}
counterpart.offLocaleChange(this.invalidate);
},
invalidate: function() {
this.forceUpdate();
},
render: function() {
var date = this.props.date;
if (isString(date) || isNumber(date)) {
date = new Date(date);
}
var content = timeAgo(date);
var dateTime = strftime(date, '%Y-%m-%dT%H:%M:%S%z');
var title = counterpart.localize(date, { format: this.props.tooltipFormat });
var props = assign({}, this.props, { dateTime: dateTime, title: title });
delete props.date;
delete props.tooltipFormat;
delete props.autoUpdate;
return DOM.time(props, content);
}
});
module.exports = Ago;