Skip to content

Commit

Permalink
Step 6.19: Add group by date to the UI
Browse files Browse the repository at this point in the history
  • Loading branch information
DAB0mB committed Feb 13, 2017
1 parent 8de8ff5 commit 58e8de4
Showing 1 changed file with 45 additions and 15 deletions.
60 changes: 45 additions & 15 deletions client/imports/pages/messages/messages.ts
@@ -1,6 +1,8 @@
import { Component, OnDestroy, OnInit, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { MeteorObservable } from 'meteor-rxjs';
import { _ } from 'meteor/underscore';
import * as Moment from 'moment';
import { Observable } from 'rxjs';
import { Messages } from '../../../../imports/collections';
import { Chat, Message, MessageType } from '../../../../imports/models';
Expand All @@ -13,7 +15,7 @@ export class MessagesPage implements OnInit, OnDestroy {
selectedChat: Chat;
title: string;
picture: string;
messages: Observable<Message[]>;
messagesDayGroups;
message: string = '';
autoScroller: MutationObserver;
scrollOffset = 0;
Expand Down Expand Up @@ -41,26 +43,54 @@ export class MessagesPage implements OnInit, OnDestroy {

ngOnInit() {
this.autoScroller = this.autoScroll();

let isEven = false;

this.messages = Messages.find(
{chatId: this.selectedChat._id},
{sort: {createdAt: 1}}
).map((messages: Message[]) => {
messages.forEach((message: Message) => {
message.ownership = isEven ? 'mine' : 'other';
isEven = !isEven;
});

return messages;
});
this.subscribeMessages();
}

ngOnDestroy() {
this.autoScroller.disconnect();
}

subscribeMessages() {
this.scrollOffset = this.scroller.scrollHeight;
this.messagesDayGroups = this.findMessagesDayGroups();
}

findMessagesDayGroups() {
let isEven = false;

return Messages.find({
chatId: this.selectedChat._id
}, {
sort: { createdAt: 1 }
})
.map((messages: Message[]) => {
const format = 'D MMMM Y';

// Compose missing data that we would like to show in the view
messages.forEach((message) => {
message.ownership = isEven ? 'mine' : 'other';
isEven = !isEven;

return message;
});

// Group by creation day
const groupedMessages = _.groupBy(messages, (message) => {
return Moment(message.createdAt).format(format);
});

// Transform dictionary into an array since Angular's view engine doesn't know how
// to iterate through it
return Object.keys(groupedMessages).map((timestamp: string) => {
return {
timestamp: timestamp,
messages: groupedMessages[timestamp],
today: Moment().format(format) === timestamp
};
});
});
}

autoScroll(): MutationObserver {
const autoScroller = new MutationObserver(this.scrollDown.bind(this));

Expand Down

0 comments on commit 58e8de4

Please sign in to comment.