forked from mui/material-ui
/
useSlotProps.ts
88 lines (83 loc) · 2.46 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
import * as React from 'react';
import { unstable_useForkRef as useForkRef } from '@mui/utils';
import appendOwnerState from './appendOwnerState';
import mergeSlotProps, { MergeSlotPropsParameters, WithCommonProps } from './mergeSlotProps';
import resolveComponentProps from './resolveComponentProps';
export type UseSlotPropsParameters<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps,
OwnerState,
> = Omit<
MergeSlotPropsParameters<SlotProps, ExternalForwardedProps, ExternalSlotProps, AdditionalProps>,
'externalSlotProps'
> & {
/**
* The type of the component used in the slot.
*/
elementType: React.ElementType;
/**
* The `componentsProps.*` of the unstyled component.
*/
externalSlotProps:
| ExternalSlotProps
| ((ownerState: OwnerState) => ExternalSlotProps)
| undefined;
/**
* The ownerState of the unstyled component.
*/
ownerState: OwnerState;
};
export type UseSlotPropsResult<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps,
OwnerState,
> = Omit<SlotProps & ExternalSlotProps & ExternalForwardedProps & AdditionalProps, 'ref'> & {
className?: string | undefined;
ownerState?: OwnerState | undefined;
ref: (instance: any | null) => void;
};
/**
* 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<
SlotProps,
ExternalForwardedProps,
ExternalSlotProps,
AdditionalProps,
OwnerState,
>(
parameters: UseSlotPropsParameters<
SlotProps,
ExternalForwardedProps,
WithCommonProps<ExternalSlotProps>,
WithCommonProps<AdditionalProps>,
OwnerState
>,
) {
const { elementType, externalSlotProps, ownerState, ...rest } = parameters;
const resolvedComponentsProps = resolveComponentProps(externalSlotProps, ownerState);
const merged = mergeSlotProps({
...rest,
externalSlotProps: resolvedComponentsProps,
});
const props = appendOwnerState(
elementType,
{
...merged.props,
ref: useForkRef(
merged.internalRef,
useForkRef(resolvedComponentsProps?.ref, parameters.additionalProps?.ref),
),
},
ownerState,
);
return props;
}