1 import autosize from "autosize";
2 import { NoOptionI18nKeys } from "i18next";
3 import { Component, linkEvent } from "inferno";
4 import { Language } from "lemmy-js-client";
5 import { i18n } from "../../i18next";
6 import { HttpService, UserService } from "../../services";
10 markdownFieldCharacterLimit,
22 import { isBrowser } from "../../utils/browser/is-browser";
23 import { EmojiPicker } from "./emoji-picker";
24 import { Icon, Spinner } from "./icon";
25 import { LanguageSelect } from "./language-select";
26 import NavigationPrompt from "./navigation-prompt";
27 import ProgressBar from "./progress-bar";
28 interface MarkdownTextAreaProps {
29 initialContent?: string;
30 initialLanguageId?: number;
38 showLanguage?: boolean;
39 hideNavigationWarnings?: boolean;
40 onContentChange?(val: string): void;
41 onReplyCancel?(): void;
42 onSubmit?(content: string, formId: string, languageId?: number): void;
43 allLanguages: Language[]; // TODO should probably be nullable
44 siteLanguages: number[]; // TODO same
47 interface ImageUploadStatus {
52 interface MarkdownTextAreaState {
56 imageUploadStatus?: ImageUploadStatus;
61 export class MarkdownTextArea extends Component<
62 MarkdownTextAreaProps,
65 private id = `comment-textarea-${randomStr()}`;
66 private formId = `comment-form-${randomStr()}`;
69 state: MarkdownTextAreaState = {
70 content: this.props.initialContent,
71 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 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
109 if (nextProps.finished) {
112 imageUploadStatus: undefined,
116 if (this.props.replyType) {
117 this.props.onReplyCancel?.();
120 const textarea: any = document.getElementById(this.id);
121 const form: any = document.getElementById(this.formId);
123 setTimeout(() => autosize.update(textarea), 10);
128 const languageId = this.state.languageId;
130 // TODO add these prompts back in at some point
132 // when={!this.props.hideNavigationWarnings && this.state.content}
133 // message={i18n.t("block_leaving")}
136 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
139 !this.props.hideNavigationWarnings &&
140 !!this.state.content &&
141 !this.state.submitted
144 <div className="form-group row">
145 <div className={`col-sm-12`}>
148 className={`form-control ${this.state.previewMode && "d-none"}`}
149 value={this.state.content}
150 onInput={linkEvent(this, this.handleContentChange)}
151 onPaste={linkEvent(this, this.handleImageUploadPaste)}
152 onKeyDown={linkEvent(this, this.handleKeyBinds)}
154 disabled={this.isDisabled}
156 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
157 placeholder={this.props.placeholder}
159 {this.state.previewMode && this.state.content && (
161 className="card border-secondary card-body md-div"
162 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
165 {this.state.imageUploadStatus &&
166 this.state.imageUploadStatus.total > 1 && (
171 value={this.state.imageUploadStatus.uploaded}
172 max={this.state.imageUploadStatus.total}
173 text={i18n.t("pictures_uploded_progess", {
174 uploaded: this.state.imageUploadStatus.uploaded,
175 total: this.state.imageUploadStatus.total,
180 <label className="sr-only" htmlFor={this.id}>
184 <div className="row">
185 <div className="col-sm-12 d-flex flex-wrap">
186 {this.getFormatButton("bold", this.handleInsertBold)}
187 {this.getFormatButton("italic", this.handleInsertItalic)}
188 {this.getFormatButton("link", this.handleInsertLink)}
190 onEmojiClick={e => this.handleEmoji(this, e)}
191 disabled={this.isDisabled}
193 <form className="btn btn-sm text-muted font-weight-bold">
195 htmlFor={`file-upload-${this.id}`}
197 UserService.Instance.myUserInfo && "pointer"
199 data-tippy-content={i18n.t("upload_image")}
201 {this.state.imageUploadStatus ? (
204 <Icon icon="image" classes="icon-inline" />
208 id={`file-upload-${this.id}`}
210 accept="image/*,video/*"
214 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
215 onChange={linkEvent(this, this.handleImageUpload)}
218 {this.getFormatButton("header", this.handleInsertHeader)}
219 {this.getFormatButton(
221 this.handleInsertStrikethrough
223 {this.getFormatButton("quote", this.handleInsertQuote)}
224 {this.getFormatButton("list", this.handleInsertList)}
225 {this.getFormatButton("code", this.handleInsertCode)}
226 {this.getFormatButton("subscript", this.handleInsertSubscript)}
227 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
228 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
230 href={markdownHelpUrl}
231 className="btn btn-sm text-muted font-weight-bold"
232 title={i18n.t("formatting_help")}
235 <Icon icon="help-circle" classes="icon-inline" />
239 <div className="col-sm-12 d-flex align-items-center flex-wrap">
240 {this.props.showLanguage && (
243 allLanguages={this.props.allLanguages}
244 selectedLanguageIds={
245 languageId ? Array.of(languageId) : undefined
247 siteLanguages={this.props.siteLanguages}
248 onChange={this.handleLanguageChange}
249 disabled={this.isDisabled}
253 {/* A flex expander */}
254 <div className="flex-grow-1"></div>
256 {this.props.buttonTitle && (
259 className="btn btn-sm btn-secondary mr-2"
260 disabled={this.isDisabled}
262 {this.state.loading ? (
265 <span>{this.props.buttonTitle}</span>
269 {this.props.replyType && (
272 className="btn btn-sm btn-secondary mr-2"
273 onClick={linkEvent(this, this.handleReplyCancel)}
278 {this.state.content && (
280 className={`btn btn-sm btn-secondary mr-2 ${
281 this.state.previewMode && "active"
283 onClick={linkEvent(this, this.handlePreviewToggle)}
285 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
295 type: NoOptionI18nKeys,
296 handleClick: (i: MarkdownTextArea, event: any) => void
298 let iconType: string;
302 iconType = "alert-triangle";
306 iconType = "format_quote";
316 className="btn btn-sm text-muted"
317 data-tippy-content={i18n.t(type)}
318 aria-label={i18n.t(type)}
319 onClick={linkEvent(this, handleClick)}
320 disabled={this.isDisabled}
322 <Icon icon={iconType} classes="icon-inline" />
327 handleEmoji(i: MarkdownTextArea, e: any) {
328 let value = e.native;
330 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
332 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
336 content: `${i.state.content ?? ""} ${value} `,
339 const textarea: any = document.getElementById(i.id);
340 autosize.update(textarea);
343 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
344 const image = event.clipboardData.files[0];
346 i.handleImageUpload(i, image);
350 handleImageUpload(i: MarkdownTextArea, event: any) {
351 const files: File[] = [];
353 event.preventDefault();
354 files.push(...event.target.files);
359 if (files.length > maxUploadImages) {
361 i18n.t("too_many_images_upload", {
362 count: Number(maxUploadImages),
363 formattedCount: numToSI(maxUploadImages),
369 imageUploadStatus: { total: files.length, uploaded: 0 },
372 i.uploadImages(i, files).then(() => {
373 i.setState({ imageUploadStatus: undefined });
378 async uploadImages(i: MarkdownTextArea, files: File[]) {
379 let errorOccurred = false;
380 const filesCopy = [...files];
381 while (filesCopy.length > 0 && !errorOccurred) {
384 filesCopy.splice(0, concurrentImageUpload).map(async file => {
385 await i.uploadSingleImage(i, file);
387 this.setState(({ imageUploadStatus }) => ({
389 ...(imageUploadStatus as Required<ImageUploadStatus>),
390 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
396 errorOccurred = true;
401 async uploadSingleImage(i: MarkdownTextArea, image: File) {
402 const res = await HttpService.client.uploadImage({ image });
403 console.log("pictrs upload:");
405 if (res.state === "success") {
406 if (res.data.msg === "ok") {
407 const imageMarkdown = `![](${res.data.url})`;
408 i.setState(({ content }) => ({
409 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
412 const textarea: any = document.getElementById(i.id);
413 autosize.update(textarea);
414 pictrsDeleteToast(image.name, res.data.delete_url as string);
416 throw JSON.stringify(res.data);
418 } else if (res.state === "failed") {
419 i.setState({ imageUploadStatus: undefined });
420 console.error(res.msg);
421 toast(res.msg, "danger");
428 // Coerces the undefineds to empty strings, for replacing in the DB
429 const content = this.state.content ?? "";
430 this.props.onContentChange?.(content);
433 handleContentChange(i: MarkdownTextArea, event: any) {
434 i.setState({ content: event.target.value });
439 // Keybinds inspired by github comment area
440 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
444 i.handleInsertLink(i, event);
448 if (!this.isDisabled) {
449 i.handleSubmit(i, event);
455 i.handleInsertBold(i, event);
459 i.handleInsertItalic(i, event);
463 i.handleInsertCode(i, event);
467 i.handleInsertList(i, event);
471 i.handleInsertSpoiler(i, event);
475 if (i.state.content) i.handlePreviewToggle(i, event);
479 i.handleInsertQuote(i, event);
486 handlePreviewToggle(i: MarkdownTextArea, event: any) {
487 event.preventDefault();
488 i.setState({ previewMode: !i.state.previewMode });
491 handleLanguageChange(val: number[]) {
492 this.setState({ languageId: val[0] });
495 handleSubmit(i: MarkdownTextArea, event: any) {
496 event.preventDefault();
497 if (i.state.content) {
498 i.setState({ loading: true, submitted: true });
499 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
503 handleReplyCancel(i: MarkdownTextArea) {
504 i.props.onReplyCancel?.();
507 handleInsertLink(i: MarkdownTextArea, event: any) {
508 event.preventDefault();
510 const textarea: any = document.getElementById(i.id);
511 const start: number = textarea.selectionStart;
512 const end: number = textarea.selectionEnd;
514 const content = i.state.content ?? "";
516 if (!i.state.content) {
517 i.setState({ content: "" });
521 const selectedText = content?.substring(start, end);
523 content: `${content?.substring(
526 )}[${selectedText}]()${content?.substring(end)}`,
529 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
531 i.setState({ content: `${content} []()` });
533 setTimeout(() => (textarea.selectionEnd -= 1), 10);
538 simpleSurround(chars: string) {
539 this.simpleSurroundBeforeAfter(chars, chars);
542 simpleBeginningofLine(chars: string) {
543 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
546 simpleSurroundBeforeAfter(
551 const content = this.state.content ?? "";
552 if (!this.state.content) {
553 this.setState({ content: "" });
555 const textarea: any = document.getElementById(this.id);
556 const start: number = textarea.selectionStart;
557 const end: number = textarea.selectionEnd;
560 const selectedText = content?.substring(start, end);
562 content: `${content?.substring(
565 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
569 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
572 this.contentChange();
577 textarea.setSelectionRange(
578 start + beforeChars.length,
579 end + afterChars.length
582 textarea.setSelectionRange(
583 start + beforeChars.length,
584 end + emptyChars.length + afterChars.length
589 autosize.update(textarea);
593 handleInsertBold(i: MarkdownTextArea, event: any) {
594 event.preventDefault();
595 i.simpleSurround("**");
598 handleInsertItalic(i: MarkdownTextArea, event: any) {
599 event.preventDefault();
600 i.simpleSurround("*");
603 handleInsertCode(i: MarkdownTextArea, event: any) {
604 event.preventDefault();
605 if (i.getSelectedText().split(/\r*\n/).length > 1) {
606 i.simpleSurroundBeforeAfter("```\n", "\n```");
608 i.simpleSurround("`");
612 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
613 event.preventDefault();
614 i.simpleSurround("~~");
617 handleInsertList(i: MarkdownTextArea, event: any) {
618 event.preventDefault();
619 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
622 handleInsertQuote(i: MarkdownTextArea, event: any) {
623 event.preventDefault();
624 i.simpleBeginningofLine(">");
627 handleInsertHeader(i: MarkdownTextArea, event: any) {
628 event.preventDefault();
629 i.simpleBeginningofLine("#");
632 handleInsertSubscript(i: MarkdownTextArea, event: any) {
633 event.preventDefault();
634 i.simpleSurround("~");
637 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
638 event.preventDefault();
639 i.simpleSurround("^");
642 simpleInsert(chars: string) {
643 const content = this.state.content;
645 this.setState({ content: `${chars} ` });
648 content: `${content}\n${chars} `,
652 const textarea: any = document.getElementById(this.id);
655 autosize.update(textarea);
657 this.contentChange();
660 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
661 event.preventDefault();
662 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
663 const afterChars = "\n:::\n";
664 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
668 const textarea: any = document.getElementById(this.id);
669 const selectedText = window.getSelection()?.toString();
670 const { content } = this.state;
676 .join("\n") + "\n\n";
678 this.setState({ content: "" });
680 this.setState({ content: `${content}\n` });
683 content: `${content}${quotedText}`,
685 this.contentChange();
686 // Not sure why this needs a delay
687 setTimeout(() => autosize.update(textarea), 10);
691 getSelectedText(): string {
692 const { selectionStart: start, selectionEnd: end } =
693 document.getElementById(this.id) as any;
694 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
699 this.state.loading ||
700 this.props.disabled ||
701 !!this.state.imageUploadStatus