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