1 import { isBrowser } from "@utils/browser";
2 import autosize from "autosize";
3 import classNames from "classnames";
4 import { NoOptionI18nKeys } from "i18next";
5 import { Component, linkEvent } from "inferno";
6 import { Language } from "lemmy-js-client";
7 import { i18n } from "../../i18next";
8 import { HttpService, UserService } from "../../services";
10 concurrentImageUpload,
12 markdownFieldCharacterLimit,
24 import { EmojiPicker } from "./emoji-picker";
25 import { Icon, Spinner } from "./icon";
26 import { LanguageSelect } from "./language-select";
27 import NavigationPrompt from "./navigation-prompt";
28 import ProgressBar from "./progress-bar";
30 interface MarkdownTextAreaProps {
31 initialContent?: string;
32 initialLanguageId?: number;
40 showLanguage?: boolean;
41 hideNavigationWarnings?: boolean;
42 onContentChange?(val: string): void;
43 onReplyCancel?(): void;
44 onSubmit?(content: string, formId: string, languageId?: number): void;
45 allLanguages: Language[]; // TODO should probably be nullable
46 siteLanguages: number[]; // TODO same
49 interface ImageUploadStatus {
54 interface MarkdownTextAreaState {
58 imageUploadStatus?: ImageUploadStatus;
63 export class MarkdownTextArea extends Component<
64 MarkdownTextAreaProps,
67 private id = `markdown-textarea-${randomStr()}`;
68 private formId = `markdown-form-${randomStr()}`;
72 state: MarkdownTextAreaState = {
73 content: this.props.initialContent,
74 languageId: this.props.initialLanguageId,
80 constructor(props: any, context: any) {
81 super(props, context);
83 this.handleLanguageChange = this.handleLanguageChange.bind(this);
86 this.tribute = setupTribute();
91 const textarea: any = document.getElementById(this.id);
94 this.tribute.attach(textarea);
95 textarea.addEventListener("tribute-replaced", () => {
96 this.setState({ content: textarea.value });
97 autosize.update(textarea);
102 if (this.props.focus) {
106 // TODO this is slow for some reason
111 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
112 if (nextProps.finished) {
115 imageUploadStatus: undefined,
119 if (this.props.replyType) {
120 this.props.onReplyCancel?.();
123 const textarea: any = document.getElementById(this.id);
124 const form: any = document.getElementById(this.formId);
126 setTimeout(() => autosize.update(textarea), 10);
131 const languageId = this.state.languageId;
133 // TODO add these prompts back in at some point
135 // when={!this.props.hideNavigationWarnings && this.state.content}
136 // message={i18n.t("block_leaving")}
140 className="markdown-textarea"
142 onSubmit={linkEvent(this, this.handleSubmit)}
146 !this.props.hideNavigationWarnings &&
147 !!this.state.content &&
148 !this.state.submitted
151 <div className="mb-3 row">
152 <div className="col-12">
153 <div className="rounded bg-light border">
154 <div className="d-flex flex-wrap border-bottom">
155 {this.getFormatButton("bold", this.handleInsertBold)}
156 {this.getFormatButton("italic", this.handleInsertItalic)}
157 {this.getFormatButton("link", this.handleInsertLink)}
159 onEmojiClick={e => this.handleEmoji(this, e)}
160 disabled={this.isDisabled}
162 <form className="btn btn-sm text-muted font-weight-bold">
164 htmlFor={`file-upload-${this.id}`}
166 UserService.Instance.myUserInfo && "pointer"
168 data-tippy-content={i18n.t("upload_image")}
170 {this.state.imageUploadStatus ? (
173 <Icon icon="image" classes="icon-inline" />
177 id={`file-upload-${this.id}`}
179 accept="image/*,video/*"
184 !UserService.Instance.myUserInfo || this.isDisabled
186 onChange={linkEvent(this, this.handleImageUpload)}
189 {this.getFormatButton("header", this.handleInsertHeader)}
190 {this.getFormatButton(
192 this.handleInsertStrikethrough
194 {this.getFormatButton("quote", this.handleInsertQuote)}
195 {this.getFormatButton("list", this.handleInsertList)}
196 {this.getFormatButton("code", this.handleInsertCode)}
197 {this.getFormatButton("subscript", this.handleInsertSubscript)}
198 {this.getFormatButton(
200 this.handleInsertSuperscript
202 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
204 href={markdownHelpUrl}
205 className="btn btn-sm text-muted font-weight-bold"
206 title={i18n.t("formatting_help")}
209 <Icon icon="help-circle" classes="icon-inline" />
216 className={classNames(
217 "form-control border-0 rounded-top-0 rounded-bottom",
219 "d-none": this.state.previewMode,
222 value={this.state.content}
223 onInput={linkEvent(this, this.handleContentChange)}
224 onPaste={linkEvent(this, this.handleImageUploadPaste)}
225 onKeyDown={linkEvent(this, this.handleKeyBinds)}
227 disabled={this.isDisabled}
230 this.props.maxLength ?? markdownFieldCharacterLimit
232 placeholder={this.props.placeholder}
234 {this.state.previewMode && this.state.content && (
236 className="card border-secondary card-body md-div"
237 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
240 {this.state.imageUploadStatus &&
241 this.state.imageUploadStatus.total > 1 && (
246 value={this.state.imageUploadStatus.uploaded}
247 max={this.state.imageUploadStatus.total}
248 text={i18n.t("pictures_uploded_progess", {
249 uploaded: this.state.imageUploadStatus.uploaded,
250 total: this.state.imageUploadStatus.total,
255 <label className="visually-hidden" htmlFor={this.id}>
261 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
262 {this.props.showLanguage && (
265 allLanguages={this.props.allLanguages}
266 selectedLanguageIds={
267 languageId ? Array.of(languageId) : undefined
269 siteLanguages={this.props.siteLanguages}
270 onChange={this.handleLanguageChange}
271 disabled={this.isDisabled}
275 {/* A flex expander */}
276 <div className="flex-grow-1"></div>
278 {this.props.buttonTitle && (
281 className="btn btn-sm btn-secondary ms-2"
282 disabled={this.isDisabled}
284 {this.state.loading ? (
287 <span>{this.props.buttonTitle}</span>
291 {this.props.replyType && (
294 className="btn btn-sm btn-secondary ms-2"
295 onClick={linkEvent(this, this.handleReplyCancel)}
300 {this.state.content && (
302 className={`btn btn-sm btn-secondary ms-2 ${
303 this.state.previewMode && "active"
305 onClick={linkEvent(this, this.handlePreviewToggle)}
307 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
317 type: NoOptionI18nKeys,
318 handleClick: (i: MarkdownTextArea, event: any) => void
320 let iconType: string;
324 iconType = "alert-triangle";
328 iconType = "format_quote";
338 className="btn btn-sm text-muted"
339 data-tippy-content={i18n.t(type)}
340 aria-label={i18n.t(type)}
341 onClick={linkEvent(this, handleClick)}
342 disabled={this.isDisabled}
344 <Icon icon={iconType} classes="icon-inline" />
349 handleEmoji(i: MarkdownTextArea, e: any) {
350 let value = e.native;
352 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
354 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
358 content: `${i.state.content ?? ""} ${value} `,
361 const textarea: any = document.getElementById(i.id);
362 autosize.update(textarea);
365 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
366 const image = event.clipboardData.files[0];
368 i.handleImageUpload(i, image);
372 handleImageUpload(i: MarkdownTextArea, event: any) {
373 const files: File[] = [];
375 event.preventDefault();
376 files.push(...event.target.files);
381 if (files.length > maxUploadImages) {
383 i18n.t("too_many_images_upload", {
384 count: Number(maxUploadImages),
385 formattedCount: numToSI(maxUploadImages),
391 imageUploadStatus: { total: files.length, uploaded: 0 },
394 i.uploadImages(i, files).then(() => {
395 i.setState({ imageUploadStatus: undefined });
400 async uploadImages(i: MarkdownTextArea, files: File[]) {
401 let errorOccurred = false;
402 const filesCopy = [...files];
403 while (filesCopy.length > 0 && !errorOccurred) {
406 filesCopy.splice(0, concurrentImageUpload).map(async file => {
407 await i.uploadSingleImage(i, file);
409 this.setState(({ imageUploadStatus }) => ({
411 ...(imageUploadStatus as Required<ImageUploadStatus>),
412 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
418 errorOccurred = true;
423 async uploadSingleImage(i: MarkdownTextArea, image: File) {
424 const res = await HttpService.client.uploadImage({ image });
425 console.log("pictrs upload:");
427 if (res.state === "success") {
428 if (res.data.msg === "ok") {
429 const imageMarkdown = `![](${res.data.url})`;
430 i.setState(({ content }) => ({
431 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
434 const textarea: any = document.getElementById(i.id);
435 autosize.update(textarea);
436 pictrsDeleteToast(image.name, res.data.delete_url as string);
438 throw JSON.stringify(res.data);
440 } else if (res.state === "failed") {
441 i.setState({ imageUploadStatus: undefined });
442 console.error(res.msg);
443 toast(res.msg, "danger");
450 // Coerces the undefineds to empty strings, for replacing in the DB
451 const content = this.state.content ?? "";
452 this.props.onContentChange?.(content);
455 handleContentChange(i: MarkdownTextArea, event: any) {
456 i.setState({ content: event.target.value });
461 // Keybinds inspired by github comment area
462 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
466 i.handleInsertLink(i, event);
470 if (!this.isDisabled) {
471 i.handleSubmit(i, event);
477 i.handleInsertBold(i, event);
481 i.handleInsertItalic(i, event);
485 i.handleInsertCode(i, event);
489 i.handleInsertList(i, event);
493 i.handleInsertSpoiler(i, event);
497 if (i.state.content) i.handlePreviewToggle(i, event);
501 i.handleInsertQuote(i, event);
508 handlePreviewToggle(i: MarkdownTextArea, event: any) {
509 event.preventDefault();
510 i.setState({ previewMode: !i.state.previewMode });
513 handleLanguageChange(val: number[]) {
514 this.setState({ languageId: val[0] });
517 handleSubmit(i: MarkdownTextArea, event: any) {
518 event.preventDefault();
519 if (i.state.content) {
520 i.setState({ loading: true, submitted: true });
521 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
525 handleReplyCancel(i: MarkdownTextArea) {
526 i.props.onReplyCancel?.();
529 handleInsertLink(i: MarkdownTextArea, event: any) {
530 event.preventDefault();
532 const textarea: any = document.getElementById(i.id);
533 const start: number = textarea.selectionStart;
534 const end: number = textarea.selectionEnd;
536 const content = i.state.content ?? "";
538 if (!i.state.content) {
539 i.setState({ content: "" });
543 const selectedText = content?.substring(start, end);
545 content: `${content?.substring(
548 )}[${selectedText}]()${content?.substring(end)}`,
551 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
553 i.setState({ content: `${content} []()` });
555 setTimeout(() => (textarea.selectionEnd -= 1), 10);
560 simpleSurround(chars: string) {
561 this.simpleSurroundBeforeAfter(chars, chars);
564 simpleBeginningofLine(chars: string) {
565 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
568 simpleSurroundBeforeAfter(
573 const content = this.state.content ?? "";
574 if (!this.state.content) {
575 this.setState({ content: "" });
577 const textarea: any = document.getElementById(this.id);
578 const start: number = textarea.selectionStart;
579 const end: number = textarea.selectionEnd;
582 const selectedText = content?.substring(start, end);
584 content: `${content?.substring(
587 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
591 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
594 this.contentChange();
599 textarea.setSelectionRange(
600 start + beforeChars.length,
601 end + afterChars.length
604 textarea.setSelectionRange(
605 start + beforeChars.length,
606 end + emptyChars.length + afterChars.length
611 autosize.update(textarea);
615 handleInsertBold(i: MarkdownTextArea, event: any) {
616 event.preventDefault();
617 i.simpleSurround("**");
620 handleInsertItalic(i: MarkdownTextArea, event: any) {
621 event.preventDefault();
622 i.simpleSurround("*");
625 handleInsertCode(i: MarkdownTextArea, event: any) {
626 event.preventDefault();
627 if (i.getSelectedText().split(/\r*\n/).length > 1) {
628 i.simpleSurroundBeforeAfter("```\n", "\n```");
630 i.simpleSurround("`");
634 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
635 event.preventDefault();
636 i.simpleSurround("~~");
639 handleInsertList(i: MarkdownTextArea, event: any) {
640 event.preventDefault();
641 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
644 handleInsertQuote(i: MarkdownTextArea, event: any) {
645 event.preventDefault();
646 i.simpleBeginningofLine(">");
649 handleInsertHeader(i: MarkdownTextArea, event: any) {
650 event.preventDefault();
651 i.simpleBeginningofLine("#");
654 handleInsertSubscript(i: MarkdownTextArea, event: any) {
655 event.preventDefault();
656 i.simpleSurround("~");
659 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
660 event.preventDefault();
661 i.simpleSurround("^");
664 simpleInsert(chars: string) {
665 const content = this.state.content;
667 this.setState({ content: `${chars} ` });
670 content: `${content}\n${chars} `,
674 const textarea: any = document.getElementById(this.id);
677 autosize.update(textarea);
679 this.contentChange();
682 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
683 event.preventDefault();
684 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
685 const afterChars = "\n:::\n";
686 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
690 const textarea: any = document.getElementById(this.id);
691 const selectedText = window.getSelection()?.toString();
692 const { content } = this.state;
698 .join("\n") + "\n\n";
700 this.setState({ content: "" });
702 this.setState({ content: `${content}\n` });
705 content: `${content}${quotedText}`,
707 this.contentChange();
708 // Not sure why this needs a delay
709 setTimeout(() => autosize.update(textarea), 10);
713 getSelectedText(): string {
714 const { selectionStart: start, selectionEnd: end } =
715 document.getElementById(this.id) as any;
716 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
721 this.state.loading ||
722 this.props.disabled ||
723 !!this.state.imageUploadStatus