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";
9 markdownFieldCharacterLimit,
20 import { Icon, Spinner } from "./icon";
21 import { LanguageSelect } from "./language-select";
23 interface MarkdownTextAreaProps {
24 initialContent?: string;
25 initialLanguageId?: number;
33 showLanguage?: boolean;
34 hideNavigationWarnings?: boolean;
35 onContentChange?(val: string): any;
36 onReplyCancel?(): any;
37 onSubmit?(msg: { val?: string; formId: string; languageId?: number }): any;
38 allLanguages: Language[]; // TODO should probably be nullable
39 siteLanguages: number[]; // TODO same
42 interface MarkdownTextAreaState {
47 imageLoading: boolean;
50 export class MarkdownTextArea extends Component<
51 MarkdownTextAreaProps,
54 private id = `comment-textarea-${randomStr()}`;
55 private formId = `comment-form-${randomStr()}`;
57 state: MarkdownTextAreaState = {
58 content: this.props.initialContent,
59 languageId: this.props.initialLanguageId,
65 constructor(props: any, context: any) {
66 super(props, context);
68 this.handleLanguageChange = this.handleLanguageChange.bind(this);
71 this.tribute = setupTribute();
76 let textarea: any = document.getElementById(this.id);
79 this.tribute.attach(textarea);
80 textarea.addEventListener("tribute-replaced", () => {
81 this.setState({ content: textarea.value });
82 autosize.update(textarea);
87 if (this.props.focus) {
91 // TODO this is slow for some reason
96 componentDidUpdate() {
97 if (!this.props.hideNavigationWarnings && this.state.content) {
98 window.onbeforeunload = () => true;
100 window.onbeforeunload = null;
104 componentWillReceiveProps(nextProps: MarkdownTextAreaProps) {
105 if (nextProps.finished) {
106 this.setState({ previewMode: false, loading: false, content: undefined });
107 if (this.props.replyType) {
108 this.props.onReplyCancel?.();
111 let textarea: any = document.getElementById(this.id);
112 let form: any = document.getElementById(this.formId);
114 setTimeout(() => autosize.update(textarea), 10);
118 componentWillUnmount() {
119 window.onbeforeunload = null;
123 let languageId = this.state.languageId;
126 <form id={this.formId} onSubmit={linkEvent(this, this.handleSubmit)}>
128 when={!this.props.hideNavigationWarnings && this.state.content}
129 message={i18n.t("block_leaving")}
131 <div className="form-group row">
132 <div className={`col-sm-12`}>
135 className={`form-control ${this.state.previewMode && "d-none"}`}
136 value={this.state.content}
137 onInput={linkEvent(this, this.handleContentChange)}
138 onPaste={linkEvent(this, this.handleImageUploadPaste)}
140 disabled={this.props.disabled}
142 maxLength={this.props.maxLength ?? markdownFieldCharacterLimit}
143 placeholder={this.props.placeholder}
145 {this.state.previewMode && this.state.content && (
147 className="card border-secondary card-body md-div"
148 dangerouslySetInnerHTML={mdToHtml(this.state.content)}
152 <label className="sr-only" htmlFor={this.id}>
156 <div className="row">
157 <div className="col-sm-12 d-flex flex-wrap">
158 {this.props.buttonTitle && (
161 className="btn btn-sm btn-secondary mr-2"
162 disabled={this.props.disabled || this.state.loading}
164 {this.state.loading ? (
167 <span>{this.props.buttonTitle}</span>
171 {this.props.replyType && (
174 className="btn btn-sm btn-secondary mr-2"
175 onClick={linkEvent(this, this.handleReplyCancel)}
180 {this.state.content && (
182 className={`btn btn-sm btn-secondary mr-2 ${
183 this.state.previewMode && "active"
185 onClick={linkEvent(this, this.handlePreviewToggle)}
190 {/* A flex expander */}
191 <div className="flex-grow-1"></div>
193 {this.props.showLanguage && (
196 allLanguages={this.props.allLanguages}
197 selectedLanguageIds={
198 languageId ? Array.of(languageId) : undefined
200 siteLanguages={this.props.siteLanguages}
202 onChange={this.handleLanguageChange}
206 className="btn btn-sm text-muted"
207 data-tippy-content={i18n.t("bold")}
208 aria-label={i18n.t("bold")}
209 onClick={linkEvent(this, this.handleInsertBold)}
211 <Icon icon="bold" classes="icon-inline" />
214 className="btn btn-sm text-muted"
215 data-tippy-content={i18n.t("italic")}
216 aria-label={i18n.t("italic")}
217 onClick={linkEvent(this, this.handleInsertItalic)}
219 <Icon icon="italic" classes="icon-inline" />
222 className="btn btn-sm text-muted"
223 data-tippy-content={i18n.t("link")}
224 aria-label={i18n.t("link")}
225 onClick={linkEvent(this, this.handleInsertLink)}
227 <Icon icon="link" classes="icon-inline" />
229 <form className="btn btn-sm text-muted font-weight-bold">
231 htmlFor={`file-upload-${this.id}`}
233 UserService.Instance.myUserInfo && "pointer"
235 data-tippy-content={i18n.t("upload_image")}
237 {this.state.imageLoading ? (
240 <Icon icon="image" classes="icon-inline" />
244 id={`file-upload-${this.id}`}
246 accept="image/*,video/*"
249 disabled={!UserService.Instance.myUserInfo}
250 onChange={linkEvent(this, this.handleImageUpload)}
254 className="btn btn-sm text-muted"
255 data-tippy-content={i18n.t("header")}
256 aria-label={i18n.t("header")}
257 onClick={linkEvent(this, this.handleInsertHeader)}
259 <Icon icon="header" classes="icon-inline" />
262 className="btn btn-sm text-muted"
263 data-tippy-content={i18n.t("strikethrough")}
264 aria-label={i18n.t("strikethrough")}
265 onClick={linkEvent(this, this.handleInsertStrikethrough)}
267 <Icon icon="strikethrough" classes="icon-inline" />
270 className="btn btn-sm text-muted"
271 data-tippy-content={i18n.t("quote")}
272 aria-label={i18n.t("quote")}
273 onClick={linkEvent(this, this.handleInsertQuote)}
275 <Icon icon="format_quote" classes="icon-inline" />
278 className="btn btn-sm text-muted"
279 data-tippy-content={i18n.t("list")}
280 aria-label={i18n.t("list")}
281 onClick={linkEvent(this, this.handleInsertList)}
283 <Icon icon="list" classes="icon-inline" />
286 className="btn btn-sm text-muted"
287 data-tippy-content={i18n.t("code")}
288 aria-label={i18n.t("code")}
289 onClick={linkEvent(this, this.handleInsertCode)}
291 <Icon icon="code" classes="icon-inline" />
294 className="btn btn-sm text-muted"
295 data-tippy-content={i18n.t("subscript")}
296 aria-label={i18n.t("subscript")}
297 onClick={linkEvent(this, this.handleInsertSubscript)}
299 <Icon icon="subscript" classes="icon-inline" />
302 className="btn btn-sm text-muted"
303 data-tippy-content={i18n.t("superscript")}
304 aria-label={i18n.t("superscript")}
305 onClick={linkEvent(this, this.handleInsertSuperscript)}
307 <Icon icon="superscript" classes="icon-inline" />
310 className="btn btn-sm text-muted"
311 data-tippy-content={i18n.t("spoiler")}
312 aria-label={i18n.t("spoiler")}
313 onClick={linkEvent(this, this.handleInsertSpoiler)}
315 <Icon icon="alert-triangle" classes="icon-inline" />
318 href={markdownHelpUrl}
319 className="btn btn-sm text-muted font-weight-bold"
320 title={i18n.t("formatting_help")}
323 <Icon icon="help-circle" classes="icon-inline" />
331 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
332 let image = event.clipboardData.files[0];
334 i.handleImageUpload(i, image);
338 handleImageUpload(i: MarkdownTextArea, event: any) {
341 event.preventDefault();
342 file = event.target.files[0];
347 i.setState({ imageLoading: true });
351 console.log("pictrs upload:");
353 if (res.msg === "ok") {
354 const imageMarkdown = `![](${res.url})`;
355 const content = i.state.content;
357 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
361 const textarea: any = document.getElementById(i.id);
362 autosize.update(textarea);
364 `${i18n.t("click_to_delete_picture")}: ${file.name}`,
365 `${i18n.t("picture_deleted")}: ${file.name}`,
366 `${i18n.t("failed_to_delete_picture")}: ${file.name}`,
367 res.delete_url as string
370 i.setState({ imageLoading: false });
371 toast(JSON.stringify(res), "danger");
375 i.setState({ imageLoading: false });
376 console.error(error);
377 toast(error, "danger");
382 // Coerces the undefineds to empty strings, for replacing in the DB
383 let content = this.state.content ?? "";
384 this.props.onContentChange?.(content);
387 handleContentChange(i: MarkdownTextArea, event: any) {
388 i.setState({ content: event.target.value });
392 handlePreviewToggle(i: MarkdownTextArea, event: any) {
393 event.preventDefault();
394 i.setState({ previewMode: !i.state.previewMode });
397 handleLanguageChange(val: number[]) {
398 this.setState({ languageId: val[0] });
401 handleSubmit(i: MarkdownTextArea, event: any) {
402 event.preventDefault();
403 i.setState({ loading: true });
405 val: i.state.content,
407 languageId: i.state.languageId,
409 i.props.onSubmit?.(msg);
412 handleReplyCancel(i: MarkdownTextArea) {
413 i.props.onReplyCancel?.();
416 handleInsertLink(i: MarkdownTextArea, event: any) {
417 event.preventDefault();
419 let textarea: any = document.getElementById(i.id);
420 let start: number = textarea.selectionStart;
421 let end: number = textarea.selectionEnd;
423 let content = i.state.content;
425 if (!i.state.content) {
426 i.setState({ content: "" });
430 let selectedText = content?.substring(start, end);
432 content: `${content?.substring(
435 )}[${selectedText}]()${content?.substring(end)}`,
438 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
440 i.setState({ content: `${content} []()` });
442 setTimeout(() => (textarea.selectionEnd -= 1), 10);
447 simpleSurround(chars: string) {
448 this.simpleSurroundBeforeAfter(chars, chars);
451 simpleBeginningofLine(chars: string) {
452 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
455 simpleSurroundBeforeAfter(
460 let content = this.state.content;
461 if (!this.state.content) {
462 this.setState({ content: "" });
464 let textarea: any = document.getElementById(this.id);
465 let start: number = textarea.selectionStart;
466 let end: number = textarea.selectionEnd;
469 let selectedText = content?.substring(start, end);
471 content: `${content?.substring(
474 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
478 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
481 this.contentChange();
486 textarea.setSelectionRange(
487 start + beforeChars.length,
488 end + afterChars.length
491 textarea.setSelectionRange(
492 start + beforeChars.length,
493 end + emptyChars.length + afterChars.length
498 autosize.update(textarea);
502 handleInsertBold(i: MarkdownTextArea, event: any) {
503 event.preventDefault();
504 i.simpleSurround("**");
507 handleInsertItalic(i: MarkdownTextArea, event: any) {
508 event.preventDefault();
509 i.simpleSurround("*");
512 handleInsertCode(i: MarkdownTextArea, event: any) {
513 event.preventDefault();
514 if (i.getSelectedText().split(/\r*\n/).length > 1) {
515 i.simpleSurroundBeforeAfter("```\n", "\n```");
517 i.simpleSurround("`");
521 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
522 event.preventDefault();
523 i.simpleSurround("~~");
526 handleInsertList(i: MarkdownTextArea, event: any) {
527 event.preventDefault();
528 i.simpleBeginningofLine("-");
531 handleInsertQuote(i: MarkdownTextArea, event: any) {
532 event.preventDefault();
533 i.simpleBeginningofLine(">");
536 handleInsertHeader(i: MarkdownTextArea, event: any) {
537 event.preventDefault();
538 i.simpleBeginningofLine("#");
541 handleInsertSubscript(i: MarkdownTextArea, event: any) {
542 event.preventDefault();
543 i.simpleSurround("~");
546 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
547 event.preventDefault();
548 i.simpleSurround("^");
551 simpleInsert(chars: string) {
552 let content = this.state.content;
554 this.setState({ content: `${chars} ` });
557 content: `${content}\n${chars} `,
561 let textarea: any = document.getElementById(this.id);
564 autosize.update(textarea);
566 this.contentChange();
569 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
570 event.preventDefault();
571 let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
572 let afterChars = "\n:::\n";
573 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
577 let textarea: any = document.getElementById(this.id);
578 let selectedText = window.getSelection()?.toString();
579 let content = this.state.content;
585 .join("\n") + "\n\n";
587 this.setState({ content: "" });
589 this.setState({ content: `${content}\n` });
592 content: `${content}${quotedText}`,
594 this.contentChange();
595 // Not sure why this needs a delay
596 setTimeout(() => autosize.update(textarea), 10);
600 getSelectedText(): string {
601 let textarea: any = document.getElementById(this.id);
602 let start: number = textarea.selectionStart;
603 let end: number = textarea.selectionEnd;
604 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";