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