]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
Merge branch 'main' into feat/markdown-format-bar-above
[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           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       this.setState(s => {
650         if (s.communityRes.state == "success") {
651           s.communityRes.data.community_view.blocked =
652             blockCommunityRes.data.blocked;
653         }
654       });
655     }
656   }
657
658   async handleBlockPerson(form: BlockPerson) {
659     const blockPersonRes = await HttpService.client.blockPerson(form);
660     if (blockPersonRes.state == "success") {
661       updatePersonBlock(blockPersonRes.data);
662     }
663   }
664
665   async handleRemoveCommunity(form: RemoveCommunity) {
666     const removeCommunityRes = await HttpService.client.removeCommunity(form);
667     this.updateCommunity(removeCommunityRes);
668   }
669
670   async handleEditCommunity(form: EditCommunity) {
671     const res = await HttpService.client.editCommunity(form);
672     this.updateCommunity(res);
673
674     return res;
675   }
676
677   async handleCreateComment(form: CreateComment) {
678     const createCommentRes = await HttpService.client.createComment(form);
679     this.createAndUpdateComments(createCommentRes);
680
681     return createCommentRes;
682   }
683
684   async handleEditComment(form: EditComment) {
685     const editCommentRes = await HttpService.client.editComment(form);
686     this.findAndUpdateComment(editCommentRes);
687
688     return editCommentRes;
689   }
690
691   async handleDeleteComment(form: DeleteComment) {
692     const deleteCommentRes = await HttpService.client.deleteComment(form);
693     this.findAndUpdateComment(deleteCommentRes);
694   }
695
696   async handleDeletePost(form: DeletePost) {
697     const deleteRes = await HttpService.client.deletePost(form);
698     this.findAndUpdatePost(deleteRes);
699   }
700
701   async handleRemovePost(form: RemovePost) {
702     const removeRes = await HttpService.client.removePost(form);
703     this.findAndUpdatePost(removeRes);
704   }
705
706   async handleRemoveComment(form: RemoveComment) {
707     const removeCommentRes = await HttpService.client.removeComment(form);
708     this.findAndUpdateComment(removeCommentRes);
709   }
710
711   async handleSaveComment(form: SaveComment) {
712     const saveCommentRes = await HttpService.client.saveComment(form);
713     this.findAndUpdateComment(saveCommentRes);
714   }
715
716   async handleSavePost(form: SavePost) {
717     const saveRes = await HttpService.client.savePost(form);
718     this.findAndUpdatePost(saveRes);
719   }
720
721   async handleFeaturePost(form: FeaturePost) {
722     const featureRes = await HttpService.client.featurePost(form);
723     this.findAndUpdatePost(featureRes);
724   }
725
726   async handleCommentVote(form: CreateCommentLike) {
727     const voteRes = await HttpService.client.likeComment(form);
728     this.findAndUpdateComment(voteRes);
729   }
730
731   async handlePostEdit(form: EditPost) {
732     const res = await HttpService.client.editPost(form);
733     this.findAndUpdatePost(res);
734   }
735
736   async handlePostVote(form: CreatePostLike) {
737     const voteRes = await HttpService.client.likePost(form);
738     this.findAndUpdatePost(voteRes);
739   }
740
741   async handleCommentReport(form: CreateCommentReport) {
742     const reportRes = await HttpService.client.createCommentReport(form);
743     if (reportRes.state == "success") {
744       toast(i18n.t("report_created"));
745     }
746   }
747
748   async handlePostReport(form: CreatePostReport) {
749     const reportRes = await HttpService.client.createPostReport(form);
750     if (reportRes.state == "success") {
751       toast(i18n.t("report_created"));
752     }
753   }
754
755   async handleLockPost(form: LockPost) {
756     const lockRes = await HttpService.client.lockPost(form);
757     this.findAndUpdatePost(lockRes);
758   }
759
760   async handleDistinguishComment(form: DistinguishComment) {
761     const distinguishRes = await HttpService.client.distinguishComment(form);
762     this.findAndUpdateComment(distinguishRes);
763   }
764
765   async handleAddAdmin(form: AddAdmin) {
766     const addAdminRes = await HttpService.client.addAdmin(form);
767
768     if (addAdminRes.state == "success") {
769       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
770     }
771   }
772
773   async handleTransferCommunity(form: TransferCommunity) {
774     const transferCommunityRes = await HttpService.client.transferCommunity(
775       form
776     );
777     toast(i18n.t("transfer_community"));
778     this.updateCommunityFull(transferCommunityRes);
779   }
780
781   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
782     const readRes = await HttpService.client.markCommentReplyAsRead(form);
783     this.findAndUpdateCommentReply(readRes);
784   }
785
786   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
787     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
788     await HttpService.client.markPersonMentionAsRead(form);
789   }
790
791   async handleBanFromCommunity(form: BanFromCommunity) {
792     const banRes = await HttpService.client.banFromCommunity(form);
793     this.updateBanFromCommunity(banRes);
794   }
795
796   async handleBanPerson(form: BanPerson) {
797     const banRes = await HttpService.client.banPerson(form);
798     this.updateBan(banRes);
799   }
800
801   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
802     // Maybe not necessary
803     if (banRes.state == "success") {
804       this.setState(s => {
805         if (s.postsRes.state == "success") {
806           s.postsRes.data.posts
807             .filter(c => c.creator.id == banRes.data.person_view.person.id)
808             .forEach(
809               c => (c.creator_banned_from_community = banRes.data.banned)
810             );
811         }
812         if (s.commentsRes.state == "success") {
813           s.commentsRes.data.comments
814             .filter(c => c.creator.id == banRes.data.person_view.person.id)
815             .forEach(
816               c => (c.creator_banned_from_community = banRes.data.banned)
817             );
818         }
819         return s;
820       });
821     }
822   }
823
824   updateBan(banRes: RequestState<BanPersonResponse>) {
825     // Maybe not necessary
826     if (banRes.state == "success") {
827       this.setState(s => {
828         if (s.postsRes.state == "success") {
829           s.postsRes.data.posts
830             .filter(c => c.creator.id == banRes.data.person_view.person.id)
831             .forEach(c => (c.creator.banned = banRes.data.banned));
832         }
833         if (s.commentsRes.state == "success") {
834           s.commentsRes.data.comments
835             .filter(c => c.creator.id == banRes.data.person_view.person.id)
836             .forEach(c => (c.creator.banned = banRes.data.banned));
837         }
838         return s;
839       });
840     }
841   }
842
843   updateCommunity(res: RequestState<CommunityResponse>) {
844     this.setState(s => {
845       if (s.communityRes.state == "success" && res.state == "success") {
846         s.communityRes.data.community_view = res.data.community_view;
847         s.communityRes.data.discussion_languages =
848           res.data.discussion_languages;
849       }
850       return s;
851     });
852   }
853
854   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
855     this.setState(s => {
856       if (s.communityRes.state == "success" && res.state == "success") {
857         s.communityRes.data.community_view = res.data.community_view;
858         s.communityRes.data.moderators = res.data.moderators;
859       }
860       return s;
861     });
862   }
863
864   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
865     if (purgeRes.state == "success") {
866       toast(i18n.t("purge_success"));
867       this.context.router.history.push(`/`);
868     }
869   }
870
871   findAndUpdateComment(res: RequestState<CommentResponse>) {
872     this.setState(s => {
873       if (s.commentsRes.state == "success" && res.state == "success") {
874         s.commentsRes.data.comments = editComment(
875           res.data.comment_view,
876           s.commentsRes.data.comments
877         );
878         s.finished.set(res.data.comment_view.comment.id, true);
879       }
880       return s;
881     });
882   }
883
884   createAndUpdateComments(res: RequestState<CommentResponse>) {
885     this.setState(s => {
886       if (s.commentsRes.state == "success" && res.state == "success") {
887         s.commentsRes.data.comments.unshift(res.data.comment_view);
888
889         // Set finished for the parent
890         s.finished.set(
891           getCommentParentId(res.data.comment_view.comment) ?? 0,
892           true
893         );
894       }
895       return s;
896     });
897   }
898
899   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
900     this.setState(s => {
901       if (s.commentsRes.state == "success" && res.state == "success") {
902         s.commentsRes.data.comments = editWith(
903           res.data.comment_reply_view,
904           s.commentsRes.data.comments
905         );
906       }
907       return s;
908     });
909   }
910
911   findAndUpdatePost(res: RequestState<PostResponse>) {
912     this.setState(s => {
913       if (s.postsRes.state == "success" && res.state == "success") {
914         s.postsRes.data.posts = editPost(
915           res.data.post_view,
916           s.postsRes.data.posts
917         );
918       }
919       return s;
920     });
921   }
922
923   updateModerators(res: RequestState<AddModToCommunityResponse>) {
924     // Update the moderators
925     this.setState(s => {
926       if (s.communityRes.state == "success" && res.state == "success") {
927         s.communityRes.data.moderators = res.data.moderators;
928       }
929       return s;
930     });
931   }
932 }