Skip to content

Commit

Permalink
synchronizeBlocksWithTemplate: extract common functions (#59682)
Browse files Browse the repository at this point in the history
Co-authored-by: jsnajdr <jsnajdr@git.wordpress.org>
Co-authored-by: tyxla <tyxla@git.wordpress.org>
  • Loading branch information
3 people authored Mar 8, 2024
1 parent ed7edbc commit 985ea06
Showing 1 changed file with 36 additions and 36 deletions.
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

0 comments on commit 985ea06

Please sign in to comment.