Skip to content

The open alternative to Salesforce, designed for AI.

Derive AvatarGroup overflow (#27646)

Raphaël Bosi6798e887321f
diff --git a/packages/twenty-docs/snippets/ui/generated/components/data-display/avatar-group.mdx b/packages/twenty-docs/snippets/ui/generated/components/data-display/avatar-group.mdx
index b8eeab9f57f..732b68b0b11 100644
--- a/packages/twenty-docs/snippets/ui/generated/components/data-display/avatar-group.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/components/data-display/avatar-group.mdx
@@ -12,7 +12,7 @@
*/}
<ParamField body="avatars" type="ReactNode[]" required>
- Avatar elements in display order. Only the first maxVisible elements are shown.
+ Avatar elements in display order. Empty React nodes are ignored. Supply stable keys to preserve identity when reordering.
</ParamField>
<ParamField body="className" type="string">
@@ -20,15 +20,7 @@
</ParamField>
<ParamField body="maxVisible" type="number" default="4">
- Maximum number of supplied avatars to show.
-</ParamField>
-
-<ParamField body="overflowAvatar" type="ReactNode">
- Custom trailing element, used instead of the numeric overflow indicator.
-</ParamField>
-
-<ParamField body="overflowCount" type="number" default="0">
- Number shown in the trailing +N indicator. Compute this in the application; it is not derived from avatars.
+ Maximum number of actual avatars to show, excluding the overflow indicator. Floored and clamped to zero; Infinity shows all avatars and NaN shows none.
</ParamField>
<ParamField body="overflowShape" type="&quot;circle&quot; | &quot;rounded-square&quot; | &quot;square&quot;" default="square">
@@ -42,3 +34,19 @@
<ParamField body="overlapOffset" type="string" default="3px">
CSS length of the overlap between avatars.
</ParamField>
+
+<ParamField body="ref" type="Ref&lt;HTMLDivElement&gt;">
+ Ref to the rendered root element.
+</ParamField>
+
+<ParamField body="render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, {}&gt;">
+ Element or render function for the root. Forward the supplied props and ref; the default element is a div.
+</ParamField>
+
+<ParamField body="renderOverflow" type="((hiddenCount: number) =&gt; ReactNode)">
+ Called with the derived hidden count when it is positive. Return a custom indicator, or null to hide it.
+</ParamField>
+
+<ParamField body="total" type="number">
+ Total collection size for partially loaded avatars. Floored and never smaller than the supplied renderable count; nonfinite values use the supplied count.
+</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 94d0f6ff913..5e08e34cbd1 100644
--- a/packages/twenty-docs/ui/components/data-display/avatar-group.mdx
+++ b/packages/twenty-docs/ui/components/data-display/avatar-group.mdx
@@ -1,12 +1,12 @@
---
title: AvatarGroup
-description: Overlapping avatars with an optional overflow indicator.
+description: Overlapping avatars with a derived overflow indicator.
---
import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
import AvatarGroupReference from '/snippets/ui/generated/components/data-display/avatar-group.mdx';
-`AvatarGroup` receives rendered avatars. Supply `overflowCount` yourself; slicing the avatars does not calculate the hidden count. `overflowAvatar` replaces the numeric indicator.
+`AvatarGroup` receives rendered avatars and derives the hidden count. `maxVisible` counts actual avatars; the overflow indicator is additional. Eight supplied avatars with `maxVisible={3}` show three avatars and `+5`.
```tsx
import { AvatarGroup } from 'twenty-ui/components/data-display';
@@ -14,25 +14,136 @@ import { Avatar } from 'twenty-ui/primitives/data-display';
export const TeamAvatars = () => (
<AvatarGroup
- maxVisible={2}
- overflowCount={1}
+ maxVisible={3}
avatars={[
- <Avatar key="ada" name="Ada Lovelace" />,
- <Avatar key="grace" name="Grace Hopper" />,
- <Avatar key="margaret" name="Margaret Hamilton" />,
- ]}
+ 'Ada',
+ 'Grace',
+ 'Margaret',
+ 'Annie',
+ 'Mary',
+ 'Dorothy',
+ 'Katherine',
+ 'Joan',
+ ].map((name) => (
+ <Avatar key={name} name={name} />
+ ))}
/>
);
```
-Keep the member names available in surrounding content. Later avatars always render above earlier ones. `overlap` only picks the physical margin, `left` or `right`, that carries the negative offset, and `overlapOffset` sets that offset as a CSS length. An empty group without an overflow element renders nothing.
+Supply stable keys to keep surviving avatars mounted when the limit, total, or display order changes. Keep the member names available in surrounding content.
<StoryEmbed
- storyId="ui-data-display-avatargroup--default"
- title="AvatarGroup example"
+ storyId="ui-data-display-avatargroup--with-derived-overflow"
+ title="Eight avatars with three visible"
height={280}
/>
+## Partially loaded collections
+
+Use `total` for the full collection size when only some avatars are loaded. Three supplied and visible avatars with `total={20}` show `+17`. Pass all loaded avatars and let the group apply `maxVisible`.
+
+```tsx
+import { AvatarGroup } from 'twenty-ui/components/data-display';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+
+export const LoadedTeamAvatars = () => (
+ <AvatarGroup
+ maxVisible={3}
+ total={20}
+ avatars={['Ada', 'Grace', 'Margaret'].map((name) => (
+ <Avatar key={name} name={name} />
+ ))}
+ />
+);
+```
+
+`total` is floored and cannot be smaller than the supplied renderable avatar count. Nonfinite totals use the supplied count. The derived hidden count is always nonnegative.
+
+`maxVisible` defaults to `4`. Finite limits are floored and clamped to zero, `Infinity` shows all supplied avatars, and `NaN` shows none. Empty React nodes do not count as avatars. A zero limit can show only the overflow indicator. An empty group with a positive total can show that total in its indicator; an empty group with no hidden avatars renders nothing.
+
+<StoryEmbed
+ storyId="ui-data-display-avatargroup--partially-loaded"
+ title="Three loaded members from a team of twenty"
+ height={280}
+/>
+
+## Custom overflow
+
+`renderOverflow` receives the same derived hidden count as the default `+N` indicator. It runs only when that count is positive. Return `null` to hide the indicator without changing which avatars are visible.
+
+Use an explicit control when the indicator performs an action. Its accessible name should explain the action and the count.
+
+```tsx
+import { AvatarGroup } from 'twenty-ui/components/data-display';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { Button } from 'twenty-ui/primitives/input';
+
+type TeamAvatarsWithActionProps = { onShowAll: () => void };
+
+export const TeamAvatarsWithAction = ({
+ onShowAll,
+}: TeamAvatarsWithActionProps) => (
+ <AvatarGroup
+ maxVisible={3}
+ total={20}
+ avatars={['Ada', 'Grace', 'Margaret'].map((name) => (
+ <Avatar key={name} name={name} />
+ ))}
+ renderOverflow={(hiddenCount) => (
+ <Button
+ size="sm"
+ aria-label={`Show ${hiddenCount} more members`}
+ onClick={onShowAll}
+ >
+ +{hiddenCount}
+ </Button>
+ )}
+ />
+);
+```
+
+<StoryEmbed
+ storyId="ui-data-display-avatargroup--custom-overflow"
+ title="Custom overflow button"
+ height={280}
+/>
+
+## Appearance
+
+Later avatars always render above earlier ones. `overlap` picks the physical margin, `left` or `right`, that carries the negative offset. `overlapOffset` sets that offset as a CSS length. `overflowShape` sets the shape of the default numeric indicator.
+
+## Root customization
+
+Native attributes, event handlers, `className`, and `style` reach the root. Its default element is a `div`, including when `onClick` is supplied. Use native interactive elements for actions, such as the overflow button above.
+
+The root accepts a ref and `render`, which can be an element or a function. Custom components must forward the supplied props and ref to their native root. See [custom components](/ui/primitives/overview#custom-components) for composition requirements.
+
+```tsx
+import { useRef } from 'react';
+import { AvatarGroup } from 'twenty-ui/components/data-display';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+
+export const NamedTeamAvatars = () => {
+ const groupRef = useRef<HTMLDivElement>(null);
+
+ return (
+ <AvatarGroup
+ ref={groupRef}
+ role="group"
+ aria-label="Project members"
+ style={{ marginBlock: 8 }}
+ render={<div data-location="project-header" />}
+ avatars={['Ada', 'Grace', 'Margaret'].map((name) => (
+ <Avatar key={name} name={name} />
+ ))}
+ />
+ );
+};
+```
+
## Props
+`AvatarGroupProps` is exported from `twenty-ui/components/data-display`.
+
<AvatarGroupReference />
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiAvatarGroup.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiAvatarGroup.stories.tsx
new file mode 100644
index 00000000000..f6f0ab5bc89
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiAvatarGroup.stories.tsx
@@ -0,0 +1,31 @@
+import { type Meta } from '@storybook/react-vite';
+
+import {
+ FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ resetFrontComponentStoryMocks,
+} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { type TwentyUiGalleryStory as Story } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryStory';
+import { avatarGroupTest } from '@/__stories__/twenty-ui-gallery/utils/avatarGroupTest';
+import { createGalleryStory } from '@/__stories__/twenty-ui-gallery/utils/createGalleryStory';
+import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
+
+const meta: Meta<typeof FrontComponentRenderer> = {
+ title: 'FrontComponent/Twenty UI AvatarGroup',
+ component: FrontComponentRenderer,
+ args: FRONT_COMPONENT_STORY_DEFAULT_ARGS,
+ beforeEach: resetFrontComponentStoryMocks,
+};
+
+export default meta;
+
+export const AvatarGroupReact: Story = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-avatar-group',
+ runtime: 'react',
+ play: avatarGroupTest,
+});
+
+export const AvatarGroupPreact: Story = createGalleryStory({
+ frontComponentBundleName: 'twenty-ui-avatar-group',
+ runtime: 'preact',
+ play: avatarGroupTest,
+});
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 af85c1c4e37..59cea45c27b 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
@@ -13,6 +13,8 @@ Popover composes Portal, Positioner, Popup, Arrow and Viewport. Its focused Reac
Typography composition checks constrained text, explicit links, semantic elements, refs and native focus handlers in both runtimes. Overflow tooltip popup acceptance still depends on renderer portal and geometry support.
+AvatarGroup checks derived counts, partially loaded totals, custom overflow and surviving keyed child state. Its native button and link (`target="_blank"`) verify refs, focus and pointer/keyboard activation in React and Preact.
+
Scenarios share their checks between runtimes where behavior matches. The story
file contains the metadata and named entries; `utils/` holds the story factory,
shared assertions, render checks, interaction checks, and known-failure
@@ -34,6 +36,7 @@ effect within the interaction timeout.
| `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 |
@@ -175,13 +178,14 @@ Then, from `packages/twenty-front-component-renderer`, run:
npx vitest run --config vitest.storybook.config.ts TwentyUiGallery.stories.tsx
```
-The Autocomplete, CountrySelect and reading-directions fixtures live in their
-own story files, so run them separately:
+The AvatarGroup, Autocomplete, CountrySelect and reading-directions fixtures
+live in their own story files, so run them separately:
```sh
npx vitest run --config vitest.storybook.config.ts TwentyUiAutocomplete.stories.tsx
npx vitest run --config vitest.storybook.config.ts TwentyUiCountrySelect.stories.tsx
npx vitest run --config vitest.storybook.config.ts TwentyUiReadingDirections.stories.tsx
+npx vitest run --config vitest.storybook.config.ts TwentyUiAvatarGroup.stories.tsx
```
Section and CommandBlock composition is checked in the Typography and DataDisplay
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/stateful-group-avatar.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/stateful-group-avatar.tsx
new file mode 100644
index 00000000000..d658cac2546
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/stateful-group-avatar.tsx
@@ -0,0 +1,21 @@
+import { useState } from 'react';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+
+type StatefulGroupAvatarProps = {
+ name: string;
+};
+
+export const StatefulGroupAvatar = ({ name }: StatefulGroupAvatarProps) => {
+ const [activations, setActivations] = useState(0);
+
+ return (
+ <button
+ type="button"
+ aria-label={`${name} activations ${activations}`}
+ onClick={() => setActivations((count) => count + 1)}
+ style={{ border: 0, padding: 0, background: 'none' }}
+ >
+ <Avatar name={name} />
+ </button>
+ );
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-group.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-group.front-component.tsx
new file mode 100644
index 00000000000..cb5d31ffdd2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-avatar-group.front-component.tsx
@@ -0,0 +1,124 @@
+import { isDefined } from 'twenty-shared/utils';
+import { createElement, useState } from 'react';
+import { defineFrontComponent } from 'twenty-sdk/define';
+import { AvatarGroup } from 'twenty-ui/components/data-display';
+import { Avatar } from 'twenty-ui/primitives/data-display';
+import { Button } from 'twenty-ui/primitives/input';
+
+import { TwentyUiGalleryCard } from '@/__stories__/shared/front-components/twenty-ui-gallery-card';
+import { StatefulGroupAvatar } from './stateful-group-avatar';
+
+const AVATAR_NAMES = ['Ada', 'Bea', 'Cam', 'Dee', 'Eli', 'Fay', 'Gia', 'Hal'];
+const AVATARS = AVATAR_NAMES.map((name) => (
+ <Avatar key={name} name={name} role="img" aria-label={name} />
+));
+
+const AvatarGroupExample = () => {
+ const [names, setNames] = useState(AVATAR_NAMES.slice(0, 4));
+ const [maxVisible, setMaxVisible] = useState(3);
+ const [total, setTotal] = useState(4);
+ const [rootActivations, setRootActivations] = useState(0);
+ const [buttonActivations, setButtonActivations] = useState(0);
+ const [linkActivations, setLinkActivations] = useState(0);
+
+ return (
+ <TwentyUiGalleryCard title="AvatarGroup overflow and composition">
+ <AvatarGroup
+ role="group"
+ aria-label="Supplied avatars"
+ avatars={AVATARS}
+ maxVisible={3}
+ />
+ <AvatarGroup
+ role="group"
+ aria-label="Partially loaded avatars"
+ avatars={AVATARS.slice(0, 3)}
+ maxVisible={3}
+ total={20}
+ />
+ <AvatarGroup
+ role="group"
+ aria-label="Custom overflow"
+ avatars={AVATARS}
+ maxVisible={3}
+ renderOverflow={(hiddenCount) => (
+ <Button aria-label={`Show ${hiddenCount} hidden people`}>
+ {hiddenCount} more
+ </Button>
+ )}
+ />
+ <AvatarGroup
+ role="group"
+ aria-label="Stateful avatars"
+ avatars={names.map((name) => (
+ <StatefulGroupAvatar key={name} name={name} />
+ ))}
+ maxVisible={maxVisible}
+ total={total}
+ />
+ <Button onClick={() => setNames(['Bea', 'Ada', 'Cam', 'Dee'])}>
+ Reorder avatars
+ </Button>
+ <Button onClick={() => setMaxVisible(2)}>Show two avatars</Button>
+ <Button onClick={() => setTotal(20)}>Load total</Button>
+ <Button onClick={() => setMaxVisible(4)}>Show four avatars</Button>
+ <AvatarGroup
+ id="native-avatar-group"
+ role="group"
+ aria-label="Native root"
+ title="Native group title"
+ className="custom-avatar-group"
+ style={{ padding: 7 }}
+ avatars={AVATARS.slice(0, 1)}
+ onClick={() => setRootActivations((count) => count + 1)}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ />
+ <AvatarGroup
+ aria-label="Open avatar group"
+ avatars={AVATARS.slice(0, 1)}
+ render={<button type="button" data-composed="button" />}
+ onClick={() => setButtonActivations((count) => count + 1)}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ />
+ <AvatarGroup
+ aria-label="Avatar group documentation"
+ avatars={AVATARS.slice(0, 1)}
+ render={(props) =>
+ createElement('a', {
+ ...props,
+ href: 'https://twenty.com',
+ target: '_blank',
+ rel: 'noreferrer',
+ 'data-composed': 'link',
+ })
+ }
+ onClick={() => setLinkActivations((count) => count + 1)}
+ ref={(element) => {
+ if (isDefined(element)) {
+ element.dataset.refTag = element.tagName;
+ }
+ }}
+ />
+ <output aria-label="Native root activations">{rootActivations}</output>
+ <output aria-label="Composed button activations">
+ {buttonActivations}
+ </output>
+ <output aria-label="Composed link activations">{linkActivations}</output>
+ </TwentyUiGalleryCard>
+ );
+};
+
+export default defineFrontComponent({
+ universalIdentifier: 'dbd13618-edb6-48a6-b4ce-c5af12b8d834',
+ name: 'twenty-ui-avatar-group',
+ description: 'AvatarGroup derived counts, child identity and native roots',
+ component: AvatarGroupExample,
+});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-reading-directions.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-reading-directions.front-component.tsx
index 0deeacbc883..028a1b025f8 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-reading-directions.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-reading-directions.front-component.tsx
@@ -69,7 +69,7 @@ const DirectionalLayoutExample = ({
avatars={['Ada', 'Bea', 'Cam'].map((name) => (
<Avatar key={name} name={name} size="lg" />
))}
- overflowCount={2}
+ total={5}
/>
</div>
))}
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarGroupTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarGroupTest.ts
new file mode 100644
index 00000000000..e8ef12125d2
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/avatarGroupTest.ts
@@ -0,0 +1,110 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+
+export const avatarGroupTest: TwentyUiGalleryPlayFunction = async ({
+ canvasElement,
+}) => {
+ const canvas = within(canvasElement);
+ await expectFrontComponentMounted(canvas);
+
+ const supplied = canvas.getByRole('group', { name: 'Supplied avatars' });
+ expect(within(supplied).getAllByRole('img')).toHaveLength(3);
+ expect(within(supplied).getByText('+5')).toBeVisible();
+ const partiallyLoaded = canvas.getByRole('group', {
+ name: 'Partially loaded avatars',
+ });
+ expect(within(partiallyLoaded).getAllByRole('img')).toHaveLength(3);
+ expect(within(partiallyLoaded).getByText('+17')).toBeVisible();
+ const custom = canvas.getByRole('group', { name: 'Custom overflow' });
+ expect(within(custom).getAllByRole('img')).toHaveLength(3);
+ expect(
+ within(custom).getByRole('button', { name: 'Show 5 hidden people' }),
+ ).toHaveTextContent('5 more');
+
+ const stateful = within(
+ canvas.getByRole('group', { name: 'Stateful avatars' }),
+ );
+ const ada = stateful.getByRole('button', { name: 'Ada activations 0' });
+ await userEvent.click(ada);
+ await waitFor(() => expect(ada).toHaveAccessibleName('Ada activations 1'));
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Reorder avatars' }),
+ );
+ await waitFor(() => {
+ expect(stateful.getAllByRole('button')[0]).toHaveAccessibleName(
+ 'Bea activations 0',
+ );
+ expect(stateful.getByRole('button', { name: 'Ada activations 1' })).toBe(
+ ada,
+ );
+ });
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Show two avatars' }),
+ );
+ await waitFor(() => {
+ expect(stateful.getAllByRole('button')).toHaveLength(2);
+ expect(stateful.getByText('+2')).toBeVisible();
+ });
+ await userEvent.click(canvas.getByRole('button', { name: 'Load total' }));
+ await waitFor(() => expect(stateful.getByText('+18')).toBeVisible());
+ await userEvent.click(
+ canvas.getByRole('button', { name: 'Show four avatars' }),
+ );
+ await waitFor(() => {
+ expect(stateful.getAllByRole('button')).toHaveLength(4);
+ expect(stateful.getByText('+16')).toBeVisible();
+ expect(stateful.getByRole('button', { name: 'Ada activations 1' })).toBe(
+ ada,
+ );
+ });
+ await userEvent.click(ada);
+ await waitFor(() => expect(ada).toHaveAccessibleName('Ada activations 2'));
+
+ const nativeRoot = canvas.getByRole('group', { name: 'Native root' });
+ expect(nativeRoot.tagName).toBe('DIV');
+ expect(nativeRoot).toHaveAttribute('id', 'native-avatar-group');
+ expect(nativeRoot).toHaveAttribute('title', 'Native group title');
+ expect(nativeRoot).toHaveClass('custom-avatar-group');
+ expect(nativeRoot).toHaveStyle({ padding: '7px' });
+ await waitFor(() =>
+ expect(nativeRoot).toHaveAttribute('data-ref-tag', 'HTML-DIV'),
+ );
+ await userEvent.click(nativeRoot);
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Native root activations')).toHaveTextContent(
+ '1',
+ ),
+ );
+
+ const button = canvas.getByRole('button', { name: 'Open avatar group' });
+ expect(button).toHaveAttribute('data-composed', 'button');
+ await waitFor(() =>
+ expect(button).toHaveAttribute('data-ref-tag', 'HTML-BUTTON'),
+ );
+ await userEvent.click(button);
+ await userEvent.keyboard('{Enter} ');
+ await waitFor(() =>
+ expect(
+ canvas.getByLabelText('Composed button activations'),
+ ).toHaveTextContent('3'),
+ );
+ expect(button).toHaveFocus();
+
+ const link = canvas.getByRole('link', { name: 'Avatar group documentation' });
+ expect(link).toHaveAttribute('href', 'https://twenty.com');
+ expect(link).toHaveAttribute('target', '_blank');
+ expect(link).toHaveAttribute('data-composed', 'link');
+ await waitFor(() => expect(link).toHaveAttribute('data-ref-tag', 'HTML-A'));
+ await userEvent.click(link);
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() =>
+ expect(
+ canvas.getByLabelText('Composed link activations'),
+ ).toHaveTextContent('2'),
+ );
+ expect(link).toHaveFocus();
+ expect(errorHandler).not.toHaveBeenCalled();
+};
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 03182f38f3f..db14593f7fd 100644
--- a/packages/twenty-front/src/modules/workspace-member/components/WorkspaceMemberAvatarStack.tsx
+++ b/packages/twenty-front/src/modules/workspace-member/components/WorkspaceMemberAvatarStack.tsx
@@ -1,4 +1,5 @@
import { styled } from '@linaria/react';
+import { isNonEmptyString } from '@sniptt/guards';
import { AvatarGroup } from 'twenty-ui/components/data-display';
import { Avatar } from 'twenty-ui/primitives/data-display';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -37,19 +38,28 @@ const StyledAvatarContainer = styled.div`
display: flex;
`;
-const getWorkspaceMemberDisplayName = (
- workspaceMember: WorkspaceMemberAvatarStackMember,
- defaultAvatarName: string,
-) => {
+const getWorkspaceMemberDisplayName = ({
+ workspaceMember,
+ defaultAvatarName,
+}: {
+ workspaceMember: WorkspaceMemberAvatarStackMember;
+ defaultAvatarName: string;
+}) => {
const fullName = [
workspaceMember.name?.firstName,
workspaceMember.name?.lastName,
]
- .filter(Boolean)
+ .filter(isNonEmptyString)
.join(' ')
.trim();
- return fullName || workspaceMember.userEmail || defaultAvatarName;
+ if (isNonEmptyString(fullName)) {
+ return fullName;
+ }
+
+ return isNonEmptyString(workspaceMember.userEmail)
+ ? workspaceMember.userEmail
+ : defaultAvatarName;
};
export const WorkspaceMemberAvatarStack = ({
@@ -58,45 +68,32 @@ export const WorkspaceMemberAvatarStack = ({
totalWorkspaceMembersCount,
workspaceMembers,
}: WorkspaceMemberAvatarStackProps) => {
- const visibleWorkspaceMembers = workspaceMembers.slice(0, maxVisible);
- const visibleWorkspaceMembersCount = visibleWorkspaceMembers.length;
- const hiddenWorkspaceMembersCount = Math.max(
- 0,
- (totalWorkspaceMembersCount ?? workspaceMembers.length) -
- visibleWorkspaceMembersCount,
- );
-
- if (visibleWorkspaceMembersCount === 0 && hiddenWorkspaceMembersCount === 0) {
- return null;
- }
-
return (
- <StyledAvatarStackContainer>
- <AvatarGroup
- avatars={visibleWorkspaceMembers.map((workspaceMember) => {
- const displayName = getWorkspaceMemberDisplayName(
- workspaceMember,
- defaultAvatarName,
- );
+ <AvatarGroup
+ render={<StyledAvatarStackContainer />}
+ avatars={workspaceMembers.map((workspaceMember) => {
+ const displayName = getWorkspaceMemberDisplayName({
+ workspaceMember,
+ defaultAvatarName,
+ });
- return (
- <StyledAvatarContainer key={workspaceMember.id}>
- <Avatar
- src={getAbsoluteImageUrl(workspaceMember.avatarUrl)}
- name={displayName}
- colorSeed={workspaceMember.id}
- size="md"
- shape="circle"
- />
- </StyledAvatarContainer>
- );
- })}
- maxVisible={maxVisible}
- overflowCount={hiddenWorkspaceMembersCount}
- overflowShape="circle"
- overlap="left"
- overlapOffset="4px"
- />
- </StyledAvatarStackContainer>
+ return (
+ <StyledAvatarContainer key={workspaceMember.id}>
+ <Avatar
+ src={getAbsoluteImageUrl(workspaceMember.avatarUrl)}
+ name={displayName}
+ colorSeed={workspaceMember.id}
+ size="md"
+ shape="circle"
+ />
+ </StyledAvatarContainer>
+ );
+ })}
+ maxVisible={maxVisible}
+ total={totalWorkspaceMembersCount ?? undefined}
+ overflowShape="circle"
+ overlap="left"
+ overlapOffset="4px"
+ />
);
};
diff --git a/packages/twenty-ui/docs/avatarGroupPropDescriptions.ts b/packages/twenty-ui/docs/avatarGroupPropDescriptions.ts
index 670303508b1..1342a10af1c 100644
--- a/packages/twenty-ui/docs/avatarGroupPropDescriptions.ts
+++ b/packages/twenty-ui/docs/avatarGroupPropDescriptions.ts
@@ -4,13 +4,17 @@ import { type AvatarGroup } from '../src/components/data-display/AvatarGroup/Ava
export const AVATAR_GROUP_PROP_DESCRIPTIONS = {
avatars:
- 'Avatar elements in display order. Only the first maxVisible elements are shown.',
+ 'Avatar elements in display order. Empty React nodes are ignored. Supply stable keys to preserve identity when reordering.',
className: 'Class applied to the group container.',
- maxVisible: 'Maximum number of supplied avatars to show.',
- overflowAvatar:
- 'Custom trailing element, used instead of the numeric overflow indicator.',
- overflowCount:
- 'Number shown in the trailing +N indicator. Compute this in the application; it is not derived from avatars.',
+ maxVisible:
+ 'Maximum number of actual avatars to show, excluding the overflow indicator. Floored and clamped to zero; Infinity shows all avatars and NaN shows none.',
+ total:
+ 'Total collection size for partially loaded avatars. Floored and never smaller than the supplied renderable count; nonfinite values use the supplied count.',
+ renderOverflow:
+ 'Called with the derived hidden count when it is positive. Return a custom indicator, or null to hide it.',
+ render:
+ 'Element or render function for the root. Forward the supplied props and ref; the default element is a div.',
+ ref: 'Ref to the rendered root element.',
overflowShape: 'Shape of the numeric overflow indicator.',
overlap:
'Physical margin, left or right, that carries the negative overlap offset. Later avatars always render above earlier ones.',
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index 19224047f25..2af3f089815 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -10710,7 +10710,7 @@
"type": "ReactNode[]",
"required": true,
"defaultValue": null,
- "description": "Avatar elements in display order. Only the first maxVisible elements are shown."
+ "description": "Avatar elements in display order. Empty React nodes are ignored. Supply stable keys to preserve identity when reordering."
},
{
"name": "className",
@@ -10724,21 +10724,7 @@
"type": "number",
"required": false,
"defaultValue": "4",
- "description": "Maximum number of supplied avatars to show."
- },
- {
- "name": "overflowAvatar",
- "type": "ReactNode",
- "required": false,
- "defaultValue": null,
- "description": "Custom trailing element, used instead of the numeric overflow indicator."
- },
- {
- "name": "overflowCount",
- "type": "number",
- "required": false,
- "defaultValue": "0",
- "description": "Number shown in the trailing +N indicator. Compute this in the application; it is not derived from avatars."
+ "description": "Maximum number of actual avatars to show, excluding the overflow indicator. Floored and clamped to zero; Infinity shows all avatars and NaN shows none."
},
{
"name": "overflowShape",
@@ -10760,6 +10746,34 @@
"required": false,
"defaultValue": "3px",
"description": "CSS length of the overlap between avatars."
+ },
+ {
+ "name": "ref",
+ "type": "Ref<HTMLDivElement>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Ref to the rendered root element."
+ },
+ {
+ "name": "render",
+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>",
+ "required": false,
+ "defaultValue": null,
+ "description": "Element or render function for the root. Forward the supplied props and ref; the default element is a div."
+ },
+ {
+ "name": "renderOverflow",
+ "type": "((hiddenCount: number) => ReactNode)",
+ "required": false,
+ "defaultValue": null,
+ "description": "Called with the derived hidden count when it is positive. Return a custom indicator, or null to hide it."
+ },
+ {
+ "name": "total",
+ "type": "number",
+ "required": false,
+ "defaultValue": null,
+ "description": "Total collection size for partially loaded avatars. Floored and never smaller than the supplied renderable count; nonfinite values use the supplied count."
}
]
},
diff --git a/packages/twenty-ui/src/components/__stories__/reading-direction/DirectionalLayoutExample.tsx b/packages/twenty-ui/src/components/__stories__/reading-direction/DirectionalLayoutExample.tsx
index 7d86209a69e..2a5d72e54ca 100644
--- a/packages/twenty-ui/src/components/__stories__/reading-direction/DirectionalLayoutExample.tsx
+++ b/packages/twenty-ui/src/components/__stories__/reading-direction/DirectionalLayoutExample.tsx
@@ -85,7 +85,7 @@ export const DirectionalLayoutExample = ({
avatars={['Ada', 'Bea', 'Cam'].map((name) => (
<Avatar key={name} name={name} size="lg" />
))}
- overflowCount={2}
+ total={5}
/>
</div>
))}
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/AvatarGroup.tsx b/packages/twenty-ui/src/components/data-display/AvatarGroup/AvatarGroup.tsx
index 4343691ec10..e4d29339334 100644
--- a/packages/twenty-ui/src/components/data-display/AvatarGroup/AvatarGroup.tsx
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/AvatarGroup.tsx
@@ -1,64 +1,88 @@
+import { useRender } from '@base-ui/react/use-render';
+import { isNonEmptyArray } from '@sniptt/guards';
import { clsx } from 'clsx';
-import { type CSSProperties } from 'react';
+import { Children, type CSSProperties, isValidElement } from 'react';
+
+import { isDefined } from '@ui/utilities/utils/isDefined';
+
import { type AvatarGroupProps } from './types/AvatarGroupProps';
import styles from './AvatarGroup.module.scss';
-const MAX_AVATARS_NB = 4;
+const DEFAULT_MAX_VISIBLE_AVATARS = 4;
export const AvatarGroup = ({
avatars,
className,
- maxVisible = MAX_AVATARS_NB,
- overflowAvatar,
- overflowCount = 0,
+ maxVisible = DEFAULT_MAX_VISIBLE_AVATARS,
+ total,
+ renderOverflow,
overflowShape = 'square',
overlap = 'right',
overlapOffset = '3px',
+ render,
+ ref,
+ ...props
}: AvatarGroupProps) => {
- const visibleAvatars = avatars.slice(0, maxVisible);
- const hasOverflowCount = !overflowAvatar && overflowCount > 0;
-
- if (!visibleAvatars.length && !overflowAvatar && !hasOverflowCount) {
- return null;
- }
-
+ const suppliedAvatars = Children.toArray(avatars);
+ const visibleLimit = Number.isNaN(maxVisible)
+ ? 0
+ : Math.max(0, Math.floor(maxVisible));
+ const visibleAvatars = suppliedAvatars.slice(0, visibleLimit);
+ const suppliedTotal = total ?? suppliedAvatars.length;
+ const avatarTotal = Number.isFinite(suppliedTotal)
+ ? Math.max(suppliedAvatars.length, Math.floor(suppliedTotal))
+ : suppliedAvatars.length;
+ const hiddenCount = avatarTotal - visibleAvatars.length;
+ const hasCustomOverflow = isDefined(renderOverflow);
+ const overflowContent =
+ hiddenCount > 0 &&
+ (hasCustomOverflow ? (
+ renderOverflow(hiddenCount)
+ ) : (
+ <span className={styles.overflowCount} data-shape={overflowShape}>
+ +{hiddenCount}
+ </span>
+ ));
+ const hasOverflow = isNonEmptyArray(Children.toArray(overflowContent));
const itemStyle = {
'--avatar-group-overlap-offset': overlapOffset,
} as CSSProperties;
- return (
- <div className={clsx(styles.container, className)}>
- {visibleAvatars.map((avatar, index) => (
- <div
- className={styles.itemContainer}
- data-overlap={overlap}
- key={index}
- style={itemStyle}
- >
- {avatar}
- </div>
- ))}
- {overflowAvatar && (
- <div
- className={styles.itemContainer}
- data-overlap={overlap}
- style={itemStyle}
- >
- {overflowAvatar}
- </div>
- )}
- {hasOverflowCount && (
- <div
- className={clsx(styles.itemContainer, styles.overflowCountContainer)}
- data-overlap={overlap}
- style={itemStyle}
- >
- <div className={styles.overflowCount} data-shape={overflowShape}>
- +{overflowCount}
- </div>
- </div>
- )}
- </div>
- );
+ const element = useRender({
+ render,
+ ref,
+ props: {
+ ...props,
+ className: clsx(styles.container, className),
+ children: (
+ <>
+ {Children.map(visibleAvatars, (avatar) => (
+ <span
+ className={styles.itemContainer}
+ key={isValidElement(avatar) ? avatar.key : undefined}
+ data-overlap={overlap}
+ style={itemStyle}
+ >
+ {avatar}
+ </span>
+ ))}
+ {hasOverflow && (
+ <span
+ className={clsx(
+ styles.itemContainer,
+ !hasCustomOverflow && styles.overflowCountContainer,
+ )}
+ data-overlap={overlap}
+ style={itemStyle}
+ >
+ {overflowContent}
+ </span>
+ )}
+ </>
+ ),
+ },
+ });
+
+ return isNonEmptyArray(visibleAvatars) || hasOverflow ? element : null;
};
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.interactions.stories.tsx b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.interactions.stories.tsx
new file mode 100644
index 00000000000..13f2705124c
--- /dev/null
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.interactions.stories.tsx
@@ -0,0 +1,155 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, within } from 'storybook/test';
+
+import { Avatar } from '@ui/primitives/data-display/Avatar/Avatar';
+import { Button } from '@ui/primitives/input/Button/Button';
+import { ComponentDecorator } from '@ui/testing';
+
+import { AvatarGroup } from '../AvatarGroup';
+import { AvatarGroupIdentityExample } from './AvatarGroupIdentityExample';
+
+const avatars = [
+ 'Matthew',
+ 'Sophie',
+ 'Jane',
+ 'Lily',
+ 'John',
+ 'Oliver',
+ 'Emma',
+ 'Noah',
+].map((name) => <Avatar key={name} name={name} role="img" aria-label={name} />);
+
+const onRootRef = fn();
+const onRootClick = fn();
+const onRootKeyDown = fn();
+
+const meta: Meta<typeof AvatarGroup> = {
+ id: 'ui-data-display-avatargroup-interactions',
+ title: 'UI/Components/Data display/AvatarGroup/Interactions',
+ component: AvatarGroup,
+ tags: ['!autodocs'],
+ decorators: [ComponentDecorator],
+ args: { avatars, maxVisible: 3 },
+ beforeEach: () => {
+ onRootRef.mockClear();
+ onRootClick.mockClear();
+ onRootKeyDown.mockClear();
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof AvatarGroup>;
+
+export const SuppliedAvatars: Story = {
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(await canvas.findByText('+5')).toBeVisible();
+
+ for (const name of ['Matthew', 'Sophie', 'Jane']) {
+ expect(canvas.getByLabelText(name)).toBeVisible();
+ }
+
+ expect(canvas.queryByLabelText('Lily')).not.toBeInTheDocument();
+ },
+};
+
+export const PartiallyLoaded: Story = {
+ args: { avatars: avatars.slice(0, 3), total: 20 },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(await canvas.findByText('+17')).toBeVisible();
+
+ for (const name of ['Matthew', 'Sophie', 'Jane']) {
+ expect(canvas.getByLabelText(name)).toBeVisible();
+ }
+ },
+};
+
+export const CustomOverflow: Story = {
+ args: {
+ avatars: avatars.slice(0, 3),
+ total: 20,
+ renderOverflow: (hiddenCount) => (
+ <Button size="sm">Show {hiddenCount} more members</Button>
+ ),
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+
+ expect(
+ await canvas.findByRole('button', { name: 'Show 17 more members' }),
+ ).toBeVisible();
+ expect(canvas.queryByText('+17')).not.toBeInTheDocument();
+ expect(canvas.getByLabelText('Jane')).toBeVisible();
+ },
+};
+
+export const SurvivingChildIdentity: Story = {
+ render: () => <AvatarGroupIdentityExample />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const sophie = canvas.getByRole('button', {
+ name: 'Sophie selected 0 times',
+ });
+
+ await userEvent.click(sophie);
+ expect(sophie).toHaveAccessibleName('Sophie selected 1 times');
+ expect(sophie).toHaveFocus();
+
+ for (const { key, hiddenCount, visibleCount } of [
+ { key: 'r', hiddenCount: 0, visibleCount: 3 },
+ { key: 'l', hiddenCount: 1, visibleCount: 2 },
+ { key: 't', hiddenCount: 18, visibleCount: 2 },
+ { key: 'l', hiddenCount: 17, visibleCount: 3 },
+ { key: 't', hiddenCount: 0, visibleCount: 3 },
+ ]) {
+ await userEvent.keyboard(key);
+ expect(
+ canvas.getByRole('button', { name: 'Sophie selected 1 times' }),
+ ).toBe(sophie);
+ expect(sophie).toHaveFocus();
+ expect(canvas.getAllByRole('button')).toHaveLength(visibleCount);
+ expect(canvas.getAllByRole('button')[0]).toBe(sophie);
+
+ if (hiddenCount > 0) {
+ expect(canvas.getByText(`+${hiddenCount}`)).toBeVisible();
+ continue;
+ }
+
+ expect(canvas.queryByText(/^\+/)).not.toBeInTheDocument();
+ }
+ },
+};
+
+export const NativeRootComposition: Story = {
+ args: {
+ ref: onRootRef,
+ onClick: onRootClick,
+ onKeyDown: onRootKeyDown,
+ 'aria-label': 'Team members',
+ role: 'group',
+ tabIndex: 0,
+ title: 'Current team',
+ lang: 'fr',
+ render: <section data-team="sales" />,
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const root = canvas.getByRole('group', { name: 'Team members' });
+
+ expect(root.tagName).toBe('SECTION');
+ expect(root).toHaveAttribute('title', 'Current team');
+ expect(root).toHaveAttribute('lang', 'fr');
+ expect(root).toHaveAttribute('data-team', 'sales');
+ expect(onRootRef).toHaveBeenCalledWith(root);
+ root.focus();
+ await userEvent.keyboard('{Enter}');
+ expect(root).toHaveFocus();
+ expect(onRootKeyDown).toHaveBeenCalledOnce();
+ expect(onRootClick).not.toHaveBeenCalled();
+ await userEvent.click(root);
+ expect(onRootClick).toHaveBeenCalledOnce();
+ },
+};
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.stories.tsx b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.stories.tsx
index 37b072c0e23..8aad7362747 100644
--- a/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.stories.tsx
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroup.stories.tsx
@@ -1,10 +1,10 @@
import { type Meta, type StoryObj } from '@storybook/react-vite';
-import { expect, within } from 'storybook/test';
import { Avatar } from '@ui/primitives/data-display/Avatar/Avatar';
import { type AvatarProps } from '@ui/primitives/data-display/Avatar/types/AvatarProps';
import { type AvatarShape } from '@ui/primitives/data-display/Avatar/types/AvatarShape';
import { type AvatarSize } from '@ui/primitives/data-display/Avatar/types/AvatarSize';
+import { Button } from '@ui/primitives/input/Button/Button';
import {
A11Y_DEFER_COLOR_CONTRAST,
AVATAR_URL_MOCK,
@@ -15,16 +15,31 @@ import {
import { AvatarGroup } from '@ui/components/data-display/AvatarGroup/AvatarGroup';
import { type AvatarGroupProps } from '@ui/components/data-display/AvatarGroup/types/AvatarGroupProps';
-const makeAvatar = (userName: string, props: Partial<AvatarProps> = {}) => (
- <Avatar name={userName} colorSeed={userName} {...props} />
+const makeAvatar = ({
+ userName,
+ props = {},
+}: {
+ userName: string;
+ props?: Partial<AvatarProps>;
+}) => (
+ <Avatar
+ key={userName}
+ name={userName}
+ colorSeed={userName}
+ role="img"
+ aria-label={userName}
+ {...props}
+ />
);
const getAvatars = (commonProps: Partial<AvatarProps> = {}) => [
- makeAvatar('Matthew', { src: AVATAR_URL_MOCK, ...commonProps }),
- makeAvatar('Sophie', commonProps),
- makeAvatar('Jane', commonProps),
- makeAvatar('Lily', commonProps),
- makeAvatar('John', commonProps),
+ makeAvatar({
+ userName: 'Matthew',
+ props: { src: AVATAR_URL_MOCK, ...commonProps },
+ }),
+ ...['Sophie', 'Jane', 'Lily', 'John', 'Oliver', 'Emma', 'Noah'].map(
+ (userName) => makeAvatar({ userName, props: commonProps }),
+ ),
];
const meta: Meta<
@@ -45,42 +60,59 @@ export const Default: Story = {
decorators: [ComponentDecorator],
};
-export const WithOverflowCount: Story = {
+export const WithDerivedOverflow: Story = {
decorators: [ComponentDecorator],
render: () => (
<AvatarGroup
avatars={getAvatars({ shape: 'circle' })}
maxVisible={3}
- overflowCount={9}
overflowShape="circle"
overlap="left"
overlapOffset="4px"
/>
),
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
+};
- expect(await canvas.findByText('+9')).toBeVisible();
- },
+export const PartiallyLoaded: Story = {
+ decorators: [ComponentDecorator],
+ render: () => (
+ <AvatarGroup
+ avatars={getAvatars({ shape: 'circle' }).slice(0, 3)}
+ maxVisible={3}
+ total={20}
+ overflowShape="circle"
+ />
+ ),
+};
+
+export const CustomOverflow: Story = {
+ decorators: [ComponentDecorator],
+ render: () => (
+ <AvatarGroup
+ avatars={getAvatars({ shape: 'circle' })}
+ maxVisible={3}
+ renderOverflow={(hiddenCount) => (
+ <Button size="sm" variant="ghost">
+ {hiddenCount} more members
+ </Button>
+ )}
+ />
+ ),
};
export const WithRing: Story = {
decorators: [ComponentDecorator],
render: () => (
<AvatarGroup
- avatars={getAvatars({ shape: 'circle', size: 'lg', ring: true })}
+ avatars={getAvatars({ shape: 'circle', size: 'lg', ring: true }).slice(
+ 0,
+ 5,
+ )}
maxVisible={5}
overlap="left"
overlapOffset="4px"
/>
),
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
-
- await expect(await canvas.findByText('S')).toBeVisible();
- await expect(canvas.getByText('L')).toBeVisible();
- await expect(canvas.getAllByText('J')).toHaveLength(2);
- },
};
export const Catalog: Story = {
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroupIdentityExample.tsx b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroupIdentityExample.tsx
new file mode 100644
index 00000000000..b1909b7d08f
--- /dev/null
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroupIdentityExample.tsx
@@ -0,0 +1,43 @@
+import { useState } from 'react';
+
+import { AvatarGroup } from '../AvatarGroup';
+import { AvatarGroupStatefulAvatar } from './AvatarGroupStatefulAvatar';
+
+export const AvatarGroupIdentityExample = () => {
+ const [names, setNames] = useState(['Matthew', 'Sophie', 'Jane']);
+ const [maxVisible, setMaxVisible] = useState(3);
+ const [total, setTotal] = useState<number>();
+
+ return (
+ <AvatarGroup
+ aria-label="Team members"
+ role="group"
+ avatars={names.map((name) => (
+ <AvatarGroupStatefulAvatar key={name} name={name} />
+ ))}
+ maxVisible={maxVisible}
+ total={total}
+ overlapOffset="0px"
+ onKeyDown={(event) => {
+ if (event.key === 'r') {
+ setNames((currentNames) => [
+ ...currentNames.slice(1),
+ ...currentNames.slice(0, 1),
+ ]);
+ return;
+ }
+
+ if (event.key === 'l') {
+ setMaxVisible((currentMaxVisible) =>
+ currentMaxVisible === 3 ? 2 : 3,
+ );
+ return;
+ }
+
+ if (event.key === 't') {
+ setTotal((currentTotal) => (currentTotal === 20 ? undefined : 20));
+ }
+ }}
+ />
+ );
+};
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroupStatefulAvatar.tsx b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroupStatefulAvatar.tsx
new file mode 100644
index 00000000000..4e74d929b7d
--- /dev/null
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/__stories__/AvatarGroupStatefulAvatar.tsx
@@ -0,0 +1,19 @@
+import { useState } from 'react';
+
+import { Avatar } from '@ui/primitives/data-display/Avatar/Avatar';
+import { Button } from '@ui/primitives/input/Button/Button';
+
+export const AvatarGroupStatefulAvatar = ({ name }: { name: string }) => {
+ const [selectionCount, setSelectionCount] = useState(0);
+
+ return (
+ <Button
+ aria-label={`${name} selected ${selectionCount} times`}
+ onClick={() => setSelectionCount((count) => count + 1)}
+ startIcon={<Avatar name={name} size="sm" />}
+ size="sm"
+ >
+ {selectionCount}
+ </Button>
+ );
+};
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/__tests__/AvatarGroup.test.tsx b/packages/twenty-ui/src/components/data-display/AvatarGroup/__tests__/AvatarGroup.test.tsx
new file mode 100644
index 00000000000..3b9a1bd2ea7
--- /dev/null
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/__tests__/AvatarGroup.test.tsx
@@ -0,0 +1,142 @@
+import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AvatarGroup } from '../AvatarGroup';
+
+const avatars = [
+ 'Alice',
+ 'Bob',
+ 'Carla',
+ 'Dylan',
+ 'Emma',
+ 'Finn',
+ 'Grace',
+ 'Hugo',
+].map((name) => <span key={name} role="img" aria-label={name} />);
+
+runComponentConformance({
+ name: 'AvatarGroup',
+ element: <AvatarGroup avatars={avatars} />,
+ refInstanceOf: HTMLDivElement,
+});
+
+describe('AvatarGroup overflow', () => {
+ it('shows three supplied avatars plus an additional indicator for the five hidden avatars', () => {
+ render(<AvatarGroup avatars={avatars} maxVisible={3} />);
+
+ expect(screen.getAllByRole('img')).toHaveLength(3);
+ expect(screen.getByRole('img', { name: 'Carla' })).toBeInTheDocument();
+ expect(screen.queryByRole('img', { name: 'Dylan' })).toBeNull();
+ expect(screen.getByText('+5')).toBeInTheDocument();
+ });
+
+ it('includes unloaded avatars in the hidden count', () => {
+ render(<AvatarGroup avatars={avatars.slice(0, 3)} total={20} />);
+
+ expect(screen.getAllByRole('img')).toHaveLength(3);
+ expect(screen.getByText('+17')).toBeInTheDocument();
+ });
+
+ it('passes updated totals and limits to the custom overflow renderer', () => {
+ const renderOverflow = vi.fn((hiddenCount: number) => (
+ <span>{hiddenCount} more people</span>
+ ));
+ const { rerender } = render(
+ <AvatarGroup
+ avatars={avatars}
+ maxVisible={3}
+ renderOverflow={renderOverflow}
+ />,
+ );
+
+ expect(screen.getByText('5 more people')).toBeInTheDocument();
+ expect(screen.queryByText('+5')).toBeNull();
+ expect(renderOverflow).toHaveBeenLastCalledWith(5);
+
+ rerender(
+ <AvatarGroup
+ avatars={avatars.slice(0, 3)}
+ maxVisible={2}
+ total={20}
+ renderOverflow={renderOverflow}
+ />,
+ );
+
+ expect(screen.getByText('18 more people')).toBeInTheDocument();
+ expect(renderOverflow).toHaveBeenLastCalledWith(18);
+ });
+
+ it('ignores empty child slots when counting and applying the visible limit', () => {
+ render(
+ <AvatarGroup
+ avatars={[null, avatars[0], false, avatars[1]]}
+ maxVisible={1}
+ />,
+ );
+
+ expect(screen.getByRole('img', { name: 'Alice' })).toBeInTheDocument();
+ expect(screen.queryByRole('img', { name: 'Bob' })).toBeNull();
+ expect(screen.getByText('+1')).toBeInTheDocument();
+ });
+
+ it('does not invoke custom overflow rendering when every avatar is visible', () => {
+ const renderOverflow = vi.fn(() => <span>More people</span>);
+
+ render(
+ <AvatarGroup
+ avatars={avatars}
+ maxVisible={Infinity}
+ renderOverflow={renderOverflow}
+ />,
+ );
+
+ expect(screen.getAllByRole('img')).toHaveLength(8);
+ expect(renderOverflow).not.toHaveBeenCalled();
+ });
+
+ it('omits the entire custom overflow slot when the renderer returns null', () => {
+ render(
+ <AvatarGroup
+ avatars={avatars}
+ maxVisible={1}
+ renderOverflow={() => null}
+ data-testid="group"
+ />,
+ );
+
+ expect(screen.getByTestId('group').children).toHaveLength(1);
+ expect(screen.queryByText('+7')).toBeNull();
+ });
+
+ it('keeps an empty collection absent until a total supplies hidden avatars', () => {
+ const { rerender } = render(
+ <AvatarGroup avatars={[]} data-testid="group" />,
+ );
+
+ expect(screen.queryByTestId('group')).toBeNull();
+
+ rerender(<AvatarGroup avatars={[]} total={20} data-testid="group" />);
+
+ expect(screen.getByTestId('group')).toHaveTextContent('+20');
+ });
+
+ it.each([
+ { maxVisible: 0, total: 20, visible: 0, hidden: 20 },
+ { maxVisible: -1, total: -2, visible: 0, hidden: 8 },
+ { maxVisible: 2.9, total: 20.9, visible: 2, hidden: 18 },
+ { maxVisible: 3, total: 2, visible: 3, hidden: 5 },
+ { maxVisible: NaN, total: NaN, visible: 0, hidden: 8 },
+ { maxVisible: 3, total: Infinity, visible: 3, hidden: 5 },
+ ])(
+ 'keeps counts predictable for maxVisible=$maxVisible and total=$total',
+ ({ maxVisible, total, visible, hidden }) => {
+ render(
+ <AvatarGroup avatars={avatars} maxVisible={maxVisible} total={total} />,
+ );
+
+ expect(screen.queryAllByRole('img')).toHaveLength(visible);
+ expect(screen.getByText(`+${hidden}`)).toBeInTheDocument();
+ },
+ );
+});
diff --git a/packages/twenty-ui/src/components/data-display/AvatarGroup/types/AvatarGroupProps.ts b/packages/twenty-ui/src/components/data-display/AvatarGroup/types/AvatarGroupProps.ts
index 270d6ebd2ef..184a4448eda 100644
--- a/packages/twenty-ui/src/components/data-display/AvatarGroup/types/AvatarGroupProps.ts
+++ b/packages/twenty-ui/src/components/data-display/AvatarGroup/types/AvatarGroupProps.ts
@@ -1,13 +1,16 @@
+import { type useRender } from '@base-ui/react/use-render';
import { type ReactNode } from 'react';
import { type AvatarShape } from '@ui/primitives/data-display/Avatar/types/AvatarShape';
-export type AvatarGroupProps = {
+export type AvatarGroupProps = Omit<
+ useRender.ComponentProps<'div'>,
+ 'children'
+> & {
avatars: ReactNode[];
- className?: string;
maxVisible?: number;
- overflowAvatar?: ReactNode;
- overflowCount?: number;
+ total?: number;
+ renderOverflow?: (hiddenCount: number) => ReactNode;
overflowShape?: AvatarShape;
overlap?: 'left' | 'right';
overlapOffset?: string;