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