]> Untitled Git - lemmy-ui.git/blob - src/shared/components/markdown-textarea.tsx
Change from using Link to NavLink. resolve #269
[lemmy-ui.git] / src / shared / components / markdown-textarea.tsx
1 import { Component, linkEvent } from "inferno";
2 import { Prompt } from "inferno-router";
3 import {
4   mdToHtml,
5   randomStr,
6   markdownHelpUrl,
7   toast,
8   setupTribute,
9   pictrsDeleteToast,
10   setupTippy,
11   isBrowser,
12 } from "../utils";
13 import { UserService } from "../services";
14 import autosize from "autosize";
15 import { i18n } from "../i18next";
16 import { pictrsUri } from "../env";
17 import { Icon, Spinner } from "./icon";
18
19 interface MarkdownTextAreaProps {
20   initialContent: string;
21   finished?: boolean;
22   buttonTitle?: string;
23   replyType?: boolean;
24   focus?: boolean;
25   disabled?: boolean;
26   maxLength?: number;
27   onSubmit?(msg: { val: string; formId: string }): any;
28   onContentChange?(val: string): any;
29   onReplyCancel?(): any;
30   hideNavigationWarnings?: boolean;
31 }
32
33 interface MarkdownTextAreaState {
34   content: string;
35   previewMode: boolean;
36   loading: boolean;
37   imageLoading: boolean;
38 }
39
40 export class MarkdownTextArea extends Component<
41   MarkdownTextAreaProps,
42   MarkdownTextAreaState
43 > {
44   private id = `comment-textarea-${randomStr()}`;
45   private formId = `comment-form-${randomStr()}`;
46   private tribute: any;
47   private emptyState: MarkdownTextAreaState = {
48     content: this.props.initialContent,
49     previewMode: false,
50     loading: false,
51     imageLoading: false,
52   };
53
54   constructor(props: any, context: any) {
55     super(props, context);
56
57     if (isBrowser()) {
58       this.tribute = setupTribute();
59     }
60     this.state = this.emptyState;
61   }
62
63   componentDidMount() {
64     let textarea: any = document.getElementById(this.id);
65     if (textarea) {
66       autosize(textarea);
67       this.tribute.attach(textarea);
68       textarea.addEventListener("tribute-replaced", () => {
69         this.state.content = textarea.value;
70         this.setState(this.state);
71         autosize.update(textarea);
72       });
73
74       this.quoteInsert();
75
76       if (this.props.focus) {
77         textarea.focus();
78       }
79
80       // TODO this is slow for some reason
81       setupTippy();
82     }
83   }
84
85   componentDidUpdate() {
86     if (!this.props.hideNavigationWarnings && this.state.content) {
87       window.onbeforeunload = () => true;
88     } else {
89       window.onbeforeunload = undefined;
90     }
91   }
92
93   componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
94     if (nextProps.finished) {
95       this.state.previewMode = false;
96       this.state.loading = false;
97       this.state.content = "";
98       this.setState(this.state);
99       if (this.props.replyType) {
100         this.props.onReplyCancel();
101       }
102
103       let textarea: any = document.getElementById(this.id);
104       let form: any = document.getElementById(this.formId);
105       form.reset();
106       setTimeout(() => autosize.update(textarea), 10);
107       this.setState(this.state);
108     }
109   }
110
111   componentWillUnmount() {
112     window.onbeforeunload = null;
113   }
114
115   render() {
116     return (
117       <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
118         <Prompt
119           when={!this.props.hideNavigationWarnings && this.state.content}
120           message={i18n.t("block_leaving")}
121         />
122         <div class="form-group row">
123           <div className={`col-sm-12`}>
124             <textarea
125               id={this.id}
126               className={`form-control ${this.state.previewMode && "d-none"}`}
127               value={this.state.content}
128               onInput={linkEvent(this, this.handleContentChange)}
129               onPaste={linkEvent(this, this.handleImageUploadPaste)}
130               required
131               disabled={this.props.disabled}
132               rows={2}
133               maxLength={this.props.maxLength || 10000}
134             />
135             {this.state.previewMode && (
136               <div
137                 className="card border-secondary card-body md-div"
138                 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
139               />
140             )}
141           </div>
142           <label class="sr-only" htmlFor={this.id}>
143             {i18n.t("body")}
144           </label>
145         </div>
146         <div class="row">
147           <div class="col-sm-12 d-flex flex-wrap">
148             {this.props.buttonTitle && (
149               <button
150                 type="submit"
151                 class="btn btn-sm btn-secondary mr-2"
152                 disabled={this.props.disabled || this.state.loading}
153               >
154                 {this.state.loading ? (
155                   <Spinner />
156                 ) : (
157                   <span>{this.props.buttonTitle}</span>
158                 )}
159               </button>
160             )}
161             {this.props.replyType && (
162               <button
163                 type="button"
164                 class="btn btn-sm btn-secondary mr-2"
165                 onClick={linkEvent(this, this.handleReplyCancel)}
166               >
167                 {i18n.t("cancel")}
168               </button>
169             )}
170             {this.state.content && (
171               <button
172                 className={`btn btn-sm btn-secondary mr-2 ${
173                   this.state.previewMode && "active"
174                 }`}
175                 onClick={linkEvent(this, this.handlePreviewToggle)}
176               >
177                 {i18n.t("preview")}
178               </button>
179             )}
180             {/* A flex expander */}
181             <div class="flex-grow-1"></div>
182             <button
183               class="btn btn-sm text-muted"
184               data-tippy-content={i18n.t("bold")}
185               aria-label={i18n.t("bold")}
186               onClick={linkEvent(this, this.handleInsertBold)}
187             >
188               <Icon icon="bold" classes="icon-inline" />
189             </button>
190             <button
191               class="btn btn-sm text-muted"
192               data-tippy-content={i18n.t("italic")}
193               aria-label={i18n.t("italic")}
194               onClick={linkEvent(this, this.handleInsertItalic)}
195             >
196               <Icon icon="italic" classes="icon-inline" />
197             </button>
198             <button
199               class="btn btn-sm text-muted"
200               data-tippy-content={i18n.t("link")}
201               aria-label={i18n.t("link")}
202               onClick={linkEvent(this, this.handleInsertLink)}
203             >
204               <Icon icon="link" classes="icon-inline" />
205             </button>
206             <form class="btn btn-sm text-muted font-weight-bold">
207               <label
208                 htmlFor={`file-upload-${this.id}`}
209                 className={`mb-0 ${
210                   UserService.Instance.localUserView && "pointer"
211                 }`}
212                 data-tippy-content={i18n.t("upload_image")}
213               >
214                 {this.state.imageLoading ? (
215                   <Spinner />
216                 ) : (
217                   <Icon icon="image" classes="icon-inline" />
218                 )}
219               </label>
220               <input
221                 id={`file-upload-${this.id}`}
222                 type="file"
223                 accept="image/*,video/*"
224                 name="file"
225                 class="d-none"
226                 disabled={!UserService.Instance.localUserView}
227                 onChange={linkEvent(this, this.handleImageUpload)}
228               />
229             </form>
230             <button
231               class="btn btn-sm text-muted"
232               data-tippy-content={i18n.t("header")}
233               aria-label={i18n.t("header")}
234               onClick={linkEvent(this, this.handleInsertHeader)}
235             >
236               <Icon icon="header" classes="icon-inline" />
237             </button>
238             <button
239               class="btn btn-sm text-muted"
240               data-tippy-content={i18n.t("strikethrough")}
241               aria-label={i18n.t("strikethrough")}
242               onClick={linkEvent(this, this.handleInsertStrikethrough)}
243             >
244               <Icon icon="strikethrough" classes="icon-inline" />
245             </button>
246             <button
247               class="btn btn-sm text-muted"
248               data-tippy-content={i18n.t("quote")}
249               aria-label={i18n.t("quote")}
250               onClick={linkEvent(this, this.handleInsertQuote)}
251             >
252               <Icon icon="format_quote" classes="icon-inline" />
253             </button>
254             <button
255               class="btn btn-sm text-muted"
256               data-tippy-content={i18n.t("list")}
257               aria-label={i18n.t("list")}
258               onClick={linkEvent(this, this.handleInsertList)}
259             >
260               <Icon icon="list" classes="icon-inline" />
261             </button>
262             <button
263               class="btn btn-sm text-muted"
264               data-tippy-content={i18n.t("code")}
265               aria-label={i18n.t("code")}
266               onClick={linkEvent(this, this.handleInsertCode)}
267             >
268               <Icon icon="code" classes="icon-inline" />
269             </button>
270             <button
271               class="btn btn-sm text-muted"
272               data-tippy-content={i18n.t("subscript")}
273               aria-label={i18n.t("subscript")}
274               onClick={linkEvent(this, this.handleInsertSubscript)}
275             >
276               <Icon icon="subscript" classes="icon-inline" />
277             </button>
278             <button
279               class="btn btn-sm text-muted"
280               data-tippy-content={i18n.t("superscript")}
281               aria-label={i18n.t("superscript")}
282               onClick={linkEvent(this, this.handleInsertSuperscript)}
283             >
284               <Icon icon="superscript" classes="icon-inline" />
285             </button>
286             <button
287               class="btn btn-sm text-muted"
288               data-tippy-content={i18n.t("spoiler")}
289               aria-label={i18n.t("spoiler")}
290               onClick={linkEvent(this, this.handleInsertSpoiler)}
291             >
292               <Icon icon="alert-triangle" classes="icon-inline" />
293             </button>
294             <a
295               href={markdownHelpUrl}
296               class="btn btn-sm text-muted font-weight-bold"
297               title={i18n.t("formatting_help")}
298               rel="noopener"
299             >
300               <Icon icon="help-circle" classes="icon-inline" />
301             </a>
302           </div>
303         </div>
304       </form>
305     );
306   }
307
308   handleImageUploadPaste(i: MarkdownTextArea, event: any) {
309     let image = event.clipboardData.files[0];
310     if (image) {
311       i.handleImageUpload(i, image);
312     }
313   }
314
315   handleImageUpload(i: MarkdownTextArea, event: any) {
316     let file: any;
317     if (event.target) {
318       event.preventDefault();
319       file = event.target.files[0];
320     } else {
321       file = event;
322     }
323
324     const formData = new FormData();
325     formData.append("images[]", file);
326
327     i.state.imageLoading = true;
328     i.setState(i.state);
329
330     fetch(pictrsUri, {
331       method: "POST",
332       body: formData,
333     })
334       .then(res => res.json())
335       .then(res => {
336         console.log("pictrs upload:");
337         console.log(res);
338         if (res.msg == "ok") {
339           let hash = res.files[0].file;
340           let url = `${pictrsUri}/${hash}`;
341           let deleteToken = res.files[0].delete_token;
342           let deleteUrl = `${pictrsUri}/delete/${deleteToken}/${hash}`;
343           let imageMarkdown = `![](${url})`;
344           let content = i.state.content;
345           content = content ? `${content}\n${imageMarkdown}` : imageMarkdown;
346           i.state.content = content;
347           i.state.imageLoading = false;
348           i.contentChange();
349           i.setState(i.state);
350           let textarea: any = document.getElementById(i.id);
351           autosize.update(textarea);
352           pictrsDeleteToast(
353             i18n.t("click_to_delete_picture"),
354             i18n.t("picture_deleted"),
355             deleteUrl
356           );
357         } else {
358           i.state.imageLoading = false;
359           i.setState(i.state);
360           toast(JSON.stringify(res), "danger");
361         }
362       })
363       .catch(error => {
364         i.state.imageLoading = false;
365         i.setState(i.state);
366         toast(error, "danger");
367       });
368   }
369
370   contentChange() {
371     if (this.props.onContentChange) {
372       this.props.onContentChange(this.state.content);
373     }
374   }
375
376   handleContentChange(i: MarkdownTextArea, event: any) {
377     i.state.content = event.target.value;
378     i.contentChange();
379     i.setState(i.state);
380   }
381
382   handlePreviewToggle(i: MarkdownTextArea, event: any) {
383     event.preventDefault();
384     i.state.previewMode = !i.state.previewMode;
385     i.setState(i.state);
386   }
387
388   handleSubmit(i: MarkdownTextArea, event: any) {
389     event.preventDefault();
390     i.state.loading = true;
391     i.setState(i.state);
392     let msg = { val: i.state.content, formId: i.formId };
393     i.props.onSubmit(msg);
394   }
395
396   handleReplyCancel(i: MarkdownTextArea) {
397     i.props.onReplyCancel();
398   }
399
400   handleInsertLink(i: MarkdownTextArea, event: any) {
401     event.preventDefault();
402     if (!i.state.content) {
403       i.state.content = "";
404     }
405     let textarea: any = document.getElementById(i.id);
406     let start: number = textarea.selectionStart;
407     let end: number = textarea.selectionEnd;
408
409     if (start !== end) {
410       let selectedText = i.state.content.substring(start, end);
411       i.state.content = `${i.state.content.substring(
412         0,
413         start
414       )}[${selectedText}]()${i.state.content.substring(end)}`;
415       textarea.focus();
416       setTimeout(() => (textarea.selectionEnd = end + 3), 10);
417     } else {
418       i.state.content += "[]()";
419       textarea.focus();
420       setTimeout(() => (textarea.selectionEnd -= 1), 10);
421     }
422     i.contentChange();
423     i.setState(i.state);
424   }
425
426   simpleSurround(chars: string) {
427     this.simpleSurroundBeforeAfter(chars, chars);
428   }
429
430   simpleBeginningofLine(chars: string) {
431     this.simpleSurroundBeforeAfter(`${chars} `, "", "");
432   }
433
434   simpleSurroundBeforeAfter(
435     beforeChars: string,
436     afterChars: string,
437     emptyChars = "___"
438   ) {
439     if (!this.state.content) {
440       this.state.content = "";
441     }
442     let textarea: any = document.getElementById(this.id);
443     let start: number = textarea.selectionStart;
444     let end: number = textarea.selectionEnd;
445
446     if (start !== end) {
447       let selectedText = this.state.content.substring(start, end);
448       this.state.content = `${this.state.content.substring(
449         0,
450         start
451       )}${beforeChars}${selectedText}${afterChars}${this.state.content.substring(
452         end
453       )}`;
454     } else {
455       this.state.content += `${beforeChars}${emptyChars}${afterChars}`;
456     }
457     this.contentChange();
458     this.setState(this.state);
459     setTimeout(() => {
460       autosize.update(textarea);
461     }, 10);
462   }
463
464   handleInsertBold(i: MarkdownTextArea, event: any) {
465     event.preventDefault();
466     i.simpleSurround("**");
467   }
468
469   handleInsertItalic(i: MarkdownTextArea, event: any) {
470     event.preventDefault();
471     i.simpleSurround("*");
472   }
473
474   handleInsertCode(i: MarkdownTextArea, event: any) {
475     event.preventDefault();
476     i.simpleSurround("`");
477   }
478
479   handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
480     event.preventDefault();
481     i.simpleSurround("~~");
482   }
483
484   handleInsertList(i: MarkdownTextArea, event: any) {
485     event.preventDefault();
486     i.simpleBeginningofLine("-");
487   }
488
489   handleInsertQuote(i: MarkdownTextArea, event: any) {
490     event.preventDefault();
491     i.simpleBeginningofLine(">");
492   }
493
494   handleInsertHeader(i: MarkdownTextArea, event: any) {
495     event.preventDefault();
496     i.simpleBeginningofLine("#");
497   }
498
499   handleInsertSubscript(i: MarkdownTextArea, event: any) {
500     event.preventDefault();
501     i.simpleSurround("~");
502   }
503
504   handleInsertSuperscript(i: MarkdownTextArea, event: any) {
505     event.preventDefault();
506     i.simpleSurround("^");
507   }
508
509   simpleInsert(chars: string) {
510     if (!this.state.content) {
511       this.state.content = `${chars} `;
512     } else {
513       this.state.content += `\n${chars} `;
514     }
515
516     let textarea: any = document.getElementById(this.id);
517     textarea.focus();
518     setTimeout(() => {
519       autosize.update(textarea);
520     }, 10);
521     this.contentChange();
522     this.setState(this.state);
523   }
524
525   handleInsertSpoiler(i: MarkdownTextArea, event: any) {
526     event.preventDefault();
527     let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
528     let afterChars = "\n:::\n";
529     i.simpleSurroundBeforeAfter(beforeChars, afterChars);
530   }
531
532   quoteInsert() {
533     let textarea: any = document.getElementById(this.id);
534     let selectedText = window.getSelection().toString();
535     if (selectedText) {
536       let quotedText =
537         selectedText
538           .split("\n")
539           .map(t => `> ${t}`)
540           .join("\n") + "\n\n";
541       if (this.state.content == null) {
542         this.state.content = "";
543       } else {
544         this.state.content += "\n";
545       }
546       this.state.content += quotedText;
547       this.contentChange();
548       this.setState(this.state);
549       // Not sure why this needs a delay
550       setTimeout(() => autosize.update(textarea), 10);
551     }
552   }
553 }