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