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