forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolveProps.ts
49 lines (46 loc) · 1.79 KB
/
resolveProps.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
/**
* Add keys, values of `defaultProps` that does not exist in `props`
* @param {object} defaultProps
* @param {object} props
* @returns {object} resolved props
*/
export default function resolveProps<
T extends {
components?: Record<string, unknown>;
componentsProps?: Record<string, unknown>;
slots?: Record<string, unknown>;
slotProps?: Record<string, unknown>;
} & Record<string, unknown>,
>(defaultProps: T, props: T) {
const output = { ...props };
(Object.keys(defaultProps) as Array<keyof T>).forEach((propName) => {
if (propName.toString().match(/^(components|slots)$/)) {
output[propName] = {
...(defaultProps[propName] as any),
...(output[propName] as any),
};
} else if (propName.toString().match(/^(componentsProps|slotProps)$/)) {
const defaultSlotProps = (defaultProps[propName] || {}) as T[keyof T];
const slotProps = props[propName] as {} as T[keyof T];
output[propName] = {} as T[keyof T];
if (!slotProps || !Object.keys(slotProps)) {
// Reduce the iteration if the slot props is empty
output[propName] = defaultSlotProps;
} else if (!defaultSlotProps || !Object.keys(defaultSlotProps)) {
// Reduce the iteration if the default slot props is empty
output[propName] = slotProps;
} else {
output[propName] = { ...slotProps };
Object.keys(defaultSlotProps).forEach((slotPropName) => {
(output[propName] as Record<string, unknown>)[slotPropName] = resolveProps(
(defaultSlotProps as Record<string, any>)[slotPropName],
(slotProps as Record<string, any>)[slotPropName],
);
});
}
} else if (output[propName] === undefined) {
output[propName] = defaultProps[propName];
}
});
return output;
}