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