]> Untitled Git - lemmy-ui.git/blob - src/shared/components/common/markdown-textarea.tsx
Merge branch 'main' into breakout-role-utils
[lemmy-ui.git] / src / shared / components / common / markdown-textarea.tsx
1 import autosize from "autosize";
2 import classNames from "classnames";
3 import { NoOptionI18nKeys } from "i18next";
4 import { Component, linkEvent } from "inferno";
5 import { Language } from "lemmy-js-client";
6 import { i18n } from "../../i18next";
7 import { HttpService, UserService } from "../../services";
8 import {
9   concurrentImageUpload,
10   customEmojisLookup,
11   markdownFieldCharacterLimit,
12   markdownHelpUrl,
13   maxUploadImages,
14   mdToHtml,
15   numToSI,
16   pictrsDeleteToast,
17   randomStr,
18   relTags,
19   setupTippy,
20   setupTribute,
21   toast,
22 } from "../../utils";
23 import { isBrowser } from "../../utils/browser/is-browser";
24 import { EmojiPicker } from "./emoji-picker";
25 import { Icon, Spinner } from "./icon";
26 import { LanguageSelect } from "./language-select";
27 import NavigationPrompt from "./navigation-prompt";
28 import ProgressBar from "./progress-bar";
29 interface MarkdownTextAreaProps {
30   initialContent?: string;
31   initialLanguageId?: number;
32   placeholder?: string;
33   buttonTitle?: string;
34   maxLength?: number;
35   replyType?: boolean;
36   focus?: boolean;
37   disabled?: boolean;
38   finished?: boolean;
39   showLanguage?: boolean;
40   hideNavigationWarnings?: boolean;
41   onContentChange?(val: string): void;
42   onReplyCancel?(): void;
43   onSubmit?(content: string, formId: string, languageId?: number): void;
44   allLanguages: Language[]; // TODO should probably be nullable
45   siteLanguages: number[]; // TODO same
46 }
47
48 interface ImageUploadStatus {
49   total: number;
50   uploaded: number;
51 }
52
53 interface MarkdownTextAreaState {
54   content?: string;
55   languageId?: number;
56   previewMode: boolean;
57   imageUploadStatus?: ImageUploadStatus;
58   loading: boolean;
59   submitted: boolean;
60 }
61
62 export class MarkdownTextArea extends Component<
63   MarkdownTextAreaProps,
64   MarkdownTextAreaState
65 > {
66   private id = `markdown-textarea-${randomStr()}`;
67   private formId = `markdown-form-${randomStr()}`;
68
69   private tribute: any;
70
71   state: MarkdownTextAreaState = {
72     content: this.props.initialContent,
73     languageId: this.props.initialLanguageId,
74     previewMode: false,
75     loading: false,
76     submitted: false,
77   };
78
79   constructor(props: any, context: any) {
80     super(props, context);
81
82     this.handleLanguageChange = this.handleLanguageChange.bind(this);
83
84     if (isBrowser()) {
85       this.tribute = setupTribute();
86     }
87   }
88
89   componentDidMount() {
90     const textarea: any = document.getElementById(this.id);
91     if (textarea) {
92       autosize(textarea);
93       this.tribute.attach(textarea);
94       textarea.addEventListener("tribute-replaced", () => {
95         this.setState({ content: textarea.value });
96         autosize.update(textarea);
97       });
98
99       this.quoteInsert();
100
101       if (this.props.focus) {
102         textarea.focus();
103       }
104
105       // TODO this is slow for some reason
106       setupTippy();
107     }
108   }
109
110   componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
111     if (nextProps.finished) {
112       this.setState({
113         previewMode: false,
114         imageUploadStatus: undefined,
115         loading: false,
116         content: undefined,
117       });
118       if (this.props.replyType) {
119         this.props.onReplyCancel?.();
120       }
121
122       const textarea: any = document.getElementById(this.id);
123       const form: any = document.getElementById(this.formId);
124       form.reset();
125       setTimeout(() => autosize.update(textarea), 10);
126     }
127   }
128
129   render() {
130     const languageId = this.state.languageId;
131
132     // TODO add these prompts back in at some point
133     // <Prompt
134     //   when={!this.props.hideNavigationWarnings && this.state.content}
135     //   message={i18n.t("block_leaving")}
136     // />
137     return (
138       <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
139         <NavigationPrompt
140           when={
141             !this.props.hideNavigationWarnings &&
142             !!this.state.content &&
143             !this.state.submitted
144           }
145         />
146         <div className="form-group row">
147           <div className="col-12">
148             <div className="rounded bg-light border border-light">
149               <div className="d-flex flex-wrap border-bottom border-light">
150                 {this.getFormatButton("bold", this.handleInsertBold)}
151                 {this.getFormatButton("italic", this.handleInsertItalic)}
152                 {this.getFormatButton("link", this.handleInsertLink)}
153                 <EmojiPicker
154                   onEmojiClick={e => this.handleEmoji(this, e)}
155                   disabled={this.isDisabled}
156                 ></EmojiPicker>
157                 <form className="btn btn-sm text-muted font-weight-bold">
158                   <label
159                     htmlFor={`file-upload-${this.id}`}
160                     className={`mb-0 ${
161                       UserService.Instance.myUserInfo && "pointer"
162                     }`}
163                     data-tippy-content={i18n.t("upload_image")}
164                   >
165                     {this.state.imageUploadStatus ? (
166                       <Spinner />
167                     ) : (
168                       <Icon icon="image" classes="icon-inline" />
169                     )}
170                   </label>
171                   <input
172                     id={`file-upload-${this.id}`}
173                     type="file"
174                     accept="image/*,video/*"
175                     name="file"
176                     className="d-none"
177                     multiple
178                     disabled={
179                       !UserService.Instance.myUserInfo || this.isDisabled
180                     }
181                     onChange={linkEvent(this, this.handleImageUpload)}
182                   />
183                 </form>
184                 {this.getFormatButton("header", this.handleInsertHeader)}
185                 {this.getFormatButton(
186                   "strikethrough",
187                   this.handleInsertStrikethrough
188                 )}
189                 {this.getFormatButton("quote", this.handleInsertQuote)}
190                 {this.getFormatButton("list", this.handleInsertList)}
191                 {this.getFormatButton("code", this.handleInsertCode)}
192                 {this.getFormatButton("subscript", this.handleInsertSubscript)}
193                 {this.getFormatButton(
194                   "superscript",
195                   this.handleInsertSuperscript
196                 )}
197                 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
198                 <a
199                   href={markdownHelpUrl}
200                   className="btn btn-sm text-muted font-weight-bold"
201                   title={i18n.t("formatting_help")}
202                   rel={relTags}
203                 >
204                   <Icon icon="help-circle" classes="icon-inline" />
205                 </a>
206               </div>
207
208               <div>
209                 <textarea
210                   id={this.id}
211                   className={classNames(
212                     "form-control border-0 rounded-top-0 rounded-bottom",
213                     {
214                       "d-none": this.state.previewMode,
215                     }
216                   )}
217                   value={this.state.content}
218                   onInput={linkEvent(this, this.handleContentChange)}
219                   onPaste={linkEvent(this, this.handleImageUploadPaste)}
220                   onKeyDown={linkEvent(this, this.handleKeyBinds)}
221                   required
222                   disabled={this.isDisabled}
223                   rows={2}
224                   maxLength={
225                     this.props.maxLength ?? markdownFieldCharacterLimit
226                   }
227                   placeholder={this.props.placeholder}
228                 />
229                 {this.state.previewMode && this.state.content && (
230                   <div
231                     className="card border-secondary card-body md-div"
232                     dangerouslySetInnerHTML={mdToHtml(this.state.content)}
233                   />
234                 )}
235                 {this.state.imageUploadStatus &&
236                   this.state.imageUploadStatus.total > 1 && (
237                     <ProgressBar
238                       className="mt-2"
239                       striped
240                       animated
241                       value={this.state.imageUploadStatus.uploaded}
242                       max={this.state.imageUploadStatus.total}
243                       text={i18n.t("pictures_uploded_progess", {
244                         uploaded: this.state.imageUploadStatus.uploaded,
245                         total: this.state.imageUploadStatus.total,
246                       })}
247                     />
248                   )}
249               </div>
250               <label className="sr-only" htmlFor={this.id}>
251                 {i18n.t("body")}
252               </label>
253             </div>
254           </div>
255
256           <div className="col-12 d-flex align-items-center flex-wrap mt-2">
257             {this.props.showLanguage && (
258               <LanguageSelect
259                 iconVersion
260                 allLanguages={this.props.allLanguages}
261                 selectedLanguageIds={
262                   languageId ? Array.of(languageId) : undefined
263                 }
264                 siteLanguages={this.props.siteLanguages}
265                 onChange={this.handleLanguageChange}
266                 disabled={this.isDisabled}
267               />
268             )}
269
270             {/* A flex expander */}
271             <div className="flex-grow-1"></div>
272
273             {this.props.buttonTitle && (
274               <button
275                 type="submit"
276                 className="btn btn-sm btn-secondary ml-2"
277                 disabled={this.isDisabled}
278               >
279                 {this.state.loading ? (
280                   <Spinner />
281                 ) : (
282                   <span>{this.props.buttonTitle}</span>
283                 )}
284               </button>
285             )}
286             {this.props.replyType && (
287               <button
288                 type="button"
289                 className="btn btn-sm btn-secondary ml-2"
290                 onClick={linkEvent(this, this.handleReplyCancel)}
291               >
292                 {i18n.t("cancel")}
293               </button>
294             )}
295             {this.state.content && (
296               <button
297                 className={`btn btn-sm btn-secondary ml-2 ${
298                   this.state.previewMode && "active"
299                 }`}
300                 onClick={linkEvent(this, this.handlePreviewToggle)}
301               >
302                 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
303               </button>
304             )}
305           </div>
306         </div>
307       </form>
308     );
309   }
310
311   getFormatButton(
312     type: NoOptionI18nKeys,
313     handleClick: (i: MarkdownTextArea, event: any) => void
314   ) {
315     let iconType: string;
316
317     switch (type) {
318       case "spoiler": {
319         iconType = "alert-triangle";
320         break;
321       }
322       case "quote": {
323         iconType = "format_quote";
324         break;
325       }
326       default: {
327         iconType = type;
328       }
329     }
330
331     return (
332       <button
333         className="btn btn-sm text-muted"
334         data-tippy-content={i18n.t(type)}
335         aria-label={i18n.t(type)}
336         onClick={linkEvent(this, handleClick)}
337         disabled={this.isDisabled}
338       >
339         <Icon icon={iconType} classes="icon-inline" />
340       </button>
341     );
342   }
343
344   handleEmoji(i: MarkdownTextArea, e: any) {
345     let value = e.native;
346     if (value == null) {
347       const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
348       if (emoji) {
349         value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
350       }
351     }
352     i.setState({
353       content: `${i.state.content ?? ""} ${value} `,
354     });
355     i.contentChange();
356     const textarea: any = document.getElementById(i.id);
357     autosize.update(textarea);
358   }
359
360   handleImageUploadPaste(i: MarkdownTextArea, event: any) {
361     const image = event.clipboardData.files[0];
362     if (image) {
363       i.handleImageUpload(i, image);
364     }
365   }
366
367   handleImageUpload(i: MarkdownTextArea, event: any) {
368     const files: File[] = [];
369     if (event.target) {
370       event.preventDefault();
371       files.push(...event.target.files);
372     } else {
373       files.push(event);
374     }
375
376     if (files.length > maxUploadImages) {
377       toast(
378         i18n.t("too_many_images_upload", {
379           count: Number(maxUploadImages),
380           formattedCount: numToSI(maxUploadImages),
381         }),
382         "danger"
383       );
384     } else {
385       i.setState({
386         imageUploadStatus: { total: files.length, uploaded: 0 },
387       });
388
389       i.uploadImages(i, files).then(() => {
390         i.setState({ imageUploadStatus: undefined });
391       });
392     }
393   }
394
395   async uploadImages(i: MarkdownTextArea, files: File[]) {
396     let errorOccurred = false;
397     const filesCopy = [...files];
398     while (filesCopy.length > 0 && !errorOccurred) {
399       try {
400         await Promise.all(
401           filesCopy.splice(0, concurrentImageUpload).map(async file => {
402             await i.uploadSingleImage(i, file);
403
404             this.setState(({ imageUploadStatus }) => ({
405               imageUploadStatus: {
406                 ...(imageUploadStatus as Required<ImageUploadStatus>),
407                 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
408               },
409             }));
410           })
411         );
412       } catch (e) {
413         errorOccurred = true;
414       }
415     }
416   }
417
418   async uploadSingleImage(i: MarkdownTextArea, image: File) {
419     const res = await HttpService.client.uploadImage({ image });
420     console.log("pictrs upload:");
421     console.log(res);
422     if (res.state === "success") {
423       if (res.data.msg === "ok") {
424         const imageMarkdown = `![](${res.data.url})`;
425         i.setState(({ content }) => ({
426           content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
427         }));
428         i.contentChange();
429         const textarea: any = document.getElementById(i.id);
430         autosize.update(textarea);
431         pictrsDeleteToast(image.name, res.data.delete_url as string);
432       } else {
433         throw JSON.stringify(res.data);
434       }
435     } else if (res.state === "failed") {
436       i.setState({ imageUploadStatus: undefined });
437       console.error(res.msg);
438       toast(res.msg, "danger");
439
440       throw res.msg;
441     }
442   }
443
444   contentChange() {
445     // Coerces the undefineds to empty strings, for replacing in the DB
446     const content = this.state.content ?? "";
447     this.props.onContentChange?.(content);
448   }
449
450   handleContentChange(i: MarkdownTextArea, event: any) {
451     i.setState({ content: event.target.value });
452     i.contentChange();
453   }
454
455   // Keybind handler
456   // Keybinds inspired by github comment area
457   handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
458     if (event.ctrlKey) {
459       switch (event.key) {
460         case "k": {
461           i.handleInsertLink(i, event);
462           break;
463         }
464         case "Enter": {
465           if (!this.isDisabled) {
466             i.handleSubmit(i, event);
467           }
468
469           break;
470         }
471         case "b": {
472           i.handleInsertBold(i, event);
473           break;
474         }
475         case "i": {
476           i.handleInsertItalic(i, event);
477           break;
478         }
479         case "e": {
480           i.handleInsertCode(i, event);
481           break;
482         }
483         case "8": {
484           i.handleInsertList(i, event);
485           break;
486         }
487         case "s": {
488           i.handleInsertSpoiler(i, event);
489           break;
490         }
491         case "p": {
492           if (i.state.content) i.handlePreviewToggle(i, event);
493           break;
494         }
495         case ".": {
496           i.handleInsertQuote(i, event);
497           break;
498         }
499       }
500     }
501   }
502
503   handlePreviewToggle(i: MarkdownTextArea, event: any) {
504     event.preventDefault();
505     i.setState({ previewMode: !i.state.previewMode });
506   }
507
508   handleLanguageChange(val: number[]) {
509     this.setState({ languageId: val[0] });
510   }
511
512   handleSubmit(i: MarkdownTextArea, event: any) {
513     event.preventDefault();
514     if (i.state.content) {
515       i.setState({ loading: true, submitted: true });
516       i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
517     }
518   }
519
520   handleReplyCancel(i: MarkdownTextArea) {
521     i.props.onReplyCancel?.();
522   }
523
524   handleInsertLink(i: MarkdownTextArea, event: any) {
525     event.preventDefault();
526
527     const textarea: any = document.getElementById(i.id);
528     const start: number = textarea.selectionStart;
529     const end: number = textarea.selectionEnd;
530
531     const content = i.state.content ?? "";
532
533     if (!i.state.content) {
534       i.setState({ content: "" });
535     }
536
537     if (start !== end) {
538       const selectedText = content?.substring(start, end);
539       i.setState({
540         content: `${content?.substring(
541           0,
542           start
543         )}[${selectedText}]()${content?.substring(end)}`,
544       });
545       textarea.focus();
546       setTimeout(() => (textarea.selectionEnd = end + 3), 10);
547     } else {
548       i.setState({ content: `${content} []()` });
549       textarea.focus();
550       setTimeout(() => (textarea.selectionEnd -= 1), 10);
551     }
552     i.contentChange();
553   }
554
555   simpleSurround(chars: string) {
556     this.simpleSurroundBeforeAfter(chars, chars);
557   }
558
559   simpleBeginningofLine(chars: string) {
560     this.simpleSurroundBeforeAfter(`${chars}`, "", "");
561   }
562
563   simpleSurroundBeforeAfter(
564     beforeChars: string,
565     afterChars: string,
566     emptyChars = "___"
567   ) {
568     const content = this.state.content ?? "";
569     if (!this.state.content) {
570       this.setState({ content: "" });
571     }
572     const textarea: any = document.getElementById(this.id);
573     const start: number = textarea.selectionStart;
574     const end: number = textarea.selectionEnd;
575
576     if (start !== end) {
577       const selectedText = content?.substring(start, end);
578       this.setState({
579         content: `${content?.substring(
580           0,
581           start
582         )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
583       });
584     } else {
585       this.setState({
586         content: `${content}${beforeChars}${emptyChars}${afterChars}`,
587       });
588     }
589     this.contentChange();
590
591     textarea.focus();
592
593     if (start !== end) {
594       textarea.setSelectionRange(
595         start + beforeChars.length,
596         end + afterChars.length
597       );
598     } else {
599       textarea.setSelectionRange(
600         start + beforeChars.length,
601         end + emptyChars.length + afterChars.length
602       );
603     }
604
605     setTimeout(() => {
606       autosize.update(textarea);
607     }, 10);
608   }
609
610   handleInsertBold(i: MarkdownTextArea, event: any) {
611     event.preventDefault();
612     i.simpleSurround("**");
613   }
614
615   handleInsertItalic(i: MarkdownTextArea, event: any) {
616     event.preventDefault();
617     i.simpleSurround("*");
618   }
619
620   handleInsertCode(i: MarkdownTextArea, event: any) {
621     event.preventDefault();
622     if (i.getSelectedText().split(/\r*\n/).length > 1) {
623       i.simpleSurroundBeforeAfter("```\n", "\n```");
624     } else {
625       i.simpleSurround("`");
626     }
627   }
628
629   handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
630     event.preventDefault();
631     i.simpleSurround("~~");
632   }
633
634   handleInsertList(i: MarkdownTextArea, event: any) {
635     event.preventDefault();
636     i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
637   }
638
639   handleInsertQuote(i: MarkdownTextArea, event: any) {
640     event.preventDefault();
641     i.simpleBeginningofLine(">");
642   }
643
644   handleInsertHeader(i: MarkdownTextArea, event: any) {
645     event.preventDefault();
646     i.simpleBeginningofLine("#");
647   }
648
649   handleInsertSubscript(i: MarkdownTextArea, event: any) {
650     event.preventDefault();
651     i.simpleSurround("~");
652   }
653
654   handleInsertSuperscript(i: MarkdownTextArea, event: any) {
655     event.preventDefault();
656     i.simpleSurround("^");
657   }
658
659   simpleInsert(chars: string) {
660     const content = this.state.content;
661     if (!content) {
662       this.setState({ content: `${chars} ` });
663     } else {
664       this.setState({
665         content: `${content}\n${chars} `,
666       });
667     }
668
669     const textarea: any = document.getElementById(this.id);
670     textarea.focus();
671     setTimeout(() => {
672       autosize.update(textarea);
673     }, 10);
674     this.contentChange();
675   }
676
677   handleInsertSpoiler(i: MarkdownTextArea, event: any) {
678     event.preventDefault();
679     const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
680     const afterChars = "\n:::\n";
681     i.simpleSurroundBeforeAfter(beforeChars, afterChars);
682   }
683
684   quoteInsert() {
685     const textarea: any = document.getElementById(this.id);
686     const selectedText = window.getSelection()?.toString();
687     const { content } = this.state;
688     if (selectedText) {
689       const quotedText =
690         selectedText
691           .split("\n")
692           .map(t => `> ${t}`)
693           .join("\n") + "\n\n";
694       if (!content) {
695         this.setState({ content: "" });
696       } else {
697         this.setState({ content: `${content}\n` });
698       }
699       this.setState({
700         content: `${content}${quotedText}`,
701       });
702       this.contentChange();
703       // Not sure why this needs a delay
704       setTimeout(() => autosize.update(textarea), 10);
705     }
706   }
707
708   getSelectedText(): string {
709     const { selectionStart: start, selectionEnd: end } =
710       document.getElementById(this.id) as any;
711     return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
712   }
713
714   get isDisabled() {
715     return (
716       this.state.loading ||
717       this.props.disabled ||
718       !!this.state.imageUploadStatus
719     );
720   }
721 }