-
-
Notifications
You must be signed in to change notification settings - Fork 866
Expand file tree
/
Copy pathMessageStream.tsx
More file actions
237 lines (197 loc) · 7.68 KB
/
MessageStream.tsx
File metadata and controls
237 lines (197 loc) · 7.68 KB
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
import app from 'flarum/forum/app';
import Component, { type ComponentAttrs } from 'flarum/common/Component';
import Mithril from 'mithril';
import LoadingIndicator from 'flarum/common/components/LoadingIndicator';
import MessageStreamState from '../states/MessageStreamState';
import DialogMessage from '../../common/models/DialogMessage';
import Stream from 'flarum/common/utils/Stream';
import Button from 'flarum/common/components/Button';
import { ModelIdentifier } from 'flarum/common/Model';
import ScrollListener from 'flarum/common/utils/ScrollListener';
import Dialog from '../../common/models/Dialog';
import Message from './Message';
export interface IDialogStreamAttrs extends ComponentAttrs {
dialog: Dialog;
state: MessageStreamState;
}
export default class MessageStream<CustomAttrs extends IDialogStreamAttrs = IDialogStreamAttrs> extends Component<CustomAttrs> {
protected replyPlaceholderComponent = Stream<any>(null);
protected loadingPostComponent = Stream<any>(null);
protected scrollListener!: ScrollListener;
protected initialToBottomScroll = false;
protected lastTime: Date | null = null;
protected checkedRead = false;
protected markingAsRead = false;
oninit(vnode: Mithril.Vnode<CustomAttrs, this>) {
super.oninit(vnode);
// We need the lazy ReplyPlaceholder and LoadingPost components to be loaded.
Promise.all([import('flarum/forum/components/ReplyPlaceholder'), import('flarum/forum/components/LoadingPost')]).then(
([ReplyPlaceholder, LoadingPost]) => {
this.replyPlaceholderComponent(ReplyPlaceholder.default);
this.loadingPostComponent(LoadingPost.default);
}
);
}
oncreate(vnode: Mithril.VnodeDOM<CustomAttrs, this>) {
super.oncreate(vnode);
this.scrollListener = new ScrollListener(this.onscroll.bind(this), this.element);
setTimeout(() => {
this.scrollListener.start();
this.element.addEventListener('scrollend', this.markAsRead.bind(this));
});
}
onupdate(vnode: Mithril.VnodeDOM<CustomAttrs, this>) {
super.onupdate(vnode);
// @todo: for future versions, consider using the post stream scrubber to scroll through the messages. (big task..)
// @todo: introduce read status, to jump to the first unread message instead.
if (!this.initialToBottomScroll && !this.attrs.state.isLoading()) {
this.scrollToBottom();
this.initialToBottomScroll = true;
}
if (this.initialToBottomScroll && !this.checkedRead) {
this.markAsRead();
this.checkedRead = true;
}
}
onremove(vnode: Mithril.VnodeDOM<CustomAttrs, this>) {
super.onremove(vnode);
this.scrollListener.stop();
}
view() {
return <div className="MessageStream">{this.attrs.state.isLoading() ? <LoadingIndicator /> : this.content()}</div>;
}
content() {
const items: Mithril.Children[] = [];
const messages = this.attrs.state.getAllItems().sort((a, b) => a.createdAt().getTime() - b.createdAt().getTime());
const ReplyPlaceholder = this.replyPlaceholderComponent();
const LoadingPost = this.loadingPostComponent();
if (messages[0].id() !== (this.attrs.dialog.data.relationships?.firstMessage.data as ModelIdentifier).id) {
items.push(
<div className="MessageStream-item" key="loadPrevious">
<Button
onclick={() => this.whileMaintainingScroll(() => this.attrs.state.loadNext())}
type="button"
className="Button Button--block MessageStream-loadPrev"
>
{app.translator.trans('flarum-messages.forum.messages_page.stream.load_previous_button')}
</Button>
</div>
);
if (LoadingPost) {
items.push(
<div className="MessageStream-item" key="loading-prev">
<LoadingPost />
</div>
);
}
}
messages.forEach((message, index) => items.push(this.messageItem(message, index)));
if (app.session.user!.canSendAnyMessage() && ReplyPlaceholder) {
items.push(
<div className="MessageStream-item" key="reply">
<ReplyPlaceholder
discussion={this.attrs.dialog}
onclick={() => {
import('flarum/forum/components/ComposerBody').then(() => {
app.composer
.load(() => import('./MessageComposer'), {
user: app.session.user,
replyingTo: this.attrs.dialog,
onsubmit: () => {
this.attrs.state.refresh().then(() => setTimeout(() => this.scrollToBottom(), 50));
},
})
.then(() => app.composer.show());
});
}}
composingReply={() => app.composer.composingMessageTo(this.attrs.dialog)}
/>
</div>
);
}
return items;
}
messageItem(message: DialogMessage, index: number) {
return (
<div className="MessageStream-item" key={index} data-id={message.id()}>
{this.timeGap(message)}
<Message message={message} />
</div>
);
}
timeGap(message: DialogMessage): Mithril.Children {
if (message.id() === (this.attrs.dialog.data.relationships?.firstMessage.data as ModelIdentifier).id) {
this.lastTime = message.createdAt()!;
return (
<div class="PostStream-timeGap">
<span>{app.translator.trans('flarum-messages.forum.messages_page.stream.start_of_the_conversation')}</span>
</div>
);
}
const lastTime = this.lastTime;
const dt = message.createdAt().getTime() - (lastTime?.getTime() || 0);
this.lastTime = message.createdAt()!;
if (lastTime && dt > 1000 * 60 * 60 * 24 * 4) {
return (
<div className="PostStream-timeGap">
<span>
{/* @ts-ignore */}
{app.translator.trans('flarum-messages.forum.messages_page.stream.time_lapsed_text', { period: dayjs().add(dt, 'ms').fromNow(true) })}
</span>
</div>
);
}
return null;
}
onscroll() {
this.whileMaintainingScroll(() => {
if (this.element.scrollTop <= 80 && this.attrs.state.hasNext()) {
return this.attrs.state.loadNext();
}
if (this.element.scrollTop + this.element.clientHeight === this.element.scrollHeight && this.attrs.state.hasPrev()) {
return this.attrs.state.loadPrev();
}
return null;
});
}
scrollToBottom() {
this.element.scrollTop = this.element.scrollHeight;
}
whileMaintainingScroll(callback: () => null | Promise<void>) {
const scrollTop = this.element.scrollTop;
const scrollHeight = this.element.scrollHeight;
const result = callback();
if (result instanceof Promise) {
result.then(() => {
requestAnimationFrame(() => {
this.element.scrollTop = this.element.scrollHeight - scrollHeight + scrollTop;
});
});
}
}
markAsRead(): void {
const lastVisibleId = Number(
this.$('.MessageStream-item[data-id]')
.filter((_, $el) => {
if (this.element.scrollHeight <= this.element.clientHeight) {
return true;
}
return this.$().offset()!.top + this.element.clientHeight > $($el).offset()!.top;
})
.last()
.data('id')
);
if (lastVisibleId && app.session.user && lastVisibleId > (this.attrs.dialog.lastReadMessageId() || 0) && !this.markingAsRead) {
this.markingAsRead = true;
this.attrs.dialog.save({ lastReadMessageId: lastVisibleId }).finally(() => {
this.markingAsRead = false;
if (this.attrs.dialog.unreadCount() === 0) {
app.session.user!.pushAttributes({
messageCount: (app.session.user!.attribute<number>('messageCount') ?? 1) - 1,
});
}
m.redraw();
});
}
}
}