Skip to content

Commit

Permalink
feat: extractStyles support types config (#169)
Browse files Browse the repository at this point in the history
* feat: extractStyles support types config

* chore: add test
  • Loading branch information
MadCcc authored Dec 20, 2023
1 parent 343567c commit c0056d1
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/extractStyle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,26 @@ const ExtractStyleFns = {
[CSS_VAR_PREFIX]: cssVarExtractStyle,
};

type ExtractStyleType = keyof typeof ExtractStyleFns;

function isNotNull<T>(value: T | null): value is T {
return value !== null;
}

export default function extractStyle(cache: Cache, plain = false) {
export default function extractStyle(
cache: Cache,
options?:
| boolean
| {
plain?: boolean;
types?: ExtractStyleType | ExtractStyleType[];
},
) {
const { plain = false, types = ['style', 'token', 'cssVar'] } =
typeof options === 'boolean' ? { plain: options } : options || {};

const matchPrefixRegexp = new RegExp(
`^(${Object.keys(ExtractStyleFns).join('|')})%`,
`^(${(typeof types === 'string' ? [types] : types).join('|')})%`,
);

// prefix with `style` is used for `useStyleRegister` to cache style context
Expand Down
28 changes: 28 additions & 0 deletions tests/css-variables.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -460,4 +460,32 @@ describe('CSS Variables', () => {
styles.some((style) => style.textContent?.includes('var(--bank-')),
).toBe(true);
});

it('could extract cssVar only', () => {
const cache = createCache();
render(
<StyleProvider cache={cache}>
<DesignTokenProvider
theme={{
cssVar: {
key: 'apple',
},
}}
>
<Box className="target" />
</DesignTokenProvider>
</StyleProvider>,
);

const cssVarStyle = extractStyle(cache, {
types: ['cssVar', 'token'],
plain: true,
});
const styleStyle = extractStyle(cache, { types: 'style', plain: true });

expect(cssVarStyle).toContain('--rc-line-height:1.5;');
expect(cssVarStyle).not.toContain('line-height:var(--rc-line-height)');
expect(styleStyle).toContain('line-height:var(--rc-line-height)');
expect(styleStyle).not.toContain('--rc-line-height:1.5;');
});
});

0 comments on commit c0056d1

Please sign in to comment.