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