Permalink
Browse files

Step 6.20: Add group by date to the UI

  • Loading branch information...
dotansimha authored and darkbasic committed Jan 24, 2017
1 parent c34886a commit b8dcd980dca215672cc0a4901771976508d9d80c
Showing with 45 additions and 16 deletions.
  1. +45 −16 src/pages/messages/messages.ts
@@ -1,9 +1,10 @@
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Chat, Message, MessageType } from 'api/models';
import { Observable } from 'rxjs';
import { Messages } from 'api/collections';
import { MeteorObservable } from 'meteor-rxjs';
import * as moment from 'moment';
import * as _ from 'lodash';
@Component({
selector: 'messages-page',
@@ -13,7 +14,7 @@ export class MessagesPage implements OnInit, OnDestroy {
selectedChat: Chat;
title: string;
picture: string;
messages: Observable<Message[]>;
messagesDayGroups;
message: string = '';
autoScroller: MutationObserver;
scrollOffset = 0;
@@ -41,26 +42,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));

0 comments on commit b8dcd98

Please sign in to comment.