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 d-flex flex-wrap">
147 {this.getFormatButton("bold", this.handleInsertBold)}
148 {this.getFormatButton("italic", this.handleInsertItalic)}
149 {this.getFormatButton("link", this.handleInsertLink)}
151 onEmojiClick={e => this.handleEmoji(this, e)}
152 disabled={this.isDisabled}
154 <form className="btn btn-sm text-muted font-weight-bold">
156 htmlFor={`file-upload-${this.id}`}
158 UserService.Instance.myUserInfo && "pointer"
160 data-tippy-content={i18n.t("upload_image")}
162 {this.state.imageUploadStatus ? (
165 <Icon icon="image" classes="icon-inline" />
169 id={`file-upload-${this.id}`}
171 accept="image/*,video/*"
175 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
176 onChange={linkEvent(this, this.handleImageUpload)}
179 {this.getFormatButton("header", this.handleInsertHeader)}
180 {this.getFormatButton(
182 this.handleInsertStrikethrough
184 {this.getFormatButton("quote", this.handleInsertQuote)}
185 {this.getFormatButton("list", this.handleInsertList)}
186 {this.getFormatButton("code", this.handleInsertCode)}
187 {this.getFormatButton("subscript", this.handleInsertSubscript)}
188 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
189 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
191 href={markdownHelpUrl}
192 className="btn btn-sm text-muted font-weight-bold"
193 title={i18n.t("formatting_help")}
196 <Icon icon="help-circle" classes="icon-inline" />
200 <div className="col-sm-12 mt-2">
203 className={`form-control ${this.state.previewMode && "d-none"}`}
204 value={this.state.content}
205 onInput={linkEvent(this, this.handleContentChange)}
206 onPaste={linkEvent(this, this.handleImageUploadPaste)}
207 onKeyDown={linkEvent(this, this.handleKeyBinds)}
209 disabled={this.isDisabled}
211 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
212 placeholder={this.props.placeholder}
214 {this.state.previewMode && this.state.content && (
216 className="card border-secondary card-body md-div"
217 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
220 {this.state.imageUploadStatus &&
221 this.state.imageUploadStatus.total > 1 && (
226 value={this.state.imageUploadStatus.uploaded}
227 max={this.state.imageUploadStatus.total}
228 text={i18n.t("pictures_uploded_progess", {
229 uploaded: this.state.imageUploadStatus.uploaded,
230 total: this.state.imageUploadStatus.total,
235 <label className="sr-only" htmlFor={this.id}>
239 <div className="col-sm-12 d-flex align-items-center flex-wrap mt-2">
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 ml-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 ml-2"
273 onClick={linkEvent(this, this.handleReplyCancel)}
278 {this.state.content && (
280 className={`btn btn-sm btn-secondary ml-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