]> Untitled Git - lemmy-ui.git/blob - src/shared/components/community/community.tsx
`utils.ts` organization, round two (#1427)
[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 { i18n } from "../../i18next";
82 import {
83   CommentViewType,
84   DataType,
85   InitialFetchRequest,
86 } from "../../interfaces";
87 import { UserService } from "../../services";
88 import { FirstLoadService } from "../../services/FirstLoadService";
89 import { HttpService, RequestState } from "../../services/HttpService";
90 import { setupTippy } from "../../tippy";
91 import { toast } from "../../toast";
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 me-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 (
362       <div className="community container-lg">{this.renderCommunity()}</div>
363     );
364   }
365
366   sidebar(res: GetCommunityResponse) {
367     const { site_res } = this.isoData;
368     // For some reason, this returns an empty vec if it matches the site langs
369     const communityLangs =
370       res.discussion_languages.length === 0
371         ? site_res.all_languages.map(({ id }) => id)
372         : res.discussion_languages;
373
374     return (
375       <>
376         <Sidebar
377           community_view={res.community_view}
378           moderators={res.moderators}
379           admins={site_res.admins}
380           enableNsfw={enableNsfw(site_res)}
381           editable
382           allLanguages={site_res.all_languages}
383           siteLanguages={site_res.discussion_languages}
384           communityLanguages={communityLangs}
385           onDeleteCommunity={this.handleDeleteCommunity}
386           onRemoveCommunity={this.handleRemoveCommunity}
387           onLeaveModTeam={this.handleAddModToCommunity}
388           onFollowCommunity={this.handleFollow}
389           onBlockCommunity={this.handleBlockCommunity}
390           onPurgeCommunity={this.handlePurgeCommunity}
391           onEditCommunity={this.handleEditCommunity}
392         />
393         {!res.community_view.community.local && res.site && (
394           <SiteSidebar site={res.site} showLocal={showLocal(this.isoData)} />
395         )}
396       </>
397     );
398   }
399
400   listings(communityRes: GetCommunityResponse) {
401     const { dataType } = getCommunityQueryParams();
402     const { site_res } = this.isoData;
403
404     if (dataType === DataType.Post) {
405       switch (this.state.postsRes.state) {
406         case "loading":
407           return (
408             <h5>
409               <Spinner large />
410             </h5>
411           );
412         case "success":
413           return (
414             <PostListings
415               posts={this.state.postsRes.data.posts}
416               removeDuplicates
417               enableDownvotes={enableDownvotes(site_res)}
418               enableNsfw={enableNsfw(site_res)}
419               allLanguages={site_res.all_languages}
420               siteLanguages={site_res.discussion_languages}
421               onBlockPerson={this.handleBlockPerson}
422               onPostEdit={this.handlePostEdit}
423               onPostVote={this.handlePostVote}
424               onPostReport={this.handlePostReport}
425               onLockPost={this.handleLockPost}
426               onDeletePost={this.handleDeletePost}
427               onRemovePost={this.handleRemovePost}
428               onSavePost={this.handleSavePost}
429               onPurgePerson={this.handlePurgePerson}
430               onPurgePost={this.handlePurgePost}
431               onBanPerson={this.handleBanPerson}
432               onBanPersonFromCommunity={this.handleBanFromCommunity}
433               onAddModToCommunity={this.handleAddModToCommunity}
434               onAddAdmin={this.handleAddAdmin}
435               onTransferCommunity={this.handleTransferCommunity}
436               onFeaturePost={this.handleFeaturePost}
437             />
438           );
439       }
440     } else {
441       switch (this.state.commentsRes.state) {
442         case "loading":
443           return (
444             <h5>
445               <Spinner large />
446             </h5>
447           );
448         case "success":
449           return (
450             <CommentNodes
451               nodes={commentsToFlatNodes(this.state.commentsRes.data.comments)}
452               viewType={CommentViewType.Flat}
453               finished={this.state.finished}
454               noIndent
455               showContext
456               enableDownvotes={enableDownvotes(site_res)}
457               moderators={communityRes.moderators}
458               admins={site_res.admins}
459               allLanguages={site_res.all_languages}
460               siteLanguages={site_res.discussion_languages}
461               onSaveComment={this.handleSaveComment}
462               onBlockPerson={this.handleBlockPerson}
463               onDeleteComment={this.handleDeleteComment}
464               onRemoveComment={this.handleRemoveComment}
465               onCommentVote={this.handleCommentVote}
466               onCommentReport={this.handleCommentReport}
467               onDistinguishComment={this.handleDistinguishComment}
468               onAddModToCommunity={this.handleAddModToCommunity}
469               onAddAdmin={this.handleAddAdmin}
470               onTransferCommunity={this.handleTransferCommunity}
471               onPurgeComment={this.handlePurgeComment}
472               onPurgePerson={this.handlePurgePerson}
473               onCommentReplyRead={this.handleCommentReplyRead}
474               onPersonMentionRead={this.handlePersonMentionRead}
475               onBanPersonFromCommunity={this.handleBanFromCommunity}
476               onBanPerson={this.handleBanPerson}
477               onCreateComment={this.handleCreateComment}
478               onEditComment={this.handleEditComment}
479             />
480           );
481       }
482     }
483   }
484
485   communityInfo(res: GetCommunityResponse) {
486     const community = res.community_view.community;
487
488     return (
489       community && (
490         <div className="mb-2">
491           <BannerIconHeader banner={community.banner} icon={community.icon} />
492           <h5 className="mb-0 overflow-wrap-anywhere">{community.title}</h5>
493           <CommunityLink
494             community={community}
495             realLink
496             useApubName
497             muted
498             hideAvatar
499           />
500         </div>
501       )
502     );
503   }
504
505   selects(res: GetCommunityResponse) {
506     // let communityRss = this.state.communityRes.map(r =>
507     //   communityRSSUrl(r.community_view.community.actor_id, this.state.sort)
508     // );
509     const { dataType, sort } = getCommunityQueryParams();
510     const communityRss = res
511       ? communityRSSUrl(res.community_view.community.actor_id, sort)
512       : undefined;
513
514     return (
515       <div className="mb-3">
516         <span className="me-3">
517           <DataTypeSelect
518             type_={dataType}
519             onChange={this.handleDataTypeChange}
520           />
521         </span>
522         <span className="me-2">
523           <SortSelect sort={sort} onChange={this.handleSortChange} />
524         </span>
525         {communityRss && (
526           <>
527             <a href={communityRss} title="RSS" rel={relTags}>
528               <Icon icon="rss" classes="text-muted small" />
529             </a>
530             <link
531               rel="alternate"
532               type="application/atom+xml"
533               href={communityRss}
534             />
535           </>
536         )}
537       </div>
538     );
539   }
540
541   handlePageChange(page: number) {
542     this.updateUrl({ page });
543     window.scrollTo(0, 0);
544   }
545
546   handleSortChange(sort: SortType) {
547     this.updateUrl({ sort, page: 1 });
548     window.scrollTo(0, 0);
549   }
550
551   handleDataTypeChange(dataType: DataType) {
552     this.updateUrl({ dataType, page: 1 });
553     window.scrollTo(0, 0);
554   }
555
556   handleShowSidebarMobile(i: Community) {
557     i.setState(({ showSidebarMobile }) => ({
558       showSidebarMobile: !showSidebarMobile,
559     }));
560   }
561
562   async updateUrl({ dataType, page, sort }: Partial<CommunityProps>) {
563     const {
564       dataType: urlDataType,
565       page: urlPage,
566       sort: urlSort,
567     } = getCommunityQueryParams();
568
569     const queryParams: QueryParams<CommunityProps> = {
570       dataType: getDataTypeString(dataType ?? urlDataType),
571       page: (page ?? urlPage).toString(),
572       sort: sort ?? urlSort,
573     };
574
575     this.props.history.push(
576       `/c/${this.props.match.params.name}${getQueryString(queryParams)}`
577     );
578
579     await this.fetchData();
580   }
581
582   async fetchData() {
583     const { dataType, page, sort } = getCommunityQueryParams();
584     const { name } = this.props.match.params;
585
586     if (dataType === DataType.Post) {
587       this.setState({ postsRes: { state: "loading" } });
588       this.setState({
589         postsRes: await HttpService.client.getPosts({
590           page,
591           limit: fetchLimit,
592           sort,
593           type_: "All",
594           community_name: name,
595           saved_only: false,
596           auth: myAuth(),
597         }),
598       });
599     } else {
600       this.setState({ commentsRes: { state: "loading" } });
601       this.setState({
602         commentsRes: await HttpService.client.getComments({
603           page,
604           limit: fetchLimit,
605           sort: postToCommentSortType(sort),
606           type_: "All",
607           community_name: name,
608           saved_only: false,
609           auth: myAuth(),
610         }),
611       });
612     }
613
614     restoreScrollPosition(this.context);
615     setupTippy();
616   }
617
618   async handleDeleteCommunity(form: DeleteCommunity) {
619     const deleteCommunityRes = await HttpService.client.deleteCommunity(form);
620     this.updateCommunity(deleteCommunityRes);
621   }
622
623   async handleAddModToCommunity(form: AddModToCommunity) {
624     const addModRes = await HttpService.client.addModToCommunity(form);
625     this.updateModerators(addModRes);
626   }
627
628   async handleFollow(form: FollowCommunity) {
629     const followCommunityRes = await HttpService.client.followCommunity(form);
630     this.updateCommunity(followCommunityRes);
631
632     // Update myUserInfo
633     if (followCommunityRes.state == "success") {
634       const communityId = followCommunityRes.data.community_view.community.id;
635       const mui = UserService.Instance.myUserInfo;
636       if (mui) {
637         mui.follows = mui.follows.filter(i => i.community.id != communityId);
638       }
639     }
640   }
641
642   async handlePurgeCommunity(form: PurgeCommunity) {
643     const purgeCommunityRes = await HttpService.client.purgeCommunity(form);
644     this.purgeItem(purgeCommunityRes);
645   }
646
647   async handlePurgePerson(form: PurgePerson) {
648     const purgePersonRes = await HttpService.client.purgePerson(form);
649     this.purgeItem(purgePersonRes);
650   }
651
652   async handlePurgeComment(form: PurgeComment) {
653     const purgeCommentRes = await HttpService.client.purgeComment(form);
654     this.purgeItem(purgeCommentRes);
655   }
656
657   async handlePurgePost(form: PurgePost) {
658     const purgeRes = await HttpService.client.purgePost(form);
659     this.purgeItem(purgeRes);
660   }
661
662   async handleBlockCommunity(form: BlockCommunity) {
663     const blockCommunityRes = await HttpService.client.blockCommunity(form);
664     if (blockCommunityRes.state == "success") {
665       updateCommunityBlock(blockCommunityRes.data);
666       this.setState(s => {
667         if (s.communityRes.state == "success") {
668           s.communityRes.data.community_view.blocked =
669             blockCommunityRes.data.blocked;
670         }
671       });
672     }
673   }
674
675   async handleBlockPerson(form: BlockPerson) {
676     const blockPersonRes = await HttpService.client.blockPerson(form);
677     if (blockPersonRes.state == "success") {
678       updatePersonBlock(blockPersonRes.data);
679     }
680   }
681
682   async handleRemoveCommunity(form: RemoveCommunity) {
683     const removeCommunityRes = await HttpService.client.removeCommunity(form);
684     this.updateCommunity(removeCommunityRes);
685   }
686
687   async handleEditCommunity(form: EditCommunity) {
688     const res = await HttpService.client.editCommunity(form);
689     this.updateCommunity(res);
690
691     return res;
692   }
693
694   async handleCreateComment(form: CreateComment) {
695     const createCommentRes = await HttpService.client.createComment(form);
696     this.createAndUpdateComments(createCommentRes);
697
698     return createCommentRes;
699   }
700
701   async handleEditComment(form: EditComment) {
702     const editCommentRes = await HttpService.client.editComment(form);
703     this.findAndUpdateComment(editCommentRes);
704
705     return editCommentRes;
706   }
707
708   async handleDeleteComment(form: DeleteComment) {
709     const deleteCommentRes = await HttpService.client.deleteComment(form);
710     this.findAndUpdateComment(deleteCommentRes);
711   }
712
713   async handleDeletePost(form: DeletePost) {
714     const deleteRes = await HttpService.client.deletePost(form);
715     this.findAndUpdatePost(deleteRes);
716   }
717
718   async handleRemovePost(form: RemovePost) {
719     const removeRes = await HttpService.client.removePost(form);
720     this.findAndUpdatePost(removeRes);
721   }
722
723   async handleRemoveComment(form: RemoveComment) {
724     const removeCommentRes = await HttpService.client.removeComment(form);
725     this.findAndUpdateComment(removeCommentRes);
726   }
727
728   async handleSaveComment(form: SaveComment) {
729     const saveCommentRes = await HttpService.client.saveComment(form);
730     this.findAndUpdateComment(saveCommentRes);
731   }
732
733   async handleSavePost(form: SavePost) {
734     const saveRes = await HttpService.client.savePost(form);
735     this.findAndUpdatePost(saveRes);
736   }
737
738   async handleFeaturePost(form: FeaturePost) {
739     const featureRes = await HttpService.client.featurePost(form);
740     this.findAndUpdatePost(featureRes);
741   }
742
743   async handleCommentVote(form: CreateCommentLike) {
744     const voteRes = await HttpService.client.likeComment(form);
745     this.findAndUpdateComment(voteRes);
746   }
747
748   async handlePostEdit(form: EditPost) {
749     const res = await HttpService.client.editPost(form);
750     this.findAndUpdatePost(res);
751   }
752
753   async handlePostVote(form: CreatePostLike) {
754     const voteRes = await HttpService.client.likePost(form);
755     this.findAndUpdatePost(voteRes);
756   }
757
758   async handleCommentReport(form: CreateCommentReport) {
759     const reportRes = await HttpService.client.createCommentReport(form);
760     if (reportRes.state == "success") {
761       toast(i18n.t("report_created"));
762     }
763   }
764
765   async handlePostReport(form: CreatePostReport) {
766     const reportRes = await HttpService.client.createPostReport(form);
767     if (reportRes.state == "success") {
768       toast(i18n.t("report_created"));
769     }
770   }
771
772   async handleLockPost(form: LockPost) {
773     const lockRes = await HttpService.client.lockPost(form);
774     this.findAndUpdatePost(lockRes);
775   }
776
777   async handleDistinguishComment(form: DistinguishComment) {
778     const distinguishRes = await HttpService.client.distinguishComment(form);
779     this.findAndUpdateComment(distinguishRes);
780   }
781
782   async handleAddAdmin(form: AddAdmin) {
783     const addAdminRes = await HttpService.client.addAdmin(form);
784
785     if (addAdminRes.state == "success") {
786       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
787     }
788   }
789
790   async handleTransferCommunity(form: TransferCommunity) {
791     const transferCommunityRes = await HttpService.client.transferCommunity(
792       form
793     );
794     toast(i18n.t("transfer_community"));
795     this.updateCommunityFull(transferCommunityRes);
796   }
797
798   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
799     const readRes = await HttpService.client.markCommentReplyAsRead(form);
800     this.findAndUpdateCommentReply(readRes);
801   }
802
803   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
804     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
805     await HttpService.client.markPersonMentionAsRead(form);
806   }
807
808   async handleBanFromCommunity(form: BanFromCommunity) {
809     const banRes = await HttpService.client.banFromCommunity(form);
810     this.updateBanFromCommunity(banRes);
811   }
812
813   async handleBanPerson(form: BanPerson) {
814     const banRes = await HttpService.client.banPerson(form);
815     this.updateBan(banRes);
816   }
817
818   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
819     // Maybe not necessary
820     if (banRes.state == "success") {
821       this.setState(s => {
822         if (s.postsRes.state == "success") {
823           s.postsRes.data.posts
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         if (s.commentsRes.state == "success") {
830           s.commentsRes.data.comments
831             .filter(c => c.creator.id == banRes.data.person_view.person.id)
832             .forEach(
833               c => (c.creator_banned_from_community = banRes.data.banned)
834             );
835         }
836         return s;
837       });
838     }
839   }
840
841   updateBan(banRes: RequestState<BanPersonResponse>) {
842     // Maybe not necessary
843     if (banRes.state == "success") {
844       this.setState(s => {
845         if (s.postsRes.state == "success") {
846           s.postsRes.data.posts
847             .filter(c => c.creator.id == banRes.data.person_view.person.id)
848             .forEach(c => (c.creator.banned = banRes.data.banned));
849         }
850         if (s.commentsRes.state == "success") {
851           s.commentsRes.data.comments
852             .filter(c => c.creator.id == banRes.data.person_view.person.id)
853             .forEach(c => (c.creator.banned = banRes.data.banned));
854         }
855         return s;
856       });
857     }
858   }
859
860   updateCommunity(res: RequestState<CommunityResponse>) {
861     this.setState(s => {
862       if (s.communityRes.state == "success" && res.state == "success") {
863         s.communityRes.data.community_view = res.data.community_view;
864         s.communityRes.data.discussion_languages =
865           res.data.discussion_languages;
866       }
867       return s;
868     });
869   }
870
871   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
872     this.setState(s => {
873       if (s.communityRes.state == "success" && res.state == "success") {
874         s.communityRes.data.community_view = res.data.community_view;
875         s.communityRes.data.moderators = res.data.moderators;
876       }
877       return s;
878     });
879   }
880
881   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
882     if (purgeRes.state == "success") {
883       toast(i18n.t("purge_success"));
884       this.context.router.history.push(`/`);
885     }
886   }
887
888   findAndUpdateComment(res: RequestState<CommentResponse>) {
889     this.setState(s => {
890       if (s.commentsRes.state == "success" && res.state == "success") {
891         s.commentsRes.data.comments = editComment(
892           res.data.comment_view,
893           s.commentsRes.data.comments
894         );
895         s.finished.set(res.data.comment_view.comment.id, true);
896       }
897       return s;
898     });
899   }
900
901   createAndUpdateComments(res: RequestState<CommentResponse>) {
902     this.setState(s => {
903       if (s.commentsRes.state == "success" && res.state == "success") {
904         s.commentsRes.data.comments.unshift(res.data.comment_view);
905
906         // Set finished for the parent
907         s.finished.set(
908           getCommentParentId(res.data.comment_view.comment) ?? 0,
909           true
910         );
911       }
912       return s;
913     });
914   }
915
916   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
917     this.setState(s => {
918       if (s.commentsRes.state == "success" && res.state == "success") {
919         s.commentsRes.data.comments = editWith(
920           res.data.comment_reply_view,
921           s.commentsRes.data.comments
922         );
923       }
924       return s;
925     });
926   }
927
928   findAndUpdatePost(res: RequestState<PostResponse>) {
929     this.setState(s => {
930       if (s.postsRes.state == "success" && res.state == "success") {
931         s.postsRes.data.posts = editPost(
932           res.data.post_view,
933           s.postsRes.data.posts
934         );
935       }
936       return s;
937     });
938   }
939
940   updateModerators(res: RequestState<AddModToCommunityResponse>) {
941     // Update the moderators
942     this.setState(s => {
943       if (s.communityRes.state == "success" && res.state == "success") {
944         s.communityRes.data.moderators = res.data.moderators;
945       }
946       return s;
947     });
948   }
949 }