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 selectedLanguageIds={
277 languageId ? Array.of(languageId) : undefined
279 siteLanguages={this.props.siteLanguages}
280 onChange={this.handleLanguageChange}
281 disabled={this.isDisabled}
285 {/* A flex expander */}
286 <div className="flex-grow-1"></div>
288 {this.props.replyType && (
291 className="btn btn-sm btn-secondary ms-2"
292 onClick={linkEvent(this, this.handleReplyCancel)}
294 {I18NextService.i18n.t("cancel")}
299 disabled={!this.state.content}
300 className={classNames("btn btn-sm btn-secondary ms-2", {
301 active: this.state.previewMode,
303 onClick={linkEvent(this, this.handlePreviewToggle)}
305 {this.state.previewMode
306 ? I18NextService.i18n.t("edit")
307 : I18NextService.i18n.t("preview")}
309 {this.props.buttonTitle && (
312 className="btn btn-sm btn-secondary ms-2"
313 disabled={this.isDisabled || !this.state.content}
315 {this.state.loading && <Spinner className="me-1" />}
316 {this.props.buttonTitle}
326 type: NoOptionI18nKeys,
327 handleClick: (i: MarkdownTextArea, event: any) => void
329 let iconType: string;
333 iconType = "alert-triangle";
337 iconType = "format_quote";
347 className="btn btn-sm text-muted"
348 data-tippy-content={I18NextService.i18n.t(type)}
349 aria-label={I18NextService.i18n.t(type)}
350 onClick={linkEvent(this, handleClick)}
351 disabled={this.isDisabled}
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