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";
10 markdownFieldCharacterLimit,
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";
25 interface MarkdownTextAreaProps {
27 * Initial content inside the textarea
29 initialContent?: string;
31 * Numerical ID of the language to select in dropdown
33 initialLanguageId?: number;
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.
46 * Whether to show the language selector
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
57 interface ImageUploadStatus {
62 interface MarkdownTextAreaState {
66 imageUploadStatus?: ImageUploadStatus;
71 export class MarkdownTextArea extends Component<
72 MarkdownTextAreaProps,
75 private id = `markdown-textarea-${randomStr()}`;
76 private formId = `markdown-form-${randomStr()}`;
80 state: MarkdownTextAreaState = {
81 content: this.props.initialContent,
82 languageId: this.props.initialLanguageId,
88 constructor(props: any, context: any) {
89 super(props, context);
91 this.handleLanguageChange = this.handleLanguageChange.bind(this);
94 this.tribute = setupTribute();
99 const textarea: any = document.getElementById(this.id);
102 this.tribute.attach(textarea);
103 textarea.addEventListener("tribute-replaced", () => {
104 this.setState({ content: textarea.value });
105 autosize.update(textarea);
110 if (this.props.focus) {
114 // TODO this is slow for some reason
119 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
120 if (nextProps.finished) {
123 imageUploadStatus: undefined,
127 if (this.props.replyType) {
128 this.props.onReplyCancel?.();
131 const textarea: any = document.getElementById(this.id);
132 const form: any = document.getElementById(this.formId);
134 setTimeout(() => autosize.update(textarea), 10);
139 const languageId = this.state.languageId;
141 // TODO add these prompts back in at some point
143 // when={!this.props.hideNavigationWarnings && this.state.content}
144 // message={I18NextService.i18n.t("block_leaving")}
148 className="markdown-textarea"
150 onSubmit={linkEvent(this, this.handleSubmit)}
154 !this.props.hideNavigationWarnings &&
155 !!this.state.content &&
156 !this.state.submitted
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)}
167 onEmojiClick={e => this.handleEmoji(this, e)}
168 disabled={this.isDisabled}
170 <form className="btn btn-sm text-muted font-weight-bold">
172 htmlFor={`file-upload-${this.id}`}
174 UserService.Instance.myUserInfo && "pointer"
176 data-tippy-content={I18NextService.i18n.t("upload_image")}
178 {this.state.imageUploadStatus ? (
181 <Icon icon="image" classes="icon-inline" />
185 id={`file-upload-${this.id}`}
187 accept="image/*,video/*"
192 !UserService.Instance.myUserInfo || this.isDisabled
194 onChange={linkEvent(this, this.handleImageUpload)}
197 {this.getFormatButton("header", this.handleInsertHeader)}
198 {this.getFormatButton(
200 this.handleInsertStrikethrough
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(
208 this.handleInsertSuperscript
210 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
212 href={markdownHelpUrl}
213 className="btn btn-sm text-muted font-weight-bold"
214 title={I18NextService.i18n.t("formatting_help")}
217 <Icon icon="help-circle" classes="icon-inline" />
224 className={classNames(
225 "form-control border-0 rounded-top-0 rounded-bottom",
227 "d-none": this.state.previewMode,
230 value={this.state.content}
231 onInput={linkEvent(this, this.handleContentChange)}
232 onPaste={linkEvent(this, this.handleImageUploadPaste)}
233 onKeyDown={linkEvent(this, this.handleKeyBinds)}
235 disabled={this.isDisabled}
238 this.props.maxLength ?? markdownFieldCharacterLimit
240 placeholder={this.props.placeholder}
242 {this.state.previewMode && this.state.content && (
244 className="card border-secondary card-body md-div"
245 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
248 {this.state.imageUploadStatus &&
249 this.state.imageUploadStatus.total > 1 && (
254 value={this.state.imageUploadStatus.uploaded}
255 max={this.state.imageUploadStatus.total}
257 I18NextService.i18n.t("pictures_uploded_progess", {
258 uploaded: this.state.imageUploadStatus.uploaded,
259 total: this.state.imageUploadStatus.total,
265 <label className="visually-hidden" htmlFor={this.id}>
266 {I18NextService.i18n.t("body")}
271 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
272 {this.props.showLanguage && (
275 allLanguages={this.props.allLanguages}
276 // Only set the selected language ID if it exists as an option
277 // in the dropdown; otherwise, set it to 0 (Undetermined)
278 selectedLanguageIds={
279 languageId && this.props.siteLanguages.includes(languageId)
283 siteLanguages={this.props.siteLanguages}
284 onChange={this.handleLanguageChange}
285 disabled={this.isDisabled}
289 {/* A flex expander */}
290 <div className="flex-grow-1"></div>
292 {this.props.replyType && (
295 className="btn btn-sm btn-secondary ms-2"
296 onClick={linkEvent(this, this.handleReplyCancel)}
298 {I18NextService.i18n.t("cancel")}
303 disabled={!this.state.content}
304 className={classNames("btn btn-sm btn-secondary ms-2", {
305 active: this.state.previewMode,
307 onClick={linkEvent(this, this.handlePreviewToggle)}
309 {this.state.previewMode
310 ? I18NextService.i18n.t("edit")
311 : I18NextService.i18n.t("preview")}
313 {this.props.buttonTitle && (
316 className="btn btn-sm btn-secondary ms-2"
317 disabled={this.isDisabled || !this.state.content}
319 {this.state.loading && <Spinner className="me-1" />}
320 {this.props.buttonTitle}
330 type: NoOptionI18nKeys,
331 handleClick: (i: MarkdownTextArea, event: any) => void
333 let iconType: string;
337 iconType = "alert-triangle";
341 iconType = "format_quote";
351 className="btn btn-sm text-muted"
352 data-tippy-content={I18NextService.i18n.t(type)}
353 aria-label={I18NextService.i18n.t(type)}
354 onClick={linkEvent(this, handleClick)}
355 disabled={this.isDisabled}
357 <Icon icon={iconType} classes="icon-inline" />
362 handleEmoji(i: MarkdownTextArea, e: any) {
363 let value = e.native;
365 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
367 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
371 content: `${i.state.content ?? ""} ${value} `,
374 const textarea: any = document.getElementById(i.id);
375 autosize.update(textarea);
378 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
379 const image = event.clipboardData.files[0];
381 i.handleImageUpload(i, image);
385 handleImageUpload(i: MarkdownTextArea, event: any) {
386 const files: File[] = [];
388 event.preventDefault();
389 files.push(...event.target.files);
394 if (files.length > maxUploadImages) {
396 I18NextService.i18n.t("too_many_images_upload", {
397 count: Number(maxUploadImages),
398 formattedCount: numToSI(maxUploadImages),
404 imageUploadStatus: { total: files.length, uploaded: 0 },
407 i.uploadImages(i, files).then(() => {
408 i.setState({ imageUploadStatus: undefined });
413 async uploadImages(i: MarkdownTextArea, files: File[]) {
414 let errorOccurred = false;
415 const filesCopy = [...files];
416 while (filesCopy.length > 0 && !errorOccurred) {
419 filesCopy.splice(0, concurrentImageUpload).map(async file => {
420 await i.uploadSingleImage(i, file);
422 this.setState(({ imageUploadStatus }) => ({
424 ...(imageUploadStatus as Required<ImageUploadStatus>),
425 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
431 errorOccurred = true;
436 async uploadSingleImage(i: MarkdownTextArea, image: File) {
437 const res = await HttpService.client.uploadImage({ image });
438 console.log("pictrs upload:");
440 if (res.state === "success") {
441 if (res.data.msg === "ok") {
442 const imageMarkdown = `![](${res.data.url})`;
443 i.setState(({ content }) => ({
444 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
447 const textarea: any = document.getElementById(i.id);
448 autosize.update(textarea);
449 pictrsDeleteToast(image.name, res.data.delete_url as string);
451 throw JSON.stringify(res.data);
453 } else if (res.state === "failed") {
454 i.setState({ imageUploadStatus: undefined });
455 console.error(res.msg);
456 toast(res.msg, "danger");
463 // Coerces the undefineds to empty strings, for replacing in the DB
464 const content = this.state.content ?? "";
465 this.props.onContentChange?.(content);
468 handleContentChange(i: MarkdownTextArea, event: any) {
469 i.setState({ content: event.target.value });
474 // Keybinds inspired by github comment area
475 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
479 i.handleInsertLink(i, event);
483 if (!this.isDisabled) {
484 i.handleSubmit(i, event);
490 i.handleInsertBold(i, event);
494 i.handleInsertItalic(i, event);
498 i.handleInsertCode(i, event);
502 i.handleInsertList(i, event);
506 i.handleInsertSpoiler(i, event);
510 if (i.state.content) i.handlePreviewToggle(i, event);
514 i.handleInsertQuote(i, event);
521 handlePreviewToggle(i: MarkdownTextArea, event: any) {
522 event.preventDefault();
523 i.setState({ previewMode: !i.state.previewMode });
526 handleLanguageChange(val: number[]) {
527 this.setState({ languageId: val[0] });
530 handleSubmit(i: MarkdownTextArea, event: any) {
531 event.preventDefault();
532 if (i.state.content) {
533 i.setState({ loading: true, submitted: true });
534 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
538 handleReplyCancel(i: MarkdownTextArea) {
539 i.props.onReplyCancel?.();
542 handleInsertLink(i: MarkdownTextArea, event: any) {
543 event.preventDefault();
545 const textarea: any = document.getElementById(i.id);
546 const start: number = textarea.selectionStart;
547 const end: number = textarea.selectionEnd;
549 const content = i.state.content ?? "";
551 if (!i.state.content) {
552 i.setState({ content: "" });
556 const selectedText = content?.substring(start, end);
558 content: `${content?.substring(
561 )}[${selectedText}]()${content?.substring(end)}`,
564 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
566 i.setState({ content: `${content} []()` });
568 setTimeout(() => (textarea.selectionEnd -= 1), 10);
573 simpleSurround(chars: string) {
574 this.simpleSurroundBeforeAfter(chars, chars);
577 simpleBeginningofLine(chars: string) {
578 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
581 simpleSurroundBeforeAfter(
586 const content = this.state.content ?? "";
587 if (!this.state.content) {
588 this.setState({ content: "" });
590 const textarea: any = document.getElementById(this.id);
591 const start: number = textarea.selectionStart;
592 const end: number = textarea.selectionEnd;
595 const selectedText = content?.substring(start, end);
597 content: `${content?.substring(
600 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
604 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
607 this.contentChange();
612 textarea.setSelectionRange(
613 start + beforeChars.length,
614 end + afterChars.length
617 textarea.setSelectionRange(
618 start + beforeChars.length,
619 end + emptyChars.length + afterChars.length
624 autosize.update(textarea);
628 handleInsertBold(i: MarkdownTextArea, event: any) {
629 event.preventDefault();
630 i.simpleSurround("**");
633 handleInsertItalic(i: MarkdownTextArea, event: any) {
634 event.preventDefault();
635 i.simpleSurround("*");
638 handleInsertCode(i: MarkdownTextArea, event: any) {
639 event.preventDefault();
640 if (i.getSelectedText().split(/\r*\n/).length > 1) {
641 i.simpleSurroundBeforeAfter("```\n", "\n```");
643 i.simpleSurround("`");
647 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
648 event.preventDefault();
649 i.simpleSurround("~~");
652 handleInsertList(i: MarkdownTextArea, event: any) {
653 event.preventDefault();
654 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
657 handleInsertQuote(i: MarkdownTextArea, event: any) {
658 event.preventDefault();
659 i.simpleBeginningofLine(">");
662 handleInsertHeader(i: MarkdownTextArea, event: any) {
663 event.preventDefault();
664 i.simpleBeginningofLine("#");
667 handleInsertSubscript(i: MarkdownTextArea, event: any) {
668 event.preventDefault();
669 i.simpleSurround("~");
672 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
673 event.preventDefault();
674 i.simpleSurround("^");
677 simpleInsert(chars: string) {
678 const content = this.state.content;
680 this.setState({ content: `${chars} ` });
683 content: `${content}\n${chars} `,
687 const textarea: any = document.getElementById(this.id);
690 autosize.update(textarea);
692 this.contentChange();
695 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
696 event.preventDefault();
697 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
698 const afterChars = "\n:::\n";
699 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
703 const textarea: any = document.getElementById(this.id);
704 const selectedText = window.getSelection()?.toString();
705 const { content } = this.state;
711 .join("\n") + "\n\n";
713 this.setState({ content: "" });
715 this.setState({ content: `${content}\n` });
718 content: `${content}${quotedText}`,
720 this.contentChange();
721 // Not sure why this needs a delay
722 setTimeout(() => autosize.update(textarea), 10);
726 getSelectedText(): string {
727 const { selectionStart: start, selectionEnd: end } =
728 document.getElementById(this.id) as any;
729 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
734 this.state.loading ||
735 this.props.disabled ||
736 !!this.state.imageUploadStatus