]> Untitled Git - lemmy-ui.git/blob - src/shared/components/post/post.tsx
Use article semantic HTML tag for posts/comments
[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         <aside className="mb-3">
552           <Sidebar
553             community_view={res.data.community_view}
554             moderators={res.data.moderators}
555             admins={this.state.siteRes.admins}
556             online={res.data.online}
557             enableNsfw={enableNsfw(this.state.siteRes)}
558             showIcon
559             allLanguages={this.state.siteRes.all_languages}
560             siteLanguages={this.state.siteRes.discussion_languages}
561             onDeleteCommunity={this.handleDeleteCommunityClick}
562             onLeaveModTeam={this.handleAddModToCommunity}
563             onFollowCommunity={this.handleFollow}
564             onRemoveCommunity={this.handleModRemoveCommunity}
565             onPurgeCommunity={this.handlePurgeCommunity}
566             onBlockCommunity={this.handleBlockCommunity}
567             onEditCommunity={this.handleEditCommunity}
568           />
569         </aside>
570       );
571     }
572   }
573
574   commentsTree() {
575     const res = this.state.postRes;
576     const firstComment = this.commentTree().at(0)?.comment_view.comment;
577     const depth = getDepthFromComment(firstComment);
578     const showContextButton = depth ? depth > 0 : false;
579
580     return (
581       res.state == "success" && (
582         <div>
583           {!!this.state.commentId && (
584             <>
585               <button
586                 className="pl-0 d-block btn btn-link text-muted"
587                 onClick={linkEvent(this, this.handleViewPost)}
588               >
589                 {i18n.t("view_all_comments")} âž”
590               </button>
591               {showContextButton && (
592                 <button
593                   className="pl-0 d-block btn btn-link text-muted"
594                   onClick={linkEvent(this, this.handleViewContext)}
595                 >
596                   {i18n.t("show_context")} âž”
597                 </button>
598               )}
599             </>
600           )}
601           <CommentNodes
602             nodes={this.commentTree()}
603             viewType={this.state.commentViewType}
604             maxCommentsShown={this.state.maxCommentsShown}
605             locked={res.data.post_view.post.locked}
606             moderators={res.data.moderators}
607             admins={this.state.siteRes.admins}
608             enableDownvotes={enableDownvotes(this.state.siteRes)}
609             finished={this.state.finished}
610             allLanguages={this.state.siteRes.all_languages}
611             siteLanguages={this.state.siteRes.discussion_languages}
612             onSaveComment={this.handleSaveComment}
613             onBlockPerson={this.handleBlockPerson}
614             onDeleteComment={this.handleDeleteComment}
615             onRemoveComment={this.handleRemoveComment}
616             onCommentVote={this.handleCommentVote}
617             onCommentReport={this.handleCommentReport}
618             onDistinguishComment={this.handleDistinguishComment}
619             onAddModToCommunity={this.handleAddModToCommunity}
620             onAddAdmin={this.handleAddAdmin}
621             onTransferCommunity={this.handleTransferCommunity}
622             onFetchChildren={this.handleFetchChildren}
623             onPurgeComment={this.handlePurgeComment}
624             onPurgePerson={this.handlePurgePerson}
625             onCommentReplyRead={this.handleCommentReplyRead}
626             onPersonMentionRead={this.handlePersonMentionRead}
627             onBanPersonFromCommunity={this.handleBanFromCommunity}
628             onBanPerson={this.handleBanPerson}
629             onCreateComment={this.handleCreateComment}
630             onEditComment={this.handleEditComment}
631           />
632         </div>
633       )
634     );
635   }
636
637   commentTree(): CommentNodeI[] {
638     if (this.state.commentsRes.state == "success") {
639       return buildCommentsTree(
640         this.state.commentsRes.data.comments,
641         !!this.state.commentId
642       );
643     } else {
644       return [];
645     }
646   }
647
648   async handleCommentSortChange(i: Post, event: any) {
649     i.setState({
650       commentSort: event.target.value as CommentSortType,
651       commentViewType: CommentViewType.Tree,
652       commentsRes: { state: "loading" },
653       postRes: { state: "loading" },
654     });
655     await i.fetchPost();
656   }
657
658   handleCommentViewTypeChange(i: Post, event: any) {
659     i.setState({
660       commentViewType: Number(event.target.value),
661       commentSort: "New",
662     });
663   }
664
665   handleShowSidebarMobile(i: Post) {
666     i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
667   }
668
669   handleViewPost(i: Post) {
670     if (i.state.postRes.state == "success") {
671       const id = i.state.postRes.data.post_view.post.id;
672       i.context.router.history.push(`/post/${id}`);
673     }
674   }
675
676   handleViewContext(i: Post) {
677     if (i.state.commentsRes.state == "success") {
678       const parentId = getCommentParentId(
679         i.state.commentsRes.data.comments.at(0)?.comment
680       );
681       if (parentId) {
682         i.context.router.history.push(`/comment/${parentId}`);
683       }
684     }
685   }
686
687   async handleDeleteCommunityClick(form: DeleteCommunity) {
688     const deleteCommunityRes = await HttpService.client.deleteCommunity(form);
689     this.updateCommunity(deleteCommunityRes);
690   }
691
692   async handleAddModToCommunity(form: AddModToCommunity) {
693     const addModRes = await HttpService.client.addModToCommunity(form);
694     this.updateModerators(addModRes);
695   }
696
697   async handleFollow(form: FollowCommunity) {
698     const followCommunityRes = await HttpService.client.followCommunity(form);
699     this.updateCommunity(followCommunityRes);
700
701     // Update myUserInfo
702     if (followCommunityRes.state === "success") {
703       const communityId = followCommunityRes.data.community_view.community.id;
704       const mui = UserService.Instance.myUserInfo;
705       if (mui) {
706         mui.follows = mui.follows.filter(i => i.community.id != communityId);
707       }
708     }
709   }
710
711   async handlePurgeCommunity(form: PurgeCommunity) {
712     const purgeCommunityRes = await HttpService.client.purgeCommunity(form);
713     this.purgeItem(purgeCommunityRes);
714   }
715
716   async handlePurgePerson(form: PurgePerson) {
717     const purgePersonRes = await HttpService.client.purgePerson(form);
718     this.purgeItem(purgePersonRes);
719   }
720
721   async handlePurgeComment(form: PurgeComment) {
722     const purgeCommentRes = await HttpService.client.purgeComment(form);
723     this.purgeItem(purgeCommentRes);
724   }
725
726   async handlePurgePost(form: PurgePost) {
727     const purgeRes = await HttpService.client.purgePost(form);
728     this.purgeItem(purgeRes);
729   }
730
731   async handleBlockCommunity(form: BlockCommunity) {
732     const blockCommunityRes = await HttpService.client.blockCommunity(form);
733     if (blockCommunityRes.state == "success") {
734       updateCommunityBlock(blockCommunityRes.data);
735       this.setState(s => {
736         if (s.postRes.state == "success") {
737           s.postRes.data.community_view.blocked =
738             blockCommunityRes.data.blocked;
739         }
740       });
741     }
742   }
743
744   async handleBlockPerson(form: BlockPerson) {
745     const blockPersonRes = await HttpService.client.blockPerson(form);
746     if (blockPersonRes.state == "success") {
747       updatePersonBlock(blockPersonRes.data);
748     }
749   }
750
751   async handleModRemoveCommunity(form: RemoveCommunity) {
752     const removeCommunityRes = await HttpService.client.removeCommunity(form);
753     this.updateCommunity(removeCommunityRes);
754   }
755
756   async handleEditCommunity(form: EditCommunity) {
757     const res = await HttpService.client.editCommunity(form);
758     this.updateCommunity(res);
759
760     return res;
761   }
762
763   async handleCreateComment(form: CreateComment) {
764     const createCommentRes = await HttpService.client.createComment(form);
765     this.createAndUpdateComments(createCommentRes);
766
767     return createCommentRes;
768   }
769
770   async handleEditComment(form: EditComment) {
771     const editCommentRes = await HttpService.client.editComment(form);
772     this.findAndUpdateComment(editCommentRes);
773
774     return editCommentRes;
775   }
776
777   async handleDeleteComment(form: DeleteComment) {
778     const deleteCommentRes = await HttpService.client.deleteComment(form);
779     this.findAndUpdateComment(deleteCommentRes);
780   }
781
782   async handleDeletePost(form: DeletePost) {
783     const deleteRes = await HttpService.client.deletePost(form);
784     this.updatePost(deleteRes);
785   }
786
787   async handleRemovePost(form: RemovePost) {
788     const removeRes = await HttpService.client.removePost(form);
789     this.updatePost(removeRes);
790   }
791
792   async handleRemoveComment(form: RemoveComment) {
793     const removeCommentRes = await HttpService.client.removeComment(form);
794     this.findAndUpdateComment(removeCommentRes);
795   }
796
797   async handleSaveComment(form: SaveComment) {
798     const saveCommentRes = await HttpService.client.saveComment(form);
799     this.findAndUpdateComment(saveCommentRes);
800   }
801
802   async handleSavePost(form: SavePost) {
803     const saveRes = await HttpService.client.savePost(form);
804     this.updatePost(saveRes);
805   }
806
807   async handleFeaturePost(form: FeaturePost) {
808     const featureRes = await HttpService.client.featurePost(form);
809     this.updatePost(featureRes);
810   }
811
812   async handleCommentVote(form: CreateCommentLike) {
813     const voteRes = await HttpService.client.likeComment(form);
814     this.findAndUpdateComment(voteRes);
815   }
816
817   async handlePostVote(form: CreatePostLike) {
818     const voteRes = await HttpService.client.likePost(form);
819     this.updatePost(voteRes);
820   }
821
822   async handlePostEdit(form: EditPost) {
823     const res = await HttpService.client.editPost(form);
824     this.updatePost(res);
825   }
826
827   async handleCommentReport(form: CreateCommentReport) {
828     const reportRes = await HttpService.client.createCommentReport(form);
829     if (reportRes.state == "success") {
830       toast(i18n.t("report_created"));
831     }
832   }
833
834   async handlePostReport(form: CreatePostReport) {
835     const reportRes = await HttpService.client.createPostReport(form);
836     if (reportRes.state == "success") {
837       toast(i18n.t("report_created"));
838     }
839   }
840
841   async handleLockPost(form: LockPost) {
842     const lockRes = await HttpService.client.lockPost(form);
843     this.updatePost(lockRes);
844   }
845
846   async handleDistinguishComment(form: DistinguishComment) {
847     const distinguishRes = await HttpService.client.distinguishComment(form);
848     this.findAndUpdateComment(distinguishRes);
849   }
850
851   async handleAddAdmin(form: AddAdmin) {
852     const addAdminRes = await HttpService.client.addAdmin(form);
853
854     if (addAdminRes.state === "success") {
855       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
856     }
857   }
858
859   async handleTransferCommunity(form: TransferCommunity) {
860     const transferCommunityRes = await HttpService.client.transferCommunity(
861       form
862     );
863     this.updateCommunityFull(transferCommunityRes);
864   }
865
866   async handleFetchChildren(form: GetComments) {
867     const moreCommentsRes = await HttpService.client.getComments(form);
868     if (
869       this.state.commentsRes.state == "success" &&
870       moreCommentsRes.state == "success"
871     ) {
872       const newComments = moreCommentsRes.data.comments;
873       // Remove the first comment, since it is the parent
874       newComments.shift();
875       const newRes = this.state.commentsRes;
876       newRes.data.comments.push(...newComments);
877       this.setState({ commentsRes: newRes });
878     }
879   }
880
881   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
882     const readRes = await HttpService.client.markCommentReplyAsRead(form);
883     this.findAndUpdateCommentReply(readRes);
884   }
885
886   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
887     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
888     await HttpService.client.markPersonMentionAsRead(form);
889   }
890
891   async handleBanFromCommunity(form: BanFromCommunity) {
892     const banRes = await HttpService.client.banFromCommunity(form);
893     this.updateBan(banRes);
894   }
895
896   async handleBanPerson(form: BanPerson) {
897     const banRes = await HttpService.client.banPerson(form);
898     this.updateBan(banRes);
899   }
900
901   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
902     // Maybe not necessary
903     if (banRes.state == "success") {
904       this.setState(s => {
905         if (
906           s.postRes.state == "success" &&
907           s.postRes.data.post_view.creator.id ==
908             banRes.data.person_view.person.id
909         ) {
910           s.postRes.data.post_view.creator_banned_from_community =
911             banRes.data.banned;
912         }
913         if (s.commentsRes.state == "success") {
914           s.commentsRes.data.comments
915             .filter(c => c.creator.id == banRes.data.person_view.person.id)
916             .forEach(
917               c => (c.creator_banned_from_community = banRes.data.banned)
918             );
919         }
920         return s;
921       });
922     }
923   }
924
925   updateBan(banRes: RequestState<BanPersonResponse>) {
926     // Maybe not necessary
927     if (banRes.state == "success") {
928       this.setState(s => {
929         if (
930           s.postRes.state == "success" &&
931           s.postRes.data.post_view.creator.id ==
932             banRes.data.person_view.person.id
933         ) {
934           s.postRes.data.post_view.creator.banned = banRes.data.banned;
935         }
936         if (s.commentsRes.state == "success") {
937           s.commentsRes.data.comments
938             .filter(c => c.creator.id == banRes.data.person_view.person.id)
939             .forEach(c => (c.creator.banned = banRes.data.banned));
940         }
941         return s;
942       });
943     }
944   }
945
946   updateCommunity(communityRes: RequestState<CommunityResponse>) {
947     this.setState(s => {
948       if (s.postRes.state == "success" && communityRes.state == "success") {
949         s.postRes.data.community_view = communityRes.data.community_view;
950       }
951       return s;
952     });
953   }
954
955   updateCommunityFull(res: RequestState<GetCommunityResponse>) {
956     this.setState(s => {
957       if (s.postRes.state == "success" && res.state == "success") {
958         s.postRes.data.community_view = res.data.community_view;
959         s.postRes.data.moderators = res.data.moderators;
960       }
961       return s;
962     });
963   }
964
965   updatePost(post: RequestState<PostResponse>) {
966     this.setState(s => {
967       if (s.postRes.state == "success" && post.state == "success") {
968         s.postRes.data.post_view = post.data.post_view;
969       }
970       return s;
971     });
972   }
973
974   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
975     if (purgeRes.state == "success") {
976       toast(i18n.t("purge_success"));
977       this.context.router.history.push(`/`);
978     }
979   }
980
981   createAndUpdateComments(res: RequestState<CommentResponse>) {
982     this.setState(s => {
983       if (s.commentsRes.state === "success" && res.state === "success") {
984         s.commentsRes.data.comments.unshift(res.data.comment_view);
985
986         // Set finished for the parent
987         s.finished.set(
988           getCommentParentId(res.data.comment_view.comment) ?? 0,
989           true
990         );
991       }
992       return s;
993     });
994   }
995
996   findAndUpdateComment(res: RequestState<CommentResponse>) {
997     this.setState(s => {
998       if (s.commentsRes.state == "success" && res.state == "success") {
999         s.commentsRes.data.comments = editComment(
1000           res.data.comment_view,
1001           s.commentsRes.data.comments
1002         );
1003         s.finished.set(res.data.comment_view.comment.id, true);
1004       }
1005       return s;
1006     });
1007   }
1008
1009   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1010     this.setState(s => {
1011       if (s.commentsRes.state == "success" && res.state == "success") {
1012         s.commentsRes.data.comments = editWith(
1013           res.data.comment_reply_view,
1014           s.commentsRes.data.comments
1015         );
1016       }
1017       return s;
1018     });
1019   }
1020
1021   updateModerators(res: RequestState<AddModToCommunityResponse>) {
1022     // Update the moderators
1023     this.setState(s => {
1024       if (s.postRes.state == "success" && res.state == "success") {
1025         s.postRes.data.moderators = res.data.moderators;
1026       }
1027       return s;
1028     });
1029   }
1030 }