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";
11 markdownFieldCharacterLimit,
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";
29 interface MarkdownTextAreaProps {
30 initialContent?: string;
31 initialLanguageId?: number;
39 showLanguage?: boolean;
40 hideNavigationWarnings?: boolean;
41 onContentChange?(val: string): void;
42 onReplyCancel?(): void;
43 onSubmit?(content: string, formId: string, languageId?: number): void;
44 allLanguages: Language[]; // TODO should probably be nullable
45 siteLanguages: number[]; // TODO same
48 interface ImageUploadStatus {
53 interface MarkdownTextAreaState {
57 imageUploadStatus?: ImageUploadStatus;
62 export class MarkdownTextArea extends Component<
63 MarkdownTextAreaProps,
66 private id = `markdown-textarea-${randomStr()}`;
67 private formId = `markdown-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-sm-12`}>
150 className={`form-control ${this.state.previewMode && "d-none"}`}
151 value={this.state.content}
152 onInput={linkEvent(this, this.handleContentChange)}
153 onPaste={linkEvent(this, this.handleImageUploadPaste)}
154 onKeyDown={linkEvent(this, this.handleKeyBinds)}
156 disabled={this.isDisabled}
158 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
159 placeholder={this.props.placeholder}
161 {this.state.previewMode && this.state.content && (
163 className="card border-secondary card-body md-div"
164 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
167 {this.state.imageUploadStatus &&
168 this.state.imageUploadStatus.total > 1 && (
173 value={this.state.imageUploadStatus.uploaded}
174 max={this.state.imageUploadStatus.total}
175 text={i18n.t("pictures_uploded_progess", {
176 uploaded: this.state.imageUploadStatus.uploaded,
177 total: this.state.imageUploadStatus.total,
182 <label className="sr-only" htmlFor={this.id}>
186 <div className="row">
187 <div className="col-sm-12 d-flex flex-wrap">
188 {this.getFormatButton("bold", this.handleInsertBold)}
189 {this.getFormatButton("italic", this.handleInsertItalic)}
190 {this.getFormatButton("link", this.handleInsertLink)}
192 onEmojiClick={e => this.handleEmoji(this, e)}
193 disabled={this.isDisabled}
195 <form className="btn btn-sm text-muted font-weight-bold">
197 htmlFor={`file-upload-${this.id}`}
199 UserService.Instance.myUserInfo && "pointer"
201 data-tippy-content={i18n.t("upload_image")}
203 {this.state.imageUploadStatus ? (
206 <Icon icon="image" classes="icon-inline" />
210 id={`file-upload-${this.id}`}
212 accept="image/*,video/*"
216 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
217 onChange={linkEvent(this, this.handleImageUpload)}
220 {this.getFormatButton("header", this.handleInsertHeader)}
221 {this.getFormatButton(
223 this.handleInsertStrikethrough
225 {this.getFormatButton("quote", this.handleInsertQuote)}
226 {this.getFormatButton("list", this.handleInsertList)}
227 {this.getFormatButton("code", this.handleInsertCode)}
228 {this.getFormatButton("subscript", this.handleInsertSubscript)}
229 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
230 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
232 href={markdownHelpUrl}
233 className="btn btn-sm text-muted font-weight-bold"
234 title={i18n.t("formatting_help")}
237 <Icon icon="help-circle" classes="icon-inline" />
241 <div className="col-sm-12 d-flex align-items-center flex-wrap">
242 {this.props.showLanguage && (
245 allLanguages={this.props.allLanguages}
246 selectedLanguageIds={
247 languageId ? Array.of(languageId) : undefined
249 siteLanguages={this.props.siteLanguages}
250 onChange={this.handleLanguageChange}
251 disabled={this.isDisabled}
255 {/* A flex expander */}
256 <div className="flex-grow-1"></div>
258 {this.props.buttonTitle && (
261 className="btn btn-sm btn-secondary mr-2"
262 disabled={this.isDisabled}
264 {this.state.loading ? (
267 <span>{this.props.buttonTitle}</span>
271 {this.props.replyType && (
274 className="btn btn-sm btn-secondary mr-2"
275 onClick={linkEvent(this, this.handleReplyCancel)}
280 {this.state.content && (
282 className={`btn btn-sm btn-secondary mr-2 ${
283 this.state.previewMode && "active"
285 onClick={linkEvent(this, this.handlePreviewToggle)}
287 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
297 type: NoOptionI18nKeys,
298 handleClick: (i: MarkdownTextArea, event: any) => void
300 let iconType: string;
304 iconType = "alert-triangle";
308 iconType = "format_quote";
318 className="btn btn-sm text-muted"
319 data-tippy-content={i18n.t(type)}
320 aria-label={i18n.t(type)}
321 onClick={linkEvent(this, handleClick)}
322 disabled={this.isDisabled}
324 <Icon icon={iconType} classes="icon-inline" />
329 handleEmoji(i: MarkdownTextArea, e: any) {
330 let value = e.native;
332 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
334 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
338 content: `${i.state.content ?? ""} ${value} `,
341 const textarea: any = document.getElementById(i.id);
342 autosize.update(textarea);
345 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
346 const image = event.clipboardData.files[0];
348 i.handleImageUpload(i, image);
352 handleImageUpload(i: MarkdownTextArea, event: any) {
353 const files: File[] = [];
355 event.preventDefault();
356 files.push(...event.target.files);
361 if (files.length > maxUploadImages) {
363 i18n.t("too_many_images_upload", {
364 count: Number(maxUploadImages),
365 formattedCount: numToSI(maxUploadImages),
371 imageUploadStatus: { total: files.length, uploaded: 0 },
374 i.uploadImages(i, files).then(() => {
375 i.setState({ imageUploadStatus: undefined });
380 async uploadImages(i: MarkdownTextArea, files: File[]) {
381 let errorOccurred = false;
382 const filesCopy = [...files];
383 while (filesCopy.length > 0 && !errorOccurred) {
386 filesCopy.splice(0, concurrentImageUpload).map(async file => {
387 await i.uploadSingleImage(i, file);
389 this.setState(({ imageUploadStatus }) => ({
391 ...(imageUploadStatus as Required<ImageUploadStatus>),
392 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
398 errorOccurred = true;
403 async uploadSingleImage(i: MarkdownTextArea, image: File) {
404 const res = await HttpService.client.uploadImage({ image });
405 console.log("pictrs upload:");
407 if (res.state === "success") {
408 if (res.data.msg === "ok") {
409 const imageMarkdown = `![](${res.data.url})`;
410 i.setState(({ content }) => ({
411 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
414 const textarea: any = document.getElementById(i.id);
415 autosize.update(textarea);
416 pictrsDeleteToast(image.name, res.data.delete_url as string);
418 throw JSON.stringify(res.data);
420 } else if (res.state === "failed") {
421 i.setState({ imageUploadStatus: undefined });
422 console.error(res.msg);
423 toast(res.msg, "danger");
430 // Coerces the undefineds to empty strings, for replacing in the DB
431 const content = this.state.content ?? "";
432 this.props.onContentChange?.(content);
435 handleContentChange(i: MarkdownTextArea, event: any) {
436 i.setState({ content: event.target.value });
441 // Keybinds inspired by github comment area
442 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
446 i.handleInsertLink(i, event);
450 if (!this.isDisabled) {
451 i.handleSubmit(i, event);
457 i.handleInsertBold(i, event);
461 i.handleInsertItalic(i, event);
465 i.handleInsertCode(i, event);
469 i.handleInsertList(i, event);
473 i.handleInsertSpoiler(i, event);
477 if (i.state.content) i.handlePreviewToggle(i, event);
481 i.handleInsertQuote(i, event);
488 handlePreviewToggle(i: MarkdownTextArea, event: any) {
489 event.preventDefault();
490 i.setState({ previewMode: !i.state.previewMode });
493 handleLanguageChange(val: number[]) {
494 this.setState({ languageId: val[0] });
497 handleSubmit(i: MarkdownTextArea, event: any) {
498 event.preventDefault();
499 if (i.state.content) {
500 i.setState({ loading: true, submitted: true });
501 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
505 handleReplyCancel(i: MarkdownTextArea) {
506 i.props.onReplyCancel?.();
509 handleInsertLink(i: MarkdownTextArea, event: any) {
510 event.preventDefault();
512 const textarea: any = document.getElementById(i.id);
513 const start: number = textarea.selectionStart;
514 const end: number = textarea.selectionEnd;
516 const content = i.state.content ?? "";
518 if (!i.state.content) {
519 i.setState({ content: "" });
523 const selectedText = content?.substring(start, end);
525 content: `${content?.substring(
528 )}[${selectedText}]()${content?.substring(end)}`,
531 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
533 i.setState({ content: `${content} []()` });
535 setTimeout(() => (textarea.selectionEnd -= 1), 10);
540 simpleSurround(chars: string) {
541 this.simpleSurroundBeforeAfter(chars, chars);
544 simpleBeginningofLine(chars: string) {
545 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
548 simpleSurroundBeforeAfter(
553 const content = this.state.content ?? "";
554 if (!this.state.content) {
555 this.setState({ content: "" });
557 const textarea: any = document.getElementById(this.id);
558 const start: number = textarea.selectionStart;
559 const end: number = textarea.selectionEnd;
562 const selectedText = content?.substring(start, end);
564 content: `${content?.substring(
567 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
571 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
574 this.contentChange();
579 textarea.setSelectionRange(
580 start + beforeChars.length,
581 end + afterChars.length
584 textarea.setSelectionRange(
585 start + beforeChars.length,
586 end + emptyChars.length + afterChars.length
591 autosize.update(textarea);
595 handleInsertBold(i: MarkdownTextArea, event: any) {
596 event.preventDefault();
597 i.simpleSurround("**");
600 handleInsertItalic(i: MarkdownTextArea, event: any) {
601 event.preventDefault();
602 i.simpleSurround("*");
605 handleInsertCode(i: MarkdownTextArea, event: any) {
606 event.preventDefault();
607 if (i.getSelectedText().split(/\r*\n/).length > 1) {
608 i.simpleSurroundBeforeAfter("```\n", "\n```");
610 i.simpleSurround("`");
614 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
615 event.preventDefault();
616 i.simpleSurround("~~");
619 handleInsertList(i: MarkdownTextArea, event: any) {
620 event.preventDefault();
621 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
624 handleInsertQuote(i: MarkdownTextArea, event: any) {
625 event.preventDefault();
626 i.simpleBeginningofLine(">");
629 handleInsertHeader(i: MarkdownTextArea, event: any) {
630 event.preventDefault();
631 i.simpleBeginningofLine("#");
634 handleInsertSubscript(i: MarkdownTextArea, event: any) {
635 event.preventDefault();
636 i.simpleSurround("~");
639 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
640 event.preventDefault();
641 i.simpleSurround("^");
644 simpleInsert(chars: string) {
645 const content = this.state.content;
647 this.setState({ content: `${chars} ` });
650 content: `${content}\n${chars} `,
654 const textarea: any = document.getElementById(this.id);
657 autosize.update(textarea);
659 this.contentChange();
662 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
663 event.preventDefault();
664 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
665 const afterChars = "\n:::\n";
666 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
670 const textarea: any = document.getElementById(this.id);
671 const selectedText = window.getSelection()?.toString();
672 const { content } = this.state;
678 .join("\n") + "\n\n";
680 this.setState({ content: "" });
682 this.setState({ content: `${content}\n` });
685 content: `${content}${quotedText}`,
687 this.contentChange();
688 // Not sure why this needs a delay
689 setTimeout(() => autosize.update(textarea), 10);
693 getSelectedText(): string {
694 const { selectionStart: start, selectionEnd: end } =
695 document.getElementById(this.id) as any;
696 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
701 this.state.loading ||
702 this.props.disabled ||
703 !!this.state.imageUploadStatus