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 { Prompt } from "inferno-router";
8 import { Language } from "lemmy-js-client";
10 concurrentImageUpload,
11 markdownFieldCharacterLimit,
15 } from "../../config";
16 import { customEmojisLookup, mdToHtml, setupTribute } from "../../markdown";
17 import { HttpService, I18NextService, UserService } from "../../services";
18 import { setupTippy } from "../../tippy";
19 import { pictrsDeleteToast, toast } from "../../toast";
20 import { EmojiPicker } from "./emoji-picker";
21 import { Icon, Spinner } from "./icon";
22 import { LanguageSelect } from "./language-select";
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;
143 className="markdown-textarea"
145 onSubmit={linkEvent(this, this.handleSubmit)}
148 message={I18NextService.i18n.t("block_leaving")}
150 !this.props.hideNavigationWarnings &&
151 !!this.state.content &&
152 !this.state.submitted
155 <div className="mb-3 row">
156 <div className="col-12">
157 <div className="rounded bg-light border">
159 className={classNames("d-flex flex-wrap border-bottom", {
160 "no-click": this.isDisabled,
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)}
170 htmlFor={`file-upload-${this.id}`}
171 className={classNames("mb-0", {
172 pointer: UserService.Instance.myUserInfo,
174 data-tippy-content={I18NextService.i18n.t("upload_image")}
176 {this.state.imageUploadStatus ? (
181 className="btn btn-sm btn-link rounded-0 text-muted mb-0"
184 .getElementById(`file-upload-${this.id}`)
188 <Icon icon="image" classes="icon-inline" />
193 id={`file-upload-${this.id}`}
195 accept="image/*,video/*"
199 disabled={!UserService.Instance.myUserInfo}
200 onChange={linkEvent(this, this.handleImageUpload)}
202 {this.getFormatButton("header", this.handleInsertHeader)}
203 {this.getFormatButton(
205 this.handleInsertStrikethrough
207 {this.getFormatButton("quote", this.handleInsertQuote)}
208 {this.getFormatButton("list", this.handleInsertList)}
209 {this.getFormatButton("code", this.handleInsertCode)}
210 {this.getFormatButton("subscript", this.handleInsertSubscript)}
211 {this.getFormatButton(
213 this.handleInsertSuperscript
215 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
217 href={markdownHelpUrl}
218 className="btn btn-sm btn-link rounded-0 text-muted fw-bold"
219 title={I18NextService.i18n.t("formatting_help")}
222 <Icon icon="help-circle" classes="icon-inline" />
229 className={classNames(
230 "form-control border-0 rounded-top-0 rounded-bottom",
232 "d-none": this.state.previewMode,
235 value={this.state.content}
236 onInput={linkEvent(this, this.handleContentChange)}
237 onPaste={linkEvent(this, this.handleImageUploadPaste)}
238 onKeyDown={linkEvent(this, this.handleKeyBinds)}
240 disabled={this.isDisabled}
243 this.props.maxLength ?? markdownFieldCharacterLimit
245 placeholder={this.props.placeholder}
247 {this.state.previewMode && this.state.content && (
249 className="card border-secondary card-body md-div"
250 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
253 {this.state.imageUploadStatus &&
254 this.state.imageUploadStatus.total > 1 && (
259 value={this.state.imageUploadStatus.uploaded}
260 max={this.state.imageUploadStatus.total}
262 I18NextService.i18n.t("pictures_uploded_progess", {
263 uploaded: this.state.imageUploadStatus.uploaded,
264 total: this.state.imageUploadStatus.total,
270 <label className="visually-hidden" htmlFor={this.id}>
271 {I18NextService.i18n.t("body")}
276 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
277 {this.props.showLanguage && (
280 allLanguages={this.props.allLanguages}
281 selectedLanguageIds={
282 languageId ? Array.of(languageId) : undefined
284 siteLanguages={this.props.siteLanguages}
285 onChange={this.handleLanguageChange}
286 disabled={this.isDisabled}
290 {/* A flex expander */}
291 <div className="flex-grow-1"></div>
293 {this.props.replyType && (
296 className="btn btn-sm btn-secondary ms-2"
297 onClick={linkEvent(this, this.handleReplyCancel)}
299 {I18NextService.i18n.t("cancel")}
304 disabled={!this.state.content}
305 className={classNames("btn btn-sm btn-secondary ms-2", {
306 active: this.state.previewMode,
308 onClick={linkEvent(this, this.handlePreviewToggle)}
310 {this.state.previewMode
311 ? I18NextService.i18n.t("edit")
312 : I18NextService.i18n.t("preview")}
314 {this.props.buttonTitle && (
317 className="btn btn-sm btn-secondary ms-2"
318 disabled={this.isDisabled || !this.state.content}
320 {this.state.loading && <Spinner className="me-1" />}
321 {this.props.buttonTitle}
331 type: NoOptionI18nKeys,
332 handleClick: (i: MarkdownTextArea, event: any) => void
334 let iconType: string;
338 iconType = "alert-triangle";
342 iconType = "format_quote";
352 className="btn btn-sm btn-link rounded-0 text-muted"
353 data-tippy-content={I18NextService.i18n.t(type)}
354 aria-label={I18NextService.i18n.t(type)}
355 onClick={linkEvent(this, handleClick)}
357 <Icon icon={iconType} classes="icon-inline" />
362 handleEmoji(i: MarkdownTextArea, e: any) {
363 let value = e.native;
365 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
367 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
371 content: `${i.state.content ?? ""} ${value} `,
374 const textarea: any = document.getElementById(i.id);
375 autosize.update(textarea);
378 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
379 const image = event.clipboardData.files[0];
381 i.handleImageUpload(i, image);
385 handleImageUpload(i: MarkdownTextArea, event: any) {
386 const files: File[] = [];
388 event.preventDefault();
389 files.push(...event.target.files);
394 if (files.length > maxUploadImages) {
396 I18NextService.i18n.t("too_many_images_upload", {
397 count: Number(maxUploadImages),
398 formattedCount: numToSI(maxUploadImages),
404 imageUploadStatus: { total: files.length, uploaded: 0 },
407 i.uploadImages(i, files).then(() => {
408 i.setState({ imageUploadStatus: undefined });
413 async uploadImages(i: MarkdownTextArea, files: File[]) {
414 let errorOccurred = false;
415 const filesCopy = [...files];
416 while (filesCopy.length > 0 && !errorOccurred) {
419 filesCopy.splice(0, concurrentImageUpload).map(async file => {
420 await i.uploadSingleImage(i, file);
422 this.setState(({ imageUploadStatus }) => ({
424 ...(imageUploadStatus as Required<ImageUploadStatus>),
425 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
431 errorOccurred = true;
436 async uploadSingleImage(i: MarkdownTextArea, image: File) {
437 const res = await HttpService.client.uploadImage({ image });
438 console.log("pictrs upload:");
440 if (res.state === "success") {
441 if (res.data.msg === "ok") {
442 const imageMarkdown = `![](${res.data.url})`;
443 i.setState(({ content }) => ({
444 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
447 const textarea: any = document.getElementById(i.id);
448 autosize.update(textarea);
449 pictrsDeleteToast(image.name, res.data.delete_url as string);
450 } else if (res.data.msg === "too_large") {
451 toast(I18NextService.i18n.t("upload_too_large"), "danger");
452 i.setState({ imageUploadStatus: undefined });
453 throw JSON.stringify(res.data);
455 throw JSON.stringify(res.data);
457 } else if (res.state === "failed") {
458 i.setState({ imageUploadStatus: undefined });
459 console.error(res.msg);
460 toast(res.msg, "danger");
467 // Coerces the undefineds to empty strings, for replacing in the DB
468 const content = this.state.content ?? "";
469 this.props.onContentChange?.(content);
472 handleContentChange(i: MarkdownTextArea, event: any) {
473 i.setState({ content: event.target.value });
478 // Keybinds inspired by github comment area
479 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
480 if (event.ctrlKey || event.metaKey) {
483 i.handleInsertLink(i, event);
487 if (!this.isDisabled) {
488 i.handleSubmit(i, event);
494 i.handleInsertBold(i, event);
498 i.handleInsertItalic(i, event);
502 i.handleInsertCode(i, event);
506 i.handleInsertList(i, event);
510 i.handleInsertSpoiler(i, event);
514 if (i.state.content) i.handlePreviewToggle(i, event);
518 i.handleInsertQuote(i, event);
525 handlePreviewToggle(i: MarkdownTextArea, event: any) {
526 event.preventDefault();
527 i.setState({ previewMode: !i.state.previewMode });
530 handleLanguageChange(val: number[]) {
531 this.setState({ languageId: val[0] });
534 handleSubmit(i: MarkdownTextArea, event: any) {
535 event.preventDefault();
536 if (i.state.content) {
537 i.setState({ loading: true, submitted: true });
538 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
542 handleReplyCancel(i: MarkdownTextArea) {
543 i.props.onReplyCancel?.();
546 handleInsertLink(i: MarkdownTextArea, event: any) {
547 event.preventDefault();
549 const textarea: any = document.getElementById(i.id);
550 const start: number = textarea.selectionStart;
551 const end: number = textarea.selectionEnd;
553 const content = i.state.content ?? "";
555 if (!i.state.content) {
556 i.setState({ content: "" });
560 const selectedText = content?.substring(start, end);
562 content: `${content?.substring(
565 )}[${selectedText}]()${content?.substring(end)}`,
568 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
570 i.setState({ content: `${content} []()` });
572 setTimeout(() => (textarea.selectionEnd -= 1), 10);
577 simpleSurround(chars: string) {
578 this.simpleSurroundBeforeAfter(chars, chars);
581 simpleBeginningofLine(chars: string) {
582 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
585 simpleSurroundBeforeAfter(
590 const content = this.state.content ?? "";
591 if (!this.state.content) {
592 this.setState({ content: "" });
594 const textarea: any = document.getElementById(this.id);
595 const start: number = textarea.selectionStart;
596 const end: number = textarea.selectionEnd;
599 const selectedText = content?.substring(start, end);
601 content: `${content?.substring(
604 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
608 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
611 this.contentChange();
616 textarea.setSelectionRange(
617 start + beforeChars.length,
618 end + afterChars.length
621 textarea.setSelectionRange(
622 start + beforeChars.length,
623 end + emptyChars.length + afterChars.length
628 autosize.update(textarea);
632 handleInsertBold(i: MarkdownTextArea, event: any) {
633 event.preventDefault();
634 i.simpleSurround("**");
637 handleInsertItalic(i: MarkdownTextArea, event: any) {
638 event.preventDefault();
639 i.simpleSurround("*");
642 handleInsertCode(i: MarkdownTextArea, event: any) {
643 event.preventDefault();
644 if (i.getSelectedText().split(/\r*\n/).length > 1) {
645 i.simpleSurroundBeforeAfter("```\n", "\n```");
647 i.simpleSurround("`");
651 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
652 event.preventDefault();
653 i.simpleSurround("~~");
656 handleInsertList(i: MarkdownTextArea, event: any) {
657 event.preventDefault();
658 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
661 handleInsertQuote(i: MarkdownTextArea, event: any) {
662 event.preventDefault();
663 i.simpleBeginningofLine(">");
666 handleInsertHeader(i: MarkdownTextArea, event: any) {
667 event.preventDefault();
668 i.simpleBeginningofLine("#");
671 handleInsertSubscript(i: MarkdownTextArea, event: any) {
672 event.preventDefault();
673 i.simpleSurround("~");
676 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
677 event.preventDefault();
678 i.simpleSurround("^");
681 simpleInsert(chars: string) {
682 const content = this.state.content;
684 this.setState({ content: `${chars} ` });
687 content: `${content}\n${chars} `,
691 const textarea: any = document.getElementById(this.id);
694 autosize.update(textarea);
696 this.contentChange();
699 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
700 event.preventDefault();
701 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
702 const afterChars = "\n:::\n";
703 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
707 const textarea: any = document.getElementById(this.id);
708 const selectedText = window.getSelection()?.toString();
709 let { content } = this.state;
715 .join("\n") + "\n\n";
720 content = `${content}\n\n`;
724 content: `${content}${quotedText}`,
726 this.contentChange();
727 // Not sure why this needs a delay
728 setTimeout(() => autosize.update(textarea), 10);
732 getSelectedText(): string {
733 const { selectionStart: start, selectionEnd: end } =
734 document.getElementById(this.id) as any;
735 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
740 this.state.loading ||
741 this.props.disabled ||
742 !!this.state.imageUploadStatus