]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
update imports
[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   RouteDataResponse,
66   commentsToFlatNodes,
67   communityRSSUrl,
68   editComment,
69   editPost,
70   editWith,
71   enableDownvotes,
72   enableNsfw,
73   fetchLimit,
74   getCommentParentId,
75   getDataTypeString,
76   getPageFromString,
77   myAuth,
78   postToCommentSortType,
79   relTags,
80   restoreScrollPosition,
81   saveScrollPosition,
82   setIsoData,
83   setupTippy,
84   showLocal,
85   toast,
86   updateCommunityBlock,
87   updatePersonBlock,
88 } from "../../utils";
89 import getQueryParams from "../../utils/helpers/get-query-params";
90 import getQueryString from "../../utils/helpers/get-query-string";
91 import type { QueryParams } from "../../utils/types/query-params";
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           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="mr-3">
515           <DataTypeSelect
516             type_={dataType}
517             onChange={this.handleDataTypeChange}
518           />
519         </span>
520         <span className="mr-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(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(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(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(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 }