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