An open source design system that's fully customizable and agent ready
TypeScript
add XDSAvatar (#18)
Cindy Zhang8336411edb99
diff --git a/apps/storybook/stories/Avatar.stories.tsx b/apps/storybook/stories/Avatar.stories.tsxnew file mode 100644index 0000000000..880f638bf6--- /dev/null+++ b/apps/storybook/stories/Avatar.stories.tsx@@ -0,0 +1,259 @@+import type { Meta, StoryObj } from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import { XDSAvatar } from '@xds/core/Avatar';+import { color, spacing, typography } from '@xds/core/theme/tokens.stylex';++const styles = stylex.create({+ storyWrapper: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacing.space6,+ },+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: spacing.space4,+ },+ heading: {+ margin: `0 0 ${spacing.space2} 0`,+ fontFamily: typography.fontFamilyBody,+ },+ statusDot: {+ width: 10,+ height: 10,+ borderRadius: '50%',+ backgroundColor: color.positive,+ borderWidth: 2,+ borderStyle: 'solid',+ borderColor: color.surface,+ },+ statusDotOffline: {+ backgroundColor: color.textSecondary,+ },+ statusDotBusy: {+ backgroundColor: color.negative,+ },+});++// Simple status indicator component for demos+const StatusDot = ({ status = 'online' }: { status?: 'online' | 'offline' | 'busy' }) => (+ <div+ {...stylex.props(+ styles.statusDot,+ status === 'offline' && styles.statusDotOffline,+ status === 'busy' && styles.statusDotBusy+ )}+ />+);++const meta: Meta<typeof XDSAvatar> = {+ title: 'Components/XDSAvatar',+ component: XDSAvatar,+ tags: ['autodocs'],+ argTypes: {+ size: {+ control: 'select',+ options: ['tiny', 'xsmall', 'small', 'medium', 'large', 16, 20, 24, 32, 36, 40, 48, 60, 64, 72, 96, 128, 144, 180],+ description: 'Size of the avatar',+ },+ src: {+ control: 'text',+ description: 'Primary image source URL',+ },+ fallbackSrc: {+ control: 'text',+ description: 'Fallback image when primary fails',+ },+ name: {+ control: 'text',+ description: 'User name for initials and alt text',+ },+ alt: {+ control: 'text',+ description: 'Alt text (falls back to name)',+ },+ status: {+ control: 'boolean',+ description: 'Show status indicator dot',+ mapping: {+ true: <StatusDot />,+ false: undefined,+ },+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSAvatar>;++export const Default: Story = {+ args: {+ name: 'John Doe',+ size: 'medium',+ },+};++export const WithImage: Story = {+ args: {+ src: 'https://i.pravatar.cc/150?img=1',+ name: 'Jane Smith',+ size: 'medium',+ },+};++export const AllSizes: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>Named Sizes</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar name="TY" size="tiny" />+ <XDSAvatar name="XS" size="xsmall" />+ <XDSAvatar name="SM" size="small" />+ <XDSAvatar name="MD" size="medium" />+ <XDSAvatar name="LG" size="large" />+ </div>+ </div>+ ),+};++export const WithImages: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>With Images (Different Sizes)</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar src="https://i.pravatar.cc/150?img=1" name="User 1" size="tiny" />+ <XDSAvatar src="https://i.pravatar.cc/150?img=2" name="User 2" size="xsmall" />+ <XDSAvatar src="https://i.pravatar.cc/150?img=3" name="User 3" size="small" />+ <XDSAvatar src="https://i.pravatar.cc/150?img=4" name="User 4" size="medium" />+ <XDSAvatar src="https://i.pravatar.cc/150?img=5" name="User 5" size="large" />+ </div>+ </div>+ ),+};++export const InitialsFallback: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>Initials Fallback</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar name="John Doe" size="medium" />+ <XDSAvatar name="Alice" size="medium" />+ <XDSAvatar name="Bob Smith Johnson" size="medium" />+ <XDSAvatar name="Dr. Sarah Connor" size="medium" />+ </div>+ </div>+ ),+};++export const NoImageNoName: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>Default Icon (No Image or Name)</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar size="tiny" />+ <XDSAvatar size="xsmall" />+ <XDSAvatar size="small" />+ <XDSAvatar size="medium" />+ <XDSAvatar size="large" />+ </div>+ </div>+ ),+};++export const FallbackChain: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>Fallback Chain Demo</h4>+ <div {...stylex.props(styles.row)}>+ <div>+ <p {...stylex.props(styles.heading)}>Valid src</p>+ <XDSAvatar src="https://i.pravatar.cc/150?img=10" name="Test User" size="large" />+ </div>+ <div>+ <p {...stylex.props(styles.heading)}>Invalid src, valid fallbackSrc</p>+ <XDSAvatar+ src="https://invalid-url.example/broken.jpg"+ fallbackSrc="https://i.pravatar.cc/150?img=11"+ name="Test User"+ size="large"+ />+ </div>+ <div>+ <p {...stylex.props(styles.heading)}>Both invalid, has name</p>+ <XDSAvatar+ src="https://invalid-url.example/broken.jpg"+ fallbackSrc="https://also-invalid.example/broken.jpg"+ name="Test User"+ size="large"+ />+ </div>+ <div>+ <p {...stylex.props(styles.heading)}>All invalid, no name</p>+ <XDSAvatar+ src="https://invalid-url.example/broken.jpg"+ size="large"+ />+ </div>+ </div>+ </div>+ ),+};++export const WithStatus: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>With Status Indicators</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar+ src="https://i.pravatar.cc/150?img=20"+ name="Online User"+ size="large"+ status={<StatusDot status="online" />}+ />+ <XDSAvatar+ src="https://i.pravatar.cc/150?img=21"+ name="Offline User"+ size="large"+ status={<StatusDot status="offline" />}+ />+ <XDSAvatar+ src="https://i.pravatar.cc/150?img=22"+ name="Busy User"+ size="large"+ status={<StatusDot status="busy" />}+ />+ </div>+ </div>+ ),+};++export const StatusWithSizes: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>Status with Different Sizes</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar name="AB" size="small" status={<StatusDot />} />+ <XDSAvatar name="CD" size="medium" status={<StatusDot />} />+ <XDSAvatar name="EF" size="large" status={<StatusDot />} />+ <XDSAvatar name="GH" size={72} status={<StatusDot />} />+ </div>+ </div>+ ),+};++export const NumericSizes: Story = {+ render: () => (+ <div {...stylex.props(styles.storyWrapper)}>+ <h4 {...stylex.props(styles.heading)}>Numeric Pixel Sizes</h4>+ <div {...stylex.props(styles.row)}>+ <XDSAvatar name="16" size={16} />+ <XDSAvatar name="24" size={24} />+ <XDSAvatar name="36" size={36} />+ <XDSAvatar name="48" size={48} />+ <XDSAvatar name="72" size={72} />+ <XDSAvatar name="96" size={96} />+ <XDSAvatar name="128" size={128} />+ </div>+ </div>+ ),+};diff --git a/packages/core/package.json b/packages/core/package.jsonindex 6d707f78ac..1536f5cf70 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -17,6 +17,11 @@"import": "./dist/index.mjs","require": "./dist/index.js"},+ "./Avatar": {+ "types": "./dist/Avatar/index.d.ts",+ "import": "./dist/Avatar/index.mjs",+ "require": "./dist/Avatar/index.js"+ },"./Button": {"types": "./dist/Button/index.d.ts","import": "./dist/Button/index.mjs",diff --git a/packages/core/src/Avatar/README.md b/packages/core/src/Avatar/README.mdnew file mode 100644index 0000000000..f639315976--- /dev/null+++ b/packages/core/src/Avatar/README.md@@ -0,0 +1,68 @@+# /packages/core/src/Avatar++Avatar component for displaying user profile pictures with fallback support.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Image loading**: Primary and fallback image sources+- **Initials fallback**: Auto-generates initials from user name+- **Default icon**: Generic person icon when no image or name provided+- **Sizes**: xsmall (24px), small (32px), medium (40px), large (56px), xlarge (80px)+- **Status slot**: Corner position for status indicators or badges+- **Accessible**: Proper role and aria-label support++## Usage++```tsx+import { XDSAvatar } from '@xds/core/Avatar';++// With image+<XDSAvatar src="/user.jpg" name="John Doe" />++// Initials fallback+<XDSAvatar name="Jane Smith" size="large" />++// With status indicator+<XDSAvatar src="/user.jpg" status={<OnlineIndicator />} />++// Different sizes+<XDSAvatar name="AB" size="xsmall" />+<XDSAvatar name="CD" size="medium" />+<XDSAvatar name="EF" size="xlarge" />+```++## Props++| Prop | Type | Default | Description |+|------|------|---------|-------------|+| `src` | `string` | — | Primary image source URL |+| `fallbackSrc` | `string` | — | Fallback image when primary fails |+| `name` | `string` | — | User name for initials and alt text |+| `alt` | `string` | — | Alt text (falls back to `name`) |+| `size` | `'xsmall' \| 'small' \| 'medium' \| 'large' \| 'xlarge'` | `'small'` | Avatar size |+| `status` | `ReactNode` | — | Corner content for status indicators |+| `data-testid` | `string` | — | Test ID for testing |++## Fallback Cascade++1. `src` loads → show image+2. `src` fails → try `fallbackSrc`+3. `fallbackSrc` fails/missing → show initials from `name`+4. No `name` → show generic person icon++## Files++| File | Role | Purpose |+|------|------|---------|+| `index.ts` | Entry | Exports component and types |+| `XDSAvatar.tsx` | Core | Component implementation |+| `XDSAvatar.test.tsx` | Test | Unit tests |++## Implementation Notes++- Always circular shape (border-radius: 50%)+- Size type derived from `keyof typeof sizes`+- Uses `color.deemphasized` and `color.textSecondary` for fallback background+- Initials extracted from first and last word of namediff --git a/packages/core/src/Avatar/XDSAvatar.tsx b/packages/core/src/Avatar/XDSAvatar.tsxnew file mode 100644index 0000000000..5a3b2c6cf8--- /dev/null+++ b/packages/core/src/Avatar/XDSAvatar.tsx@@ -0,0 +1,315 @@+/**+ * @file XDSAvatar.tsx+ * @input Uses React forwardRef, HTMLAttributes, ReactNode, useState+ * @output Exports XDSAvatar component, XDSAvatarProps, XDSAvatarSize types+ * @position Core implementation; consumed by index.ts+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/Avatar/README.md (props table, features, implementation notes)+ * - /packages/core/src/Avatar/XDSAvatar.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/Avatar/index.ts (exports if types change)+ * - /apps/storybook/stories/Avatar.stories.tsx (storybook stories)+ */++import { forwardRef, useState, type HTMLAttributes, type ReactNode } from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ color,+ spacing,+ radius,+ typography,+} from '../theme/tokens.stylex';++/**+ * The offset ratio for positioning elements on a circle's edge at 45°.+ *+ * For a square with side length S containing an inscribed circle of diameter S,+ * a diagonal line from corner to corner intersects the circle at:+ * x = S/2 × (1 ± 1/√2)+ *+ * The distance from the corner to this intersection point (along each axis) is:+ * S/2 × (1 - 1/√2) ≈ 0.146S+ *+ * This constant represents that ratio: (1 - 1/√2) / 2 ≈ 0.146+ */+const CIRCLE_EDGE_OFFSET_RATIO = (1 - 1 / Math.SQRT2) / 2;++/**+ * The ratio of font size to avatar size for initials.+ *+ * At 40%, two-letter initials fit comfortably within the circle with adequate+ * padding. This ratio provides good legibility across all avatar sizes:+ * - 24px avatar → 9.6px font+ * - 48px avatar → 19.2px font+ * - 128px avatar → 51.2px font+ */+const INITIALS_FONT_SIZE_RATIO = 0.4;++/**+ * Named size options+ */+type XDSAvatarNamedSize = 'tiny' | 'xsmall' | 'small' | 'medium' | 'large';++/**+ * Numeric size options (in pixels)+ */+type XDSAvatarNumericSize =+ | 16+ | 20+ | 24+ | 32+ | 36+ | 40+ | 48+ | 60+ | 64+ | 72+ | 96+ | 128+ | 144+ | 180;++/**+ * Avatar size - can be a named size or a specific pixel value+ */+export type XDSAvatarSize = XDSAvatarNamedSize | XDSAvatarNumericSize;++/**+ * Resolves named sizes to their numeric pixel values+ */+function resolveSize(size: XDSAvatarSize): number {+ if (typeof size === 'number') {+ return size;+ }+ switch (size) {+ case 'tiny':+ return 20;+ case 'xsmall':+ return 24;+ case 'small':+ return 36;+ case 'medium':+ return 48;+ case 'large':+ return 128;+ }+}++/**+ * Base styles for the avatar+ * Uses a wrapper/content structure so status isn't clipped by overflow:hidden+ */+const styles = stylex.create({+ wrapper: {+ position: 'relative',+ display: 'inline-flex',+ flexShrink: 0,+ },+ content: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: '50%',+ overflow: 'hidden',+ userSelect: 'none',+ },+ image: {+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ },+ fallback: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '100%',+ height: '100%',+ backgroundColor: color.deemphasized,+ color: color.textSecondary,+ fontFamily: typography.fontFamilyBody,+ fontWeight: 500,+ textTransform: 'uppercase',+ },+ status: {+ position: 'absolute',+ },+});++/**+ * Dynamic styles that depend on the avatar size+ */+const dynamicStyles = stylex.create({+ size: (size: number) => ({+ width: size,+ height: size,+ }),+ fontSize: (size: number) => ({+ fontSize: size * INITIALS_FONT_SIZE_RATIO,+ }),+ statusPosition: (size: number) => ({+ bottom: size * CIRCLE_EDGE_OFFSET_RATIO,+ right: size * CIRCLE_EDGE_OFFSET_RATIO,+ // Shift by half the element's size to center it on the circle edge+ transform: 'translate(50%, 50%)',+ }),+});++export interface XDSAvatarProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {+ /**+ * The alt text shown on hover and made accessible to screen readers.+ * Falls back to `name` if not provided.+ */+ alt?: string;+ /**+ * testid for tests.+ */+ 'data-testid'?: string;+ /**+ * Fallback image source when primary `src` fails to load.+ * If this also fails, shows initials derived from `name`.+ */+ fallbackSrc?: string;+ /**+ * The user's name. Used for:+ * - Generating initials when no image is available+ * - Default alt text if `alt` is not provided+ */+ name?: string;+ /**+ * The size of the avatar.+ * @default 'small'+ */+ size?: XDSAvatarSize;+ /**+ * The primary image source for the avatar.+ */+ src?: string;+ /**+ * Content displayed in the corner of the avatar.+ * Typically used for status indicators or badges.+ */+ status?: ReactNode;+}++/**+ * Generates initials from a name string.+ * Takes the first letter of the first two words.+ * @example getInitials('John Doe') // 'JD'+ * @example getInitials('Alice') // 'A'+ */+function getInitials(name: string): string {+ const words = name.trim().split(/\s+/);+ if (words.length === 0) return '';+ if (words.length === 1) return words[0].charAt(0).toUpperCase();+ return (words[0].charAt(0) + words[words.length - 1].charAt(0)).toUpperCase();+}++/**+ * Default person icon SVG for when no image or name is provided+ */+function DefaultIcon({ size }: { size: number }) {+ return (+ <svg+ width={size * 0.6}+ height={size * 0.6}+ viewBox="0 0 24 24"+ fill="currentColor"+ aria-hidden="true"+ >+ <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />+ </svg>+ );+}++/**+ * Avatar component for displaying user profile pictures.+ *+ * Displays an image when available, falling back to initials derived from+ * the name prop, or a generic person icon if neither is provided.+ *+ * @example+ * ```tsx+ * <XDSAvatar src="/user.jpg" name="John Doe" />+ * <XDSAvatar name="Jane Smith" size="large" />+ * <XDSAvatar src="/user.jpg" status={<OnlineIndicator />} />+ * ```+ */+export const XDSAvatar = forwardRef<HTMLDivElement, XDSAvatarProps>(+ (+ {+ alt,+ 'data-testid': testId,+ fallbackSrc,+ name,+ size = 'small',+ src,+ status,+ ...props+ },+ ref+ ) => {+ const [imageError, setImageError] = useState(false);+ const [fallbackError, setFallbackError] = useState(false);++ const showImage = src && !imageError;+ const showFallbackImage = !showImage && fallbackSrc && !fallbackError;+ const showInitials = !showImage && !showFallbackImage && name;+ const showIcon = !showImage && !showFallbackImage && !name;++ const accessibleName = alt || name || 'Avatar';+ const numericSize = resolveSize(size);++ return (+ <div+ ref={ref}+ role="img"+ aria-label={accessibleName}+ data-testid={testId}+ {...stylex.props(styles.wrapper)}+ {...props}+ >+ <div+ {...stylex.props(styles.content, dynamicStyles.size(numericSize))}+ >+ {showImage && (+ <img+ src={src}+ alt={accessibleName}+ onError={() => setImageError(true)}+ {...stylex.props(styles.image)}+ />+ )}+ {showFallbackImage && (+ <img+ src={fallbackSrc}+ alt={accessibleName}+ onError={() => setFallbackError(true)}+ {...stylex.props(styles.image)}+ />+ )}+ {showInitials && (+ <div+ {...stylex.props(styles.fallback, dynamicStyles.fontSize(numericSize))}+ >+ {getInitials(name)}+ </div>+ )}+ {showIcon && (+ <div {...stylex.props(styles.fallback)}>+ <DefaultIcon size={numericSize} />+ </div>+ )}+ </div>+ {status && (+ <div+ {...stylex.props(styles.status, dynamicStyles.statusPosition(numericSize))}+ >+ {status}+ </div>+ )}+ </div>+ );+ }+);++XDSAvatar.displayName = 'XDSAvatar';diff --git a/packages/core/src/Avatar/index.ts b/packages/core/src/Avatar/index.tsnew file mode 100644index 0000000000..437d90862c--- /dev/null+++ b/packages/core/src/Avatar/index.ts@@ -0,0 +1,11 @@+/**+ * @file index.ts+ * @input Imports XDSAvatar component and types from XDSAvatar.tsx+ * @output Exports XDSAvatar, XDSAvatarProps, XDSAvatarSize+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/Avatar/README.md+ */++export { XDSAvatar } from './XDSAvatar';+export type { XDSAvatarProps, XDSAvatarSize } from './XDSAvatar';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex e4bcf2ce80..0185b7bc29 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -8,6 +8,7 @@*/// Components+export * from './Avatar';export * from './Button';export * from './TextInput';diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.tsindex 2ae26956ba..5817a92ba8 100644--- a/packages/core/tsup.config.ts+++ b/packages/core/tsup.config.ts@@ -11,7 +11,7 @@ import { defineConfig } from 'tsup';import babel from 'esbuild-plugin-babel';export default defineConfig({- entry: ['src/index.ts', 'src/Button/index.ts', 'src/Layout/index.ts', 'src/TextInput/index.ts'],+ entry: ['src/index.ts', 'src/Avatar/index.ts', 'src/Button/index.ts', 'src/Layout/index.ts', 'src/TextInput/index.ts'],format: ['cjs', 'esm'],dts: true,splitting: true,