@wordpress/blocks
Version:
Block API for WordPress.
72 lines (71 loc) • 2.31 kB
JavaScript
// packages/blocks/src/api/templates.js
import { renderToString } from "@wordpress/element";
import { convertLegacyBlockNameAndAttributes } from "./parser/convert-legacy-block";
import { createBlock } from "./factory";
import { getBlockType } from "./registration";
function doBlocksMatchTemplate(blocks = [], template = []) {
return blocks.length === template.length && template.every(([name, , innerBlocksTemplate], index) => {
const block = blocks[index];
return name === block.name && doBlocksMatchTemplate(block.innerBlocks, innerBlocksTemplate);
});
}
var isHTMLAttribute = (attributeDefinition) => attributeDefinition?.source === "html";
var 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)) {
return renderToString(value);
}
if (isQueryAttribute(definition) && value) {
return value.map((subValues) => {
return normalizeAttributes(definition.query, subValues);
});
}
return value;
}
function synchronizeBlocksWithTemplate(blocks = [], template) {
if (!template) {
return blocks;
}
return template.map(
([name, attributes, innerBlocksTemplate], index) => {
const block = blocks[index];
if (block && block.name === name) {
const innerBlocks = synchronizeBlocksWithTemplate(
block.innerBlocks,
innerBlocksTemplate
);
return { ...block, innerBlocks };
}
const blockType = getBlockType(name);
const normalizedAttributes = normalizeAttributes(
blockType?.attributes ?? {},
attributes
);
const [blockName, blockAttributes] = convertLegacyBlockNameAndAttributes(
name,
normalizedAttributes
);
return createBlock(
blockName,
blockAttributes,
synchronizeBlocksWithTemplate([], innerBlocksTemplate)
);
}
);
}
export {
doBlocksMatchTemplate,
synchronizeBlocksWithTemplate
};
//# sourceMappingURL=templates.js.map