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.props.buttonTitle && (
190 className="btn btn-sm btn-secondary mr-2"
191 disabled={this.isDisabled}
193 {this.state.loading ? (
196 <span>{this.props.buttonTitle}</span>
200 {this.props.replyType && (
203 className="btn btn-sm btn-secondary mr-2"
204 onClick={linkEvent(this, this.handleReplyCancel)}
209 {this.state.content && (
211 className={`btn btn-sm btn-secondary mr-2 ${
212 this.state.previewMode && "active"
214 onClick={linkEvent(this, this.handlePreviewToggle)}
216 {this.state.previewMode ? i18n.t("edit") : i18n.t("preview")}
219 {/* A flex expander */}
220 <div className="flex-grow-1"></div>
222 {this.props.showLanguage && (
225 allLanguages={this.props.allLanguages}
226 selectedLanguageIds={
227 languageId ? Array.of(languageId) : undefined
229 siteLanguages={this.props.siteLanguages}
230 onChange={this.handleLanguageChange}
231 disabled={this.isDisabled}
234 {this.getFormatButton("bold", this.handleInsertBold)}
235 {this.getFormatButton("italic", this.handleInsertItalic)}
236 {this.getFormatButton("link", this.handleInsertLink)}
238 onEmojiClick={e => this.handleEmoji(this, e)}
239 disabled={this.isDisabled}
241 <form className="btn btn-sm text-muted font-weight-bold">
243 htmlFor={`file-upload-${this.id}`}
245 UserService.Instance.myUserInfo && "pointer"
247 data-tippy-content={i18n.t("upload_image")}
249 {this.state.imageUploadStatus ? (
252 <Icon icon="image" classes="icon-inline" />
256 id={`file-upload-${this.id}`}
258 accept="image/*,video/*"
262 disabled={!UserService.Instance.myUserInfo || this.isDisabled}
263 onChange={linkEvent(this, this.handleImageUpload)}
266 {this.getFormatButton("header", this.handleInsertHeader)}
267 {this.getFormatButton(
269 this.handleInsertStrikethrough
271 {this.getFormatButton("quote", this.handleInsertQuote)}
272 {this.getFormatButton("list", this.handleInsertList)}
273 {this.getFormatButton("code", this.handleInsertCode)}
274 {this.getFormatButton("subscript", this.handleInsertSubscript)}
275 {this.getFormatButton("superscript", this.handleInsertSuperscript)}
276 {this.getFormatButton("spoiler", this.handleInsertSpoiler)}
278 href={markdownHelpUrl}
279 className="btn btn-sm text-muted font-weight-bold"
280 title={i18n.t("formatting_help")}
283 <Icon icon="help-circle" classes="icon-inline" />
292 type: NoOptionI18nKeys,
293 handleClick: (i: MarkdownTextArea, event: any) => void
295 let iconType: string;
299 iconType = "alert-triangle";
303 iconType = "format_quote";
313 className="btn btn-sm text-muted"
314 data-tippy-content={i18n.t(type)}
315 aria-label={i18n.t(type)}
316 onClick={linkEvent(this, handleClick)}
317 disabled={this.isDisabled}
319 <Icon icon={iconType} classes="icon-inline" />
324 handleEmoji(i: MarkdownTextArea, e: any) {
325 let value = e.native;
327 const emoji = customEmojisLookup.get(e.id)?.custom_emoji;
329 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
333 content: `${i.state.content ?? ""} ${value} `,
336 const textarea: any = document.getElementById(i.id);
337 autosize.update(textarea);
340 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
341 const image = event.clipboardData.files[0];
343 i.handleImageUpload(i, image);
347 handleImageUpload(i: MarkdownTextArea, event: any) {
348 const files: File[] = [];
350 event.preventDefault();
351 files.push(...event.target.files);
356 if (files.length > maxUploadImages) {
358 i18n.t("too_many_images_upload", {
359 count: Number(maxUploadImages),
360 formattedCount: numToSI(maxUploadImages),
366 imageUploadStatus: { total: files.length, uploaded: 0 },
369 i.uploadImages(i, files).then(() => {
370 i.setState({ imageUploadStatus: undefined });
375 async uploadImages(i: MarkdownTextArea, files: File[]) {
376 let errorOccurred = false;
377 const filesCopy = [...files];
378 while (filesCopy.length > 0 && !errorOccurred) {
381 filesCopy.splice(0, concurrentImageUpload).map(async file => {
382 await i.uploadSingleImage(i, file);
384 this.setState(({ imageUploadStatus }) => ({
386 ...(imageUploadStatus as Required<ImageUploadStatus>),
387 uploaded: (imageUploadStatus?.uploaded ?? 0) + 1,
393 errorOccurred = true;
398 async uploadSingleImage(i: MarkdownTextArea, image: File) {
399 const res = await HttpService.client.uploadImage({ image });
400 console.log("pictrs upload:");
402 if (res.state === "success") {
403 if (res.data.msg === "ok") {
404 const imageMarkdown = `![](${res.data.url})`;
405 i.setState(({ content }) => ({
406 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
409 const textarea: any = document.getElementById(i.id);
410 autosize.update(textarea);
411 pictrsDeleteToast(image.name, res.data.delete_url as string);
413 throw JSON.stringify(res.data);
415 } else if (res.state === "failed") {
416 i.setState({ imageUploadStatus: undefined });
417 console.error(res.msg);
418 toast(res.msg, "danger");
425 // Coerces the undefineds to empty strings, for replacing in the DB
426 const content = this.state.content ?? "";
427 this.props.onContentChange?.(content);
430 handleContentChange(i: MarkdownTextArea, event: any) {
431 i.setState({ content: event.target.value });
436 // Keybinds inspired by github comment area
437 handleKeyBinds(i: MarkdownTextArea, event: KeyboardEvent) {
441 i.handleInsertLink(i, event);
445 if (!this.isDisabled) {
446 i.handleSubmit(i, event);
452 i.handleInsertBold(i, event);
456 i.handleInsertItalic(i, event);
460 i.handleInsertCode(i, event);
464 i.handleInsertList(i, event);
468 i.handleInsertSpoiler(i, event);
472 if (i.state.content) i.handlePreviewToggle(i, event);
476 i.handleInsertQuote(i, event);
483 handlePreviewToggle(i: MarkdownTextArea, event: any) {
484 event.preventDefault();
485 i.setState({ previewMode: !i.state.previewMode });
488 handleLanguageChange(val: number[]) {
489 this.setState({ languageId: val[0] });
492 handleSubmit(i: MarkdownTextArea, event: any) {
493 event.preventDefault();
494 if (i.state.content) {
495 i.setState({ loading: true, submitted: true });
496 i.props.onSubmit?.(i.state.content, i.formId, i.state.languageId);
500 handleReplyCancel(i: MarkdownTextArea) {
501 i.props.onReplyCancel?.();
504 handleInsertLink(i: MarkdownTextArea, event: any) {
505 event.preventDefault();
507 const textarea: any = document.getElementById(i.id);
508 const start: number = textarea.selectionStart;
509 const end: number = textarea.selectionEnd;
511 const content = i.state.content ?? "";
513 if (!i.state.content) {
514 i.setState({ content: "" });
518 const selectedText = content?.substring(start, end);
520 content: `${content?.substring(
523 )}[${selectedText}]()${content?.substring(end)}`,
526 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
528 i.setState({ content: `${content} []()` });
530 setTimeout(() => (textarea.selectionEnd -= 1), 10);
535 simpleSurround(chars: string) {
536 this.simpleSurroundBeforeAfter(chars, chars);
539 simpleBeginningofLine(chars: string) {
540 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
543 simpleSurroundBeforeAfter(
548 const content = this.state.content ?? "";
549 if (!this.state.content) {
550 this.setState({ content: "" });
552 const textarea: any = document.getElementById(this.id);
553 const start: number = textarea.selectionStart;
554 const end: number = textarea.selectionEnd;
557 const selectedText = content?.substring(start, end);
559 content: `${content?.substring(
562 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
566 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
569 this.contentChange();
574 textarea.setSelectionRange(
575 start + beforeChars.length,
576 end + afterChars.length
579 textarea.setSelectionRange(
580 start + beforeChars.length,
581 end + emptyChars.length + afterChars.length
586 autosize.update(textarea);
590 handleInsertBold(i: MarkdownTextArea, event: any) {
591 event.preventDefault();
592 i.simpleSurround("**");
595 handleInsertItalic(i: MarkdownTextArea, event: any) {
596 event.preventDefault();
597 i.simpleSurround("*");
600 handleInsertCode(i: MarkdownTextArea, event: any) {
601 event.preventDefault();
602 if (i.getSelectedText().split(/\r*\n/).length > 1) {
603 i.simpleSurroundBeforeAfter("```\n", "\n```");
605 i.simpleSurround("`");
609 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
610 event.preventDefault();
611 i.simpleSurround("~~");
614 handleInsertList(i: MarkdownTextArea, event: any) {
615 event.preventDefault();
616 i.simpleBeginningofLine(`-${i.getSelectedText() ? " " : ""}`);
619 handleInsertQuote(i: MarkdownTextArea, event: any) {
620 event.preventDefault();
621 i.simpleBeginningofLine(">");
624 handleInsertHeader(i: MarkdownTextArea, event: any) {
625 event.preventDefault();
626 i.simpleBeginningofLine("#");
629 handleInsertSubscript(i: MarkdownTextArea, event: any) {
630 event.preventDefault();
631 i.simpleSurround("~");
634 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
635 event.preventDefault();
636 i.simpleSurround("^");
639 simpleInsert(chars: string) {
640 const content = this.state.content;
642 this.setState({ content: `${chars} ` });
645 content: `${content}\n${chars} `,
649 const textarea: any = document.getElementById(this.id);
652 autosize.update(textarea);
654 this.contentChange();
657 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
658 event.preventDefault();
659 const beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
660 const afterChars = "\n:::\n";
661 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
665 const textarea: any = document.getElementById(this.id);
666 const selectedText = window.getSelection()?.toString();
667 const { content } = this.state;
673 .join("\n") + "\n\n";
675 this.setState({ content: "" });
677 this.setState({ content: `${content}\n` });
680 content: `${content}${quotedText}`,
682 this.contentChange();
683 // Not sure why this needs a delay
684 setTimeout(() => autosize.update(textarea), 10);
688 getSelectedText(): string {
689 const { selectionStart: start, selectionEnd: end } =
690 document.getElementById(this.id) as any;
691 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";
696 this.state.loading ||
697 this.props.disabled ||
698 !!this.state.imageUploadStatus