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 Bindings: Refactor block bindings editor implementation #58059

Closed
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
12 changes: 12 additions & 0 deletions packages/block-editor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,18 @@ _Properties_

Ensures that the text selection keeps the same vertical distance from the viewport during keyboard events within this component. The vertical distance can vary. It is the last clicked or scrolled to position.

### updateBlockBindingsAttribute

Helper to update the bindings attribute used by the Block Bindings API.

_Parameters_

- _blockAttributes_ `Object`: - The original block attributes.
- _setAttributes_ `Function`: - setAttributes function to modify the bindings property.
- _attributeName_ `string`: - The attribute in the bindings object to update.
- _sourceName_ `string`: - The source name added to the bindings property.
- _sourceAttributes_ `string`: - The source attributes added to the bindings property.

### URLInput

_Related_
Expand Down
147 changes: 147 additions & 0 deletions packages/block-editor/src/hooks/bindings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';
import {
Button,
privateApis as componentsPrivateApis,
} from '@wordpress/components';
import { useContext } from '@wordpress/element';
import { addFilter } from '@wordpress/hooks';
import { plugins as pluginsIcon } from '@wordpress/icons';
/**
* Internal dependencies
*/
import { BlockControls } from '../components';
import { store as blockEditorStore } from '../store';
import { unlock } from '../lock-unlock';
import BlockContext from '../components/block-context';

const {
DropdownMenuV2: DropdownMenu,
DropdownMenuItemV2: DropdownMenuItem,
DropdownMenuItemLabelV2: DropdownMenuItemLabel,
} = unlock( componentsPrivateApis );

const BLOCK_BINDINGS_ALLOWED_BLOCKS = {
'core/paragraph': [ 'content' ],
'core/heading': [ 'content' ],
'core/image': [ 'url', 'title' ],
'core/button': [ 'url', 'text' ],
};

function BlockBindingsUI( props ) {
const { name: blockName, clientId } = props;
const { attributes, sources } = useSelect(
( select ) => {
return {
attributes:
select( blockEditorStore ).getBlockAttributes( clientId ),
sources: unlock(
select( blockEditorStore )
).getAllBlockBindingsSources(),
};
},
[ clientId ]
);
const blockContext = useContext( BlockContext );
if ( ! ( blockName in BLOCK_BINDINGS_ALLOWED_BLOCKS ) ) {
return null;
}

return (
<>
<BlockControls group="other">
<DropdownMenu
onOpenChange={ function noRefCheck() {} }
trigger={
<Button __next40pxDefaultSize icon={ pluginsIcon } />
}
>
{ /* Iterate over block attributes */ }
{ BLOCK_BINDINGS_ALLOWED_BLOCKS[ blockName ].map(
( attribute ) => {
return (
<DropdownMenu
trigger={
<DropdownMenuItem>
<DropdownMenuItemLabel>
{ attribute }
</DropdownMenuItemLabel>
</DropdownMenuItem>
}
key={ attribute }
>
{ /* Iterate over sources */ }
{ Object.entries( sources ).map(
( [ sourceName, source ] ) => {
return (
<DropdownMenu
trigger={
<DropdownMenuItem>
<DropdownMenuItemLabel
className={
attributes
.metadata
?.bindings?.[
attribute
]?.source
?.name ===
sourceName &&
'is-source-bound'
}
>
{ source.label }
</DropdownMenuItemLabel>
</DropdownMenuItem>
}
key={ sourceName }
>
{ source.component(
props,
blockContext,
attribute
) }
</DropdownMenu>
);
}
) }
</DropdownMenu>
);
}
) }
</DropdownMenu>
</BlockControls>
</>
);
}

export default {
edit: BlockBindingsUI,
attributeKeys: [ 'metadata' ],
hasSupport() {
return true;
},
};

if ( window.__experimentalBlockBindings ) {
addFilter(
'blocks.registerBlockType',
'core/block-bindings-ui',
( settings, name ) => {
if ( ! ( name in BLOCK_BINDINGS_ALLOWED_BLOCKS ) ) {
return settings;
}
const contextItems = [ 'postId', 'postType', 'queryId' ];
const usesContextArray = settings.usesContext;
const oldUsesContextArray = new Set( usesContextArray );
contextItems.forEach( ( item ) => {
if ( ! oldUsesContextArray.has( item ) ) {
usesContextArray.push( item );
}
} );
settings.usesContext = usesContextArray;
return settings;
}
);
}
3 changes: 3 additions & 0 deletions packages/block-editor/src/hooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import align from './align';
import './lock';
import anchor from './anchor';
import ariaLabel from './aria-label';
import bindings from './bindings';
import customClassName from './custom-class-name';
import './generated-class-name';
import style from './style';
Expand All @@ -27,11 +28,13 @@ import contentLockUI from './content-lock-ui';
import './metadata';
import blockHooks from './block-hooks';
import blockRenaming from './block-renaming';
import './use-bindings-attributes';

createBlockEditFilter(
[
align,
anchor,
bindings,
customClassName,
style,
duotone,
Expand Down
123 changes: 123 additions & 0 deletions packages/block-editor/src/hooks/use-bindings-attributes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* WordPress dependencies
*/
import { createHigherOrderComponent } from '@wordpress/compose';
import { useRegistry, useSelect } from '@wordpress/data';
import { addFilter } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import { store as blockEditorStore } from '../store';
import { useBlockEditContext } from '../components/block-edit/context';
import { unlock } from '../lock-unlock';

/** @typedef {import('@wordpress/compose').WPHigherOrderComponent} WPHigherOrderComponent */
/** @typedef {import('@wordpress/blocks').WPBlockSettings} WPBlockSettings */

/**
* Given a binding of block attributes, returns a higher order component that
* overrides its `attributes` and `setAttributes` props to sync any changes needed.
*
* @return {WPHigherOrderComponent} Higher-order component.
*/

const BLOCK_BINDINGS_ALLOWED_BLOCKS = {
'core/paragraph': [ 'content' ],
'core/heading': [ 'content' ],
'core/image': [ 'url', 'title' ],
'core/button': [ 'url', 'text' ],
};

const createEditFunctionWithBindingsAttribute = () =>
createHigherOrderComponent(
( BlockEdit ) => ( props ) => {
const { clientId } = useBlockEditContext();

const {
getBlockBindingsSource,
getBlockAttributes,
updateBlockAttributes,
} = useSelect( ( select ) => {
return {
getBlockBindingsSource: unlock( select( blockEditorStore ) )
.getBlockBindingsSource,
getBlockAttributes:
select( blockEditorStore ).getBlockAttributes,
updateBlockAttributes:
select( blockEditorStore ).updateBlockAttributes,
};
}, [] );

const updatedAttributes = getBlockAttributes( clientId );
if ( updatedAttributes?.metadata?.bindings ) {
Object.entries( updatedAttributes.metadata.bindings ).forEach(
( [ attributeName, settings ] ) => {
const source = getBlockBindingsSource(
settings.source.name
);

if ( source ) {
// Second argument (`updateMetaValue`) will be used to update the value in the future.
const {
placeholder,
useValue: [ metaValue = null ] = [],
} = source.useSource(
props,
settings.source.attributes
);

if ( placeholder ) {
updatedAttributes.placeholder = placeholder;
updatedAttributes[ attributeName ] = null;
}

if ( metaValue ) {
updatedAttributes[ attributeName ] = metaValue;
}
}
}
);
}

const registry = useRegistry();

return (
<>
<BlockEdit
key="edit"
attributes={ updatedAttributes }
setAttributes={ ( newAttributes, blockId ) =>
registry.batch( () =>
updateBlockAttributes( blockId, newAttributes )
)
}
{ ...props }
/>
</>
);
},
'useBoundAttributes'
);

/**
* Filters a registered block's settings to enhance a block's `edit` component
* to upgrade bound attributes.
*
* @param {WPBlockSettings} settings Registered block settings.
*
* @return {WPBlockSettings} Filtered block settings.
*/
function shimAttributeSource( settings ) {
if ( ! ( settings.name in BLOCK_BINDINGS_ALLOWED_BLOCKS ) ) {
return settings;
}
settings.edit = createEditFunctionWithBindingsAttribute()( settings.edit );

return settings;
}

addFilter(
'blocks.registerBlockType',
'core/editor/custom-sources-backwards-compatibility/shim-attribute-source',
shimAttributeSource
);
10 changes: 10 additions & 0 deletions packages/block-editor/src/store/private-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,16 @@ export function clearBlockRemovalPrompt() {
};
}

export function registerBlockBindingsSource( source ) {
return {
type: 'REGISTER_BLOCK_BINDINGS_SOURCE',
sourceName: source.name,
sourceLabel: source.label,
sourceComponent: source.component,
useSource: source.useSource,
};
}

/**
* Returns an action object used to set up any rules that a block editor may
* provide in order to prevent a user from accidentally removing certain
Expand Down
8 changes: 8 additions & 0 deletions packages/block-editor/src/store/private-selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,14 @@ export function getStyleOverrides( state ) {
return state.styleOverrides;
}

export function getAllBlockBindingsSources( state ) {
return state.blockBindingsSources;
}

export function getBlockBindingsSource( state, sourceName ) {
return state?.blockBindingsSources?.[ sourceName ];
}

/** @typedef {import('./actions').InserterMediaCategory} InserterMediaCategory */
/**
* Returns the registered inserter media categories through the public API.
Expand Down
16 changes: 16 additions & 0 deletions packages/block-editor/src/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -1513,6 +1513,21 @@ function removalPromptData( state = false, action ) {
return state;
}

function blockBindingsSources( state = {}, action ) {
if ( action.type === 'REGISTER_BLOCK_BINDINGS_SOURCE' ) {
return {
...state,
[ action.sourceName ]: {
label: action.sourceLabel,
component: action.sourceComponent,
useSource: action.useSource,
},
};
}

return state;
}

/**
* Reducer returning any rules that a block editor may provide in order to
* prevent a user from accidentally removing certain blocks. These rules are
Expand Down Expand Up @@ -2044,6 +2059,7 @@ const combinedReducers = combineReducers( {
blockEditingModes,
styleOverrides,
removalPromptData,
blockBindingsSources,
blockRemovalRules,
openedBlockSettingsMenu,
registeredInserterMediaCategories,
Expand Down
1 change: 1 addition & 0 deletions packages/block-editor/src/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { default as transformStyles } from './transform-styles';
export * from './block-variation-transforms';
export { default as getPxFromCssUnit } from './get-px-from-css-unit';
export * from './update-bindings-attribute';
Loading
Loading