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