fix(system): extend variants fuction adapted (#1927)

This commit is contained in:
Junior Garcia 2023-11-08 11:15:10 -03:00 committed by GitHub
parent 9189b3fbf2
commit 6ecdc278ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 61 additions and 23 deletions

View File

@ -0,0 +1,5 @@
---
"@nextui-org/system-rsc": patch
---
Fix #1921 `extendVariants` function adapted to consider props variants over `defaultVariants`.

View File

@ -182,7 +182,9 @@ const MyButton2 = extendVariants(Button, {
xl: "px-12 py-6 text-xl",
},
},
defaultVariants: {},
defaultVariants: {
color: "foreground",
},
});
const usersData = [
@ -544,7 +546,7 @@ export default function NextUIPerf() {
<Button>Click Me!</Button>
<MyButton2 color="foreground">Press Me!</MyButton2>
<MyButton2 color="primary">Press Me!</MyButton2>
<Pagination
showControls

View File

@ -21,7 +21,40 @@ function getSlots(variants) {
: {};
}
function getClassNamesWithProps({props, defaultVariants, customTv, hasSlots}) {
function getClassNamesWithProps({
props = {},
variants,
slots,
defaultVariants,
compoundVariants,
hasSlots,
opts,
}) {
// Do not apply default variants when the props variant is different
if (defaultVariants && typeof defaultVariants === "object") {
for (const key in defaultVariants) {
const value = defaultVariants[key];
const propValue = props?.[key];
if (propValue && propValue !== value) {
delete defaultVariants[key];
}
}
}
const customTv = tv(
{
variants,
defaultVariants,
compoundVariants,
...(hasSlots && {slots}),
},
{
twMerge: opts.twMerge ?? true,
twMergeConfig: opts.twMergeConfig ?? {},
},
);
const [baseProps, variantProps] = mapPropsVariants(props, customTv.variantKeys, false);
const newProps = {...defaultVariants, ...baseProps};
@ -62,26 +95,21 @@ export function extendVariants(BaseComponent, styles = {}, opts = {}) {
const slots = getSlots(variants);
const hasSlots = typeof slots === "object" && Object.keys(slots).length !== 0;
const customTv = tv(
{
variants,
defaultVariants,
compoundVariants,
...(hasSlots && {slots}),
},
{
twMerge: opts.twMerge ?? true,
twMergeConfig: opts.twMergeConfig ?? {},
},
);
const ForwardedComponent = React.forwardRef((originalProps = {}, ref) => {
const newProps = getClassNamesWithProps({
props: originalProps,
defaultVariants,
customTv,
hasSlots,
});
const newProps = React.useMemo(() =>
getClassNamesWithProps(
{
slots,
variants,
compoundVariants,
props: originalProps,
defaultVariants,
hasSlots,
opts,
},
[originalProps],
),
);
return React.createElement(BaseComponent, {...originalProps, ...newProps, ref});
});
@ -90,10 +118,13 @@ export function extendVariants(BaseComponent, styles = {}, opts = {}) {
if (BaseComponent.getCollectionNode) {
ForwardedComponent.getCollectionNode = (itemProps) => {
const newProps = getClassNamesWithProps({
slots,
variants,
compoundVariants,
props: itemProps,
defaultVariants,
customTv,
hasSlots,
opts,
});
return BaseComponent.getCollectionNode({...itemProps, ...newProps});