ant-design/components/theme/useToken.ts
MadCcc 94b3d03765
feat: component token support algorithm (#43810)
* feat: component theme

* feat: component token support algorith,

* docs: fix form

* chore: add test

* chore: fix test case

* chore: code clean

* chore: code clean

* chore: code clean

* docs: update toc

* chore: update cssinjs

* chore
2023-07-27 11:31:38 +08:00

79 lines
2.2 KiB
TypeScript

import type { Theme } from '@ant-design/cssinjs';
import { useCacheToken } from '@ant-design/cssinjs';
import React from 'react';
import version from '../version';
import type { AliasToken, GlobalToken, MapToken, SeedToken } from './interface';
import type { DesignTokenProviderProps } from './context';
import { defaultTheme, DesignTokenContext } from './context';
import defaultSeedToken from './themes/seed';
import formatToken from './util/alias';
export const getComputedToken = (
originToken: SeedToken,
overrideToken: DesignTokenProviderProps['components'] & {
override?: Partial<AliasToken>;
},
theme: Theme<any, any>,
) => {
const derivativeToken = theme.getDerivativeToken(originToken);
const { override, ...components } = overrideToken;
// Merge with override
let mergedDerivativeToken = {
...derivativeToken,
override,
};
// Format if needed
mergedDerivativeToken = formatToken(mergedDerivativeToken);
if (components) {
Object.entries(components).forEach(([key, value]) => {
const { theme: componentTheme, ...componentTokens } = value;
let mergedComponentToken = componentTokens;
if (componentTheme) {
mergedComponentToken = getComputedToken(
{
...mergedDerivativeToken,
...componentTokens,
},
{
override: componentTokens,
},
componentTheme,
);
}
mergedDerivativeToken[key] = mergedComponentToken;
});
}
return mergedDerivativeToken;
};
// ================================== Hook ==================================
export default function useToken(): [Theme<SeedToken, MapToken>, GlobalToken, string] {
const {
token: rootDesignToken,
hashed,
theme,
components,
} = React.useContext(DesignTokenContext);
const salt = `${version}-${hashed || ''}`;
const mergedTheme = theme || defaultTheme;
const [token, hashId] = useCacheToken<GlobalToken, SeedToken>(
mergedTheme,
[defaultSeedToken, rootDesignToken],
{
salt,
override: { override: rootDesignToken, ...components },
getComputedToken,
},
);
return [mergedTheme, token, hashed ? hashId : ''];
}