@hitachivantara/uikit-styles
Version:
UI Kit styling solution.
83 lines (82 loc) • 2.41 kB
JavaScript
const spacingUtil = (value, vars) => {
switch (typeof value) {
case "number":
return value === 0 ? "0" : `calc(${vars.space.base} * ${value}px)`;
case "string":
return vars.space[value] || value;
default:
return value;
}
};
const toCSSVars = (obj, prefix = "--uikit") => {
const vars = {};
if (!obj || typeof obj !== "object") return vars;
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "object") {
const nestedVars = toCSSVars(value, `${prefix}-${key}`);
for (const [nestedKey, nestedValue] of Object.entries(nestedVars)) {
vars[nestedKey] = nestedValue;
}
} else {
vars[`${prefix}-${key}`] = value;
}
}
return vars;
};
const hasMultipleArgs = (args) => {
return args.length > 1;
};
const mapCSSVars = (obj, prefix = "--uikit") => {
const vars = {};
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "object") {
vars[key] = mapCSSVars(value, `${prefix}-${key}`);
} else {
vars[key] = `var(${prefix}-${key})`;
}
}
return vars;
};
const isObject = (obj) => obj && typeof obj === "object";
const mergeTheme = (...objects) => {
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach((key) => {
const pVal = prev[key];
const oVal = obj[key];
if (isObject(pVal) && isObject(oVal)) {
prev[key] = mergeTheme(pVal, oVal);
} else {
prev[key] = oVal !== void 0 ? oVal : pVal;
}
});
return prev;
}, {});
};
function removeDuplicate(obj, base) {
return Object.fromEntries(
Object.entries(obj).filter(([key, value]) => base[key] !== value)
);
}
const getThemeVars = (theme) => {
const cssVars = {};
const defaultColorMode = theme.defaultColorMode || "light";
const altColorMode = defaultColorMode === "light" ? "dark" : "light";
const styleName = `[data-theme="${theme.name}"][data-color-mode="${altColorMode}"]`;
const themeName = `[data-theme="${theme.name}"]`;
const { base, components, name, colors, palette, icons, vars, ...rest } = theme;
cssVars[styleName] = toCSSVars({
colors: removeDuplicate(colors[altColorMode], colors[defaultColorMode])
});
cssVars[themeName] = toCSSVars({
...rest,
colors: colors[defaultColorMode]
});
return cssVars;
};
export {
getThemeVars,
hasMultipleArgs,
mapCSSVars,
mergeTheme,
spacingUtil
};