UNPKG

@wordpress/style-engine

Version:
70 lines (59 loc) 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.compileCSS = compileCSS; exports.getCSSRules = getCSSRules; var _lodash = require("lodash"); var _styles = require("./styles"); /** * External dependencies */ /** * Generates a stylesheet for a given style object and selector. * * @since 6.1.0 Introduced in WordPress core. * * @param style Style object, for example, the value of a block's attributes.style object or the top level styles in theme.json * @param options Options object with settings to adjust how the styles are generated. * * @return A generated stylesheet or inline style declarations. */ function compileCSS(style) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const rules = getCSSRules(style, options); // If no selector is provided, treat generated rules as inline styles to be returned as a single string. if (!(options !== null && options !== void 0 && options.selector)) { const inlineRules = []; rules.forEach(rule => { inlineRules.push(`${(0, _lodash.kebabCase)(rule.key)}: ${rule.value};`); }); return inlineRules.join(' '); } const groupedRules = (0, _lodash.groupBy)(rules, 'selector'); const selectorRules = Object.keys(groupedRules).reduce((acc, subSelector) => { acc.push(`${subSelector} { ${groupedRules[subSelector].map(rule => `${(0, _lodash.kebabCase)(rule.key)}: ${rule.value};`).join(' ')} }`); return acc; }, []); return selectorRules.join('\n'); } /** * Returns a JSON representation of the generated CSS rules. * * @since 6.1.0 Introduced in WordPress core. * * @param style Style object, for example, the value of a block's attributes.style object or the top level styles in theme.json * @param options Options object with settings to adjust how the styles are generated. * * @return A collection of objects containing the selector, if any, the CSS property key (camelcase) and parsed CSS value. */ function getCSSRules(style) { let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; const rules = []; _styles.styleDefinitions.forEach(definition => { if (typeof definition.generate === 'function') { rules.push(...definition.generate(style, options)); } }); return rules; } //# sourceMappingURL=index.js.map