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={classNames("d-flex flex-wrap border-bottom", {
164 "no-click": this.isDisabled,
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 selectedLanguageIds={
278 languageId ? Array.of(languageId) : undefined
280 siteLanguages={this.props.siteLanguages}
281 onChange={this.handleLanguageChange}
282 disabled={this.isDisabled}
286 {/* A flex expander */}
287 <div className="flex-grow-1"></div>
289 {this.props.replyType && (
292 className="btn btn-sm btn-secondary ms-2"
293 onClick={linkEvent(this, this.handleReplyCancel)}
295 {I18NextService.i18n.t("cancel")}
300 disabled={!this.state.content}
301 className={classNames("btn btn-sm btn-secondary ms-2", {
302 active: this.state.previewMode,
304 onClick={linkEvent(this, this.handlePreviewToggle)}
306 {this.state.previewMode
307 ? I18NextService.i18n.t("edit")
308 : I18NextService.i18n.t("preview")}
310 {this.props.buttonTitle && (
313 className="btn btn-sm btn-secondary ms-2"
314 disabled={this.isDisabled || !this.state.content}
316 {this.state.loading && <Spinner className="me-1" />}
317 {this.props.buttonTitle}
327 type: NoOptionI18nKeys,
328 handleClick: (i: MarkdownTextArea, event: any) => void
330 let iconType: string;
334 iconType = "alert-triangle";
338 iconType = "format_quote";
348 className="btn btn-sm text-muted"
349 data-tippy-content={I18NextService.i18n.t(type)}
350 aria-label={I18NextService.i18n.t(type)}
351 onClick={linkEvent(this, handleClick)}
353 <Icon icon={iconType} classes="icon-inline" />
358 handleEmoji(i: MarkdownTextArea, e: any) {
359 let value = e.native;
361 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
363 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
367 content: `${i.state.content ?? ""} ${value} `,
370 const textarea: any = document.getElementById(i.id);
371 autosize.update(textarea);
374 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
375 const image = event.clipboardData.files[0];
377 i.handleImageUpload(i, image);
381 handleImageUpload(i: MarkdownTextArea, event: any) {
382 const files: File[] = [];
384 event.preventDefault();
385 files.push(...event.target.files);
390 if (files.length > maxUploadImages) {
392 I18NextService.i18n.t("too_many_images_upload", {
393 count: Number(maxUploadImages),
394 formattedCount: numToSI(maxUploadImages),
400 imageUploadStatus: { total: files.length, uploaded: 0 },
403 i.uploadImages(i, files).then(() => {
404 i.setState({ imageUploadStatus: undefined });
409 async uploadImages(i: MarkdownTextArea, files: File[]) {
410 let errorOccurred = false;
411 const filesCopy = [...files];
412 while (filesCopy.length > 0 && !errorOccurred) {
415 filesCopy.splice(0, concurrentImageUpload).map(async file => {
416 await i.uploadSingleImage(i, file);
418 this.setState(({ imageUploadStatus }) => ({
420 ...(imageUploadStatus as Required<ImageUploadStatus>),
421 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
427 errorOccurred = true;
432 async uploadSingleImage(i: MarkdownTextArea, image: File) {
433 const res = await HttpService.client.uploadImage({ image });
434 console.log("pictrs upload:");
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,
443 const textarea: any = document.getElementById(i.id);
444 autosize.update(textarea);
445 pictrsDeleteToast(image.name, res.data.delete_url as string);
446 } else if (res.data.msg === "too_large") {
447 toast(I18NextService.i18n.t("upload_too_large"), "danger");
448 i.setState({ imageUploadStatus: undefined });
449 throw JSON.stringify(res.data);
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