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: Use post meta label from register_meta in block bindings workflows #65099

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
12f355e
Initial commit. Add meta field to post types.
cbravobernal Sep 17, 2024
9ba93b0
Add post meta
cbravobernal Sep 17, 2024
364dc27
Add todos
cbravobernal Sep 17, 2024
d3491d6
Add fields in all postType
SantosGuillamot Sep 17, 2024
19cb1f9
WIP: Add first version to link templates and entities
SantosGuillamot Sep 17, 2024
1e8c3bf
Revert "WIP: Add first version to link templates and entities"
SantosGuillamot Sep 17, 2024
f8f18fc
Only expose public fields
SantosGuillamot Sep 17, 2024
82006cf
Add subtype to meta properties
SantosGuillamot Sep 17, 2024
ae6037e
Render the appropriate fields depending on the postType in templates
SantosGuillamot Sep 17, 2024
faa713f
Use context postType when available
SantosGuillamot Sep 17, 2024
8706071
Fetch the data on render, preventing one click needed
cbravobernal Sep 17, 2024
7593629
Yoda conditions..
cbravobernal Sep 17, 2024
6758ec1
Try: Expose registered meta fields in schema
SantosGuillamot Sep 17, 2024
35127e0
Try: Create a resolver to get registered post meta
SantosGuillamot Sep 17, 2024
ef6c64b
Use rest namespace
cbravobernal Sep 17, 2024
0330ddf
Move actions and selectors to private.
cbravobernal Sep 17, 2024
53ac96d
Merge useSelect
cbravobernal Sep 17, 2024
c41877b
Fix duplicated
cbravobernal Sep 17, 2024
bf7ab98
Add object_subtype to schema
SantosGuillamot Sep 17, 2024
da336be
Update docs to object_subtype
cbravobernal Sep 17, 2024
0734e02
Add explanatory comment
cbravobernal Sep 17, 2024
d76d0a4
Block Bindings: Use default values in connected custom fields in temp…
SantosGuillamot Sep 17, 2024
ca45424
Try removing all object subtype
cbravobernal Sep 17, 2024
b911680
Fix e2e
cbravobernal Sep 17, 2024
44048d7
Update code
cbravobernal Sep 17, 2024
17e0bd6
Fix `useSelect` warning
SantosGuillamot Sep 17, 2024
1d33103
Remove old comment
SantosGuillamot Sep 17, 2024
e17fde7
Remove support for generic templates
SantosGuillamot Sep 17, 2024
782a123
Revert changes to e2e tests
SantosGuillamot Sep 17, 2024
344cbf7
Change the value returned by `getFieldsList` to include label
SantosGuillamot Sep 17, 2024
4914c8f
Use label in bindings panel
SantosGuillamot Sep 17, 2024
780ae67
Use label in rich text placeholders
SantosGuillamot Sep 17, 2024
a23dd37
Add filter to include `label`
SantosGuillamot Sep 17, 2024
a4436b0
Use title instead of label in schema
SantosGuillamot Sep 17, 2024
d5eb220
Add safety check
SantosGuillamot Sep 17, 2024
0a92891
Adapt branch after rebase
SantosGuillamot Sep 17, 2024
0a0ee3f
Remove extra spaces
SantosGuillamot Sep 17, 2024
f089676
Don't rely on key outside of post meta
SantosGuillamot Sep 17, 2024
6288d34
Remove key from bindings component
SantosGuillamot Sep 17, 2024
efa3b5d
Read title instead of label
SantosGuillamot Sep 17, 2024
23908f7
Add backport to changelog
SantosGuillamot Sep 17, 2024
d724026
Update translator comment
SantosGuillamot Sep 18, 2024
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
3 changes: 3 additions & 0 deletions backport-changelog/6.7/7298.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
https://github.com/WordPress/wordpress-develop/pull/7298

* https://github.com/WordPress/gutenberg/pull/65099
32 changes: 32 additions & 0 deletions lib/compat/wordpress-6.7/block-bindings.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,35 @@ function gutenberg_add_can_update_block_bindings_editor_setting( $editor_setting
}

add_filter( 'block_editor_settings_all', 'gutenberg_add_can_update_block_bindings_editor_setting', 10 );

/**
* Add `label` to `register_meta`.
*
* @param array $args Array of arguments for registering meta.
* @return array Modified arguments array including `label`.
*/
function gutenberg_update_meta_args_with_label( $args ) {
// Don't update schema when label isn't provided.
if ( ! isset( $args['label'] ) ) {
return $args;
}

$schema = array( 'title' => $args['label'] );
if ( ! is_array( $args['show_in_rest'] ) ) {
$args['show_in_rest'] = array(
'schema' => $schema,
);
return $args;
}

if ( ! empty( $args['show_in_rest']['schema'] ) ) {
$args['show_in_rest']['schema'] = array_merge( $args['show_in_rest']['schema'], $schema );
} else {
$args['show_in_rest']['schema'] = $schema;
}

return $args;
}

// Priority must be lower than 10 to ensure the label is not removed.
add_filter( 'register_meta_args', 'gutenberg_update_meta_args_with_label', 5, 1 );
25 changes: 20 additions & 5 deletions packages/block-editor/src/components/rich-text/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ export function RichTextWrapper(
const { clientId, isSelected: isBlockSelected, name: blockName } = context;
const blockBindings = context[ blockBindingsKey ];
const blockContext = useContext( BlockContext );
const registry = useRegistry();
const selector = ( select ) => {
// Avoid subscribing to the block editor store if the block is not
// selected.
Expand Down Expand Up @@ -178,6 +179,10 @@ export function RichTextWrapper(
const blockBindingsSource = getBlockBindingsSource(
relatedBinding.source
);
const fieldsList = blockBindingsSource?.getFieldsList?.( {
registry,
context: blockContext,
} );

const _disableBoundBlock =
! blockBindingsSource?.canUserEditValue?.( {
Expand All @@ -186,12 +191,16 @@ export function RichTextWrapper(
args: relatedBinding.args,
} );

const bindingKey =
fieldsList?.[ relatedBinding?.args?.key ]?.label ??
blockBindingsSource?.label;

const _bindingsPlaceholder = _disableBoundBlock
? relatedBinding?.args?.key || blockBindingsSource?.label
? bindingKey
: sprintf(
/* translators: %s: source label or key */
/* translators: %s: connected field label or source label */
__( 'Add %s' ),
relatedBinding?.args?.key || blockBindingsSource?.label
bindingKey
);

return {
Expand All @@ -201,7 +210,14 @@ export function RichTextWrapper(
_bindingsPlaceholder,
};
},
[ blockBindings, identifier, blockName, blockContext, adjustedValue ]
[
blockBindings,
identifier,
blockName,
blockContext,
registry,
adjustedValue,
]
);

const shouldDisableEditing = readOnly || disableBoundBlock;
Expand Down Expand Up @@ -371,7 +387,6 @@ export function RichTextWrapper(
element.focus();
}

const registry = useRegistry();
const TagName = tagName;
return (
<>
Expand Down
17 changes: 11 additions & 6 deletions packages/block-editor/src/hooks/block-bindings.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function BlockBindingsPanelDropdown( { fieldsList, attribute, binding } ) {
{ registeredSources[ name ].label }
</DropdownMenuV2.GroupLabel>
) }
{ Object.entries( fields ).map( ( [ key, value ] ) => (
{ Object.entries( fields ).map( ( [ key, args ] ) => (
<DropdownMenuV2.RadioItem
key={ key }
onChange={ () =>
Copy link
Member

Choose a reason for hiding this comment

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

This part needs further enhancements to become more flexible. In particular:

[ attribute ]: {
	source: name,
		args: { key },
}

In my opinion, every source should construct args argument, which for Post Meta happens to be { key }. For Pattern Overrides that would be {} or undefined, and every other source could decide what that it.

In effect, I believe the object item from the fields should have the following shape:

{
    label: string,
    value: string,
    args: any,
}

This way it's up to the implementor to provide all that's necessary to make it work when defining getFieldsList fir the source.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I plan to create an issue to discuss the whole getFieldsList API to ensure it feels good before making it public.

I believe I shouldn't have used the args variable name here because it doesn't refer to the source args, but the object returned by getFieldsList. There are two different things:

  • The binding object: It specifies which attribute is connected to which source, which can already use any args they want. For example, in post meta we use key to specify which custom field the attribute is connected to:
"content": {
	source: "core/post-meta",
		args: { key: "my_custom_field" },
}
  • The getFieldsList API: This is used just to get a list of ALL the bindable fields in order to show them in the UI and let the user select. In this case, I believe we only need the label and the value. As it is a callback, each source can decide what to show as the label and the value.

I hope we can clarify it by improving the getFieldsList API (probably needs a new name) and that part of the code, because I agree it feels confusing right now.

Expand All @@ -77,10 +77,10 @@ function BlockBindingsPanelDropdown( { fieldsList, attribute, binding } ) {
checked={ key === currentKey }
>
<DropdownMenuV2.ItemLabel>
{ key }
{ args?.label }
gziolo marked this conversation as resolved.
Show resolved Hide resolved
</DropdownMenuV2.ItemLabel>
<DropdownMenuV2.ItemHelpText>
{ value }
{ args?.value }
</DropdownMenuV2.ItemHelpText>
</DropdownMenuV2.RadioItem>
) ) }
Expand All @@ -94,7 +94,7 @@ function BlockBindingsPanelDropdown( { fieldsList, attribute, binding } ) {
);
}

function BlockBindingsAttribute( { attribute, binding } ) {
function BlockBindingsAttribute( { attribute, binding, fieldsList } ) {
const { source: sourceName, args } = binding || {};
const sourceProps =
unlock( blocksPrivateApis ).getBlockBindingsSource( sourceName );
Expand All @@ -110,21 +110,24 @@ function BlockBindingsAttribute( { attribute, binding } ) {
>
{ isSourceInvalid
? __( 'Invalid source' )
: args?.key || sourceProps?.label || sourceName }
: fieldsList?.[ sourceName ]?.[ args?.key ]?.label ||
sourceProps?.label ||
sourceName }
</Text>
) }
</VStack>
);
}

function ReadOnlyBlockBindingsPanelItems( { bindings } ) {
function ReadOnlyBlockBindingsPanelItems( { bindings, fieldsList } ) {
return (
<>
{ Object.entries( bindings ).map( ( [ attribute, binding ] ) => (
<Item key={ attribute }>
<BlockBindingsAttribute
attribute={ attribute }
binding={ binding }
fieldsList={ fieldsList }
/>
</Item>
) ) }
Expand Down Expand Up @@ -164,6 +167,7 @@ function EditableBlockBindingsPanelItems( {
<BlockBindingsAttribute
attribute={ attribute }
binding={ binding }
fieldsList={ fieldsList }
/>
</Item>
}
Expand Down Expand Up @@ -276,6 +280,7 @@ export const BlockBindingsPanel = ( { name: blockName, metadata } ) => {
{ readOnly ? (
<ReadOnlyBlockBindingsPanelItems
bindings={ filteredBindings }
fieldsList={ fieldsList }
/>
) : (
<EditableBlockBindingsPanelItems
Expand Down
54 changes: 37 additions & 17 deletions packages/editor/src/bindings/post-meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ import { store as coreDataStore } from '@wordpress/core-data';
import { store as editorStore } from '../store';
import { unlock } from '../lock-unlock';

function getMetadata( registry, context ) {
function getMetadata( registry, context, registeredFields ) {
let metaFields = {};
const { type } = registry.select( editorStore ).getCurrentPost();
const { getEditedEntityRecord } = registry.select( coreDataStore );
const { getRegisteredPostMeta } = unlock(
registry.select( coreDataStore )
);

if ( type === 'wp_template' ) {
const fields = getRegisteredPostMeta( context?.postType );
// Populate the `metaFields` object with the default values.
Object.entries( fields || {} ).forEach( ( [ key, props ] ) => {
metaFields[ key ] = props.default;
} );
Object.entries( registeredFields || {} ).forEach(
( [ key, props ] ) => {
if ( props.default ) {
metaFields[ key ] = props.default;
}
}
);
} else {
metaFields = getEditedEntityRecord(
'postType',
Expand All @@ -37,13 +37,20 @@ function getMetadata( registry, context ) {
export default {
name: 'core/post-meta',
getValues( { registry, context, bindings } ) {
const metaFields = getMetadata( registry, context );
const { getRegisteredPostMeta } = unlock(
registry.select( coreDataStore )
);
const registeredFields = getRegisteredPostMeta( context?.postType );
const metaFields = getMetadata( registry, context, registeredFields );
gziolo marked this conversation as resolved.
Show resolved Hide resolved

const newValues = {};
for ( const [ attributeName, source ] of Object.entries( bindings ) ) {
// Use the key if the value is not set.
// Use the value, the field label, or the field key.
const metaKey = source.args.key;
newValues[ attributeName ] =
metaFields?.[ source.args.key ] ?? source.args.key;
metaFields?.[ metaKey ] ??
registeredFields?.[ metaKey ]?.title ??
metaKey;
}
return newValues;
},
Expand Down Expand Up @@ -103,18 +110,31 @@ export default {
return true;
},
getFieldsList( { registry, context } ) {
const metaFields = getMetadata( registry, context );
const { getRegisteredPostMeta } = unlock(
registry.select( coreDataStore )
);
const registeredFields = getRegisteredPostMeta( context?.postType );
const metaFields = getMetadata( registry, context, registeredFields );

if ( ! metaFields || ! Object.keys( metaFields ).length ) {
return null;
}

// Remove footnotes or private keys from the list of fields.
// TODO: Remove this once we retrieve the fields from 'types' endpoint in post or page editor.
return Object.fromEntries(
Object.entries( metaFields ).filter(
( [ key ] ) => key !== 'footnotes' && key.charAt( 0 ) !== '_'
)
Object.entries( metaFields )
// Remove footnotes or private keys from the list of fields.
.filter(
( [ key ] ) =>
key !== 'footnotes' && key.charAt( 0 ) !== '_'
)
// Return object with label and value.
.map( ( [ key, value ] ) => [
key,
{
label: registeredFields?.[ key ]?.title || key,
gziolo marked this conversation as resolved.
Show resolved Hide resolved
value,
},
] )
);
},
};
Loading