1 import autosize from "autosize";
2 import classNames from "classnames";
3 import { NoOptionI18nKeys } from "i18next";
4 import { Component, linkEvent } from "inferno";
5 import { Language } from "lemmy-js-client";
6 import { i18n } from "../../i18next";
7 import { HttpService, UserService } from "../../services";
12 markdownFieldCharacterLimit,
24 import { EmojiPicker } from "./emoji-picker";
25 import { Icon, Spinner } from "./icon";
26 import { LanguageSelect } from "./language-select";
27 import NavigationPrompt from "./navigation-prompt";
28 import ProgressBar from "./progress-bar";
30 interface MarkdownTextAreaProps {
31 initialContent?: string;
32 initialLanguageId?: number;
40 showLanguage?: boolean;
41 hideNavigationWarnings?: boolean;
42 onContentChange?(val: string): void;
43 onReplyCancel?(): void;
44 onSubmit?(content: string, formId: string, languageId?: number): void;
45 allLanguages: Language[]; // TODO should probably be nullable
46 siteLanguages: number[]; // TODO same
49 interface ImageUploadStatus {
54 interface MarkdownTextAreaState {
58 imageUploadStatus?: ImageUploadStatus;
63 export class MarkdownTextArea extends Component<
64 MarkdownTextAreaProps,
67 private id = `markdown-textarea-${randomStr()}`;
68 private formId = `markdown-form-${randomStr()}`;
72 state: MarkdownTextAreaState = {
73 content: this.props.initialContent,
74 languageId: this.props.initialLanguageId,
80 constructor(props: any, context: any) {
81 super(props, context);
83 this.handleLanguageChange = this.handleLanguageChange.bind(this);
86 this.tribute = setupTribute();
91 const textarea: any = document.getElementById(this.id);
94 this.tribute.attach(textarea);
95 textarea.addEventListener("tribute-replaced", () => {
96 this.setState({ content: textarea.value });
97 autosize.update(textarea);
102 if (this.props.focus) {
106 // TODO this is slow for some reason
111 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
112 if (nextProps.finished) {
115 imageUploadStatus: undefined,
119 if (this.props.replyType) {
120 this.props.onReplyCancel?.();
123 const textarea: any = document.getElementById(this.id);
124 const form: any = document.getElementById(this.formId);
126 setTimeout(() => autosize.update(textarea), 10);
131 const languageId = this.state.languageId;
133 // TODO add these prompts back in at some point
135 // when={!this.props.hideNavigationWarnings && this.state.content}
136 // message={i18n.t("block_leaving")}
139 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
142 !this.props.hideNavigationWarnings &&
143 !!this.state.content &&
144 !this.state.submitted
147 <div className="mb-3 row">
148 <div className="col-12">
149 <div className="rounded bg-light border">
150 <div className="d-flex flex-wrap border-bottom">
151 {this.getFormatButton("bold", this.handleInsertBold)}
152 {this.getFormatButton("italic", this.handleInsertItalic)}
153 {this.getFormatButton("link", this.handleInsertLink)}
155 onEmojiClick={e => this.handleEmoji(this, e)}
156 disabled={this.isDisabled}
158 <form className="btn btn-sm text-muted font-weight-bold">
160 htmlFor={`file-upload-${this.id}`}
162 UserService.Instance.myUserInfo && "pointer"
164 data-tippy-content={i18n.t("upload_image")}
166 {this.state.imageUploadStatus ? (
169 <Icon icon="image" classes="icon-inline" />
173 id={`file-upload-${this.id}`}
175 accept="image/*,video/*"
180 !UserService.Instance.myUserInfo || this.isDisabled
182 onChange={linkEvent(this, this.handleImageUpload)}
185 {this.getFormatButton("header", this.handleInsertHeader)}
186 {this.getFormatButton(
188 this.handleInsertStrikethrough
190 {this.getFormatButton("quote", this.handleInsertQuote)}
191 {this.getFormatButton("list", this.handleInsertList)}
192 {this.getFormatButton("code", this.handleInsertCode)}
193 {this.getFormatButton("subscript", this.handleInsertSubscript)}
194 {this.getFormatButton(
196 this.handleInsertSuperscript
198 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
200 href={markdownHelpUrl}
201 className="btn btn-sm text-muted font-weight-bold"
202 title={i18n.t("formatting_help")}
205 <Icon icon="help-circle" classes="icon-inline" />
212 className={classNames(
213 "form-control border-0 rounded-top-0 rounded-bottom",
215 "d-none": this.state.previewMode,
218 value={this.state.content}
219 onInput={linkEvent(this, this.handleContentChange)}
220 onPaste={linkEvent(this, this.handleImageUploadPaste)}
221 onKeyDown={linkEvent(this, this.handleKeyBinds)}
223 disabled={this.isDisabled}
226 this.props.maxLength ?? markdownFieldCharacterLimit
228 placeholder={this.props.placeholder}
230 {this.state.previewMode && this.state.content && (
232 className="card border-secondary card-body md-div"
233 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
236 {this.state.imageUploadStatus &&
237 this.state.imageUploadStatus.total > 1 && (
242 value={this.state.imageUploadStatus.uploaded}
243 max={this.state.imageUploadStatus.total}
244 text={i18n.t("pictures_uploded_progess", {
245 uploaded: this.state.imageUploadStatus.uploaded,
246 total: this.state.imageUploadStatus.total,
251 <label className="visually-hidden" htmlFor={this.id}>
257 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
258 {this.props.showLanguage && (
261 allLanguages={this.props.allLanguages}
262 selectedLanguageIds={
263 languageId ? Array.of(languageId) : undefined
265 siteLanguages={this.props.siteLanguages}
266 onChange={this.handleLanguageChange}
267 disabled={this.isDisabled}
271 {/* A flex expander */}
272 <div className="flex-grow-1"></div>
274 {this.props.buttonTitle && (
277 className="btn btn-sm btn-secondary ms-2"
278 disabled={this.isDisabled}
280 {this.state.loading ? (
283 <span>{this.props.buttonTitle}</span>
287 {this.props.replyType && (
290 className="btn btn-sm btn-secondary ms-2"
291 onClick={linkEvent(this, this.handleReplyCancel)}
296 {this.state.content && (
298 className={`btn btn-sm btn-secondary ms-2 ${
299 this.state.previewMode && "active"
301 onClick={linkEvent(this, this.handlePreviewToggle)}
303 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
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={i18n.t(type)}
336 aria-label={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 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 ${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