import { useState, useId } from '@wordpress/element'; import { InspectorControls, useBlockBindingsUtils, } from '@wordpress/block-editor'; import { BaseControl, Button } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; import { PATTERN_OVERRIDES_BINDING_SOURCE } from '../constants'; import { AllowOverridesModal, DisallowOverridesModal, } from './allow-overrides-modal'; import type { PatternOverridesControlsProps } from './types'; function PatternOverridesControls( { attributes, setAttributes, name: blockName, }: PatternOverridesControlsProps ) { const controlId = useId(); const [ showAllowOverridesModal, setShowAllowOverridesModal ] = useState( false ); const [ showDisallowOverridesModal, setShowDisallowOverridesModal ] = useState( false ); const hasName = !! attributes.metadata?.name; const defaultBindings = attributes.metadata?.bindings?.__default; const hasOverrides = hasName && defaultBindings?.source === PATTERN_OVERRIDES_BINDING_SOURCE; const isConnectedToOtherSources = defaultBindings?.source && defaultBindings.source !== PATTERN_OVERRIDES_BINDING_SOURCE; const { updateBlockBindings } = useBlockBindingsUtils(); function updateBindings( isChecked: boolean, customName?: string ) { if ( customName ) { setAttributes( { metadata: { ...attributes.metadata, name: customName, }, } ); } updateBlockBindings( { __default: isChecked ? { source: PATTERN_OVERRIDES_BINDING_SOURCE } : undefined, } ); } // Avoid overwriting other (e.g. meta) bindings. if ( isConnectedToOtherSources ) { return null; } const hasUnsupportedImageAttributes = blockName === 'core/image' && !! attributes.href?.length; const helpText = ! hasOverrides && hasUnsupportedImageAttributes ? __( `Overrides currently don't support image links. Remove the link first before enabling overrides.` ) : __( 'Allow changes to this block throughout instances of this pattern.' ); return ( <> { showAllowOverridesModal && ( setShowAllowOverridesModal( false ) } onSave={ ( newName ) => { updateBindings( true, newName ); } } /> ) } { showDisallowOverridesModal && ( setShowDisallowOverridesModal( false ) } onSave={ () => updateBindings( false ) } /> ) } ); } export default PatternOverridesControls;