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