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