]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community.tsx
c7d0a277cc647dd0d80074bfbc430ccc21c21424
[lemmy-ui.git] / src / shared / components / community.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Subscription } from 'rxjs';
3 import { DataType, InitialFetchRequest } from '../interfaces';
4 import {
5   UserOperation,
6   GetCommunityResponse,
7   CommunityResponse,
8   SortType,
9   Post,
10   GetPostsForm,
11   GetCommunityForm,
12   ListingType,
13   GetPostsResponse,
14   PostResponse,
15   AddModToCommunityResponse,
16   BanFromCommunityResponse,
17   Comment,
18   GetCommentsForm,
19   GetCommentsResponse,
20   CommentResponse,
21   WebSocketJsonResponse,
22   GetSiteResponse,
23   Category,
24   ListCategoriesResponse,
25 } from 'lemmy-js-client';
26 import { UserService, WebSocketService } from '../services';
27 import { PostListings } from './post-listings';
28 import { CommentNodes } from './comment-nodes';
29 import { HtmlTags } from './html-tags';
30 import { SortSelect } from './sort-select';
31 import { DataTypeSelect } from './data-type-select';
32 import { Sidebar } from './sidebar';
33 import { CommunityLink } from './community-link';
34 import { BannerIconHeader } from './banner-icon-header';
35 import {
36   wsJsonToRes,
37   fetchLimit,
38   toast,
39   getPageFromProps,
40   getSortTypeFromProps,
41   getDataTypeFromProps,
42   editCommentRes,
43   saveCommentRes,
44   createCommentLikeRes,
45   createPostLikeFindRes,
46   editPostFindRes,
47   commentsToFlatNodes,
48   setupTippy,
49   notifyPost,
50   setIsoData,
51   wsSubscribe,
52   isBrowser,
53   setAuth,
54   communityRSSUrl,
55 } from '../utils';
56 import { i18n } from '../i18next';
57
58 interface State {
59   communityRes: GetCommunityResponse;
60   siteRes: GetSiteResponse;
61   communityId: number;
62   communityName: string;
63   communityLoading: boolean;
64   postsLoading: boolean;
65   commentsLoading: boolean;
66   posts: Post[];
67   comments: Comment[];
68   dataType: DataType;
69   sort: SortType;
70   page: number;
71   categories: Category[];
72 }
73
74 interface CommunityProps {
75   dataType: DataType;
76   sort: SortType;
77   page: number;
78 }
79
80 interface UrlParams {
81   dataType?: string;
82   sort?: SortType;
83   page?: number;
84 }
85
86 export class Community extends Component<any, State> {
87   private isoData = setIsoData(this.context);
88   private subscription: Subscription;
89   private emptyState: State = {
90     communityRes: undefined,
91     communityId: Number(this.props.match.params.id),
92     communityName: this.props.match.params.name,
93     communityLoading: true,
94     postsLoading: true,
95     commentsLoading: true,
96     posts: [],
97     comments: [],
98     dataType: getDataTypeFromProps(this.props),
99     sort: getSortTypeFromProps(this.props),
100     page: getPageFromProps(this.props),
101     siteRes: this.isoData.site,
102     categories: [],
103   };
104
105   constructor(props: any, context: any) {
106     super(props, context);
107
108     this.state = this.emptyState;
109     this.handleSortChange = this.handleSortChange.bind(this);
110     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
111
112     this.parseMessage = this.parseMessage.bind(this);
113     this.subscription = wsSubscribe(this.parseMessage);
114
115     // Only fetch the data if coming from another route
116     if (this.isoData.path == this.context.router.route.match.url) {
117       this.state.communityRes = this.isoData.routeData[0];
118       if (this.state.dataType == DataType.Post) {
119         this.state.posts = this.isoData.routeData[1].posts;
120       } else {
121         this.state.comments = this.isoData.routeData[1].comments;
122       }
123       this.state.categories = this.isoData.routeData[2].categories;
124       this.state.communityLoading = false;
125       this.state.postsLoading = false;
126       this.state.commentsLoading = false;
127     } else {
128       this.fetchCommunity();
129       this.fetchData();
130       WebSocketService.Instance.listCategories();
131     }
132     setupTippy();
133   }
134
135   fetchCommunity() {
136     let form: GetCommunityForm = {
137       id: this.state.communityId ? this.state.communityId : null,
138       name: this.state.communityName ? this.state.communityName : null,
139     };
140     WebSocketService.Instance.getCommunity(form);
141   }
142
143   componentWillUnmount() {
144     if (isBrowser()) {
145       this.subscription.unsubscribe();
146       window.isoData.path = undefined;
147     }
148   }
149
150   static getDerivedStateFromProps(props: any): CommunityProps {
151     return {
152       dataType: getDataTypeFromProps(props),
153       sort: getSortTypeFromProps(props),
154       page: getPageFromProps(props),
155     };
156   }
157
158   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
159     let pathSplit = req.path.split('/');
160     let promises: Promise<any>[] = [];
161
162     // It can be /c/main, or /c/1
163     let idOrName = pathSplit[2];
164     let id: number;
165     let name_: string;
166     if (isNaN(Number(idOrName))) {
167       name_ = idOrName;
168     } else {
169       id = Number(idOrName);
170     }
171
172     let communityForm: GetCommunityForm = id ? { id } : { name: name_ };
173     setAuth(communityForm, req.auth);
174     promises.push(req.client.getCommunity(communityForm));
175
176     let dataType: DataType = pathSplit[4]
177       ? DataType[pathSplit[4]]
178       : DataType.Post;
179
180     let sort: SortType = pathSplit[6]
181       ? SortType[pathSplit[6]]
182       : UserService.Instance.user
183       ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
184       : SortType.Active;
185
186     let page = pathSplit[8] ? Number(pathSplit[8]) : 1;
187
188     if (dataType == DataType.Post) {
189       let getPostsForm: GetPostsForm = {
190         page,
191         limit: fetchLimit,
192         sort,
193         type_: ListingType.Community,
194       };
195       this.setIdOrName(getPostsForm, id, name_);
196       setAuth(getPostsForm, req.auth);
197       promises.push(req.client.getPosts(getPostsForm));
198     } else {
199       let getCommentsForm: GetCommentsForm = {
200         page,
201         limit: fetchLimit,
202         sort,
203         type_: ListingType.Community,
204       };
205       this.setIdOrName(getCommentsForm, id, name_);
206       setAuth(getCommentsForm, req.auth);
207       promises.push(req.client.getComments(getCommentsForm));
208     }
209
210     promises.push(req.client.listCategories());
211
212     return promises;
213   }
214
215   static setIdOrName(obj: any, id: number, name_: string) {
216     if (id) {
217       obj.community_id = id;
218     } else {
219       obj.community_name = name_;
220     }
221   }
222
223   componentDidUpdate(_: any, lastState: State) {
224     if (
225       lastState.dataType !== this.state.dataType ||
226       lastState.sort !== this.state.sort ||
227       lastState.page !== this.state.page
228     ) {
229       this.setState({ postsLoading: true, commentsLoading: true });
230       this.fetchData();
231     }
232   }
233
234   get documentTitle(): string {
235     return `${this.state.communityRes.community.title} - ${this.state.siteRes.site.name}`;
236   }
237
238   render() {
239     return (
240       <div class="container">
241         {this.state.communityLoading ? (
242           <h5>
243             <svg class="icon icon-spinner spin">
244               <use xlinkHref="#icon-spinner"></use>
245             </svg>
246           </h5>
247         ) : (
248           <div class="row">
249             <div class="col-12 col-md-8">
250               <HtmlTags
251                 title={this.documentTitle}
252                 path={this.context.router.route.match.url}
253                 description={this.state.communityRes.community.description}
254                 image={this.state.communityRes.community.icon}
255               />
256               {this.communityInfo()}
257               {this.selects()}
258               {this.listings()}
259               {this.paginator()}
260             </div>
261             <div class="col-12 col-md-4">
262               <Sidebar
263                 community={this.state.communityRes.community}
264                 moderators={this.state.communityRes.moderators}
265                 admins={this.state.siteRes.admins}
266                 online={this.state.communityRes.online}
267                 enableNsfw={this.state.siteRes.site.enable_nsfw}
268                 categories={this.state.categories}
269               />
270             </div>
271           </div>
272         )}
273       </div>
274     );
275   }
276
277   listings() {
278     return this.state.dataType == DataType.Post ? (
279       this.state.postsLoading ? (
280         <h5>
281           <svg class="icon icon-spinner spin">
282             <use xlinkHref="#icon-spinner"></use>
283           </svg>
284         </h5>
285       ) : (
286         <PostListings
287           posts={this.state.posts}
288           removeDuplicates
289           sort={this.state.sort}
290           enableDownvotes={this.state.siteRes.site.enable_downvotes}
291           enableNsfw={this.state.siteRes.site.enable_nsfw}
292         />
293       )
294     ) : this.state.commentsLoading ? (
295       <h5>
296         <svg class="icon icon-spinner spin">
297           <use xlinkHref="#icon-spinner"></use>
298         </svg>
299       </h5>
300     ) : (
301       <CommentNodes
302         nodes={commentsToFlatNodes(this.state.comments)}
303         noIndent
304         sortType={this.state.sort}
305         showContext
306         enableDownvotes={this.state.siteRes.site.enable_downvotes}
307       />
308     );
309   }
310
311   communityInfo() {
312     return (
313       <div>
314         <BannerIconHeader
315           banner={this.state.communityRes.community.banner}
316           icon={this.state.communityRes.community.icon}
317         />
318         <h5 class="mb-0">{this.state.communityRes.community.title}</h5>
319         <CommunityLink
320           community={this.state.communityRes.community}
321           realLink
322           useApubName
323           muted
324           hideAvatar
325         />
326         <hr />
327       </div>
328     );
329   }
330
331   selects() {
332     return (
333       <div class="mb-3">
334         <span class="mr-3">
335           <DataTypeSelect
336             type_={this.state.dataType}
337             onChange={this.handleDataTypeChange}
338           />
339         </span>
340         <span class="mr-2">
341           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
342         </span>
343         <a
344           href={communityRSSUrl(
345             this.state.communityRes.community.actor_id,
346             this.state.sort
347           )}
348           target="_blank"
349           title="RSS"
350           rel="noopener"
351         >
352           <svg class="icon text-muted small">
353             <use xlinkHref="#icon-rss">#</use>
354           </svg>
355         </a>
356       </div>
357     );
358   }
359
360   paginator() {
361     return (
362       <div class="my-2">
363         {this.state.page > 1 && (
364           <button
365             class="btn btn-secondary mr-1"
366             onClick={linkEvent(this, this.prevPage)}
367           >
368             {i18n.t('prev')}
369           </button>
370         )}
371         {this.state.posts.length > 0 && (
372           <button
373             class="btn btn-secondary"
374             onClick={linkEvent(this, this.nextPage)}
375           >
376             {i18n.t('next')}
377           </button>
378         )}
379       </div>
380     );
381   }
382
383   nextPage(i: Community) {
384     i.updateUrl({ page: i.state.page + 1 });
385     window.scrollTo(0, 0);
386   }
387
388   prevPage(i: Community) {
389     i.updateUrl({ page: i.state.page - 1 });
390     window.scrollTo(0, 0);
391   }
392
393   handleSortChange(val: SortType) {
394     this.updateUrl({ sort: val, page: 1 });
395     window.scrollTo(0, 0);
396   }
397
398   handleDataTypeChange(val: DataType) {
399     this.updateUrl({ dataType: DataType[val], page: 1 });
400     window.scrollTo(0, 0);
401   }
402
403   updateUrl(paramUpdates: UrlParams) {
404     const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
405     const sortStr = paramUpdates.sort || this.state.sort;
406     const page = paramUpdates.page || this.state.page;
407     this.props.history.push(
408       `/c/${this.state.communityRes.community.name}/data_type/${dataTypeStr}/sort/${sortStr}/page/${page}`
409     );
410   }
411
412   fetchData() {
413     if (this.state.dataType == DataType.Post) {
414       let getPostsForm: GetPostsForm = {
415         page: this.state.page,
416         limit: fetchLimit,
417         sort: this.state.sort,
418         type_: ListingType.Community,
419         community_id: this.state.communityId,
420         community_name: this.state.communityName,
421       };
422       WebSocketService.Instance.getPosts(getPostsForm);
423     } else {
424       let getCommentsForm: GetCommentsForm = {
425         page: this.state.page,
426         limit: fetchLimit,
427         sort: this.state.sort,
428         type_: ListingType.Community,
429         community_id: this.state.communityId,
430         community_name: this.state.communityName,
431       };
432       WebSocketService.Instance.getComments(getCommentsForm);
433     }
434   }
435
436   parseMessage(msg: WebSocketJsonResponse) {
437     console.log(msg);
438     let res = wsJsonToRes(msg);
439     if (msg.error) {
440       toast(i18n.t(msg.error), 'danger');
441       this.context.router.history.push('/');
442       return;
443     } else if (msg.reconnect) {
444       WebSocketService.Instance.communityJoin({
445         community_id: this.state.communityRes.community.id,
446       });
447       this.fetchData();
448     } else if (res.op == UserOperation.GetCommunity) {
449       let data = res.data as GetCommunityResponse;
450       this.state.communityRes = data;
451       this.state.communityLoading = false;
452       this.setState(this.state);
453       WebSocketService.Instance.communityJoin({
454         community_id: data.community.id,
455       });
456     } else if (
457       res.op == UserOperation.EditCommunity ||
458       res.op == UserOperation.DeleteCommunity ||
459       res.op == UserOperation.RemoveCommunity
460     ) {
461       let data = res.data as CommunityResponse;
462       this.state.communityRes.community = data.community;
463       this.setState(this.state);
464     } else if (res.op == UserOperation.FollowCommunity) {
465       let data = res.data as CommunityResponse;
466       this.state.communityRes.community.subscribed = data.community.subscribed;
467       this.state.communityRes.community.number_of_subscribers =
468         data.community.number_of_subscribers;
469       this.setState(this.state);
470     } else if (res.op == UserOperation.GetPosts) {
471       let data = res.data as GetPostsResponse;
472       this.state.posts = data.posts;
473       this.state.postsLoading = false;
474       this.setState(this.state);
475       setupTippy();
476     } else if (
477       res.op == UserOperation.EditPost ||
478       res.op == UserOperation.DeletePost ||
479       res.op == UserOperation.RemovePost ||
480       res.op == UserOperation.LockPost ||
481       res.op == UserOperation.StickyPost ||
482       res.op == UserOperation.SavePost
483     ) {
484       let data = res.data as PostResponse;
485       editPostFindRes(data, this.state.posts);
486       this.setState(this.state);
487     } else if (res.op == UserOperation.CreatePost) {
488       let data = res.data as PostResponse;
489       this.state.posts.unshift(data.post);
490       notifyPost(data.post, this.context.router);
491       this.setState(this.state);
492     } else if (res.op == UserOperation.CreatePostLike) {
493       let data = res.data as PostResponse;
494       createPostLikeFindRes(data, this.state.posts);
495       this.setState(this.state);
496     } else if (res.op == UserOperation.AddModToCommunity) {
497       let data = res.data as AddModToCommunityResponse;
498       this.state.communityRes.moderators = data.moderators;
499       this.setState(this.state);
500     } else if (res.op == UserOperation.BanFromCommunity) {
501       let data = res.data as BanFromCommunityResponse;
502
503       this.state.posts
504         .filter(p => p.creator_id == data.user.id)
505         .forEach(p => (p.banned = data.banned));
506
507       this.setState(this.state);
508     } else if (res.op == UserOperation.GetComments) {
509       let data = res.data as GetCommentsResponse;
510       this.state.comments = data.comments;
511       this.state.commentsLoading = false;
512       this.setState(this.state);
513     } else if (
514       res.op == UserOperation.EditComment ||
515       res.op == UserOperation.DeleteComment ||
516       res.op == UserOperation.RemoveComment
517     ) {
518       let data = res.data as CommentResponse;
519       editCommentRes(data, this.state.comments);
520       this.setState(this.state);
521     } else if (res.op == UserOperation.CreateComment) {
522       let data = res.data as CommentResponse;
523
524       // Necessary since it might be a user reply
525       if (data.recipient_ids.length == 0) {
526         this.state.comments.unshift(data.comment);
527         this.setState(this.state);
528       }
529     } else if (res.op == UserOperation.SaveComment) {
530       let data = res.data as CommentResponse;
531       saveCommentRes(data, this.state.comments);
532       this.setState(this.state);
533     } else if (res.op == UserOperation.CreateCommentLike) {
534       let data = res.data as CommentResponse;
535       createCommentLikeRes(data, this.state.comments);
536       this.setState(this.state);
537     } else if (res.op == UserOperation.ListCategories) {
538       let data = res.data as ListCategoriesResponse;
539       this.state.categories = data.categories;
540       this.setState(this.state);
541     }
542   }
543 }