import { __ } from '@wordpress/i18n'; import { useBlockProps, store as blockEditorStore, } from '@wordpress/block-editor'; import { Popover as WCPopover } from '@wordpress/components'; import { // eslint-disable-next-line @wordpress/use-recommended-components ValidatedTextareaControl, Link, } from '@wordpress/ui'; import type { BlockEditProps } from '@wordpress/blocks'; import { useState, useEffect } from '@wordpress/element'; import { useDispatch } from '@wordpress/data'; import { useEvent } from '@wordpress/compose'; import type { LatexToMathML, MathAttributes } from './types'; export default function MathEdit( { attributes, setAttributes, isSelected, }: BlockEditProps< MathAttributes > ) { const { latex, mathML } = attributes; const [ blockRef, setBlockRef ] = useState< HTMLElement | null >(); const [ error, setError ] = useState< string | null >( null ); const [ latexToMathML, setLatexToMathML ] = useState< LatexToMathML | undefined >(); const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( blockEditorStore ); // Re-render once the converter loads, so MathML saved from a corrupted // source is repaired and a source typed before the converter loaded is // rendered. The converter loads asynchronously, and the user can type in // the meantime, so read the source at that time rather than on mount. const renderLatest = useEvent( ( convert: LatexToMathML ) => { if ( ! latex ) { return; } try { const newMathML = convert( latex, { displayMode: true } ); __unstableMarkNextChangeAsNotPersistent(); setAttributes( { mathML: newMathML } ); } catch ( err ) { setError( ( err as Error ).message ); } } ); useEffect( () => { import( '@wordpress/latex-to-mathml' ).then( ( module ) => { setLatexToMathML( () => module.default ); renderLatest( module.default ); } ); }, [ renderLatest ] ); const blockProps = useBlockProps( { ref: setBlockRef, position: 'relative', } ); return (
{ mathML ? ( ) : ( // Show the source until it renders, as the front end does. { /* eslint-disable-next-line react/no-unknown-property -- MathML attribute. */ } { latex || '\u200B' } ) } { isSelected && (
event.preventDefault() } > { if ( ! latexToMathML ) { // The source is read back from the MathML, // so clear a stale render along with it. setAttributes( { latex: newLatex, mathML: '', } ); return; } let newMathML = ''; try { newMathML = latexToMathML( newLatex, { displayMode: true, } ); setError( null ); } catch ( err ) { setError( ( err as Error ).message ); } setAttributes( { mathML: newMathML, latex: newLatex, } ); } } placeholder={ __( 'e.g., x^2, \\frac{a}{b}, \\sqrt{x}' ) } /> { __( 'Learn more about LaTeX syntax' ) }
) }
); }