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