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