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