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

[Avatar] Fix img slot types and add missing slots #45483

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,34 @@ If both `slotProps.root` and additional props have the same keys but different v
This does not apply to classes or the `style` prop—they will be merged instead.
:::

### Type safety

The `slotProps` prop is not dynamically typed based on the custom `slots` prop, so if the custom slot has a different type than the default slot, you have to cast the type to avoid TypeScript errors and use `satisfies` (available in TypeScript 4.9) to ensure type safety for the custom slot.

The example below shows how to customize the `img` slot of the [Avatar](/material-ui/react-avatar/) component using [Next.js Image](https://nextjs.org/docs/app/api-reference/components/image) component:

```tsx
import Image, { ImageProps } from 'next/image';
import Avatar, { AvatarProps } from '@mui/material/Avatar';

<Avatar
slots={{
img: Image,
}}
slotProps={
{
img: {
src: 'https://example.com/image.jpg',
alt: 'Image',
width: 40,
height: 40,
blurDataURL: 'data:image/png;base64',
} satisfies ImageProps,
} as AvatarProps['slotProps']
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unnecessary assertion

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case, it's still required because the slotProps.img has a fixed structure that's different from ImageProps.

If you exclude the line, TS throws an error.

}
/>;
```

## Best practices

Use the `component` or `slotProps.{slot}.component` prop when you need to override the element while preserving the styles of the slot.
Expand Down
38 changes: 22 additions & 16 deletions docs/pages/material-ui/api/avatar.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@
},
"sizes": { "type": { "name": "string" } },
"slotProps": {
"type": { "name": "shape", "description": "{ img?: func<br>&#124;&nbsp;object }" },
"type": {
"name": "shape",
"description": "{ fallback?: func<br>&#124;&nbsp;object, img?: func<br>&#124;&nbsp;object, root?: func<br>&#124;&nbsp;object }"
},
"default": "{}"
},
"slots": {
"type": { "name": "shape", "description": "{ img?: elementType }" },
"type": {
"name": "shape",
"description": "{ fallback?: elementType, img?: elementType, root?: elementType }"
},
"default": "{}"
},
"src": { "type": { "name": "string" } },
Expand All @@ -41,11 +47,23 @@
"import { Avatar } from '@mui/material';"
],
"slots": [
{
"name": "root",
"description": "The component that renders the root slot.",
"default": "'div'",
"class": "MuiAvatar-root"
},
{
"name": "img",
"description": "The component that renders the transition.\n[Follow this guide](https://mui.com/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is wrong.

"default": "Collapse",
"description": "The component that renders the img slot.",
"default": "'img'",
"class": "MuiAvatar-img"
},
{
"name": "fallback",
"description": "The component that renders the fallback slot.",
"default": "Person icon",
"class": "MuiAvatar-fallback"
}
],
"classes": [
Expand All @@ -61,18 +79,6 @@
"description": "Styles applied to the root element if not `src` or `srcSet`.",
"isGlobal": false
},
{
"key": "fallback",
"className": "MuiAvatar-fallback",
"description": "Styles applied to the fallback icon",
"isGlobal": false
},
{
"key": "root",
"className": "MuiAvatar-root",
"description": "Styles applied to the root element.",
"isGlobal": false
},
{
"key": "rounded",
"className": "MuiAvatar-rounded",
Expand Down
6 changes: 3 additions & 3 deletions docs/translations/api-docs/avatar/avatar.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@
"nodeName": "the root element",
"conditions": "not <code>src</code> or <code>srcSet</code>"
},
"fallback": { "description": "Styles applied to the fallback icon" },
"root": { "description": "Styles applied to the root element." },
"rounded": {
"description": "Styles applied to {{nodeName}} if {{conditions}}.",
"nodeName": "the root element",
Expand All @@ -53,6 +51,8 @@
}
},
"slotDescriptions": {
"img": "The component that renders the transition. <a href=\"https://mui.com/material-ui/transitions/#transitioncomponent-prop\">Follow this guide</a> to learn more about the requirements for this component."
"fallback": "The component that renders the fallback slot.",
"img": "The component that renders the img slot.",
"root": "The component that renders the root slot."
}
}
42 changes: 35 additions & 7 deletions packages/mui-material/src/Avatar/Avatar.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,52 @@ import { Theme } from '../styles';
import { OverridableComponent, OverrideProps } from '../OverridableComponent';
import { AvatarClasses } from './avatarClasses';
import { CreateSlotsAndSlotProps, SlotProps } from '../utils/types';
import { SvgIconProps } from '../SvgIcon';

export interface AvatarSlots {
/**
* The component that renders the transition.
* [Follow this guide](https://mui.com/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Collapse
* The component that renders the root slot.
* @default 'div'
*/
img: React.JSXElementConstructor<React.ImgHTMLAttributes<HTMLImageElement>>;
root: React.ElementType;
/**
* The component that renders the img slot.
* @default 'img'
*/
img: React.ElementType;
/**
* The component that renders the fallback slot.
* @default Person icon
*/
fallback: React.ElementType;
}

export interface AvatarPropsVariantOverrides {}

export interface AvatarRootSlotPropsOverrides {}
export interface AvatarImgSlotPropsOverrides {}
export interface AvatarFallbackSlotPropsOverrides {}

export type AvatarSlotsAndSlotProps = CreateSlotsAndSlotProps<
AvatarSlots,
{
img: SlotProps<
React.ElementType<React.ImgHTMLAttributes<HTMLImageElement>>,
{},
/**
* Props forwarded to the root slot.
* By default, the avaible props are based on the div element.
*/
root: SlotProps<'div', AvatarRootSlotPropsOverrides, AvatarOwnProps>;
/**
* Props forwarded to the img slot.
* By default, the avaible props are based on the img element.
*/
img: SlotProps<'img', AvatarImgSlotPropsOverrides, AvatarOwnProps>;
/**
* Props forwarded to the fallback slot.
* By default, the avaible props are based on the [SvgIcon](https://mui.com/material-ui/api/svg-icon/#props) component.
*/
fallback: SlotProps<
React.ElementType<SvgIconProps>,
AvatarFallbackSlotPropsOverrides,
AvatarOwnProps
>;
}
Expand Down
42 changes: 30 additions & 12 deletions packages/mui-material/src/Avatar/Avatar.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,19 @@ const Avatar = React.forwardRef(function Avatar(inProps, ref) {

const classes = useUtilityClasses(ownerState);

const [RootSlot, rootSlotProps] = useSlot('root', {
ref,
className: clsx(classes.root, className),
elementType: AvatarRoot,
externalForwardedProps: {
slots,
slotProps,
component,
...other,
},
ownerState,
});

const [ImgSlot, imgSlotProps] = useSlot('img', {
className: classes.img,
elementType: AvatarImg,
Expand All @@ -196,6 +209,17 @@ const Avatar = React.forwardRef(function Avatar(inProps, ref) {
ownerState,
});

const [FallbackSlot, fallbackSlotProps] = useSlot('fallback', {
className: classes.fallback,
elementType: AvatarFallback,
externalForwardedProps: {
slots,
slotProps,
},
shouldForwardComponentProp: true,
ownerState,
});

if (hasImgNotFailing) {
children = <ImgSlot {...imgSlotProps} />;
// We only render valid children, non valid children are rendered with a fallback
Expand All @@ -205,20 +229,10 @@ const Avatar = React.forwardRef(function Avatar(inProps, ref) {
} else if (hasImg && alt) {
children = alt[0];
} else {
children = <AvatarFallback ownerState={ownerState} className={classes.fallback} />;
children = <FallbackSlot {...fallbackSlotProps} />;
}

return (
<AvatarRoot
as={component}
className={clsx(classes.root, className)}
ref={ref}
{...other}
ownerState={ownerState}
>
{children}
</AvatarRoot>
);
return <RootSlot {...rootSlotProps}>{children}</RootSlot>;
});

Avatar.propTypes /* remove-proptypes */ = {
Expand Down Expand Up @@ -264,14 +278,18 @@ Avatar.propTypes /* remove-proptypes */ = {
* @default {}
*/
slotProps: PropTypes.shape({
fallback: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
img: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
}),
/**
* The components used for each slot inside.
* @default {}
*/
slots: PropTypes.shape({
fallback: PropTypes.elementType,
img: PropTypes.elementType,
root: PropTypes.elementType,
}),
/**
* The `src` attribute for the `img` element.
Expand Down
55 changes: 55 additions & 0 deletions packages/mui-material/src/Avatar/Avatar.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,58 @@ function CustomImg() {
}
<Avatar slotProps={{ img: { alt: '' } }} />;
<Avatar slots={{ img: CustomImg }} />;

// Next.js Image component
interface StaticImageData {
src: string;
height: number;
width: number;
blurDataURL?: string;
blurWidth?: number;
blurHeight?: number;
}
interface StaticRequire {
default: StaticImageData;
}
type StaticImport = StaticRequire | StaticImageData;

type ImageLoaderProps = {
src: string;
width: number;
quality?: number;
};

type ImageLoader = (p: ImageLoaderProps) => string;

type PlaceholderValue = 'blur' | 'empty' | `data:image/${string}`;

type OnLoadingComplete = (img: HTMLImageElement) => void;

declare const Image: React.ForwardRefExoticComponent<
Omit<
React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>,
'height' | 'width' | 'loading' | 'ref' | 'alt' | 'src' | 'srcSet'
> & {
src: string | StaticImport;
alt: string;
width?: number | `${number}`;
height?: number | `${number}`;
fill?: boolean;
loader?: ImageLoader;
quality?: number | `${number}`;
priority?: boolean;
loading?: 'eager' | 'lazy' | undefined;
placeholder?: PlaceholderValue;
blurDataURL?: string;
unoptimized?: boolean;
overrideSrc?: string;
onLoadingComplete?: OnLoadingComplete;
layout?: string;
objectFit?: string;
objectPosition?: string;
lazyBoundary?: string;
lazyRoot?: string;
} & React.RefAttributes<HTMLImageElement | null>
>;

<Avatar slots={{ img: Image }} />;
8 changes: 8 additions & 0 deletions packages/mui-material/src/Avatar/Avatar.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ describe('<Avatar />', () => {
testDeepOverrides: { slotName: 'fallback', slotClassName: classes.fallback },
testVariantProps: { variant: 'foo' },
testStateOverrides: { prop: 'variant', value: 'rounded', styleKey: 'rounded' },
slots: {
root: {
expectedClassName: classes.root,
},
fallback: {
expectedClassName: classes.fallback,
},
},
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cannot test the img slot together with fallback here because there is a logic within the component that dynamically render either one of them.

skip: ['componentsProp'],
}));

Expand Down