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