]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
c00380ab2db9ff1b1258cadde8bd0f25a6d2efb8
[lemmy-ui.git] / src / shared / components / community / community.tsx
1 import {
2   commentsToFlatNodes,
3   communityRSSUrl,
4   editComment,
5   editPost,
6   editWith,
7   enableDownvotes,
8   enableNsfw,
9   getCommentParentId,
10   getDataTypeString,
11   myAuth,
12   postToCommentSortType,
13   setIsoData,
14   showLocal,
15   updateCommunityBlock,
16   updatePersonBlock,
17 } from "@utils/app";
18 import {
19   getPageFromString,
20   getQueryParams,
21   getQueryString,
22 } from "@utils/helpers";
23 import type { QueryParams } from "@utils/types";
24 import { RouteDataResponse } from "@utils/types";
25 import { Component, RefObject, createRef, linkEvent } from "inferno";
26 import { RouteComponentProps } from "inferno-router/dist/Route";
27 import {
28   AddAdmin,
29   AddModToCommunity,
30   AddModToCommunityResponse,
31   BanFromCommunity,
32   BanFromCommunityResponse,
33   BanPerson,
34   BanPersonResponse,
35   BlockCommunity,
36   BlockPerson,
37   CommentId,
38   CommentReplyResponse,
39   CommentResponse,
40   CommunityResponse,
41   CreateComment,
42   CreateCommentLike,
43   CreateCommentReport,
44   CreatePostLike,
45   CreatePostReport,
46   DeleteComment,
47   DeleteCommunity,
48   DeletePost,
49   DistinguishComment,
50   EditComment,
51   EditCommunity,
52   EditPost,
53   FeaturePost,
54   FollowCommunity,
55   GetComments,
56   GetCommentsResponse,
57   GetCommunity,
58   GetCommunityResponse,
59   GetPosts,
60   GetPostsResponse,
61   GetSiteResponse,
62   LockPost,
63   MarkCommentReplyAsRead,
64   MarkPersonMentionAsRead,
65   PostResponse,
66   PurgeComment,
67   PurgeCommunity,
68   PurgeItemResponse,
69   PurgePerson,
70   PurgePost,
71   RemoveComment,
72   RemoveCommunity,
73   RemovePost,
74   SaveComment,
75   SavePost,
76   SortType,
77   TransferCommunity,
78 } from "lemmy-js-client";
79 import { fetchLimit, relTags } from "../../config";
80 import {
81   CommentViewType,
82   DataType,
83   InitialFetchRequest,
84 } from "../../interfaces";
85 import { FirstLoadService, I18NextService, UserService } from "../../services";
86 import { HttpService, RequestState } from "../../services/HttpService";
87 import { setupTippy } from "../../tippy";
88 import { toast } from "../../toast";
89 import { CommentNodes } from "../comment/comment-nodes";
90 import { BannerIconHeader } from "../common/banner-icon-header";
91 import { DataTypeSelect } from "../common/data-type-select";
92 import { HtmlTags } from "../common/html-tags";
93 import { Icon, Spinner } from "../common/icon";
94 import { Paginator } from "../common/paginator";
95 import { SortSelect } from "../common/sort-select";
96 import { Sidebar } from "../community/sidebar";
97 import { SiteSidebar } from "../home/site-sidebar";
98 import { PostListings } from "../post/post-listings";
99 import { CommunityLink } from "./community-link";
100
101 type CommunityData = RouteDataResponse<{
102   communityRes: GetCommunityResponse;
103   postsRes: GetPostsResponse;
104   commentsRes: GetCommentsResponse;
105 }>;
106
107 interface State {
108   communityRes: RequestState<GetCommunityResponse>;
109   postsRes: RequestState<GetPostsResponse>;
110   commentsRes: RequestState<GetCommentsResponse>;
111   siteRes: GetSiteResponse;
112   showSidebarMobile: boolean;
113   finished: Map<CommentId, boolean | undefined>;
114   isIsomorphic: boolean;
115 }
116
117 interface CommunityProps {
118   dataType: DataType;
119   sort: SortType;
120   page: number;
121 }
122
123 function getCommunityQueryParams() {
124   return getQueryParams<CommunityProps>({
125     dataType: getDataTypeFromQuery,
126     page: getPageFromString,
127     sort: getSortTypeFromQuery,
128   });
129 }
130
131 function getDataTypeFromQuery(type?: string): DataType {
132   return type ? DataType[type] : DataType.Post;
133 }
134
135 function getSortTypeFromQuery(type?: string): SortType {
136   const mySortType =
137     UserService.Instance.myUserInfo?.local_user_view.local_user
138       .default_sort_type;
139
140   return type ? (type as SortType) : mySortType ?? "Active";
141 }
142
143 export class Community extends Component<
144   RouteComponentProps<{ name: string }>,
145   State
146 > {
147   private isoData = setIsoData<CommunityData>(this.context);
148   state: State = {
149     communityRes: { state: "empty" },
150     postsRes: { state: "empty" },
151     commentsRes: { state: "empty" },
152     siteRes: this.isoData.site_res,
153     showSidebarMobile: false,
154     finished: new Map(),
155     isIsomorphic: false,
156   };
157   private readonly mainContentRef: RefObject<HTMLElement>;
158   constructor(props: RouteComponentProps<{ name: string }>, context: any) {
159     super(props, context);
160
161     this.handleSortChange = this.handleSortChange.bind(this);
162     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
163     this.handlePageChange = this.handlePageChange.bind(this);
164
165     // All of the action binds
166     this.handleDeleteCommunity = this.handleDeleteCommunity.bind(this);
167     this.handleEditCommunity = this.handleEditCommunity.bind(this);
168     this.handleFollow = this.handleFollow.bind(this);
169     this.handleRemoveCommunity = this.handleRemoveCommunity.bind(this);
170     this.handleCreateComment = this.handleCreateComment.bind(this);
171     this.handleEditComment = this.handleEditComment.bind(this);
172     this.handleSaveComment = this.handleSaveComment.bind(this);
173     this.handleBlockCommunity = this.handleBlockCommunity.bind(this);
174     this.handleBlockPerson = this.handleBlockPerson.bind(this);
175     this.handleDeleteComment = this.handleDeleteComment.bind(this);
176     this.handleRemoveComment = this.handleRemoveComment.bind(this);
177     this.handleCommentVote = this.handleCommentVote.bind(this);
178     this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
179     this.handleAddAdmin = this.handleAddAdmin.bind(this);
180     this.handlePurgePerson = this.handlePurgePerson.bind(this);
181     this.handlePurgeComment = this.handlePurgeComment.bind(this);
182     this.handleCommentReport = this.handleCommentReport.bind(this);
183     this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
184     this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
185     this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
186     this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
187     this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
188     this.handleBanPerson = this.handleBanPerson.bind(this);
189     this.handlePostVote = this.handlePostVote.bind(this);
190     this.handlePostEdit = this.handlePostEdit.bind(this);
191     this.handlePostReport = this.handlePostReport.bind(this);
192     this.handleLockPost = this.handleLockPost.bind(this);
193     this.handleDeletePost = this.handleDeletePost.bind(this);
194     this.handleRemovePost = this.handleRemovePost.bind(this);
195     this.handleSavePost = this.handleSavePost.bind(this);
196     this.handlePurgePost = this.handlePurgePost.bind(this);
197     this.handleFeaturePost = this.handleFeaturePost.bind(this);
198     this.mainContentRef = createRef();
199     // Only fetch the data if coming from another route
200     if (FirstLoadService.isFirstLoad) {
201       const { communityRes, commentsRes, postsRes } = this.isoData.routeData;
202
203       this.state = {
204         ...this.state,
205         isIsomorphic: true,
206         commentsRes,
207         communityRes,
208         postsRes,
209       };
210     }
211   }
212
213   async fetchCommunity() {
214     this.setState({ communityRes: { state: "loading" } });
215     this.setState({
216       communityRes: await HttpService.client.getCommunity({
217         name: this.props.match.params.name,
218         auth: myAuth(),
219       }),
220     });
221   }
222
223   async componentDidMount() {
224     if (!this.state.isIsomorphic) {
225       await Promise.all([this.fetchCommunity(), this.fetchData()]);
226     }
227
228     setupTippy();
229   }
230
231   static async fetchInitialData({
232     client,
233     path,
234     query: { dataType: urlDataType, page: urlPage, sort: urlSort },
235     auth,
236   }: InitialFetchRequest<QueryParams<CommunityProps>>): Promise<
237     Promise<CommunityData>
238   > {
239     const pathSplit = path.split("/");
240
241     const communityName = pathSplit[2];
242     const communityForm: GetCommunity = {
243       name: communityName,
244       auth,
245     };
246
247     const dataType = getDataTypeFromQuery(urlDataType);
248
249     const sort = getSortTypeFromQuery(urlSort);
250
251     const page = getPageFromString(urlPage);
252
253     let postsResponse: RequestState<GetPostsResponse> = { state: "empty" };
254     let commentsResponse: RequestState<GetCommentsResponse> = {
255       state: "empty",
256     };
257
258     if (dataType === DataType.Post) {
259       const getPostsForm: GetPosts = {
260         community_name: communityName,
261         page,
262         limit: fetchLimit,
263         sort,
264         type_: "All",
265         saved_only: false,
266         auth,
267       };
268
269       postsResponse = await client.getPosts(getPostsForm);
270     } else {
271       const getCommentsForm: GetComments = {
272         community_name: communityName,
273         page,
274         limit: fetchLimit,
275         sort: postToCommentSortType(sort),
276         type_: "All",
277         saved_only: false,
278         auth,
279       };
280
281       commentsResponse = await client.getComments(getCommentsForm);
282     }
283
284     return {
285       communityRes: await client.getCommunity(communityForm),
286       commentsRes: commentsResponse,
287       postsRes: postsResponse,
288     };
289   }
290
291   get documentTitle(): string {
292     const cRes = this.state.communityRes;
293     return cRes.state == "success"
294       ? `${cRes.data.community_view.community.title} - ${this.isoData.site_res.site_view.site.name}`
295       : "";
296   }
297
298   renderCommunity() {
299     switch (this.state.communityRes.state) {
300       case "loading":
301         return (
302           <h5>
303             <Spinner large />
304           </h5>
305         );
306       case "success": {
307         const res = this.state.communityRes.data;
308         const { page } = getCommunityQueryParams();
309
310         return (
311           <>
312             <HtmlTags
313               title={this.documentTitle}
314               path={this.context.router.route.match.url}
315               description={res.community_view.community.description}
316               image={res.community_view.community.icon}
317             />
318
319             <div className="row">
320               <main
321                 className="col-12 col-md-8 col-lg-9"
322                 ref={this.mainContentRef}
323               >
324                 {this.communityInfo(res)}
325                 <div className="d-block d-md-none">
326                   <button
327                     className="btn btn-secondary d-inline-block mb-2 me-3"
328                     onClick={linkEvent(this, this.handleShowSidebarMobile)}
329                   >
330                     {I18NextService.i18n.t("sidebar")}{" "}
331                     <Icon
332                       icon={
333                         this.state.showSidebarMobile
334                           ? `minus-square`
335                           : `plus-square`
336                       }
337                       classes="icon-inline"
338                     />
339                   </button>
340                   {this.state.showSidebarMobile && this.sidebar(res)}
341                 </div>
342                 {this.selects(res)}
343                 {this.listings(res)}
344                 <Paginator page={page} onChange={this.handlePageChange} />
345               </main>
346               <aside className="d-none d-md-block col-md-4 col-lg-3">
347                 {this.sidebar(res)}
348               </aside>
349             </div>
350           </>
351         );
352       }
353     }
354   }
355
356   render() {
357     return (
358       <div className="community container-lg">{this.renderCommunity()}</div>
359     );
360   }
361
362   sidebar(res: GetCommunityResponse) {
363     const { site_res } = this.isoData;
364     // For some reason, this returns an empty vec if it matches the site langs
365     const communityLangs =
366       res.discussion_languages.length === 0
367         ? site_res.all_languages.map(({ id }) => id)
368         : res.discussion_languages;
369
370     return (
371       <>
372         <Sidebar
373           community_view={res.community_view}
374           moderators={res.moderators}
375           admins={site_res.admins}
376           enableNsfw={enableNsfw(site_res)}
377           editable
378           allLanguages={site_res.all_languages}
379           siteLanguages={site_res.discussion_languages}
380           communityLanguages={communityLangs}
381           onDeleteCommunity={this.handleDeleteCommunity}
382           onRemoveCommunity={this.handleRemoveCommunity}
383           onLeaveModTeam={this.handleAddModToCommunity}
384           onFollowCommunity={this.handleFollow}
385           onBlockCommunity={this.handleBlockCommunity}
386           onPurgeCommunity={this.handlePurgeCommunity}
387           onEditCommunity={this.handleEditCommunity}
388         />
389         {!res.community_view.community.local && res.site && (
390           <SiteSidebar site={res.site} showLocal={showLocal(this.isoData)} />
391         )}
392       </>
393     );
394   }
395
396   listings(communityRes: GetCommunityResponse) {
397     const { dataType } = getCommunityQueryParams();
398     const { site_res } = this.isoData;
399
400     if (dataType === DataType.Post) {
401       switch (this.state.postsRes.state) {
402         case "loading":
403           return (
404             <h5>
405               <Spinner large />
406             </h5>
407           );
408         case "success":
409           return (
410             <PostListings
411               posts={this.state.postsRes.data.posts}
412               removeDuplicates
413               enableDownvotes={enableDownvotes(site_res)}
414               enableNsfw={enableNsfw(site_res)}
415               allLanguages={site_res.all_languages}
416               siteLanguages={site_res.discussion_languages}
417               onBlockPerson={this.handleBlockPerson}
418               onPostEdit={this.handlePostEdit}
419               onPostVote={this.handlePostVote}
420               onPostReport={this.handlePostReport}
421               onLockPost={this.handleLockPost}
422               onDeletePost={this.handleDeletePost}
423               onRemovePost={this.handleRemovePost}
424               onSavePost={this.handleSavePost}
425               onPurgePerson={this.handlePurgePerson}
426               onPurgePost={this.handlePurgePost}
427               onBanPerson={this.handleBanPerson}
428               onBanPersonFromCommunity={this.handleBanFromCommunity}
429               onAddModToCommunity={this.handleAddModToCommunity}
430               onAddAdmin={this.handleAddAdmin}
431               onTransferCommunity={this.handleTransferCommunity}
432               onFeaturePost={this.handleFeaturePost}
433             />
434           );
435       }
436     } else {
437       switch (this.state.commentsRes.state) {
438         case "loading":
439           return (
440             <h5>
441               <Spinner large />
442             </h5>
443           );
444         case "success":
445           return (
446             <CommentNodes
447               nodes={commentsToFlatNodes(this.state.commentsRes.data.comments)}
448               viewType={CommentViewType.Flat}
449               finished={this.state.finished}
450               noIndent
451               showContext
452               enableDownvotes={enableDownvotes(site_res)}
453               moderators={communityRes.moderators}
454               admins={site_res.admins}
455               allLanguages={site_res.all_languages}
456               siteLanguages={site_res.discussion_languages}
457               onSaveComment={this.handleSaveComment}
458               onBlockPerson={this.handleBlockPerson}
459               onDeleteComment={this.handleDeleteComment}
460               onRemoveComment={this.handleRemoveComment}
461               onCommentVote={this.handleCommentVote}
462               onCommentReport={this.handleCommentReport}
463               onDistinguishComment={this.handleDistinguishComment}
464               onAddModToCommunity={this.handleAddModToCommunity}
465               onAddAdmin={this.handleAddAdmin}
466               onTransferCommunity={this.handleTransferCommunity}
467               onPurgeComment={this.handlePurgeComment}
468               onPurgePerson={this.handlePurgePerson}
469               onCommentReplyRead={this.handleCommentReplyRead}
470               onPersonMentionRead={this.handlePersonMentionRead}
471               onBanPersonFromCommunity={this.handleBanFromCommunity}
472               onBanPerson={this.handleBanPerson}
473               onCreateComment={this.handleCreateComment}
474               onEditComment={this.handleEditComment}
475             />
476           );
477       }
478     }
479   }
480
481   communityInfo(res: GetCommunityResponse) {
482     const community = res.community_view.community;
483
484     return (
485       community && (
486         <div className="mb-2">
487           <BannerIconHeader banner={community.banner} icon={community.icon} />
488           <h1 className="h4 mb-0 overflow-wrap-anywhere">{community.title}</h1>
489           <CommunityLink
490             community={community}
491             realLink
492             useApubName
493             muted
494             hideAvatar
495           />
496         </div>
497       )
498     );
499   }
500
501   selects(res: GetCommunityResponse) {
502     // let communityRss = this.state.communityRes.map(r =>
503     //   communityRSSUrl(r.community_view.community.actor_id, this.state.sort)
504     // );
505     const { dataType, sort } = getCommunityQueryParams();
506     const communityRss = res
507       ? communityRSSUrl(res.community_view.community.actor_id, sort)
508       : undefined;
509
510     return (
511       <div className="mb-3">
512         <span className="me-3">
513           <DataTypeSelect
514             type_={dataType}
515             onChange={this.handleDataTypeChange}
516           />
517         </span>
518         <span className="me-2">
519           <SortSelect sort={sort} onChange={this.handleSortChange} />
520         </span>
521         {communityRss && (
522           <>
523             <a href={communityRss} title="RSS" rel={relTags}>
524               <Icon icon="rss" classes="text-muted small" />
525             </a>
526             <link
527               rel="alternate"
528               type="application/atom+xml"
529               href={communityRss}
530             />
531           </>
532         )}
533       </div>
534     );
535   }
536
537   handlePageChange(page: number) {
538     this.updateUrl({ page });
539     window.scrollTo(0, 0);
540   }
541
542   handleSortChange(sort: SortType) {
543     this.updateUrl({ sort, page: 1 });
544     window.scrollTo(0, 0);
545   }
546
547   handleDataTypeChange(dataType: DataType) {
548     this.updateUrl({ dataType, page: 1 });
549     window.scrollTo(0, 0);
550   }
551
552   handleShowSidebarMobile(i: Community) {
553     i.setState(({ showSidebarMobile }) => ({
554       showSidebarMobile: !showSidebarMobile,
555     }));
556   }
557
558   async updateUrl({ dataType, page, sort }: Partial<CommunityProps>) {
559     const {
560       dataType: urlDataType,
561       page: urlPage,
562       sort: urlSort,
563     } = getCommunityQueryParams();
564
565     const queryParams: QueryParams<CommunityProps> = {
566       dataType: getDataTypeString(dataType ?? urlDataType),
567       page: (page ?? urlPage).toString(),
568       sort: sort ?? urlSort,
569     };
570
571     this.props.history.push(
572       `/c/${this.props.match.params.name}${getQueryString(queryParams)}`
573     );
574
575     await this.fetchData();
576   }
577
578   async fetchData() {
579     const { dataType, page, sort } = getCommunityQueryParams();
580     const { name } = this.props.match.params;
581
582     if (dataType === DataType.Post) {
583       this.setState({ postsRes: { state: "loading" } });
584       this.setState({
585         postsRes: await HttpService.client.getPosts({
586           page,
587           limit: fetchLimit,
588           sort,
589           type_: "All",
590           community_name: name,
591           saved_only: false,
592           auth: myAuth(),
593         }),
594       });
595     } else {
596       this.setState({ commentsRes: { state: "loading" } });
597       this.setState({
598         commentsRes: await HttpService.client.getComments({
599           page,
600           limit: fetchLimit,
601           sort: postToCommentSortType(sort),
602           type_: "All",
603           community_name: name,
604           saved_only: false,
605           auth: myAuth(),
606         }),
607       });
608     }
609
610     setupTippy();
611   }
612
613   async handleDeleteCommunity(form: DeleteCommunity) {
614     const deleteCommunityRes = await HttpService.client.deleteCommunity(form);
615     this.updateCommunity(deleteCommunityRes);
616   }
617
618   async handleAddModToCommunity(form: AddModToCommunity) {
619     const addModRes = await HttpService.client.addModToCommunity(form);
620     this.updateModerators(addModRes);
621   }
622
623   async handleFollow(form: FollowCommunity) {
624     const followCommunityRes = await HttpService.client.followCommunity(form);
625     this.updateCommunity(followCommunityRes);
626
627     // Update myUserInfo
628     if (followCommunityRes.state == "success") {
629       const communityId = followCommunityRes.data.community_view.community.id;
630       const mui = UserService.Instance.myUserInfo;
631       if (mui) {
632         mui.follows = mui.follows.filter(i => i.community.id != communityId);
633       }
634     }
635   }
636
637   async handlePurgeCommunity(form: PurgeCommunity) {
638     const purgeCommunityRes = await HttpService.client.purgeCommunity(form);
639     this.purgeItem(purgeCommunityRes);
640   }
641
642   async handlePurgePerson(form: PurgePerson) {
643     const purgePersonRes = await HttpService.client.purgePerson(form);
644     this.purgeItem(purgePersonRes);
645   }
646
647   async handlePurgeComment(form: PurgeComment) {
648     const purgeCommentRes = await HttpService.client.purgeComment(form);
649     this.purgeItem(purgeCommentRes);
650   }
651
652   async handlePurgePost(form: PurgePost) {
653     const purgeRes = await HttpService.client.purgePost(form);
654     this.purgeItem(purgeRes);
655   }
656
657   async handleBlockCommunity(form: BlockCommunity) {
658     const blockCommunityRes = await HttpService.client.blockCommunity(form);
659     if (blockCommunityRes.state == "success") {
660       updateCommunityBlock(blockCommunityRes.data);
661       this.setState(s => {
662         if (s.communityRes.state == "success") {
663           s.communityRes.data.community_view.blocked =
664             blockCommunityRes.data.blocked;
665         }
666       });
667     }
668   }
669
670   async handleBlockPerson(form: BlockPerson) {
671     const blockPersonRes = await HttpService.client.blockPerson(form);
672     if (blockPersonRes.state == "success") {
673       updatePersonBlock(blockPersonRes.data);
674     }
675   }
676
677   async handleRemoveCommunity(form: RemoveCommunity) {
678     const removeCommunityRes = await HttpService.client.removeCommunity(form);
679     this.updateCommunity(removeCommunityRes);
680   }
681
682   async handleEditCommunity(form: EditCommunity) {
683     const res = await HttpService.client.editCommunity(form);
684     this.updateCommunity(res);
685
686     return res;
687   }
688
689   async handleCreateComment(form: CreateComment) {
690     const createCommentRes = await HttpService.client.createComment(form);
691     this.createAndUpdateComments(createCommentRes);
692
693     return createCommentRes;
694   }
695
696   async handleEditComment(form: EditComment) {
697     const editCommentRes = await HttpService.client.editComment(form);
698     this.findAndUpdateComment(editCommentRes);
699
700     return editCommentRes;
701   }
702
703   async handleDeleteComment(form: DeleteComment) {
704     const deleteCommentRes = await HttpService.client.deleteComment(form);
705     this.findAndUpdateComment(deleteCommentRes);
706   }
707
708   async handleDeletePost(form: DeletePost) {
709     const deleteRes = await HttpService.client.deletePost(form);
710     this.findAndUpdatePost(deleteRes);
711   }
712
713   async handleRemovePost(form: RemovePost) {
714     const removeRes = await HttpService.client.removePost(form);
715     this.findAndUpdatePost(removeRes);
716   }
717
718   async handleRemoveComment(form: RemoveComment) {
719     const removeCommentRes = await HttpService.client.removeComment(form);
720     this.findAndUpdateComment(removeCommentRes);
721   }
722
723   async handleSaveComment(form: SaveComment) {
724     const saveCommentRes = await HttpService.client.saveComment(form);
725     this.findAndUpdateComment(saveCommentRes);
726   }
727
728   async handleSavePost(form: SavePost) {
729     const saveRes = await HttpService.client.savePost(form);
730     this.findAndUpdatePost(saveRes);
731   }
732
733   async handleFeaturePost(form: FeaturePost) {
734     const featureRes = await HttpService.client.featurePost(form);
735     this.findAndUpdatePost(featureRes);
736   }
737
738   async handleCommentVote(form: CreateCommentLike) {
739     const voteRes = await HttpService.client.likeComment(form);
740     this.findAndUpdateComment(voteRes);
741   }
742
743   async handlePostEdit(form: EditPost) {
744     const res = await HttpService.client.editPost(form);
745     this.findAndUpdatePost(res);
746   }
747
748   async handlePostVote(form: CreatePostLike) {
749     const voteRes = await HttpService.client.likePost(form);
750     this.findAndUpdatePost(voteRes);
751   }
752
753   async handleCommentReport(form: CreateCommentReport) {
754     const reportRes = await HttpService.client.createCommentReport(form);
755     if (reportRes.state == "success") {
756       toast(I18NextService.i18n.t("report_created"));
757     }
758   }
759
760   async handlePostReport(form: CreatePostReport) {
761     const reportRes = await HttpService.client.createPostReport(form);
762     if (reportRes.state == "success") {
763       toast(I18NextService.i18n.t("report_created"));
764     }
765   }
766
767   async handleLockPost(form: LockPost) {
768     const lockRes = await HttpService.client.lockPost(form);
769     this.findAndUpdatePost(lockRes);
770   }
771
772   async handleDistinguishComment(form: DistinguishComment) {
773     const distinguishRes = await HttpService.client.distinguishComment(form);
774     this.findAndUpdateComment(distinguishRes);
775   }
776
777   async handleAddAdmin(form: AddAdmin) {
778     const addAdminRes = await HttpService.client.addAdmin(form);
779
780     if (addAdminRes.state == "success") {
781       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
782     }
783   }
784
785   async handleTransferCommunity(form: TransferCommunity) {
786     const transferCommunityRes = await HttpService.client.transferCommunity(
787       form
788     );
789     toast(I18NextService.i18n.t("transfer_community"));
790     this.updateCommunityFull(transferCommunityRes);
791   }
792
793   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
794     const readRes = await HttpService.client.markCommentReplyAsRead(form);
795     this.findAndUpdateCommentReply(readRes);
796   }
797
798   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
799     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
800     await HttpService.client.markPersonMentionAsRead(form);
801   }
802
803   async handleBanFromCommunity(form: BanFromCommunity) {
804     const banRes = await HttpService.client.banFromCommunity(form);
805     this.updateBanFromCommunity(banRes);
806   }
807
808   async handleBanPerson(form: BanPerson) {
809     const banRes = await HttpService.client.banPerson(form);
810     this.updateBan(banRes);
811   }
812
813   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
814     // Maybe not necessary
815     if (banRes.state == "success") {
816       this.setState(s => {
817         if (s.postsRes.state == "success") {
818           s.postsRes.data.posts
819             .filter(c => c.creator.id == banRes.data.person_view.person.id)
820             .forEach(
821               c => (c.creator_banned_from_community = banRes.data.banned)
822             );
823         }
824         if (s.commentsRes.state == "success") {
825           s.commentsRes.data.comments
826             .filter(c => c.creator.id == banRes.data.person_view.person.id)
827             .forEach(
828               c => (c.creator_banned_from_community = banRes.data.banned)
829             );
830         }
831         return s;
832       });
833     }
834   }
835
836   updateBan(banRes: RequestState<BanPersonResponse>) {
837     // Maybe not necessary
838     if (banRes.state == "success") {
839       this.setState(s => {
840         if (s.postsRes.state == "success") {
841           s.postsRes.data.posts
842             .filter(c => c.creator.id == banRes.data.person_view.person.id)
843             .forEach(c => (c.creator.banned = banRes.data.banned));
844         }
845         if (s.commentsRes.state == "success") {
846           s.commentsRes.data.comments
847             .filter(c => c.creator.id == banRes.data.person_view.person.id)
848             .forEach(c => (c.creator.banned = banRes.data.banned));
849         }
850         return s;
851       });
852     }
853   }
854
855   updateCommunity(res: RequestState<CommunityResponse>) {
856     this.setState(s => {
857       if (s.communityRes.state == "success" && res.state == "success") {
858         s.communityRes.data.community_view = res.data.community_view;
859         s.communityRes.data.discussion_languages =
860           res.data.discussion_languages;
861       }
862       return s;
863     });
864   }
865
866   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
867     this.setState(s => {
868       if (s.communityRes.state == "success" && res.state == "success") {
869         s.communityRes.data.community_view = res.data.community_view;
870         s.communityRes.data.moderators = res.data.moderators;
871       }
872       return s;
873     });
874   }
875
876   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
877     if (purgeRes.state == "success") {
878       toast(I18NextService.i18n.t("purge_success"));
879       this.context.router.history.push(`/`);
880     }
881   }
882
883   findAndUpdateComment(res: RequestState<CommentResponse>) {
884     this.setState(s => {
885       if (s.commentsRes.state == "success" && res.state == "success") {
886         s.commentsRes.data.comments = editComment(
887           res.data.comment_view,
888           s.commentsRes.data.comments
889         );
890         s.finished.set(res.data.comment_view.comment.id, true);
891       }
892       return s;
893     });
894   }
895
896   createAndUpdateComments(res: RequestState<CommentResponse>) {
897     this.setState(s => {
898       if (s.commentsRes.state == "success" && res.state == "success") {
899         s.commentsRes.data.comments.unshift(res.data.comment_view);
900
901         // Set finished for the parent
902         s.finished.set(
903           getCommentParentId(res.data.comment_view.comment) ?? 0,
904           true
905         );
906       }
907       return s;
908     });
909   }
910
911   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
912     this.setState(s => {
913       if (s.commentsRes.state == "success" && res.state == "success") {
914         s.commentsRes.data.comments = editWith(
915           res.data.comment_reply_view,
916           s.commentsRes.data.comments
917         );
918       }
919       return s;
920     });
921   }
922
923   findAndUpdatePost(res: RequestState<PostResponse>) {
924     this.setState(s => {
925       if (s.postsRes.state == "success" && res.state == "success") {
926         s.postsRes.data.posts = editPost(
927           res.data.post_view,
928           s.postsRes.data.posts
929         );
930       }
931       return s;
932     });
933   }
934
935   updateModerators(res: RequestState<AddModToCommunityResponse>) {
936     // Update the moderators
937     this.setState(s => {
938       if (s.communityRes.state == "success" && res.state == "success") {
939         s.communityRes.data.moderators = res.data.moderators;
940       }
941       return s;
942     });
943   }
944 }