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