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