@madeja-studio/telar
Version:
UI component library by Madeja Studio
48 lines (46 loc) • 1.51 kB
JavaScript
;
import { createContext, useContext } from 'react';
import { merge } from 'smob';
import { theme as fallbackTheme } from "./theme.js";
import { jsx as _jsx } from "react/jsx-runtime";
const ThemeContext = /*#__PURE__*/createContext({});
/**
* Takes an unresolved theme and traverses all its properties calling whatever
* values have not been yet resolved (functions that depend on other theme values).
*
* The algorithm does not take into account dependency between elements inside the theme.
* It just calls functions to return their value, but if that function depends on unresolved
* values, it will just fail (returning a fn for something that should be a value).
*/
const resolveTheme = (obj, context) => {
switch (typeof obj) {
case 'function':
return obj(context);
case 'object':
{
const resolvedObj = {};
for (const entry of Object.entries(obj)) {
const [key, value] = entry;
resolvedObj[key] = resolveTheme(value, context);
}
return resolvedObj;
}
default:
return obj;
}
};
const ThemeContextProvider = ({
children,
theme = {}
}) => {
const mergedTheme = merge(theme, fallbackTheme);
return /*#__PURE__*/_jsx(ThemeContext.Provider, {
value: {
theme: resolveTheme(mergedTheme, mergedTheme.core)
},
children: children
});
};
export const useTheme = () => useContext(ThemeContext);
export default ThemeContextProvider;
//# sourceMappingURL=ThemeContextProvider.js.map