1 import autosize from "autosize";
2 import { NoOptionI18nKeys } from "i18next";
3 import { Component, linkEvent } from "inferno";
4 import { Prompt } from "inferno-router";
5 import { Language } from "lemmy-js-client";
6 import { i18n } from "../../i18next";
7 import { UserService } from "../../services";
12 markdownFieldCharacterLimit,
25 import { EmojiPicker } from "./emoji-picker";
26 import { Icon, Spinner } from "./icon";
27 import { LanguageSelect } from "./language-select";
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)}>
140 when={!this.props.hideNavigationWarnings && this.state.content}
141 message={i18n.t("block_leaving")}
143 <div className="form-group row">
144 <div className={`col-sm-12`}>
147 className={`form-control ${this.state.previewMode && "d-none"}`}
148 value={this.state.content}
149 onInput={linkEvent(this, this.handleContentChange)}
150 onPaste={linkEvent(this, this.handleImageUploadPaste)}
151 onKeyDown={linkEvent(this, this.handleKeyBinds)}
153 disabled={this.isDisabled}
155 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
156 placeholder={this.props.placeholder}
158 {this.state.previewMode && this.state.content && (
160 className="card border-secondary card-body md-div"
161 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
164 {this.state.imageUploadStatus &&
165 this.state.imageUploadStatus.total > 1 && (
170 value={this.state.imageUploadStatus.uploaded}
171 max={this.state.imageUploadStatus.total}
172 text={i18n.t("pictures_uploded_progess", {
173 uploaded: this.state.imageUploadStatus.uploaded,
174 total: this.state.imageUploadStatus.total,
179 <label className="sr-only" htmlFor={this.id}>
183 <div className="row">
184 <div className="col-sm-12 d-flex flex-wrap">
185 {this.props.buttonTitle && (
188 className="btn btn-sm btn-secondary mr-2"
189 disabled={this.isDisabled}
191 {this.state.loading ? (
194 <span>{this.props.buttonTitle}</span>
198 {this.props.replyType && (
201 className="btn btn-sm btn-secondary mr-2"
202 onClick={linkEvent(this, this.handleReplyCancel)}
207 {this.state.content && (
209 className={`btn btn-sm btn-secondary mr-2 ${
210 this.state.previewMode && "active"
212 onClick={linkEvent(this, this.handlePreviewToggle)}
214 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
217 {/* A flex expander */}
218 <div className="flex-grow-1"></div>
220 {this.props.showLanguage && (
223 allLanguages={this.props.allLanguages}
224 selectedLanguageIds={
225 languageId ? Array.of(languageId) : undefined
227 siteLanguages={this.props.siteLanguages}
228 onChange={this.handleLanguageChange}
229 disabled={this.isDisabled}
232 {this.getFormatButton("bold", this.handleInsertBold)}
233 {this.getFormatButton("italic", this.handleInsertItalic)}
234 {this.getFormatButton("link", this.handleInsertLink)}
236 onEmojiClick={e => this.handleEmoji(this, e)}
237 disabled={this.isDisabled}
239 <form className="btn btn-sm text-muted font-weight-bold">
241 htmlFor={`file-upload-${this.id}`}
243 UserService.Instance.myUserInfo && "pointer"
245 data-tippy-content={i18n.t("upload_image")}
247 {this.state.imageUploadStatus ? (
250 <Icon icon="image" classes="icon-inline" />
254 id={`file-upload-${this.id}`}
256 accept="image/*,video/*"
260 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
261 onChange={linkEvent(this, this.handleImageUpload)}
264 {this.getFormatButton("header", this.handleInsertHeader)}
265 {this.getFormatButton(
267 this.handleInsertStrikethrough
269 {this.getFormatButton("quote", this.handleInsertQuote)}
270 {this.getFormatButton("list", this.handleInsertList)}
271 {this.getFormatButton("code", this.handleInsertCode)}
272 {this.getFormatButton("subscript", this.handleInsertSubscript)}
273 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
274 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
276 href={markdownHelpUrl}
277 className="btn btn-sm text-muted font-weight-bold"
278 title={i18n.t("formatting_help")}
281 <Icon icon="help-circle" classes="icon-inline" />
290 type: NoOptionI18nKeys,
291 handleClick: (i: MarkdownTextArea, event: any) => void
293 let iconType: string;
297 iconType = "alert-triangle";
301 iconType = "format_quote";
311 className="btn btn-sm text-muted"
312 data-tippy-content={i18n.t(type)}
313 aria-label={i18n.t(type)}
314 onClick={linkEvent(this, handleClick)}
315 disabled={this.isDisabled}
317 <Icon icon={iconType} classes="icon-inline" />
322 handleEmoji(i: MarkdownTextArea, e: any) {
323 let value = e.native;
325 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
327 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
331 content: `${i.state.content ?? ""} ${value} `,
334 const textarea: any = document.getElementById(i.id);
335 autosize.update(textarea);
338 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
339 const image = event.clipboardData.files[0];
341 i.handleImageUpload(i, image);
345 handleImageUpload(i: MarkdownTextArea, event: any) {
346 const files: File[] = [];
348 event.preventDefault();
349 files.push(...event.target.files);
354 if (files.length > maxUploadImages) {
356 i18n.t("too_many_images_upload", {
357 count: Number(maxUploadImages),
358 formattedCount: numToSI(maxUploadImages),
364 imageUploadStatus: { total: files.length, uploaded: 0 },
367 i.uploadImages(i, files).then(() => {
368 i.setState({ imageUploadStatus: undefined });
373 async uploadImages(i: MarkdownTextArea, files: File[]) {
374 let errorOccurred = false;
375 const filesCopy = [...files];
376 while (filesCopy.length > 0 && !errorOccurred) {
379 filesCopy.splice(0, concurrentImageUpload).map(async file => {
380 await i.uploadSingleImage(i, file);
382 this.setState(({ imageUploadStatus }) => ({
384 ...(imageUploadStatus as Required<ImageUploadStatus>),
385 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
391 errorOccurred = true;
396 async uploadSingleImage(i: MarkdownTextArea, file: File) {
398 const res = await uploadImage(file);
399 console.log("pictrs upload:");
401 if (res.msg === "ok") {
402 const imageMarkdown = `![](${res.url})`;
403 i.setState(({ content }) => ({
404 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
407 const textarea: any = document.getElementById(i.id);
408 autosize.update(textarea);
409 pictrsDeleteToast(file.name, res.delete_url as string);
411 throw JSON.stringify(res);
414 i.setState({ imageUploadStatus: undefined });
415 console.error(error);
416 toast(error, "danger");
423 // Coerces the undefineds to empty strings, for replacing in the DB
424 const content = this.state.content ?? "";
425 this.props.onContentChange?.(content);
428 handleContentChange(i: MarkdownTextArea, event: any) {
429 i.setState({ content: event.target.value });
434 // Keybinds inspired by github comment area
435 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
439 i.handleInsertLink(i, event);
443 if (!this.isDisabled) {
444 i.handleSubmit(i, event);
450 i.handleInsertBold(i, event);
454 i.handleInsertItalic(i, event);
458 i.handleInsertCode(i, event);
462 i.handleInsertList(i, event);
466 i.handleInsertSpoiler(i, event);
470 if (i.state.content) i.handlePreviewToggle(i, event);
474 i.handleInsertQuote(i, event);
481 handlePreviewToggle(i: MarkdownTextArea, event: any) {
482 event.preventDefault();
483 i.setState({ previewMode: !i.state.previewMode });
486 handleLanguageChange(val: number[]) {
487 this.setState({ languageId: val[0] });
490 handleSubmit(i: MarkdownTextArea, event: any) {
491 event.preventDefault();
492 i.setState({ loading: true });
494 val: i.state.content,
496 languageId: i.state.languageId,
498 i.props.onSubmit?.(msg);
501 handleReplyCancel(i: MarkdownTextArea) {
502 i.props.onReplyCancel?.();
505 handleInsertLink(i: MarkdownTextArea, event: any) {
506 event.preventDefault();
508 const textarea: any = document.getElementById(i.id);
509 const start: number = textarea.selectionStart;
510 const end: number = textarea.selectionEnd;
512 const content = i.state.content ?? "";
514 if (!i.state.content) {
515 i.setState({ content: "" });
519 const selectedText = content?.substring(start, end);
521 content: `${content?.substring(
524 )}[${selectedText}]()${content?.substring(end)}`,
527 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
529 i.setState({ content: `${content} []()` });
531 setTimeout(() => (textarea.selectionEnd -= 1), 10);
536 simpleSurround(chars: string) {
537 this.simpleSurroundBeforeAfter(chars, chars);
540 simpleBeginningofLine(chars: string) {
541 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
544 simpleSurroundBeforeAfter(
549 const content = this.state.content ?? "";
550 if (!this.state.content) {
551 this.setState({ content: "" });
553 const textarea: any = document.getElementById(this.id);
554 const start: number = textarea.selectionStart;
555 const end: number = textarea.selectionEnd;
558 const selectedText = content?.substring(start, end);
560 content: `${content?.substring(
563 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
567 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
570 this.contentChange();
575 textarea.setSelectionRange(
576 start + beforeChars.length,
577 end + afterChars.length
580 textarea.setSelectionRange(
581 start + beforeChars.length,
582 end + emptyChars.length + afterChars.length
587 autosize.update(textarea);
591 handleInsertBold(i: MarkdownTextArea, event: any) {
592 event.preventDefault();
593 i.simpleSurround("**");
596 handleInsertItalic(i: MarkdownTextArea, event: any) {
597 event.preventDefault();
598 i.simpleSurround("*");
601 handleInsertCode(i: MarkdownTextArea, event: any) {
602 event.preventDefault();
603 if (i.getSelectedText().split(/\r*\n/).length > 1) {
604 i.simpleSurroundBeforeAfter("```\n", "\n```");
606 i.simpleSurround("`");
610 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
611 event.preventDefault();
612 i.simpleSurround("~~");
615 handleInsertList(i: MarkdownTextArea, event: any) {
616 event.preventDefault();
617 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
620 handleInsertQuote(i: MarkdownTextArea, event: any) {
621 event.preventDefault();
622 i.simpleBeginningofLine(">");
625 handleInsertHeader(i: MarkdownTextArea, event: any) {
626 event.preventDefault();
627 i.simpleBeginningofLine("#");
630 handleInsertSubscript(i: MarkdownTextArea, event: any) {
631 event.preventDefault();
632 i.simpleSurround("~");
635 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
636 event.preventDefault();
637 i.simpleSurround("^");
640 simpleInsert(chars: string) {
641 const content = this.state.content;
643 this.setState({ content: `${chars} ` });
646 content: `${content}\n${chars} `,
650 const textarea: any = document.getElementById(this.id);
653 autosize.update(textarea);
655 this.contentChange();
658 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
659 event.preventDefault();
660 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
661 const afterChars = "\n:::\n";
662 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
666 const textarea: any = document.getElementById(this.id);
667 const selectedText = window.getSelection()?.toString();
668 const { content } = this.state;
674 .join("\n") + "\n\n";
676 this.setState({ content: "" });
678 this.setState({ content: `${content}\n` });
681 content: `${content}${quotedText}`,
683 this.contentChange();
684 // Not sure why this needs a delay
685 setTimeout(() => autosize.update(textarea), 10);
689 getSelectedText(): string {
690 const { selectionStart: start, selectionEnd: end } =
691 document.getElementById(this.id) as any;
692 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
697 this.state.loading ||
698 this.props.disabled ||
699 !!this.state.imageUploadStatus