-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime-elements.js
525 lines (466 loc) · 14.4 KB
/
time-elements.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
(function() {
'use strict';
// Shout out to https://github.com/basecamp/local_time/blob/master/app/assets/javascripts/local_time.js.coffee
var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
function pad(num) {
return ('0' + num).slice(-2);
}
function strftime(time, formatString) {
var day = time.getDay();
var date = time.getDate();
var month = time.getMonth();
var year = time.getFullYear();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
return formatString.replace(/%([%aAbBcdeHIlmMpPSwyYZz])/g, function(_arg) {
var match;
var modifier = _arg[1];
switch (modifier) {
case '%':
return '%';
case 'a':
return weekdays[day].slice(0, 3);
case 'A':
return weekdays[day];
case 'b':
return months[month].slice(0, 3);
case 'B':
return months[month];
case 'c':
return time.toString();
case 'd':
return pad(date);
case 'e':
return date;
case 'H':
return pad(hour);
case 'I':
return pad(strftime(time, '%l'));
case 'l':
if (hour === 0 || hour === 12) {
return 12;
} else {
return (hour + 12) % 12;
}
break;
case 'm':
return pad(month + 1);
case 'M':
return pad(minute);
case 'p':
if (hour > 11) {
return 'PM';
} else {
return 'AM';
}
break;
case 'P':
if (hour > 11) {
return 'pm';
} else {
return 'am';
}
break;
case 'S':
return pad(second);
case 'w':
return day;
case 'y':
return pad(year % 100);
case 'Y':
return year;
case 'Z':
match = time.toString().match(/\((\w+)\)$/);
return match ? match[1] : '';
case 'z':
match = time.toString().match(/\w([+-]\d\d\d\d) /);
return match ? match[1] : '';
}
});
}
function RelativeTime(date) {
this.date = date;
}
RelativeTime.prototype.toString = function() {
var ago = this.timeElapsed();
if (ago) {
return ago;
} else {
return 'on ' + this.formatDate();
}
};
RelativeTime.prototype.timeElapsed = function() {
var ms = new Date().getTime() - this.date.getTime();
var sec = Math.round(ms / 1000);
var min = Math.round(sec / 60);
var hr = Math.round(min / 60);
var day = Math.round(hr / 24);
if (ms < 0) {
return 'just now';
} else if (sec < 10) {
return 'just now';
} else if (sec < 45) {
return sec + ' seconds ago';
} else if (sec < 90) {
return 'a minute ago';
} else if (min < 45) {
return min + ' minutes ago';
} else if (min < 90) {
return 'an hour ago';
} else if (hr < 24) {
return hr + ' hours ago';
} else if (hr < 36) {
return 'a day ago';
} else if (day < 30) {
return day + ' days ago';
} else {
return null;
}
};
RelativeTime.prototype.timeAgo = function() {
var ms = new Date().getTime() - this.date.getTime();
var sec = Math.round(ms / 1000);
var min = Math.round(sec / 60);
var hr = Math.round(min / 60);
var day = Math.round(hr / 24);
var month = Math.round(day / 30);
var year = Math.round(month / 12);
if (ms < 0) {
return 'just now';
} else if (sec < 10) {
return 'just now';
} else if (sec < 45) {
return sec + ' seconds ago';
} else if (sec < 90) {
return 'a minute ago';
} else if (min < 45) {
return min + ' minutes ago';
} else if (min < 90) {
return 'an hour ago';
} else if (hr < 24) {
return hr + ' hours ago';
} else if (hr < 36) {
return 'a day ago';
} else if (day < 30) {
return day + ' days ago';
} else if (day < 45) {
return 'a month ago';
} else if (month < 12) {
return month + ' months ago';
} else if (month < 18) {
return 'a year ago';
} else {
return year + ' years ago';
}
};
RelativeTime.prototype.microTimeAgo = function() {
var ms = new Date().getTime() - this.date.getTime();
var sec = ms / 1000;
var min = sec / 60;
var hr = min / 60;
var day = hr / 24;
var month = day / 30;
var year = month / 12;
if (min < 1) {
return '1m';
} else if (min < 60) {
return Math.round(min) + 'm';
} else if (hr < 24) {
return Math.round(hr) + 'h';
} else if (day < 365) {
return Math.round(day) + 'd';
} else {
return Math.round(year) + 'y';
}
};
// Private: Determine if the day should be formatted before the month name in
// the user's current locale. For example, `9 Jun` for en-GB and `Jun 9`
// for en-US.
//
// Returns true if the day appears before the month.
function isDayFirst() {
if (dayFirst !== null) {
return dayFirst;
}
if (!('Intl' in window)) {
return false;
}
var options = {day: 'numeric', month: 'short'};
var formatter = new window.Intl.DateTimeFormat(undefined, options);
var output = formatter.format(new Date(0));
dayFirst = !!output.match(/^\d/);
return dayFirst;
}
var dayFirst = null;
// Private: Determine if the year should be separated from the month and day
// with a comma. For example, `9 Jun 2014` in en-GB and `Jun 9, 2014` in en-US.
//
// Returns true if the date needs a separator.
function isYearSeparator() {
if (yearSeparator !== null) {
return yearSeparator;
}
if (!('Intl' in window)) {
return true;
}
var options = {day: 'numeric', month: 'short', year: 'numeric'};
var formatter = new window.Intl.DateTimeFormat(undefined, options);
var output = formatter.format(new Date(0));
yearSeparator = !!output.match(/\d,/);
return yearSeparator;
}
var yearSeparator = null;
// Private: Determine if the date occurs in the same year as today's date.
//
// date - The Date to test.
//
// Returns true if it's this year.
function isThisYear(date) {
var now = new Date();
return now.getUTCFullYear() === date.getUTCFullYear();
}
RelativeTime.prototype.formatDate = function() {
var format = isDayFirst() ? '%e %b' : '%b %e';
if (!isThisYear(this.date)) {
format += isYearSeparator() ? ', %Y': ' %Y';
}
return strftime(this.date, format);
};
RelativeTime.prototype.formatTime = function() {
if ('Intl' in window) {
var formatter = new window.Intl.DateTimeFormat(undefined, {hour: 'numeric', minute: '2-digit'});
return formatter.format(this.date);
} else {
return strftime(this.date, '%l:%M%P');
}
};
// Internal: Array tracking all elements attached to the document that need
// to be updated every minute.
var nowElements = [];
// Internal: Timer ID for `updateNowElements` interval.
var updateNowElementsId;
// Internal: Install a timer to refresh all attached relative-time elements every
// minute.
function updateNowElements() {
var time, i, len;
for (i = 0, len = nowElements.length; i < len; i++) {
time = nowElements[i];
time.textContent = time.getFormattedDate();
}
}
var ExtendedTimePrototype;
if ('HTMLTimeElement' in window) {
ExtendedTimePrototype = Object.create(window.HTMLTimeElement.prototype);
} else {
ExtendedTimePrototype = Object.create(window.HTMLElement.prototype);
}
// Internal: Refresh the time element's formatted date when an attribute changes.
//
// Returns nothing.
ExtendedTimePrototype.attributeChangedCallback = function(attrName, oldValue, newValue) {
if (attrName === 'datetime') {
var millis = Date.parse(newValue);
this._date = isNaN(millis) ? null : new Date(millis);
}
var title = this.getFormattedTitle();
if (title) {
this.setAttribute('title', title);
}
var text = this.getFormattedDate();
if (text) {
this.textContent = text;
}
};
// Internal: Format the ISO 8601 timestamp according to the user agent's
// locale-aware formatting rules. The element's existing `title` attribute
// value takes precedence over this custom format.
//
// Returns a formatted time String.
ExtendedTimePrototype.getFormattedTitle = function() {
if (!this._date) {
return;
}
if (this.hasAttribute('title')) {
return this.getAttribute('title');
}
if ('Intl' in window) {
var options = {day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: '2-digit', timeZoneName: 'short'};
var formatter = new window.Intl.DateTimeFormat(undefined, options);
return formatter.format(this._date);
}
return this._date.toLocaleString();
};
var RelativeTimePrototype = Object.create(ExtendedTimePrototype);
RelativeTimePrototype.createdCallback = function() {
var value = this.getAttribute('datetime');
if (value) {
this.attributeChangedCallback('datetime', null, value);
}
};
RelativeTimePrototype.getFormattedDate = function() {
if (this._date) {
return new RelativeTime(this._date).toString();
}
};
RelativeTimePrototype.attachedCallback = function() {
nowElements.push(this);
if (!updateNowElementsId) {
updateNowElements();
updateNowElementsId = setInterval(updateNowElements, 60 * 1000);
}
};
RelativeTimePrototype.detachedCallback = function() {
var ix = nowElements.indexOf(this);
if (ix !== -1) {
nowElements.splice(ix, 1);
}
if (!nowElements.length) {
if (updateNowElementsId) {
clearInterval(updateNowElementsId);
updateNowElementsId = null;
}
}
};
var TimeAgoPrototype = Object.create(RelativeTimePrototype);
TimeAgoPrototype.getFormattedDate = function() {
if (this._date) {
var format = this.getAttribute('format');
if (format === 'micro') {
return new RelativeTime(this._date).microTimeAgo();
} else {
return new RelativeTime(this._date).timeAgo();
}
}
};
var LocalTimePrototype = Object.create(ExtendedTimePrototype);
LocalTimePrototype.createdCallback = function() {
var value;
if (value = this.getAttribute('datetime')) {
this.attributeChangedCallback('datetime', null, value);
}
if (value = this.getAttribute('format')) {
this.attributeChangedCallback('format', null, value);
}
};
// Formats the element's date, in the user's current locale, according to
// the formatting attribute values. Values are not passed straight through to
// an Intl.DateTimeFormat instance so that weekday and month names are always
// displayed in English, for now.
//
// Supported attributes are:
//
// weekday - "short", "long"
// year - "numeric", "2-digit"
// month - "short", "long"
// day - "numeric", "2-digit"
// hour - "numeric", "2-digit"
// minute - "numeric", "2-digit"
// second - "numeric", "2-digit"
//
// Returns a formatted time String.
LocalTimePrototype.getFormattedDate = function() {
if (!this._date) {
return;
}
var date = formatDate(this) || '';
var time = formatTime(this) || '';
return (date + ' ' + time).trim();
};
// Private: Format a date according to the `weekday`, `day`, `month`,
// and `year` attribute values.
//
// This doesn't use Intl.DateTimeFormat to avoid creating text in the user's
// language when the majority of the surrounding text is in English. There's
// currently no way to separate the language from the format in Intl.
//
// el - The local-time element to format.
//
// Returns a date String or null if no date formats are provided.
function formatDate(el) {
// map attribute values to strftime
var props = {
weekday: {
'short': '%a',
'long': '%A'
},
day: {
'numeric': '%e',
'2-digit': '%d'
},
month: {
'short': '%b',
'long': '%B'
},
year: {
'numeric': '%Y',
'2-digit': '%y'
}
};
// build a strftime format string
var format = isDayFirst() ? 'weekday day month year' : 'weekday month day, year';
for (var prop in props) {
var value = props[prop][el.getAttribute(prop)];
format = format.replace(prop, value || '');
}
// clean up year separator comma
format = format.replace(/(\s,)|(,\s$)/, '');
// squeeze spaces from final string
return strftime(el._date, format).replace(/\s+/, ' ').trim();
}
// Private: Format a time according to the `hour`, `minute`, and `second`
// attribute values.
//
// el - The local-time element to format.
//
// Returns a time String or null if no time formats are provided.
function formatTime(el) {
// retrieve format settings from attributes
var options = {
hour: el.getAttribute('hour'),
minute: el.getAttribute('minute'),
second: el.getAttribute('second')
};
// remove unset format attributes
for (var opt in options) {
if (!options[opt]) {
delete options[opt];
}
}
// no time format attributes provided
if (Object.keys(options).length === 0) {
return;
}
// locale-aware formatting of 24 or 12 hour times
if ('Intl' in window) {
var formatter = new window.Intl.DateTimeFormat(undefined, options);
return formatter.format(el._date);
}
// fall back to strftime for non-Intl browsers
var timef = options.second ? '%H:%M:%S' : '%H:%M';
return strftime(el._date, timef);
}
// Public: RelativeTimeElement constructor.
//
// var time = new RelativeTimeElement()
// # => <time is='relative-time'></time>
//
window.RelativeTimeElement = document.registerElement('relative-time', {
prototype: RelativeTimePrototype,
'extends': 'time'
});
window.TimeAgoElement = document.registerElement('time-ago', {
prototype: TimeAgoPrototype,
'extends': 'time'
});
// Public: LocalTimeElement constructor.
//
// var time = new LocalTimeElement()
// # => <time is='local-time'></time>
//
window.LocalTimeElement = document.registerElement('local-time', {
prototype: LocalTimePrototype,
'extends': 'time'
});
})();