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 fw-bold">
172 htmlFor={`file-upload-${this.id}`}
173 // TODO: Fix this linting violation
174 // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex
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/*"
195 !UserService.Instance.myUserInfo || this.isDisabled
197 onChange={linkEvent(this, this.handleImageUpload)}
200 {this.getFormatButton("header", this.handleInsertHeader)}
201 {this.getFormatButton(
203 this.handleInsertStrikethrough
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(
211 this.handleInsertSuperscript
213 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
215 href={markdownHelpUrl}
216 className="btn btn-sm text-muted fw-bold"
217 title={I18NextService.i18n.t("formatting_help")}
220 <Icon icon="help-circle" classes="icon-inline" />
227 className={classNames(
228 "form-control border-0 rounded-top-0 rounded-bottom",
230 "d-none": this.state.previewMode,
233 value={this.state.content}
234 onInput={linkEvent(this, this.handleContentChange)}
235 onPaste={linkEvent(this, this.handleImageUploadPaste)}
236 onKeyDown={linkEvent(this, this.handleKeyBinds)}
238 disabled={this.isDisabled}
241 this.props.maxLength ?? markdownFieldCharacterLimit
243 placeholder={this.props.placeholder}
245 {this.state.previewMode && this.state.content && (
247 className="card border-secondary card-body md-div"
248 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
251 {this.state.imageUploadStatus &&
252 this.state.imageUploadStatus.total > 1 && (
257 value={this.state.imageUploadStatus.uploaded}
258 max={this.state.imageUploadStatus.total}
260 I18NextService.i18n.t("pictures_uploded_progess", {
261 uploaded: this.state.imageUploadStatus.uploaded,
262 total: this.state.imageUploadStatus.total,
268 <label className="visually-hidden" htmlFor={this.id}>
269 {I18NextService.i18n.t("body")}
274 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
275 {this.props.showLanguage && (
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)
286 siteLanguages={this.props.siteLanguages}
287 onChange={this.handleLanguageChange}
288 disabled={this.isDisabled}
292 {/* A flex expander */}
293 <div className="flex-grow-1"></div>
295 {this.props.replyType && (
298 className="btn btn-sm btn-secondary ms-2"
299 onClick={linkEvent(this, this.handleReplyCancel)}
301 {I18NextService.i18n.t("cancel")}
306 disabled={!this.state.content}
307 className={classNames("btn btn-sm btn-secondary ms-2", {
308 active: this.state.previewMode,
310 onClick={linkEvent(this, this.handlePreviewToggle)}
312 {this.state.previewMode
313 ? I18NextService.i18n.t("edit")
314 : I18NextService.i18n.t("preview")}
316 {this.props.buttonTitle && (
319 className="btn btn-sm btn-secondary ms-2"
320 disabled={this.isDisabled || !this.state.content}
322 {this.state.loading && <Spinner className="me-1" />}
323 {this.props.buttonTitle}
333 type: NoOptionI18nKeys,
334 handleClick: (i: MarkdownTextArea, event: any) => void
336 let iconType: string;
340 iconType = "alert-triangle";
344 iconType = "format_quote";
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}
360 <Icon icon={iconType} classes="icon-inline" />
365 handleEmoji(i: MarkdownTextArea, e: any) {
366 let value = e.native;
368 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
370 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
374 content: `${i.state.content ?? ""} ${value} `,
377 const textarea: any = document.getElementById(i.id);
378 autosize.update(textarea);
381 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
382 const image = event.clipboardData.files[0];
384 i.handleImageUpload(i, image);
388 handleImageUpload(i: MarkdownTextArea, event: any) {
389 const files: File[] = [];
391 event.preventDefault();
392 files.push(...event.target.files);
397 if (files.length > maxUploadImages) {
399 I18NextService.i18n.t("too_many_images_upload", {
400 count: Number(maxUploadImages),
401 formattedCount: numToSI(maxUploadImages),
407 imageUploadStatus: { total: files.length, uploaded: 0 },
410 i.uploadImages(i, files).then(() => {
411 i.setState({ imageUploadStatus: undefined });
416 async uploadImages(i: MarkdownTextArea, files: File[]) {
417 let errorOccurred = false;
418 const filesCopy = [...files];
419 while (filesCopy.length > 0 && !errorOccurred) {
422 filesCopy.splice(0, concurrentImageUpload).map(async file => {
423 await i.uploadSingleImage(i, file);
425 this.setState(({ imageUploadStatus }) => ({
427 ...(imageUploadStatus as Required<ImageUploadStatus>),
428 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
434 errorOccurred = true;
439 async uploadSingleImage(i: MarkdownTextArea, image: File) {
440 const res = await HttpService.client.uploadImage({ image });
441 console.log("pictrs upload:");
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,
450 const textarea: any = document.getElementById(i.id);
451 autosize.update(textarea);
452 pictrsDeleteToast(image.name, res.data.delete_url as string);
454 throw JSON.stringify(res.data);
456 } else if (res.state === "failed") {
457 i.setState({ imageUploadStatus: undefined });
458 console.error(res.msg);
459 toast(res.msg, "danger");
466 // Coerces the undefineds to empty strings, for replacing in the DB
467 const content = this.state.content ?? "";
468 this.props.onContentChange?.(content);
471 handleContentChange(i: MarkdownTextArea, event: any) {
472 i.setState({ content: event.target.value });
477 // Keybinds inspired by github comment area
478 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
482 i.handleInsertLink(i, event);
486 if (!this.isDisabled) {
487 i.handleSubmit(i, event);
493 i.handleInsertBold(i, event);
497 i.handleInsertItalic(i, event);
501 i.handleInsertCode(i, event);
505 i.handleInsertList(i, event);
509 i.handleInsertSpoiler(i, event);
513 if (i.state.content) i.handlePreviewToggle(i, event);
517 i.handleInsertQuote(i, event);
524 handlePreviewToggle(i: MarkdownTextArea, event: any) {
525 event.preventDefault();
526 i.setState({ previewMode: !i.state.previewMode });
529 handleLanguageChange(val: number[]) {
530 this.setState({ languageId: val[0] });
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);
541 handleReplyCancel(i: MarkdownTextArea) {
542 i.props.onReplyCancel?.();
545 handleInsertLink(i: MarkdownTextArea, event: any) {
546 event.preventDefault();
548 const textarea: any = document.getElementById(i.id);
549 const start: number = textarea.selectionStart;
550 const end: number = textarea.selectionEnd;
552 const content = i.state.content ?? "";
554 if (!i.state.content) {
555 i.setState({ content: "" });
559 const selectedText = content?.substring(start, end);
561 content: `${content?.substring(
564 )}[${selectedText}]()${content?.substring(end)}`,
567 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
569 i.setState({ content: `${content} []()` });
571 setTimeout(() => (textarea.selectionEnd -= 1), 10);
576 simpleSurround(chars: string) {
577 this.simpleSurroundBeforeAfter(chars, chars);
580 simpleBeginningofLine(chars: string) {
581 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
584 simpleSurroundBeforeAfter(
589 const content = this.state.content ?? "";
590 if (!this.state.content) {
591 this.setState({ content: "" });
593 const textarea: any = document.getElementById(this.id);
594 const start: number = textarea.selectionStart;
595 const end: number = textarea.selectionEnd;
598 const selectedText = content?.substring(start, end);
600 content: `${content?.substring(
603 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
607 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
610 this.contentChange();
615 textarea.setSelectionRange(
616 start + beforeChars.length,
617 end + afterChars.length
620 textarea.setSelectionRange(
621 start + beforeChars.length,
622 end + emptyChars.length + afterChars.length
627 autosize.update(textarea);
631 handleInsertBold(i: MarkdownTextArea, event: any) {
632 event.preventDefault();
633 i.simpleSurround("**");
636 handleInsertItalic(i: MarkdownTextArea, event: any) {
637 event.preventDefault();
638 i.simpleSurround("*");
641 handleInsertCode(i: MarkdownTextArea, event: any) {
642 event.preventDefault();
643 if (i.getSelectedText().split(/\r*\n/).length > 1) {
644 i.simpleSurroundBeforeAfter("```\n", "\n```");
646 i.simpleSurround("`");
650 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
651 event.preventDefault();
652 i.simpleSurround("~~");
655 handleInsertList(i: MarkdownTextArea, event: any) {
656 event.preventDefault();
657 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
660 handleInsertQuote(i: MarkdownTextArea, event: any) {
661 event.preventDefault();
662 i.simpleBeginningofLine(">");
665 handleInsertHeader(i: MarkdownTextArea, event: any) {
666 event.preventDefault();
667 i.simpleBeginningofLine("#");
670 handleInsertSubscript(i: MarkdownTextArea, event: any) {
671 event.preventDefault();
672 i.simpleSurround("~");
675 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
676 event.preventDefault();
677 i.simpleSurround("^");
680 simpleInsert(chars: string) {
681 const content = this.state.content;
683 this.setState({ content: `${chars} ` });
686 content: `${content}\n${chars} `,
690 const textarea: any = document.getElementById(this.id);
693 autosize.update(textarea);
695 this.contentChange();
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);
706 const textarea: any = document.getElementById(this.id);
707 const selectedText = window.getSelection()?.toString();
708 const { content } = this.state;
714 .join("\n") + "\n\n";
716 this.setState({ content: "" });
718 this.setState({ content: `${content}\n` });
721 content: `${content}${quotedText}`,
723 this.contentChange();
724 // Not sure why this needs a delay
725 setTimeout(() => autosize.update(textarea), 10);
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) ?? "" : "";
737 this.state.loading ||
738 this.props.disabled ||
739 !!this.state.imageUploadStatus