]> Untitled Git - lemmy.git/blob - ui/src/components/post-form.tsx
Use twemoji style for emoji picker.
[lemmy.git] / ui / src / components / post-form.tsx
1 import { Component, linkEvent } from 'inferno';
2 import { Prompt } from 'inferno-router';
3 import { PostListings } from './post-listings';
4 import { Subscription } from 'rxjs';
5 import { retryWhen, delay, take } from 'rxjs/operators';
6 import {
7   PostForm as PostFormI,
8   PostFormParams,
9   Post,
10   PostResponse,
11   UserOperation,
12   Community,
13   ListCommunitiesResponse,
14   ListCommunitiesForm,
15   SortType,
16   SearchForm,
17   SearchType,
18   SearchResponse,
19   GetSiteResponse,
20   WebSocketJsonResponse,
21 } from '../interfaces';
22 import { WebSocketService, UserService } from '../services';
23 import {
24   wsJsonToRes,
25   getPageTitle,
26   validURL,
27   capitalizeFirstLetter,
28   markdownHelpUrl,
29   archiveUrl,
30   mdToHtml,
31   debounce,
32   isImage,
33   toast,
34   randomStr,
35   setupTribute,
36   setupTippy,
37   emojiPicker,
38 } from '../utils';
39 import autosize from 'autosize';
40 import Tribute from 'tributejs/src/Tribute.js';
41 import emojiShortName from 'emoji-short-name';
42 import Selectr from 'mobius1-selectr';
43 import { i18n } from '../i18next';
44
45 const MAX_POST_TITLE_LENGTH = 200;
46
47 interface PostFormProps {
48   post?: Post; // If a post is given, that means this is an edit
49   params?: PostFormParams;
50   onCancel?(): any;
51   onCreate?(id: number): any;
52   onEdit?(post: Post): any;
53 }
54
55 interface PostFormState {
56   postForm: PostFormI;
57   communities: Array<Community>;
58   loading: boolean;
59   imageLoading: boolean;
60   previewMode: boolean;
61   suggestedTitle: string;
62   suggestedPosts: Array<Post>;
63   crossPosts: Array<Post>;
64   enable_nsfw: boolean;
65 }
66
67 export class PostForm extends Component<PostFormProps, PostFormState> {
68   private id = `post-form-${randomStr()}`;
69   private tribute: Tribute;
70   private subscription: Subscription;
71   private emptyState: PostFormState = {
72     postForm: {
73       name: null,
74       nsfw: false,
75       auth: null,
76       community_id: null,
77       creator_id: UserService.Instance.user
78         ? UserService.Instance.user.id
79         : null,
80     },
81     communities: [],
82     loading: false,
83     imageLoading: false,
84     previewMode: false,
85     suggestedTitle: undefined,
86     suggestedPosts: [],
87     crossPosts: [],
88     enable_nsfw: undefined,
89   };
90
91   constructor(props: any, context: any) {
92     super(props, context);
93     this.fetchSimilarPosts = debounce(this.fetchSimilarPosts).bind(this);
94     this.fetchPageTitle = debounce(this.fetchPageTitle).bind(this);
95
96     this.tribute = setupTribute();
97     this.setupEmojiPicker();
98
99     this.state = this.emptyState;
100
101     if (this.props.post) {
102       this.state.postForm = {
103         body: this.props.post.body,
104         // NOTE: debouncing breaks both these for some reason, unless you use defaultValue
105         name: this.props.post.name,
106         community_id: this.props.post.community_id,
107         edit_id: this.props.post.id,
108         creator_id: this.props.post.creator_id,
109         url: this.props.post.url,
110         nsfw: this.props.post.nsfw,
111         auth: null,
112       };
113     }
114
115     if (this.props.params) {
116       this.state.postForm.name = this.props.params.name;
117       if (this.props.params.url) {
118         this.state.postForm.url = this.props.params.url;
119       }
120       if (this.props.params.body) {
121         this.state.postForm.body = this.props.params.body;
122       }
123     }
124
125     this.subscription = WebSocketService.Instance.subject
126       .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
127       .subscribe(
128         msg => this.parseMessage(msg),
129         err => console.error(err),
130         () => console.log('complete')
131       );
132
133     let listCommunitiesForm: ListCommunitiesForm = {
134       sort: SortType[SortType.TopAll],
135       limit: 9999,
136     };
137
138     WebSocketService.Instance.listCommunities(listCommunitiesForm);
139     WebSocketService.Instance.getSite();
140   }
141
142   componentDidMount() {
143     var textarea: any = document.getElementById(this.id);
144     autosize(textarea);
145     this.tribute.attach(textarea);
146     textarea.addEventListener('tribute-replaced', () => {
147       this.state.postForm.body = textarea.value;
148       this.setState(this.state);
149       autosize.update(textarea);
150     });
151     setupTippy();
152   }
153
154   componentWillUnmount() {
155     this.subscription.unsubscribe();
156   }
157
158   render() {
159     return (
160       <div>
161         <Prompt
162           when={
163             !this.state.loading &&
164             (this.state.postForm.name ||
165               this.state.postForm.url ||
166               this.state.postForm.body)
167           }
168           message={i18n.t('block_leaving')}
169         />
170         <form onSubmit={linkEvent(this, this.handlePostSubmit)}>
171           <div class="form-group row">
172             <label class="col-sm-2 col-form-label" htmlFor="post-url">
173               {i18n.t('url')}
174             </label>
175             <div class="col-sm-10">
176               <input
177                 type="url"
178                 id="post-url"
179                 class="form-control"
180                 value={this.state.postForm.url}
181                 onInput={linkEvent(this, this.handlePostUrlChange)}
182                 onPaste={linkEvent(this, this.handleImageUploadPaste)}
183               />
184               {this.state.suggestedTitle && (
185                 <div
186                   class="mt-1 text-muted small font-weight-bold pointer"
187                   onClick={linkEvent(this, this.copySuggestedTitle)}
188                 >
189                   {i18n.t('copy_suggested_title', {
190                     title: this.state.suggestedTitle,
191                   })}
192                 </div>
193               )}
194               <form>
195                 <label
196                   htmlFor="file-upload"
197                   className={`${UserService.Instance.user &&
198                     'pointer'} d-inline-block float-right text-muted font-weight-bold`}
199                   data-tippy-content={i18n.t('upload_image')}
200                 >
201                   <svg class="icon icon-inline">
202                     <use xlinkHref="#icon-image"></use>
203                   </svg>
204                 </label>
205                 <input
206                   id="file-upload"
207                   type="file"
208                   accept="image/*,video/*"
209                   name="file"
210                   class="d-none"
211                   disabled={!UserService.Instance.user}
212                   onChange={linkEvent(this, this.handleImageUpload)}
213                 />
214               </form>
215               {validURL(this.state.postForm.url) && (
216                 <a
217                   href={`${archiveUrl}/?run=1&url=${encodeURIComponent(
218                     this.state.postForm.url
219                   )}`}
220                   target="_blank"
221                   class="mr-2 d-inline-block float-right text-muted small font-weight-bold"
222                 >
223                   {i18n.t('archive_link')}
224                 </a>
225               )}
226               {this.state.imageLoading && (
227                 <svg class="icon icon-spinner spin">
228                   <use xlinkHref="#icon-spinner"></use>
229                 </svg>
230               )}
231               {isImage(this.state.postForm.url) && (
232                 <img src={this.state.postForm.url} class="img-fluid" />
233               )}
234               {this.state.crossPosts.length > 0 && (
235                 <>
236                   <div class="my-1 text-muted small font-weight-bold">
237                     {i18n.t('cross_posts')}
238                   </div>
239                   <PostListings showCommunity posts={this.state.crossPosts} />
240                 </>
241               )}
242             </div>
243           </div>
244           <div class="form-group row">
245             <label class="col-sm-2 col-form-label" htmlFor="post-title">
246               {i18n.t('title')}
247             </label>
248             <div class="col-sm-10">
249               <textarea
250                 value={this.state.postForm.name}
251                 id="post-title"
252                 onInput={linkEvent(this, this.handlePostNameChange)}
253                 class="form-control"
254                 required
255                 rows={2}
256                 minLength={3}
257                 maxLength={MAX_POST_TITLE_LENGTH}
258               />
259               {this.state.suggestedPosts.length > 0 && (
260                 <>
261                   <div class="my-1 text-muted small font-weight-bold">
262                     {i18n.t('related_posts')}
263                   </div>
264                   <PostListings posts={this.state.suggestedPosts} />
265                 </>
266               )}
267             </div>
268           </div>
269
270           <div class="form-group row">
271             <label class="col-sm-2 col-form-label" htmlFor={this.id}>
272               {i18n.t('body')}
273             </label>
274             <div class="col-sm-10">
275               <textarea
276                 id={this.id}
277                 value={this.state.postForm.body}
278                 onInput={linkEvent(this, this.handlePostBodyChange)}
279                 className={`form-control ${this.state.previewMode && 'd-none'}`}
280                 rows={4}
281                 maxLength={10000}
282               />
283               {this.state.previewMode && (
284                 <div
285                   className="md-div"
286                   dangerouslySetInnerHTML={mdToHtml(this.state.postForm.body)}
287                 />
288               )}
289               {this.state.postForm.body && (
290                 <button
291                   className={`mt-1 mr-2 btn btn-sm btn-secondary ${this.state
292                     .previewMode && 'active'}`}
293                   onClick={linkEvent(this, this.handlePreviewToggle)}
294                 >
295                   {i18n.t('preview')}
296                 </button>
297               )}
298               <a
299                 href={markdownHelpUrl}
300                 target="_blank"
301                 class="d-inline-block float-right text-muted font-weight-bold"
302                 title={i18n.t('formatting_help')}
303               >
304                 <svg class="icon icon-inline">
305                   <use xlinkHref="#icon-help-circle"></use>
306                 </svg>
307               </a>
308               <span
309                 onClick={linkEvent(this, this.handleEmojiPickerClick)}
310                 class="pointer unselectable d-inline-block mr-3 float-right text-muted font-weight-bold"
311                 data-tippy-content={i18n.t('emoji_picker')}
312               >
313                 <svg class="icon icon-inline">
314                   <use xlinkHref="#icon-smile"></use>
315                 </svg>
316               </span>
317             </div>
318           </div>
319           {!this.props.post && (
320             <div class="form-group row">
321               <label class="col-sm-2 col-form-label" htmlFor="post-community">
322                 {i18n.t('community')}
323               </label>
324               <div class="col-sm-10">
325                 <select
326                   class="form-control"
327                   id="post-community"
328                   value={this.state.postForm.community_id}
329                   onInput={linkEvent(this, this.handlePostCommunityChange)}
330                 >
331                   {this.state.communities.map(community => (
332                     <option value={community.id}>{community.name}</option>
333                   ))}
334                 </select>
335               </div>
336             </div>
337           )}
338           {this.state.enable_nsfw && (
339             <div class="form-group row">
340               <div class="col-sm-10">
341                 <div class="form-check">
342                   <input
343                     class="form-check-input"
344                     id="post-nsfw"
345                     type="checkbox"
346                     checked={this.state.postForm.nsfw}
347                     onChange={linkEvent(this, this.handlePostNsfwChange)}
348                   />
349                   <label class="form-check-label" htmlFor="post-nsfw">
350                     {i18n.t('nsfw')}
351                   </label>
352                 </div>
353               </div>
354             </div>
355           )}
356           <div class="form-group row">
357             <div class="col-sm-10">
358               <button type="submit" class="btn btn-secondary mr-2">
359                 {this.state.loading ? (
360                   <svg class="icon icon-spinner spin">
361                     <use xlinkHref="#icon-spinner"></use>
362                   </svg>
363                 ) : this.props.post ? (
364                   capitalizeFirstLetter(i18n.t('save'))
365                 ) : (
366                   capitalizeFirstLetter(i18n.t('create'))
367                 )}
368               </button>
369               {this.props.post && (
370                 <button
371                   type="button"
372                   class="btn btn-secondary"
373                   onClick={linkEvent(this, this.handleCancel)}
374                 >
375                   {i18n.t('cancel')}
376                 </button>
377               )}
378             </div>
379           </div>
380         </form>
381       </div>
382     );
383   }
384
385   setupEmojiPicker() {
386     emojiPicker.on('emoji', twemojiHtmlStr => {
387       if (this.state.postForm.body == null) {
388         this.state.postForm.body = '';
389       }
390       var el = document.createElement('div');
391       el.innerHTML = twemojiHtmlStr;
392       let nativeUnicode = (el.childNodes[0] as HTMLElement).getAttribute('alt');
393       let shortName = `:${emojiShortName[nativeUnicode]}:`;
394       this.state.postForm.body += shortName;
395       this.setState(this.state);
396     });
397   }
398
399   handlePostSubmit(i: PostForm, event: any) {
400     event.preventDefault();
401     if (i.props.post) {
402       WebSocketService.Instance.editPost(i.state.postForm);
403     } else {
404       WebSocketService.Instance.createPost(i.state.postForm);
405     }
406     i.state.loading = true;
407     i.setState(i.state);
408   }
409
410   copySuggestedTitle(i: PostForm) {
411     i.state.postForm.name = i.state.suggestedTitle.substring(
412       0,
413       MAX_POST_TITLE_LENGTH
414     );
415     i.state.suggestedTitle = undefined;
416     i.setState(i.state);
417   }
418
419   handlePostUrlChange(i: PostForm, event: any) {
420     i.state.postForm.url = event.target.value;
421     i.setState(i.state);
422     i.fetchPageTitle();
423   }
424
425   fetchPageTitle() {
426     if (validURL(this.state.postForm.url)) {
427       let form: SearchForm = {
428         q: this.state.postForm.url,
429         type_: SearchType[SearchType.Url],
430         sort: SortType[SortType.TopAll],
431         page: 1,
432         limit: 6,
433       };
434
435       WebSocketService.Instance.search(form);
436
437       // Fetch the page title
438       getPageTitle(this.state.postForm.url).then(d => {
439         this.state.suggestedTitle = d;
440         this.setState(this.state);
441       });
442     } else {
443       this.state.suggestedTitle = undefined;
444       this.state.crossPosts = [];
445     }
446   }
447
448   handlePostNameChange(i: PostForm, event: any) {
449     i.state.postForm.name = event.target.value;
450     i.setState(i.state);
451     i.fetchSimilarPosts();
452   }
453
454   fetchSimilarPosts() {
455     let form: SearchForm = {
456       q: this.state.postForm.name,
457       type_: SearchType[SearchType.Posts],
458       sort: SortType[SortType.TopAll],
459       community_id: this.state.postForm.community_id,
460       page: 1,
461       limit: 6,
462     };
463
464     if (this.state.postForm.name !== '') {
465       WebSocketService.Instance.search(form);
466     } else {
467       this.state.suggestedPosts = [];
468     }
469
470     this.setState(this.state);
471   }
472
473   handlePostBodyChange(i: PostForm, event: any) {
474     i.state.postForm.body = event.target.value;
475     i.setState(i.state);
476   }
477
478   handlePostCommunityChange(i: PostForm, event: any) {
479     i.state.postForm.community_id = Number(event.target.value);
480     i.setState(i.state);
481   }
482
483   handlePostNsfwChange(i: PostForm, event: any) {
484     i.state.postForm.nsfw = event.target.checked;
485     i.setState(i.state);
486   }
487
488   handleCancel(i: PostForm) {
489     i.props.onCancel();
490   }
491
492   handlePreviewToggle(i: PostForm, event: any) {
493     event.preventDefault();
494     i.state.previewMode = !i.state.previewMode;
495     i.setState(i.state);
496   }
497
498   handleImageUploadPaste(i: PostForm, event: any) {
499     let image = event.clipboardData.files[0];
500     if (image) {
501       i.handleImageUpload(i, image);
502     }
503   }
504
505   handleImageUpload(i: PostForm, event: any) {
506     let file: any;
507     if (event.target) {
508       event.preventDefault();
509       file = event.target.files[0];
510     } else {
511       file = event;
512     }
513
514     const imageUploadUrl = `/pictshare/api/upload.php`;
515     const formData = new FormData();
516     formData.append('file', file);
517
518     i.state.imageLoading = true;
519     i.setState(i.state);
520
521     fetch(imageUploadUrl, {
522       method: 'POST',
523       body: formData,
524     })
525       .then(res => res.json())
526       .then(res => {
527         let url = `${window.location.origin}/pictshare/${encodeURI(res.url)}`;
528         if (res.filetype == 'mp4') {
529           url += '/raw';
530         }
531         i.state.postForm.url = url;
532         i.state.imageLoading = false;
533         i.setState(i.state);
534       })
535       .catch(error => {
536         i.state.imageLoading = false;
537         i.setState(i.state);
538         toast(error, 'danger');
539       });
540   }
541
542   handleEmojiPickerClick(_i: PostForm, event: any) {
543     emojiPicker.togglePicker(event.target);
544   }
545
546   parseMessage(msg: WebSocketJsonResponse) {
547     let res = wsJsonToRes(msg);
548     if (msg.error) {
549       toast(i18n.t(msg.error), 'danger');
550       this.state.loading = false;
551       this.setState(this.state);
552       return;
553     } else if (res.op == UserOperation.ListCommunities) {
554       let data = res.data as ListCommunitiesResponse;
555       this.state.communities = data.communities;
556       if (this.props.post) {
557         this.state.postForm.community_id = this.props.post.community_id;
558       } else if (this.props.params && this.props.params.community) {
559         let foundCommunityId = data.communities.find(
560           r => r.name == this.props.params.community
561         ).id;
562         this.state.postForm.community_id = foundCommunityId;
563       } else {
564         this.state.postForm.community_id = data.communities[0].id;
565       }
566       this.setState(this.state);
567
568       // Set up select searching
569       let selectId: any = document.getElementById('post-community');
570       if (selectId) {
571         let selector = new Selectr(selectId, { nativeDropdown: false });
572         selector.on('selectr.select', option => {
573           this.state.postForm.community_id = Number(option.value);
574         });
575       }
576     } else if (res.op == UserOperation.CreatePost) {
577       let data = res.data as PostResponse;
578       if (data.post.creator_id == UserService.Instance.user.id) {
579         this.state.loading = false;
580         this.props.onCreate(data.post.id);
581       }
582     } else if (res.op == UserOperation.EditPost) {
583       let data = res.data as PostResponse;
584       if (data.post.creator_id == UserService.Instance.user.id) {
585         this.state.loading = false;
586         this.props.onEdit(data.post);
587       }
588     } else if (res.op == UserOperation.Search) {
589       let data = res.data as SearchResponse;
590
591       if (data.type_ == SearchType[SearchType.Posts]) {
592         this.state.suggestedPosts = data.posts;
593       } else if (data.type_ == SearchType[SearchType.Url]) {
594         this.state.crossPosts = data.posts;
595       }
596       this.setState(this.state);
597     } else if (res.op == UserOperation.GetSite) {
598       let data = res.data as GetSiteResponse;
599       this.state.enable_nsfw = data.site.enable_nsfw;
600       this.setState(this.state);
601     }
602   }
603 }