Skip to content

Commit

Permalink
test: cssVarRegister
Browse files Browse the repository at this point in the history
  • Loading branch information
MadCcc committed Oct 25, 2023
1 parent bb2dd58 commit cf12c02
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 33 deletions.
8 changes: 3 additions & 5 deletions src/hooks/useCSSVarRegister.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ import type { TokenWithCSSVar } from '../util/css-variables';
import { transformToken } from '../util/css-variables';
import useGlobalCache from './useGlobalCache';

const useCSSVarRegister = <T>(
const useCSSVarRegister = <V, T extends Record<string, V>>(
config: {
path: string[];
key: string;
prefix?: string;
unitless?: Record<string, boolean>;
token: any;
},
fn: () => Record<string, T>,
fn: () => T,
) => {
const { key, prefix, unitless, token } = config;
const {
Expand All @@ -31,9 +31,7 @@ const useCSSVarRegister = <T>(

const fullPath = [...config.path, key, tokenKey];

const cache = useGlobalCache<
[TokenWithCSSVar<T>, string, Record<string, T>, string]
>(
const cache = useGlobalCache<[TokenWithCSSVar<T>, string, T, string]>(
'variables',
fullPath,
() => {
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useStyleRegister/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ export default function useStyleRegister(
// == SSR ==
// ============================================================================
export function extractStyle(cache: Cache, plain = false) {
const matchPrefixRegexp = /^(style|variables|token)%/;
const matchPrefixRegexp = /^style%/;

// prefix with `style` is used for `useStyleRegister` to cache style context
const styleKeys = Array.from(cache.cache.keys()).filter((key) =>
Expand Down
2 changes: 1 addition & 1 deletion src/util/css-variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const serializeCSSVar = <T extends Record<string, any>>(
};

export type TokenWithCSSVar<T> = {
[key in keyof T]?: string | TokenWithCSSVar<T>;
[key in keyof T]?: string;
};

export const transformToken = <
Expand Down
87 changes: 61 additions & 26 deletions tests/css-variables.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ import { render } from '@testing-library/react';
import classNames from 'classnames';
import type { PropsWithChildren } from 'react';
import React from 'react';
import { createTheme, unit, useCacheToken, useStyleRegister } from '../src';
import {
createTheme,
unit,
useCacheToken,
useCSSVarRegister,
useStyleRegister,
} from '../src';

export interface DesignToken {
primaryColor: string;
Expand Down Expand Up @@ -81,35 +87,49 @@ const DesignTokenProvider: React.FC<
);
};

function useToken(): [DerivativeToken, string, string | undefined] {
function useToken(): [DerivativeToken, string, string, DerivativeToken] {
const {
token: rootDesignToken = {},
hashed,
cssVar,
} = React.useContext(DesignTokenContext);

const [token, hashId] = useCacheToken<DerivativeToken, DesignToken>(
theme,
[defaultDesignToken, rootDesignToken],
{
salt: typeof hashed === 'string' ? hashed : '',
cssVar: cssVar && {
prefix: 'rc',
key: cssVar.key,
unitless: {
lineHeight: true,
},
ignore: {
lineHeightBase: true,
},
const [token, hashId, realToken] = useCacheToken<
DerivativeToken,
DesignToken
>(theme, [defaultDesignToken, rootDesignToken], {
salt: typeof hashed === 'string' ? hashed : '',
cssVar: cssVar && {
prefix: 'rc',
key: cssVar.key,
unitless: {
lineHeight: true,
},
ignore: {
lineHeightBase: true,
},
},
);
return [token, hashed ? hashId : '', cssVar?.key];
});
return [token, hashed ? hashId : '', cssVar?.key || '', realToken];
}

const useStyle = () => {
const [token, hashId, cssVarKey] = useToken();
const [token, hashId, cssVarKey, realToken] = useToken();

const getComponentToken = () => ({ boxColor: '#5c21ff' });

const [cssVarToken] = useCSSVarRegister(
{
path: ['Box'],
key: cssVarKey,
token: realToken,
prefix: 'rc-box',
unitless: {
lineHeight: true,
},
},
cssVarKey ? getComponentToken : () => ({}),
);

useStyleRegister(
{
Expand All @@ -119,12 +139,20 @@ const useStyle = () => {
path: ['Box'],
},
() => {
// @ts-ignore
const mergedToken: DerivativeToken & { boxColor: string } = {
...token,
...(cssVarKey ? cssVarToken : getComponentToken()),
};

return {
'.box': {
lineHeight: token.lineHeight,
border: `${unit(token.borderWidth)} solid ${token.borderColor}`,
color: '#fff',
backgroundColor: token.primaryColor,
lineHeight: mergedToken.lineHeight,
border: `${unit(mergedToken.borderWidth)} solid ${
mergedToken.borderColor
}`,
color: mergedToken.boxColor,
backgroundColor: mergedToken.primaryColor,
},
};
},
Expand Down Expand Up @@ -163,10 +191,11 @@ describe('CSS Variables', () => {
const styles = Array.from(document.head.querySelectorAll('style'));
const box = container.querySelector('.target')!;

expect(styles.length).toBe(2);
expect(styles.length).toBe(3);
expect(styles[0].textContent).toContain('.apple{');
expect(styles[0].textContent).toContain('--rc-line-height:1.5;');
expect(styles[1].textContent).toContain(
expect(styles[1].textContent).toContain('--rc-box-box-color:#5c21ff');
expect(styles[2].textContent).toContain(
'line-height:var(--rc-line-height);',
);
expect(box).toHaveClass('apple');
Expand Down Expand Up @@ -217,13 +246,14 @@ describe('CSS Variables', () => {
);

const styles = Array.from(document.head.querySelectorAll('style'));
expect(styles).toHaveLength(5);
expect(styles).toHaveLength(7);

const nonCssVarBox = container.querySelector('.non-css-var')!;
expect(nonCssVarBox).toHaveStyle({
lineHeight: '1.5',
border: '1px solid black',
backgroundColor: '#1890ff',
color: '#5c21ff',
});

const cssVarBox = container.querySelector('.css-var')!;
Expand All @@ -232,9 +262,11 @@ describe('CSS Variables', () => {
'--rc-border-width': '1px',
'--rc-border-color': 'black',
'--rc-primary-color': '#1677ff',
'--rc-box-box-color': '#5c21ff',
lineHeight: 'var(--rc-line-height)',
border: 'var(--rc-border-width) solid var(--rc-border-color)',
backgroundColor: 'var(--rc-primary-color)',
color: 'var(--rc-box-box-color)',
});

const cssVarBox2 = container.querySelector('.css-var-2')!;
Expand All @@ -245,9 +277,11 @@ describe('CSS Variables', () => {
'--rc-border-width': '2px',
'--rc-border-color': 'black',
'--rc-primary-color': '#1677ff',
'--rc-box-box-color': '#5c21ff',
lineHeight: 'var(--rc-line-height)',
border: 'var(--rc-border-width) solid var(--rc-border-color)',
backgroundColor: 'var(--rc-primary-color)',
color: 'var(--rc-box-box-color)',
});

const nonCssVarBox2 = container.querySelector('.non-css-var-2')!;
Expand All @@ -257,6 +291,7 @@ describe('CSS Variables', () => {
lineHeight: '1.5',
border: '3px solid black',
backgroundColor: '#1677ff',
color: '#5c21ff',
});
});
});

0 comments on commit cf12c02

Please sign in to comment.