1 import { isBrowser, platform } 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";
24 interface MarkdownTextAreaProps {
26 * Initial content inside the textarea
28 initialContent?: string;
30 * Numerical ID of the language to select in dropdown
32 initialLanguageId?: number;
37 * Whether this form is for a reply to a Private Message.
38 * If true, a "Cancel" button is shown that will close the reply.
45 * Whether to show the language selector
47 showLanguage?: boolean;
48 hideNavigationWarnings?: boolean;
49 onContentChange?(val: string): void;
50 onReplyCancel?(): void;
51 onSubmit?(content: string, formId: string, languageId?: number): void;
52 allLanguages: Language[]; // TODO should probably be nullable
53 siteLanguages: number[]; // TODO same
56 interface ImageUploadStatus {
61 interface MarkdownTextAreaState {
65 imageUploadStatus?: ImageUploadStatus;
70 export class MarkdownTextArea extends Component<
71 MarkdownTextAreaProps,
74 private id = `markdown-textarea-${randomStr()}`;
75 private formId = `markdown-form-${randomStr()}`;
79 state: MarkdownTextAreaState = {
80 content: this.props.initialContent,
81 languageId: this.props.initialLanguageId,
87 constructor(props: any, context: any) {
88 super(props, context);
90 this.handleLanguageChange = this.handleLanguageChange.bind(this);
93 this.tribute = setupTribute();
98 const textarea: any = document.getElementById(this.id);
101 this.tribute.attach(textarea);
102 textarea.addEventListener("tribute-replaced", () => {
103 this.setState({ content: textarea.value });
104 autosize.update(textarea);
109 if (this.props.focus) {
113 // TODO this is slow for some reason
118 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
119 if (nextProps.finished) {
122 imageUploadStatus: undefined,
126 if (this.props.replyType) {
127 this.props.onReplyCancel?.();
130 const textarea: any = document.getElementById(this.id);
131 const form: any = document.getElementById(this.formId);
133 setTimeout(() => autosize.update(textarea), 10);
138 const languageId = this.state.languageId;
142 className="markdown-textarea"
144 onSubmit={linkEvent(this, this.handleSubmit)}
147 message={I18NextService.i18n.t("block_leaving")}
149 !this.props.hideNavigationWarnings &&
150 !!this.state.content &&
151 !this.state.submitted
154 <div className="mb-3 row">
155 <div className="col-12">
156 <div className="rounded bg-light border">
158 className={classNames("d-flex flex-wrap border-bottom", {
159 "no-click": this.isDisabled,
162 {this.getFormatButton("bold", this.handleInsertBold)}
163 {this.getFormatButton("italic", this.handleInsertItalic)}
164 {this.getFormatButton("link", this.handleInsertLink)}
166 onEmojiClick={e => this.handleEmoji(this, e)}
169 htmlFor={`file-upload-${this.id}`}
170 className={classNames("mb-0", {
171 pointer: UserService.Instance.myUserInfo,
173 data-tippy-content={I18NextService.i18n.t("upload_image")}
175 {this.state.imageUploadStatus ? (
180 className="btn btn-sm btn-link rounded-0 text-muted mb-0"
183 .getElementById(`file-upload-${this.id}`)
187 <Icon icon="image" classes="icon-inline" />
192 id={`file-upload-${this.id}`}
194 accept="image/*,video/*"
198 disabled={!UserService.Instance.myUserInfo}
199 onChange={linkEvent(this, this.handleImageUpload)}
201 {this.getFormatButton("header", this.handleInsertHeader)}
202 {this.getFormatButton(
204 this.handleInsertStrikethrough,
206 {this.getFormatButton("quote", this.handleInsertQuote)}
207 {this.getFormatButton("list", this.handleInsertList)}
208 {this.getFormatButton("code", this.handleInsertCode)}
209 {this.getFormatButton("subscript", this.handleInsertSubscript)}
210 {this.getFormatButton(
212 this.handleInsertSuperscript,
214 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
216 href={markdownHelpUrl}
217 className="btn btn-sm btn-link rounded-0 text-muted fw-bold"
218 title={I18NextService.i18n.t("formatting_help")}
221 <Icon icon="help-circle" classes="icon-inline" />
228 className={classNames(
229 "form-control border-0 rounded-top-0 rounded-bottom",
231 "d-none": this.state.previewMode,
234 value={this.state.content}
235 onInput={linkEvent(this, this.handleContentChange)}
236 onPaste={linkEvent(this, this.handleImageUploadPaste)}
237 onKeyDown={linkEvent(this, this.handleKeyBinds)}
239 disabled={this.isDisabled}
242 this.props.maxLength ?? markdownFieldCharacterLimit
244 placeholder={this.props.placeholder}
246 {this.state.previewMode && this.state.content && (
248 className="card border-secondary card-body md-div"
249 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
252 {this.state.imageUploadStatus &&
253 this.state.imageUploadStatus.total > 1 && (
258 value={this.state.imageUploadStatus.uploaded}
259 max={this.state.imageUploadStatus.total}
261 I18NextService.i18n.t("pictures_uploded_progess", {
262 uploaded: this.state.imageUploadStatus.uploaded,
263 total: this.state.imageUploadStatus.total,
269 <label className="visually-hidden" htmlFor={this.id}>
270 {I18NextService.i18n.t("body")}
275 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
276 {this.props.showLanguage && (
279 allLanguages={this.props.allLanguages}
280 selectedLanguageIds={
281 languageId ? Array.of(languageId) : undefined
283 siteLanguages={this.props.siteLanguages}
284 onChange={this.handleLanguageChange}
285 disabled={this.isDisabled}
289 {/* A flex expander */}
290 <div className="flex-grow-1"></div>
292 {this.props.replyType && (
295 className="btn btn-sm btn-secondary ms-2"
296 onClick={linkEvent(this, this.handleReplyCancel)}
298 {I18NextService.i18n.t("cancel")}
303 disabled={!this.state.content}
304 className={classNames("btn btn-sm btn-secondary ms-2", {
305 active: this.state.previewMode,
307 onClick={linkEvent(this, this.handlePreviewToggle)}
309 {this.state.previewMode
310 ? I18NextService.i18n.t("edit")
311 : I18NextService.i18n.t("preview")}
313 {this.props.buttonTitle && (
316 className="btn btn-sm btn-secondary ms-2"
317 disabled={this.isDisabled || !this.state.content}
319 {this.state.loading && <Spinner className="me-1" />}
320 {this.props.buttonTitle}
330 type: NoOptionI18nKeys,
331 handleClick: (i: MarkdownTextArea, event: any) => void,
333 let iconType: string;
337 iconType = "alert-triangle";
341 iconType = "format_quote";
351 className="btn btn-sm btn-link rounded-0 text-muted"
352 data-tippy-content={I18NextService.i18n.t(type)}
353 aria-label={I18NextService.i18n.t(type)}
354 onClick={linkEvent(this, handleClick)}
356 <Icon icon={iconType} classes="icon-inline" />
361 handleEmoji(i: MarkdownTextArea, e: any) {
362 let value = e.native;
363 if (value === null) {
364 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
366 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
370 content: `${i.state.content ?? ""} ${value} `,
373 const textarea: any = document.getElementById(i.id);
374 autosize.update(textarea);
377 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
378 const image = event.clipboardData.files[0];
380 i.handleImageUpload(i, image);
384 handleImageUpload(i: MarkdownTextArea, event: any) {
385 const files: File[] = [];
387 event.preventDefault();
388 files.push(...event.target.files);
393 if (files.length > maxUploadImages) {
395 I18NextService.i18n.t("too_many_images_upload", {
396 count: Number(maxUploadImages),
397 formattedCount: numToSI(maxUploadImages),
403 imageUploadStatus: { total: files.length, uploaded: 0 },
406 i.uploadImages(i, files).then(() => {
407 i.setState({ imageUploadStatus: undefined });
412 async uploadImages(i: MarkdownTextArea, files: File[]) {
413 let errorOccurred = false;
414 const filesCopy = [...files];
415 while (filesCopy.length > 0 && !errorOccurred) {
418 filesCopy.splice(0, concurrentImageUpload).map(async file => {
419 await i.uploadSingleImage(i, file);
421 this.setState(({ imageUploadStatus }) => ({
423 ...(imageUploadStatus as Required<ImageUploadStatus>),
424 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
430 errorOccurred = true;
435 async uploadSingleImage(i: MarkdownTextArea, image: File) {
436 const res = await HttpService.client.uploadImage({ image });
437 console.log("pictrs upload:");
439 if (res.state === "success") {
440 if (res.data.msg === "ok") {
441 const imageMarkdown = `![](${res.data.url})`;
442 i.setState(({ content }) => ({
443 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
446 const textarea: any = document.getElementById(i.id);
447 autosize.update(textarea);
448 pictrsDeleteToast(image.name, res.data.delete_url as string);
449 } else if (res.data.msg === "too_large") {
450 toast(I18NextService.i18n.t("upload_too_large"), "danger");
451 i.setState({ imageUploadStatus: undefined });
452 throw JSON.stringify(res.data);
454 throw JSON.stringify(res.data);
456 } else if (res.state === "failed") {
457 i.setState({ imageUploadStatus: undefined });
458 console.error(res.msg);
459 toast(res.msg, "danger");
466 // Coerces the undefineds to empty strings, for replacing in the DB
467 const content = this.state.content ?? "";
468 this.props.onContentChange?.(content);
471 handleContentChange(i: MarkdownTextArea, event: any) {
472 i.setState({ content: event.target.value });
477 // Keybinds inspired by github comment area
478 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
479 if (platform.isMac() ? event.metaKey : event.ctrlKey) {
482 i.handleInsertLink(i, event);
486 if (!this.isDisabled) {
487 i.handleSubmit(i, event);
493 i.handleInsertBold(i, event);
497 i.handleInsertItalic(i, event);
501 i.handleInsertCode(i, event);
505 i.handleInsertList(i, event);
509 i.handleInsertSpoiler(i, event);
513 if (i.state.content) i.handlePreviewToggle(i, event);
517 i.handleInsertQuote(i, event);
524 handlePreviewToggle(i: MarkdownTextArea, event: any) {
525 event.preventDefault();
526 i.setState({ previewMode: !i.state.previewMode });
529 handleLanguageChange(val: number[]) {
530 this.setState({ languageId: val[0] });
533 handleSubmit(i: MarkdownTextArea, event: any) {
534 event.preventDefault();
535 if (i.state.content) {
536 i.setState({ loading: true, submitted: true });
537 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
541 handleReplyCancel(i: MarkdownTextArea) {
542 i.props.onReplyCancel?.();
545 handleInsertLink(i: MarkdownTextArea, event: any) {
546 event.preventDefault();
548 const textarea: any = document.getElementById(i.id);
549 const start: number = textarea.selectionStart;
550 const end: number = textarea.selectionEnd;
552 const content = i.state.content ?? "";
554 if (!i.state.content) {
555 i.setState({ content: "" });
559 const selectedText = content?.substring(start, end);
561 content: `${content?.substring(
564 )}[${selectedText}]()${content?.substring(end)}`,
567 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
569 i.setState({ content: `${content} []()` });
571 setTimeout(() => (textarea.selectionEnd -= 1), 10);
576 simpleSurround(chars: string) {
577 this.simpleSurroundBeforeAfter(chars, chars);
580 simpleBeginningofLine(chars: string) {
581 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
584 simpleSurroundBeforeAfter(
589 const content = this.state.content ?? "";
590 if (!this.state.content) {
591 this.setState({ content: "" });
593 const textarea: any = document.getElementById(this.id);
594 const start: number = textarea.selectionStart;
595 const end: number = textarea.selectionEnd;
598 const selectedText = content?.substring(start, end);
600 content: `${content?.substring(
603 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
607 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
610 this.contentChange();
615 textarea.setSelectionRange(
616 start + beforeChars.length,
617 end + afterChars.length,
620 textarea.setSelectionRange(
621 start + beforeChars.length,
622 end + emptyChars.length + afterChars.length,
627 autosize.update(textarea);
631 handleInsertBold(i: MarkdownTextArea, event: any) {
632 event.preventDefault();
633 i.simpleSurround("**");
636 handleInsertItalic(i: MarkdownTextArea, event: any) {
637 event.preventDefault();
638 i.simpleSurround("*");
641 handleInsertCode(i: MarkdownTextArea, event: any) {
642 event.preventDefault();
643 if (i.getSelectedText().split(/\r*\n/).length > 1) {
644 i.simpleSurroundBeforeAfter("```\n", "\n```");
646 i.simpleSurround("`");
650 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
651 event.preventDefault();
652 i.simpleSurround("~~");
655 handleInsertList(i: MarkdownTextArea, event: any) {
656 event.preventDefault();
657 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
660 handleInsertQuote(i: MarkdownTextArea, event: any) {
661 event.preventDefault();
662 i.simpleBeginningofLine(">");
665 handleInsertHeader(i: MarkdownTextArea, event: any) {
666 event.preventDefault();
667 i.simpleBeginningofLine("#");
670 handleInsertSubscript(i: MarkdownTextArea, event: any) {
671 event.preventDefault();
672 i.simpleSurround("~");
675 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
676 event.preventDefault();
677 i.simpleSurround("^");
680 simpleInsert(chars: string) {
681 const content = this.state.content;
683 this.setState({ content: `${chars} ` });
686 content: `${content}\n${chars} `,
690 const textarea: any = document.getElementById(this.id);
693 autosize.update(textarea);
695 this.contentChange();
698 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
699 event.preventDefault();
700 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
701 const afterChars = "\n:::\n";
702 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
706 const textarea: any = document.getElementById(this.id);
707 const selectedText = window.getSelection()?.toString();
708 let { content } = this.state;
714 .join("\n") + "\n\n";
719 content = `${content}\n\n`;
723 content: `${content}${quotedText}`,
725 this.contentChange();
726 // Not sure why this needs a delay
727 setTimeout(() => autosize.update(textarea), 10);
731 getSelectedText(): string {
732 const { selectionStart: start, selectionEnd: end } =
733 document.getElementById(this.id) as any;
734 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
739 this.state.loading ||
740 this.props.disabled ||
741 !!this.state.imageUploadStatus