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