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