UNPKG

@wordpress/block-library

Version:
108 lines (107 loc) 3.43 kB
// packages/block-library/src/math/edit.js import { __ } from "@wordpress/i18n"; import { useBlockProps, store as blockEditorStore } from "@wordpress/block-editor"; import { Popover, privateApis as componentsPrivateApis } from "@wordpress/components"; import { useState, useEffect, useRef } from "@wordpress/element"; import { useDispatch } from "@wordpress/data"; import { unlock } from "../lock-unlock.mjs"; import { jsx, jsxs } from "react/jsx-runtime"; var { ValidatedTextareaControl } = unlock(componentsPrivateApis); function MathEdit({ attributes, setAttributes, isSelected }) { const { latex, mathML } = attributes; const [blockRef, setBlockRef] = useState(); const [error, setError] = useState(null); const [latexToMathML, setLatexToMathML] = useState(); const initialLatex = useRef(latex); const formRef = useRef(); const { __unstableMarkNextChangeAsNotPersistent } = useDispatch(blockEditorStore); useEffect(() => { import("@wordpress/latex-to-mathml").then((module) => { setLatexToMathML(() => module.default); if (initialLatex.current) { __unstableMarkNextChangeAsNotPersistent(); setAttributes({ mathML: module.default(initialLatex.current, { displayMode: true }) }); } }); }, [ initialLatex, setAttributes, __unstableMarkNextChangeAsNotPersistent ]); const blockProps = useBlockProps({ ref: setBlockRef, position: "relative" }); return /* @__PURE__ */ jsxs("div", { ...blockProps, children: [ mathML ? /* @__PURE__ */ jsx( "math", { display: "block", dangerouslySetInnerHTML: { __html: mathML } } ) : "​", isSelected && /* @__PURE__ */ jsx( Popover, { placement: "bottom-start", offset: 8, anchor: blockRef, focusOnMount: false, onFocusOutside: () => formRef.current?.reportValidity(), __unstableSlotName: "__unstable-block-tools-after", children: /* @__PURE__ */ jsx( "form", { ref: formRef, style: { padding: "4px", minWidth: "300px" }, onSubmit: (event) => event.preventDefault(), children: /* @__PURE__ */ jsx( ValidatedTextareaControl, { label: __("LaTeX math syntax"), hideLabelFromVision: true, value: latex, className: "wp-block-math__textarea-control", customValidity: error ? { type: "invalid", message: error } : void 0, onChange: (newLatex) => { if (!latexToMathML) { setAttributes({ latex: newLatex }); return; } let newMathML = ""; try { newMathML = latexToMathML(newLatex, { displayMode: true }); setError(null); } catch (err) { setError(err.message); } setAttributes({ mathML: newMathML, latex: newLatex }); }, placeholder: __("e.g., x^2, \\frac{a}{b}") } ) } ) } ) ] }); } export { MathEdit as default }; //# sourceMappingURL=edit.mjs.map