forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useSlotProps.ts
98 lines (92 loc) · 2.67 KB
/
useSlotProps.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import * as React from 'react';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import appendOwnerState, { AppendOwnerStateReturnType } from './appendOwnerState';
import mergeSlotProps, {
MergeSlotPropsParameters,
MergeSlotPropsResult,
WithCommonProps,
} from './mergeSlotProps';
import resolveComponentProps from './resolveComponentProps';
export type UseSlotPropsParameters<
ElementType extends React.ElementType,
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps,
OwnerState,
> = Omit<
MergeSlotPropsParameters<SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps>,
'externalSlotProps'
> & {
/**
* The type of the component used in the slot.
*/
elementType: ElementType | undefined;
/**
* The `slotProps.*` of the unstyled component.
*/
externalSlotProps:
| ExternalSlotProps
| ((ownerState: OwnerState) => ExternalSlotProps)
| undefined;
/**
* The ownerState of the unstyled component.
*/
ownerState: OwnerState;
};
export type UseSlotPropsResult<
ElementType extends React.ElementType,
SlotProps,
AdditionalProps,
OwnerState,
> = AppendOwnerStateReturnType<
ElementType,
MergeSlotPropsResult<SlotProps, object, object, AdditionalProps>['props'] & {
ref: ((instance: any | null) => void) | null;
},
OwnerState
>;
/**
* Builds the props to be passed into the slot of an unstyled component.
* It merges the internal props of the component with the ones supplied by the user, allowing to customize the behavior.
* If the slot component is not a host component, it also merges in the `ownerState`.
*
* @param parameters.getSlotProps - A function that returns the props to be passed to the slot component.
*/
export default function useSlotProps<
ElementType extends React.ElementType,
SlotProps,
AdditionalProps,
OwnerState,
>(
parameters: UseSlotPropsParameters<
ElementType,
SlotProps,
object,
WithCommonProps<Record<string, any>>,
AdditionalProps,
OwnerState
>,
) {
const { elementType, externalSlotProps, ownerState, ...rest } = parameters;
const resolvedComponentsProps = resolveComponentProps(externalSlotProps, ownerState);
const { props: mergedProps, internalRef } = mergeSlotProps({
...rest,
externalSlotProps: resolvedComponentsProps,
});
const ref = useForkRef(
internalRef,
resolvedComponentsProps?.ref,
parameters.additionalProps?.ref,
) as ((instance: any | null) => void) | null;
const props: UseSlotPropsResult<ElementType, SlotProps, AdditionalProps, OwnerState> =
appendOwnerState(
elementType,
{
...mergedProps,
ref,
},
ownerState,
);
return props;
}