import "katex/dist/katex.min.css"; import katex from "katex"; //import "katex/dist/contrib/mhchem.min.js"; import { useEffect, useRef, useState } from "react"; import { NodeViewProps, NodeViewWrapper } from "@tiptap/react"; import { ActionIcon, Flex, Popover, Stack, Textarea } from "@mantine/core"; import classes from "./math.module.css"; import { v4 } from "uuid"; import { IconTrashX } from "@tabler/icons-react"; import { useDebouncedValue } from "@mantine/hooks"; import { useTranslation } from "react-i18next"; export default function MathBlockView(props: NodeViewProps) { const { t } = useTranslation(); const { node, updateAttributes, editor, getPos } = props; const mathResultContainer = useRef(null); const mathPreviewContainer = useRef(null); const [error, setError] = useState(null); const [preview, setPreview] = useState(null); const textAreaRef = useRef(null); const [isEditing, setIsEditing] = useState(false); const [debouncedPreview] = useDebouncedValue(preview, 500); const renderMath = ( katexString: string, container: HTMLDivElement | null, ) => { try { katex.render(katexString, container!, { displayMode: true, strict: false, }); setError(null); } catch (e) { //console.error(e.message); setError(e.message); } }; useEffect(() => { renderMath(node.attrs.text, mathResultContainer.current); }, [node.attrs.text]); useEffect(() => { if (isEditing) { renderMath(preview || "", mathPreviewContainer.current); } }, [preview, isEditing]); useEffect(() => { if (debouncedPreview !== null) { queueMicrotask(() => { updateAttributes({ text: debouncedPreview }); }); } }, [debouncedPreview]); useEffect(() => { setIsEditing(!!props.selected); if (props.selected) setPreview(node.attrs.text); }, [props.selected]); return (
{((isEditing && !preview?.trim().length) || (!isEditing && !node.attrs.text.trim().length)) && (
{t("Empty equation")}
)} {error &&
{t("Invalid equation")}
}
props.deleteNode()} />
); }