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