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