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