]> Untitled Git - lemmy-ui.git/blob - src/shared/components/post/post.tsx
Merge branch 'main' into feat/markdown-format-bar-above
[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                 containerClass="post-comment-container"
388                 onUpsertComment={this.handleCreateComment}
389                 finished={this.state.finished.get(0)}
390               />
391               <div className="d-block d-md-none">
392                 <button
393                   className="btn btn-secondary d-inline-block mb-2 mr-3"
394                   onClick={linkEvent(this, this.handleShowSidebarMobile)}
395                 >
396                   {i18n.t("sidebar")}{" "}
397                   <Icon
398                     icon={
399                       this.state.showSidebarMobile
400                         ? `minus-square`
401                         : `plus-square`
402                     }
403                     classes="icon-inline"
404                   />
405                 </button>
406                 {this.state.showSidebarMobile && this.sidebar()}
407               </div>
408               {this.sortRadios()}
409               {this.state.commentViewType == CommentViewType.Tree &&
410                 this.commentsTree()}
411               {this.state.commentViewType == CommentViewType.Flat &&
412                 this.commentsFlat()}
413             </div>
414             <div className="d-none d-md-block col-md-4">{this.sidebar()}</div>
415           </div>
416         );
417       }
418     }
419   }
420
421   render() {
422     return <div className="container-lg">{this.renderPostRes()}</div>;
423   }
424
425   sortRadios() {
426     return (
427       <>
428         <div className="btn-group btn-group-toggle flex-wrap mr-3 mb-2">
429           <label
430             className={`btn btn-outline-secondary pointer ${
431               this.state.commentSort === "Hot" && "active"
432             }`}
433           >
434             {i18n.t("hot")}
435             <input
436               type="radio"
437               value={"Hot"}
438               checked={this.state.commentSort === "Hot"}
439               onChange={linkEvent(this, this.handleCommentSortChange)}
440             />
441           </label>
442           <label
443             className={`btn btn-outline-secondary pointer ${
444               this.state.commentSort === "Top" && "active"
445             }`}
446           >
447             {i18n.t("top")}
448             <input
449               type="radio"
450               value={"Top"}
451               checked={this.state.commentSort === "Top"}
452               onChange={linkEvent(this, this.handleCommentSortChange)}
453             />
454           </label>
455           <label
456             className={`btn btn-outline-secondary pointer ${
457               this.state.commentSort === "New" && "active"
458             }`}
459           >
460             {i18n.t("new")}
461             <input
462               type="radio"
463               value={"New"}
464               checked={this.state.commentSort === "New"}
465               onChange={linkEvent(this, this.handleCommentSortChange)}
466             />
467           </label>
468           <label
469             className={`btn btn-outline-secondary pointer ${
470               this.state.commentSort === "Old" && "active"
471             }`}
472           >
473             {i18n.t("old")}
474             <input
475               type="radio"
476               value={"Old"}
477               checked={this.state.commentSort === "Old"}
478               onChange={linkEvent(this, this.handleCommentSortChange)}
479             />
480           </label>
481         </div>
482         <div className="btn-group btn-group-toggle flex-wrap mb-2">
483           <label
484             className={`btn btn-outline-secondary pointer ${
485               this.state.commentViewType === CommentViewType.Flat && "active"
486             }`}
487           >
488             {i18n.t("chat")}
489             <input
490               type="radio"
491               value={CommentViewType.Flat}
492               checked={this.state.commentViewType === CommentViewType.Flat}
493               onChange={linkEvent(this, this.handleCommentViewTypeChange)}
494             />
495           </label>
496         </div>
497       </>
498     );
499   }
500
501   commentsFlat() {
502     // These are already sorted by new
503     const commentsRes = this.state.commentsRes;
504     const postRes = this.state.postRes;
505
506     if (commentsRes.state == "success" && postRes.state == "success") {
507       return (
508         <div>
509           <CommentNodes
510             nodes={commentsToFlatNodes(commentsRes.data.comments)}
511             viewType={this.state.commentViewType}
512             maxCommentsShown={this.state.maxCommentsShown}
513             noIndent
514             locked={postRes.data.post_view.post.locked}
515             moderators={postRes.data.moderators}
516             admins={this.state.siteRes.admins}
517             enableDownvotes={enableDownvotes(this.state.siteRes)}
518             showContext
519             finished={this.state.finished}
520             allLanguages={this.state.siteRes.all_languages}
521             siteLanguages={this.state.siteRes.discussion_languages}
522             onSaveComment={this.handleSaveComment}
523             onBlockPerson={this.handleBlockPerson}
524             onDeleteComment={this.handleDeleteComment}
525             onRemoveComment={this.handleRemoveComment}
526             onCommentVote={this.handleCommentVote}
527             onCommentReport={this.handleCommentReport}
528             onDistinguishComment={this.handleDistinguishComment}
529             onAddModToCommunity={this.handleAddModToCommunity}
530             onAddAdmin={this.handleAddAdmin}
531             onTransferCommunity={this.handleTransferCommunity}
532             onFetchChildren={this.handleFetchChildren}
533             onPurgeComment={this.handlePurgeComment}
534             onPurgePerson={this.handlePurgePerson}
535             onCommentReplyRead={this.handleCommentReplyRead}
536             onPersonMentionRead={this.handlePersonMentionRead}
537             onBanPersonFromCommunity={this.handleBanFromCommunity}
538             onBanPerson={this.handleBanPerson}
539             onCreateComment={this.handleCreateComment}
540             onEditComment={this.handleEditComment}
541           />
542         </div>
543       );
544     }
545   }
546
547   sidebar() {
548     const res = this.state.postRes;
549     if (res.state === "success") {
550       return (
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       );
568     }
569   }
570
571   commentsTree() {
572     const res = this.state.postRes;
573     const firstComment = this.commentTree().at(0)?.comment_view.comment;
574     const depth = getDepthFromComment(firstComment);
575     const showContextButton = depth ? depth > 0 : false;
576
577     return (
578       res.state == "success" && (
579         <div>
580           {!!this.state.commentId && (
581             <>
582               <button
583                 className="pl-0 d-block btn btn-link text-muted"
584                 onClick={linkEvent(this, this.handleViewPost)}
585               >
586                 {i18n.t("view_all_comments")} âž”
587               </button>
588               {showContextButton && (
589                 <button
590                   className="pl-0 d-block btn btn-link text-muted"
591                   onClick={linkEvent(this, this.handleViewContext)}
592                 >
593                   {i18n.t("show_context")} âž”
594                 </button>
595               )}
596             </>
597           )}
598           <CommentNodes
599             nodes={this.commentTree()}
600             viewType={this.state.commentViewType}
601             maxCommentsShown={this.state.maxCommentsShown}
602             locked={res.data.post_view.post.locked}
603             moderators={res.data.moderators}
604             admins={this.state.siteRes.admins}
605             enableDownvotes={enableDownvotes(this.state.siteRes)}
606             finished={this.state.finished}
607             allLanguages={this.state.siteRes.all_languages}
608             siteLanguages={this.state.siteRes.discussion_languages}
609             onSaveComment={this.handleSaveComment}
610             onBlockPerson={this.handleBlockPerson}
611             onDeleteComment={this.handleDeleteComment}
612             onRemoveComment={this.handleRemoveComment}
613             onCommentVote={this.handleCommentVote}
614             onCommentReport={this.handleCommentReport}
615             onDistinguishComment={this.handleDistinguishComment}
616             onAddModToCommunity={this.handleAddModToCommunity}
617             onAddAdmin={this.handleAddAdmin}
618             onTransferCommunity={this.handleTransferCommunity}
619             onFetchChildren={this.handleFetchChildren}
620             onPurgeComment={this.handlePurgeComment}
621             onPurgePerson={this.handlePurgePerson}
622             onCommentReplyRead={this.handleCommentReplyRead}
623             onPersonMentionRead={this.handlePersonMentionRead}
624             onBanPersonFromCommunity={this.handleBanFromCommunity}
625             onBanPerson={this.handleBanPerson}
626             onCreateComment={this.handleCreateComment}
627             onEditComment={this.handleEditComment}
628           />
629         </div>
630       )
631     );
632   }
633
634   commentTree(): CommentNodeI[] {
635     if (this.state.commentsRes.state == "success") {
636       return buildCommentsTree(
637         this.state.commentsRes.data.comments,
638         !!this.state.commentId
639       );
640     } else {
641       return [];
642     }
643   }
644
645   async handleCommentSortChange(i: Post, event: any) {
646     i.setState({
647       commentSort: event.target.value as CommentSortType,
648       commentViewType: CommentViewType.Tree,
649       commentsRes: { state: "loading" },
650       postRes: { state: "loading" },
651     });
652     await i.fetchPost();
653   }
654
655   handleCommentViewTypeChange(i: Post, event: any) {
656     i.setState({
657       commentViewType: Number(event.target.value),
658       commentSort: "New",
659     });
660   }
661
662   handleShowSidebarMobile(i: Post) {
663     i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
664   }
665
666   handleViewPost(i: Post) {
667     if (i.state.postRes.state == "success") {
668       const id = i.state.postRes.data.post_view.post.id;
669       i.context.router.history.push(`/post/${id}`);
670     }
671   }
672
673   handleViewContext(i: Post) {
674     if (i.state.commentsRes.state == "success") {
675       const parentId = getCommentParentId(
676         i.state.commentsRes.data.comments.at(0)?.comment
677       );
678       if (parentId) {
679         i.context.router.history.push(`/comment/${parentId}`);
680       }
681     }
682   }
683
684   async handleDeleteCommunityClick(form: DeleteCommunity) {
685     const deleteCommunityRes = await HttpService.client.deleteCommunity(form);
686     this.updateCommunity(deleteCommunityRes);
687   }
688
689   async handleAddModToCommunity(form: AddModToCommunity) {
690     const addModRes = await HttpService.client.addModToCommunity(form);
691     this.updateModerators(addModRes);
692   }
693
694   async handleFollow(form: FollowCommunity) {
695     const followCommunityRes = await HttpService.client.followCommunity(form);
696     this.updateCommunity(followCommunityRes);
697
698     // Update myUserInfo
699     if (followCommunityRes.state === "success") {
700       const communityId = followCommunityRes.data.community_view.community.id;
701       const mui = UserService.Instance.myUserInfo;
702       if (mui) {
703         mui.follows = mui.follows.filter(i => i.community.id != communityId);
704       }
705     }
706   }
707
708   async handlePurgeCommunity(form: PurgeCommunity) {
709     const purgeCommunityRes = await HttpService.client.purgeCommunity(form);
710     this.purgeItem(purgeCommunityRes);
711   }
712
713   async handlePurgePerson(form: PurgePerson) {
714     const purgePersonRes = await HttpService.client.purgePerson(form);
715     this.purgeItem(purgePersonRes);
716   }
717
718   async handlePurgeComment(form: PurgeComment) {
719     const purgeCommentRes = await HttpService.client.purgeComment(form);
720     this.purgeItem(purgeCommentRes);
721   }
722
723   async handlePurgePost(form: PurgePost) {
724     const purgeRes = await HttpService.client.purgePost(form);
725     this.purgeItem(purgeRes);
726   }
727
728   async handleBlockCommunity(form: BlockCommunity) {
729     const blockCommunityRes = await HttpService.client.blockCommunity(form);
730     if (blockCommunityRes.state == "success") {
731       updateCommunityBlock(blockCommunityRes.data);
732       this.setState(s => {
733         if (s.postRes.state == "success") {
734           s.postRes.data.community_view.blocked =
735             blockCommunityRes.data.blocked;
736         }
737       });
738     }
739   }
740
741   async handleBlockPerson(form: BlockPerson) {
742     const blockPersonRes = await HttpService.client.blockPerson(form);
743     if (blockPersonRes.state == "success") {
744       updatePersonBlock(blockPersonRes.data);
745     }
746   }
747
748   async handleModRemoveCommunity(form: RemoveCommunity) {
749     const removeCommunityRes = await HttpService.client.removeCommunity(form);
750     this.updateCommunity(removeCommunityRes);
751   }
752
753   async handleEditCommunity(form: EditCommunity) {
754     const res = await HttpService.client.editCommunity(form);
755     this.updateCommunity(res);
756
757     return res;
758   }
759
760   async handleCreateComment(form: CreateComment) {
761     const createCommentRes = await HttpService.client.createComment(form);
762     this.createAndUpdateComments(createCommentRes);
763
764     return createCommentRes;
765   }
766
767   async handleEditComment(form: EditComment) {
768     const editCommentRes = await HttpService.client.editComment(form);
769     this.findAndUpdateComment(editCommentRes);
770
771     return editCommentRes;
772   }
773
774   async handleDeleteComment(form: DeleteComment) {
775     const deleteCommentRes = await HttpService.client.deleteComment(form);
776     this.findAndUpdateComment(deleteCommentRes);
777   }
778
779   async handleDeletePost(form: DeletePost) {
780     const deleteRes = await HttpService.client.deletePost(form);
781     this.updatePost(deleteRes);
782   }
783
784   async handleRemovePost(form: RemovePost) {
785     const removeRes = await HttpService.client.removePost(form);
786     this.updatePost(removeRes);
787   }
788
789   async handleRemoveComment(form: RemoveComment) {
790     const removeCommentRes = await HttpService.client.removeComment(form);
791     this.findAndUpdateComment(removeCommentRes);
792   }
793
794   async handleSaveComment(form: SaveComment) {
795     const saveCommentRes = await HttpService.client.saveComment(form);
796     this.findAndUpdateComment(saveCommentRes);
797   }
798
799   async handleSavePost(form: SavePost) {
800     const saveRes = await HttpService.client.savePost(form);
801     this.updatePost(saveRes);
802   }
803
804   async handleFeaturePost(form: FeaturePost) {
805     const featureRes = await HttpService.client.featurePost(form);
806     this.updatePost(featureRes);
807   }
808
809   async handleCommentVote(form: CreateCommentLike) {
810     const voteRes = await HttpService.client.likeComment(form);
811     this.findAndUpdateComment(voteRes);
812   }
813
814   async handlePostVote(form: CreatePostLike) {
815     const voteRes = await HttpService.client.likePost(form);
816     this.updatePost(voteRes);
817   }
818
819   async handlePostEdit(form: EditPost) {
820     const res = await HttpService.client.editPost(form);
821     this.updatePost(res);
822   }
823
824   async handleCommentReport(form: CreateCommentReport) {
825     const reportRes = await HttpService.client.createCommentReport(form);
826     if (reportRes.state == "success") {
827       toast(i18n.t("report_created"));
828     }
829   }
830
831   async handlePostReport(form: CreatePostReport) {
832     const reportRes = await HttpService.client.createPostReport(form);
833     if (reportRes.state == "success") {
834       toast(i18n.t("report_created"));
835     }
836   }
837
838   async handleLockPost(form: LockPost) {
839     const lockRes = await HttpService.client.lockPost(form);
840     this.updatePost(lockRes);
841   }
842
843   async handleDistinguishComment(form: DistinguishComment) {
844     const distinguishRes = await HttpService.client.distinguishComment(form);
845     this.findAndUpdateComment(distinguishRes);
846   }
847
848   async handleAddAdmin(form: AddAdmin) {
849     const addAdminRes = await HttpService.client.addAdmin(form);
850
851     if (addAdminRes.state === "success") {
852       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
853     }
854   }
855
856   async handleTransferCommunity(form: TransferCommunity) {
857     const transferCommunityRes = await HttpService.client.transferCommunity(
858       form
859     );
860     this.updateCommunityFull(transferCommunityRes);
861   }
862
863   async handleFetchChildren(form: GetComments) {
864     const moreCommentsRes = await HttpService.client.getComments(form);
865     if (
866       this.state.commentsRes.state == "success" &&
867       moreCommentsRes.state == "success"
868     ) {
869       const newComments = moreCommentsRes.data.comments;
870       // Remove the first comment, since it is the parent
871       newComments.shift();
872       const newRes = this.state.commentsRes;
873       newRes.data.comments.push(...newComments);
874       this.setState({ commentsRes: newRes });
875     }
876   }
877
878   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
879     const readRes = await HttpService.client.markCommentReplyAsRead(form);
880     this.findAndUpdateCommentReply(readRes);
881   }
882
883   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
884     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
885     await HttpService.client.markPersonMentionAsRead(form);
886   }
887
888   async handleBanFromCommunity(form: BanFromCommunity) {
889     const banRes = await HttpService.client.banFromCommunity(form);
890     this.updateBan(banRes);
891   }
892
893   async handleBanPerson(form: BanPerson) {
894     const banRes = await HttpService.client.banPerson(form);
895     this.updateBan(banRes);
896   }
897
898   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
899     // Maybe not necessary
900     if (banRes.state == "success") {
901       this.setState(s => {
902         if (
903           s.postRes.state == "success" &&
904           s.postRes.data.post_view.creator.id ==
905             banRes.data.person_view.person.id
906         ) {
907           s.postRes.data.post_view.creator_banned_from_community =
908             banRes.data.banned;
909         }
910         if (s.commentsRes.state == "success") {
911           s.commentsRes.data.comments
912             .filter(c => c.creator.id == banRes.data.person_view.person.id)
913             .forEach(
914               c => (c.creator_banned_from_community = banRes.data.banned)
915             );
916         }
917         return s;
918       });
919     }
920   }
921
922   updateBan(banRes: RequestState<BanPersonResponse>) {
923     // Maybe not necessary
924     if (banRes.state == "success") {
925       this.setState(s => {
926         if (
927           s.postRes.state == "success" &&
928           s.postRes.data.post_view.creator.id ==
929             banRes.data.person_view.person.id
930         ) {
931           s.postRes.data.post_view.creator.banned = banRes.data.banned;
932         }
933         if (s.commentsRes.state == "success") {
934           s.commentsRes.data.comments
935             .filter(c => c.creator.id == banRes.data.person_view.person.id)
936             .forEach(c => (c.creator.banned = banRes.data.banned));
937         }
938         return s;
939       });
940     }
941   }
942
943   updateCommunity(communityRes: RequestState<CommunityResponse>) {
944     this.setState(s => {
945       if (s.postRes.state == "success" && communityRes.state == "success") {
946         s.postRes.data.community_view = communityRes.data.community_view;
947       }
948       return s;
949     });
950   }
951
952   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
953     this.setState(s => {
954       if (s.postRes.state == "success" && res.state == "success") {
955         s.postRes.data.community_view = res.data.community_view;
956         s.postRes.data.moderators = res.data.moderators;
957       }
958       return s;
959     });
960   }
961
962   updatePost(post: RequestState<PostResponse>) {
963     this.setState(s => {
964       if (s.postRes.state == "success" && post.state == "success") {
965         s.postRes.data.post_view = post.data.post_view;
966       }
967       return s;
968     });
969   }
970
971   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
972     if (purgeRes.state == "success") {
973       toast(i18n.t("purge_success"));
974       this.context.router.history.push(`/`);
975     }
976   }
977
978   createAndUpdateComments(res: RequestState<CommentResponse>) {
979     this.setState(s => {
980       if (s.commentsRes.state === "success" && res.state === "success") {
981         s.commentsRes.data.comments.unshift(res.data.comment_view);
982
983         // Set finished for the parent
984         s.finished.set(
985           getCommentParentId(res.data.comment_view.comment) ?? 0,
986           true
987         );
988       }
989       return s;
990     });
991   }
992
993   findAndUpdateComment(res: RequestState<CommentResponse>) {
994     this.setState(s => {
995       if (s.commentsRes.state == "success" && res.state == "success") {
996         s.commentsRes.data.comments = editComment(
997           res.data.comment_view,
998           s.commentsRes.data.comments
999         );
1000         s.finished.set(res.data.comment_view.comment.id, true);
1001       }
1002       return s;
1003     });
1004   }
1005
1006   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1007     this.setState(s => {
1008       if (s.commentsRes.state == "success" && res.state == "success") {
1009         s.commentsRes.data.comments = editWith(
1010           res.data.comment_reply_view,
1011           s.commentsRes.data.comments
1012         );
1013       }
1014       return s;
1015     });
1016   }
1017
1018   updateModerators(res: RequestState<AddModToCommunityResponse>) {
1019     // Update the moderators
1020     this.setState(s => {
1021       if (s.postRes.state == "success" && res.state == "success") {
1022         s.postRes.data.moderators = res.data.moderators;
1023       }
1024       return s;
1025     });
1026   }
1027 }