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] Add avatar component #1210

Merged
merged 21 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from 20 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
20 changes: 20 additions & 0 deletions docs/reference/generated/avatar-fallback.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "AvatarFallback",
"description": "Rendered when the image fails to load or when no image is provided.\nRenders a `<span>` element.",
"props": {
"delay": {
"type": "number",
"description": "How long to wait before showing the fallback. Specified in milliseconds."
},
"className": {
"type": "string | (state) => string",
"description": "CSS class applied to the element, or a function that\nreturns a class based on the component’s state."
},
"render": {
"type": "React.ReactElement | (props, state) => React.ReactElement",
"description": "Allows you to replace the component’s HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
}
},
"dataAttributes": {},
"cssVariables": {}
}
20 changes: 20 additions & 0 deletions docs/reference/generated/avatar-image.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "AvatarImage",
"description": "The image to be displayed in the avatar.\nRenders an `<img>` element.",
"props": {
"onLoadingStatusChange": {
"type": "(status) => void",
"description": "Callback fired when the loading status changes."
},
"className": {
"type": "string | (state) => string",
"description": "CSS class applied to the element, or a function that\nreturns a class based on the component’s state."
},
"render": {
"type": "React.ReactElement | (props, state) => React.ReactElement",
"description": "Allows you to replace the component’s HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
}
},
"dataAttributes": {},
"cssVariables": {}
}
16 changes: 16 additions & 0 deletions docs/reference/generated/avatar-root.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "AvatarRoot",
"description": "Displays a user's profile picture, initials, or fallback icon.\nRenders a `<span>` element.",
"props": {
"className": {
"type": "string | (state) => string",
"description": "CSS class applied to the element, or a function that\nreturns a class based on the component’s state."
},
"render": {
"type": "React.ReactElement | (props, state) => React.ReactElement",
"description": "Allows you to replace the component’s HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
}
},
"dataAttributes": {},
"cssVariables": {}
}
8 changes: 8 additions & 0 deletions docs/reference/overrides/avatar-image.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "AvatarImage",
"props": {
"onLoadingStatusChange": {
"type": "(status) => void"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
.Root {
display: inline-flex;
justify-content: center;
align-items: center;
vertical-align: middle;
border-radius: 100%;
user-select: none;
font-weight: 500;
color: var(--color-gray-900);
background-color: var(--color-gray-100);
font-size: 1rem;
line-height: 1;
overflow: hidden;
height: 3rem;
width: 3rem;
}

.Image {
object-fit: cover;
height: 100%;
width: 100%;
}

.Fallback {
align-items: center;
display: flex;
justify-content: center;
height: 100%;
width: 100%;
font-size: 1rem;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as React from 'react';
import { Avatar } from '@base-ui-components/react/avatar';
import styles from './index.module.css';

export default function ExampleAvatar() {
return (
<div style={{ display: 'flex', gap: 20 }}>
<Avatar.Root className={styles.Root}>
<Avatar.Image
src="https://images.unsplash.com/photo-1543610892-0b1f7e6d8ac1?w=128&h=128&dpr=2&q=80"
width="48"
height="48"
className={styles.Image}
/>
<Avatar.Fallback className={styles.Fallback}>LT</Avatar.Fallback>
</Avatar.Root>
<Avatar.Root className={styles.Root}>LT</Avatar.Root>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
'use client';
export { default as CssModules } from './css-modules';
export { default as Tailwind } from './tailwind';
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as React from 'react';
import { Avatar } from '@base-ui-components/react/avatar';

export default function ExampleAvatar() {
return (
<div style={{ display: 'flex', gap: 20 }}>
<Avatar.Root className="inline-flex size-12 items-center justify-center overflow-hidden rounded-full bg-gray-100 align-middle text-base font-medium text-black select-none">
<Avatar.Image
src="https://images.unsplash.com/photo-1543610892-0b1f7e6d8ac1?w=128&h=128&dpr=2&q=80"
width="48"
height="48"
className="size-full object-cover"
/>
<Avatar.Fallback className="flex size-full items-center justify-center text-base">
LT
</Avatar.Fallback>
</Avatar.Root>
<Avatar.Root className="inline-flex size-12 items-center justify-center overflow-hidden rounded-full bg-gray-100 align-middle text-base font-medium text-black select-none">
LT
</Avatar.Root>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Avatar

<Subtitle>An easily stylable avatar component.</Subtitle>
<Meta
name="description"
content="A high-quality, unstyled React avatar component that is easy to customize."
/>

<Demo path="./demos/hero" />

## API reference

Import the component and assemble its parts:

```jsx title="Anatomy"
import { Avatar } from '@base-ui-components/react/avatar';

<Avatar.Root>
<Avatar.Image src="" />
<Avatar.Fallback>LT</Avatar.Fallback>
</Avatar.Root>;
```

<Reference component="Avatar" parts="Root, Image, Fallback" />
4 changes: 4 additions & 0 deletions docs/src/nav.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ export const nav = [
label: 'Alert Dialog',
href: '/react/components/alert-dialog',
},
{
label: 'Avatar',
href: '/react/components/avatar',
},
{
label: 'Checkbox',
href: '/react/components/checkbox',
Expand Down
1 change: 1 addition & 0 deletions packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
".": "./src/index.ts",
"./accordion": "./src/accordion/index.ts",
"./alert-dialog": "./src/alert-dialog/index.ts",
"./avatar": "./src/avatar/index.ts",
"./checkbox": "./src/checkbox/index.ts",
"./checkbox-group": "./src/checkbox-group/index.ts",
"./collapsible": "./src/collapsible/index.ts",
Expand Down
69 changes: 69 additions & 0 deletions packages/react/src/avatar/fallback/AvatarFallback.test.tsx
Copy link
Member

Choose a reason for hiding this comment

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

We could use a test that verifies if the fallback is displayed when the image fails to load and a one testing the delay prop.

Copy link
Member

Choose a reason for hiding this comment

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

Added in 98457eb

Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import * as React from 'react';
import { Mock } from 'vitest';
import { Avatar } from '@base-ui-components/react/avatar';
import { describeConformance, createRenderer } from '#test-utils';
import { useImageLoadingStatus } from '../image/useImageLoadingStatus';

vi.mock('../image/useImageLoadingStatus');

describe('<Avatar.Fallback />', () => {
const { render } = createRenderer();

afterEach(() => {
vi.clearAllMocks();
});

describeConformance(<Avatar.Fallback />, () => ({
render: (node) => {
return render(<Avatar.Root>{node}</Avatar.Root>);
},
refInstanceof: window.HTMLSpanElement,
}));

it('should not render the children if the image loaded', async () => {
(useImageLoadingStatus as Mock).mockReturnValue('loaded');

const { queryByTestId } = await render(
<Avatar.Root>
<Avatar.Image />
<Avatar.Fallback data-testid="fallback" />
</Avatar.Root>,
);

expect(queryByTestId('fallback')).to.equal(null);
});

it('should render the fallback if the image fails to load', async () => {
(useImageLoadingStatus as Mock).mockReturnValue('error');

const { queryByText } = await render(
<Avatar.Root>
<Avatar.Image />
<Avatar.Fallback>AC</Avatar.Fallback>
</Avatar.Root>,
);

expect(queryByText('AC')).to.not.equal(null);
});

describe('prop: delay', () => {
const { clock, render: renderFakeTimers } = createRenderer();

clock.withFakeTimers();

it('shows the fallback when the delay has elapsed', async () => {
const { queryByText } = await renderFakeTimers(
<Avatar.Root>
<Avatar.Image />
<Avatar.Fallback delay={100}>AC</Avatar.Fallback>
</Avatar.Root>,
);

expect(queryByText('AC')).to.equal(null);

clock.tick(100);

expect(queryByText('AC')).to.not.equal(null);
});
});
});
91 changes: 91 additions & 0 deletions packages/react/src/avatar/fallback/AvatarFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import { BaseUIComponentProps } from '../../utils/types';
import { useComponentRenderer } from '../../utils/useComponentRenderer';
import { useAvatarRootContext } from '../root/AvatarRootContext';
import type { AvatarRoot } from '../root/AvatarRoot';

/**
* Rendered when the image fails to load or when no image is provided.
* Renders a `<span>` element.
*
* Documentation: [Base UI Avatar](https://base-ui.com/react/components/avatar)
*/
const AvatarFallback = React.forwardRef<HTMLSpanElement, AvatarFallback.Props>(
function AvatarFallback(props: AvatarFallback.Props, forwardedRef) {
const { className, render, delay, ...otherProps } = props;

const { imageLoadingStatus } = useAvatarRootContext();
const [delayPassed, setDelayPassed] = React.useState(delay === undefined);

React.useEffect(() => {
let timerId: number | undefined;

if (delay !== undefined) {
timerId = window.setTimeout(() => setDelayPassed(true), delay);
}

return () => {
window.clearTimeout(timerId);
};
}, [delay]);

const state: AvatarRoot.State = React.useMemo(
() => ({
imageLoadingStatus,
}),
[imageLoadingStatus],
);

const { renderElement } = useComponentRenderer({
render: render ?? 'span',
state,
className,
ref: forwardedRef,
extraProps: otherProps,
});

const shouldRender = imageLoadingStatus !== 'loaded' && delayPassed;

return shouldRender ? renderElement() : null;
},
);

export namespace AvatarFallback {
export interface Props extends BaseUIComponentProps<'span', AvatarRoot.State> {
/**
* How long to wait before showing the fallback. Specified in milliseconds.
*/
delay?: number;
}
}

export { AvatarFallback };

AvatarFallback.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the TypeScript types and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* @ignore
*/
children: PropTypes.node,
/**
* CSS class applied to the element, or a function that
* returns a class based on the component’s state.
*/
className: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
/**
* How long to wait before showing the fallback. Specified in milliseconds.
*/
delay: PropTypes.number,
/**
* Allows you to replace the component’s HTML element
* with a different tag, or compose it with another component.
*
* Accepts a `ReactElement` or a function that returns the element to render.
*/
render: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
} as any;
17 changes: 17 additions & 0 deletions packages/react/src/avatar/image/AvatarImage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as React from 'react';
import { Avatar } from '@base-ui-components/react/avatar';
import { describeConformance, createRenderer } from '#test-utils';

describe('<Avatar.Image />', () => {
const { render } = createRenderer();
vi.mock('./useImageLoadingStatus', () => ({
useImageLoadingStatus: () => 'loaded',
}));

describeConformance(<Avatar.Image />, () => ({
render: (node) => {
return render(<Avatar.Root>{node}</Avatar.Root>);
},
refInstanceof: window.HTMLImageElement,
}));
});
Loading