-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
/
Copy pathappendOwnerState.ts
53 lines (48 loc) · 1.8 KB
/
appendOwnerState.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
import * as React from 'react';
import { Simplify } from '@mui/types';
import isHostComponent from '../isHostComponent';
/**
* Type of the ownerState based on the type of an element it applies to.
* This resolves to the provided OwnerState for React components and `undefined` for host components.
* Falls back to `OwnerState | undefined` when the exact type can't be determined in development time.
*/
type OwnerStateWhenApplicable<ElementType extends React.ElementType, OwnerState> =
ElementType extends React.ComponentType<any>
? OwnerState
: ElementType extends keyof React.JSX.IntrinsicElements
? undefined
: OwnerState | undefined;
export type AppendOwnerStateReturnType<
ElementType extends React.ElementType,
OtherProps,
OwnerState,
> = Simplify<
OtherProps & {
ownerState: OwnerStateWhenApplicable<ElementType, OwnerState>;
}
>;
/**
* Appends the ownerState object to the props, merging with the existing one if necessary.
*
* @param elementType Type of the element that owns the `existingProps`. If the element is a DOM node or undefined, `ownerState` is not applied.
* @param otherProps Props of the element.
* @param ownerState
*/
function appendOwnerState<
ElementType extends React.ElementType,
OtherProps extends Record<string, any>,
OwnerState,
>(
elementType: ElementType | undefined,
otherProps: OtherProps,
ownerState: OwnerState,
): AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState> {
if (elementType === undefined || isHostComponent(elementType)) {
return otherProps as AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState>;
}
return {
...otherProps,
ownerState: { ...otherProps.ownerState, ...ownerState },
} as AppendOwnerStateReturnType<ElementType, OtherProps, OwnerState>;
}
export default appendOwnerState;