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 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
438 // Currently only one case but will support further keybinds
439 i.handleInsertLink(i, event);
445 handlePreviewToggle(i: MarkdownTextArea, event: any) {
446 event.preventDefault();
447 i.setState({ previewMode: !i.state.previewMode });
450 handleLanguageChange(val: number[]) {
451 this.setState({ languageId: val[0] });
454 handleSubmit(i: MarkdownTextArea, event: any) {
455 event.preventDefault();
456 i.setState({ loading: true });
458 val: i.state.content,
460 languageId: i.state.languageId,
462 i.props.onSubmit?.(msg);
465 handleReplyCancel(i: MarkdownTextArea) {
466 i.props.onReplyCancel?.();
469 handleInsertLink(i: MarkdownTextArea, event: any) {
470 event.preventDefault();
472 const textarea: any = document.getElementById(i.id);
473 const start: number = textarea.selectionStart;
474 const end: number = textarea.selectionEnd;
476 const content = i.state.content ?? "";
478 if (!i.state.content) {
479 i.setState({ content: "" });
483 const selectedText = content?.substring(start, end);
485 content: `${content?.substring(
488 )}[${selectedText}]()${content?.substring(end)}`,
491 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
493 i.setState({ content: `${content} []()` });
495 setTimeout(() => (textarea.selectionEnd -= 1), 10);
500 simpleSurround(chars: string) {
501 this.simpleSurroundBeforeAfter(chars, chars);
504 simpleBeginningofLine(chars: string) {
505 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
508 simpleSurroundBeforeAfter(
513 const content = this.state.content ?? "";
514 if (!this.state.content) {
515 this.setState({ content: "" });
517 const textarea: any = document.getElementById(this.id);
518 const start: number = textarea.selectionStart;
519 const end: number = textarea.selectionEnd;
522 const selectedText = content?.substring(start, end);
524 content: `${content?.substring(
527 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
531 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
534 this.contentChange();
539 textarea.setSelectionRange(
540 start + beforeChars.length,
541 end + afterChars.length
544 textarea.setSelectionRange(
545 start + beforeChars.length,
546 end + emptyChars.length + afterChars.length
551 autosize.update(textarea);
555 handleInsertBold(i: MarkdownTextArea, event: any) {
556 event.preventDefault();
557 i.simpleSurround("**");
560 handleInsertItalic(i: MarkdownTextArea, event: any) {
561 event.preventDefault();
562 i.simpleSurround("*");
565 handleInsertCode(i: MarkdownTextArea, event: any) {
566 event.preventDefault();
567 if (i.getSelectedText().split(/\r*\n/).length > 1) {
568 i.simpleSurroundBeforeAfter("```\n", "\n```");
570 i.simpleSurround("`");
574 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
575 event.preventDefault();
576 i.simpleSurround("~~");
579 handleInsertList(i: MarkdownTextArea, event: any) {
580 event.preventDefault();
581 i.simpleBeginningofLine("-");
584 handleInsertQuote(i: MarkdownTextArea, event: any) {
585 event.preventDefault();
586 i.simpleBeginningofLine(">");
589 handleInsertHeader(i: MarkdownTextArea, event: any) {
590 event.preventDefault();
591 i.simpleBeginningofLine("#");
594 handleInsertSubscript(i: MarkdownTextArea, event: any) {
595 event.preventDefault();
596 i.simpleSurround("~");
599 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
600 event.preventDefault();
601 i.simpleSurround("^");
604 simpleInsert(chars: string) {
605 const content = this.state.content;
607 this.setState({ content: `${chars} ` });
610 content: `${content}\n${chars} `,
614 const textarea: any = document.getElementById(this.id);
617 autosize.update(textarea);
619 this.contentChange();
622 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
623 event.preventDefault();
624 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
625 const afterChars = "\n:::\n";
626 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
630 const textarea: any = document.getElementById(this.id);
631 const selectedText = window.getSelection()?.toString();
632 const { content } = this.state;
638 .join("\n") + "\n\n";
640 this.setState({ content: "" });
642 this.setState({ content: `${content}\n` });
645 content: `${content}${quotedText}`,
647 this.contentChange();
648 // Not sure why this needs a delay
649 setTimeout(() => autosize.update(textarea), 10);
653 getSelectedText(): string {
654 const { selectionStart: start, selectionEnd: end } =
655 document.getElementById(this.id) as any;
656 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
661 this.state.loading ||
662 this.props.disabled ||
663 !!this.state.imageUploadStatus