]> Untitled Git - lemmy.git/blob - ui/src/components/inbox.tsx
Merge branch 'master' into iav-arm-musl-dessalines
[lemmy.git] / ui / src / components / inbox.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Subscription } from 'rxjs';
3 import { retryWhen, delay, take } from 'rxjs/operators';
4 import {
5   UserOperation,
6   Comment,
7   SortType,
8   GetRepliesForm,
9   GetRepliesResponse,
10   GetUserMentionsForm,
11   GetUserMentionsResponse,
12   UserMentionResponse,
13   CommentResponse,
14   WebSocketJsonResponse,
15   PrivateMessage as PrivateMessageI,
16   GetPrivateMessagesForm,
17   PrivateMessagesResponse,
18   PrivateMessageResponse,
19 } from '../interfaces';
20 import { WebSocketService, UserService } from '../services';
21 import {
22   wsJsonToRes,
23   fetchLimit,
24   isCommentType,
25   toast,
26   editCommentRes,
27   saveCommentRes,
28   createCommentLikeRes,
29   commentsToFlatNodes,
30   setupTippy,
31 } from '../utils';
32 import { CommentNodes } from './comment-nodes';
33 import { PrivateMessage } from './private-message';
34 import { SortSelect } from './sort-select';
35 import { i18n } from '../i18next';
36
37 enum UnreadOrAll {
38   Unread,
39   All,
40 }
41
42 enum MessageType {
43   All,
44   Replies,
45   Mentions,
46   Messages,
47 }
48
49 type ReplyType = Comment | PrivateMessageI;
50
51 interface InboxState {
52   unreadOrAll: UnreadOrAll;
53   messageType: MessageType;
54   replies: Array<Comment>;
55   mentions: Array<Comment>;
56   messages: Array<PrivateMessageI>;
57   sort: SortType;
58   page: number;
59 }
60
61 export class Inbox extends Component<any, InboxState> {
62   private subscription: Subscription;
63   private emptyState: InboxState = {
64     unreadOrAll: UnreadOrAll.Unread,
65     messageType: MessageType.All,
66     replies: [],
67     mentions: [],
68     messages: [],
69     sort: SortType.New,
70     page: 1,
71   };
72
73   constructor(props: any, context: any) {
74     super(props, context);
75
76     this.state = this.emptyState;
77     this.handleSortChange = this.handleSortChange.bind(this);
78
79     this.subscription = WebSocketService.Instance.subject
80       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
81       .subscribe(
82         msg => this.parseMessage(msg),
83         err => console.error(err),
84         () => console.log('complete')
85       );
86
87     this.refetch();
88   }
89
90   componentWillUnmount() {
91     this.subscription.unsubscribe();
92   }
93
94   componentDidMount() {
95     document.title = `/u/${UserService.Instance.user.username} ${i18n.t(
96       'inbox'
97     )} - ${WebSocketService.Instance.site.name}`;
98   }
99
100   render() {
101     return (
102       <div class="container">
103         <div class="row">
104           <div class="col-12">
105             <h5 class="mb-1">
106               {i18n.t('inbox')}
107               <small>
108                 <a
109                   href={`/feeds/inbox/${UserService.Instance.auth}.xml`}
110                   target="_blank"
111                   title="RSS"
112                 >
113                   <svg class="icon ml-2 text-muted small">
114                     <use xlinkHref="#icon-rss">#</use>
115                   </svg>
116                 </a>
117               </small>
118             </h5>
119             {this.state.replies.length +
120               this.state.mentions.length +
121               this.state.messages.length >
122               0 &&
123               this.state.unreadOrAll == UnreadOrAll.Unread && (
124                 <ul class="list-inline mb-1 text-muted small font-weight-bold">
125                   <li className="list-inline-item">
126                     <span
127                       class="pointer"
128                       onClick={linkEvent(this, this.markAllAsRead)}
129                     >
130                       {i18n.t('mark_all_as_read')}
131                     </span>
132                   </li>
133                 </ul>
134               )}
135             {this.selects()}
136             {this.state.messageType == MessageType.All && this.all()}
137             {this.state.messageType == MessageType.Replies && this.replies()}
138             {this.state.messageType == MessageType.Mentions && this.mentions()}
139             {this.state.messageType == MessageType.Messages && this.messages()}
140             {this.paginator()}
141           </div>
142         </div>
143       </div>
144     );
145   }
146
147   unreadOrAllRadios() {
148     return (
149       <div class="btn-group btn-group-toggle">
150         <label
151           className={`btn btn-sm btn-secondary pointer
152             ${this.state.unreadOrAll == UnreadOrAll.Unread && 'active'}
153           `}
154         >
155           <input
156             type="radio"
157             value={UnreadOrAll.Unread}
158             checked={this.state.unreadOrAll == UnreadOrAll.Unread}
159             onChange={linkEvent(this, this.handleUnreadOrAllChange)}
160           />
161           {i18n.t('unread')}
162         </label>
163         <label
164           className={`btn btn-sm btn-secondary pointer
165             ${this.state.unreadOrAll == UnreadOrAll.All && 'active'}
166           `}
167         >
168           <input
169             type="radio"
170             value={UnreadOrAll.All}
171             checked={this.state.unreadOrAll == UnreadOrAll.All}
172             onChange={linkEvent(this, this.handleUnreadOrAllChange)}
173           />
174           {i18n.t('all')}
175         </label>
176       </div>
177     );
178   }
179
180   messageTypeRadios() {
181     return (
182       <div class="btn-group btn-group-toggle">
183         <label
184           className={`btn btn-sm btn-secondary pointer btn-outline-light
185             ${this.state.messageType == MessageType.All && 'active'}
186           `}
187         >
188           <input
189             type="radio"
190             value={MessageType.All}
191             checked={this.state.messageType == MessageType.All}
192             onChange={linkEvent(this, this.handleMessageTypeChange)}
193           />
194           {i18n.t('all')}
195         </label>
196         <label
197           className={`btn btn-sm btn-secondary pointer btn-outline-light
198             ${this.state.messageType == MessageType.Replies && 'active'}
199           `}
200         >
201           <input
202             type="radio"
203             value={MessageType.Replies}
204             checked={this.state.messageType == MessageType.Replies}
205             onChange={linkEvent(this, this.handleMessageTypeChange)}
206           />
207           {i18n.t('replies')}
208         </label>
209         <label
210           className={`btn btn-sm btn-secondary pointer btn-outline-light
211             ${this.state.messageType == MessageType.Mentions && 'active'}
212           `}
213         >
214           <input
215             type="radio"
216             value={MessageType.Mentions}
217             checked={this.state.messageType == MessageType.Mentions}
218             onChange={linkEvent(this, this.handleMessageTypeChange)}
219           />
220           {i18n.t('mentions')}
221         </label>
222         <label
223           className={`btn btn-sm btn-secondary pointer btn-outline-light
224             ${this.state.messageType == MessageType.Messages && 'active'}
225           `}
226         >
227           <input
228             type="radio"
229             value={MessageType.Messages}
230             checked={this.state.messageType == MessageType.Messages}
231             onChange={linkEvent(this, this.handleMessageTypeChange)}
232           />
233           {i18n.t('messages')}
234         </label>
235       </div>
236     );
237   }
238
239   selects() {
240     return (
241       <div className="mb-2">
242         <span class="mr-3">{this.unreadOrAllRadios()}</span>
243         <span class="mr-3">{this.messageTypeRadios()}</span>
244         <SortSelect
245           sort={this.state.sort}
246           onChange={this.handleSortChange}
247           hideHot
248         />
249       </div>
250     );
251   }
252
253   all() {
254     let combined: Array<ReplyType> = [];
255
256     combined.push(...this.state.replies);
257     combined.push(...this.state.mentions);
258     combined.push(...this.state.messages);
259
260     // Sort it
261     combined.sort((a, b) => b.published.localeCompare(a.published));
262
263     return (
264       <div>
265         {combined.map(i =>
266           isCommentType(i) ? (
267             <CommentNodes
268               nodes={[{ comment: i }]}
269               noIndent
270               markable
271               showContext
272             />
273           ) : (
274             <PrivateMessage privateMessage={i} />
275           )
276         )}
277       </div>
278     );
279   }
280
281   replies() {
282     return (
283       <div>
284         <CommentNodes
285           nodes={commentsToFlatNodes(this.state.replies)}
286           noIndent
287           markable
288           showContext
289         />
290       </div>
291     );
292   }
293
294   mentions() {
295     return (
296       <div>
297         {this.state.mentions.map(mention => (
298           <CommentNodes
299             nodes={[{ comment: mention }]}
300             noIndent
301             markable
302             showContext
303           />
304         ))}
305       </div>
306     );
307   }
308
309   messages() {
310     return (
311       <div>
312         {this.state.messages.map(message => (
313           <PrivateMessage privateMessage={message} />
314         ))}
315       </div>
316     );
317   }
318
319   paginator() {
320     return (
321       <div class="mt-2">
322         {this.state.page > 1 && (
323           <button
324             class="btn btn-sm btn-secondary mr-1"
325             onClick={linkEvent(this, this.prevPage)}
326           >
327             {i18n.t('prev')}
328           </button>
329         )}
330         <button
331           class="btn btn-sm btn-secondary"
332           onClick={linkEvent(this, this.nextPage)}
333         >
334           {i18n.t('next')}
335         </button>
336       </div>
337     );
338   }
339
340   nextPage(i: Inbox) {
341     i.state.page++;
342     i.setState(i.state);
343     i.refetch();
344   }
345
346   prevPage(i: Inbox) {
347     i.state.page--;
348     i.setState(i.state);
349     i.refetch();
350   }
351
352   handleUnreadOrAllChange(i: Inbox, event: any) {
353     i.state.unreadOrAll = Number(event.target.value);
354     i.state.page = 1;
355     i.setState(i.state);
356     i.refetch();
357   }
358
359   handleMessageTypeChange(i: Inbox, event: any) {
360     i.state.messageType = Number(event.target.value);
361     i.state.page = 1;
362     i.setState(i.state);
363     i.refetch();
364   }
365
366   refetch() {
367     let repliesForm: GetRepliesForm = {
368       sort: SortType[this.state.sort],
369       unread_only: this.state.unreadOrAll == UnreadOrAll.Unread,
370       page: this.state.page,
371       limit: fetchLimit,
372     };
373     WebSocketService.Instance.getReplies(repliesForm);
374
375     let userMentionsForm: GetUserMentionsForm = {
376       sort: SortType[this.state.sort],
377       unread_only: this.state.unreadOrAll == UnreadOrAll.Unread,
378       page: this.state.page,
379       limit: fetchLimit,
380     };
381     WebSocketService.Instance.getUserMentions(userMentionsForm);
382
383     let privateMessagesForm: GetPrivateMessagesForm = {
384       unread_only: this.state.unreadOrAll == UnreadOrAll.Unread,
385       page: this.state.page,
386       limit: fetchLimit,
387     };
388     WebSocketService.Instance.getPrivateMessages(privateMessagesForm);
389   }
390
391   handleSortChange(val: SortType) {
392     this.state.sort = val;
393     this.state.page = 1;
394     this.setState(this.state);
395     this.refetch();
396   }
397
398   markAllAsRead(i: Inbox) {
399     WebSocketService.Instance.markAllAsRead();
400     i.state.replies = [];
401     i.state.mentions = [];
402     i.state.messages = [];
403     i.sendUnreadCount();
404     window.scrollTo(0, 0);
405     i.setState(i.state);
406   }
407
408   parseMessage(msg: WebSocketJsonResponse) {
409     console.log(msg);
410     let res = wsJsonToRes(msg);
411     if (msg.error) {
412       toast(i18n.t(msg.error), 'danger');
413       return;
414     } else if (msg.reconnect) {
415       this.refetch();
416     } else if (res.op == UserOperation.GetReplies) {
417       let data = res.data as GetRepliesResponse;
418       this.state.replies = data.replies;
419       this.sendUnreadCount();
420       window.scrollTo(0, 0);
421       this.setState(this.state);
422       setupTippy();
423     } else if (res.op == UserOperation.GetUserMentions) {
424       let data = res.data as GetUserMentionsResponse;
425       this.state.mentions = data.mentions;
426       this.sendUnreadCount();
427       window.scrollTo(0, 0);
428       this.setState(this.state);
429       setupTippy();
430     } else if (res.op == UserOperation.GetPrivateMessages) {
431       let data = res.data as PrivateMessagesResponse;
432       this.state.messages = data.messages;
433       this.sendUnreadCount();
434       window.scrollTo(0, 0);
435       this.setState(this.state);
436       setupTippy();
437     } else if (res.op == UserOperation.EditPrivateMessage) {
438       let data = res.data as PrivateMessageResponse;
439       let found: PrivateMessageI = this.state.messages.find(
440         m => m.id === data.message.id
441       );
442       found.content = data.message.content;
443       found.updated = data.message.updated;
444       found.deleted = data.message.deleted;
445       // If youre in the unread view, just remove it from the list
446       if (this.state.unreadOrAll == UnreadOrAll.Unread && data.message.read) {
447         this.state.messages = this.state.messages.filter(
448           r => r.id !== data.message.id
449         );
450       } else {
451         let found = this.state.messages.find(c => c.id == data.message.id);
452         found.read = data.message.read;
453       }
454       this.sendUnreadCount();
455       window.scrollTo(0, 0);
456       this.setState(this.state);
457       setupTippy();
458     } else if (res.op == UserOperation.MarkAllAsRead) {
459       // Moved to be instant
460     } else if (res.op == UserOperation.EditComment) {
461       let data = res.data as CommentResponse;
462       editCommentRes(data, this.state.replies);
463
464       // If youre in the unread view, just remove it from the list
465       if (this.state.unreadOrAll == UnreadOrAll.Unread && data.comment.read) {
466         this.state.replies = this.state.replies.filter(
467           r => r.id !== data.comment.id
468         );
469       } else {
470         let found = this.state.replies.find(c => c.id == data.comment.id);
471         found.read = data.comment.read;
472       }
473       this.sendUnreadCount();
474       this.setState(this.state);
475       setupTippy();
476     } else if (res.op == UserOperation.EditUserMention) {
477       let data = res.data as UserMentionResponse;
478
479       let found = this.state.mentions.find(c => c.id == data.mention.id);
480       found.content = data.mention.content;
481       found.updated = data.mention.updated;
482       found.removed = data.mention.removed;
483       found.deleted = data.mention.deleted;
484       found.upvotes = data.mention.upvotes;
485       found.downvotes = data.mention.downvotes;
486       found.score = data.mention.score;
487
488       // If youre in the unread view, just remove it from the list
489       if (this.state.unreadOrAll == UnreadOrAll.Unread && data.mention.read) {
490         this.state.mentions = this.state.mentions.filter(
491           r => r.id !== data.mention.id
492         );
493       } else {
494         let found = this.state.mentions.find(c => c.id == data.mention.id);
495         found.read = data.mention.read;
496       }
497       this.sendUnreadCount();
498       this.setState(this.state);
499     } else if (res.op == UserOperation.CreateComment) {
500       let data = res.data as CommentResponse;
501
502       if (data.recipient_ids.includes(UserService.Instance.user.id)) {
503         this.state.replies.unshift(data.comment);
504         this.setState(this.state);
505       } else if (data.comment.creator_id == UserService.Instance.user.id) {
506         toast(i18n.t('reply_sent'));
507       }
508       this.setState(this.state);
509     } else if (res.op == UserOperation.CreatePrivateMessage) {
510       let data = res.data as PrivateMessageResponse;
511       if (data.message.recipient_id == UserService.Instance.user.id) {
512         this.state.messages.unshift(data.message);
513         this.setState(this.state);
514       }
515     } else if (res.op == UserOperation.SaveComment) {
516       let data = res.data as CommentResponse;
517       saveCommentRes(data, this.state.replies);
518       this.setState(this.state);
519       setupTippy();
520     } else if (res.op == UserOperation.CreateCommentLike) {
521       let data = res.data as CommentResponse;
522       createCommentLikeRes(data, this.state.replies);
523       this.setState(this.state);
524     }
525   }
526
527   sendUnreadCount() {
528     let count =
529       this.state.replies.filter(r => !r.read).length +
530       this.state.mentions.filter(r => !r.read).length +
531       this.state.messages.filter(
532         r => !r.read && r.creator_id !== UserService.Instance.user.id
533       ).length;
534     UserService.Instance.user.unreadCount = count;
535     UserService.Instance.sub.next({
536       user: UserService.Instance.user,
537     });
538   }
539 }