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