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