2022-03-24 18:44:42 +08:00
|
|
|
import useMemo from 'rc-util/lib/hooks/useMemo';
|
|
|
|
import shallowEqual from 'shallowequal';
|
2022-06-27 14:25:59 +08:00
|
|
|
import type { OverrideToken } from '../../theme/interface';
|
2022-03-24 18:44:42 +08:00
|
|
|
import type { ThemeConfig } from '../context';
|
|
|
|
|
|
|
|
export default function useTheme(
|
|
|
|
theme?: ThemeConfig,
|
|
|
|
parentTheme?: ThemeConfig,
|
|
|
|
): ThemeConfig | undefined {
|
|
|
|
const themeConfig = theme || {};
|
|
|
|
const parentThemeConfig = parentTheme || {};
|
|
|
|
|
|
|
|
const mergedTheme = useMemo<ThemeConfig | undefined>(
|
|
|
|
() => {
|
|
|
|
if (!theme) {
|
|
|
|
return parentTheme;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Override
|
|
|
|
const mergedOverride = {
|
2022-09-15 21:26:04 +08:00
|
|
|
...parentThemeConfig.components,
|
2022-03-24 18:44:42 +08:00
|
|
|
};
|
|
|
|
|
2022-09-15 21:26:04 +08:00
|
|
|
Object.keys(theme.components || {}).forEach((componentName: keyof OverrideToken) => {
|
2022-03-24 18:44:42 +08:00
|
|
|
mergedOverride[componentName] = {
|
|
|
|
...mergedOverride[componentName],
|
2022-09-15 21:26:04 +08:00
|
|
|
...theme.components![componentName],
|
2022-03-24 18:44:42 +08:00
|
|
|
} as any;
|
|
|
|
});
|
|
|
|
|
|
|
|
// Base token
|
|
|
|
const merged = {
|
|
|
|
...parentThemeConfig,
|
|
|
|
...themeConfig,
|
|
|
|
|
|
|
|
token: {
|
|
|
|
...parentThemeConfig.token,
|
|
|
|
...themeConfig.token,
|
|
|
|
},
|
|
|
|
override: mergedOverride,
|
|
|
|
};
|
|
|
|
|
|
|
|
return merged;
|
|
|
|
},
|
|
|
|
[themeConfig, parentThemeConfig],
|
|
|
|
(prev, next) =>
|
|
|
|
prev.some((prevTheme, index) => {
|
|
|
|
const nextTheme = next[index];
|
|
|
|
|
|
|
|
return !shallowEqual(prevTheme, nextTheme);
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
|
|
|
return mergedTheme;
|
|
|
|
}
|