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