diff --git a/packages/block-editor/src/components/inner-blocks/index.js b/packages/block-editor/src/components/inner-blocks/index.js index 58faf9f9a34e1a..0733e5e6dac09c 100644 --- a/packages/block-editor/src/components/inner-blocks/index.js +++ b/packages/block-editor/src/components/inner-blocks/index.js @@ -7,13 +7,14 @@ import clsx from 'clsx'; * WordPress dependencies */ import { useMergeRefs } from '@wordpress/compose'; -import { forwardRef, useMemo, memo } from '@wordpress/element'; +import { forwardRef, useMemo, useState, memo } from '@wordpress/element'; import { useSelect } from '@wordpress/data'; import { getBlockSupport, store as blocksStore, __unstableGetInnerBlocksProps as getInnerBlocksProps, } from '@wordpress/blocks'; +import warning from '@wordpress/warning'; /** * Internal dependencies @@ -23,6 +24,7 @@ import DefaultBlockAppender from './default-block-appender'; import useNestedSettingsUpdate from './use-nested-settings-update'; import useInnerBlockTemplateSync from './use-inner-block-template-sync'; import useBlockContext from './use-block-context'; +import { useBoundInnerBlocksProps } from './use-bound-inner-blocks'; import { BlockListItems } from '../block-list'; import { BlockContextProvider } from '../block-context'; import { useBlockEditContext } from '../block-edit/context'; @@ -30,6 +32,7 @@ import useBlockSync from '../provider/use-block-sync'; import { store as blockEditorStore } from '../../store'; import useBlockDropZone from '../use-block-drop-zone'; import { unlock } from '../../lock-unlock'; +import { getInnerBlocksBinding } from '../../utils/block-bindings'; const EMPTY_OBJECT = {}; @@ -75,6 +78,7 @@ function UncontrolledInnerBlocks( props ) { blockType, parentLock, defaultLayout, + boundInnerBlocks, } = props; useNestedSettingsUpdate( @@ -89,7 +93,8 @@ function UncontrolledInnerBlocks( props ) { templateLock, captureToolbars, orientation, - layout + layout, + boundInnerBlocks ); useInnerBlockTemplateSync( @@ -156,6 +161,63 @@ function ControlledInnerBlocks( props ) { return ; } +function useEditablePatternOverrideSource( clientId, binding ) { + const sourceName = binding?.source; + return useSelect( + ( select ) => { + if ( ! clientId || sourceName !== 'core/pattern-overrides' ) { + return undefined; + } + + const blockEditor = select( blockEditorStore ); + const attributes = blockEditor.getBlockAttributes( clientId ); + const blockName = attributes?.metadata?.name; + const patternParents = blockEditor.getBlockParentsByBlockName( + clientId, + 'core/block', + true + ); + + return typeof blockName === 'string' && + blockName !== '' && + patternParents.length === 1 + ? sourceName + : undefined; + }, + [ clientId, sourceName ] + ); +} + +function BoundInnerBlocks( { binding, ...props } ) { + const editablePatternOverrideSource = useEditablePatternOverrideSource( + props.clientId, + binding + ); + const boundInnerBlocksProps = useBoundInnerBlocksProps( + props.clientId, + binding, + props.blockType, + !! editablePatternOverrideSource + ); + const innerBlocksProps = { + ...props, + ...boundInnerBlocksProps, + boundInnerBlocks: editablePatternOverrideSource ?? false, + }; + const InnerBlocks = hasControlledInnerBlocks( innerBlocksProps ) + ? ControlledInnerBlocks + : UncontrolledInnerBlocks; + + return ; +} + +function hasControlledInnerBlocks( innerBlocksProps ) { + return ( + innerBlocksProps.value !== undefined && + innerBlocksProps.onChange !== undefined + ); +} + const ForwardedInnerBlocks = forwardRef( ( props, ref ) => { const innerBlocksProps = useInnerBlocksProps( { ref }, props ); return ( @@ -195,6 +257,8 @@ export function useInnerBlocksProps( props = {}, options = {} ) { ( select ) => { const { getBlockName, + getBlockAttributes, + getSettings, isZoomOut, getTemplateLock, getBlockRootClientId, @@ -220,6 +284,12 @@ export function useInnerBlocksProps( props = {}, options = {} ) { const blockEditingMode = getBlockEditingMode( clientId ); const parentClientId = getBlockRootClientId( clientId ); const [ defaultLayout ] = getBlockSettings( clientId, 'layout' ); + const innerBlocksBinding = getSettings().blockBindingsInnerBlocks + ? getInnerBlocksBinding( + getBlockAttributes( clientId ), + blockName + ) + : undefined; let _isDropZoneDisabled = blockEditingMode === 'disabled'; @@ -243,6 +313,7 @@ export function useInnerBlocksProps( props = {}, options = {} ) { parentClientId, isDropZoneDisabled: _isDropZoneDisabled, defaultLayout, + innerBlocksBinding, }; }, [ clientId ] @@ -255,6 +326,7 @@ export function useInnerBlocksProps( props = {}, options = {} ) { parentClientId, isDropZoneDisabled, defaultLayout, + innerBlocksBinding, } = selected; const blockDropZoneRef = useBlockDropZone( { @@ -281,11 +353,45 @@ export function useInnerBlocksProps( props = {}, options = {} ) { parentLock, defaultLayout, ...options, + // This marker is owned by BoundInnerBlocks and is never caller-controlled. + boundInnerBlocks: undefined, }; - const InnerBlocks = - innerBlocksProps.value && innerBlocksProps.onChange - ? ControlledInnerBlocks - : UncontrolledInnerBlocks; + const InnerBlocks = hasControlledInnerBlocks( innerBlocksProps ) + ? ControlledInnerBlocks + : UncontrolledInnerBlocks; + const hasCallerControlledProps = + options.value !== undefined || + options.onChange !== undefined || + options.onInput !== undefined; + if ( innerBlocksBinding && hasCallerControlledProps ) { + warning( + `The "innerBlocks" block binding to source "${ innerBlocksBinding.source }" is ignored because the block's inner blocks are already controlled through caller-supplied value/onChange props.` + ); + } + const bindingApplies = !! innerBlocksBinding && ! hasCallerControlledProps; + const [ wasBound, setWasBound ] = useState( bindingApplies ); + if ( bindingApplies && ! wasBound ) { + setWasBound( true ); + } + const shouldUseBoundInnerBlocks = + ! hasCallerControlledProps && ( innerBlocksBinding || wasBound ); + + let children; + if ( ! clientId ) { + children = ; + } else if ( shouldUseBoundInnerBlocks ) { + children = ( + + ); + } else { + children = ( + + ); + } return { ...props, @@ -295,11 +401,7 @@ export function useInnerBlocksProps( props = {}, options = {} ) { 'block-editor-block-list__layout', __unstableDisableLayoutClassNames ? '' : layoutClassNames ), - children: clientId ? ( - - ) : ( - - ), + children, }; } diff --git a/packages/block-editor/src/components/inner-blocks/test/use-bound-inner-blocks.js b/packages/block-editor/src/components/inner-blocks/test/use-bound-inner-blocks.js new file mode 100644 index 00000000000000..e929a3924ed36a --- /dev/null +++ b/packages/block-editor/src/components/inner-blocks/test/use-bound-inner-blocks.js @@ -0,0 +1,548 @@ +/** + * External dependencies + */ +import { act, render, renderHook, waitFor } from '@testing-library/react'; + +/** + * WordPress dependencies + */ +import { dispatch, select } from '@wordpress/data'; +import { RawHTML } from '@wordpress/element'; +import { + __unstableGetInnerBlocksProps as getInnerBlocksProps, + createBlock, + getBlockTypes, + registerBlockBindingsSource, + registerBlockType, + unregisterBlockBindingsSource, + unregisterBlockType, +} from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import { store as blockEditorStore } from '../../../store'; +import { useBoundInnerBlocksProps } from '../use-bound-inner-blocks'; +import { BlockContextProvider } from '../../block-context'; +import useBlockSync from '../../provider/use-block-sync'; + +const SOURCE_NAME = 'test/inner-blocks'; +const PARAGRAPH_MARKUP = + '

Bound paragraph

'; + +function SyncedInnerBlocks( props ) { + useBlockSync( props ); + return null; +} + +function BoundInnerBlocksController( { + clientId, + binding, + isPatternOverrideInstance = false, +} ) { + const props = useBoundInnerBlocksProps( + clientId, + binding, + undefined, + isPatternOverrideInstance + ); + return props ? ( + + ) : null; +} + +describe( 'useBoundInnerBlocksProps', () => { + let mountedHooks; + + beforeEach( () => { + mountedHooks = []; + registerBlockType( 'core/paragraph', { + apiVersion: 3, + category: 'text', + title: 'Paragraph', + attributes: { + content: { type: 'string', source: 'html', selector: 'p' }, + }, + save: ( { attributes } ) => ( +

+ { attributes.content } +

+ ), + } ); + registerBlockType( 'test/inner-host', { + apiVersion: 3, + category: 'text', + title: 'Inner host', + usesContext: [ 'test/host-context' ], + save: () => { + const { children } = getInnerBlocksProps(); + return
{ children }
; + }, + } ); + } ); + + afterEach( async () => { + await act( async () => { + mountedHooks.forEach( ( { unmount } ) => unmount() ); + dispatch( blockEditorStore ).resetBlocks( [] ); + } ); + unregisterBlockBindingsSource( SOURCE_NAME ); + getBlockTypes().forEach( ( blockType ) => { + unregisterBlockType( blockType.name ); + } ); + } ); + + function setupHost( binding ) { + const block = createBlock( + 'test/inner-host', + { metadata: { bindings: { innerBlocks: binding } } }, + [ + createBlock( 'core/paragraph', { + content: 'Fallback paragraph', + } ), + ] + ); + act( () => { + dispatch( blockEditorStore ).resetBlocks( [ block ] ); + } ); + return block.clientId; + } + + function renderBoundHook( clientId, binding, wrapper ) { + const view = renderHook( + () => useBoundInnerBlocksProps( clientId, binding ), + { wrapper } + ); + mountedHooks.push( view ); + return view; + } + + function renderBoundController( + clientId, + binding, + isPatternOverrideInstance = false + ) { + const view = render( + + ); + mountedHooks.push( view ); + return view; + } + + it( 'parses a serialized value from a registered source', () => { + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: PARAGRAPH_MARKUP } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME, args: { key: 'hero' } }; + const clientId = setupHost( binding ); + + const { result } = renderBoundHook( clientId, binding ); + + expect( result.current.value ).toHaveLength( 1 ); + expect( result.current.value[ 0 ].name ).toBe( 'core/paragraph' ); + expect( result.current.value[ 0 ].attributes.content ).toBe( + 'Bound paragraph' + ); + } ); + + it( 'treats an empty string as an intentionally empty controlled area', () => { + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: '' } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + + const { result } = renderBoundHook( clientId, binding ); + + expect( result.current.value ).toEqual( [] ); + } ); + + it( 'returns undefined when the source value is absent', () => { + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: undefined } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + + const { result } = renderBoundHook( clientId, binding ); + + expect( result.current ).toBeUndefined(); + } ); + + it( 'creates the first pattern override from fallback children', async () => { + const setValues = jest.fn(); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: undefined } ), + setValues, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + renderBoundController( clientId, binding, true ); + + await waitFor( () => + expect( + select( blockEditorStore ).areInnerBlocksControlled( clientId ) + ).toBe( true ) + ); + const [ child ] = select( blockEditorStore ).getBlocks( clientId ); + expect( child.attributes.content ).toBe( 'Fallback paragraph' ); + + act( () => { + dispatch( blockEditorStore ).updateBlockAttributes( + child.clientId, + { + content: 'First override', + } + ); + } ); + + await waitFor( () => expect( setValues ).toHaveBeenCalled() ); + expect( + setValues.mock.calls.at( -1 )[ 0 ].bindings.innerBlocks.newValue + ).toContain( 'First override' ); + } ); + + it( 'resets an existing pattern override to fallback without releasing control', async () => { + let sourceValue = PARAGRAPH_MARKUP; + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: sourceValue } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const view = renderBoundController( clientId, binding, true ); + + await waitFor( () => + expect( + select( blockEditorStore ).getBlocks( clientId )[ 0 ] + ?.attributes.content + ).toBe( 'Bound paragraph' ) + ); + + sourceValue = undefined; + view.rerender( + + ); + + await waitFor( () => + expect( + select( blockEditorStore ).getBlocks( clientId )[ 0 ] + ?.attributes.content + ).toBe( 'Fallback paragraph' ) + ); + expect( + select( blockEditorStore ).areInnerBlocksControlled( clientId ) + ).toBe( true ); + } ); + + it.each( [ null, 1, [], {} ] )( + 'treats a non-string source value as absent: %p', + ( sourceValue ) => { + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: sourceValue } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + + const { result } = renderBoundHook( clientId, binding ); + + expect( result.current ).toBeUndefined(); + } + ); + + it( 'normalizes malformed source arguments to absence', () => { + const getValues = jest.fn( () => ( { + innerBlocks: PARAGRAPH_MARKUP, + } ) ); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues, + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME, args: 'not-an-object' }; + const clientId = setupHost( binding ); + + renderBoundHook( clientId, binding ); + + expect( getValues ).toHaveBeenCalledWith( + expect.objectContaining( { + bindings: { innerBlocks: { args: undefined } }, + } ) + ); + } ); + + it( 'fails closed for a nonempty source without fallback children', () => { + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: PARAGRAPH_MARKUP } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const block = createBlock( 'test/inner-host', { + metadata: { bindings: { innerBlocks: binding } }, + } ); + act( () => { + dispatch( blockEditorStore ).resetBlocks( [ block ] ); + } ); + + const { result } = renderBoundHook( block.clientId, binding ); + + expect( result.current ).toBeUndefined(); + } ); + + it( 'writes serialized edits back to the source', () => { + const setValues = jest.fn(); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: PARAGRAPH_MARKUP } ), + setValues, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const { result } = renderBoundHook( clientId, binding ); + act( () => { + dispatch( blockEditorStore ).setHasControlledInnerBlocks( + clientId, + true + ); + } ); + const editedBlocks = [ + createBlock( 'core/paragraph', { content: 'Edited paragraph' } ), + ]; + + act( () => { + result.current.onChange( editedBlocks ); + } ); + + expect( setValues ).toHaveBeenCalledWith( + expect.objectContaining( { + clientId, + bindings: { + innerBlocks: expect.objectContaining( { + newValue: expect.stringContaining( 'Edited paragraph' ), + } ), + }, + } ) + ); + } ); + + it( 'drops writes after the host no longer owns controlled inner blocks', () => { + const setValues = jest.fn(); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: PARAGRAPH_MARKUP } ), + setValues, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const { result } = renderBoundHook( clientId, binding ); + + act( () => { + result.current.onChange( [ + createBlock( 'core/paragraph', { content: 'Stale edit' } ), + ] ); + } ); + + expect( setValues ).not.toHaveBeenCalled(); + } ); + + it( 'marks block-editor source writes as non-persistent only for input', () => { + const markNextChange = jest.spyOn( + dispatch( blockEditorStore ), + '__unstableMarkNextChangeAsNotPersistent' + ); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: PARAGRAPH_MARKUP } ), + setValues: ( { dispatch: sourceDispatch } ) => { + sourceDispatch( blockEditorStore ); + }, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const { result } = renderBoundHook( clientId, binding ); + act( () => { + dispatch( blockEditorStore ).setHasControlledInnerBlocks( + clientId, + true + ); + } ); + const editedBlocks = [ + createBlock( 'core/paragraph', { content: 'Edited paragraph' } ), + ]; + + act( () => { + result.current.onInput( editedBlocks ); + } ); + expect( markNextChange ).toHaveBeenCalledTimes( 1 ); + + markNextChange.mockClear(); + act( () => { + result.current.onChange( editedBlocks ); + } ); + expect( markNextChange ).not.toHaveBeenCalled(); + markNextChange.mockRestore(); + } ); + + it( 'keeps the same edited block mounted when the source echoes typing', async () => { + let sourceValue = PARAGRAPH_MARKUP; + const setValues = jest.fn( ( { bindings } ) => { + sourceValue = bindings.innerBlocks.newValue; + } ); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: sourceValue } ), + setValues, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const view = renderBoundController( clientId, binding ); + await waitFor( () => + expect( + select( blockEditorStore ).getBlocks( clientId )[ 0 ] + ?.attributes.content + ).toBe( 'Bound paragraph' ) + ); + const initialChild = + select( blockEditorStore ).getBlocks( clientId )[ 0 ]; + + act( () => { + dispatch( + blockEditorStore + ).__unstableMarkNextChangeAsNotPersistent(); + dispatch( blockEditorStore ).updateBlockAttributes( + initialChild.clientId, + { content: 'Typed paragraph' } + ); + } ); + view.rerender( + + ); + await waitFor( () => + expect( + select( blockEditorStore ).getBlocks( clientId )[ 0 ] + ?.attributes.content + ).toBe( 'Typed paragraph' ) + ); + + const echoedChild = + select( blockEditorStore ).getBlocks( clientId )[ 0 ]; + expect( setValues ).toHaveBeenCalled(); + expect( sourceValue ).toContain( 'Typed paragraph' ); + expect( echoedChild.clientId ).toBe( initialChild.clientId ); + expect( echoedChild.attributes.content ).toBe( 'Typed paragraph' ); + } ); + + it( 'keeps the current children when control is released', async () => { + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + getValues: () => ( { innerBlocks: PARAGRAPH_MARKUP } ), + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const view = renderBoundController( clientId, binding ); + await waitFor( () => + expect( + select( blockEditorStore ).getBlocks( clientId )[ 0 ] + ?.attributes.content + ).toBe( 'Bound paragraph' ) + ); + + expect( + select( blockEditorStore ).getBlocks( clientId )[ 0 ].attributes + .content + ).toBe( 'Bound paragraph' ); + + view.rerender( + + ); + await waitFor( () => + expect( + select( blockEditorStore ).areInnerBlocksControlled( clientId ) + ).toBe( false ) + ); + + const restoredBlocks = select( blockEditorStore ).getBlocks( clientId ); + expect( + select( blockEditorStore ).areInnerBlocksControlled( clientId ) + ).toBe( false ); + expect( restoredBlocks ).toHaveLength( 1 ); + expect( restoredBlocks[ 0 ].attributes.content ).toBe( + 'Bound paragraph' + ); + } ); + + it( 'passes host and source context to the source', () => { + const getValues = jest.fn( () => ( { + innerBlocks: PARAGRAPH_MARKUP, + } ) ); + registerBlockBindingsSource( { + name: SOURCE_NAME, + label: 'Test source', + usesContext: [ 'test/source-context' ], + getValues, + setValues: () => {}, + } ); + const binding = { source: SOURCE_NAME }; + const clientId = setupHost( binding ); + const wrapper = ( { children } ) => ( + + { children } + + ); + + renderBoundHook( clientId, binding, wrapper ); + + expect( getValues ).toHaveBeenCalledWith( + expect.objectContaining( { + context: { + 'test/host-context': 'host value', + 'test/source-context': 'source value', + }, + } ) + ); + } ); +} ); diff --git a/packages/block-editor/src/components/inner-blocks/use-bound-inner-blocks.js b/packages/block-editor/src/components/inner-blocks/use-bound-inner-blocks.js new file mode 100644 index 00000000000000..0d0cb8339aadbd --- /dev/null +++ b/packages/block-editor/src/components/inner-blocks/use-bound-inner-blocks.js @@ -0,0 +1,313 @@ +/** + * WordPress dependencies + */ +import { useSelect, useRegistry } from '@wordpress/data'; +import { parse, serialize, store as blocksStore } from '@wordpress/blocks'; +import { + useCallback, + useContext, + useEffect, + useLayoutEffect, + useMemo, + useRef, + useState, +} from '@wordpress/element'; + +/** + * Internal dependencies + */ +import { store as blockEditorStore } from '../../store'; +import BlockContext from '../block-context'; +import { + getBlockBindingsContext, + INNER_BLOCKS_BINDING_KEY, +} from '../../utils/block-bindings'; +import { unlock } from '../../lock-unlock'; + +const EMPTY_ARRAY = []; + +/** + * Resolves controlled InnerBlocks props from a structural binding. + * + * @param {string} clientId Host block client ID. + * @param {Object|undefined} binding Structural binding descriptor. + * @param {Object} blockType Host block type. + * @param {boolean} isPatternOverrideInstance Whether the host belongs to one synced-pattern instance. + * @return {Object|undefined} Controlled inner-block props. + */ +export function useBoundInnerBlocksProps( + clientId, + binding, + blockType, + isPatternOverrideInstance = false +) { + const registry = useRegistry(); + const blockContext = useContext( BlockContext ); + const appliedRef = useRef( { serialized: undefined, blocks: undefined } ); + + const sourceName = + typeof binding?.source === 'string' && binding.source !== '' + ? binding.source + : undefined; + const args = + sourceName && + binding?.args !== null && + typeof binding?.args === 'object' + ? binding.args + : undefined; + const source = useSelect( + ( select ) => + sourceName + ? unlock( select( blocksStore ) ).getBlockBindingsSource( + sourceName + ) + : undefined, + [ sourceName ] + ); + const resolvedBlockType = useSelect( + ( select ) => { + if ( blockType || ! clientId ) { + return blockType; + } + const blockName = + select( blockEditorStore ).getBlockName( clientId ); + return blockName + ? select( blocksStore ).getBlockType( blockName ) + : undefined; + }, + [ blockType, clientId ] + ); + const context = useMemo( + () => + getBlockBindingsContext( + blockContext, + resolvedBlockType?.usesContext, + [ source ] + ), + [ blockContext, resolvedBlockType, source ] + ); + const currentFallbackBlocks = useSelect( + ( select ) => { + if ( ! clientId ) { + return EMPTY_ARRAY; + } + return select( blockEditorStore ).getBlocks( clientId ); + }, + [ clientId ] + ); + // Keep the pattern entity's original children separate from the controlled + // instance tree. This lets absence render the fallback while the first edit + // creates an override, and lets Reset restore the original fallback. + const [ fallbackBlocks ] = useState( () => [ ...currentFallbackBlocks ] ); + const hasFallbackSlot = fallbackBlocks.length > 0; + const serialized = useSelect( + ( select ) => { + if ( ! source?.getValues ) { + return undefined; + } + const values = source.getValues( { + select, + context, + clientId, + bindings: { [ INNER_BLOCKS_BINDING_KEY ]: { args } }, + } ); + const value = values?.[ INNER_BLOCKS_BINDING_KEY ]; + return typeof value === 'string' ? value : undefined; + }, + [ source, context, clientId, args ] + ); + const value = useMemo( () => { + if ( serialized === undefined ) { + return isPatternOverrideInstance && hasFallbackSlot + ? fallbackBlocks + : undefined; + } + if ( serialized !== '' && ! hasFallbackSlot ) { + return undefined; + } + if ( appliedRef.current.serialized === serialized ) { + return appliedRef.current.blocks; + } + const blocks = serialized === '' ? EMPTY_ARRAY : parse( serialized ); + appliedRef.current = { serialized, blocks }; + return blocks; + }, [ + serialized, + hasFallbackSlot, + fallbackBlocks, + isPatternOverrideInstance, + ] ); + + const writeBack = useCallback( + ( blocks, persistent ) => { + if ( + clientId && + ! registry + .select( blockEditorStore ) + .areInnerBlocksControlled( clientId ) + ) { + return; + } + if ( ! source?.setValues ) { + return; + } + + const newValue = serialize( blocks ); + if ( ! persistent && newValue === appliedRef.current.serialized ) { + return; + } + appliedRef.current = { serialized: newValue, blocks }; + + registry.batch( () => { + const blockEditorDispatch = + registry.dispatch( blockEditorStore ); + const dispatch = persistent + ? registry.dispatch + : ( store ) => { + const actions = registry.dispatch( store ); + if ( actions === blockEditorDispatch ) { + blockEditorDispatch.__unstableMarkNextChangeAsNotPersistent(); + } + return actions; + }; + source.setValues( { + select: registry.select, + dispatch, + context, + clientId, + bindings: { + [ INNER_BLOCKS_BINDING_KEY ]: { args, newValue }, + }, + } ); + } ); + }, + [ source, registry, context, clientId, args ] + ); + const onChange = useCallback( + ( blocks ) => writeBack( blocks, true ), + [ writeBack ] + ); + const onInput = useCallback( + ( blocks ) => writeBack( blocks, false ), + [ writeBack ] + ); + const boundProps = useMemo( + () => + source && value !== undefined + ? { value, onChange, onInput } + : undefined, + [ source, value, onChange, onInput ] + ); + const editableClientIds = useSelect( + ( select ) => { + if ( ! boundProps || ! clientId || ! isPatternOverrideInstance ) { + return EMPTY_ARRAY; + } + + const blockEditor = select( blockEditorStore ); + if ( unlock( blockEditor ).isZoomOut() ) { + return EMPTY_ARRAY; + } + + return blockEditor + .getClientIdsOfDescendants( clientId ) + .filter( + ( id ) => + blockEditor.getBlockName( id ) !== 'core/block' && + blockEditor.getBlockParentsByBlockName( + id, + 'core/block', + true + ).length === 1 + ); + }, + [ boundProps, clientId, isPatternOverrideInstance ] + ); + const editingModeOwnershipRef = useRef( new Map() ); + useLayoutEffect( () => { + const blockEditorSelect = registry.select( blockEditorStore ); + const { getExplicitBlockEditingMode } = unlock( blockEditorSelect ); + const { setBlockEditingMode, unsetBlockEditingMode } = + registry.dispatch( blockEditorStore ); + const ownedModes = editingModeOwnershipRef.current; + const desiredClientIds = new Set( editableClientIds ); + + registry.batch( () => { + ownedModes.forEach( ( appliedMode, id ) => { + if ( getExplicitBlockEditingMode( id ) !== appliedMode ) { + ownedModes.delete( id ); + return; + } + if ( desiredClientIds.has( id ) ) { + return; + } + unsetBlockEditingMode( id ); + ownedModes.delete( id ); + } ); + + desiredClientIds.forEach( ( id ) => { + if ( + ownedModes.has( id ) || + getExplicitBlockEditingMode( id ) !== undefined + ) { + return; + } + setBlockEditingMode( id, 'default' ); + ownedModes.set( id, 'default' ); + } ); + } ); + }, [ editableClientIds, registry ] ); + useLayoutEffect( () => { + const ownedModes = editingModeOwnershipRef.current; + return () => { + const blockEditorSelect = registry.select( blockEditorStore ); + const { getExplicitBlockEditingMode } = unlock( blockEditorSelect ); + const { unsetBlockEditingMode } = + registry.dispatch( blockEditorStore ); + registry.batch( () => { + ownedModes.forEach( ( appliedMode, id ) => { + if ( getExplicitBlockEditingMode( id ) === appliedMode ) { + unsetBlockEditingMode( id ); + } + } ); + ownedModes.clear(); + } ); + }; + }, [ registry ] ); + + const wasControlledRef = useRef( false ); + const wasControlledLayoutRef = useRef( false ); + const releasedBlocksRef = useRef( EMPTY_ARRAY ); + useLayoutEffect( () => { + const isControlled = boundProps !== undefined; + if ( wasControlledLayoutRef.current && ! isControlled && clientId ) { + releasedBlocksRef.current = registry + .select( blockEditorStore ) + .getBlocks( clientId ); + } + wasControlledLayoutRef.current = isControlled; + } ); + useEffect( () => { + const isControlled = boundProps !== undefined; + if ( wasControlledRef.current && ! isControlled && clientId ) { + const restoreBlocks = releasedBlocksRef.current; + releasedBlocksRef.current = EMPTY_ARRAY; + if ( + restoreBlocks.length && + registry + .select( blockEditorStore ) + .getBlockCount( clientId ) === 0 + ) { + const { + replaceInnerBlocks, + __unstableMarkNextChangeAsNotPersistent, + } = registry.dispatch( blockEditorStore ); + __unstableMarkNextChangeAsNotPersistent(); + replaceInnerBlocks( clientId, restoreBlocks ); + } + } + wasControlledRef.current = isControlled; + } ); + + return boundProps; +} diff --git a/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js b/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js index 942c78977fca69..061f2a244cb678 100644 --- a/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js +++ b/packages/block-editor/src/components/inner-blocks/use-nested-settings-update.js @@ -11,6 +11,7 @@ import { isShallowEqual } from '@wordpress/is-shallow-equal'; */ import { store as blockEditorStore } from '../../store'; import { getLayoutType } from '../../layouts'; +import { BOUND_INNER_BLOCKS_SETTINGS_KEY } from '../../utils/block-bindings'; /** @typedef {import('../../selectors').WPDirectInsertBlock } WPDirectInsertBlock */ @@ -60,6 +61,7 @@ function useShallowMemo( value ) { * @param {string} orientation The direction in which the block * should face. * @param {Object} layout The layout object for the block container. + * @param {string|false} boundInnerBlocks Editable structural binding source, or false. */ export default function useNestedSettingsUpdate( clientId, @@ -73,7 +75,8 @@ export default function useNestedSettingsUpdate( templateLock, captureToolbars, orientation, - layout + layout, + boundInnerBlocks ) { // Instead of adding a useSelect mapping here, please add to the useSelect // mapping in InnerBlocks! Every subscription impacts performance. @@ -108,6 +111,10 @@ export default function useNestedSettingsUpdate( newSettings.__experimentalCaptureToolbars = captureToolbars; } + if ( boundInnerBlocks !== undefined ) { + newSettings[ BOUND_INNER_BLOCKS_SETTINGS_KEY ] = boundInnerBlocks; + } + // Orientation depends on layout, // ideally the separate orientation prop should be deprecated. if ( orientation !== undefined ) { @@ -184,6 +191,7 @@ export default function useNestedSettingsUpdate( captureToolbars, orientation, layout, + boundInnerBlocks, registry, ] ); } diff --git a/packages/block-editor/src/components/rich-text/index.js b/packages/block-editor/src/components/rich-text/index.js index c66f86ecebe04a..4589b2d8b92fa8 100644 --- a/packages/block-editor/src/components/rich-text/index.js +++ b/packages/block-editor/src/components/rich-text/index.js @@ -236,9 +236,28 @@ export function RichTextWrapper( const isInsidePatternOverrides = !! blockContext?.[ 'pattern/overrides' ]; const hasOverrideEnabled = blockBindings?.__default?.source === 'core/pattern-overrides'; + const isInsideEditableBoundInnerBlocks = useSelect( + ( select ) => { + if ( ! isInsidePatternOverrides || hasOverrideEnabled ) { + return false; + } + + const blockEditor = select( blockEditorStore ); + if ( ! blockEditor.getSettings().blockBindingsInnerBlocks ) { + return false; + } + + return unlock( blockEditor ).isWithinBoundInnerBlocks( + blockEditor.getBlockRootClientId( clientId ) + ); + }, + [ clientId, isInsidePatternOverrides, hasOverrideEnabled ] + ); const shouldDisableForPattern = - isInsidePatternOverrides && ! hasOverrideEnabled; + isInsidePatternOverrides && + ! hasOverrideEnabled && + ! isInsideEditableBoundInnerBlocks; const shouldDisableEditing = readOnly || disableBoundBlock || shouldDisableForPattern; diff --git a/packages/block-editor/src/private-apis.js b/packages/block-editor/src/private-apis.js index 906f2c4eed213c..8a47445e3824de 100644 --- a/packages/block-editor/src/private-apis.js +++ b/packages/block-editor/src/private-apis.js @@ -83,6 +83,7 @@ import { isHashLink, isRelativePath, } from './components/link-control/is-url-like'; +import { getInnerBlocksBinding } from './utils/block-bindings'; /** * Private @wordpress/block-editor APIs. @@ -157,4 +158,5 @@ lock( privateApis, { isHashLink, isRelativePath, InnerContent, + getInnerBlocksBinding, } ); diff --git a/packages/block-editor/src/store/private-selectors.js b/packages/block-editor/src/store/private-selectors.js index 8cb58d5dbabf97..0b8fb86517ee99 100644 --- a/packages/block-editor/src/store/private-selectors.js +++ b/packages/block-editor/src/store/private-selectors.js @@ -41,6 +41,7 @@ import { isIsolatedEditorKey, } from './private-keys'; import { BLOCK_VISIBILITY_VIEWPORTS } from '../components/block-visibility/constants'; +import { BOUND_INNER_BLOCKS_SETTINGS_KEY } from '../utils/block-bindings'; const { isContentBlock } = unlock( blocksPrivateApis ); const { getViewportBreakpoints } = unlock( globalStylesEnginePrivateApis ); @@ -84,6 +85,60 @@ export function getBlockWithoutAttributes( state, clientId ) { return state.blocks.byClientId.get( clientId ); } +/** + * Returns the editing mode explicitly owned by a block, before derived modes. + * + * @param {Object} state Global application state. + * @param {string} clientId Block client ID. + * @return {string|undefined} Explicitly assigned mode. + */ +export function getExplicitBlockEditingMode( state, clientId ) { + return state.blocks.blockEditingModes.get( clientId ); +} + +/** + * Returns whether a block-list root is inside the plugin-gated editable area + * of exactly one synced-pattern instance. + * + * @param {Object} state Global application state. + * @param {string} clientId Block-list root client ID. + * @return {boolean} Whether the block list belongs to the editable area. + */ +export function isWithinBoundInnerBlocks( state, clientId ) { + const isBoundRoot = + getBlockListSettings( state, clientId )?.[ + BOUND_INNER_BLOCKS_SETTINGS_KEY + ] === 'core/pattern-overrides'; + if ( + ! getSettings( state ).blockBindingsInnerBlocks || + ! clientId || + isZoomOut( state ) || + ( getBlockEditingMode( state, clientId ) === 'disabled' && + ! isBoundRoot ) + ) { + return false; + } + + let current = clientId; + let patternParentCount = 0; + let hasPatternOverrideArea = false; + while ( current ) { + if ( + getBlockListSettings( state, current )?.[ + BOUND_INNER_BLOCKS_SETTINGS_KEY + ] === 'core/pattern-overrides' + ) { + hasPatternOverrideArea = true; + } + if ( getBlockName( state, current ) === 'core/block' ) { + patternParentCount++; + } + current = state.blocks.parents.get( current ); + } + + return hasPatternOverrideArea && patternParentCount === 1; +} + /** * Returns true if all of the descendants of a block with the given client ID * have an editing mode of 'disabled', or false otherwise. diff --git a/packages/block-editor/src/store/selectors.js b/packages/block-editor/src/store/selectors.js index 511ee9183fc49a..59674de29b3d4c 100644 --- a/packages/block-editor/src/store/selectors.js +++ b/packages/block-editor/src/store/selectors.js @@ -45,6 +45,7 @@ import { isContainerInsertableToInContentOnlyMode, getClientIdWithClientIdsTree, getClientIdsTree, + isWithinBoundInnerBlocks, } from './private-selectors'; const { isContentBlock } = unlock( blocksPrivateApis ); @@ -1706,6 +1707,9 @@ const canInsertBlockTypeUnmemoized = ( ? rootClientId : getParentSectionBlock( state, rootClientId ); const isWithinSection = !! sectionClientId; + const isWithinBoundArea = + !! state.settings.blockBindingsInnerBlocks && + isWithinBoundInnerBlocks( state, rootClientId ); // Disabled containers reject all blocks, with one exception: within a // section, the default block (paragraph) is allowed through so it can @@ -1713,6 +1717,7 @@ const canInsertBlockTypeUnmemoized = ( // which conditionally permits it where a sibling paragraph exists. if ( blockEditingMode === 'disabled' && + ! isWithinBoundArea && ( ! isWithinSection || blockName !== getDefaultBlockName() ) ) { return false; @@ -1729,13 +1734,14 @@ const canInsertBlockTypeUnmemoized = ( // It shouldn't be possible to insert inside a section block unless in // some cases when the block is a content block. const isContentRoleBlock = isContentBlock( blockName ); - if ( isWithinSection && ! isContentRoleBlock ) { + if ( isWithinSection && ! isWithinBoundArea && ! isContentRoleBlock ) { return false; } // Don't allow insertion into synced patterns. if ( isWithinSection && + ! isWithinBoundArea && getBlockName( state, sectionClientId ) === 'core/block' ) { return false; @@ -1755,6 +1761,7 @@ const canInsertBlockTypeUnmemoized = ( */ if ( isWithinSection && + ! isWithinBoundArea && ( isParentSectionBlock || blockEditingMode === 'contentOnly' || blockEditingMode === 'disabled' ) && @@ -1966,16 +1973,20 @@ export function canRemoveBlock( state, clientId ) { ? rootClientId : getParentSectionBlock( state, rootClientId ); const isWithinSection = !! sectionClientId; + const isWithinBoundArea = + !! state.settings.blockBindingsInnerBlocks && + isWithinBoundInnerBlocks( state, rootClientId ); const isContentRoleBlock = isContentBlock( getBlockName( state, clientId ) ); - if ( isWithinSection && ! isContentRoleBlock ) { + if ( isWithinSection && ! isWithinBoundArea && ! isContentRoleBlock ) { return false; } // Disallow removal from synced patterns. if ( isWithinSection && + ! isWithinBoundArea && getBlockName( state, sectionClientId ) === 'core/block' ) { return false; @@ -1992,6 +2003,7 @@ export function canRemoveBlock( state, clientId ) { // their *children*. if ( isWithinSection && + ! isWithinBoundArea && ( isParentSectionBlock || blockName === defaultBlockName || rootBlockEditingMode === 'contentOnly' ) && @@ -2017,7 +2029,7 @@ export function canRemoveBlock( state, clientId ) { return false; } - return rootBlockEditingMode !== 'disabled'; + return isWithinBoundArea || rootBlockEditingMode !== 'disabled'; } /** @@ -2069,10 +2081,13 @@ export function canMoveBlock( state, clientId ) { } const isBlockWithinSection = !! getParentSectionBlock( state, clientId ); + const isWithinBoundArea = + !! state.settings.blockBindingsInnerBlocks && + isWithinBoundInnerBlocks( state, rootClientId ); const isContentRoleBlock = isContentBlock( getBlockName( state, clientId ) ); - if ( isBlockWithinSection && ! isContentRoleBlock ) { + if ( isBlockWithinSection && ! isWithinBoundArea && ! isContentRoleBlock ) { return false; } @@ -2086,6 +2101,7 @@ export function canMoveBlock( state, clientId ) { const rootBlockEditingMode = getBlockEditingMode( state, rootClientId ); if ( isBlockWithinSection && + ! isWithinBoundArea && ( isParentSectionBlock || rootBlockEditingMode === 'contentOnly' ) && ! isContainerInsertableToInContentOnlyMode( state, @@ -2096,7 +2112,10 @@ export function canMoveBlock( state, clientId ) { return false; } - return getBlockEditingMode( state, rootClientId ) !== 'disabled'; + return ( + isWithinBoundArea || + getBlockEditingMode( state, rootClientId ) !== 'disabled' + ); } /** diff --git a/packages/block-editor/src/store/test/private-selectors.js b/packages/block-editor/src/store/test/private-selectors.js index eee15435e8cc44..88ccb36dea798f 100644 --- a/packages/block-editor/src/store/test/private-selectors.js +++ b/packages/block-editor/src/store/test/private-selectors.js @@ -29,11 +29,90 @@ import { hasSelectedStyleState, isSelectedBlockStyleStateShownOnCanvas, shouldRenderBlockListView, + isWithinBoundInnerBlocks, } from '../private-selectors'; import { getBlockEditingMode } from '../selectors'; import { deviceTypeKey } from '../private-keys'; +import { BOUND_INNER_BLOCKS_SETTINGS_KEY } from '../../utils/block-bindings'; describe( 'private selectors', () => { + describe( 'isWithinBoundInnerBlocks', () => { + const createState = () => ( { + blocks: { + byClientId: new Map( [ + [ 'pattern', { name: 'core/block' } ], + [ 'container', { name: 'core/group' } ], + [ 'child', { name: 'core/paragraph' } ], + ] ), + parents: new Map( [ + [ 'pattern', '' ], + [ 'container', 'pattern' ], + [ 'child', 'container' ], + ] ), + blockEditingModes: new Map(), + }, + blockListSettings: new Map( [ + [ + 'container', + { + [ BOUND_INNER_BLOCKS_SETTINGS_KEY ]: + 'core/pattern-overrides', + }, + ], + ] ), + settings: { blockBindingsInnerBlocks: true }, + derivedBlockEditingModes: new Map(), + } ); + + it( 'recognizes only the gated editable area of one synced pattern', () => { + const state = createState(); + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( true ); + + state.settings.blockBindingsInnerBlocks = false; + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( false ); + state.settings.blockBindingsInnerBlocks = true; + + state.blockListSettings.set( 'container', { + [ BOUND_INNER_BLOCKS_SETTINGS_KEY ]: 'plugin/source', + } ); + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( false ); + + state.blockListSettings.set( 'container', { + [ BOUND_INNER_BLOCKS_SETTINGS_KEY ]: 'core/pattern-overrides', + } ); + state.blocks.byClientId.set( 'pattern', { name: 'core/group' } ); + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( false ); + } ); + + it( 'allows the disabled bound root while keeping disabled descendants protected', () => { + const state = createState(); + state.derivedBlockEditingModes.set( 'container', 'disabled' ); + expect( isWithinBoundInnerBlocks( state, 'container' ) ).toBe( + true + ); + state.derivedBlockEditingModes.delete( 'container' ); + + state.derivedBlockEditingModes.set( 'child', 'disabled' ); + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( false ); + state.derivedBlockEditingModes.delete( 'child' ); + } ); + + it( 'keeps zoomed and nested pattern descendants protected', () => { + const state = createState(); + + state.zoomLevel = 80; + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( false ); + state.zoomLevel = 100; + + state.blocks.byClientId.set( 'nested-pattern', { + name: 'core/block', + } ); + state.blocks.parents.set( 'nested-pattern', 'container' ); + state.blocks.parents.set( 'child', 'nested-pattern' ); + expect( isWithinBoundInnerBlocks( state, 'child' ) ).toBe( false ); + } ); + } ); + describe( 'isBlockInterfaceHidden', () => { it( 'should return the true if toggled true in state', () => { const state = { diff --git a/packages/block-editor/src/store/test/selectors.js b/packages/block-editor/src/store/test/selectors.js index 017099630c9b39..b67b29912d0652 100644 --- a/packages/block-editor/src/store/test/selectors.js +++ b/packages/block-editor/src/store/test/selectors.js @@ -21,6 +21,7 @@ import * as selectors from '../selectors'; import { store } from '../'; import { lock } from '../../lock-unlock'; import { sectionRootClientIdKey } from '../private-keys'; +import { BOUND_INNER_BLOCKS_SETTINGS_KEY } from '../../utils/block-bindings'; const { getBlockName, @@ -2693,6 +2694,76 @@ describe( 'selectors', () => { } ); describe( 'canInsertBlockType', () => { + it( 'allows structural editing inside a live plugin-gated bound area', () => { + const state = { + blocks: { + byClientId: new Map( [ + [ 'pattern', { name: 'core/block' } ], + [ 'container', { name: 'core/test-block-a' } ], + [ 'child', { name: 'core/test-block-b' } ], + ] ), + attributes: new Map( [ + [ 'pattern', {} ], + [ 'container', {} ], + [ 'child', {} ], + ] ), + parents: new Map( [ + [ 'pattern', '' ], + [ 'container', 'pattern' ], + [ 'child', 'container' ], + ] ), + order: new Map( [ + [ '', [ 'pattern' ] ], + [ 'pattern', [ 'container' ] ], + [ 'container', [ 'child' ] ], + ] ), + blockEditingModes: new Map( [ + [ 'container', 'disabled' ], + ] ), + }, + blockListSettings: new Map( [ + [ 'pattern', {} ], + [ + 'container', + { + [ BOUND_INNER_BLOCKS_SETTINGS_KEY ]: + 'core/pattern-overrides', + }, + ], + ] ), + settings: { + blockBindingsInnerBlocks: true, + [ sectionRootClientIdKey ]: '', + }, + derivedBlockEditingModes: new Map( [ + [ 'container', 'disabled' ], + ] ), + }; + + expect( + canInsertBlockType( state, 'core/test-block-a', 'container' ) + ).toBe( true ); + expect( canRemoveBlock( state, 'child' ) ).toBe( true ); + expect( canMoveBlock( state, 'child' ) ).toBe( true ); + + const coreState = { + ...state, + settings: { + ...state.settings, + blockBindingsInnerBlocks: false, + }, + }; + expect( + canInsertBlockType( + coreState, + 'core/test-block-a', + 'container' + ) + ).toBe( false ); + expect( canRemoveBlock( coreState, 'child' ) ).toBe( false ); + expect( canMoveBlock( coreState, 'child' ) ).toBe( false ); + } ); + it( 'should deny blocks that are not registered', () => { const state = { blocks: { diff --git a/packages/block-editor/src/store/utils.js b/packages/block-editor/src/store/utils.js index 542c0bdb26d83d..fac4db353941ee 100644 --- a/packages/block-editor/src/store/utils.js +++ b/packages/block-editor/src/store/utils.js @@ -17,6 +17,7 @@ import { getSectionRootClientId, isSectionBlock, getParentSectionBlock, + isWithinBoundInnerBlocks, } from './private-selectors'; import { getBlockEditingMode } from './selectors'; import { INSERTER_PATTERN_TYPES } from '../components/inserter/block-patterns-tab/utils'; @@ -141,6 +142,8 @@ export const getAllPatternsDependants = ( select ) => ( state ) => { }; export const getInsertBlockTypeDependants = () => ( state, rootClientId ) => { + const innerBlocksBindingsEnabled = + !! state.settings.blockBindingsInnerBlocks; return [ state.blockListSettings.get( rootClientId ), state.blocks.byClientId.get( rootClientId ), @@ -151,5 +154,9 @@ export const getInsertBlockTypeDependants = () => ( state, rootClientId ) => { getSectionRootClientId( state ), isSectionBlock( state, rootClientId ), getParentSectionBlock( state, rootClientId ), + innerBlocksBindingsEnabled, + innerBlocksBindingsEnabled + ? isWithinBoundInnerBlocks( state, rootClientId ) + : false, ]; }; diff --git a/packages/block-editor/src/utils/block-bindings.ts b/packages/block-editor/src/utils/block-bindings.ts index abf5cd9da93805..0ba39224f06573 100644 --- a/packages/block-editor/src/utils/block-bindings.ts +++ b/packages/block-editor/src/utils/block-bindings.ts @@ -1,6 +1,10 @@ type Binding = { source?: string }; type Bindings = Record< string, Binding >; type BlockBindingsSource = { usesContext?: readonly string[] }; +type InnerBlocksBinding = { + source: string; + args?: Record< string, unknown >; +}; const DEFAULT_ATTRIBUTE = '__default'; const PATTERN_OVERRIDES_SOURCE = 'core/pattern-overrides'; @@ -54,6 +58,43 @@ export function getBlockBindingsContext( return context ?? EMPTY_CONTEXT; } +/** + * Reserved binding key for a block's structural InnerBlocks area. Its value is + * serialized block markup; `undefined`/`null` falls back to the block's own + * inner blocks and `''` represents an intentionally empty area. + */ +export const INNER_BLOCKS_BINDING_KEY = 'innerBlocks'; + +/** + * Private block-list setting that marks an editable pattern-overrides area. + */ +export const BOUND_INNER_BLOCKS_SETTINGS_KEY = 'boundInnerBlocks'; + +/** + * Gets a usable structural binding descriptor from block attributes. + * + * The private experiment is restricted to pattern overrides on Core blocks. + * `core/html` owns several interleaved editable areas rather than one ordinary + * InnerBlocks area, so it is excluded until it has a separate contract. + * + * @param attributes Block attributes. + * @param blockName Block name. + * @return Structural binding descriptor, if present. + */ +export function getInnerBlocksBinding( + attributes: Record< string, any > | undefined, + blockName: string | undefined +): InnerBlocksBinding | undefined { + if ( ! blockName?.startsWith( 'core/' ) || blockName === 'core/html' ) { + return undefined; + } + + const binding = + attributes?.metadata?.bindings?.[ INNER_BLOCKS_BINDING_KEY ]; + + return binding?.source === PATTERN_OVERRIDES_SOURCE ? binding : undefined; +} + /** * Checks if the block has the `__default` binding for pattern overrides. * diff --git a/packages/block-editor/src/utils/test/block-bindings.js b/packages/block-editor/src/utils/test/block-bindings.js index 6d061b853702bc..f4e1ec3fcd6846 100644 --- a/packages/block-editor/src/utils/test/block-bindings.js +++ b/packages/block-editor/src/utils/test/block-bindings.js @@ -3,10 +3,77 @@ */ import { getBlockBindingsContext, + getInnerBlocksBinding, hasPatternOverridesDefaultBinding, replacePatternOverridesDefaultBinding, } from '../block-bindings'; +describe( 'getInnerBlocksBinding', () => { + it( 'returns a pattern-overrides structural binding on a Core host', () => { + expect( + getInnerBlocksBinding( + { + metadata: { + bindings: { + innerBlocks: { + source: 'core/pattern-overrides', + args: { key: 'value' }, + }, + }, + }, + }, + 'core/group' + ) + ).toEqual( { + source: 'core/pattern-overrides', + args: { key: 'value' }, + } ); + } ); + + it( 'ignores missing or malformed descriptors', () => { + expect( getInnerBlocksBinding( {}, 'core/group' ) ).toBeUndefined(); + expect( + getInnerBlocksBinding( + { metadata: { bindings: { innerBlocks: { source: '' } } } }, + 'core/group' + ) + ).toBeUndefined(); + } ); + + it( 'excludes core/html until it has a single-area contract', () => { + expect( + getInnerBlocksBinding( + { + metadata: { + bindings: { + innerBlocks: { + source: 'core/pattern-overrides', + }, + }, + }, + }, + 'core/html' + ) + ).toBeUndefined(); + } ); + + it.each( [ + [ 'a custom source', 'core/group', 'test/source' ], + [ 'a custom host', 'test/container', 'core/pattern-overrides' ], + ] )( 'excludes %s', ( _description, blockName, source ) => { + expect( + getInnerBlocksBinding( + { + metadata: { + bindings: { innerBlocks: { source } }, + }, + }, + blockName + ) + ).toBeUndefined(); + } ); +} ); + describe( 'hasPatternOverridesDefaultBinding', () => { it( 'returns true when the `__default` binding targets pattern overrides', () => { expect( diff --git a/packages/block-library/src/block/edit.js b/packages/block-library/src/block/edit.js index 05dffdc38321ea..488faf9a2e31d4 100644 --- a/packages/block-library/src/block/edit.js +++ b/packages/block-library/src/block/edit.js @@ -38,8 +38,11 @@ import { getBlockBindingsSource } from '@wordpress/blocks'; * Internal dependencies */ import { unlock } from '../lock-unlock'; +import hasOverridablePatternBlocks from '../utils/has-overridable-pattern-blocks'; -const { useLayoutClasses } = unlock( blockEditorPrivateApis ); +const { getInnerBlocksBinding, useLayoutClasses } = unlock( + blockEditorPrivateApis +); const { isOverridableBlock } = unlock( patternsPrivateApis ); const fullAlignments = [ 'full', 'wide', 'left', 'right' ]; @@ -174,6 +177,7 @@ function ReusableBlockEdit( { onNavigateToEntityRecord, hasPatternOverridesSource, supportedBlockTypesRaw, + blockBindingsInnerBlocks, } = useSelect( ( select ) => { const { getSettings } = select( blockEditorStore ); // For editing link to the site editor if the theme and user permissions support it. @@ -185,23 +189,27 @@ function ReusableBlockEdit( { supportedBlockTypesRaw: getSettings().__experimentalBlockBindingsSupportedAttributes || EMPTY_OBJECT, + blockBindingsInnerBlocks: !! getSettings().blockBindingsInnerBlocks, }; }, [] ); const canOverrideBlocks = useMemo( () => { const supportedBlockTypes = Object.keys( supportedBlockTypesRaw ); - const hasOverridableBlocks = ( _blocks ) => - _blocks.some( ( block ) => { - if ( - supportedBlockTypes.includes( block.name ) && - isOverridableBlock( block ) - ) { - return true; - } - return hasOverridableBlocks( block.innerBlocks ); - } ); - return hasPatternOverridesSource && hasOverridableBlocks( blocks ); - }, [ hasPatternOverridesSource, blocks, supportedBlockTypesRaw ] ); + return ( + hasPatternOverridesSource && + hasOverridablePatternBlocks( blocks, { + innerBlocks: blockBindingsInnerBlocks, + getBinding: getInnerBlocksBinding, + isOverridable: isOverridableBlock, + supportedTypes: supportedBlockTypes, + } ) + ); + }, [ + hasPatternOverridesSource, + blocks, + supportedBlockTypesRaw, + blockBindingsInnerBlocks, + ] ); const { alignment, layout } = useInferredLayout( blocks, parentLayout ); const layoutClasses = useLayoutClasses( { layout }, name ); diff --git a/packages/block-library/src/utils/has-overridable-pattern-blocks.js b/packages/block-library/src/utils/has-overridable-pattern-blocks.js new file mode 100644 index 00000000000000..d744db7a86f1cd --- /dev/null +++ b/packages/block-library/src/utils/has-overridable-pattern-blocks.js @@ -0,0 +1,33 @@ +/** + * Returns whether a synced pattern contains content that its instance can + * override. Structural bindings are considered only while the private + * inner-blocks feature is enabled, and only named pattern-overrides areas + * participate in core/block's Reset action. + * + * @param {Object[]} blocks Pattern blocks. + * @param {Object} options Detection dependencies. + * @return {boolean} Whether the pattern contains overridable content. + */ +export default function hasOverridablePatternBlocks( blocks, options ) { + const { innerBlocks, getBinding, isOverridable, supportedTypes } = options; + return blocks.some( ( block ) => { + if ( + innerBlocks && + typeof block.attributes?.metadata?.name === 'string' && + block.attributes.metadata.name !== '' && + getBinding( block.attributes, block.name )?.source === + 'core/pattern-overrides' + ) { + return true; + } + if ( supportedTypes.includes( block.name ) && isOverridable( block ) ) { + return true; + } + return hasOverridablePatternBlocks( block.innerBlocks, { + innerBlocks, + getBinding, + isOverridable, + supportedTypes, + } ); + } ); +} diff --git a/packages/block-library/src/utils/test/has-overridable-pattern-blocks.js b/packages/block-library/src/utils/test/has-overridable-pattern-blocks.js new file mode 100644 index 00000000000000..2fa2c2b90e341f --- /dev/null +++ b/packages/block-library/src/utils/test/has-overridable-pattern-blocks.js @@ -0,0 +1,111 @@ +/** + * Internal dependencies + */ +import hasOverridablePatternBlocks from '../has-overridable-pattern-blocks'; + +const getBinding = ( attributes, blockName ) => + blockName === 'core/html' + ? undefined + : attributes?.metadata?.bindings?.innerBlocks; + +describe( 'hasOverridablePatternBlocks', () => { + const structuralBlock = { + name: 'core/group', + attributes: { + metadata: { + name: 'Free area', + bindings: { + innerBlocks: { source: 'core/pattern-overrides' }, + }, + }, + }, + innerBlocks: [], + }; + const options = { + innerBlocks: true, + getBinding, + isOverridable: () => false, + supportedTypes: [], + }; + + it( 'finds a structural-only pattern override', () => { + expect( + hasOverridablePatternBlocks( [ structuralBlock ], options ) + ).toBe( true ); + } ); + + it( 'keeps structural detection inert without the plugin setting', () => { + expect( + hasOverridablePatternBlocks( [ structuralBlock ], { + ...options, + innerBlocks: false, + } ) + ).toBe( false ); + } ); + + it( 'preserves attribute-based detection without the plugin setting', () => { + expect( + hasOverridablePatternBlocks( + [ + { + name: 'core/paragraph', + attributes: {}, + innerBlocks: [], + }, + ], + { + ...options, + innerBlocks: false, + isOverridable: () => true, + supportedTypes: [ 'core/paragraph' ], + } + ) + ).toBe( true ); + } ); + + it.each( [ + [ 'another source', 'plugin/custom-source', 'Free area', 'core/group' ], + [ + 'an unnamed area', + 'core/pattern-overrides', + undefined, + 'core/group', + ], + [ 'core/html', 'core/pattern-overrides', 'Free area', 'core/html' ], + ] )( 'ignores %s', ( _label, source, name, blockName ) => { + expect( + hasOverridablePatternBlocks( + [ + { + ...structuralBlock, + name: blockName, + attributes: { + metadata: { + name, + bindings: { + innerBlocks: { source }, + }, + }, + }, + }, + ], + options + ) + ).toBe( false ); + } ); + + it( 'finds structural bindings nested in the pattern', () => { + expect( + hasOverridablePatternBlocks( + [ + { + name: 'core/group', + attributes: {}, + innerBlocks: [ structuralBlock ], + }, + ], + options + ) + ).toBe( true ); + } ); +} ); diff --git a/packages/editor/src/bindings/pattern-overrides.js b/packages/editor/src/bindings/pattern-overrides.js index ee1929b36d144d..e009148bf02014 100644 --- a/packages/editor/src/bindings/pattern-overrides.js +++ b/packages/editor/src/bindings/pattern-overrides.js @@ -4,6 +4,7 @@ import { store as blockEditorStore } from '@wordpress/block-editor'; const CONTENT = 'content'; +const INNER_BLOCKS = 'innerBlocks'; /** * @type {WPBlockBindingsSource} @@ -12,8 +13,9 @@ export default { name: 'core/pattern-overrides', getValues( { select, clientId, context, bindings } ) { const patternOverridesContent = context[ 'pattern/overrides' ]; - const { getBlockAttributes } = select( blockEditorStore ); + const { getBlockAttributes, getSettings } = select( blockEditorStore ); const currentBlockAttributes = getBlockAttributes( clientId ); + const supportsInnerBlocks = !! getSettings?.().blockBindingsInnerBlocks; const overridesValues = {}; for ( const attributeName of Object.keys( bindings ) ) { @@ -26,20 +28,32 @@ export default { // Check undefined because empty string is a valid value. if ( overridableValue === undefined ) { overridesValues[ attributeName ] = - currentBlockAttributes?.[ attributeName ]; + supportsInnerBlocks && attributeName === INNER_BLOCKS + ? undefined + : currentBlockAttributes?.[ attributeName ]; + continue; + } + if ( + overridableValue === '' && + ( ! supportsInnerBlocks || attributeName !== INNER_BLOCKS ) + ) { + overridesValues[ attributeName ] = undefined; continue; - } else { - overridesValues[ attributeName ] = - overridableValue === '' ? undefined : overridableValue; } + overridesValues[ attributeName ] = overridableValue; } return overridesValues; }, setValues( { select, dispatch, clientId, bindings } ) { - const { getBlockAttributes, getBlockParentsByBlockName, getBlocks } = - select( blockEditorStore ); + const { + getBlockAttributes, + getBlockParentsByBlockName, + getBlocks, + getSettings, + } = select( blockEditorStore ); const currentBlockAttributes = getBlockAttributes( clientId ); const blockName = currentBlockAttributes?.metadata?.name; + const supportsInnerBlocks = !! getSettings?.().blockBindingsInnerBlocks; if ( ! blockName ) { return; } @@ -61,12 +75,19 @@ export default { // If there is no pattern client ID, sync blocks with the same name and same attributes. if ( ! patternClientId ) { + const attributeValues = { ...attributes }; + if ( supportsInnerBlocks ) { + delete attributeValues[ INNER_BLOCKS ]; + } + if ( Object.keys( attributeValues ).length === 0 ) { + return; + } const syncBlocksWithSameName = ( blocks ) => { for ( const block of blocks ) { if ( block.attributes?.metadata?.name === blockName ) { dispatch( blockEditorStore ).updateBlockAttributes( block.clientId, - attributes + attributeValues ); } syncBlocksWithSameName( block.innerBlocks ); diff --git a/packages/editor/src/bindings/test/pattern-overrides.js b/packages/editor/src/bindings/test/pattern-overrides.js index c64ea9b12f7798..0733c732644b50 100644 --- a/packages/editor/src/bindings/test/pattern-overrides.js +++ b/packages/editor/src/bindings/test/pattern-overrides.js @@ -14,9 +14,12 @@ describe( 'pattern-overrides bindings', () => { }, }; - const makeSelect = ( attributes ) => () => ( { - getBlockAttributes: () => attributes, - } ); + const makeSelect = + ( attributes, settings = {} ) => + () => ( { + getBlockAttributes: () => attributes, + getSettings: () => settings, + } ); describe( 'getValues', () => { it( 'returns the current attribute value when there is no override', () => { @@ -49,6 +52,25 @@ describe( 'pattern-overrides bindings', () => { expect( values ).toEqual( { content: 'overridden' } ); } ); + it( 'keeps the existing empty-string sentinel for attributes', () => { + const values = patternOverridesBindings.getValues( { + select: makeSelect( blockAttributes, { + blockBindingsInnerBlocks: true, + } ), + clientId: 'block-1', + context: { + 'pattern/overrides': { + 'Editable Paragraph': { content: '' }, + }, + }, + bindings: { + content: { source: 'core/pattern-overrides' }, + }, + } ); + + expect( values ).toEqual( { content: undefined } ); + } ); + it( 'does not throw when block attributes are unavailable', () => { expect( () => patternOverridesBindings.getValues( { @@ -61,5 +83,159 @@ describe( 'pattern-overrides bindings', () => { } ) ).not.toThrow(); } ); + + it( 'keeps an empty structural override as an intentional value', () => { + const values = patternOverridesBindings.getValues( { + select: makeSelect( blockAttributes, { + blockBindingsInnerBlocks: true, + } ), + clientId: 'block-1', + context: { + 'pattern/overrides': { + 'Editable Paragraph': { innerBlocks: '' }, + }, + }, + bindings: { + innerBlocks: { source: 'core/pattern-overrides' }, + }, + } ); + + expect( values ).toEqual( { innerBlocks: '' } ); + } ); + + it( 'returns structural absence instead of looking for an attribute fallback', () => { + const values = patternOverridesBindings.getValues( { + select: makeSelect( + { + ...blockAttributes, + innerBlocks: 'not structural children', + }, + { blockBindingsInnerBlocks: true } + ), + clientId: 'block-1', + context: {}, + bindings: { + innerBlocks: { source: 'core/pattern-overrides' }, + }, + } ); + + expect( values ).toEqual( { innerBlocks: undefined } ); + } ); + } ); + + describe( 'setValues', () => { + const makeSetValuesSelect = + ( { + patternClientId = 'pattern-1', + patternContent = {}, + settings = { blockBindingsInnerBlocks: true }, + blocks = [], + } = {} ) => + () => ( { + getBlockAttributes: ( clientId ) => + clientId === 'block-1' + ? blockAttributes + : { content: patternContent }, + getBlockParentsByBlockName: () => + patternClientId ? [ patternClientId ] : [], + getBlocks: () => blocks, + getSettings: () => settings, + } ); + + it( 'stores serialized inner blocks on the pattern instance', () => { + const updateBlockAttributes = jest.fn(); + const markup = + '

Override

'; + + patternOverridesBindings.setValues( { + select: makeSetValuesSelect( { + patternContent: { + 'Editable Paragraph': { content: 'Existing' }, + }, + } ), + dispatch: () => ( { updateBlockAttributes } ), + clientId: 'block-1', + bindings: { innerBlocks: { newValue: markup } }, + } ); + + expect( updateBlockAttributes ).toHaveBeenCalledWith( 'pattern-1', { + content: { + 'Editable Paragraph': { + content: 'Existing', + innerBlocks: markup, + }, + }, + } ); + } ); + + it( 'keeps an intentionally empty structural value when writing', () => { + const updateBlockAttributes = jest.fn(); + + patternOverridesBindings.setValues( { + select: makeSetValuesSelect(), + dispatch: () => ( { updateBlockAttributes } ), + clientId: 'block-1', + bindings: { innerBlocks: { newValue: '' } }, + } ); + + expect( updateBlockAttributes ).toHaveBeenCalledWith( 'pattern-1', { + content: { + 'Editable Paragraph': { innerBlocks: '' }, + }, + } ); + } ); + + it( 'does not treat inner blocks as an attribute outside a pattern instance', () => { + const updateBlockAttributes = jest.fn(); + + patternOverridesBindings.setValues( { + select: makeSetValuesSelect( { + patternClientId: null, + blocks: [ + { + clientId: 'matching-block', + attributes: blockAttributes, + innerBlocks: [], + }, + ], + } ), + dispatch: () => ( { updateBlockAttributes } ), + clientId: 'block-1', + bindings: { + content: { newValue: 'Updated' }, + innerBlocks: { newValue: '' }, + }, + } ); + + expect( updateBlockAttributes ).toHaveBeenCalledTimes( 1 ); + expect( updateBlockAttributes ).toHaveBeenCalledWith( + 'matching-block', + { content: 'Updated' } + ); + } ); + + it( 'does nothing for a structural-only write outside a pattern instance', () => { + const updateBlockAttributes = jest.fn(); + + patternOverridesBindings.setValues( { + select: makeSetValuesSelect( { + patternClientId: null, + blocks: [ + { + clientId: 'matching-block', + attributes: blockAttributes, + innerBlocks: [], + }, + ], + } ), + dispatch: () => ( { updateBlockAttributes } ), + clientId: 'block-1', + bindings: { + innerBlocks: { newValue: '' }, + }, + } ); + + expect( updateBlockAttributes ).not.toHaveBeenCalled(); + } ); } ); } ); diff --git a/packages/editor/src/components/provider/use-block-editor-settings.js b/packages/editor/src/components/provider/use-block-editor-settings.js index db85f17fa07d8c..bae4897fae656b 100644 --- a/packages/editor/src/components/provider/use-block-editor-settings.js +++ b/packages/editor/src/components/provider/use-block-editor-settings.js @@ -59,6 +59,7 @@ const BLOCK_EDITOR_SETTINGS = [ 'allImageSizes', 'alignWide', 'blockInspectorTabs', + 'blockBindingsInnerBlocks', 'maxUploadFileSize', 'allowedMimeTypes', 'bodyPlaceholder',