From 0541a132333aadcaa0960bfb426e40b936a86533 Mon Sep 17 00:00:00 2001 From: Rodrigo Nascimento Date: Thu, 10 Aug 2017 20:21:46 -0300 Subject: [PATCH] Load more messages. Closes #15 --- app/lib/rocketchat.js | 14 +++++++++++--- app/views/room.js | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/app/lib/rocketchat.js b/app/lib/rocketchat.js index c6c261c9..980ae3c1 100644 --- a/app/lib/rocketchat.js +++ b/app/lib/rocketchat.js @@ -104,10 +104,14 @@ const RocketChat = { }); }, - loadMessagesForRoom(rid, cb) { - Meteor.call('loadHistory', rid, null, 50, (err, data) => { + loadMessagesForRoom(rid, end, cb) { + Meteor.call('loadHistory', rid, end, 20, (err, data) => { if (err) { console.error(err); + if (cb) { + cb({ end: true }); + } + return; } realm.write(() => { @@ -119,7 +123,11 @@ const RocketChat = { }); if (cb) { - cb(); + if (data.messages.length < 20) { + cb({ end: true }); + } else { + cb({ end: false }); + } } }); diff --git a/app/views/room.js b/app/views/room.js index b3058f01..78eca59b 100644 --- a/app/views/room.js +++ b/app/views/room.js @@ -27,6 +27,12 @@ const styles = StyleSheet.create({ margin: 5, textAlign: 'center', color: '#a00' + }, + header: { + transform: [{ scaleY: -1 }], + textAlign: 'center', + padding: 5, + color: '#ccc' } }); @@ -57,7 +63,7 @@ export default class RoomView extends React.Component { const late = setTimeout(() => this.setState({ loaded: false }), 1000); - RocketChat.loadMessagesForRoom(this.rid, () => { + RocketChat.loadMessagesForRoom(this.rid, null, () => { clearTimeout(late); this.setState({ loaded: true @@ -70,6 +76,22 @@ export default class RoomView extends React.Component { realm.removeListener('change', this.updateState); } + onEndReached = () => { + if (this.state.dataSource.length && this.state.loaded && this.state.loadingMore !== true && this.state.end !== true) { + this.setState({ + ...this.state, + loadingMore: true + }); + RocketChat.loadMessagesForRoom(this.rid, this.state.dataSource[this.state.dataSource.length - 1].ts, ({ end }) => { + this.setState({ + ...this.state, + loadingMore: false, + end + }); + }); + } + } + getMessages = () => realm.objects('messages').filtered('_server.id = $0 AND rid = $1', RocketChat.currentServer, this.rid).sorted('ts', true) updateState = () => { @@ -129,6 +151,16 @@ export default class RoomView extends React.Component { ); } + renderHeader = () => { + if (this.state.loadingMore) { + return Loading more messages...; + } + + if (this.state.end) { + return Start of conversation; + } + } + render() { return ( @@ -140,6 +172,9 @@ export default class RoomView extends React.Component { extraData={this.state} renderItem={this.renderItem} keyExtractor={item => item._id} + onEndReached={this.onEndReached} + onEndReachedThreshold={0.1} + ListFooterComponent={this.renderHeader()} /> {this.renderFooter()}