import clsx from 'clsx'; import { useRef, useEffect } from '@wordpress/element'; import { useDispatch } from '@wordpress/data'; import { store as noticesStore } from '@wordpress/notices'; import { __, sprintf } from '@wordpress/i18n'; import { Popover as WCPopover } from '@wordpress/components'; import { useViewportMatch } from '@wordpress/compose'; import Control from './control'; interface FormProps { title?: string; isVisible: boolean; id?: string | null; idBase?: string | null; instance?: Record< string, unknown > | null; isWide?: boolean; onChangeInstance: ( instance: Record< string, unknown > ) => void; onChangeHasPreview: ( hasPreview: boolean ) => void; } export default function Form( { title, isVisible, id, idBase, instance, isWide, onChangeInstance, onChangeHasPreview, }: FormProps ) { const ref = useRef< HTMLDivElement >( null ); const isMediumLargeViewport = useViewportMatch( 'small' ); // We only want to remount the control when the instance changes // *externally*. For example, if the user performs an undo. To do this, we // keep track of changes made to instance by the control itself and then // ignore those. const outgoingInstances = useRef( new Set< Record< string, unknown > | null | undefined >() ); const incomingInstances = useRef( new Set< Record< string, unknown > | null | undefined >() ); const { createNotice } = useDispatch( noticesStore ); useEffect( () => { if ( incomingInstances.current.has( instance ) ) { incomingInstances.current.delete( instance ); return; } const control = new Control( { id, idBase, instance, onChangeInstance( nextInstance ) { outgoingInstances.current.add( instance ); incomingInstances.current.add( nextInstance ); onChangeInstance( nextInstance ); }, onChangeHasPreview, onError( error ) { window.console.error( error ); createNotice( 'error', sprintf( /* translators: %s: the name of the affected block. */ __( 'The "%s" block was affected by errors and may not function properly. Check the developer tools for more details.' ), ( idBase || id )! ) ); }, } ); ref.current!.appendChild( control.element ); return () => { if ( outgoingInstances.current.has( instance ) ) { outgoingInstances.current.delete( instance ); return; } control.destroy(); }; }, [ id, idBase, instance, onChangeInstance, onChangeHasPreview, isMediumLargeViewport, ] ); if ( isWide && isMediumLargeViewport ) { return (