Skip to content

Commit

Permalink
Step 6.18: Implement auto scroll
Browse files Browse the repository at this point in the history
  • Loading branch information
dotansimha authored and darkbasic committed Oct 16, 2017
1 parent 682653e commit f8fa759
Showing 1 changed file with 45 additions and 4 deletions.
49 changes: 45 additions & 4 deletions src/pages/messages/messages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnInit } from '@angular/core';
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { NavParams } from 'ionic-angular';
import { Chat, Message, MessageType } from 'api/models';
import { Observable } from 'rxjs';
Expand All @@ -9,20 +9,39 @@ import { MeteorObservable } from 'meteor-rxjs';
selector: 'messages-page',
templateUrl: 'messages.html'
})
export class MessagesPage implements OnInit {
export class MessagesPage implements OnInit, OnDestroy {
selectedChat: Chat;
title: string;
picture: string;
messages: Observable<Message[]>;
message: string = '';
autoScroller: MutationObserver;
scrollOffset = 0;

constructor(navParams: NavParams) {
constructor(
navParams: NavParams,
private el: ElementRef
) {
this.selectedChat = <Chat>navParams.get('chat');
this.title = this.selectedChat.title;
this.picture = this.selectedChat.picture;
}

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();

let isEven = false;

this.messages = Messages.find(
Expand All @@ -38,8 +57,30 @@ export class MessagesPage implements OnInit {
});
}

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

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

autoScroller.observe(this.messagesList, {
childList: true,
subtree: true
});

return autoScroller;
}

scrollDown(): void {
// 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.charCode === 13) {
if (keyCode === 13) {
this.sendTextMessage();
}
}
Expand Down

0 comments on commit f8fa759

Please sign in to comment.