]> Untitled Git - lemmy-ui.git/blob - src/shared/components/common/markdown-textarea.tsx
Merge remote-tracking branch 'lemmy/main' into feat/create-private-message-updates
[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 font-weight-bold">
171                   <label
172                     htmlFor={`file-upload-${this.id}`}
173                     className={`mb-0 ${
174                       UserService.Instance.myUserInfo && "pointer"
175                     }`}
176                     data-tippy-content={I18NextService.i18n.t("upload_image")}
177                   >
178                     {this.state.imageUploadStatus ? (
179                       <Spinner />
180                     ) : (
181                       <Icon icon="image" classes="icon-inline" />
182                     )}
183                   </label>
184                   <input
185                     id={`file-upload-${this.id}`}
186                     type="file"
187                     accept="image/*,video/*"
188                     name="file"
189                     className="d-none"
190                     multiple
191                     disabled={
192                       !UserService.Instance.myUserInfo || this.isDisabled
193                     }
194                     onChange={linkEvent(this, this.handleImageUpload)}
195                   />
196                 </form>
197                 {this.getFormatButton("header", this.handleInsertHeader)}
198                 {this.getFormatButton(
199                   "strikethrough",
200                   this.handleInsertStrikethrough
201                 )}
202                 {this.getFormatButton("quote", this.handleInsertQuote)}
203                 {this.getFormatButton("list", this.handleInsertList)}
204                 {this.getFormatButton("code", this.handleInsertCode)}
205                 {this.getFormatButton("subscript", this.handleInsertSubscript)}
206                 {this.getFormatButton(
207                   "superscript",
208                   this.handleInsertSuperscript
209                 )}
210                 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
211                 <a
212                   href={markdownHelpUrl}
213                   className="btn btn-sm text-muted font-weight-bold"
214                   title={I18NextService.i18n.t("formatting_help")}
215                   rel={relTags}
216                 >
217                   <Icon icon="help-circle" classes="icon-inline" />
218                 </a>
219               </div>
220
221               <div>
222                 <textarea
223                   id={this.id}
224                   className={classNames(
225                     "form-control border-0 rounded-top-0 rounded-bottom",
226                     {
227                       "d-none": this.state.previewMode,
228                     }
229                   )}
230                   value={this.state.content}
231                   onInput={linkEvent(this, this.handleContentChange)}
232                   onPaste={linkEvent(this, this.handleImageUploadPaste)}
233                   onKeyDown={linkEvent(this, this.handleKeyBinds)}
234                   required
235                   disabled={this.isDisabled}
236                   rows={2}
237                   maxLength={
238                     this.props.maxLength ?? markdownFieldCharacterLimit
239                   }
240                   placeholder={this.props.placeholder}
241                 />
242                 {this.state.previewMode && this.state.content && (
243                   <div
244                     className="card border-secondary card-body md-div"
245                     dangerouslySetInnerHTML={mdToHtml(this.state.content)}
246                   />
247                 )}
248                 {this.state.imageUploadStatus &&
249                   this.state.imageUploadStatus.total > 1 && (
250                     <ProgressBar
251                       className="mt-2"
252                       striped
253                       animated
254                       value={this.state.imageUploadStatus.uploaded}
255                       max={this.state.imageUploadStatus.total}
256                       text={
257                         I18NextService.i18n.t("pictures_uploded_progess", {
258                           uploaded: this.state.imageUploadStatus.uploaded,
259                           total: this.state.imageUploadStatus.total,
260                         }) ?? undefined
261                       }
262                     />
263                   )}
264               </div>
265               <label className="visually-hidden" htmlFor={this.id}>
266                 {I18NextService.i18n.t("body")}
267               </label>
268             </div>
269           </div>
270
271           <div className="col-12 d-flex align-items-center flex-wrap mt-2">
272             {this.props.showLanguage && (
273               <LanguageSelect
274                 iconVersion
275                 allLanguages={this.props.allLanguages}
276                 selectedLanguageIds={
277                   languageId ? Array.of(languageId) : undefined
278                 }
279                 siteLanguages={this.props.siteLanguages}
280                 onChange={this.handleLanguageChange}
281                 disabled={this.isDisabled}
282               />
283             )}
284
285             {/* A flex expander */}
286             <div className="flex-grow-1"></div>
287
288             {this.props.replyType && (
289               <button
290                 type="button"
291                 className="btn btn-sm btn-secondary ms-2"
292                 onClick={linkEvent(this, this.handleReplyCancel)}
293               >
294                 {I18NextService.i18n.t("cancel")}
295               </button>
296             )}
297             <button
298               type="button"
299               disabled={!this.state.content}
300               className={classNames("btn btn-sm btn-secondary ms-2", {
301                 active: this.state.previewMode,
302               })}
303               onClick={linkEvent(this, this.handlePreviewToggle)}
304             >
305               {this.state.previewMode
306                 ? I18NextService.i18n.t("edit")
307                 : I18NextService.i18n.t("preview")}
308             </button>
309             {this.props.buttonTitle && (
310               <button
311                 type="submit"
312                 className="btn btn-sm btn-secondary ms-2"
313                 disabled={this.isDisabled || !this.state.content}
314               >
315                 {this.state.loading && <Spinner className="me-1" />}
316                 {this.props.buttonTitle}
317               </button>
318             )}
319           </div>
320         </div>
321       </form>
322     );
323   }
324
325   getFormatButton(
326     type: NoOptionI18nKeys,
327     handleClick: (i: MarkdownTextArea, event: any) => void
328   ) {
329     let iconType: string;
330
331     switch (type) {
332       case "spoiler": {
333         iconType = "alert-triangle";
334         break;
335       }
336       case "quote": {
337         iconType = "format_quote";
338         break;
339       }
340       default: {
341         iconType = type;
342       }
343     }
344
345     return (
346       <button
347         className="btn btn-sm text-muted"
348         data-tippy-content={I18NextService.i18n.t(type)}
349         aria-label={I18NextService.i18n.t(type)}
350         onClick={linkEvent(this, handleClick)}
351         disabled={this.isDisabled}
352       >
353         <Icon icon={iconType} classes="icon-inline" />
354       </button>
355     );
356   }
357
358   handleEmoji(i: MarkdownTextArea, e: any) {
359     let value = e.native;
360     if (value == null) {
361       const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
362       if (emoji) {
363         value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
364       }
365     }
366     i.setState({
367       content: `${i.state.content ?? ""} ${value} `,
368     });
369     i.contentChange();
370     const textarea: any = document.getElementById(i.id);
371     autosize.update(textarea);
372   }
373
374   handleImageUploadPaste(i: MarkdownTextArea, event: any) {
375     const image = event.clipboardData.files[0];
376     if (image) {
377       i.handleImageUpload(i, image);
378     }
379   }
380
381   handleImageUpload(i: MarkdownTextArea, event: any) {
382     const files: File[] = [];
383     if (event.target) {
384       event.preventDefault();
385       files.push(...event.target.files);
386     } else {
387       files.push(event);
388     }
389
390     if (files.length > maxUploadImages) {
391       toast(
392         I18NextService.i18n.t("too_many_images_upload", {
393           count: Number(maxUploadImages),
394           formattedCount: numToSI(maxUploadImages),
395         }),
396         "danger"
397       );
398     } else {
399       i.setState({
400         imageUploadStatus: { total: files.length, uploaded: 0 },
401       });
402
403       i.uploadImages(i, files).then(() => {
404         i.setState({ imageUploadStatus: undefined });
405       });
406     }
407   }
408
409   async uploadImages(i: MarkdownTextArea, files: File[]) {
410     let errorOccurred = false;
411     const filesCopy = [...files];
412     while (filesCopy.length > 0 && !errorOccurred) {
413       try {
414         await Promise.all(
415           filesCopy.splice(0, concurrentImageUpload).map(async file => {
416             await i.uploadSingleImage(i, file);
417
418             this.setState(({ imageUploadStatus }) => ({
419               imageUploadStatus: {
420                 ...(imageUploadStatus as Required<ImageUploadStatus>),
421                 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
422               },
423             }));
424           })
425         );
426       } catch (e) {
427         errorOccurred = true;
428       }
429     }
430   }
431
432   async uploadSingleImage(i: MarkdownTextArea, image: File) {
433     const res = await HttpService.client.uploadImage({ image });
434     console.log("pictrs upload:");
435     console.log(res);
436     if (res.state === "success") {
437       if (res.data.msg === "ok") {
438         const imageMarkdown = `![](${res.data.url})`;
439         i.setState(({ content }) => ({
440           content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
441         }));
442         i.contentChange();
443         const textarea: any = document.getElementById(i.id);
444         autosize.update(textarea);
445         pictrsDeleteToast(image.name, res.data.delete_url as string);
446       } else {
447         throw JSON.stringify(res.data);
448       }
449     } else if (res.state === "failed") {
450       i.setState({ imageUploadStatus: undefined });
451       console.error(res.msg);
452       toast(res.msg, "danger");
453
454       throw res.msg;
455     }
456   }
457
458   contentChange() {
459     // Coerces the undefineds to empty strings, for replacing in the DB
460     const content = this.state.content ?? "";
461     this.props.onContentChange?.(content);
462   }
463
464   handleContentChange(i: MarkdownTextArea, event: any) {
465     i.setState({ content: event.target.value });
466     i.contentChange();
467   }
468
469   // Keybind handler
470   // Keybinds inspired by github comment area
471   handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
472     if (event.ctrlKey) {
473       switch (event.key) {
474         case "k": {
475           i.handleInsertLink(i, event);
476           break;
477         }
478         case "Enter": {
479           if (!this.isDisabled) {
480             i.handleSubmit(i, event);
481           }
482
483           break;
484         }
485         case "b": {
486           i.handleInsertBold(i, event);
487           break;
488         }
489         case "i": {
490           i.handleInsertItalic(i, event);
491           break;
492         }
493         case "e": {
494           i.handleInsertCode(i, event);
495           break;
496         }
497         case "8": {
498           i.handleInsertList(i, event);
499           break;
500         }
501         case "s": {
502           i.handleInsertSpoiler(i, event);
503           break;
504         }
505         case "p": {
506           if (i.state.content) i.handlePreviewToggle(i, event);
507           break;
508         }
509         case ".": {
510           i.handleInsertQuote(i, event);
511           break;
512         }
513       }
514     }
515   }
516
517   handlePreviewToggle(i: MarkdownTextArea, event: any) {
518     event.preventDefault();
519     i.setState({ previewMode: !i.state.previewMode });
520   }
521
522   handleLanguageChange(val: number[]) {
523     this.setState({ languageId: val[0] });
524   }
525
526   handleSubmit(i: MarkdownTextArea, event: any) {
527     event.preventDefault();
528     if (i.state.content) {
529       i.setState({ loading: true, submitted: true });
530       i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
531     }
532   }
533
534   handleReplyCancel(i: MarkdownTextArea) {
535     i.props.onReplyCancel?.();
536   }
537
538   handleInsertLink(i: MarkdownTextArea, event: any) {
539     event.preventDefault();
540
541     const textarea: any = document.getElementById(i.id);
542     const start: number = textarea.selectionStart;
543     const end: number = textarea.selectionEnd;
544
545     const content = i.state.content ?? "";
546
547     if (!i.state.content) {
548       i.setState({ content: "" });
549     }
550
551     if (start !== end) {
552       const selectedText = content?.substring(start, end);
553       i.setState({
554         content: `${content?.substring(
555           0,
556           start
557         )}[${selectedText}]()${content?.substring(end)}`,
558       });
559       textarea.focus();
560       setTimeout(() => (textarea.selectionEnd = end + 3), 10);
561     } else {
562       i.setState({ content: `${content} []()` });
563       textarea.focus();
564       setTimeout(() => (textarea.selectionEnd -= 1), 10);
565     }
566     i.contentChange();
567   }
568
569   simpleSurround(chars: string) {
570     this.simpleSurroundBeforeAfter(chars, chars);
571   }
572
573   simpleBeginningofLine(chars: string) {
574     this.simpleSurroundBeforeAfter(`${chars}`, "", "");
575   }
576
577   simpleSurroundBeforeAfter(
578     beforeChars: string,
579     afterChars: string,
580     emptyChars = "___"
581   ) {
582     const content = this.state.content ?? "";
583     if (!this.state.content) {
584       this.setState({ content: "" });
585     }
586     const textarea: any = document.getElementById(this.id);
587     const start: number = textarea.selectionStart;
588     const end: number = textarea.selectionEnd;
589
590     if (start !== end) {
591       const selectedText = content?.substring(start, end);
592       this.setState({
593         content: `${content?.substring(
594           0,
595           start
596         )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
597       });
598     } else {
599       this.setState({
600         content: `${content}${beforeChars}${emptyChars}${afterChars}`,
601       });
602     }
603     this.contentChange();
604
605     textarea.focus();
606
607     if (start !== end) {
608       textarea.setSelectionRange(
609         start + beforeChars.length,
610         end + afterChars.length
611       );
612     } else {
613       textarea.setSelectionRange(
614         start + beforeChars.length,
615         end + emptyChars.length + afterChars.length
616       );
617     }
618
619     setTimeout(() => {
620       autosize.update(textarea);
621     }, 10);
622   }
623
624   handleInsertBold(i: MarkdownTextArea, event: any) {
625     event.preventDefault();
626     i.simpleSurround("**");
627   }
628
629   handleInsertItalic(i: MarkdownTextArea, event: any) {
630     event.preventDefault();
631     i.simpleSurround("*");
632   }
633
634   handleInsertCode(i: MarkdownTextArea, event: any) {
635     event.preventDefault();
636     if (i.getSelectedText().split(/\r*\n/).length > 1) {
637       i.simpleSurroundBeforeAfter("```\n", "\n```");
638     } else {
639       i.simpleSurround("`");
640     }
641   }
642
643   handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
644     event.preventDefault();
645     i.simpleSurround("~~");
646   }
647
648   handleInsertList(i: MarkdownTextArea, event: any) {
649     event.preventDefault();
650     i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
651   }
652
653   handleInsertQuote(i: MarkdownTextArea, event: any) {
654     event.preventDefault();
655     i.simpleBeginningofLine(">");
656   }
657
658   handleInsertHeader(i: MarkdownTextArea, event: any) {
659     event.preventDefault();
660     i.simpleBeginningofLine("#");
661   }
662
663   handleInsertSubscript(i: MarkdownTextArea, event: any) {
664     event.preventDefault();
665     i.simpleSurround("~");
666   }
667
668   handleInsertSuperscript(i: MarkdownTextArea, event: any) {
669     event.preventDefault();
670     i.simpleSurround("^");
671   }
672
673   simpleInsert(chars: string) {
674     const content = this.state.content;
675     if (!content) {
676       this.setState({ content: `${chars} ` });
677     } else {
678       this.setState({
679         content: `${content}\n${chars} `,
680       });
681     }
682
683     const textarea: any = document.getElementById(this.id);
684     textarea.focus();
685     setTimeout(() => {
686       autosize.update(textarea);
687     }, 10);
688     this.contentChange();
689   }
690
691   handleInsertSpoiler(i: MarkdownTextArea, event: any) {
692     event.preventDefault();
693     const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
694     const afterChars = "\n:::\n";
695     i.simpleSurroundBeforeAfter(beforeChars, afterChars);
696   }
697
698   quoteInsert() {
699     const textarea: any = document.getElementById(this.id);
700     const selectedText = window.getSelection()?.toString();
701     const { content } = this.state;
702     if (selectedText) {
703       const quotedText =
704         selectedText
705           .split("\n")
706           .map(t => `> ${t}`)
707           .join("\n") + "\n\n";
708       if (!content) {
709         this.setState({ content: "" });
710       } else {
711         this.setState({ content: `${content}\n` });
712       }
713       this.setState({
714         content: `${content}${quotedText}`,
715       });
716       this.contentChange();
717       // Not sure why this needs a delay
718       setTimeout(() => autosize.update(textarea), 10);
719     }
720   }
721
722   getSelectedText(): string {
723     const { selectionStart: start, selectionEnd: end } =
724       document.getElementById(this.id) as any;
725     return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
726   }
727
728   get isDisabled() {
729     return (
730       this.state.loading ||
731       this.props.disabled ||
732       !!this.state.imageUploadStatus
733     );
734   }
735 }