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