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)}
174 htmlFor={`file-upload-${this.id}`}
175 className={classNames("mb-0", {
176 pointer: UserService.Instance.myUserInfo,
178 data-tippy-content={I18NextService.i18n.t("upload_image")}
180 {this.state.imageUploadStatus ? (
185 className="btn btn-sm btn-link rounded-0 text-muted mb-0"
188 .getElementById(`file-upload-${this.id}`)
192 <Icon icon="image" classes="icon-inline" />
197 id={`file-upload-${this.id}`}
199 accept="image/*,video/*"
203 disabled={!UserService.Instance.myUserInfo}
204 onChange={linkEvent(this, this.handleImageUpload)}
206 {this.getFormatButton("header", this.handleInsertHeader)}
207 {this.getFormatButton(
209 this.handleInsertStrikethrough
211 {this.getFormatButton("quote", this.handleInsertQuote)}
212 {this.getFormatButton("list", this.handleInsertList)}
213 {this.getFormatButton("code", this.handleInsertCode)}
214 {this.getFormatButton("subscript", this.handleInsertSubscript)}
215 {this.getFormatButton(
217 this.handleInsertSuperscript
219 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
221 href={markdownHelpUrl}
222 className="btn btn-sm text-muted fw-bold"
223 title={I18NextService.i18n.t("formatting_help")}
226 <Icon icon="help-circle" classes="icon-inline" />
233 className={classNames(
234 "form-control border-0 rounded-top-0 rounded-bottom",
236 "d-none": this.state.previewMode,
239 value={this.state.content}
240 onInput={linkEvent(this, this.handleContentChange)}
241 onPaste={linkEvent(this, this.handleImageUploadPaste)}
242 onKeyDown={linkEvent(this, this.handleKeyBinds)}
244 disabled={this.isDisabled}
247 this.props.maxLength ?? markdownFieldCharacterLimit
249 placeholder={this.props.placeholder}
251 {this.state.previewMode && this.state.content && (
253 className="card border-secondary card-body md-div"
254 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
257 {this.state.imageUploadStatus &&
258 this.state.imageUploadStatus.total > 1 && (
263 value={this.state.imageUploadStatus.uploaded}
264 max={this.state.imageUploadStatus.total}
266 I18NextService.i18n.t("pictures_uploded_progess", {
267 uploaded: this.state.imageUploadStatus.uploaded,
268 total: this.state.imageUploadStatus.total,
274 <label className="visually-hidden" htmlFor={this.id}>
275 {I18NextService.i18n.t("body")}
280 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
281 {this.props.showLanguage && (
284 allLanguages={this.props.allLanguages}
285 selectedLanguageIds={
286 languageId ? Array.of(languageId) : undefined
288 siteLanguages={this.props.siteLanguages}
289 onChange={this.handleLanguageChange}
290 disabled={this.isDisabled}
294 {/* A flex expander */}
295 <div className="flex-grow-1"></div>
297 {this.props.replyType && (
300 className="btn btn-sm btn-secondary ms-2"
301 onClick={linkEvent(this, this.handleReplyCancel)}
303 {I18NextService.i18n.t("cancel")}
308 disabled={!this.state.content}
309 className={classNames("btn btn-sm btn-secondary ms-2", {
310 active: this.state.previewMode,
312 onClick={linkEvent(this, this.handlePreviewToggle)}
314 {this.state.previewMode
315 ? I18NextService.i18n.t("edit")
316 : I18NextService.i18n.t("preview")}
318 {this.props.buttonTitle && (
321 className="btn btn-sm btn-secondary ms-2"
322 disabled={this.isDisabled || !this.state.content}
324 {this.state.loading && <Spinner className="me-1" />}
325 {this.props.buttonTitle}
335 type: NoOptionI18nKeys,
336 handleClick: (i: MarkdownTextArea, event: any) => void
338 let iconType: string;
342 iconType = "alert-triangle";
346 iconType = "format_quote";
356 className="btn btn-sm btn-link rounded-0 text-muted"
357 data-tippy-content={I18NextService.i18n.t(type)}
358 aria-label={I18NextService.i18n.t(type)}
359 onClick={linkEvent(this, handleClick)}
361 <Icon icon={iconType} classes="icon-inline" />
366 handleEmoji(i: MarkdownTextArea, e: any) {
367 let value = e.native;
369 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
371 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
375 content: `${i.state.content ?? ""} ${value} `,
378 const textarea: any = document.getElementById(i.id);
379 autosize.update(textarea);
382 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
383 const image = event.clipboardData.files[0];
385 i.handleImageUpload(i, image);
389 handleImageUpload(i: MarkdownTextArea, event: any) {
390 const files: File[] = [];
392 event.preventDefault();
393 files.push(...event.target.files);
398 if (files.length > maxUploadImages) {
400 I18NextService.i18n.t("too_many_images_upload", {
401 count: Number(maxUploadImages),
402 formattedCount: numToSI(maxUploadImages),
408 imageUploadStatus: { total: files.length, uploaded: 0 },
411 i.uploadImages(i, files).then(() => {
412 i.setState({ imageUploadStatus: undefined });
417 async uploadImages(i: MarkdownTextArea, files: File[]) {
418 let errorOccurred = false;
419 const filesCopy = [...files];
420 while (filesCopy.length > 0 && !errorOccurred) {
423 filesCopy.splice(0, concurrentImageUpload).map(async file => {
424 await i.uploadSingleImage(i, file);
426 this.setState(({ imageUploadStatus }) => ({
428 ...(imageUploadStatus as Required<ImageUploadStatus>),
429 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
435 errorOccurred = true;
440 async uploadSingleImage(i: MarkdownTextArea, image: File) {
441 const res = await HttpService.client.uploadImage({ image });
442 console.log("pictrs upload:");
444 if (res.state === "success") {
445 if (res.data.msg === "ok") {
446 const imageMarkdown = `![](${res.data.url})`;
447 i.setState(({ content }) => ({
448 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
451 const textarea: any = document.getElementById(i.id);
452 autosize.update(textarea);
453 pictrsDeleteToast(image.name, res.data.delete_url as string);
454 } else if (res.data.msg === "too_large") {
455 toast(I18NextService.i18n.t("upload_too_large"), "danger");
456 i.setState({ imageUploadStatus: undefined });
457 throw JSON.stringify(res.data);
459 throw JSON.stringify(res.data);
461 } else if (res.state === "failed") {
462 i.setState({ imageUploadStatus: undefined });
463 console.error(res.msg);
464 toast(res.msg, "danger");
471 // Coerces the undefineds to empty strings, for replacing in the DB
472 const content = this.state.content ?? "";
473 this.props.onContentChange?.(content);
476 handleContentChange(i: MarkdownTextArea, event: any) {
477 i.setState({ content: event.target.value });
482 // Keybinds inspired by github comment area
483 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
484 if (event.ctrlKey || event.metaKey) {
487 i.handleInsertLink(i, event);
491 if (!this.isDisabled) {
492 i.handleSubmit(i, event);
498 i.handleInsertBold(i, event);
502 i.handleInsertItalic(i, event);
506 i.handleInsertCode(i, event);
510 i.handleInsertList(i, event);
514 i.handleInsertSpoiler(i, event);
518 if (i.state.content) i.handlePreviewToggle(i, event);
522 i.handleInsertQuote(i, event);
529 handlePreviewToggle(i: MarkdownTextArea, event: any) {
530 event.preventDefault();
531 i.setState({ previewMode: !i.state.previewMode });
534 handleLanguageChange(val: number[]) {
535 this.setState({ languageId: val[0] });
538 handleSubmit(i: MarkdownTextArea, event: any) {
539 event.preventDefault();
540 if (i.state.content) {
541 i.setState({ loading: true, submitted: true });
542 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
546 handleReplyCancel(i: MarkdownTextArea) {
547 i.props.onReplyCancel?.();
550 handleInsertLink(i: MarkdownTextArea, event: any) {
551 event.preventDefault();
553 const textarea: any = document.getElementById(i.id);
554 const start: number = textarea.selectionStart;
555 const end: number = textarea.selectionEnd;
557 const content = i.state.content ?? "";
559 if (!i.state.content) {
560 i.setState({ content: "" });
564 const selectedText = content?.substring(start, end);
566 content: `${content?.substring(
569 )}[${selectedText}]()${content?.substring(end)}`,
572 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
574 i.setState({ content: `${content} []()` });
576 setTimeout(() => (textarea.selectionEnd -= 1), 10);
581 simpleSurround(chars: string) {
582 this.simpleSurroundBeforeAfter(chars, chars);
585 simpleBeginningofLine(chars: string) {
586 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
589 simpleSurroundBeforeAfter(
594 const content = this.state.content ?? "";
595 if (!this.state.content) {
596 this.setState({ content: "" });
598 const textarea: any = document.getElementById(this.id);
599 const start: number = textarea.selectionStart;
600 const end: number = textarea.selectionEnd;
603 const selectedText = content?.substring(start, end);
605 content: `${content?.substring(
608 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
612 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
615 this.contentChange();
620 textarea.setSelectionRange(
621 start + beforeChars.length,
622 end + afterChars.length
625 textarea.setSelectionRange(
626 start + beforeChars.length,
627 end + emptyChars.length + afterChars.length
632 autosize.update(textarea);
636 handleInsertBold(i: MarkdownTextArea, event: any) {
637 event.preventDefault();
638 i.simpleSurround("**");
641 handleInsertItalic(i: MarkdownTextArea, event: any) {
642 event.preventDefault();
643 i.simpleSurround("*");
646 handleInsertCode(i: MarkdownTextArea, event: any) {
647 event.preventDefault();
648 if (i.getSelectedText().split(/\r*\n/).length > 1) {
649 i.simpleSurroundBeforeAfter("```\n", "\n```");
651 i.simpleSurround("`");
655 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
656 event.preventDefault();
657 i.simpleSurround("~~");
660 handleInsertList(i: MarkdownTextArea, event: any) {
661 event.preventDefault();
662 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
665 handleInsertQuote(i: MarkdownTextArea, event: any) {
666 event.preventDefault();
667 i.simpleBeginningofLine(">");
670 handleInsertHeader(i: MarkdownTextArea, event: any) {
671 event.preventDefault();
672 i.simpleBeginningofLine("#");
675 handleInsertSubscript(i: MarkdownTextArea, event: any) {
676 event.preventDefault();
677 i.simpleSurround("~");
680 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
681 event.preventDefault();
682 i.simpleSurround("^");
685 simpleInsert(chars: string) {
686 const content = this.state.content;
688 this.setState({ content: `${chars} ` });
691 content: `${content}\n${chars} `,
695 const textarea: any = document.getElementById(this.id);
698 autosize.update(textarea);
700 this.contentChange();
703 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
704 event.preventDefault();
705 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
706 const afterChars = "\n:::\n";
707 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
711 const textarea: any = document.getElementById(this.id);
712 const selectedText = window.getSelection()?.toString();
713 let { content } = this.state;
719 .join("\n") + "\n\n";
724 content = `${content}\n\n`;
728 content: `${content}${quotedText}`,
730 this.contentChange();
731 // Not sure why this needs a delay
732 setTimeout(() => autosize.update(textarea), 10);
736 getSelectedText(): string {
737 const { selectionStart: start, selectionEnd: end } =
738 document.getElementById(this.id) as any;
739 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
744 this.state.loading ||
745 this.props.disabled ||
746 !!this.state.imageUploadStatus