@wordpress/block-library
Version:
Block library for the WordPress editor.
100 lines (99 loc) • 3.16 kB
JavaScript
import { __ } from "@wordpress/i18n";
import { store, useBlockProps } from "@wordpress/block-editor";
import { Popover } from "@wordpress/components";
import { Link, ValidatedTextareaControl } from "@wordpress/ui";
import { useEffect, useState } from "@wordpress/element";
import { useDispatch } from "@wordpress/data";
import { useEvent } from "@wordpress/compose";
import { jsx, jsxs } from "react/jsx-runtime";
// packages/block-library/src/math/edit.jsx
function MathEdit({ attributes, setAttributes, isSelected }) {
const { latex, mathML } = attributes;
const [blockRef, setBlockRef] = useState();
const [error, setError] = useState(null);
const [latexToMathML, setLatexToMathML] = useState();
const { __unstableMarkNextChangeAsNotPersistent } = useDispatch(store);
const renderLatest = useEvent((convert) => {
if (!latex) return;
try {
const newMathML = convert(latex, { displayMode: true });
__unstableMarkNextChangeAsNotPersistent();
setAttributes({ mathML: newMathML });
} catch (err) {
setError(err.message);
}
});
useEffect(() => {
import("@wordpress/latex-to-mathml").then((module) => {
setLatexToMathML(() => module.default);
renderLatest(module.default);
});
}, [renderLatest]);
const blockProps = useBlockProps({
ref: setBlockRef,
position: "relative"
});
return /* @__PURE__ */ jsxs("div", {
...blockProps,
children: [mathML ? /* @__PURE__ */ jsx("math", {
display: "block",
dangerouslySetInnerHTML: { __html: mathML }
}) : /* @__PURE__ */ jsx("math", {
display: "block",
children: /* @__PURE__ */ jsx("semantics", { children: /* @__PURE__ */ jsx("annotation", {
encoding: "application/x-tex",
children: latex || ""
}) })
}), isSelected && /* @__PURE__ */ jsx(Popover, {
placement: "bottom-start",
offset: 8,
anchor: blockRef,
focusOnMount: false,
__unstableSlotName: "__unstable-block-tools-after",
children: /* @__PURE__ */ jsxs("form", {
style: {
padding: "16px",
minWidth: "300px"
},
onSubmit: (event) => event.preventDefault(),
children: [/* @__PURE__ */ jsx(ValidatedTextareaControl, {
label: __("LaTeX math syntax"),
value: latex ?? "",
className: "wp-block-math__textarea-control",
customValidity: error ? {
type: "invalid",
message: error
} : void 0,
onValueChange: (newLatex) => {
if (!latexToMathML) {
setAttributes({
latex: newLatex,
mathML: ""
});
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}, \\sqrt{x}")
}), /* @__PURE__ */ jsx(Link, {
openInNewTab: true,
className: "wp-block-math__learn-more",
href: __("https://wordpress.org/documentation/article/math-block/"),
children: __("Learn more about LaTeX syntax")
})]
})
})]
});
}
export { MathEdit as default };
//# sourceMappingURL=edit.mjs.map