dynamic-theme-utilities
Version:
The dynamic-theme-utilities is a JavaScript package designed to facilitate the creation and manipulation of dynamic themes, particularly for Material Design color schemes.
49 lines (42 loc) • 1.47 kB
JavaScript
// --dtu stands for dynamic theme utils this prefix helps you to
// recognize colors generated by this library
// This function generates css variables from the theme object
// It takes two arguments
// 1. theme: object
// 2. prefix: string
// If you don't provide a prefix it will use --dtu-sys as a default prefix
// It returns an object with css variables
export const generateCssVariables = (theme, prefix = "--dtu-sys") => {
const cssVariables = {};
for (const key in theme) {
if (typeof theme[key] === "object" && !Array.isArray(theme[key])) {
let keys = Object.keys(theme[key]);
if (
keys.includes("r") &&
keys.includes("g") &&
keys.includes("b") &&
keys.includes("a")
) {
const rgb = Object.entries(theme[key])
.filter(([key]) => key !== "a") // Exclude the 'a' key
.map(([, value]) => value) // Get the values
.join(" "); // Join them together
cssVariables[`${prefix}-${key}`] = rgb;
} else {
const nestedVariables = generateCssVariables(
theme[key],
`${prefix}-${key}`,
);
for (const nestedKey in nestedVariables) {
cssVariables[nestedKey] = nestedVariables[nestedKey];
}
}
} else {
if (key === "r" || key === "g" || key === "b" || key === "a") {
continue;
}
cssVariables[`${prefix}-${key}`] = theme[key];
}
}
return cssVariables;
};