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 = `comment-textarea-${randomStr()}`;
67 private formId = `comment-form-${randomStr()}`;
70 state: MarkdownTextAreaState = {
71 content: this.props.initialContent,
72 languageId: this.props.initialLanguageId,
78 constructor(props: any, context: any) {
79 super(props, context);
81 this.handleLanguageChange = this.handleLanguageChange.bind(this);
84 this.tribute = setupTribute();
89 const textarea: any = document.getElementById(this.id);
92 this.tribute.attach(textarea);
93 textarea.addEventListener("tribute-replaced", () => {
94 this.setState({ content: textarea.value });
95 autosize.update(textarea);
100 if (this.props.focus) {
104 // TODO this is slow for some reason
109 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
110 if (nextProps.finished) {
113 imageUploadStatus: undefined,
117 if (this.props.replyType) {
118 this.props.onReplyCancel?.();
121 const textarea: any = document.getElementById(this.id);
122 const form: any = document.getElementById(this.formId);
124 setTimeout(() => autosize.update(textarea), 10);
129 const languageId = this.state.languageId;
131 // TODO add these prompts back in at some point
133 // when={!this.props.hideNavigationWarnings && this.state.content}
134 // message={i18n.t("block_leaving")}
137 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
140 !this.props.hideNavigationWarnings &&
141 !!this.state.content &&
142 !this.state.submitted
145 <div className="form-group row">
146 <div className={`col-sm-12`}>
149 className={`form-control ${this.state.previewMode && "d-none"}`}
150 value={this.state.content}
151 onInput={linkEvent(this, this.handleContentChange)}
152 onPaste={linkEvent(this, this.handleImageUploadPaste)}
153 onKeyDown={linkEvent(this, this.handleKeyBinds)}
155 disabled={this.isDisabled}
157 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
158 placeholder={this.props.placeholder}
160 {this.state.previewMode && this.state.content && (
162 className="card border-secondary card-body md-div"
163 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
166 {this.state.imageUploadStatus &&
167 this.state.imageUploadStatus.total > 1 && (
172 value={this.state.imageUploadStatus.uploaded}
173 max={this.state.imageUploadStatus.total}
174 text={i18n.t("pictures_uploded_progess", {
175 uploaded: this.state.imageUploadStatus.uploaded,
176 total: this.state.imageUploadStatus.total,
181 <label className="sr-only" htmlFor={this.id}>
185 <div className="row">
186 <div className="col-sm-12 d-flex flex-wrap">
187 {this.getFormatButton("bold", this.handleInsertBold)}
188 {this.getFormatButton("italic", this.handleInsertItalic)}
189 {this.getFormatButton("link", this.handleInsertLink)}
191 onEmojiClick={e => this.handleEmoji(this, e)}
192 disabled={this.isDisabled}
194 <form className="btn btn-sm text-muted font-weight-bold">
196 htmlFor={`file-upload-${this.id}`}
198 UserService.Instance.myUserInfo && "pointer"
200 data-tippy-content={i18n.t("upload_image")}
202 {this.state.imageUploadStatus ? (
205 <Icon icon="image" classes="icon-inline" />
209 id={`file-upload-${this.id}`}
211 accept="image/*,video/*"
215 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
216 onChange={linkEvent(this, this.handleImageUpload)}
219 {this.getFormatButton("header", this.handleInsertHeader)}
220 {this.getFormatButton(
222 this.handleInsertStrikethrough
224 {this.getFormatButton("quote", this.handleInsertQuote)}
225 {this.getFormatButton("list", this.handleInsertList)}
226 {this.getFormatButton("code", this.handleInsertCode)}
227 {this.getFormatButton("subscript", this.handleInsertSubscript)}
228 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
229 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
231 href={markdownHelpUrl}
232 className="btn btn-sm text-muted font-weight-bold"
233 title={i18n.t("formatting_help")}
236 <Icon icon="help-circle" classes="icon-inline" />
240 <div className="col-sm-12 d-flex align-items-center flex-wrap">
241 {this.props.showLanguage && (
244 allLanguages={this.props.allLanguages}
245 selectedLanguageIds={
246 languageId ? Array.of(languageId) : undefined
248 siteLanguages={this.props.siteLanguages}
249 onChange={this.handleLanguageChange}
250 disabled={this.isDisabled}
254 {/* A flex expander */}
255 <div className="flex-grow-1"></div>
257 {this.props.buttonTitle && (
260 className="btn btn-sm btn-secondary mr-2"
261 disabled={this.isDisabled}
263 {this.state.loading ? (
266 <span>{this.props.buttonTitle}</span>
270 {this.props.replyType && (
273 className="btn btn-sm btn-secondary mr-2"
274 onClick={linkEvent(this, this.handleReplyCancel)}
279 {this.state.content && (
281 className={`btn btn-sm btn-secondary mr-2 ${
282 this.state.previewMode && "active"
284 onClick={linkEvent(this, this.handlePreviewToggle)}
286 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
296 type: NoOptionI18nKeys,
297 handleClick: (i: MarkdownTextArea, event: any) => void
299 let iconType: string;
303 iconType = "alert-triangle";
307 iconType = "format_quote";
317 className="btn btn-sm text-muted"
318 data-tippy-content={i18n.t(type)}
319 aria-label={i18n.t(type)}
320 onClick={linkEvent(this, handleClick)}
321 disabled={this.isDisabled}
323 <Icon icon={iconType} classes="icon-inline" />
328 handleEmoji(i: MarkdownTextArea, e: any) {
329 let value = e.native;
331 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
333 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
337 content: `${i.state.content ?? ""} ${value} `,
340 const textarea: any = document.getElementById(i.id);
341 autosize.update(textarea);
344 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
345 const image = event.clipboardData.files[0];
347 i.handleImageUpload(i, image);
351 handleImageUpload(i: MarkdownTextArea, event: any) {
352 const files: File[] = [];
354 event.preventDefault();
355 files.push(...event.target.files);
360 if (files.length > maxUploadImages) {
362 i18n.t("too_many_images_upload", {
363 count: Number(maxUploadImages),
364 formattedCount: numToSI(maxUploadImages),
370 imageUploadStatus: { total: files.length, uploaded: 0 },
373 i.uploadImages(i, files).then(() => {
374 i.setState({ imageUploadStatus: undefined });
379 async uploadImages(i: MarkdownTextArea, files: File[]) {
380 let errorOccurred = false;
381 const filesCopy = [...files];
382 while (filesCopy.length > 0 && !errorOccurred) {
385 filesCopy.splice(0, concurrentImageUpload).map(async file => {
386 await i.uploadSingleImage(i, file);
388 this.setState(({ imageUploadStatus }) => ({
390 ...(imageUploadStatus as Required<ImageUploadStatus>),
391 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
397 errorOccurred = true;
402 async uploadSingleImage(i: MarkdownTextArea, image: File) {
403 const res = await HttpService.client.uploadImage({ image });
404 console.log("pictrs upload:");
406 if (res.state === "success") {
407 if (res.data.msg === "ok") {
408 const imageMarkdown = `![](${res.data.url})`;
409 i.setState(({ content }) => ({
410 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
413 const textarea: any = document.getElementById(i.id);
414 autosize.update(textarea);
415 pictrsDeleteToast(image.name, res.data.delete_url as string);
417 throw JSON.stringify(res.data);
419 } else if (res.state === "failed") {
420 i.setState({ imageUploadStatus: undefined });
421 console.error(res.msg);
422 toast(res.msg, "danger");
429 // Coerces the undefineds to empty strings, for replacing in the DB
430 const content = this.state.content ?? "";
431 this.props.onContentChange?.(content);
434 handleContentChange(i: MarkdownTextArea, event: any) {
435 i.setState({ content: event.target.value });
440 // Keybinds inspired by github comment area
441 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
445 i.handleInsertLink(i, event);
449 if (!this.isDisabled) {
450 i.handleSubmit(i, event);
456 i.handleInsertBold(i, event);
460 i.handleInsertItalic(i, event);
464 i.handleInsertCode(i, event);
468 i.handleInsertList(i, event);
472 i.handleInsertSpoiler(i, event);
476 if (i.state.content) i.handlePreviewToggle(i, event);
480 i.handleInsertQuote(i, event);
487 handlePreviewToggle(i: MarkdownTextArea, event: any) {
488 event.preventDefault();
489 i.setState({ previewMode: !i.state.previewMode });
492 handleLanguageChange(val: number[]) {
493 this.setState({ languageId: val[0] });
496 handleSubmit(i: MarkdownTextArea, event: any) {
497 event.preventDefault();
498 if (i.state.content) {
499 i.setState({ loading: true, submitted: true });
500 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
504 handleReplyCancel(i: MarkdownTextArea) {
505 i.props.onReplyCancel?.();
508 handleInsertLink(i: MarkdownTextArea, event: any) {
509 event.preventDefault();
511 const textarea: any = document.getElementById(i.id);
512 const start: number = textarea.selectionStart;
513 const end: number = textarea.selectionEnd;
515 const content = i.state.content ?? "";
517 if (!i.state.content) {
518 i.setState({ content: "" });
522 const selectedText = content?.substring(start, end);
524 content: `${content?.substring(
527 )}[${selectedText}]()${content?.substring(end)}`,
530 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
532 i.setState({ content: `${content} []()` });
534 setTimeout(() => (textarea.selectionEnd -= 1), 10);
539 simpleSurround(chars: string) {
540 this.simpleSurroundBeforeAfter(chars, chars);
543 simpleBeginningofLine(chars: string) {
544 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
547 simpleSurroundBeforeAfter(
552 const content = this.state.content ?? "";
553 if (!this.state.content) {
554 this.setState({ content: "" });
556 const textarea: any = document.getElementById(this.id);
557 const start: number = textarea.selectionStart;
558 const end: number = textarea.selectionEnd;
561 const selectedText = content?.substring(start, end);
563 content: `${content?.substring(
566 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
570 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
573 this.contentChange();
578 textarea.setSelectionRange(
579 start + beforeChars.length,
580 end + afterChars.length
583 textarea.setSelectionRange(
584 start + beforeChars.length,
585 end + emptyChars.length + afterChars.length
590 autosize.update(textarea);
594 handleInsertBold(i: MarkdownTextArea, event: any) {
595 event.preventDefault();
596 i.simpleSurround("**");
599 handleInsertItalic(i: MarkdownTextArea, event: any) {
600 event.preventDefault();
601 i.simpleSurround("*");
604 handleInsertCode(i: MarkdownTextArea, event: any) {
605 event.preventDefault();
606 if (i.getSelectedText().split(/\r*\n/).length > 1) {
607 i.simpleSurroundBeforeAfter("```\n", "\n```");
609 i.simpleSurround("`");
613 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
614 event.preventDefault();
615 i.simpleSurround("~~");
618 handleInsertList(i: MarkdownTextArea, event: any) {
619 event.preventDefault();
620 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
623 handleInsertQuote(i: MarkdownTextArea, event: any) {
624 event.preventDefault();
625 i.simpleBeginningofLine(">");
628 handleInsertHeader(i: MarkdownTextArea, event: any) {
629 event.preventDefault();
630 i.simpleBeginningofLine("#");
633 handleInsertSubscript(i: MarkdownTextArea, event: any) {
634 event.preventDefault();
635 i.simpleSurround("~");
638 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
639 event.preventDefault();
640 i.simpleSurround("^");
643 simpleInsert(chars: string) {
644 const content = this.state.content;
646 this.setState({ content: `${chars} ` });
649 content: `${content}\n${chars} `,
653 const textarea: any = document.getElementById(this.id);
656 autosize.update(textarea);
658 this.contentChange();
661 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
662 event.preventDefault();
663 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
664 const afterChars = "\n:::\n";
665 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
669 const textarea: any = document.getElementById(this.id);
670 const selectedText = window.getSelection()?.toString();
671 const { content } = this.state;
677 .join("\n") + "\n\n";
679 this.setState({ content: "" });
681 this.setState({ content: `${content}\n` });
684 content: `${content}${quotedText}`,
686 this.contentChange();
687 // Not sure why this needs a delay
688 setTimeout(() => autosize.update(textarea), 10);
692 getSelectedText(): string {
693 const { selectionStart: start, selectionEnd: end } =
694 document.getElementById(this.id) as any;
695 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
700 this.state.loading ||
701 this.props.disabled ||
702 !!this.state.imageUploadStatus