]> Untitled Git - lemmy.git/blob - ui/src/components/post-form.tsx
Adding preview, image upload, and formatting help to comment and post
[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, PostFormParams, Post, PostResponse, UserOperation, Community, ListCommunitiesResponse, ListCommunitiesForm, SortType, SearchForm, SearchType, SearchResponse } from '../interfaces';
6 import { WebSocketService, UserService } from '../services';
7 import { msgOp, getPageTitle, debounce, validURL, capitalizeFirstLetter, imageUploadUrl, markdownHelpUrl, mdToHtml } 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   params?: PostFormParams;
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   previewMode: boolean;
25   suggestedTitle: string;
26   suggestedPosts: Array<Post>;
27   crossPosts: Array<Post>;
28 }
29
30 export class PostForm extends Component<PostFormProps, PostFormState> {
31
32   private subscription: Subscription;
33   private emptyState: PostFormState = {
34     postForm: {
35       name: null,
36       nsfw: false,
37       auth: null,
38       community_id: null,
39       creator_id: (UserService.Instance.user) ? UserService.Instance.user.id : null,
40     },
41     communities: [],
42     loading: false,
43     previewMode: false,
44     suggestedTitle: undefined,
45     suggestedPosts: [],
46     crossPosts: [],
47   }
48
49   constructor(props: any, context: any) {
50     super(props, context);
51
52     this.state = this.emptyState;
53
54     if (this.props.post) {
55       this.state.postForm = {
56         body: this.props.post.body,
57         name: this.props.post.name,
58         community_id: this.props.post.community_id,
59         edit_id: this.props.post.id,
60         creator_id: this.props.post.creator_id,
61         url: this.props.post.url,
62         nsfw: this.props.post.nsfw,
63         auth: null
64       }
65     }
66
67     if (this.props.params) {
68       this.state.postForm.name = this.props.params.name;
69       if (this.props.params.url) {
70         this.state.postForm.url = this.props.params.url;
71       }
72       if (this.props.params.body) {
73         this.state.postForm.body = this.props.params.body;
74       }
75     }
76
77     this.subscription = WebSocketService.Instance.subject
78     .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
79     .subscribe(
80       (msg) => this.parseMessage(msg),
81         (err) => console.error(err),
82         () => console.log('complete')
83     );
84
85     let listCommunitiesForm: ListCommunitiesForm = {
86       sort: SortType[SortType.TopAll],
87       limit: 9999,
88     }
89
90     WebSocketService.Instance.listCommunities(listCommunitiesForm);
91   }
92
93   componentDidMount() {
94     autosize(document.querySelectorAll('textarea'));
95   }
96
97   componentWillUnmount() {
98     this.subscription.unsubscribe();
99   }
100
101   render() {
102     return (
103       <div>
104         <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
105           <div class="form-group row">
106             <label class="col-sm-2 col-form-label"><T i18nKey="url">#</T></label>
107             <div class="col-sm-10">
108               <input type="url" class="form-control" value={this.state.postForm.url} onInput={linkEvent(this, this.handlePostUrlChange)} />
109               {this.state.suggestedTitle && 
110                 <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>
111               }
112               <a href={imageUploadUrl} target="_blank" class="d-inline-block mr-2 float-right text-muted small font-weight-bold"><T i18nKey="upload_image">#</T></a>
113               {this.state.crossPosts.length > 0 && 
114                 <>
115                   <div class="my-1 text-muted small font-weight-bold"><T i18nKey="cross_posts">#</T></div>
116                   <PostListings showCommunity posts={this.state.crossPosts} />
117                 </>
118               }
119             </div>
120           </div>
121           <div class="form-group row">
122             <label class="col-sm-2 col-form-label"><T i18nKey="title">#</T></label>
123             <div class="col-sm-10">
124               <textarea value={this.state.postForm.name} onInput={linkEvent(this, this.handlePostNameChange)} class="form-control" required rows={2} minLength={3} maxLength={100} />
125               {this.state.suggestedPosts.length > 0 && 
126                 <>
127                   <div class="my-1 text-muted small font-weight-bold"><T i18nKey="related_posts">#</T></div>
128                   <PostListings posts={this.state.suggestedPosts} />
129                 </>
130               }
131             </div>
132           </div>
133           <div class="form-group row">
134             <label class="col-sm-2 col-form-label"><T i18nKey="body">#</T></label>
135             <div class="col-sm-10">
136               <textarea value={this.state.postForm.body} onInput={linkEvent(this, this.handlePostBodyChange)} className={`form-control ${this.state.previewMode && 'd-none'}`} rows={4} maxLength={10000} />
137               {this.state.previewMode && 
138                 <div className="md-div" dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)} />
139               }
140               {this.state.postForm.body &&
141                 <button className={`mt-1 mr-2 btn btn-sm btn-secondary ${this.state.previewMode && 'active'}`} onClick={linkEvent(this, this.handlePreviewToggle)}><T i18nKey="preview">#</T></button>
142               }
143               <a href={markdownHelpUrl} target="_blank" class="d-inline-block float-right text-muted small font-weight-bold"><T i18nKey="formatting_help">#</T></a>
144             </div>
145           </div>
146           {!this.props.post &&
147             <div class="form-group row">
148             <label class="col-sm-2 col-form-label"><T i18nKey="community">#</T></label>
149             <div class="col-sm-10">
150               <select class="form-control" value={this.state.postForm.community_id} onInput={linkEvent(this, this.handlePostCommunityChange)}>
151                 {this.state.communities.map(community =>
152                   <option value={community.id}>{community.name}</option>
153                 )}
154               </select>
155             </div>
156             </div>
157             }
158           <div class="form-group row">
159             <div class="col-sm-10">
160               <div class="form-check">
161                 <input class="form-check-input" type="checkbox" checked={this.state.postForm.nsfw} onChange={linkEvent(this, this.handlePostNsfwChange)}/>
162                 <label class="form-check-label"><T i18nKey="nsfw">#</T></label>
163               </div>
164             </div>
165           </div>
166           <div class="form-group row">
167             <div class="col-sm-10">
168               <button type="submit" class="btn btn-secondary mr-2">
169               {this.state.loading ? 
170               <svg class="icon icon-spinner spin"><use xlinkHref="#icon-spinner"></use></svg> : 
171               this.props.post ? capitalizeFirstLetter(i18n.t('save')) : capitalizeFirstLetter(i18n.t('create'))}</button>
172               {this.props.post && <button type="button" class="btn btn-secondary" onClick={linkEvent(this, this.handleCancel)}><T i18nKey="cancel">#</T></button>}
173             </div>
174           </div>
175         </form>
176       </div>
177     );
178   }
179
180   handlePostSubmit(i: PostForm, event: any) {
181     event.preventDefault();
182     if (i.props.post) {
183       WebSocketService.Instance.editPost(i.state.postForm);
184     } else {
185       WebSocketService.Instance.createPost(i.state.postForm);
186     }
187     i.state.loading = true;
188     i.setState(i.state);
189   }
190
191   copySuggestedTitle(i: PostForm) {
192     i.state.postForm.name = i.state.suggestedTitle;
193     i.state.suggestedTitle = undefined;
194     i.setState(i.state);
195   }
196
197   handlePostUrlChange(i: PostForm, event: any) {
198     i.state.postForm.url = event.target.value;
199     if (validURL(i.state.postForm.url)) {
200
201       let form: SearchForm = {
202         q: i.state.postForm.url,
203         type_: SearchType[SearchType.Url],
204         sort: SortType[SortType.TopAll],
205         page: 1,
206         limit: 6,
207       };
208
209       WebSocketService.Instance.search(form);
210
211       // Fetch the page title
212       getPageTitle(i.state.postForm.url).then(d => {
213         i.state.suggestedTitle = d;
214         i.setState(i.state);
215       });
216     } else {
217       i.state.suggestedTitle = undefined;
218       i.state.crossPosts = [];
219     }
220
221     i.setState(i.state);
222   }
223
224   handlePostNameChange(i: PostForm, event: any) {
225     i.state.postForm.name = event.target.value;
226     let form: SearchForm = {
227       q: i.state.postForm.name,
228       type_: SearchType[SearchType.Posts],
229       sort: SortType[SortType.TopAll],
230       community_id: i.state.postForm.community_id,
231       page: 1,
232       limit: 6,
233     };
234
235     if (i.state.postForm.name !== '') {
236       WebSocketService.Instance.search(form);
237     } else {
238       i.state.suggestedPosts = [];
239     }
240
241     i.setState(i.state);
242   }
243
244   handlePostBodyChange(i: PostForm, event: any) {
245     i.state.postForm.body = event.target.value;
246     i.setState(i.state);
247   }
248
249   handlePostCommunityChange(i: PostForm, event: any) {
250     i.state.postForm.community_id = Number(event.target.value);
251     i.setState(i.state);
252   }
253
254   handlePostNsfwChange(i: PostForm, event: any) {
255     i.state.postForm.nsfw = event.target.checked;
256     i.setState(i.state);
257   }
258
259   handleCancel(i: PostForm) {
260     i.props.onCancel();
261   }
262
263   handlePreviewToggle(i: PostForm, event: any) {
264     event.preventDefault();
265     i.state.previewMode = !i.state.previewMode;
266     i.setState(i.state);
267   }
268
269   parseMessage(msg: any) {
270     let op: UserOperation = msgOp(msg);
271     if (msg.error) {
272       alert(i18n.t(msg.error));
273       this.state.loading = false;
274       this.setState(this.state);
275       return;
276     } else if (op == UserOperation.ListCommunities) {
277       let res: ListCommunitiesResponse = msg;
278       this.state.communities = res.communities;
279       if (this.props.post) {
280         this.state.postForm.community_id = this.props.post.community_id;
281       } else if (this.props.params && this.props.params.community) {
282         let foundCommunityId = res.communities.find(r => r.name == this.props.params.community).id;
283         this.state.postForm.community_id = foundCommunityId;
284       } else {
285         this.state.postForm.community_id = res.communities[0].id;
286       }
287       this.setState(this.state);
288     } else if (op == UserOperation.CreatePost) {
289       this.state.loading = false;
290       let res: PostResponse = msg;
291       this.props.onCreate(res.post.id);
292     } else if (op == UserOperation.EditPost) {
293       this.state.loading = false;
294       let res: PostResponse = msg;
295       this.props.onEdit(res.post);
296     } else if (op == UserOperation.Search) {
297       let res: SearchResponse = msg;
298       
299       if (res.type_ == SearchType[SearchType.Posts]) {
300         this.state.suggestedPosts = res.posts;
301       } else if (res.type_ == SearchType[SearchType.Url]) {
302         this.state.crossPosts = res.posts;
303       }
304       this.setState(this.state);
305     }
306   }
307
308 }
309
310