1 import autosize from "autosize";
2 import { Component, linkEvent } from "inferno";
3 import { Prompt } from "inferno-router";
4 import { Language } from "lemmy-js-client";
5 import { i18n } from "../../i18next";
6 import { UserService } from "../../services";
10 markdownFieldCharacterLimit,
21 import { EmojiPicker } from "./emoji-picker";
22 import { Icon, Spinner } from "./icon";
23 import { LanguageSelect } from "./language-select";
25 interface MarkdownTextAreaProps {
26 initialContent?: string;
27 initialLanguageId?: number;
35 showLanguage?: boolean;
36 hideNavigationWarnings?: boolean;
37 onContentChange?(val: string): any;
38 onReplyCancel?(): any;
39 onSubmit?(msg: { val?: string; formId: string; languageId?: number }): any;
40 allLanguages: Language[]; // TODO should probably be nullable
41 siteLanguages: number[]; // TODO same
44 interface MarkdownTextAreaState {
49 imageLoading: boolean;
52 export class MarkdownTextArea extends Component<
53 MarkdownTextAreaProps,
56 private id = `comment-textarea-${randomStr()}`;
57 private formId = `comment-form-${randomStr()}`;
59 state: MarkdownTextAreaState = {
60 content: this.props.initialContent,
61 languageId: this.props.initialLanguageId,
67 constructor(props: any, context: any) {
68 super(props, context);
70 this.handleLanguageChange = this.handleLanguageChange.bind(this);
73 this.tribute = setupTribute();
78 let textarea: any = document.getElementById(this.id);
81 this.tribute.attach(textarea);
82 textarea.addEventListener("tribute-replaced", () => {
83 this.setState({ content: textarea.value });
84 autosize.update(textarea);
89 if (this.props.focus) {
93 // TODO this is slow for some reason
98 componentDidUpdate() {
99 if (!this.props.hideNavigationWarnings && this.state.content) {
100 window.onbeforeunload = () => true;
102 window.onbeforeunload = null;
106 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
107 if (nextProps.finished) {
108 this.setState({ previewMode: false, loading: false, content: undefined });
109 if (this.props.replyType) {
110 this.props.onReplyCancel?.();
113 let textarea: any = document.getElementById(this.id);
114 let form: any = document.getElementById(this.formId);
116 setTimeout(() => autosize.update(textarea), 10);
120 componentWillUnmount() {
121 window.onbeforeunload = null;
125 let languageId = this.state.languageId;
128 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
130 when={!this.props.hideNavigationWarnings && this.state.content}
131 message={i18n.t("block_leaving")}
133 <div className="form-group row">
134 <div className={`col-sm-12`}>
137 className={`form-control ${this.state.previewMode && "d-none"}`}
138 value={this.state.content}
139 onInput={linkEvent(this, this.handleContentChange)}
140 onPaste={linkEvent(this, this.handleImageUploadPaste)}
142 disabled={this.props.disabled}
144 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
145 placeholder={this.props.placeholder}
147 {this.state.previewMode && this.state.content && (
149 className="card border-secondary card-body md-div"
150 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
154 <label className="sr-only" htmlFor={this.id}>
158 <div className="row">
159 <div className="col-sm-12 d-flex flex-wrap">
160 {this.props.buttonTitle && (
163 className="btn btn-sm btn-secondary mr-2"
164 disabled={this.props.disabled || this.state.loading}
166 {this.state.loading ? (
169 <span>{this.props.buttonTitle}</span>
173 {this.props.replyType && (
176 className="btn btn-sm btn-secondary mr-2"
177 onClick={linkEvent(this, this.handleReplyCancel)}
182 {this.state.content && (
184 className={`btn btn-sm btn-secondary mr-2 ${
185 this.state.previewMode && "active"
187 onClick={linkEvent(this, this.handlePreviewToggle)}
192 {/* A flex expander */}
193 <div className="flex-grow-1"></div>
195 {this.props.showLanguage && (
198 allLanguages={this.props.allLanguages}
199 selectedLanguageIds={
200 languageId ? Array.of(languageId) : undefined
202 siteLanguages={this.props.siteLanguages}
204 onChange={this.handleLanguageChange}
208 className="btn btn-sm text-muted"
209 data-tippy-content={i18n.t("bold")}
210 aria-label={i18n.t("bold")}
211 onClick={linkEvent(this, this.handleInsertBold)}
213 <Icon icon="bold" classes="icon-inline" />
216 className="btn btn-sm text-muted"
217 data-tippy-content={i18n.t("italic")}
218 aria-label={i18n.t("italic")}
219 onClick={linkEvent(this, this.handleInsertItalic)}
221 <Icon icon="italic" classes="icon-inline" />
224 className="btn btn-sm text-muted"
225 data-tippy-content={i18n.t("link")}
226 aria-label={i18n.t("link")}
227 onClick={linkEvent(this, this.handleInsertLink)}
229 <Icon icon="link" classes="icon-inline" />
232 onEmojiClick={e => this.handleEmoji(this, e)}
234 <form className="btn btn-sm text-muted font-weight-bold">
236 htmlFor={`file-upload-${this.id}`}
238 UserService.Instance.myUserInfo && "pointer"
240 data-tippy-content={i18n.t("upload_image")}
242 {this.state.imageLoading ? (
245 <Icon icon="image" classes="icon-inline" />
249 id={`file-upload-${this.id}`}
251 accept="image/*,video/*"
254 disabled={!UserService.Instance.myUserInfo}
255 onChange={linkEvent(this, this.handleImageUpload)}
259 className="btn btn-sm text-muted"
260 data-tippy-content={i18n.t("header")}
261 aria-label={i18n.t("header")}
262 onClick={linkEvent(this, this.handleInsertHeader)}
264 <Icon icon="header" classes="icon-inline" />
267 className="btn btn-sm text-muted"
268 data-tippy-content={i18n.t("strikethrough")}
269 aria-label={i18n.t("strikethrough")}
270 onClick={linkEvent(this, this.handleInsertStrikethrough)}
272 <Icon icon="strikethrough" classes="icon-inline" />
275 className="btn btn-sm text-muted"
276 data-tippy-content={i18n.t("quote")}
277 aria-label={i18n.t("quote")}
278 onClick={linkEvent(this, this.handleInsertQuote)}
280 <Icon icon="format_quote" classes="icon-inline" />
283 className="btn btn-sm text-muted"
284 data-tippy-content={i18n.t("list")}
285 aria-label={i18n.t("list")}
286 onClick={linkEvent(this, this.handleInsertList)}
288 <Icon icon="list" classes="icon-inline" />
291 className="btn btn-sm text-muted"
292 data-tippy-content={i18n.t("code")}
293 aria-label={i18n.t("code")}
294 onClick={linkEvent(this, this.handleInsertCode)}
296 <Icon icon="code" classes="icon-inline" />
299 className="btn btn-sm text-muted"
300 data-tippy-content={i18n.t("subscript")}
301 aria-label={i18n.t("subscript")}
302 onClick={linkEvent(this, this.handleInsertSubscript)}
304 <Icon icon="subscript" classes="icon-inline" />
307 className="btn btn-sm text-muted"
308 data-tippy-content={i18n.t("superscript")}
309 aria-label={i18n.t("superscript")}
310 onClick={linkEvent(this, this.handleInsertSuperscript)}
312 <Icon icon="superscript" classes="icon-inline" />
315 className="btn btn-sm text-muted"
316 data-tippy-content={i18n.t("spoiler")}
317 aria-label={i18n.t("spoiler")}
318 onClick={linkEvent(this, this.handleInsertSpoiler)}
320 <Icon icon="alert-triangle" classes="icon-inline" />
323 href={markdownHelpUrl}
324 className="btn btn-sm text-muted font-weight-bold"
325 title={i18n.t("formatting_help")}
328 <Icon icon="help-circle" classes="icon-inline" />
336 handleEmoji(i: MarkdownTextArea, e: any) {
337 let value = e.native;
339 let emoji = customEmojisLookup.get(e.id)?.custom_emoji;
341 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
345 content: `${i.state.content ?? ""} ${value} `,
348 let textarea: any = document.getElementById(i.id);
349 autosize.update(textarea);
352 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
353 let image = event.clipboardData.files[0];
355 i.handleImageUpload(i, image);
359 handleImageUpload(i: MarkdownTextArea, event: any) {
362 event.preventDefault();
363 file = event.target.files[0];
368 i.setState({ imageLoading: true });
372 console.log("pictrs upload:");
374 if (res.msg === "ok") {
375 const imageMarkdown = `![](${res.url})`;
376 const content = i.state.content;
378 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
382 const textarea: any = document.getElementById(i.id);
383 autosize.update(textarea);
385 `${i18n.t("click_to_delete_picture")}: ${file.name}`,
386 `${i18n.t("picture_deleted")}: ${file.name}`,
387 `${i18n.t("failed_to_delete_picture")}: ${file.name}`,
388 res.delete_url as string
391 i.setState({ imageLoading: false });
392 toast(JSON.stringify(res), "danger");
396 i.setState({ imageLoading: false });
397 console.error(error);
398 toast(error, "danger");
403 // Coerces the undefineds to empty strings, for replacing in the DB
404 let content = this.state.content ?? "";
405 this.props.onContentChange?.(content);
408 handleContentChange(i: MarkdownTextArea, event: any) {
409 i.setState({ content: event.target.value });
413 handlePreviewToggle(i: MarkdownTextArea, event: any) {
414 event.preventDefault();
415 i.setState({ previewMode: !i.state.previewMode });
418 handleLanguageChange(val: number[]) {
419 this.setState({ languageId: val[0] });
422 handleSubmit(i: MarkdownTextArea, event: any) {
423 event.preventDefault();
424 i.setState({ loading: true });
426 val: i.state.content,
428 languageId: i.state.languageId,
430 i.props.onSubmit?.(msg);
433 handleReplyCancel(i: MarkdownTextArea) {
434 i.props.onReplyCancel?.();
437 handleInsertLink(i: MarkdownTextArea, event: any) {
438 event.preventDefault();
440 const textarea: any = document.getElementById(i.id);
441 const start: number = textarea.selectionStart;
442 const end: number = textarea.selectionEnd;
444 const content = i.state.content ?? "";
446 if (!i.state.content) {
447 i.setState({ content: "" });
451 const selectedText = content?.substring(start, end);
453 content: `${content?.substring(
456 )}[${selectedText}]()${content?.substring(end)}`,
459 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
461 i.setState({ content: `${content} []()` });
463 setTimeout(() => (textarea.selectionEnd -= 1), 10);
468 simpleSurround(chars: string) {
469 this.simpleSurroundBeforeAfter(chars, chars);
472 simpleBeginningofLine(chars: string) {
473 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
476 simpleSurroundBeforeAfter(
481 const content = this.state.content ?? "";
482 if (!this.state.content) {
483 this.setState({ content: "" });
485 const textarea: any = document.getElementById(this.id);
486 const start: number = textarea.selectionStart;
487 const end: number = textarea.selectionEnd;
490 const selectedText = content?.substring(start, end);
492 content: `${content?.substring(
495 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
499 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
502 this.contentChange();
507 textarea.setSelectionRange(
508 start + beforeChars.length,
509 end + afterChars.length
512 textarea.setSelectionRange(
513 start + beforeChars.length,
514 end + emptyChars.length + afterChars.length
519 autosize.update(textarea);
523 handleInsertBold(i: MarkdownTextArea, event: any) {
524 event.preventDefault();
525 i.simpleSurround("**");
528 handleInsertItalic(i: MarkdownTextArea, event: any) {
529 event.preventDefault();
530 i.simpleSurround("*");
533 handleInsertCode(i: MarkdownTextArea, event: any) {
534 event.preventDefault();
535 if (i.getSelectedText().split(/\r*\n/).length > 1) {
536 i.simpleSurroundBeforeAfter("```\n", "\n```");
538 i.simpleSurround("`");
542 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
543 event.preventDefault();
544 i.simpleSurround("~~");
547 handleInsertList(i: MarkdownTextArea, event: any) {
548 event.preventDefault();
549 i.simpleBeginningofLine("-");
552 handleInsertQuote(i: MarkdownTextArea, event: any) {
553 event.preventDefault();
554 i.simpleBeginningofLine(">");
557 handleInsertHeader(i: MarkdownTextArea, event: any) {
558 event.preventDefault();
559 i.simpleBeginningofLine("#");
562 handleInsertSubscript(i: MarkdownTextArea, event: any) {
563 event.preventDefault();
564 i.simpleSurround("~");
567 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
568 event.preventDefault();
569 i.simpleSurround("^");
572 simpleInsert(chars: string) {
573 let content = this.state.content;
575 this.setState({ content: `${chars} ` });
578 content: `${content}\n${chars} `,
582 let textarea: any = document.getElementById(this.id);
585 autosize.update(textarea);
587 this.contentChange();
590 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
591 event.preventDefault();
592 let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
593 let afterChars = "\n:::\n";
594 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
598 let textarea: any = document.getElementById(this.id);
599 let selectedText = window.getSelection()?.toString();
600 let content = this.state.content;
606 .join("\n") + "\n\n";
608 this.setState({ content: "" });
610 this.setState({ content: `${content}\n` });
613 content: `${content}${quotedText}`,
615 this.contentChange();
616 // Not sure why this needs a delay
617 setTimeout(() => autosize.update(textarea), 10);
621 getSelectedText(): string {
622 let textarea: any = document.getElementById(this.id);
623 let start: number = textarea.selectionStart;
624 let end: number = textarea.selectionEnd;
625 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";