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.replyType && (
278 className="btn btn-sm btn-secondary ms-2"
279 onClick={linkEvent(this, this.handleReplyCancel)}
281 {I18NextService.i18n.t("cancel")}
286 disabled={!this.state.content ? true : false}
287 className={`btn btn-sm btn-secondary ms-2 ${
288 this.state.previewMode && "active"
290 onClick={linkEvent(this, this.handlePreviewToggle)}
292 {this.state.previewMode
293 ? I18NextService.i18n.t("edit")
294 : I18NextService.i18n.t("preview")}
296 {this.props.buttonTitle && (
299 className="btn btn-sm btn-secondary ms-2"
300 disabled={this.isDisabled}
302 {this.state.loading && <Spinner className="me-1" />}
303 {this.props.buttonTitle}
313 type: NoOptionI18nKeys,
314 handleClick: (i: MarkdownTextArea, event: any) => void
316 let iconType: string;
320 iconType = "alert-triangle";
324 iconType = "format_quote";
334 className="btn btn-sm text-muted"
335 data-tippy-content={I18NextService.i18n.t(type)}
336 aria-label={I18NextService.i18n.t(type)}
337 onClick={linkEvent(this, handleClick)}
338 disabled={this.isDisabled}
340 <Icon icon={iconType} classes="icon-inline" />
345 handleEmoji(i: MarkdownTextArea, e: any) {
346 let value = e.native;
348 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
350 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
354 content: `${i.state.content ?? ""} ${value} `,
357 const textarea: any = document.getElementById(i.id);
358 autosize.update(textarea);
361 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
362 const image = event.clipboardData.files[0];
364 i.handleImageUpload(i, image);
368 handleImageUpload(i: MarkdownTextArea, event: any) {
369 const files: File[] = [];
371 event.preventDefault();
372 files.push(...event.target.files);
377 if (files.length > maxUploadImages) {
379 I18NextService.i18n.t("too_many_images_upload", {
380 count: Number(maxUploadImages),
381 formattedCount: numToSI(maxUploadImages),
387 imageUploadStatus: { total: files.length, uploaded: 0 },
390 i.uploadImages(i, files).then(() => {
391 i.setState({ imageUploadStatus: undefined });
396 async uploadImages(i: MarkdownTextArea, files: File[]) {
397 let errorOccurred = false;
398 const filesCopy = [...files];
399 while (filesCopy.length > 0 && !errorOccurred) {
402 filesCopy.splice(0, concurrentImageUpload).map(async file => {
403 await i.uploadSingleImage(i, file);
405 this.setState(({ imageUploadStatus }) => ({
407 ...(imageUploadStatus as Required<ImageUploadStatus>),
408 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
414 errorOccurred = true;
419 async uploadSingleImage(i: MarkdownTextArea, image: File) {
420 const res = await HttpService.client.uploadImage({ image });
421 console.log("pictrs upload:");
423 if (res.state === "success") {
424 if (res.data.msg === "ok") {
425 const imageMarkdown = `![](${res.data.url})`;
426 i.setState(({ content }) => ({
427 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
430 const textarea: any = document.getElementById(i.id);
431 autosize.update(textarea);
432 pictrsDeleteToast(image.name, res.data.delete_url as string);
434 throw JSON.stringify(res.data);
436 } else if (res.state === "failed") {
437 i.setState({ imageUploadStatus: undefined });
438 console.error(res.msg);
439 toast(res.msg, "danger");
446 // Coerces the undefineds to empty strings, for replacing in the DB
447 const content = this.state.content ?? "";
448 this.props.onContentChange?.(content);
451 handleContentChange(i: MarkdownTextArea, event: any) {
452 i.setState({ content: event.target.value });
457 // Keybinds inspired by github comment area
458 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
462 i.handleInsertLink(i, event);
466 if (!this.isDisabled) {
467 i.handleSubmit(i, event);
473 i.handleInsertBold(i, event);
477 i.handleInsertItalic(i, event);
481 i.handleInsertCode(i, event);
485 i.handleInsertList(i, event);
489 i.handleInsertSpoiler(i, event);
493 if (i.state.content) i.handlePreviewToggle(i, event);
497 i.handleInsertQuote(i, event);
504 handlePreviewToggle(i: MarkdownTextArea, event: any) {
505 event.preventDefault();
506 i.setState({ previewMode: !i.state.previewMode });
509 handleLanguageChange(val: number[]) {
510 this.setState({ languageId: val[0] });
513 handleSubmit(i: MarkdownTextArea, event: any) {
514 event.preventDefault();
515 if (i.state.content) {
516 i.setState({ loading: true, submitted: true });
517 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
521 handleReplyCancel(i: MarkdownTextArea) {
522 i.props.onReplyCancel?.();
525 handleInsertLink(i: MarkdownTextArea, event: any) {
526 event.preventDefault();
528 const textarea: any = document.getElementById(i.id);
529 const start: number = textarea.selectionStart;
530 const end: number = textarea.selectionEnd;
532 const content = i.state.content ?? "";
534 if (!i.state.content) {
535 i.setState({ content: "" });
539 const selectedText = content?.substring(start, end);
541 content: `${content?.substring(
544 )}[${selectedText}]()${content?.substring(end)}`,
547 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
549 i.setState({ content: `${content} []()` });
551 setTimeout(() => (textarea.selectionEnd -= 1), 10);
556 simpleSurround(chars: string) {
557 this.simpleSurroundBeforeAfter(chars, chars);
560 simpleBeginningofLine(chars: string) {
561 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
564 simpleSurroundBeforeAfter(
569 const content = this.state.content ?? "";
570 if (!this.state.content) {
571 this.setState({ content: "" });
573 const textarea: any = document.getElementById(this.id);
574 const start: number = textarea.selectionStart;
575 const end: number = textarea.selectionEnd;
578 const selectedText = content?.substring(start, end);
580 content: `${content?.substring(
583 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
587 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
590 this.contentChange();
595 textarea.setSelectionRange(
596 start + beforeChars.length,
597 end + afterChars.length
600 textarea.setSelectionRange(
601 start + beforeChars.length,
602 end + emptyChars.length + afterChars.length
607 autosize.update(textarea);
611 handleInsertBold(i: MarkdownTextArea, event: any) {
612 event.preventDefault();
613 i.simpleSurround("**");
616 handleInsertItalic(i: MarkdownTextArea, event: any) {
617 event.preventDefault();
618 i.simpleSurround("*");
621 handleInsertCode(i: MarkdownTextArea, event: any) {
622 event.preventDefault();
623 if (i.getSelectedText().split(/\r*\n/).length > 1) {
624 i.simpleSurroundBeforeAfter("```\n", "\n```");
626 i.simpleSurround("`");
630 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
631 event.preventDefault();
632 i.simpleSurround("~~");
635 handleInsertList(i: MarkdownTextArea, event: any) {
636 event.preventDefault();
637 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
640 handleInsertQuote(i: MarkdownTextArea, event: any) {
641 event.preventDefault();
642 i.simpleBeginningofLine(">");
645 handleInsertHeader(i: MarkdownTextArea, event: any) {
646 event.preventDefault();
647 i.simpleBeginningofLine("#");
650 handleInsertSubscript(i: MarkdownTextArea, event: any) {
651 event.preventDefault();
652 i.simpleSurround("~");
655 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
656 event.preventDefault();
657 i.simpleSurround("^");
660 simpleInsert(chars: string) {
661 const content = this.state.content;
663 this.setState({ content: `${chars} ` });
666 content: `${content}\n${chars} `,
670 const textarea: any = document.getElementById(this.id);
673 autosize.update(textarea);
675 this.contentChange();
678 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
679 event.preventDefault();
680 const beforeChars = `\n::: spoiler ${I18NextService.i18n.t("spoiler")}\n`;
681 const afterChars = "\n:::\n";
682 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
686 const textarea: any = document.getElementById(this.id);
687 const selectedText = window.getSelection()?.toString();
688 const { content } = this.state;
694 .join("\n") + "\n\n";
696 this.setState({ content: "" });
698 this.setState({ content: `${content}\n` });
701 content: `${content}${quotedText}`,
703 this.contentChange();
704 // Not sure why this needs a delay
705 setTimeout(() => autosize.update(textarea), 10);
709 getSelectedText(): string {
710 const { selectionStart: start, selectionEnd: end } =
711 document.getElementById(this.id) as any;
712 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
717 this.state.loading ||
718 this.props.disabled ||
719 !!this.state.imageUploadStatus