1 import autosize from "autosize";
2 import classNames from "classnames";
3 import { NoOptionI18nKeys } from "i18next";
4 import { Component, linkEvent } from "inferno";
5 import { Language } from "lemmy-js-client";
6 import { i18n } from "../../i18next";
7 import { HttpService, UserService } from "../../services";
12 markdownFieldCharacterLimit,
24 import { EmojiPicker } from "./emoji-picker";
25 import { Icon, Spinner } from "./icon";
26 import { LanguageSelect } from "./language-select";
27 import NavigationPrompt from "./navigation-prompt";
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): void;
43 onReplyCancel?(): void;
44 onSubmit?(content: string, formId: string, languageId?: number): void;
45 allLanguages: Language[]; // TODO should probably be nullable
46 siteLanguages: number[]; // TODO same
49 interface ImageUploadStatus {
54 interface MarkdownTextAreaState {
58 imageUploadStatus?: ImageUploadStatus;
63 export class MarkdownTextArea extends Component<
64 MarkdownTextAreaProps,
67 private id = `markdown-textarea-${randomStr()}`;
68 private formId = `markdown-form-${randomStr()}`;
72 state: MarkdownTextAreaState = {
73 content: this.props.initialContent,
74 languageId: this.props.initialLanguageId,
80 constructor(props: any, context: any) {
81 super(props, context);
83 this.handleLanguageChange = this.handleLanguageChange.bind(this);
86 this.tribute = setupTribute();
91 const textarea: any = document.getElementById(this.id);
94 this.tribute.attach(textarea);
95 textarea.addEventListener("tribute-replaced", () => {
96 this.setState({ content: textarea.value });
97 autosize.update(textarea);
102 if (this.props.focus) {
106 // TODO this is slow for some reason
111 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
112 if (nextProps.finished) {
115 imageUploadStatus: 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);
131 const languageId = this.state.languageId;
133 // TODO add these prompts back in at some point
135 // when={!this.props.hideNavigationWarnings && this.state.content}
136 // message={i18n.t("block_leaving")}
139 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
142 !this.props.hideNavigationWarnings &&
143 !!this.state.content &&
144 !this.state.submitted
147 <div className="form-group row">
148 <div className="col-12">
150 className="rounded bg-light overflow-hidden"
152 border: "1px solid var(--medium-light)",
156 className="d-flex flex-wrap"
158 "border-bottom": "1px solid var(--medium-light)",
161 {this.getFormatButton("bold", this.handleInsertBold)}
162 {this.getFormatButton("italic", this.handleInsertItalic)}
163 {this.getFormatButton("link", this.handleInsertLink)}
165 onEmojiClick={e => this.handleEmoji(this, e)}
166 disabled={this.isDisabled}
168 <form className="btn btn-sm text-muted font-weight-bold">
170 htmlFor={`file-upload-${this.id}`}
172 UserService.Instance.myUserInfo && "pointer"
174 data-tippy-content={i18n.t("upload_image")}
176 {this.state.imageUploadStatus ? (
179 <Icon icon="image" classes="icon-inline" />
183 id={`file-upload-${this.id}`}
185 accept="image/*,video/*"
190 !UserService.Instance.myUserInfo || this.isDisabled
192 onChange={linkEvent(this, this.handleImageUpload)}
195 {this.getFormatButton("header", this.handleInsertHeader)}
196 {this.getFormatButton(
198 this.handleInsertStrikethrough
200 {this.getFormatButton("quote", this.handleInsertQuote)}
201 {this.getFormatButton("list", this.handleInsertList)}
202 {this.getFormatButton("code", this.handleInsertCode)}
203 {this.getFormatButton("subscript", this.handleInsertSubscript)}
204 {this.getFormatButton(
206 this.handleInsertSuperscript
208 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
210 href={markdownHelpUrl}
211 className="btn btn-sm text-muted font-weight-bold"
212 title={i18n.t("formatting_help")}
215 <Icon icon="help-circle" classes="icon-inline" />
222 className={classNames("form-control border-0 rounded-0", {
223 "d-none": this.state.previewMode,
225 value={this.state.content}
226 onInput={linkEvent(this, this.handleContentChange)}
227 onPaste={linkEvent(this, this.handleImageUploadPaste)}
228 onKeyDown={linkEvent(this, this.handleKeyBinds)}
230 disabled={this.isDisabled}
233 this.props.maxLength ?? markdownFieldCharacterLimit
235 placeholder={this.props.placeholder}
237 {this.state.previewMode && this.state.content && (
239 className="card border-secondary card-body md-div"
240 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
243 {this.state.imageUploadStatus &&
244 this.state.imageUploadStatus.total > 1 && (
249 value={this.state.imageUploadStatus.uploaded}
250 max={this.state.imageUploadStatus.total}
251 text={i18n.t("pictures_uploded_progess", {
252 uploaded: this.state.imageUploadStatus.uploaded,
253 total: this.state.imageUploadStatus.total,
258 <label className="sr-only" htmlFor={this.id}>
264 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
265 {this.props.showLanguage && (
268 allLanguages={this.props.allLanguages}
269 selectedLanguageIds={
270 languageId ? Array.of(languageId) : undefined
272 siteLanguages={this.props.siteLanguages}
273 onChange={this.handleLanguageChange}
274 disabled={this.isDisabled}
278 {/* A flex expander */}
279 <div className="flex-grow-1"></div>
281 {this.props.buttonTitle && (
284 className="btn btn-sm btn-secondary ml-2"
285 disabled={this.isDisabled}
287 {this.state.loading ? (
290 <span>{this.props.buttonTitle}</span>
294 {this.props.replyType && (
297 className="btn btn-sm btn-secondary ml-2"
298 onClick={linkEvent(this, this.handleReplyCancel)}
303 {this.state.content && (
305 className={`btn btn-sm btn-secondary ml-2 ${
306 this.state.previewMode && "active"
308 onClick={linkEvent(this, this.handlePreviewToggle)}
310 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
320 type: NoOptionI18nKeys,
321 handleClick: (i: MarkdownTextArea, event: any) => void
323 let iconType: string;
327 iconType = "alert-triangle";
331 iconType = "format_quote";
341 className="btn btn-sm text-muted"
342 data-tippy-content={i18n.t(type)}
343 aria-label={i18n.t(type)}
344 onClick={linkEvent(this, handleClick)}
345 disabled={this.isDisabled}
347 <Icon icon={iconType} classes="icon-inline" />
352 handleEmoji(i: MarkdownTextArea, e: any) {
353 let value = e.native;
355 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
357 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
361 content: `${i.state.content ?? ""} ${value} `,
364 const textarea: any = document.getElementById(i.id);
365 autosize.update(textarea);
368 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
369 const image = event.clipboardData.files[0];
371 i.handleImageUpload(i, image);
375 handleImageUpload(i: MarkdownTextArea, event: any) {
376 const files: File[] = [];
378 event.preventDefault();
379 files.push(...event.target.files);
384 if (files.length > maxUploadImages) {
386 i18n.t("too_many_images_upload", {
387 count: Number(maxUploadImages),
388 formattedCount: numToSI(maxUploadImages),
394 imageUploadStatus: { total: files.length, uploaded: 0 },
397 i.uploadImages(i, files).then(() => {
398 i.setState({ imageUploadStatus: undefined });
403 async uploadImages(i: MarkdownTextArea, files: File[]) {
404 let errorOccurred = false;
405 const filesCopy = [...files];
406 while (filesCopy.length > 0 && !errorOccurred) {
409 filesCopy.splice(0, concurrentImageUpload).map(async file => {
410 await i.uploadSingleImage(i, file);
412 this.setState(({ imageUploadStatus }) => ({
414 ...(imageUploadStatus as Required<ImageUploadStatus>),
415 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
421 errorOccurred = true;
426 async uploadSingleImage(i: MarkdownTextArea, image: File) {
427 const res = await HttpService.client.uploadImage({ image });
428 console.log("pictrs upload:");
430 if (res.state === "success") {
431 if (res.data.msg === "ok") {
432 const imageMarkdown = `![](${res.data.url})`;
433 i.setState(({ content }) => ({
434 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
437 const textarea: any = document.getElementById(i.id);
438 autosize.update(textarea);
439 pictrsDeleteToast(image.name, res.data.delete_url as string);
441 throw JSON.stringify(res.data);
443 } else if (res.state === "failed") {
444 i.setState({ imageUploadStatus: undefined });
445 console.error(res.msg);
446 toast(res.msg, "danger");
453 // Coerces the undefineds to empty strings, for replacing in the DB
454 const content = this.state.content ?? "";
455 this.props.onContentChange?.(content);
458 handleContentChange(i: MarkdownTextArea, event: any) {
459 i.setState({ content: event.target.value });
464 // Keybinds inspired by github comment area
465 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
469 i.handleInsertLink(i, event);
473 if (!this.isDisabled) {
474 i.handleSubmit(i, event);
480 i.handleInsertBold(i, event);
484 i.handleInsertItalic(i, event);
488 i.handleInsertCode(i, event);
492 i.handleInsertList(i, event);
496 i.handleInsertSpoiler(i, event);
500 if (i.state.content) i.handlePreviewToggle(i, event);
504 i.handleInsertQuote(i, event);
511 handlePreviewToggle(i: MarkdownTextArea, event: any) {
512 event.preventDefault();
513 i.setState({ previewMode: !i.state.previewMode });
516 handleLanguageChange(val: number[]) {
517 this.setState({ languageId: val[0] });
520 handleSubmit(i: MarkdownTextArea, event: any) {
521 event.preventDefault();
522 if (i.state.content) {
523 i.setState({ loading: true, submitted: true });
524 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
528 handleReplyCancel(i: MarkdownTextArea) {
529 i.props.onReplyCancel?.();
532 handleInsertLink(i: MarkdownTextArea, event: any) {
533 event.preventDefault();
535 const textarea: any = document.getElementById(i.id);
536 const start: number = textarea.selectionStart;
537 const end: number = textarea.selectionEnd;
539 const content = i.state.content ?? "";
541 if (!i.state.content) {
542 i.setState({ content: "" });
546 const selectedText = content?.substring(start, end);
548 content: `${content?.substring(
551 )}[${selectedText}]()${content?.substring(end)}`,
554 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
556 i.setState({ content: `${content} []()` });
558 setTimeout(() => (textarea.selectionEnd -= 1), 10);
563 simpleSurround(chars: string) {
564 this.simpleSurroundBeforeAfter(chars, chars);
567 simpleBeginningofLine(chars: string) {
568 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
571 simpleSurroundBeforeAfter(
576 const content = this.state.content ?? "";
577 if (!this.state.content) {
578 this.setState({ content: "" });
580 const textarea: any = document.getElementById(this.id);
581 const start: number = textarea.selectionStart;
582 const end: number = textarea.selectionEnd;
585 const selectedText = content?.substring(start, end);
587 content: `${content?.substring(
590 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
594 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
597 this.contentChange();
602 textarea.setSelectionRange(
603 start + beforeChars.length,
604 end + afterChars.length
607 textarea.setSelectionRange(
608 start + beforeChars.length,
609 end + emptyChars.length + afterChars.length
614 autosize.update(textarea);
618 handleInsertBold(i: MarkdownTextArea, event: any) {
619 event.preventDefault();
620 i.simpleSurround("**");
623 handleInsertItalic(i: MarkdownTextArea, event: any) {
624 event.preventDefault();
625 i.simpleSurround("*");
628 handleInsertCode(i: MarkdownTextArea, event: any) {
629 event.preventDefault();
630 if (i.getSelectedText().split(/\r*\n/).length > 1) {
631 i.simpleSurroundBeforeAfter("```\n", "\n```");
633 i.simpleSurround("`");
637 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
638 event.preventDefault();
639 i.simpleSurround("~~");
642 handleInsertList(i: MarkdownTextArea, event: any) {
643 event.preventDefault();
644 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
647 handleInsertQuote(i: MarkdownTextArea, event: any) {
648 event.preventDefault();
649 i.simpleBeginningofLine(">");
652 handleInsertHeader(i: MarkdownTextArea, event: any) {
653 event.preventDefault();
654 i.simpleBeginningofLine("#");
657 handleInsertSubscript(i: MarkdownTextArea, event: any) {
658 event.preventDefault();
659 i.simpleSurround("~");
662 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
663 event.preventDefault();
664 i.simpleSurround("^");
667 simpleInsert(chars: string) {
668 const content = this.state.content;
670 this.setState({ content: `${chars} ` });
673 content: `${content}\n${chars} `,
677 const textarea: any = document.getElementById(this.id);
680 autosize.update(textarea);
682 this.contentChange();
685 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
686 event.preventDefault();
687 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
688 const afterChars = "\n:::\n";
689 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
693 const textarea: any = document.getElementById(this.id);
694 const selectedText = window.getSelection()?.toString();
695 const { content } = this.state;
701 .join("\n") + "\n\n";
703 this.setState({ content: "" });
705 this.setState({ content: `${content}\n` });
708 content: `${content}${quotedText}`,
710 this.contentChange();
711 // Not sure why this needs a delay
712 setTimeout(() => autosize.update(textarea), 10);
716 getSelectedText(): string {
717 const { selectionStart: start, selectionEnd: end } =
718 document.getElementById(this.id) as any;
719 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
724 this.state.loading ||
725 this.props.disabled ||
726 !!this.state.imageUploadStatus