@wordpress/block-editor
Version:
103 lines (98 loc) • 2.65 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useStylesForBlocks;
var _data = require("@wordpress/data");
var _blocks = require("@wordpress/blocks");
var _element = require("@wordpress/element");
var _utils = require("./utils");
var _store = require("../../store");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
*
* @param {WPBlock} block Block object.
* @param {WPBlockType} type Block type settings.
* @return {WPBlock} A generic block ready for styles preview.
*/
function useGenericPreviewBlock(block, type) {
return (0, _element.useMemo)(() => {
const example = type?.example;
const blockName = type?.name;
if (example && blockName) {
return (0, _blocks.getBlockFromExample)(blockName, {
attributes: example.attributes,
innerBlocks: example.innerBlocks
});
}
if (block) {
return (0, _blocks.cloneBlock)(block);
}
}, [type?.example ? block?.name : block, type]);
}
/**
* @typedef useStylesForBlocksArguments
* @property {string} clientId Block client ID.
* @property {() => void} onSwitch Block style switch callback function.
*/
/**
*
* @param {useStylesForBlocksArguments} useStylesForBlocks arguments.
* @return {Object} Results of the select methods.
*/
function useStylesForBlocks({
clientId,
onSwitch
}) {
const selector = select => {
const {
getBlock
} = select(_store.store);
const block = getBlock(clientId);
if (!block) {
return {};
}
const blockType = (0, _blocks.getBlockType)(block.name);
const {
getBlockStyles
} = select(_blocks.store);
return {
block,
blockType,
styles: getBlockStyles(block.name),
className: block.attributes.className || ''
};
};
const {
styles,
block,
blockType,
className
} = (0, _data.useSelect)(selector, [clientId]);
const {
updateBlockAttributes
} = (0, _data.useDispatch)(_store.store);
const stylesToRender = (0, _utils.getRenderedStyles)(styles);
const activeStyle = (0, _utils.getActiveStyle)(stylesToRender, className);
const genericPreviewBlock = useGenericPreviewBlock(block, blockType);
const onSelect = style => {
const styleClassName = (0, _utils.replaceActiveStyle)(className, activeStyle, style);
updateBlockAttributes(clientId, {
className: styleClassName
});
onSwitch();
};
return {
onSelect,
stylesToRender,
activeStyle,
genericPreviewBlock,
className
};
}
//# sourceMappingURL=use-styles-for-block.js.map