/
messages.ts
269 lines (232 loc) · 7.81 KB
/
messages.ts
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
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { NavParams, PopoverController } from 'ionic-angular';
import { Chat, Message, MessageType, Location } from 'api/models';
import { Messages } from 'api/collections';
import { MeteorObservable } from 'meteor-rxjs';
import * as moment from 'moment';
import { _ } from 'meteor/underscore';
import { MessagesOptionsComponent } from './messages-options';
import { Subscription, Observable, Subscriber } from 'rxjs';
import { MessagesAttachmentsComponent } from './messages-attachments';
import { PictureService } from '../../services/picture';
@Component({
selector: 'messages-page',
templateUrl: 'messages.html'
})
export class MessagesPage implements OnInit, OnDestroy {
selectedChat: Chat;
title: string;
picture: string;
messagesDayGroups;
message: string = '';
autoScroller: MutationObserver;
scrollOffset = 0;
senderId: string;
loadingMessages: boolean;
messagesComputation: Subscription;
messagesBatchCounter: number = 0;
constructor(
navParams: NavParams,
private el: ElementRef,
private popoverCtrl: PopoverController,
private pictureService: PictureService
) {
this.selectedChat = <Chat>navParams.get('chat');
this.title = this.selectedChat.title;
this.picture = this.selectedChat.picture;
this.senderId = Meteor.userId();
}
private get messagesPageContent(): Element {
return this.el.nativeElement.querySelector('.messages-page-content');
}
private get messagesList(): Element {
return this.messagesPageContent.querySelector('.messages');
}
private get scroller(): Element {
return this.messagesList.querySelector('.scroll-content');
}
ngOnInit() {
this.autoScroller = this.autoScroll();
this.subscribeMessages();
// Get total messages count in database so we can have an indication of when to
// stop the auto-subscriber
MeteorObservable.call('countMessages').subscribe((messagesCount: number) => {
Observable
// Chain every scroll event
.fromEvent(this.scroller, 'scroll')
// Remove the scroll listener once all messages have been fetched
.takeUntil(this.autoRemoveScrollListener(messagesCount))
// Filter event handling unless we're at the top of the page
.filter(() => !this.scroller.scrollTop)
// Prohibit parallel subscriptions
.filter(() => !this.loadingMessages)
// Invoke the messages subscription once all the requirements have been met
.forEach(() => this.subscribeMessages());
});
}
ngOnDestroy() {
this.autoScroller.disconnect();
}
// Subscribes to the relevant set of messages
subscribeMessages(): void {
// A flag which indicates if there's a subscription in process
this.loadingMessages = true;
// A custom offset to be used to re-adjust the scrolling position once
// new dataset is fetched
this.scrollOffset = this.scroller.scrollHeight;
MeteorObservable.subscribe('messages',
this.selectedChat._id,
++this.messagesBatchCounter
).subscribe(() => {
// Keep tracking changes in the dataset and re-render the view
if (!this.messagesComputation) {
this.messagesComputation = this.autorunMessages();
}
// Allow incoming subscription requests
this.loadingMessages = false;
});
}
// Detects changes in the messages dataset and re-renders the view
autorunMessages(): Subscription {
return MeteorObservable.autorun().subscribe(() => {
this.messagesDayGroups = this.findMessagesDayGroups();
});
}
// Removes the scroll listener once all messages from the past were fetched
autoRemoveScrollListener<T>(messagesCount: number): Observable<T> {
return Observable.create((observer: Subscriber<T>) => {
Messages.find().subscribe({
next: (messages) => {
// Once all messages have been fetched
if (messagesCount !== messages.length) {
return;
}
// Signal to stop listening to the scroll event
observer.next();
// Finish the observation to prevent unnecessary calculations
observer.complete();
},
error: (e) => {
observer.error(e);
}
});
});
}
showOptions(): void {
const popover = this.popoverCtrl.create(MessagesOptionsComponent, {
chat: this.selectedChat
}, {
cssClass: 'options-popover messages-options-popover'
});
popover.present();
}
findMessagesDayGroups() {
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 = this.senderId == message.senderId ? 'mine' : 'other';
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));
autoScroller.observe(this.messagesList, {
childList: true,
subtree: true
});
return autoScroller;
}
scrollDown(): void {
// Don't scroll down if messages subscription is being loaded
if (this.loadingMessages) {
return;
}
// Scroll down and apply specified offset
this.scroller.scrollTop = this.scroller.scrollHeight - this.scrollOffset;
// Zero offset for next invocation
this.scrollOffset = 0;
}
onInputKeypress({ keyCode }: KeyboardEvent): void {
if (keyCode === 13) {
this.sendTextMessage();
}
}
sendTextMessage(): void {
// If message was yet to be typed, abort
if (!this.message) {
return;
}
MeteorObservable.call('addMessage', MessageType.TEXT,
this.selectedChat._id,
this.message
).zone().subscribe(() => {
// Zero the input field
this.message = '';
});
}
sendLocationMessage(location: Location): void {
MeteorObservable.call('addMessage', MessageType.LOCATION,
this.selectedChat._id,
`${location.lat},${location.lng},${location.zoom}`
).zone().subscribe(() => {
// Zero the input field
this.message = '';
});
}
showAttachments(): void {
const popover = this.popoverCtrl.create(MessagesAttachmentsComponent, {
chat: this.selectedChat
}, {
cssClass: 'attachments-popover'
});
popover.onDidDismiss((params) => {
if (params) {
if (params.messageType === MessageType.LOCATION) {
const location = params.selectedLocation;
this.sendLocationMessage(location);
}
else if (params.messageType === MessageType.PICTURE) {
const blob: Blob = params.selectedPicture;
this.sendPictureMessage(blob);
}
}
});
popover.present();
}
sendPictureMessage(blob: Blob): void {
this.pictureService.upload(blob).then((picture) => {
MeteorObservable.call('addMessage', MessageType.PICTURE,
this.selectedChat._id,
picture.url
).zone().subscribe();
});
}
getLocation(locationString: string): Location {
const splitted = locationString.split(',').map(Number);
return <Location>{
lat: splitted[0],
lng: splitted[1],
zoom: Math.min(splitted[2] || 0, 19)
};
}
}