import autosize from "autosize"; import { Component, linkEvent } from "inferno"; import { Prompt } from "inferno-router"; import { Language } from "lemmy-js-client"; import { pictrsUri } from "../../env"; import { i18n } from "../../i18next"; import { UserService } from "../../services"; import { customEmojisLookup, isBrowser, markdownFieldCharacterLimit, markdownHelpUrl, mdToHtml, pictrsDeleteToast, randomStr, relTags, setupTippy, setupTribute, toast, } from "../../utils"; import { EmojiPicker } from "./emoji-picker"; import { Icon, Spinner } from "./icon"; import { LanguageSelect } from "./language-select"; interface MarkdownTextAreaProps { initialContent?: string; initialLanguageId?: number; placeholder?: string; buttonTitle?: string; maxLength?: number; replyType?: boolean; focus?: boolean; disabled?: boolean; finished?: boolean; showLanguage?: boolean; hideNavigationWarnings?: boolean; onContentChange?(val: string): any; onReplyCancel?(): any; onSubmit?(msg: { val?: string; formId: string; languageId?: number }): any; allLanguages: Language[]; // TODO should probably be nullable siteLanguages: number[]; // TODO same } interface MarkdownTextAreaState { content?: string; languageId?: number; previewMode: boolean; loading: boolean; imageLoading: boolean; } export class MarkdownTextArea extends Component< MarkdownTextAreaProps, MarkdownTextAreaState > { private id = `comment-textarea-${randomStr()}`; private formId = `comment-form-${randomStr()}`; private tribute: any; state: MarkdownTextAreaState = { content: this.props.initialContent, languageId: this.props.initialLanguageId, previewMode: false, loading: false, imageLoading: false, }; constructor(props: any, context: any) { super(props, context); this.handleLanguageChange = this.handleLanguageChange.bind(this); if (isBrowser()) { this.tribute = setupTribute(); } } componentDidMount() { let textarea: any = document.getElementById(this.id); if (textarea) { autosize(textarea); this.tribute.attach(textarea); textarea.addEventListener("tribute-replaced", () => { this.setState({ content: textarea.value }); autosize.update(textarea); }); this.quoteInsert(); if (this.props.focus) { textarea.focus(); } // TODO this is slow for some reason setupTippy(); } } componentDidUpdate() { if (!this.props.hideNavigationWarnings && this.state.content) { window.onbeforeunload = () => true; } else { window.onbeforeunload = null; } } componentWillReceiveProps(nextProps: MarkdownTextAreaProps) { if (nextProps.finished) { this.setState({ previewMode: false, loading: false, content: undefined }); if (this.props.replyType) { this.props.onReplyCancel?.(); } let textarea: any = document.getElementById(this.id); let form: any = document.getElementById(this.formId); form.reset(); setTimeout(() => autosize.update(textarea), 10); } } componentWillUnmount() { window.onbeforeunload = null; } render() { let languageId = this.state.languageId; return (
); } handleEmoji(i: MarkdownTextArea, e: any) { let value = e.native; if (value == null){ let emoji = customEmojisLookup.get(e.id)?.custom_emoji; if (emoji){ value = `![${emoji.alt_text}](${emoji.image_url} "${emoji.shortcode}")`; } } i.setState({ content: `${i.state.content ?? ""} ${value} `, }); i.contentChange(); let textarea: any = document.getElementById(i.id); autosize.update(textarea); } handleImageUploadPaste(i: MarkdownTextArea, event: any) { let image = event.clipboardData.files[0]; if (image) { i.handleImageUpload(i, image); } } handleImageUpload(i: MarkdownTextArea, event: any) { let file: any; if (event.target) { event.preventDefault(); file = event.target.files[0]; } else { file = event; } const formData = new FormData(); formData.append("images[]", file); i.setState({ imageLoading: true }); fetch(pictrsUri, { method: "POST", body: formData, }) .then(res => res.json()) .then(res => { console.log("pictrs upload:"); console.log(res); if (res.msg == "ok") { let hash = res.files[0].file; let url = `${pictrsUri}/${hash}`; let deleteToken = res.files[0].delete_token; let deleteUrl = `${pictrsUri}/delete/${deleteToken}/${hash}`; let imageMarkdown = `![](${url})`; let content = i.state.content; i.setState({ content: content ? `${content}\n${imageMarkdown}` : imageMarkdown, imageLoading: false, }); i.contentChange(); let textarea: any = document.getElementById(i.id); autosize.update(textarea); pictrsDeleteToast( `${i18n.t("click_to_delete_picture")}: ${file.name}`, `${i18n.t("picture_deleted")}: ${file.name}`, `${i18n.t("failed_to_delete_picture")}: ${file.name}`, deleteUrl ); } else { i.setState({ imageLoading: false }); toast(JSON.stringify(res), "danger"); } }) .catch(error => { i.setState({ imageLoading: false }); console.error(error); toast(error, "danger"); }); } contentChange() { // Coerces the undefineds to empty strings, for replacing in the DB let content = this.state.content ?? ""; this.props.onContentChange?.(content); } handleContentChange(i: MarkdownTextArea, event: any) { i.setState({ content: event.target.value }); i.contentChange(); } handlePreviewToggle(i: MarkdownTextArea, event: any) { event.preventDefault(); i.setState({ previewMode: !i.state.previewMode }); } handleLanguageChange(val: number[]) { this.setState({ languageId: val[0] }); } handleSubmit(i: MarkdownTextArea, event: any) { event.preventDefault(); i.setState({ loading: true }); let msg = { val: i.state.content, formId: i.formId, languageId: i.state.languageId, }; i.props.onSubmit?.(msg); } handleReplyCancel(i: MarkdownTextArea) { i.props.onReplyCancel?.(); } handleInsertLink(i: MarkdownTextArea, event: any) { event.preventDefault(); let textarea: any = document.getElementById(i.id); let start: number = textarea.selectionStart; let end: number = textarea.selectionEnd; let content = i.state.content; if (!i.state.content) { i.setState({ content: "" }); } if (start !== end) { let selectedText = content?.substring(start, end); i.setState({ content: `${content?.substring( 0, start )}[${selectedText}]()${content?.substring(end)}`, }); textarea.focus(); setTimeout(() => (textarea.selectionEnd = end + 3), 10); } else { i.setState({ content: `${content} []()` }); textarea.focus(); setTimeout(() => (textarea.selectionEnd -= 1), 10); } i.contentChange(); } simpleSurround(chars: string) { this.simpleSurroundBeforeAfter(chars, chars); } simpleBeginningofLine(chars: string) { this.simpleSurroundBeforeAfter(`${chars}`, "", ""); } simpleSurroundBeforeAfter( beforeChars: string, afterChars: string, emptyChars = "___" ) { let content = this.state.content; if (!this.state.content) { this.setState({ content: "" }); } let textarea: any = document.getElementById(this.id); let start: number = textarea.selectionStart; let end: number = textarea.selectionEnd; if (start !== end) { let selectedText = content?.substring(start, end); this.setState({ content: `${content?.substring( 0, start )}${beforeChars}${selectedText}${afterChars}${content?.substring(end)}`, }); } else { this.setState({ content: `${content}${beforeChars}${emptyChars}${afterChars}`, }); } this.contentChange(); textarea.focus(); if (start !== end) { textarea.setSelectionRange( start + beforeChars.length, end + afterChars.length ); } else { textarea.setSelectionRange( start + beforeChars.length, end + emptyChars.length + afterChars.length ); } setTimeout(() => { autosize.update(textarea); }, 10); } handleInsertBold(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleSurround("**"); } handleInsertItalic(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleSurround("*"); } handleInsertCode(i: MarkdownTextArea, event: any) { event.preventDefault(); if (i.getSelectedText().split(/\r*\n/).length > 1) { i.simpleSurroundBeforeAfter("```\n", "\n```"); } else { i.simpleSurround("`"); } } handleInsertStrikethrough(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleSurround("~~"); } handleInsertList(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleBeginningofLine("-"); } handleInsertQuote(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleBeginningofLine(">"); } handleInsertHeader(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleBeginningofLine("#"); } handleInsertSubscript(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleSurround("~"); } handleInsertSuperscript(i: MarkdownTextArea, event: any) { event.preventDefault(); i.simpleSurround("^"); } simpleInsert(chars: string) { let content = this.state.content; if (!content) { this.setState({ content: `${chars} ` }); } else { this.setState({ content: `${content}\n${chars} `, }); } let textarea: any = document.getElementById(this.id); textarea.focus(); setTimeout(() => { autosize.update(textarea); }, 10); this.contentChange(); } handleInsertSpoiler(i: MarkdownTextArea, event: any) { event.preventDefault(); let beforeChars = `\n::: spoiler ${i18n.t("spoiler")}\n`; let afterChars = "\n:::\n"; i.simpleSurroundBeforeAfter(beforeChars, afterChars); } quoteInsert() { let textarea: any = document.getElementById(this.id); let selectedText = window.getSelection()?.toString(); let content = this.state.content; if (selectedText) { let quotedText = selectedText .split("\n") .map(t => `> ${t}`) .join("\n") + "\n\n"; if (!content) { this.setState({ content: "" }); } else { this.setState({ content: `${content}\n` }); } this.setState({ content: `${content}${quotedText}`, }); this.contentChange(); // Not sure why this needs a delay setTimeout(() => autosize.update(textarea), 10); } } getSelectedText(): string { let textarea: any = document.getElementById(this.id); let start: number = textarea.selectionStart; let end: number = textarea.selectionEnd; return start !== end ? this.state.content?.substring(start, end) ?? "" : ""; } }