Created
November 6, 2015 08:51
-
-
Save gregtap/02f1068557741c89f344 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Ember from 'ember'; | |
| const { Service, inject, run } = Ember; | |
| const TWO_HOURS = 2 * 60 * 60 * 1000; | |
| const TWO_DAYS = 2 * 24 * 60 * 60 * 1000; | |
| /** | |
| * Ticking clock service. | |
| * We use this service to sync all our momentjs udpates every second | |
| * and not start one timer for each message. | |
| */ | |
| export default Service.extend({ | |
| store: inject.service('store'), | |
| init: function() { | |
| run.later(this, this.tick, 1000); | |
| }, | |
| tick: function() { | |
| let messageRecords = this.get('store').peekAll('chat-message'); | |
| messageRecords.forEach(message => { | |
| let timeAgoStr = this.timeAgoString(message.get('createdAt')); | |
| message.set('timeago', timeAgoStr); | |
| console.log('TIMESET'); | |
| }); | |
| run.later(this, this.tick, 1000); | |
| }, | |
| /** | |
| * Compare message date to current. If it has been less than 2 hours ago | |
| * we use relative time otherwise we show the day + time. | |
| */ | |
| timeAgoString: function(date) { | |
| var now = new Date(); | |
| // Handles the slight out of sync clocks than can result in | |
| // showing `in a few seconds` instead of `a few seconds ago`. | |
| date = date > now ? now : date; | |
| var elapsedTime = now - date; | |
| if (elapsedTime < TWO_HOURS) { | |
| return moment(date).fromNow(); | |
| } | |
| if (elapsedTime < TWO_DAYS) { | |
| return moment(date).format('ddd, h:m A'); | |
| } | |
| return moment(date).format('MMM, DD h:m A'); | |
| }, | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment