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 {
26 initialContent?: string;
27 initialLanguageId?: number;
35 showLanguage?: boolean;
36 hideNavigationWarnings?: boolean;
37 onContentChange?(val: string): void;
38 onReplyCancel?(): void;
39 onSubmit?(content: string, formId: string, languageId?: number): void;
40 allLanguages: Language[]; // TODO should probably be nullable
41 siteLanguages: number[]; // TODO same
44 interface ImageUploadStatus {
49 interface MarkdownTextAreaState {
53 imageUploadStatus?: ImageUploadStatus;
58 export class MarkdownTextArea extends Component<
59 MarkdownTextAreaProps,
62 private id = `markdown-textarea-${randomStr()}`;
63 private formId = `markdown-form-${randomStr()}`;
67 state: MarkdownTextAreaState = {
68 content: this.props.initialContent,
69 languageId: this.props.initialLanguageId,
75 constructor(props: any, context: any) {
76 super(props, context);
78 this.handleLanguageChange = this.handleLanguageChange.bind(this);
81 this.tribute = setupTribute();
86 const textarea: any = document.getElementById(this.id);
89 this.tribute.attach(textarea);
90 textarea.addEventListener("tribute-replaced", () => {
91 this.setState({ content: textarea.value });
92 autosize.update(textarea);
97 if (this.props.focus) {
101 // TODO this is slow for some reason
106 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
107 if (nextProps.finished) {
110 imageUploadStatus: undefined,
114 if (this.props.replyType) {
115 this.props.onReplyCancel?.();
118 const textarea: any = document.getElementById(this.id);
119 const form: any = document.getElementById(this.formId);
121 setTimeout(() => autosize.update(textarea), 10);
126 const languageId = this.state.languageId;
128 // TODO add these prompts back in at some point
130 // when={!this.props.hideNavigationWarnings && this.state.content}
131 // message={I18NextService.i18n.t("block_leaving")}
135 className="markdown-textarea"
137 onSubmit={linkEvent(this, this.handleSubmit)}
141 !this.props.hideNavigationWarnings &&
142 !!this.state.content &&
143 !this.state.submitted
146 <div className="mb-3 row">
147 <div className="col-12">
148 <div className="rounded bg-light border">
149 <div className="d-flex flex-wrap border-bottom">
150 {this.getFormatButton("bold", this.handleInsertBold)}
151 {this.getFormatButton("italic", this.handleInsertItalic)}
152 {this.getFormatButton("link", this.handleInsertLink)}
154 onEmojiClick={e => this.handleEmoji(this, e)}
155 disabled={this.isDisabled}
157 <form className="btn btn-sm text-muted font-weight-bold">
159 htmlFor={`file-upload-${this.id}`}
161 UserService.Instance.myUserInfo && "pointer"
163 data-tippy-content={I18NextService.i18n.t("upload_image")}
165 {this.state.imageUploadStatus ? (
168 <Icon icon="image" classes="icon-inline" />
172 id={`file-upload-${this.id}`}
174 accept="image/*,video/*"
179 !UserService.Instance.myUserInfo || this.isDisabled
181 onChange={linkEvent(this, this.handleImageUpload)}
184 {this.getFormatButton("header", this.handleInsertHeader)}
185 {this.getFormatButton(
187 this.handleInsertStrikethrough
189 {this.getFormatButton("quote", this.handleInsertQuote)}
190 {this.getFormatButton("list", this.handleInsertList)}
191 {this.getFormatButton("code", this.handleInsertCode)}
192 {this.getFormatButton("subscript", this.handleInsertSubscript)}
193 {this.getFormatButton(
195 this.handleInsertSuperscript
197 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
199 href={markdownHelpUrl}
200 className="btn btn-sm text-muted font-weight-bold"
201 title={I18NextService.i18n.t("formatting_help")}
204 <Icon icon="help-circle" classes="icon-inline" />
211 className={classNames(
212 "form-control border-0 rounded-top-0 rounded-bottom",
214 "d-none": this.state.previewMode,
217 value={this.state.content}
218 onInput={linkEvent(this, this.handleContentChange)}
219 onPaste={linkEvent(this, this.handleImageUploadPaste)}
220 onKeyDown={linkEvent(this, this.handleKeyBinds)}
222 disabled={this.isDisabled}
225 this.props.maxLength ?? markdownFieldCharacterLimit
227 placeholder={this.props.placeholder}
229 {this.state.previewMode && this.state.content && (
231 className="card border-secondary card-body md-div"
232 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
235 {this.state.imageUploadStatus &&
236 this.state.imageUploadStatus.total > 1 && (
241 value={this.state.imageUploadStatus.uploaded}
242 max={this.state.imageUploadStatus.total}
244 I18NextService.i18n.t("pictures_uploded_progess", {
245 uploaded: this.state.imageUploadStatus.uploaded,
246 total: this.state.imageUploadStatus.total,
252 <label className="visually-hidden" htmlFor={this.id}>
253 {I18NextService.i18n.t("body")}
258 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
259 {this.props.showLanguage && (
262 allLanguages={this.props.allLanguages}
263 // Only set the selected language ID if it exists as an option
264 // in the dropdown; otherwise, set it to 0 (Undetermined)
265 selectedLanguageIds={
266 languageId && this.props.siteLanguages.includes(languageId)
267 ? Array.of(languageId)
270 siteLanguages={this.props.siteLanguages}
271 onChange={this.handleLanguageChange}
272 disabled={this.isDisabled}
276 {/* A flex expander */}
277 <div className="flex-grow-1"></div>
279 {this.props.buttonTitle && (
282 className="btn btn-sm btn-secondary ms-2"
283 disabled={this.isDisabled}
285 {this.state.loading ? (
288 <span>{this.props.buttonTitle}</span>
292 {this.props.replyType && (
295 className="btn btn-sm btn-secondary ms-2"
296 onClick={linkEvent(this, this.handleReplyCancel)}
298 {I18NextService.i18n.t("cancel")}
301 {this.state.content && (
303 className={`btn btn-sm btn-secondary ms-2 ${
304 this.state.previewMode && "active"
306 onClick={linkEvent(this, this.handlePreviewToggle)}
308 {this.state.previewMode
309 ? I18NextService.i18n.t("edit")
310 : I18NextService.i18n.t("preview")}
320 type: NoOptionI18nKeys,
321 handleClick: (i: MarkdownTextArea, event: any) => void
323 let iconType: string;
327 iconType = "alert-triangle";
331 iconType = "format_quote";
341 className="btn btn-sm text-muted"
342 data-tippy-content={I18NextService.i18n.t(type)}
343 aria-label={I18NextService.i18n.t(type)}
344 onClick={linkEvent(this, handleClick)}
345 disabled={this.isDisabled}
347 <Icon icon={iconType} classes="icon-inline" />
352 handleEmoji(i: MarkdownTextArea, e: any) {
353 let value = e.native;
355 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
357 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
361 content: `${i.state.content ?? ""} ${value} `,
364 const textarea: any = document.getElementById(i.id);
365 autosize.update(textarea);
368 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
369 const image = event.clipboardData.files[0];
371 i.handleImageUpload(i, image);
375 handleImageUpload(i: MarkdownTextArea, event: any) {
376 const files: File[] = [];
378 event.preventDefault();
379 files.push(...event.target.files);
384 if (files.length > maxUploadImages) {
386 I18NextService.i18n.t("too_many_images_upload", {
387 count: Number(maxUploadImages),
388 formattedCount: numToSI(maxUploadImages),
394 imageUploadStatus: { total: files.length, uploaded: 0 },
397 i.uploadImages(i, files).then(() => {
398 i.setState({ imageUploadStatus: undefined });
403 async uploadImages(i: MarkdownTextArea, files: File[]) {
404 let errorOccurred = false;
405 const filesCopy = [...files];
406 while (filesCopy.length > 0 && !errorOccurred) {
409 filesCopy.splice(0, concurrentImageUpload).map(async file => {
410 await i.uploadSingleImage(i, file);
412 this.setState(({ imageUploadStatus }) => ({
414 ...(imageUploadStatus as Required<ImageUploadStatus>),
415 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
421 errorOccurred = true;
426 async uploadSingleImage(i: MarkdownTextArea, image: File) {
427 const res = await HttpService.client.uploadImage({ image });
428 console.log("pictrs upload:");
430 if (res.state === "success") {
431 if (res.data.msg === "ok") {
432 const imageMarkdown = `![](${res.data.url})`;
433 i.setState(({ content }) => ({
434 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
437 const textarea: any = document.getElementById(i.id);
438 autosize.update(textarea);
439 pictrsDeleteToast(image.name, res.data.delete_url as string);
441 throw JSON.stringify(res.data);
443 } else if (res.state === "failed") {
444 i.setState({ imageUploadStatus: undefined });
445 console.error(res.msg);
446 toast(res.msg, "danger");
453 // Coerces the undefineds to empty strings, for replacing in the DB
454 const content = this.state.content ?? "";
455 this.props.onContentChange?.(content);
458 handleContentChange(i: MarkdownTextArea, event: any) {
459 i.setState({ content: event.target.value });
464 // Keybinds inspired by github comment area
465 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
469 i.handleInsertLink(i, event);
473 if (!this.isDisabled) {
474 i.handleSubmit(i, event);
480 i.handleInsertBold(i, event);
484 i.handleInsertItalic(i, event);
488 i.handleInsertCode(i, event);
492 i.handleInsertList(i, event);
496 i.handleInsertSpoiler(i, event);
500 if (i.state.content) i.handlePreviewToggle(i, event);
504 i.handleInsertQuote(i, event);
511 handlePreviewToggle(i: MarkdownTextArea, event: any) {
512 event.preventDefault();
513 i.setState({ previewMode: !i.state.previewMode });
516 handleLanguageChange(val: number[]) {
517 this.setState({ languageId: val[0] });
520 handleSubmit(i: MarkdownTextArea, event: any) {
521 event.preventDefault();
522 if (i.state.content) {
523 i.setState({ loading: true, submitted: true });
524 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
528 handleReplyCancel(i: MarkdownTextArea) {
529 i.props.onReplyCancel?.();
532 handleInsertLink(i: MarkdownTextArea, event: any) {
533 event.preventDefault();
535 const textarea: any = document.getElementById(i.id);
536 const start: number = textarea.selectionStart;
537 const end: number = textarea.selectionEnd;
539 const content = i.state.content ?? "";
541 if (!i.state.content) {
542 i.setState({ content: "" });
546 const selectedText = content?.substring(start, end);
548 content: `${content?.substring(
551 )}[${selectedText}]()${content?.substring(end)}`,
554 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
556 i.setState({ content: `${content} []()` });
558 setTimeout(() => (textarea.selectionEnd -= 1), 10);
563 simpleSurround(chars: string) {
564 this.simpleSurroundBeforeAfter(chars, chars);
567 simpleBeginningofLine(chars: string) {
568 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
571 simpleSurroundBeforeAfter(
576 const content = this.state.content ?? "";
577 if (!this.state.content) {
578 this.setState({ content: "" });
580 const textarea: any = document.getElementById(this.id);
581 const start: number = textarea.selectionStart;
582 const end: number = textarea.selectionEnd;
585 const selectedText = content?.substring(start, end);
587 content: `${content?.substring(
590 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
594 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
597 this.contentChange();
602 textarea.setSelectionRange(
603 start + beforeChars.length,
604 end + afterChars.length
607 textarea.setSelectionRange(
608 start + beforeChars.length,
609 end + emptyChars.length + afterChars.length
614 autosize.update(textarea);
618 handleInsertBold(i: MarkdownTextArea, event: any) {
619 event.preventDefault();
620 i.simpleSurround("**");
623 handleInsertItalic(i: MarkdownTextArea, event: any) {
624 event.preventDefault();
625 i.simpleSurround("*");
628 handleInsertCode(i: MarkdownTextArea, event: any) {
629 event.preventDefault();
630 if (i.getSelectedText().split(/\r*\n/).length > 1) {
631 i.simpleSurroundBeforeAfter("```\n", "\n```");
633 i.simpleSurround("`");
637 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
638 event.preventDefault();
639 i.simpleSurround("~~");
642 handleInsertList(i: MarkdownTextArea, event: any) {
643 event.preventDefault();
644 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
647 handleInsertQuote(i: MarkdownTextArea, event: any) {
648 event.preventDefault();
649 i.simpleBeginningofLine(">");
652 handleInsertHeader(i: MarkdownTextArea, event: any) {
653 event.preventDefault();
654 i.simpleBeginningofLine("#");
657 handleInsertSubscript(i: MarkdownTextArea, event: any) {
658 event.preventDefault();
659 i.simpleSurround("~");
662 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
663 event.preventDefault();
664 i.simpleSurround("^");
667 simpleInsert(chars: string) {
668 const content = this.state.content;
670 this.setState({ content: `${chars} ` });
673 content: `${content}\n${chars} `,
677 const textarea: any = document.getElementById(this.id);
680 autosize.update(textarea);
682 this.contentChange();
685 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
686 event.preventDefault();
687 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
688 const afterChars = "\n:::\n";
689 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
693 const textarea: any = document.getElementById(this.id);
694 const selectedText = window.getSelection()?.toString();
695 const { content } = this.state;
701 .join("\n") + "\n\n";
703 this.setState({ content: "" });
705 this.setState({ content: `${content}\n` });
708 content: `${content}${quotedText}`,
710 this.contentChange();
711 // Not sure why this needs a delay
712 setTimeout(() => autosize.update(textarea), 10);
716 getSelectedText(): string {
717 const { selectionStart: start, selectionEnd: end } =
718 document.getElementById(this.id) as any;
719 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
724 this.state.loading ||
725 this.props.disabled ||
726 !!this.state.imageUploadStatus