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)}
152 disabled={this.isDisabled}
154 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
155 placeholder={this.props.placeholder}
157 {this.state.previewMode && this.state.content && (
159 className="card border-secondary card-body md-div"
160 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
163 {this.state.imageUploadStatus &&
164 this.state.imageUploadStatus.total > 1 && (
169 value={this.state.imageUploadStatus.uploaded}
170 max={this.state.imageUploadStatus.total}
171 text={i18n.t("pictures_uploded_progess", {
172 uploaded: this.state.imageUploadStatus.uploaded,
173 total: this.state.imageUploadStatus.total,
178 <label className="sr-only" htmlFor={this.id}>
182 <div className="row">
183 <div className="col-sm-12 d-flex flex-wrap">
184 {this.props.buttonTitle && (
187 className="btn btn-sm btn-secondary mr-2"
188 disabled={this.isDisabled}
190 {this.state.loading ? (
193 <span>{this.props.buttonTitle}</span>
197 {this.props.replyType && (
200 className="btn btn-sm btn-secondary mr-2"
201 onClick={linkEvent(this, this.handleReplyCancel)}
206 {this.state.content && (
208 className={`btn btn-sm btn-secondary mr-2 ${
209 this.state.previewMode && "active"
211 onClick={linkEvent(this, this.handlePreviewToggle)}
216 {/* A flex expander */}
217 <div className="flex-grow-1"></div>
219 {this.props.showLanguage && (
222 allLanguages={this.props.allLanguages}
223 selectedLanguageIds={
224 languageId ? Array.of(languageId) : undefined
226 siteLanguages={this.props.siteLanguages}
227 onChange={this.handleLanguageChange}
228 disabled={this.isDisabled}
231 {this.getFormatButton("bold", this.handleInsertBold)}
232 {this.getFormatButton("italic", this.handleInsertItalic)}
233 {this.getFormatButton("link", this.handleInsertLink)}
235 onEmojiClick={e => this.handleEmoji(this, e)}
236 disabled={this.isDisabled}
238 <form className="btn btn-sm text-muted font-weight-bold">
240 htmlFor={`file-upload-${this.id}`}
242 UserService.Instance.myUserInfo && "pointer"
244 data-tippy-content={i18n.t("upload_image")}
246 {this.state.imageUploadStatus ? (
249 <Icon icon="image" classes="icon-inline" />
253 id={`file-upload-${this.id}`}
255 accept="image/*,video/*"
259 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
260 onChange={linkEvent(this, this.handleImageUpload)}
263 {this.getFormatButton("header", this.handleInsertHeader)}
264 {this.getFormatButton(
266 this.handleInsertStrikethrough
268 {this.getFormatButton("quote", this.handleInsertQuote)}
269 {this.getFormatButton("list", this.handleInsertList)}
270 {this.getFormatButton("code", this.handleInsertCode)}
271 {this.getFormatButton("subscript", this.handleInsertSubscript)}
272 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
273 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
275 href={markdownHelpUrl}
276 className="btn btn-sm text-muted font-weight-bold"
277 title={i18n.t("formatting_help")}
280 <Icon icon="help-circle" classes="icon-inline" />
289 type: NoOptionI18nKeys,
290 handleClick: (i: MarkdownTextArea, event: any) => void
292 let iconType: string;
296 iconType = "alert-triangle";
300 iconType = "format_quote";
310 className="btn btn-sm text-muted"
311 data-tippy-content={i18n.t(type)}
312 aria-label={i18n.t(type)}
313 onClick={linkEvent(this, handleClick)}
314 disabled={this.isDisabled}
316 <Icon icon={iconType} classes="icon-inline" />
321 handleEmoji(i: MarkdownTextArea, e: any) {
322 let value = e.native;
324 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
326 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
330 content: `${i.state.content ?? ""} ${value} `,
333 const textarea: any = document.getElementById(i.id);
334 autosize.update(textarea);
337 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
338 const image = event.clipboardData.files[0];
340 i.handleImageUpload(i, image);
344 handleImageUpload(i: MarkdownTextArea, event: any) {
345 const files: File[] = [];
347 event.preventDefault();
348 files.push(...event.target.files);
353 if (files.length > maxUploadImages) {
355 i18n.t("too_many_images_upload", {
356 count: Number(maxUploadImages),
357 formattedCount: numToSI(maxUploadImages),
363 imageUploadStatus: { total: files.length, uploaded: 0 },
366 i.uploadImages(i, files).then(() => {
367 i.setState({ imageUploadStatus: undefined });
372 async uploadImages(i: MarkdownTextArea, files: File[]) {
373 let errorOccurred = false;
374 const filesCopy = [...files];
375 while (filesCopy.length > 0 && !errorOccurred) {
378 filesCopy.splice(0, concurrentImageUpload).map(async file => {
379 await i.uploadSingleImage(i, file);
381 this.setState(({ imageUploadStatus }) => ({
383 ...(imageUploadStatus as Required<ImageUploadStatus>),
384 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
390 errorOccurred = true;
395 async uploadSingleImage(i: MarkdownTextArea, file: File) {
397 const res = await uploadImage(file);
398 console.log("pictrs upload:");
400 if (res.msg === "ok") {
401 const imageMarkdown = `![](${res.url})`;
402 i.setState(({ content }) => ({
403 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
406 const textarea: any = document.getElementById(i.id);
407 autosize.update(textarea);
408 pictrsDeleteToast(file.name, res.delete_url as string);
410 throw JSON.stringify(res);
413 i.setState({ imageUploadStatus: undefined });
414 console.error(error);
415 toast(error, "danger");
422 // Coerces the undefineds to empty strings, for replacing in the DB
423 const content = this.state.content ?? "";
424 this.props.onContentChange?.(content);
427 handleContentChange(i: MarkdownTextArea, event: any) {
428 i.setState({ content: event.target.value });
432 handlePreviewToggle(i: MarkdownTextArea, event: any) {
433 event.preventDefault();
434 i.setState({ previewMode: !i.state.previewMode });
437 handleLanguageChange(val: number[]) {
438 this.setState({ languageId: val[0] });
441 handleSubmit(i: MarkdownTextArea, event: any) {
442 event.preventDefault();
443 i.setState({ loading: true });
445 val: i.state.content,
447 languageId: i.state.languageId,
449 i.props.onSubmit?.(msg);
452 handleReplyCancel(i: MarkdownTextArea) {
453 i.props.onReplyCancel?.();
456 handleInsertLink(i: MarkdownTextArea, event: any) {
457 event.preventDefault();
459 const textarea: any = document.getElementById(i.id);
460 const start: number = textarea.selectionStart;
461 const end: number = textarea.selectionEnd;
463 const content = i.state.content ?? "";
465 if (!i.state.content) {
466 i.setState({ content: "" });
470 const selectedText = content?.substring(start, end);
472 content: `${content?.substring(
475 )}[${selectedText}]()${content?.substring(end)}`,
478 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
480 i.setState({ content: `${content} []()` });
482 setTimeout(() => (textarea.selectionEnd -= 1), 10);
487 simpleSurround(chars: string) {
488 this.simpleSurroundBeforeAfter(chars, chars);
491 simpleBeginningofLine(chars: string) {
492 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
495 simpleSurroundBeforeAfter(
500 const content = this.state.content ?? "";
501 if (!this.state.content) {
502 this.setState({ content: "" });
504 const textarea: any = document.getElementById(this.id);
505 const start: number = textarea.selectionStart;
506 const end: number = textarea.selectionEnd;
509 const selectedText = content?.substring(start, end);
511 content: `${content?.substring(
514 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
518 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
521 this.contentChange();
526 textarea.setSelectionRange(
527 start + beforeChars.length,
528 end + afterChars.length
531 textarea.setSelectionRange(
532 start + beforeChars.length,
533 end + emptyChars.length + afterChars.length
538 autosize.update(textarea);
542 handleInsertBold(i: MarkdownTextArea, event: any) {
543 event.preventDefault();
544 i.simpleSurround("**");
547 handleInsertItalic(i: MarkdownTextArea, event: any) {
548 event.preventDefault();
549 i.simpleSurround("*");
552 handleInsertCode(i: MarkdownTextArea, event: any) {
553 event.preventDefault();
554 if (i.getSelectedText().split(/\r*\n/).length > 1) {
555 i.simpleSurroundBeforeAfter("```\n", "\n```");
557 i.simpleSurround("`");
561 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
562 event.preventDefault();
563 i.simpleSurround("~~");
566 handleInsertList(i: MarkdownTextArea, event: any) {
567 event.preventDefault();
568 i.simpleBeginningofLine("-");
571 handleInsertQuote(i: MarkdownTextArea, event: any) {
572 event.preventDefault();
573 i.simpleBeginningofLine(">");
576 handleInsertHeader(i: MarkdownTextArea, event: any) {
577 event.preventDefault();
578 i.simpleBeginningofLine("#");
581 handleInsertSubscript(i: MarkdownTextArea, event: any) {
582 event.preventDefault();
583 i.simpleSurround("~");
586 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
587 event.preventDefault();
588 i.simpleSurround("^");
591 simpleInsert(chars: string) {
592 const content = this.state.content;
594 this.setState({ content: `${chars} ` });
597 content: `${content}\n${chars} `,
601 const textarea: any = document.getElementById(this.id);
604 autosize.update(textarea);
606 this.contentChange();
609 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
610 event.preventDefault();
611 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
612 const afterChars = "\n:::\n";
613 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
617 const textarea: any = document.getElementById(this.id);
618 const selectedText = window.getSelection()?.toString();
619 const { content } = this.state;
625 .join("\n") + "\n\n";
627 this.setState({ content: "" });
629 this.setState({ content: `${content}\n` });
632 content: `${content}${quotedText}`,
634 this.contentChange();
635 // Not sure why this needs a delay
636 setTimeout(() => autosize.update(textarea), 10);
640 getSelectedText(): string {
641 const { selectionStart: start, selectionEnd: end } =
642 document.getElementById(this.id) as any;
643 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
648 this.state.loading ||
649 this.props.disabled ||
650 !!this.state.imageUploadStatus