@hitachivantara/uikit-react-core
Version:
Core React components for the NEXT Design System.
89 lines (88 loc) • 2.87 kB
JavaScript
import { themes } from "../themes/index.js";
import { getContainerElement, getElementById } from "./document.js";
const setElementAttrs = (themeName, modeName, colorScheme, themeRootId) => {
const element = getContainerElement(themeRootId);
if (element) {
element.setAttribute(`data-theme`, themeName);
element.setAttribute(`data-color-mode`, modeName);
element.classList.add(`uikit-root-element`);
element.style.colorScheme = colorScheme;
}
};
const applyThemeCustomizations = (obj, customizations) => {
const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
const customizedTheme = { ...obj };
Object.keys(customizations).forEach((key) => {
if (customizedTheme[key]) {
if (isObject(customizedTheme[key]) && isObject(customizations[key])) {
customizedTheme[key] = applyThemeCustomizations(
customizedTheme[key],
customizations[key]
);
} else if (typeof customizedTheme[key] === typeof customizations[key]) {
customizedTheme[key] = customizations[key];
}
} else {
customizedTheme[key] = customizations[key];
}
});
return customizedTheme;
};
const createTheme = (props) => {
const {
name,
base = "ds5",
inheritColorModes = true,
...customizations
} = props;
const customizedTheme = customizations ? applyThemeCustomizations(themes[base], customizations) : { ...themes[base] };
customizedTheme.name = name.trim();
customizedTheme.base = base;
if (customizations) {
Object.keys(customizedTheme.colors.modes).forEach((mode) => {
if (!themes[base].colors.modes[mode]) {
customizedTheme.colors.modes[mode] = {
...themes[base].colors.modes.dawn,
...customizedTheme.colors.modes[mode]
};
}
});
}
if (!inheritColorModes && customizations.colors?.modes) {
Object.keys(customizedTheme.colors.modes).forEach((mode) => {
if (!Object.keys(customizations.colors?.modes || {}).includes(mode)) {
delete customizedTheme.colors.modes[mode];
}
});
}
return customizedTheme;
};
const processThemes = (themesList) => {
if (themesList && Array.isArray(themesList) && themesList.length > 0) {
const list = [];
themesList.forEach((thm) => {
const i = list.findIndex(
(t) => t.name.trim() === thm.name.trim()
);
if (i !== -1) {
list.splice(i, 1);
list.push(thm);
} else {
list.push(thm);
}
});
return list;
}
return [themes.ds5];
};
const getVarValue = (cssVar, rootElementId) => {
const root = getElementById(rootElementId || "hv-root");
if (!root) return void 0;
return getComputedStyle(root).getPropertyValue(cssVar.replace("var(", "").replace(")", "")).trim();
};
export {
createTheme,
getVarValue,
processThemes,
setElementAttrs
};