1 import autosize from "autosize";
2 import { NoOptionI18nKeys } from "i18next";
3 import { Component, linkEvent } from "inferno";
4 import { Language } from "lemmy-js-client";
5 import { i18n } from "../../i18next";
6 import { UserService } from "../../services";
11 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): any;
43 onReplyCancel?(): any;
44 onSubmit?(msg: { val?: string; formId: string; languageId?: number }): any;
45 allLanguages: Language[]; // TODO should probably be nullable
46 siteLanguages: number[]; // TODO same
49 interface ImageUploadStatus {
54 interface MarkdownTextAreaState {
59 imageUploadStatus?: ImageUploadStatus;
62 export class MarkdownTextArea extends Component<
63 MarkdownTextAreaProps,
66 private id = `comment-textarea-${randomStr()}`;
67 private formId = `comment-form-${randomStr()}`;
70 state: MarkdownTextAreaState = {
71 content: this.props.initialContent,
72 languageId: this.props.initialLanguageId,
77 constructor(props: any, context: any) {
78 super(props, context);
80 this.handleLanguageChange = this.handleLanguageChange.bind(this);
83 this.tribute = setupTribute();
88 const textarea: any = document.getElementById(this.id);
91 this.tribute.attach(textarea);
92 textarea.addEventListener("tribute-replaced", () => {
93 this.setState({ content: textarea.value });
94 autosize.update(textarea);
99 if (this.props.focus) {
103 // TODO this is slow for some reason
108 componentDidUpdate() {
109 if (!this.props.hideNavigationWarnings && this.state.content) {
110 window.onbeforeunload = () => true;
112 window.onbeforeunload = null;
116 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
117 if (nextProps.finished) {
118 this.setState({ previewMode: false, loading: false, content: 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);
130 componentWillUnmount() {
131 window.onbeforeunload = null;
135 const languageId = this.state.languageId;
138 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
139 <NavigationPrompt when={!!this.state.content} />
140 <div className="form-group row">
141 <div className={`col-sm-12`}>
144 className={`form-control ${this.state.previewMode && "d-none"}`}
145 value={this.state.content}
146 onInput={linkEvent(this, this.handleContentChange)}
147 onPaste={linkEvent(this, this.handleImageUploadPaste)}
148 onKeyDown={linkEvent(this, this.handleKeyBinds)}
150 disabled={this.isDisabled}
152 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
153 placeholder={this.props.placeholder}
155 {this.state.previewMode && this.state.content && (
157 className="card border-secondary card-body md-div"
158 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
161 {this.state.imageUploadStatus &&
162 this.state.imageUploadStatus.total > 1 && (
167 value={this.state.imageUploadStatus.uploaded}
168 max={this.state.imageUploadStatus.total}
169 text={i18n.t("pictures_uploded_progess", {
170 uploaded: this.state.imageUploadStatus.uploaded,
171 total: this.state.imageUploadStatus.total,
176 <label className="sr-only" htmlFor={this.id}>
180 <div className="row">
181 <div className="col-sm-12 d-flex flex-wrap">
182 {this.props.buttonTitle && (
185 className="btn btn-sm btn-secondary mr-2"
186 disabled={this.isDisabled}
188 {this.state.loading ? (
191 <span>{this.props.buttonTitle}</span>
195 {this.props.replyType && (
198 className="btn btn-sm btn-secondary mr-2"
199 onClick={linkEvent(this, this.handleReplyCancel)}
204 {this.state.content && (
206 className={`btn btn-sm btn-secondary mr-2 ${
207 this.state.previewMode && "active"
209 onClick={linkEvent(this, this.handlePreviewToggle)}
211 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
214 {/* A flex expander */}
215 <div className="flex-grow-1"></div>
217 {this.props.showLanguage && (
220 allLanguages={this.props.allLanguages}
221 selectedLanguageIds={
222 languageId ? Array.of(languageId) : undefined
224 siteLanguages={this.props.siteLanguages}
225 onChange={this.handleLanguageChange}
226 disabled={this.isDisabled}
229 {this.getFormatButton("bold", this.handleInsertBold)}
230 {this.getFormatButton("italic", this.handleInsertItalic)}
231 {this.getFormatButton("link", this.handleInsertLink)}
233 onEmojiClick={e => this.handleEmoji(this, e)}
234 disabled={this.isDisabled}
236 <form className="btn btn-sm text-muted font-weight-bold">
238 htmlFor={`file-upload-${this.id}`}
240 UserService.Instance.myUserInfo && "pointer"
242 data-tippy-content={i18n.t("upload_image")}
244 {this.state.imageUploadStatus ? (
247 <Icon icon="image" classes="icon-inline" />
251 id={`file-upload-${this.id}`}
253 accept="image/*,video/*"
257 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
258 onChange={linkEvent(this, this.handleImageUpload)}
261 {this.getFormatButton("header", this.handleInsertHeader)}
262 {this.getFormatButton(
264 this.handleInsertStrikethrough
266 {this.getFormatButton("quote", this.handleInsertQuote)}
267 {this.getFormatButton("list", this.handleInsertList)}
268 {this.getFormatButton("code", this.handleInsertCode)}
269 {this.getFormatButton("subscript", this.handleInsertSubscript)}
270 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
271 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
273 href={markdownHelpUrl}
274 className="btn btn-sm text-muted font-weight-bold"
275 title={i18n.t("formatting_help")}
278 <Icon icon="help-circle" classes="icon-inline" />
287 type: NoOptionI18nKeys,
288 handleClick: (i: MarkdownTextArea, event: any) => void
290 let iconType: string;
294 iconType = "alert-triangle";
298 iconType = "format_quote";
308 className="btn btn-sm text-muted"
309 data-tippy-content={i18n.t(type)}
310 aria-label={i18n.t(type)}
311 onClick={linkEvent(this, handleClick)}
312 disabled={this.isDisabled}
314 <Icon icon={iconType} classes="icon-inline" />
319 handleEmoji(i: MarkdownTextArea, e: any) {
320 let value = e.native;
322 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
324 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
328 content: `${i.state.content ?? ""} ${value} `,
331 const textarea: any = document.getElementById(i.id);
332 autosize.update(textarea);
335 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
336 const image = event.clipboardData.files[0];
338 i.handleImageUpload(i, image);
342 handleImageUpload(i: MarkdownTextArea, event: any) {
343 const files: File[] = [];
345 event.preventDefault();
346 files.push(...event.target.files);
351 if (files.length > maxUploadImages) {
353 i18n.t("too_many_images_upload", {
354 count: Number(maxUploadImages),
355 formattedCount: numToSI(maxUploadImages),
361 imageUploadStatus: { total: files.length, uploaded: 0 },
364 i.uploadImages(i, files).then(() => {
365 i.setState({ imageUploadStatus: undefined });
370 async uploadImages(i: MarkdownTextArea, files: File[]) {
371 let errorOccurred = false;
372 const filesCopy = [...files];
373 while (filesCopy.length > 0 && !errorOccurred) {
376 filesCopy.splice(0, concurrentImageUpload).map(async file => {
377 await i.uploadSingleImage(i, file);
379 this.setState(({ imageUploadStatus }) => ({
381 ...(imageUploadStatus as Required<ImageUploadStatus>),
382 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
388 errorOccurred = true;
393 async uploadSingleImage(i: MarkdownTextArea, file: File) {
395 const res = await uploadImage(file);
396 console.log("pictrs upload:");
398 if (res.msg === "ok") {
399 const imageMarkdown = `![](${res.url})`;
400 i.setState(({ content }) => ({
401 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
404 const textarea: any = document.getElementById(i.id);
405 autosize.update(textarea);
406 pictrsDeleteToast(file.name, res.delete_url as string);
408 throw JSON.stringify(res);
411 i.setState({ imageUploadStatus: undefined });
412 console.error(error);
413 toast(error, "danger");
420 // Coerces the undefineds to empty strings, for replacing in the DB
421 const content = this.state.content ?? "";
422 this.props.onContentChange?.(content);
425 handleContentChange(i: MarkdownTextArea, event: any) {
426 i.setState({ content: event.target.value });
431 // Keybinds inspired by github comment area
432 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
436 i.handleInsertLink(i, event);
440 if (!this.isDisabled) {
441 i.handleSubmit(i, event);
447 i.handleInsertBold(i, event);
451 i.handleInsertItalic(i, event);
455 i.handleInsertCode(i, event);
459 i.handleInsertList(i, event);
463 i.handleInsertSpoiler(i, event);
467 if (i.state.content) i.handlePreviewToggle(i, event);
471 i.handleInsertQuote(i, event);
478 handlePreviewToggle(i: MarkdownTextArea, event: any) {
479 event.preventDefault();
480 i.setState({ previewMode: !i.state.previewMode });
483 handleLanguageChange(val: number[]) {
484 this.setState({ languageId: val[0] });
487 handleSubmit(i: MarkdownTextArea, event: any) {
488 event.preventDefault();
489 i.setState({ loading: true });
491 val: i.state.content,
493 languageId: i.state.languageId,
495 i.props.onSubmit?.(msg);
498 handleReplyCancel(i: MarkdownTextArea) {
499 i.props.onReplyCancel?.();
502 handleInsertLink(i: MarkdownTextArea, event: any) {
503 event.preventDefault();
505 const textarea: any = document.getElementById(i.id);
506 const start: number = textarea.selectionStart;
507 const end: number = textarea.selectionEnd;
509 const content = i.state.content ?? "";
511 if (!i.state.content) {
512 i.setState({ content: "" });
516 const selectedText = content?.substring(start, end);
518 content: `${content?.substring(
521 )}[${selectedText}]()${content?.substring(end)}`,
524 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
526 i.setState({ content: `${content} []()` });
528 setTimeout(() => (textarea.selectionEnd -= 1), 10);
533 simpleSurround(chars: string) {
534 this.simpleSurroundBeforeAfter(chars, chars);
537 simpleBeginningofLine(chars: string) {
538 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
541 simpleSurroundBeforeAfter(
546 const content = this.state.content ?? "";
547 if (!this.state.content) {
548 this.setState({ content: "" });
550 const textarea: any = document.getElementById(this.id);
551 const start: number = textarea.selectionStart;
552 const end: number = textarea.selectionEnd;
555 const selectedText = content?.substring(start, end);
557 content: `${content?.substring(
560 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
564 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
567 this.contentChange();
572 textarea.setSelectionRange(
573 start + beforeChars.length,
574 end + afterChars.length
577 textarea.setSelectionRange(
578 start + beforeChars.length,
579 end + emptyChars.length + afterChars.length
584 autosize.update(textarea);
588 handleInsertBold(i: MarkdownTextArea, event: any) {
589 event.preventDefault();
590 i.simpleSurround("**");
593 handleInsertItalic(i: MarkdownTextArea, event: any) {
594 event.preventDefault();
595 i.simpleSurround("*");
598 handleInsertCode(i: MarkdownTextArea, event: any) {
599 event.preventDefault();
600 if (i.getSelectedText().split(/\r*\n/).length > 1) {
601 i.simpleSurroundBeforeAfter("```\n", "\n```");
603 i.simpleSurround("`");
607 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
608 event.preventDefault();
609 i.simpleSurround("~~");
612 handleInsertList(i: MarkdownTextArea, event: any) {
613 event.preventDefault();
614 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
617 handleInsertQuote(i: MarkdownTextArea, event: any) {
618 event.preventDefault();
619 i.simpleBeginningofLine(">");
622 handleInsertHeader(i: MarkdownTextArea, event: any) {
623 event.preventDefault();
624 i.simpleBeginningofLine("#");
627 handleInsertSubscript(i: MarkdownTextArea, event: any) {
628 event.preventDefault();
629 i.simpleSurround("~");
632 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
633 event.preventDefault();
634 i.simpleSurround("^");
637 simpleInsert(chars: string) {
638 const content = this.state.content;
640 this.setState({ content: `${chars} ` });
643 content: `${content}\n${chars} `,
647 const textarea: any = document.getElementById(this.id);
650 autosize.update(textarea);
652 this.contentChange();
655 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
656 event.preventDefault();
657 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
658 const afterChars = "\n:::\n";
659 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
663 const textarea: any = document.getElementById(this.id);
664 const selectedText = window.getSelection()?.toString();
665 const { content } = this.state;
671 .join("\n") + "\n\n";
673 this.setState({ content: "" });
675 this.setState({ content: `${content}\n` });
678 content: `${content}${quotedText}`,
680 this.contentChange();
681 // Not sure why this needs a delay
682 setTimeout(() => autosize.update(textarea), 10);
686 getSelectedText(): string {
687 const { selectionStart: start, selectionEnd: end } =
688 document.getElementById(this.id) as any;
689 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
694 this.state.loading ||
695 this.props.disabled ||
696 !!this.state.imageUploadStatus