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 selectedLanguageIds={
264 languageId ? Array.of(languageId) : undefined
266 siteLanguages={this.props.siteLanguages}
267 onChange={this.handleLanguageChange}
268 disabled={this.isDisabled}
272 {/* A flex expander */}
273 <div className="flex-grow-1"></div>
275 {this.props.buttonTitle && (
278 className="btn btn-sm btn-secondary ms-2"
279 disabled={this.isDisabled}
281 {this.state.loading ? (
284 <span>{this.props.buttonTitle}</span>
288 {this.props.replyType && (
291 className="btn btn-sm btn-secondary ms-2"
292 onClick={linkEvent(this, this.handleReplyCancel)}
294 {I18NextService.i18n.t("cancel")}
297 {this.state.content && (
299 className={`btn btn-sm btn-secondary ms-2 ${
300 this.state.previewMode && "active"
302 onClick={linkEvent(this, this.handlePreviewToggle)}
304 {this.state.previewMode
305 ? I18NextService.i18n.t("edit")
306 : I18NextService.i18n.t("preview")}
316 type: NoOptionI18nKeys,
317 handleClick: (i: MarkdownTextArea, event: any) => void
319 let iconType: string;
323 iconType = "alert-triangle";
327 iconType = "format_quote";
337 className="btn btn-sm text-muted"
338 data-tippy-content={I18NextService.i18n.t(type)}
339 aria-label={I18NextService.i18n.t(type)}
340 onClick={linkEvent(this, handleClick)}
341 disabled={this.isDisabled}
343 <Icon icon={iconType} classes="icon-inline" />
348 handleEmoji(i: MarkdownTextArea, e: any) {
349 let value = e.native;
351 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
353 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
357 content: `${i.state.content ?? ""} ${value} `,
360 const textarea: any = document.getElementById(i.id);
361 autosize.update(textarea);
364 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
365 const image = event.clipboardData.files[0];
367 i.handleImageUpload(i, image);
371 handleImageUpload(i: MarkdownTextArea, event: any) {
372 const files: File[] = [];
374 event.preventDefault();
375 files.push(...event.target.files);
380 if (files.length > maxUploadImages) {
382 I18NextService.i18n.t("too_many_images_upload", {
383 count: Number(maxUploadImages),
384 formattedCount: numToSI(maxUploadImages),
390 imageUploadStatus: { total: files.length, uploaded: 0 },
393 i.uploadImages(i, files).then(() => {
394 i.setState({ imageUploadStatus: undefined });
399 async uploadImages(i: MarkdownTextArea, files: File[]) {
400 let errorOccurred = false;
401 const filesCopy = [...files];
402 while (filesCopy.length > 0 && !errorOccurred) {
405 filesCopy.splice(0, concurrentImageUpload).map(async file => {
406 await i.uploadSingleImage(i, file);
408 this.setState(({ imageUploadStatus }) => ({
410 ...(imageUploadStatus as Required<ImageUploadStatus>),
411 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
417 errorOccurred = true;
422 async uploadSingleImage(i: MarkdownTextArea, image: File) {
423 const res = await HttpService.client.uploadImage({ image });
424 console.log("pictrs upload:");
426 if (res.state === "success") {
427 if (res.data.msg === "ok") {
428 const imageMarkdown = `![](${res.data.url})`;
429 i.setState(({ content }) => ({
430 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
433 const textarea: any = document.getElementById(i.id);
434 autosize.update(textarea);
435 pictrsDeleteToast(image.name, res.data.delete_url as string);
437 throw JSON.stringify(res.data);
439 } else if (res.state === "failed") {
440 i.setState({ imageUploadStatus: undefined });
441 console.error(res.msg);
442 toast(res.msg, "danger");
449 // Coerces the undefineds to empty strings, for replacing in the DB
450 const content = this.state.content ?? "";
451 this.props.onContentChange?.(content);
454 handleContentChange(i: MarkdownTextArea, event: any) {
455 i.setState({ content: event.target.value });
460 // Keybinds inspired by github comment area
461 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
465 i.handleInsertLink(i, event);
469 if (!this.isDisabled) {
470 i.handleSubmit(i, event);
476 i.handleInsertBold(i, event);
480 i.handleInsertItalic(i, event);
484 i.handleInsertCode(i, event);
488 i.handleInsertList(i, event);
492 i.handleInsertSpoiler(i, event);
496 if (i.state.content) i.handlePreviewToggle(i, event);
500 i.handleInsertQuote(i, event);
507 handlePreviewToggle(i: MarkdownTextArea, event: any) {
508 event.preventDefault();
509 i.setState({ previewMode: !i.state.previewMode });
512 handleLanguageChange(val: number[]) {
513 this.setState({ languageId: val[0] });
516 handleSubmit(i: MarkdownTextArea, event: any) {
517 event.preventDefault();
518 if (i.state.content) {
519 i.setState({ loading: true, submitted: true });
520 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
524 handleReplyCancel(i: MarkdownTextArea) {
525 i.props.onReplyCancel?.();
528 handleInsertLink(i: MarkdownTextArea, event: any) {
529 event.preventDefault();
531 const textarea: any = document.getElementById(i.id);
532 const start: number = textarea.selectionStart;
533 const end: number = textarea.selectionEnd;
535 const content = i.state.content ?? "";
537 if (!i.state.content) {
538 i.setState({ content: "" });
542 const selectedText = content?.substring(start, end);
544 content: `${content?.substring(
547 )}[${selectedText}]()${content?.substring(end)}`,
550 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
552 i.setState({ content: `${content} []()` });
554 setTimeout(() => (textarea.selectionEnd -= 1), 10);
559 simpleSurround(chars: string) {
560 this.simpleSurroundBeforeAfter(chars, chars);
563 simpleBeginningofLine(chars: string) {
564 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
567 simpleSurroundBeforeAfter(
572 const content = this.state.content ?? "";
573 if (!this.state.content) {
574 this.setState({ content: "" });
576 const textarea: any = document.getElementById(this.id);
577 const start: number = textarea.selectionStart;
578 const end: number = textarea.selectionEnd;
581 const selectedText = content?.substring(start, end);
583 content: `${content?.substring(
586 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
590 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
593 this.contentChange();
598 textarea.setSelectionRange(
599 start + beforeChars.length,
600 end + afterChars.length
603 textarea.setSelectionRange(
604 start + beforeChars.length,
605 end + emptyChars.length + afterChars.length
610 autosize.update(textarea);
614 handleInsertBold(i: MarkdownTextArea, event: any) {
615 event.preventDefault();
616 i.simpleSurround("**");
619 handleInsertItalic(i: MarkdownTextArea, event: any) {
620 event.preventDefault();
621 i.simpleSurround("*");
624 handleInsertCode(i: MarkdownTextArea, event: any) {
625 event.preventDefault();
626 if (i.getSelectedText().split(/\r*\n/).length > 1) {
627 i.simpleSurroundBeforeAfter("```\n", "\n```");
629 i.simpleSurround("`");
633 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
634 event.preventDefault();
635 i.simpleSurround("~~");
638 handleInsertList(i: MarkdownTextArea, event: any) {
639 event.preventDefault();
640 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
643 handleInsertQuote(i: MarkdownTextArea, event: any) {
644 event.preventDefault();
645 i.simpleBeginningofLine(">");
648 handleInsertHeader(i: MarkdownTextArea, event: any) {
649 event.preventDefault();
650 i.simpleBeginningofLine("#");
653 handleInsertSubscript(i: MarkdownTextArea, event: any) {
654 event.preventDefault();
655 i.simpleSurround("~");
658 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
659 event.preventDefault();
660 i.simpleSurround("^");
663 simpleInsert(chars: string) {
664 const content = this.state.content;
666 this.setState({ content: `${chars} ` });
669 content: `${content}\n${chars} `,
673 const textarea: any = document.getElementById(this.id);
676 autosize.update(textarea);
678 this.contentChange();
681 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
682 event.preventDefault();
683 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
684 const afterChars = "\n:::\n";
685 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
689 const textarea: any = document.getElementById(this.id);
690 const selectedText = window.getSelection()?.toString();
691 const { content } = this.state;
697 .join("\n") + "\n\n";
699 this.setState({ content: "" });
701 this.setState({ content: `${content}\n` });
704 content: `${content}${quotedText}`,
706 this.contentChange();
707 // Not sure why this needs a delay
708 setTimeout(() => autosize.update(textarea), 10);
712 getSelectedText(): string {
713 const { selectionStart: start, selectionEnd: end } =
714 document.getElementById(this.id) as any;
715 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
720 this.state.loading ||
721 this.props.disabled ||
722 !!this.state.imageUploadStatus