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