]> Untitled Git - lemmy.git/blob - ui/src/components/user.tsx
Some more prettifying, cleaning up community and main.tsx
[lemmy.git] / ui / src / components / user.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Helmet } from 'inferno-helmet';
3 import { Link } from 'inferno-router';
4 import { Subscription } from 'rxjs';
5 import { retryWhen, delay, take } from 'rxjs/operators';
6 import {
7   UserOperation,
8   CommunityUser,
9   SortType,
10   ListingType,
11   UserView,
12   UserSettingsForm,
13   LoginResponse,
14   DeleteAccountForm,
15   WebSocketJsonResponse,
16   GetSiteResponse,
17   UserDetailsView,
18   UserDetailsResponse,
19   AddAdminResponse,
20 } from '../interfaces';
21 import { WebSocketService, UserService } from '../services';
22 import {
23   wsJsonToRes,
24   fetchLimit,
25   routeSortTypeToEnum,
26   capitalizeFirstLetter,
27   themes,
28   setTheme,
29   languages,
30   showAvatars,
31   toast,
32   setupTippy,
33 } from '../utils';
34 import { UserListing } from './user-listing';
35 import { SortSelect } from './sort-select';
36 import { ListingTypeSelect } from './listing-type-select';
37 import { MomentTime } from './moment-time';
38 import { i18n } from '../i18next';
39 import moment from 'moment';
40 import { UserDetails } from './user-details';
41
42 interface UserState {
43   user: UserView;
44   user_id: number;
45   username: string;
46   follows: Array<CommunityUser>;
47   moderates: Array<CommunityUser>;
48   view: UserDetailsView;
49   sort: SortType;
50   page: number;
51   loading: boolean;
52   avatarLoading: boolean;
53   userSettingsForm: UserSettingsForm;
54   userSettingsLoading: boolean;
55   deleteAccountLoading: boolean;
56   deleteAccountShowConfirm: boolean;
57   deleteAccountForm: DeleteAccountForm;
58   siteRes: GetSiteResponse;
59 }
60
61 interface UserProps {
62   view: UserDetailsView;
63   sort: SortType;
64   page: number;
65   user_id: number | null;
66   username: string;
67 }
68
69 interface UrlParams {
70   view?: string;
71   sort?: string;
72   page?: number;
73 }
74
75 export class User extends Component<any, UserState> {
76   private subscription: Subscription;
77   private emptyState: UserState = {
78     user: {
79       id: null,
80       name: null,
81       published: null,
82       number_of_posts: null,
83       post_score: null,
84       number_of_comments: null,
85       comment_score: null,
86       banned: null,
87       avatar: null,
88       show_avatars: null,
89       send_notifications_to_email: null,
90       actor_id: null,
91       local: null,
92     },
93     user_id: null,
94     username: null,
95     follows: [],
96     moderates: [],
97     loading: true,
98     avatarLoading: false,
99     view: User.getViewFromProps(this.props.match.view),
100     sort: User.getSortTypeFromProps(this.props.match.sort),
101     page: User.getPageFromProps(this.props.match.page),
102     userSettingsForm: {
103       show_nsfw: null,
104       theme: null,
105       default_sort_type: null,
106       default_listing_type: null,
107       lang: null,
108       show_avatars: null,
109       send_notifications_to_email: null,
110       auth: null,
111     },
112     userSettingsLoading: null,
113     deleteAccountLoading: null,
114     deleteAccountShowConfirm: false,
115     deleteAccountForm: {
116       password: null,
117     },
118     siteRes: {
119       admins: [],
120       banned: [],
121       online: undefined,
122       site: {
123         id: undefined,
124         name: undefined,
125         creator_id: undefined,
126         published: undefined,
127         creator_name: undefined,
128         number_of_users: undefined,
129         number_of_posts: undefined,
130         number_of_comments: undefined,
131         number_of_communities: undefined,
132         enable_downvotes: undefined,
133         open_registration: undefined,
134         enable_nsfw: undefined,
135       },
136       version: undefined,
137     },
138   };
139
140   constructor(props: any, context: any) {
141     super(props, context);
142
143     this.state = this.emptyState;
144     this.handleSortChange = this.handleSortChange.bind(this);
145     this.handleUserSettingsSortTypeChange = this.handleUserSettingsSortTypeChange.bind(
146       this
147     );
148     this.handleUserSettingsListingTypeChange = this.handleUserSettingsListingTypeChange.bind(
149       this
150     );
151     this.handlePageChange = this.handlePageChange.bind(this);
152
153     this.state.user_id = Number(this.props.match.params.id) || null;
154     this.state.username = this.props.match.params.username;
155
156     this.subscription = WebSocketService.Instance.subject
157       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
158       .subscribe(
159         msg => this.parseMessage(msg),
160         err => console.error(err),
161         () => console.log('complete')
162       );
163
164     WebSocketService.Instance.getSite();
165   }
166
167   get isCurrentUser() {
168     return (
169       UserService.Instance.user &&
170       UserService.Instance.user.id == this.state.user.id
171     );
172   }
173
174   static getViewFromProps(view: any): UserDetailsView {
175     return view
176       ? UserDetailsView[capitalizeFirstLetter(view)]
177       : UserDetailsView.Overview;
178   }
179
180   static getSortTypeFromProps(sort: any): SortType {
181     return sort ? routeSortTypeToEnum(sort) : SortType.New;
182   }
183
184   static getPageFromProps(page: any): number {
185     return page ? Number(page) : 1;
186   }
187
188   componentWillUnmount() {
189     this.subscription.unsubscribe();
190   }
191
192   static getDerivedStateFromProps(props: any): UserProps {
193     return {
194       view: this.getViewFromProps(props.match.params.view),
195       sort: this.getSortTypeFromProps(props.match.params.sort),
196       page: this.getPageFromProps(props.match.params.page),
197       user_id: Number(props.match.params.id) || null,
198       username: props.match.params.username,
199     };
200   }
201
202   componentDidUpdate(lastProps: any, _lastState: UserState, _snapshot: any) {
203     // Necessary if you are on a post and you click another post (same route)
204     if (
205       lastProps.location.pathname.split('/')[2] !==
206       lastProps.history.location.pathname.split('/')[2]
207     ) {
208       // Couldnt get a refresh working. This does for now.
209       location.reload();
210     }
211     setupTippy();
212   }
213
214   get documentTitle(): string {
215     if (this.state.siteRes.site.name) {
216       return `/u/${this.state.username} - ${this.state.siteRes.site.name}`;
217     } else {
218       return 'Lemmy';
219     }
220   }
221
222   render() {
223     return (
224       <div class="container">
225         <Helmet title={this.documentTitle} />
226         <div class="row">
227           <div class="col-12 col-md-8">
228             <h5>
229               {this.state.user.avatar && showAvatars() && (
230                 <img
231                   height="80"
232                   width="80"
233                   src={this.state.user.avatar}
234                   class="rounded-circle mr-2"
235                 />
236               )}
237               <span>/u/{this.state.username}</span>
238             </h5>
239             {this.state.loading ? (
240               <h5>
241                 <svg class="icon icon-spinner spin">
242                   <use xlinkHref="#icon-spinner"></use>
243                 </svg>
244               </h5>
245             ) : (
246               this.selects()
247             )}
248             <UserDetails
249               user_id={this.state.user_id}
250               username={this.state.username}
251               sort={SortType[this.state.sort]}
252               page={this.state.page}
253               limit={fetchLimit}
254               enableDownvotes={this.state.siteRes.site.enable_downvotes}
255               enableNsfw={this.state.siteRes.site.enable_nsfw}
256               admins={this.state.siteRes.admins}
257               view={this.state.view}
258               onPageChange={this.handlePageChange}
259             />
260           </div>
261
262           {!this.state.loading && (
263             <div class="col-12 col-md-4">
264               {this.userInfo()}
265               {this.isCurrentUser && this.userSettings()}
266               {this.moderates()}
267               {this.follows()}
268             </div>
269           )}
270         </div>
271       </div>
272     );
273   }
274
275   viewRadios() {
276     return (
277       <div class="btn-group btn-group-toggle flex-wrap mb-2">
278         <label
279           className={`btn btn-outline-secondary pointer 
280             ${this.state.view == UserDetailsView.Overview && 'active'}
281           `}
282         >
283           <input
284             type="radio"
285             value={UserDetailsView.Overview}
286             checked={this.state.view === UserDetailsView.Overview}
287             onChange={linkEvent(this, this.handleViewChange)}
288           />
289           {i18n.t('overview')}
290         </label>
291         <label
292           className={`btn btn-outline-secondary pointer 
293             ${this.state.view == UserDetailsView.Comments && 'active'}
294           `}
295         >
296           <input
297             type="radio"
298             value={UserDetailsView.Comments}
299             checked={this.state.view == UserDetailsView.Comments}
300             onChange={linkEvent(this, this.handleViewChange)}
301           />
302           {i18n.t('comments')}
303         </label>
304         <label
305           className={`btn btn-outline-secondary pointer 
306             ${this.state.view == UserDetailsView.Posts && 'active'}
307           `}
308         >
309           <input
310             type="radio"
311             value={UserDetailsView.Posts}
312             checked={this.state.view == UserDetailsView.Posts}
313             onChange={linkEvent(this, this.handleViewChange)}
314           />
315           {i18n.t('posts')}
316         </label>
317         <label
318           className={`btn btn-outline-secondary pointer 
319             ${this.state.view == UserDetailsView.Saved && 'active'}
320           `}
321         >
322           <input
323             type="radio"
324             value={UserDetailsView.Saved}
325             checked={this.state.view == UserDetailsView.Saved}
326             onChange={linkEvent(this, this.handleViewChange)}
327           />
328           {i18n.t('saved')}
329         </label>
330       </div>
331     );
332   }
333
334   selects() {
335     return (
336       <div className="mb-2">
337         <span class="mr-3">{this.viewRadios()}</span>
338         <SortSelect
339           sort={this.state.sort}
340           onChange={this.handleSortChange}
341           hideHot
342         />
343         <a
344           href={`/feeds/u/${this.state.username}.xml?sort=${
345             SortType[this.state.sort]
346           }`}
347           target="_blank"
348           rel="noopener"
349           title="RSS"
350         >
351           <svg class="icon mx-2 text-muted small">
352             <use xlinkHref="#icon-rss">#</use>
353           </svg>
354         </a>
355       </div>
356     );
357   }
358
359   userInfo() {
360     let user = this.state.user;
361     return (
362       <div>
363         <div class="card bg-transparent border-secondary mb-3">
364           <div class="card-body">
365             <h5>
366               <ul class="list-inline mb-0">
367                 <li className="list-inline-item">
368                   <UserListing user={user} realLink />
369                 </li>
370                 {user.banned && (
371                   <li className="list-inline-item badge badge-danger">
372                     {i18n.t('banned')}
373                   </li>
374                 )}
375               </ul>
376             </h5>
377             <div className="d-flex align-items-center mb-2">
378               <svg class="icon">
379                 <use xlinkHref="#icon-cake"></use>
380               </svg>
381               <span className="ml-2">
382                 {i18n.t('cake_day_title')}{' '}
383                 {moment.utc(user.published).local().format('MMM DD, YYYY')}
384               </span>
385             </div>
386             <div>
387               {i18n.t('joined')} <MomentTime data={user} showAgo />
388             </div>
389             <div class="table-responsive mt-1">
390               <table class="table table-bordered table-sm mt-2 mb-0">
391                 {/*
392                 <tr>
393                   <td class="text-center" colSpan={2}>
394                     {i18n.t('number_of_points', {
395                       count: user.post_score + user.comment_score,
396                     })}
397                   </td>
398                 </tr>
399                 */}
400                 <tr>
401                   {/* 
402                   <td>
403                     {i18n.t('number_of_points', { count: user.post_score })}
404                   </td>
405                   */}
406                   <td>
407                     {i18n.t('number_of_posts', { count: user.number_of_posts })}
408                   </td>
409                   {/* 
410                 </tr>
411                 <tr>
412                   <td>
413                     {i18n.t('number_of_points', { count: user.comment_score })}
414                   </td>
415                   */}
416                   <td>
417                     {i18n.t('number_of_comments', {
418                       count: user.number_of_comments,
419                     })}
420                   </td>
421                 </tr>
422               </table>
423             </div>
424             {this.isCurrentUser ? (
425               <button
426                 class="btn btn-block btn-secondary mt-3"
427                 onClick={linkEvent(this, this.handleLogoutClick)}
428               >
429                 {i18n.t('logout')}
430               </button>
431             ) : (
432               <>
433                 <a
434                   className={`btn btn-block btn-secondary mt-3 ${
435                     !this.state.user.matrix_user_id && 'disabled'
436                   }`}
437                   target="_blank"
438                   rel="noopener"
439                   href={`https://matrix.to/#/${this.state.user.matrix_user_id}`}
440                 >
441                   {i18n.t('send_secure_message')}
442                 </a>
443                 <Link
444                   class="btn btn-block btn-secondary mt-3"
445                   to={`/create_private_message?recipient_id=${this.state.user.id}`}
446                 >
447                   {i18n.t('send_message')}
448                 </Link>
449               </>
450             )}
451           </div>
452         </div>
453       </div>
454     );
455   }
456
457   userSettings() {
458     return (
459       <div>
460         <div class="card bg-transparent border-secondary mb-3">
461           <div class="card-body">
462             <h5>{i18n.t('settings')}</h5>
463             <form onSubmit={linkEvent(this, this.handleUserSettingsSubmit)}>
464               <div class="form-group">
465                 <label>{i18n.t('avatar')}</label>
466                 <form class="d-inline">
467                   <label
468                     htmlFor="file-upload"
469                     class="pointer ml-4 text-muted small font-weight-bold"
470                   >
471                     {!this.checkSettingsAvatar ? (
472                       <span class="btn btn-secondary">
473                         {i18n.t('upload_avatar')}
474                       </span>
475                     ) : (
476                       <img
477                         height="80"
478                         width="80"
479                         src={this.state.userSettingsForm.avatar}
480                         class="rounded-circle"
481                       />
482                     )}
483                   </label>
484                   <input
485                     id="file-upload"
486                     type="file"
487                     accept="image/*,video/*"
488                     name="file"
489                     class="d-none"
490                     disabled={!UserService.Instance.user}
491                     onChange={linkEvent(this, this.handleImageUpload)}
492                   />
493                 </form>
494               </div>
495               {this.checkSettingsAvatar && (
496                 <div class="form-group">
497                   <button
498                     class="btn btn-secondary btn-block"
499                     onClick={linkEvent(this, this.removeAvatar)}
500                   >
501                     {`${capitalizeFirstLetter(i18n.t('remove'))} ${i18n.t(
502                       'avatar'
503                     )}`}
504                   </button>
505                 </div>
506               )}
507               <div class="form-group">
508                 <label>{i18n.t('language')}</label>
509                 <select
510                   value={this.state.userSettingsForm.lang}
511                   onChange={linkEvent(this, this.handleUserSettingsLangChange)}
512                   class="ml-2 custom-select w-auto"
513                 >
514                   <option disabled>{i18n.t('language')}</option>
515                   <option value="browser">{i18n.t('browser_default')}</option>
516                   <option disabled>──</option>
517                   {languages.map(lang => (
518                     <option value={lang.code}>{lang.name}</option>
519                   ))}
520                 </select>
521               </div>
522               <div class="form-group">
523                 <label>{i18n.t('theme')}</label>
524                 <select
525                   value={this.state.userSettingsForm.theme}
526                   onChange={linkEvent(this, this.handleUserSettingsThemeChange)}
527                   class="ml-2 custom-select w-auto"
528                 >
529                   <option disabled>{i18n.t('theme')}</option>
530                   {themes.map(theme => (
531                     <option value={theme}>{theme}</option>
532                   ))}
533                 </select>
534               </div>
535               <form className="form-group">
536                 <label>
537                   <div class="mr-2">{i18n.t('sort_type')}</div>
538                 </label>
539                 <ListingTypeSelect
540                   type_={this.state.userSettingsForm.default_listing_type}
541                   onChange={this.handleUserSettingsListingTypeChange}
542                 />
543               </form>
544               <form className="form-group">
545                 <label>
546                   <div class="mr-2">{i18n.t('type')}</div>
547                 </label>
548                 <SortSelect
549                   sort={this.state.userSettingsForm.default_sort_type}
550                   onChange={this.handleUserSettingsSortTypeChange}
551                 />
552               </form>
553               <div class="form-group row">
554                 <label class="col-lg-3 col-form-label" htmlFor="user-email">
555                   {i18n.t('email')}
556                 </label>
557                 <div class="col-lg-9">
558                   <input
559                     type="email"
560                     id="user-email"
561                     class="form-control"
562                     placeholder={i18n.t('optional')}
563                     value={this.state.userSettingsForm.email}
564                     onInput={linkEvent(
565                       this,
566                       this.handleUserSettingsEmailChange
567                     )}
568                     minLength={3}
569                   />
570                 </div>
571               </div>
572               <div class="form-group row">
573                 <label class="col-lg-5 col-form-label">
574                   <a
575                     href="https://about.riot.im/"
576                     target="_blank"
577                     rel="noopener"
578                   >
579                     {i18n.t('matrix_user_id')}
580                   </a>
581                 </label>
582                 <div class="col-lg-7">
583                   <input
584                     type="text"
585                     class="form-control"
586                     placeholder="@user:example.com"
587                     value={this.state.userSettingsForm.matrix_user_id}
588                     onInput={linkEvent(
589                       this,
590                       this.handleUserSettingsMatrixUserIdChange
591                     )}
592                     minLength={3}
593                   />
594                 </div>
595               </div>
596               <div class="form-group row">
597                 <label class="col-lg-5 col-form-label" htmlFor="user-password">
598                   {i18n.t('new_password')}
599                 </label>
600                 <div class="col-lg-7">
601                   <input
602                     type="password"
603                     id="user-password"
604                     class="form-control"
605                     value={this.state.userSettingsForm.new_password}
606                     autoComplete="new-password"
607                     onInput={linkEvent(
608                       this,
609                       this.handleUserSettingsNewPasswordChange
610                     )}
611                   />
612                 </div>
613               </div>
614               <div class="form-group row">
615                 <label
616                   class="col-lg-5 col-form-label"
617                   htmlFor="user-verify-password"
618                 >
619                   {i18n.t('verify_password')}
620                 </label>
621                 <div class="col-lg-7">
622                   <input
623                     type="password"
624                     id="user-verify-password"
625                     class="form-control"
626                     value={this.state.userSettingsForm.new_password_verify}
627                     autoComplete="new-password"
628                     onInput={linkEvent(
629                       this,
630                       this.handleUserSettingsNewPasswordVerifyChange
631                     )}
632                   />
633                 </div>
634               </div>
635               <div class="form-group row">
636                 <label
637                   class="col-lg-5 col-form-label"
638                   htmlFor="user-old-password"
639                 >
640                   {i18n.t('old_password')}
641                 </label>
642                 <div class="col-lg-7">
643                   <input
644                     type="password"
645                     id="user-old-password"
646                     class="form-control"
647                     value={this.state.userSettingsForm.old_password}
648                     autoComplete="new-password"
649                     onInput={linkEvent(
650                       this,
651                       this.handleUserSettingsOldPasswordChange
652                     )}
653                   />
654                 </div>
655               </div>
656               {this.state.siteRes.site.enable_nsfw && (
657                 <div class="form-group">
658                   <div class="form-check">
659                     <input
660                       class="form-check-input"
661                       id="user-show-nsfw"
662                       type="checkbox"
663                       checked={this.state.userSettingsForm.show_nsfw}
664                       onChange={linkEvent(
665                         this,
666                         this.handleUserSettingsShowNsfwChange
667                       )}
668                     />
669                     <label class="form-check-label" htmlFor="user-show-nsfw">
670                       {i18n.t('show_nsfw')}
671                     </label>
672                   </div>
673                 </div>
674               )}
675               <div class="form-group">
676                 <div class="form-check">
677                   <input
678                     class="form-check-input"
679                     id="user-show-avatars"
680                     type="checkbox"
681                     checked={this.state.userSettingsForm.show_avatars}
682                     onChange={linkEvent(
683                       this,
684                       this.handleUserSettingsShowAvatarsChange
685                     )}
686                   />
687                   <label class="form-check-label" htmlFor="user-show-avatars">
688                     {i18n.t('show_avatars')}
689                   </label>
690                 </div>
691               </div>
692               <div class="form-group">
693                 <div class="form-check">
694                   <input
695                     class="form-check-input"
696                     id="user-send-notifications-to-email"
697                     type="checkbox"
698                     disabled={!this.state.user.email}
699                     checked={
700                       this.state.userSettingsForm.send_notifications_to_email
701                     }
702                     onChange={linkEvent(
703                       this,
704                       this.handleUserSettingsSendNotificationsToEmailChange
705                     )}
706                   />
707                   <label
708                     class="form-check-label"
709                     htmlFor="user-send-notifications-to-email"
710                   >
711                     {i18n.t('send_notifications_to_email')}
712                   </label>
713                 </div>
714               </div>
715               <div class="form-group">
716                 <button type="submit" class="btn btn-block btn-secondary mr-4">
717                   {this.state.userSettingsLoading ? (
718                     <svg class="icon icon-spinner spin">
719                       <use xlinkHref="#icon-spinner"></use>
720                     </svg>
721                   ) : (
722                     capitalizeFirstLetter(i18n.t('save'))
723                   )}
724                 </button>
725               </div>
726               <hr />
727               <div class="form-group mb-0">
728                 <button
729                   class="btn btn-block btn-danger"
730                   onClick={linkEvent(
731                     this,
732                     this.handleDeleteAccountShowConfirmToggle
733                   )}
734                 >
735                   {i18n.t('delete_account')}
736                 </button>
737                 {this.state.deleteAccountShowConfirm && (
738                   <>
739                     <div class="my-2 alert alert-danger" role="alert">
740                       {i18n.t('delete_account_confirm')}
741                     </div>
742                     <input
743                       type="password"
744                       value={this.state.deleteAccountForm.password}
745                       autoComplete="new-password"
746                       onInput={linkEvent(
747                         this,
748                         this.handleDeleteAccountPasswordChange
749                       )}
750                       class="form-control my-2"
751                     />
752                     <button
753                       class="btn btn-danger mr-4"
754                       disabled={!this.state.deleteAccountForm.password}
755                       onClick={linkEvent(this, this.handleDeleteAccount)}
756                     >
757                       {this.state.deleteAccountLoading ? (
758                         <svg class="icon icon-spinner spin">
759                           <use xlinkHref="#icon-spinner"></use>
760                         </svg>
761                       ) : (
762                         capitalizeFirstLetter(i18n.t('delete'))
763                       )}
764                     </button>
765                     <button
766                       class="btn btn-secondary"
767                       onClick={linkEvent(
768                         this,
769                         this.handleDeleteAccountShowConfirmToggle
770                       )}
771                     >
772                       {i18n.t('cancel')}
773                     </button>
774                   </>
775                 )}
776               </div>
777             </form>
778           </div>
779         </div>
780       </div>
781     );
782   }
783
784   moderates() {
785     return (
786       <div>
787         {this.state.moderates.length > 0 && (
788           <div class="card bg-transparent border-secondary mb-3">
789             <div class="card-body">
790               <h5>{i18n.t('moderates')}</h5>
791               <ul class="list-unstyled mb-0">
792                 {this.state.moderates.map(community => (
793                   <li>
794                     <Link to={`/c/${community.community_name}`}>
795                       {community.community_name}
796                     </Link>
797                   </li>
798                 ))}
799               </ul>
800             </div>
801           </div>
802         )}
803       </div>
804     );
805   }
806
807   follows() {
808     return (
809       <div>
810         {this.state.follows.length > 0 && (
811           <div class="card bg-transparent border-secondary mb-3">
812             <div class="card-body">
813               <h5>{i18n.t('subscribed')}</h5>
814               <ul class="list-unstyled mb-0">
815                 {this.state.follows.map(community => (
816                   <li>
817                     <Link to={`/c/${community.community_name}`}>
818                       {community.community_name}
819                     </Link>
820                   </li>
821                 ))}
822               </ul>
823             </div>
824           </div>
825         )}
826       </div>
827     );
828   }
829
830   updateUrl(paramUpdates: UrlParams) {
831     const page = paramUpdates.page || this.state.page;
832     const viewStr =
833       paramUpdates.view || UserDetailsView[this.state.view].toLowerCase();
834     const sortStr =
835       paramUpdates.sort || SortType[this.state.sort].toLowerCase();
836     this.props.history.push(
837       `/u/${this.state.username}/view/${viewStr}/sort/${sortStr}/page/${page}`
838     );
839   }
840
841   handlePageChange(page: number) {
842     this.updateUrl({ page });
843   }
844
845   handleSortChange(val: SortType) {
846     this.updateUrl({ sort: SortType[val].toLowerCase(), page: 1 });
847   }
848
849   handleViewChange(i: User, event: any) {
850     i.updateUrl({
851       view: UserDetailsView[Number(event.target.value)].toLowerCase(),
852       page: 1,
853     });
854   }
855
856   handleUserSettingsShowNsfwChange(i: User, event: any) {
857     i.state.userSettingsForm.show_nsfw = event.target.checked;
858     i.setState(i.state);
859   }
860
861   handleUserSettingsShowAvatarsChange(i: User, event: any) {
862     i.state.userSettingsForm.show_avatars = event.target.checked;
863     UserService.Instance.user.show_avatars = event.target.checked; // Just for instant updates
864     i.setState(i.state);
865   }
866
867   handleUserSettingsSendNotificationsToEmailChange(i: User, event: any) {
868     i.state.userSettingsForm.send_notifications_to_email = event.target.checked;
869     i.setState(i.state);
870   }
871
872   handleUserSettingsThemeChange(i: User, event: any) {
873     i.state.userSettingsForm.theme = event.target.value;
874     setTheme(event.target.value, true);
875     i.setState(i.state);
876   }
877
878   handleUserSettingsLangChange(i: User, event: any) {
879     i.state.userSettingsForm.lang = event.target.value;
880     i18n.changeLanguage(i.state.userSettingsForm.lang);
881     i.setState(i.state);
882   }
883
884   handleUserSettingsSortTypeChange(val: SortType) {
885     this.state.userSettingsForm.default_sort_type = val;
886     this.setState(this.state);
887   }
888
889   handleUserSettingsListingTypeChange(val: ListingType) {
890     this.state.userSettingsForm.default_listing_type = val;
891     this.setState(this.state);
892   }
893
894   handleUserSettingsEmailChange(i: User, event: any) {
895     i.state.userSettingsForm.email = event.target.value;
896     if (i.state.userSettingsForm.email == '' && !i.state.user.email) {
897       i.state.userSettingsForm.email = undefined;
898     }
899     i.setState(i.state);
900   }
901
902   handleUserSettingsMatrixUserIdChange(i: User, event: any) {
903     i.state.userSettingsForm.matrix_user_id = event.target.value;
904     if (
905       i.state.userSettingsForm.matrix_user_id == '' &&
906       !i.state.user.matrix_user_id
907     ) {
908       i.state.userSettingsForm.matrix_user_id = undefined;
909     }
910     i.setState(i.state);
911   }
912
913   handleUserSettingsNewPasswordChange(i: User, event: any) {
914     i.state.userSettingsForm.new_password = event.target.value;
915     if (i.state.userSettingsForm.new_password == '') {
916       i.state.userSettingsForm.new_password = undefined;
917     }
918     i.setState(i.state);
919   }
920
921   handleUserSettingsNewPasswordVerifyChange(i: User, event: any) {
922     i.state.userSettingsForm.new_password_verify = event.target.value;
923     if (i.state.userSettingsForm.new_password_verify == '') {
924       i.state.userSettingsForm.new_password_verify = undefined;
925     }
926     i.setState(i.state);
927   }
928
929   handleUserSettingsOldPasswordChange(i: User, event: any) {
930     i.state.userSettingsForm.old_password = event.target.value;
931     if (i.state.userSettingsForm.old_password == '') {
932       i.state.userSettingsForm.old_password = undefined;
933     }
934     i.setState(i.state);
935   }
936
937   handleImageUpload(i: User, event: any) {
938     event.preventDefault();
939     let file = event.target.files[0];
940     const imageUploadUrl = `/pictrs/image`;
941     const formData = new FormData();
942     formData.append('images[]', file);
943
944     i.state.avatarLoading = true;
945     i.setState(i.state);
946
947     fetch(imageUploadUrl, {
948       method: 'POST',
949       body: formData,
950     })
951       .then(res => res.json())
952       .then(res => {
953         console.log('pictrs upload:');
954         console.log(res);
955         if (res.msg == 'ok') {
956           let hash = res.files[0].file;
957           let url = `${window.location.origin}/pictrs/image/${hash}`;
958           i.state.userSettingsForm.avatar = url;
959           i.state.avatarLoading = false;
960           i.setState(i.state);
961         } else {
962           i.state.avatarLoading = false;
963           i.setState(i.state);
964           toast(JSON.stringify(res), 'danger');
965         }
966       })
967       .catch(error => {
968         i.state.avatarLoading = false;
969         i.setState(i.state);
970         toast(error, 'danger');
971       });
972   }
973
974   removeAvatar(i: User, event: any) {
975     event.preventDefault();
976     i.state.userSettingsLoading = true;
977     i.state.userSettingsForm.avatar = '';
978     i.setState(i.state);
979
980     WebSocketService.Instance.saveUserSettings(i.state.userSettingsForm);
981   }
982
983   get checkSettingsAvatar(): boolean {
984     return (
985       this.state.userSettingsForm.avatar &&
986       this.state.userSettingsForm.avatar != ''
987     );
988   }
989
990   handleUserSettingsSubmit(i: User, event: any) {
991     event.preventDefault();
992     i.state.userSettingsLoading = true;
993     i.setState(i.state);
994
995     WebSocketService.Instance.saveUserSettings(i.state.userSettingsForm);
996   }
997
998   handleDeleteAccountShowConfirmToggle(i: User, event: any) {
999     event.preventDefault();
1000     i.state.deleteAccountShowConfirm = !i.state.deleteAccountShowConfirm;
1001     i.setState(i.state);
1002   }
1003
1004   handleDeleteAccountPasswordChange(i: User, event: any) {
1005     i.state.deleteAccountForm.password = event.target.value;
1006     i.setState(i.state);
1007   }
1008
1009   handleLogoutClick(i: User) {
1010     UserService.Instance.logout();
1011     i.context.router.history.push('/');
1012   }
1013
1014   handleDeleteAccount(i: User, event: any) {
1015     event.preventDefault();
1016     i.state.deleteAccountLoading = true;
1017     i.setState(i.state);
1018
1019     WebSocketService.Instance.deleteAccount(i.state.deleteAccountForm);
1020   }
1021
1022   parseMessage(msg: WebSocketJsonResponse) {
1023     console.log(msg);
1024     const res = wsJsonToRes(msg);
1025     if (msg.error) {
1026       toast(i18n.t(msg.error), 'danger');
1027       if (msg.error == 'couldnt_find_that_username_or_email') {
1028         this.context.router.history.push('/');
1029       }
1030       this.setState({
1031         deleteAccountLoading: false,
1032         avatarLoading: false,
1033         userSettingsLoading: false,
1034       });
1035       return;
1036     } else if (res.op == UserOperation.GetUserDetails) {
1037       // Since the UserDetails contains posts/comments as well as some general user info we listen here as well
1038       // and set the parent state if it is not set or differs
1039       const data = res.data as UserDetailsResponse;
1040
1041       if (this.state.user.id !== data.user.id) {
1042         this.state.user = data.user;
1043         this.state.follows = data.follows;
1044         this.state.moderates = data.moderates;
1045
1046         if (this.isCurrentUser) {
1047           this.state.userSettingsForm.show_nsfw =
1048             UserService.Instance.user.show_nsfw;
1049           this.state.userSettingsForm.theme = UserService.Instance.user.theme
1050             ? UserService.Instance.user.theme
1051             : 'darkly';
1052           this.state.userSettingsForm.default_sort_type =
1053             UserService.Instance.user.default_sort_type;
1054           this.state.userSettingsForm.default_listing_type =
1055             UserService.Instance.user.default_listing_type;
1056           this.state.userSettingsForm.lang = UserService.Instance.user.lang;
1057           this.state.userSettingsForm.avatar = UserService.Instance.user.avatar;
1058           this.state.userSettingsForm.email = this.state.user.email;
1059           this.state.userSettingsForm.send_notifications_to_email = this.state.user.send_notifications_to_email;
1060           this.state.userSettingsForm.show_avatars =
1061             UserService.Instance.user.show_avatars;
1062           this.state.userSettingsForm.matrix_user_id = this.state.user.matrix_user_id;
1063         }
1064         this.state.loading = false;
1065         this.setState(this.state);
1066       }
1067     } else if (res.op == UserOperation.SaveUserSettings) {
1068       const data = res.data as LoginResponse;
1069       UserService.Instance.login(data);
1070       this.setState({
1071         userSettingsLoading: false,
1072       });
1073       window.scrollTo(0, 0);
1074     } else if (res.op == UserOperation.DeleteAccount) {
1075       this.setState({
1076         deleteAccountLoading: false,
1077         deleteAccountShowConfirm: false,
1078       });
1079       this.context.router.history.push('/');
1080     } else if (res.op == UserOperation.GetSite) {
1081       const data = res.data as GetSiteResponse;
1082       this.state.siteRes = data;
1083       this.setState(this.state);
1084     } else if (res.op == UserOperation.AddAdmin) {
1085       const data = res.data as AddAdminResponse;
1086       this.state.siteRes.admins = data.admins;
1087       this.setState(this.state);
1088     }
1089   }
1090 }