Skip to content

Commit

Permalink
synchronizeBlocksWithTemplate: extract common functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jsnajdr committed Mar 6, 2024
1 parent fbf5ac9 commit 67862ad
Showing 1 changed file with 35 additions and 36 deletions.
71 changes: 35 additions & 36 deletions packages/blocks/src/api/templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,41 @@ export function doBlocksMatchTemplate( blocks = [], template = [] ) {
);
}

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;
};

/**
* Synchronize a block list with a block template.
*
Expand Down Expand Up @@ -67,42 +102,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 67862ad

Please sign in to comment.