Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[material-ui] Add merging function to mergeSlotProps utility #45543

Merged
merged 15 commits into from
Mar 18, 2025
91 changes: 50 additions & 41 deletions docs/data/material/guides/composition/composition.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,47 +27,56 @@ WrappedIcon.muiName = Icon.muiName;
Use the `mergeSlotProps` utility function to merge custom props with the slot props.
If the arguments are functions then they'll be resolved before merging, and the result from the first argument will override the second.

```jsx
import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { mergeSlotProps } from '@mui/material/utils';

export const CustomTooltip = (props: TooltipProps) => {
const { children, title, sx: sxProps } = props;

return (
<Tooltip
{...props}
title={<Box sx={{ p: 4 }}>{title}</Box>}
slotProps={{
...props.slotProps,
popper: mergeSlotProps(props.slotProps?.popper, {
className: 'custom-tooltip-popper',
disablePortal: true,
placement: 'top',
}),
}}
>
{children}
</Tooltip>
);
};
```

:::info
`className` values are concatenated rather than overriding one another.
In the snippet above, the `custom-tooltip-popper` class is applied to the Tooltip's popper slot.
If you added another `className` via the `slotProps` prop on the Custom Tooltip—as shown below—then both would be present on the rendered popper slot:

```js
<CustomTooltip slotProps={{ popper: { className: 'foo' } }} />
```

The popper slot in the original example would now have both classes applied to it, in addition to any others that may be present: `"[…] custom-tooltip-popper foo"`.
:::

:::info
`style` object are shallow merged rather than replacing one another. The style keys from the first argument have higher priority.
:::
Special properties that merged between the two arguments are listed below:

- `className`: values are concatenated rather than overriding one another.

In the snippet below, the `custom-tooltip-popper` class is applied to the Tooltip's popper slot.

```jsx
import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { mergeSlotProps } from '@mui/material/utils';

export const CustomTooltip = (props: TooltipProps) => {
const { children, title, sx: sxProps } = props;

return (
<Tooltip
{...props}
title={<Box sx={{ p: 4 }}>{title}</Box>}
slotProps={{
...props.slotProps,
popper: mergeSlotProps(props.slotProps?.popper, {
className: 'custom-tooltip-popper',
disablePortal: true,
placement: 'top',
}),
}}
>
{children}
</Tooltip>
);
};
```

If you added another `className` via the `slotProps` prop on the Custom Tooltip—as shown below—then both would be present on the rendered popper slot:

```js
<CustomTooltip slotProps={{ popper: { className: 'foo' } }} />
```

The popper slot in the original example would now have both classes applied to it, in addition to any others that may be present: `"[…] custom-tooltip-popper foo"`.

- `style`: object are shallow merged rather than replacing one another. The style keys from the first argument have higher priority.
- `sx`: values are concatenated into an array.
- `^on[A-Z]` event handlers: these functions are composed between the two arguments.

```js
mergeSlotProps(props.slotProps?.popper, {
onClick: (event) => {}, // composed with the `slotProps?.popper?.onClick`
createPopper: (popperOptions) => {}, // overridden by the `slotProps?.popper?.createPopper`
});
```

## Component prop

Expand Down
25 changes: 25 additions & 0 deletions packages/mui-material/src/utils/mergeSlotProps.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as React from 'react';
import { expectType } from '@mui/types';
import Box from '@mui/material/Box';
import Dialog, { DialogProps } from '@mui/material/Dialog';
import Tooltip, { TooltipProps } from '@mui/material/Tooltip';
import { mergeSlotProps, SlotComponentProps } from '@mui/material/utils';

Expand Down Expand Up @@ -62,3 +63,27 @@ export const CustomTooltip2 = (props: TooltipProps) => {
</Tooltip>
);
};

type SimpleDialogProps = Omit<DialogProps, 'children' | 'onClose'> & {
onClose: () => void;
};
function UserDetailsDialog(props: SimpleDialogProps) {
const { onClose, slotProps: dialogSlotProps, ...dialogProps } = props;

return (
<Dialog
onClose={() => onClose()}
slotProps={{
...dialogSlotProps,
transition: mergeSlotProps(dialogSlotProps?.transition, {
onExited: (node) => {
expectType<HTMLElement, typeof node>(node);
},
}),
}}
{...dialogProps}
>
content
</Dialog>
);
}
42 changes: 42 additions & 0 deletions packages/mui-material/src/utils/mergeSlotProps.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { SxProps } from '@mui/material/styles';

import mergeSlotProps from './mergeSlotProps';
Expand Down Expand Up @@ -202,5 +203,46 @@ describe('utils/index.js', () => {
'aria-label': 'bar',
});
});

it('automatically merge function based on the default slot props', () => {
const slotPropsOnClick = spy();
const defaultPropsOnClick = spy();

const defaultPropsOnChange = spy();

const slotPropsFoo = spy();
const defaultPropsFoo = spy();

const mergedSlotProps = mergeSlotProps<{
onClick: (arg1: string, arg2: string) => string;
onChange?: (arg1: string, arg2: string) => string;
foo: (arg1: string, arg2: string) => string;
}>(
{
onClick: slotPropsOnClick,
foo: slotPropsFoo,
},
{
onClick: defaultPropsOnClick,
onChange: defaultPropsOnChange,
foo: defaultPropsFoo,
},
);

mergedSlotProps.onClick('arg1', 'arg2');
expect(defaultPropsOnClick.callCount).to.equal(1);
expect(defaultPropsOnClick.args[0]).to.deep.equal(['arg1', 'arg2']);
expect(slotPropsOnClick.callCount).to.equal(1);
expect(slotPropsOnClick.args[0]).to.deep.equal(['arg1', 'arg2']);

mergedSlotProps.onChange?.('arg1', 'arg2');
expect(defaultPropsOnChange.callCount).to.equal(1);
expect(defaultPropsOnChange.args[0]).to.deep.equal(['arg1', 'arg2']);

mergedSlotProps.foo('arg1', 'arg2');
expect(defaultPropsFoo.callCount).to.equal(0);
expect(slotPropsFoo.callCount).to.equal(1);
expect(slotPropsFoo.args[0]).to.deep.equal(['arg1', 'arg2']);
});
});
});
39 changes: 39 additions & 0 deletions packages/mui-material/src/utils/mergeSlotProps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { SlotComponentProps } from '@mui/utils';
import clsx from 'clsx';

// Brought from [Base UI](https://github.com/mui/base-ui/blob/master/packages/react/src/merge-props/mergeProps.ts#L119)
// Use it directly from Base UI once it's a package dependency.
function isEventHandler(key: string, value: unknown) {
// This approach is more efficient than using a regex.
const thirdCharCode = key.charCodeAt(2);
return (
key[0] === 'o' &&
key[1] === 'n' &&
thirdCharCode >= 65 /* A */ &&
thirdCharCode <= 90 /* Z */ &&
typeof value === 'function'
);
}

export default function mergeSlotProps<
T extends SlotComponentProps<React.ElementType, {}, {}>,
K = T,
Expand All @@ -10,6 +24,26 @@ export default function mergeSlotProps<
if (!externalSlotProps) {
return defaultSlotProps as unknown as U;
}
function extractHandlers(
externalSlotPropsValue: Record<string, any>,
defaultSlotPropsValue: Record<string, any>,
) {
const handlers: Record<string, Function> = {};

Object.keys(defaultSlotPropsValue).forEach((key) => {
if (
isEventHandler(key, defaultSlotPropsValue[key]) &&
typeof externalSlotPropsValue[key] === 'function'
) {
// only compose the handlers if both default and external slot props match the event handler
handlers[key] = (...args: unknown[]) => {
externalSlotPropsValue[key](...args);
defaultSlotPropsValue[key](...args);
};
}
});
return handlers;
}
if (typeof externalSlotProps === 'function' || typeof defaultSlotProps === 'function') {
return ((ownerState: Record<string, any>) => {
const defaultSlotPropsValue =
Expand All @@ -24,9 +58,12 @@ export default function mergeSlotProps<
defaultSlotPropsValue?.className,
externalSlotPropsValue?.className,
);
const handlers = extractHandlers(externalSlotPropsValue, defaultSlotPropsValue);

return {
...defaultSlotPropsValue,
...externalSlotPropsValue,
...handlers,
...(!!className && { className }),
...(defaultSlotPropsValue?.style &&
externalSlotPropsValue?.style && {
Expand All @@ -47,10 +84,12 @@ export default function mergeSlotProps<
}) as U;
}
const typedDefaultSlotProps = defaultSlotProps as Record<string, any>;
const handlers = extractHandlers(externalSlotProps, typedDefaultSlotProps);
const className = clsx(typedDefaultSlotProps?.className, externalSlotProps?.className);
return {
...defaultSlotProps,
...externalSlotProps,
...handlers,
...(!!className && { className }),
...(typedDefaultSlotProps?.style &&
externalSlotProps?.style && {
Expand Down
Loading
Loading