]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community.tsx
Running newer prettier.
[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   PostView,
10   GetPosts,
11   GetCommunity,
12   ListingType,
13   GetPostsResponse,
14   PostResponse,
15   AddModToCommunityResponse,
16   BanFromCommunityResponse,
17   CommentView,
18   GetComments,
19   GetCommentsResponse,
20   CommentResponse,
21   GetSiteResponse,
22   Category,
23   ListCategoriesResponse,
24 } from "lemmy-js-client";
25 import { UserService, WebSocketService } from "../services";
26 import { PostListings } from "./post-listings";
27 import { CommentNodes } from "./comment-nodes";
28 import { HtmlTags } from "./html-tags";
29 import { SortSelect } from "./sort-select";
30 import { DataTypeSelect } from "./data-type-select";
31 import { Sidebar } from "./sidebar";
32 import { CommunityLink } from "./community-link";
33 import { BannerIconHeader } from "./banner-icon-header";
34 import { Icon, Spinner } from "./icon";
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   communityRSSUrl,
53   wsUserOp,
54   wsClient,
55   authField,
56   setOptionalAuth,
57   saveScrollPosition,
58   restoreScrollPosition,
59 } from "../utils";
60 import { i18n } from "../i18next";
61
62 interface State {
63   communityRes: GetCommunityResponse;
64   siteRes: GetSiteResponse;
65   communityId: number;
66   communityName: string;
67   communityLoading: boolean;
68   postsLoading: boolean;
69   commentsLoading: boolean;
70   posts: PostView[];
71   comments: CommentView[];
72   dataType: DataType;
73   sort: SortType;
74   page: number;
75   categories: Category[];
76 }
77
78 interface CommunityProps {
79   dataType: DataType;
80   sort: SortType;
81   page: number;
82 }
83
84 interface UrlParams {
85   dataType?: string;
86   sort?: SortType;
87   page?: number;
88 }
89
90 export class Community extends Component<any, State> {
91   private isoData = setIsoData(this.context);
92   private subscription: Subscription;
93   private emptyState: State = {
94     communityRes: undefined,
95     communityId: Number(this.props.match.params.id),
96     communityName: this.props.match.params.name,
97     communityLoading: true,
98     postsLoading: true,
99     commentsLoading: true,
100     posts: [],
101     comments: [],
102     dataType: getDataTypeFromProps(this.props),
103     sort: getSortTypeFromProps(this.props),
104     page: getPageFromProps(this.props),
105     siteRes: this.isoData.site_res,
106     categories: [],
107   };
108
109   constructor(props: any, context: any) {
110     super(props, context);
111
112     this.state = this.emptyState;
113     this.handleSortChange = this.handleSortChange.bind(this);
114     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
115
116     this.parseMessage = this.parseMessage.bind(this);
117     this.subscription = wsSubscribe(this.parseMessage);
118
119     // Only fetch the data if coming from another route
120     if (this.isoData.path == this.context.router.route.match.url) {
121       this.state.communityRes = this.isoData.routeData[0];
122       if (this.state.dataType == DataType.Post) {
123         this.state.posts = this.isoData.routeData[1].posts;
124       } else {
125         this.state.comments = this.isoData.routeData[1].comments;
126       }
127       this.state.categories = this.isoData.routeData[2].categories;
128       this.state.communityLoading = false;
129       this.state.postsLoading = false;
130       this.state.commentsLoading = false;
131     } else {
132       this.fetchCommunity();
133       this.fetchData();
134       WebSocketService.Instance.send(wsClient.listCategories());
135     }
136     setupTippy();
137   }
138
139   fetchCommunity() {
140     let form: GetCommunity = {
141       id: this.state.communityId ? this.state.communityId : null,
142       name: this.state.communityName ? this.state.communityName : null,
143       auth: authField(false),
144     };
145     WebSocketService.Instance.send(wsClient.getCommunity(form));
146   }
147
148   componentWillUnmount() {
149     saveScrollPosition(this.context);
150     this.subscription.unsubscribe();
151     window.isoData.path = undefined;
152   }
153
154   static getDerivedStateFromProps(props: any): CommunityProps {
155     return {
156       dataType: getDataTypeFromProps(props),
157       sort: getSortTypeFromProps(props),
158       page: getPageFromProps(props),
159     };
160   }
161
162   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
163     let pathSplit = req.path.split("/");
164     let promises: Promise<any>[] = [];
165
166     // It can be /c/main, or /c/1
167     let idOrName = pathSplit[2];
168     let id: number;
169     let name_: string;
170     if (isNaN(Number(idOrName))) {
171       name_ = idOrName;
172     } else {
173       id = Number(idOrName);
174     }
175
176     let communityForm: GetCommunity = id ? { id } : { name: name_ };
177     setOptionalAuth(communityForm, req.auth);
178     promises.push(req.client.getCommunity(communityForm));
179
180     let dataType: DataType = pathSplit[4]
181       ? DataType[pathSplit[4]]
182       : DataType.Post;
183
184     let sort: SortType = pathSplit[6]
185       ? SortType[pathSplit[6]]
186       : UserService.Instance.user
187       ? Object.values(SortType)[UserService.Instance.user.default_sort_type]
188       : SortType.Active;
189
190     let page = pathSplit[8] ? Number(pathSplit[8]) : 1;
191
192     if (dataType == DataType.Post) {
193       let getPostsForm: GetPosts = {
194         page,
195         limit: fetchLimit,
196         sort,
197         type_: ListingType.Community,
198       };
199       setOptionalAuth(getPostsForm, req.auth);
200       this.setIdOrName(getPostsForm, id, name_);
201       promises.push(req.client.getPosts(getPostsForm));
202     } else {
203       let getCommentsForm: GetComments = {
204         page,
205         limit: fetchLimit,
206         sort,
207         type_: ListingType.Community,
208       };
209       setOptionalAuth(getCommentsForm, req.auth);
210       this.setIdOrName(getCommentsForm, id, name_);
211       promises.push(req.client.getComments(getCommentsForm));
212     }
213
214     promises.push(req.client.listCategories());
215
216     return promises;
217   }
218
219   static setIdOrName(obj: any, id: number, name_: string) {
220     if (id) {
221       obj.community_id = id;
222     } else {
223       obj.community_name = name_;
224     }
225   }
226
227   componentDidUpdate(_: any, lastState: State) {
228     if (
229       lastState.dataType !== this.state.dataType ||
230       lastState.sort !== this.state.sort ||
231       lastState.page !== this.state.page
232     ) {
233       this.setState({ postsLoading: true, commentsLoading: true });
234       this.fetchData();
235     }
236   }
237
238   get documentTitle(): string {
239     return `${this.state.communityRes.community_view.community.title} - ${this.state.siteRes.site_view.site.name}`;
240   }
241
242   render() {
243     let cv = this.state.communityRes?.community_view;
244     return (
245       <div class="container">
246         {this.state.communityLoading ? (
247           <h5>
248             <Spinner />
249           </h5>
250         ) : (
251           <div class="row">
252             <div class="col-12 col-md-8">
253               <HtmlTags
254                 title={this.documentTitle}
255                 path={this.context.router.route.match.url}
256                 description={cv.community.description}
257                 image={cv.community.icon}
258               />
259               {this.communityInfo()}
260               {this.selects()}
261               {this.listings()}
262               {this.paginator()}
263             </div>
264             <div class="col-12 col-md-4">
265               <Sidebar
266                 community_view={cv}
267                 moderators={this.state.communityRes.moderators}
268                 admins={this.state.siteRes.admins}
269                 online={this.state.communityRes.online}
270                 enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
271                 categories={this.state.categories}
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 />
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 />
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   paginator() {
354     return (
355       <div class="my-2">
356         {this.state.page > 1 && (
357           <button
358             class="btn btn-secondary mr-1"
359             onClick={linkEvent(this, this.prevPage)}
360           >
361             {i18n.t("prev")}
362           </button>
363         )}
364         {this.state.posts.length > 0 && (
365           <button
366             class="btn btn-secondary"
367             onClick={linkEvent(this, this.nextPage)}
368           >
369             {i18n.t("next")}
370           </button>
371         )}
372       </div>
373     );
374   }
375
376   nextPage(i: Community) {
377     i.updateUrl({ page: i.state.page + 1 });
378     window.scrollTo(0, 0);
379   }
380
381   prevPage(i: Community) {
382     i.updateUrl({ page: i.state.page - 1 });
383     window.scrollTo(0, 0);
384   }
385
386   handleSortChange(val: SortType) {
387     this.updateUrl({ sort: val, page: 1 });
388     window.scrollTo(0, 0);
389   }
390
391   handleDataTypeChange(val: DataType) {
392     this.updateUrl({ dataType: DataType[val], page: 1 });
393     window.scrollTo(0, 0);
394   }
395
396   updateUrl(paramUpdates: UrlParams) {
397     const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
398     const sortStr = paramUpdates.sort || this.state.sort;
399     const page = paramUpdates.page || this.state.page;
400
401     let typeView = this.state.communityName
402       ? `/c/${this.state.communityName}`
403       : `/community/${this.state.communityId}`;
404
405     this.props.history.push(
406       `${typeView}/data_type/${dataTypeStr}/sort/${sortStr}/page/${page}`
407     );
408   }
409
410   fetchData() {
411     if (this.state.dataType == DataType.Post) {
412       let form: GetPosts = {
413         page: this.state.page,
414         limit: fetchLimit,
415         sort: this.state.sort,
416         type_: ListingType.Community,
417         community_id: this.state.communityId,
418         community_name: this.state.communityName,
419         auth: authField(false),
420       };
421       WebSocketService.Instance.send(wsClient.getPosts(form));
422     } else {
423       let form: GetComments = {
424         page: this.state.page,
425         limit: fetchLimit,
426         sort: this.state.sort,
427         type_: ListingType.Community,
428         community_id: this.state.communityId,
429         community_name: this.state.communityName,
430         auth: authField(false),
431       };
432       WebSocketService.Instance.send(wsClient.getComments(form));
433     }
434   }
435
436   parseMessage(msg: any) {
437     let op = wsUserOp(msg);
438     if (msg.error) {
439       toast(i18n.t(msg.error), "danger");
440       this.context.router.history.push("/");
441       return;
442     } else if (msg.reconnect) {
443       WebSocketService.Instance.send(
444         wsClient.communityJoin({
445           community_id: this.state.communityRes.community_view.community.id,
446         })
447       );
448       this.fetchData();
449     } else if (op == UserOperation.GetCommunity) {
450       let data = wsJsonToRes<GetCommunityResponse>(msg).data;
451       this.state.communityRes = data;
452       this.state.communityLoading = false;
453       this.setState(this.state);
454       // TODO why is there no auth in this form?
455       WebSocketService.Instance.send(
456         wsClient.communityJoin({
457           community_id: data.community_view.community.id,
458         })
459       );
460     } else if (
461       op == UserOperation.EditCommunity ||
462       op == UserOperation.DeleteCommunity ||
463       op == UserOperation.RemoveCommunity
464     ) {
465       let data = wsJsonToRes<CommunityResponse>(msg).data;
466       this.state.communityRes.community_view = data.community_view;
467       this.setState(this.state);
468     } else if (op == UserOperation.FollowCommunity) {
469       let data = wsJsonToRes<CommunityResponse>(msg).data;
470       this.state.communityRes.community_view.subscribed =
471         data.community_view.subscribed;
472       this.state.communityRes.community_view.counts.subscribers =
473         data.community_view.counts.subscribers;
474       this.setState(this.state);
475     } else if (op == UserOperation.GetPosts) {
476       let data = wsJsonToRes<GetPostsResponse>(msg).data;
477       this.state.posts = data.posts;
478       this.state.postsLoading = false;
479       this.setState(this.state);
480       restoreScrollPosition(this.context);
481       setupTippy();
482     } else if (
483       op == UserOperation.EditPost ||
484       op == UserOperation.DeletePost ||
485       op == UserOperation.RemovePost ||
486       op == UserOperation.LockPost ||
487       op == UserOperation.StickyPost ||
488       op == UserOperation.SavePost
489     ) {
490       let data = wsJsonToRes<PostResponse>(msg).data;
491       editPostFindRes(data.post_view, this.state.posts);
492       this.setState(this.state);
493     } else if (op == UserOperation.CreatePost) {
494       let data = wsJsonToRes<PostResponse>(msg).data;
495       this.state.posts.unshift(data.post_view);
496       notifyPost(data.post_view, this.context.router);
497       this.setState(this.state);
498     } else if (op == UserOperation.CreatePostLike) {
499       let data = wsJsonToRes<PostResponse>(msg).data;
500       createPostLikeFindRes(data.post_view, this.state.posts);
501       this.setState(this.state);
502     } else if (op == UserOperation.AddModToCommunity) {
503       let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
504       this.state.communityRes.moderators = data.moderators;
505       this.setState(this.state);
506     } else if (op == UserOperation.BanFromCommunity) {
507       let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
508
509       // TODO this might be incorrect
510       this.state.posts
511         .filter(p => p.creator.id == data.user_view.user.id)
512         .forEach(p => (p.creator_banned_from_community = data.banned));
513
514       this.setState(this.state);
515     } else if (op == UserOperation.GetComments) {
516       let data = wsJsonToRes<GetCommentsResponse>(msg).data;
517       this.state.comments = data.comments;
518       this.state.commentsLoading = false;
519       this.setState(this.state);
520     } else if (
521       op == UserOperation.EditComment ||
522       op == UserOperation.DeleteComment ||
523       op == UserOperation.RemoveComment
524     ) {
525       let data = wsJsonToRes<CommentResponse>(msg).data;
526       editCommentRes(data.comment_view, this.state.comments);
527       this.setState(this.state);
528     } else if (op == UserOperation.CreateComment) {
529       let data = wsJsonToRes<CommentResponse>(msg).data;
530
531       // Necessary since it might be a user reply
532       if (data.form_id) {
533         this.state.comments.unshift(data.comment_view);
534         this.setState(this.state);
535       }
536     } else if (op == UserOperation.SaveComment) {
537       let data = wsJsonToRes<CommentResponse>(msg).data;
538       saveCommentRes(data.comment_view, this.state.comments);
539       this.setState(this.state);
540     } else if (op == UserOperation.CreateCommentLike) {
541       let data = wsJsonToRes<CommentResponse>(msg).data;
542       createCommentLikeRes(data.comment_view, this.state.comments);
543       this.setState(this.state);
544     } else if (op == UserOperation.ListCategories) {
545       let data = wsJsonToRes<ListCategoriesResponse>(msg).data;
546       this.state.categories = data.categories;
547       this.setState(this.state);
548     }
549   }
550 }