forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeSlotProps.ts
69 lines (67 loc) · 2.61 KB
/
mergeSlotProps.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { SlotComponentProps } from '@mui/utils';
import clsx from 'clsx';
export default function mergeSlotProps<
T extends SlotComponentProps<React.ElementType, {}, {}>,
K = T,
// infer external slot props first to provide autocomplete for default slot props
U = T extends Function ? T : K extends Function ? K : T extends undefined ? K : T,
>(externalSlotProps: T | undefined, defaultSlotProps: K): U {
if (!externalSlotProps) {
return defaultSlotProps as unknown as U;
}
if (typeof externalSlotProps === 'function' || typeof defaultSlotProps === 'function') {
return ((ownerState: Record<string, any>) => {
const defaultSlotPropsValue =
typeof defaultSlotProps === 'function' ? defaultSlotProps(ownerState) : defaultSlotProps;
const externalSlotPropsValue =
typeof externalSlotProps === 'function'
? externalSlotProps({ ...ownerState, ...defaultSlotPropsValue })
: externalSlotProps;
const className = clsx(
ownerState?.className,
defaultSlotPropsValue?.className,
externalSlotPropsValue?.className,
);
return {
...defaultSlotPropsValue,
...externalSlotPropsValue,
...(!!className && { className }),
...(defaultSlotPropsValue?.style &&
externalSlotPropsValue?.style && {
style: { ...defaultSlotPropsValue.style, ...externalSlotPropsValue.style },
}),
...(defaultSlotPropsValue?.sx &&
externalSlotPropsValue?.sx && {
sx: [
...(Array.isArray(defaultSlotPropsValue.sx)
? defaultSlotPropsValue.sx
: [defaultSlotPropsValue.sx]),
...(Array.isArray(externalSlotPropsValue.sx)
? externalSlotPropsValue.sx
: [externalSlotPropsValue.sx]),
],
}),
};
}) as U;
}
const typedDefaultSlotProps = defaultSlotProps as Record<string, any>;
const className = clsx(typedDefaultSlotProps?.className, externalSlotProps?.className);
return {
...defaultSlotProps,
...externalSlotProps,
...(!!className && { className }),
...(typedDefaultSlotProps?.style &&
externalSlotProps?.style && {
style: { ...typedDefaultSlotProps.style, ...externalSlotProps.style },
}),
...(typedDefaultSlotProps?.sx &&
externalSlotProps?.sx && {
sx: [
...(Array.isArray(typedDefaultSlotProps.sx)
? typedDefaultSlotProps.sx
: [typedDefaultSlotProps.sx]),
...(Array.isArray(externalSlotProps.sx) ? externalSlotProps.sx : [externalSlotProps.sx]),
],
}),
} as U;
}