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