@nex-ui/system
Version:
A lightweight and performant styling library based on Emotion, focusing on component architecture and developer experience.
57 lines (54 loc) • 2.07 kB
JavaScript
import { forEach, merge, isArray } from '@nex-ui/utils';
import { memoizeFn } from '../utils.mjs';
function shouldApplyCompound(compoundCheck, selections) {
for(const key in compoundCheck){
if (Object.prototype.hasOwnProperty.call(compoundCheck, key)) {
const variantValue = selections[key];
if (!(isArray(compoundCheck[key]) && compoundCheck[key]?.includes(variantValue) || compoundCheck[key] === variantValue)) {
return false;
}
}
}
return true;
}
function createRuntimeFn(options) {
const { mainStyles, variants = {}, compoundVariants = [], defaultVariants = {} } = options;
function splitVariantProps(props) {
const variantKeys = Object.keys(variants);
const result = {};
forEach(variantKeys, (key)=>{
if (props[key] !== undefined) result[key] = props[key];
});
return result;
}
function runtimeFn(variantsProps = {}) {
let mergedStyles = {
...mainStyles
};
const selections = {
...defaultVariants,
...variantsProps
};
forEach(selections, (variantSelection, variantName)=>{
if (variantSelection !== null) {
let selection = variantSelection;
if (typeof selection === 'boolean') {
selection = selection === true ? 'true' : 'false';
}
mergedStyles = merge({}, mergedStyles, variants?.[variantName]?.[selection]);
}
});
forEach(compoundVariants, (compoundVariant)=>{
const { css: compoundVariantCSS, ...compoundCheck } = compoundVariant;
if (shouldApplyCompound(compoundCheck, selections)) {
mergedStyles = merge({}, mergedStyles, compoundVariantCSS);
}
});
return mergedStyles;
}
const memoized = memoizeFn(runtimeFn);
// @ts-ignore
memoized.splitVariantProps = splitVariantProps;
return memoized;
}
export { createRuntimeFn };