]> Untitled Git - lemmy-ui.git/blob - src/shared/components/home/home.tsx
Changing all bigints to numbers
[lemmy-ui.git] / src / shared / components / home / home.tsx
1 import { NoOptionI18nKeys } from "i18next";
2 import { Component, linkEvent, MouseEventHandler } from "inferno";
3 import { T } from "inferno-i18next-dess";
4 import { Link } from "inferno-router";
5 import {
6   AddAdminResponse,
7   BanPersonResponse,
8   BlockPersonResponse,
9   CommentReportResponse,
10   CommentResponse,
11   CommentView,
12   CommunityView,
13   GetComments,
14   GetCommentsResponse,
15   GetPosts,
16   GetPostsResponse,
17   GetSiteResponse,
18   ListCommunities,
19   ListCommunitiesResponse,
20   ListingType,
21   PostReportResponse,
22   PostResponse,
23   PostView,
24   PurgeItemResponse,
25   SiteResponse,
26   SortType,
27   UserOperation,
28   wsJsonToRes,
29   wsUserOp,
30 } from "lemmy-js-client";
31 import { Subscription } from "rxjs";
32 import { i18n } from "../../i18next";
33 import {
34   CommentViewType,
35   DataType,
36   InitialFetchRequest,
37 } from "../../interfaces";
38 import { UserService, WebSocketService } from "../../services";
39 import {
40   canCreateCommunity,
41   commentsToFlatNodes,
42   createCommentLikeRes,
43   createPostLikeFindRes,
44   editCommentRes,
45   editPostFindRes,
46   enableDownvotes,
47   enableNsfw,
48   fetchLimit,
49   getDataTypeString,
50   getPageFromString,
51   getQueryParams,
52   getQueryString,
53   getRandomFromList,
54   isBrowser,
55   isPostBlocked,
56   mdToHtml,
57   myAuth,
58   notifyPost,
59   nsfwCheck,
60   postToCommentSortType,
61   QueryParams,
62   relTags,
63   restoreScrollPosition,
64   saveCommentRes,
65   saveScrollPosition,
66   setIsoData,
67   setupTippy,
68   showLocal,
69   toast,
70   trendingFetchLimit,
71   updatePersonBlock,
72   wsClient,
73   wsSubscribe,
74 } from "../../utils";
75 import { CommentNodes } from "../comment/comment-nodes";
76 import { DataTypeSelect } from "../common/data-type-select";
77 import { HtmlTags } from "../common/html-tags";
78 import { Icon, Spinner } from "../common/icon";
79 import { ListingTypeSelect } from "../common/listing-type-select";
80 import { Paginator } from "../common/paginator";
81 import { SortSelect } from "../common/sort-select";
82 import { CommunityLink } from "../community/community-link";
83 import { PostListings } from "../post/post-listings";
84 import { SiteSidebar } from "./site-sidebar";
85
86 interface HomeState {
87   trendingCommunities: CommunityView[];
88   siteRes: GetSiteResponse;
89   posts: PostView[];
90   comments: CommentView[];
91   showSubscribedMobile: boolean;
92   showTrendingMobile: boolean;
93   showSidebarMobile: boolean;
94   subscribedCollapsed: boolean;
95   loading: boolean;
96   tagline?: string;
97 }
98
99 interface HomeProps {
100   listingType: ListingType;
101   dataType: DataType;
102   sort: SortType;
103   page: number;
104 }
105
106 function getDataTypeFromQuery(type?: string): DataType {
107   return type ? DataType[type] : DataType.Post;
108 }
109
110 function getListingTypeFromQuery(type?: string): ListingType {
111   const myListingType =
112     UserService.Instance.myUserInfo?.local_user_view?.local_user
113       ?.default_listing_type;
114
115   return type ? (type as ListingType) : myListingType ?? "Local";
116 }
117
118 function getSortTypeFromQuery(type?: string): SortType {
119   const mySortType =
120     UserService.Instance.myUserInfo?.local_user_view?.local_user
121       ?.default_sort_type;
122
123   return type ? (type as SortType) : mySortType ?? "Active";
124 }
125
126 const getHomeQueryParams = () =>
127   getQueryParams<HomeProps>({
128     sort: getSortTypeFromQuery,
129     listingType: getListingTypeFromQuery,
130     page: getPageFromString,
131     dataType: getDataTypeFromQuery,
132   });
133
134 function fetchTrendingCommunities() {
135   const listCommunitiesForm: ListCommunities = {
136     type_: "Local",
137     sort: "Hot",
138     limit: trendingFetchLimit,
139     auth: myAuth(false),
140   };
141   WebSocketService.Instance.send(wsClient.listCommunities(listCommunitiesForm));
142 }
143
144 function fetchData() {
145   const auth = myAuth(false);
146   const { dataType, page, listingType, sort } = getHomeQueryParams();
147   let req: string;
148
149   if (dataType === DataType.Post) {
150     const getPostsForm: GetPosts = {
151       page,
152       limit: fetchLimit,
153       sort,
154       saved_only: false,
155       type_: listingType,
156       auth,
157     };
158
159     req = wsClient.getPosts(getPostsForm);
160   } else {
161     const getCommentsForm: GetComments = {
162       page,
163       limit: fetchLimit,
164       sort: postToCommentSortType(sort),
165       saved_only: false,
166       type_: listingType,
167       auth,
168     };
169
170     req = wsClient.getComments(getCommentsForm);
171   }
172
173   WebSocketService.Instance.send(req);
174 }
175
176 const MobileButton = ({
177   textKey,
178   show,
179   onClick,
180 }: {
181   textKey: NoOptionI18nKeys;
182   show: boolean;
183   onClick: MouseEventHandler<HTMLButtonElement>;
184 }) => (
185   <button
186     className="btn btn-secondary d-inline-block mb-2 mr-3"
187     onClick={onClick}
188   >
189     {i18n.t(textKey)}{" "}
190     <Icon icon={show ? `minus-square` : `plus-square`} classes="icon-inline" />
191   </button>
192 );
193
194 const LinkButton = ({
195   path,
196   translationKey,
197 }: {
198   path: string;
199   translationKey: NoOptionI18nKeys;
200 }) => (
201   <Link className="btn btn-secondary btn-block" to={path}>
202     {i18n.t(translationKey)}
203   </Link>
204 );
205
206 function getRss(listingType: ListingType) {
207   const { sort } = getHomeQueryParams();
208   const auth = myAuth(false);
209
210   let rss: string | undefined = undefined;
211
212   switch (listingType) {
213     case "All": {
214       rss = `/feeds/all.xml?sort=${sort}`;
215       break;
216     }
217     case "Local": {
218       rss = `/feeds/local.xml?sort=${sort}`;
219       break;
220     }
221     case "Subscribed": {
222       rss = auth ? `/feeds/front/${auth}.xml?sort=${sort}` : undefined;
223       break;
224     }
225   }
226
227   return (
228     rss && (
229       <>
230         <a href={rss} rel={relTags} title="RSS">
231           <Icon icon="rss" classes="text-muted small" />
232         </a>
233         <link rel="alternate" type="application/atom+xml" href={rss} />
234       </>
235     )
236   );
237 }
238
239 export class Home extends Component<any, HomeState> {
240   private isoData = setIsoData(this.context);
241   private subscription?: Subscription;
242   state: HomeState = {
243     trendingCommunities: [],
244     siteRes: this.isoData.site_res,
245     showSubscribedMobile: false,
246     showTrendingMobile: false,
247     showSidebarMobile: false,
248     subscribedCollapsed: false,
249     loading: true,
250     posts: [],
251     comments: [],
252   };
253
254   constructor(props: any, context: any) {
255     super(props, context);
256
257     this.handleSortChange = this.handleSortChange.bind(this);
258     this.handleListingTypeChange = this.handleListingTypeChange.bind(this);
259     this.handleDataTypeChange = this.handleDataTypeChange.bind(this);
260     this.handlePageChange = this.handlePageChange.bind(this);
261
262     this.parseMessage = this.parseMessage.bind(this);
263     this.subscription = wsSubscribe(this.parseMessage);
264
265     // Only fetch the data if coming from another route
266     if (this.isoData.path === this.context.router.route.match.url) {
267       const postsRes = this.isoData.routeData[0] as
268         | GetPostsResponse
269         | undefined;
270       const commentsRes = this.isoData.routeData[1] as
271         | GetCommentsResponse
272         | undefined;
273       const trendingRes = this.isoData.routeData[2] as
274         | ListCommunitiesResponse
275         | undefined;
276
277       if (postsRes) {
278         this.state = { ...this.state, posts: postsRes.posts };
279       }
280
281       if (commentsRes) {
282         this.state = { ...this.state, comments: commentsRes.comments };
283       }
284
285       if (isBrowser()) {
286         WebSocketService.Instance.send(
287           wsClient.communityJoin({ community_id: 0 })
288         );
289       }
290       const taglines = this.state?.siteRes?.taglines ?? [];
291       this.state = {
292         ...this.state,
293         trendingCommunities: trendingRes?.communities ?? [],
294         loading: false,
295         tagline: getRandomFromList(taglines)?.content,
296       };
297     } else {
298       fetchTrendingCommunities();
299       fetchData();
300     }
301   }
302
303   componentDidMount() {
304     // This means it hasn't been set up yet
305     if (!this.state.siteRes.site_view.local_site.site_setup) {
306       this.context.router.history.push("/setup");
307     }
308     setupTippy();
309   }
310
311   componentWillUnmount() {
312     saveScrollPosition(this.context);
313     this.subscription?.unsubscribe();
314   }
315
316   static fetchInitialData({
317     client,
318     auth,
319     query: { dataType: urlDataType, listingType, page: urlPage, sort: urlSort },
320   }: InitialFetchRequest<QueryParams<HomeProps>>): Promise<any>[] {
321     const dataType = getDataTypeFromQuery(urlDataType);
322
323     // TODO figure out auth default_listingType, default_sort_type
324     const type_ = getListingTypeFromQuery(listingType);
325     const sort = getSortTypeFromQuery(urlSort);
326
327     const page = urlPage ? Number(urlPage) : 1;
328
329     const promises: Promise<any>[] = [];
330
331     if (dataType === DataType.Post) {
332       const getPostsForm: GetPosts = {
333         type_,
334         page,
335         limit: fetchLimit,
336         sort,
337         saved_only: false,
338         auth,
339       };
340
341       promises.push(client.getPosts(getPostsForm));
342       promises.push(Promise.resolve());
343     } else {
344       const getCommentsForm: GetComments = {
345         page,
346         limit: fetchLimit,
347         sort: postToCommentSortType(sort),
348         type_,
349         saved_only: false,
350         auth,
351       };
352       promises.push(Promise.resolve());
353       promises.push(client.getComments(getCommentsForm));
354     }
355
356     const trendingCommunitiesForm: ListCommunities = {
357       type_: "Local",
358       sort: "Hot",
359       limit: trendingFetchLimit,
360       auth,
361     };
362     promises.push(client.listCommunities(trendingCommunitiesForm));
363
364     return promises;
365   }
366
367   get documentTitle(): string {
368     const { name, description } = this.state.siteRes.site_view.site;
369
370     return description ? `${name} - ${description}` : name;
371   }
372
373   render() {
374     const {
375       tagline,
376       siteRes: {
377         site_view: {
378           local_site: { site_setup },
379         },
380       },
381     } = this.state;
382
383     return (
384       <div className="container-lg">
385         <HtmlTags
386           title={this.documentTitle}
387           path={this.context.router.route.match.url}
388         />
389         {site_setup && (
390           <div className="row">
391             <main role="main" className="col-12 col-md-8">
392               {tagline && (
393                 <div
394                   id="tagline"
395                   dangerouslySetInnerHTML={mdToHtml(tagline)}
396                 ></div>
397               )}
398               <div className="d-block d-md-none">{this.mobileView}</div>
399               {this.posts()}
400             </main>
401             <aside className="d-none d-md-block col-md-4">
402               {this.mySidebar}
403             </aside>
404           </div>
405         )}
406       </div>
407     );
408   }
409
410   get hasFollows(): boolean {
411     const mui = UserService.Instance.myUserInfo;
412     return !!mui && mui.follows.length > 0;
413   }
414
415   get mobileView() {
416     const {
417       siteRes: {
418         site_view: { counts, site },
419         admins,
420         online,
421       },
422       showSubscribedMobile,
423       showTrendingMobile,
424       showSidebarMobile,
425     } = this.state;
426
427     return (
428       <div className="row">
429         <div className="col-12">
430           {this.hasFollows && (
431             <MobileButton
432               textKey="subscribed"
433               show={showSubscribedMobile}
434               onClick={linkEvent(this, this.handleShowSubscribedMobile)}
435             />
436           )}
437           <MobileButton
438             textKey="trending"
439             show={showTrendingMobile}
440             onClick={linkEvent(this, this.handleShowTrendingMobile)}
441           />
442           <MobileButton
443             textKey="sidebar"
444             show={showSidebarMobile}
445             onClick={linkEvent(this, this.handleShowSidebarMobile)}
446           />
447           {showSidebarMobile && (
448             <SiteSidebar
449               site={site}
450               admins={admins}
451               counts={counts}
452               online={online}
453               showLocal={showLocal(this.isoData)}
454             />
455           )}
456           {showTrendingMobile && (
457             <div className="col-12 card border-secondary mb-3">
458               <div className="card-body">{this.trendingCommunities(true)}</div>
459             </div>
460           )}
461           {showSubscribedMobile && (
462             <div className="col-12 card border-secondary mb-3">
463               <div className="card-body">{this.subscribedCommunities}</div>
464             </div>
465           )}
466         </div>
467       </div>
468     );
469   }
470
471   get mySidebar() {
472     const {
473       siteRes: {
474         site_view: { counts, site },
475         admins,
476         online,
477       },
478       loading,
479     } = this.state;
480
481     return (
482       <div>
483         {!loading && (
484           <div>
485             <div className="card border-secondary mb-3">
486               <div className="card-body">
487                 {this.trendingCommunities()}
488                 {canCreateCommunity(this.state.siteRes) && (
489                   <LinkButton
490                     path="/create_community"
491                     translationKey="create_a_community"
492                   />
493                 )}
494                 <LinkButton
495                   path="/communities"
496                   translationKey="explore_communities"
497                 />
498               </div>
499             </div>
500             <SiteSidebar
501               site={site}
502               admins={admins}
503               counts={counts}
504               online={online}
505               showLocal={showLocal(this.isoData)}
506             />
507             {this.hasFollows && (
508               <div className="card border-secondary mb-3">
509                 <div className="card-body">{this.subscribedCommunities}</div>
510               </div>
511             )}
512           </div>
513         )}
514       </div>
515     );
516   }
517
518   trendingCommunities(isMobile = false) {
519     return (
520       <div className={!isMobile ? "mb-2" : ""}>
521         <h5>
522           <T i18nKey="trending_communities">
523             #
524             <Link className="text-body" to="/communities">
525               #
526             </Link>
527           </T>
528         </h5>
529         <ul className="list-inline mb-0">
530           {this.state.trendingCommunities.map(cv => (
531             <li
532               key={cv.community.id}
533               className="list-inline-item d-inline-block"
534             >
535               <CommunityLink community={cv.community} />
536             </li>
537           ))}
538         </ul>
539       </div>
540     );
541   }
542
543   get subscribedCommunities() {
544     const { subscribedCollapsed } = this.state;
545
546     return (
547       <div>
548         <h5>
549           <T class="d-inline" i18nKey="subscribed_to_communities">
550             #
551             <Link className="text-body" to="/communities">
552               #
553             </Link>
554           </T>
555           <button
556             className="btn btn-sm text-muted"
557             onClick={linkEvent(this, this.handleCollapseSubscribe)}
558             aria-label={i18n.t("collapse")}
559             data-tippy-content={i18n.t("collapse")}
560           >
561             <Icon
562               icon={`${subscribedCollapsed ? "plus" : "minus"}-square`}
563               classes="icon-inline"
564             />
565           </button>
566         </h5>
567         {!subscribedCollapsed && (
568           <ul className="list-inline mb-0">
569             {UserService.Instance.myUserInfo?.follows.map(cfv => (
570               <li
571                 key={cfv.community.id}
572                 className="list-inline-item d-inline-block"
573               >
574                 <CommunityLink community={cfv.community} />
575               </li>
576             ))}
577           </ul>
578         )}
579       </div>
580     );
581   }
582
583   updateUrl({ dataType, listingType, page, sort }: Partial<HomeProps>) {
584     const {
585       dataType: urlDataType,
586       listingType: urlListingType,
587       page: urlPage,
588       sort: urlSort,
589     } = getHomeQueryParams();
590
591     const queryParams: QueryParams<HomeProps> = {
592       dataType: getDataTypeString(dataType ?? urlDataType),
593       listingType: listingType ?? urlListingType,
594       page: (page ?? urlPage).toString(),
595       sort: sort ?? urlSort,
596     };
597
598     this.props.history.push({
599       pathname: "/",
600       search: getQueryString(queryParams),
601     });
602
603     this.setState({
604       loading: true,
605       posts: [],
606       comments: [],
607     });
608
609     fetchData();
610   }
611
612   posts() {
613     const { page } = getHomeQueryParams();
614
615     return (
616       <div className="main-content-wrapper">
617         {this.state.loading ? (
618           <h5>
619             <Spinner large />
620           </h5>
621         ) : (
622           <div>
623             {this.selects()}
624             {this.listings}
625             <Paginator page={page} onChange={this.handlePageChange} />
626           </div>
627         )}
628       </div>
629     );
630   }
631
632   get listings() {
633     const { dataType } = getHomeQueryParams();
634     const { siteRes, posts, comments } = this.state;
635
636     return dataType === DataType.Post ? (
637       <PostListings
638         posts={posts}
639         showCommunity
640         removeDuplicates
641         enableDownvotes={enableDownvotes(siteRes)}
642         enableNsfw={enableNsfw(siteRes)}
643         allLanguages={siteRes.all_languages}
644         siteLanguages={siteRes.discussion_languages}
645       />
646     ) : (
647       <CommentNodes
648         nodes={commentsToFlatNodes(comments)}
649         viewType={CommentViewType.Flat}
650         noIndent
651         showCommunity
652         showContext
653         enableDownvotes={enableDownvotes(siteRes)}
654         allLanguages={siteRes.all_languages}
655         siteLanguages={siteRes.discussion_languages}
656       />
657     );
658   }
659
660   selects() {
661     const { listingType, dataType, sort } = getHomeQueryParams();
662
663     return (
664       <div className="mb-3">
665         <span className="mr-3">
666           <DataTypeSelect
667             type_={dataType}
668             onChange={this.handleDataTypeChange}
669           />
670         </span>
671         <span className="mr-3">
672           <ListingTypeSelect
673             type_={listingType}
674             showLocal={showLocal(this.isoData)}
675             showSubscribed
676             onChange={this.handleListingTypeChange}
677           />
678         </span>
679         <span className="mr-2">
680           <SortSelect sort={sort} onChange={this.handleSortChange} />
681         </span>
682         {getRss(listingType)}
683       </div>
684     );
685   }
686
687   handleShowSubscribedMobile(i: Home) {
688     i.setState({ showSubscribedMobile: !i.state.showSubscribedMobile });
689   }
690
691   handleShowTrendingMobile(i: Home) {
692     i.setState({ showTrendingMobile: !i.state.showTrendingMobile });
693   }
694
695   handleShowSidebarMobile(i: Home) {
696     i.setState({ showSidebarMobile: !i.state.showSidebarMobile });
697   }
698
699   handleCollapseSubscribe(i: Home) {
700     i.setState({ subscribedCollapsed: !i.state.subscribedCollapsed });
701   }
702
703   handlePageChange(page: number) {
704     this.updateUrl({ page });
705     window.scrollTo(0, 0);
706   }
707
708   handleSortChange(val: SortType) {
709     this.updateUrl({ sort: val, page: 1 });
710     window.scrollTo(0, 0);
711   }
712
713   handleListingTypeChange(val: ListingType) {
714     this.updateUrl({ listingType: val, page: 1 });
715     window.scrollTo(0, 0);
716   }
717
718   handleDataTypeChange(val: DataType) {
719     this.updateUrl({ dataType: val, page: 1 });
720     window.scrollTo(0, 0);
721   }
722
723   parseMessage(msg: any) {
724     const op = wsUserOp(msg);
725     console.log(msg);
726
727     if (msg.error) {
728       toast(i18n.t(msg.error), "danger");
729     } else if (msg.reconnect) {
730       WebSocketService.Instance.send(
731         wsClient.communityJoin({ community_id: 0 })
732       );
733       fetchData();
734     } else {
735       switch (op) {
736         case UserOperation.ListCommunities: {
737           const { communities } = wsJsonToRes<ListCommunitiesResponse>(msg);
738           this.setState({ trendingCommunities: communities });
739
740           break;
741         }
742
743         case UserOperation.EditSite: {
744           const { site_view } = wsJsonToRes<SiteResponse>(msg);
745           this.setState(s => ((s.siteRes.site_view = site_view), s));
746           toast(i18n.t("site_saved"));
747
748           break;
749         }
750
751         case UserOperation.GetPosts: {
752           const { posts } = wsJsonToRes<GetPostsResponse>(msg);
753           this.setState({ posts, loading: false });
754           WebSocketService.Instance.send(
755             wsClient.communityJoin({ community_id: 0 })
756           );
757           restoreScrollPosition(this.context);
758           setupTippy();
759
760           break;
761         }
762
763         case UserOperation.CreatePost: {
764           const { page, listingType } = getHomeQueryParams();
765           const { post_view } = wsJsonToRes<PostResponse>(msg);
766
767           // Only push these if you're on the first page, you pass the nsfw check, and it isn't blocked
768           if (page === 1 && nsfwCheck(post_view) && !isPostBlocked(post_view)) {
769             const mui = UserService.Instance.myUserInfo;
770             const showPostNotifs =
771               mui?.local_user_view.local_user.show_new_post_notifs;
772             let shouldAddPost: boolean;
773
774             switch (listingType) {
775               case "Subscribed": {
776                 // If you're on subscribed, only push it if you're subscribed.
777                 shouldAddPost = !!mui?.follows.some(
778                   ({ community: { id } }) => id === post_view.community.id
779                 );
780                 break;
781               }
782               case "Local": {
783                 // If you're on the local view, only push it if its local
784                 shouldAddPost = post_view.post.local;
785                 break;
786               }
787               default: {
788                 shouldAddPost = true;
789                 break;
790               }
791             }
792
793             if (shouldAddPost) {
794               this.setState(({ posts }) => ({
795                 posts: [post_view].concat(posts),
796               }));
797               if (showPostNotifs) {
798                 notifyPost(post_view, this.context.router);
799               }
800             }
801           }
802
803           break;
804         }
805
806         case UserOperation.EditPost:
807         case UserOperation.DeletePost:
808         case UserOperation.RemovePost:
809         case UserOperation.LockPost:
810         case UserOperation.FeaturePost:
811         case UserOperation.SavePost: {
812           const { post_view } = wsJsonToRes<PostResponse>(msg);
813           editPostFindRes(post_view, this.state.posts);
814           this.setState(this.state);
815
816           break;
817         }
818
819         case UserOperation.CreatePostLike: {
820           const { post_view } = wsJsonToRes<PostResponse>(msg);
821           createPostLikeFindRes(post_view, this.state.posts);
822           this.setState(this.state);
823
824           break;
825         }
826
827         case UserOperation.AddAdmin: {
828           const { admins } = wsJsonToRes<AddAdminResponse>(msg);
829           this.setState(s => ((s.siteRes.admins = admins), s));
830
831           break;
832         }
833
834         case UserOperation.BanPerson: {
835           const {
836             banned,
837             person_view: {
838               person: { id },
839             },
840           } = wsJsonToRes<BanPersonResponse>(msg);
841
842           this.state.posts
843             .filter(p => p.creator.id == id)
844             .forEach(p => (p.creator.banned = banned));
845           this.setState(this.state);
846
847           break;
848         }
849
850         case UserOperation.GetComments: {
851           const { comments } = wsJsonToRes<GetCommentsResponse>(msg);
852           this.setState({ comments, loading: false });
853
854           break;
855         }
856
857         case UserOperation.EditComment:
858         case UserOperation.DeleteComment:
859         case UserOperation.RemoveComment: {
860           const { comment_view } = wsJsonToRes<CommentResponse>(msg);
861           editCommentRes(comment_view, this.state.comments);
862           this.setState(this.state);
863
864           break;
865         }
866
867         case UserOperation.CreateComment: {
868           const { form_id, comment_view } = wsJsonToRes<CommentResponse>(msg);
869
870           // Necessary since it might be a user reply
871           if (form_id) {
872             const { listingType } = getHomeQueryParams();
873
874             // If you're on subscribed, only push it if you're subscribed.
875             const shouldAddComment =
876               listingType === "Subscribed"
877                 ? UserService.Instance.myUserInfo?.follows.some(
878                     ({ community: { id } }) => id === comment_view.community.id
879                   )
880                 : true;
881
882             if (shouldAddComment) {
883               this.setState(({ comments }) => ({
884                 comments: [comment_view].concat(comments),
885               }));
886             }
887           }
888
889           break;
890         }
891
892         case UserOperation.SaveComment: {
893           const { comment_view } = wsJsonToRes<CommentResponse>(msg);
894           saveCommentRes(comment_view, this.state.comments);
895           this.setState(this.state);
896
897           break;
898         }
899
900         case UserOperation.CreateCommentLike: {
901           const { comment_view } = wsJsonToRes<CommentResponse>(msg);
902           createCommentLikeRes(comment_view, this.state.comments);
903           this.setState(this.state);
904
905           break;
906         }
907
908         case UserOperation.BlockPerson: {
909           const data = wsJsonToRes<BlockPersonResponse>(msg);
910           updatePersonBlock(data);
911
912           break;
913         }
914
915         case UserOperation.CreatePostReport: {
916           const data = wsJsonToRes<PostReportResponse>(msg);
917           if (data) {
918             toast(i18n.t("report_created"));
919           }
920
921           break;
922         }
923
924         case UserOperation.CreateCommentReport: {
925           const data = wsJsonToRes<CommentReportResponse>(msg);
926           if (data) {
927             toast(i18n.t("report_created"));
928           }
929
930           break;
931         }
932
933         case UserOperation.PurgePerson:
934         case UserOperation.PurgePost:
935         case UserOperation.PurgeComment:
936         case UserOperation.PurgeCommunity: {
937           const data = wsJsonToRes<PurgeItemResponse>(msg);
938           if (data.success) {
939             toast(i18n.t("purge_success"));
940             this.context.router.history.push(`/`);
941           }
942
943           break;
944         }
945       }
946     }
947   }
948 }