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