]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
Merge pull request #1332 from alectrocute/breakout-role-utils
[lemmy-ui.git] / src / shared / components / community / community.tsx
1 import { getQueryParams, getQueryString } from "@utils/helpers";
2 import type { QueryParams } from "@utils/types";
3 import { Component, linkEvent } from "inferno";
4 import { RouteComponentProps } from "inferno-router/dist/Route";
5 import {
6   AddAdmin,
7   AddModToCommunity,
8   AddModToCommunityResponse,
9   BanFromCommunity,
10   BanFromCommunityResponse,
11   BanPerson,
12   BanPersonResponse,
13   BlockCommunity,
14   BlockPerson,
15   CommentId,
16   CommentReplyResponse,
17   CommentResponse,
18   CommunityResponse,
19   CreateComment,
20   CreateCommentLike,
21   CreateCommentReport,
22   CreatePostLike,
23   CreatePostReport,
24   DeleteComment,
25   DeleteCommunity,
26   DeletePost,
27   DistinguishComment,
28   EditComment,
29   EditCommunity,
30   EditPost,
31   FeaturePost,
32   FollowCommunity,
33   GetComments,
34   GetCommentsResponse,
35   GetCommunity,
36   GetCommunityResponse,
37   GetPosts,
38   GetPostsResponse,
39   GetSiteResponse,
40   LockPost,
41   MarkCommentReplyAsRead,
42   MarkPersonMentionAsRead,
43   PostResponse,
44   PurgeComment,
45   PurgeCommunity,
46   PurgeItemResponse,
47   PurgePerson,
48   PurgePost,
49   RemoveComment,
50   RemoveCommunity,
51   RemovePost,
52   SaveComment,
53   SavePost,
54   SortType,
55   TransferCommunity,
56 } from "lemmy-js-client";
57 import { i18n } from "../../i18next";
58 import {
59   CommentViewType,
60   DataType,
61   InitialFetchRequest,
62 } from "../../interfaces";
63 import { UserService } from "../../services";
64 import { FirstLoadService } from "../../services/FirstLoadService";
65 import { HttpService, RequestState } from "../../services/HttpService";
66 import {
67   RouteDataResponse,
68   commentsToFlatNodes,
69   communityRSSUrl,
70   editComment,
71   editPost,
72   editWith,
73   enableDownvotes,
74   enableNsfw,
75   fetchLimit,
76   getCommentParentId,
77   getDataTypeString,
78   getPageFromString,
79   myAuth,
80   postToCommentSortType,
81   relTags,
82   restoreScrollPosition,
83   saveScrollPosition,
84   setIsoData,
85   setupTippy,
86   showLocal,
87   toast,
88   updateCommunityBlock,
89   updatePersonBlock,
90 } from "../../utils";
91 import { CommentNodes } from "../comment/comment-nodes";
92 import { BannerIconHeader } from "../common/banner-icon-header";
93 import { DataTypeSelect } from "../common/data-type-select";
94 import { HtmlTags } from "../common/html-tags";
95 import { Icon, Spinner } from "../common/icon";
96 import { Paginator } from "../common/paginator";
97 import { SortSelect } from "../common/sort-select";
98 import { Sidebar } from "../community/sidebar";
99 import { SiteSidebar } from "../home/site-sidebar";
100 import { PostListings } from "../post/post-listings";
101 import { CommunityLink } from "./community-link";
102
103 type CommunityData = RouteDataResponse<{
104   communityRes: GetCommunityResponse;
105   postsRes: GetPostsResponse;
106   commentsRes: GetCommentsResponse;
107 }>;
108
109 interface State {
110   communityRes: RequestState<GetCommunityResponse>;
111   postsRes: RequestState<GetPostsResponse>;
112   commentsRes: RequestState<GetCommentsResponse>;
113   siteRes: GetSiteResponse;
114   showSidebarMobile: boolean;
115   finished: Map<CommentId, boolean | undefined>;
116   isIsomorphic: boolean;
117 }
118
119 interface CommunityProps {
120   dataType: DataType;
121   sort: SortType;
122   page: number;
123 }
124
125 function getCommunityQueryParams() {
126   return getQueryParams<CommunityProps>({
127     dataType: getDataTypeFromQuery,
128     page: getPageFromString,
129     sort: getSortTypeFromQuery,
130   });
131 }
132
133 function getDataTypeFromQuery(type?: string): DataType {
134   return type ? DataType[type] : DataType.Post;
135 }
136
137 function getSortTypeFromQuery(type?: string): SortType {
138   const mySortType =
139     UserService.Instance.myUserInfo?.local_user_view.local_user
140       .default_sort_type;
141
142   return type ? (type as SortType) : mySortType ?? "Active";
143 }
144
145 export class Community extends Component<
146   RouteComponentProps<{ name: string }>,
147   State
148 > {
149   private isoData = setIsoData<CommunityData>(this.context);
150   state: State = {
151     communityRes: { state: "empty" },
152     postsRes: { state: "empty" },
153     commentsRes: { state: "empty" },
154     siteRes: this.isoData.site_res,
155     showSidebarMobile: false,
156     finished: new Map(),
157     isIsomorphic: false,
158   };
159
160   constructor(props: RouteComponentProps<{ name: string }>, context: any) {
161     super(props, context);
162
163     this.handleSortChange = this.handleSortChange.bind(this);
164     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
165     this.handlePageChange = this.handlePageChange.bind(this);
166
167     // All of the action binds
168     this.handleDeleteCommunity = this.handleDeleteCommunity.bind(this);
169     this.handleEditCommunity = this.handleEditCommunity.bind(this);
170     this.handleFollow = this.handleFollow.bind(this);
171     this.handleRemoveCommunity = this.handleRemoveCommunity.bind(this);
172     this.handleCreateComment = this.handleCreateComment.bind(this);
173     this.handleEditComment = this.handleEditComment.bind(this);
174     this.handleSaveComment = this.handleSaveComment.bind(this);
175     this.handleBlockCommunity = this.handleBlockCommunity.bind(this);
176     this.handleBlockPerson = this.handleBlockPerson.bind(this);
177     this.handleDeleteComment = this.handleDeleteComment.bind(this);
178     this.handleRemoveComment = this.handleRemoveComment.bind(this);
179     this.handleCommentVote = this.handleCommentVote.bind(this);
180     this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
181     this.handleAddAdmin = this.handleAddAdmin.bind(this);
182     this.handlePurgePerson = this.handlePurgePerson.bind(this);
183     this.handlePurgeComment = this.handlePurgeComment.bind(this);
184     this.handleCommentReport = this.handleCommentReport.bind(this);
185     this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
186     this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
187     this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
188     this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
189     this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
190     this.handleBanPerson = this.handleBanPerson.bind(this);
191     this.handlePostVote = this.handlePostVote.bind(this);
192     this.handlePostEdit = this.handlePostEdit.bind(this);
193     this.handlePostReport = this.handlePostReport.bind(this);
194     this.handleLockPost = this.handleLockPost.bind(this);
195     this.handleDeletePost = this.handleDeletePost.bind(this);
196     this.handleRemovePost = this.handleRemovePost.bind(this);
197     this.handleSavePost = this.handleSavePost.bind(this);
198     this.handlePurgePost = this.handlePurgePost.bind(this);
199     this.handleFeaturePost = this.handleFeaturePost.bind(this);
200
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   componentWillUnmount() {
234     saveScrollPosition(this.context);
235   }
236
237   static async fetchInitialData({
238     client,
239     path,
240     query: { dataType: urlDataType, page: urlPage, sort: urlSort },
241     auth,
242   }: InitialFetchRequest<QueryParams<CommunityProps>>): Promise<
243     Promise<CommunityData>
244   > {
245     const pathSplit = path.split("/");
246
247     const communityName = pathSplit[2];
248     const communityForm: GetCommunity = {
249       name: communityName,
250       auth,
251     };
252
253     const dataType = getDataTypeFromQuery(urlDataType);
254
255     const sort = getSortTypeFromQuery(urlSort);
256
257     const page = getPageFromString(urlPage);
258
259     let postsResponse: RequestState<GetPostsResponse> = { state: "empty" };
260     let commentsResponse: RequestState<GetCommentsResponse> = {
261       state: "empty",
262     };
263
264     if (dataType === DataType.Post) {
265       const getPostsForm: GetPosts = {
266         community_name: communityName,
267         page,
268         limit: fetchLimit,
269         sort,
270         type_: "All",
271         saved_only: false,
272         auth,
273       };
274
275       postsResponse = await client.getPosts(getPostsForm);
276     } else {
277       const getCommentsForm: GetComments = {
278         community_name: communityName,
279         page,
280         limit: fetchLimit,
281         sort: postToCommentSortType(sort),
282         type_: "All",
283         saved_only: false,
284         auth,
285       };
286
287       commentsResponse = await client.getComments(getCommentsForm);
288     }
289
290     return {
291       communityRes: await client.getCommunity(communityForm),
292       commentsRes: commentsResponse,
293       postsRes: postsResponse,
294     };
295   }
296
297   get documentTitle(): string {
298     const cRes = this.state.communityRes;
299     return cRes.state == "success"
300       ? `${cRes.data.community_view.community.title} - ${this.isoData.site_res.site_view.site.name}`
301       : "";
302   }
303
304   renderCommunity() {
305     switch (this.state.communityRes.state) {
306       case "loading":
307         return (
308           <h5>
309             <Spinner large />
310           </h5>
311         );
312       case "success": {
313         const res = this.state.communityRes.data;
314         const { page } = getCommunityQueryParams();
315
316         return (
317           <>
318             <HtmlTags
319               title={this.documentTitle}
320               path={this.context.router.route.match.url}
321               description={res.community_view.community.description}
322               image={res.community_view.community.icon}
323             />
324
325             <div className="row">
326               <div className="col-12 col-md-8">
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                     {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               </div>
349               <div className="d-none d-md-block col-md-4">
350                 {this.sidebar(res)}
351               </div>
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             />
437           );
438       }
439     } else {
440       switch (this.state.commentsRes.state) {
441         case "loading":
442           return (
443             <h5>
444               <Spinner large />
445             </h5>
446           );
447         case "success":
448           return (
449             <CommentNodes
450               nodes={commentsToFlatNodes(this.state.commentsRes.data.comments)}
451               viewType={CommentViewType.Flat}
452               finished={this.state.finished}
453               noIndent
454               showContext
455               enableDownvotes={enableDownvotes(site_res)}
456               moderators={communityRes.moderators}
457               admins={site_res.admins}
458               allLanguages={site_res.all_languages}
459               siteLanguages={site_res.discussion_languages}
460               onSaveComment={this.handleSaveComment}
461               onBlockPerson={this.handleBlockPerson}
462               onDeleteComment={this.handleDeleteComment}
463               onRemoveComment={this.handleRemoveComment}
464               onCommentVote={this.handleCommentVote}
465               onCommentReport={this.handleCommentReport}
466               onDistinguishComment={this.handleDistinguishComment}
467               onAddModToCommunity={this.handleAddModToCommunity}
468               onAddAdmin={this.handleAddAdmin}
469               onTransferCommunity={this.handleTransferCommunity}
470               onPurgeComment={this.handlePurgeComment}
471               onPurgePerson={this.handlePurgePerson}
472               onCommentReplyRead={this.handleCommentReplyRead}
473               onPersonMentionRead={this.handlePersonMentionRead}
474               onBanPersonFromCommunity={this.handleBanFromCommunity}
475               onBanPerson={this.handleBanPerson}
476               onCreateComment={this.handleCreateComment}
477               onEditComment={this.handleEditComment}
478             />
479           );
480       }
481     }
482   }
483
484   communityInfo(res: GetCommunityResponse) {
485     const community = res.community_view.community;
486
487     return (
488       community && (
489         <div className="mb-2">
490           <BannerIconHeader banner={community.banner} icon={community.icon} />
491           <h5 className="mb-0 overflow-wrap-anywhere">{community.title}</h5>
492           <CommunityLink
493             community={community}
494             realLink
495             useApubName
496             muted
497             hideAvatar
498           />
499         </div>
500       )
501     );
502   }
503
504   selects(res: GetCommunityResponse) {
505     // let communityRss = this.state.communityRes.map(r =>
506     //   communityRSSUrl(r.community_view.community.actor_id, this.state.sort)
507     // );
508     const { dataType, sort } = getCommunityQueryParams();
509     const communityRss = res
510       ? communityRSSUrl(res.community_view.community.actor_id, sort)
511       : undefined;
512
513     return (
514       <div className="mb-3">
515         <span className="me-3">
516           <DataTypeSelect
517             type_={dataType}
518             onChange={this.handleDataTypeChange}
519           />
520         </span>
521         <span className="me-2">
522           <SortSelect sort={sort} onChange={this.handleSortChange} />
523         </span>
524         {communityRss && (
525           <>
526             <a href={communityRss} title="RSS" rel={relTags}>
527               <Icon icon="rss" classes="text-muted small" />
528             </a>
529             <link
530               rel="alternate"
531               type="application/atom+xml"
532               href={communityRss}
533             />
534           </>
535         )}
536       </div>
537     );
538   }
539
540   handlePageChange(page: number) {
541     this.updateUrl({ page });
542     window.scrollTo(0, 0);
543   }
544
545   handleSortChange(sort: SortType) {
546     this.updateUrl({ sort, page: 1 });
547     window.scrollTo(0, 0);
548   }
549
550   handleDataTypeChange(dataType: DataType) {
551     this.updateUrl({ dataType, page: 1 });
552     window.scrollTo(0, 0);
553   }
554
555   handleShowSidebarMobile(i: Community) {
556     i.setState(({ showSidebarMobile }) => ({
557       showSidebarMobile: !showSidebarMobile,
558     }));
559   }
560
561   async updateUrl({ dataType, page, sort }: Partial<CommunityProps>) {
562     const {
563       dataType: urlDataType,
564       page: urlPage,
565       sort: urlSort,
566     } = getCommunityQueryParams();
567
568     const queryParams: QueryParams<CommunityProps> = {
569       dataType: getDataTypeString(dataType ?? urlDataType),
570       page: (page ?? urlPage).toString(),
571       sort: sort ?? urlSort,
572     };
573
574     this.props.history.push(
575       `/c/${this.props.match.params.name}${getQueryString(queryParams)}`
576     );
577
578     await this.fetchData();
579   }
580
581   async fetchData() {
582     const { dataType, page, sort } = getCommunityQueryParams();
583     const { name } = this.props.match.params;
584
585     if (dataType === DataType.Post) {
586       this.setState({ postsRes: { state: "loading" } });
587       this.setState({
588         postsRes: await HttpService.client.getPosts({
589           page,
590           limit: fetchLimit,
591           sort,
592           type_: "All",
593           community_name: name,
594           saved_only: false,
595           auth: myAuth(),
596         }),
597       });
598     } else {
599       this.setState({ commentsRes: { state: "loading" } });
600       this.setState({
601         commentsRes: await HttpService.client.getComments({
602           page,
603           limit: fetchLimit,
604           sort: postToCommentSortType(sort),
605           type_: "All",
606           community_name: name,
607           saved_only: false,
608           auth: myAuth(),
609         }),
610       });
611     }
612
613     restoreScrollPosition(this.context);
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(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(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(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 handleBanFromCommunity(form: BanFromCommunity) {
808     const banRes = await HttpService.client.banFromCommunity(form);
809     this.updateBanFromCommunity(banRes);
810   }
811
812   async handleBanPerson(form: BanPerson) {
813     const banRes = await HttpService.client.banPerson(form);
814     this.updateBan(banRes);
815   }
816
817   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
818     // Maybe not necessary
819     if (banRes.state == "success") {
820       this.setState(s => {
821         if (s.postsRes.state == "success") {
822           s.postsRes.data.posts
823             .filter(c => c.creator.id == banRes.data.person_view.person.id)
824             .forEach(
825               c => (c.creator_banned_from_community = banRes.data.banned)
826             );
827         }
828         if (s.commentsRes.state == "success") {
829           s.commentsRes.data.comments
830             .filter(c => c.creator.id == banRes.data.person_view.person.id)
831             .forEach(
832               c => (c.creator_banned_from_community = banRes.data.banned)
833             );
834         }
835         return s;
836       });
837     }
838   }
839
840   updateBan(banRes: RequestState<BanPersonResponse>) {
841     // Maybe not necessary
842     if (banRes.state == "success") {
843       this.setState(s => {
844         if (s.postsRes.state == "success") {
845           s.postsRes.data.posts
846             .filter(c => c.creator.id == banRes.data.person_view.person.id)
847             .forEach(c => (c.creator.banned = banRes.data.banned));
848         }
849         if (s.commentsRes.state == "success") {
850           s.commentsRes.data.comments
851             .filter(c => c.creator.id == banRes.data.person_view.person.id)
852             .forEach(c => (c.creator.banned = banRes.data.banned));
853         }
854         return s;
855       });
856     }
857   }
858
859   updateCommunity(res: RequestState<CommunityResponse>) {
860     this.setState(s => {
861       if (s.communityRes.state == "success" && res.state == "success") {
862         s.communityRes.data.community_view = res.data.community_view;
863         s.communityRes.data.discussion_languages =
864           res.data.discussion_languages;
865       }
866       return s;
867     });
868   }
869
870   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
871     this.setState(s => {
872       if (s.communityRes.state == "success" && res.state == "success") {
873         s.communityRes.data.community_view = res.data.community_view;
874         s.communityRes.data.moderators = res.data.moderators;
875       }
876       return s;
877     });
878   }
879
880   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
881     if (purgeRes.state == "success") {
882       toast(i18n.t("purge_success"));
883       this.context.router.history.push(`/`);
884     }
885   }
886
887   findAndUpdateComment(res: RequestState<CommentResponse>) {
888     this.setState(s => {
889       if (s.commentsRes.state == "success" && res.state == "success") {
890         s.commentsRes.data.comments = editComment(
891           res.data.comment_view,
892           s.commentsRes.data.comments
893         );
894         s.finished.set(res.data.comment_view.comment.id, true);
895       }
896       return s;
897     });
898   }
899
900   createAndUpdateComments(res: RequestState<CommentResponse>) {
901     this.setState(s => {
902       if (s.commentsRes.state == "success" && res.state == "success") {
903         s.commentsRes.data.comments.unshift(res.data.comment_view);
904
905         // Set finished for the parent
906         s.finished.set(
907           getCommentParentId(res.data.comment_view.comment) ?? 0,
908           true
909         );
910       }
911       return s;
912     });
913   }
914
915   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
916     this.setState(s => {
917       if (s.commentsRes.state == "success" && res.state == "success") {
918         s.commentsRes.data.comments = editWith(
919           res.data.comment_reply_view,
920           s.commentsRes.data.comments
921         );
922       }
923       return s;
924     });
925   }
926
927   findAndUpdatePost(res: RequestState<PostResponse>) {
928     this.setState(s => {
929       if (s.postsRes.state == "success" && res.state == "success") {
930         s.postsRes.data.posts = editPost(
931           res.data.post_view,
932           s.postsRes.data.posts
933         );
934       }
935       return s;
936     });
937   }
938
939   updateModerators(res: RequestState<AddModToCommunityResponse>) {
940     // Update the moderators
941     this.setState(s => {
942       if (s.communityRes.state == "success" && res.state == "success") {
943         s.communityRes.data.moderators = res.data.moderators;
944       }
945       return s;
946     });
947   }
948 }