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";
11 markdownFieldCharacterLimit,
23 import { isBrowser } from "../../utils/browser/is-browser";
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";
29 interface MarkdownTextAreaProps {
30 initialContent?: string;
31 initialLanguageId?: number;
39 showLanguage?: boolean;
40 hideNavigationWarnings?: boolean;
41 onContentChange?(val: string): void;
42 onReplyCancel?(): void;
43 onSubmit?(content: string, formId: string, languageId?: number): void;
44 allLanguages: Language[]; // TODO should probably be nullable
45 siteLanguages: number[]; // TODO same
48 interface ImageUploadStatus {
53 interface MarkdownTextAreaState {
57 imageUploadStatus?: ImageUploadStatus;
62 export class MarkdownTextArea extends Component<
63 MarkdownTextAreaProps,
66 private id = `markdown-textarea-${randomStr()}`;
67 private formId = `markdown-form-${randomStr()}`;
71 state: MarkdownTextAreaState = {
72 content: this.props.initialContent,
73 languageId: this.props.initialLanguageId,
79 constructor(props: any, context: any) {
80 super(props, context);
82 this.handleLanguageChange = this.handleLanguageChange.bind(this);
85 this.tribute = setupTribute();
90 const textarea: any = document.getElementById(this.id);
93 this.tribute.attach(textarea);
94 textarea.addEventListener("tribute-replaced", () => {
95 this.setState({ content: textarea.value });
96 autosize.update(textarea);
101 if (this.props.focus) {
105 // TODO this is slow for some reason
110 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
111 if (nextProps.finished) {
114 imageUploadStatus: undefined,
118 if (this.props.replyType) {
119 this.props.onReplyCancel?.();
122 const textarea: any = document.getElementById(this.id);
123 const form: any = document.getElementById(this.formId);
125 setTimeout(() => autosize.update(textarea), 10);
130 const languageId = this.state.languageId;
132 // TODO add these prompts back in at some point
134 // when={!this.props.hideNavigationWarnings && this.state.content}
135 // message={i18n.t("block_leaving")}
138 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
141 !this.props.hideNavigationWarnings &&
142 !!this.state.content &&
143 !this.state.submitted
146 <div className="form-group row">
147 <div className="col-12">
148 <div className="rounded bg-light border border-light">
149 <div className="d-flex flex-wrap border-bottom border-light">
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={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={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}
243 text={i18n.t("pictures_uploded_progess", {
244 uploaded: this.state.imageUploadStatus.uploaded,
245 total: this.state.imageUploadStatus.total,
250 <label className="sr-only" htmlFor={this.id}>
256 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
257 {this.props.showLanguage && (
260 allLanguages={this.props.allLanguages}
261 selectedLanguageIds={
262 languageId ? Array.of(languageId) : undefined
264 siteLanguages={this.props.siteLanguages}
265 onChange={this.handleLanguageChange}
266 disabled={this.isDisabled}
270 {/* A flex expander */}
271 <div className="flex-grow-1"></div>
273 {this.props.buttonTitle && (
276 className="btn btn-sm btn-secondary ml-2"
277 disabled={this.isDisabled}
279 {this.state.loading ? (
282 <span>{this.props.buttonTitle}</span>
286 {this.props.replyType && (
289 className="btn btn-sm btn-secondary ml-2"
290 onClick={linkEvent(this, this.handleReplyCancel)}
295 {this.state.content && (
297 className={`btn btn-sm btn-secondary ml-2 ${
298 this.state.previewMode && "active"
300 onClick={linkEvent(this, this.handlePreviewToggle)}
302 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
312 type: NoOptionI18nKeys,
313 handleClick: (i: MarkdownTextArea, event: any) => void
315 let iconType: string;
319 iconType = "alert-triangle";
323 iconType = "format_quote";
333 className="btn btn-sm text-muted"
334 data-tippy-content={i18n.t(type)}
335 aria-label={i18n.t(type)}
336 onClick={linkEvent(this, handleClick)}
337 disabled={this.isDisabled}
339 <Icon icon={iconType} classes="icon-inline" />
344 handleEmoji(i: MarkdownTextArea, e: any) {
345 let value = e.native;
347 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
349 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
353 content: `${i.state.content ?? ""} ${value} `,
356 const textarea: any = document.getElementById(i.id);
357 autosize.update(textarea);
360 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
361 const image = event.clipboardData.files[0];
363 i.handleImageUpload(i, image);
367 handleImageUpload(i: MarkdownTextArea, event: any) {
368 const files: File[] = [];
370 event.preventDefault();
371 files.push(...event.target.files);
376 if (files.length > maxUploadImages) {
378 i18n.t("too_many_images_upload", {
379 count: Number(maxUploadImages),
380 formattedCount: numToSI(maxUploadImages),
386 imageUploadStatus: { total: files.length, uploaded: 0 },
389 i.uploadImages(i, files).then(() => {
390 i.setState({ imageUploadStatus: undefined });
395 async uploadImages(i: MarkdownTextArea, files: File[]) {
396 let errorOccurred = false;
397 const filesCopy = [...files];
398 while (filesCopy.length > 0 && !errorOccurred) {
401 filesCopy.splice(0, concurrentImageUpload).map(async file => {
402 await i.uploadSingleImage(i, file);
404 this.setState(({ imageUploadStatus }) => ({
406 ...(imageUploadStatus as Required<ImageUploadStatus>),
407 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
413 errorOccurred = true;
418 async uploadSingleImage(i: MarkdownTextArea, image: File) {
419 const res = await HttpService.client.uploadImage({ image });
420 console.log("pictrs upload:");
422 if (res.state === "success") {
423 if (res.data.msg === "ok") {
424 const imageMarkdown = `![](${res.data.url})`;
425 i.setState(({ content }) => ({
426 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
429 const textarea: any = document.getElementById(i.id);
430 autosize.update(textarea);
431 pictrsDeleteToast(image.name, res.data.delete_url as string);
433 throw JSON.stringify(res.data);
435 } else if (res.state === "failed") {
436 i.setState({ imageUploadStatus: undefined });
437 console.error(res.msg);
438 toast(res.msg, "danger");
445 // Coerces the undefineds to empty strings, for replacing in the DB
446 const content = this.state.content ?? "";
447 this.props.onContentChange?.(content);
450 handleContentChange(i: MarkdownTextArea, event: any) {
451 i.setState({ content: event.target.value });
456 // Keybinds inspired by github comment area
457 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
461 i.handleInsertLink(i, event);
465 if (!this.isDisabled) {
466 i.handleSubmit(i, event);
472 i.handleInsertBold(i, event);
476 i.handleInsertItalic(i, event);
480 i.handleInsertCode(i, event);
484 i.handleInsertList(i, event);
488 i.handleInsertSpoiler(i, event);
492 if (i.state.content) i.handlePreviewToggle(i, event);
496 i.handleInsertQuote(i, event);
503 handlePreviewToggle(i: MarkdownTextArea, event: any) {
504 event.preventDefault();
505 i.setState({ previewMode: !i.state.previewMode });
508 handleLanguageChange(val: number[]) {
509 this.setState({ languageId: val[0] });
512 handleSubmit(i: MarkdownTextArea, event: any) {
513 event.preventDefault();
514 if (i.state.content) {
515 i.setState({ loading: true, submitted: true });
516 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
520 handleReplyCancel(i: MarkdownTextArea) {
521 i.props.onReplyCancel?.();
524 handleInsertLink(i: MarkdownTextArea, event: any) {
525 event.preventDefault();
527 const textarea: any = document.getElementById(i.id);
528 const start: number = textarea.selectionStart;
529 const end: number = textarea.selectionEnd;
531 const content = i.state.content ?? "";
533 if (!i.state.content) {
534 i.setState({ content: "" });
538 const selectedText = content?.substring(start, end);
540 content: `${content?.substring(
543 )}[${selectedText}]()${content?.substring(end)}`,
546 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
548 i.setState({ content: `${content} []()` });
550 setTimeout(() => (textarea.selectionEnd -= 1), 10);
555 simpleSurround(chars: string) {
556 this.simpleSurroundBeforeAfter(chars, chars);
559 simpleBeginningofLine(chars: string) {
560 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
563 simpleSurroundBeforeAfter(
568 const content = this.state.content ?? "";
569 if (!this.state.content) {
570 this.setState({ content: "" });
572 const textarea: any = document.getElementById(this.id);
573 const start: number = textarea.selectionStart;
574 const end: number = textarea.selectionEnd;
577 const selectedText = content?.substring(start, end);
579 content: `${content?.substring(
582 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
586 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
589 this.contentChange();
594 textarea.setSelectionRange(
595 start + beforeChars.length,
596 end + afterChars.length
599 textarea.setSelectionRange(
600 start + beforeChars.length,
601 end + emptyChars.length + afterChars.length
606 autosize.update(textarea);
610 handleInsertBold(i: MarkdownTextArea, event: any) {
611 event.preventDefault();
612 i.simpleSurround("**");
615 handleInsertItalic(i: MarkdownTextArea, event: any) {
616 event.preventDefault();
617 i.simpleSurround("*");
620 handleInsertCode(i: MarkdownTextArea, event: any) {
621 event.preventDefault();
622 if (i.getSelectedText().split(/\r*\n/).length > 1) {
623 i.simpleSurroundBeforeAfter("```\n", "\n```");
625 i.simpleSurround("`");
629 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
630 event.preventDefault();
631 i.simpleSurround("~~");
634 handleInsertList(i: MarkdownTextArea, event: any) {
635 event.preventDefault();
636 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
639 handleInsertQuote(i: MarkdownTextArea, event: any) {
640 event.preventDefault();
641 i.simpleBeginningofLine(">");
644 handleInsertHeader(i: MarkdownTextArea, event: any) {
645 event.preventDefault();
646 i.simpleBeginningofLine("#");
649 handleInsertSubscript(i: MarkdownTextArea, event: any) {
650 event.preventDefault();
651 i.simpleSurround("~");
654 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
655 event.preventDefault();
656 i.simpleSurround("^");
659 simpleInsert(chars: string) {
660 const content = this.state.content;
662 this.setState({ content: `${chars} ` });
665 content: `${content}\n${chars} `,
669 const textarea: any = document.getElementById(this.id);
672 autosize.update(textarea);
674 this.contentChange();
677 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
678 event.preventDefault();
679 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
680 const afterChars = "\n:::\n";
681 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
685 const textarea: any = document.getElementById(this.id);
686 const selectedText = window.getSelection()?.toString();
687 const { content } = this.state;
693 .join("\n") + "\n\n";
695 this.setState({ content: "" });
697 this.setState({ content: `${content}\n` });
700 content: `${content}${quotedText}`,
702 this.contentChange();
703 // Not sure why this needs a delay
704 setTimeout(() => autosize.update(textarea), 10);
708 getSelectedText(): string {
709 const { selectionStart: start, selectionEnd: end } =
710 document.getElementById(this.id) as any;
711 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
716 this.state.loading ||
717 this.props.disabled ||
718 !!this.state.imageUploadStatus