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">
163 className={`d-flex flex-wrap border-bottom ${
164 this.isDisabled ? "no-click" : ""
167 {this.getFormatButton("bold", this.handleInsertBold)}
168 {this.getFormatButton("italic", this.handleInsertItalic)}
169 {this.getFormatButton("link", this.handleInsertLink)}
171 onEmojiClick={e => this.handleEmoji(this, e)}
173 <form className="btn btn-sm text-muted fw-bold">
175 htmlFor={`file-upload-${this.id}`}
177 UserService.Instance.myUserInfo && "pointer"
179 data-tippy-content={I18NextService.i18n.t("upload_image")}
181 {this.state.imageUploadStatus ? (
184 <Icon icon="image" classes="icon-inline" />
188 id={`file-upload-${this.id}`}
190 accept="image/*,video/*"
194 disabled={!UserService.Instance.myUserInfo}
195 onChange={linkEvent(this, this.handleImageUpload)}
198 {this.getFormatButton("header", this.handleInsertHeader)}
199 {this.getFormatButton(
201 this.handleInsertStrikethrough
203 {this.getFormatButton("quote", this.handleInsertQuote)}
204 {this.getFormatButton("list", this.handleInsertList)}
205 {this.getFormatButton("code", this.handleInsertCode)}
206 {this.getFormatButton("subscript", this.handleInsertSubscript)}
207 {this.getFormatButton(
209 this.handleInsertSuperscript
211 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
213 href={markdownHelpUrl}
214 className="btn btn-sm text-muted fw-bold"
215 title={I18NextService.i18n.t("formatting_help")}
218 <Icon icon="help-circle" classes="icon-inline" />
225 className={classNames(
226 "form-control border-0 rounded-top-0 rounded-bottom",
228 "d-none": this.state.previewMode,
231 value={this.state.content}
232 onInput={linkEvent(this, this.handleContentChange)}
233 onPaste={linkEvent(this, this.handleImageUploadPaste)}
234 onKeyDown={linkEvent(this, this.handleKeyBinds)}
236 disabled={this.isDisabled}
239 this.props.maxLength ?? markdownFieldCharacterLimit
241 placeholder={this.props.placeholder}
243 {this.state.previewMode && this.state.content && (
245 className="card border-secondary card-body md-div"
246 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
249 {this.state.imageUploadStatus &&
250 this.state.imageUploadStatus.total > 1 && (
255 value={this.state.imageUploadStatus.uploaded}
256 max={this.state.imageUploadStatus.total}
258 I18NextService.i18n.t("pictures_uploded_progess", {
259 uploaded: this.state.imageUploadStatus.uploaded,
260 total: this.state.imageUploadStatus.total,
266 <label className="visually-hidden" htmlFor={this.id}>
267 {I18NextService.i18n.t("body")}
272 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
273 {this.props.showLanguage && (
276 allLanguages={this.props.allLanguages}
277 // Only set the selected language ID if it exists as an option
278 // in the dropdown; otherwise, set it to 0 (Undetermined)
279 selectedLanguageIds={
280 languageId && this.props.siteLanguages.includes(languageId)
284 siteLanguages={this.props.siteLanguages}
285 onChange={this.handleLanguageChange}
286 disabled={this.isDisabled}
290 {/* A flex expander */}
291 <div className="flex-grow-1"></div>
293 {this.props.replyType && (
296 className="btn btn-sm btn-secondary ms-2"
297 onClick={linkEvent(this, this.handleReplyCancel)}
299 {I18NextService.i18n.t("cancel")}
304 disabled={!this.state.content}
305 className={classNames("btn btn-sm btn-secondary ms-2", {
306 active: this.state.previewMode,
308 onClick={linkEvent(this, this.handlePreviewToggle)}
310 {this.state.previewMode
311 ? I18NextService.i18n.t("edit")
312 : I18NextService.i18n.t("preview")}
314 {this.props.buttonTitle && (
317 className="btn btn-sm btn-secondary ms-2"
318 disabled={this.isDisabled || !this.state.content}
320 {this.state.loading && <Spinner className="me-1" />}
321 {this.props.buttonTitle}
331 type: NoOptionI18nKeys,
332 handleClick: (i: MarkdownTextArea, event: any) => void
334 let iconType: string;
338 iconType = "alert-triangle";
342 iconType = "format_quote";
352 className="btn btn-sm text-muted"
353 data-tippy-content={I18NextService.i18n.t(type)}
354 aria-label={I18NextService.i18n.t(type)}
355 onClick={linkEvent(this, handleClick)}
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