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