]> Untitled Git - lemmy.git/blob - ui/src/components/create-community.tsx
Merge branch 'master' into jmarthernandez-remove-karma-from-search
[lemmy.git] / ui / src / components / create-community.tsx
1 import { Component } from 'inferno';
2 import { Subscription } from 'rxjs';
3 import { retryWhen, delay, take } from 'rxjs/operators';
4 import { CommunityForm } from './community-form';
5 import {
6   Community,
7   UserOperation,
8   WebSocketJsonResponse,
9   GetSiteResponse,
10 } from '../interfaces';
11 import { toast, wsJsonToRes } from '../utils';
12 import { WebSocketService, UserService } from '../services';
13 import { i18n } from '../i18next';
14
15 interface CreateCommunityState {
16   enableNsfw: boolean;
17 }
18
19 export class CreateCommunity extends Component<any, CreateCommunityState> {
20   private subscription: Subscription;
21   private emptyState: CreateCommunityState = {
22     enableNsfw: null,
23   };
24   constructor(props: any, context: any) {
25     super(props, context);
26     this.handleCommunityCreate = this.handleCommunityCreate.bind(this);
27     this.state = this.emptyState;
28
29     if (!UserService.Instance.user) {
30       toast(i18n.t('not_logged_in'), 'danger');
31       this.context.router.history.push(`/login`);
32     }
33
34     this.subscription = WebSocketService.Instance.subject
35       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
36       .subscribe(
37         msg => this.parseMessage(msg),
38         err => console.error(err),
39         () => console.log('complete')
40       );
41
42     WebSocketService.Instance.getSite();
43   }
44
45   componentWillUnmount() {
46     this.subscription.unsubscribe();
47   }
48
49   render() {
50     return (
51       <div class="container">
52         <div class="row">
53           <div class="col-12 col-lg-6 offset-lg-3 mb-4">
54             <h5>{i18n.t('create_community')}</h5>
55             <CommunityForm
56               onCreate={this.handleCommunityCreate}
57               enableNsfw={this.state.enableNsfw}
58             />
59           </div>
60         </div>
61       </div>
62     );
63   }
64
65   handleCommunityCreate(community: Community) {
66     this.props.history.push(`/c/${community.name}`);
67   }
68
69   parseMessage(msg: WebSocketJsonResponse) {
70     console.log(msg);
71     let res = wsJsonToRes(msg);
72     if (msg.error) {
73       toast(i18n.t(msg.error), 'danger');
74       return;
75     } else if (res.op == UserOperation.GetSite) {
76       let data = res.data as GetSiteResponse;
77       this.state.enableNsfw = data.site.enable_nsfw;
78       this.setState(this.state);
79       document.title = `${i18n.t('create_community')} - ${data.site.name}`;
80     }
81   }
82 }