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
45 * Whether to show the language selector
47 showLanguage?: boolean;
48 hideNavigationWarnings?: boolean;
49 onContentChange?(val: string): void;
50 onReplyCancel?(): void;
51 onSubmit?(content: string, formId: string, languageId?: number): void;
52 allLanguages: Language[]; // TODO should probably be nullable
53 siteLanguages: number[]; // TODO same
56 interface ImageUploadStatus {
61 interface MarkdownTextAreaState {
65 imageUploadStatus?: ImageUploadStatus;
70 export class MarkdownTextArea extends Component<
71 MarkdownTextAreaProps,
74 private id = `markdown-textarea-${randomStr()}`;
75 private formId = `markdown-form-${randomStr()}`;
79 state: MarkdownTextAreaState = {
80 content: this.props.initialContent,
81 languageId: this.props.initialLanguageId,
87 constructor(props: any, context: any) {
88 super(props, context);
90 this.handleLanguageChange = this.handleLanguageChange.bind(this);
93 this.tribute = setupTribute();
98 const textarea: any = document.getElementById(this.id);
101 this.tribute.attach(textarea);
102 textarea.addEventListener("tribute-replaced", () => {
103 this.setState({ content: textarea.value });
104 autosize.update(textarea);
109 if (this.props.focus) {
113 // TODO this is slow for some reason
118 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
119 if (nextProps.finished) {
122 imageUploadStatus: undefined,
126 if (this.props.replyType) {
127 this.props.onReplyCancel?.();
130 const textarea: any = document.getElementById(this.id);
131 const form: any = document.getElementById(this.formId);
133 setTimeout(() => autosize.update(textarea), 10);
138 const languageId = this.state.languageId;
140 // TODO add these prompts back in at some point
142 // when={!this.props.hideNavigationWarnings && this.state.content}
143 // message={I18NextService.i18n.t("block_leaving")}
147 className="markdown-textarea"
149 onSubmit={linkEvent(this, this.handleSubmit)}
153 !this.props.hideNavigationWarnings &&
154 !!this.state.content &&
155 !this.state.submitted
158 <div className="mb-3 row">
159 <div className="col-12">
160 <div className="rounded bg-light border">
161 <div className="d-flex flex-wrap border-bottom">
162 {this.getFormatButton("bold", this.handleInsertBold)}
163 {this.getFormatButton("italic", this.handleInsertItalic)}
164 {this.getFormatButton("link", this.handleInsertLink)}
166 onEmojiClick={e => this.handleEmoji(this, e)}
167 disabled={this.isDisabled}
169 <form className="btn btn-sm text-muted font-weight-bold">
171 htmlFor={`file-upload-${this.id}`}
173 UserService.Instance.myUserInfo && "pointer"
175 data-tippy-content={I18NextService.i18n.t("upload_image")}
177 {this.state.imageUploadStatus ? (
180 <Icon icon="image" classes="icon-inline" />
184 id={`file-upload-${this.id}`}
186 accept="image/*,video/*"
191 !UserService.Instance.myUserInfo || this.isDisabled
193 onChange={linkEvent(this, this.handleImageUpload)}
196 {this.getFormatButton("header", this.handleInsertHeader)}
197 {this.getFormatButton(
199 this.handleInsertStrikethrough
201 {this.getFormatButton("quote", this.handleInsertQuote)}
202 {this.getFormatButton("list", this.handleInsertList)}
203 {this.getFormatButton("code", this.handleInsertCode)}
204 {this.getFormatButton("subscript", this.handleInsertSubscript)}
205 {this.getFormatButton(
207 this.handleInsertSuperscript
209 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
211 href={markdownHelpUrl}
212 className="btn btn-sm text-muted font-weight-bold"
213 title={I18NextService.i18n.t("formatting_help")}
216 <Icon icon="help-circle" classes="icon-inline" />
223 className={classNames(
224 "form-control border-0 rounded-top-0 rounded-bottom",
226 "d-none": this.state.previewMode,
229 value={this.state.content}
230 onInput={linkEvent(this, this.handleContentChange)}
231 onPaste={linkEvent(this, this.handleImageUploadPaste)}
232 onKeyDown={linkEvent(this, this.handleKeyBinds)}
234 disabled={this.isDisabled}
237 this.props.maxLength ?? markdownFieldCharacterLimit
239 placeholder={this.props.placeholder}
241 {this.state.previewMode && this.state.content && (
243 className="card border-secondary card-body md-div"
244 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
247 {this.state.imageUploadStatus &&
248 this.state.imageUploadStatus.total > 1 && (
253 value={this.state.imageUploadStatus.uploaded}
254 max={this.state.imageUploadStatus.total}
256 I18NextService.i18n.t("pictures_uploded_progess", {
257 uploaded: this.state.imageUploadStatus.uploaded,
258 total: this.state.imageUploadStatus.total,
264 <label className="visually-hidden" htmlFor={this.id}>
265 {I18NextService.i18n.t("body")}
270 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
271 {this.props.showLanguage && (
274 allLanguages={this.props.allLanguages}
275 selectedLanguageIds={
276 languageId ? Array.of(languageId) : undefined
278 siteLanguages={this.props.siteLanguages}
279 onChange={this.handleLanguageChange}
280 disabled={this.isDisabled}
284 {/* A flex expander */}
285 <div className="flex-grow-1"></div>
287 {this.props.replyType && (
290 className="btn btn-sm btn-secondary ms-2"
291 onClick={linkEvent(this, this.handleReplyCancel)}
293 {I18NextService.i18n.t("cancel")}
298 disabled={!this.state.content}
299 className={classNames("btn btn-sm btn-secondary ms-2", {
300 active: this.state.previewMode
302 onClick={linkEvent(this, this.handlePreviewToggle)}
304 {this.state.previewMode
305 ? I18NextService.i18n.t("edit")
306 : I18NextService.i18n.t("preview")}
308 {this.props.buttonTitle && (
311 className="btn btn-sm btn-secondary ms-2"
312 disabled={this.isDisabled || !this.state.content}
314 {this.state.loading && <Spinner className="me-1" />}
315 {this.props.buttonTitle}
325 type: NoOptionI18nKeys,
326 handleClick: (i: MarkdownTextArea, event: any) => void
328 let iconType: string;
332 iconType = "alert-triangle";
336 iconType = "format_quote";
346 className="btn btn-sm text-muted"
347 data-tippy-content={I18NextService.i18n.t(type)}
348 aria-label={I18NextService.i18n.t(type)}
349 onClick={linkEvent(this, handleClick)}
350 disabled={this.isDisabled}
352 <Icon icon={iconType} classes="icon-inline" />
357 handleEmoji(i: MarkdownTextArea, e: any) {
358 let value = e.native;
360 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
362 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
366 content: `${i.state.content ?? ""} ${value} `,
369 const textarea: any = document.getElementById(i.id);
370 autosize.update(textarea);
373 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
374 const image = event.clipboardData.files[0];
376 i.handleImageUpload(i, image);
380 handleImageUpload(i: MarkdownTextArea, event: any) {
381 const files: File[] = [];
383 event.preventDefault();
384 files.push(...event.target.files);
389 if (files.length > maxUploadImages) {
391 I18NextService.i18n.t("too_many_images_upload", {
392 count: Number(maxUploadImages),
393 formattedCount: numToSI(maxUploadImages),
399 imageUploadStatus: { total: files.length, uploaded: 0 },
402 i.uploadImages(i, files).then(() => {
403 i.setState({ imageUploadStatus: undefined });
408 async uploadImages(i: MarkdownTextArea, files: File[]) {
409 let errorOccurred = false;
410 const filesCopy = [...files];
411 while (filesCopy.length > 0 && !errorOccurred) {
414 filesCopy.splice(0, concurrentImageUpload).map(async file => {
415 await i.uploadSingleImage(i, file);
417 this.setState(({ imageUploadStatus }) => ({
419 ...(imageUploadStatus as Required<ImageUploadStatus>),
420 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
426 errorOccurred = true;
431 async uploadSingleImage(i: MarkdownTextArea, image: File) {
432 const res = await HttpService.client.uploadImage({ image });
433 console.log("pictrs upload:");
435 if (res.state === "success") {
436 if (res.data.msg === "ok") {
437 const imageMarkdown = `![](${res.data.url})`;
438 i.setState(({ content }) => ({
439 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
442 const textarea: any = document.getElementById(i.id);
443 autosize.update(textarea);
444 pictrsDeleteToast(image.name, res.data.delete_url as string);
446 throw JSON.stringify(res.data);
448 } else if (res.state === "failed") {
449 i.setState({ imageUploadStatus: undefined });
450 console.error(res.msg);
451 toast(res.msg, "danger");
458 // Coerces the undefineds to empty strings, for replacing in the DB
459 const content = this.state.content ?? "";
460 this.props.onContentChange?.(content);
463 handleContentChange(i: MarkdownTextArea, event: any) {
464 i.setState({ content: event.target.value });
469 // Keybinds inspired by github comment area
470 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
474 i.handleInsertLink(i, event);
478 if (!this.isDisabled) {
479 i.handleSubmit(i, event);
485 i.handleInsertBold(i, event);
489 i.handleInsertItalic(i, event);
493 i.handleInsertCode(i, event);
497 i.handleInsertList(i, event);
501 i.handleInsertSpoiler(i, event);
505 if (i.state.content) i.handlePreviewToggle(i, event);
509 i.handleInsertQuote(i, event);
516 handlePreviewToggle(i: MarkdownTextArea, event: any) {
517 event.preventDefault();
518 i.setState({ previewMode: !i.state.previewMode });
521 handleLanguageChange(val: number[]) {
522 this.setState({ languageId: val[0] });
525 handleSubmit(i: MarkdownTextArea, event: any) {
526 event.preventDefault();
527 if (i.state.content) {
528 i.setState({ loading: true, submitted: true });
529 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
533 handleReplyCancel(i: MarkdownTextArea) {
534 i.props.onReplyCancel?.();
537 handleInsertLink(i: MarkdownTextArea, event: any) {
538 event.preventDefault();
540 const textarea: any = document.getElementById(i.id);
541 const start: number = textarea.selectionStart;
542 const end: number = textarea.selectionEnd;
544 const content = i.state.content ?? "";
546 if (!i.state.content) {
547 i.setState({ content: "" });
551 const selectedText = content?.substring(start, end);
553 content: `${content?.substring(
556 )}[${selectedText}]()${content?.substring(end)}`,
559 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
561 i.setState({ content: `${content} []()` });
563 setTimeout(() => (textarea.selectionEnd -= 1), 10);
568 simpleSurround(chars: string) {
569 this.simpleSurroundBeforeAfter(chars, chars);
572 simpleBeginningofLine(chars: string) {
573 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
576 simpleSurroundBeforeAfter(
581 const content = this.state.content ?? "";
582 if (!this.state.content) {
583 this.setState({ content: "" });
585 const textarea: any = document.getElementById(this.id);
586 const start: number = textarea.selectionStart;
587 const end: number = textarea.selectionEnd;
590 const selectedText = content?.substring(start, end);
592 content: `${content?.substring(
595 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
599 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
602 this.contentChange();
607 textarea.setSelectionRange(
608 start + beforeChars.length,
609 end + afterChars.length
612 textarea.setSelectionRange(
613 start + beforeChars.length,
614 end + emptyChars.length + afterChars.length
619 autosize.update(textarea);
623 handleInsertBold(i: MarkdownTextArea, event: any) {
624 event.preventDefault();
625 i.simpleSurround("**");
628 handleInsertItalic(i: MarkdownTextArea, event: any) {
629 event.preventDefault();
630 i.simpleSurround("*");
633 handleInsertCode(i: MarkdownTextArea, event: any) {
634 event.preventDefault();
635 if (i.getSelectedText().split(/\r*\n/).length > 1) {
636 i.simpleSurroundBeforeAfter("```\n", "\n```");
638 i.simpleSurround("`");
642 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
643 event.preventDefault();
644 i.simpleSurround("~~");
647 handleInsertList(i: MarkdownTextArea, event: any) {
648 event.preventDefault();
649 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
652 handleInsertQuote(i: MarkdownTextArea, event: any) {
653 event.preventDefault();
654 i.simpleBeginningofLine(">");
657 handleInsertHeader(i: MarkdownTextArea, event: any) {
658 event.preventDefault();
659 i.simpleBeginningofLine("#");
662 handleInsertSubscript(i: MarkdownTextArea, event: any) {
663 event.preventDefault();
664 i.simpleSurround("~");
667 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
668 event.preventDefault();
669 i.simpleSurround("^");
672 simpleInsert(chars: string) {
673 const content = this.state.content;
675 this.setState({ content: `${chars} ` });
678 content: `${content}\n${chars} `,
682 const textarea: any = document.getElementById(this.id);
685 autosize.update(textarea);
687 this.contentChange();
690 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
691 event.preventDefault();
692 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
693 const afterChars = "\n:::\n";
694 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
698 const textarea: any = document.getElementById(this.id);
699 const selectedText = window.getSelection()?.toString();
700 const { content } = this.state;
706 .join("\n") + "\n\n";
708 this.setState({ content: "" });
710 this.setState({ content: `${content}\n` });
713 content: `${content}${quotedText}`,
715 this.contentChange();
716 // Not sure why this needs a delay
717 setTimeout(() => autosize.update(textarea), 10);
721 getSelectedText(): string {
722 const { selectionStart: start, selectionEnd: end } =
723 document.getElementById(this.id) as any;
724 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
729 this.state.loading ||
730 this.props.disabled ||
731 !!this.state.imageUploadStatus