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 { pictrsUri } from "../../env";
6 import { i18n } from "../../i18next";
7 import { UserService } from "../../services";
11 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" />
231 <EmojiPicker onEmojiClick={(e) => this.handleEmoji(this,e)}></EmojiPicker>
232 <form className="btn btn-sm text-muted font-weight-bold">
234 htmlFor={`file-upload-${this.id}`}
236 UserService.Instance.myUserInfo && "pointer"
238 data-tippy-content={i18n.t("upload_image")}
240 {this.state.imageLoading ? (
243 <Icon icon="image" classes="icon-inline" />
247 id={`file-upload-${this.id}`}
249 accept="image/*,video/*"
252 disabled={!UserService.Instance.myUserInfo}
253 onChange={linkEvent(this, this.handleImageUpload)}
257 className="btn btn-sm text-muted"
258 data-tippy-content={i18n.t("header")}
259 aria-label={i18n.t("header")}
260 onClick={linkEvent(this, this.handleInsertHeader)}
262 <Icon icon="header" classes="icon-inline" />
265 className="btn btn-sm text-muted"
266 data-tippy-content={i18n.t("strikethrough")}
267 aria-label={i18n.t("strikethrough")}
268 onClick={linkEvent(this, this.handleInsertStrikethrough)}
270 <Icon icon="strikethrough" classes="icon-inline" />
273 className="btn btn-sm text-muted"
274 data-tippy-content={i18n.t("quote")}
275 aria-label={i18n.t("quote")}
276 onClick={linkEvent(this, this.handleInsertQuote)}
278 <Icon icon="format_quote" classes="icon-inline" />
281 className="btn btn-sm text-muted"
282 data-tippy-content={i18n.t("list")}
283 aria-label={i18n.t("list")}
284 onClick={linkEvent(this, this.handleInsertList)}
286 <Icon icon="list" classes="icon-inline" />
289 className="btn btn-sm text-muted"
290 data-tippy-content={i18n.t("code")}
291 aria-label={i18n.t("code")}
292 onClick={linkEvent(this, this.handleInsertCode)}
294 <Icon icon="code" classes="icon-inline" />
297 className="btn btn-sm text-muted"
298 data-tippy-content={i18n.t("subscript")}
299 aria-label={i18n.t("subscript")}
300 onClick={linkEvent(this, this.handleInsertSubscript)}
302 <Icon icon="subscript" classes="icon-inline" />
305 className="btn btn-sm text-muted"
306 data-tippy-content={i18n.t("superscript")}
307 aria-label={i18n.t("superscript")}
308 onClick={linkEvent(this, this.handleInsertSuperscript)}
310 <Icon icon="superscript" classes="icon-inline" />
313 className="btn btn-sm text-muted"
314 data-tippy-content={i18n.t("spoiler")}
315 aria-label={i18n.t("spoiler")}
316 onClick={linkEvent(this, this.handleInsertSpoiler)}
318 <Icon icon="alert-triangle" classes="icon-inline" />
321 href={markdownHelpUrl}
322 className="btn btn-sm text-muted font-weight-bold"
323 title={i18n.t("formatting_help")}
326 <Icon icon="help-circle" classes="icon-inline" />
334 handleEmoji(i: MarkdownTextArea, e: any) {
335 let value = e.native;
337 let emoji = customEmojisLookup.get(e.id)?.custom_emoji;
339 value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`;
343 content: `${i.state.content ?? ""} ${value} `,
346 let textarea: any = document.getElementById(i.id);
347 autosize.update(textarea);
350 handleImageUploadPaste(i: MarkdownTextArea, event: any) {
351 let image = event.clipboardData.files[0];
353 i.handleImageUpload(i, image);
357 handleImageUpload(i: MarkdownTextArea, event: any) {
360 event.preventDefault();
361 file = event.target.files[0];
366 const formData = new FormData();
367 formData.append("images[]", file);
369 i.setState({ imageLoading: true });
375 .then(res => res.json())
377 console.log("pictrs upload:");
379 if (res.msg == "ok") {
380 let hash = res.files[0].file;
381 let url = `${pictrsUri}/${hash}`;
382 let deleteToken = res.files[0].delete_token;
383 let deleteUrl = `${pictrsUri}/delete/${deleteToken}/${hash}`;
384 let imageMarkdown = `![](${url})`;
385 let content = i.state.content;
387 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
391 let textarea: any = document.getElementById(i.id);
392 autosize.update(textarea);
394 `${i18n.t("click_to_delete_picture")}: ${file.name}`,
395 `${i18n.t("picture_deleted")}: ${file.name}`,
396 `${i18n.t("failed_to_delete_picture")}: ${file.name}`,
400 i.setState({ imageLoading: false });
401 toast(JSON.stringify(res), "danger");
405 i.setState({ imageLoading: false });
406 console.error(error);
407 toast(error, "danger");
412 // Coerces the undefineds to empty strings, for replacing in the DB
413 let content = this.state.content ?? "";
414 this.props.onContentChange?.(content);
417 handleContentChange(i: MarkdownTextArea, event: any) {
418 i.setState({ content: event.target.value });
422 handlePreviewToggle(i: MarkdownTextArea, event: any) {
423 event.preventDefault();
424 i.setState({ previewMode: !i.state.previewMode });
427 handleLanguageChange(val: number[]) {
428 this.setState({ languageId: val[0] });
431 handleSubmit(i: MarkdownTextArea, event: any) {
432 event.preventDefault();
433 i.setState({ loading: true });
435 val: i.state.content,
437 languageId: i.state.languageId,
439 i.props.onSubmit?.(msg);
442 handleReplyCancel(i: MarkdownTextArea) {
443 i.props.onReplyCancel?.();
446 handleInsertLink(i: MarkdownTextArea, event: any) {
447 event.preventDefault();
449 let textarea: any = document.getElementById(i.id);
450 let start: number = textarea.selectionStart;
451 let end: number = textarea.selectionEnd;
453 let content = i.state.content;
455 if (!i.state.content) {
456 i.setState({ content: "" });
460 let selectedText = content?.substring(start, end);
462 content: `${content?.substring(
465 )}[${selectedText}]()${content?.substring(end)}`,
468 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
470 i.setState({ content: `${content} []()` });
472 setTimeout(() => (textarea.selectionEnd -= 1), 10);
477 simpleSurround(chars: string) {
478 this.simpleSurroundBeforeAfter(chars, chars);
481 simpleBeginningofLine(chars: string) {
482 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
485 simpleSurroundBeforeAfter(
490 let content = this.state.content;
491 if (!this.state.content) {
492 this.setState({ content: "" });
494 let textarea: any = document.getElementById(this.id);
495 let start: number = textarea.selectionStart;
496 let end: number = textarea.selectionEnd;
499 let selectedText = content?.substring(start, end);
501 content: `${content?.substring(
504 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
508 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
511 this.contentChange();
516 textarea.setSelectionRange(
517 start + beforeChars.length,
518 end + afterChars.length
521 textarea.setSelectionRange(
522 start + beforeChars.length,
523 end + emptyChars.length + afterChars.length
528 autosize.update(textarea);
532 handleInsertBold(i: MarkdownTextArea, event: any) {
533 event.preventDefault();
534 i.simpleSurround("**");
537 handleInsertItalic(i: MarkdownTextArea, event: any) {
538 event.preventDefault();
539 i.simpleSurround("*");
542 handleInsertCode(i: MarkdownTextArea, event: any) {
543 event.preventDefault();
544 if (i.getSelectedText().split(/\r*\n/).length > 1) {
545 i.simpleSurroundBeforeAfter("```\n", "\n```");
547 i.simpleSurround("`");
551 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
552 event.preventDefault();
553 i.simpleSurround("~~");
556 handleInsertList(i: MarkdownTextArea, event: any) {
557 event.preventDefault();
558 i.simpleBeginningofLine("-");
561 handleInsertQuote(i: MarkdownTextArea, event: any) {
562 event.preventDefault();
563 i.simpleBeginningofLine(">");
566 handleInsertHeader(i: MarkdownTextArea, event: any) {
567 event.preventDefault();
568 i.simpleBeginningofLine("#");
571 handleInsertSubscript(i: MarkdownTextArea, event: any) {
572 event.preventDefault();
573 i.simpleSurround("~");
576 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
577 event.preventDefault();
578 i.simpleSurround("^");
581 simpleInsert(chars: string) {
582 let content = this.state.content;
584 this.setState({ content: `${chars} ` });
587 content: `${content}\n${chars} `,
591 let textarea: any = document.getElementById(this.id);
594 autosize.update(textarea);
596 this.contentChange();
599 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
600 event.preventDefault();
601 let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
602 let afterChars = "\n:::\n";
603 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
607 let textarea: any = document.getElementById(this.id);
608 let selectedText = window.getSelection()?.toString();
609 let content = this.state.content;
615 .join("\n") + "\n\n";
617 this.setState({ content: "" });
619 this.setState({ content: `${content}\n` });
622 content: `${content}${quotedText}`,
624 this.contentChange();
625 // Not sure why this needs a delay
626 setTimeout(() => autosize.update(textarea), 10);
630 getSelectedText(): string {
631 let textarea: any = document.getElementById(this.id);
632 let start: number = textarea.selectionStart;
633 let end: number = textarea.selectionEnd;
634 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";