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