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