zss-engine
Version:
A CSS-in-JS transpiler engine for building zero-runtime stylesheets at build time.
50 lines (49 loc) • 1.97 kB
JavaScript
import { camelToKebabCase, applyCssValue, isAtRule } from './helper.js';
import { transpileAtomic } from './transpile-atomic.js';
import { genBase36Hash } from './hash.js';
function splitAtomicAndNested(obj, flat, nonFlat) {
const queryFlat = flat;
const queryNonFlat = nonFlat;
Object.entries(obj).forEach(([property, value]) => {
if (property.startsWith(':') || property.startsWith('[')) {
queryNonFlat[property] = value;
}
else if (isAtRule(property)) {
const innerFlat = {};
const innerNonFlat = {};
splitAtomicAndNested(value, innerFlat, innerNonFlat);
if (Object.keys(innerFlat).length)
queryFlat[property] = innerFlat;
if (Object.keys(innerNonFlat).length)
queryNonFlat[property] = innerNonFlat;
}
else {
queryFlat[property] = value;
}
});
}
function processAtomicProps(flatProps, atomicMap, parentAtRule) {
const resultQueue = [];
for (const [key, style] of Object.entries(flatProps)) {
if (isAtRule(key)) {
processAtomicProps(style, atomicMap, key);
continue;
}
resultQueue.push([key, style]);
}
for (const [property, value] of resultQueue) {
const CSSProp = camelToKebabCase(property);
const normalizedValue = applyCssValue(value, CSSProp);
const singlePropObj = { [property]: normalizedValue };
const styleObj = parentAtRule ? { [parentAtRule]: singlePropObj } : singlePropObj;
const atomicHash = genBase36Hash(styleObj, 1, 8);
if (atomicMap.has(atomicHash))
continue;
let styleSheet = transpileAtomic(property, value, atomicHash);
if (parentAtRule) {
styleSheet = `${parentAtRule} { ${styleSheet} }`;
}
atomicMap.set(atomicHash, styleSheet + '\n');
}
}
export { splitAtomicAndNested, processAtomicProps };