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