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 = `comment-textarea-${randomStr()}`;
68 private formId = `comment-form-${randomStr()}`;
71 state: MarkdownTextAreaState = {
72 content: this.props.initialContent,
73 languageId: this.props.initialLanguageId,
79 constructor(props: any, context: any) {
80 super(props, context);
82 this.handleLanguageChange = this.handleLanguageChange.bind(this);
85 this.tribute = setupTribute();
90 const textarea: any = document.getElementById(this.id);
93 this.tribute.attach(textarea);
94 textarea.addEventListener("tribute-replaced", () => {
95 this.setState({ content: textarea.value });
96 autosize.update(textarea);
101 if (this.props.focus) {
105 // TODO this is slow for some reason
110 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
111 if (nextProps.finished) {
114 imageUploadStatus: undefined,
118 if (this.props.replyType) {
119 this.props.onReplyCancel?.();
122 const textarea: any = document.getElementById(this.id);
123 const form: any = document.getElementById(this.formId);
125 setTimeout(() => autosize.update(textarea), 10);
130 const languageId = this.state.languageId;
132 // TODO add these prompts back in at some point
134 // when={!this.props.hideNavigationWarnings && this.state.content}
135 // message={i18n.t("block_leaving")}
138 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
141 !this.props.hideNavigationWarnings &&
142 !!this.state.content &&
143 !this.state.submitted
146 <div className="form-group row">
147 <div className="col-12">
149 className="rounded bg-light"
151 border: "1px solid var(--medium-light)",
155 className="d-flex flex-wrap"
157 "border-bottom": "1px solid var(--medium-light)",
160 {this.getFormatButton("bold", this.handleInsertBold)}
161 {this.getFormatButton("italic", this.handleInsertItalic)}
162 {this.getFormatButton("link", this.handleInsertLink)}
164 onEmojiClick={e => this.handleEmoji(this, e)}
165 disabled={this.isDisabled}
167 <form className="btn btn-sm text-muted font-weight-bold">
169 htmlFor={`file-upload-${this.id}`}
171 UserService.Instance.myUserInfo && "pointer"
173 data-tippy-content={i18n.t("upload_image")}
175 {this.state.imageUploadStatus ? (
178 <Icon icon="image" classes="icon-inline" />
182 id={`file-upload-${this.id}`}
184 accept="image/*,video/*"
189 !UserService.Instance.myUserInfo || this.isDisabled
191 onChange={linkEvent(this, this.handleImageUpload)}
194 {this.getFormatButton("header", this.handleInsertHeader)}
195 {this.getFormatButton(
197 this.handleInsertStrikethrough
199 {this.getFormatButton("quote", this.handleInsertQuote)}
200 {this.getFormatButton("list", this.handleInsertList)}
201 {this.getFormatButton("code", this.handleInsertCode)}
202 {this.getFormatButton("subscript", this.handleInsertSubscript)}
203 {this.getFormatButton(
205 this.handleInsertSuperscript
207 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
209 href={markdownHelpUrl}
210 className="btn btn-sm text-muted font-weight-bold"
211 title={i18n.t("formatting_help")}
214 <Icon icon="help-circle" classes="icon-inline" />
221 className={classNames("form-control border-0", {
222 "d-none": this.state.previewMode,
224 value={this.state.content}
225 onInput={linkEvent(this, this.handleContentChange)}
226 onPaste={linkEvent(this, this.handleImageUploadPaste)}
227 onKeyDown={linkEvent(this, this.handleKeyBinds)}
229 disabled={this.isDisabled}
232 this.props.maxLength ?? markdownFieldCharacterLimit
234 placeholder={this.props.placeholder}
236 {this.state.previewMode && this.state.content && (
238 className="card border-secondary card-body md-div"
239 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
242 {this.state.imageUploadStatus &&
243 this.state.imageUploadStatus.total > 1 && (
248 value={this.state.imageUploadStatus.uploaded}
249 max={this.state.imageUploadStatus.total}
250 text={i18n.t("pictures_uploded_progess", {
251 uploaded: this.state.imageUploadStatus.uploaded,
252 total: this.state.imageUploadStatus.total,
257 <label className="sr-only" htmlFor={this.id}>
263 <div className="col-12 d-flex align-items-center flex-wrap mt-2">
264 {this.props.showLanguage && (
267 allLanguages={this.props.allLanguages}
268 selectedLanguageIds={
269 languageId ? Array.of(languageId) : undefined
271 siteLanguages={this.props.siteLanguages}
272 onChange={this.handleLanguageChange}
273 disabled={this.isDisabled}
277 {/* A flex expander */}
278 <div className="flex-grow-1"></div>
280 {this.props.buttonTitle && (
283 className="btn btn-sm btn-secondary ml-2"
284 disabled={this.isDisabled}
286 {this.state.loading ? (
289 <span>{this.props.buttonTitle}</span>
293 {this.props.replyType && (
296 className="btn btn-sm btn-secondary ml-2"
297 onClick={linkEvent(this, this.handleReplyCancel)}
302 {this.state.content && (
304 className={`btn btn-sm btn-secondary ml-2 ${
305 this.state.previewMode && "active"
307 onClick={linkEvent(this, this.handlePreviewToggle)}
309 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
319 type: NoOptionI18nKeys,
320 handleClick: (i: MarkdownTextArea, event: any) => void
322 let iconType: string;
326 iconType = "alert-triangle";
330 iconType = "format_quote";
340 className="btn btn-sm text-muted"
341 data-tippy-content={i18n.t(type)}
342 aria-label={i18n.t(type)}
343 onClick={linkEvent(this, handleClick)}
344 disabled={this.isDisabled}
346 <Icon icon={iconType} classes="icon-inline" />
351 handleEmoji(i: MarkdownTextArea, e: any) {
352 let value = e.native;
354 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
356 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
360 content: `${i.state.content ?? ""} ${value} `,
363 const textarea: any = document.getElementById(i.id);
364 autosize.update(textarea);
367 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
368 const image = event.clipboardData.files[0];
370 i.handleImageUpload(i, image);
374 handleImageUpload(i: MarkdownTextArea, event: any) {
375 const files: File[] = [];
377 event.preventDefault();
378 files.push(...event.target.files);
383 if (files.length > maxUploadImages) {
385 i18n.t("too_many_images_upload", {
386 count: Number(maxUploadImages),
387 formattedCount: numToSI(maxUploadImages),
393 imageUploadStatus: { total: files.length, uploaded: 0 },
396 i.uploadImages(i, files).then(() => {
397 i.setState({ imageUploadStatus: undefined });
402 async uploadImages(i: MarkdownTextArea, files: File[]) {
403 let errorOccurred = false;
404 const filesCopy = [...files];
405 while (filesCopy.length > 0 && !errorOccurred) {
408 filesCopy.splice(0, concurrentImageUpload).map(async file => {
409 await i.uploadSingleImage(i, file);
411 this.setState(({ imageUploadStatus }) => ({
413 ...(imageUploadStatus as Required<ImageUploadStatus>),
414 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
420 errorOccurred = true;
425 async uploadSingleImage(i: MarkdownTextArea, image: File) {
426 const res = await HttpService.client.uploadImage({ image });
427 console.log("pictrs upload:");
429 if (res.state === "success") {
430 if (res.data.msg === "ok") {
431 const imageMarkdown = `![](${res.data.url})`;
432 i.setState(({ content }) => ({
433 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
436 const textarea: any = document.getElementById(i.id);
437 autosize.update(textarea);
438 pictrsDeleteToast(image.name, res.data.delete_url as string);
440 throw JSON.stringify(res.data);
442 } else if (res.state === "failed") {
443 i.setState({ imageUploadStatus: undefined });
444 console.error(res.msg);
445 toast(res.msg, "danger");
452 // Coerces the undefineds to empty strings, for replacing in the DB
453 const content = this.state.content ?? "";
454 this.props.onContentChange?.(content);
457 handleContentChange(i: MarkdownTextArea, event: any) {
458 i.setState({ content: event.target.value });
463 // Keybinds inspired by github comment area
464 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
468 i.handleInsertLink(i, event);
472 if (!this.isDisabled) {
473 i.handleSubmit(i, event);
479 i.handleInsertBold(i, event);
483 i.handleInsertItalic(i, event);
487 i.handleInsertCode(i, event);
491 i.handleInsertList(i, event);
495 i.handleInsertSpoiler(i, event);
499 if (i.state.content) i.handlePreviewToggle(i, event);
503 i.handleInsertQuote(i, event);
510 handlePreviewToggle(i: MarkdownTextArea, event: any) {
511 event.preventDefault();
512 i.setState({ previewMode: !i.state.previewMode });
515 handleLanguageChange(val: number[]) {
516 this.setState({ languageId: val[0] });
519 handleSubmit(i: MarkdownTextArea, event: any) {
520 event.preventDefault();
521 if (i.state.content) {
522 i.setState({ loading: true, submitted: true });
523 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
527 handleReplyCancel(i: MarkdownTextArea) {
528 i.props.onReplyCancel?.();
531 handleInsertLink(i: MarkdownTextArea, event: any) {
532 event.preventDefault();
534 const textarea: any = document.getElementById(i.id);
535 const start: number = textarea.selectionStart;
536 const end: number = textarea.selectionEnd;
538 const content = i.state.content ?? "";
540 if (!i.state.content) {
541 i.setState({ content: "" });
545 const selectedText = content?.substring(start, end);
547 content: `${content?.substring(
550 )}[${selectedText}]()${content?.substring(end)}`,
553 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
555 i.setState({ content: `${content} []()` });
557 setTimeout(() => (textarea.selectionEnd -= 1), 10);
562 simpleSurround(chars: string) {
563 this.simpleSurroundBeforeAfter(chars, chars);
566 simpleBeginningofLine(chars: string) {
567 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
570 simpleSurroundBeforeAfter(
575 const content = this.state.content ?? "";
576 if (!this.state.content) {
577 this.setState({ content: "" });
579 const textarea: any = document.getElementById(this.id);
580 const start: number = textarea.selectionStart;
581 const end: number = textarea.selectionEnd;
584 const selectedText = content?.substring(start, end);
586 content: `${content?.substring(
589 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
593 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
596 this.contentChange();
601 textarea.setSelectionRange(
602 start + beforeChars.length,
603 end + afterChars.length
606 textarea.setSelectionRange(
607 start + beforeChars.length,
608 end + emptyChars.length + afterChars.length
613 autosize.update(textarea);
617 handleInsertBold(i: MarkdownTextArea, event: any) {
618 event.preventDefault();
619 i.simpleSurround("**");
622 handleInsertItalic(i: MarkdownTextArea, event: any) {
623 event.preventDefault();
624 i.simpleSurround("*");
627 handleInsertCode(i: MarkdownTextArea, event: any) {
628 event.preventDefault();
629 if (i.getSelectedText().split(/\r*\n/).length > 1) {
630 i.simpleSurroundBeforeAfter("```\n", "\n```");
632 i.simpleSurround("`");
636 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
637 event.preventDefault();
638 i.simpleSurround("~~");
641 handleInsertList(i: MarkdownTextArea, event: any) {
642 event.preventDefault();
643 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
646 handleInsertQuote(i: MarkdownTextArea, event: any) {
647 event.preventDefault();
648 i.simpleBeginningofLine(">");
651 handleInsertHeader(i: MarkdownTextArea, event: any) {
652 event.preventDefault();
653 i.simpleBeginningofLine("#");
656 handleInsertSubscript(i: MarkdownTextArea, event: any) {
657 event.preventDefault();
658 i.simpleSurround("~");
661 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
662 event.preventDefault();
663 i.simpleSurround("^");
666 simpleInsert(chars: string) {
667 const content = this.state.content;
669 this.setState({ content: `${chars} ` });
672 content: `${content}\n${chars} `,
676 const textarea: any = document.getElementById(this.id);
679 autosize.update(textarea);
681 this.contentChange();
684 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
685 event.preventDefault();
686 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
687 const afterChars = "\n:::\n";
688 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
692 const textarea: any = document.getElementById(this.id);
693 const selectedText = window.getSelection()?.toString();
694 const { content } = this.state;
700 .join("\n") + "\n\n";
702 this.setState({ content: "" });
704 this.setState({ content: `${content}\n` });
707 content: `${content}${quotedText}`,
709 this.contentChange();
710 // Not sure why this needs a delay
711 setTimeout(() => autosize.update(textarea), 10);
715 getSelectedText(): string {
716 const { selectionStart: start, selectionEnd: end } =
717 document.getElementById(this.id) as any;
718 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
723 this.state.loading ||
724 this.props.disabled ||
725 !!this.state.imageUploadStatus