3 var Marionette = require('backbone.marionette');
4 var behaviourLookup = require('./lookup');
5 var timeFormat = require('gitter-web-shared/time/time-format');
7 var MS_IN_SECOND = 1000;
8 var MS_IN_MINUTE = 60 * MS_IN_SECOND;
9 var MS_IN_HOUR = 60 * MS_IN_MINUTE;
10 var MS_IN_DAY = 24 * MS_IN_HOUR;
13 * If the supplied time is 'today' from the persepective of the
14 * user's local timezone, returns the number of milliseconds until
15 * midnight in the user's local timezone.
18 * At midnight, will return 86400k
19 * At noon, will return 43200k
20 * At 11pm, will return 3600k
21 * At 11:59:59.000, will return 1k
23 * Currently, does not handle daylight savings changeover days.
25 function timeRemainingTodayLocalTZ(time) {
29 var nowYear = now.getFullYear();
30 var nowMonth = now.getMonth();
31 var nowDay = now.getDate();
33 if (time instanceof Date) {
35 time.getDate() === nowDay &&
36 time.getMonth() === nowMonth &&
37 time.getFullYear() === nowYear
41 time.getHours() * MS_IN_HOUR +
42 time.getMinutes() * MS_IN_MINUTE +
43 time.getSeconds() * MS_IN_SECOND +
44 time.getMilliseconds()
49 // Deal with moment dates
51 if (time.date() === nowDay && time.month() === nowMonth && time.year() === nowYear) {
54 time.hour() * MS_IN_HOUR +
55 time.minute() * MS_IN_MINUTE +
56 time.second() * MS_IN_SECOND +
65 var Behavior = Marionette.Behavior.extend({
77 modelEvents: function() {
79 result['change:' + this.options.modelAttribute] = 'onTimeChange';
83 initialize: function() {
87 onTimeChange: function(model) {
89 clearTimeout(this.timer);
93 var time = model.get(this.options.modelAttribute);
95 var timeRemaining = timeRemainingTodayLocalTZ(time);
96 if (timeRemaining > 0) {
97 // Add one millisecond onto the time to make sure that it's definitely
99 this.timer = setTimeout(this.onTimeChange.bind(this, model), timeRemaining + 1);
102 this.renderTime(time);
105 renderTime: function(time) {
106 var timeElement = this.ui.time[0];
108 var text = timeFormat(time, { compact: this.options.compact });
109 timeElement.textContent = text;
113 onDestroy: function() {
115 clearTimeout(this.timer);
121 behaviourLookup.register('TimeAgo', Behavior);
122 module.exports = Behavior;