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

synchronizeBlocksWithTemplate: extract common functions #59682

Merged
merged 1 commit into from
Mar 8, 2024
Merged
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
72 changes: 36 additions & 36 deletions packages/blocks/src/api/templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,42 @@ export function doBlocksMatchTemplate( blocks = [], template = [] ) {
);
}

const isHTMLAttribute = ( attributeDefinition ) =>
attributeDefinition?.source === 'html';

const isQueryAttribute = ( attributeDefinition ) =>
attributeDefinition?.source === 'query';

function normalizeAttributes( schema, values ) {
if ( ! values ) {
return {};
}

return Object.fromEntries(
Object.entries( values ).map( ( [ key, value ] ) => [
key,
normalizeAttribute( schema[ key ], value ),
] )
);
}

function normalizeAttribute( definition, value ) {
if ( isHTMLAttribute( definition ) && Array.isArray( value ) ) {
// Introduce a deprecated call at this point
// When we're confident that "children" format should be removed from the templates.

return renderToString( value );
}

if ( isQueryAttribute( definition ) && value ) {
return value.map( ( subValues ) => {
return normalizeAttributes( definition.query, subValues );
} );
}

return value;
}

/**
* Synchronize a block list with a block template.
*
Expand Down Expand Up @@ -67,42 +103,6 @@ export function synchronizeBlocksWithTemplate( blocks = [], template ) {
// before creating the blocks.

const blockType = getBlockType( name );
const isHTMLAttribute = ( attributeDefinition ) =>
attributeDefinition?.source === 'html';
const isQueryAttribute = ( attributeDefinition ) =>
attributeDefinition?.source === 'query';

const normalizeAttributes = ( schema, values ) => {
if ( ! values ) {
return {};
}

return Object.fromEntries(
Object.entries( values ).map( ( [ key, value ] ) => [
key,
normalizeAttribute( schema[ key ], value ),
] )
);
};
const normalizeAttribute = ( definition, value ) => {
if ( isHTMLAttribute( definition ) && Array.isArray( value ) ) {
// Introduce a deprecated call at this point
// When we're confident that "children" format should be removed from the templates.

return renderToString( value );
}

if ( isQueryAttribute( definition ) && value ) {
return value.map( ( subValues ) => {
return normalizeAttributes(
definition.query,
subValues
);
} );
}

return value;
};

const normalizedAttributes = normalizeAttributes(
blockType?.attributes ?? {},
Expand Down
Loading