Skip to content

The open alternative to Salesforce, designed for AI.

Expose Avatar parts and explicit interaction (#27640)

Raphaël Bosi59e631b9ab06
diff --git a/packages/twenty-docs/snippets/ui/generated/data-display/avatar.mdx b/packages/twenty-docs/snippets/ui/generated/data-display/avatar.mdx
index 4c8a35af98d..00ab8acd6df 100644
--- a/packages/twenty-docs/snippets/ui/generated/data-display/avatar.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/data-display/avatar.mdx
@@ -32,20 +32,20 @@
Stable value used to choose fallback colors. Defaults to `name`.
</ParamField>
-<ParamField body="disabled" type="boolean" default="false">
- Applies disabled styling and disables activation when `onClick` is supplied.
+<ParamField body="fallbackProps" type="AvatarFallbackProps">
+ Complete `Avatar.Fallback` props, including caller-owned children, labeling, refs, `render`, and fallback `delay` in milliseconds.
</ParamField>
<ParamField body="icon" type="ReactNode">
- Icon rendered instead of the image and first-letter fallback.
+ Decorative icon rendered instead of the image and first-letter fallback. Give the root an accessible label when the icon conveys information.
</ParamField>
-<ParamField body="name" type="string">
- Name used for the first-letter fallback and the default accessible name when clickable.
+<ParamField body="imageProps" type="AvatarImageProps">
+ Complete `Avatar.Image` props, including native image attributes, refs, `render`, `keepMounted`, and `onLoadingStatusChange`. Alternative text defaults to an empty string. Supply a nonempty `alt` to label the image and default fallback.
</ParamField>
-<ParamField body="nativeButton" type="boolean" default="true">
- Set to `false` when a clickable avatar uses `render` with an element other than a native button.
+<ParamField body="name" type="string">
+ Name used for the first-letter fallback and fallback colors. Does not add an accessible label.
</ParamField>
<ParamField body="pulsing" type="boolean" default="false">
@@ -53,10 +53,7 @@
</ParamField>
<ParamField body="render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, AvatarRootState&gt;">
- 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.
+ Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.
</ParamField>
<ParamField body="ring" type="boolean" default="false">
@@ -72,7 +69,7 @@
</ParamField>
<ParamField body="src" type="string | null">
- Image URL. A missing or failed image shows the fallback.
+ Image URL. A missing or failed image shows the fallback. `imageProps.src` overrides this value.
</ParamField>
<ParamField body="style" type="CSSProperties | ((state: AvatarRootState) =&gt; CSSProperties | undefined)">
@@ -83,3 +80,139 @@
<ParamField body="variant" type="&quot;outline&quot; | &quot;soft&quot;" default="soft">
Visual treatment of the fallback.
</ParamField>
+
+### Avatar.Root
+
+<ParamField body="Root.backgroundColor" type="string">
+ Background color override for a first-letter fallback.
+</ParamField>
+
+<ParamField body="Root.borderColor" type="string">
+ Border color override for the outline fallback.
+</ParamField>
+
+<ParamField body="Root.children" type="ReactNode">
+ Caller-owned Image, Fallback, and other content.
+</ParamField>
+
+<ParamField body="Root.className" type="string | ((state: AvatarRootState) =&gt; string | undefined)">
+ CSS class applied to the element, or a function that
+ returns a class based on the component's state.
+</ParamField>
+
+<ParamField body="Root.color" type="string">
+ Text color override for a first-letter fallback.
+</ParamField>
+
+<ParamField body="Root.colorSeed" type="string">
+ Stable value used to choose fallback colors. Defaults to `name`.
+</ParamField>
+
+<ParamField body="Root.name" type="string">
+ Name used to choose fallback colors. Does not add children or accessible labels.
+</ParamField>
+
+<ParamField body="Root.pulsing" type="boolean" default="false">
+ Animates the avatar opacity. Respects reduced-motion preferences.
+</ParamField>
+
+<ParamField body="Root.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, AvatarRootState&gt;">
+ Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.
+</ParamField>
+
+<ParamField body="Root.ring" type="boolean" default="false">
+ Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct.
+</ParamField>
+
+<ParamField body="Root.shape" type="&quot;circle&quot; | &quot;rounded-square&quot; | &quot;square&quot;" default="square">
+ Shape of the avatar and its fallback.
+</ParamField>
+
+<ParamField body="Root.size" type="&quot;lg&quot; | &quot;md&quot; | &quot;sm&quot; | &quot;xl&quot; | &quot;xs&quot;" default="md">
+ Avatar size: `xs` (12px), `sm` (14px), `md` (16px), `lg` (24px), or `xl` (40px).
+</ParamField>
+
+<ParamField body="Root.style" type="CSSProperties | ((state: AvatarRootState) =&gt; CSSProperties | undefined)">
+ Style applied to the element, or a function that
+ returns a style object based on the component's state.
+</ParamField>
+
+<ParamField body="Root.variant" type="&quot;outline&quot; | &quot;soft&quot;" default="soft">
+ Visual treatment of the fallback.
+</ParamField>
+
+### Avatar.Image
+
+<ParamField body="Image.alt" type="string">
+ Caller-owned alternative text. Use an empty string for decorative images.
+</ParamField>
+
+<ParamField body="Image.className" type="string | ((state: AvatarImageState) =&gt; string | undefined)">
+ CSS class applied to the element, or a function that
+ returns a class based on the component's state.
+</ParamField>
+
+<ParamField body="Image.crossOrigin" type="&quot;&quot; | &quot;anonymous&quot; | &quot;use-credentials&quot;">
+ Native image cross-origin policy, also used during preloading.
+</ParamField>
+
+<ParamField body="Image.keepMounted" type="boolean" default="false">
+ Keeps the image mounted and loads it in place. Loading and failed images stay hidden while Fallback is shown.
+</ParamField>
+
+<ParamField body="Image.loading" type="&quot;eager&quot; | &quot;lazy&quot;">
+ Native eager or lazy loading. Use keepMounted for lazy loading.
+</ParamField>
+
+<ParamField body="Image.onLoadingStatusChange" type="((status: ImageLoadingStatus) =&gt; void)">
+ Called when Base UI reports a loading, loaded, or error status. Shares that state with Root and Fallback.
+</ParamField>
+
+<ParamField body="Image.referrerPolicy" type="&quot;&quot; | &quot;no-referrer-when-downgrade&quot; | &quot;no-referrer&quot; | &quot;origin-when-cross-origin&quot; | &quot;origin&quot; | &quot;same-origin&quot; | &quot;strict-origin-when-cross-origin&quot; | &quot;strict-origin&quot; | &quot;unsafe-url&quot;">
+ Native image referrer policy, also used during preloading.
+</ParamField>
+
+<ParamField body="Image.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;DetailedHTMLProps&lt;ImgHTMLAttributes&lt;HTMLImageElement&gt;, HTMLImageElement&gt;, AvatarImageState&gt;">
+ Replaces the image. Preserve a native image and forward the supplied attributes, events, and ref.
+</ParamField>
+
+<ParamField body="Image.sizes" type="string">
+ Native responsive image sizes used with srcSet.
+</ParamField>
+
+<ParamField body="Image.src" type="string">
+ Image URL. Image renders after a successful load unless keepMounted is enabled.
+</ParamField>
+
+<ParamField body="Image.srcSet" type="string">
+ Native responsive image source candidates.
+</ParamField>
+
+<ParamField body="Image.style" type="CSSProperties | ((state: AvatarImageState) =&gt; CSSProperties | undefined)">
+ Style applied to the element, or a function that
+ returns a style object based on the component's state.
+</ParamField>
+
+### Avatar.Fallback
+
+<ParamField body="Fallback.children" type="ReactNode">
+ Caller-owned fallback content, such as initials or an icon.
+</ParamField>
+
+<ParamField body="Fallback.className" type="string | ((state: AvatarFallbackState) =&gt; string | undefined)">
+ CSS class applied to the element, or a function that
+ returns a class based on the component's state.
+</ParamField>
+
+<ParamField body="Fallback.delay" type="number" default="0">
+ Milliseconds before the initial fallback is shown. Defaults to 0.
+</ParamField>
+
+<ParamField body="Fallback.render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, AvatarFallbackState&gt;">
+ Replaces the fallback span. Forward the supplied props and ref, and provide its accessible label or decorative attributes.
+</ParamField>
+
+<ParamField body="Fallback.style" type="CSSProperties | ((state: AvatarFallbackState) =&gt; CSSProperties | undefined)">
+ Style applied to the element, or a function that
+ returns a style object based on the component's state.
+</ParamField>
diff --git a/packages/twenty-docs/ui/components/data-display/avatar-group.mdx b/packages/twenty-docs/ui/components/data-display/avatar-group.mdx
index 5e08e34cbd1..97e0f3d1bea 100644
--- a/packages/twenty-docs/ui/components/data-display/avatar-group.mdx
+++ b/packages/twenty-docs/ui/components/data-display/avatar-group.mdx
@@ -25,13 +25,13 @@ export const TeamAvatars = () => (
'Katherine',
'Joan',
].map((name) => (
- <Avatar key={name} name={name} />
+ <Avatar key={name} name={name} imageProps={{ alt: name }} />
))}
/>
);
```
-Supply stable keys to keep surviving avatars mounted when the limit, total, or display order changes. Keep the member names available in surrounding content.
+Supply stable keys to keep surviving avatars mounted when the limit, total, or display order changes. Avatars are decorative by default. When the group is the only representation of its members, supply each member's name through `imageProps.alt` to label the image and default fallback. Keep avatars decorative when visible text or an owner label already supplies that identity.
<StoryEmbed
storyId="ui-data-display-avatargroup--with-derived-overflow"
@@ -52,7 +52,7 @@ export const LoadedTeamAvatars = () => (
maxVisible={3}
total={20}
avatars={['Ada', 'Grace', 'Margaret'].map((name) => (
- <Avatar key={name} name={name} />
+ <Avatar key={name} name={name} imageProps={{ alt: name }} />
))}
/>
);
@@ -88,7 +88,7 @@ export const TeamAvatarsWithAction = ({
maxVisible={3}
total={20}
avatars={['Ada', 'Grace', 'Margaret'].map((name) => (
- <Avatar key={name} name={name} />
+ <Avatar key={name} name={name} imageProps={{ alt: name }} />
))}
renderOverflow={(hiddenCount) => (
<Button
@@ -135,7 +135,7 @@ export const NamedTeamAvatars = () => {
style={{ marginBlock: 8 }}
render={<div data-location="project-header" />}
avatars={['Ada', 'Grace', 'Margaret'].map((name) => (
- <Avatar key={name} name={name} />
+ <Avatar key={name} name={name} imageProps={{ alt: name }} />
))}
/>
);
diff --git a/packages/twenty-docs/ui/primitives/data-display/avatar.mdx b/packages/twenty-docs/ui/primitives/data-display/avatar.mdx
index 5f36a58a557..5c47ed493ab 100644
--- a/packages/twenty-docs/ui/primitives/data-display/avatar.mdx
+++ b/packages/twenty-docs/ui/primitives/data-display/avatar.mdx
@@ -7,7 +7,7 @@ import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
import AvatarReference from '/snippets/ui/generated/data-display/avatar.mdx';
-`Avatar` shows an image with a first-letter fallback. Use it beside a record name or inside a [Chip](/ui/primitives/data-display/chip).
+`Avatar` shows an image with a first-letter fallback. Use it beside a record name or inside a [Chip](/ui/primitives/data-display/chip). Its default root is a presentational `span`.
<StoryEmbed storyId="ui-data-display-avatar--app" title="Avatar example" />
@@ -19,16 +19,78 @@ import { Avatar } from 'twenty-ui/primitives/data-display';
type PersonAvatarProps = { name: string; imageUrl?: string | null };
export const PersonAvatar = ({ name, imageUrl }: PersonAvatarProps) => (
- <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
- <Avatar src={imageUrl} name={name} shape="circle" size="lg" />
- {name}
- </span>
+ <Avatar src={imageUrl} name={name} shape="circle" size="lg" />
);
```
When the image is absent or fails to load, the fallback shows the first letter of the trimmed name in uppercase. An empty name shows `-`. `colorSeed` chooses stable fallback colors and defaults to `name`; use a record identifier to keep the color stable when the name changes.
-The image and fallback are decorative. Keep the visible name beside the avatar, as above. For a standalone avatar that conveys information, supply `role="img"` and an `aria-label`.
+The image and default fallback are decorative. `name` supplies the visual initial and fallback colors without adding an accessible label. When the avatar is the only representation of a person or record, set `imageProps={{ alt: name }}` to label both the image and default fallback. Keep the avatar decorative when a visible name or labeled owner already provides that information.
+
+`imageProps` accepts the complete image contract, including `srcSet`, `sizes`, `crossOrigin`, `referrerPolicy`, native events, refs, and `render`. Its `src` overrides the shorthand `src`. `fallbackProps` accepts the complete fallback contract, including `delay`, children, labeling, refs, and `render`. A custom fallback `render` owns its accessibility semantics; set `aria-hidden` explicitly when it is decorative.
+
+```tsx
+import { Avatar } from 'twenty-ui/primitives/data-display';
+
+type RecordAvatarProps = {
+ name: string;
+ imageUrl?: string;
+ initials: string;
+};
+
+export const RecordAvatar = ({
+ name,
+ imageUrl,
+ initials,
+}: RecordAvatarProps) => (
+ <Avatar
+ name={name}
+ src={imageUrl}
+ size="lg"
+ imageProps={{ alt: name, decoding: 'async', referrerPolicy: 'no-referrer' }}
+ fallbackProps={{ children: initials, delay: 150 }}
+ />
+);
+```
+
+## Compose the parts
+
+Use `Avatar.Root`, `Avatar.Image`, and `Avatar.Fallback` when you own the anatomy. Root supplies the size, shape, and fallback appearance; it does not generate children or accessible labels.
+
+```tsx
+import { Avatar } from 'twenty-ui/primitives/data-display';
+
+type ContactAvatarProps = {
+ name: string;
+ imageUrl?: string;
+ initials: string;
+};
+
+export const ContactAvatar = ({
+ name,
+ imageUrl,
+ initials,
+}: ContactAvatarProps) => (
+ <Avatar.Root name={name} shape="circle" size="xl">
+ <Avatar.Image src={imageUrl} alt={name} decoding="async" />
+ <Avatar.Fallback role="img" aria-label={name} delay={150}>
+ {initials}
+ </Avatar.Fallback>
+ </Avatar.Root>
+);
+```
+
+<StoryEmbed storyId="ui-data-display-avatar--parts" title="Avatar parts" />
+
+The parts share Base UI's image loading state. Image renders an `img` after a successful load by default, and Fallback renders a `span` while the image is absent, loading, or has failed. `delay` postpones the initial fallback display in milliseconds and defaults to `0`. A changed source is loaded again and can replace either the current image or fallback.
+
+`Avatar.Image` exposes `onLoadingStatusChange` with `idle`, `loading`, `loaded`, and `error` status values. The callback runs when Base UI reports a non-idle status change; unmounting the Image part resets the shared root state to `idle`. Root, Image, and Fallback accept state-aware `className`, `style`, and `render` functions with `imageLoadingStatus`; Image also exposes `transitionStatus`.
+
+Use `keepMounted` on Image when the rendered image must load in place, including `loading="lazy"` or an optimized image component. Forward native attributes, events, and the ref from custom image renderers. A mounted image can still be loading or failed; inspect loading state rather than treating its presence as success.
+
+The front component renderer currently supports the default preload path with `src`. Its host image does not receive `srcSet`, `sizes`, `loading`, `decoding`, or `referrerPolicy`. A changing custom `render` function with `keepMounted` can leave a decoded image hidden because the worker cannot read its completion state or dimensions. Use default preloading there until those renderer capabilities are available.
+
+The public `AvatarRootProps`, `AvatarImageProps`, `AvatarFallbackProps`, `AvatarRootState`, `AvatarImageState`, `AvatarFallbackState`, and `AvatarImageLoadingStatus` types are exported from `twenty-ui/primitives/data-display`. Refs target the rendered DOM element: `span`, `img`, and `span` by default, or the element supplied through `render`.
## Shape and appearance
@@ -49,30 +111,68 @@ export const ContactIcon = () => (
);
```
-An `icon` takes precedence over both the image and the first-letter fallback. `pulsing` animates opacity and respects reduced-motion preferences.
+An `icon` takes precedence over both the image and the first-letter fallback. The icon itself is decorative, so label the root when it conveys information. `pulsing` animates opacity and respects reduced-motion preferences.
## Open a profile
```tsx
import { Avatar } from 'twenty-ui/primitives/data-display';
-type ProfileAvatarProps = { onOpenProfile: () => void };
+type ProfileAvatarProps = {
+ onOpenProfile: () => void;
+ disabled?: boolean;
+};
+
+export const ProfileAvatar = ({
+ onOpenProfile,
+ disabled = false,
+}: ProfileAvatarProps) => (
+ <Avatar
+ name="Jane"
+ shape="circle"
+ size="lg"
+ render={
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label="Open Jane's profile"
+ onClick={onOpenProfile}
+ />
+ }
+ />
+);
+```
+
+<StoryEmbed
+ storyId="ui-data-display-avatar--button-composition"
+ title="Avatar composed as a button"
+/>
+
+Compose a native button for actions. It owns focus, Enter and Space activation, and disabled behavior. Supply an action-specific accessible name. Put `onClick` and `disabled` on the rendered button; shorthand Avatar has no `onClick`, `disabled`, or `nativeButton` prop.
+
+For navigation, compose an anchor with an `href` or a router link that preserves anchor semantics. Native links activate with Enter. Keep navigation and disabled behavior with the link or interactive component you compose.
-export const ProfileAvatar = ({ onOpenProfile }: ProfileAvatarProps) => (
+```tsx
+import { Avatar } from 'twenty-ui/primitives/data-display';
+
+export const ProfileLink = () => (
<Avatar
name="Jane"
shape="circle"
size="lg"
- aria-label="Open Jane's profile"
- onClick={onOpenProfile}
+ render={<a href="/people/jane" aria-label="Open Jane's profile" />}
/>
);
```
-Supplying `onClick` renders a button with pointer, Enter, and Space activation. Use `disabled` to prevent activation. The default accessible name comes from `name`, but an action-specific `aria-label` makes the purpose clearer. When replacing the button through `render`, set `nativeButton={false}` for a non-button element.
+## Migrate clickable avatars
+
+Compose a native button through `render` for actions, or an anchor or router link for navigation. Move `onClick` and `disabled` onto that owner and remove `nativeButton`. Give the owner a useful accessible name and avoid nesting interactive elements. `Avatar.Root` and the other explicit parts retain the complete Base UI event contract.
+
+Shorthand avatars are decorative by default. `name` does not name the image, fallback, or interactive owner. Use a nonempty `imageProps.alt` only when the avatar conveys identity that is not already supplied by visible text or an owner label. With explicit parts, supply image alternative text and fallback labels or decorative attributes yourself, and keep translated content in your application.
## Props
-Types and defaults are generated from the public component types. Native attributes and event handlers are also accepted.
+Types and defaults are generated from the public component types. The explicit parts accept native attributes and event handlers. Shorthand Avatar omits `onClick`; supply it on the owner passed through `render`.
<AvatarReference />
diff --git a/packages/twenty-docs/ui/primitives/data-display/chip.mdx b/packages/twenty-docs/ui/primitives/data-display/chip.mdx
index 046e77ee21c..25b0fe5f490 100644
--- a/packages/twenty-docs/ui/primitives/data-display/chip.mdx
+++ b/packages/twenty-docs/ui/primitives/data-display/chip.mdx
@@ -22,7 +22,9 @@ import { Avatar, Chip } from 'twenty-ui/primitives/data-display';
export const AssigneeChip = () => (
<Chip
variant="soft"
- startElement={<Avatar name="Jane" size="sm" shape="circle" />}
+ startElement={
+ <Avatar name="Jane" size="sm" shape="circle" imageProps={{ alt: '' }} />
+ }
>
Jane
</Chip>
@@ -42,7 +44,9 @@ export const AssigneeAction = ({ onOpenAssignee }: AssigneeActionProps) => (
<Chip
onClick={onOpenAssignee}
aria-label="Open Jane's record"
- startElement={<Avatar name="Jane" size="sm" shape="circle" />}
+ startElement={
+ <Avatar name="Jane" size="sm" shape="circle" imageProps={{ alt: '' }} />
+ }
>
Jane
</Chip>
diff --git a/packages/twenty-docs/ui/primitives/navigation/list-item.mdx b/packages/twenty-docs/ui/primitives/navigation/list-item.mdx
index 140e0e88ed6..39188897303 100644
--- a/packages/twenty-docs/ui/primitives/navigation/list-item.mdx
+++ b/packages/twenty-docs/ui/primitives/navigation/list-item.mdx
@@ -121,7 +121,7 @@ export const AssigneeButtons = () => {
aria-pressed={assignee === name}
selected={assignee === name}
indicator="check"
- startIcon={<Avatar name={name} size="md" />}
+ startIcon={<Avatar name={name} size="md" imageProps={{ alt: '' }} />}
onClick={() => setAssignee(name)}
>
{name}
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
index 4e6daee82cc..8f5d86f6ad9 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -38,7 +38,6 @@ import { type TwentyUiGalleryStory as Story } from '@/__stories__/twenty-ui-gall
import {
statusControlsTest,
tagControlsTest,
- avatarControlsTest,
chipControlsTest,
} from '@/__stories__/twenty-ui-gallery/utils/displayControlTests';
import { PortalBoundsDecorator } from '@/__stories__/twenty-ui-gallery/components/PortalBoundsDecorator';
@@ -66,6 +65,7 @@ import { sliderRangeTest } from '@/__stories__/twenty-ui-gallery/utils/sliderRan
import { sliderTest } from '@/__stories__/twenty-ui-gallery/utils/sliderTest';
import { toastTest } from '@/__stories__/twenty-ui-gallery/utils/toastTest';
import { avatarImageTest } from '@/__stories__/twenty-ui-gallery/utils/avatarImageTest';
+import { avatarControlsTest } from '@/__stories__/twenty-ui-gallery/utils/avatarControlsTest';
import { commandBlockTest } from '@/__stories__/twenty-ui-gallery/utils/commandBlockTest';
import { calloutTest } from '@/__stories__/twenty-ui-gallery/utils/calloutTest';
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index 59cea45c27b..480d91f3559 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
@@ -29,36 +29,36 @@ popups.
error. `expectAssertionToKeepFailing` pins an interaction that must have no
effect within the interaction timeout.
-| Fixture | Components |
-| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
-| `twenty-ui-field-controls` | Field, Input, InputGroup, Textarea |
-| `twenty-ui-number-stepper` | NumberStepper (pointer stepping, selected-range paste, caret restoration, keyboard bounds, disabled/read-only state and forms) |
-| `twenty-ui-autocomplete` | Autocomplete (caret keys, controlled editing, composition, filtering, disabled state, Empty; `TwentyUiAutocomplete.stories.tsx`) |
-| `twenty-ui-display-helpers` | Text |
-| `twenty-ui-avatar-controls` | Avatar (fallback, pointer/keyboard activation and disabled state) |
-| `twenty-ui-avatar-group` | AvatarGroup (derived and partial totals, custom overflow, keyed child state, native refs and explicit button/link composition) |
-| `twenty-ui-avatar-image` | Avatar (decoded images, broken-source fallback, replacement and unmount/remount) |
-| `twenty-ui-image-input` | ImageInput |
-| `twenty-ui-list-item` | ListItem |
-| `twenty-ui-settings-row` | SettingsRow |
-| `twenty-ui-tabs` | Tabs |
-| `twenty-ui-overflowing-list` | OverflowingList |
-| `twenty-ui-phone-country-picker` | PhoneCountryPicker |
-| `twenty-ui-currency-picker` | CurrencyPicker |
-| `twenty-ui-popover` | Popover |
-| `twenty-ui-dialog` | SDK `openCommandConfirmationModal` confirmation request |
-| `twenty-ui-menu` | Menu |
-| `twenty-ui-select` | Select |
-| `twenty-ui-portals` | Body portal callbacks, removal, nearby overflow, menu placement and confinement |
-| `twenty-ui-dropdown` | Dropdown |
-| `twenty-ui-toast` | Toast |
-| `twenty-ui-switch` | Switch (interaction coverage in addition to the original input gallery) |
-| `twenty-ui-checkbox` | Checkbox |
-| `twenty-ui-radio-group` | RadioGroup, Radio (standard and card) |
-| `twenty-ui-tooltip` | Tooltip (convenience and compound APIs) |
-| `twenty-ui-responsive-hooks` | useIsMobile, useIsTouchDevice, Button hotkeys |
-| `twenty-ui-reading-directions` | Callout, ButtonGroup, Button, AvatarGroup, ListItem, JsonTree in LTR and RTL side by side (`TwentyUiReadingDirections.stories.tsx`) |
-| `twenty-ui-country-select` | CountrySelect (`TwentyUiCountrySelect.stories.tsx`) |
+| Fixture | Components |
+| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
+| `twenty-ui-field-controls` | Field, Input, InputGroup, Textarea |
+| `twenty-ui-number-stepper` | NumberStepper (pointer stepping, selected-range paste, caret restoration, keyboard bounds, disabled/read-only state and forms) |
+| `twenty-ui-autocomplete` | Autocomplete (caret keys, controlled editing, composition, filtering, disabled state, Empty; `TwentyUiAutocomplete.stories.tsx`) |
+| `twenty-ui-display-helpers` | Text |
+| `twenty-ui-avatar-controls` | Avatar (stable presentational root, compound fallback, refs, explicit button/link composition and native keyboard/disabled behavior) |
+| `twenty-ui-avatar-group` | AvatarGroup (derived and partial totals, custom overflow, keyed child state, native refs and explicit button/link composition) |
+| `twenty-ui-avatar-image` | Avatar Root/Image/Fallback (image labels/attributes/refs, loading callbacks, decoded images, fallback, replacement and unmount/remount) |
+| `twenty-ui-image-input` | ImageInput |
+| `twenty-ui-list-item` | ListItem |
+| `twenty-ui-settings-row` | SettingsRow |
+| `twenty-ui-tabs` | Tabs |
+| `twenty-ui-overflowing-list` | OverflowingList |
+| `twenty-ui-phone-country-picker` | PhoneCountryPicker |
+| `twenty-ui-currency-picker` | CurrencyPicker |
+| `twenty-ui-popover` | Popover |
+| `twenty-ui-dialog` | SDK `openCommandConfirmationModal` confirmation request |
+| `twenty-ui-menu` | Menu |
+| `twenty-ui-select` | Select |
+| `twenty-ui-portals` | Body portal callbacks, removal, nearby overflow, menu placement and confinement |
+| `twenty-ui-dropdown` | Dropdown |
+| `twenty-ui-toast` | Toast |
+| `twenty-ui-switch` | Switch (interaction coverage in addition to the original input gallery) |
+| `twenty-ui-checkbox` | Checkbox |
+| `twenty-ui-radio-group` | RadioGroup, Radio (standard and card) |
+| `twenty-ui-tooltip` | Tooltip (convenience and compound APIs) |
+| `twenty-ui-responsive-hooks` | useIsMobile, useIsTouchDevice, Button hotkeys |
+| `twenty-ui-reading-directions` | Callout, ButtonGroup, Button, AvatarGroup, ListItem, JsonTree in LTR and RTL side by side (`TwentyUiReadingDirections.stories.tsx`) |
+| `twenty-ui-country-select` | CountrySelect (`TwentyUiCountrySelect.stories.tsx`) |
The focused fixtures import public twenty-ui entry points and use
`TwentyUiGalleryCard` for the light theme, mount marker, and `twenty-ui/style.css`.
@@ -77,6 +77,31 @@ remounted Avatar. The Storybook Vite fixture middleware owns these pending
responses and closes them on teardown or timeout. These delayed-response steps
run only in test mode; the regular and static stories use data images and
retain working source controls, fallback, replacement and unmount/remount checks.
+Both runtimes also pin the current retained-image and responsive-source gaps
+described below. The controls fixture uses
+native buttons and an anchor through `render`; the anchor targets a local
+fragment with `target="_self"` and checks pointer and Enter activation without changing navigation
+policy. Callback refs expose the renderer's registered HTML element proxies,
+whose tag names use the `HTML-` prefix.
+Shorthand Avatar content is decorative by default; a nonempty `imageProps.alt`
+labels its image and fallback.
+
+Avatar's default preloaded `src` path decodes visible images and supports image
+labels, custom image/fallback rendering, refs, status/native load callbacks,
+replacement and fallback in both runtimes. The host image element currently
+forwards only `src`, `alt`, `width` and `height` among image-specific properties;
+`srcSet`, `sizes`, `loading`, `decoding` and `referrerPolicy` do not reach it.
+The detached preloader accepts responsive sources, so a `srcSet`-only Avatar
+reports loaded while its host image has no source and a zero natural width.
+The fixture pins this as an unsupported visible-image case.
+
+`keepMounted` with the fixture's caller-supplied `render` and loading callback
+also remains unsupported. Its native host image decodes to the expected width,
+but the worker element has no `complete` or `naturalWidth` readback. Base UI
+therefore returns to loading after the callback updates its parent, leaving the
+decoded image hidden and the fallback visible. The fixture pins that failure
+and checks recovery when returning to the default preload mode. These boundary
+assertions do not establish responsive-source or retained-image acceptance.
Body portals render in a host layer outside widget scroll frames, clipped to
200px around the component, and the worker's `window.visualViewport` reports
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/AvatarImageFixture.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/AvatarImageFixture.ts
index ed92f1fc0f2..0deb69a2ffd 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/AvatarImageFixture.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/constants/AvatarImageFixture.ts
@@ -4,6 +4,8 @@ export const AVATAR_IMAGE_FIXTURE = {
'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="40" height="40"%3E%3Crect width="40" height="40" fill="royalblue"/%3E%3C/svg%3E',
replacementSource:
'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="64" height="64"%3E%3Ccircle cx="32" cy="32" r="32" fill="seagreen"/%3E%3C/svg%3E',
+ sourceSetSource:
+ 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0OCIgaGVpZ2h0PSI0OCI+PHJlY3Qgd2lkdGg9IjQ4IiBoZWlnaHQ9IjQ4IiBmaWxsPSJwdXJwbGUiLz48L3N2Zz4=',
brokenSource: 'data:image/png;base64,invalid',
pendingImage:
'<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80"><rect width="80" height="80" fill="tomato"/></svg>',
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-controls.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-controls.front-component.tsx
index e7ba85b6141..84f52892bf1 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-controls.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-controls.front-component.tsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
import { defineFrontComponent } from 'twenty-sdk/define';
+import { isDefined } from 'twenty-shared/utils';
import { Avatar } from 'twenty-ui/primitives/data-display';
import { ThemeProvider } from 'twenty-ui/theme';
import 'twenty-ui/style.css';
@@ -8,6 +9,8 @@ import { ComponentGallery } from '../shared/front-components/component-gallery';
const AvatarControls = () => {
const [activations, setActivations] = useState(0);
+ const [linkActivations, setLinkActivations] = useState(0);
+ const [presentationalActivations, setPresentationalActivations] = useState(0);
const handleClick = () => setActivations((count) => count + 1);
return (
<ThemeProvider colorScheme="light">
@@ -20,6 +23,7 @@ const AvatarControls = () => {
<Avatar
src="data:image/png;base64,invalid"
name="Image fallback"
+ imageProps={{ alt: 'Portrait unavailable' }}
/>
),
},
@@ -29,11 +33,58 @@ const AvatarControls = () => {
<>
<Avatar
name="Jane"
- onClick={handleClick}
+ aria-label="Open Jane"
+ render={<button type="button" onClick={handleClick} />}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
shape="circle"
size="xl"
/>
- <Avatar name="Disabled avatar" onClick={handleClick} disabled />
+ <Avatar
+ name="Disabled avatar"
+ aria-label="Disabled avatar"
+ render={
+ <button type="button" disabled onClick={handleClick} />
+ }
+ />
+ <Avatar.Root
+ render={<a href="#avatar-profile" target="_self" />}
+ aria-label="View Jane profile"
+ onClick={() => setLinkActivations((count) => count + 1)}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ >
+ <Avatar.Fallback
+ render={<strong />}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ >
+ Profile
+ </Avatar.Fallback>
+ </Avatar.Root>
+ <Avatar.Root
+ name="Presentational avatar"
+ data-testid="presentational-avatar"
+ onClick={() =>
+ setPresentationalActivations((count) => count + 1)
+ }
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ >
+ <Avatar.Fallback aria-hidden>P</Avatar.Fallback>
+ </Avatar.Root>
<Avatar
name="Acme"
shape="rounded-square"
@@ -46,6 +97,10 @@ const AvatarControls = () => {
]}
/>
<output aria-label="Activations">{activations}</output>
+ <output aria-label="Link activations">{linkActivations}</output>
+ <output aria-label="Presentational activations">
+ {presentationalActivations}
+ </output>
</ThemeProvider>
);
};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-image.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-image.front-component.tsx
index f16d7028cb8..4a655b6c01c 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-image.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-image.front-component.tsx
@@ -1,5 +1,6 @@
import { type CSSProperties, useState } from 'react';
import { defineFrontComponent } from 'twenty-sdk/define';
+import { isDefined } from 'twenty-shared/utils';
import { Avatar } from 'twenty-ui/primitives/data-display';
import { Button, Input } from 'twenty-ui/primitives/input';
@@ -13,22 +14,60 @@ const AvatarImageExample = () => {
const [customSource, setCustomSource] = useState('');
const [isMounted, setIsMounted] = useState(true);
const [activations, setActivations] = useState(0);
+ const [loadingStatus, setLoadingStatus] = useState('idle');
+ const [imageLoads, setImageLoads] = useState(0);
+ const [isImageKeptMounted, setIsImageKeptMounted] = useState(false);
+ const [isSourceSetOnly, setIsSourceSetOnly] = useState(false);
return (
<TwentyUiGalleryCard title="Avatar image loading">
{isMounted && (
- <Avatar
- src={source}
- name="Image fallback"
+ <Avatar.Root
aria-label="Profile avatar"
size="xl"
+ render={<button type="button" />}
onClick={() => setActivations((count) => count + 1)}
style={({ imageLoadingStatus }) =>
({
'--avatar-image-status': imageLoadingStatus,
}) as CSSProperties
}
- />
+ >
+ <Avatar.Image
+ key={isImageKeptMounted ? 'in-place' : 'preloaded'}
+ src={isSourceSetOnly ? undefined : source}
+ srcSet={
+ isSourceSetOnly
+ ? `${AVATAR_IMAGE_FIXTURE.sourceSetSource} 1x`
+ : undefined
+ }
+ sizes="40px"
+ keepMounted={isImageKeptMounted}
+ alt="Portrait of Jane"
+ loading="eager"
+ decoding="async"
+ referrerPolicy="no-referrer"
+ render={<img data-composed-image="" />}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ onLoadingStatusChange={setLoadingStatus}
+ onLoad={() => setImageLoads((count) => count + 1)}
+ />
+ <Avatar.Fallback
+ delay={100}
+ render={<strong />}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ >
+ IF
+ </Avatar.Fallback>
+ </Avatar.Root>
)}
<Button onClick={() => setSource(AVATAR_IMAGE_FIXTURE.firstSource)}>
Restore avatar image
@@ -39,6 +78,14 @@ const AvatarImageExample = () => {
<Button onClick={() => setSource(AVATAR_IMAGE_FIXTURE.brokenSource)}>
Break avatar image
</Button>
+ <Button onClick={() => setIsImageKeptMounted((value) => !value)}>
+ {isImageKeptMounted
+ ? 'Preload avatar image'
+ : 'Load avatar image in place'}
+ </Button>
+ <Button onClick={() => setIsSourceSetOnly((value) => !value)}>
+ {isSourceSetOnly ? 'Use avatar source' : 'Use avatar source set'}
+ </Button>
<Input
aria-label="Avatar image source"
value={customSource}
@@ -51,6 +98,8 @@ const AvatarImageExample = () => {
{isMounted ? 'Remove avatar' : 'Mount avatar'}
</Button>
<output aria-label="Avatar activations">{activations}</output>
+ <output aria-label="Avatar image loading status">{loadingStatus}</output>
+ <output aria-label="Avatar image load events">{imageLoads}</output>
</TwentyUiGalleryCard>
);
};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarControlsTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarControlsTest.ts
new file mode 100644
index 00000000000..1606d6a0918
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarControlsTest.ts
@@ -0,0 +1,84 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { galleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/galleryRenderTests';
+
+export const avatarControlsTest: TwentyUiGalleryPlayFunction = async (
+ context,
+) => {
+ await galleryRenderTest(context);
+ const canvas = within(context.canvasElement);
+ const imageEntry = within(canvas.getByTestId('gallery-item-AvatarImage'));
+
+ const labelledFallback = imageEntry.getByRole('img', {
+ name: 'Portrait unavailable',
+ });
+ const decorativeFallback = canvas.getByText('A');
+
+ await expect(labelledFallback).toHaveTextContent('I');
+ await expect(labelledFallback).toBeVisible();
+ await expect(decorativeFallback).toBeVisible();
+ await expect(decorativeFallback).toHaveAttribute('aria-hidden', 'true');
+ await expect(
+ canvas.queryByRole('img', { name: 'Acme' }),
+ ).not.toBeInTheDocument();
+
+ const button = canvas.getByRole('button', { name: 'Open Jane' });
+ const activations = canvas.getByLabelText('Activations');
+
+ await expect(button.tagName).toBe('BUTTON');
+ await expect(button).toHaveAttribute('type', 'button');
+ await expect(button).toHaveAttribute('data-ref-tag', 'HTML-BUTTON');
+ await userEvent.click(button);
+ await userEvent.keyboard('{Enter} ');
+ await waitFor(() => expect(activations).toHaveTextContent('3'));
+ await expect(button).toHaveFocus();
+
+ const disabledButton = canvas.getByRole('button', {
+ name: 'Disabled avatar',
+ });
+
+ await expect(disabledButton).toBeDisabled();
+ await userEvent.click(disabledButton);
+ await userEvent.tab();
+ await expect(disabledButton).not.toHaveFocus();
+ await expect(activations).toHaveTextContent('3');
+
+ const link = canvas.getByRole('link', { name: 'View Jane profile' });
+ const fallback = within(link).getByText('Profile');
+
+ await expect(link.tagName).toBe('A');
+ await expect(link).toHaveAttribute('href', '#avatar-profile');
+ await expect(link).toHaveAttribute('target', '_self');
+ await expect(link).toHaveAttribute('data-ref-tag', 'HTML-A');
+ await expect(fallback.tagName).toBe('STRONG');
+ await expect(fallback).toHaveAttribute('data-ref-tag', 'HTML-STRONG');
+ await userEvent.click(link);
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Link activations')).toHaveTextContent('2'),
+ );
+ await expect(link).toHaveFocus();
+ await userEvent.keyboard(' ');
+ await expect(canvas.getByLabelText('Link activations')).toHaveTextContent(
+ '2',
+ );
+
+ const presentationalAvatar = canvas.getByTestId('presentational-avatar');
+
+ await expect(presentationalAvatar.tagName).toBe('SPAN');
+ await expect(presentationalAvatar).toHaveAttribute(
+ 'data-ref-tag',
+ 'HTML-SPAN',
+ );
+ await expect(presentationalAvatar).not.toHaveAttribute('role');
+ await expect(presentationalAvatar).not.toHaveAttribute('tabindex');
+ await expect(presentationalAvatar).not.toHaveAttribute('aria-label');
+ await userEvent.click(presentationalAvatar);
+ await waitFor(() =>
+ expect(
+ canvas.getByLabelText('Presentational activations'),
+ ).toHaveTextContent('1'),
+ );
+ await expect(presentationalAvatar).not.toHaveFocus();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarImageTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarImageTest.ts
index 7672e07374e..fbffefd4c30 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarImageTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarImageTest.ts
@@ -7,6 +7,7 @@ import { TYPING_DELAY } from '@/__stories__/shared/test-utils/timeouts';
import { AVATAR_IMAGE_FIXTURE } from '@/__stories__/twenty-ui-gallery/constants/AvatarImageFixture';
import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
import { observeAvatarImageLoads } from '@/__stories__/twenty-ui-gallery/utils/observeAvatarImageLoads';
+import { expectAssertionToKeepFailing } from '@/__stories__/twenty-ui-gallery/utils/expectAssertionToKeepFailing';
const IS_BROWSER_TEST = import.meta.env.MODE === 'test';
@@ -16,19 +17,23 @@ const expectLoadedAvatar = async ({
width,
}: {
avatar: HTMLElement;
- source: string;
+ source?: string;
width: number;
}) => {
await waitFor(() => {
- const image = within(avatar).getByRole('presentation');
+ const image = within(avatar).getByRole('img', { name: 'Portrait of Jane' });
expect(avatar.style.getPropertyValue('--avatar-image-status')).toBe(
'loaded',
);
- expect(image).toHaveAttribute('src', source);
+ if (isDefined(source)) {
+ expect(image).toHaveAttribute('src', source);
+ }
+ expect(image).toHaveAttribute('data-composed-image');
+ expect(image).toHaveAttribute('data-ref-tag', 'HTML-IMG');
expect(image).toHaveProperty('naturalWidth', width);
expect(image).toBeVisible();
- expect(within(avatar).queryByText('I')).not.toBeInTheDocument();
+ expect(within(avatar).queryByText('IF')).not.toBeInTheDocument();
});
};
@@ -40,6 +45,8 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
const avatar = canvas.getByRole('button', { name: 'Profile avatar' });
const activations = canvas.getByLabelText('Avatar activations');
+ const loadingStatus = canvas.getByLabelText('Avatar image loading status');
+ const imageLoadEvents = canvas.getByLabelText('Avatar image load events');
const pendingSources: string[] = [];
const imageLoads = IS_BROWSER_TEST ? observeAvatarImageLoads() : undefined;
@@ -75,7 +82,7 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
expect(requestStatus.pending).toBeGreaterThan(0);
});
- await expect(within(avatar).getByText('I')).toBeVisible();
+ await expect(within(avatar).getByText('IF')).toBeVisible();
return source;
};
@@ -86,6 +93,22 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
source: AVATAR_IMAGE_FIXTURE.firstSource,
width: 40,
});
+ await waitFor(() => {
+ expect(loadingStatus).toHaveTextContent('loaded');
+ expect(imageLoadEvents).toHaveTextContent('1');
+ });
+ const initialImage = within(avatar).getByRole('img', {
+ name: 'Portrait of Jane',
+ });
+
+ for (const attribute of [
+ 'sizes',
+ 'loading',
+ 'decoding',
+ 'referrerpolicy',
+ ]) {
+ await expect(initialImage).not.toHaveAttribute(attribute);
+ }
await userEvent.click(avatar);
await waitFor(() => expect(activations).toHaveTextContent('1'));
await userEvent.click(
@@ -96,6 +119,10 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
source: AVATAR_IMAGE_FIXTURE.replacementSource,
width: 64,
});
+ await waitFor(() => {
+ expect(loadingStatus).toHaveTextContent('loaded');
+ expect(imageLoadEvents).toHaveTextContent('2');
+ });
const replacedSource = IS_BROWSER_TEST
? await startPendingImage()
@@ -108,10 +135,13 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
expect(avatar.style.getPropertyValue('--avatar-image-status')).toBe(
'error',
);
- expect(
- within(avatar).queryByRole('presentation'),
- ).not.toBeInTheDocument();
- expect(within(avatar).getByText('I')).toBeVisible();
+ expect(loadingStatus).toHaveTextContent('error');
+ expect(within(avatar).queryByRole('img')).not.toBeInTheDocument();
+ const fallback = within(avatar).getByText('IF');
+
+ expect(fallback).toBeVisible();
+ expect(fallback.tagName).toBe('STRONG');
+ expect(fallback).toHaveAttribute('data-ref-tag', 'HTML-STRONG');
});
if (isDefined(replacedSource)) {
await releasePendingImage(replacedSource);
@@ -121,10 +151,8 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
await expect(avatar.style.getPropertyValue('--avatar-image-status')).toBe(
'error',
);
- await expect(within(avatar).getByText('I')).toBeVisible();
- await expect(
- within(avatar).queryByRole('presentation'),
- ).not.toBeInTheDocument();
+ await expect(within(avatar).getByText('IF')).toBeVisible();
+ await expect(within(avatar).queryByRole('img')).not.toBeInTheDocument();
const unmountedSource = IS_BROWSER_TEST
? await startPendingImage()
@@ -157,6 +185,58 @@ export const avatarImageTest: TwentyUiGalleryPlayFunction = async ({
await userEvent.click(remountedAvatar);
await userEvent.keyboard('{Enter}');
await waitFor(() => expect(activations).toHaveTextContent('4'));
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Use avatar source set' }),
+ );
+ await waitFor(() => {
+ const image = within(remountedAvatar).getByRole('img', {
+ name: 'Portrait of Jane',
+ });
+
+ expect(loadingStatus).toHaveTextContent('loaded');
+ expect(image).not.toHaveAttribute('src');
+ expect(image).not.toHaveAttribute('srcset');
+ expect(image).toHaveProperty('naturalWidth', 0);
+ expect(within(remountedAvatar).queryByText('IF')).not.toBeInTheDocument();
+ });
+ await expectAssertionToKeepFailing(() =>
+ expect(within(remountedAvatar).getByRole('img')).toHaveProperty(
+ 'naturalWidth',
+ 48,
+ ),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Use avatar source' }),
+ );
+ await expectLoadedAvatar({
+ avatar: remountedAvatar,
+ source: AVATAR_IMAGE_FIXTURE.firstSource,
+ width: 40,
+ });
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Load avatar image in place' }),
+ );
+ await waitFor(() => {
+ const image = within(remountedAvatar).getByAltText('Portrait of Jane');
+
+ expect(image).toHaveProperty('naturalWidth', 40);
+ expect(loadingStatus).toHaveTextContent('loading');
+ expect(image).toHaveAttribute('data-loading');
+ expect(image).toHaveAttribute('aria-hidden', 'true');
+ expect(image).not.toBeVisible();
+ expect(within(remountedAvatar).getByText('IF')).toBeVisible();
+ });
+ await expectAssertionToKeepFailing(() =>
+ expect(loadingStatus).toHaveTextContent('loaded'),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Preload avatar image' }),
+ );
+ await expectLoadedAvatar({
+ avatar: remountedAvatar,
+ source: AVATAR_IMAGE_FIXTURE.firstSource,
+ width: 40,
+ });
await expect(errorHandler).not.toHaveBeenCalled();
} finally {
imageLoads?.restore();
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts
index d6ee3e7bc72..826b5c5e46c 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts
@@ -55,23 +55,6 @@ export const tagControlsTest = createDisplayControlTest({
staticContent: 'Static tag',
});
-const avatarGalleryTest: TwentyUiGalleryPlayFunction = async (context) => {
- await galleryRenderTest(context);
- const imageEntry = within(
- within(context.canvasElement).getByTestId('gallery-item-AvatarImage'),
- );
-
- await expect(imageEntry.getByText('I')).toBeVisible();
- await expect(imageEntry.queryByRole('presentation')).not.toBeInTheDocument();
-};
-
-export const avatarControlsTest = createDisplayControlTest({
- buttonName: 'Jane',
- disabledButtonName: 'Disabled avatar',
- staticContent: 'A',
- checkGallery: avatarGalleryTest,
-});
-
export const chipControlsTest = createDisplayControlTest({
buttonName: 'Open chip',
disabledButtonName: 'Disabled chip',
diff --git a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventParticipantsAvatarGroup.tsx b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventParticipantsAvatarGroup.tsx
index 978aeb0ef53..3bbe465e4f5 100644
--- a/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventParticipantsAvatarGroup.tsx
+++ b/packages/twenty-front/src/modules/activities/calendar/components/CalendarEventParticipantsAvatarGroup.tsx
@@ -2,6 +2,7 @@ import { CalendarEventCallRecorderAvatar } from '@/activities/calendar/component
import { type CalendarEventCallRecording } from '@/activities/calendar/types/CalendarEventCallRecording';
import { type CalendarEventParticipant } from '@/activities/calendar/types/CalendarEventParticipant';
import { isTimelineCalendarEventParticipant } from '@/activities/calendar/types/guards/IsTimelineCalendarEventParticipant';
+import { isNonEmptyString } from '@sniptt/guards';
import { isDefined } from 'twenty-shared/utils';
import { AvatarGroup } from 'twenty-ui/components/data-display';
import { Avatar } from 'twenty-ui/primitives/data-display';
@@ -60,23 +61,28 @@ export const CalendarEventParticipantsAvatarGroup = ({
status={callRecording.status}
/>
)),
- ...timelineParticipants.map((participant) => (
- <Avatar
- key={[participant.workspaceMemberId, participant.displayName]
- .filter(isDefined)
- .join('-')}
- src={getAbsoluteImageUrl(participant.avatarUrl)}
- name={
- participant.firstName && participant.lastName
- ? `${participant.firstName} ${participant.lastName}`
- : participant.displayName
- }
- colorSeed={
- participant.workspaceMemberId || participant.personId || ''
- }
- shape="circle"
- />
- )),
+ ...timelineParticipants.map((participant) => {
+ const participantName =
+ isNonEmptyString(participant.firstName) &&
+ isNonEmptyString(participant.lastName)
+ ? `${participant.firstName} ${participant.lastName}`
+ : participant.displayName;
+
+ return (
+ <Avatar
+ key={[participant.workspaceMemberId, participant.displayName]
+ .filter(isDefined)
+ .join('-')}
+ src={getAbsoluteImageUrl(participant.avatarUrl)}
+ name={participantName}
+ imageProps={{ alt: participantName }}
+ colorSeed={
+ participant.workspaceMemberId || participant.personId || ''
+ }
+ shape="circle"
+ />
+ );
+ }),
]}
/>
);
diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
index 253e10d3466..e299b7a3f8c 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/useChatReferenceTarget.tsx
@@ -1,4 +1,3 @@
-import { AvatarOrIcon } from '@/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon';
import { isNonEmptyString } from '@sniptt/guards';
import { type ReactNode } from 'react';
import { AppPath, SettingsPath } from 'twenty-shared/types';
@@ -9,6 +8,7 @@ import {
isDefined,
} from 'twenty-shared/utils';
import { IconApps, IconLock, useIcons } from 'twenty-ui/icon';
+import { Avatar } from 'twenty-ui/primitives/data-display';
import { useTheme } from 'twenty-ui/theme';
import { CHAT_REFERENCE_PERMISSION_FLAG_BY_KIND } from '@/ai/constants/ChatReferencePermissionFlagByKind';
@@ -92,11 +92,13 @@ export const useChatReferenceTarget = (
return {
path: isNonEmptyString(recordPath) ? recordPath : undefined,
leftComponent: (
- <AvatarOrIcon
+ <Avatar
name={reference.displayName}
colorSeed={reference.recordId}
shape="circle"
src=""
+ size="sm"
+ imageProps={{ alt: '' }}
/>
),
};
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpWorkspaceCreationForm.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpWorkspaceCreationForm.tsx
index 404bf03670c..cd6cd86bc66 100644
--- a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpWorkspaceCreationForm.tsx
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpWorkspaceCreationForm.tsx
@@ -257,7 +257,13 @@ export const SignInUpWorkspaceCreationForm = () => {
colorSeed={getWorkspaceAvatarColorSeed(workspaceName)}
shape="square"
size="xl"
- onClick={openFilePicker}
+ render={
+ <button
+ type="button"
+ aria-label={t`Upload logo`}
+ onClick={openFilePicker}
+ />
+ }
/>
<StyledHiddenFileInput
type="file"
diff --git a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/__stories__/MultiWorkspaceDropdownButton.stories.tsx b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/__stories__/MultiWorkspaceDropdownButton.stories.tsx
index e70bfb4473b..b8723365a00 100644
--- a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/__stories__/MultiWorkspaceDropdownButton.stories.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/__stories__/MultiWorkspaceDropdownButton.stories.tsx
@@ -244,3 +244,31 @@ export const MobileBoundary: Story = {
});
},
};
+
+const HIDDEN_WORKSPACE_LABEL_STORY: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement.ownerDocument.body);
+ const trigger = canvas.getByRole('button', { name: 'Twenty' });
+
+ await expect(
+ within(trigger).getByRole('img', { name: 'Twenty' }),
+ ).toBeVisible();
+ await userEvent.click(trigger);
+ await expect(
+ await canvas.findByRole('menu', { name: 'Twenty' }),
+ ).toBeVisible();
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const HiddenWorkspaceLabel: Story = {
+ ...HIDDEN_WORKSPACE_LABEL_STORY,
+ args: { shouldHideLabel: true },
+};
+
+export const CollapsedWorkspaceLabel: Story = {
+ ...HIDDEN_WORKSPACE_LABEL_STORY,
+ beforeEach: () => {
+ jotaiStore.set(isNavigationDrawerExpandedState.atom, false);
+ },
+};
diff --git a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownClickableComponent.tsx b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownClickableComponent.tsx
index d3e65ee4539..b968d0757c9 100644
--- a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownClickableComponent.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownClickableComponent.tsx
@@ -27,6 +27,8 @@ export const MultiWorkspaceDropdownClickableComponent = ({
const currentWorkspace = useAtomStateValue(currentWorkspaceState);
const isNavigationDrawerExpanded = useIsNavigationDrawerContentExpanded();
+ const isWorkspaceLabelVisible =
+ !shouldHideLabel && isNavigationDrawerExpanded;
return (
<StyledContainer
data-testid="workspace-dropdown"
@@ -34,6 +36,11 @@ export const MultiWorkspaceDropdownClickableComponent = ({
disabled={disabled}
>
<Avatar
+ imageProps={{
+ alt: isWorkspaceLabelVisible
+ ? ''
+ : (currentWorkspace?.displayName ?? ''),
+ }}
name={currentWorkspace?.displayName || ''}
colorSeed={getWorkspaceAvatarColorSeed(currentWorkspace?.displayName)}
src={getAbsoluteImageUrl(
@@ -42,7 +49,7 @@ export const MultiWorkspaceDropdownClickableComponent = ({
/>
{!shouldHideLabel && (
<>
- <StyledLabelWrapper>
+ <StyledLabelWrapper aria-hidden={!isWorkspaceLabelVisible}>
<NavigationDrawerAnimatedCollapseWrapper>
<StyledLabel>{currentWorkspace?.displayName ?? ''}</StyledLabel>
</NavigationDrawerAnimatedCollapseWrapper>
diff --git a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownDefaultComponents.tsx b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownDefaultComponents.tsx
index b1a4a83c566..6de0019649e 100644
--- a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownDefaultComponents.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/MultiWorkspaceDropdownDefaultComponents.tsx
@@ -76,6 +76,7 @@ export const MultiWorkspaceDropdownDefaultComponents = () => {
<>
<Dropdown.Header>
<Avatar
+ imageProps={{ alt: '' }}
name={currentWorkspace?.displayName || ''}
colorSeed={getWorkspaceAvatarColorSeed(currentWorkspace?.displayName)}
src={getAbsoluteImageUrl(
diff --git a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/components/AvailableWorkspaceItem.tsx b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/components/AvailableWorkspaceItem.tsx
index cbd3d50c5a8..9040217102f 100644
--- a/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/components/AvailableWorkspaceItem.tsx
+++ b/packages/twenty-front/src/modules/navigation/components/MultiWorkspaceDropdown/internal/components/AvailableWorkspaceItem.tsx
@@ -50,6 +50,7 @@ export const AvailableWorkspaceItem = ({
selected={isSelected}
startIcon={
<Avatar
+ imageProps={{ alt: '' }}
name={availableWorkspace.displayName || ''}
colorSeed={getWorkspaceAvatarColorSeed(
availableWorkspace.displayName,
diff --git a/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetRelationPickerMenuItem.tsx b/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetRelationPickerMenuItem.tsx
index 7d30037be2f..2cd0a3598df 100644
--- a/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetRelationPickerMenuItem.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-table-widget/components/RecordTableWidgetRelationPickerMenuItem.tsx
@@ -19,6 +19,7 @@ export const RecordTableWidgetRelationPickerMenuItem = ({
startIcon={
<Avatar
src={getAbsoluteImageUrl(relationRecord.avatarUrl)}
+ imageProps={{ alt: '' }}
colorSeed={relationRecord.id}
name={relationRecord.name}
size="md"
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon.tsx b/packages/twenty-front/src/modules/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon.tsx
index e08cf23b32d..3cd24d37999 100644
--- a/packages/twenty-front/src/modules/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon.tsx
+++ b/packages/twenty-front/src/modules/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon.tsx
@@ -1,3 +1,5 @@
+import { getAvatarButtonRender } from '@/ui/field/display/utils/getAvatarButtonRender';
+import { t } from '@lingui/core/macro';
import { css } from '@linaria/core';
import { isNonEmptyString } from '@sniptt/guards';
@@ -67,12 +69,12 @@ export const AvatarOrIcon = ({
name={name}
size="sm"
shape={shape ?? undefined}
- onClick={onClick}
+ render={getAvatarButtonRender({ name, onClick })}
/>
);
}
- const accessibleLabel = isNonEmptyString(name) ? name : 'Avatar';
+ const accessibleLabel = isNonEmptyString(name) ? name : t`Avatar`;
const iconContent =
isIconInverted || isDefined(IconBackgroundColor) ? (
diff --git a/packages/twenty-front/src/modules/ui/field/display/utils/getAvatarButtonRender.tsx b/packages/twenty-front/src/modules/ui/field/display/utils/getAvatarButtonRender.tsx
new file mode 100644
index 00000000000..ed65719d6d5
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/field/display/utils/getAvatarButtonRender.tsx
@@ -0,0 +1,25 @@
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type MouseEventHandler } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { type AvatarProps } from 'twenty-ui/primitives/data-display';
+
+export const getAvatarButtonRender = ({
+ name,
+ onClick,
+}: Pick<AvatarProps, 'name'> & {
+ onClick?: MouseEventHandler<HTMLButtonElement>;
+}) => {
+ if (!isDefined(onClick)) {
+ return undefined;
+ }
+
+ const trimmedName = name?.trim();
+ const accessibleLabel = isNonEmptyString(trimmedName)
+ ? trimmedName
+ : t`Avatar`;
+
+ return (
+ <button type="button" aria-label={accessibleLabel} onClick={onClick} />
+ );
+};
diff --git a/packages/twenty-front/src/modules/ui/layout/page/components/HeaderIdentifier.tsx b/packages/twenty-front/src/modules/ui/layout/page/components/HeaderIdentifier.tsx
index 0643e83b5b3..6ec579a065c 100644
--- a/packages/twenty-front/src/modules/ui/layout/page/components/HeaderIdentifier.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/page/components/HeaderIdentifier.tsx
@@ -1,6 +1,7 @@
+import { getAvatarButtonRender } from '@/ui/field/display/utils/getAvatarButtonRender';
import { StyledHeaderIdentifierLabel } from '@/ui/layout/page/components/StyledHeaderIdentifierLabel';
import { styled } from '@linaria/react';
-import { type ReactNode } from 'react';
+import { type MouseEventHandler, type ReactNode } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';
import {
@@ -52,8 +53,10 @@ const StyledTitle = styled.h3<{ fontSize: 'md' | 'lg' }>`
type HeaderIdentifierProps = {
avatar?: Pick<
AvatarProps,
- 'src' | 'onClick' | 'name' | 'colorSeed' | 'shape' | 'variant'
- >;
+ 'src' | 'name' | 'colorSeed' | 'shape' | 'variant'
+ > & {
+ onClick?: MouseEventHandler<HTMLButtonElement>;
+ };
icon?: ReactNode;
iconColor?: string;
fontSize?: 'md' | 'lg';
@@ -72,7 +75,7 @@ export const HeaderIdentifier = ({
const identifierIcon = isDefined(avatar) ? (
<Avatar
src={avatar.src}
- onClick={avatar.onClick}
+ render={getAvatarButtonRender(avatar)}
name={avatar.name}
colorSeed={avatar.colorSeed}
shape={avatar.shape}
diff --git a/packages/twenty-front/src/modules/workspace-member/components/WorkspaceMemberAvatarStack.tsx b/packages/twenty-front/src/modules/workspace-member/components/WorkspaceMemberAvatarStack.tsx
index db14593f7fd..0491235ec1a 100644
--- a/packages/twenty-front/src/modules/workspace-member/components/WorkspaceMemberAvatarStack.tsx
+++ b/packages/twenty-front/src/modules/workspace-member/components/WorkspaceMemberAvatarStack.tsx
@@ -82,6 +82,7 @@ export const WorkspaceMemberAvatarStack = ({
<Avatar
src={getAbsoluteImageUrl(workspaceMember.avatarUrl)}
name={displayName}
+ imageProps={{ alt: displayName }}
colorSeed={workspaceMember.id}
size="md"
shape="circle"
diff --git a/packages/twenty-ui/docs/avatarPartPropDescriptions.ts b/packages/twenty-ui/docs/avatarPartPropDescriptions.ts
new file mode 100644
index 00000000000..721303e58b5
--- /dev/null
+++ b/packages/twenty-ui/docs/avatarPartPropDescriptions.ts
@@ -0,0 +1,45 @@
+import { type AvatarFallbackProps } from '../src/primitives/data-display/Avatar/types/AvatarFallbackProps';
+import { type AvatarImageProps } from '../src/primitives/data-display/Avatar/types/AvatarImageProps';
+import { type AvatarRootProps } from '../src/primitives/data-display/Avatar/types/AvatarRootProps';
+
+import { AVATAR_PROP_DESCRIPTIONS } from './avatarPropDescriptions';
+
+export const AVATAR_PART_PROP_DESCRIPTIONS = {
+ Root: {
+ name: 'Name used to choose fallback colors. Does not add children or accessible labels.',
+ colorSeed: AVATAR_PROP_DESCRIPTIONS.colorSeed,
+ size: AVATAR_PROP_DESCRIPTIONS.size,
+ shape: AVATAR_PROP_DESCRIPTIONS.shape,
+ variant: AVATAR_PROP_DESCRIPTIONS.variant,
+ color: AVATAR_PROP_DESCRIPTIONS.color,
+ backgroundColor: AVATAR_PROP_DESCRIPTIONS.backgroundColor,
+ borderColor: AVATAR_PROP_DESCRIPTIONS.borderColor,
+ pulsing: AVATAR_PROP_DESCRIPTIONS.pulsing,
+ ring: AVATAR_PROP_DESCRIPTIONS.ring,
+ children: 'Caller-owned Image, Fallback, and other content.',
+ render: AVATAR_PROP_DESCRIPTIONS.render,
+ } satisfies Partial<Record<keyof AvatarRootProps, string>>,
+ Image: {
+ src: 'Image URL. Image renders after a successful load unless keepMounted is enabled.',
+ alt: 'Caller-owned alternative text. Use an empty string for decorative images.',
+ srcSet: 'Native responsive image source candidates.',
+ sizes: 'Native responsive image sizes used with srcSet.',
+ crossOrigin:
+ 'Native image cross-origin policy, also used during preloading.',
+ referrerPolicy:
+ 'Native image referrer policy, also used during preloading.',
+ loading: 'Native eager or lazy loading. Use keepMounted for lazy loading.',
+ onLoadingStatusChange:
+ 'Called when Base UI reports a loading, loaded, or error status. Shares that state with Root and Fallback.',
+ keepMounted:
+ 'Keeps the image mounted and loads it in place. Loading and failed images stay hidden while Fallback is shown.',
+ render:
+ 'Replaces the image. Preserve a native image and forward the supplied attributes, events, and ref.',
+ } satisfies Partial<Record<keyof AvatarImageProps, string>>,
+ Fallback: {
+ children: 'Caller-owned fallback content, such as initials or an icon.',
+ delay: 'Milliseconds before the initial fallback is shown. Defaults to 0.',
+ render:
+ 'Replaces the fallback span. Forward the supplied props and ref, and provide its accessible label or decorative attributes.',
+ } satisfies Partial<Record<keyof AvatarFallbackProps, string>>,
+};
diff --git a/packages/twenty-ui/docs/avatarPropDescriptions.ts b/packages/twenty-ui/docs/avatarPropDescriptions.ts
index 6b8517f1fae..c310aa91490 100644
--- a/packages/twenty-ui/docs/avatarPropDescriptions.ts
+++ b/packages/twenty-ui/docs/avatarPropDescriptions.ts
@@ -1,20 +1,22 @@
import { type AvatarProps } from '../src/primitives/data-display/Avatar/types/AvatarProps';
export const AVATAR_PROP_DESCRIPTIONS = {
- src: 'Image URL. A missing or failed image shows the fallback.',
- name: 'Name used for the first-letter fallback and the default accessible name when clickable.',
+ src: 'Image URL. A missing or failed image shows the fallback. `imageProps.src` overrides this value.',
+ name: 'Name used for the first-letter fallback and fallback colors. Does not add an accessible label.',
colorSeed: 'Stable value used to choose fallback colors. Defaults to `name`.',
size: 'Avatar size: `xs` (12px), `sm` (14px), `md` (16px), `lg` (24px), or `xl` (40px).',
shape: 'Shape of the avatar and its fallback.',
variant: 'Visual treatment of the fallback.',
- icon: 'Icon rendered instead of the image and first-letter fallback.',
+ icon: 'Decorative icon rendered instead of the image and first-letter fallback. Give the root an accessible label when the icon conveys information.',
color: 'Text color override for a first-letter fallback.',
backgroundColor: 'Background color override for a first-letter fallback.',
borderColor: 'Border color override for the outline fallback.',
pulsing: 'Animates the avatar opacity. Respects reduced-motion preferences.',
ring: 'Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct.',
- disabled:
- 'Applies disabled styling and disables activation when `onClick` is supplied.',
- nativeButton:
- 'Set to `false` when a clickable avatar uses `render` with an element other than a native button.',
+ imageProps:
+ 'Complete `Avatar.Image` props, including native image attributes, refs, `render`, `keepMounted`, and `onLoadingStatusChange`. Alternative text defaults to an empty string. Supply a nonempty `alt` to label the image and default fallback.',
+ fallbackProps:
+ 'Complete `Avatar.Fallback` props, including caller-owned children, labeling, refs, `render`, and fallback `delay` in milliseconds.',
+ render:
+ 'Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner.',
} satisfies Partial<Record<keyof AvatarProps, string>>;
diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.ts
index 1272a4b81b0..1785f638988 100644
--- a/packages/twenty-ui/docs/components.ts
+++ b/packages/twenty-ui/docs/components.ts
@@ -36,6 +36,7 @@ import { THINKING_ORBIT_LOADER_ICON_PROP_DESCRIPTIONS } from './thinkingOrbitLoa
import { COMPONENT_STORYBOOK_LAYOUT_PROP_DESCRIPTIONS } from './componentStorybookLayoutPropDescriptions';
import { COLLAPSIBLE_PART_PROP_DESCRIPTIONS } from './collapsiblePropDescriptions';
import { AVATAR_PROP_DESCRIPTIONS } from './avatarPropDescriptions';
+import { AVATAR_PART_PROP_DESCRIPTIONS } from './avatarPartPropDescriptions';
import { BANNER_PROP_DESCRIPTIONS } from './bannerPropDescriptions';
import { BREADCRUMB_PROP_DESCRIPTIONS } from './breadcrumbPropDescriptions';
import { BUTTON_GROUP_PROP_DESCRIPTIONS } from './buttonGroupPropDescriptions';
@@ -610,6 +611,15 @@ export const DOCUMENTED_COMPONENTS = [
entryPoint: 'twenty-ui/primitives/data-display',
slug: 'data-display/avatar',
propDescriptions: AVATAR_PROP_DESCRIPTIONS,
+ propDefaults: {
+ size: 'md',
+ shape: 'square',
+ variant: 'soft',
+ pulsing: 'false',
+ ring: 'false',
+ },
+ parts: ['Root', 'Image', 'Fallback'],
+ partPropDescriptions: AVATAR_PART_PROP_DESCRIPTIONS,
},
{
name: 'Chip',
diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.md
index b441629e62e..02c8883698b 100644
--- a/packages/twenty-ui/docs/label-ownership.md
+++ b/packages/twenty-ui/docs/label-ownership.md
@@ -16,7 +16,7 @@ This covers production exports under components, primitives, and icons, includin
| PhoneCountryPicker | Callers supply country labels and the trigger accessible name. The popup takes the trigger name unless a `Dropdown.Title` or an explicit `Dropdown.Content` label names it, and the selected country label describes the trigger. `searchLabel` defaults to `Search`; `emptyLabel` defaults to `No results`. Calling codes are supplied as data without a leading plus sign. |
| ImageInput | `uploadLabel`, `removeLabel`, and `abortLabel` default to `Upload`, `Remove`, and `Abort`. The upload label names the visible upload button and the preview button. Applications supply `helperText` and `errorMessage`, including validation instructions and translated strings. |
| Toast and Toaster | Children, description and action slots, `iconLabel`, `cancelLabel` (default `Cancel`), and `closeLabel` (default `Close`). Toaster accepts native accessible attributes over its `Notifications` region default. |
-| Chip and Avatar | Chip `emptyLabel` defaults to `Untitled`. Avatar accepts native accessible names over its interactive fallback of the supplied name or `Avatar`. The visual initial or dash is hidden from assistive technology; the image has empty alternative text. |
+| Chip and Avatar | Chip `emptyLabel` defaults to `Untitled`. Avatar's image and default fallback are decorative. `name` supplies the visual initial and colors. Explicit `imageProps.alt` labels the image and default fallback; caller fallback semantics take precedence. Composed buttons and links own their labels and interaction handlers. |
| JsonTree | Callers supply empty string, array, and object labels and expanded/collapsed arrow names. JSON booleans, null, property names, and values are data. |
| ResizeHandle and CodeEditor | ResizeHandle accepts native labels over `Resize`. Hosts supply a contextual label, `aria-controls`, and the focus destination when collapsing a panel removes its handle. CodeEditor exposes `resizeLabel` (default `Resize editor`) and Monaco `options`, including its editor accessible label. The loading indicator adds no text. Monaco owns its internal editor messages. |
| Input, Textarea, Select, Field, Slider, Radio, RadioGroup, Checkbox, Switch, SegmentedControl | Native attributes, compound label/description/error parts, options, and children belong to the caller. Browser validation messages remain browser-owned; Field.Error children or render content can replace them. |
diff --git a/packages/twenty-ui/docs/public-exports.json b/packages/twenty-ui/docs/public-exports.json
index fb1eca909d5..e2afe5774ef 100644
--- a/packages/twenty-ui/docs/public-exports.json
+++ b/packages/twenty-ui/docs/public-exports.json
@@ -728,7 +728,14 @@
"Tag": "primitives/data-display/Tag/Tag"
},
"types": {
+ "AvatarFallbackProps": "primitives/data-display/Avatar/types/AvatarFallbackProps",
+ "AvatarFallbackState": "primitives/data-display/Avatar/types/AvatarFallbackState",
+ "AvatarImageLoadingStatus": "primitives/data-display/Avatar/types/AvatarImageLoadingStatus",
+ "AvatarImageProps": "primitives/data-display/Avatar/types/AvatarImageProps",
+ "AvatarImageState": "primitives/data-display/Avatar/types/AvatarImageState",
"AvatarProps": "primitives/data-display/Avatar/types/AvatarProps",
+ "AvatarRootProps": "primitives/data-display/Avatar/types/AvatarRootProps",
+ "AvatarRootState": "primitives/data-display/Avatar/types/AvatarRootState",
"AvatarShape": "primitives/data-display/Avatar/types/AvatarShape",
"AvatarSize": "primitives/data-display/Avatar/types/AvatarSize",
"ChipProps": "primitives/data-display/Chip/types/ChipProps",
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index 86696d1d5e9..7f2faf28d13 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -9068,32 +9068,32 @@
"description": "Stable value used to choose fallback colors. Defaults to `name`."
},
{
- "name": "disabled",
- "type": "boolean",
+ "name": "fallbackProps",
+ "type": "AvatarFallbackProps",
"required": false,
- "defaultValue": "false",
- "description": "Applies disabled styling and disables activation when `onClick` is supplied."
+ "defaultValue": null,
+ "description": "Complete `Avatar.Fallback` props, including caller-owned children, labeling, refs, `render`, and fallback `delay` in milliseconds."
},
{
"name": "icon",
"type": "ReactNode",
"required": false,
"defaultValue": null,
- "description": "Icon rendered instead of the image and first-letter fallback."
+ "description": "Decorative icon rendered instead of the image and first-letter fallback. Give the root an accessible label when the icon conveys information."
},
{
- "name": "name",
- "type": "string",
+ "name": "imageProps",
+ "type": "AvatarImageProps",
"required": false,
"defaultValue": null,
- "description": "Name used for the first-letter fallback and the default accessible name when clickable."
+ "description": "Complete `Avatar.Image` props, including native image attributes, refs, `render`, `keepMounted`, and `onLoadingStatusChange`. Alternative text defaults to an empty string. Supply a nonempty `alt` to label the image and default fallback."
},
{
- "name": "nativeButton",
- "type": "boolean",
+ "name": "name",
+ "type": "string",
"required": false,
- "defaultValue": "true",
- "description": "Set to `false` when a clickable avatar uses `render` with an element other than a native button."
+ "defaultValue": null,
+ "description": "Name used for the first-letter fallback and fallback colors. Does not add an accessible label."
},
{
"name": "pulsing",
@@ -9107,7 +9107,7 @@
"type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AvatarRootState>",
"required": false,
"defaultValue": null,
- "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."
+ "description": "Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner."
},
{
"name": "ring",
@@ -9135,7 +9135,7 @@
"type": "string | null",
"required": false,
"defaultValue": null,
- "description": "Image URL. A missing or failed image shows the fallback."
+ "description": "Image URL. A missing or failed image shows the fallback. `imageProps.src` overrides this value."
},
{
"name": "style",
@@ -9151,6 +9151,240 @@
"defaultValue": "soft",
"description": "Visual treatment of the fallback."
}
+ ],
+ "parts": [
+ {
+ "name": "Root",
+ "props": [
+ {
+ "name": "backgroundColor",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Background color override for a first-letter fallback."
+ },
+ {
+ "name": "borderColor",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Border color override for the outline fallback."
+ },
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Caller-owned Image, Fallback, and other content."
+ },
+ {
+ "name": "className",
+ "type": "string | ((state: AvatarRootState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."
+ },
+ {
+ "name": "color",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Text color override for a first-letter fallback."
+ },
+ {
+ "name": "colorSeed",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Stable value used to choose fallback colors. Defaults to `name`."
+ },
+ {
+ "name": "name",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Name used to choose fallback colors. Does not add children or accessible labels."
+ },
+ {
+ "name": "pulsing",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Animates the avatar opacity. Respects reduced-motion preferences."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AvatarRootState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Caller-supplied root element or renderer. Defaults to a presentational span. Compose a native button or link explicitly for interaction, and put its click handler and disabled state on that owner."
+ },
+ {
+ "name": "ring",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Surrounds the avatar with a background-colored ring so overlapping avatars stay distinct."
+ },
+ {
+ "name": "shape",
+ "type": "\"circle\" | \"rounded-square\" | \"square\"",
+ "required": false,
+ "defaultValue": "square",
+ "description": "Shape of the avatar and its fallback."
+ },
+ {
+ "name": "size",
+ "type": "\"lg\" | \"md\" | \"sm\" | \"xl\" | \"xs\"",
+ "required": false,
+ "defaultValue": "md",
+ "description": "Avatar size: `xs` (12px), `sm` (14px), `md` (16px), `lg` (24px), or `xl` (40px)."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: AvatarRootState) => CSSProperties | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."
+ },
+ {
+ "name": "variant",
+ "type": "\"outline\" | \"soft\"",
+ "required": false,
+ "defaultValue": "soft",
+ "description": "Visual treatment of the fallback."
+ }
+ ]
+ },
+ {
+ "name": "Image",
+ "props": [
+ {
+ "name": "alt",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Caller-owned alternative text. Use an empty string for decorative images."
+ },
+ {
+ "name": "className",
+ "type": "string | ((state: AvatarImageState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."
+ },
+ {
+ "name": "crossOrigin",
+ "type": "\"\" | \"anonymous\" | \"use-credentials\"",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native image cross-origin policy, also used during preloading."
+ },
+ {
+ "name": "keepMounted",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "false",
+ "description": "Keeps the image mounted and loads it in place. Loading and failed images stay hidden while Fallback is shown."
+ },
+ {
+ "name": "loading",
+ "type": "\"eager\" | \"lazy\"",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native eager or lazy loading. Use keepMounted for lazy loading."
+ },
+ {
+ "name": "onLoadingStatusChange",
+ "type": "((status: ImageLoadingStatus) => void)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Called when Base UI reports a loading, loaded, or error status. Shares that state with Root and Fallback."
+ },
+ {
+ "name": "referrerPolicy",
+ "type": "\"\" | \"no-referrer-when-downgrade\" | \"no-referrer\" | \"origin-when-cross-origin\" | \"origin\" | \"same-origin\" | \"strict-origin-when-cross-origin\" | \"strict-origin\" | \"unsafe-url\"",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native image referrer policy, also used during preloading."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, AvatarImageState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Replaces the image. Preserve a native image and forward the supplied attributes, events, and ref."
+ },
+ {
+ "name": "sizes",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native responsive image sizes used with srcSet."
+ },
+ {
+ "name": "src",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Image URL. Image renders after a successful load unless keepMounted is enabled."
+ },
+ {
+ "name": "srcSet",
+ "type": "string",
+ "required": false,
+ "defaultValue": null,
+ "description": "Native responsive image source candidates."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: AvatarImageState) => CSSProperties | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."
+ }
+ ]
+ },
+ {
+ "name": "Fallback",
+ "props": [
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Caller-owned fallback content, such as initials or an icon."
+ },
+ {
+ "name": "className",
+ "type": "string | ((state: AvatarFallbackState) => string | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "CSS class applied to the element, or a function that\nreturns a class based on the component's state."
+ },
+ {
+ "name": "delay",
+ "type": "number",
+ "required": false,
+ "defaultValue": "0",
+ "description": "Milliseconds before the initial fallback is shown. Defaults to 0."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, AvatarFallbackState>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Replaces the fallback span. Forward the supplied props and ref, and provide its accessible label or decorative attributes."
+ },
+ {
+ "name": "style",
+ "type": "CSSProperties | ((state: AvatarFallbackState) => CSSProperties | undefined)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Style applied to the element, or a function that\nreturns a style object based on the component's state."
+ }
+ ]
+ }
]
},
{
diff --git a/packages/twenty-ui/src/components/__stories__/LabelOverrides.stories.tsx b/packages/twenty-ui/src/components/__stories__/LabelOverrides.stories.tsx
index 1ccfdf45536..ad67efe3eb6 100644
--- a/packages/twenty-ui/src/components/__stories__/LabelOverrides.stories.tsx
+++ b/packages/twenty-ui/src/components/__stories__/LabelOverrides.stories.tsx
@@ -94,7 +94,7 @@ export const NativeNames: Story = {
/>
<Text id="avatar-label">Open profile</Text>
<Avatar
- onClick={fn()}
+ render={<button type="button" onClick={fn()} />}
aria-label="Fallback avatar"
aria-labelledby="avatar-label"
/>
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss b/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss
index 4e357564338..19876bed1a1 100644
--- a/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss
@@ -14,6 +14,8 @@
justify-content: center;
color: var(--tw-avatar-color);
background: var(--tw-avatar-background);
+ text-decoration: none;
+ position: relative;
&[data-shape='rounded-square'] {
border-radius: var(--t-border-radius-sm);
@@ -30,12 +32,16 @@
0 0 0 2px var(--t-background-primary);
}
- &[data-clickable]:not([data-disabled]) {
+ &:is(button, a[href], [role='button'], [role='link']):not(:disabled):not(
+ [aria-disabled='true']
+ ) {
cursor: pointer;
}
@include hover-capable {
- &[data-clickable]:not([data-disabled]):hover {
+ &:is(button, a[href], [role='button'], [role='link']):not(:disabled):not(
+ [aria-disabled='true']
+ ):hover {
box-shadow: 0 0 0 4px var(--t-background-transparent-light);
}
}
@@ -95,11 +101,17 @@
object-fit: cover;
block-size: 100%;
inline-size: 100%;
+
+ &[data-loading],
+ &[data-error] {
+ opacity: 0;
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ }
}
.fallback {
font-weight: var(--t-font-weight-medium);
-}
-.icon {
display: flex;
& > svg {
inline-size: calc(var(--t-icon-size-xl) * 1px);
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss.d.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss.d.ts
index ba095dcb59e..caa8e8ca044 100644
--- a/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss.d.ts
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.module.scss.d.ts
@@ -2,6 +2,5 @@ declare const classNames: {
readonly root: 'root';
readonly image: 'image';
readonly fallback: 'fallback';
- readonly icon: 'icon';
};
export default classNames;
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.tsx b/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.tsx
index 5fb5786f5f2..21df087b022 100644
--- a/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.tsx
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/Avatar.tsx
@@ -1,131 +1,60 @@
-import { Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
-import { Button as ButtonPrimitive } from '@base-ui/react/button';
-import { type CSSProperties } from 'react';
+import { isBoolean, isNonEmptyString } from '@sniptt/guards';
-import { useTheme } from '@ui/theme';
-import { stringToThemeColorP3String } from '@ui/utilities';
import { isDefined } from '@ui/utilities/utils/isDefined';
-import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
-import styles from './Avatar.module.scss';
+import { AvatarFallback } from './internal/AvatarFallback';
+import { AvatarImage } from './internal/AvatarImage';
+import { AvatarRoot } from './internal/AvatarRoot';
+import { getAvatarInitial } from './internal/getAvatarInitial';
import { type AvatarProps } from './types/AvatarProps';
-export const Avatar = ({
+const AvatarAssembly = ({
src,
name,
- colorSeed = name,
- size = 'md',
- shape = 'square',
- variant = 'soft',
icon,
- color,
+ imageProps,
+ fallbackProps,
backgroundColor,
- borderColor,
- pulsing = false,
- ring = false,
- disabled = false,
- nativeButton = true,
- onClick,
- className,
- style,
- render,
- 'aria-label': ariaLabel,
...props
}: AvatarProps) => {
- const theme = useTheme();
- const initial = name?.trim().charAt(0).toUpperCase();
- const fallbackColor = initial
- ? (color ??
- stringToThemeColorP3String({
- string: colorSeed ?? '',
- variant: 12,
- theme,
- }))
- : theme.font.color.tertiary;
- const fallbackBackground = initial
- ? (backgroundColor ??
- stringToThemeColorP3String({
- string: colorSeed ?? '',
- variant: variant === 'outline' ? 5 : 4,
- theme,
- }))
- : theme.background.transparent.light;
- const fallbackBorder =
- borderColor ??
- (initial
- ? stringToThemeColorP3String({
- string: colorSeed ?? '',
- variant: 6,
- theme,
- })
- : undefined);
- const isInteractive = isDefined(onClick);
- const hasIcon = isDefined(icon) && typeof icon !== 'boolean' && icon !== '';
+ const initial = getAvatarInitial(name);
+ const hasIcon = isDefined(icon) && !isBoolean(icon) && icon !== '';
+ const imageLabel = imageProps?.alt ?? '';
+ const hasImageLabel = !hasIcon && isNonEmptyString(imageLabel);
+ const { children = hasIcon ? icon : initial || '-', ...fallbackAttributes } =
+ fallbackProps ?? {};
+ const hasFallbackSemantics =
+ isDefined(fallbackAttributes.role) ||
+ isDefined(fallbackAttributes['aria-label']) ||
+ isDefined(fallbackAttributes['aria-labelledby']);
+ const isFallbackDecorative =
+ !hasImageLabel &&
+ !hasFallbackSemantics &&
+ !isDefined(fallbackAttributes.render);
return (
- <AvatarPrimitive.Root
+ <AvatarRoot
{...props}
- onClick={onClick}
- aria-label={
- ariaLabel ?? (isInteractive ? name?.trim() || 'Avatar' : undefined)
- }
- data-size={size}
- data-shape={shape}
- data-pulsing={pulsing || undefined}
- data-ring={ring || undefined}
- data-disabled={disabled || undefined}
- data-clickable={isInteractive || undefined}
- className={mergeClassNames(styles.root, className)}
- style={(state) =>
- ({
- '--tw-avatar-color': fallbackColor,
- '--tw-avatar-background': hasIcon
- ? 'inherit'
- : state.imageLoadingStatus === 'loaded'
- ? 'none'
- : fallbackBackground,
- '--tw-avatar-border':
- variant === 'outline' &&
- state.imageLoadingStatus !== 'loaded' &&
- fallbackBorder
- ? `1px solid ${fallbackBorder}`
- : 'none',
- ...(typeof style === 'function' ? style(state) : style),
- }) as CSSProperties
- }
- render={
- isInteractive
- ? (rootProps, state) => (
- <ButtonPrimitive
- {...rootProps}
- disabled={disabled}
- nativeButton={nativeButton}
- render={
- typeof render === 'function'
- ? (buttonProps) => render(buttonProps, state)
- : render
- }
- />
- )
- : render
- }
+ name={name}
+ backgroundColor={hasIcon ? 'inherit' : backgroundColor}
>
- {hasIcon ? (
- <span className={styles.icon} aria-hidden>
- {icon}
- </span>
- ) : (
- <>
- <AvatarPrimitive.Image
- src={src ?? undefined}
- alt=""
- className={styles.image}
- />
- <AvatarPrimitive.Fallback className={styles.fallback} aria-hidden>
- {initial || '-'}
- </AvatarPrimitive.Fallback>
- </>
+ {!hasIcon && (
+ <AvatarImage src={src ?? undefined} {...imageProps} alt={imageLabel} />
)}
- </AvatarPrimitive.Root>
+ <AvatarFallback
+ role={hasImageLabel ? 'img' : undefined}
+ aria-label={hasImageLabel ? imageLabel : undefined}
+ aria-hidden={isFallbackDecorative || undefined}
+ {...fallbackAttributes}
+ >
+ {children}
+ </AvatarFallback>
+ </AvatarRoot>
);
};
+
+export const Avatar = Object.assign(AvatarAssembly, {
+ Root: AvatarRoot,
+ Image: AvatarImage,
+ Fallback: AvatarFallback,
+});
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/__stories__/Avatar.stories.tsx b/packages/twenty-ui/src/primitives/data-display/Avatar/__stories__/Avatar.stories.tsx
index 44d4fee17b9..977aadb5d18 100644
--- a/packages/twenty-ui/src/primitives/data-display/Avatar/__stories__/Avatar.stories.tsx
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/__stories__/Avatar.stories.tsx
@@ -1,7 +1,9 @@
-import { useState } from 'react';
+import { type MouseEvent, type MouseEventHandler, useState } from 'react';
import { type Meta, type StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, waitFor, within } from 'storybook/test';
+import illustrationUserUrl from '@assets/icons/illustration-user.svg?url';
+
import {
AVATAR_URL_MOCK,
ComponentDecorator,
@@ -11,9 +13,15 @@ import {
} from '@ui/testing';
import { Avatar } from '@ui/primitives/data-display/Avatar/Avatar';
+import { type AvatarProps } from '@ui/primitives/data-display/Avatar/types/AvatarProps';
+import { type AvatarRootProps } from '@ui/primitives/data-display/Avatar/types/AvatarRootProps';
import { type AvatarShape } from '@ui/primitives/data-display/Avatar/types/AvatarShape';
+import { Button } from '@ui/primitives/input/Button/Button';
import { IconUser } from '@ui/icon';
+const VALID_IMAGE = illustrationUserUrl;
+const INVALID_IMAGE = 'data:image/png;base64,invalid';
+
const meta: Meta<typeof Avatar> = {
title: 'UI/Data Display/Avatar',
component: Avatar,
@@ -27,6 +35,13 @@ const meta: Meta<typeof Avatar> = {
export default meta;
type Story = StoryObj<typeof Avatar>;
+type RootInteractionStory = StoryObj<AvatarRootProps>;
+type ButtonInteractionStory = StoryObj<
+ AvatarProps & { onActivate?: MouseEventHandler<HTMLButtonElement> }
+>;
+type LinkInteractionStory = StoryObj<
+ AvatarProps & { onNavigate?: MouseEventHandler<HTMLAnchorElement> }
+>;
export const Rounded: Story = { decorators: [ComponentDecorator] };
@@ -44,6 +59,10 @@ export const IconTile: Story = {
role: 'img',
'aria-label': 'Workspace icon',
},
+};
+
+export const IconTileInteraction: Story = {
+ ...IconTile,
play: async ({ canvasElement }) => {
const iconTile = within(canvasElement).getByRole('img', {
name: 'Workspace icon',
@@ -81,74 +100,312 @@ export const App: Story = {
},
};
+export const Parts: Story = {
+ decorators: [ComponentDecorator],
+ render: () => (
+ <Avatar.Root name="Jane Doe" shape="circle" size="xl">
+ <Avatar.Image src={VALID_IMAGE} alt="Jane Doe" decoding="async" />
+ <Avatar.Fallback role="img" aria-label="Jane Doe">
+ JD
+ </Avatar.Fallback>
+ </Avatar.Root>
+ ),
+};
+
+export const PartsInteraction: Story = {
+ ...Parts,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const image = await canvas.findByAltText('Jane Doe');
+
+ await expect(image).toBeVisible();
+ await expect(image).toHaveAttribute('decoding', 'async');
+ await expect(canvas.queryByText('JD')).not.toBeInTheDocument();
+ },
+};
+
export const ImageFailingToLoadFallsBackToPlaceholder: Story = {
decorators: [ComponentDecorator],
args: {
- src: 'data:image/png;base64,not-a-valid-image',
+ src: INVALID_IMAGE,
name: 'Eldritch',
+ imageProps: { alt: 'Eldritch' },
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
+ const fallback = await canvas.findByRole('img', { name: 'Eldritch' });
- const placeholderChar = await canvas.findByText('E');
-
- await expect(placeholderChar).toBeVisible();
+ await expect(fallback).toHaveTextContent('E');
+ await expect(fallback).toBeVisible();
+ await expect(canvas.queryByAltText('Eldritch')).not.toBeInTheDocument();
},
};
-export const NotClickable: Story = {
+export const OnClickKeepsPresentationalRoot: RootInteractionStory = {
decorators: [ComponentDecorator],
- play: async ({ canvasElement }) => {
+ args: {
+ name: 'Jane',
+ onClick: fn(),
+ ref: fn(),
+ },
+ render: ({ name, onClick, ref, size, shape }) => (
+ <Avatar.Root
+ name={name}
+ onClick={onClick}
+ ref={ref}
+ size={size}
+ shape={shape}
+ >
+ <Avatar.Fallback aria-hidden>J</Avatar.Fallback>
+ </Avatar.Root>
+ ),
+ play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
+ const fallback = canvas.getByText('J');
+ const root = fallback.parentElement;
+ await expect(root?.tagName).toBe('SPAN');
+ await expect(root).not.toHaveAttribute('tabindex');
await expect(canvas.queryByRole('button')).not.toBeInTheDocument();
+ await expect(args.ref).toHaveBeenCalledWith(root);
+ await userEvent.click(fallback);
+ await expect(args.onClick).toHaveBeenCalledOnce();
},
};
-const clickFromEnterKey = fn();
-
-export const ClickableActivatesOnEnter: Story = {
+export const ButtonComposition: Story = {
decorators: [ComponentDecorator],
- args: { name: 'Eldritch', onClick: clickFromEnterKey },
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
+ args: {
+ src: undefined,
+ name: 'Jane',
+ size: 'xl',
+ imageProps: { alt: '' },
+ render: <button type="button" />,
+ 'aria-label': "Open Jane's profile",
+ },
+};
+
+export const ButtonKeyboardInteraction: ButtonInteractionStory = {
+ ...ButtonComposition,
+ args: { ...ButtonComposition.args, onActivate: fn(), ref: fn() },
+ render: ({ onActivate, ...args }) => (
+ <Avatar {...args} render={<button type="button" onClick={onActivate} />} />
+ ),
+ play: async ({ canvasElement, args }) => {
+ const avatar = within(canvasElement).getByRole('button', {
+ name: "Open Jane's profile",
+ });
- const avatar = await canvas.findByRole('button', { name: 'Eldritch' });
await expect(avatar.tagName).toBe('BUTTON');
+ await expect(args.ref).toHaveBeenCalledWith(avatar);
+ avatar.focus();
+ await expect(avatar).toHaveFocus();
+ await userEvent.keyboard('{Enter} ');
+ await expect(args.onActivate).toHaveBeenCalledTimes(2);
+ },
+};
+
+export const DisabledButtonInteraction: ButtonInteractionStory = {
+ ...ButtonComposition,
+ args: {
+ ...ButtonComposition.args,
+ render: <button type="button" disabled />,
+ onActivate: fn(),
+ },
+ render: ({ onActivate, ...args }) => (
+ <Avatar
+ {...args}
+ render={<button type="button" disabled onClick={onActivate} />}
+ />
+ ),
+ play: async ({ canvasElement, args }) => {
+ const avatar = within(canvasElement).getByRole('button', {
+ name: "Open Jane's profile",
+ });
+ await expect(avatar).toBeDisabled();
+ await userEvent.click(avatar);
avatar.focus();
- await userEvent.keyboard('{Enter}');
+ await expect(avatar).not.toHaveFocus();
+ await userEvent.keyboard('{Enter} ');
+ await expect(args.onActivate).not.toHaveBeenCalled();
+ },
+};
- await expect(clickFromEnterKey).toHaveBeenCalledTimes(1);
+export const LinkComposition: Story = {
+ ...ButtonComposition,
+ args: {
+ ...ButtonComposition.args,
+ render: <a href="#avatar-profile" aria-label="Open Jane's profile" />,
},
};
-const clickFromSpaceKey = fn();
+export const LinkKeyboardInteraction: LinkInteractionStory = {
+ ...LinkComposition,
+ args: {
+ ...LinkComposition.args,
+ onNavigate: fn((event: MouseEvent<HTMLAnchorElement>) =>
+ event.preventDefault(),
+ ),
+ ref: fn(),
+ },
+ render: ({ onNavigate, ...args }) => (
+ <Avatar
+ {...args}
+ render={
+ <a
+ href="#avatar-profile"
+ aria-label="Open Jane's profile"
+ onClick={onNavigate}
+ />
+ }
+ />
+ ),
+ play: async ({ canvasElement, args }) => {
+ const avatar = within(canvasElement).getByRole('link', {
+ name: "Open Jane's profile",
+ });
+
+ await expect(avatar.tagName).toBe('A');
+ await expect(avatar).toHaveAttribute('href', '#avatar-profile');
+ await expect(args.ref).toHaveBeenCalledWith(avatar);
+ avatar.focus();
+ await expect(avatar).toHaveFocus();
+ await userEvent.keyboard('{Enter}');
+ await expect(args.onNavigate).toHaveBeenCalledOnce();
+ await userEvent.keyboard(' ');
+ await expect(args.onNavigate).toHaveBeenCalledOnce();
+ },
+};
-export const ClickableActivatesOnSpace: Story = {
+export const DecorativeImageInteraction: Story = {
decorators: [ComponentDecorator],
- args: { name: 'Eldritch', onClick: clickFromSpaceKey },
+ args: { src: VALID_IMAGE, name: 'Jane' },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- const avatar = await canvas.findByRole('button', { name: 'Eldritch' });
+ await expect(await canvas.findByRole('presentation')).toBeVisible();
+ await expect(canvas.queryByRole('img')).not.toBeInTheDocument();
+ },
+};
- avatar.focus();
- await userEvent.keyboard(' ');
+const ImageChangesExample = (props: AvatarProps) => {
+ const [src, setSrc] = useState<string | undefined>(VALID_IMAGE);
- await expect(clickFromSpaceKey).toHaveBeenCalledTimes(1);
+ return (
+ <>
+ <Avatar
+ {...props}
+ src={src}
+ name="Jane"
+ size="xl"
+ render={<a href="#jane" aria-label="Jane" />}
+ aria-label="Jane"
+ imageProps={{ ...props.imageProps, alt: '' }}
+ />
+ <Button onClick={() => setSrc(INVALID_IMAGE)}>Break image</Button>
+ <Button onClick={() => setSrc(VALID_IMAGE)}>Restore image</Button>
+ <Button onClick={() => setSrc(undefined)}>Remove image</Button>
+ </>
+ );
+};
+
+export const ImageChanges: Story = {
+ decorators: [ComponentDecorator],
+ args: {
+ ref: fn(),
+ imageProps: { onLoadingStatusChange: fn(), ref: fn() },
+ fallbackProps: { children: 'JD', ref: fn() },
+ },
+ render: (args) => <ImageChangesExample {...args} />,
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const image = await canvas.findByRole('presentation');
+ const recordLink = canvas.getByRole('link', { name: 'Jane' });
+
+ await expect(image).toBeVisible();
+ await expect((image as HTMLImageElement).naturalWidth).toBeGreaterThan(0);
+ await expect(args.imageProps?.ref).toHaveBeenCalledWith(image);
+ await expect(args.imageProps?.onLoadingStatusChange).toHaveBeenCalledWith(
+ 'loaded',
+ );
+ await expect(args.ref).toHaveBeenCalledWith(recordLink);
+ await userEvent.click(canvas.getByRole('button', { name: 'Break image' }));
+ const fallback = await canvas.findByText('JD');
+ await expect(fallback).toBeVisible();
+ await expect(args.fallbackProps?.ref).toHaveBeenCalledWith(fallback);
+ await expect(recordLink).toHaveAccessibleName('Jane');
+ await expect(args.imageProps?.onLoadingStatusChange).toHaveBeenCalledWith(
+ 'error',
+ );
+ await waitFor(() =>
+ expect(canvas.queryByRole('presentation')).not.toBeInTheDocument(),
+ );
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Restore image' }),
+ );
+ const restoredImage = await canvas.findByRole('presentation');
+ await expect(restoredImage).toBeVisible();
+ await expect(
+ (restoredImage as HTMLImageElement).naturalWidth,
+ ).toBeGreaterThan(0);
+ await expect(canvas.queryByText('JD')).not.toBeInTheDocument();
+ await expect(recordLink).toHaveAccessibleName('Jane');
+ await userEvent.click(canvas.getByRole('button', { name: 'Remove image' }));
+ await expect(await canvas.findByText('JD')).toBeVisible();
+ await expect(recordLink).toHaveAccessibleName('Jane');
},
};
-export const ClickableWithoutPlaceholderIsStillLabelled: Story = {
+export const MountedImageChanges: Story = {
+ ...ImageChanges,
+ args: {
+ ...ImageChanges.args,
+ imageProps: {
+ keepMounted: true,
+ loading: 'lazy',
+ onLoadingStatusChange: fn(),
+ ref: fn(),
+ },
+ fallbackProps: { children: 'JD', ref: fn() },
+ ref: fn(),
+ },
+};
+
+const FallbackDelayExample = () => {
+ const [isVisible, setIsVisible] = useState(false);
+
+ return (
+ <>
+ <Button onClick={() => setIsVisible(true)}>Show avatar</Button>
+ {isVisible && (
+ <Avatar.Root name="Jane Doe" size="xl">
+ <Avatar.Fallback
+ delay={300}
+ render={<strong />}
+ role="img"
+ aria-label="Jane Doe"
+ >
+ JD
+ </Avatar.Fallback>
+ </Avatar.Root>
+ )}
+ </>
+ );
+};
+
+export const FallbackDelayInteraction: Story = {
decorators: [ComponentDecorator],
- args: { name: '', onClick: fn() },
+ render: () => <FallbackDelayExample />,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
- await expect(
- await canvas.findByRole('button', { name: 'Avatar' }),
- ).toBeVisible();
+ await userEvent.click(canvas.getByRole('button', { name: 'Show avatar' }));
+ await expect(canvas.queryByText('JD')).not.toBeInTheDocument();
+ const fallback = await canvas.findByRole('img', { name: 'Jane Doe' });
+ await expect(fallback).toBeVisible();
+ await expect(fallback).toHaveTextContent('JD');
+ await expect(fallback.tagName).toBe('STRONG');
},
};
@@ -185,70 +442,3 @@ export const CatalogDark: typeof Catalog = {
tags: ['!autodocs'],
globals: { colorScheme: 'dark' },
};
-
-const VALID_IMAGE =
- 'data:image/svg+xml,' +
- encodeURIComponent(
- '<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40"><rect width="40" height="40" fill="blue"/></svg>',
- );
-const INVALID_IMAGE = 'data:image/png;base64,invalid';
-
-const ImageChangesExample = () => {
- const [src, setSrc] = useState<string | undefined>(VALID_IMAGE);
- return (
- <>
- <a href="#jane">
- <Avatar src={src} name="Jane" size="xl" />
- Jane
- </a>
- <button type="button" onClick={() => setSrc(INVALID_IMAGE)}>
- Break image
- </button>
- <button type="button" onClick={() => setSrc(VALID_IMAGE)}>
- Restore image
- </button>
- <button type="button" onClick={() => setSrc(undefined)}>
- Remove image
- </button>
- </>
- );
-};
-
-export const ImageChanges: Story = {
- decorators: [ComponentDecorator],
- render: () => <ImageChangesExample />,
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
- await expect(await canvas.findByRole('presentation')).toBeVisible();
- const recordLink = canvas.getByRole('link', { name: 'Jane' });
- await expect(recordLink).toHaveAccessibleName('Jane');
- await userEvent.click(canvas.getByRole('button', { name: 'Break image' }));
- await expect(await canvas.findByText('J')).toBeVisible();
- await expect(recordLink).toHaveAccessibleName('Jane');
- await waitFor(() =>
- expect(canvas.queryByRole('presentation')).not.toBeInTheDocument(),
- );
- await userEvent.click(
- canvas.getByRole('button', { name: 'Restore image' }),
- );
- await expect(await canvas.findByRole('presentation')).toBeVisible();
- await expect(recordLink).toHaveAccessibleName('Jane');
- await userEvent.click(canvas.getByRole('button', { name: 'Remove image' }));
- await expect(await canvas.findByText('J')).toBeVisible();
- await expect(recordLink).toHaveAccessibleName('Jane');
- },
-};
-
-export const Disabled: Story = {
- decorators: [ComponentDecorator],
- args: { name: 'Jane', src: undefined, disabled: true, onClick: fn() },
- play: async ({ canvasElement, args }) => {
- const avatar = within(canvasElement).getByRole('button', { name: 'Jane' });
- await expect(avatar).toBeDisabled();
- await userEvent.hover(avatar);
- await expect(getComputedStyle(avatar).cursor).not.toBe('pointer');
- await expect(getComputedStyle(avatar).boxShadow).toBe('none');
- await userEvent.click(avatar);
- await expect(args.onClick).not.toHaveBeenCalled();
- },
-};
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/__tests__/Avatar.test.tsx b/packages/twenty-ui/src/primitives/data-display/Avatar/__tests__/Avatar.test.tsx
index 1b83ada4121..54f1d54f0cd 100644
--- a/packages/twenty-ui/src/primitives/data-display/Avatar/__tests__/Avatar.test.tsx
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/__tests__/Avatar.test.tsx
@@ -1,7 +1,19 @@
import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createRef, type ReactNode } from 'react';
+import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest';
+
+import { ThemeProvider } from '@ui/theme';
import { Avatar } from '../Avatar';
import styles from '../Avatar.module.scss';
+import { type AvatarProps } from '../types/AvatarProps';
+import { type AvatarRootProps } from '../types/AvatarRootProps';
+
+const AvatarRootWrapper = ({ children }: { children: ReactNode }) => (
+ <Avatar.Root>{children}</Avatar.Root>
+);
runComponentConformance({
name: 'Avatar',
@@ -9,3 +21,414 @@ runComponentConformance({
ownClassName: styles.root,
refInstanceOf: HTMLSpanElement,
});
+
+runComponentConformance({
+ name: 'Avatar.Root',
+ element: <Avatar.Root>Jane</Avatar.Root>,
+ ownClassName: styles.root,
+ refInstanceOf: HTMLSpanElement,
+});
+
+runComponentConformance({
+ name: 'Avatar.Image',
+ element: <Avatar.Image keepMounted alt="Jane" />,
+ ownClassName: styles.image,
+ refInstanceOf: HTMLImageElement,
+ renderPropTagName: 'img',
+ wrapper: AvatarRootWrapper,
+});
+
+runComponentConformance({
+ name: 'Avatar.Fallback',
+ element: <Avatar.Fallback>Jane</Avatar.Fallback>,
+ ownClassName: styles.fallback,
+ refInstanceOf: HTMLSpanElement,
+ wrapper: AvatarRootWrapper,
+});
+
+describe('Avatar composition', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('omits shorthand click handlers while retaining the Root contract', () => {
+ expectTypeOf<AvatarProps>().not.toHaveProperty('onClick');
+ expectTypeOf<AvatarRootProps>().toHaveProperty('onClick');
+ });
+
+ it('keeps Root presentational when a click handler is supplied', async () => {
+ const handleClick = vi.fn();
+ const avatarRef = createRef<HTMLSpanElement>();
+
+ render(
+ <ThemeProvider colorScheme="light">
+ <Avatar.Root
+ name="Jane"
+ aria-label="Profile avatar"
+ ref={avatarRef}
+ onClick={(event) => {
+ expectTypeOf(event.currentTarget).toEqualTypeOf<
+ EventTarget & HTMLSpanElement
+ >();
+ handleClick(event.currentTarget);
+ }}
+ >
+ <Avatar.Fallback aria-hidden>J</Avatar.Fallback>
+ </Avatar.Root>
+ </ThemeProvider>,
+ );
+
+ const avatar = screen.getByLabelText('Profile avatar');
+
+ expect(avatar.tagName).toBe('SPAN');
+ expect(avatarRef.current).toBe(avatar);
+ expect(avatar).not.toHaveAttribute('role');
+ expect(avatar).not.toHaveAttribute('tabindex');
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+
+ await userEvent.click(avatar);
+
+ expect(handleClick).toHaveBeenCalledWith(avatar);
+ });
+
+ it('preserves native owner callbacks, disabled behavior and ref targets', async () => {
+ const buttonRef = createRef<HTMLButtonElement>();
+ const linkRef = createRef<HTMLAnchorElement>();
+ const handleButtonClick = vi.fn();
+ const handleLinkClick = vi.fn();
+
+ render(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ name="Jane"
+ ref={buttonRef}
+ render={
+ <button
+ type="button"
+ aria-label="Open profile"
+ onClick={(event) => {
+ expectTypeOf(event.currentTarget).toEqualTypeOf<
+ EventTarget & HTMLButtonElement
+ >();
+ handleButtonClick(event.currentTarget);
+ }}
+ />
+ }
+ />
+ <Avatar
+ name="Jane"
+ render={
+ <button
+ type="button"
+ disabled
+ aria-label="Disabled profile"
+ onClick={handleButtonClick}
+ />
+ }
+ />
+ <Avatar.Root
+ ref={linkRef}
+ render={
+ <a
+ href="/people/jane"
+ aria-label="View Jane"
+ onClick={(event) => {
+ event.preventDefault();
+ expectTypeOf(event.currentTarget).toEqualTypeOf<
+ EventTarget & HTMLAnchorElement
+ >();
+ handleLinkClick(event.currentTarget);
+ }}
+ />
+ }
+ >
+ <Avatar.Fallback>Jane</Avatar.Fallback>
+ </Avatar.Root>
+ </ThemeProvider>,
+ );
+
+ const button = screen.getByRole('button', { name: 'Open profile' });
+ const disabledButton = screen.getByRole('button', {
+ name: 'Disabled profile',
+ });
+ const link = screen.getByRole('link', { name: 'View Jane' });
+
+ expect(buttonRef.current).toBe(button);
+ expect(buttonRef.current).toBeInstanceOf(HTMLButtonElement);
+ expect(button).toHaveAttribute('type', 'button');
+ expect(disabledButton).toBeDisabled();
+ expect(linkRef.current).toBe(link);
+ expect(linkRef.current).toBeInstanceOf(HTMLAnchorElement);
+ expect(link).toHaveAttribute('href', '/people/jane');
+
+ await userEvent.click(button);
+
+ expect(handleButtonClick).toHaveBeenCalledWith(button);
+
+ await userEvent.click(disabledButton);
+
+ expect(handleButtonClick).toHaveBeenCalledTimes(1);
+
+ await userEvent.click(link);
+
+ expect(handleLinkClick).toHaveBeenCalledWith(link);
+ });
+
+ it('preserves caller fallback content, native props, handlers and render refs', async () => {
+ const fallbackRef = createRef<HTMLDivElement>();
+ const handleClick = vi.fn();
+
+ const { rerender } = render(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ name="Jane"
+ fallbackProps={{
+ children: <strong>Unavailable</strong>,
+ role: 'status',
+ 'aria-label': 'Profile unavailable',
+ render: <div />,
+ ref: fallbackRef,
+ onClick: (event) => handleClick(event.currentTarget),
+ }}
+ />
+ </ThemeProvider>,
+ );
+
+ const fallback = screen.getByRole('status', {
+ name: 'Profile unavailable',
+ });
+
+ expect(screen.getByText('Unavailable')).toBeVisible();
+ expect(screen.queryByText('J')).not.toBeInTheDocument();
+ expect(fallbackRef.current).toBe(fallback);
+ expect(fallbackRef.current).toBeInstanceOf(HTMLDivElement);
+
+ await userEvent.click(fallback);
+
+ expect(handleClick).toHaveBeenCalledWith(fallback);
+
+ rerender(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ name="Jane"
+ imageProps={{ alt: 'Jane' }}
+ fallbackProps={{ children: null }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(screen.getByRole('img', { name: 'Jane' })).toBeEmptyDOMElement();
+
+ for (const fallbackSemantics of [
+ { role: 'status' as const },
+ { 'aria-label': 'Portrait unavailable' },
+ { 'aria-labelledby': 'portrait-fallback-label' },
+ ]) {
+ rerender(
+ <ThemeProvider colorScheme="light">
+ <span id="portrait-fallback-label">Portrait unavailable</span>
+ <Avatar
+ fallbackProps={{ children: 'Unavailable', ...fallbackSemantics }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(screen.getByText('Unavailable')).not.toHaveAttribute(
+ 'aria-hidden',
+ );
+ }
+
+ rerender(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ fallbackProps={{
+ children: 'Unavailable',
+ role: 'status',
+ 'aria-label': 'Portrait unavailable',
+ 'aria-hidden': true,
+ }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+ expect(screen.getByText('Unavailable')).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ });
+
+ it.each(['aria-label', 'aria-labelledby'] as const)(
+ 'preserves fallback semantics supplied through render with %s',
+ (labelAttribute) => {
+ const fallbackRef = createRef<HTMLSpanElement>();
+ const fallbackLabel =
+ labelAttribute === 'aria-label'
+ ? 'Portrait unavailable'
+ : 'portrait-fallback-label';
+ const fallbackRender = (
+ <span role="img" {...{ [labelAttribute]: fallbackLabel }} />
+ );
+ render(
+ <ThemeProvider colorScheme="light">
+ <span id="portrait-fallback-label">Portrait unavailable</span>
+ <Avatar
+ fallbackProps={{
+ render: fallbackRender,
+ ref: fallbackRef,
+ children: 'NA',
+ }}
+ />
+ </ThemeProvider>,
+ );
+
+ const fallback = screen.getByRole('img', {
+ name: 'Portrait unavailable',
+ });
+
+ expect(fallback).toHaveTextContent('NA');
+ expect(fallback).not.toHaveAttribute('aria-hidden');
+ expect(fallbackRef.current).toBe(fallback);
+ },
+ );
+
+ it('lets a fallback render function own its semantics and preserves explicit hiding', () => {
+ const { rerender } = render(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ fallbackProps={{
+ render: (props) => (
+ <span {...props} role="img" aria-label="Portrait unavailable" />
+ ),
+ children: 'NA',
+ }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(
+ screen.getByRole('img', { name: 'Portrait unavailable' }),
+ ).toHaveTextContent('NA');
+
+ rerender(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ fallbackProps={{
+ render: (
+ <span role="img" aria-label="Portrait unavailable" aria-hidden />
+ ),
+ children: 'NA',
+ }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(screen.queryByRole('img')).not.toBeInTheDocument();
+ expect(screen.getByText('NA')).toHaveAttribute('aria-hidden', 'true');
+ });
+
+ it('is decorative by default and uses explicit image alternative text for its fallback', () => {
+ const { rerender } = render(
+ <ThemeProvider colorScheme="light">
+ <Avatar name="Jane" imageProps={{ alt: 'Jane portrait' }} />
+ </ThemeProvider>,
+ );
+
+ expect(
+ screen.getByRole('img', { name: 'Jane portrait' }),
+ ).toHaveTextContent('J');
+
+ rerender(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ name="Jane"
+ src="/jane.png"
+ imageProps={{ keepMounted: true }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(screen.getByAltText('')).toHaveAttribute('alt', '');
+ expect(screen.queryByRole('img')).not.toBeInTheDocument();
+ expect(screen.getByText('J')).toHaveAttribute('aria-hidden', 'true');
+ });
+
+ it('passes the fallback delay through the shorthand', () => {
+ vi.useFakeTimers();
+
+ render(
+ <ThemeProvider colorScheme="light">
+ <Avatar
+ name="Jane"
+ imageProps={{ alt: 'Jane' }}
+ fallbackProps={{ delay: 100 }}
+ />
+ </ThemeProvider>,
+ );
+
+ expect(screen.queryByRole('img', { name: 'Jane' })).not.toBeInTheDocument();
+
+ act(() => vi.advanceTimersByTime(100));
+
+ expect(screen.getByRole('img', { name: 'Jane' })).toHaveTextContent('J');
+ });
+
+ it('shares rendered image loading, error and replacement state with its fallback', () => {
+ const imageRef = createRef<HTMLImageElement>();
+ const handleLoadingStatusChange = vi.fn();
+ const handleLoad = vi.fn();
+ const handleError = vi.fn();
+ const imageProps = {
+ alt: 'Jane',
+ keepMounted: true,
+ ref: imageRef,
+ onLoadingStatusChange: handleLoadingStatusChange,
+ onLoad: handleLoad,
+ onError: handleError,
+ loading: 'lazy',
+ crossOrigin: 'anonymous',
+ } as const;
+ const { rerender } = render(
+ <ThemeProvider colorScheme="light">
+ <Avatar name="Jane" src="/jane.png" imageProps={imageProps} />
+ </ThemeProvider>,
+ );
+
+ const image = screen.getByAltText<HTMLImageElement>('Jane');
+
+ expect(imageRef.current).toBe(image);
+ expect(image).toBeInstanceOf(HTMLImageElement);
+ expect(image).toHaveAttribute('loading', 'lazy');
+ expect(image).toHaveAttribute('crossorigin', 'anonymous');
+ expect(image).toHaveAttribute('alt', 'Jane');
+ expect(image).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByRole('img', { name: 'Jane' })).toHaveTextContent('J');
+ expect(handleLoadingStatusChange).toHaveBeenLastCalledWith('loading');
+
+ fireEvent.load(image);
+
+ expect(handleLoad).toHaveBeenCalledTimes(1);
+ expect(handleLoadingStatusChange).toHaveBeenLastCalledWith('loaded');
+ expect(screen.getByRole('img', { name: 'Jane' })).toBe(image);
+ expect(screen.queryByText('J')).not.toBeInTheDocument();
+
+ rerender(
+ <ThemeProvider colorScheme="light">
+ <Avatar name="Jane" src="/replacement.png" imageProps={imageProps} />
+ </ThemeProvider>,
+ );
+
+ expect(imageRef.current).toBe(image);
+ expect(image).toHaveAttribute('src', '/replacement.png');
+ expect(handleLoadingStatusChange).toHaveBeenLastCalledWith('loading');
+ expect(screen.getByRole('img', { name: 'Jane' })).toHaveTextContent('J');
+
+ fireEvent.error(image);
+
+ expect(handleError).toHaveBeenCalledTimes(1);
+ expect(handleLoadingStatusChange).toHaveBeenLastCalledWith('error');
+ expect(image).toHaveAttribute('data-error');
+ expect(image).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByRole('img', { name: 'Jane' })).toHaveTextContent('J');
+ });
+});
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarFallback.tsx b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarFallback.tsx
new file mode 100644
index 00000000000..070ec35e073
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarFallback.tsx
@@ -0,0 +1,16 @@
+import { Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
+
+import styles from '../Avatar.module.scss';
+import { type AvatarFallbackProps } from '../types/AvatarFallbackProps';
+
+export const AvatarFallback = ({
+ className,
+ ...props
+}: AvatarFallbackProps) => (
+ <AvatarPrimitive.Fallback
+ {...props}
+ className={mergeClassNames(styles.fallback, className)}
+ />
+);
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarImage.tsx b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarImage.tsx
new file mode 100644
index 00000000000..15c94329dd7
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarImage.tsx
@@ -0,0 +1,13 @@
+import { Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
+
+import styles from '../Avatar.module.scss';
+import { type AvatarImageProps } from '../types/AvatarImageProps';
+
+export const AvatarImage = ({ className, ...props }: AvatarImageProps) => (
+ <AvatarPrimitive.Image
+ {...props}
+ className={mergeClassNames(styles.image, className)}
+ />
+);
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarRoot.tsx b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarRoot.tsx
new file mode 100644
index 00000000000..63d609e1a48
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/AvatarRoot.tsx
@@ -0,0 +1,81 @@
+import { Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+import { isFunction } from '@sniptt/guards';
+import { type CSSProperties } from 'react';
+
+import { useTheme } from '@ui/theme';
+import { mergeClassNames } from '@ui/utilities/internal/mergeClassNames';
+import { stringToThemeColorP3String } from '@ui/utilities';
+
+import styles from '../Avatar.module.scss';
+import { type AvatarRootProps } from '../types/AvatarRootProps';
+
+import { getAvatarInitial } from './getAvatarInitial';
+
+export const AvatarRoot = ({
+ name,
+ colorSeed = name,
+ size = 'md',
+ shape = 'square',
+ variant = 'soft',
+ color,
+ backgroundColor,
+ borderColor,
+ pulsing = false,
+ ring = false,
+ className,
+ style,
+ ...props
+}: AvatarRootProps) => {
+ const theme = useTheme();
+ const initial = getAvatarInitial(name);
+ const fallbackColor = initial
+ ? (color ??
+ stringToThemeColorP3String({
+ string: colorSeed ?? '',
+ variant: 12,
+ theme,
+ }))
+ : (color ?? theme.font.color.tertiary);
+ const fallbackBackground = initial
+ ? (backgroundColor ??
+ stringToThemeColorP3String({
+ string: colorSeed ?? '',
+ variant: variant === 'outline' ? 5 : 4,
+ theme,
+ }))
+ : (backgroundColor ?? theme.background.transparent.light);
+ const fallbackBorder =
+ borderColor ??
+ (initial
+ ? stringToThemeColorP3String({
+ string: colorSeed ?? '',
+ variant: 6,
+ theme,
+ })
+ : undefined);
+
+ return (
+ <AvatarPrimitive.Root
+ {...props}
+ data-size={size}
+ data-shape={shape}
+ data-pulsing={pulsing || undefined}
+ data-ring={ring || undefined}
+ className={mergeClassNames(styles.root, className)}
+ style={(state) =>
+ ({
+ '--tw-avatar-color': fallbackColor,
+ '--tw-avatar-background':
+ state.imageLoadingStatus === 'loaded' ? 'none' : fallbackBackground,
+ '--tw-avatar-border':
+ variant === 'outline' &&
+ state.imageLoadingStatus !== 'loaded' &&
+ fallbackBorder
+ ? `1px solid ${fallbackBorder}`
+ : 'none',
+ ...(isFunction(style) ? style(state) : style),
+ }) as CSSProperties
+ }
+ />
+ );
+};
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/internal/getAvatarInitial.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/getAvatarInitial.ts
new file mode 100644
index 00000000000..b6737af25b4
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/internal/getAvatarInitial.ts
@@ -0,0 +1,2 @@
+export const getAvatarInitial = (name?: string) =>
+ name?.trim().charAt(0).toUpperCase();
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarFallbackProps.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarFallbackProps.ts
new file mode 100644
index 00000000000..890a7a64a84
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarFallbackProps.ts
@@ -0,0 +1,3 @@
+import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+export type AvatarFallbackProps = AvatarPrimitive.Fallback.Props;
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarFallbackState.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarFallbackState.ts
new file mode 100644
index 00000000000..0fa199073a7
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarFallbackState.ts
@@ -0,0 +1,3 @@
+import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+export type AvatarFallbackState = AvatarPrimitive.Fallback.State;
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageLoadingStatus.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageLoadingStatus.ts
new file mode 100644
index 00000000000..731786392fa
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageLoadingStatus.ts
@@ -0,0 +1,3 @@
+import { type AvatarRootState } from './AvatarRootState';
+
+export type AvatarImageLoadingStatus = AvatarRootState['imageLoadingStatus'];
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageProps.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageProps.ts
new file mode 100644
index 00000000000..1dd4b972510
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageProps.ts
@@ -0,0 +1,3 @@
+import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+export type AvatarImageProps = AvatarPrimitive.Image.Props;
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageState.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageState.ts
new file mode 100644
index 00000000000..c733ed6f93f
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarImageState.ts
@@ -0,0 +1,3 @@
+import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+export type AvatarImageState = AvatarPrimitive.Image.State;
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarProps.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarProps.ts
index 521f377737a..7e7e35c1cbd 100644
--- a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarProps.ts
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarProps.ts
@@ -1,22 +1,12 @@
-import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
import { type ReactNode } from 'react';
-import { type AvatarSize } from './AvatarSize';
-import { type AvatarShape } from './AvatarShape';
+import { type AvatarFallbackProps } from './AvatarFallbackProps';
+import { type AvatarImageProps } from './AvatarImageProps';
+import { type AvatarRootProps } from './AvatarRootProps';
-export type AvatarProps = Omit<AvatarPrimitive.Root.Props, 'children'> & {
+export type AvatarProps = Omit<AvatarRootProps, 'children' | 'onClick'> & {
src?: string | null;
- name?: string;
- colorSeed?: string;
- size?: AvatarSize;
- shape?: AvatarShape;
- variant?: 'soft' | 'outline';
icon?: ReactNode;
- color?: string;
- backgroundColor?: string;
- borderColor?: string;
- pulsing?: boolean;
- ring?: boolean;
- disabled?: boolean;
- nativeButton?: boolean;
+ imageProps?: AvatarImageProps;
+ fallbackProps?: AvatarFallbackProps;
};
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarRootProps.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarRootProps.ts
new file mode 100644
index 00000000000..506d98eb8be
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarRootProps.ts
@@ -0,0 +1,17 @@
+import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+import { type AvatarShape } from './AvatarShape';
+import { type AvatarSize } from './AvatarSize';
+
+export type AvatarRootProps = AvatarPrimitive.Root.Props & {
+ name?: string;
+ colorSeed?: string;
+ size?: AvatarSize;
+ shape?: AvatarShape;
+ variant?: 'soft' | 'outline';
+ color?: string;
+ backgroundColor?: string;
+ borderColor?: string;
+ pulsing?: boolean;
+ ring?: boolean;
+};
diff --git a/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarRootState.ts b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarRootState.ts
new file mode 100644
index 00000000000..7899762526a
--- /dev/null
+++ b/packages/twenty-ui/src/primitives/data-display/Avatar/types/AvatarRootState.ts
@@ -0,0 +1,3 @@
+import { type Avatar as AvatarPrimitive } from '@base-ui/react/avatar';
+
+export type AvatarRootState = AvatarPrimitive.Root.State;
diff --git a/packages/twenty-ui/src/primitives/data-display/index.ts b/packages/twenty-ui/src/primitives/data-display/index.ts
index 9da76565774..356f674e899 100644
--- a/packages/twenty-ui/src/primitives/data-display/index.ts
+++ b/packages/twenty-ui/src/primitives/data-display/index.ts
@@ -9,7 +9,14 @@
export { Avatar } from './Avatar/Avatar';
export { AVATAR_PROPERTIES_BY_SIZE } from './Avatar/constants/AvatarPropertiesBySize';
+export type { AvatarFallbackProps } from './Avatar/types/AvatarFallbackProps';
+export type { AvatarFallbackState } from './Avatar/types/AvatarFallbackState';
+export type { AvatarImageLoadingStatus } from './Avatar/types/AvatarImageLoadingStatus';
+export type { AvatarImageProps } from './Avatar/types/AvatarImageProps';
+export type { AvatarImageState } from './Avatar/types/AvatarImageState';
export type { AvatarProps } from './Avatar/types/AvatarProps';
+export type { AvatarRootProps } from './Avatar/types/AvatarRootProps';
+export type { AvatarRootState } from './Avatar/types/AvatarRootState';
export type { AvatarShape } from './Avatar/types/AvatarShape';
export type { AvatarSize } from './Avatar/types/AvatarSize';
export { Chip } from './Chip/Chip';