]> Untitled Git - lemmy-ui.git/blob - src/shared/components/post/post.tsx
Merge branch 'main' into generate-theme-css
[lemmy-ui.git] / src / shared / components / post / post.tsx
1 import autosize from "autosize";
2 import { Component, createRef, linkEvent, RefObject } from "inferno";
3 import {
4   AddAdmin,
5   AddModToCommunity,
6   AddModToCommunityResponse,
7   BanFromCommunity,
8   BanFromCommunityResponse,
9   BanPerson,
10   BanPersonResponse,
11   BlockCommunity,
12   BlockPerson,
13   CommentId,
14   CommentReplyResponse,
15   CommentResponse,
16   CommentSortType,
17   CommunityResponse,
18   CreateComment,
19   CreateCommentLike,
20   CreateCommentReport,
21   CreatePostLike,
22   CreatePostReport,
23   DeleteComment,
24   DeleteCommunity,
25   DeletePost,
26   DistinguishComment,
27   EditComment,
28   EditCommunity,
29   EditPost,
30   FeaturePost,
31   FollowCommunity,
32   GetComments,
33   GetCommentsResponse,
34   GetCommunityResponse,
35   GetPost,
36   GetPostResponse,
37   GetSiteResponse,
38   LockPost,
39   MarkCommentReplyAsRead,
40   MarkPersonMentionAsRead,
41   PostResponse,
42   PurgeComment,
43   PurgeCommunity,
44   PurgeItemResponse,
45   PurgePerson,
46   PurgePost,
47   RemoveComment,
48   RemoveCommunity,
49   RemovePost,
50   SaveComment,
51   SavePost,
52   TransferCommunity,
53 } from "lemmy-js-client";
54 import { i18n } from "../../i18next";
55 import {
56   CommentNodeI,
57   CommentViewType,
58   InitialFetchRequest,
59 } from "../../interfaces";
60 import { UserService } from "../../services";
61 import { FirstLoadService } from "../../services/FirstLoadService";
62 import { HttpService, RequestState } from "../../services/HttpService";
63 import {
64   buildCommentsTree,
65   commentsToFlatNodes,
66   commentTreeMaxDepth,
67   debounce,
68   editComment,
69   editWith,
70   enableDownvotes,
71   enableNsfw,
72   getCommentIdFromProps,
73   getCommentParentId,
74   getDepthFromComment,
75   getIdFromProps,
76   isBrowser,
77   isImage,
78   myAuth,
79   restoreScrollPosition,
80   saveScrollPosition,
81   setIsoData,
82   setupTippy,
83   toast,
84   updateCommunityBlock,
85   updatePersonBlock,
86 } from "../../utils";
87 import { CommentForm } from "../comment/comment-form";
88 import { CommentNodes } from "../comment/comment-nodes";
89 import { HtmlTags } from "../common/html-tags";
90 import { Icon, Spinner } from "../common/icon";
91 import { Sidebar } from "../community/sidebar";
92 import { PostListing } from "./post-listing";
93
94 const commentsShownInterval = 15;
95
96 interface PostState {
97   postId?: number;
98   commentId?: number;
99   postRes: RequestState<GetPostResponse>;
100   commentsRes: RequestState<GetCommentsResponse>;
101   commentSort: CommentSortType;
102   commentViewType: CommentViewType;
103   scrolled?: boolean;
104   siteRes: GetSiteResponse;
105   commentSectionRef?: RefObject<HTMLDivElement>;
106   showSidebarMobile: boolean;
107   maxCommentsShown: number;
108   finished: Map<CommentId, boolean | undefined>;
109   isIsomorphic: boolean;
110 }
111
112 export class Post extends Component<any, PostState> {
113   private isoData = setIsoData(this.context);
114   private commentScrollDebounced: () => void;
115   state: PostState = {
116     postRes: { state: "empty" },
117     commentsRes: { state: "empty" },
118     postId: getIdFromProps(this.props),
119     commentId: getCommentIdFromProps(this.props),
120     commentSort: "Hot",
121     commentViewType: CommentViewType.Tree,
122     scrolled: false,
123     siteRes: this.isoData.site_res,
124     showSidebarMobile: false,
125     maxCommentsShown: commentsShownInterval,
126     finished: new Map(),
127     isIsomorphic: false,
128   };
129
130   constructor(props: any, context: any) {
131     super(props, context);
132
133     this.handleDeleteCommunityClick =
134       this.handleDeleteCommunityClick.bind(this);
135     this.handleEditCommunity = this.handleEditCommunity.bind(this);
136     this.handleFollow = this.handleFollow.bind(this);
137     this.handleModRemoveCommunity = this.handleModRemoveCommunity.bind(this);
138     this.handleCreateComment = this.handleCreateComment.bind(this);
139     this.handleEditComment = this.handleEditComment.bind(this);
140     this.handleSaveComment = this.handleSaveComment.bind(this);
141     this.handleBlockCommunity = this.handleBlockCommunity.bind(this);
142     this.handleBlockPerson = this.handleBlockPerson.bind(this);
143     this.handleDeleteComment = this.handleDeleteComment.bind(this);
144     this.handleRemoveComment = this.handleRemoveComment.bind(this);
145     this.handleCommentVote = this.handleCommentVote.bind(this);
146     this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
147     this.handleAddAdmin = this.handleAddAdmin.bind(this);
148     this.handlePurgePerson = this.handlePurgePerson.bind(this);
149     this.handlePurgeComment = this.handlePurgeComment.bind(this);
150     this.handleCommentReport = this.handleCommentReport.bind(this);
151     this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
152     this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
153     this.handleFetchChildren = this.handleFetchChildren.bind(this);
154     this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
155     this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
156     this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
157     this.handleBanPerson = this.handleBanPerson.bind(this);
158     this.handlePostEdit = this.handlePostEdit.bind(this);
159     this.handlePostVote = this.handlePostVote.bind(this);
160     this.handlePostReport = this.handlePostReport.bind(this);
161     this.handleLockPost = this.handleLockPost.bind(this);
162     this.handleDeletePost = this.handleDeletePost.bind(this);
163     this.handleRemovePost = this.handleRemovePost.bind(this);
164     this.handleSavePost = this.handleSavePost.bind(this);
165     this.handlePurgePost = this.handlePurgePost.bind(this);
166     this.handleFeaturePost = this.handleFeaturePost.bind(this);
167
168     this.state = { ...this.state, commentSectionRef: createRef() };
169
170     // Only fetch the data if coming from another route
171     if (FirstLoadService.isFirstLoad) {
172       const [postRes, commentsRes] = this.isoData.routeData;
173
174       this.state = {
175         ...this.state,
176         postRes,
177         commentsRes,
178         isIsomorphic: true,
179       };
180
181       if (isBrowser()) {
182         if (this.checkScrollIntoCommentsParam) {
183           this.scrollIntoCommentSection();
184         }
185       }
186     }
187   }
188
189   async fetchPost() {
190     this.setState({
191       postRes: { state: "loading" },
192       commentsRes: { state: "loading" },
193     });
194
195     const auth = myAuth();
196
197     this.setState({
198       postRes: await HttpService.client.getPost({
199         id: this.state.postId,
200         comment_id: this.state.commentId,
201         auth,
202       }),
203       commentsRes: await HttpService.client.getComments({
204         post_id: this.state.postId,
205         parent_id: this.state.commentId,
206         max_depth: commentTreeMaxDepth,
207         sort: this.state.commentSort,
208         type_: "All",
209         saved_only: false,
210         auth,
211       }),
212     });
213
214     setupTippy();
215
216     if (!this.state.commentId) restoreScrollPosition(this.context);
217
218     if (this.checkScrollIntoCommentsParam) {
219       this.scrollIntoCommentSection();
220     }
221   }
222
223   static fetchInitialData({
224     auth,
225     client,
226     path,
227   }: InitialFetchRequest): Promise<any>[] {
228     const pathSplit = path.split("/");
229     const promises: Promise<RequestState<any>>[] = [];
230
231     const pathType = pathSplit.at(1);
232     const id = pathSplit.at(2) ? Number(pathSplit.at(2)) : undefined;
233
234     const postForm: GetPost = {
235       auth,
236     };
237
238     const commentsForm: GetComments = {
239       max_depth: commentTreeMaxDepth,
240       sort: "Hot",
241       type_: "All",
242       saved_only: false,
243       auth,
244     };
245
246     // Set the correct id based on the path type
247     if (pathType === "post") {
248       postForm.id = id;
249       commentsForm.post_id = id;
250     } else {
251       postForm.comment_id = id;
252       commentsForm.parent_id = id;
253     }
254
255     promises.push(client.getPost(postForm));
256     promises.push(client.getComments(commentsForm));
257
258     return promises;
259   }
260
261   componentWillUnmount() {
262     document.removeEventListener("scroll", this.commentScrollDebounced);
263
264     saveScrollPosition(this.context);
265   }
266
267   async componentDidMount() {
268     if (!this.state.isIsomorphic) {
269       await this.fetchPost();
270     }
271
272     autosize(document.querySelectorAll("textarea"));
273
274     this.commentScrollDebounced = debounce(this.trackCommentsBoxScrolling, 100);
275     document.addEventListener("scroll", this.commentScrollDebounced);
276   }
277
278   async componentDidUpdate(_lastProps: any) {
279     // Necessary if you are on a post and you click another post (same route)
280     if (_lastProps.location.pathname !== _lastProps.history.location.pathname) {
281       await this.fetchPost();
282     }
283   }
284
285   get checkScrollIntoCommentsParam() {
286     return Boolean(
287       new URLSearchParams(this.props.location.search).get("scrollToComments")
288     );
289   }
290
291   scrollIntoCommentSection() {
292     this.state.commentSectionRef?.current?.scrollIntoView();
293   }
294
295   isBottom(el: Element): boolean {
296     return el?.getBoundingClientRect().bottom <= window.innerHeight;
297   }
298
299   /**
300    * Shows new comments when scrolling to the bottom of the comments div
301    */
302   trackCommentsBoxScrolling = () => {
303     const wrappedElement = document.getElementsByClassName("comments")[0];
304     if (wrappedElement && this.isBottom(wrappedElement)) {
305       const commentCount =
306         this.state.commentsRes.state == "success"
307           ? this.state.commentsRes.data.comments.length
308           : 0;
309
310       if (this.state.maxCommentsShown < commentCount) {
311         this.setState({
312           maxCommentsShown: this.state.maxCommentsShown + commentsShownInterval,
313         });
314       }
315     }
316   };
317
318   get documentTitle(): string {
319     const siteName = this.state.siteRes.site_view.site.name;
320     return this.state.postRes.state == "success"
321       ? `${this.state.postRes.data.post_view.post.name} - ${siteName}`
322       : siteName;
323   }
324
325   get imageTag(): string | undefined {
326     if (this.state.postRes.state == "success") {
327       const post = this.state.postRes.data.post_view.post;
328       const thumbnail = post.thumbnail_url;
329       const url = post.url;
330       return thumbnail || (url && isImage(url) ? url : undefined);
331     } else return undefined;
332   }
333
334   renderPostRes() {
335     switch (this.state.postRes.state) {
336       case "loading":
337         return (
338           <h5>
339             <Spinner large />
340           </h5>
341         );
342       case "success": {
343         const res = this.state.postRes.data;
344         return (
345           <div className="row">
346             <div className="col-12 col-md-8 mb-3">
347               <HtmlTags
348                 title={this.documentTitle}
349                 path={this.context.router.route.match.url}
350                 image={this.imageTag}
351                 description={res.post_view.post.body}
352               />
353               <PostListing
354                 post_view={res.post_view}
355                 crossPosts={res.cross_posts}
356                 showBody
357                 showCommunity
358                 moderators={res.moderators}
359                 admins={this.state.siteRes.admins}
360                 enableDownvotes={enableDownvotes(this.state.siteRes)}
361                 enableNsfw={enableNsfw(this.state.siteRes)}
362                 allLanguages={this.state.siteRes.all_languages}
363                 siteLanguages={this.state.siteRes.discussion_languages}
364                 onBlockPerson={this.handleBlockPerson}
365                 onPostEdit={this.handlePostEdit}
366                 onPostVote={this.handlePostVote}
367                 onPostReport={this.handlePostReport}
368                 onLockPost={this.handleLockPost}
369                 onDeletePost={this.handleDeletePost}
370                 onRemovePost={this.handleRemovePost}
371                 onSavePost={this.handleSavePost}
372                 onPurgePerson={this.handlePurgePerson}
373                 onPurgePost={this.handlePurgePost}
374                 onBanPerson={this.handleBanPerson}
375                 onBanPersonFromCommunity={this.handleBanFromCommunity}
376                 onAddModToCommunity={this.handleAddModToCommunity}
377                 onAddAdmin={this.handleAddAdmin}
378                 onTransferCommunity={this.handleTransferCommunity}
379                 onFeaturePost={this.handleFeaturePost}
380               />
381               <div ref={this.state.commentSectionRef} className="mb-2" />
382               <CommentForm
383                 node={res.post_view.post.id}
384                 disabled={res.post_view.post.locked}
385                 allLanguages={this.state.siteRes.all_languages}
386                 siteLanguages={this.state.siteRes.discussion_languages}
387                 onUpsertComment={this.handleCreateComment}
388                 finished={this.state.finished.get(0)}
389               />
390               <div className="d-block d-md-none">
391                 <button
392                   className="btn btn-secondary d-inline-block mb-2 mr-3"
393                   onClick={linkEvent(this, this.handleShowSidebarMobile)}
394                 >
395                   {i18n.t("sidebar")}{" "}
396                   <Icon
397                     icon={
398                       this.state.showSidebarMobile
399                         ? `minus-square`
400                         : `plus-square`
401                     }
402                     classes="icon-inline"
403                   />
404                 </button>
405                 {this.state.showSidebarMobile && this.sidebar()}
406               </div>
407               {this.sortRadios()}
408               {this.state.commentViewType == CommentViewType.Tree &&
409                 this.commentsTree()}
410               {this.state.commentViewType == CommentViewType.Flat &&
411                 this.commentsFlat()}
412             </div>
413             <div className="d-none d-md-block col-md-4">{this.sidebar()}</div>
414           </div>
415         );
416       }
417     }
418   }
419
420   render() {
421     return <div className="container-lg">{this.renderPostRes()}</div>;
422   }
423
424   sortRadios() {
425     return (
426       <>
427         <div className="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
428           <label
429             className={`btn btn-outline-secondary pointer ${
430               this.state.commentSort === "Hot" && "active"
431             }`}
432           >
433             {i18n.t("hot")}
434             <input
435               type="radio"
436               value={"Hot"}
437               checked={this.state.commentSort === "Hot"}
438               onChange={linkEvent(this, this.handleCommentSortChange)}
439             />
440           </label>
441           <label
442             className={`btn btn-outline-secondary pointer ${
443               this.state.commentSort === "Top" && "active"
444             }`}
445           >
446             {i18n.t("top")}
447             <input
448               type="radio"
449               value={"Top"}
450               checked={this.state.commentSort === "Top"}
451               onChange={linkEvent(this, this.handleCommentSortChange)}
452             />
453           </label>
454           <label
455             className={`btn btn-outline-secondary pointer ${
456               this.state.commentSort === "New" && "active"
457             }`}
458           >
459             {i18n.t("new")}
460             <input
461               type="radio"
462               value={"New"}
463               checked={this.state.commentSort === "New"}
464               onChange={linkEvent(this, this.handleCommentSortChange)}
465             />
466           </label>
467           <label
468             className={`btn btn-outline-secondary pointer ${
469               this.state.commentSort === "Old" && "active"
470             }`}
471           >
472             {i18n.t("old")}
473             <input
474               type="radio"
475               value={"Old"}
476               checked={this.state.commentSort === "Old"}
477               onChange={linkEvent(this, this.handleCommentSortChange)}
478             />
479           </label>
480         </div>
481         <div className="btn-group btn-group-toggle flex-wrap mb-2">
482           <label
483             className={`btn btn-outline-secondary pointer ${
484               this.state.commentViewType === CommentViewType.Flat && "active"
485             }`}
486           >
487             {i18n.t("chat")}
488             <input
489               type="radio"
490               value={CommentViewType.Flat}
491               checked={this.state.commentViewType === CommentViewType.Flat}
492               onChange={linkEvent(this, this.handleCommentViewTypeChange)}
493             />
494           </label>
495         </div>
496       </>
497     );
498   }
499
500   commentsFlat() {
501     // These are already sorted by new
502     const commentsRes = this.state.commentsRes;
503     const postRes = this.state.postRes;
504
505     if (commentsRes.state == "success" && postRes.state == "success") {
506       return (
507         <div>
508           <CommentNodes
509             nodes={commentsToFlatNodes(commentsRes.data.comments)}
510             viewType={this.state.commentViewType}
511             maxCommentsShown={this.state.maxCommentsShown}
512             noIndent
513             locked={postRes.data.post_view.post.locked}
514             moderators={postRes.data.moderators}
515             admins={this.state.siteRes.admins}
516             enableDownvotes={enableDownvotes(this.state.siteRes)}
517             showContext
518             finished={this.state.finished}
519             allLanguages={this.state.siteRes.all_languages}
520             siteLanguages={this.state.siteRes.discussion_languages}
521             onSaveComment={this.handleSaveComment}
522             onBlockPerson={this.handleBlockPerson}
523             onDeleteComment={this.handleDeleteComment}
524             onRemoveComment={this.handleRemoveComment}
525             onCommentVote={this.handleCommentVote}
526             onCommentReport={this.handleCommentReport}
527             onDistinguishComment={this.handleDistinguishComment}
528             onAddModToCommunity={this.handleAddModToCommunity}
529             onAddAdmin={this.handleAddAdmin}
530             onTransferCommunity={this.handleTransferCommunity}
531             onFetchChildren={this.handleFetchChildren}
532             onPurgeComment={this.handlePurgeComment}
533             onPurgePerson={this.handlePurgePerson}
534             onCommentReplyRead={this.handleCommentReplyRead}
535             onPersonMentionRead={this.handlePersonMentionRead}
536             onBanPersonFromCommunity={this.handleBanFromCommunity}
537             onBanPerson={this.handleBanPerson}
538             onCreateComment={this.handleCreateComment}
539             onEditComment={this.handleEditComment}
540           />
541         </div>
542       );
543     }
544   }
545
546   sidebar() {
547     const res = this.state.postRes;
548     if (res.state === "success") {
549       return (
550         <div className="mb-3">
551           <Sidebar
552             community_view={res.data.community_view}
553             moderators={res.data.moderators}
554             admins={this.state.siteRes.admins}
555             enableNsfw={enableNsfw(this.state.siteRes)}
556             showIcon
557             allLanguages={this.state.siteRes.all_languages}
558             siteLanguages={this.state.siteRes.discussion_languages}
559             onDeleteCommunity={this.handleDeleteCommunityClick}
560             onLeaveModTeam={this.handleAddModToCommunity}
561             onFollowCommunity={this.handleFollow}
562             onRemoveCommunity={this.handleModRemoveCommunity}
563             onPurgeCommunity={this.handlePurgeCommunity}
564             onBlockCommunity={this.handleBlockCommunity}
565             onEditCommunity={this.handleEditCommunity}
566           />
567         </div>
568       );
569     }
570   }
571
572   commentsTree() {
573     const res = this.state.postRes;
574     const firstComment = this.commentTree().at(0)?.comment_view.comment;
575     const depth = getDepthFromComment(firstComment);
576     const showContextButton = depth ? depth > 0 : false;
577
578     return (
579       res.state == "success" && (
580         <div>
581           {!!this.state.commentId && (
582             <>
583               <button
584                 className="pl-0 d-block btn btn-link text-muted"
585                 onClick={linkEvent(this, this.handleViewPost)}
586               >
587                 {i18n.t("view_all_comments")} âž”
588               </button>
589               {showContextButton && (
590                 <button
591                   className="pl-0 d-block btn btn-link text-muted"
592                   onClick={linkEvent(this, this.handleViewContext)}
593                 >
594                   {i18n.t("show_context")} âž”
595                 </button>
596               )}
597             </>
598           )}
599           <CommentNodes
600             nodes={this.commentTree()}
601             viewType={this.state.commentViewType}
602             maxCommentsShown={this.state.maxCommentsShown}
603             locked={res.data.post_view.post.locked}
604             moderators={res.data.moderators}
605             admins={this.state.siteRes.admins}
606             enableDownvotes={enableDownvotes(this.state.siteRes)}
607             finished={this.state.finished}
608             allLanguages={this.state.siteRes.all_languages}
609             siteLanguages={this.state.siteRes.discussion_languages}
610             onSaveComment={this.handleSaveComment}
611             onBlockPerson={this.handleBlockPerson}
612             onDeleteComment={this.handleDeleteComment}
613             onRemoveComment={this.handleRemoveComment}
614             onCommentVote={this.handleCommentVote}
615             onCommentReport={this.handleCommentReport}
616             onDistinguishComment={this.handleDistinguishComment}
617             onAddModToCommunity={this.handleAddModToCommunity}
618             onAddAdmin={this.handleAddAdmin}
619             onTransferCommunity={this.handleTransferCommunity}
620             onFetchChildren={this.handleFetchChildren}
621             onPurgeComment={this.handlePurgeComment}
622             onPurgePerson={this.handlePurgePerson}
623             onCommentReplyRead={this.handleCommentReplyRead}
624             onPersonMentionRead={this.handlePersonMentionRead}
625             onBanPersonFromCommunity={this.handleBanFromCommunity}
626             onBanPerson={this.handleBanPerson}
627             onCreateComment={this.handleCreateComment}
628             onEditComment={this.handleEditComment}
629           />
630         </div>
631       )
632     );
633   }
634
635   commentTree(): CommentNodeI[] {
636     if (this.state.commentsRes.state == "success") {
637       return buildCommentsTree(
638         this.state.commentsRes.data.comments,
639         !!this.state.commentId
640       );
641     } else {
642       return [];
643     }
644   }
645
646   async handleCommentSortChange(i: Post, event: any) {
647     i.setState({
648       commentSort: event.target.value as CommentSortType,
649       commentViewType: CommentViewType.Tree,
650       commentsRes: { state: "loading" },
651       postRes: { state: "loading" },
652     });
653     await i.fetchPost();
654   }
655
656   handleCommentViewTypeChange(i: Post, event: any) {
657     i.setState({
658       commentViewType: Number(event.target.value),
659       commentSort: "New",
660     });
661   }
662
663   handleShowSidebarMobile(i: Post) {
664     i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
665   }
666
667   handleViewPost(i: Post) {
668     if (i.state.postRes.state == "success") {
669       const id = i.state.postRes.data.post_view.post.id;
670       i.context.router.history.push(`/post/${id}`);
671     }
672   }
673
674   handleViewContext(i: Post) {
675     if (i.state.commentsRes.state == "success") {
676       const parentId = getCommentParentId(
677         i.state.commentsRes.data.comments.at(0)?.comment
678       );
679       if (parentId) {
680         i.context.router.history.push(`/comment/${parentId}`);
681       }
682     }
683   }
684
685   async handleDeleteCommunityClick(form: DeleteCommunity) {
686     const deleteCommunityRes = await HttpService.client.deleteCommunity(form);
687     this.updateCommunity(deleteCommunityRes);
688   }
689
690   async handleAddModToCommunity(form: AddModToCommunity) {
691     const addModRes = await HttpService.client.addModToCommunity(form);
692     this.updateModerators(addModRes);
693   }
694
695   async handleFollow(form: FollowCommunity) {
696     const followCommunityRes = await HttpService.client.followCommunity(form);
697     this.updateCommunity(followCommunityRes);
698
699     // Update myUserInfo
700     if (followCommunityRes.state === "success") {
701       const communityId = followCommunityRes.data.community_view.community.id;
702       const mui = UserService.Instance.myUserInfo;
703       if (mui) {
704         mui.follows = mui.follows.filter(i => i.community.id != communityId);
705       }
706     }
707   }
708
709   async handlePurgeCommunity(form: PurgeCommunity) {
710     const purgeCommunityRes = await HttpService.client.purgeCommunity(form);
711     this.purgeItem(purgeCommunityRes);
712   }
713
714   async handlePurgePerson(form: PurgePerson) {
715     const purgePersonRes = await HttpService.client.purgePerson(form);
716     this.purgeItem(purgePersonRes);
717   }
718
719   async handlePurgeComment(form: PurgeComment) {
720     const purgeCommentRes = await HttpService.client.purgeComment(form);
721     this.purgeItem(purgeCommentRes);
722   }
723
724   async handlePurgePost(form: PurgePost) {
725     const purgeRes = await HttpService.client.purgePost(form);
726     this.purgeItem(purgeRes);
727   }
728
729   async handleBlockCommunity(form: BlockCommunity) {
730     const blockCommunityRes = await HttpService.client.blockCommunity(form);
731     if (blockCommunityRes.state == "success") {
732       updateCommunityBlock(blockCommunityRes.data);
733       this.setState(s => {
734         if (s.postRes.state == "success") {
735           s.postRes.data.community_view.blocked =
736             blockCommunityRes.data.blocked;
737         }
738       });
739     }
740   }
741
742   async handleBlockPerson(form: BlockPerson) {
743     const blockPersonRes = await HttpService.client.blockPerson(form);
744     if (blockPersonRes.state == "success") {
745       updatePersonBlock(blockPersonRes.data);
746     }
747   }
748
749   async handleModRemoveCommunity(form: RemoveCommunity) {
750     const removeCommunityRes = await HttpService.client.removeCommunity(form);
751     this.updateCommunity(removeCommunityRes);
752   }
753
754   async handleEditCommunity(form: EditCommunity) {
755     const res = await HttpService.client.editCommunity(form);
756     this.updateCommunity(res);
757
758     return res;
759   }
760
761   async handleCreateComment(form: CreateComment) {
762     const createCommentRes = await HttpService.client.createComment(form);
763     this.createAndUpdateComments(createCommentRes);
764
765     return createCommentRes;
766   }
767
768   async handleEditComment(form: EditComment) {
769     const editCommentRes = await HttpService.client.editComment(form);
770     this.findAndUpdateComment(editCommentRes);
771
772     return editCommentRes;
773   }
774
775   async handleDeleteComment(form: DeleteComment) {
776     const deleteCommentRes = await HttpService.client.deleteComment(form);
777     this.findAndUpdateComment(deleteCommentRes);
778   }
779
780   async handleDeletePost(form: DeletePost) {
781     const deleteRes = await HttpService.client.deletePost(form);
782     this.updatePost(deleteRes);
783   }
784
785   async handleRemovePost(form: RemovePost) {
786     const removeRes = await HttpService.client.removePost(form);
787     this.updatePost(removeRes);
788   }
789
790   async handleRemoveComment(form: RemoveComment) {
791     const removeCommentRes = await HttpService.client.removeComment(form);
792     this.findAndUpdateComment(removeCommentRes);
793   }
794
795   async handleSaveComment(form: SaveComment) {
796     const saveCommentRes = await HttpService.client.saveComment(form);
797     this.findAndUpdateComment(saveCommentRes);
798   }
799
800   async handleSavePost(form: SavePost) {
801     const saveRes = await HttpService.client.savePost(form);
802     this.updatePost(saveRes);
803   }
804
805   async handleFeaturePost(form: FeaturePost) {
806     const featureRes = await HttpService.client.featurePost(form);
807     this.updatePost(featureRes);
808   }
809
810   async handleCommentVote(form: CreateCommentLike) {
811     const voteRes = await HttpService.client.likeComment(form);
812     this.findAndUpdateComment(voteRes);
813   }
814
815   async handlePostVote(form: CreatePostLike) {
816     const voteRes = await HttpService.client.likePost(form);
817     this.updatePost(voteRes);
818   }
819
820   async handlePostEdit(form: EditPost) {
821     const res = await HttpService.client.editPost(form);
822     this.updatePost(res);
823   }
824
825   async handleCommentReport(form: CreateCommentReport) {
826     const reportRes = await HttpService.client.createCommentReport(form);
827     if (reportRes.state == "success") {
828       toast(i18n.t("report_created"));
829     }
830   }
831
832   async handlePostReport(form: CreatePostReport) {
833     const reportRes = await HttpService.client.createPostReport(form);
834     if (reportRes.state == "success") {
835       toast(i18n.t("report_created"));
836     }
837   }
838
839   async handleLockPost(form: LockPost) {
840     const lockRes = await HttpService.client.lockPost(form);
841     this.updatePost(lockRes);
842   }
843
844   async handleDistinguishComment(form: DistinguishComment) {
845     const distinguishRes = await HttpService.client.distinguishComment(form);
846     this.findAndUpdateComment(distinguishRes);
847   }
848
849   async handleAddAdmin(form: AddAdmin) {
850     const addAdminRes = await HttpService.client.addAdmin(form);
851
852     if (addAdminRes.state === "success") {
853       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
854     }
855   }
856
857   async handleTransferCommunity(form: TransferCommunity) {
858     const transferCommunityRes = await HttpService.client.transferCommunity(
859       form
860     );
861     this.updateCommunityFull(transferCommunityRes);
862   }
863
864   async handleFetchChildren(form: GetComments) {
865     const moreCommentsRes = await HttpService.client.getComments(form);
866     if (
867       this.state.commentsRes.state == "success" &&
868       moreCommentsRes.state == "success"
869     ) {
870       const newComments = moreCommentsRes.data.comments;
871       // Remove the first comment, since it is the parent
872       newComments.shift();
873       const newRes = this.state.commentsRes;
874       newRes.data.comments.push(...newComments);
875       this.setState({ commentsRes: newRes });
876     }
877   }
878
879   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
880     const readRes = await HttpService.client.markCommentReplyAsRead(form);
881     this.findAndUpdateCommentReply(readRes);
882   }
883
884   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
885     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
886     await HttpService.client.markPersonMentionAsRead(form);
887   }
888
889   async handleBanFromCommunity(form: BanFromCommunity) {
890     const banRes = await HttpService.client.banFromCommunity(form);
891     this.updateBan(banRes);
892   }
893
894   async handleBanPerson(form: BanPerson) {
895     const banRes = await HttpService.client.banPerson(form);
896     this.updateBan(banRes);
897   }
898
899   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
900     // Maybe not necessary
901     if (banRes.state == "success") {
902       this.setState(s => {
903         if (
904           s.postRes.state == "success" &&
905           s.postRes.data.post_view.creator.id ==
906             banRes.data.person_view.person.id
907         ) {
908           s.postRes.data.post_view.creator_banned_from_community =
909             banRes.data.banned;
910         }
911         if (s.commentsRes.state == "success") {
912           s.commentsRes.data.comments
913             .filter(c => c.creator.id == banRes.data.person_view.person.id)
914             .forEach(
915               c => (c.creator_banned_from_community = banRes.data.banned)
916             );
917         }
918         return s;
919       });
920     }
921   }
922
923   updateBan(banRes: RequestState<BanPersonResponse>) {
924     // Maybe not necessary
925     if (banRes.state == "success") {
926       this.setState(s => {
927         if (
928           s.postRes.state == "success" &&
929           s.postRes.data.post_view.creator.id ==
930             banRes.data.person_view.person.id
931         ) {
932           s.postRes.data.post_view.creator.banned = banRes.data.banned;
933         }
934         if (s.commentsRes.state == "success") {
935           s.commentsRes.data.comments
936             .filter(c => c.creator.id == banRes.data.person_view.person.id)
937             .forEach(c => (c.creator.banned = banRes.data.banned));
938         }
939         return s;
940       });
941     }
942   }
943
944   updateCommunity(communityRes: RequestState<CommunityResponse>) {
945     this.setState(s => {
946       if (s.postRes.state == "success" && communityRes.state == "success") {
947         s.postRes.data.community_view = communityRes.data.community_view;
948       }
949       return s;
950     });
951   }
952
953   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
954     this.setState(s => {
955       if (s.postRes.state == "success" && res.state == "success") {
956         s.postRes.data.community_view = res.data.community_view;
957         s.postRes.data.moderators = res.data.moderators;
958       }
959       return s;
960     });
961   }
962
963   updatePost(post: RequestState<PostResponse>) {
964     this.setState(s => {
965       if (s.postRes.state == "success" && post.state == "success") {
966         s.postRes.data.post_view = post.data.post_view;
967       }
968       return s;
969     });
970   }
971
972   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
973     if (purgeRes.state == "success") {
974       toast(i18n.t("purge_success"));
975       this.context.router.history.push(`/`);
976     }
977   }
978
979   createAndUpdateComments(res: RequestState<CommentResponse>) {
980     this.setState(s => {
981       if (s.commentsRes.state === "success" && res.state === "success") {
982         s.commentsRes.data.comments.unshift(res.data.comment_view);
983
984         // Set finished for the parent
985         s.finished.set(
986           getCommentParentId(res.data.comment_view.comment) ?? 0,
987           true
988         );
989       }
990       return s;
991     });
992   }
993
994   findAndUpdateComment(res: RequestState<CommentResponse>) {
995     this.setState(s => {
996       if (s.commentsRes.state == "success" && res.state == "success") {
997         s.commentsRes.data.comments = editComment(
998           res.data.comment_view,
999           s.commentsRes.data.comments
1000         );
1001         s.finished.set(res.data.comment_view.comment.id, true);
1002       }
1003       return s;
1004     });
1005   }
1006
1007   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1008     this.setState(s => {
1009       if (s.commentsRes.state == "success" && res.state == "success") {
1010         s.commentsRes.data.comments = editWith(
1011           res.data.comment_reply_view,
1012           s.commentsRes.data.comments
1013         );
1014       }
1015       return s;
1016     });
1017   }
1018
1019   updateModerators(res: RequestState<AddModToCommunityResponse>) {
1020     // Update the moderators
1021     this.setState(s => {
1022       if (s.postRes.state == "success" && res.state == "success") {
1023         s.postRes.data.moderators = res.data.moderators;
1024       }
1025       return s;
1026     });
1027   }
1028 }