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 { HttpService, UserService } from "../../services";
10 markdownFieldCharacterLimit,
22 import { isBrowser } from "../../utils/browser/is-browser";
23 import { EmojiPicker } from "./emoji-picker";
24 import { Icon, Spinner } from "./icon";
25 import { LanguageSelect } from "./language-select";
26 import NavigationPrompt from "./navigation-prompt";
27 import ProgressBar from "./progress-bar";
28 interface MarkdownTextAreaProps {
29 initialContent?: string;
30 initialLanguageId?: number;
38 showLanguage?: boolean;
39 hideNavigationWarnings?: boolean;
40 onContentChange?(val: string): void;
41 onReplyCancel?(): void;
42 onSubmit?(content: string, formId: string, languageId?: number): void;
43 allLanguages: Language[]; // TODO should probably be nullable
44 siteLanguages: number[]; // TODO same
47 interface ImageUploadStatus {
52 interface MarkdownTextAreaState {
56 imageUploadStatus?: ImageUploadStatus;
61 export class MarkdownTextArea extends Component<
62 MarkdownTextAreaProps,
65 private id = `comment-textarea-${randomStr()}`;
66 private formId = `comment-form-${randomStr()}`;
69 state: MarkdownTextAreaState = {
70 content: this.props.initialContent,
71 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 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
109 if (nextProps.finished) {
112 imageUploadStatus: undefined,
116 if (this.props.replyType) {
117 this.props.onReplyCancel?.();
120 const textarea: any = document.getElementById(this.id);
121 const form: any = document.getElementById(this.formId);
123 setTimeout(() => autosize.update(textarea), 10);
128 const languageId = this.state.languageId;
130 // TODO add these prompts back in at some point
132 // when={!this.props.hideNavigationWarnings && this.state.content}
133 // message={i18n.t("block_leaving")}
136 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
139 !this.props.hideNavigationWarnings &&
140 !!this.state.content &&
141 !this.state.submitted
144 <div className="form-group row">
145 <div className={`col-sm-12`}>
148 className={`form-control ${this.state.previewMode && "d-none"}`}
149 value={this.state.content}
150 onInput={linkEvent(this, this.handleContentChange)}
151 onPaste={linkEvent(this, this.handleImageUploadPaste)}
152 onKeyDown={linkEvent(this, this.handleKeyBinds)}
154 disabled={this.isDisabled}
156 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
157 placeholder={this.props.placeholder}
159 {this.state.previewMode && this.state.content && (
161 className="card border-secondary card-body md-div"
162 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
165 {this.state.imageUploadStatus &&
166 this.state.imageUploadStatus.total > 1 && (
171 value={this.state.imageUploadStatus.uploaded}
172 max={this.state.imageUploadStatus.total}
173 text={i18n.t("pictures_uploded_progess", {
174 uploaded: this.state.imageUploadStatus.uploaded,
175 total: this.state.imageUploadStatus.total,
180 <label className="sr-only" htmlFor={this.id}>
184 <div className="row">
185 <div className="col-sm-12 d-flex flex-wrap">
186 {this.props.buttonTitle && (
189 className="btn btn-sm btn-secondary mr-2"
190 disabled={this.isDisabled}
192 {this.state.loading ? (
195 <span>{this.props.buttonTitle}</span>
199 {this.props.replyType && (
202 className="btn btn-sm btn-secondary mr-2"
203 onClick={linkEvent(this, this.handleReplyCancel)}
208 {this.state.content && (
210 className={`btn btn-sm btn-secondary mr-2 ${
211 this.state.previewMode && "active"
213 onClick={linkEvent(this, this.handlePreviewToggle)}
215 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
218 {/* A flex expander */}
219 <div className="flex-grow-1"></div>
221 {this.props.showLanguage && (
224 allLanguages={this.props.allLanguages}
225 selectedLanguageIds={
226 languageId ? Array.of(languageId) : undefined
228 siteLanguages={this.props.siteLanguages}
229 onChange={this.handleLanguageChange}
230 disabled={this.isDisabled}
233 {this.getFormatButton("bold", this.handleInsertBold)}
234 {this.getFormatButton("italic", this.handleInsertItalic)}
235 {this.getFormatButton("link", this.handleInsertLink)}
237 onEmojiClick={e => this.handleEmoji(this, e)}
238 disabled={this.isDisabled}
240 <form className="btn btn-sm text-muted font-weight-bold">
242 htmlFor={`file-upload-${this.id}`}
244 UserService.Instance.myUserInfo && "pointer"
246 data-tippy-content={i18n.t("upload_image")}
248 {this.state.imageUploadStatus ? (
251 <Icon icon="image" classes="icon-inline" />
255 id={`file-upload-${this.id}`}
257 accept="image/*,video/*"
261 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
262 onChange={linkEvent(this, this.handleImageUpload)}
265 {this.getFormatButton("header", this.handleInsertHeader)}
266 {this.getFormatButton(
268 this.handleInsertStrikethrough
270 {this.getFormatButton("quote", this.handleInsertQuote)}
271 {this.getFormatButton("list", this.handleInsertList)}
272 {this.getFormatButton("code", this.handleInsertCode)}
273 {this.getFormatButton("subscript", this.handleInsertSubscript)}
274 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
275 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
277 href={markdownHelpUrl}
278 className="btn btn-sm text-muted font-weight-bold"
279 title={i18n.t("formatting_help")}
282 <Icon icon="help-circle" classes="icon-inline" />
291 type: NoOptionI18nKeys,
292 handleClick: (i: MarkdownTextArea, event: any) => void
294 let iconType: string;
298 iconType = "alert-triangle";
302 iconType = "format_quote";
312 className="btn btn-sm text-muted"
313 data-tippy-content={i18n.t(type)}
314 aria-label={i18n.t(type)}
315 onClick={linkEvent(this, handleClick)}
316 disabled={this.isDisabled}
318 <Icon icon={iconType} classes="icon-inline" />
323 handleEmoji(i: MarkdownTextArea, e: any) {
324 let value = e.native;
326 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
328 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
332 content: `${i.state.content ?? ""} ${value} `,
335 const textarea: any = document.getElementById(i.id);
336 autosize.update(textarea);
339 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
340 const image = event.clipboardData.files[0];
342 i.handleImageUpload(i, image);
346 handleImageUpload(i: MarkdownTextArea, event: any) {
347 const files: File[] = [];
349 event.preventDefault();
350 files.push(...event.target.files);
355 if (files.length > maxUploadImages) {
357 i18n.t("too_many_images_upload", {
358 count: Number(maxUploadImages),
359 formattedCount: numToSI(maxUploadImages),
365 imageUploadStatus: { total: files.length, uploaded: 0 },
368 i.uploadImages(i, files).then(() => {
369 i.setState({ imageUploadStatus: undefined });
374 async uploadImages(i: MarkdownTextArea, files: File[]) {
375 let errorOccurred = false;
376 const filesCopy = [...files];
377 while (filesCopy.length > 0 && !errorOccurred) {
380 filesCopy.splice(0, concurrentImageUpload).map(async file => {
381 await i.uploadSingleImage(i, file);
383 this.setState(({ imageUploadStatus }) => ({
385 ...(imageUploadStatus as Required<ImageUploadStatus>),
386 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
392 errorOccurred = true;
397 async uploadSingleImage(i: MarkdownTextArea, image: File) {
398 const res = await HttpService.client.uploadImage({ image });
399 console.log("pictrs upload:");
401 if (res.state === "success") {
402 if (res.data.msg === "ok") {
403 const imageMarkdown = `![](${res.data.url})`;
404 i.setState(({ content }) => ({
405 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
408 const textarea: any = document.getElementById(i.id);
409 autosize.update(textarea);
410 pictrsDeleteToast(image.name, res.data.delete_url as string);
412 throw JSON.stringify(res.data);
414 } else if (res.state === "failed") {
415 i.setState({ imageUploadStatus: undefined });
416 console.error(res.msg);
417 toast(res.msg, "danger");
424 // Coerces the undefineds to empty strings, for replacing in the DB
425 const content = this.state.content ?? "";
426 this.props.onContentChange?.(content);
429 handleContentChange(i: MarkdownTextArea, event: any) {
430 i.setState({ content: event.target.value });
435 // Keybinds inspired by github comment area
436 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
440 i.handleInsertLink(i, event);
444 if (!this.isDisabled) {
445 i.handleSubmit(i, event);
451 i.handleInsertBold(i, event);
455 i.handleInsertItalic(i, event);
459 i.handleInsertCode(i, event);
463 i.handleInsertList(i, event);
467 i.handleInsertSpoiler(i, event);
471 if (i.state.content) i.handlePreviewToggle(i, event);
475 i.handleInsertQuote(i, event);
482 handlePreviewToggle(i: MarkdownTextArea, event: any) {
483 event.preventDefault();
484 i.setState({ previewMode: !i.state.previewMode });
487 handleLanguageChange(val: number[]) {
488 this.setState({ languageId: val[0] });
491 handleSubmit(i: MarkdownTextArea, event: any) {
492 event.preventDefault();
493 if (i.state.content) {
494 i.setState({ loading: true, submitted: true });
495 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
499 handleReplyCancel(i: MarkdownTextArea) {
500 i.props.onReplyCancel?.();
503 handleInsertLink(i: MarkdownTextArea, event: any) {
504 event.preventDefault();
506 const textarea: any = document.getElementById(i.id);
507 const start: number = textarea.selectionStart;
508 const end: number = textarea.selectionEnd;
510 const content = i.state.content ?? "";
512 if (!i.state.content) {
513 i.setState({ content: "" });
517 const selectedText = content?.substring(start, end);
519 content: `${content?.substring(
522 )}[${selectedText}]()${content?.substring(end)}`,
525 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
527 i.setState({ content: `${content} []()` });
529 setTimeout(() => (textarea.selectionEnd -= 1), 10);
534 simpleSurround(chars: string) {
535 this.simpleSurroundBeforeAfter(chars, chars);
538 simpleBeginningofLine(chars: string) {
539 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
542 simpleSurroundBeforeAfter(
547 const content = this.state.content ?? "";
548 if (!this.state.content) {
549 this.setState({ content: "" });
551 const textarea: any = document.getElementById(this.id);
552 const start: number = textarea.selectionStart;
553 const end: number = textarea.selectionEnd;
556 const selectedText = content?.substring(start, end);
558 content: `${content?.substring(
561 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
565 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
568 this.contentChange();
573 textarea.setSelectionRange(
574 start + beforeChars.length,
575 end + afterChars.length
578 textarea.setSelectionRange(
579 start + beforeChars.length,
580 end + emptyChars.length + afterChars.length
585 autosize.update(textarea);
589 handleInsertBold(i: MarkdownTextArea, event: any) {
590 event.preventDefault();
591 i.simpleSurround("**");
594 handleInsertItalic(i: MarkdownTextArea, event: any) {
595 event.preventDefault();
596 i.simpleSurround("*");
599 handleInsertCode(i: MarkdownTextArea, event: any) {
600 event.preventDefault();
601 if (i.getSelectedText().split(/\r*\n/).length > 1) {
602 i.simpleSurroundBeforeAfter("```\n", "\n```");
604 i.simpleSurround("`");
608 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
609 event.preventDefault();
610 i.simpleSurround("~~");
613 handleInsertList(i: MarkdownTextArea, event: any) {
614 event.preventDefault();
615 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
618 handleInsertQuote(i: MarkdownTextArea, event: any) {
619 event.preventDefault();
620 i.simpleBeginningofLine(">");
623 handleInsertHeader(i: MarkdownTextArea, event: any) {
624 event.preventDefault();
625 i.simpleBeginningofLine("#");
628 handleInsertSubscript(i: MarkdownTextArea, event: any) {
629 event.preventDefault();
630 i.simpleSurround("~");
633 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
634 event.preventDefault();
635 i.simpleSurround("^");
638 simpleInsert(chars: string) {
639 const content = this.state.content;
641 this.setState({ content: `${chars} ` });
644 content: `${content}\n${chars} `,
648 const textarea: any = document.getElementById(this.id);
651 autosize.update(textarea);
653 this.contentChange();
656 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
657 event.preventDefault();
658 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
659 const afterChars = "\n:::\n";
660 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
664 const textarea: any = document.getElementById(this.id);
665 const selectedText = window.getSelection()?.toString();
666 const { content } = this.state;
672 .join("\n") + "\n\n";
674 this.setState({ content: "" });
676 this.setState({ content: `${content}\n` });
679 content: `${content}${quotedText}`,
681 this.contentChange();
682 // Not sure why this needs a delay
683 setTimeout(() => autosize.update(textarea), 10);
687 getSelectedText(): string {
688 const { selectionStart: start, selectionEnd: end } =
689 document.getElementById(this.id) as any;
690 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
695 this.state.loading ||
696 this.props.disabled ||
697 !!this.state.imageUploadStatus