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