Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Block editor: new blockEditor.useBlockProps filter #48884

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 92 additions & 8 deletions packages/block-editor/src/components/block-list/index.js
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ import {
} from '@wordpress/compose'; } from '@wordpress/compose';
import { import {
createContext, createContext,
useState,
useMemo, useMemo,
useCallback, useCallback,
useLayoutEffect,
useContext,
useRef,
useReducer,
useId,
} from '@wordpress/element'; } from '@wordpress/element';


/** /**
Expand All @@ -41,13 +45,92 @@ import {
DEFAULT_BLOCK_EDIT_CONTEXT, DEFAULT_BLOCK_EDIT_CONTEXT,
} from '../block-edit/context'; } from '../block-edit/context';


const elementContext = createContext(); const componentsContext = createContext( { render() {}, unmount() {} } );


export const IntersectionObserver = createContext(); export const IntersectionObserver = createContext();
const pendingBlockVisibilityUpdatesPerRegistry = new WeakMap(); const pendingBlockVisibilityUpdatesPerRegistry = new WeakMap();


function useRootPortal( component ) {
const components = useContext( componentsContext );
const id = useId();

// Run every time the component rerenders.
useLayoutEffect( () => {
if ( component ) {
components.render( id, component );
} else {
components.unmount( id );
}
}, [ components, id, component ] );

// Run only on unmount.
useLayoutEffect( () => () => components.unmount( id ), [ components, id ] );
}

function Component( { id, componentsById, renderById } ) {
const [ , forceRender ] = useReducer( () => ( {} ) );
useLayoutEffect( () => {
renderById.current.set( id, forceRender );
}, [ id, renderById ] );
return componentsById.current.get( id );
}

function Components( { componentsById, renderById, renderAll } ) {
const [ , forceRender ] = useReducer( () => ( {} ) );

useLayoutEffect( () => {
renderAll.current = forceRender;
}, [ renderAll ] );

return Array.from( componentsById.current.keys() ).map( ( key ) => (
<Component
key={ key }
id={ key }
componentsById={ componentsById }
renderById={ renderById }
/>
) );
}

function ComponentRenderer( { children } ) {
const componentsById = useRef( new Map() );
const renderById = useRef( new Map() );
const renderAll = useRef( () => {} );
return (
<componentsContext.Provider
value={ useMemo(
() => ( {
render( id, component ) {
if ( componentsById.current.has( id ) ) {
componentsById.current.set( id, component );
renderById.current.get( id )();
} else {
componentsById.current.set( id, component );
renderAll.current();
}
},
unmount( id ) {
if ( componentsById.current.has( id ) ) {
componentsById.current.delete( id );
renderById.current.delete( id );
renderAll.current();
}
},
} ),
[]
) }
>
<Components
componentsById={ componentsById }
renderById={ renderById }
renderAll={ renderAll }
/>
{ children }
</componentsContext.Provider>
);
}

function Root( { className, ...settings } ) { function Root( { className, ...settings } ) {
const [ element, setElement ] = useState();
const isLargeViewport = useViewportMatch( 'medium' ); const isLargeViewport = useViewportMatch( 'medium' );
const { isOutlineMode, isFocusMode, editorMode } = useSelect( const { isOutlineMode, isFocusMode, editorMode } = useSelect(
( select ) => { ( select ) => {
Expand Down Expand Up @@ -105,7 +188,6 @@ function Root( { className, ...settings } ) {
ref: useMergeRefs( [ ref: useMergeRefs( [
useBlockSelectionClearer(), useBlockSelectionClearer(),
useInBetweenInserter(), useInBetweenInserter(),
setElement,
] ), ] ),
className: classnames( 'is-root-container', className, { className: classnames( 'is-root-container', className, {
'is-outline-mode': isOutlineMode, 'is-outline-mode': isOutlineMode,
Expand All @@ -116,11 +198,13 @@ function Root( { className, ...settings } ) {
settings settings
); );
return ( return (
<elementContext.Provider value={ element }>
<IntersectionObserver.Provider value={ intersectionObserver }> <IntersectionObserver.Provider value={ intersectionObserver }>
<div { ...innerBlocksProps } /> <div { ...innerBlocksProps }>
<ComponentRenderer>
{ innerBlocksProps.children }
</ComponentRenderer>
</div>
</IntersectionObserver.Provider> </IntersectionObserver.Provider>
</elementContext.Provider>
); );
} }


Expand All @@ -135,7 +219,7 @@ export default function BlockList( settings ) {
); );
} }


BlockList.__unstableElementContext = elementContext; BlockList.useRootPortal = useRootPortal;


function Items( { function Items( {
placeholder, placeholder,
Expand Down
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { useMergeRefs, useDisabled } from '@wordpress/compose'; import { useMergeRefs, useDisabled } from '@wordpress/compose';
import { useSelect } from '@wordpress/data'; import { useSelect } from '@wordpress/data';
import warning from '@wordpress/warning'; import warning from '@wordpress/warning';
import { applyFilters } from '@wordpress/hooks';


/** /**
* Internal dependencies * Internal dependencies
Expand Down Expand Up @@ -75,6 +76,8 @@ export function useBlockProps( props = {}, { __unstableIsHtml } = {} ) {
isPartOfSelection, isPartOfSelection,
adjustScrolling, adjustScrolling,
enableAnimation, enableAnimation,
blockType,
attributes,
} = useSelect( } = useSelect(
( select ) => { ( select ) => {
const { const {
Expand All @@ -95,22 +98,24 @@ export function useBlockProps( props = {}, { __unstableIsHtml } = {} ) {
isBlockMultiSelected( clientId ) || isBlockMultiSelected( clientId ) ||
isAncestorMultiSelected( clientId ); isAncestorMultiSelected( clientId );
const blockName = getBlockName( clientId ); const blockName = getBlockName( clientId );
const blockType = getBlockType( blockName ); const _blockType = getBlockType( blockName );
const attributes = getBlockAttributes( clientId ); const _attributes = getBlockAttributes( clientId );
const match = getActiveBlockVariation( blockName, attributes ); const match = getActiveBlockVariation( blockName, _attributes );


return { return {
index: getBlockIndex( clientId ), index: getBlockIndex( clientId ),
mode: getBlockMode( clientId ), mode: getBlockMode( clientId ),
name: blockName, name: blockName,
blockApiVersion: blockType?.apiVersion || 1, blockApiVersion: _blockType?.apiVersion || 1,
blockTitle: match?.title || blockType?.title, blockTitle: match?.title || _blockType?.title,
isPartOfSelection: isSelected || isPartOfMultiSelection, isPartOfSelection: isSelected || isPartOfMultiSelection,
adjustScrolling: adjustScrolling:
isSelected || isFirstMultiSelectedBlock( clientId ), isSelected || isFirstMultiSelectedBlock( clientId ),
enableAnimation: enableAnimation:
! isTyping() && ! isTyping() &&
getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD, getGlobalBlockCount() <= BLOCK_ANIMATION_THRESHOLD,
blockType: _blockType,
attributes: _attributes,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should use context for this, I'm not sure what's best for performance.

}; };
}, },
[ clientId ] [ clientId ]
Expand Down Expand Up @@ -147,9 +152,16 @@ export function useBlockProps( props = {}, { __unstableIsHtml } = {} ) {
); );
} }


const filteredWrapperProps = applyFilters(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This approach suffers from the hooks rules errors as filters get added/removed over time. I think it's probably going to create a lot of bugs.

'blockEditor.useBlockProps',
wrapperProps,
blockType,
attributes
);

return { return {
tabIndex: 0, tabIndex: 0,
...wrapperProps, ...filteredWrapperProps,
...props, ...props,
ref: mergedRefs, ref: mergedRefs,
id: `block-${ clientId }${ htmlSuffix }`, id: `block-${ clientId }${ htmlSuffix }`,
Expand All @@ -166,13 +178,13 @@ export function useBlockProps( props = {}, { __unstableIsHtml } = {} ) {
} ), } ),
className, className,
props.className, props.className,
wrapperProps.className, filteredWrapperProps.className,
useBlockClassNames( clientId ), useBlockClassNames( clientId ),
useBlockDefaultClassName( clientId ), useBlockDefaultClassName( clientId ),
useBlockCustomClassName( clientId ), useBlockCustomClassName( clientId ),
useBlockMovingModeClassNames( clientId ) useBlockMovingModeClassNames( clientId )
), ),
style: { ...wrapperProps.style, ...props.style }, style: { ...filteredWrapperProps.style, ...props.style },
}; };
} }


Expand Down
36 changes: 14 additions & 22 deletions packages/block-editor/src/hooks/align.js
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -175,38 +175,30 @@ export const withToolbarControls = createHigherOrderComponent(
/** /**
* Override the default block element to add alignment wrapper props. * Override the default block element to add alignment wrapper props.
* *
* @param {Function} BlockListBlock Original component. * @param {Object} props Additional props applied to edit element.
* * @param {Object} blockType Block type.
* @return {Function} Wrapped component. * @param {Object} attributes Block attributes.
*/ */
export const withDataAlign = createHigherOrderComponent( export const useDataAlign = ( props, blockType, attributes ) => {
( BlockListBlock ) => ( props ) => {
const { name, attributes } = props;
const { align } = attributes; const { align } = attributes;
const blockAllowedAlignments = getValidAlignments( const blockAllowedAlignments = getValidAlignments(
getBlockSupport( name, 'align' ), getBlockSupport( blockType, 'align' ),
hasBlockSupport( name, 'alignWide', true ) hasBlockSupport( blockType, 'alignWide', true )
);
const validAlignments = useAvailableAlignments(
blockAllowedAlignments
); );
const validAlignments = useAvailableAlignments( blockAllowedAlignments );


// If an alignment is not assigned, there's no need to go through the // If an alignment is not assigned, there's no need to go through the
// effort to validate or assign its value. // effort to validate or assign its value.
if ( align === undefined ) { if ( align === undefined ) {
return <BlockListBlock { ...props } />; return props;
} }


let wrapperProps = props.wrapperProps; if ( validAlignments.some( ( alignment ) => alignment.name === align ) ) {
if ( return { ...props, 'data-align': align };
validAlignments.some( ( alignment ) => alignment.name === align )
) {
wrapperProps = { ...wrapperProps, 'data-align': align };
} }


return <BlockListBlock { ...props } wrapperProps={ wrapperProps } />; return props;
} };
);


/** /**
* Override props assigned to save component to inject alignment class name if * Override props assigned to save component to inject alignment class name if
Expand Down Expand Up @@ -243,9 +235,9 @@ addFilter(
addAttribute addAttribute
); );
addFilter( addFilter(
'editor.BlockListBlock', 'blockEditor.useBlockProps',
'core/editor/align/with-data-align', 'core/editor/align/with-data-align',
withDataAlign useDataAlign
); );
addFilter( addFilter(
'editor.BlockEdit', 'editor.BlockEdit',
Expand Down
37 changes: 14 additions & 23 deletions packages/block-editor/src/hooks/border.js
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import classnames from 'classnames';
*/ */
import { getBlockSupport } from '@wordpress/blocks'; import { getBlockSupport } from '@wordpress/blocks';
import { __experimentalHasSplitBorders as hasSplitBorders } from '@wordpress/components'; import { __experimentalHasSplitBorders as hasSplitBorders } from '@wordpress/components';
import { createHigherOrderComponent } from '@wordpress/compose';
import { Platform, useCallback, useMemo } from '@wordpress/element'; import { Platform, useCallback, useMemo } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks'; import { addFilter } from '@wordpress/hooks';


Expand Down Expand Up @@ -331,21 +330,19 @@ function addEditProps( settings ) {
* This adds inline styles for color palette colors. * This adds inline styles for color palette colors.
* Ideally, this is not needed and themes should load their palettes on the editor. * Ideally, this is not needed and themes should load their palettes on the editor.
* *
* @param {Function} BlockListBlock Original component. * @param {Object} props Additional props applied to save element.
* * @param {Object} blockType Block type definition.
* @return {Function} Wrapped component. * @param {Object} attributes Block's attributes.
*/ */
export const withBorderColorPaletteStyles = createHigherOrderComponent( export const useBorderColorPaletteStyles = ( props, blockType, attributes ) => {
( BlockListBlock ) => ( props ) => {
const { name, attributes } = props;
const { borderColor, style } = attributes; const { borderColor, style } = attributes;
const { colors } = useMultipleOriginColorsAndGradients(); const { colors } = useMultipleOriginColorsAndGradients();


if ( if (
! hasBorderSupport( name, 'color' ) || ! hasBorderSupport( blockType, 'color' ) ||
shouldSkipSerialization( name, BORDER_SUPPORT_KEY, 'color' ) shouldSkipSerialization( blockType, BORDER_SUPPORT_KEY, 'color' )
) { ) {
return <BlockListBlock { ...props } />; return props;
} }


const { color: borderColorValue } = getMultiOriginColor( { const { color: borderColorValue } = getMultiOriginColor( {
Expand All @@ -363,9 +360,7 @@ export const withBorderColorPaletteStyles = createHigherOrderComponent(


const { color: borderBottomColor } = getMultiOriginColor( { const { color: borderBottomColor } = getMultiOriginColor( {
colors, colors,
namedColor: getColorSlugFromVariable( namedColor: getColorSlugFromVariable( style?.border?.bottom?.color ),
style?.border?.bottom?.color
),
} ); } );
const { color: borderLeftColor } = getMultiOriginColor( { const { color: borderLeftColor } = getMultiOriginColor( {
colors, colors,
Expand All @@ -379,18 +374,14 @@ export const withBorderColorPaletteStyles = createHigherOrderComponent(
borderLeftColor: borderLeftColor || borderColorValue, borderLeftColor: borderLeftColor || borderColorValue,
}; };


let wrapperProps = props.wrapperProps; return {
wrapperProps = { ...props,
...props.wrapperProps,
style: { style: {
...props.wrapperProps?.style, ...props.style,
...extraStyles, ...extraStyles,
}, },
}; };

};
return <BlockListBlock { ...props } wrapperProps={ wrapperProps } />;
}
);


addFilter( addFilter(
'blocks.registerBlockType', 'blocks.registerBlockType',
Expand All @@ -411,7 +402,7 @@ addFilter(
); );


addFilter( addFilter(
'editor.BlockListBlock', 'blockEditor.useBlockProps',
'core/border/with-border-color-palette-styles', 'core/border/with-border-color-palette-styles',
withBorderColorPaletteStyles useBorderColorPaletteStyles
); );
Loading