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);
447 throw JSON.stringify(res.data);
449 } else if (res.state === "failed") {
450 i.setState({ imageUploadStatus: undefined });
451 console.error(res.msg);
452 toast(res.msg, "danger");
459 // Coerces the undefineds to empty strings, for replacing in the DB
460 const content = this.state.content ?? "";
461 this.props.onContentChange?.(content);
464 handleContentChange(i: MarkdownTextArea, event: any) {
465 i.setState({ content: event.target.value });
470 // Keybinds inspired by github comment area
471 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
475 i.handleInsertLink(i, event);
479 if (!this.isDisabled) {
480 i.handleSubmit(i, event);
486 i.handleInsertBold(i, event);
490 i.handleInsertItalic(i, event);
494 i.handleInsertCode(i, event);
498 i.handleInsertList(i, event);
502 i.handleInsertSpoiler(i, event);
506 if (i.state.content) i.handlePreviewToggle(i, event);
510 i.handleInsertQuote(i, event);
517 handlePreviewToggle(i: MarkdownTextArea, event: any) {
518 event.preventDefault();
519 i.setState({ previewMode: !i.state.previewMode });
522 handleLanguageChange(val: number[]) {
523 this.setState({ languageId: val[0] });
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);
534 handleReplyCancel(i: MarkdownTextArea) {
535 i.props.onReplyCancel?.();
538 handleInsertLink(i: MarkdownTextArea, event: any) {
539 event.preventDefault();
541 const textarea: any = document.getElementById(i.id);
542 const start: number = textarea.selectionStart;
543 const end: number = textarea.selectionEnd;
545 const content = i.state.content ?? "";
547 if (!i.state.content) {
548 i.setState({ content: "" });
552 const selectedText = content?.substring(start, end);
554 content: `${content?.substring(
557 )}[${selectedText}]()${content?.substring(end)}`,
560 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
562 i.setState({ content: `${content} []()` });
564 setTimeout(() => (textarea.selectionEnd -= 1), 10);
569 simpleSurround(chars: string) {
570 this.simpleSurroundBeforeAfter(chars, chars);
573 simpleBeginningofLine(chars: string) {
574 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
577 simpleSurroundBeforeAfter(
582 const content = this.state.content ?? "";
583 if (!this.state.content) {
584 this.setState({ content: "" });
586 const textarea: any = document.getElementById(this.id);
587 const start: number = textarea.selectionStart;
588 const end: number = textarea.selectionEnd;
591 const selectedText = content?.substring(start, end);
593 content: `${content?.substring(
596 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
600 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
603 this.contentChange();
608 textarea.setSelectionRange(
609 start + beforeChars.length,
610 end + afterChars.length
613 textarea.setSelectionRange(
614 start + beforeChars.length,
615 end + emptyChars.length + afterChars.length
620 autosize.update(textarea);
624 handleInsertBold(i: MarkdownTextArea, event: any) {
625 event.preventDefault();
626 i.simpleSurround("**");
629 handleInsertItalic(i: MarkdownTextArea, event: any) {
630 event.preventDefault();
631 i.simpleSurround("*");
634 handleInsertCode(i: MarkdownTextArea, event: any) {
635 event.preventDefault();
636 if (i.getSelectedText().split(/\r*\n/).length > 1) {
637 i.simpleSurroundBeforeAfter("```\n", "\n```");
639 i.simpleSurround("`");
643 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
644 event.preventDefault();
645 i.simpleSurround("~~");
648 handleInsertList(i: MarkdownTextArea, event: any) {
649 event.preventDefault();
650 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
653 handleInsertQuote(i: MarkdownTextArea, event: any) {
654 event.preventDefault();
655 i.simpleBeginningofLine(">");
658 handleInsertHeader(i: MarkdownTextArea, event: any) {
659 event.preventDefault();
660 i.simpleBeginningofLine("#");
663 handleInsertSubscript(i: MarkdownTextArea, event: any) {
664 event.preventDefault();
665 i.simpleSurround("~");
668 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
669 event.preventDefault();
670 i.simpleSurround("^");
673 simpleInsert(chars: string) {
674 const content = this.state.content;
676 this.setState({ content: `${chars} ` });
679 content: `${content}\n${chars} `,
683 const textarea: any = document.getElementById(this.id);
686 autosize.update(textarea);
688 this.contentChange();
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);
699 const textarea: any = document.getElementById(this.id);
700 const selectedText = window.getSelection()?.toString();
701 const { content } = this.state;
707 .join("\n") + "\n\n";
709 this.setState({ content: "" });
711 this.setState({ content: `${content}\n` });
714 content: `${content}${quotedText}`,
716 this.contentChange();
717 // Not sure why this needs a delay
718 setTimeout(() => autosize.update(textarea), 10);
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) ?? "" : "";
730 this.state.loading ||
731 this.props.disabled ||
732 !!this.state.imageUploadStatus