]> Untitled Git - lemmy-ui.git/blob - src/shared/components/person/profile.tsx
Use canonical URLs (#1883)
[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   randomStr,
22 } from "@utils/helpers";
23 import { canMod, isAdmin, isBanned } from "@utils/roles";
24 import type { QueryParams } from "@utils/types";
25 import { RouteDataResponse } from "@utils/types";
26 import classNames from "classnames";
27 import format from "date-fns/format";
28 import parseISO from "date-fns/parseISO";
29 import { NoOptionI18nKeys } from "i18next";
30 import { Component, linkEvent } from "inferno";
31 import { Link } from "inferno-router";
32 import { RouteComponentProps } from "inferno-router/dist/Route";
33 import {
34   AddAdmin,
35   AddModToCommunity,
36   BanFromCommunity,
37   BanFromCommunityResponse,
38   BanPerson,
39   BanPersonResponse,
40   BlockPerson,
41   CommentId,
42   CommentReplyResponse,
43   CommentResponse,
44   Community,
45   CommunityModeratorView,
46   CreateComment,
47   CreateCommentLike,
48   CreateCommentReport,
49   CreatePostLike,
50   CreatePostReport,
51   DeleteComment,
52   DeletePost,
53   DistinguishComment,
54   EditComment,
55   EditPost,
56   FeaturePost,
57   GetPersonDetails,
58   GetPersonDetailsResponse,
59   GetSiteResponse,
60   LockPost,
61   MarkCommentReplyAsRead,
62   MarkPersonMentionAsRead,
63   PersonView,
64   PostResponse,
65   PurgeComment,
66   PurgeItemResponse,
67   PurgePerson,
68   PurgePost,
69   RemoveComment,
70   RemovePost,
71   SaveComment,
72   SavePost,
73   SortType,
74   TransferCommunity,
75 } from "lemmy-js-client";
76 import { fetchLimit, relTags } from "../../config";
77 import { InitialFetchRequest, PersonDetailsView } from "../../interfaces";
78 import { mdToHtml } from "../../markdown";
79 import { FirstLoadService, I18NextService, UserService } from "../../services";
80 import { HttpService, RequestState } from "../../services/HttpService";
81 import { setupTippy } from "../../tippy";
82 import { toast } from "../../toast";
83 import { BannerIconHeader } from "../common/banner-icon-header";
84 import { HtmlTags } from "../common/html-tags";
85 import { Icon, Spinner } from "../common/icon";
86 import { MomentTime } from "../common/moment-time";
87 import { SortSelect } from "../common/sort-select";
88 import { UserBadges } from "../common/user-badges";
89 import { CommunityLink } from "../community/community-link";
90 import { PersonDetails } from "./person-details";
91 import { PersonListing } from "./person-listing";
92
93 type ProfileData = RouteDataResponse<{
94   personResponse: GetPersonDetailsResponse;
95 }>;
96
97 interface ProfileState {
98   personRes: RequestState<GetPersonDetailsResponse>;
99   personBlocked: boolean;
100   banReason?: string;
101   banExpireDays?: number;
102   showBanDialog: boolean;
103   removeData: boolean;
104   siteRes: GetSiteResponse;
105   finished: Map<CommentId, boolean | undefined>;
106   isIsomorphic: boolean;
107 }
108
109 interface ProfileProps {
110   view: PersonDetailsView;
111   sort: SortType;
112   page: number;
113 }
114
115 function getProfileQueryParams() {
116   return getQueryParams<ProfileProps>({
117     view: getViewFromProps,
118     page: getPageFromString,
119     sort: getSortTypeFromQuery,
120   });
121 }
122
123 function getSortTypeFromQuery(sort?: string): SortType {
124   return sort ? (sort as SortType) : "New";
125 }
126
127 function getViewFromProps(view?: string): PersonDetailsView {
128   return view
129     ? PersonDetailsView[view] ?? PersonDetailsView.Overview
130     : PersonDetailsView.Overview;
131 }
132
133 const getCommunitiesListing = (
134   translationKey: NoOptionI18nKeys,
135   communityViews?: { community: Community }[]
136 ) =>
137   communityViews &&
138   communityViews.length > 0 && (
139     <div className="card border-secondary mb-3">
140       <div className="card-body">
141         <h2 className="h5">{I18NextService.i18n.t(translationKey)}</h2>
142         <ul className="list-unstyled mb-0">
143           {communityViews.map(({ community }) => (
144             <li key={community.id}>
145               <CommunityLink community={community} />
146             </li>
147           ))}
148         </ul>
149       </div>
150     </div>
151   );
152
153 const Moderates = ({ moderates }: { moderates?: CommunityModeratorView[] }) =>
154   getCommunitiesListing("moderates", moderates);
155
156 const Follows = () =>
157   getCommunitiesListing("subscribed", UserService.Instance.myUserInfo?.follows);
158
159 export class Profile extends Component<
160   RouteComponentProps<{ username: string }>,
161   ProfileState
162 > {
163   private isoData = setIsoData<ProfileData>(this.context);
164   state: ProfileState = {
165     personRes: { state: "empty" },
166     personBlocked: false,
167     siteRes: this.isoData.site_res,
168     showBanDialog: false,
169     removeData: false,
170     finished: new Map(),
171     isIsomorphic: false,
172   };
173
174   constructor(props: RouteComponentProps<{ username: string }>, context: any) {
175     super(props, context);
176
177     this.handleSortChange = this.handleSortChange.bind(this);
178     this.handlePageChange = this.handlePageChange.bind(this);
179
180     this.handleBlockPerson = this.handleBlockPerson.bind(this);
181     this.handleUnblockPerson = this.handleUnblockPerson.bind(this);
182
183     this.handleCreateComment = this.handleCreateComment.bind(this);
184     this.handleEditComment = this.handleEditComment.bind(this);
185     this.handleSaveComment = this.handleSaveComment.bind(this);
186     this.handleBlockPersonAlt = this.handleBlockPersonAlt.bind(this);
187     this.handleDeleteComment = this.handleDeleteComment.bind(this);
188     this.handleRemoveComment = this.handleRemoveComment.bind(this);
189     this.handleCommentVote = this.handleCommentVote.bind(this);
190     this.handleAddModToCommunity = this.handleAddModToCommunity.bind(this);
191     this.handleAddAdmin = this.handleAddAdmin.bind(this);
192     this.handlePurgePerson = this.handlePurgePerson.bind(this);
193     this.handlePurgeComment = this.handlePurgeComment.bind(this);
194     this.handleCommentReport = this.handleCommentReport.bind(this);
195     this.handleDistinguishComment = this.handleDistinguishComment.bind(this);
196     this.handleTransferCommunity = this.handleTransferCommunity.bind(this);
197     this.handleCommentReplyRead = this.handleCommentReplyRead.bind(this);
198     this.handlePersonMentionRead = this.handlePersonMentionRead.bind(this);
199     this.handleBanFromCommunity = this.handleBanFromCommunity.bind(this);
200     this.handleBanPerson = this.handleBanPerson.bind(this);
201     this.handlePostVote = this.handlePostVote.bind(this);
202     this.handlePostEdit = this.handlePostEdit.bind(this);
203     this.handlePostReport = this.handlePostReport.bind(this);
204     this.handleLockPost = this.handleLockPost.bind(this);
205     this.handleDeletePost = this.handleDeletePost.bind(this);
206     this.handleRemovePost = this.handleRemovePost.bind(this);
207     this.handleSavePost = this.handleSavePost.bind(this);
208     this.handlePurgePost = this.handlePurgePost.bind(this);
209     this.handleFeaturePost = this.handleFeaturePost.bind(this);
210     this.handleModBanSubmit = this.handleModBanSubmit.bind(this);
211
212     // Only fetch the data if coming from another route
213     if (FirstLoadService.isFirstLoad) {
214       this.state = {
215         ...this.state,
216         personRes: this.isoData.routeData.personResponse,
217         isIsomorphic: true,
218       };
219     }
220   }
221
222   async componentDidMount() {
223     if (!this.state.isIsomorphic) {
224       await this.fetchUserData();
225     }
226     setupTippy();
227   }
228
229   componentWillUnmount() {
230     saveScrollPosition(this.context);
231   }
232
233   async fetchUserData() {
234     const { page, sort, view } = getProfileQueryParams();
235
236     this.setState({ personRes: { state: "loading" } });
237     this.setState({
238       personRes: await HttpService.client.getPersonDetails({
239         username: this.props.match.params.username,
240         sort,
241         saved_only: view === PersonDetailsView.Saved,
242         page,
243         limit: fetchLimit,
244         auth: myAuth(),
245       }),
246     });
247     restoreScrollPosition(this.context);
248     this.setPersonBlock();
249   }
250
251   get amCurrentUser() {
252     if (this.state.personRes.state === "success") {
253       return (
254         UserService.Instance.myUserInfo?.local_user_view.person.id ===
255         this.state.personRes.data.person_view.person.id
256       );
257     } else {
258       return false;
259     }
260   }
261
262   setPersonBlock() {
263     const mui = UserService.Instance.myUserInfo;
264     const res = this.state.personRes;
265
266     if (mui && res.state === "success") {
267       this.setState({
268         personBlocked: mui.person_blocks.some(
269           ({ target: { id } }) => id === res.data.person_view.person.id
270         ),
271       });
272     }
273   }
274
275   static async fetchInitialData({
276     client,
277     path,
278     query: { page, sort, view: urlView },
279     auth,
280   }: InitialFetchRequest<QueryParams<ProfileProps>>): Promise<ProfileData> {
281     const pathSplit = path.split("/");
282
283     const username = pathSplit[2];
284     const view = getViewFromProps(urlView);
285
286     const form: GetPersonDetails = {
287       username: username,
288       sort: getSortTypeFromQuery(sort),
289       saved_only: view === PersonDetailsView.Saved,
290       page: getPageFromString(page),
291       limit: fetchLimit,
292       auth,
293     };
294
295     return {
296       personResponse: await client.getPersonDetails(form),
297     };
298   }
299
300   get documentTitle(): string {
301     const siteName = this.state.siteRes.site_view.site.name;
302     const res = this.state.personRes;
303     return res.state == "success"
304       ? `@${res.data.person_view.person.name} - ${siteName}`
305       : siteName;
306   }
307
308   renderPersonRes() {
309     switch (this.state.personRes.state) {
310       case "loading":
311         return (
312           <h5>
313             <Spinner large />
314           </h5>
315         );
316       case "success": {
317         const siteRes = this.state.siteRes;
318         const personRes = this.state.personRes.data;
319         const { page, sort, view } = getProfileQueryParams();
320
321         return (
322           <div className="row">
323             <div className="col-12 col-md-8">
324               <HtmlTags
325                 title={this.documentTitle}
326                 path={this.context.router.route.match.url}
327                 canonicalPath={personRes.person_view.person.actor_id}
328                 description={personRes.person_view.person.bio}
329                 image={personRes.person_view.person.avatar}
330               />
331
332               {this.userInfo(personRes.person_view)}
333
334               <hr />
335
336               {this.selects}
337
338               <PersonDetails
339                 personRes={personRes}
340                 admins={siteRes.admins}
341                 sort={sort}
342                 page={page}
343                 limit={fetchLimit}
344                 finished={this.state.finished}
345                 enableDownvotes={enableDownvotes(siteRes)}
346                 enableNsfw={enableNsfw(siteRes)}
347                 view={view}
348                 onPageChange={this.handlePageChange}
349                 allLanguages={siteRes.all_languages}
350                 siteLanguages={siteRes.discussion_languages}
351                 // TODO all the forms here
352                 onSaveComment={this.handleSaveComment}
353                 onBlockPerson={this.handleBlockPersonAlt}
354                 onDeleteComment={this.handleDeleteComment}
355                 onRemoveComment={this.handleRemoveComment}
356                 onCommentVote={this.handleCommentVote}
357                 onCommentReport={this.handleCommentReport}
358                 onDistinguishComment={this.handleDistinguishComment}
359                 onAddModToCommunity={this.handleAddModToCommunity}
360                 onAddAdmin={this.handleAddAdmin}
361                 onTransferCommunity={this.handleTransferCommunity}
362                 onPurgeComment={this.handlePurgeComment}
363                 onPurgePerson={this.handlePurgePerson}
364                 onCommentReplyRead={this.handleCommentReplyRead}
365                 onPersonMentionRead={this.handlePersonMentionRead}
366                 onBanPersonFromCommunity={this.handleBanFromCommunity}
367                 onBanPerson={this.handleBanPerson}
368                 onCreateComment={this.handleCreateComment}
369                 onEditComment={this.handleEditComment}
370                 onPostEdit={this.handlePostEdit}
371                 onPostVote={this.handlePostVote}
372                 onPostReport={this.handlePostReport}
373                 onLockPost={this.handleLockPost}
374                 onDeletePost={this.handleDeletePost}
375                 onRemovePost={this.handleRemovePost}
376                 onSavePost={this.handleSavePost}
377                 onPurgePost={this.handlePurgePost}
378                 onFeaturePost={this.handleFeaturePost}
379               />
380             </div>
381
382             <div className="col-12 col-md-4">
383               <Moderates moderates={personRes.moderates} />
384               {this.amCurrentUser && <Follows />}
385             </div>
386           </div>
387         );
388       }
389     }
390   }
391
392   render() {
393     return (
394       <div className="person-profile container-lg">
395         {this.renderPersonRes()}
396       </div>
397     );
398   }
399
400   get viewRadios() {
401     return (
402       <div className="btn-group btn-group-toggle flex-wrap mb-2" role="group">
403         {this.getRadio(PersonDetailsView.Overview)}
404         {this.getRadio(PersonDetailsView.Comments)}
405         {this.getRadio(PersonDetailsView.Posts)}
406         {this.amCurrentUser && this.getRadio(PersonDetailsView.Saved)}
407       </div>
408     );
409   }
410
411   getRadio(view: PersonDetailsView) {
412     const { view: urlView } = getProfileQueryParams();
413     const active = view === urlView;
414     const radioId = randomStr();
415
416     return (
417       <>
418         <input
419           id={radioId}
420           type="radio"
421           className="btn-check"
422           value={view}
423           checked={active}
424           onChange={linkEvent(this, this.handleViewChange)}
425         />
426         <label
427           htmlFor={radioId}
428           className={classNames("btn btn-outline-secondary pointer", {
429             active,
430           })}
431         >
432           {I18NextService.i18n.t(view.toLowerCase() as NoOptionI18nKeys)}
433         </label>
434       </>
435     );
436   }
437
438   get selects() {
439     const { sort } = getProfileQueryParams();
440     const { username } = this.props.match.params;
441
442     const profileRss = `/feeds/u/${username}.xml?sort=${sort}`;
443
444     return (
445       <div className="mb-2">
446         <span className="me-3">{this.viewRadios}</span>
447         <SortSelect
448           sort={sort}
449           onChange={this.handleSortChange}
450           hideHot
451           hideMostComments
452         />
453         <a href={profileRss} rel={relTags} title="RSS">
454           <Icon icon="rss" classes="text-muted small mx-2" />
455         </a>
456         <link rel="alternate" type="application/atom+xml" href={profileRss} />
457       </div>
458     );
459   }
460
461   userInfo(pv: PersonView) {
462     const {
463       personBlocked,
464       siteRes: { admins },
465       showBanDialog,
466     } = this.state;
467
468     return (
469       pv && (
470         <div>
471           {!isBanned(pv.person) && (
472             <BannerIconHeader
473               banner={pv.person.banner}
474               icon={pv.person.avatar}
475             />
476           )}
477           <div className="mb-3">
478             <div className="">
479               <div className="mb-0 d-flex flex-wrap">
480                 <div>
481                   {pv.person.display_name && (
482                     <h1 className="h4 mb-4">{pv.person.display_name}</h1>
483                   )}
484                   <ul className="list-inline mb-2">
485                     <li className="list-inline-item">
486                       <PersonListing
487                         person={pv.person}
488                         realLink
489                         useApubName
490                         muted
491                         hideAvatar
492                       />
493                     </li>
494                     <li className="list-inline-item">
495                       <UserBadges
496                         classNames="ms-1"
497                         isBanned={isBanned(pv.person)}
498                         isDeleted={pv.person.deleted}
499                         isAdmin={pv.person.admin}
500                         isBot={pv.person.bot_account}
501                       />
502                     </li>
503                   </ul>
504                 </div>
505                 {this.banDialog(pv)}
506                 <div className="flex-grow-1 unselectable pointer mx-2"></div>
507                 {!this.amCurrentUser && UserService.Instance.myUserInfo && (
508                   <>
509                     <a
510                       className={`d-flex align-self-start btn btn-secondary me-2 ${
511                         !pv.person.matrix_user_id && "invisible"
512                       }`}
513                       rel={relTags}
514                       href={`https://matrix.to/#/${pv.person.matrix_user_id}`}
515                     >
516                       {I18NextService.i18n.t("send_secure_message")}
517                     </a>
518                     <Link
519                       className={
520                         "d-flex align-self-start btn btn-secondary me-2"
521                       }
522                       to={`/create_private_message/${pv.person.id}`}
523                     >
524                       {I18NextService.i18n.t("send_message")}
525                     </Link>
526                     {personBlocked ? (
527                       <button
528                         className={
529                           "d-flex align-self-start btn btn-secondary me-2"
530                         }
531                         onClick={linkEvent(
532                           pv.person.id,
533                           this.handleUnblockPerson
534                         )}
535                       >
536                         {I18NextService.i18n.t("unblock_user")}
537                       </button>
538                     ) : (
539                       <button
540                         className={
541                           "d-flex align-self-start btn btn-secondary me-2"
542                         }
543                         onClick={linkEvent(
544                           pv.person.id,
545                           this.handleBlockPerson
546                         )}
547                       >
548                         {I18NextService.i18n.t("block_user")}
549                       </button>
550                     )}
551                   </>
552                 )}
553
554                 {canMod(pv.person.id, undefined, admins) &&
555                   !isAdmin(pv.person.id, admins) &&
556                   !showBanDialog &&
557                   (!isBanned(pv.person) ? (
558                     <button
559                       className={
560                         "d-flex align-self-start btn btn-secondary me-2"
561                       }
562                       onClick={linkEvent(this, this.handleModBanShow)}
563                       aria-label={I18NextService.i18n.t("ban")}
564                     >
565                       {capitalizeFirstLetter(I18NextService.i18n.t("ban"))}
566                     </button>
567                   ) : (
568                     <button
569                       className={
570                         "d-flex align-self-start btn btn-secondary me-2"
571                       }
572                       onClick={linkEvent(this, this.handleModBanSubmit)}
573                       aria-label={I18NextService.i18n.t("unban")}
574                     >
575                       {capitalizeFirstLetter(I18NextService.i18n.t("unban"))}
576                     </button>
577                   ))}
578               </div>
579               {pv.person.bio && (
580                 <div className="d-flex align-items-center mb-2">
581                   <div
582                     className="md-div"
583                     dangerouslySetInnerHTML={mdToHtml(pv.person.bio)}
584                   />
585                 </div>
586               )}
587               <div>
588                 <ul className="list-inline mb-2">
589                   <li className="list-inline-item badge text-bg-light">
590                     {I18NextService.i18n.t("number_of_posts", {
591                       count: Number(pv.counts.post_count),
592                       formattedCount: numToSI(pv.counts.post_count),
593                     })}
594                   </li>
595                   <li className="list-inline-item badge text-bg-light">
596                     {I18NextService.i18n.t("number_of_comments", {
597                       count: Number(pv.counts.comment_count),
598                       formattedCount: numToSI(pv.counts.comment_count),
599                     })}
600                   </li>
601                 </ul>
602               </div>
603               <div className="text-muted">
604                 {I18NextService.i18n.t("joined")}{" "}
605                 <MomentTime
606                   published={pv.person.published}
607                   showAgo
608                   ignoreUpdated
609                 />
610               </div>
611               <div className="d-flex align-items-center text-muted mb-2">
612                 <Icon icon="cake" />
613                 <span className="ms-2">
614                   {I18NextService.i18n.t("cake_day_title")}{" "}
615                   {format(parseISO(pv.person.published), "PPP")}
616                 </span>
617               </div>
618               {!UserService.Instance.myUserInfo && (
619                 <div className="alert alert-info" role="alert">
620                   {I18NextService.i18n.t("profile_not_logged_in_alert")}
621                 </div>
622               )}
623             </div>
624           </div>
625         </div>
626       )
627     );
628   }
629
630   banDialog(pv: PersonView) {
631     const { showBanDialog } = this.state;
632
633     return (
634       showBanDialog && (
635         <form onSubmit={linkEvent(this, this.handleModBanSubmit)}>
636           <div className="mb-3 row col-12">
637             <label className="col-form-label" htmlFor="profile-ban-reason">
638               {I18NextService.i18n.t("reason")}
639             </label>
640             <input
641               type="text"
642               id="profile-ban-reason"
643               className="form-control me-2"
644               placeholder={I18NextService.i18n.t("reason")}
645               value={this.state.banReason}
646               onInput={linkEvent(this, this.handleModBanReasonChange)}
647             />
648             <label className="col-form-label" htmlFor="mod-ban-expires">
649               {I18NextService.i18n.t("expires")}
650             </label>
651             <input
652               type="number"
653               id="mod-ban-expires"
654               className="form-control me-2"
655               placeholder={I18NextService.i18n.t("number_of_days")}
656               value={this.state.banExpireDays}
657               onInput={linkEvent(this, this.handleModBanExpireDaysChange)}
658             />
659             <div className="input-group mb-3">
660               <div className="form-check">
661                 <input
662                   className="form-check-input"
663                   id="mod-ban-remove-data"
664                   type="checkbox"
665                   checked={this.state.removeData}
666                   onChange={linkEvent(this, this.handleModRemoveDataChange)}
667                 />
668                 <label
669                   className="form-check-label"
670                   htmlFor="mod-ban-remove-data"
671                   title={I18NextService.i18n.t("remove_content_more")}
672                 >
673                   {I18NextService.i18n.t("remove_content")}
674                 </label>
675               </div>
676             </div>
677           </div>
678           {/* TODO hold off on expires until later */}
679           {/* <div class="mb-3 row"> */}
680           {/*   <label class="col-form-label">Expires</label> */}
681           {/*   <input type="date" class="form-control me-2" placeholder={I18NextService.i18n.t('expires')} value={this.state.banExpires} onInput={linkEvent(this, this.handleModBanExpiresChange)} /> */}
682           {/* </div> */}
683           <div className="mb-3 row">
684             <button
685               type="reset"
686               className="btn btn-secondary me-2"
687               aria-label={I18NextService.i18n.t("cancel")}
688               onClick={linkEvent(this, this.handleModBanSubmitCancel)}
689             >
690               {I18NextService.i18n.t("cancel")}
691             </button>
692           </div>
693           <div className="mb-3 row">
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           s.personRes.data.person_view.person.banned = banRes.data.banned;
991         }
992         return s;
993       });
994     }
995   }
996
997   purgeItem(purgeRes: RequestState<PurgeItemResponse>) {
998     if (purgeRes.state == "success") {
999       toast(I18NextService.i18n.t("purge_success"));
1000       this.context.router.history.push(`/`);
1001     }
1002   }
1003
1004   findAndUpdateComment(res: RequestState<CommentResponse>) {
1005     this.setState(s => {
1006       if (s.personRes.state == "success" && res.state == "success") {
1007         s.personRes.data.comments = editComment(
1008           res.data.comment_view,
1009           s.personRes.data.comments
1010         );
1011         s.finished.set(res.data.comment_view.comment.id, true);
1012       }
1013       return s;
1014     });
1015   }
1016
1017   createAndUpdateComments(res: RequestState<CommentResponse>) {
1018     this.setState(s => {
1019       if (s.personRes.state == "success" && res.state == "success") {
1020         s.personRes.data.comments.unshift(res.data.comment_view);
1021         // Set finished for the parent
1022         s.finished.set(
1023           getCommentParentId(res.data.comment_view.comment) ?? 0,
1024           true
1025         );
1026       }
1027       return s;
1028     });
1029   }
1030
1031   findAndUpdateCommentReply(res: RequestState<CommentReplyResponse>) {
1032     this.setState(s => {
1033       if (s.personRes.state == "success" && res.state == "success") {
1034         s.personRes.data.comments = editWith(
1035           res.data.comment_reply_view,
1036           s.personRes.data.comments
1037         );
1038       }
1039       return s;
1040     });
1041   }
1042
1043   findAndUpdatePost(res: RequestState<PostResponse>) {
1044     this.setState(s => {
1045       if (s.personRes.state == "success" && res.state == "success") {
1046         s.personRes.data.posts = editPost(
1047           res.data.post_view,
1048           s.personRes.data.posts
1049         );
1050       }
1051       return s;
1052     });
1053   }
1054 }