]> Untitled Git - lemmy.git/blob - ui/src/components/comment-form.tsx
Squashed commit of the following:
[lemmy.git] / ui / src / components / comment-form.tsx
1 import { Component, linkEvent } from 'inferno';
2 import {
3   CommentNode as CommentNodeI,
4   CommentForm as CommentFormI,
5   SearchForm,
6   SearchType,
7   SortType,
8   UserOperation,
9   SearchResponse,
10 } from '../interfaces';
11 import { Subscription } from 'rxjs';
12 import {
13   wsJsonToRes,
14   capitalizeFirstLetter,
15   mentionDropdownFetchLimit,
16   mdToHtml,
17   randomStr,
18   markdownHelpUrl,
19   toast,
20 } from '../utils';
21 import { WebSocketService, UserService } from '../services';
22 import autosize from 'autosize';
23 import { i18n } from '../i18next';
24 import { T } from 'inferno-i18next';
25 import Tribute from 'tributejs/src/Tribute.js';
26 import emojiShortName from 'emoji-short-name';
27
28 interface CommentFormProps {
29   postId?: number;
30   node?: CommentNodeI;
31   onReplyCancel?(): any;
32   edit?: boolean;
33   disabled?: boolean;
34 }
35
36 interface CommentFormState {
37   commentForm: CommentFormI;
38   buttonTitle: string;
39   previewMode: boolean;
40   imageLoading: boolean;
41 }
42
43 export class CommentForm extends Component<CommentFormProps, CommentFormState> {
44   private id = `comment-form-${randomStr()}`;
45   private userSub: Subscription;
46   private communitySub: Subscription;
47   private tribute: any;
48   private emptyState: CommentFormState = {
49     commentForm: {
50       auth: null,
51       content: null,
52       post_id: this.props.node
53         ? this.props.node.comment.post_id
54         : this.props.postId,
55       creator_id: UserService.Instance.user
56         ? UserService.Instance.user.id
57         : null,
58     },
59     buttonTitle: !this.props.node
60       ? capitalizeFirstLetter(i18n.t('post'))
61       : this.props.edit
62       ? capitalizeFirstLetter(i18n.t('edit'))
63       : capitalizeFirstLetter(i18n.t('reply')),
64     previewMode: false,
65     imageLoading: false,
66   };
67
68   constructor(props: any, context: any) {
69     super(props, context);
70
71     this.tribute = new Tribute({
72       collection: [
73         // Emojis
74         {
75           trigger: ':',
76           menuItemTemplate: (item: any) => {
77             let emoji = `:${item.original.key}:`;
78             return `${item.original.val} ${emoji}`;
79           },
80           selectTemplate: (item: any) => {
81             return `:${item.original.key}:`;
82           },
83           values: Object.entries(emojiShortName).map(e => {
84             return { key: e[1], val: e[0] };
85           }),
86           allowSpaces: false,
87           autocompleteMode: true,
88           menuItemLimit: mentionDropdownFetchLimit,
89         },
90         // Users
91         {
92           trigger: '@',
93           selectTemplate: (item: any) => {
94             return `[/u/${item.original.key}](/u/${item.original.key})`;
95           },
96           values: (text: string, cb: any) => {
97             this.userSearch(text, (users: any) => cb(users));
98           },
99           allowSpaces: false,
100           autocompleteMode: true,
101           menuItemLimit: mentionDropdownFetchLimit,
102         },
103
104         // Communities
105         {
106           trigger: '#',
107           selectTemplate: (item: any) => {
108             return `[/c/${item.original.key}](/c/${item.original.key})`;
109           },
110           values: (text: string, cb: any) => {
111             this.communitySearch(text, (communities: any) => cb(communities));
112           },
113           allowSpaces: false,
114           autocompleteMode: true,
115           menuItemLimit: mentionDropdownFetchLimit,
116         },
117       ],
118     });
119
120     this.state = this.emptyState;
121
122     if (this.props.node) {
123       if (this.props.edit) {
124         this.state.commentForm.edit_id = this.props.node.comment.id;
125         this.state.commentForm.parent_id = this.props.node.comment.parent_id;
126         this.state.commentForm.content = this.props.node.comment.content;
127         this.state.commentForm.creator_id = this.props.node.comment.creator_id;
128       } else {
129         // A reply gets a new parent id
130         this.state.commentForm.parent_id = this.props.node.comment.id;
131       }
132     }
133   }
134
135   componentDidMount() {
136     var textarea: any = document.getElementById(this.id);
137     autosize(textarea);
138     this.tribute.attach(textarea);
139     textarea.addEventListener('tribute-replaced', () => {
140       this.state.commentForm.content = textarea.value;
141       this.setState(this.state);
142       autosize.update(textarea);
143     });
144   }
145
146   render() {
147     return (
148       <div class="mb-3">
149         <form onSubmit={linkEvent(this, this.handleCommentSubmit)}>
150           <div class="form-group row">
151             <div className={`col-sm-12`}>
152               <textarea
153                 id={this.id}
154                 className={`form-control ${this.state.previewMode && 'd-none'}`}
155                 value={this.state.commentForm.content}
156                 onInput={linkEvent(this, this.handleCommentContentChange)}
157                 required
158                 disabled={this.props.disabled}
159                 rows={2}
160                 maxLength={10000}
161               />
162               {this.state.previewMode && (
163                 <div
164                   className="md-div"
165                   dangerouslySetInnerHTML={mdToHtml(
166                     this.state.commentForm.content
167                   )}
168                 />
169               )}
170             </div>
171           </div>
172           <div class="row">
173             <div class="col-sm-12">
174               <button
175                 type="submit"
176                 class="btn btn-sm btn-secondary mr-2"
177                 disabled={this.props.disabled}
178               >
179                 {this.state.buttonTitle}
180               </button>
181               {this.state.commentForm.content && (
182                 <button
183                   className={`btn btn-sm mr-2 btn-secondary ${this.state
184                     .previewMode && 'active'}`}
185                   onClick={linkEvent(this, this.handlePreviewToggle)}
186                 >
187                   <T i18nKey="preview">#</T>
188                 </button>
189               )}
190               {this.props.node && (
191                 <button
192                   type="button"
193                   class="btn btn-sm btn-secondary mr-2"
194                   onClick={linkEvent(this, this.handleReplyCancel)}
195                 >
196                   <T i18nKey="cancel">#</T>
197                 </button>
198               )}
199               <a
200                 href={markdownHelpUrl}
201                 target="_blank"
202                 class="d-inline-block float-right text-muted small font-weight-bold"
203               >
204                 <T i18nKey="formatting_help">#</T>
205               </a>
206               <form class="d-inline-block mr-2 float-right text-muted small font-weight-bold">
207                 <label
208                   htmlFor={`file-upload-${this.id}`}
209                   className={`${UserService.Instance.user && 'pointer'}`}
210                 >
211                   <T i18nKey="upload_image">#</T>
212                 </label>
213                 <input
214                   id={`file-upload-${this.id}`}
215                   type="file"
216                   accept="image/*,video/*"
217                   name="file"
218                   class="d-none"
219                   disabled={!UserService.Instance.user}
220                   onChange={linkEvent(this, this.handleImageUpload)}
221                 />
222               </form>
223               {this.state.imageLoading && (
224                 <svg class="icon icon-spinner spin">
225                   <use xlinkHref="#icon-spinner"></use>
226                 </svg>
227               )}
228             </div>
229           </div>
230         </form>
231       </div>
232     );
233   }
234
235   handleCommentSubmit(i: CommentForm, event: any) {
236     event.preventDefault();
237     if (i.props.edit) {
238       WebSocketService.Instance.editComment(i.state.commentForm);
239     } else {
240       WebSocketService.Instance.createComment(i.state.commentForm);
241     }
242
243     i.state.previewMode = false;
244     i.state.commentForm.content = undefined;
245     event.target.reset();
246     i.setState(i.state);
247     if (i.props.node) {
248       i.props.onReplyCancel();
249     }
250
251     autosize.update(document.querySelector('textarea'));
252   }
253
254   handleCommentContentChange(i: CommentForm, event: any) {
255     i.state.commentForm.content = event.target.value;
256     i.setState(i.state);
257   }
258
259   handlePreviewToggle(i: CommentForm, event: any) {
260     event.preventDefault();
261     i.state.previewMode = !i.state.previewMode;
262     i.setState(i.state);
263   }
264
265   handleReplyCancel(i: CommentForm) {
266     i.props.onReplyCancel();
267   }
268
269   handleImageUpload(i: CommentForm, event: any) {
270     event.preventDefault();
271     let file = event.target.files[0];
272     const imageUploadUrl = `/pictshare/api/upload.php`;
273     const formData = new FormData();
274     formData.append('file', file);
275
276     i.state.imageLoading = true;
277     i.setState(i.state);
278
279     fetch(imageUploadUrl, {
280       method: 'POST',
281       body: formData,
282     })
283       .then(res => res.json())
284       .then(res => {
285         let url = `${window.location.origin}/pictshare/${res.url}`;
286         let markdown =
287           res.filetype == 'mp4' ? `[vid](${url}/raw)` : `![](${url})`;
288         let content = i.state.commentForm.content;
289         content = content ? `${content} ${markdown}` : markdown;
290         i.state.commentForm.content = content;
291         i.state.imageLoading = false;
292         i.setState(i.state);
293       })
294       .catch(error => {
295         i.state.imageLoading = false;
296         i.setState(i.state);
297         toast(error, 'danger');
298       });
299   }
300
301   userSearch(text: string, cb: any) {
302     if (text) {
303       let form: SearchForm = {
304         q: text,
305         type_: SearchType[SearchType.Users],
306         sort: SortType[SortType.TopAll],
307         page: 1,
308         limit: mentionDropdownFetchLimit,
309       };
310
311       WebSocketService.Instance.search(form);
312
313       this.userSub = WebSocketService.Instance.subject.subscribe(
314         msg => {
315           let res = wsJsonToRes(msg);
316           if (res.op == UserOperation.Search) {
317             let data = res.data as SearchResponse;
318             let users = data.users.map(u => {
319               return { key: u.name };
320             });
321             cb(users);
322             this.userSub.unsubscribe();
323           }
324         },
325         err => console.error(err),
326         () => console.log('complete')
327       );
328     } else {
329       cb([]);
330     }
331   }
332
333   communitySearch(text: string, cb: any) {
334     if (text) {
335       let form: SearchForm = {
336         q: text,
337         type_: SearchType[SearchType.Communities],
338         sort: SortType[SortType.TopAll],
339         page: 1,
340         limit: mentionDropdownFetchLimit,
341       };
342
343       WebSocketService.Instance.search(form);
344
345       this.communitySub = WebSocketService.Instance.subject.subscribe(
346         msg => {
347           let res = wsJsonToRes(msg);
348           if (res.op == UserOperation.Search) {
349             let data = res.data as SearchResponse;
350             let communities = data.communities.map(u => {
351               return { key: u.name };
352             });
353             cb(communities);
354             this.communitySub.unsubscribe();
355           }
356         },
357         err => console.error(err),
358         () => console.log('complete')
359       );
360     } else {
361       cb([]);
362     }
363   }
364 }