Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mosaic-avatar-group.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/mosaic': minor
---

Add `AvatarGroup`, which stacks avatars in an overlapping row with an optional "+N" count of the ones left out. Each avatar is cut where the next one overlaps it, so whatever sits behind the group shows through the gap. `AvatarGroup.Root` sets the default `size` and `shape` (`circle` or `square`) of the avatars inside it; an avatar's own prop still wins. `AvatarGroup.Overflow` takes a `count`, renders nothing when it is 0 or less, and can be made a button with `render`.
5 changes: 5 additions & 0 deletions packages/mosaic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@
"import": "./dist/components/avatar.js",
"default": "./dist/components/avatar.js"
},
"./components/avatar-group": {
"types": "./dist/components/avatar-group.d.ts",
"import": "./dist/components/avatar-group.js",
"default": "./dist/components/avatar-group.js"
},
"./components/badge": {
"types": "./dist/components/badge.d.ts",
"import": "./dist/components/badge.js",
Expand Down
68 changes: 68 additions & 0 deletions packages/mosaic/src/components/avatar-group/avatar-group.doc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { ComponentDoc } from '../../docs-schema';
import type { AvatarGroupOverflowProps, AvatarGroupProps } from './avatar-group';

export default {
name: 'AvatarGroup',
description:
'Stacks avatars in an overlapping row, cutting each one where the next overlaps it so the background shows through, with an optional count of the rest.',
useFor: ['a row of member or collaborator avatars', 'a facepile with a "+N" count of the rest'],
keywords: ['avatar group', 'facepile', 'avatar stack', 'members', 'overflow', 'more'],
practices: [
{
do: true,
text: 'Slice the list yourself and pass only the avatars to show, then `AvatarGroup.Overflow` with the rest.',
},
{ do: true, text: 'Name the group with `aria-label`, such as "Members".' },
{
do: false,
text: 'Set `size` on the avatars inside. The group sets it as the default, and an avatar of another size breaks the overlap.',
},
{ do: false, text: 'Nest one `AvatarGroup.Root` inside another.' },
],
parts: {
'AvatarGroup.Root': {
description: 'Lays the avatars out in an overlapping row and sets their default size and shape.',
slot: 'cl-avatar-group',
props: {
shape: {
type: "'circle' | 'square'",
doc: 'Default shape of the avatars inside, and the shape of the overflow.',
default: "'circle'",
},
size: {
type: "'xs' | 'sm' | 'md' | 'lg'",
doc: 'Default size of the avatars inside, and the size of the overflow.',
default: "'md'",
},
},
},
'AvatarGroup.Overflow': {
description:
'Shows "+N" for the avatars left out, named "N more". Renders nothing when `count` is 0 or less. Use `render` to make it a button.',
slot: 'cl-avatar-group-overflow',
props: {
count: { type: 'number', doc: 'How many avatars are not shown.' },
label: { type: 'string', doc: 'The accessible name, with `{count}` filled in.', default: "'{count} more'" },
},
},
},
examples: [
{
title: 'Members with an overflow count',
code: `
<AvatarGroup.Root aria-label='Members' size='sm'>
{members.slice(0, 3).map(member => (
<Avatar.Root key={member.id}>
<Avatar.Image src={member.imageUrl} alt={member.name} />
<Avatar.Fallback />
</Avatar.Root>
))}
<AvatarGroup.Overflow count={members.length - 3} />
</AvatarGroup.Root>
`,
},
],
} satisfies ComponentDoc<{
'AvatarGroup.Root': AvatarGroupProps;
'AvatarGroup.Overflow': AvatarGroupOverflowProps;
}>;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { AvatarGroupRoot as Root, AvatarGroupOverflow as Overflow } from './avatar-group';
108 changes: 108 additions & 0 deletions packages/mosaic/src/components/avatar-group/avatar-group.styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import * as stylex from '@stylexjs/stylex';

import { colorVars, fontFamilyVars, fontWeightVars, space } from '../../tokens.stylex';

const size = 'var(--_cl-avatar-group-size)';
const overlap = 'var(--_cl-avatar-group-overlap)';
const gap = 'var(--_cl-avatar-group-gap)';
const radius = 'var(--_cl-avatar-group-radius)';

const cutoutRadius = `(${radius} + ${gap})`;
const cutoutDiameter = `calc(2 * ${cutoutRadius})`;
const cutoutStart = `calc(${size} - ${overlap} - ${gap})`;
const cutoutTop = `calc(-1 * ${gap})`;
const cutoutBottomCorner = `calc(${size} + ${gap} - 2 * ${cutoutRadius})`;
const cutoutColumn = `calc(${cutoutStart} + ${cutoutRadius})`;

const disc = 'radial-gradient(closest-side, #000 calc(100% - 0.5px), transparent)';
const fill = 'linear-gradient(#000 0 0)';

const ltrPosition = `left 0px top 0px, left ${cutoutStart} top ${cutoutTop}, left ${cutoutStart} top ${cutoutBottomCorner}, left ${cutoutColumn} top ${cutoutTop}, left ${cutoutStart} top ${radius}`;
const ltrCenter = `left ${cutoutColumn} top 50%`;
const rtlCenter = `right ${cutoutColumn} top 50%`;
const rtlPosition = `right 0px top 0px, right ${cutoutStart} top ${cutoutTop}, right ${cutoutStart} top ${cutoutBottomCorner}, right ${cutoutColumn} top ${cutoutTop}, right ${cutoutStart} top ${radius}`;

const shapeSupport = '@supports (clip-path: shape(from 0 0, line to 0 0))' as const;

const cutoutBottom = `calc(100% + ${gap})`;
const cutoutCornerTop = `calc(${cutoutTop} + ${cutoutRadius})`;
const cutoutCornerBottom = `calc(${cutoutBottom} - ${cutoutRadius})`;
const cutoutArc = `calc(${cutoutRadius})`;
const outerShape = 'shape(evenodd from 0 0, hline to 100%, vline to 100%, hline to 0, close';
const ltrShape = `${outerShape}, move to ${cutoutBottom} ${cutoutTop}, hline to ${cutoutColumn}, arc to ${cutoutStart} ${cutoutCornerTop} of ${cutoutArc} ccw, vline to ${cutoutCornerBottom}, arc to ${cutoutColumn} ${cutoutBottom} of ${cutoutArc} ccw, hline to ${cutoutBottom}, close)`;
const rtlShape = `${outerShape}, move to ${cutoutTop} ${cutoutTop}, hline to calc(100% - ${cutoutColumn}), arc to calc(100% - ${cutoutStart}) ${cutoutCornerTop} of ${cutoutArc} cw, vline to ${cutoutCornerBottom}, arc to calc(100% - ${cutoutColumn}) ${cutoutBottom} of ${cutoutArc} cw, hline to ${cutoutTop}, close)`;

export const styles = stylex.create({
root: {
'--_cl-avatar-group-gap': '2px',
'--_cl-avatar-group-overlap': `calc(${size} * 0.25)`,
alignItems: 'center',
display: 'inline-flex',
verticalAlign: 'middle',
},

item: {
'--_cl-avatar-group-cutout-center': { default: ltrCenter, ':is([dir="rtl"] *)': rtlCenter },
'--_cl-avatar-group-mask-position': { default: ltrPosition, ':is([dir="rtl"] *)': rtlPosition },
marginInlineStart: { default: `calc(-1 * ${overlap})`, ':first-child': 0 },
},

overflow: {
paddingInline: space['1.5'],
alignItems: 'center',
backgroundColor: colorVars['--cl-color-surface'],
backgroundImage: `linear-gradient(${colorVars['--cl-color-neutral-alpha-200']}, ${colorVars['--cl-color-neutral-alpha-200']})`,
boxSizing: 'border-box',
color: colorVars['--cl-color-foreground-secondary'],
display: 'inline-flex',
flexShrink: 0,
fontFamily: fontFamilyVars['--cl-font-family-sans'],
fontVariantNumeric: 'tabular-nums',
fontWeight: fontWeightVars['--cl-font-medium'],
justifyContent: 'center',
lineHeight: 1,
position: 'relative',
userSelect: 'none',
whiteSpace: 'nowrap',
minWidth: size,
width: 'auto',
},
});

export const sizes = stylex.create({
xs: { '--_cl-avatar-group-size': space['6'] },
sm: { '--_cl-avatar-group-size': space['8'] },
md: { '--_cl-avatar-group-size': space['10'] },
lg: { '--_cl-avatar-group-size': space['12'] },
});

export const itemShapes = stylex.create({
circle: {
'--_cl-avatar-group-radius': `calc(${size} / 2)`,
maskImage: {
default: null,
':not(:last-child)': `radial-gradient(circle at var(--_cl-avatar-group-cutout-center), transparent calc(${cutoutRadius} - 0.5px), #000 calc(${cutoutRadius}))`,
},
},
square: {
'--_cl-avatar-group-cutout-shape': { default: ltrShape, ':is([dir="rtl"] *)': rtlShape },
'--_cl-avatar-group-radius': 'var(--_cl-media-radius)',
clipPath: {
default: null,
[shapeSupport]: { default: null, ':not(:last-child)': 'var(--_cl-avatar-group-cutout-shape)' },
},
// eslint-disable-next-line @stylexjs/valid-styles -- the rule only admits a single keyword; a per-layer list is valid CSS and compiles as written.
maskComposite: { default: null, ':not(:last-child)': 'exclude, add, add, add, add' },
maskImage: {
default: null,
[shapeSupport]: { default: null, ':not(:last-child)': 'none' },
':not(:last-child)': `${fill}, ${disc}, ${disc}, ${fill}, ${fill}`,
},
maskPosition: { default: null, ':not(:last-child)': 'var(--_cl-avatar-group-mask-position)' },
maskRepeat: { default: null, ':not(:last-child)': 'no-repeat' },
maskSize: {
default: null,
':not(:last-child)': `100% 100%, ${cutoutDiameter} ${cutoutDiameter}, ${cutoutDiameter} ${cutoutDiameter}, ${size} calc(${size} + 2 * ${gap}), ${size} calc(${size} - 2 * ${radius})`,
},
},
});
146 changes: 146 additions & 0 deletions packages/mosaic/src/components/avatar-group/avatar-group.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { render, screen } from '@testing-library/react';
import React from 'react';
import { describe, expect, it, vi } from 'vitest';

import { Avatar } from '../avatar';
import { AvatarGroup } from '.';

function Member({ size }: { size?: 'xs' | 'lg' }) {
return (
<Avatar.Root
data-testid='member'
size={size}
>
<Avatar.Fallback>AB</Avatar.Fallback>
</Avatar.Root>
);
}

describe('Mosaic AvatarGroup', () => {
it('renders a group that reflects its size and shape', () => {
render(
<AvatarGroup.Root
aria-label='Members'
size='sm'
shape='square'
>
<Member />
</AvatarGroup.Root>,
);
const group = screen.getByRole('group', { name: 'Members' });
expect(group).toHaveClass('cl-avatar-group');
expect(group).toHaveAttribute('data-size', 'sm');
expect(group).toHaveAttribute('data-shape', 'square');
});

it('defaults to medium circles', () => {
render(
<AvatarGroup.Root aria-label='Members'>
<Member />
</AvatarGroup.Root>,
);
const group = screen.getByRole('group', { name: 'Members' });
expect(group).toHaveAttribute('data-size', 'md');
expect(group).toHaveAttribute('data-shape', 'circle');
});

it('sets the default size and shape of every avatar inside it', () => {
render(
<AvatarGroup.Root
size='sm'
shape='square'
>
<Member />
<Member />
</AvatarGroup.Root>,
);
for (const member of screen.getAllByTestId('member')) {
expect(member).toHaveAttribute('data-size', 'sm');
expect(member).toHaveAttribute('data-shape', 'square');
}
});

it('lets an avatar’s own size win over the group default', () => {
render(
<AvatarGroup.Root size='sm'>
<Member size='lg' />
</AvatarGroup.Root>,
);
expect(screen.getByTestId('member')).toHaveAttribute('data-size', 'lg');
});

it('shows the overflow count, named for assistive tech', () => {
render(
<AvatarGroup.Root
size='sm'
shape='square'
>
<Member />
<AvatarGroup.Overflow count={3} />
</AvatarGroup.Root>,
);
const overflow = screen.getByRole('img', { name: '3 more' });
expect(overflow).toHaveTextContent('+3');
expect(overflow).toHaveClass('cl-avatar-group-overflow');
expect(overflow).toHaveAttribute('data-size', 'sm');
expect(overflow).toHaveAttribute('data-shape', 'square');
});

it('takes a label template and custom content for the overflow', () => {
render(
<AvatarGroup.Root>
<AvatarGroup.Overflow
count={12}
label='{count} other members'
>
12+
</AvatarGroup.Overflow>
</AvatarGroup.Root>,
);
expect(screen.getByRole('img', { name: '12 other members' })).toHaveTextContent('12+');
});

it('renders no overflow when nothing is left over', () => {
render(
<AvatarGroup.Root>
<Member />
<AvatarGroup.Overflow count={0} />
</AvatarGroup.Root>,
);
expect(screen.queryByText(/^\+/)).not.toBeInTheDocument();
expect(document.querySelector('.cl-avatar-group-overflow')).toBeNull();
});

it('composes the overflow onto a button', () => {
render(
<AvatarGroup.Root>
<Member />
<AvatarGroup.Overflow
count={5}
render={<button type='button' />}
/>
</AvatarGroup.Root>,
);
const button = screen.getByRole('button', { name: '5 more' });
expect(button).toHaveClass('cl-avatar-group-overflow');
expect(button).toHaveTextContent('+5');
});

it('throws when the overflow is rendered outside <AvatarGroup.Root>', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
expect(() => render(<AvatarGroup.Overflow count={2} />)).toThrow(/must be rendered inside <AvatarGroup.Root>/);
});

it('forwards its ref to the group element', () => {
const ref = React.createRef<HTMLDivElement>();
render(
<AvatarGroup.Root
ref={ref}
aria-label='Members'
>
<Member />
</AvatarGroup.Root>,
);
expect(ref.current).toBe(screen.getByRole('group', { name: 'Members' }));
});
});
Loading
Loading