]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
Collapse sidebar on mobile. Fixes #335 (#340)
[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   communityId: number;
65   communityName: string;
66   communityLoading: boolean;
67   postsLoading: boolean;
68   commentsLoading: boolean;
69   posts: PostView[];
70   comments: CommentView[];
71   dataType: DataType;
72   sort: SortType;
73   page: number;
74   showSidebarMobile: boolean;
75 }
76
77 interface CommunityProps {
78   dataType: DataType;
79   sort: SortType;
80   page: number;
81 }
82
83 interface UrlParams {
84   dataType?: string;
85   sort?: SortType;
86   page?: number;
87 }
88
89 export class Community extends Component<any, State> {
90   private isoData = setIsoData(this.context);
91   private subscription: Subscription;
92   private emptyState: State = {
93     communityRes: undefined,
94     communityId: Number(this.props.match.params.id),
95     communityName: this.props.match.params.name,
96     communityLoading: true,
97     postsLoading: true,
98     commentsLoading: true,
99     posts: [],
100     comments: [],
101     dataType: getDataTypeFromProps(this.props),
102     sort: getSortTypeFromProps(this.props),
103     page: getPageFromProps(this.props),
104     siteRes: this.isoData.site_res,
105     showSidebarMobile: false,
106   };
107
108   constructor(props: any, context: any) {
109     super(props, context);
110
111     this.state = this.emptyState;
112     this.handleSortChange = this.handleSortChange.bind(this);
113     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
114     this.handlePageChange = this.handlePageChange.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.communityLoading = false;
128       this.state.postsLoading = false;
129       this.state.commentsLoading = false;
130     } else {
131       this.fetchCommunity();
132       this.fetchData();
133     }
134     setupTippy();
135   }
136
137   fetchCommunity() {
138     let form: GetCommunity = {
139       id: this.state.communityId ? this.state.communityId : null,
140       name: this.state.communityName ? this.state.communityName : null,
141       auth: authField(false),
142     };
143     WebSocketService.Instance.send(wsClient.getCommunity(form));
144   }
145
146   componentWillUnmount() {
147     saveScrollPosition(this.context);
148     this.subscription.unsubscribe();
149     window.isoData.path = undefined;
150   }
151
152   static getDerivedStateFromProps(props: any): CommunityProps {
153     return {
154       dataType: getDataTypeFromProps(props),
155       sort: getSortTypeFromProps(props),
156       page: getPageFromProps(props),
157     };
158   }
159
160   static fetchInitialData(req: InitialFetchRequest): Promise<any>[] {
161     let pathSplit = req.path.split("/");
162     let promises: Promise<any>[] = [];
163
164     // It can be /c/main, or /c/1
165     let idOrName = pathSplit[2];
166     let id: number;
167     let name_: string;
168     if (isNaN(Number(idOrName))) {
169       name_ = idOrName;
170     } else {
171       id = Number(idOrName);
172     }
173
174     let communityForm: GetCommunity = id ? { id } : { name: name_ };
175     setOptionalAuth(communityForm, req.auth);
176     promises.push(req.client.getCommunity(communityForm));
177
178     let dataType: DataType = pathSplit[4]
179       ? DataType[pathSplit[4]]
180       : DataType.Post;
181
182     let sort: SortType = pathSplit[6]
183       ? SortType[pathSplit[6]]
184       : UserService.Instance.localUserView
185       ? Object.values(SortType)[
186           UserService.Instance.localUserView.local_user.default_sort_type
187         ]
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         saved_only: false,
199       };
200       setOptionalAuth(getPostsForm, req.auth);
201       this.setIdOrName(getPostsForm, id, name_);
202       promises.push(req.client.getPosts(getPostsForm));
203     } else {
204       let getCommentsForm: GetComments = {
205         page,
206         limit: fetchLimit,
207         sort,
208         type_: ListingType.Community,
209         saved_only: false,
210       };
211       setOptionalAuth(getCommentsForm, req.auth);
212       this.setIdOrName(getCommentsForm, id, name_);
213       promises.push(req.client.getComments(getCommentsForm));
214     }
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 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">{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     return (
358       <div class="mb-3">
359         <span class="mr-3">
360           <DataTypeSelect
361             type_={this.state.dataType}
362             onChange={this.handleDataTypeChange}
363           />
364         </span>
365         <span class="mr-2">
366           <SortSelect sort={this.state.sort} onChange={this.handleSortChange} />
367         </span>
368         <a
369           href={communityRSSUrl(
370             this.state.communityRes.community_view.community.actor_id,
371             this.state.sort
372           )}
373           title="RSS"
374           rel="noopener"
375         >
376           <Icon icon="rss" classes="text-muted small" />
377         </a>
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 = this.state.communityName
408       ? `/c/${this.state.communityName}`
409       : `/community/${this.state.communityId}`;
410
411     this.props.history.push(
412       `${typeView}/data_type/${dataTypeStr}/sort/${sortStr}/page/${page}`
413     );
414   }
415
416   fetchData() {
417     if (this.state.dataType == DataType.Post) {
418       let form: GetPosts = {
419         page: this.state.page,
420         limit: fetchLimit,
421         sort: this.state.sort,
422         type_: ListingType.Community,
423         community_id: this.state.communityId,
424         community_name: this.state.communityName,
425         saved_only: false,
426         auth: authField(false),
427       };
428       WebSocketService.Instance.send(wsClient.getPosts(form));
429     } else {
430       let form: GetComments = {
431         page: this.state.page,
432         limit: fetchLimit,
433         sort: this.state.sort,
434         type_: ListingType.Community,
435         community_id: this.state.communityId,
436         community_name: this.state.communityName,
437         saved_only: false,
438         auth: authField(false),
439       };
440       WebSocketService.Instance.send(wsClient.getComments(form));
441     }
442   }
443
444   parseMessage(msg: any) {
445     let op = wsUserOp(msg);
446     console.log(msg);
447     if (msg.error) {
448       toast(i18n.t(msg.error), "danger");
449       this.context.router.history.push("/");
450       return;
451     } else if (msg.reconnect) {
452       WebSocketService.Instance.send(
453         wsClient.communityJoin({
454           community_id: this.state.communityRes.community_view.community.id,
455         })
456       );
457       this.fetchData();
458     } else if (op == UserOperation.GetCommunity) {
459       let data = wsJsonToRes<GetCommunityResponse>(msg).data;
460       this.state.communityRes = data;
461       this.state.communityLoading = false;
462       this.setState(this.state);
463       // TODO why is there no auth in this form?
464       WebSocketService.Instance.send(
465         wsClient.communityJoin({
466           community_id: data.community_view.community.id,
467         })
468       );
469     } else if (
470       op == UserOperation.EditCommunity ||
471       op == UserOperation.DeleteCommunity ||
472       op == UserOperation.RemoveCommunity
473     ) {
474       let data = wsJsonToRes<CommunityResponse>(msg).data;
475       this.state.communityRes.community_view = data.community_view;
476       this.setState(this.state);
477     } else if (op == UserOperation.FollowCommunity) {
478       let data = wsJsonToRes<CommunityResponse>(msg).data;
479       this.state.communityRes.community_view.subscribed =
480         data.community_view.subscribed;
481       this.state.communityRes.community_view.counts.subscribers =
482         data.community_view.counts.subscribers;
483       this.setState(this.state);
484     } else if (op == UserOperation.GetPosts) {
485       let data = wsJsonToRes<GetPostsResponse>(msg).data;
486       this.state.posts = data.posts;
487       this.state.postsLoading = false;
488       this.setState(this.state);
489       restoreScrollPosition(this.context);
490       setupTippy();
491     } else if (
492       op == UserOperation.EditPost ||
493       op == UserOperation.DeletePost ||
494       op == UserOperation.RemovePost ||
495       op == UserOperation.LockPost ||
496       op == UserOperation.StickyPost ||
497       op == UserOperation.SavePost
498     ) {
499       let data = wsJsonToRes<PostResponse>(msg).data;
500       editPostFindRes(data.post_view, this.state.posts);
501       this.setState(this.state);
502     } else if (op == UserOperation.CreatePost) {
503       let data = wsJsonToRes<PostResponse>(msg).data;
504       this.state.posts.unshift(data.post_view);
505       notifyPost(data.post_view, this.context.router);
506       this.setState(this.state);
507     } else if (op == UserOperation.CreatePostLike) {
508       let data = wsJsonToRes<PostResponse>(msg).data;
509       createPostLikeFindRes(data.post_view, this.state.posts);
510       this.setState(this.state);
511     } else if (op == UserOperation.AddModToCommunity) {
512       let data = wsJsonToRes<AddModToCommunityResponse>(msg).data;
513       this.state.communityRes.moderators = data.moderators;
514       this.setState(this.state);
515     } else if (op == UserOperation.BanFromCommunity) {
516       let data = wsJsonToRes<BanFromCommunityResponse>(msg).data;
517
518       // TODO this might be incorrect
519       this.state.posts
520         .filter(p => p.creator.id == data.person_view.person.id)
521         .forEach(p => (p.creator_banned_from_community = data.banned));
522
523       this.setState(this.state);
524     } else if (op == UserOperation.GetComments) {
525       let data = wsJsonToRes<GetCommentsResponse>(msg).data;
526       this.state.comments = data.comments;
527       this.state.commentsLoading = false;
528       this.setState(this.state);
529     } else if (
530       op == UserOperation.EditComment ||
531       op == UserOperation.DeleteComment ||
532       op == UserOperation.RemoveComment
533     ) {
534       let data = wsJsonToRes<CommentResponse>(msg).data;
535       editCommentRes(data.comment_view, this.state.comments);
536       this.setState(this.state);
537     } else if (op == UserOperation.CreateComment) {
538       let data = wsJsonToRes<CommentResponse>(msg).data;
539
540       // Necessary since it might be a user reply
541       if (data.form_id) {
542         this.state.comments.unshift(data.comment_view);
543         this.setState(this.state);
544       }
545     } else if (op == UserOperation.SaveComment) {
546       let data = wsJsonToRes<CommentResponse>(msg).data;
547       saveCommentRes(data.comment_view, this.state.comments);
548       this.setState(this.state);
549     } else if (op == UserOperation.CreateCommentLike) {
550       let data = wsJsonToRes<CommentResponse>(msg).data;
551       createCommentLikeRes(data.comment_view, this.state.comments);
552       this.setState(this.state);
553     }
554   }
555 }