]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
Have setting to disable notifs for new posts. Fixes #132 (#345)
[lemmy-ui.git] / src / shared / components / community / community.tsx
1 import { Component, linkEvent } 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   communityName: string;
65   communityLoading: boolean;
66   postsLoading: boolean;
67   commentsLoading: boolean;
68   posts: PostView[];
69   comments: CommentView[];
70   dataType: DataType;
71   sort: SortType;
72   page: number;
73   showSidebarMobile: boolean;
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     communityName: this.props.match.params.name,
94     communityLoading: true,
95     postsLoading: true,
96     commentsLoading: true,
97     posts: [],
98     comments: [],
99     dataType: getDataTypeFromProps(this.props),
100     sort: getSortTypeFromProps(this.props),
101     page: getPageFromProps(this.props),
102     siteRes: this.isoData.site_res,
103     showSidebarMobile: false,
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       name: this.state.communityName ? this.state.communityName : null,
138       auth: authField(false),
139     };
140     WebSocketService.Instance.send(wsClient.getCommunity(form));
141   }
142
143   componentWillUnmount() {
144     saveScrollPosition(this.context);
145     this.subscription.unsubscribe();
146     window.isoData.path = undefined;
147   }
148
149   static getDerivedStateFromProps(props: any): CommunityProps {
150     return {
151       dataType: getDataTypeFromProps(props),
152       sort: getSortTypeFromProps(props),
153       page: getPageFromProps(props),
154     };
155   }
156
157   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
158     let pathSplit = req.path.split("/");
159     let promises: Promise<any>[] = [];
160
161     // It can be /c/main, or /c/1
162     let idOrName = pathSplit[2];
163     let id: number;
164     let name_: string;
165     if (isNaN(Number(idOrName))) {
166       name_ = idOrName;
167     } else {
168       id = Number(idOrName);
169     }
170
171     let communityForm: GetCommunity = id ? { id } : { name: name_ };
172     setOptionalAuth(communityForm, req.auth);
173     promises.push(req.client.getCommunity(communityForm));
174
175     let dataType: DataType = pathSplit[4]
176       ? DataType[pathSplit[4]]
177       : DataType.Post;
178
179     let sort: SortType = pathSplit[6]
180       ? SortType[pathSplit[6]]
181       : UserService.Instance.localUserView
182       ? Object.values(SortType)[
183           UserService.Instance.localUserView.local_user.default_sort_type
184         ]
185       : SortType.Active;
186
187     let page = pathSplit[8] ? Number(pathSplit[8]) : 1;
188
189     if (dataType == DataType.Post) {
190       let getPostsForm: GetPosts = {
191         page,
192         limit: fetchLimit,
193         sort,
194         type_: ListingType.Community,
195         saved_only: false,
196       };
197       setOptionalAuth(getPostsForm, req.auth);
198       this.setName(getPostsForm, name_);
199       promises.push(req.client.getPosts(getPostsForm));
200     } else {
201       let getCommentsForm: GetComments = {
202         page,
203         limit: fetchLimit,
204         sort,
205         type_: ListingType.Community,
206         saved_only: false,
207       };
208       setOptionalAuth(getCommentsForm, req.auth);
209       promises.push(req.client.getComments(getCommentsForm));
210     }
211
212     return promises;
213   }
214
215   static setName(obj: any, name_: string) {
216     obj.community_name = name_;
217   }
218
219   componentDidUpdate(_: any, lastState: State) {
220     if (
221       lastState.dataType !== this.state.dataType ||
222       lastState.sort !== this.state.sort ||
223       lastState.page !== this.state.page
224     ) {
225       this.setState({ postsLoading: true, commentsLoading: true });
226       this.fetchData();
227     }
228   }
229
230   get documentTitle(): string {
231     return `${this.state.communityRes.community_view.community.title} - ${this.state.siteRes.site_view.site.name}`;
232   }
233
234   render() {
235     let cv = this.state.communityRes?.community_view;
236     return (
237       <div class="container">
238         {this.state.communityLoading ? (
239           <h5>
240             <Spinner large />
241           </h5>
242         ) : (
243           <>
244             <HtmlTags
245               title={this.documentTitle}
246               path={this.context.router.route.match.url}
247               description={cv.community.description}
248               image={cv.community.icon}
249             />
250
251             <div class="row">
252               <div class="col-12 col-md-8">
253                 {this.communityInfo()}
254                 <div class="d-block d-md-none">
255                   <button
256                     class="btn btn-secondary d-inline-block mb-2 mr-3"
257                     onClick={linkEvent(this, this.handleShowSidebarMobile)}
258                   >
259                     {i18n.t("sidebar")}{" "}
260                     <Icon
261                       icon={
262                         this.state.showSidebarMobile
263                           ? `minus-square`
264                           : `plus-square`
265                       }
266                       classes="icon-inline"
267                     />
268                   </button>
269                   {this.state.showSidebarMobile && (
270                     <Sidebar
271                       community_view={cv}
272                       moderators={this.state.communityRes.moderators}
273                       admins={this.state.siteRes.admins}
274                       online={this.state.communityRes.online}
275                       enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
276                     />
277                   )}
278                 </div>
279                 {this.selects()}
280                 {this.listings()}
281                 <Paginator
282                   page={this.state.page}
283                   onChange={this.handlePageChange}
284                 />
285               </div>
286               <div class="d-none d-md-block col-md-4">
287                 <Sidebar
288                   community_view={cv}
289                   moderators={this.state.communityRes.moderators}
290                   admins={this.state.siteRes.admins}
291                   online={this.state.communityRes.online}
292                   enableNsfw={this.state.siteRes.site_view.site.enable_nsfw}
293                 />
294               </div>
295             </div>
296           </>
297         )}
298       </div>
299     );
300   }
301
302   listings() {
303     let site = this.state.siteRes.site_view.site;
304     return this.state.dataType == DataType.Post ? (
305       this.state.postsLoading ? (
306         <h5>
307           <Spinner large />
308         </h5>
309       ) : (
310         <PostListings
311           posts={this.state.posts}
312           removeDuplicates
313           enableDownvotes={site.enable_downvotes}
314           enableNsfw={site.enable_nsfw}
315         />
316       )
317     ) : this.state.commentsLoading ? (
318       <h5>
319         <Spinner large />
320       </h5>
321     ) : (
322       <CommentNodes
323         nodes={commentsToFlatNodes(this.state.comments)}
324         noIndent
325         showContext
326         enableDownvotes={site.enable_downvotes}
327       />
328     );
329   }
330
331   communityInfo() {
332     let community = this.state.communityRes.community_view.community;
333     return (
334       <div class="mb-2">
335         <BannerIconHeader banner={community.banner} icon={community.icon} />
336         <h5 class="mb-0">{community.title}</h5>
337         <CommunityLink
338           community={community}
339           realLink
340           useApubName
341           muted
342           hideAvatar
343         />
344       </div>
345     );
346   }
347
348   selects() {
349     return (
350       <div class="mb-3">
351         <span class="mr-3">
352           <DataTypeSelect
353             type_={this.state.dataType}
354             onChange={this.handleDataTypeChange}
355           />
356         </span>
357         <span class="mr-2">
358           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
359         </span>
360         <a
361           href={communityRSSUrl(
362             this.state.communityRes.community_view.community.actor_id,
363             this.state.sort
364           )}
365           title="RSS"
366           rel="noopener"
367         >
368           <Icon icon="rss" classes="text-muted small" />
369         </a>
370       </div>
371     );
372   }
373
374   handlePageChange(page: number) {
375     this.updateUrl({ page });
376     window.scrollTo(0, 0);
377   }
378
379   handleSortChange(val: SortType) {
380     this.updateUrl({ sort: val, page: 1 });
381     window.scrollTo(0, 0);
382   }
383
384   handleDataTypeChange(val: DataType) {
385     this.updateUrl({ dataType: DataType[val], page: 1 });
386     window.scrollTo(0, 0);
387   }
388
389   handleShowSidebarMobile(i: Community) {
390     i.state.showSidebarMobile = !i.state.showSidebarMobile;
391     i.setState(i.state);
392   }
393
394   updateUrl(paramUpdates: UrlParams) {
395     const dataTypeStr = paramUpdates.dataType || DataType[this.state.dataType];
396     const sortStr = paramUpdates.sort || this.state.sort;
397     const page = paramUpdates.page || this.state.page;
398
399     let typeView = `/c/${this.state.communityName}`;
400
401     this.props.history.push(
402       `${typeView}/data_type/${dataTypeStr}/sort/${sortStr}/page/${page}`
403     );
404   }
405
406   fetchData() {
407     if (this.state.dataType == DataType.Post) {
408       let form: GetPosts = {
409         page: this.state.page,
410         limit: fetchLimit,
411         sort: this.state.sort,
412         type_: ListingType.Community,
413         community_name: this.state.communityName,
414         saved_only: false,
415         auth: authField(false),
416       };
417       WebSocketService.Instance.send(wsClient.getPosts(form));
418     } else {
419       let form: GetComments = {
420         page: this.state.page,
421         limit: fetchLimit,
422         sort: this.state.sort,
423         type_: ListingType.Community,
424         community_name: this.state.communityName,
425         saved_only: false,
426         auth: authField(false),
427       };
428       WebSocketService.Instance.send(wsClient.getComments(form));
429     }
430   }
431
432   parseMessage(msg: any) {
433     let op = wsUserOp(msg);
434     console.log(msg);
435     if (msg.error) {
436       toast(i18n.t(msg.error), "danger");
437       this.context.router.history.push("/");
438       return;
439     } else if (msg.reconnect) {
440       WebSocketService.Instance.send(
441         wsClient.communityJoin({
442           community_id: this.state.communityRes.community_view.community.id,
443         })
444       );
445       this.fetchData();
446     } else if (op == UserOperation.GetCommunity) {
447       let data = wsJsonToRes<GetCommunityResponse>(msg).data;
448       this.state.communityRes = data;
449       this.state.communityLoading = false;
450       this.setState(this.state);
451       // TODO why is there no auth in this form?
452       WebSocketService.Instance.send(
453         wsClient.communityJoin({
454           community_id: data.community_view.community.id,
455         })
456       );
457     } else if (
458       op == UserOperation.EditCommunity ||
459       op == UserOperation.DeleteCommunity ||
460       op == UserOperation.RemoveCommunity
461     ) {
462       let data = wsJsonToRes<CommunityResponse>(msg).data;
463       this.state.communityRes.community_view = data.community_view;
464       this.setState(this.state);
465     } else if (op == UserOperation.FollowCommunity) {
466       let data = wsJsonToRes<CommunityResponse>(msg).data;
467       this.state.communityRes.community_view.subscribed =
468         data.community_view.subscribed;
469       this.state.communityRes.community_view.counts.subscribers =
470         data.community_view.counts.subscribers;
471       this.setState(this.state);
472     } else if (op == UserOperation.GetPosts) {
473       let data = wsJsonToRes<GetPostsResponse>(msg).data;
474       this.state.posts = data.posts;
475       this.state.postsLoading = false;
476       this.setState(this.state);
477       restoreScrollPosition(this.context);
478       setupTippy();
479     } else if (
480       op == UserOperation.EditPost ||
481       op == UserOperation.DeletePost ||
482       op == UserOperation.RemovePost ||
483       op == UserOperation.LockPost ||
484       op == UserOperation.StickyPost ||
485       op == UserOperation.SavePost
486     ) {
487       let data = wsJsonToRes<PostResponse>(msg).data;
488       editPostFindRes(data.post_view, this.state.posts);
489       this.setState(this.state);
490     } else if (op == UserOperation.CreatePost) {
491       let data = wsJsonToRes<PostResponse>(msg).data;
492       this.state.posts.unshift(data.post_view);
493       if (UserService.Instance.localUserView?.local_user.show_new_post_notifs) {
494         notifyPost(data.post_view, this.context.router);
495       }
496       this.setState(this.state);
497     } else if (op == UserOperation.CreatePostLike) {
498       let data = wsJsonToRes<PostResponse>(msg).data;
499       createPostLikeFindRes(data.post_view, this.state.posts);
500       this.setState(this.state);
501     } else if (op == UserOperation.AddModToCommunity) {
502       let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
503       this.state.communityRes.moderators = data.moderators;
504       this.setState(this.state);
505     } else if (op == UserOperation.BanFromCommunity) {
506       let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
507
508       // TODO this might be incorrect
509       this.state.posts
510         .filter(p => p.creator.id == data.person_view.person.id)
511         .forEach(p => (p.creator_banned_from_community = data.banned));
512
513       this.setState(this.state);
514     } else if (op == UserOperation.GetComments) {
515       let data = wsJsonToRes<GetCommentsResponse>(msg).data;
516       this.state.comments = data.comments;
517       this.state.commentsLoading = false;
518       this.setState(this.state);
519     } else if (
520       op == UserOperation.EditComment ||
521       op == UserOperation.DeleteComment ||
522       op == UserOperation.RemoveComment
523     ) {
524       let data = wsJsonToRes<CommentResponse>(msg).data;
525       editCommentRes(data.comment_view, this.state.comments);
526       this.setState(this.state);
527     } else if (op == UserOperation.CreateComment) {
528       let data = wsJsonToRes<CommentResponse>(msg).data;
529
530       // Necessary since it might be a user reply
531       if (data.form_id) {
532         this.state.comments.unshift(data.comment_view);
533         this.setState(this.state);
534       }
535     } else if (op == UserOperation.SaveComment) {
536       let data = wsJsonToRes<CommentResponse>(msg).data;
537       saveCommentRes(data.comment_view, this.state.comments);
538       this.setState(this.state);
539     } else if (op == UserOperation.CreateCommentLike) {
540       let data = wsJsonToRes<CommentResponse>(msg).data;
541       createCommentLikeRes(data.comment_view, this.state.comments);
542       this.setState(this.state);
543     }
544   }
545 }