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