Skip to content

Commit

Permalink
[@mantine/styles] Improve useComponentDefaultProps types (#2065)
Browse files Browse the repository at this point in the history
* fix(CompDefaultProps): comp default props type

* fix: prettier

* fix: use input props

* fix: use input props

Co-authored-by: cong <cong.li@carbonnt.com>
  • Loading branch information
congyaqwq and cong committed Oct 24, 2022
1 parent 88ecf88 commit 965fb64
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 8 deletions.
6 changes: 3 additions & 3 deletions src/mantine-core/src/Input/use-input-props.ts
Expand Up @@ -8,9 +8,9 @@ interface BaseProps extends InputWrapperBaseProps, InputSharedProps, DefaultProp
id?: string;
}

export function useInputProps<T extends BaseProps>(
export function useInputProps<T extends BaseProps, U extends Partial<T>>(
component: string,
defaultProps: Partial<T>,
defaultProps: U,
props: T
) {
const {
Expand All @@ -35,7 +35,7 @@ export function useInputProps<T extends BaseProps>(
inputWrapperOrder,
withAsterisk,
...others
} = useComponentDefaultProps(component, defaultProps, props);
} = useComponentDefaultProps<T>(component, defaultProps, props);

const uid = useId(id);

Expand Down
12 changes: 9 additions & 3 deletions src/mantine-styles/src/theme/MantineProvider.tsx
Expand Up @@ -41,11 +41,17 @@ export function useMantineEmotionCache() {
return useContext(MantineProviderContext)?.emotionCache;
}

export function useComponentDefaultProps<T extends Record<string, any>>(
export function useComponentDefaultProps<T extends Record<string, any>, U extends Partial<T> = {}>(
component: string,
defaultProps: Partial<T>,
defaultProps: U,
props: T
): T {
): [keyof U] extends [keyof T]
? T
: {
[Key in Exclude<keyof T, keyof U>]: T[Key];
} & {
[Key in Extract<keyof T, keyof U>]-?: U[Key] & T[Key];
} {
const theme = useMantineTheme();
const contextProps = theme.components[component]?.defaultProps;
return { ...defaultProps, ...contextProps, ...filterProps(props) };
Expand Down
@@ -1,8 +1,12 @@
type FilterPropsRes<T extends Record<string, any>> = {
[Key in keyof T]-?: T[Key] extends undefined ? never : T[Key];
};

export function filterProps<T extends Record<string, any>>(props: T) {
return Object.keys(props).reduce<T>((acc, key: keyof T) => {
return Object.keys(props).reduce<FilterPropsRes<T>>((acc, key: keyof T) => {
if (props[key] !== undefined) {
acc[key] = props[key];
}
return acc;
}, {} as T);
}, {} as FilterPropsRes<T>);
}

0 comments on commit 965fb64

Please sign in to comment.