UNPKG

@styn/core

Version:
59 lines (48 loc) 2.04 kB
import { parse, walk, stringify } from '@styn/tree'; const nested = (tree, walk) => { return walk(tree, (rule, parent, index) => { const unnest = (declarations, selector) => { const selectors = selector.split(","); for (const property in declarations) { if (typeof declarations[property] === "object" && property.includes("&")) { const nestedDeclarations = declarations[property]; const nestedSelector = selectors.map(sel => property.replace(/&/gm, sel)).join(","); unnest(nestedDeclarations, nestedSelector); parent.splice(index + 1, 0, { type: "rule", selector: nestedSelector, declarations: nestedDeclarations }); delete declarations[property]; } } }; if (rule.type === "rule" && rule.declarations) { unnest(rule.declarations, rule.selector); } }); }; const corePlugins = [nested]; const css = (objectRules, options = {}) => { var _options$plugins; let tree = parse(objectRules); // apply pipe of plugins to generate a new tree // plugins applies in array order 0, 1... // plugin[2](plugin[1](plugin[0](tree))) const plugins = [...corePlugins, ...((_options$plugins = options.plugins) !== null && _options$plugins !== void 0 ? _options$plugins : [])]; tree = plugins.reduce((tree, plugin) => plugin(tree, walk), tree); return stringify(tree); }; const genHash = (prefix = "styn") => prefix + (Math.random() * 46656 | 0).toString(36) + (Math.random() * 46656 | 0).toString(36); const element = (object, options = {}) => { var _options$className, _options$prefix; const className = (_options$className = options.className) !== null && _options$className !== void 0 ? _options$className : genHash((_options$prefix = options.prefix) !== null && _options$prefix !== void 0 ? _options$prefix : "styn"); return { className, styles: css({ [`.${className}`]: object }, { plugins: options.plugins }) }; }; export { css, element };