]> Untitled Git - lemmy-ui.git/blob - src/shared/components/person/profile.tsx
fix: Fix badge alignment and break out into component
[lemmy-ui.git] / src / shared / components / person / profile.tsx
1 import {
2   editComment,
3   editPost,
4   editWith,
5   enableDownvotes,
6   enableNsfw,
7   getCommentParentId,
8   myAuth,
9   myAuthRequired,
10   setIsoData,
11   updatePersonBlock,
12 } from "@utils/app";
13 import { restoreScrollPosition, saveScrollPosition } from "@utils/browser";
14 import {
15   capitalizeFirstLetter,
16   futureDaysToUnixTime,
17   getPageFromString,
18   getQueryParams,
19   getQueryString,
20   numToSI,
21 } from "@utils/helpers";
22 import { canMod, isAdmin, isBanned } from "@utils/roles";
23 import type { QueryParams } from "@utils/types";
24 import { RouteDataResponse } from "@utils/types";
25 import classNames from "classnames";
26 import format from "date-fns/format";
27 import parseISO from "date-fns/parseISO";
28 import { NoOptionI18nKeys } from "i18next";
29 import { Component, linkEvent } from "inferno";
30 import { Link } from "inferno-router";
31 import { RouteComponentProps } from "inferno-router/dist/Route";
32 import {
33   AddAdmin,
34   AddModToCommunity,
35   BanFromCommunity,
36   BanFromCommunityResponse,
37   BanPerson,
38   BanPersonResponse,
39   BlockPerson,
40   CommentId,
41   CommentReplyResponse,
42   CommentResponse,
43   Community,
44   CommunityModeratorView,
45   CreateComment,
46   CreateCommentLike,
47   CreateCommentReport,
48   CreatePostLike,
49   CreatePostReport,
50   DeleteComment,
51   DeletePost,
52   DistinguishComment,
53   EditComment,
54   EditPost,
55   FeaturePost,
56   GetPersonDetails,
57   GetPersonDetailsResponse,
58   GetSiteResponse,
59   LockPost,
60   MarkCommentReplyAsRead,
61   MarkPersonMentionAsRead,
62   PersonView,
63   PostResponse,
64   PurgeComment,
65   PurgeItemResponse,
66   PurgePerson,
67   PurgePost,
68   RemoveComment,
69   RemovePost,
70   SaveComment,
71   SavePost,
72   SortType,
73   TransferCommunity,
74 } from "lemmy-js-client";
75 import { fetchLimit, relTags } from "../../config";
76 import { InitialFetchRequest, PersonDetailsView } from "../../interfaces";
77 import { mdToHtml } from "../../markdown";
78 import { FirstLoadService, I18NextService, UserService } from "../../services";
79 import { HttpService, RequestState } from "../../services/HttpService";
80 import { setupTippy } from "../../tippy";
81 import { toast } from "../../toast";
82 import { BannerIconHeader } from "../common/banner-icon-header";
83 import { HtmlTags } from "../common/html-tags";
84 import { Icon, Spinner } from "../common/icon";
85 import { MomentTime } from "../common/moment-time";
86 import { SortSelect } from "../common/sort-select";
87 import { UserBadges } from "../common/user-badges";
88 import { CommunityLink } from "../community/community-link";
89 import { PersonDetails } from "./person-details";
90 import { PersonListing } from "./person-listing";
91
92 type ProfileData = RouteDataResponse<{
93   personResponse: GetPersonDetailsResponse;
94 }>;
95
96 interface ProfileState {
97   personRes: RequestState<GetPersonDetailsResponse>;
98   personBlocked: boolean;
99   banReason?: string;
100   banExpireDays?: number;
101   showBanDialog: boolean;
102   removeData: boolean;
103   siteRes: GetSiteResponse;
104   finished: Map<CommentId, boolean | undefined>;
105   isIsomorphic: boolean;
106 }
107
108 interface ProfileProps {
109   view: PersonDetailsView;
110   sort: SortType;
111   page: number;
112 }
113
114 function getProfileQueryParams() {
115   return getQueryParams<ProfileProps>({
116     view: getViewFromProps,
117     page: getPageFromString,
118     sort: getSortTypeFromQuery,
119   });
120 }
121
122 function getSortTypeFromQuery(sort?: string): SortType {
123   return sort ? (sort as SortType) : "New";
124 }
125
126 function getViewFromProps(view?: string): PersonDetailsView {
127   return view
128     ? PersonDetailsView[view] ?? PersonDetailsView.Overview
129     : PersonDetailsView.Overview;
130 }
131
132 const getCommunitiesListing = (
133   translationKey: NoOptionI18nKeys,
134   communityViews?: { community: Community }[]
135 ) =>
136   communityViews &&
137   communityViews.length > 0 && (
138     <div className="card border-secondary mb-3">
139       <div className="card-body">
140         <h5>{I18NextService.i18n.t(translationKey)}</h5>
141         <ul className="list-unstyled mb-0">
142           {communityViews.map(({ community }) => (
143             <li key={community.id}>
144               <CommunityLink community={community} />
145             </li>
146           ))}
147         </ul>
148       </div>
149     </div>
150   );
151
152 const Moderates = ({ moderates }: { moderates?: CommunityModeratorView[] }) =>
153   getCommunitiesListing("moderates", moderates);
154
155 const Follows = () =>
156   getCommunitiesListing("subscribed", UserService.Instance.myUserInfo?.follows);
157
158 export class Profile extends Component<
159   RouteComponentProps<{ username: string }>,
160   ProfileState
161 > {
162   private isoData = setIsoData<ProfileData>(this.context);
163   state: ProfileState = {
164     personRes: { state: "empty" },
165     personBlocked: false,
166     siteRes: this.isoData.site_res,
167     showBanDialog: false,
168     removeData: false,
169     finished: new Map(),
170     isIsomorphic: false,
171   };
172
173   constructor(props: RouteComponentProps<{ username: string }>, context: any) {
174     super(props, context);
175
176     this.handleSortChange = this.handleSortChange.bind(this);
177     this.handlePageChange = this.handlePageChange.bind(this);
178
179     this.handleBlockPerson = this.handleBlockPerson.bind(this);
180     this.handleUnblockPerson = this.handleUnblockPerson.bind(this);
181
182     this.handleCreateComment = this.handleCreateComment.bind(this);
183     this.handleEditComment = this.handleEditComment.bind(this);
184     this.handleSaveComment = this.handleSaveComment.bind(this);
185     this.handleBlockPersonAlt = this.handleBlockPersonAlt.bind(this);
186     this.handleDeleteComment = this.handleDeleteComment.bind(this);
187     this.handleRemoveComment = this.handleRemoveComment.bind(this);
188     this.handleCommentVote = this.handleCommentVote.bind(this);
189     this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
190     this.handleAddAdmin = this.handleAddAdmin.bind(this);
191     this.handlePurgePerson = this.handlePurgePerson.bind(this);
192     this.handlePurgeComment = this.handlePurgeComment.bind(this);
193     this.handleCommentReport = this.handleCommentReport.bind(this);
194     this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
195     this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
196     this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
197     this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
198     this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
199     this.handleBanPerson = this.handleBanPerson.bind(this);
200     this.handlePostVote = this.handlePostVote.bind(this);
201     this.handlePostEdit = this.handlePostEdit.bind(this);
202     this.handlePostReport = this.handlePostReport.bind(this);
203     this.handleLockPost = this.handleLockPost.bind(this);
204     this.handleDeletePost = this.handleDeletePost.bind(this);
205     this.handleRemovePost = this.handleRemovePost.bind(this);
206     this.handleSavePost = this.handleSavePost.bind(this);
207     this.handlePurgePost = this.handlePurgePost.bind(this);
208     this.handleFeaturePost = this.handleFeaturePost.bind(this);
209     this.handleModBanSubmit = this.handleModBanSubmit.bind(this);
210
211     // Only fetch the data if coming from another route
212     if (FirstLoadService.isFirstLoad) {
213       this.state = {
214         ...this.state,
215         personRes: this.isoData.routeData.personResponse,
216         isIsomorphic: true,
217       };
218     }
219   }
220
221   async componentDidMount() {
222     if (!this.state.isIsomorphic) {
223       await this.fetchUserData();
224     }
225     setupTippy();
226   }
227
228   componentWillUnmount() {
229     saveScrollPosition(this.context);
230   }
231
232   async fetchUserData() {
233     const { page, sort, view } = getProfileQueryParams();
234
235     this.setState({ personRes: { state: "empty" } });
236     this.setState({
237       personRes: await HttpService.client.getPersonDetails({
238         username: this.props.match.params.username,
239         sort,
240         saved_only: view === PersonDetailsView.Saved,
241         page,
242         limit: fetchLimit,
243         auth: myAuth(),
244       }),
245     });
246     restoreScrollPosition(this.context);
247     this.setPersonBlock();
248   }
249
250   get amCurrentUser() {
251     if (this.state.personRes.state === "success") {
252       return (
253         UserService.Instance.myUserInfo?.local_user_view.person.id ===
254         this.state.personRes.data.person_view.person.id
255       );
256     } else {
257       return false;
258     }
259   }
260
261   setPersonBlock() {
262     const mui = UserService.Instance.myUserInfo;
263     const res = this.state.personRes;
264
265     if (mui && res.state === "success") {
266       this.setState({
267         personBlocked: mui.person_blocks.some(
268           ({ target: { id } }) => id === res.data.person_view.person.id
269         ),
270       });
271     }
272   }
273
274   static async fetchInitialData({
275     client,
276     path,
277     query: { page, sort, view: urlView },
278     auth,
279   }: InitialFetchRequest<QueryParams<ProfileProps>>): Promise<ProfileData> {
280     const pathSplit = path.split("/");
281
282     const username = pathSplit[2];
283     const view = getViewFromProps(urlView);
284
285     const form: GetPersonDetails = {
286       username: username,
287       sort: getSortTypeFromQuery(sort),
288       saved_only: view === PersonDetailsView.Saved,
289       page: getPageFromString(page),
290       limit: fetchLimit,
291       auth,
292     };
293
294     return {
295       personResponse: await client.getPersonDetails(form),
296     };
297   }
298
299   get documentTitle(): string {
300     const siteName = this.state.siteRes.site_view.site.name;
301     const res = this.state.personRes;
302     return res.state == "success"
303       ? `@${res.data.person_view.person.name} - ${siteName}`
304       : siteName;
305   }
306
307   renderPersonRes() {
308     switch (this.state.personRes.state) {
309       case "loading":
310         return (
311           <h5>
312             <Spinner large />
313           </h5>
314         );
315       case "success": {
316         const siteRes = this.state.siteRes;
317         const personRes = this.state.personRes.data;
318         const { page, sort, view } = getProfileQueryParams();
319
320         return (
321           <div className="row">
322             <div className="col-12 col-md-8">
323               <HtmlTags
324                 title={this.documentTitle}
325                 path={this.context.router.route.match.url}
326                 description={personRes.person_view.person.bio}
327                 image={personRes.person_view.person.avatar}
328               />
329
330               {this.userInfo(personRes.person_view)}
331
332               <hr />
333
334               {this.selects}
335
336               <PersonDetails
337                 personRes={personRes}
338                 admins={siteRes.admins}
339                 sort={sort}
340                 page={page}
341                 limit={fetchLimit}
342                 finished={this.state.finished}
343                 enableDownvotes={enableDownvotes(siteRes)}
344                 enableNsfw={enableNsfw(siteRes)}
345                 view={view}
346                 onPageChange={this.handlePageChange}
347                 allLanguages={siteRes.all_languages}
348                 siteLanguages={siteRes.discussion_languages}
349                 // TODO all the forms here
350                 onSaveComment={this.handleSaveComment}
351                 onBlockPerson={this.handleBlockPersonAlt}
352                 onDeleteComment={this.handleDeleteComment}
353                 onRemoveComment={this.handleRemoveComment}
354                 onCommentVote={this.handleCommentVote}
355                 onCommentReport={this.handleCommentReport}
356                 onDistinguishComment={this.handleDistinguishComment}
357                 onAddModToCommunity={this.handleAddModToCommunity}
358                 onAddAdmin={this.handleAddAdmin}
359                 onTransferCommunity={this.handleTransferCommunity}
360                 onPurgeComment={this.handlePurgeComment}
361                 onPurgePerson={this.handlePurgePerson}
362                 onCommentReplyRead={this.handleCommentReplyRead}
363                 onPersonMentionRead={this.handlePersonMentionRead}
364                 onBanPersonFromCommunity={this.handleBanFromCommunity}
365                 onBanPerson={this.handleBanPerson}
366                 onCreateComment={this.handleCreateComment}
367                 onEditComment={this.handleEditComment}
368                 onPostEdit={this.handlePostEdit}
369                 onPostVote={this.handlePostVote}
370                 onPostReport={this.handlePostReport}
371                 onLockPost={this.handleLockPost}
372                 onDeletePost={this.handleDeletePost}
373                 onRemovePost={this.handleRemovePost}
374                 onSavePost={this.handleSavePost}
375                 onPurgePost={this.handlePurgePost}
376                 onFeaturePost={this.handleFeaturePost}
377               />
378             </div>
379
380             <div className="col-12 col-md-4">
381               <Moderates moderates={personRes.moderates} />
382               {this.amCurrentUser && <Follows />}
383             </div>
384           </div>
385         );
386       }
387     }
388   }
389
390   render() {
391     return (
392       <div className="person-profile container-lg">
393         {this.renderPersonRes()}
394       </div>
395     );
396   }
397
398   get viewRadios() {
399     return (
400       <div className="btn-group btn-group-toggle flex-wrap mb-2">
401         {this.getRadio(PersonDetailsView.Overview)}
402         {this.getRadio(PersonDetailsView.Comments)}
403         {this.getRadio(PersonDetailsView.Posts)}
404         {this.amCurrentUser && this.getRadio(PersonDetailsView.Saved)}
405       </div>
406     );
407   }
408
409   getRadio(view: PersonDetailsView) {
410     const { view: urlView } = getProfileQueryParams();
411     const active = view === urlView;
412
413     return (
414       <label
415         className={classNames("btn btn-outline-secondary pointer", {
416           active,
417         })}
418       >
419         <input
420           type="radio"
421           className="btn-check"
422           value={view}
423           checked={active}
424           onChange={linkEvent(this, this.handleViewChange)}
425         />
426         {I18NextService.i18n.t(view.toLowerCase() as NoOptionI18nKeys)}
427       </label>
428     );
429   }
430
431   get selects() {
432     const { sort } = getProfileQueryParams();
433     const { username } = this.props.match.params;
434
435     const profileRss = `/feeds/u/${username}.xml?sort=${sort}`;
436
437     return (
438       <div className="mb-2">
439         <span className="me-3">{this.viewRadios}</span>
440         <SortSelect
441           sort={sort}
442           onChange={this.handleSortChange}
443           hideHot
444           hideMostComments
445         />
446         <a href={profileRss} rel={relTags} title="RSS">
447           <Icon icon="rss" classes="text-muted small mx-2" />
448         </a>
449         <link rel="alternate" type="application/atom+xml" href={profileRss} />
450       </div>
451     );
452   }
453
454   userInfo(pv: PersonView) {
455     const {
456       personBlocked,
457       siteRes: { admins },
458       showBanDialog,
459     } = this.state;
460
461     return (
462       pv && (
463         <div>
464           {!isBanned(pv.person) && (
465             <BannerIconHeader
466               banner={pv.person.banner}
467               icon={pv.person.avatar}
468             />
469           )}
470           <div className="mb-3">
471             <div className="">
472               <div className="mb-0 d-flex flex-wrap">
473                 <div>
474                   {pv.person.display_name && (
475                     <h5 className="mb-0">{pv.person.display_name}</h5>
476                   )}
477                   <ul className="list-inline mb-2">
478                     <li className="list-inline-item">
479                       <PersonListing
480                         person={pv.person}
481                         realLink
482                         useApubName
483                         muted
484                         hideAvatar
485                       />
486                     </li>
487                     <li className="list-inline-item">
488                       <UserBadges
489                         classNames="ms-1"
490                         isBanned={isBanned(pv.person)}
491                         isDeleted={pv.person.deleted}
492                         isAdmin={pv.person.admin}
493                         isBot={pv.person.bot_account}
494                       />
495                     </li>
496                   </ul>
497                 </div>
498                 {this.banDialog(pv)}
499                 <div className="flex-grow-1 unselectable pointer mx-2"></div>
500                 {!this.amCurrentUser && UserService.Instance.myUserInfo && (
501                   <>
502                     <a
503                       className={`d-flex align-self-start btn btn-secondary me-2 ${
504                         !pv.person.matrix_user_id && "invisible"
505                       }`}
506                       rel={relTags}
507                       href={`https://matrix.to/#/${pv.person.matrix_user_id}`}
508                     >
509                       {I18NextService.i18n.t("send_secure_message")}
510                     </a>
511                     <Link
512                       className={
513                         "d-flex align-self-start btn btn-secondary me-2"
514                       }
515                       to={`/create_private_message/${pv.person.id}`}
516                     >
517                       {I18NextService.i18n.t("send_message")}
518                     </Link>
519                     {personBlocked ? (
520                       <button
521                         className={
522                           "d-flex align-self-start btn btn-secondary me-2"
523                         }
524                         onClick={linkEvent(
525                           pv.person.id,
526                           this.handleUnblockPerson
527                         )}
528                       >
529                         {I18NextService.i18n.t("unblock_user")}
530                       </button>
531                     ) : (
532                       <button
533                         className={
534                           "d-flex align-self-start btn btn-secondary me-2"
535                         }
536                         onClick={linkEvent(
537                           pv.person.id,
538                           this.handleBlockPerson
539                         )}
540                       >
541                         {I18NextService.i18n.t("block_user")}
542                       </button>
543                     )}
544                   </>
545                 )}
546
547                 {canMod(pv.person.id, undefined, admins) &&
548                   !isAdmin(pv.person.id, admins) &&
549                   !showBanDialog &&
550                   (!isBanned(pv.person) ? (
551                     <button
552                       className={
553                         "d-flex align-self-start btn btn-secondary me-2"
554                       }
555                       onClick={linkEvent(this, this.handleModBanShow)}
556                       aria-label={I18NextService.i18n.t("ban")}
557                     >
558                       {capitalizeFirstLetter(I18NextService.i18n.t("ban"))}
559                     </button>
560                   ) : (
561                     <button
562                       className={
563                         "d-flex align-self-start btn btn-secondary me-2"
564                       }
565                       onClick={linkEvent(this, this.handleModBanSubmit)}
566                       aria-label={I18NextService.i18n.t("unban")}
567                     >
568                       {capitalizeFirstLetter(I18NextService.i18n.t("unban"))}
569                     </button>
570                   ))}
571               </div>
572               {pv.person.bio && (
573                 <div className="d-flex align-items-center mb-2">
574                   <div
575                     className="md-div"
576                     dangerouslySetInnerHTML={mdToHtml(pv.person.bio)}
577                   />
578                 </div>
579               )}
580               <div>
581                 <ul className="list-inline mb-2">
582                   <li className="list-inline-item badge text-bg-light">
583                     {I18NextService.i18n.t("number_of_posts", {
584                       count: Number(pv.counts.post_count),
585                       formattedCount: numToSI(pv.counts.post_count),
586                     })}
587                   </li>
588                   <li className="list-inline-item badge text-bg-light">
589                     {I18NextService.i18n.t("number_of_comments", {
590                       count: Number(pv.counts.comment_count),
591                       formattedCount: numToSI(pv.counts.comment_count),
592                     })}
593                   </li>
594                 </ul>
595               </div>
596               <div className="text-muted">
597                 {I18NextService.i18n.t("joined")}{" "}
598                 <MomentTime
599                   published={pv.person.published}
600                   showAgo
601                   ignoreUpdated
602                 />
603               </div>
604               <div className="d-flex align-items-center text-muted mb-2">
605                 <Icon icon="cake" />
606                 <span className="ms-2">
607                   {I18NextService.i18n.t("cake_day_title")}{" "}
608                   {format(parseISO(pv.person.published), "PPP")}
609                 </span>
610               </div>
611               {!UserService.Instance.myUserInfo && (
612                 <div className="alert alert-info" role="alert">
613                   {I18NextService.i18n.t("profile_not_logged_in_alert")}
614                 </div>
615               )}
616             </div>
617           </div>
618         </div>
619       )
620     );
621   }
622
623   banDialog(pv: PersonView) {
624     const { showBanDialog } = this.state;
625
626     return (
627       showBanDialog && (
628         <form onSubmit={linkEvent(this, this.handleModBanSubmit)}>
629           <div className="mb-3 row col-12">
630             <label className="col-form-label" htmlFor="profile-ban-reason">
631               {I18NextService.i18n.t("reason")}
632             </label>
633             <input
634               type="text"
635               id="profile-ban-reason"
636               className="form-control me-2"
637               placeholder={I18NextService.i18n.t("reason")}
638               value={this.state.banReason}
639               onInput={linkEvent(this, this.handleModBanReasonChange)}
640             />
641             <label className="col-form-label" htmlFor="mod-ban-expires">
642               {I18NextService.i18n.t("expires")}
643             </label>
644             <input
645               type="number"
646               id="mod-ban-expires"
647               className="form-control me-2"
648               placeholder={I18NextService.i18n.t("number_of_days")}
649               value={this.state.banExpireDays}
650               onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
651             />
652             <div className="input-group mb-3">
653               <div className="form-check">
654                 <input
655                   className="form-check-input"
656                   id="mod-ban-remove-data"
657                   type="checkbox"
658                   checked={this.state.removeData}
659                   onChange={linkEvent(this, this.handleModRemoveDataChange)}
660                 />
661                 <label
662                   className="form-check-label"
663                   htmlFor="mod-ban-remove-data"
664                   title={I18NextService.i18n.t("remove_content_more")}
665                 >
666                   {I18NextService.i18n.t("remove_content")}
667                 </label>
668               </div>
669             </div>
670           </div>
671           {/* TODO hold off on expires until later */}
672           {/* <div class="mb-3 row"> */}
673           {/*   <label class="col-form-label">Expires</label> */}
674           {/*   <input type="date" class="form-control me-2" placeholder={I18NextService.i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
675           {/* </div> */}
676           <div className="mb-3 row">
677             <button
678               type="reset"
679               className="btn btn-secondary me-2"
680               aria-label={I18NextService.i18n.t("cancel")}
681               onClick={linkEvent(this, this.handleModBanSubmitCancel)}
682             >
683               {I18NextService.i18n.t("cancel")}
684             </button>
685           </div>
686           <div className="mb-3 row">
687             <button
688               type="submit"
689               className="btn btn-secondary"
690               aria-label={I18NextService.i18n.t("ban")}
691             >
692               {I18NextService.i18n.t("ban")} {pv.person.name}
693             </button>
694           </div>
695         </form>
696       )
697     );
698   }
699
700   async updateUrl({ page, sort, view }: Partial<ProfileProps>) {
701     const {
702       page: urlPage,
703       sort: urlSort,
704       view: urlView,
705     } = getProfileQueryParams();
706
707     const queryParams: QueryParams<ProfileProps> = {
708       page: (page ?? urlPage).toString(),
709       sort: sort ?? urlSort,
710       view: view ?? urlView,
711     };
712
713     const { username } = this.props.match.params;
714
715     this.props.history.push(`/u/${username}${getQueryString(queryParams)}`);
716     await this.fetchUserData();
717   }
718
719   handlePageChange(page: number) {
720     this.updateUrl({ page });
721   }
722
723   handleSortChange(sort: SortType) {
724     this.updateUrl({ sort, page: 1 });
725   }
726
727   handleViewChange(i: Profile, event: any) {
728     i.updateUrl({
729       view: PersonDetailsView[event.target.value],
730       page: 1,
731     });
732   }
733
734   handleModBanShow(i: Profile) {
735     i.setState({ showBanDialog: true });
736   }
737
738   handleModBanReasonChange(i: Profile, event: any) {
739     i.setState({ banReason: event.target.value });
740   }
741
742   handleModBanExpireDaysChange(i: Profile, event: any) {
743     i.setState({ banExpireDays: event.target.value });
744   }
745
746   handleModRemoveDataChange(i: Profile, event: any) {
747     i.setState({ removeData: event.target.checked });
748   }
749
750   handleModBanSubmitCancel(i: Profile) {
751     i.setState({ showBanDialog: false });
752   }
753
754   async handleModBanSubmit(i: Profile, event: any) {
755     event.preventDefault();
756     const { removeData, banReason, banExpireDays } = i.state;
757
758     const personRes = i.state.personRes;
759
760     if (personRes.state == "success") {
761       const person = personRes.data.person_view.person;
762       const ban = !person.banned;
763
764       // If its an unban, restore all their data
765       if (!ban) {
766         i.setState({ removeData: false });
767       }
768
769       const res = await HttpService.client.banPerson({
770         person_id: person.id,
771         ban,
772         remove_data: removeData,
773         reason: banReason,
774         expires: futureDaysToUnixTime(banExpireDays),
775         auth: myAuthRequired(),
776       });
777       // TODO
778       this.updateBan(res);
779       i.setState({ showBanDialog: false });
780     }
781   }
782
783   async toggleBlockPerson(recipientId: number, block: boolean) {
784     const res = await HttpService.client.blockPerson({
785       person_id: recipientId,
786       block,
787       auth: myAuthRequired(),
788     });
789     if (res.state == "success") {
790       updatePersonBlock(res.data);
791     }
792   }
793
794   handleUnblockPerson(personId: number) {
795     this.toggleBlockPerson(personId, false);
796   }
797
798   handleBlockPerson(personId: number) {
799     this.toggleBlockPerson(personId, true);
800   }
801
802   async handleAddModToCommunity(form: AddModToCommunity) {
803     // TODO not sure what to do here
804     await HttpService.client.addModToCommunity(form);
805   }
806
807   async handlePurgePerson(form: PurgePerson) {
808     const purgePersonRes = await HttpService.client.purgePerson(form);
809     this.purgeItem(purgePersonRes);
810   }
811
812   async handlePurgeComment(form: PurgeComment) {
813     const purgeCommentRes = await HttpService.client.purgeComment(form);
814     this.purgeItem(purgeCommentRes);
815   }
816
817   async handlePurgePost(form: PurgePost) {
818     const purgeRes = await HttpService.client.purgePost(form);
819     this.purgeItem(purgeRes);
820   }
821
822   async handleBlockPersonAlt(form: BlockPerson) {
823     const blockPersonRes = await HttpService.client.blockPerson(form);
824     if (blockPersonRes.state === "success") {
825       updatePersonBlock(blockPersonRes.data);
826     }
827   }
828
829   async handleCreateComment(form: CreateComment) {
830     const createCommentRes = await HttpService.client.createComment(form);
831     this.createAndUpdateComments(createCommentRes);
832
833     return createCommentRes;
834   }
835
836   async handleEditComment(form: EditComment) {
837     const editCommentRes = await HttpService.client.editComment(form);
838     this.findAndUpdateComment(editCommentRes);
839
840     return editCommentRes;
841   }
842
843   async handleDeleteComment(form: DeleteComment) {
844     const deleteCommentRes = await HttpService.client.deleteComment(form);
845     this.findAndUpdateComment(deleteCommentRes);
846   }
847
848   async handleDeletePost(form: DeletePost) {
849     const deleteRes = await HttpService.client.deletePost(form);
850     this.findAndUpdatePost(deleteRes);
851   }
852
853   async handleRemovePost(form: RemovePost) {
854     const removeRes = await HttpService.client.removePost(form);
855     this.findAndUpdatePost(removeRes);
856   }
857
858   async handleRemoveComment(form: RemoveComment) {
859     const removeCommentRes = await HttpService.client.removeComment(form);
860     this.findAndUpdateComment(removeCommentRes);
861   }
862
863   async handleSaveComment(form: SaveComment) {
864     const saveCommentRes = await HttpService.client.saveComment(form);
865     this.findAndUpdateComment(saveCommentRes);
866   }
867
868   async handleSavePost(form: SavePost) {
869     const saveRes = await HttpService.client.savePost(form);
870     this.findAndUpdatePost(saveRes);
871   }
872
873   async handleFeaturePost(form: FeaturePost) {
874     const featureRes = await HttpService.client.featurePost(form);
875     this.findAndUpdatePost(featureRes);
876   }
877
878   async handleCommentVote(form: CreateCommentLike) {
879     const voteRes = await HttpService.client.likeComment(form);
880     this.findAndUpdateComment(voteRes);
881   }
882
883   async handlePostVote(form: CreatePostLike) {
884     const voteRes = await HttpService.client.likePost(form);
885     this.findAndUpdatePost(voteRes);
886   }
887
888   async handlePostEdit(form: EditPost) {
889     const res = await HttpService.client.editPost(form);
890     this.findAndUpdatePost(res);
891   }
892
893   async handleCommentReport(form: CreateCommentReport) {
894     const reportRes = await HttpService.client.createCommentReport(form);
895     if (reportRes.state === "success") {
896       toast(I18NextService.i18n.t("report_created"));
897     }
898   }
899
900   async handlePostReport(form: CreatePostReport) {
901     const reportRes = await HttpService.client.createPostReport(form);
902     if (reportRes.state === "success") {
903       toast(I18NextService.i18n.t("report_created"));
904     }
905   }
906
907   async handleLockPost(form: LockPost) {
908     const lockRes = await HttpService.client.lockPost(form);
909     this.findAndUpdatePost(lockRes);
910   }
911
912   async handleDistinguishComment(form: DistinguishComment) {
913     const distinguishRes = await HttpService.client.distinguishComment(form);
914     this.findAndUpdateComment(distinguishRes);
915   }
916
917   async handleAddAdmin(form: AddAdmin) {
918     const addAdminRes = await HttpService.client.addAdmin(form);
919
920     if (addAdminRes.state == "success") {
921       this.setState(s => ((s.siteRes.admins = addAdminRes.data.admins), s));
922     }
923   }
924
925   async handleTransferCommunity(form: TransferCommunity) {
926     await HttpService.client.transferCommunity(form);
927     toast(I18NextService.i18n.t("transfer_community"));
928   }
929
930   async handleCommentReplyRead(form: MarkCommentReplyAsRead) {
931     const readRes = await HttpService.client.markCommentReplyAsRead(form);
932     this.findAndUpdateCommentReply(readRes);
933   }
934
935   async handlePersonMentionRead(form: MarkPersonMentionAsRead) {
936     // TODO not sure what to do here. Maybe it is actually optional, because post doesn't need it.
937     await HttpService.client.markPersonMentionAsRead(form);
938   }
939
940   async handleBanFromCommunity(form: BanFromCommunity) {
941     const banRes = await HttpService.client.banFromCommunity(form);
942     this.updateBanFromCommunity(banRes);
943   }
944
945   async handleBanPerson(form: BanPerson) {
946     const banRes = await HttpService.client.banPerson(form);
947     this.updateBan(banRes);
948   }
949
950   updateBanFromCommunity(banRes: RequestState<BanFromCommunityResponse>) {
951     // Maybe not necessary
952     if (banRes.state === "success") {
953       this.setState(s => {
954         if (s.personRes.state == "success") {
955           s.personRes.data.posts
956             .filter(c => c.creator.id === banRes.data.person_view.person.id)
957             .forEach(
958               c => (c.creator_banned_from_community = banRes.data.banned)
959             );
960
961           s.personRes.data.comments
962             .filter(c => c.creator.id === banRes.data.person_view.person.id)
963             .forEach(
964               c => (c.creator_banned_from_community = banRes.data.banned)
965             );
966         }
967         return s;
968       });
969     }
970   }
971
972   updateBan(banRes: RequestState<BanPersonResponse>) {
973     // Maybe not necessary
974     if (banRes.state == "success") {
975       this.setState(s => {
976         if (s.personRes.state == "success") {
977           s.personRes.data.posts
978             .filter(c => c.creator.id == banRes.data.person_view.person.id)
979             .forEach(c => (c.creator.banned = banRes.data.banned));
980           s.personRes.data.comments
981             .filter(c => c.creator.id == banRes.data.person_view.person.id)
982             .forEach(c => (c.creator.banned = banRes.data.banned));
983           s.personRes.data.person_view.person.banned = banRes.data.banned;
984         }
985         return s;
986       });
987     }
988   }
989
990   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
991     if (purgeRes.state == "success") {
992       toast(I18NextService.i18n.t("purge_success"));
993       this.context.router.history.push(`/`);
994     }
995   }
996
997   findAndUpdateComment(res: RequestState<CommentResponse>) {
998     this.setState(s => {
999       if (s.personRes.state == "success" && res.state == "success") {
1000         s.personRes.data.comments = editComment(
1001           res.data.comment_view,
1002           s.personRes.data.comments
1003         );
1004         s.finished.set(res.data.comment_view.comment.id, true);
1005       }
1006       return s;
1007     });
1008   }
1009
1010   createAndUpdateComments(res: RequestState<CommentResponse>) {
1011     this.setState(s => {
1012       if (s.personRes.state == "success" && res.state == "success") {
1013         s.personRes.data.comments.unshift(res.data.comment_view);
1014         // Set finished for the parent
1015         s.finished.set(
1016           getCommentParentId(res.data.comment_view.comment) ?? 0,
1017           true
1018         );
1019       }
1020       return s;
1021     });
1022   }
1023
1024   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1025     this.setState(s => {
1026       if (s.personRes.state == "success" && res.state == "success") {
1027         s.personRes.data.comments = editWith(
1028           res.data.comment_reply_view,
1029           s.personRes.data.comments
1030         );
1031       }
1032       return s;
1033     });
1034   }
1035
1036   findAndUpdatePost(res: RequestState<PostResponse>) {
1037     this.setState(s => {
1038       if (s.personRes.state == "success" && res.state == "success") {
1039         s.personRes.data.posts = editPost(
1040           res.data.post_view,
1041           s.personRes.data.posts
1042         );
1043       }
1044       return s;
1045     });
1046   }
1047 }