Skip to content
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
19 changes: 16 additions & 3 deletions src/util/genStyleUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,16 +165,21 @@ function genStyleUtils<
injectStyle?: boolean;
/**
* Extra prefixCls to inject CSS variables.
* 为额外的 prefixCls 注入 CSS 变量(不注入样式)。
*
* @example
* ```typescript
* {
* extraCssVarPrefixCls: ['my-comp-compact', 'my-comp-large']
* }
* // or
* {
* extraCssVarPrefixCls: ({ prefixCls, rootCls }) => [`${prefixCls}-container`]
* }
* ```
*/
extraCssVarPrefixCls?: string[];
extraCssVarPrefixCls?:
| string[]
| ((info: { prefixCls: string; rootCls: string }) => string[]);
},
) {
const componentName = Array.isArray(component) ? component[0] : component;
Expand Down Expand Up @@ -212,8 +217,16 @@ function genStyleUtils<

return (prefixCls: string, rootCls: string = prefixCls) => {
const hashId = useStyle(prefixCls, rootCls);

// Resolve function type to get dynamic extra prefix
const extraPrefixCls = options?.extraCssVarPrefixCls;
const resolvedExtraPrefixCls =
typeof extraPrefixCls === 'function'
? extraPrefixCls({ prefixCls, rootCls })
: extraPrefixCls;

const cssVarCls = useCSSVar(
options?.extraCssVarPrefixCls?.length ? [rootCls, ...options.extraCssVarPrefixCls] : rootCls,
resolvedExtraPrefixCls?.length ? [rootCls, ...resolvedExtraPrefixCls] : rootCls,
);

return [hashId, cssVarCls] as const;
Expand Down
41 changes: 41 additions & 0 deletions tests/extraCssVarPrefixCls.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,45 @@ describe('extraCssVarPrefixCls', () => {
expect(totalStyle).toContain('.custom-a');
expect(totalStyle).toContain('.custom-b');
});

it('should support function type for extraCssVarPrefixCls', () => {
const hooks = genStyleHooks(
'TestComponent',
(token) => ({
[`${token.componentCls}`]: {
color: token.colorPrimary,
fontSize: token.fontSize,
},
}),
() => ({
colorPrimary: '#ff0000',
fontSize: 16,
}),
{
extraCssVarPrefixCls: ({ prefixCls, rootCls }) => [
`${prefixCls}-container`,
`${rootCls}-wrapper`,
],
},
);

const TestComponent = () => {
const [hashId, cssVarCls] = hooks('custom-list', 'custom');
const className = [hashId, cssVarCls].filter(Boolean).join(' ');
return <div className={className}>{hashId}</div>;
};

render(
<StyleProvider cache={createCache()}>
<TestComponent />
</StyleProvider>,
);

const totalStyle = Array.from(document.querySelectorAll('style'))
.map((el) => el.textContent)
.join('\n');

expect(totalStyle).toContain('.custom-list-container');
expect(totalStyle).toContain('.custom-wrapper');
});
});