Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: rm style tokenKey #213

Merged
merged 5 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions docs/demo/auto-clear.md

This file was deleted.

37 changes: 0 additions & 37 deletions docs/examples/auto-clear.tsx

This file was deleted.

6 changes: 3 additions & 3 deletions docs/examples/components/Button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ const Button = ({ className, type, ...restProps }: ButtonProps) => {
const ghostCls = `${prefixCls}-ghost`;

// 全局注册,内部会做缓存优化
const wrapSSR = useStyleRegister(
useStyleRegister(
{ theme, token, hashId, path: [prefixCls] },
() => [
genDefaultButtonStyle(defaultCls, token),
Expand All @@ -128,11 +128,11 @@ const Button = ({ className, type, ...restProps }: ButtonProps) => {
} as any
)[type as any] || defaultCls;

return wrapSSR(
return (
<button
className={classNames(prefixCls, typeCls, hashId, className, cssVarKey)}
{...restProps}
/>,
/>
);
};

Expand Down
6 changes: 3 additions & 3 deletions docs/examples/components/Spin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ const Spin = ({ className, ...restProps }: SpinProps) => {
const [theme, token, hashId] = useToken();

// 全局注册,内部会做缓存优化
const wrapSSR = useStyleRegister(
useStyleRegister(
{ theme, token, hashId, path: [prefixCls] },
() => [genSpinStyle(prefixCls, token)],
);

return wrapSSR(
<div className={classNames(prefixCls, hashId, className)} {...restProps} />,
return (
<div className={classNames(prefixCls, hashId, className)} {...restProps} />
);
};

Expand Down
4 changes: 2 additions & 2 deletions docs/examples/components/theme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ export function useToken(): [
[defaultDesignToken, rootDesignToken],
{
salt: typeof hashed === 'string' ? hashed : '',
cssVar: cssVar && {
cssVar: {
prefix: 'rc',
key: cssVar.key,
key: cssVar?.key || 'css-var-root',
unitless: {
lineHeight: true,
},
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/css-var.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function App() {
{show && (
<div>
<DesignTokenContext.Provider
value={{ cssVar: { key: 'default' }, hashed: true }}
value={{ cssVar: { key: 'default' }, hashed: false }}
>
<Button>Default</Button>
<Button type="primary">Primary</Button>
Expand All @@ -36,7 +36,7 @@ export default function App() {
value={{
token: { primaryColor: 'green' },
cssVar: { key: 'default2' },
hashed: true,
hashed: false,
}}
>
<Button>Default</Button>
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"@ctrl/tinycolor": "^3.4.0",
"@rc-component/father-plugin": "^1.0.1",
"@testing-library/jest-dom": "^5.16.3",
"@testing-library/react": "^13.0.0",
"@testing-library/react": "^14.0.0",
"@types/classnames": "^2.2.9",
"@types/enzyme": "^3.10.11",
"@types/react": "^18.0.0",
Expand Down
1 change: 0 additions & 1 deletion src/StyleContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ export function createCache() {
export type HashPriority = 'low' | 'high';

export interface StyleContextProps {
autoClear?: boolean;
/** @private Test only. Not work in production. */
mock?: 'server' | 'client';
/**
Expand Down
91 changes: 38 additions & 53 deletions src/hooks/useCacheToken.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export interface Option<DerivativeToken, DesignToken> {
/**
* Transform token to css variables.
*/
cssVar?: {
cssVar: {
/** Prefix for css variables */
prefix?: string;
/** Tokens that should not be appended with unit */
Expand All @@ -65,7 +65,7 @@ export interface Option<DerivativeToken, DesignToken> {
/** Tokens that preserves origin value */
preserve?: Record<string, boolean>;
/** Key for current theme. Useful for customizing and should be unique */
key?: string;
key: string;
};
}

Expand All @@ -86,7 +86,7 @@ function removeStyleTags(key: string, instanceId: string) {
}
}

const TOKEN_THRESHOLD = 0;
const TOKEN_THRESHOLD = -1;

// Remove will check current keys first
function cleanTokenStyle(tokenKey: string, instanceId: string) {
Expand Down Expand Up @@ -136,9 +136,9 @@ export const getComputedToken = <
export const TOKEN_PREFIX = 'token';

type TokenCacheValue<DerivativeToken> = [
token: DerivativeToken & { _tokenKey: string; _themeKey: string },
token: DerivativeToken,
hashId: string,
realToken: DerivativeToken & { _tokenKey: string },
realToken: DerivativeToken,
cssVarStr: string,
cssVarKey: string,
];
Expand All @@ -156,7 +156,7 @@ export default function useCacheToken<
>(
theme: Theme<any, any>,
tokens: Partial<DesignToken>[],
option: Option<DerivativeToken, DesignToken> = {},
option: Option<DerivativeToken, DesignToken>,
): TokenCacheValue<DerivativeToken> {
const {
cache: { instanceId },
Expand All @@ -182,68 +182,53 @@ export default function useCacheToken<
TOKEN_PREFIX,
[salt, theme.id, tokenStr, overrideTokenStr, cssVarStr],
() => {
let mergedDerivativeToken = compute
const mergedDerivativeToken = compute
? compute(mergedToken, override, theme)
: getComputedToken(mergedToken, override, theme, formatToken);

// Replace token value with css variables
const actualToken = { ...mergedDerivativeToken };
let cssVarsStr = '';
if (!!cssVar) {
[mergedDerivativeToken, cssVarsStr] = transformToken(
mergedDerivativeToken,
cssVar.key!,
{
prefix: cssVar.prefix,
ignore: cssVar.ignore,
unitless: cssVar.unitless,
preserve: cssVar.preserve,
},
);
}
const [tokenWithCssVar, cssVarsStr] = transformToken(
mergedDerivativeToken,
cssVar.key,
{
prefix: cssVar.prefix,
ignore: cssVar.ignore,
unitless: cssVar.unitless,
preserve: cssVar.preserve,
},
) as [any, string];

// Optimize for `useStyleRegister` performance
const tokenKey = token2key(mergedDerivativeToken, salt);
mergedDerivativeToken._tokenKey = tokenKey;
actualToken._tokenKey = token2key(actualToken, salt);
const mergedSalt = `${salt}_${cssVar.prefix || ''}`;
actualToken._tokenKey = token2key(actualToken, mergedSalt);

const themeKey = cssVar?.key ?? tokenKey;
mergedDerivativeToken._themeKey = themeKey;
const themeKey = cssVar.key;
recordCleanToken(themeKey);

const hashId = `${hashPrefix}-${hash(tokenKey)}`;
mergedDerivativeToken._hashId = hashId; // Not used
const hashId = `${hashPrefix}-${hash(mergedSalt)}`;

return [
mergedDerivativeToken,
hashId,
actualToken,
cssVarsStr,
cssVar?.key || '',
];
return [tokenWithCssVar, hashId, actualToken, cssVarsStr, cssVar.key];
},
(cache) => {
([, , , , themeKey]) => {
// Remove token will remove all related style
cleanTokenStyle(cache[0]._themeKey, instanceId);
cleanTokenStyle(themeKey, instanceId);
},
([token, , , cssVarsStr]) => {
if (cssVar && cssVarsStr) {
const style = updateCSS(
cssVarsStr,
hash(`css-variables-${token._themeKey}`),
{
mark: ATTR_MARK,
prepend: 'queue',
attachTo: container,
priority: -999,
},
);

(style as any)[CSS_IN_JS_INSTANCE] = instanceId;

// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, token._themeKey);
([, , , cssVarsStr, themeKey]) => {
if (!cssVarsStr) {
return;
}
const style = updateCSS(cssVarsStr, hash(`css-var-${themeKey}`), {
mark: ATTR_MARK,
prepend: 'queue',
attachTo: container,
priority: -999,
});

(style as any)[CSS_IN_JS_INSTANCE] = instanceId;

// Used for `useCacheToken` to remove on batch when token removed
style.setAttribute(ATTR_TOKEN, themeKey);
},
);

Expand Down
Loading