]> Untitled Git - lemmy.git/blob - ui/src/components/post-form.tsx
Squashed commit of the following:
[lemmy.git] / ui / src / components / post-form.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { PostListings } from './post-listings';
3 import { Subscription } from "rxjs";
4 import { retryWhen, delay, take } from 'rxjs/operators';
5 import { PostForm as PostFormI, Post, PostResponse, UserOperation, Community, ListCommunitiesResponse, ListCommunitiesForm, SortType, SearchForm, SearchType, SearchResponse } from '../interfaces';
6 import { WebSocketService, UserService } from '../services';
7 import { msgOp, getPageTitle, debounce, capitalizeFirstLetter } from '../utils';
8 import * as autosize from 'autosize';
9 import { i18n } from '../i18next';
10 import { T } from 'inferno-i18next';
11
12 interface PostFormProps {
13   post?: Post; // If a post is given, that means this is an edit
14   prevCommunityName?: string;
15   onCancel?(): any;
16   onCreate?(id: number): any;
17   onEdit?(post: Post): any;
18 }
19
20 interface PostFormState {
21   postForm: PostFormI;
22   communities: Array<Community>;
23   loading: boolean;
24   suggestedTitle: string;
25   suggestedPosts: Array<Post>;
26 }
27
28 export class PostForm extends Component<PostFormProps, PostFormState> {
29
30   private subscription: Subscription;
31   private emptyState: PostFormState = {
32     postForm: {
33       name: null,
34       nsfw: false,
35       auth: null,
36       community_id: null,
37       creator_id: (UserService.Instance.user) ? UserService.Instance.user.id : null,
38     },
39     communities: [],
40     loading: false,
41     suggestedTitle: undefined,
42     suggestedPosts: [],
43   }
44
45   constructor(props: any, context: any) {
46     super(props, context);
47
48     this.state = this.emptyState;
49
50     if (this.props.post) {
51       this.state.postForm = {
52         body: this.props.post.body,
53         name: this.props.post.name,
54         community_id: this.props.post.community_id,
55         edit_id: this.props.post.id,
56         creator_id: this.props.post.creator_id,
57         url: this.props.post.url,
58         nsfw: this.props.post.nsfw,
59         auth: null
60       }
61     }
62
63     this.subscription = WebSocketService.Instance.subject
64       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
65       .subscribe(
66         (msg) => this.parseMessage(msg),
67         (err) => console.error(err),
68         () => console.log('complete')
69       );
70
71       let listCommunitiesForm: ListCommunitiesForm = {
72         sort: SortType[SortType.TopAll],
73         limit: 9999,
74       }
75
76       WebSocketService.Instance.listCommunities(listCommunitiesForm);
77   }
78
79   componentDidMount() {
80     autosize(document.querySelectorAll('textarea'));
81   }
82
83   componentWillUnmount() {
84     this.subscription.unsubscribe();
85   }
86
87   render() {
88     return (
89       <div>
90         <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
91           <div class="form-group row">
92             <label class="col-sm-2 col-form-label"><T i18nKey="url">#</T></label>
93             <div class="col-sm-10">
94               <input type="url" class="form-control" value={this.state.postForm.url} onInput={linkEvent(this, debounce(this.handlePostUrlChange))} />
95               {this.state.suggestedTitle && 
96                 <div class="mt-1 text-muted small font-weight-bold pointer" onClick={linkEvent(this, this.copySuggestedTitle)}><T i18nKey="copy_suggested_title" interpolation={{title: this.state.suggestedTitle}}>#</T></div>
97               }
98             </div>
99           </div>
100           <div class="form-group row">
101             <label class="col-sm-2 col-form-label"><T i18nKey="title">#</T></label>
102             <div class="col-sm-10">
103               <textarea value={this.state.postForm.name} onInput={linkEvent(this, debounce(this.handlePostNameChange))} class="form-control" required rows={2} minLength={3} maxLength={100} />
104               {this.state.suggestedPosts.length > 0 && 
105                 <>
106                   <div class="my-1 text-muted small font-weight-bold"><T i18nKey="related_posts">#</T></div>
107                   <PostListings posts={this.state.suggestedPosts} />
108                 </>
109               }
110             </div>
111           </div>
112           <div class="form-group row">
113             <label class="col-sm-2 col-form-label"><T i18nKey="body">#</T></label>
114             <div class="col-sm-10">
115               <textarea value={this.state.postForm.body} onInput={linkEvent(this, this.handlePostBodyChange)} class="form-control" rows={4} maxLength={10000} />
116             </div>
117           </div>
118           {/* Cant change a community from an edit */}
119           {!this.props.post &&
120             <div class="form-group row">
121             <label class="col-sm-2 col-form-label"><T i18nKey="community">#</T></label>
122             <div class="col-sm-10">
123               <select class="form-control" value={this.state.postForm.community_id} onInput={linkEvent(this, this.handlePostCommunityChange)}>
124                 {this.state.communities.map(community =>
125                   <option value={community.id}>{community.name}</option>
126                 )}
127               </select>
128             </div>
129             </div>
130             }
131           <div class="form-group row">
132             <div class="col-sm-10">
133               <div class="form-check">
134                 <input class="form-check-input" type="checkbox" checked={this.state.postForm.nsfw} onChange={linkEvent(this, this.handlePostNsfwChange)}/>
135                 <label class="form-check-label"><T i18nKey="nsfw">#</T></label>
136               </div>
137             </div>
138           </div>
139           <div class="form-group row">
140             <div class="col-sm-10">
141               <button type="submit" class="btn btn-secondary mr-2">
142               {this.state.loading ? 
143               <svg class="icon icon-spinner spin"><use xlinkHref="#icon-spinner"></use></svg> : 
144               this.props.post ? capitalizeFirstLetter(i18n.t('save')) : capitalizeFirstLetter(i18n.t('create'))}</button>
145               {this.props.post && <button type="button" class="btn btn-secondary" onClick={linkEvent(this, this.handleCancel)}><T i18nKey="cancel">#</T></button>}
146             </div>
147           </div>
148         </form>
149       </div>
150     );
151   }
152
153   handlePostSubmit(i: PostForm, event: any) {
154     event.preventDefault();
155     if (i.props.post) {
156       WebSocketService.Instance.editPost(i.state.postForm);
157     } else {
158       WebSocketService.Instance.createPost(i.state.postForm);
159     }
160     i.state.loading = true;
161     i.setState(i.state);
162   }
163
164   copySuggestedTitle(i: PostForm) {
165     i.state.postForm.name = i.state.suggestedTitle;
166     i.state.suggestedTitle = undefined;
167     i.setState(i.state);
168   }
169
170   handlePostUrlChange(i: PostForm, event: any) {
171     i.state.postForm.url = event.target.value;
172     getPageTitle(i.state.postForm.url).then(d => {
173       i.state.suggestedTitle = d;
174       i.setState(i.state);
175     });
176     i.setState(i.state);
177   }
178
179   handlePostNameChange(i: PostForm, event: any) {
180     i.state.postForm.name = event.target.value;
181     let form: SearchForm = {
182       q: i.state.postForm.name,
183       type_: SearchType[SearchType.Posts],
184       sort: SortType[SortType.TopAll],
185       community_id: i.state.postForm.community_id,
186       page: 1,
187       limit: 6,
188     };
189
190     if (i.state.postForm.name !== '') {
191       WebSocketService.Instance.search(form);
192     } else {
193       i.state.suggestedPosts = [];
194     }
195
196     i.setState(i.state);
197   }
198
199   handlePostBodyChange(i: PostForm, event: any) {
200     i.state.postForm.body = event.target.value;
201     i.setState(i.state);
202   }
203
204   handlePostCommunityChange(i: PostForm, event: any) {
205     i.state.postForm.community_id = Number(event.target.value);
206     i.setState(i.state);
207   }
208
209   handlePostNsfwChange(i: PostForm, event: any) {
210     i.state.postForm.nsfw = event.target.checked;
211     i.setState(i.state);
212   }
213
214   handleCancel(i: PostForm) {
215     i.props.onCancel();
216   }
217
218   parseMessage(msg: any) {
219     let op: UserOperation = msgOp(msg);
220     if (msg.error) {
221       alert(i18n.t(msg.error));
222       this.state.loading = false;
223       this.setState(this.state);
224       return;
225     } else if (op == UserOperation.ListCommunities) {
226       let res: ListCommunitiesResponse = msg;
227       this.state.communities = res.communities;
228       if (this.props.post) {
229         this.state.postForm.community_id = this.props.post.community_id;
230       } else if (this.props.prevCommunityName) {
231         let foundCommunityId = res.communities.find(r => r.name == this.props.prevCommunityName).id;
232         this.state.postForm.community_id = foundCommunityId;
233       } else {
234         this.state.postForm.community_id = res.communities[0].id;
235       }
236       this.setState(this.state);
237     } else if (op == UserOperation.CreatePost) {
238       this.state.loading = false;
239       let res: PostResponse = msg;
240       this.props.onCreate(res.post.id);
241     } else if (op == UserOperation.EditPost) {
242       this.state.loading = false;
243       let res: PostResponse = msg;
244       this.props.onEdit(res.post);
245     } else if (op == UserOperation.Search) {
246       let res: SearchResponse = msg;
247       this.state.suggestedPosts = res.posts;
248       this.setState(this.state);
249     }
250   }
251
252 }
253
254