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