@wordpress/block-library
Version:
Block library for the WordPress editor.
50 lines (49 loc) • 2.18 kB
JavaScript
import { cloneBlock, createBlock, getGroupingBlockName, getPossibleBlockTransformations, parse, switchToBlockType } from "@wordpress/blocks";
// packages/block-library/src/template-part/edit/utils/transformers.js
/**
* Converts a widget entity record into a block.
*
* @param {Object} widget The widget entity record.
* @return {Object} a block (converted from the entity record).
*/
function transformWidgetToBlock(widget) {
if (widget.id_base !== "block") {
let attributes;
if (widget._embedded.about[0].is_multi) attributes = {
idBase: widget.id_base,
instance: widget.instance
};
else attributes = { id: widget.id };
return switchLegacyWidgetType(createBlock("core/legacy-widget", attributes));
}
const parsedBlocks = parse(widget.instance.raw.content, { __unstableSkipAutop: true });
if (!parsedBlocks.length) return;
const block = parsedBlocks[0];
if (block.name === "core/widget-group") return createBlock(getGroupingBlockName(), void 0, transformInnerBlocks(block.innerBlocks));
if (block.innerBlocks.length > 0) return cloneBlock(block, void 0, transformInnerBlocks(block.innerBlocks));
return block;
}
/**
* Switch Legacy Widget to the first matching transformation block.
*
* @param {Object} block Legacy Widget block object
* @return {Object|undefined} a block
*/
function switchLegacyWidgetType(block) {
const transforms = getPossibleBlockTransformations([block]).filter((item) => {
if (!item.transforms) return true;
const hasWildCardFrom = item.transforms?.from?.find((from) => from.blocks && from.blocks.includes("*"));
const hasWildCardTo = item.transforms?.to?.find((to) => to.blocks && to.blocks.includes("*"));
return !hasWildCardFrom && !hasWildCardTo;
});
if (!transforms.length) return;
return switchToBlockType(block, transforms[0].name);
}
function transformInnerBlocks(innerBlocks = []) {
return innerBlocks.flatMap((block) => {
if (block.name === "core/legacy-widget") return switchLegacyWidgetType(block);
return createBlock(block.name, block.attributes, transformInnerBlocks(block.innerBlocks));
}).filter((block) => !!block);
}
export { transformWidgetToBlock };
//# sourceMappingURL=transformers.mjs.map