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";
10 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 const formData = new FormData();
348 formData.append("images[]", file);
350 i.setState({ imageLoading: true });
356 .then(res => res.json())
358 console.log("pictrs upload:");
360 if (res.msg == "ok") {
361 let hash = res.files[0].file;
362 let url = `${pictrsUri}/${hash}`;
363 let deleteToken = res.files[0].delete_token;
364 let deleteUrl = `${pictrsUri}/delete/${deleteToken}/${hash}`;
365 let imageMarkdown = `![](${url})`;
366 let content = i.state.content;
368 content: content ? `${content}\n${imageMarkdown}` : imageMarkdown,
372 let textarea: any = document.getElementById(i.id);
373 autosize.update(textarea);
375 `${i18n.t("click_to_delete_picture")}: ${file.name}`,
376 `${i18n.t("picture_deleted")}: ${file.name}`,
377 `${i18n.t("failed_to_delete_picture")}: ${file.name}`,
381 i.setState({ imageLoading: false });
382 toast(JSON.stringify(res), "danger");
386 i.setState({ imageLoading: false });
387 console.error(error);
388 toast(error, "danger");
393 // Coerces the undefineds to empty strings, for replacing in the DB
394 let content = this.state.content ?? "";
395 this.props.onContentChange?.(content);
398 handleContentChange(i: MarkdownTextArea, event: any) {
399 i.setState({ content: event.target.value });
403 handlePreviewToggle(i: MarkdownTextArea, event: any) {
404 event.preventDefault();
405 i.setState({ previewMode: !i.state.previewMode });
408 handleLanguageChange(val: number[]) {
409 this.setState({ languageId: val[0] });
412 handleSubmit(i: MarkdownTextArea, event: any) {
413 event.preventDefault();
414 i.setState({ loading: true });
416 val: i.state.content,
418 languageId: i.state.languageId,
420 i.props.onSubmit?.(msg);
423 handleReplyCancel(i: MarkdownTextArea) {
424 i.props.onReplyCancel?.();
427 handleInsertLink(i: MarkdownTextArea, event: any) {
428 event.preventDefault();
430 let textarea: any = document.getElementById(i.id);
431 let start: number = textarea.selectionStart;
432 let end: number = textarea.selectionEnd;
434 let content = i.state.content;
436 if (!i.state.content) {
437 i.setState({ content: "" });
441 let selectedText = content?.substring(start, end);
443 content: `${content?.substring(
446 )}[${selectedText}]()${content?.substring(end)}`,
449 setTimeout(() => (textarea.selectionEnd = end + 3), 10);
451 i.setState({ content: `${content} []()` });
453 setTimeout(() => (textarea.selectionEnd -= 1), 10);
458 simpleSurround(chars: string) {
459 this.simpleSurroundBeforeAfter(chars, chars);
462 simpleBeginningofLine(chars: string) {
463 this.simpleSurroundBeforeAfter(`${chars}`, "", "");
466 simpleSurroundBeforeAfter(
471 let content = this.state.content;
472 if (!this.state.content) {
473 this.setState({ content: "" });
475 let textarea: any = document.getElementById(this.id);
476 let start: number = textarea.selectionStart;
477 let end: number = textarea.selectionEnd;
480 let selectedText = content?.substring(start, end);
482 content: `${content?.substring(
485 )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`,
489 content: `${content}${beforeChars}${emptyChars}${afterChars}`,
492 this.contentChange();
497 textarea.setSelectionRange(
498 start + beforeChars.length,
499 end + afterChars.length
502 textarea.setSelectionRange(
503 start + beforeChars.length,
504 end + emptyChars.length + afterChars.length
509 autosize.update(textarea);
513 handleInsertBold(i: MarkdownTextArea, event: any) {
514 event.preventDefault();
515 i.simpleSurround("**");
518 handleInsertItalic(i: MarkdownTextArea, event: any) {
519 event.preventDefault();
520 i.simpleSurround("*");
523 handleInsertCode(i: MarkdownTextArea, event: any) {
524 event.preventDefault();
525 if (i.getSelectedText().split(/\r*\n/).length > 1) {
526 i.simpleSurroundBeforeAfter("```\n", "\n```");
528 i.simpleSurround("`");
532 handleInsertStrikethrough(i: MarkdownTextArea, event: any) {
533 event.preventDefault();
534 i.simpleSurround("~~");
537 handleInsertList(i: MarkdownTextArea, event: any) {
538 event.preventDefault();
539 i.simpleBeginningofLine("-");
542 handleInsertQuote(i: MarkdownTextArea, event: any) {
543 event.preventDefault();
544 i.simpleBeginningofLine(">");
547 handleInsertHeader(i: MarkdownTextArea, event: any) {
548 event.preventDefault();
549 i.simpleBeginningofLine("#");
552 handleInsertSubscript(i: MarkdownTextArea, event: any) {
553 event.preventDefault();
554 i.simpleSurround("~");
557 handleInsertSuperscript(i: MarkdownTextArea, event: any) {
558 event.preventDefault();
559 i.simpleSurround("^");
562 simpleInsert(chars: string) {
563 let content = this.state.content;
565 this.setState({ content: `${chars} ` });
568 content: `${content}\n${chars} `,
572 let textarea: any = document.getElementById(this.id);
575 autosize.update(textarea);
577 this.contentChange();
580 handleInsertSpoiler(i: MarkdownTextArea, event: any) {
581 event.preventDefault();
582 let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`;
583 let afterChars = "\n:::\n";
584 i.simpleSurroundBeforeAfter(beforeChars, afterChars);
588 let textarea: any = document.getElementById(this.id);
589 let selectedText = window.getSelection()?.toString();
590 let content = this.state.content;
596 .join("\n") + "\n\n";
598 this.setState({ content: "" });
600 this.setState({ content: `${content}\n` });
603 content: `${content}${quotedText}`,
605 this.contentChange();
606 // Not sure why this needs a delay
607 setTimeout(() => autosize.update(textarea), 10);
611 getSelectedText(): string {
612 let textarea: any = document.getElementById(this.id);
613 let start: number = textarea.selectionStart;
614 let end: number = textarea.selectionEnd;
615 return start !== end ? this.state.content?.substring(start, end) ?? "" : "";