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)}
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) {
438 case "k": // Insert link
439 i.handleInsertLink(i, event);
441 case "b": // Insert bold
442 i.handleInsertBold(i, event);
444 case "i": // Insert italic
445 i.handleInsertItalic(i, event);
447 case "e": // Insert code
448 i.handleInsertCode(i, event);
450 case "8": // Insert unordered list
451 i.handleInsertList(i, event);
453 case "s": // Insert spoiler
454 i.handleInsertSpoiler(i, event);
456 case "p": // Move to preview view
457 if (i.state.content) i.handlePreviewToggle(i, event);
459 case ".": // Insert quote
460 i.handleInsertQuote(i, event);
466 handlePreviewToggle(i: MarkdownTextArea, event: any) {
467 event.preventDefault();
468 i.setState({ previewMode: !i.state.previewMode });
471 handleLanguageChange(val: number[]) {
472 this.setState({ languageId: val[0] });
475 handleSubmit(i: MarkdownTextArea, event: any) {
476 event.preventDefault();
477 i.setState({ loading: true });
479 val: i.state.content,
481 languageId: i.state.languageId,
483 i.props.onSubmit?.(msg);
486 handleReplyCancel(i: MarkdownTextArea) {
487 i.props.onReplyCancel?.();
490 handleInsertLink(i: MarkdownTextArea, event: any) {
491 event.preventDefault();
493 const textarea: any = document.getElementById(i.id);
494 const start: number = textarea.selectionStart;
495 const end: number = textarea.selectionEnd;
497 const content = i.state.content ?? "";
499 if (!i.state.content) {
500 i.setState({ content: "" });
504 const selectedText = content?.substring(start, end);
506 content: `${content?.substring(
509 )}[${selectedText}]()${content?.substring(end)}`,
512 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
514 i.setState({ content: `${content} []()` });
516 setTimeout(() => (textarea.selectionEnd -= 1), 10);
521 simpleSurround(chars: string) {
522 this.simpleSurroundBeforeAfter(chars, chars);
525 simpleBeginningofLine(chars: string) {
526 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
529 simpleSurroundBeforeAfter(
534 const content = this.state.content ?? "";
535 if (!this.state.content) {
536 this.setState({ content: "" });
538 const textarea: any = document.getElementById(this.id);
539 const start: number = textarea.selectionStart;
540 const end: number = textarea.selectionEnd;
543 const selectedText = content?.substring(start, end);
545 content: `${content?.substring(
548 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
552 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
555 this.contentChange();
560 textarea.setSelectionRange(
561 start + beforeChars.length,
562 end + afterChars.length
565 textarea.setSelectionRange(
566 start + beforeChars.length,
567 end + emptyChars.length + afterChars.length
572 autosize.update(textarea);
576 handleInsertBold(i: MarkdownTextArea, event: any) {
577 event.preventDefault();
578 i.simpleSurround("**");
581 handleInsertItalic(i: MarkdownTextArea, event: any) {
582 event.preventDefault();
583 i.simpleSurround("*");
586 handleInsertCode(i: MarkdownTextArea, event: any) {
587 event.preventDefault();
588 if (i.getSelectedText().split(/\r*\n/).length > 1) {
589 i.simpleSurroundBeforeAfter("```\n", "\n```");
591 i.simpleSurround("`");
595 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
596 event.preventDefault();
597 i.simpleSurround("~~");
600 handleInsertList(i: MarkdownTextArea, event: any) {
601 event.preventDefault();
602 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
605 handleInsertQuote(i: MarkdownTextArea, event: any) {
606 event.preventDefault();
607 i.simpleBeginningofLine(">");
610 handleInsertHeader(i: MarkdownTextArea, event: any) {
611 event.preventDefault();
612 i.simpleBeginningofLine("#");
615 handleInsertSubscript(i: MarkdownTextArea, event: any) {
616 event.preventDefault();
617 i.simpleSurround("~");
620 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
621 event.preventDefault();
622 i.simpleSurround("^");
625 simpleInsert(chars: string) {
626 const content = this.state.content;
628 this.setState({ content: `${chars} ` });
631 content: `${content}\n${chars} `,
635 const textarea: any = document.getElementById(this.id);
638 autosize.update(textarea);
640 this.contentChange();
643 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
644 event.preventDefault();
645 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
646 const afterChars = "\n:::\n";
647 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
651 const textarea: any = document.getElementById(this.id);
652 const selectedText = window.getSelection()?.toString();
653 const { content } = this.state;
659 .join("\n") + "\n\n";
661 this.setState({ content: "" });
663 this.setState({ content: `${content}\n` });
666 content: `${content}${quotedText}`,
668 this.contentChange();
669 // Not sure why this needs a delay
670 setTimeout(() => autosize.update(textarea), 10);
674 getSelectedText(): string {
675 const { selectionStart: start, selectionEnd: end } =
676 document.getElementById(this.id) as any;
677 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
682 this.state.loading ||
683 this.props.disabled ||
684 !!this.state.imageUploadStatus