-
-
-
-
+ parameters: { docs: { description: { story: 'Every colour in the default `soft` variant.' } } },
+ render: (args) => (
+
+ {ALERT_COLORS.map((color) => (
+
+ {MESSAGES[color].body}
+
+ ))}
),
}
-export const Variants: Story = {
- render: () => (
-
- ),
+export const Solid: Story = {
+ args: { variant: 'solid' },
+ render: Colors.render,
}
-export const WithoutCloseButton: Story = {
- render: () => (
-
- ),
+export const Outline: Story = {
+ args: { variant: 'outline' },
+ render: Colors.render,
}
export const TitleOnly: Story = {
- render: () =>
,
-}
-
-/** Auto-closes after 2s; the Remount button brings it back. */
-export const AutoClose: Story = {
render: (args) => (
-
-
-
+
+ {ALERT_VARIANTS.map((variant) => (
+
+ {null}
+
+ ))}
+
),
}
+
+export const WithActions: Story = {
+ render: (args) => (
+
+
+
+ Add payment method
+
+
+ Compare plans
+
+ >
+ }
+ >
+ {MESSAGES.warning.body}
+
+
+ Update card
+
+ }
+ >
+ {MESSAGES.danger.body}
+
+
}
+ dismissible
+ actions={
+
+ Invite teammates
+
+ }
+ >
+ {MESSAGES.primary.body}
+
+
+ ),
+}
+
+export const Dismissible: Story = {
+ args: { dismissible: true, color: 'success', title: MESSAGES.success.title, children: MESSAGES.success.body },
+ render: function Render(args) {
+ const [open, setOpen] = useState(true)
+ return (
+
+
{
+ setOpen(next)
+ args.onOpenChange?.(next)
+ }}
+ />
+ {!open && (
+
+ setOpen(true)}>
+ Show the alert again
+
+
+ )}
+
+ )
+ },
+}
+
+export const AutoClose: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story: 'Closes after 6 seconds. Hover or focus the alert to pause the countdown.',
+ },
+ },
+ },
+ args: {
+ autoClose: 6000,
+ dismissible: true,
+ color: 'neutral',
+ title: MESSAGES.neutral.title,
+ children: MESSAGES.neutral.body,
+ },
+ render: function Render(args) {
+ const [key, setKey] = useState(0)
+ const [open, setOpen] = useState(true)
+ return (
+
+
+ View changes
+
+ }
+ onOpenChange={(next) => {
+ setOpen(next)
+ args.onOpenChange?.(next)
+ }}
+ />
+ {!open && (
+
+ {
+ setKey((k) => k + 1)
+ setOpen(true)
+ }}
+ >
+ Restart
+
+
+ )}
+
+ )
+ },
+}
+
+export const WithoutIcon: Story = {
+ args: { hideIcon: true, color: 'neutral', title: undefined, children: 'You are viewing an archived project. Restore it to make changes.' },
+}
diff --git a/src/components/Alert.test.tsx b/src/components/Alert.test.tsx
new file mode 100644
index 0000000..e3550ba
--- /dev/null
+++ b/src/components/Alert.test.tsx
@@ -0,0 +1,109 @@
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Alert } from './Alert'
+import { ALERT_COLORS, ALERT_VARIANTS } from './alert.tokens'
+
+describe('Alert', () => {
+ afterEach(() => vi.useRealTimers())
+
+ it.each(ALERT_COLORS)('uses the right live-region role for %s', (color) => {
+ render(
Body )
+ const expected = color === 'danger' || color === 'warning' ? 'alert' : 'status'
+ expect(screen.getByRole(expected)).toHaveTextContent('Heads up')
+ expect(screen.queryByRole(expected === 'alert' ? 'status' : 'alert')).toBeNull()
+ })
+
+ it('renders a default icon, a custom icon, or none', () => {
+ const { container, rerender } = render(
Message )
+ expect(container.querySelector('svg')).not.toBeNull()
+ rerender(
}>Message)
+ expect(screen.getByTestId('custom')).toBeInTheDocument()
+ rerender(
Message )
+ expect(container.querySelector('svg')).toBeNull()
+ })
+
+ it('dismisses (uncontrolled) and calls onOpenChange', async () => {
+ const onOpenChange = vi.fn()
+ render(
+
+ Done
+ ,
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
+ expect(onOpenChange).toHaveBeenCalledWith(false)
+ expect(screen.queryByRole('status')).toBeNull()
+ })
+
+ it('stays open when controlled until the parent closes it', async () => {
+ const onOpenChange = vi.fn()
+ const { rerender } = render(
+
+ Done
+ ,
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
+ expect(onOpenChange).toHaveBeenCalledWith(false)
+ expect(screen.getByRole('status')).toBeInTheDocument()
+ rerender(
+
+ Done
+ ,
+ )
+ expect(screen.queryByRole('status')).toBeNull()
+ })
+
+ it('auto-closes after the delay', () => {
+ vi.useFakeTimers()
+ const onOpenChange = vi.fn()
+ render(
Saved )
+ act(() => vi.advanceTimersByTime(2900))
+ expect(screen.getByRole('status')).toBeInTheDocument()
+ act(() => vi.advanceTimersByTime(200))
+ expect(screen.queryByRole('status')).toBeNull()
+ expect(onOpenChange).toHaveBeenCalledWith(false)
+ })
+
+ it('pauses auto-close while hovered and resumes with the remaining time', () => {
+ vi.useFakeTimers()
+ render(
Saved )
+ const alert = screen.getByRole('status')
+ act(() => vi.advanceTimersByTime(2000))
+ fireEvent.mouseEnter(alert)
+ act(() => vi.advanceTimersByTime(5000))
+ expect(screen.getByRole('status')).toBeInTheDocument()
+ fireEvent.mouseLeave(alert)
+ act(() => vi.advanceTimersByTime(900))
+ expect(screen.getByRole('status')).toBeInTheDocument()
+ act(() => vi.advanceTimersByTime(200))
+ expect(screen.queryByRole('status')).toBeNull()
+ })
+
+ it('pauses auto-close while focus is inside', () => {
+ vi.useFakeTimers()
+ render(
+
+ Saved
+ ,
+ )
+ act(() => screen.getByRole('button', { name: 'Dismiss' }).focus())
+ act(() => vi.advanceTimersByTime(5000))
+ expect(screen.getByRole('status')).toBeInTheDocument()
+ })
+
+ it('has no axe violations in any variant', async () => {
+ const { container } = render(
+
+ {ALERT_VARIANTS.map((variant) =>
+ ALERT_COLORS.map((color) => (
+
Act}>
+ Message
+
+ )),
+ )}
+
,
+ )
+ await expectNoA11yViolations(container)
+ }, 20000)
+})
diff --git a/src/components/Alert.tsx b/src/components/Alert.tsx
index 9397ab8..05ccdae 100644
--- a/src/components/Alert.tsx
+++ b/src/components/Alert.tsx
@@ -1,156 +1,150 @@
+import { useEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react'
+import { CircleAlert, CircleCheck, CircleX, Info, TriangleAlert, X } from 'lucide-react'
+import { cn } from '../lib/cn'
+import { useControllableState } from '../lib/useControllableState'
+import { IconButton } from './Button'
import {
- useCallback,
- useEffect,
- useRef,
- useState,
- forwardRef,
- type HTMLAttributes,
- type ReactNode,
-} from 'react'
-import * as Icons from 'lucide-react'
-import { cn } from '@/lib/cn'
-import {
- ALERT_COLORS,
- ALERT_GRADIENT,
+ ALERT_CLOSE_STYLES,
+ ALERT_ICON_STYLES,
+ ALERT_STYLES,
+ ALERT_URGENT_COLORS,
type AlertColor,
type AlertVariant,
} from './alert.tokens'
-/**
- * Dismissible inline alert.
- *
- * Ported from the original `Alert` component.
- *
- * `iconName` takes a Lucide icon name as a string (looked up on the module), so
- * the icon is controllable from Storybook without importing every icon.
- */
-
-export type AlertProps = HTMLAttributes
& {
- title?: string
- message?: ReactNode
- /** Name of a Lucide icon, e.g. `"Info"`, `"CheckCircle2"`. Falls back to `Info`. */
- iconName?: string
- onClose?: () => void
- variant?: AlertVariant
+export type AlertProps = Omit, 'color' | 'title'> & {
+ /** Semantic colour. `danger` and `warning` use `role="alert"`; the rest are polite `role="status"`. */
color?: AlertColor
- showCloseButton?: boolean
- width?: string
- height?: string
- closeOnOutsideClick?: boolean
- /** Auto-close delay in ms. `0` disables. */
+ /** Visual weight. */
+ variant?: AlertVariant
+ /** Short bold heading. */
+ title?: ReactNode
+ /** The message. */
+ children?: ReactNode
+ /** Replaces the colour's default icon. */
+ icon?: ReactNode
+ /** Hides the icon. */
+ hideIcon?: boolean
+ /** Buttons or links shown under the message. */
+ actions?: ReactNode
+ /** Shows a close button labelled "Dismiss". */
+ dismissible?: boolean
+ /** Controlled visibility. */
+ open?: boolean
+ /** Initial visibility when uncontrolled. */
+ defaultOpen?: boolean
+ /** Called when the alert is dismissed or auto-closes. */
+ onOpenChange?: (open: boolean) => void
+ /** Closes the alert after this many milliseconds. Pauses while hovered or focused. `0` disables. */
autoClose?: number
- showMessage?: boolean
- customClose?: ReactNode
}
-export const Alert = forwardRef(function Alert(
- {
- title,
- message,
- iconName = 'Info',
- onClose,
- variant = 'default',
- color = 'success',
- className = '',
- showCloseButton = true,
- width = 'w-full',
- height = 'h-auto',
- closeOnOutsideClick = false,
- autoClose = 0,
- showMessage = true,
- customClose,
- ...props
- },
- forwardedRef,
-) {
- const [visible, setVisible] = useState(true)
- const internalRef = useRef(null)
+const DEFAULT_ICONS: Record = {
+ info: ,
+ success: ,
+ warning: ,
+ danger: ,
+ neutral: ,
+ primary: ,
+}
- const handleClose = useCallback(() => {
- setVisible(false)
- onClose?.()
- }, [onClose])
-
- // Mirror the internal node onto the forwarded ref.
+/** Counts down `delay` ms, pausing while `paused` is true, then calls `onDone`. */
+function useAutoClose(delay: number, paused: boolean, active: boolean, onDone: () => void) {
+ const remaining = useRef(delay)
+ const onDoneRef = useRef(onDone)
useEffect(() => {
- const node = internalRef.current
- if (typeof forwardedRef === 'function') forwardedRef(node)
- else if (forwardedRef) forwardedRef.current = node
- }, [forwardedRef])
-
+ onDoneRef.current = onDone
+ })
useEffect(() => {
- if (autoClose > 0) {
- const timer = setTimeout(handleClose, autoClose)
- return () => clearTimeout(timer)
+ remaining.current = delay
+ }, [delay])
+ useEffect(() => {
+ if (!active || delay <= 0 || paused) return
+ const started = Date.now()
+ const timer = setTimeout(() => onDoneRef.current(), remaining.current)
+ return () => {
+ clearTimeout(timer)
+ remaining.current = Math.max(0, remaining.current - (Date.now() - started))
}
- }, [autoClose, handleClose])
+ }, [active, delay, paused])
+}
- useEffect(() => {
- if (!closeOnOutsideClick) return
+/** An inline status message, optionally dismissible or auto-closing. */
+export function Alert({
+ color = 'info',
+ variant = 'soft',
+ title,
+ children,
+ icon,
+ hideIcon = false,
+ actions,
+ dismissible = false,
+ open: openProp,
+ defaultOpen = true,
+ onOpenChange,
+ autoClose = 0,
+ className,
+ onMouseEnter,
+ onMouseLeave,
+ onFocus,
+ onBlur,
+ ...props
+}: AlertProps) {
+ const [open, setOpen] = useControllableState(openProp, defaultOpen, onOpenChange)
+ const [hovered, setHovered] = useState(false)
+ const [focused, setFocused] = useState(false)
- const handleClickOutside = (event: MouseEvent) => {
- if (internalRef.current && !internalRef.current.contains(event.target as Node)) {
- handleClose()
- }
- }
+ useAutoClose(autoClose, hovered || focused, open, () => setOpen(false))
- document.addEventListener('mousedown', handleClickOutside)
- return () => document.removeEventListener('mousedown', handleClickOutside)
- }, [closeOnOutsideClick, handleClose])
+ if (!open) return null
- if (!visible) return null
-
- const iconMap = Icons as unknown as Record
- const LucideIcon = (iconName && iconMap[iconName]) || Icons.Info
- const theme = ALERT_COLORS[color] ?? ALERT_COLORS.success
-
- let variantClasses: string
- if (variant === 'filled') {
- variantClasses = cn(theme.bg, 'text-white')
- } else if (variant === 'outlined') {
- variantClasses = cn('bg-transparent', theme.text, theme.border, 'border')
- } else if (variant === 'gradient') {
- variantClasses = ALERT_GRADIENT
- } else {
- variantClasses = cn(theme.lightBg, theme.text)
- }
+ const urgent = ALERT_URGENT_COLORS.includes(color)
return (
{
+ setHovered(true)
+ onMouseEnter?.(e)
+ }}
+ onMouseLeave={(e) => {
+ setHovered(false)
+ onMouseLeave?.(e)
+ }}
+ onFocus={(e) => {
+ setFocused(true)
+ onFocus?.(e)
+ }}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false)
+ onBlur?.(e)
+ }}
{...props}
>
-
-
- {LucideIcon &&
}
-
-
- {title &&
{title} }
- {showMessage && message &&
{message}
}
-
-
-
- {showCloseButton && (
-
- {customClose ?? }
-
- )}
+ {!hideIcon && (
+
+ {icon ?? DEFAULT_ICONS[color]}
+
+ )}
+
+ {title != null &&
{title}
}
+ {children != null &&
{children}
}
+ {actions != null &&
{actions}
}
+ {dismissible && (
+
}
+ onClick={() => setOpen(false)}
+ className={cn('-my-1.5 -mr-1.5 size-8', ALERT_CLOSE_STYLES[variant])}
+ />
+ )}
)
-})
-
-export default Alert
+}
diff --git a/src/components/AlertDialog.stories.tsx b/src/components/AlertDialog.stories.tsx
new file mode 100644
index 0000000..54970fb
--- /dev/null
+++ b/src/components/AlertDialog.stories.tsx
@@ -0,0 +1,150 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { AlertTriangle, LogOut, Send, Trash2 } from 'lucide-react'
+import { fn } from 'storybook/test'
+import { AlertDialog } from './AlertDialog'
+import { Button } from './Button'
+import { ALERT_DIALOG_COLORS } from './dialog.tokens'
+
+const ownFrame = (height = 520) => ({ docs: { story: { inline: false, iframeHeight: height } } })
+
+const wait = (ms: number) => new Promise
((resolve) => setTimeout(resolve, ms))
+
+const meta = {
+ title: 'Overlays/AlertDialog',
+ component: AlertDialog,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Asks the user to confirm an action, on Base UI AlertDialog (`role="alertdialog"`). It doesn’t close on outside clicks and focus starts on Cancel. Use `color="danger"` for destructive actions. When `onConfirm` returns a Promise the confirm button shows a spinner, Cancel and Escape are blocked, and the dialog closes when it resolves (or stays open if it rejects).',
+ },
+ },
+ },
+ argTypes: {
+ title: { control: 'text' },
+ description: { control: 'text' },
+ confirmLabel: { control: 'text', table: { defaultValue: { summary: 'Confirm' } } },
+ cancelLabel: { control: 'text', table: { defaultValue: { summary: 'Cancel' } } },
+ loadingLabel: { control: 'text' },
+ color: { control: 'inline-radio', options: ALERT_DIALOG_COLORS, table: { defaultValue: { summary: 'primary' } } },
+ open: { control: 'boolean' },
+ defaultOpen: { control: 'boolean' },
+ className: { control: 'text' },
+ icon: { control: false },
+ trigger: { control: false },
+ children: { control: false },
+ onConfirm: { control: false },
+ onCancel: { control: false },
+ onOpenChange: { control: false },
+ },
+ args: {
+ title: 'Delete this project?',
+ description: 'Acme Website and its 48 files will be deleted for everyone. This can’t be undone.',
+ confirmLabel: 'Delete project',
+ cancelLabel: 'Cancel',
+ color: 'danger',
+ icon: ,
+ trigger: (
+ }>
+ Delete project
+
+ ),
+ onConfirm: fn(),
+ onCancel: fn(),
+ onOpenChange: fn(),
+ },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Open: Story = {
+ args: { defaultOpen: true },
+ parameters: ownFrame(),
+}
+
+export const AsyncConfirm: Story = {
+ args: {
+ defaultOpen: true,
+ loadingLabel: 'Deleting…',
+ onConfirm: fn(() => wait(2000)),
+ },
+ parameters: {
+ ...ownFrame(),
+ docs: {
+ ...ownFrame().docs,
+ description: { story: 'Press **Delete project**: the button loads for two seconds, then the dialog closes.' },
+ },
+ },
+}
+
+export const WithoutIcon: Story = {
+ args: {
+ defaultOpen: true,
+ icon: undefined,
+ color: 'primary',
+ title: 'Publish changes?',
+ description: 'Your edits to the pricing page will go live for all visitors.',
+ confirmLabel: 'Publish',
+ cancelLabel: 'Keep editing',
+ trigger: }>Publish,
+ },
+ parameters: ownFrame(),
+}
+
+export const Warning: Story = {
+ args: {
+ defaultOpen: true,
+ color: 'warning',
+ icon: ,
+ title: 'Sign out of all devices?',
+ description: 'You will need to sign in again on your phone, tablet and other computers.',
+ confirmLabel: 'Sign out everywhere',
+ trigger: (
+ }>
+ Sign out everywhere
+
+ ),
+ },
+ parameters: ownFrame(),
+}
+
+export const WithDetails: Story = {
+ args: {
+ defaultOpen: true,
+ title: 'Remove 3 members?',
+ description: 'They lose access to Acme Corporation immediately.',
+ confirmLabel: 'Remove members',
+ children: (
+
+ Jane Doe (name@example.com)
+ John Smith (john@example.com)
+ Alex Kim (alex@example.com)
+
+ ),
+ },
+ parameters: ownFrame(560),
+}
+
+export const Colors: Story = {
+ render: (args) => (
+
+ {ALERT_DIALOG_COLORS.map((color) => (
+
+ {color[0].toUpperCase() + color.slice(1)}
+
+ }
+ />
+ ))}
+
+ ),
+}
diff --git a/src/components/AlertDialog.test.tsx b/src/components/AlertDialog.test.tsx
new file mode 100644
index 0000000..2051098
--- /dev/null
+++ b/src/components/AlertDialog.test.tsx
@@ -0,0 +1,83 @@
+import { act, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { AlertDialog } from './AlertDialog'
+import { Button } from './Button'
+
+const base = {
+ trigger: Delete project ,
+ title: 'Delete project?',
+ description: 'All files in Acme Website will be removed.',
+ confirmLabel: 'Delete',
+ color: 'danger' as const,
+}
+
+describe('AlertDialog', () => {
+ it('opens as a named alertdialog with focus on Cancel', async () => {
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Delete project' }))
+ const dialog = await screen.findByRole('alertdialog', { name: 'Delete project?' })
+ expect(dialog).toHaveAccessibleDescription('All files in Acme Website will be removed.')
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Cancel' })).toHaveFocus())
+ })
+
+ it('confirms and closes', async () => {
+ const onConfirm = vi.fn()
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Delete project' }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Delete' }))
+ expect(onConfirm).toHaveBeenCalledOnce()
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ })
+
+ it('cancels, closes and returns focus to the trigger', async () => {
+ const onConfirm = vi.fn()
+ const onCancel = vi.fn()
+ render( )
+ const trigger = screen.getByRole('button', { name: 'Delete project' })
+ await userEvent.click(trigger)
+ await userEvent.click(await screen.findByRole('button', { name: 'Cancel' }))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(onCancel).toHaveBeenCalledOnce()
+ await waitFor(() => expect(trigger).toHaveFocus())
+ })
+
+ it('closes on Escape', async () => {
+ render( )
+ await screen.findByRole('alertdialog')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ })
+
+ it('shows the confirm button loading until an async onConfirm resolves', async () => {
+ let resolve!: () => void
+ const onConfirm = vi.fn(() => new Promise((r) => (resolve = r)))
+ render( )
+ await userEvent.click(await screen.findByRole('button', { name: 'Delete' }))
+ const busy = screen.getByRole('button', { name: 'Deleting…' })
+ expect(busy).toBeDisabled()
+ expect(busy).toHaveAttribute('aria-busy', 'true')
+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()
+ // Escape is ignored while pending.
+ await userEvent.keyboard('{Escape}')
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ await act(async () => resolve())
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ })
+
+ it('stays open when an async onConfirm rejects', async () => {
+ const onConfirm = vi.fn(() => Promise.reject(new Error('Network error')))
+ render( )
+ await userEvent.click(await screen.findByRole('button', { name: 'Delete' }))
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Delete' })).toBeEnabled())
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ })
+
+ it('has no axe violations when open', async () => {
+ render( } />)
+ await screen.findByRole('alertdialog')
+ await expectNoA11yViolations(document.body)
+ })
+})
diff --git a/src/components/AlertDialog.tsx b/src/components/AlertDialog.tsx
new file mode 100644
index 0000000..1239f71
--- /dev/null
+++ b/src/components/AlertDialog.tsx
@@ -0,0 +1,149 @@
+import { AlertDialog as BaseAlertDialog } from '@base-ui/react/alert-dialog'
+import { useState, type ReactElement, type ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { useControllableState } from '../lib/useControllableState'
+import { Button } from './Button'
+import {
+ ALERT_ICON_STYLES,
+ backdropClass,
+ dialogDescriptionClass,
+ dialogPanelClass,
+ dialogTitleClass,
+ type AlertDialogColor,
+} from './dialog.tokens'
+
+export type AlertDialogProps = {
+ /** Controlled open state. Pair with `onOpenChange`. */
+ open?: boolean
+ /** Initial open state when uncontrolled. */
+ defaultOpen?: boolean
+ /** Fires with the next open state. */
+ onOpenChange?: (open: boolean) => void
+ /** Element that opens the dialog, usually a ``. */
+ trigger?: ReactElement
+ /** The question, e.g. "Delete this project?". Also the accessible name. */
+ title: ReactNode
+ /** What happens if the user confirms. */
+ description?: ReactNode
+ /** Label of the confirm button. */
+ confirmLabel?: ReactNode
+ /** Label of the cancel button. */
+ cancelLabel?: ReactNode
+ /** Label of the confirm button while `onConfirm` is pending. Defaults to `confirmLabel`. */
+ loadingLabel?: ReactNode
+ /** Colour of the confirm button and icon. `danger` for destructive actions. */
+ color?: AlertDialogColor
+ /**
+ * Runs when the user confirms. Return a Promise to keep the dialog open with
+ * the confirm button loading until it resolves; then the dialog closes. If it
+ * rejects, the dialog stays open so you can show the error.
+ */
+ onConfirm?: () => void | Promise
+ /** Fires when the user cancels (button or Escape). */
+ onCancel?: () => void
+ /** Icon shown in a tinted circle beside the text. */
+ icon?: ReactNode
+ /** Extra content under the description, such as a list of affected items. */
+ children?: ReactNode
+ /** Classes for the panel. */
+ className?: string
+}
+
+function isPromise(value: unknown): value is Promise {
+ return typeof (value as Promise | undefined)?.then === 'function'
+}
+
+/**
+ * Asks the user to confirm an action (Base UI AlertDialog). It doesn't close
+ * on outside clicks, focus starts on Cancel, and an async `onConfirm` shows a
+ * loading confirm button until it settles.
+ */
+export function AlertDialog({
+ open: openProp,
+ defaultOpen = false,
+ onOpenChange,
+ trigger,
+ title,
+ description,
+ confirmLabel = 'Confirm',
+ cancelLabel = 'Cancel',
+ loadingLabel,
+ color = 'primary',
+ onConfirm,
+ onCancel,
+ icon,
+ children,
+ className,
+}: AlertDialogProps) {
+ const [open, setOpen] = useControllableState(openProp, defaultOpen, onOpenChange)
+ const [pending, setPending] = useState(false)
+
+ function handleOpenChange(next: boolean, details: BaseAlertDialog.Root.ChangeEventDetails) {
+ if (!next && pending) {
+ details.cancel()
+ return
+ }
+ if (!next) onCancel?.()
+ setOpen(next)
+ }
+
+ async function handleConfirm() {
+ const result = onConfirm?.()
+ if (!isPromise(result)) {
+ setOpen(false)
+ return
+ }
+ setPending(true)
+ try {
+ await result
+ setOpen(false)
+ } catch {
+ // Stay open: the caller shows the error and the user can retry or cancel.
+ } finally {
+ setPending(false)
+ }
+ }
+
+ return (
+
+ {trigger && }
+
+
+
+
+
+ {icon != null && (
+
+ {icon}
+
+ )}
+
+
{title}
+ {description != null && (
+
+ {description}
+
+ )}
+ {children != null &&
{children}
}
+
+
+
+ }>
+ {cancelLabel}
+
+
+ {confirmLabel}
+
+
+
+
+
+
+ )
+}
diff --git a/src/components/Avatar.stories.tsx b/src/components/Avatar.stories.tsx
new file mode 100644
index 0000000..126794e
--- /dev/null
+++ b/src/components/Avatar.stories.tsx
@@ -0,0 +1,185 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Avatar, AvatarGroup } from './Avatar'
+import { AVATAR_SHAPES, AVATAR_SIZES_LIST, AVATAR_STATUSES } from './avatar.tokens'
+import { PORTRAITS } from './display.fixtures'
+
+const meta = {
+ title: 'Display/Avatar',
+ component: Avatar,
+ subcomponents: { AvatarGroup },
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ "A person's picture, built on Base UI Avatar. While the image loads, or if it fails, the avatar shows the initials of `name` on a colour derived from the name (so a person keeps their colour everywhere), or a generic icon. `status` adds a presence dot with an accessible label. `AvatarGroup` stacks avatars with a \"+N\" overflow.",
+ },
+ },
+ },
+ argTypes: {
+ src: { control: 'text' },
+ alt: { control: 'text' },
+ name: { control: 'text' },
+ size: { control: 'inline-radio', options: AVATAR_SIZES_LIST, table: { defaultValue: { summary: 'md' } } },
+ shape: { control: 'inline-radio', options: AVATAR_SHAPES, table: { defaultValue: { summary: 'circle' } } },
+ status: { control: 'inline-radio', options: [undefined, ...AVATAR_STATUSES] },
+ statusLabel: { control: 'text' },
+ },
+ args: {
+ name: 'Jane Doe',
+ src: PORTRAITS.jane,
+ size: 'lg',
+ shape: 'circle',
+ },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+
+ {AVATAR_SIZES_LIST.map((size) => (
+
+ ))}
+
+
+ {AVATAR_SIZES_LIST.map((size) => (
+
+ ))}
+
+
+ ),
+}
+
+export const Shapes: Story = {
+ render: (args) => (
+
+ {AVATAR_SHAPES.map((shape) => (
+
+ ))}
+ {AVATAR_SHAPES.map((shape) => (
+
+ ))}
+
+ ),
+}
+
+export const Fallbacks: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Initials come from the first and last word of `name`, on a colour picked from the name. With no name, a generic icon. A broken `src` falls back the same way.',
+ },
+ },
+ },
+ render: (args) => (
+
+ {['Jane Doe', 'John Smith', 'Maya Chen', 'Carlos Mendez', 'Aiko Tanaka', 'Samuel Okafor', 'Lena Fischer', 'Acme'].map(
+ (name) => (
+
+ ),
+ )}
+
+
+
+ ),
+}
+
+export const WithStatus: Story = {
+ render: (args) => (
+
+
+ {AVATAR_STATUSES.map((status) => (
+
+ ))}
+
+
+ {AVATAR_SIZES_LIST.map((size) => (
+
+ ))}
+ {AVATAR_SIZES_LIST.map((size) => (
+
+ ))}
+
+
+ ),
+}
+
+export const Group: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story: '`AvatarGroup` overlaps its avatars with a ring in the surface colour and collapses the rest into "+N".',
+ },
+ },
+ },
+ render: () => (
+
+ {(['sm', 'md', 'lg'] as const).map((size) => (
+
+
+
+
+
+
+
+
+
+ ))}
+
+
+
+
+
+
+
+
+ ),
+}
+
+export const InContext: Story = {
+ render: () => (
+
+
+
+
Jane Doe
+
jane.doe@example.com
+
+
+
+
+
+
+
+
+ ),
+}
+
+export const GroupPlayground: StoryObj = {
+ name: 'Group playground',
+ argTypes: {
+ max: { control: { type: 'number', min: 0, max: 8 }, table: { defaultValue: { summary: '4' } } },
+ size: { control: 'inline-radio', options: AVATAR_SIZES_LIST, table: { defaultValue: { summary: 'md' } } },
+ shape: { control: 'inline-radio', options: AVATAR_SHAPES, table: { defaultValue: { summary: 'circle' } } },
+ children: { control: false },
+ },
+ args: { max: 4, size: 'md', shape: 'circle', 'aria-label': 'Team members' },
+ render: (args) => (
+
+
+
+
+
+
+
+
+ ),
+}
diff --git a/src/components/Avatar.test.tsx b/src/components/Avatar.test.tsx
new file mode 100644
index 0000000..6f5fbaf
--- /dev/null
+++ b/src/components/Avatar.test.tsx
@@ -0,0 +1,65 @@
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Avatar, AvatarGroup } from './Avatar'
+import { colorFromName, initialsFromName } from './avatar.tokens'
+
+describe('Avatar', () => {
+ it('falls back to initials with the name as accessible text', () => {
+ render( )
+ expect(screen.getByText('JD')).toHaveAttribute('aria-hidden', 'true')
+ expect(screen.getByText('Jane Doe')).toHaveClass('sr-only')
+ })
+
+ it('falls back to initials while the image has not loaded', () => {
+ render( )
+ expect(screen.getByText('JS')).toBeInTheDocument()
+ })
+
+ it('labels the status dot', () => {
+ render( )
+ expect(screen.getByRole('img', { name: 'Online' })).toBeInTheDocument()
+ })
+
+ it('accepts a custom status label', () => {
+ render( )
+ expect(screen.getByRole('img', { name: 'In a meeting' })).toBeInTheDocument()
+ })
+
+ it('derives initials and a stable colour from the name', () => {
+ expect(initialsFromName('Jane Mary Doe')).toBe('JD')
+ expect(initialsFromName('Acme')).toBe('AC')
+ expect(colorFromName('Jane Doe')).toBe(colorFromName('Jane Doe'))
+ })
+})
+
+describe('AvatarGroup', () => {
+ it('shows max avatars and an overflow count', () => {
+ render(
+
+
+
+
+
+ ,
+ )
+ expect(screen.getByRole('group', { name: 'Team' })).toBeInTheDocument()
+ expect(screen.queryByText('PR')).not.toBeInTheDocument()
+ expect(screen.getByText('+2')).toBeInTheDocument()
+ expect(screen.getByText('and 2 more')).toBeInTheDocument()
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ ,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Avatar.tsx b/src/components/Avatar.tsx
new file mode 100644
index 0000000..d9d224a
--- /dev/null
+++ b/src/components/Avatar.tsx
@@ -0,0 +1,133 @@
+import { Children, use, type ComponentProps } from 'react'
+import { Avatar as BaseAvatar } from '@base-ui/react/avatar'
+import { User } from 'lucide-react'
+import { cn } from '../lib/cn'
+import {
+ AVATAR_COLORS,
+ AVATAR_GROUP_OVERLAP,
+ AVATAR_SIZES,
+ AVATAR_SQUARE_RADIUS,
+ AVATAR_STATUS_LABELS,
+ AVATAR_STATUS_SIZES,
+ AVATAR_STATUS_STYLES,
+ AvatarGroupContext,
+ colorFromName,
+ initialsFromName,
+ type AvatarShape,
+ type AvatarSize,
+ type AvatarStatus,
+} from './avatar.tokens'
+
+export type AvatarProps = Omit, 'children'> & {
+ /** Image URL. Falls back to initials (or a generic icon) while loading or on error. */
+ src?: string
+ /** Alternative text for the image. Defaults to `name`. */
+ alt?: string
+ /** The person's name: gives the initials, the fallback colour and the accessible name. */
+ name?: string
+ size?: AvatarSize
+ shape?: AvatarShape
+ /** Presence dot on the bottom corner, announced as its label. */
+ status?: AvatarStatus
+ /** Accessible name of the status dot. Defaults to "Online", "Away", "Busy" or "Offline". */
+ statusLabel?: string
+}
+
+function radius(shape: AvatarShape, size: AvatarSize) {
+ return shape === 'circle' ? 'rounded-full' : AVATAR_SQUARE_RADIUS[size]
+}
+
+/** A person's picture, with initials as the fallback and an optional presence dot. */
+export function Avatar({
+ src,
+ alt,
+ name,
+ size: sizeProp,
+ shape: shapeProp,
+ status,
+ statusLabel,
+ className,
+ ...props
+}: AvatarProps) {
+ const group = use(AvatarGroupContext)
+ const size = sizeProp ?? group?.size ?? 'md'
+ const shape = shapeProp ?? group?.shape ?? 'circle'
+ const label = alt ?? name
+ const initials = name ? initialsFromName(name) : ''
+ const shapeClass = radius(shape, size)
+
+ return (
+
+
+ {src && }
+
+ {initials ? {initials} : }
+ {label && {label} }
+
+
+ {status && (
+
+ )}
+
+ )
+}
+
+export type AvatarGroupProps = ComponentProps<'div'> & {
+ /** How many avatars to show before collapsing the rest into "+N". */
+ max?: number
+ /** Size of every avatar in the group. */
+ size?: AvatarSize
+ /** Shape of every avatar in the group. */
+ shape?: AvatarShape
+}
+
+/** An overlapping stack of avatars with a "+N" overflow. Give it an `aria-label`, e.g. "Project members". */
+export function AvatarGroup({
+ max = 4,
+ size = 'md',
+ shape = 'circle',
+ className,
+ children,
+ ...props
+}: AvatarGroupProps) {
+ const items = Children.toArray(children)
+ const visible = items.slice(0, Math.max(max, 0))
+ const hidden = items.length - visible.length
+
+ return (
+
+
+ {visible}
+ {hidden > 0 && (
+
+ +{hidden}
+ and {hidden} more
+
+ )}
+
+
+ )
+}
diff --git a/src/components/Badge.stories.tsx b/src/components/Badge.stories.tsx
index bcd7100..2acf6b7 100644
--- a/src/components/Badge.stories.tsx
+++ b/src/components/Badge.stories.tsx
@@ -1,139 +1,328 @@
+import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
-import { Bell, Inbox, Settings } from 'lucide-react'
-import { Badge } from './Badge'
+import { Bell, Check, Clock, Inbox, Mail, ShoppingCart, Sparkles } from 'lucide-react'
+import { fn } from 'storybook/test'
+import { COLORS, SIZES } from '../lib/styles'
+import { Avatar } from './Avatar'
+import { Badge, CountBadge } from './Badge'
+import { IconButton } from './Button'
+import { BADGE_VARIANTS, COUNT_BADGE_PLACEMENTS, type ColorRange } from './badge.tokens'
+import { PORTRAITS } from './display.fixtures'
+
+const APPROVAL_RANGES: ColorRange[] = [
+ { min: 0, max: 4, color: 'success' },
+ { min: 5, max: 9, color: 'warning' },
+ { min: 10, max: Infinity, color: 'danger' },
+]
const meta = {
title: 'Display/Badge',
component: Badge,
+ subcomponents: { CountBadge },
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
- 'Status count or label. `floating` pins to a corner of its child; `default` renders a standalone chip. `colorRanges` colours the badge by numeric value.',
+ 'A short status label. Pick the **color** by meaning and the **variant** by weight: `soft` for most labels, `solid` for emphasis, `outline` for quiet metadata. Add a `dot` for live status, an `icon`, or `onRemove` for filter chips. `colorRanges` colours numeric badges by value. `CountBadge` pins a count or a dot to the corner of an icon, button or avatar.',
},
},
},
argTypes: {
- type: { control: 'radio', options: ['floating', 'default'] },
- color: {
- control: 'select',
- options: ['primary', 'info', 'gray', 'danger', 'success', 'warning'],
- },
- floatingPosition: {
- control: 'select',
- options: ['top_right', 'top_left', 'bottom_right', 'bottom_left'],
- },
- floatingSize: { control: 'select', options: ['xs', 'sm', 'md', 'lg'] },
- defaultSize: { control: 'select', options: ['sm', 'md', 'lg'] },
- defaultBorder: { control: 'select', options: ['sm', 'md', 'lg', 'full'] },
- pulse: { control: 'boolean' },
- content: { control: 'text' },
+ color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'neutral' } } },
+ variant: { control: 'inline-radio', options: BADGE_VARIANTS, table: { defaultValue: { summary: 'soft' } } },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ dot: { control: 'boolean' },
+ children: { control: 'text' },
+ icon: { control: false },
+ onRemove: { control: false },
+ removeLabel: { control: 'text' },
+ colorRanges: { control: 'object' },
},
args: {
- type: 'floating',
- color: 'danger',
- content: '5',
- floatingPosition: 'top_right',
- floatingSize: 'sm',
- defaultSize: 'sm',
- defaultBorder: 'lg',
- pulse: false,
+ children: 'Active',
+ color: 'success',
+ variant: 'soft',
+ size: 'md',
+ dot: false,
},
} satisfies Meta
export default meta
type Story = StoryObj
-const BellIcon = () =>
+const title = (s: string) => s[0].toUpperCase() + s.slice(1)
-export const Playground: Story = {
+export const Playground: Story = {}
+
+export const Variants: Story = {
render: (args) => (
-
-
-
- ),
-}
-
-export const FloatingPositions: Story = {
- render: () => (
-
- {(['top_right', 'top_left', 'bottom_right', 'bottom_left'] as const).map((pos) => (
-
-
-
-
- {pos}
-
- ))}
-
- ),
-}
-
-export const FloatingSizes: Story = {
- render: () => (
-
- {(['xs', 'sm', 'md', 'lg'] as const).map((size) => (
-
-
-
-
- {size}
-
- ))}
-
- ),
-}
-
-export const Colors: Story = {
- render: () => (
- {(['primary', 'info', 'gray', 'danger', 'success', 'warning'] as const).map((color) => (
-
- {color}
+ {BADGE_VARIANTS.map((variant) => (
+
+ {title(variant)}
))}
),
}
-/** Colours by numeric content — the pending-approval pattern from the source app. */
-export const ColorRanges: Story = {
- render: () => {
- const ranges = [
- { min: 0, max: 2, color: 'success' },
- { min: 3, max: 7, color: 'warning' },
- { min: 8, max: 99, color: 'danger' },
- ]
- return (
-
- {[1, 5, 12].map((n) => (
-
-
-
+export const Colors: Story = {
+ parameters: { docs: { description: { story: 'Every colour in every variant, with and without a dot.' } } },
+ render: (args) => (
+
+ {BADGE_VARIANTS.map((variant) => (
+
+ {title(variant)}
+ {COLORS.map((color) => (
+
+ {title(color)}
- {n} pending
-
+ ))}
+ {COLORS.map((color) => (
+
+ {title(color)}
+
+ ))}
+
+ ))}
+
+ ),
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+ Size {size}
+
+ ))}
+
+ ),
+}
+
+export const WithIcons: Story = {
+ render: (args) => (
+
+ }>
+ Approved
+
+ }>
+ Pending review
+
+ }>
+ New
+
+ }>
+ Invited
+
+
+ ),
+}
+
+export const StatusDots: Story = {
+ parameters: { docs: { description: { story: 'A leading dot reads as live status.' } } },
+ render: () => (
+
+
+ Operational
+
+
+ Degraded
+
+
+ Outage
+
+
+ Paused
+
+
+ Scheduled
+
+
+ ),
+}
+
+function FilterChips() {
+ const [filters, setFilters] = useState(['Engineering', 'Full-time', 'Remote', 'Started 2024'])
+ return (
+
+
+ Filters
+ {filters.map((f) => (
+ setFilters((all) => all.filter((x) => x !== f))}>
+ {f}
+
+ ))}
+ {filters.length === 0 && No filters applied. }
+
+
+ {SIZES.map((size) => (
+
+ Acme Corporation
+
))}
- )
+
+ )
+}
+
+export const RemovableFilters: Story = {
+ parameters: {
+ docs: {
+ description: { story: '`onRemove` adds a labelled remove button ("Remove Engineering"). Press one to remove the filter.' },
+ },
},
+ render: () =>
,
}
-export const Pulse: Story = {
+export const ColorByValue: Story = {
+ parameters: {
+ docs: { description: { story: '`colorRanges`: 0–4 success, 5–9 warning, 10+ danger. The colour follows the number.' } },
+ },
render: () => (
-
-
-
+
+ {[0, 3, 5, 8, 12, 42].map((n) => (
+
+ {n}
+
+ ))}
+ {[2, 7, 15].map((n) => (
+
+ {n}
+
+ ))}
+
),
}
-/** `default` type renders a standalone chip; children take precedence over content. */
-export const ChipWithIcon: Story = {
+export const InContext: Story = {
render: () => (
-
-
- Configured
-
+
+ {[
+ { name: 'Q3 invoice run', meta: 'Acme Corporation · 142 invoices', status: Paid },
+ { name: 'Vendor onboarding', meta: 'Globex Ltd · 3 documents', status: In review },
+ { name: 'Card payment', meta: 'Initech · Declined twice', status: Failed },
+ { name: 'Annual renewal', meta: 'Umbrella Group · Due 12 Oct', status: Scheduled },
+ ].map((row) => (
+
+
+
{row.name}
+
{row.meta}
+
+ {row.status}
+
+ ))}
+
+ ),
+}
+
+export const CountBadges: Story = {
+ name: 'Count badge',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ '`CountBadge` pins a count to an element. Counts above `max` show as "99+", zero hides unless `showZero`, and `label` gives the accessible name ("3 unread notifications").',
+ },
+ },
+ },
+ render: () => (
+
+
`${n} unread notifications`}>
+ } />
+
+
`${n} unread messages`}>
+ } />
+
+
+ } />
+
+
+ } />
+
+
+ } />
+
+
+
+
+
`${n} pending approvals`}>
+
+
+
+ ),
+}
+
+export const CountBadgePlacements: Story = {
+ render: () => (
+
+ {COUNT_BADGE_PLACEMENTS.map((placement) => (
+
+
`${n} new`}>
+
+
+
{placement}
+
+ ))}
+
+ ),
+}
+
+export const CountBadgeColors: Story = {
+ render: () => (
+
+ {COLORS.map((color) => (
+
+
+
+
+
+ ))}
+
+
+
+
+
+
+
+
+
+
+
+ ),
+}
+
+export const CountBadgePlayground: StoryObj
= {
+ name: 'Count badge playground',
+ argTypes: {
+ count: { control: 'number' },
+ max: { control: 'number', table: { defaultValue: { summary: '99' } } },
+ showZero: { control: 'boolean' },
+ dot: { control: 'boolean' },
+ placement: { control: 'inline-radio', options: COUNT_BADGE_PLACEMENTS, table: { defaultValue: { summary: 'top-end' } } },
+ pulse: { control: 'boolean' },
+ color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'danger' } } },
+ size: { control: 'inline-radio', options: ['sm', 'md'], table: { defaultValue: { summary: 'md' } } },
+ label: { control: 'text' },
+ colorRanges: { control: 'object' },
+ children: { control: false },
+ },
+ args: {
+ count: 3,
+ max: 99,
+ showZero: false,
+ dot: false,
+ placement: 'top-end',
+ pulse: false,
+ color: 'danger',
+ size: 'md',
+ label: '3 unread notifications',
+ },
+ render: (args) => (
+
+ } />
+
),
}
diff --git a/src/components/Badge.test.tsx b/src/components/Badge.test.tsx
new file mode 100644
index 0000000..23cf954
--- /dev/null
+++ b/src/components/Badge.test.tsx
@@ -0,0 +1,110 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Badge, CountBadge } from './Badge'
+
+describe('Badge', () => {
+ it('renders its label', () => {
+ render(Active )
+ expect(screen.getByText('Active')).toBeInTheDocument()
+ })
+
+ it('renders a labelled remove button that calls onRemove', async () => {
+ const onRemove = vi.fn()
+ render(Engineering )
+ const button = screen.getByRole('button', { name: 'Remove Engineering' })
+ await userEvent.click(button)
+ expect(onRemove).toHaveBeenCalledOnce()
+ })
+
+ it('accepts a custom remove label', () => {
+ render(
+ {}} removeLabel="Clear department filter">
+ Engineering
+ ,
+ )
+ expect(screen.getByRole('button', { name: 'Clear department filter' })).toBeInTheDocument()
+ })
+
+ it('colours a numeric badge by range', () => {
+ const ranges = [
+ { min: 0, max: 4, color: 'success' as const },
+ { min: 5, max: Infinity, color: 'danger' as const },
+ ]
+ render(
+ <>
+ {2}
+ {12}
+ >,
+ )
+ expect(screen.getByText('2').className).toContain('text-success-700')
+ expect(screen.getByText('12').className).toContain('text-danger-700')
+ })
+
+ it('merges className so consumer classes win', () => {
+ render(Big )
+ expect(screen.getByText('Big').className).toContain('h-10')
+ expect(screen.getByText('Big').className).not.toContain('h-6')
+ })
+})
+
+describe('CountBadge', () => {
+ it('gives the count an accessible name from label', () => {
+ render(
+ `${n} unread notifications`}>
+ Notifications
+ ,
+ )
+ expect(screen.getByRole('status', { name: '3 unread notifications' })).toHaveTextContent('3')
+ })
+
+ it('caps the count at max', () => {
+ render(
+
+ Inbox
+ ,
+ )
+ expect(screen.getByRole('status', { name: '99+' })).toHaveTextContent('99+')
+ })
+
+ it('hides a zero count unless showZero', () => {
+ const { rerender } = render(
+
+ Inbox
+ ,
+ )
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ rerender(
+
+ Inbox
+ ,
+ )
+ expect(screen.getByRole('status', { name: '0' })).toBeInTheDocument()
+ })
+
+ it('renders a dot without a number', () => {
+ render(
+
+ Activity
+ ,
+ )
+ const dot = screen.getByRole('status', { name: 'New activity' })
+ expect(dot).toHaveTextContent('')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+
+
+ Active
+
+ {}}>Remote
+
+ Inbox
+
+
,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Badge.tsx b/src/components/Badge.tsx
index f9139ad..fa03733 100644
--- a/src/components/Badge.tsx
+++ b/src/components/Badge.tsx
@@ -1,113 +1,172 @@
-import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
-import { cn } from '@/lib/cn'
+import type { ComponentProps, MouseEvent, ReactNode } from 'react'
+import { X } from 'lucide-react'
+import { cn } from '../lib/cn'
+import { focusRing } from '../lib/styles'
import {
- BADGE_COLORS,
- BADGE_COLOR_ALIAS,
- BADGE_POSITIONS,
- BADGE_ROUNDED,
+ BADGE_DOT,
+ BADGE_DOT_SIZES,
BADGE_SIZES,
- DEFAULT_BADGE_SIZES,
- resolveBadgeColor,
- type BadgeBorder,
+ BADGE_STYLES,
+ COUNT_BADGE_PING,
+ COUNT_BADGE_PLACEMENT,
+ COUNT_BADGE_SIZES,
+ COUNT_BADGE_STYLES,
+ colorForValue,
type BadgeColor,
- type BadgeDefaultSize,
- type BadgeFloatingPosition,
- type BadgeFloatingSize,
- type BadgeType,
+ type BadgeSize,
+ type BadgeVariant,
type ColorRange,
+ type CountBadgePlacement,
+ type CountBadgeSize,
} from './badge.tokens'
-/**
- * Status indicator / count badge.
- *
- * Ported from the original `Badge` component.
- *
- * Two shapes:
- * - `floating` (default) — pins the badge to a corner of its child (an icon or
- * avatar), so the child wraps it.
- * - `default` — a standalone inline chip.
- *
- * `colorRanges` maps a numeric `content` onto a colour band, which is how the
- * source app colours pending-approval counts without a per-row className.
- */
-
-export type BadgeProps = Omit, 'content'> & {
- type?: BadgeType
- /** The count or label. Accepts a number — counts arrive as numbers in the source app. */
- content?: ReactNode | number
- color?: BadgeColor | string
- /** Colour the badge by numeric value, e.g. `[{min:5,max:9,color:'warning'}]`. */
+export type BadgeProps = Omit, 'color'> & {
+ /** Semantic colour. Overridden by a matching `colorRanges` entry. */
+ color?: BadgeColor
+ /** Visual weight. `soft` for most status labels, `solid` for emphasis. */
+ variant?: BadgeVariant
+ size?: BadgeSize
+ /** Shows a leading status dot. */
+ dot?: boolean
+ /** Icon before the label. Pass a decorative icon, e.g. ` `. */
+ icon?: ReactNode
+ /** Renders a remove button after the label, e.g. for filter chips. */
+ onRemove?: (event: MouseEvent) => void
+ /** Accessible name of the remove button. Defaults to "Remove {children}". */
+ removeLabel?: string
+ /** Colour the badge by value when `children` is a number, e.g. `[{ min: 10, max: Infinity, color: 'danger' }]`. */
colorRanges?: ColorRange[]
- floatingPosition?: BadgeFloatingPosition
- floatingSize?: BadgeFloatingSize
- defaultSize?: BadgeDefaultSize
- defaultBorder?: BadgeBorder
- /** Remix-icon class name, e.g. `"ri-home-line"`. Needs the Remix font. */
- defaultIcon?: string
- pulse?: boolean
}
-export const Badge = forwardRef(function Badge(
- {
- type = 'floating',
- content,
- color = 'danger',
- colorRanges,
- children,
- floatingPosition = 'top_right',
- floatingSize = 'sm',
- pulse = false,
- className = '',
- defaultSize = 'sm',
- defaultBorder = 'lg',
- defaultIcon,
- ...props
- },
- ref,
-) {
- const normalized = BADGE_COLOR_ALIAS[color] ?? (color as BadgeColor)
- const computed =
- type === 'floating' ? resolveBadgeColor(color, content, colorRanges) : normalized
- const theme = BADGE_COLORS[computed] ?? BADGE_COLORS[normalized] ?? BADGE_COLORS.danger
-
- if (type === 'default') {
- return (
-
- {defaultIcon && }
- {children ?? content}
-
- )
- }
-
+/** A short status label: a state, a category or a count. */
+export function Badge({
+ color = 'neutral',
+ variant = 'soft',
+ size = 'md',
+ dot = false,
+ icon,
+ onRemove,
+ removeLabel,
+ colorRanges,
+ className,
+ children,
+ ...props
+}: BadgeProps) {
+ const resolved = colorForValue(children, colorRanges, color)
+ const text = typeof children === 'string' || typeof children === 'number' ? String(children) : undefined
return (
-
+
+ {dot && (
+
+ )}
+ {icon}
{children}
-
- {content}
-
+ {onRemove && (
+
+
+
+ )}
)
-})
+}
-export default Badge
+export type CountBadgeProps = Omit, 'color'> & {
+ /** The element the count is pinned to: an icon, an avatar or a button. */
+ children: ReactNode
+ /** The number to show. */
+ count?: number
+ /** Counts above this show as "{max}+". */
+ max?: number
+ /** Show the badge when `count` is 0. */
+ showZero?: boolean
+ /** Show a small dot instead of the number. */
+ dot?: boolean
+ /** Which corner of the element the badge sits on. */
+ placement?: CountBadgePlacement
+ /** Draws attention with a pulsing ring (off under reduced motion). */
+ pulse?: boolean
+ color?: BadgeColor
+ size?: CountBadgeSize
+ /** Colour by value, e.g. warning from 5 and danger from 10. */
+ colorRanges?: ColorRange[]
+ /**
+ * Accessible name of the badge, e.g. "3 unread notifications". A function
+ * receives the count. Defaults to the visible text.
+ */
+ label?: string | ((count: number) => string)
+}
+
+/** Pins a count or a dot to a corner of an element. */
+export function CountBadge({
+ children,
+ count = 0,
+ max = 99,
+ showZero = false,
+ dot = false,
+ placement = 'top-end',
+ pulse = false,
+ color = 'danger',
+ size = 'md',
+ colorRanges,
+ label,
+ className,
+ ...props
+}: CountBadgeProps) {
+ const visible = dot || count > 0 || showZero
+ const display = count > max ? `${max}+` : String(count)
+ const name = typeof label === 'function' ? label(count) : (label ?? (dot ? undefined : display))
+ const resolved = colorForValue(count, colorRanges, color)
+ const sizes = COUNT_BADGE_SIZES[size]
+
+ return (
+
+ {children}
+ {visible && (
+
+ {pulse && (
+
+ )}
+ {!dot && {display} }
+
+ )}
+
+ )
+}
diff --git a/src/components/Breadcrumb.stories.tsx b/src/components/Breadcrumb.stories.tsx
new file mode 100644
index 0000000..a1ab959
--- /dev/null
+++ b/src/components/Breadcrumb.stories.tsx
@@ -0,0 +1,61 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Folder, House, Slash } from 'lucide-react'
+import { Breadcrumb, type BreadcrumbItem } from './Breadcrumb'
+
+const PATH: BreadcrumbItem[] = [
+ { label: 'Home', href: '#', icon: },
+ { label: 'Projects', href: '#' },
+ { label: 'Acme Corporation', href: '#' },
+ { label: 'Website redesign', href: '#' },
+ { label: 'Assets', href: '#' },
+ { label: 'Hero banner.png' },
+]
+
+const meta = {
+ title: 'Navigation/Breadcrumb',
+ component: Breadcrumb,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Shows where the current page sits in the hierarchy: a `nav` labelled "Breadcrumb" with an ordered list. The last item is the current page (`aria-current="page"`) and is not a link. With `maxItems`, the middle collapses into a "…" button that reveals the full path.',
+ },
+ },
+ },
+ argTypes: {
+ items: { control: false },
+ separator: { control: false },
+ maxItems: { control: { type: 'number', min: 2 } },
+ itemsBeforeCollapse: { control: { type: 'number', min: 1 }, table: { defaultValue: { summary: '1' } } },
+ itemsAfterCollapse: { control: { type: 'number', min: 1 }, table: { defaultValue: { summary: '2' } } },
+ },
+ args: { items: PATH.slice(0, 4), itemsBeforeCollapse: 1, itemsAfterCollapse: 2 },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Collapsed: Story = {
+ parameters: { docs: { description: { story: 'Six levels with `maxItems={4}`. Press "…" to expand.' } } },
+ args: { items: PATH, maxItems: 4 },
+}
+
+export const LongPath: Story = { args: { items: PATH } }
+
+export const CustomSeparator: Story = {
+ args: { items: PATH.slice(0, 4), separator: },
+}
+
+export const WithIcons: Story = {
+ args: {
+ items: [
+ { label: 'Home', href: '#', icon: },
+ { label: 'Documents', href: '#', icon: },
+ { label: 'Contracts', href: '#', icon: },
+ { label: 'Service agreement.pdf' },
+ ],
+ },
+}
diff --git a/src/components/Breadcrumb.test.tsx b/src/components/Breadcrumb.test.tsx
new file mode 100644
index 0000000..6169bdd
--- /dev/null
+++ b/src/components/Breadcrumb.test.tsx
@@ -0,0 +1,49 @@
+import { render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Breadcrumb, type BreadcrumbItem } from './Breadcrumb'
+
+const items: BreadcrumbItem[] = [
+ { label: 'Home', href: '/' },
+ { label: 'Projects', href: '/projects' },
+ { label: 'Acme', href: '/projects/acme' },
+ { label: 'Website', href: '/projects/acme/web' },
+ { label: 'Assets', href: '/projects/acme/web/assets' },
+ { label: 'Banner.png' },
+]
+
+describe('Breadcrumb', () => {
+ it('is a labelled nav with links and the current page last', () => {
+ render( )
+ const nav = screen.getByRole('navigation', { name: 'Breadcrumb' })
+ expect(within(nav).getAllByRole('listitem')).toHaveLength(3)
+ expect(screen.getByRole('link', { name: 'Home' })).toHaveAttribute('href', '/')
+ const current = screen.getByText('Acme')
+ expect(current).toHaveAttribute('aria-current', 'page')
+ expect(screen.queryByRole('link', { name: 'Acme' })).toBeNull()
+ })
+
+ it('collapses the middle and expands on request', async () => {
+ render( )
+ expect(screen.getByRole('link', { name: 'Home' })).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: 'Projects' })).toBeNull()
+ expect(screen.queryByRole('link', { name: 'Acme' })).toBeNull()
+ expect(screen.getByRole('link', { name: 'Assets' })).toBeInTheDocument()
+ expect(screen.getByText('Banner.png')).toHaveAttribute('aria-current', 'page')
+
+ await userEvent.click(screen.getByRole('button', { name: 'Show all breadcrumbs' }))
+ expect(screen.getByRole('link', { name: 'Projects' })).toHaveFocus()
+ expect(screen.getAllByRole('listitem')).toHaveLength(6)
+ })
+
+ it('does not collapse when within maxItems', () => {
+ render( )
+ expect(screen.queryByRole('button')).toBeNull()
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render( )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Breadcrumb.tsx b/src/components/Breadcrumb.tsx
new file mode 100644
index 0000000..29ee5a2
--- /dev/null
+++ b/src/components/Breadcrumb.tsx
@@ -0,0 +1,113 @@
+import { useEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react'
+import { ChevronRight } from 'lucide-react'
+import { cn } from '../lib/cn'
+import { focusRing } from '../lib/styles'
+
+export type BreadcrumbItem = {
+ label: ReactNode
+ /** Link target. The last item is the current page and never a link. */
+ href?: string
+ /** Icon before the label. */
+ icon?: ReactNode
+}
+
+export type BreadcrumbProps = Omit, 'children'> & {
+ items: BreadcrumbItem[]
+ /** Replaces the chevron between items. */
+ separator?: ReactNode
+ /** Collapse the middle items into "…" when there are more than this. */
+ maxItems?: number
+ /** Items kept before the "…" when collapsed. */
+ itemsBeforeCollapse?: number
+ /** Items kept after the "…" when collapsed. */
+ itemsAfterCollapse?: number
+}
+
+const linkClass =
+ 'inline-flex items-center gap-1.5 rounded-sm text-fg-muted underline-offset-4 transition-colors hover:text-fg hover:underline [&_svg]:size-4 [&_svg]:shrink-0'
+
+/** Shows where the current page sits in the site hierarchy. */
+export function Breadcrumb({
+ items,
+ separator,
+ maxItems,
+ itemsBeforeCollapse = 1,
+ itemsAfterCollapse = 2,
+ className,
+ 'aria-label': ariaLabel = 'Breadcrumb',
+ ...props
+}: BreadcrumbProps) {
+ const [expanded, setExpanded] = useState(false)
+ const listRef = useRef(null)
+
+ // After expanding, move focus to the first revealed item so it isn't lost with the "…" button.
+ useEffect(() => {
+ if (!expanded) return
+ const revealed = listRef.current?.children[itemsBeforeCollapse]
+ revealed?.querySelector('a, [aria-current]')?.focus()
+ }, [expanded, itemsBeforeCollapse])
+ const collapse =
+ !expanded && maxItems != null && items.length > maxItems && itemsBeforeCollapse + itemsAfterCollapse < items.length
+
+ type Entry = { item: BreadcrumbItem; index: number } | 'ellipsis'
+ const entries: Entry[] = items.map((item, index) => ({ item, index }))
+ const visible: Entry[] = collapse
+ ? [...entries.slice(0, itemsBeforeCollapse), 'ellipsis', ...entries.slice(items.length - itemsAfterCollapse)]
+ : entries
+
+ const sep = (
+
+ {separator ?? }
+
+ )
+
+ return (
+
+
+ {visible.map((entry, i) => {
+ const last = i === visible.length - 1
+ if (entry === 'ellipsis') {
+ return (
+
+ setExpanded(true)}
+ className={cn(
+ 'inline-flex h-6 min-w-6 items-center justify-center rounded-md px-1 text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg',
+ focusRing,
+ )}
+ >
+ …
+
+ {sep}
+
+ )
+ }
+ const { item, index } = entry
+ return (
+
+ {last ? (
+
+ {item.icon}
+ {item.label}
+
+ ) : item.href != null ? (
+
+ {item.icon}
+ {item.label}
+
+ ) : (
+
+ {item.icon}
+ {item.label}
+
+ )}
+ {!last && sep}
+
+ )
+ })}
+
+
+ )
+}
diff --git a/src/components/Button.stories.tsx b/src/components/Button.stories.tsx
index 6393f51..5b66770 100644
--- a/src/components/Button.stories.tsx
+++ b/src/components/Button.stories.tsx
@@ -1,5 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
-import { Button, LinkButton } from './Button'
+import { ArrowRight, Download, Plus, Trash2 } from 'lucide-react'
+import { fn } from 'storybook/test'
+import { COLORS, SIZES } from '../lib/styles'
+import { Button, IconButton, LinkButton } from './Button'
+import { BUTTON_VARIANTS } from './button.tokens'
const meta = {
title: 'Actions/Button',
@@ -8,24 +12,33 @@ const meta = {
parameters: {
docs: {
description: {
- component: 'A reusable button with visual variants and size tokens. Use semantic variants rather than ad-hoc colors.',
+ component:
+ 'Triggers an action. Pick the **variant** by importance (one `solid` button per view) and the **color** by meaning (`danger` for destructive actions). For navigation use `LinkButton`; for icon-only actions use `IconButton`.',
},
},
},
argTypes: {
- variant: {
- control: 'select',
- options: ['primary', 'secondary', 'outline', 'ghost', 'danger'],
- },
- size: {
- control: 'select',
- options: ['sm', 'md', 'lg'],
- },
+ variant: { control: 'inline-radio', options: BUTTON_VARIANTS, table: { defaultValue: { summary: 'solid' } } },
+ color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'primary' } } },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ loading: { control: 'boolean' },
+ loadingText: { control: 'text' },
+ disabled: { control: 'boolean' },
+ fullWidth: { control: 'boolean' },
+ children: { control: 'text' },
+ startIcon: { control: false },
+ endIcon: { control: false },
+ type: { control: 'inline-radio', options: ['button', 'submit', 'reset'] },
},
args: {
- children: 'Continue',
- variant: 'primary',
+ children: 'Save changes',
+ variant: 'solid',
+ color: 'primary',
size: 'md',
+ loading: false,
+ disabled: false,
+ fullWidth: false,
+ onClick: fn(),
},
} satisfies Meta
@@ -35,46 +48,119 @@ type Story = StoryObj
export const Playground: Story = {}
export const Variants: Story = {
- render: () => (
-
-
Primary
-
Secondary
-
Outline
-
Ghost
-
Danger
+ render: (args) => (
+
+ {BUTTON_VARIANTS.map((variant) => (
+
+ {variant[0].toUpperCase() + variant.slice(1)}
+
+ ))}
+
+ ),
+}
+
+export const Colors: Story = {
+ parameters: { docs: { description: { story: 'Every colour in every variant.' } } },
+ render: (args) => (
+
+ {BUTTON_VARIANTS.map((variant) => (
+
+ {COLORS.map((color) => (
+
+ {color[0].toUpperCase() + color.slice(1)}
+
+ ))}
+
+ ))}
),
}
export const Sizes: Story = {
- render: () => (
+ render: (args) => (
- Small
- Medium
- Large
+ {SIZES.map((size) => (
+
+ Size {size}
+
+ ))}
),
}
+export const WithIcons: Story = {
+ render: (args) => (
+
+ }>
+ New employee
+
+ }>
+ Continue
+
+ }>
+ Export CSV
+
+
+ ),
+}
+
+export const Loading: Story = {
+ args: { loading: true, loadingText: 'Saving…' },
+}
+
export const Disabled: Story = {
- args: {
- disabled: true,
- children: 'Unavailable',
- },
+ args: { disabled: true },
+}
+
+export const Destructive: Story = {
+ args: { color: 'danger', children: 'Delete run', startIcon:
},
+}
+
+export const FullWidth: Story = {
+ args: { fullWidth: true },
+ render: (args) => (
+
+
+
+ ),
}
export const AsLink: Story = {
parameters: {
docs: {
description: {
- story: '`LinkButton` renders an anchor with the same variants and sizes. Use it for navigation so the page keeps real links.',
+ story: '`LinkButton` renders an anchor with the same styles. A disabled link is inert and announced as disabled.',
},
},
},
render: () => (
-
+
Browse components
- Read the guide
+ }>
+ Read the guide
+
+
+ Link style
+
+
+ Disabled link
+
+
+ ),
+}
+
+export const IconOnly: Story = {
+ parameters: {
+ docs: { description: { story: '`IconButton` is square and requires an `aria-label`.' } },
+ },
+ render: () => (
+
+ {SIZES.map((size) => (
+ } />
+ ))}
+ } />
+ } />
+ } loading />
),
}
diff --git a/src/components/Button.test.tsx b/src/components/Button.test.tsx
new file mode 100644
index 0000000..01fd34f
--- /dev/null
+++ b/src/components/Button.test.tsx
@@ -0,0 +1,80 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Button, IconButton, LinkButton } from './Button'
+
+describe('Button', () => {
+ it('renders a button that fires onClick', async () => {
+ const onClick = vi.fn()
+ render(
Save )
+ await userEvent.click(screen.getByRole('button', { name: 'Save' }))
+ expect(onClick).toHaveBeenCalledOnce()
+ })
+
+ it('defaults to type="button" so it never submits a form by accident', () => {
+ render(
Save )
+ expect(screen.getByRole('button')).toHaveAttribute('type', 'button')
+ })
+
+ it('is disabled and busy while loading', async () => {
+ const onClick = vi.fn()
+ render(
+
+ Save
+ ,
+ )
+ const button = screen.getByRole('button', { name: 'Saving…' })
+ expect(button).toBeDisabled()
+ expect(button).toHaveAttribute('aria-busy', 'true')
+ await userEvent.click(button)
+ expect(onClick).not.toHaveBeenCalled()
+ })
+
+ it('is reachable by keyboard', async () => {
+ const onClick = vi.fn()
+ render(
Save )
+ await userEvent.tab()
+ expect(screen.getByRole('button')).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ expect(onClick).toHaveBeenCalledOnce()
+ })
+
+ it('merges className so consumer classes win', () => {
+ render(
Save )
+ expect(screen.getByRole('button').className).toContain('h-20')
+ expect(screen.getByRole('button').className).not.toContain('h-10')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+
+ Save
+ } />
+ Docs
+
,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
+
+describe('LinkButton', () => {
+ it('renders a link', () => {
+ render(
Docs )
+ expect(screen.getByRole('link', { name: 'Docs' })).toHaveAttribute('href', '/docs')
+ })
+
+ it('is inert when disabled', async () => {
+ const onClick = vi.fn()
+ render(
+
+ Docs
+ ,
+ )
+ const link = screen.getByRole('link', { name: 'Docs' })
+ expect(link).toHaveAttribute('aria-disabled', 'true')
+ expect(link).not.toHaveAttribute('href')
+ await userEvent.click(link)
+ expect(onClick).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/components/Button.tsx b/src/components/Button.tsx
index 380531e..3123c5f 100644
--- a/src/components/Button.tsx
+++ b/src/components/Button.tsx
@@ -1,73 +1,169 @@
-import type { AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode } from 'react'
-
-export type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger'
-export type ButtonSize = 'sm' | 'md' | 'lg'
+import type { ComponentProps, MouseEvent, ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { focusRing } from '../lib/styles'
+import {
+ BUTTON_SIZES,
+ BUTTON_STYLES,
+ ICON_BUTTON_SIZES,
+ type ButtonColor,
+ type ButtonSize,
+ type ButtonVariant,
+} from './button.tokens'
type ButtonStyleProps = {
+ /** Visual weight. `solid` is for the main action on a screen. */
variant?: ButtonVariant
+ /** Semantic colour. `danger` for destructive actions. */
+ color?: ButtonColor
size?: ButtonSize
- icon?: ReactNode
+ /** Icon before the label. */
+ startIcon?: ReactNode
+ /** Icon after the label. */
+ endIcon?: ReactNode
+ /** Stretch to the width of the container. */
+ fullWidth?: boolean
}
-export type ButtonProps = ButtonHTMLAttributes
& ButtonStyleProps
+export type ButtonProps = Omit, 'color'> &
+ ButtonStyleProps & {
+ /** Shows a spinner, disables the button and marks it busy. */
+ loading?: boolean
+ /** Label shown while `loading`. Defaults to the normal label. */
+ loadingText?: ReactNode
+ }
-/** A navigation link that looks like a Button. Use it wherever the action is "go somewhere". */
-export type LinkButtonProps = AnchorHTMLAttributes & ButtonStyleProps & {
- href: string
+export type LinkButtonProps = Omit, 'color'> &
+ ButtonStyleProps & {
+ href: string
+ /** Renders the link inert and announces it as disabled. */
+ disabled?: boolean
+ }
+
+export type IconButtonProps = Omit, 'color' | 'children'> &
+ Pick & {
+ /** The icon to show. */
+ icon: ReactNode
+ /** Required: an icon-only button needs an accessible name. */
+ 'aria-label': string
+ loading?: boolean
+ }
+
+const base =
+ 'inline-flex shrink-0 items-center justify-center whitespace-nowrap border font-semibold transition-colors ' +
+ 'select-none disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 ' +
+ '[&_svg]:shrink-0'
+
+function styles(variant: ButtonVariant, color: ButtonColor, size: ButtonSize, fullWidth?: boolean) {
+ return cn(
+ base,
+ focusRing,
+ BUTTON_STYLES[variant][color],
+ variant === 'link' ? 'h-auto gap-1.5 px-0 text-sm [&_svg]:size-4' : BUTTON_SIZES[size],
+ fullWidth && 'w-full',
+ )
}
-const variantClasses: Record = {
- primary:
- 'border-primary-500 bg-primary-500 text-white shadow-sm hover:border-primary-600 hover:bg-primary-600',
- secondary:
- 'border-slate-200 bg-slate-100 text-slate-800 hover:border-slate-300 hover:bg-slate-200',
- outline:
- 'border-slate-300 bg-white text-slate-700 hover:border-primary-500 hover:bg-primary-50 hover:text-primary-700',
- ghost:
- 'border-transparent bg-transparent text-slate-600 hover:bg-slate-100 hover:text-slate-950',
- danger:
- 'border-red-600 bg-red-600 text-white shadow-sm shadow-red-200 hover:border-red-700 hover:bg-red-700',
-}
-
-const sizeClasses: Record = {
- sm: 'min-h-9 gap-1.5 rounded-lg px-3 text-sm',
- md: 'min-h-11 gap-2 rounded-xl px-4 text-sm',
- lg: 'min-h-12 gap-2.5 rounded-xl px-5 text-base',
-}
-
-function buttonClasses(variant: ButtonVariant, size: ButtonSize, className: string) {
- return `inline-flex items-center justify-center border font-semibold transition duration-200 disabled:cursor-not-allowed disabled:opacity-50 ${variantClasses[variant]} ${sizeClasses[size]} ${className}`
+function Spinner() {
+ return (
+
+
+
+
+ )
}
+/** The main action element. For navigation, use LinkButton; for icon-only actions, IconButton. */
export function Button({
- variant = 'primary',
+ variant = 'solid',
+ color = 'primary',
size = 'md',
- icon,
- className = '',
- children,
+ startIcon,
+ endIcon,
+ fullWidth,
+ loading = false,
+ loadingText,
+ disabled,
type = 'button',
+ className,
+ children,
...props
}: ButtonProps) {
return (
-
- {icon}
- {children}
+
+ {loading ? : startIcon}
+ {loading && loadingText != null ? loadingText : children}
+ {!loading && endIcon}
)
}
+/** A link styled as a Button. Keeps real anchor semantics for navigation. */
export function LinkButton({
- variant = 'primary',
+ variant = 'solid',
+ color = 'primary',
size = 'md',
- icon,
- className = '',
+ startIcon,
+ endIcon,
+ fullWidth,
+ disabled = false,
+ className,
children,
+ onClick,
+ href,
...props
}: LinkButtonProps) {
+ function handleClick(event: MouseEvent) {
+ if (disabled) {
+ event.preventDefault()
+ return
+ }
+ onClick?.(event)
+ }
+
return (
-
+
+ {startIcon}
{children}
- {icon}
+ {endIcon}
)
}
+
+/** A square button that shows only an icon. `aria-label` is required. */
+export function IconButton({
+ variant = 'ghost',
+ color = 'neutral',
+ size = 'md',
+ icon,
+ loading = false,
+ disabled,
+ type = 'button',
+ className,
+ ...props
+}: IconButtonProps) {
+ return (
+
+ {loading ? : icon}
+
+ )
+}
diff --git a/src/components/Card.stories.tsx b/src/components/Card.stories.tsx
index 6d9cb05..5fd97cb 100644
--- a/src/components/Card.stories.tsx
+++ b/src/components/Card.stories.tsx
@@ -1,105 +1,285 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
+import { ArrowRight, ArrowUpRight, BookOpen, MapPin, MoreHorizontal, TrendingUp, Users } from 'lucide-react'
+import { fn } from 'storybook/test'
+import { Avatar, AvatarGroup } from './Avatar'
+import { Badge } from './Badge'
+import { Button, IconButton } from './Button'
import { Card } from './Card'
+import { CARD_LAYOUTS, CARD_PADDINGS, CARD_VARIANTS } from './card.tokens'
+import { PORTRAITS, landscape } from './display.fixtures'
const meta = {
title: 'Layout/Card',
component: Card,
+ subcomponents: {
+ 'Card.Header': Card.Header,
+ 'Card.Title': Card.Title,
+ 'Card.Description': Card.Description,
+ 'Card.Body': Card.Body,
+ 'Card.Footer': Card.Footer,
+ 'Card.Media': Card.Media,
+ },
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
- 'Surface container with a compound API: `Card.Header`, `Card.Title`, `Card.Body`, `Card.Footer`. Theme and layout are passed down to children automatically.',
+ 'A surface that groups related content. Compose `Card.Media`, `Card.Header` (with `Card.Title`, `Card.Description` and an optional `action`), `Card.Body` and `Card.Footer`; the card spaces them by `padding`. `layout="horizontal"` puts the media beside the text. Pass `href` (or `render={ }`) to make the whole card a link or button with a hover lift and focus ring. `headingLevel` fits the title into the page outline.',
},
},
},
argTypes: {
- theme: {
- control: 'select',
- options: ['primary', 'secondary', 'success', 'danger', 'no-preset'],
- },
- layout: { control: 'radio', options: ['vertical', 'horizontal'] },
- shadow: { control: 'select', options: ['none', 'sm', 'md', 'lg', 'xl'] },
- rounded: { control: 'select', options: ['none', 'sm', 'md', 'lg', 'xl', 'full'] },
+ variant: { control: 'inline-radio', options: CARD_VARIANTS, table: { defaultValue: { summary: 'outline' } } },
+ padding: { control: 'inline-radio', options: CARD_PADDINGS, table: { defaultValue: { summary: 'md' } } },
+ layout: { control: 'inline-radio', options: CARD_LAYOUTS, table: { defaultValue: { summary: 'vertical' } } },
+ interactive: { control: 'boolean' },
+ href: { control: 'text' },
+ headingLevel: { control: 'inline-radio', options: [2, 3, 4, 5, 6], table: { defaultValue: { summary: '3' } } },
+ render: { control: false },
+ children: { control: false },
+ },
+ args: {
+ variant: 'outline',
+ padding: 'md',
+ layout: 'vertical',
+ headingLevel: 3,
},
- args: { theme: 'primary', layout: 'vertical', shadow: 'md', rounded: 'lg' },
} satisfies Meta
export default meta
type Story = StoryObj
+const title = (s: string) => s[0].toUpperCase() + s.slice(1)
+
export const Playground: Story = {
render: (args) => (
- Payroll run
+ Quarterly review
+ Acme Corporation · Due 14 October
- March 2026 · 148 employees · ₹42,10,550 net
- Processed 2 hours ago
+
+ Collect the self-assessments from your team and schedule a 30-minute conversation with each person before the
+ end of the month.
+
+
+
+ Start review
+
+
+ Later
+
+
),
}
-export const Themes: Story = {
- render: () => (
-
- {(['primary', 'secondary', 'success', 'danger'] as const).map((theme) => (
-
+export const Variants: Story = {
+ render: (args) => (
+
+ {CARD_VARIANTS.map((variant) => (
+
- {theme}
+ {title(variant)}
+
+ {variant === 'outline'
+ ? 'A bordered surface for most content.'
+ : variant === 'elevated'
+ ? 'A soft shadow lifts it off the page.'
+ : 'A quiet fill for secondary content.'}
+
- Surface tinted for the {theme} state.
+ Cards group related content and actions about a single subject.
))}
),
}
-export const Shadows: Story = {
- render: () => (
-
- {(['none', 'sm', 'md', 'lg', 'xl'] as const).map((shadow) => (
-
-
- {shadow}
-
- {shadow}
-
+export const Padding: Story = {
+ render: (args) => (
+
+ {CARD_PADDINGS.map((padding) => (
+
+
+ padding="{padding}"
+
+ Spacing shared by every section.
+
))}
),
}
-export const Rounded: Story = {
- render: () => (
-
- {(['none', 'sm', 'md', 'lg', 'xl', 'full'] as const).map((rounded) => (
-
-
- {rounded}
-
-
{rounded}
+export const ProfileCard: Story = {
+ render: (args) => (
+
+ } onClick={fn()} />}
+ >
+
+
+
+ Jane Doe
+ Senior Product Engineer
+
- ))}
-
- ),
-}
-
-/** `horizontal` splits into a 2-column grid; `fullRow` makes a child span both. */
-export const HorizontalLayout: Story = {
- render: () => (
-
-
- Employee breakdown
-
-
-
Full-time · 132
-
Part-time · 11
-
Contract · 5
+
+
+ Engineering
+ Full-time
+
+ Available
+
+
+ Lisbon, Portugal · jane.doe@example.com
+
-
As of 31 Mar 2026
+
+
+ Message
+
+
+ View profile
+
+
),
}
+
+export const StatCards: Story = {
+ parameters: { docs: { description: { story: 'Compact stat cards in a dashboard row.' } } },
+ render: (args) => (
+
+ {[
+ { label: 'Active employees', value: '1,284', delta: '+4.2%', note: 'vs last month', color: 'success' as const, icon: Users },
+ { label: 'Open positions', value: '37', delta: '+6', note: 'across 9 teams', color: 'info' as const, icon: TrendingUp },
+ { label: 'Attrition (12 mo)', value: '8.1%', delta: '+0.6 pts', note: 'above target', color: 'warning' as const, icon: ArrowUpRight },
+ ].map((s) => (
+
+
+
+
+ }
+ >
+ {s.label}
+ {s.value}
+
+
+
+ {s.delta}
+
+ {s.note}
+
+
+ ))}
+
+ ),
+}
+
+export const HorizontalMedia: Story = {
+ args: { layout: 'horizontal' },
+ render: (args) => (
+
+
+
+
+
+
+ Offsite
+
+ Team offsite in the Sintra hills
+ 12–14 November · 24 attending
+
+
+ Three days of planning, workshops and long walks. Travel and accommodation are booked; bring layers, the
+ evenings get cold.
+
+
+
+
+
+
+
+
+
+ } onClick={fn()}>
+ Details
+
+
+
+ ),
+}
+
+export const VerticalMedia: Story = {
+ render: (args) => (
+
+ {[
+ { t: 'Designing for dark mode', d: 'Five rules for surfaces, borders and text that hold up at night.', sky: '#fde68a', hills: '#d97706', tag: 'Guide' },
+ { t: 'Accessible data tables', d: 'Captions, header scopes and sort state that screen readers announce.', sky: '#a7f3d0', hills: '#047857', tag: 'Article' },
+ ].map((p) => (
+
+
+
+
+
+ {p.t}
+ {p.d}
+
+
+
+ {p.tag}
+
+ 6 min read
+
+
+ ))}
+
+ ),
+}
+
+export const InteractiveLink: Story = {
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'With `href` the whole card is one link: it lifts on hover and shows a focus ring. Keep other interactive elements out of a link card. `render={
}` makes a button card.',
+ },
+ },
+ },
+ render: (args) => (
+
+
+
+
+
+
+ Getting started
+ Install the kit and render your first component.
+
+
+
+
+
+
+
+ Theming
+ Swap palettes and switch to dark mode.
+
+
+ }>
+
+
+
+
+ Invite your team
+ A button card that opens a dialog.
+
+
+
+ ),
+}
diff --git a/src/components/Card.test.tsx b/src/components/Card.test.tsx
new file mode 100644
index 0000000..f79af07
--- /dev/null
+++ b/src/components/Card.test.tsx
@@ -0,0 +1,82 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Card } from './Card'
+
+function Sample(props: Parameters
[0]) {
+ return (
+
+
+ Quarterly review
+ Due 14 October
+
+ Collect the self-assessments.
+ Footer
+
+ )
+}
+
+describe('Card', () => {
+ it('renders the title as an h3 by default', () => {
+ render( )
+ expect(screen.getByRole('heading', { level: 3, name: 'Quarterly review' })).toBeInTheDocument()
+ })
+
+ it('uses headingLevel for the title', () => {
+ render( )
+ expect(screen.getByRole('heading', { level: 2, name: 'Quarterly review' })).toBeInTheDocument()
+ })
+
+ it('renders an interactive link with href', async () => {
+ render( )
+ const link = screen.getByRole('link', { name: /Quarterly review/ })
+ expect(link).toHaveAttribute('href', '/reviews/q3')
+ expect(link.className).toContain('hover:-translate-y-0.5')
+ await userEvent.tab()
+ expect(link).toHaveFocus()
+ })
+
+ it('renders as a button through render', async () => {
+ const onClick = vi.fn()
+ render(
+ }>
+ Invite your team
+ ,
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Invite your team' }))
+ expect(onClick).toHaveBeenCalledOnce()
+ })
+
+ it('is not interactive by default', () => {
+ const { container } = render( )
+ expect(container.firstElementChild?.tagName).toBe('DIV')
+ expect(container.firstElementChild?.className).not.toContain('cursor-pointer')
+ })
+
+ it('puts media beside the content in the horizontal layout', () => {
+ const { container } = render(
+
+
+ Offsite
+
+
+
+
+ ,
+ )
+ const root = container.firstElementChild!
+ expect(root.firstElementChild).toContainElement(screen.getByRole('img', { name: 'Hills' }))
+ expect(root.lastElementChild).toContainElement(screen.getByRole('heading'))
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+
+
+
+
,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Card.tsx b/src/components/Card.tsx
index 35ebc46..6a5d6fb 100644
--- a/src/components/Card.tsx
+++ b/src/components/Card.tsx
@@ -1,183 +1,172 @@
+import { Children, isValidElement, use, type ComponentProps, type ReactNode } from 'react'
+import { useRender } from '@base-ui/react/use-render'
+import { mergeProps } from '@base-ui/react/merge-props'
+import { cn } from '../lib/cn'
+import { focusRing } from '../lib/styles'
import {
- Children,
- cloneElement,
- forwardRef,
- isValidElement,
- type ForwardRefExoticComponent,
- type HTMLAttributes,
- type ReactElement,
- type RefAttributes,
-} from 'react'
-import { cn } from '@/lib/cn'
-import {
- CARD_THEMES,
- ROUNDED_SIZES,
- SHADOW_SIZES,
+ CARD_FOOTER_DIVIDER,
+ CARD_FOOTER_PADDING,
+ CARD_INTERACTIVE,
+ CARD_SECTION_PADDING,
+ CARD_VARIANT_STYLES,
+ CardContext,
+ type CardHeadingLevel,
type CardLayout,
- type CardRounded,
- type CardShadow,
- type CardTheme,
+ type CardPadding,
+ type CardVariant,
} from './card.tokens'
-/**
- * Surface container with a header / body / footer compound API.
- *
- * Ported from the original `Card` component.
- *
- * Note: the original used `dark:` variants throughout. Those are dropped here
- * because this showcase renders on a light canvas and Storybook backgrounds are
- * controlled independently — leaving them in produced dark rules that could
- * never be inspected. Add them back per-component if dark mode returns.
- */
-
-type SpanProps = {
+export type CardProps = useRender.ComponentProps<'div'> & {
+ /** Surface style. `elevated` adds a shadow; `filled` sits on a sunken fill with no border. */
+ variant?: CardVariant
+ /** Padding of every section. `none` lets you lay out the content yourself. */
+ padding?: CardPadding
+ /** `horizontal` puts `Card.Media` beside the other sections (stacks on narrow screens). */
layout?: CardLayout
- fullRow?: boolean
- fullCol?: boolean
+ /** Hover lift and a focus ring. Set automatically with `href`. */
+ interactive?: boolean
+ /** Renders the whole card as a link. For a button, pass `render={ }`. */
+ href?: string
+ /** Heading level of `Card.Title`, to fit the page outline. */
+ headingLevel?: CardHeadingLevel
}
-/** Grid span helper shared by header / body / footer. */
-function spanClasses({ layout, fullRow, fullCol }: SpanProps): string {
+/** A surface that groups related content. Compose with Card.Media, Header, Title, Description, Body and Footer. */
+function CardRoot({
+ variant = 'outline',
+ padding = 'md',
+ layout = 'vertical',
+ interactive,
+ href,
+ headingLevel = 3,
+ render,
+ className,
+ children,
+ ...props
+}: CardProps) {
+ const isInteractive = interactive ?? (href != null || render != null)
+
+ let content: ReactNode = children
if (layout === 'horizontal') {
- if (fullRow) return 'col-span-2'
- if (fullCol) return 'row-span-2'
- return 'col-span-1'
+ // Media goes in the first column; everything else stacks in the second.
+ const media: ReactNode[] = []
+ const rest: ReactNode[] = []
+ Children.forEach(children, (child) => {
+ if (isValidElement(child) && child.type === CardMedia) media.push(child)
+ else rest.push(child)
+ })
+ content = (
+ <>
+ {media}
+ {rest}
+ >
+ )
}
- return 'col-span-1'
+
+ const element = useRender({
+ defaultTagName: 'div',
+ render: render ?? (href != null ? : undefined),
+ props: mergeProps<'div'>(
+ {
+ className: cn(
+ 'relative flex overflow-hidden rounded-xl text-fg',
+ layout === 'horizontal' ? 'flex-col sm:flex-row' : 'flex-col',
+ CARD_VARIANT_STYLES[variant],
+ isInteractive && [
+ 'cursor-pointer text-left transition-[transform,box-shadow,border-color,background-color] duration-150 ease-out',
+ 'hover:-translate-y-0.5 active:translate-y-0 motion-reduce:transform-none motion-reduce:transition-none',
+ CARD_INTERACTIVE[variant],
+ focusRing,
+ ],
+ className,
+ ),
+ children: content,
+ },
+ props,
+ ),
+ })
+
+ return {element}
}
-export type CardProps = HTMLAttributes & {
- theme?: CardTheme
- layout?: CardLayout
- shadow?: CardShadow
- rounded?: CardRounded
+export type CardHeaderProps = ComponentProps<'div'> & {
+ /** Content aligned to the top-right corner, e.g. a menu button or a badge. */
+ action?: ReactNode
}
-type CardComponent = ForwardRefExoticComponent> & {
- Header: typeof CardHeader
- Title: typeof CardTitle
- Body: typeof CardBody
- Content: typeof CardBody
- Footer: typeof CardFooter
-}
-
-const CardBase = forwardRef(function Card(
- {
- children,
- theme = 'primary',
- layout = 'vertical',
- shadow = 'md',
- rounded = 'lg',
- className = '',
- ...props
- },
- ref,
-) {
- const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
- const gridCols = layout === 'horizontal' ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1'
-
+function CardHeader({ action, className, children, ...props }: CardHeaderProps) {
+ const { padding } = use(CardContext)
return (
+
{children}
+ {action &&
{action}
}
+
+ )
+}
+
+export type CardTitleProps = ComponentProps<'h3'>
+
+function CardTitle({ className, ...props }: CardTitleProps) {
+ const { headingLevel } = use(CardContext)
+ const Heading = `h${headingLevel}` as 'h3'
+ return
+}
+
+function CardDescription({ className, ...props }: ComponentProps<'p'>) {
+ return
+}
+
+function CardBody({ className, ...props }: ComponentProps<'div'>) {
+ const { padding } = use(CardContext)
+ return
+}
+
+export type CardFooterProps = ComponentProps<'div'> & {
+ /** Separates the footer with a rule, e.g. for a row of actions. */
+ divider?: boolean
+}
+
+function CardFooter({ divider = false, className, ...props }: CardFooterProps) {
+ const { padding } = use(CardContext)
+ return (
+
- {/* Pass theme/layout down so nested header/body/footer stay in sync. */}
- {Children.map(children, (child) => {
- if (!isValidElement(child)) return null
- const childProps = child.props as SpanProps & { theme?: CardTheme; layout?: CardLayout }
- return cloneElement(child as ReactElement>, {
- theme: childProps.theme ?? theme,
- layout: childProps.layout ?? layout,
- })
- })}
-
+ />
)
-})
+}
-export function CardHeader({
- children,
- className = '',
- theme = 'primary',
- layout = 'vertical',
- fullRow = false,
- fullCol = false,
- ...props
-}: HTMLAttributes & SpanProps & { theme?: CardTheme }) {
- const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
+export type CardMediaProps = ComponentProps<'div'>
+
+/** An image or illustration, flush with the card edges. Put an ` ` inside; it's cropped to fill. */
+function CardMedia({ className, ...props }: CardMediaProps) {
+ const { layout } = use(CardContext)
return (
img]:size-full [&>img]:object-cover',
+ layout === 'horizontal' && 'aspect-video sm:aspect-auto sm:w-2/5',
+ className,
+ )}
{...props}
- >
- {children}
-
+ />
)
}
-export function CardTitle({ children, className = '', ...props }: HTMLAttributes) {
- return (
-
- {children}
-
- )
-}
-
-export function CardBody({
- children,
- className = '',
- theme = 'primary',
- layout = 'vertical',
- fullRow = false,
- fullCol = false,
- ...props
-}: HTMLAttributes & SpanProps & { theme?: CardTheme }) {
- const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
- return (
-
- {children}
-
- )
-}
-
-export const CardContent = CardBody
-
-export function CardFooter({
- children,
- className = '',
- theme = 'primary',
- layout = 'vertical',
- fullRow = false,
- fullCol = false,
- ...props
-}: HTMLAttributes & SpanProps & { theme?: CardTheme }) {
- const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
- return (
-
- {children}
-
- )
-}
-
-export const Card = Object.assign(CardBase, {
+export const Card = Object.assign(CardRoot, {
Header: CardHeader,
Title: CardTitle,
+ Description: CardDescription,
Body: CardBody,
- Content: CardContent,
Footer: CardFooter,
-}) as CardComponent
-
-export default Card
+ Media: CardMedia,
+})
diff --git a/src/components/Checkbox.stories.tsx b/src/components/Checkbox.stories.tsx
index d469a89..3d89155 100644
--- a/src/components/Checkbox.stories.tsx
+++ b/src/components/Checkbox.stories.tsx
@@ -1,5 +1,8 @@
-import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { COLORS, SIZES } from '../lib/styles'
+import { Button } from './Button'
import { Checkbox } from './Checkbox'
const meta = {
@@ -10,110 +13,182 @@ const meta = {
docs: {
description: {
component:
- 'Checkbox with an optional label, help tooltip and error message. The checked colour uses the native `accent-*` property, so it follows the palette tokens rather than a fixed hex.',
+ 'A single yes/no choice with its label to the right; clicking the label toggles the box. `description` and `error` sit under the label and are announced with it. `indeterminate` shows a dash for a partly chosen set. For a list of options, use `CheckboxGroup`.',
},
},
},
argTypes: {
- size: { control: 'select', options: ['sm', 'md', 'lg'] },
- theme: {
- control: 'select',
- options: ['primary', 'secondary', 'success', 'danger', 'warning', 'info'],
- },
label: { control: 'text' },
- disabled: { control: 'boolean' },
- tooltip: { control: 'text', description: 'Help text shown in a tooltip beside the label.' },
- helpText: { control: 'text', description: 'Alias for tooltip; tooltip wins if both are set.' },
+ description: { control: 'text' },
error: { control: 'text' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'primary' } } },
+ checked: { control: 'boolean' },
+ defaultChecked: { control: 'boolean' },
+ indeterminate: { control: 'boolean' },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ readOnly: { control: 'boolean' },
+ name: { control: 'text' },
+ value: { control: 'text' },
+ className: { control: 'text' },
+ controlClassName: { control: 'text' },
+ onCheckedChange: { control: false },
},
args: {
- label: 'Send payroll summary email',
+ label: 'Email me when a payslip is ready',
+ description: 'Sent to name@example.com on each pay day.',
size: 'md',
- theme: 'primary',
+ color: 'primary',
+ defaultChecked: false,
+ indeterminate: false,
+ required: false,
disabled: false,
- tooltip: '',
- helpText: '',
- error: '',
+ readOnly: false,
+ onCheckedChange: fn(),
},
} satisfies Meta
export default meta
type Story = StoryObj
-/** Checkbox state lives with the caller, so it is controlled here. */
-/**
- * Wraps Checkbox with local state so it is interactive.
- *
- * `initial` matters: supplying `checked` at all makes the component controlled,
- * so `defaultChecked` on the same element would be ignored. Stories that need to
- * show the checked appearance set the initial value here.
- */
-function ControlledCheckbox({
- initial = false,
- ...args
-}: React.ComponentProps & { initial?: boolean }) {
- const [checked, setChecked] = useState(initial)
- return setChecked(e.target.checked)} />
+export const Playground: Story = {}
+
+export const Unchecked: Story = {
+ args: { description: undefined },
}
-export const Playground: Story = {
- render: (args) => ,
+export const Checked: Story = {
+ args: { defaultChecked: true },
}
-export const Uncontrolled: Story = {
- render: (args) => ,
+export const Indeterminate: Story = {
+ args: { label: 'All departments', description: '3 of 7 departments selected.', indeterminate: true },
+}
+
+export const Disabled: Story = {
+ render: (args) => (
+
+
+
+
+
+ ),
+}
+
+export const ReadOnly: Story = {
+ args: {
+ readOnly: true,
+ defaultChecked: true,
+ label: 'Two-factor authentication enforced',
+ description: 'Managed by Acme Corporation. Contact IT to change it.',
+ },
+}
+
+export const WithError: Story = {
+ args: {
+ required: true,
+ label: 'I agree to the Terms of Service',
+ error: 'You need to accept the terms to create an account.',
+ },
+}
+
+export const Required: Story = {
+ args: { required: true, label: 'I confirm these details are correct', description: undefined },
+}
+
+export const WithoutDescription: Story = {
+ args: { description: undefined, label: 'Remember me for 30 days' },
}
export const Sizes: Story = {
render: (args) => (
-
- {(['sm', 'md', 'lg'] as const).map((size) => (
-
+
+ {SIZES.map((size) => (
+
))}
),
}
-export const Themes: Story = {
- render: () => (
-
- {(['primary', 'secondary', 'success', 'danger', 'warning', 'info'] as const).map((theme) => (
-
+export const Colors: Story = {
+ render: (args) => (
+
+ {COLORS.map((color) => (
+
+
+
+
))}
),
}
-export const WithTooltip: Story = {
- args: { tooltip: 'Recipients can be configured per entity in Settings → Notifications.' },
- render: (args) =>
,
+export const Uncontrolled: Story = {
+ args: { defaultChecked: true, label: 'Show weekends on the calendar', description: 'Starts ticked and keeps its own state.' },
}
-export const WithError: Story = {
- args: { error: 'You must acknowledge the policy before continuing.' },
- render: (args) =>
,
-}
-
-/** Error accepts an object too, matching a form-library error shape. */
-export const ErrorAsObject: Story = {
- render: () => (
-
- ),
-}
-
-export const Disabled: Story = {
- render: () => (
-
-
-
+function ControlledCheckbox(args: Story['args']) {
+ const [checked, setChecked] = useState(false)
+ return (
+
+
{
+ setChecked(next)
+ args?.onCheckedChange?.(next)
+ }}
+ />
+ Subscribed: {checked ? 'yes' : 'no'}
- ),
+ )
}
-/** No label — a bare control for use inside a table row or toolbar. */
-export const WithoutLabel: Story = {
- render: () =>
+export const Controlled: Story = {
+ render: (args) =>
,
+}
+
+function SignUpForm() {
+ const [terms, setTerms] = useState(false)
+ const [submitted, setSubmitted] = useState(false)
+ return (
+
+ )
+}
+
+/** Consent checkboxes in a sign-up form. Submit without ticking the terms to see the error. */
+export const SignUpConsent: Story = {
+ render: () =>
,
}
diff --git a/src/components/Checkbox.test.tsx b/src/components/Checkbox.test.tsx
new file mode 100644
index 0000000..8f50513
--- /dev/null
+++ b/src/components/Checkbox.test.tsx
@@ -0,0 +1,89 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Checkbox } from './Checkbox'
+
+describe('Checkbox', () => {
+ it('renders a checkbox named by its label', () => {
+ render(
)
+ expect(screen.getByRole('checkbox', { name: 'Remember me' })).not.toBeChecked()
+ })
+
+ it('toggles when the label is clicked', async () => {
+ render(
)
+ await userEvent.click(screen.getByText('Remember me'))
+ expect(screen.getByRole('checkbox')).toBeChecked()
+ })
+
+ it('toggles with Space', async () => {
+ const onCheckedChange = vi.fn()
+ render(
)
+ await userEvent.tab()
+ expect(screen.getByRole('checkbox')).toHaveFocus()
+ await userEvent.keyboard(' ')
+ expect(screen.getByRole('checkbox')).toBeChecked()
+ expect(onCheckedChange).toHaveBeenLastCalledWith(true)
+ })
+
+ it('works uncontrolled with defaultChecked', async () => {
+ render(
)
+ const box = screen.getByRole('checkbox')
+ expect(box).toBeChecked()
+ await userEvent.click(box)
+ expect(box).not.toBeChecked()
+ })
+
+ it('works controlled', async () => {
+ const onCheckedChange = vi.fn()
+ render(
)
+ await userEvent.click(screen.getByRole('checkbox'))
+ expect(onCheckedChange).toHaveBeenCalledWith(true)
+ expect(screen.getByRole('checkbox')).not.toBeChecked()
+ })
+
+ it('shows the indeterminate state', () => {
+ render(
)
+ expect(screen.getByRole('checkbox')).toHaveAttribute('aria-checked', 'mixed')
+ })
+
+ it('announces the description', () => {
+ render(
)
+ expect(screen.getByRole('checkbox')).toHaveAccessibleDescription('Two emails a month.')
+ })
+
+ it('marks itself invalid and announces the error instead of the description', () => {
+ render(
)
+ const box = screen.getByRole('checkbox')
+ expect(box).toHaveAttribute('data-invalid')
+ expect(box).toHaveAccessibleDescription('Accept the terms.')
+ expect(screen.queryByText('Hidden while invalid')).not.toBeInTheDocument()
+ expect(box).toHaveAttribute('aria-required', 'true')
+ })
+
+ it('ignores clicks when disabled or read-only', async () => {
+ const onCheckedChange = vi.fn()
+ render(
+ <>
+
+
+ >,
+ )
+ await userEvent.click(screen.getByText('Disabled'))
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Read only' }))
+ expect(onCheckedChange).not.toHaveBeenCalled()
+ expect(screen.getByRole('checkbox', { name: 'Disabled' })).toHaveAttribute('aria-disabled', 'true')
+ expect(screen.getByRole('checkbox', { name: 'Read only' })).toHaveAttribute('aria-readonly', 'true')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ <>
+
+
+
+ >,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Checkbox.tsx b/src/components/Checkbox.tsx
index 3bb7295..b287e67 100644
--- a/src/components/Checkbox.tsx
+++ b/src/components/Checkbox.tsx
@@ -1,106 +1,152 @@
-import { forwardRef, type InputHTMLAttributes } from 'react'
-import type { LucideIcon } from 'lucide-react'
-import { cn } from '@/lib/cn'
-import { Tooltip } from './Tooltip'
-import { CHECKBOX_SIZES, CHECKBOX_THEMES, type CheckboxSize, type CheckboxTheme } from './checkbox.tokens'
+import { Checkbox as BaseCheckbox } from '@base-ui/react/checkbox'
+import { Field as BaseField } from '@base-ui/react/field'
+import type { ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { descriptionText, errorText, focusRing } from '../lib/styles'
+import {
+ CHECKBOX_BOX_OFFSET,
+ CHECKBOX_BOX_SIZES,
+ CHECKBOX_COLORS,
+ CHECKBOX_GAP,
+ CHECKBOX_LABEL_SIZES,
+ type CheckboxColor,
+ type CheckboxSize,
+} from './checkbox.tokens'
+import { FieldLabel } from './Field'
-/**
- * Checkbox with an optional label, error message and help tooltip.
- *
- * Ported from the original `Checkbox` component.
- *
- * The checked colour uses the native `accent-*` property, so the browser paints
- * it — that means `theme` follows the CSS custom properties, not a hard-coded hex.
- *
- * The `register` / `validation` props are React Hook Form plumbing and are not
- * part of a design-system component; they are left out here. Pass `name`,
- * `checked` and `onChange` directly.
- */
+type BaseRootProps = Omit
-// `size` and `type` are omitted from the DOM props: `InputHTMLAttributes` declares
-// `size` as a number, which would collide with the visual-size token below.
-export type CheckboxProps = Omit, 'type' | 'size'> & {
- label?: string
+export type CheckboxControlProps = BaseRootProps & {
size?: CheckboxSize
- theme?: CheckboxTheme
- /** Error text, or an object carrying a `message`. */
- error?: string | { message?: string }
- tooltip?: string
- tooltipIcon?: LucideIcon
- helpText?: string
+ /** Fill colour when ticked or indeterminate. */
+ color?: CheckboxColor
+ /** Fires with the new ticked state. */
+ onCheckedChange?: (checked: boolean) => void
+ className?: string
}
-export const Checkbox = forwardRef(function Checkbox(
- {
- name,
- label,
- size = 'md',
- disabled = false,
- theme = 'primary',
- error,
- className,
- checked,
- onChange,
- tooltip,
- tooltipIcon,
- helpText,
- ...props
- },
- ref,
-) {
- const sizeClass = CHECKBOX_SIZES[size] ?? CHECKBOX_SIZES.md
- const themeClass = CHECKBOX_THEMES[theme] ?? CHECKBOX_THEMES.primary
- const errorMessage = typeof error === 'string' ? error : error?.message
+export type CheckboxProps = CheckboxControlProps & {
+ /** Text to the right of the box. Clicking it toggles the box. */
+ label?: ReactNode
+ /** Help text under the label, announced with the checkbox. */
+ description?: ReactNode
+ /** Error message. Marks the checkbox invalid and replaces `description`. */
+ error?: ReactNode
+ /** Adds the required mark and requires a tick before the form submits. */
+ required?: boolean
+ disabled?: boolean
+ /** Shows the state but ignores clicks and keys. */
+ readOnly?: boolean
+ /** Shows a dash instead of a tick: some, but not all, of a set is chosen. */
+ indeterminate?: boolean
+ checked?: boolean
+ defaultChecked?: boolean
+ /** Identifies the checkbox in a form. */
+ name?: string
+ /** Submitted when ticked. Defaults to "on". */
+ value?: string
+ /** Classes for the outer wrapper. Use `controlClassName` for the box itself. */
+ className?: string
+ controlClassName?: string
+}
+
+function CheckIcon() {
+ return (
+
+
+
+ )
+}
+
+function DashIcon() {
+ return (
+
+
+
+ )
+}
+
+/**
+ * The bare checkbox box, with no label or field wiring. Use it inside your own
+ * `` or Base UI `Field`, or reach for `Checkbox` which does that for you.
+ */
+export function CheckboxControl({ size = 'md', color = 'primary', onCheckedChange, className, ...props }: CheckboxControlProps) {
+ return (
+ onCheckedChange(checked) : undefined}
+ className={cn(
+ 'inline-flex shrink-0 cursor-pointer items-center justify-center border border-border-strong bg-surface transition-colors dark:not-data-checked:not-data-indeterminate:not-data-invalid:border-fg-subtle/60',
+ 'hover:border-fg-subtle data-invalid:border-danger-500',
+ 'data-disabled:cursor-not-allowed data-disabled:opacity-55 data-readonly:cursor-default',
+ CHECKBOX_BOX_SIZES[size],
+ CHECKBOX_COLORS[color],
+ focusRing,
+ className,
+ )}
+ {...props}
+ >
+ (
+ {state.indeterminate ? : }
+ )}
+ />
+
+ )
+}
+
+/**
+ * A checkbox with its label to the right and optional help or error text
+ * underneath. Built on Base UI Checkbox and Field, so the label, description
+ * and error are linked for screen readers.
+ */
+export function Checkbox({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ size = 'md',
+ name,
+ className,
+ controlClassName,
+ ...props
+}: CheckboxProps) {
+ const invalid = error != null && error !== false && error !== ''
return (
-
-
-
+
+
- {label && (
-
-
{label}
- {(tooltip || helpText) && (
-
e.preventDefault()}>
-
-
+ {(label != null || description != null || invalid) && (
+
+ {label != null && (
+
+ {label}
+
+ )}
+ {description != null && !invalid && (
+ {description}
+ )}
+ {invalid && (
+
+ {error}
+
)}
)}
-
-
- {errorMessage && (
-
- {errorMessage}
-
- )}
-
+
+
)
-})
-
-export default Checkbox
+}
diff --git a/src/components/CheckboxGroup.stories.tsx b/src/components/CheckboxGroup.stories.tsx
new file mode 100644
index 0000000..6958d0f
--- /dev/null
+++ b/src/components/CheckboxGroup.stories.tsx
@@ -0,0 +1,203 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { COLORS, SIZES } from '../lib/styles'
+import { CheckboxGroup } from './CheckboxGroup'
+
+const channels = [
+ { value: 'email', label: 'Email', description: 'A daily digest to name@example.com.' },
+ { value: 'sms', label: 'Text message', description: 'Only for urgent alerts.' },
+ { value: 'push', label: 'Push notification', description: 'On the mobile app.' },
+ { value: 'slack', label: 'Chat workspace', description: 'Posts to #team-alerts.' },
+]
+
+const days = [
+ { value: 'mon', label: 'Mon' },
+ { value: 'tue', label: 'Tue' },
+ { value: 'wed', label: 'Wed' },
+ { value: 'thu', label: 'Thu' },
+ { value: 'fri', label: 'Fri' },
+ { value: 'sat', label: 'Sat' },
+ { value: 'sun', label: 'Sun' },
+]
+
+const meta = {
+ title: 'Forms/CheckboxGroup',
+ component: CheckboxGroup,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Several checkboxes that share one `string[]` value, under a legend. `selectAll` adds a parent checkbox that ticks or clears every enabled option and shows a dash when only some are ticked. Works controlled (`value` + `onValueChange`) or uncontrolled (`defaultValue`).',
+ },
+ },
+ },
+ argTypes: {
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ options: { control: 'object' },
+ value: { control: 'object' },
+ defaultValue: { control: 'object' },
+ orientation: {
+ control: 'inline-radio',
+ options: ['vertical', 'horizontal'],
+ table: { defaultValue: { summary: 'vertical' } },
+ },
+ selectAll: { control: 'boolean' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'primary' } } },
+ name: { control: 'text' },
+ className: { control: 'text' },
+ onValueChange: { control: false },
+ },
+ args: {
+ label: 'Notification channels',
+ description: 'Choose where we reach you about account activity.',
+ options: channels,
+ defaultValue: ['email'],
+ orientation: 'vertical',
+ selectAll: false,
+ size: 'md',
+ color: 'primary',
+ required: false,
+ disabled: false,
+ onValueChange: fn(),
+ },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const SelectAll: Story = {
+ args: { selectAll: true, defaultValue: ['email', 'push'] },
+}
+
+export const Horizontal: Story = {
+ args: {
+ label: 'Working days',
+ description: 'Shifts are only scheduled on these days.',
+ options: days,
+ defaultValue: ['mon', 'tue', 'wed', 'thu', 'fri'],
+ orientation: 'horizontal',
+ },
+}
+
+export const DisabledOption: Story = {
+ args: {
+ options: [...channels.slice(0, 3), { value: 'fax', label: 'Fax', description: 'No longer supported.', disabled: true }],
+ },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: ['email', 'sms'] },
+}
+
+export const WithError: Story = {
+ args: { required: true, defaultValue: [], error: 'Choose at least one channel.' },
+}
+
+export const Required: Story = {
+ args: { required: true },
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+ ({ value, label }))}
+ defaultValue={['email', 'sms']}
+ />
+ ))}
+
+ ),
+}
+
+export const Colors: Story = {
+ render: (args) => (
+
+ {COLORS.map((color) => (
+ ({ value, label }))}
+ defaultValue={['email']}
+ />
+ ))}
+
+ ),
+}
+
+export const Uncontrolled: Story = {
+ args: { defaultValue: ['sms', 'push'], description: 'Starts with a default and keeps its own state.' },
+}
+
+function ControlledGroup(args: Story['args']) {
+ const [value, setValue] = useState(['email'])
+ return (
+
+
{
+ setValue(next)
+ args?.onValueChange?.(next)
+ }}
+ />
+ Value: {value.length ? value.join(', ') : '(none)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) => ,
+}
+
+/** A permissions editor, grouped by area, with a select-all per area. */
+export const RolePermissions: Story = {
+ render: () => (
+
+
+
Role: Billing manager
+
Acme Corporation · 4 members
+
+
+
+
+ ),
+}
diff --git a/src/components/CheckboxGroup.test.tsx b/src/components/CheckboxGroup.test.tsx
new file mode 100644
index 0000000..70cb3e4
--- /dev/null
+++ b/src/components/CheckboxGroup.test.tsx
@@ -0,0 +1,84 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { CheckboxGroup } from './CheckboxGroup'
+
+const options = [
+ { value: 'email', label: 'Email', description: 'A daily digest.' },
+ { value: 'sms', label: 'Text message' },
+ { value: 'push', label: 'Push' },
+]
+
+describe('CheckboxGroup', () => {
+ it('names the group with its legend and renders each option', () => {
+ render( )
+ expect(screen.getByRole('group', { name: 'Channels' })).toBeInTheDocument()
+ expect(screen.getAllByRole('checkbox')).toHaveLength(3)
+ expect(screen.getByRole('checkbox', { name: 'Email' })).toHaveAccessibleDescription('A daily digest.')
+ })
+
+ it('works uncontrolled and reports the full value', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ expect(screen.getByRole('checkbox', { name: 'Email' })).toBeChecked()
+ await userEvent.click(screen.getByText('Push'))
+ expect(screen.getByRole('checkbox', { name: 'Push' })).toBeChecked()
+ expect(onValueChange).toHaveBeenLastCalledWith(['email', 'push'])
+ })
+
+ it('works controlled', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Email' }))
+ expect(onValueChange).toHaveBeenCalledWith(['sms', 'email'])
+ expect(screen.getByRole('checkbox', { name: 'Email' })).not.toBeChecked()
+ })
+
+ it('toggles an option with Space', async () => {
+ render( )
+ await userEvent.tab()
+ await userEvent.keyboard(' ')
+ expect(screen.getByRole('checkbox', { name: 'Email' })).toBeChecked()
+ })
+
+ it('select all shows indeterminate, then ticks and clears every enabled option', async () => {
+ const onValueChange = vi.fn()
+ render(
+ ,
+ )
+ const all = screen.getByRole('checkbox', { name: 'Select all' })
+ expect(all).toHaveAttribute('aria-checked', 'mixed')
+ await userEvent.click(all)
+ expect(onValueChange).toHaveBeenLastCalledWith(['email', 'sms', 'push'])
+ expect(all).toBeChecked()
+ expect(screen.getByRole('checkbox', { name: 'Fax' })).not.toBeChecked()
+ await userEvent.click(all)
+ expect(onValueChange).toHaveBeenLastCalledWith([])
+ expect(all).not.toBeChecked()
+ })
+
+ it('marks the options invalid and announces the error', () => {
+ render( )
+ expect(screen.getByText('Choose at least one.')).toBeInTheDocument()
+ for (const box of screen.getAllByRole('checkbox')) expect(box).toHaveAttribute('data-invalid')
+ })
+
+ it('disables every option', () => {
+ render( )
+ for (const box of screen.getAllByRole('checkbox')) expect(box).toHaveAttribute('aria-disabled', 'true')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ ,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/CheckboxGroup.tsx b/src/components/CheckboxGroup.tsx
new file mode 100644
index 0000000..9c3f569
--- /dev/null
+++ b/src/components/CheckboxGroup.tsx
@@ -0,0 +1,186 @@
+import { CheckboxGroup as BaseCheckboxGroup } from '@base-ui/react/checkbox-group'
+import { Field as BaseField } from '@base-ui/react/field'
+import { Fieldset } from '@base-ui/react/fieldset'
+import type { ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { descriptionText, errorText, labelText, requiredMark } from '../lib/styles'
+import { useControllableState } from '../lib/useControllableState'
+import { CheckboxControl } from './Checkbox'
+import {
+ CHECKBOX_BOX_OFFSET,
+ CHECKBOX_GAP,
+ CHECKBOX_INDENT,
+ CHECKBOX_LABEL_SIZES,
+ type CheckboxColor,
+ type CheckboxGroupOrientation,
+ type CheckboxSize,
+} from './checkbox.tokens'
+
+export type CheckboxGroupOption = {
+ value: string
+ label: ReactNode
+ /** Help text under the option's label. */
+ description?: ReactNode
+ disabled?: boolean
+}
+
+export type CheckboxGroupProps = {
+ /** The group's legend. */
+ label?: ReactNode
+ /** Help text under the legend. */
+ description?: ReactNode
+ /** Error message. Marks every checkbox invalid and replaces `description`. */
+ error?: ReactNode
+ /** Adds the required mark to the legend. */
+ required?: boolean
+ /** Disables every option. */
+ disabled?: boolean
+ options: CheckboxGroupOption[]
+ /** Ticked option values (controlled). */
+ value?: string[]
+ /** Initially ticked option values (uncontrolled). */
+ defaultValue?: string[]
+ /** Fires with every ticked value. */
+ onValueChange?: (value: string[]) => void
+ /** Stack options (`vertical`) or lay them out in a wrapping row. */
+ orientation?: CheckboxGroupOrientation
+ /**
+ * Adds a parent checkbox that ticks or clears every enabled option and shows
+ * a dash when only some are ticked. `true` labels it "Select all"; pass a
+ * node for your own label.
+ */
+ selectAll?: boolean | ReactNode
+ size?: CheckboxSize
+ /** Fill colour when ticked. */
+ color?: CheckboxColor
+ /** Identifies the group in a form; each ticked option submits its value. */
+ name?: string
+ className?: string
+}
+
+const EMPTY: string[] = []
+
+function Option({
+ value,
+ label,
+ description,
+ disabled,
+ size,
+ color,
+ parent,
+}: Omit & {
+ value?: string
+ size: CheckboxSize
+ color: CheckboxColor
+ parent?: boolean
+}) {
+ return (
+
+
+
+
+ {label}
+
+ {description != null && (
+
+ {description}
+
+ )}
+
+
+ )
+}
+
+/**
+ * A set of checkboxes that share one value (`string[]`), with a legend, help
+ * text and an optional "Select all" parent. Built on Base UI CheckboxGroup and
+ * Fieldset, so the legend names the group for screen readers.
+ */
+export function CheckboxGroup({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ options,
+ value: valueProp,
+ defaultValue,
+ onValueChange,
+ orientation = 'vertical',
+ selectAll,
+ size = 'md',
+ color = 'primary',
+ name,
+ className,
+}: CheckboxGroupProps) {
+ const invalid = error != null && error !== false && error !== ''
+ const [value, setValue] = useControllableState(valueProp, defaultValue ?? EMPTY, onValueChange)
+ const hasSelectAll = selectAll != null && selectAll !== false
+ const allValues = options.filter((o) => !o.disabled).map((o) => o.value)
+
+ return (
+
+ setValue(next)}
+ allValues={hasSelectAll ? allValues : undefined}
+ disabled={disabled}
+ />
+ }
+ className="flex flex-col gap-3"
+ >
+ {(label != null || description != null || invalid) && (
+
+ {label != null && (
+
+ {label}
+ {required && (
+
+ *
+
+ )}
+
+ )}
+ {description != null && !invalid && (
+ {description}
+ )}
+
+ )}
+ {hasSelectAll && (
+
+
+
+ )}
+
+ {options.map((option) => (
+
+ ))}
+
+ {invalid && (
+
+ {error}
+
+ )}
+
+
+ )
+}
diff --git a/src/components/Combobox.stories.tsx b/src/components/Combobox.stories.tsx
new file mode 100644
index 0000000..84cfe0a
--- /dev/null
+++ b/src/components/Combobox.stories.tsx
@@ -0,0 +1,310 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Search, UserRound } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { fn, userEvent, within } from 'storybook/test'
+import { SIZES } from '../lib/styles'
+import { Combobox } from './Combobox'
+import { COUNTRIES, CURRENCIES, DEPARTMENTS, EMPLOYEES, searchEmployees, withoutValue } from './select.fixtures'
+import { SELECT_VARIANTS, type SelectOption } from './select.tokens'
+
+const meta = {
+ title: 'Forms/Combobox',
+ component: Combobox,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A searchable input that filters a list of options as you type, with its label above. Built on Base UI Combobox: arrow keys move through matches (`aria-activedescendant`), Enter chooses, Escape closes. With `multiple`, choices show as removable chips inside the input and Backspace removes the last one. For async search, pass `onInputValueChange`, `loading` and `filterOptions={false}`.',
+ },
+ },
+ },
+ argTypes: {
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ placeholder: { control: 'text' },
+ emptyText: { control: 'text' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ variant: { control: 'inline-radio', options: SELECT_VARIANTS, table: { defaultValue: { summary: 'outline' } } },
+ side: { control: 'inline-radio', options: ['bottom', 'top'], table: { defaultValue: { summary: 'bottom' } } },
+ multiple: { control: 'boolean' },
+ filterOptions: { control: 'boolean' },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ readOnly: { control: 'boolean' },
+ clearable: { control: 'boolean' },
+ loading: { control: 'boolean' },
+ loadingText: { control: 'text' },
+ name: { control: 'text' },
+ options: { control: 'object' },
+ value: { control: 'object' },
+ defaultValue: { control: 'object' },
+ open: { control: 'boolean' },
+ defaultOpen: { control: 'boolean' },
+ className: { control: 'text' },
+ inputClassName: { control: 'text' },
+ startIcon: { control: false },
+ renderOption: { control: false },
+ onValueChange: { control: false },
+ onInputValueChange: { control: false },
+ onOpenChange: { control: false },
+ },
+ args: {
+ label: 'Country',
+ placeholder: 'Search countries',
+ options: COUNTRIES,
+ size: 'md',
+ variant: 'outline',
+ side: 'bottom',
+ multiple: false,
+ required: false,
+ disabled: false,
+ readOnly: false,
+ clearable: false,
+ loading: false,
+ onValueChange: fn(),
+ onInputValueChange: fn(),
+ onOpenChange: fn(),
+ },
+ decorators: [
+ // Forms sit on a surface, as they would in a card or dialog.
+ (Story, { parameters }) => (
+
+
+
+ ),
+ ],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+const tall = (Story: () => React.JSX.Element) => (
+
+
+
+)
+
+export const Playground: Story = {}
+
+/** The popup rendered open, for review without clicking. */
+export const Open: Story = {
+ args: { defaultOpen: true, clearable: true },
+ decorators: [tall],
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+ ))}
+
+ ),
+}
+
+export const Variants: Story = {
+ render: (args) => (
+
+ {SELECT_VARIANTS.map((variant) => (
+
+ ))}
+
+ ),
+}
+
+export const WithDescription: Story = {
+ args: { description: 'Where the employee pays income tax.' },
+}
+
+export const WithError: Story = {
+ args: { error: 'Choose a country from the list.', required: true },
+}
+
+export const Required: Story = {
+ args: { required: true, name: 'country' },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: 'de' },
+}
+
+export const ReadOnly: Story = {
+ args: { readOnly: true, defaultValue: 'fr', description: 'Set by your HR system.' },
+}
+
+export const WithStartIcon: Story = {
+ args: { startIcon: , clearable: true },
+}
+
+export const Clearable: Story = {
+ args: { clearable: true, defaultValue: 'jp' },
+}
+
+/** Typing narrows the list; with no match, `emptyText` shows. */
+export const EmptyState: Story = {
+ args: { emptyText: 'No countries match your search' },
+ decorators: [tall],
+ play: async ({ canvasElement }) => {
+ await userEvent.type(within(canvasElement).getByRole('combobox'), 'Atlantis')
+ },
+}
+
+export const Loading: Story = {
+ args: { loading: true, options: [], defaultOpen: true, filterOptions: false },
+ decorators: [tall],
+}
+
+export const Grouped: Story = {
+ args: { label: 'Payroll currency', placeholder: 'Search currencies', options: CURRENCIES, defaultOpen: true },
+ decorators: [tall],
+}
+
+/** Chosen values become chips. Backspace in the empty input removes the last one. */
+export const Multiple: Story = {
+ args: {
+ label: 'Countries with employees',
+ placeholder: 'Add a country',
+ multiple: true,
+ clearable: true,
+ defaultValue: ['ca', 'de', 'gb', 'in', 'jp', 'nl', 'sg', 'ae'],
+ },
+}
+
+export const MultipleOpen: Story = {
+ args: {
+ label: 'Departments',
+ placeholder: 'Add a department',
+ options: DEPARTMENTS,
+ multiple: true,
+ defaultValue: ['eng', 'design'],
+ defaultOpen: true,
+ },
+ decorators: [tall],
+}
+
+export const MultipleSizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+ ))}
+
+ ),
+}
+
+export const CustomOptionRendering: Story = {
+ args: {
+ label: 'Employee',
+ placeholder: 'Search people',
+ options: EMPLOYEES,
+ startIcon: ,
+ defaultOpen: true,
+ renderOption: (option) => (
+
+
+ {option.label
+ .split(' ')
+ .map((part) => part[0])
+ .join('')}
+
+
+ {option.label}
+ {option.description}
+
+
+ ),
+ },
+ decorators: [tall],
+}
+
+function AsyncCombobox(args: Story['args']) {
+ const [query, setQuery] = useState('')
+ const [options, setOptions] = useState(EMPLOYEES)
+ // Starts loading: the effect below runs the first search on mount.
+ const [loading, setLoading] = useState(true)
+ useEffect(() => {
+ let current = true
+ searchEmployees(query).then((results) => {
+ if (!current) return
+ setOptions(results)
+ setLoading(false)
+ })
+ return () => {
+ current = false
+ }
+ }, [query])
+ return (
+ {
+ setQuery(value)
+ setLoading(true)
+ }}
+ />
+ )
+}
+
+/** `onInputValueChange` drives a (simulated) server search; `loading` shows while it runs. */
+export const AsyncSearch: Story = {
+ render: (args) => ,
+ decorators: [tall],
+}
+
+function ControlledCombobox(args: Story['args']) {
+ const [value, setValue] = useState(['eng', 'hr'])
+ return (
+
+
+
Value: {value.length ? value.join(', ') : '(none)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) => ,
+}
+
+export const Uncontrolled: Story = {
+ args: { defaultValue: 'se', name: 'country', clearable: true },
+}
+
+/** 50 countries, filtered as you type. */
+export const LongList: Story = {
+ args: { defaultOpen: true, label: 'Country of residence' },
+ decorators: [tall],
+}
diff --git a/src/components/Combobox.test.tsx b/src/components/Combobox.test.tsx
new file mode 100644
index 0000000..867afc6
--- /dev/null
+++ b/src/components/Combobox.test.tsx
@@ -0,0 +1,161 @@
+import { render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Combobox } from './Combobox'
+import type { SelectOption } from './select.tokens'
+
+const countries: SelectOption[] = [
+ { value: 'ca', label: 'Canada' },
+ { value: 'de', label: 'Germany' },
+ { value: 'fr', label: 'France' },
+ { value: 'gb', label: 'United Kingdom' },
+ { value: 'us', label: 'United States' },
+]
+
+describe('Combobox', () => {
+ it('links the label to the input', () => {
+ render( )
+ expect(screen.getByRole('combobox', { name: 'Country' })).toBeInTheDocument()
+ })
+
+ it('filters as you type and shows the empty state', async () => {
+ render( )
+ const input = screen.getByRole('combobox', { name: 'Country' })
+ await userEvent.type(input, 'united')
+ const listbox = await screen.findByRole('listbox')
+ expect(within(listbox).getAllByRole('option').map((o) => o.textContent)).toEqual([
+ 'United Kingdom',
+ 'United States',
+ ])
+ await userEvent.type(input, 'zzz')
+ expect(await screen.findByText('No countries found')).toBeInTheDocument()
+ expect(screen.queryAllByRole('option')).toHaveLength(0)
+ })
+
+ it('chooses with the keyboard and points aria-activedescendant at the highlighted option', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ const input = screen.getByRole('combobox', { name: 'Country' })
+ input.focus()
+ await userEvent.keyboard('{ArrowDown}')
+ await screen.findByRole('listbox')
+ await userEvent.keyboard('{ArrowDown}')
+ const active = input.getAttribute('aria-activedescendant')
+ expect(active).toBeTruthy()
+ expect(document.getElementById(active!)).toHaveAttribute('role', 'option')
+ await userEvent.keyboard('{Enter}')
+ expect(onValueChange).toHaveBeenCalledTimes(1)
+ expect(typeof onValueChange.mock.calls[0][0]).toBe('string')
+ expect(input).toHaveFocus()
+ })
+
+ it('closes on Escape and keeps focus in the input', async () => {
+ render( )
+ const input = screen.getByRole('combobox', { name: 'Country' })
+ await userEvent.click(input)
+ await screen.findByRole('listbox')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'false'))
+ expect(input).toHaveFocus()
+ })
+
+ it('works uncontrolled and shows the chosen label', async () => {
+ render( )
+ const input = screen.getByRole('combobox', { name: 'Country' })
+ expect(input).toHaveValue('Germany')
+ await userEvent.clear(input)
+ await userEvent.type(input, 'Fra')
+ await userEvent.click(await screen.findByRole('option', { name: 'France' }))
+ expect(input).toHaveValue('France')
+ })
+
+ it('works controlled', async () => {
+ function Controlled() {
+ const [value, setValue] = useState('ca')
+ return (
+ <>
+
+ {String(value)}
+ >
+ )
+ }
+ render( )
+ const input = screen.getByRole('combobox', { name: 'Country' })
+ expect(input).toHaveValue('Canada')
+ await userEvent.click(screen.getByRole('button', { name: 'Country' }))
+ await userEvent.click(await screen.findByRole('option', { name: 'United States' }))
+ expect(screen.getByTestId('value')).toHaveTextContent('us')
+ })
+
+ it('clears with a labelled button', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Clear selection' }))
+ expect(onValueChange).toHaveBeenLastCalledWith(null)
+ expect(screen.getByRole('combobox', { name: 'Country' })).toHaveValue('')
+ })
+
+ it('shows multiple values as chips; Backspace removes the last one', async () => {
+ const onValueChange = vi.fn()
+ render(
+ ,
+ )
+ expect(screen.getByRole('button', { name: 'Remove Canada' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Remove Germany' })).toBeInTheDocument()
+ const input = screen.getByRole('combobox', { name: 'Countries' })
+ await userEvent.click(input)
+ await userEvent.click(await screen.findByRole('option', { name: 'France' }))
+ expect(onValueChange).toHaveBeenLastCalledWith(['ca', 'de', 'fr'])
+ input.focus()
+ await userEvent.keyboard('{Backspace}')
+ expect(onValueChange).toHaveBeenLastCalledWith(['ca', 'de'])
+ await userEvent.keyboard('{Escape}')
+ await userEvent.click(screen.getByRole('button', { name: 'Remove Canada' }))
+ expect(onValueChange).toHaveBeenLastCalledWith(['de'])
+ })
+
+ it('reports typing through onInputValueChange and shows loading', async () => {
+ const onInputValueChange = vi.fn()
+ render(
+ ,
+ )
+ const input = screen.getByRole('combobox', { name: 'Employee' })
+ await userEvent.type(input, 'Ja')
+ expect(onInputValueChange).toHaveBeenLastCalledWith('Ja')
+ expect(await screen.findByText('Loading…')).toBeInTheDocument()
+ expect(screen.queryByText('No results')).not.toBeInTheDocument()
+ })
+
+ it('announces the description, and the error when invalid', () => {
+ const { rerender } = render( )
+ expect(screen.getByRole('combobox')).toHaveAccessibleDescription('Where you pay tax.')
+ rerender( )
+ const input = screen.getByRole('combobox')
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(input).toHaveAccessibleDescription('Choose a country.')
+ })
+
+ it('passes required and disabled to the input', () => {
+ render( )
+ const input = screen.getByRole('combobox', { name: /Country/ })
+ expect(input).toBeDisabled()
+ })
+
+ it('has no axe violations, closed and open', async () => {
+ const { container } = render(
+ ,
+ )
+ await expectNoA11yViolations(container)
+ await userEvent.click(screen.getByRole('combobox', { name: 'Countries' }))
+ await screen.findByRole('listbox')
+ await expectNoA11yViolations(document.body)
+ })
+})
diff --git a/src/components/Combobox.tsx b/src/components/Combobox.tsx
new file mode 100644
index 0000000..5472f75
--- /dev/null
+++ b/src/components/Combobox.tsx
@@ -0,0 +1,267 @@
+import { Combobox as BaseCombobox } from '@base-ui/react/combobox'
+import { X } from 'lucide-react'
+import { useState, type ComponentProps, type ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { controlHeight, controlPaddingX, focusRing, focusWithinRing, iconSize } from '../lib/styles'
+import { useControllableState } from '../lib/useControllableState'
+import { Field } from './Field'
+import { Chevron, ComboboxOptions, Spinner, StatusRow } from './SelectParts'
+import {
+ CHIP_SIZE,
+ CHIPS_MIN_HEIGHT,
+ FIELD_BOX,
+ comboboxItems,
+ hasGroups,
+ popupClass,
+ type RenderOption,
+ type SelectOption,
+ type SelectSide,
+ type SelectSize,
+ type SelectValue,
+ type SelectVariant,
+} from './select.tokens'
+
+export type ComboboxProps = Omit<
+ ComponentProps<'input'>,
+ 'value' | 'defaultValue' | 'onChange' | 'size' | 'className' | 'children' | 'type'
+> & {
+ /** Visible label, linked to the input. */
+ label?: ReactNode
+ /** Help text under the input, announced with it. */
+ description?: ReactNode
+ /** Error message. Marks the input invalid and replaces `description`. */
+ error?: ReactNode
+ /** Shows the required mark and requires a value in forms. */
+ required?: boolean
+ disabled?: boolean
+ /** Shows the value but prevents changing it. */
+ readOnly?: boolean
+ size?: SelectSize
+ /** `outline` draws a bordered box; `filled` a tinted one. */
+ variant?: SelectVariant
+ /** Text shown in the empty input. */
+ placeholder?: string
+ /** The choices. Options sharing a `group` are listed under that heading. */
+ options: SelectOption[]
+ /** Allows several values, shown as removable chips. `value` is then a `string[]`. */
+ multiple?: Multiple
+ /** The selected value (controlled): a string or null, or a string array with `multiple`. */
+ value?: SelectValue
+ /** The initial value (uncontrolled). */
+ defaultValue?: SelectValue
+ /** Fires with the new value. */
+ onValueChange?: (value: SelectValue) => void
+ /** Fires as the user types. Use it to fetch options for an async search. */
+ onInputValueChange?: (inputValue: string) => void
+ /** Filters `options` by the typed text. Turn off when the server filters them. */
+ filterOptions?: boolean
+ /** Shown when no option matches. */
+ emptyText?: ReactNode
+ /** Shows a spinner and a loading row while options load. */
+ loading?: boolean
+ /** Text of the loading row. */
+ loadingText?: ReactNode
+ /** Shows a button that clears the value and the typed text. */
+ clearable?: boolean
+ /** Custom content for each option in the list. */
+ renderOption?: RenderOption
+ /** Icon before the input. */
+ startIcon?: ReactNode
+ /** Submits the value under this name in a form. */
+ name?: string
+ /** Whether the popup is open (controlled). */
+ open?: boolean
+ /** Whether the popup starts open (uncontrolled). */
+ defaultOpen?: boolean
+ onOpenChange?: (open: boolean) => void
+ /** Preferred side for the popup. It flips when there isn't room. */
+ side?: SelectSide
+ /** Classes for the outer field wrapper. Use `inputClassName` for the input itself. */
+ className?: string
+ inputClassName?: string
+}
+
+const CHIP_INPUT_HEIGHT: Record = { sm: 'h-5', md: 'h-6', lg: 'h-7' }
+
+const iconButton = cn(
+ 'flex size-6 shrink-0 items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg',
+ focusRing,
+ 'focus-visible:outline-offset-0 data-disabled:pointer-events-none',
+)
+
+/**
+ * A searchable input that filters a list of options as you type, with its
+ * label above. With `multiple`, choices appear as removable chips inside the
+ * input; Backspace removes the last one. Built on Base UI Combobox.
+ */
+export function Combobox({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ readOnly,
+ size = 'md',
+ variant = 'outline',
+ placeholder,
+ options,
+ multiple,
+ value: valueProp,
+ defaultValue,
+ onValueChange,
+ onInputValueChange,
+ filterOptions = true,
+ emptyText = 'No results',
+ loading,
+ loadingText = 'Loading…',
+ clearable,
+ renderOption,
+ startIcon,
+ name,
+ open: openProp,
+ defaultOpen = false,
+ onOpenChange,
+ side = 'bottom',
+ className,
+ inputClassName,
+ ...props
+}: ComboboxProps) {
+ const empty = (multiple ? [] : null) as SelectValue
+ const [value, setValue] = useControllableState>(
+ valueProp,
+ defaultValue ?? empty,
+ onValueChange,
+ )
+ const [open, setOpen] = useControllableState(openProp, defaultOpen, onOpenChange)
+ // Labels of chosen options, so chips keep their text when async results change.
+ const [known, setKnown] = useState>({})
+
+ const toOption = (v: string): SelectOption =>
+ options.find((o) => o.value === v) ?? { value: v, label: known[v] ?? v }
+ const selectedValues: string[] = Array.isArray(value) ? value : value != null ? [value] : []
+ const selectedOptions = selectedValues.map(toOption)
+ const selected = new Set(selectedValues)
+ const grouped = hasGroups(options)
+ const invalid = error != null && error !== false && error !== ''
+
+ function handleValueChange(next: SelectOption | SelectOption[] | null) {
+ const list = Array.isArray(next) ? next : next ? [next] : []
+ setKnown((prev) => ({ ...prev, ...Object.fromEntries(list.map((o) => [o.value, o.label])) }))
+ setValue((Array.isArray(next) ? next.map((o) => o.value) : (next?.value ?? null)) as SelectValue)
+ }
+
+ const input = (
+ 0 ? undefined : placeholder}
+ aria-invalid={invalid || undefined}
+ aria-busy={loading || undefined}
+ className={cn(
+ 'min-w-0 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-muted disabled:cursor-not-allowed',
+ multiple ? cn('min-w-16 px-1', CHIP_INPUT_HEIGHT[size]) : cn('h-full', controlPaddingX[size]),
+ !multiple && startIcon != null && 'pl-2',
+ inputClassName,
+ )}
+ {...props}
+ />
+ )
+
+ return (
+
+ handleValueChange(next as SelectOption | SelectOption[] | null)}
+ isItemEqualToValue={(a: SelectOption, b: SelectOption) => a?.value === b?.value}
+ onInputValueChange={onInputValueChange ? (text) => onInputValueChange(text) : undefined}
+ filter={filterOptions ? undefined : null}
+ open={open}
+ onOpenChange={setOpen}
+ name={name}
+ required={required}
+ disabled={disabled}
+ readOnly={readOnly}
+ >
+
+ {startIcon != null && (
+
+ {startIcon}
+
+ )}
+ {multiple ? (
+
+ {selectedOptions.map((option) => (
+
+ {option.label}
+
+
+
+
+ ))}
+ {input}
+
+ ) : (
+ input
+ )}
+
+ {loading && (
+
+
+
+ )}
+ {clearable && !readOnly && (
+
+
+
+ )}
+
+
+
+
+
+
+
+
+ {loading && {loadingText} }
+ {!loading && {emptyText} }
+ selected.has(v)}
+ renderOption={renderOption}
+ />
+
+
+
+
+
+ )
+}
diff --git a/src/components/Dialog.stories.tsx b/src/components/Dialog.stories.tsx
new file mode 100644
index 0000000..c470db2
--- /dev/null
+++ b/src/components/Dialog.stories.tsx
@@ -0,0 +1,278 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Mail, UserPlus } from 'lucide-react'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { Button } from './Button'
+import { Dialog } from './Dialog'
+import { DIALOG_SIZES_LIST } from './dialog.tokens'
+import { Input } from './Input'
+
+/** Open stories render in their own frame on the docs page, so their backdrops don't cover it. */
+const ownFrame = (height = 620) => ({ docs: { story: { inline: false, iframeHeight: height } } })
+
+const footer = (
+ <>
+ }>Cancel
+ Save changes
+ >
+)
+
+const meta = {
+ title: 'Overlays/Dialog',
+ component: Dialog,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A modal dialog on Base UI Dialog: backdrop, focus trap, focus return to the trigger, Escape and outside click to close, and a scrolling body with a fixed header and footer. Pass `trigger`, `title`, `description`, `children` and `footer` for the common case, or compose `Dialog.Root`, `Dialog.Trigger`, `Dialog.Content`, `Dialog.Header`, `Dialog.Title`, `Dialog.Description`, `Dialog.Body`, `Dialog.Footer` and `Dialog.Close` for custom layouts. `Modal` is an alias.',
+ },
+ },
+ },
+ argTypes: {
+ title: { control: 'text' },
+ description: { control: 'text' },
+ size: { control: 'inline-radio', options: DIALOG_SIZES_LIST, table: { defaultValue: { summary: 'md' } } },
+ open: { control: 'boolean' },
+ defaultOpen: { control: 'boolean' },
+ closeOnOutsideClick: { control: 'boolean', table: { defaultValue: { summary: 'true' } } },
+ hideCloseButton: { control: 'boolean' },
+ modal: { control: 'boolean', table: { defaultValue: { summary: 'true' } } },
+ 'aria-label': { control: 'text' },
+ className: { control: 'text' },
+ children: { control: 'text' },
+ trigger: { control: false },
+ footer: { control: false },
+ onOpenChange: { control: false },
+ },
+ args: {
+ title: 'Edit workspace',
+ description: 'Changes apply to everyone in Acme Corporation.',
+ size: 'md',
+ closeOnOutsideClick: true,
+ hideCloseButton: false,
+ modal: true,
+ children:
+ 'Workspace settings control the name, time zone and default currency that new projects use. Existing projects keep their current settings.',
+ trigger: Edit workspace ,
+ footer,
+ onOpenChange: fn(),
+ },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Open: Story = {
+ args: { defaultOpen: true },
+ parameters: ownFrame(),
+}
+
+export const Sizes: Story = {
+ parameters: { docs: { description: { story: '`sm` 384px, `md` 512px, `lg` 672px, `xl` 896px, `full` fills the screen.' } } },
+ render: (args) => (
+
+ {DIALOG_SIZES_LIST.map((size) => (
+
+ Open {size}
+
+ }
+ />
+ ))}
+
+ ),
+}
+
+export const Small: Story = {
+ args: {
+ defaultOpen: true,
+ size: 'sm',
+ title: 'Rename file',
+ description: undefined,
+ children: ,
+ footer: (
+ <>
+ }>Cancel
+ Rename
+ >
+ ),
+ },
+ parameters: ownFrame(),
+}
+
+export const Large: Story = {
+ args: { defaultOpen: true, size: 'lg' },
+ parameters: ownFrame(),
+}
+
+export const ExtraLarge: Story = {
+ args: { defaultOpen: true, size: 'xl' },
+ parameters: ownFrame(),
+}
+
+export const FullScreen: Story = {
+ args: { defaultOpen: true, size: 'full', title: 'Preview report' },
+ parameters: ownFrame(),
+}
+
+const paragraphs = [
+ 'These terms govern your use of the Acme Corporation workspace, including every project, file and integration created in it.',
+ 'You keep ownership of the content you upload. You grant Acme Corporation a limited licence to store, process and display it so the service can work.',
+ 'Workspace admins can invite and remove members, change roles and export data at any time from the settings page.',
+ 'We back up workspace data every day and keep backups for 30 days. Deleted projects can be restored by an admin within that period.',
+ 'Integrations you connect can read the data you allow them to. Review their permissions before you connect them, and remove any you no longer use.',
+ 'Usage is billed monthly per active member. A member is active if they signed in at least once during the billing period.',
+ 'We may update these terms. When we do, we will tell workspace admins by email at least 30 days before the change takes effect.',
+ 'If you have questions about these terms, contact support at name@example.com.',
+]
+
+export const LongContent: Story = {
+ args: {
+ defaultOpen: true,
+ title: 'Terms of service',
+ description: 'Last updated 1 September 2026.',
+ children: (
+
+ {[...paragraphs, ...paragraphs].map((text, index) => (
+
+ {text}
+
+ ))}
+
+ ),
+ footer: (
+ <>
+ }>Decline
+ }>Accept
+ >
+ ),
+ },
+ parameters: {
+ ...ownFrame(),
+ docs: {
+ ...ownFrame().docs,
+ description: { story: 'Only the body scrolls; the title and the actions stay in view. The body becomes focusable so keyboard users can scroll it.' },
+ },
+ },
+}
+
+export const WithForm: Story = {
+ args: {
+ defaultOpen: true,
+ title: 'Invite a teammate',
+ description: 'They get an email with a link to join Acme Corporation.',
+ size: 'sm',
+ children: (
+
+ ),
+ footer: (
+ <>
+ }>Cancel
+ }>
+ Send invite
+
+ >
+ ),
+ },
+ parameters: {
+ ...ownFrame(680),
+ docs: {
+ ...ownFrame(680).docs,
+ description: { story: 'Focus starts in the first field. The footer button submits the form through its `form` attribute.' },
+ },
+ },
+}
+
+export const NoCloseButton: Story = {
+ args: { defaultOpen: true, hideCloseButton: true, closeOnOutsideClick: false, title: 'Session expiring' , description: 'You will be signed out in 2 minutes.', children: 'Save your work, or stay signed in to keep editing.', footer: (
+ <>
+ }>Sign out
+ }>Stay signed in
+ >
+ ) },
+ parameters: ownFrame(),
+}
+
+export const Controlled: Story = {
+ parameters: { docs: { description: { story: 'Control `open` to open the dialog from anywhere, for example after a menu choice or a save.' } } },
+ render: function Render(args) {
+ const [open, setOpen] = useState(false)
+ return (
+
+ setOpen(true)}>Open from state
+ open: {String(open)}
+ {
+ setOpen(next)
+ args.onOpenChange?.(next)
+ }}
+ footer={
+ <>
+ setOpen(false)}>
+ Cancel
+
+ setOpen(false)}>Save changes
+ >
+ }
+ />
+
+ )
+ },
+}
+
+export const CustomLayout: Story = {
+ parameters: {
+ ...ownFrame(),
+ docs: { ...ownFrame().docs, description: { story: 'Compound parts for a layout the props don’t cover.' } },
+ },
+ render: () => (
+
+ Upgrade plan} />
+
+
+
Team plan
+
+ $12 / member / month
+
+
+
+ Upgrade to Team
+ Unlimited projects, shared templates and priority support.
+
+
+
+ {['Unlimited projects', 'Shared templates', 'Audit log', 'Priority support'].map((feature) => (
+
+
+ {feature}
+
+ ))}
+
+
+
+ }>Not now
+ Upgrade
+
+
+
+ ),
+}
diff --git a/src/components/Dialog.test.tsx b/src/components/Dialog.test.tsx
new file mode 100644
index 0000000..e768b72
--- /dev/null
+++ b/src/components/Dialog.test.tsx
@@ -0,0 +1,94 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Button } from './Button'
+import { Dialog, Modal } from './Dialog'
+import { Input } from './Input'
+
+function Example(props: Partial>) {
+ return (
+ Edit profile}
+ title="Edit profile"
+ description="Changes are visible to your team."
+ footer={
+ <>
+ }>Cancel
+ Save
+ >
+ }
+ {...props}
+ >
+
+
+ )
+}
+
+describe('Dialog', () => {
+ it('opens from the trigger as a named dialog', async () => {
+ render( )
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ await userEvent.click(screen.getByRole('button', { name: 'Edit profile' }))
+ const dialog = await screen.findByRole('dialog', { name: 'Edit profile' })
+ expect(dialog).toHaveAccessibleDescription('Changes are visible to your team.')
+ expect(screen.getByRole('textbox', { name: 'Full name' })).toBeInTheDocument()
+ })
+
+ it('closes on Escape and returns focus to the trigger', async () => {
+ render( )
+ const trigger = screen.getByRole('button', { name: 'Edit profile' })
+ await userEvent.click(trigger)
+ await screen.findByRole('dialog')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await waitFor(() => expect(trigger).toHaveFocus())
+ })
+
+ it('moves focus inside and has a labelled close button', async () => {
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Edit profile' }))
+ const dialog = await screen.findByRole('dialog')
+ await waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement))
+ await userEvent.click(screen.getByRole('button', { name: 'Close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ })
+
+ it('hides the close button on request', async () => {
+ render( )
+ await screen.findByRole('dialog')
+ expect(screen.queryByRole('button', { name: 'Close' })).not.toBeInTheDocument()
+ })
+
+ it('works controlled', async () => {
+ const onOpenChange = vi.fn()
+ const { rerender } = render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Edit profile' }))
+ expect(onOpenChange).toHaveBeenCalledWith(true)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ rerender( )
+ expect(await screen.findByRole('dialog')).toBeInTheDocument()
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(onOpenChange).toHaveBeenLastCalledWith(false)
+ })
+
+ it('builds a custom layout from compound parts, and Modal is an alias', async () => {
+ render(
+
+
+
+ Invite people
+
+ Body text
+
+ ,
+ )
+ expect(await screen.findByRole('dialog', { name: 'Invite people' })).toHaveTextContent('Body text')
+ })
+
+ it('has no axe violations when open', async () => {
+ render( )
+ await screen.findByRole('dialog')
+ await expectNoA11yViolations(document.body)
+ })
+})
diff --git a/src/components/Dialog.tsx b/src/components/Dialog.tsx
new file mode 100644
index 0000000..45dd091
--- /dev/null
+++ b/src/components/Dialog.tsx
@@ -0,0 +1,245 @@
+import { Dialog as BaseDialog } from '@base-ui/react/dialog'
+import { X } from 'lucide-react'
+import {
+ useCallback,
+ useEffect,
+ useState,
+ type ComponentProps,
+ type ReactElement,
+ type ReactNode,
+} from 'react'
+import { cn } from '../lib/cn'
+import { focusRing } from '../lib/styles'
+import { IconButton } from './Button'
+import {
+ DIALOG_SIZES,
+ backdropClass,
+ dialogDescriptionClass,
+ dialogPanelClass,
+ dialogTitleClass,
+ type DialogSize,
+} from './dialog.tokens'
+
+type OpenProps = {
+ /** Controlled open state. Pair with `onOpenChange`. */
+ open?: boolean
+ /** Initial open state when uncontrolled. */
+ defaultOpen?: boolean
+ /** Fires with the next open state: trigger press, Escape, outside click or a close button. */
+ onOpenChange?: (open: boolean) => void
+}
+
+export type DialogRootProps = OpenProps & {
+ /** Close when the backdrop is clicked. Escape always closes. */
+ closeOnOutsideClick?: boolean
+ /** `false` lets the page behind stay interactive; the default traps focus and locks scroll. */
+ modal?: boolean
+ children?: ReactNode
+}
+
+/** Holds the open state. Wrap Trigger and Content in it for a custom layout. */
+function DialogRoot({ closeOnOutsideClick = true, modal = true, onOpenChange, children, ...props }: DialogRootProps) {
+ return (
+ onOpenChange(open) : undefined}
+ >
+ {children}
+
+ )
+}
+
+/**
+ * Opens the dialog. Pass your button as `render` (`Edit} />`)
+ * so it keeps the Tansy styles.
+ */
+function DialogTrigger(props: BaseDialog.Trigger.Props) {
+ return
+}
+
+export type DialogContentProps = Omit & {
+ /** Panel width. `full` fills the screen. */
+ size?: DialogSize
+ /** Hide the × button in the corner. Escape still closes. */
+ hideCloseButton?: boolean
+ className?: string
+}
+
+/** Portal, backdrop and the panel. Put Header, Body and Footer inside. */
+function DialogContent({ size = 'md', hideCloseButton = false, className, children, ...props }: DialogContentProps) {
+ return (
+
+
+
+
+ {children}
+ {!hideCloseButton && (
+ } />}
+ className="absolute right-3 top-3 sm:right-4 sm:top-4"
+ />
+ )}
+
+
+
+ )
+}
+
+/** Title and description block at the top. It stays put while the body scrolls. */
+export function DialogHeader({ className, ...props }: ComponentProps<'div'>) {
+ return
+}
+
+/** The dialog's accessible name. Renders an ``. */
+function DialogTitle({ className, ...props }: Omit & { className?: string }) {
+ return
+}
+
+/** Supporting text, announced with the title. */
+function DialogDescription({
+ className,
+ ...props
+}: Omit & { className?: string }) {
+ return
+}
+
+/**
+ * The scrolling middle of a dialog or drawer. When its content overflows it
+ * becomes keyboard-focusable (so it can be scrolled without a mouse) and
+ * draws a rule under the header.
+ */
+export function DialogBody({ className, ref, ...props }: ComponentProps<'div'>) {
+ const [node, setNode] = useState(null)
+ const [scrollable, setScrollable] = useState(false)
+
+ const setRefs = useCallback(
+ (element: HTMLDivElement | null) => {
+ setNode(element)
+ if (typeof ref === 'function') ref(element)
+ else if (ref) ref.current = element
+ },
+ [ref],
+ )
+
+ useEffect(() => {
+ if (!node) return
+ const measure = () => setScrollable(node.scrollHeight > node.clientHeight + 1)
+ measure()
+ const observer = new ResizeObserver(measure)
+ observer.observe(node)
+ for (const child of Array.from(node.children)) observer.observe(child)
+ return () => observer.disconnect()
+ }, [node])
+
+ return (
+
+ )
+}
+
+/** Actions at the bottom, right-aligned. Stacks full-width on phones, primary action on top. */
+export function DialogFooter({ className, ...props }: ComponentProps<'div'>) {
+ return (
+
+ )
+}
+
+/** Closes the dialog. Pass a Button as `render`. */
+function DialogClose(props: BaseDialog.Close.Props) {
+ return
+}
+
+export type DialogProps = DialogRootProps & {
+ /** Element that opens the dialog, usually a ``. Leave out when you control `open` yourself. */
+ trigger?: ReactElement
+ /** Heading; also the dialog's accessible name. */
+ title?: ReactNode
+ /** Supporting text under the title. */
+ description?: ReactNode
+ /** Panel width. `full` fills the screen. */
+ size?: DialogSize
+ /** Action buttons, shown in a bar under the body. */
+ footer?: ReactNode
+ /** Hide the × button in the corner. Escape still closes. */
+ hideCloseButton?: boolean
+ /** Accessible name when there is no `title`. */
+ 'aria-label'?: string
+ /** Classes for the panel. */
+ className?: string
+ /** The body. Scrolls when it's taller than the screen; header and footer stay visible. */
+ children?: ReactNode
+}
+
+/**
+ * A modal dialog (Base UI Dialog). Pass `title`, `children` and `footer` for
+ * the common case, or build a custom layout from `Dialog.Root`,
+ * `Dialog.Trigger`, `Dialog.Content`, `Dialog.Header`, `Dialog.Title`,
+ * `Dialog.Description`, `Dialog.Body`, `Dialog.Footer` and `Dialog.Close`.
+ */
+function DialogComponent({
+ trigger,
+ title,
+ description,
+ size = 'md',
+ footer,
+ hideCloseButton,
+ className,
+ children,
+ 'aria-label': ariaLabel,
+ ...rootProps
+}: DialogProps) {
+ return (
+
+ {trigger && }
+
+ {(title != null || description != null) && (
+
+ {title != null && {title} }
+ {description != null && {description} }
+
+ )}
+ {children != null && {children} }
+ {footer != null && {footer} }
+
+
+ )
+}
+
+export const Dialog = Object.assign(DialogComponent, {
+ Root: DialogRoot,
+ Trigger: DialogTrigger,
+ Content: DialogContent,
+ Header: DialogHeader,
+ Title: DialogTitle,
+ Description: DialogDescription,
+ Body: DialogBody,
+ Footer: DialogFooter,
+ Close: DialogClose,
+})
+
+/** Alias of `Dialog`, for teams that call it a modal. */
+export const Modal = Dialog
diff --git a/src/components/Drawer.stories.tsx b/src/components/Drawer.stories.tsx
new file mode 100644
index 0000000..9976ff6
--- /dev/null
+++ b/src/components/Drawer.stories.tsx
@@ -0,0 +1,213 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Filter, Search } from 'lucide-react'
+import { fn } from 'storybook/test'
+import { Button } from './Button'
+import { DRAWER_SIDES, DRAWER_SIZES_LIST } from './dialog.tokens'
+import { Drawer } from './Drawer'
+import { Input } from './Input'
+
+const ownFrame = (height = 620) => ({ docs: { story: { inline: false, iframeHeight: height } } })
+
+const activity = [
+ ['Jane Doe', 'changed the project owner', '2 minutes ago'],
+ ['John Smith', 'uploaded Brand guidelines.pdf', '1 hour ago'],
+ ['Alex Kim', 'commented on Homepage hero', '3 hours ago'],
+ ['Jane Doe', 'invited name@example.com', 'Yesterday'],
+ ['Dana Brooks', 'archived Old landing page', 'Yesterday'],
+ ['John Smith', 'renamed the project to Acme Website', '2 days ago'],
+]
+
+const ActivityList = ({ repeat = 1 }: { repeat?: number }) => (
+
+ {Array.from({ length: repeat }, () => activity)
+ .flat()
+ .map(([who, what, when], index) => (
+
+
+ {who} {what}
+
+ {when}
+
+ ))}
+
+)
+
+const footer = (
+ <>
+ }>Cancel
+ Apply filters
+ >
+)
+
+const meta = {
+ title: 'Overlays/Drawer',
+ component: Drawer,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A panel that slides in from an edge, on Base UI Drawer: modal, with focus trap, focus return, Escape, backdrop click and swipe to dismiss on touch screens. Use it for filters, record details and secondary forms that shouldn’t leave the page. `Sheet` is an alias.',
+ },
+ },
+ },
+ argTypes: {
+ side: { control: 'inline-radio', options: DRAWER_SIDES, table: { defaultValue: { summary: 'right' } } },
+ size: { control: 'inline-radio', options: DRAWER_SIZES_LIST, table: { defaultValue: { summary: 'md' } } },
+ title: { control: 'text' },
+ description: { control: 'text' },
+ open: { control: 'boolean' },
+ defaultOpen: { control: 'boolean' },
+ hideCloseButton: { control: 'boolean' },
+ closeOnOutsideClick: { control: 'boolean', table: { defaultValue: { summary: 'true' } } },
+ 'aria-label': { control: 'text' },
+ className: { control: 'text' },
+ trigger: { control: false },
+ footer: { control: false },
+ children: { control: false },
+ onOpenChange: { control: false },
+ },
+ args: {
+ side: 'right',
+ size: 'md',
+ title: 'Recent activity',
+ description: 'Everything that happened in Acme Website this week.',
+ hideCloseButton: false,
+ closeOnOutsideClick: true,
+ trigger: Show activity ,
+ children: ,
+ onOpenChange: fn(),
+ },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Right: Story = {
+ args: { defaultOpen: true, side: 'right' },
+ parameters: ownFrame(),
+}
+
+export const Left: Story = {
+ args: {
+ defaultOpen: true,
+ side: 'left',
+ size: 'sm',
+ title: 'Acme Corporation',
+ description: undefined,
+ children: (
+
+
+ {['Dashboard', 'Projects', 'Team', 'Billing', 'Settings'].map((item, index) => (
+
+
+ {item}
+
+
+ ))}
+
+
+ ),
+ },
+ parameters: ownFrame(),
+}
+
+export const Top: Story = {
+ args: {
+ defaultOpen: true,
+ side: 'top',
+ size: 'sm',
+ title: 'Search',
+ description: undefined,
+ children: } />,
+ },
+ parameters: ownFrame(),
+}
+
+export const Bottom: Story = {
+ args: {
+ defaultOpen: true,
+ side: 'bottom',
+ title: 'Share project',
+ description: 'Anyone in Acme Corporation with the link can view.',
+ children: (
+
+
+ Send invite
+
+ ),
+ },
+ parameters: ownFrame(),
+}
+
+export const WithFooter: Story = {
+ args: {
+ defaultOpen: true,
+ title: 'Filter employees',
+ description: 'Show only the people who match.',
+ footer,
+ children: (
+
+
+
+
+
+ ),
+ trigger: (
+ }>
+ Filters
+
+ ),
+ },
+ parameters: ownFrame(),
+}
+
+export const LongContent: Story = {
+ args: { defaultOpen: true, children: , footer: Load more },
+ parameters: ownFrame(),
+}
+
+export const Sides: Story = {
+ render: (args) => (
+
+ {DRAWER_SIDES.map((side) => (
+
+ From {side}
+
+ }
+ />
+ ))}
+
+ ),
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {DRAWER_SIZES_LIST.map((size) => (
+
+ Size {size}
+
+ }
+ />
+ ))}
+
+ ),
+}
diff --git a/src/components/Drawer.test.tsx b/src/components/Drawer.test.tsx
new file mode 100644
index 0000000..ac8287e
--- /dev/null
+++ b/src/components/Drawer.test.tsx
@@ -0,0 +1,55 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Button } from './Button'
+import { Drawer, Sheet } from './Drawer'
+
+function Example(props: Partial>) {
+ return (
+ Filters}
+ title="Filter employees"
+ description="Narrow the list by team and status."
+ footer={Apply }
+ {...props}
+ >
+ Team, status and location filters.
+
+ )
+}
+
+describe('Drawer', () => {
+ it('opens from the trigger as a named dialog', async () => {
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Filters' }))
+ const dialog = await screen.findByRole('dialog', { name: 'Filter employees' })
+ expect(dialog).toHaveAccessibleDescription('Narrow the list by team and status.')
+ expect(dialog).toHaveTextContent('Team, status and location filters.')
+ })
+
+ it('closes on Escape and returns focus to the trigger', async () => {
+ const onOpenChange = vi.fn()
+ render( )
+ const trigger = screen.getByRole('button', { name: 'Filters' })
+ await userEvent.click(trigger)
+ await screen.findByRole('dialog')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(onOpenChange).toHaveBeenLastCalledWith(false)
+ await waitFor(() => expect(trigger).toHaveFocus())
+ })
+
+ it('closes from the labelled close button', async () => {
+ render( )
+ await screen.findByRole('dialog', { name: 'Details' })
+ await userEvent.click(screen.getByRole('button', { name: 'Close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ })
+
+ it('has no axe violations when open', async () => {
+ render( )
+ await screen.findByRole('dialog')
+ await expectNoA11yViolations(document.body)
+ })
+})
diff --git a/src/components/Drawer.tsx b/src/components/Drawer.tsx
new file mode 100644
index 0000000..46cef98
--- /dev/null
+++ b/src/components/Drawer.tsx
@@ -0,0 +1,138 @@
+import { Drawer as BaseDrawer } from '@base-ui/react/drawer'
+import { X } from 'lucide-react'
+import type { ReactElement, ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { IconButton } from './Button'
+import { DialogBody, DialogFooter, DialogHeader } from './Dialog'
+import {
+ DRAWER_HEIGHTS,
+ DRAWER_PANEL,
+ DRAWER_SWIPE,
+ DRAWER_VIEWPORT,
+ DRAWER_WIDTHS,
+ backdropClass,
+ dialogDescriptionClass,
+ dialogTitleClass,
+ type DrawerSide,
+ type DrawerSize,
+} from './dialog.tokens'
+
+export type DrawerProps = {
+ /** Controlled open state. Pair with `onOpenChange`. */
+ open?: boolean
+ /** Initial open state when uncontrolled. */
+ defaultOpen?: boolean
+ /** Fires with the next open state. */
+ onOpenChange?: (open: boolean) => void
+ /** Element that opens the drawer, usually a ``. */
+ trigger?: ReactElement
+ /** The edge it slides in from. Swiping towards that edge dismisses it on touch screens. */
+ side?: DrawerSide
+ /** Width for `left`/`right`, maximum height for `top`/`bottom`. `full` covers the screen. */
+ size?: DrawerSize
+ /** Heading; also the drawer's accessible name. */
+ title?: ReactNode
+ /** Supporting text under the title. */
+ description?: ReactNode
+ /** Action buttons, pinned to the bottom. */
+ footer?: ReactNode
+ /** Hide the × button. Escape, swipe and the backdrop still close it. */
+ hideCloseButton?: boolean
+ /** Close when the backdrop is clicked. */
+ closeOnOutsideClick?: boolean
+ /** Accessible name when there is no `title`. */
+ 'aria-label'?: string
+ /** Classes for the panel. */
+ className?: string
+ /** The body. It scrolls; header and footer stay put. */
+ children?: ReactNode
+}
+
+/**
+ * A panel that slides in from an edge of the screen (Base UI Drawer): for
+ * filters, details and secondary forms. Modal, with focus trap, focus return
+ * and swipe to dismiss.
+ */
+function DrawerComponent({
+ open,
+ defaultOpen,
+ onOpenChange,
+ trigger,
+ side = 'right',
+ size = 'md',
+ title,
+ description,
+ footer,
+ hideCloseButton = false,
+ closeOnOutsideClick = true,
+ 'aria-label': ariaLabel,
+ className,
+ children,
+}: DrawerProps) {
+ const vertical = side === 'top' || side === 'bottom'
+
+ return (
+ onOpenChange(next) : undefined}
+ swipeDirection={DRAWER_SWIPE[side]}
+ disablePointerDismissal={!closeOnOutsideClick}
+ >
+ {trigger && }
+
+
+
+
+ {side === 'bottom' && size !== 'full' && (
+
+ )}
+
+ {(title != null || description != null) && (
+
+ {title != null && {title} }
+ {description != null && (
+ {description}
+ )}
+
+ )}
+ {children != null && {children} }
+ {footer != null && {footer} }
+
+ {!hideCloseButton && (
+ } />}
+ className={cn('absolute right-3 sm:right-4', side === 'bottom' && size !== 'full' ? 'top-5 sm:top-6' : 'top-3 sm:top-4')}
+ />
+ )}
+
+
+
+
+ )
+}
+
+/** Closes the drawer. Pass a Button as `render`: `Cancel } />`. */
+function DrawerClose(props: BaseDrawer.Close.Props) {
+ return
+}
+
+export const Drawer = Object.assign(DrawerComponent, { Close: DrawerClose })
+
+/** Alias of `Drawer`. */
+export const Sheet = Drawer
diff --git a/src/components/DropdownMenu.stories.tsx b/src/components/DropdownMenu.stories.tsx
new file mode 100644
index 0000000..af07bfa
--- /dev/null
+++ b/src/components/DropdownMenu.stories.tsx
@@ -0,0 +1,242 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import {
+ Archive,
+ ChevronDown,
+ Copy,
+ Download,
+ FolderInput,
+ LogOut,
+ MoreHorizontal,
+ Pencil,
+ Settings,
+ Share2,
+ Trash2,
+ User,
+ Users,
+} from 'lucide-react'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { Button, IconButton } from './Button'
+import { DropdownMenu } from './DropdownMenu'
+import type { DropdownMenuItemData } from './dropdown-menu.tokens'
+import { POPUP_ALIGNS, POPUP_SIDES } from './popover.tokens'
+
+const ownFrame = (height = 460) => ({ docs: { story: { inline: false, iframeHeight: height } } })
+
+const projectItems: DropdownMenuItemData[] = [
+ { type: 'label', label: 'Project' },
+ { label: 'Rename', icon: , shortcut: '⌘R', onSelect: fn() },
+ { label: 'Duplicate', icon: , shortcut: '⌘D', onSelect: fn() },
+ { label: 'Share', icon: , shortcut: '⇧⌘S', onSelect: fn() },
+ {
+ type: 'submenu',
+ label: 'Move to',
+ icon: ,
+ items: [
+ { label: 'Design', onSelect: fn() },
+ { label: 'Marketing', onSelect: fn() },
+ { label: 'Engineering', onSelect: fn() },
+ { type: 'separator' },
+ { label: 'New folder…', onSelect: fn() },
+ ],
+ },
+ { label: 'Download', icon: , disabled: true },
+ { type: 'separator' },
+ { label: 'Archive', icon: , onSelect: fn() },
+ { label: 'Delete', icon: , shortcut: '⌫', color: 'danger', onSelect: fn() },
+]
+
+const viewItems: DropdownMenuItemData[] = [
+ { type: 'label', label: 'Show' },
+ { type: 'checkbox', label: 'Status bar', defaultChecked: true, shortcut: '⌘/' },
+ { type: 'checkbox', label: 'Activity panel' },
+ { type: 'checkbox', label: 'Archived projects', disabled: true },
+ { type: 'separator' },
+ {
+ type: 'radio',
+ label: 'Sort by',
+ defaultValue: 'updated',
+ items: [
+ { value: 'name', label: 'Name' },
+ { value: 'updated', label: 'Last updated' },
+ { value: 'created', label: 'Date created' },
+ ],
+ },
+]
+
+const meta = {
+ title: 'Overlays/DropdownMenu',
+ component: DropdownMenu,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'A menu of actions and settings on Base UI Menu. Pass `items` as data (`item`, `checkbox`, `radio`, `separator`, `label`, `submenu`), or compose `DropdownMenu.Root`, `Trigger`, `Content`, `Item`, `CheckboxItem`, `RadioGroup`, `RadioItem`, `Separator`, `Group`, `Label`, `Sub`, `SubTrigger` and `SubContent`. Arrow keys move, Enter or Space chooses, typing jumps to a matching item, ArrowRight opens a submenu and Escape closes, returning focus to the trigger. Shortcuts are display only.',
+ },
+ },
+ },
+ argTypes: {
+ side: { control: 'inline-radio', options: POPUP_SIDES, table: { defaultValue: { summary: 'bottom' } } },
+ align: { control: 'inline-radio', options: POPUP_ALIGNS, table: { defaultValue: { summary: 'start' } } },
+ sideOffset: { control: { type: 'number', min: 0, max: 24 }, table: { defaultValue: { summary: '6' } } },
+ open: { control: 'boolean' },
+ defaultOpen: { control: 'boolean' },
+ modal: { control: 'boolean', table: { defaultValue: { summary: 'true' } } },
+ className: { control: 'text' },
+ items: { control: 'object' },
+ trigger: { control: false },
+ children: { control: false },
+ onOpenChange: { control: false },
+ },
+ args: {
+ side: 'bottom',
+ align: 'start',
+ sideOffset: 6,
+ modal: true,
+ items: projectItems,
+ trigger: (
+ }>
+ Actions
+
+ ),
+ onOpenChange: fn(),
+ },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Open: Story = {
+ args: { defaultOpen: true },
+ parameters: {
+ ...ownFrame(),
+ docs: { ...ownFrame().docs, description: { story: 'Icons, shortcuts, a label, a submenu, a disabled item and a danger item.' } },
+ },
+}
+
+export const CheckboxAndRadio: Story = {
+ args: {
+ defaultOpen: true,
+ items: viewItems,
+ trigger: (
+ }>
+ View
+
+ ),
+ },
+ parameters: {
+ ...ownFrame(),
+ docs: { ...ownFrame().docs, description: { story: 'Checkbox and radio items keep the menu open, so several can be changed in a row.' } },
+ },
+}
+
+export const IconTrigger: Story = {
+ args: {
+ defaultOpen: true,
+ align: 'end',
+ trigger: } />,
+ },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+ parameters: ownFrame(),
+}
+
+export const OpenSubmenu: Story = {
+ parameters: {
+ ...ownFrame(),
+ docs: { ...ownFrame().docs, description: { story: 'Built from compound parts, with the submenu open.' } },
+ },
+ render: () => (
+
+ } endIcon={ }>
+ Jane Doe
+
+ }
+ />
+
+
+ name@example.com
+ } shortcut="⇧⌘P">
+ Profile
+
+ } shortcut="⌘,">
+ Settings
+
+
+
+ }>Switch workspace
+
+
+ Acme Corporation
+ Globex Studio
+ Initech Labs
+
+
+
+
+ } color="danger">
+ Sign out
+
+
+
+ ),
+}
+
+export const Controlled: Story = {
+ render: function Render(args) {
+ const [compact, setCompact] = useState(false)
+ const [density, setDensity] = useState('comfortable')
+ return (
+
+
}>
+ Display
+
+ }
+ />
+
+ compact sidebar: {String(compact)}, density: {density}
+
+
+ )
+ },
+}
+
+export const Placement: Story = {
+ args: { side: 'right', align: 'start', defaultOpen: true, items: projectItems.slice(1, 4) },
+ parameters: ownFrame(),
+}
diff --git a/src/components/DropdownMenu.test.tsx b/src/components/DropdownMenu.test.tsx
new file mode 100644
index 0000000..54aa00a
--- /dev/null
+++ b/src/components/DropdownMenu.test.tsx
@@ -0,0 +1,128 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Button } from './Button'
+import { DropdownMenu } from './DropdownMenu'
+import type { DropdownMenuItemData } from './dropdown-menu.tokens'
+
+function items(overrides: Partial void>> = {}): DropdownMenuItemData[] {
+ return [
+ { label: 'Edit', shortcut: '⌘E', onSelect: overrides.edit },
+ { label: 'Duplicate', onSelect: overrides.duplicate },
+ { type: 'separator' },
+ { type: 'checkbox', label: 'Show archived', defaultChecked: false },
+ { type: 'radio', label: 'Sort by', defaultValue: 'name', items: [{ value: 'name', label: 'Name' }, { value: 'date', label: 'Date' }] },
+ { type: 'separator' },
+ { label: 'Delete', color: 'danger', onSelect: overrides.remove },
+ ]
+}
+
+describe('DropdownMenu', () => {
+ it('opens from the trigger as a menu', async () => {
+ render(Actions} items={items()} />)
+ const trigger = screen.getByRole('button', { name: 'Actions' })
+ expect(trigger).toHaveAttribute('aria-haspopup', 'menu')
+ await userEvent.click(trigger)
+ const menu = await screen.findByRole('menu')
+ expect(menu).toHaveAccessibleName('Actions')
+ expect(screen.getByRole('menuitem', { name: /Edit/ })).toHaveTextContent('⌘E')
+ expect(screen.getByRole('menuitem', { name: /Edit/ }).querySelector('kbd')).toHaveTextContent('⌘E')
+ })
+
+ it('moves with ArrowDown and runs onSelect on Enter', async () => {
+ const duplicate = vi.fn()
+ render(Actions} items={items({ duplicate })} />)
+ screen.getByRole('button', { name: 'Actions' }).focus()
+ await userEvent.keyboard('{Enter}')
+ await screen.findByRole('menu')
+ await waitFor(() => expect(screen.getByRole('menuitem', { name: /Edit/ })).toHaveFocus())
+ await userEvent.keyboard('{ArrowDown}')
+ expect(screen.getByRole('menuitem', { name: 'Duplicate' })).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ expect(duplicate).toHaveBeenCalledOnce()
+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument())
+ })
+
+ it('runs onSelect on click', async () => {
+ const remove = vi.fn()
+ render(Actions} items={items({ remove })} />)
+ await userEvent.click(screen.getByRole('button', { name: 'Actions' }))
+ await userEvent.click(await screen.findByRole('menuitem', { name: 'Delete' }))
+ expect(remove).toHaveBeenCalledOnce()
+ })
+
+ it('toggles checkbox items and selects radio items', async () => {
+ render(Actions} items={items()} />)
+ await userEvent.click(screen.getByRole('button', { name: 'Actions' }))
+ const checkbox = await screen.findByRole('menuitemcheckbox', { name: 'Show archived' })
+ expect(checkbox).toHaveAttribute('aria-checked', 'false')
+ await userEvent.click(checkbox)
+ expect(checkbox).toHaveAttribute('aria-checked', 'true')
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ const date = screen.getByRole('menuitemradio', { name: 'Date' })
+ await userEvent.click(date)
+ expect(date).toHaveAttribute('aria-checked', 'true')
+ expect(screen.getByRole('menuitemradio', { name: 'Name' })).toHaveAttribute('aria-checked', 'false')
+ })
+
+ it('closes on Escape and returns focus to the trigger', async () => {
+ render(Actions} items={items()} />)
+ const trigger = screen.getByRole('button', { name: 'Actions' })
+ await userEvent.click(trigger)
+ await screen.findByRole('menu')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument())
+ await waitFor(() => expect(trigger).toHaveFocus())
+ })
+
+ it('opens a submenu with ArrowRight', async () => {
+ const onSelect = vi.fn()
+ render(
+ Actions}
+ items={[{ type: 'submenu', label: 'Move to', items: [{ label: 'Design team', onSelect }] }]}
+ />,
+ )
+ await userEvent.click(screen.getByRole('button', { name: 'Actions' }))
+ const sub = await screen.findByRole('menuitem', { name: 'Move to' })
+ expect(sub).toHaveAttribute('aria-haspopup', 'menu')
+ sub.focus()
+ await userEvent.keyboard('{ArrowRight}')
+ await userEvent.click(await screen.findByRole('menuitem', { name: 'Design team' }))
+ expect(onSelect).toHaveBeenCalledOnce()
+ })
+
+ it('builds from compound parts', async () => {
+ const onSelect = vi.fn()
+ render(
+
+ Options} />
+
+
+ Account
+ Profile
+
+
+ Notifications
+
+ ,
+ )
+ expect(await screen.findByRole('group', { name: 'Account' })).toBeInTheDocument()
+ expect(screen.getByRole('menuitemcheckbox', { name: 'Notifications' })).toHaveAttribute('aria-checked', 'true')
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Profile' }))
+ expect(onSelect).toHaveBeenCalledOnce()
+ })
+
+ it('has no axe violations when open', async () => {
+ render(
+ Actions}
+ items={[{ type: 'label', label: 'Project' }, ...items()]}
+ />,
+ )
+ await screen.findByRole('menu')
+ await expectNoA11yViolations(document.body)
+ })
+})
diff --git a/src/components/DropdownMenu.tsx b/src/components/DropdownMenu.tsx
new file mode 100644
index 0000000..4d5567f
--- /dev/null
+++ b/src/components/DropdownMenu.tsx
@@ -0,0 +1,357 @@
+import { Menu as BaseMenu } from '@base-ui/react/menu'
+import { Check, ChevronRight } from 'lucide-react'
+import { Fragment, type ReactElement, type ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { listItem, popupMotion, popupSurface } from '../lib/styles'
+import {
+ menuDangerItem,
+ menuLabel,
+ menuPopupClass,
+ menuShortcut,
+ type DropdownMenuItemData,
+} from './dropdown-menu.tokens'
+import type { PopupAlign, PopupSide } from './popover.tokens'
+
+type OpenProps = {
+ /** Controlled open state. Pair with `onOpenChange`. */
+ open?: boolean
+ /** Initial open state when uncontrolled. */
+ defaultOpen?: boolean
+ /** Fires with the next open state. */
+ onOpenChange?: (open: boolean) => void
+}
+
+export type DropdownMenuRootProps = OpenProps & {
+ /** Lock page scroll and block outside pointer events while open. */
+ modal?: boolean
+ children?: ReactNode
+}
+
+function MenuRoot({ onOpenChange, modal = true, children, ...props }: DropdownMenuRootProps) {
+ return (
+ onOpenChange(open) : undefined}>
+ {children}
+
+ )
+}
+
+/** Opens the menu. Pass your button as `render`: `Actions} />`. */
+function MenuTrigger(props: BaseMenu.Trigger.Props) {
+ return
+}
+
+export type DropdownMenuContentProps = Omit & {
+ /** Preferred side of the trigger. */
+ side?: PopupSide
+ /** Alignment along that side. */
+ align?: PopupAlign
+ /** Gap between trigger and menu, in px. */
+ sideOffset?: number
+ className?: string
+}
+
+/** The floating list. Holds Item, CheckboxItem, RadioGroup, Separator, Group and Sub. */
+function MenuContent({ side = 'bottom', align = 'start', sideOffset = 6, className, ...props }: DropdownMenuContentProps) {
+ return (
+
+
+
+
+
+ )
+}
+
+function ItemIcon({ children }: { children: ReactNode }) {
+ return (
+
+ {children}
+
+ )
+}
+
+function Shortcut({ children }: { children: ReactNode }) {
+ return {children}
+}
+
+export type DropdownMenuItemProps = Omit & {
+ icon?: ReactNode
+ /** Keyboard shortcut shown right-aligned. Display only; bind the keys yourself. */
+ shortcut?: string
+ /** `danger` for destructive actions. */
+ color?: 'danger'
+ /** Runs when the item is chosen by click, Enter or Space. */
+ onSelect?: () => void
+ className?: string
+}
+
+/** An action. The menu closes after it runs. */
+function MenuItem({ icon, shortcut, color, onSelect, onClick, className, children, ...props }: DropdownMenuItemProps) {
+ return (
+ {
+ onClick?.(event)
+ onSelect?.()
+ }}
+ {...props}
+ >
+ {icon != null && {icon} }
+ {children}
+ {shortcut && {shortcut} }
+
+ )
+}
+
+export type DropdownMenuCheckboxItemProps = Omit & {
+ shortcut?: string
+ className?: string
+}
+
+/** A setting that toggles on and off. The menu stays open. */
+function MenuCheckboxItem({ shortcut, className, children, ...props }: DropdownMenuCheckboxItemProps) {
+ return (
+
+
+
+
+
+
+ {children}
+ {shortcut && {shortcut} }
+
+ )
+}
+
+/** Groups RadioItems; only one can be chosen. */
+function MenuRadioGroup(props: BaseMenu.RadioGroup.Props) {
+ return
+}
+
+export type DropdownMenuRadioItemProps = Omit & {
+ icon?: ReactNode
+ className?: string
+}
+
+/** One option in a RadioGroup. */
+function MenuRadioItem({ icon, className, children, ...props }: DropdownMenuRadioItemProps) {
+ return (
+
+
+
+
+ {icon != null && {icon} }
+ {children}
+
+ )
+}
+
+function MenuSeparator({ className, ...props }: Omit & { className?: string }) {
+ return
+}
+
+/** Groups items under a Label. */
+function MenuGroup(props: BaseMenu.Group.Props) {
+ return
+}
+
+/** A heading for a Group or RadioGroup. Must sit inside one of them. */
+function MenuLabel({ className, ...props }: Omit & { className?: string }) {
+ return
+}
+
+/** A nested menu. Holds a SubTrigger and a SubContent. */
+function MenuSub(props: BaseMenu.SubmenuRoot.Props) {
+ return
+}
+
+export type DropdownMenuSubTriggerProps = Omit & {
+ icon?: ReactNode
+ className?: string
+}
+
+/** The item that opens a submenu, on hover, click or ArrowRight. */
+function MenuSubTrigger({ icon, className, children, ...props }: DropdownMenuSubTriggerProps) {
+ return (
+
+ {icon != null && {icon} }
+ {children}
+
+
+ )
+}
+
+/** The submenu's list. */
+function MenuSubContent({ className, ...props }: Omit & { className?: string }) {
+ return (
+
+
+
+
+
+ )
+}
+
+function textOf(label: ReactNode, textValue?: string) {
+ return textValue ?? (typeof label === 'string' ? label : undefined)
+}
+
+function renderItem(item: DropdownMenuItemData, key: string): ReactNode {
+ switch (item.type) {
+ case 'separator':
+ return
+ case 'label':
+ return {item.label}
+ case 'checkbox':
+ return (
+ item.onCheckedChange?.(checked) : undefined}
+ shortcut={item.shortcut}
+ >
+ {item.label}
+
+ )
+ case 'radio':
+ return (
+ item.onValueChange?.(value) : undefined}
+ >
+ {item.label != null && {item.label} }
+ {item.items.map((option) => (
+
+ {option.label}
+
+ ))}
+
+ )
+ case 'submenu':
+ return (
+
+
+ {item.label}
+
+ {renderItems(item.items)}
+
+ )
+ default:
+ return (
+
+ {item.label}
+
+ )
+ }
+}
+
+/** Renders item data. A `label` entry opens a Group that runs to the next label or separator. */
+function renderItems(items: DropdownMenuItemData[]): ReactNode {
+ const out: ReactNode[] = []
+ let groupKey = ''
+ let groupChildren: ReactNode[] | null = null
+
+ const closeGroup = () => {
+ if (groupChildren) out.push({groupChildren} )
+ groupChildren = null
+ }
+
+ items.forEach((item, index) => {
+ const key = item.key ?? String(index)
+ const node = renderItem(item, key)
+ if (item.type === 'label') {
+ closeGroup()
+ groupKey = `group-${key}`
+ groupChildren = [node]
+ } else if (item.type === 'separator') {
+ closeGroup()
+ out.push(node)
+ } else {
+ ;(groupChildren ?? out).push(node)
+ }
+ })
+ closeGroup()
+ return {out}
+}
+
+export type DropdownMenuProps = OpenProps & {
+ /** The element that opens the menu, usually a `` or ``. */
+ trigger: ReactElement
+ /** Menu entries: actions, checkboxes, radio groups, separators, labels and submenus. */
+ items?: DropdownMenuItemData[]
+ /** Preferred side of the trigger. */
+ side?: PopupSide
+ /** Alignment along that side. */
+ align?: PopupAlign
+ /** Gap between trigger and menu, in px. */
+ sideOffset?: number
+ /** Lock page scroll and block outside pointer events while open. */
+ modal?: boolean
+ /** Classes for the menu popup. */
+ className?: string
+ /** Compound items, rendered after `items`. */
+ children?: ReactNode
+}
+
+/**
+ * A menu of actions and settings opened from a button (Base UI Menu). Arrow
+ * keys move, Enter or Space chooses, typing jumps to a matching item, Escape
+ * closes and returns focus to the trigger. Pass `items` as data, or build it
+ * from `DropdownMenu.Root`, `Trigger`, `Content`, `Item`, `CheckboxItem`,
+ * `RadioGroup`, `RadioItem`, `Separator`, `Group`, `Label`, `Sub`,
+ * `SubTrigger` and `SubContent`.
+ */
+function DropdownMenuComponent({
+ trigger,
+ items,
+ side,
+ align,
+ sideOffset,
+ className,
+ children,
+ ...rootProps
+}: DropdownMenuProps) {
+ return (
+
+
+
+ {items && renderItems(items)}
+ {children}
+
+
+ )
+}
+
+export const DropdownMenu = Object.assign(DropdownMenuComponent, {
+ Root: MenuRoot,
+ Trigger: MenuTrigger,
+ Content: MenuContent,
+ Item: MenuItem,
+ CheckboxItem: MenuCheckboxItem,
+ RadioGroup: MenuRadioGroup,
+ RadioItem: MenuRadioItem,
+ Separator: MenuSeparator,
+ Group: MenuGroup,
+ Label: MenuLabel,
+ Sub: MenuSub,
+ SubTrigger: MenuSubTrigger,
+ SubContent: MenuSubContent,
+})
diff --git a/src/components/FeaturedInput.stories.tsx b/src/components/FeaturedInput.stories.tsx
index 102037a..8ac3211 100644
--- a/src/components/FeaturedInput.stories.tsx
+++ b/src/components/FeaturedInput.stories.tsx
@@ -1,9 +1,12 @@
-import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
-import { Mail, Lock, User, Search } from 'lucide-react'
+import { AtSign, Lock, Mail, Search, UserRound } from 'lucide-react'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { SIZES } from '../lib/styles'
import { FeaturedInput } from './FeaturedInput'
+import { TEXT_FIELD_VARIANTS } from './featuredinput.tokens'
-const meta: Meta = {
+const meta = {
title: 'Forms/FeaturedInput',
component: FeaturedInput,
tags: ['autodocs'],
@@ -11,159 +14,192 @@ const meta: Meta = {
docs: {
description: {
component:
- 'Input with an animated floating label, a built-in password show/hide toggle, and number-input hardening (blocks `e`/`+`/`-` and blurs on wheel). The floated label gets extra top padding here — the source omits it, which renders the text underneath the label.',
+ 'A single-line text input whose label sits inside the box and floats up when the input is focused or filled. The float is pure CSS, so it works controlled, uncontrolled and with browser autofill. Same API as `Input`, plus a password reveal toggle (`type="password"`), `loading` and `clearable`. The label stays the accessible name; `description` and `error` are linked to the input.',
},
},
},
argTypes: {
- size: { control: 'select', options: ['sm', 'md', 'lg'] },
- theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
- variant: { control: 'select', options: ['outlined', 'underlined'] },
- type: { control: 'select', options: ['text', 'email', 'password', 'number', 'tel'] },
- shrink: { control: 'boolean' },
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ placeholder: { control: 'text', description: 'Shown once the label has floated, while the input is focused and empty.' },
+ type: { control: 'select', options: ['text', 'email', 'password', 'search', 'tel', 'url'] },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ variant: {
+ control: 'inline-radio',
+ options: TEXT_FIELD_VARIANTS,
+ table: { defaultValue: { summary: 'outline' } },
+ },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
- showPasswordToggle: { control: 'boolean' },
- roundedFull: { control: 'boolean' },
- dashedBorder: { control: 'boolean' },
- label: { control: 'text' },
- placeholder: { control: 'text' },
- error: { control: 'text' },
+ readOnly: { control: 'boolean' },
+ loading: { control: 'boolean' },
+ clearable: { control: 'boolean' },
+ value: { control: 'text' },
+ defaultValue: { control: 'text' },
+ name: { control: 'text' },
+ className: { control: 'text' },
+ inputClassName: { control: 'text' },
+ startIcon: { control: false },
+ endIcon: { control: false },
+ onValueChange: { control: false },
+ onChange: { control: false },
},
args: {
- label: 'Full name',
- placeholder: 'Jane Doe',
- type: 'text',
+ label: 'Work email',
+ type: 'email',
size: 'md',
- theme: 'primary',
- variant: 'outlined',
- shrink: false,
+ variant: 'outline',
required: false,
disabled: false,
- showPasswordToggle: true,
- roundedFull: false,
- dashedBorder: false,
- error: '',
+ readOnly: false,
+ loading: false,
+ clearable: false,
+ onValueChange: fn(),
+ onChange: fn(),
+ },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Filled: Story = {
+ args: { defaultValue: 'jane.doe@example.com' },
+}
+
+export const WithDescription: Story = {
+ args: { description: 'Invoices from Acme Corporation are sent here.' },
+}
+
+export const WithError: Story = {
+ args: { defaultValue: 'jane.doe@', error: 'Enter a full email address, like name@example.com.' },
+}
+
+export const Required: Story = {
+ args: { required: true, description: 'We never share your email.' },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: 'jane.doe@example.com' },
+}
+
+export const ReadOnly: Story = {
+ args: { readOnly: true, defaultValue: 'jane.doe@example.com', description: 'Managed by your identity provider.' },
+}
+
+export const Loading: Story = {
+ args: { label: 'Username', type: 'text', loading: true, defaultValue: 'janedoe', description: 'Checking availability…' },
+}
+
+export const Clearable: Story = {
+ args: { label: 'Search people', type: 'search', clearable: true, defaultValue: 'Jane Doe', startIcon: },
+}
+
+export const Password: Story = {
+ args: {
+ label: 'Password',
+ type: 'password',
+ defaultValue: 'correct-horse-battery',
+ required: true,
+ description: 'At least 12 characters.',
+ autoComplete: 'current-password',
},
}
-export default meta
-
-function ControlledFeatured({
- initial = '',
- ...args
-}: React.ComponentProps & { initial?: string }) {
- const [value, setValue] = useState(initial)
- return (
- setValue(e.target.value)} />
- )
-}
-
-export const FeaturedPlayground: StoryObj = {
+export const Variants: Story = {
render: (args) => (
-
-
-
- ),
-}
-
-export const FloatingStates: StoryObj = {
- name: 'Floating states',
- render: () => (
-
-
-
-
Floated (has value)
-
-
-
-
-
- ),
-}
-
-export const PasswordWithToggle: StoryObj = {
- render: () => (
-
-
-
- ),
-}
-
-export const PasswordToggleDisabled: StoryObj = {
- render: () => (
-
-
-
- ),
-}
-
-export const WithLucideIcon: StoryObj = {
- render: () => (
-
-
-
-
-
-
- ),
-}
-
-export const NumberHardening: StoryObj = {
- name: 'Number hardening',
- render: () => (
-
-
-
- ),
-}
-
-export const FeaturedThemes: StoryObj = {
- name: 'Themes',
- render: () => (
-
- {(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
-
+
+ {TEXT_FIELD_VARIANTS.map((variant) => (
+
+
+
+
))}
),
}
-export const FeaturedVariants: StoryObj
= {
- name: 'Variants',
- render: () => (
-
-
-
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+
+
+
+ ))}
),
}
-export const FeaturedDisabled: StoryObj
= {
- name: 'Disabled',
- render: () => (
-
-
-
+export const WithIcons: Story = {
+ render: (args) => (
+
+ } />
+ } defaultValue="Jane Doe" />
+ } defaultValue="janedoe" />
+ } defaultValue="sk_test_4eC39HqLyjWDarjtT1" clearable />
),
}
+
+export const AllStates: Story = {
+ render: (args) => (
+
+
+
+
+
+
+
+
+
+ ),
+}
+
+export const Uncontrolled: Story = {
+ args: { label: 'Company', type: 'text', defaultValue: 'Acme Corporation', clearable: true },
+}
+
+function ControlledFeaturedInput(args: Story['args']) {
+ const [value, setValue] = useState('Jane Doe')
+ return (
+
+
{
+ setValue(next)
+ args?.onValueChange?.(next)
+ }}
+ />
+ Value: {value || '(empty)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) =>
,
+}
+
+export const SignInForm: Story = {
+ render: (args) => (
+
+ ),
+}
diff --git a/src/components/FeaturedInput.test.tsx b/src/components/FeaturedInput.test.tsx
new file mode 100644
index 0000000..32d6eda
--- /dev/null
+++ b/src/components/FeaturedInput.test.tsx
@@ -0,0 +1,132 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { createRef } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { FeaturedInput } from './FeaturedInput'
+
+describe('FeaturedInput', () => {
+ it('uses the floating label as the accessible name', () => {
+ render(
)
+ const input = screen.getByRole('textbox', { name: 'Work email' })
+ expect(input).toBeInTheDocument()
+ // The label floats with CSS only: the input always has a placeholder.
+ expect(input).toHaveAttribute('placeholder', ' ')
+ })
+
+ it('keeps a custom placeholder', () => {
+ render(
)
+ expect(screen.getByRole('textbox')).toHaveAttribute('placeholder', 'name@example.com')
+ })
+
+ it('announces the description with the input', () => {
+ render(
)
+ expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Invoices go here.')
+ })
+
+ it('marks the input invalid and announces the error instead of the description', () => {
+ render(
)
+ const input = screen.getByRole('textbox')
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(input).toHaveAccessibleDescription('Enter a full email address.')
+ })
+
+ it('passes required, disabled and readOnly to the input', () => {
+ const { rerender } = render(
)
+ expect(screen.getByRole('textbox')).toBeRequired()
+ expect(screen.getByRole('textbox')).toBeDisabled()
+ rerender(
)
+ expect(screen.getByRole('textbox')).toHaveAttribute('readonly')
+ })
+
+ it('works uncontrolled with defaultValue', async () => {
+ const onValueChange = vi.fn()
+ render(
)
+ const input = screen.getByRole('textbox')
+ expect(input).toHaveValue('Jane')
+ await userEvent.type(input, ' Doe')
+ expect(input).toHaveValue('Jane Doe')
+ expect(onValueChange).toHaveBeenLastCalledWith('Jane Doe')
+ })
+
+ it('works controlled and still fires native onChange', async () => {
+ const onValueChange = vi.fn()
+ const onChange = vi.fn()
+ render(
)
+ await userEvent.type(screen.getByRole('textbox'), 'x')
+ expect(onValueChange).toHaveBeenLastCalledWith('Janex')
+ expect(onChange).toHaveBeenCalled()
+ expect(screen.getByRole('textbox')).toHaveValue('Jane')
+ })
+
+ it('forwards ref to the input', () => {
+ const ref = createRef
()
+ render( )
+ expect(ref.current).toBe(screen.getByRole('textbox'))
+ })
+
+ it('reveals and hides the password with a pressed toggle', async () => {
+ const user = userEvent.setup()
+ render( )
+ const input = screen.getByLabelText('Password', { selector: 'input' })
+ const toggle = screen.getByRole('button', { name: 'Show password' })
+ expect(input).toHaveAttribute('type', 'password')
+ expect(toggle).toHaveAttribute('aria-pressed', 'false')
+
+ await user.click(toggle)
+ expect(input).toHaveAttribute('type', 'text')
+ expect(screen.getByRole('button', { name: 'Hide password' })).toHaveAttribute('aria-pressed', 'true')
+
+ // Keyboard: Tab from the input reaches the toggle, Space toggles back.
+ input.focus()
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'Hide password' })).toHaveFocus()
+ await user.keyboard(' ')
+ expect(input).toHaveAttribute('type', 'password')
+ })
+
+ it('clears the value and refocuses the input', async () => {
+ const user = userEvent.setup()
+ const onValueChange = vi.fn()
+ render( )
+ const input = screen.getByRole('textbox')
+ await user.click(screen.getByRole('button', { name: 'Clear' }))
+ expect(input).toHaveValue('')
+ expect(input).toHaveFocus()
+ expect(onValueChange).toHaveBeenLastCalledWith('')
+ expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument()
+ })
+
+ it('clears with the keyboard', async () => {
+ const user = userEvent.setup()
+ render( )
+ await user.tab()
+ await user.tab()
+ expect(screen.getByRole('button', { name: 'Clear' })).toHaveFocus()
+ await user.keyboard('{Enter}')
+ expect(screen.getByRole('textbox')).toHaveValue('')
+ expect(screen.getByRole('textbox')).toHaveFocus()
+ })
+
+ it('hides the clear button when empty, disabled or read-only', () => {
+ const { rerender } = render( )
+ expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument()
+ rerender( )
+ expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument()
+ })
+
+ it('marks the input busy while loading', () => {
+ render( )
+ expect(screen.getByRole('textbox')).toHaveAttribute('aria-busy', 'true')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ <>
+ } clearable defaultValue="jane@example.com" />
+
+ >,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/FeaturedInput.tsx b/src/components/FeaturedInput.tsx
index 64b3eff..a1c9042 100644
--- a/src/components/FeaturedInput.tsx
+++ b/src/components/FeaturedInput.tsx
@@ -1,327 +1,208 @@
+import { Input as BaseInput } from '@base-ui/react/input'
+import { Eye, EyeOff, LoaderCircle, X } from 'lucide-react'
+import { useCallback, useRef, useState, type ComponentProps, type ReactNode, type Ref } from 'react'
+import { cn } from '../lib/cn'
+import { controlHeight, iconSize, type Size } from '../lib/styles'
+import { useControllableState } from '../lib/useControllableState'
+import { IconButton } from './Button'
+import { Field, FieldLabel } from './Field'
import {
- forwardRef,
- useEffect,
- useRef,
- useState,
- type ChangeEvent,
- type FocusEvent,
- type InputHTMLAttributes,
- type KeyboardEvent,
- type ReactNode,
- type WheelEvent,
-} from 'react'
-import { Eye, EyeOff, type LucideIcon } from 'lucide-react'
-import { cn } from '@/lib/cn'
-import { omit } from '@/lib/omit'
-import { Tooltip } from './Tooltip'
-import {
- FLOATING_CONTENT_PADDING,
- FLOATING_LABEL_SIZES,
- ICON_SIZES,
- INPUT_HOVER_THEMES,
- INPUT_SIZES,
- INPUT_THEMES,
- INPUT_VARIANTS,
- LABEL_COLORS,
- LABEL_SIZES,
- type InputSize,
- type InputTheme,
- type InputVariant,
-} from './input.tokens'
+ FIELD_BOX,
+ FIELD_BOX_DISABLED_INPUT,
+ FIELD_BOX_RING_INPUT,
+ FIELD_BOX_RING_UNDERLINE,
+ FLOAT_INPUT,
+ FLOAT_LABEL_BASE,
+ FLOAT_LABEL_COLOR,
+ FLOAT_PLACEHOLDER,
+ INNER_BUTTON,
+ TEXT_INSET,
+ type TextFieldVariant,
+} from './featuredinput.tokens'
-/**
- * Input with an animated floating label.
- *
- * Ported from the original `Input/FeaturedInput` component.
- *
- * Upstream fixes kept:
- * - a `password` field gets a built-in show/hide toggle (IP-4091: dots with no
- * way to check what was typed);
- * - `type="number"` blocks `e`/`E`/`+`/`-` and blurs on wheel scroll, so the
- * value cannot change under the cursor.
- *
- * Fixes added here:
- * - the floated label needs top padding on the field, or the text renders
- * underneath it (see `FLOATING_CONTENT_PADDING`);
- * - a `LucideIcon` slot replaces the Remix-icon class name, which needs a font
- * this showcase does not load.
- */
-
-export type FeaturedInputProps = Omit<
- InputHTMLAttributes,
- 'size' | 'value' | 'defaultValue'
-> & {
- label?: string
- value?: string
- size?: InputSize
- theme?: InputTheme
- variant?: InputVariant
- name?: string
- onChange?: (e: ChangeEvent) => void
- onBlur?: (e: FocusEvent) => void
- onKeyDown?: (e: KeyboardEvent) => void
- /** Keep the label floated even when the field is empty and unfocused. */
- shrink?: boolean
- roundedFull?: boolean
- dashedBorder?: boolean
- error?: string | { message?: string }
- /** Lucide icon rendered inside the field. */
- icon?: LucideIcon
- iconPosition?: 'left' | 'right'
- /** Adds a show/hide toggle when `type` is `password`. */
- showPasswordToggle?: boolean
- floatinglabelClass?: string
- tooltip?: string
- tooltipIcon?: LucideIcon
- helpText?: string
- isLoading?: boolean
- /** Rendered inside the field, before the password toggle. */
- trailing?: ReactNode
+export type FeaturedInputProps = Omit, 'size' | 'value' | 'defaultValue'> & {
+ /** Label shown inside the box. It floats up when the input is focused or filled, and stays the accessible name. */
+ label?: ReactNode
+ /** Help text under the input. */
+ description?: ReactNode
+ /** Error message; marks the input invalid and replaces `description`. */
+ error?: ReactNode
+ /** Shows the required mark and sets `required` on the input. */
+ required?: boolean
+ disabled?: boolean
+ readOnly?: boolean
+ size?: Size
+ /** `outline` draws a box; `filled` a tinted box; `underline` a bottom rule. */
+ variant?: TextFieldVariant
+ /** Icon inside the start of the box. Decorative. */
+ startIcon?: ReactNode
+ /** Icon inside the end of the box. Decorative. */
+ endIcon?: ReactNode
+ /** Shows a small spinner at the end and marks the input busy. */
+ loading?: boolean
+ /** Shows a button that clears the value and returns focus to the input. */
+ clearable?: boolean
+ value?: string | number
+ defaultValue?: string | number
+ /** Fires with the new value (also when cleared). Native `onChange` still works too. */
+ onValueChange?: (value: string) => void
+ /** Classes for the outer field wrapper. Use `inputClassName` for the input itself. */
+ className?: string
+ inputClassName?: string
}
-export const FeaturedInput = forwardRef(
- function FeaturedInput(
- {
- type = 'text',
- label = '',
- disabled = false,
- required = false,
- icon: Icon,
- iconPosition = 'left',
- className = '',
- roundedFull = false,
- dashedBorder = false,
- size = 'md',
- variant = 'outlined',
- onKeyDown,
- onChange,
- onBlur,
- onFocus,
- theme = 'primary',
- name,
- error,
- value,
- floatinglabelClass,
- shrink = false,
- placeholder,
- showPasswordToggle = true,
- tooltip,
- tooltipIcon,
- helpText,
- isLoading = false,
- trailing,
- ...props
+/**
+ * A single-line text input whose label sits inside the box and floats up when
+ * the input is focused or filled. Same API as Input, plus a password reveal
+ * toggle, `loading` and `clearable`.
+ */
+export function FeaturedInput({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ readOnly,
+ size = 'md',
+ variant = 'outline',
+ startIcon,
+ endIcon,
+ loading = false,
+ clearable = false,
+ type = 'text',
+ value,
+ defaultValue,
+ onValueChange,
+ placeholder,
+ className,
+ inputClassName,
+ name,
+ ref,
+ ...props
+}: FeaturedInputProps) {
+ const inputRef = useRef(null)
+ const [current, setCurrent] = useControllableState(
+ value === undefined ? undefined : String(value),
+ defaultValue === undefined ? '' : String(defaultValue),
+ onValueChange,
+ )
+ const [revealed, setRevealed] = useState(false)
+ const setRefs = useCallback(
+ (node: HTMLInputElement | null) => {
+ inputRef.current = node
+ assignRef(ref, node)
},
- ref,
- ) {
- const [isFocused, setIsFocused] = useState(false)
- const [isRevealed, setIsRevealed] = useState(false)
- const wrapperRef = useRef(null)
+ [ref],
+ )
- const isPassword = type === 'password'
- const hasRevealToggle = isPassword && showPasswordToggle
- const resolvedType = isPassword && isRevealed ? 'text' : type
+ const invalid = error != null && error !== false && error !== ''
+ const isPassword = type === 'password'
+ const showClear = clearable && current !== '' && !disabled && !readOnly
+ const hasEnd = loading || showClear || isPassword || endIcon != null
+ const inset = TEXT_INSET[size]
+ const geometry = FLOAT_INPUT[size]
- const htmlProps = omit(props as Record, [
- 'isDynamic', 'valueKey', 'labelKey', 'endpoint', 'endpointParams', 'isMulti',
- 'searchable', 'infiniteScroll', 'options', 'tooltip', 'tooltipIcon', 'helpText',
- 'isLoading', 'showPasswordToggle', 'register', 'validation', 'floatinglabelClass',
- ])
+ function clear() {
+ setCurrent('')
+ inputRef.current?.focus()
+ }
- const errorMessage = typeof error === 'string' ? error : error?.message
-
- const handleFocus = () => setIsFocused(true)
-
- const handleBlur = (e: FocusEvent) => {
- onBlur?.(e)
- // An empty field drops back to the resting label position.
- if (e.target.value === '' && !shrink) setIsFocused(false)
- }
-
- const handleChange = (e: ChangeEvent) => onChange?.(e)
-
- // A native number input still accepts e/E/+/-, so scientific notation can be
- // typed into a field that only takes plain numbers. The caller's handler
- // still runs.
- const handleKeyDown = (e: KeyboardEvent) => {
- if (type === 'number' && ['e', 'E', '+', '-'].includes(e.key)) e.preventDefault()
- onKeyDown?.(e)
- }
-
- // Prevent a wheel scroll from silently changing a focused number field.
- const handleWheel = (e: WheelEvent) => {
- if (type === 'number') e.currentTarget.blur()
- }
-
- // A field rendered with a value is filled from the first paint, so the label
- // has to start floated — otherwise it sits on top of the value.
- useEffect(() => {
- const el = name ? document.getElementById(name) : null
- if (el && (el as HTMLInputElement).value) setIsFocused(true)
- }, [name])
-
- useEffect(() => {
- const handleClickOutside = (event: MouseEvent) => {
- if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
- setTimeout(() => {
- const el = name ? (document.getElementById(name) as HTMLInputElement | null) : null
- if (el && !el.value) setIsFocused(false)
- }, 300)
- }
- }
- document.addEventListener('mousedown', handleClickOutside)
- return () => document.removeEventListener('mousedown', handleClickOutside)
- }, [name])
-
- const hasValue = value !== undefined && value !== null && value !== ''
- const shouldFloat = shrink || hasValue || isFocused || Boolean(errorMessage)
-
- const labelColor = errorMessage
- ? 'text-red-500'
- : isFocused || hasValue
- ? (floatinglabelClass || LABEL_COLORS[theme] || LABEL_COLORS.primary)
- : 'text-slate-400'
-
- const isUnderlined = variant === 'underlined'
- const variantTokens = INPUT_VARIANTS[variant] ?? INPUT_VARIANTS.outlined
-
- return (
-
-
- {Icon && iconPosition === 'left' && (
-
- )}
-
-
+
+ {startIcon != null && (
+
+ {startIcon}
+
+ )}
+
+
{
- handleFocus()
- onFocus?.(e)
- }}
- onBlur={handleBlur}
- onChange={handleChange}
- onKeyDown={handleKeyDown}
- onWheel={handleWheel}
+ disabled={disabled}
+ readOnly={readOnly}
+ value={current}
+ onValueChange={(next) => setCurrent(next)}
+ placeholder={placeholder || ' '}
+ aria-busy={loading || undefined}
className={cn(
- 'w-full bg-transparent text-gray-800 placeholder:text-transparent',
- 'focus:outline-none transition-all duration-200',
- 'disabled:text-slate-400',
- Icon && iconPosition === 'left' ? 'pl-9' : 'pl-3',
- hasRevealToggle || Icon || trailing || isLoading ? 'pr-10' : 'pr-3',
+ 'peer size-full bg-transparent text-fg outline-none disabled:cursor-not-allowed',
+ FLOAT_PLACEHOLDER,
+ geometry.input,
+ variant === 'underline' ? 'px-0.5' : inset.input,
+ startIcon != null && 'pl-2',
+ hasEnd && 'pr-1.5',
+ inputClassName,
)}
- {...htmlProps}
+ {...props}
/>
-
-
- {isLoading && … }
- {trailing}
- {hasRevealToggle && (
- setIsRevealed((v) => !v)}
- aria-label={isRevealed ? 'Hide password' : 'Show password'}
- className="text-gray-400 hover:text-gray-600"
- >
- {isRevealed ? : }
-
- )}
-
-
- {Icon && iconPosition === 'right' && (
-
- )}
-
- {label && (
-
-
-
- {label}
- {required && * }
-
- {(tooltip || helpText) && (
- e.stopPropagation()}
- onClick={(e) => e.preventDefault()}
- >
-
-
- )}
-
-
+ {label}
+
)}
-
- {errorMessage && (
-
- {errorMessage}
-
+ {hasEnd && (
+
+ {loading && (
+
+
+
+ )}
+ {showClear && (
+ }
+ onClick={clear}
+ className={INNER_BUTTON[size]}
+ />
+ )}
+ {isPassword && (
+ : }
+ disabled={disabled}
+ onClick={() => setRevealed((r) => !r)}
+ className={INNER_BUTTON[size]}
+ />
+ )}
+ {endIcon != null && (
+
+ {endIcon}
+
+ )}
+
)}
- )
- },
-)
+
+ )
+}
-export default FeaturedInput
+function assignRef
(ref: Ref | undefined, node: T | null) {
+ if (typeof ref === 'function') ref(node)
+ else if (ref) ref.current = node
+}
diff --git a/src/components/FeaturedSelect.stories.tsx b/src/components/FeaturedSelect.stories.tsx
new file mode 100644
index 0000000..831373c
--- /dev/null
+++ b/src/components/FeaturedSelect.stories.tsx
@@ -0,0 +1,275 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Briefcase, Plus } from 'lucide-react'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { SIZES } from '../lib/styles'
+import { FeaturedSelect } from './FeaturedSelect'
+import { COUNTRIES, CURRENCIES, DEPARTMENTS, DEPARTMENTS_DESCRIBED, EMPLOYEES, withoutValue } from './select.fixtures'
+import { SELECT_VARIANTS } from './select.tokens'
+
+const meta = {
+ title: 'Forms/FeaturedSelect',
+ component: FeaturedSelect,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Select with a floating label inside the trigger: the label rests where the value goes and floats onto the border when the popup opens or a value is chosen. Same API as `Select`, plus `searchable` (a search box in the popup, built on Base UI Combobox, with filtering, arrow keys, `aria-activedescendant` and a "No results" state) and `actionButton`, a footer button such as "Add department".',
+ },
+ },
+ },
+ argTypes: {
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ placeholder: { control: 'text' },
+ searchPlaceholder: { control: 'text' },
+ emptyText: { control: 'text' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ variant: { control: 'inline-radio', options: SELECT_VARIANTS, table: { defaultValue: { summary: 'outline' } } },
+ side: { control: 'inline-radio', options: ['bottom', 'top'], table: { defaultValue: { summary: 'bottom' } } },
+ searchable: { control: 'boolean' },
+ filterOptions: { control: 'boolean' },
+ multiple: { control: 'boolean' },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ readOnly: { control: 'boolean' },
+ clearable: { control: 'boolean' },
+ loading: { control: 'boolean' },
+ loadingText: { control: 'text' },
+ name: { control: 'text' },
+ options: { control: 'object' },
+ value: { control: 'object' },
+ defaultValue: { control: 'object' },
+ open: { control: 'boolean' },
+ defaultOpen: { control: 'boolean' },
+ actionButton: { control: 'object' },
+ className: { control: 'text' },
+ triggerClassName: { control: 'text' },
+ startIcon: { control: false },
+ renderOption: { control: false },
+ onValueChange: { control: false },
+ onOpenChange: { control: false },
+ onInputValueChange: { control: false },
+ },
+ args: {
+ label: 'Department',
+ options: DEPARTMENTS,
+ size: 'md',
+ variant: 'outline',
+ side: 'bottom',
+ searchable: false,
+ multiple: false,
+ required: false,
+ disabled: false,
+ readOnly: false,
+ clearable: false,
+ loading: false,
+ onValueChange: fn(),
+ onOpenChange: fn(),
+ },
+ decorators: [
+ // Forms sit on a surface, as they would in a card or dialog.
+ (Story, { parameters }) => (
+
+
+
+ ),
+ ],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+const tall = (Story: () => React.JSX.Element) => (
+
+
+
+)
+
+export const Playground: Story = {}
+
+/** The popup rendered open: the label has floated and the placeholder shows. */
+export const Open: Story = {
+ args: { defaultOpen: true, options: DEPARTMENTS_DESCRIBED, placeholder: 'Select a department' },
+ decorators: [tall],
+}
+
+/** Empty, with a value, and invalid: the label rests, floats, and turns red. */
+export const LabelStates: Story = {
+ render: (args) => (
+
+
+
+
+
+
+ ),
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+
+
+
+ ))}
+
+ ),
+ parameters: { wide: true },
+}
+
+export const Variants: Story = {
+ render: (args) => (
+
+ {SELECT_VARIANTS.map((variant) => (
+
+
+
+
+ ))}
+
+ ),
+ parameters: { wide: true },
+}
+
+export const WithDescription: Story = {
+ args: { description: 'Payroll reports are grouped by department.' },
+}
+
+export const WithError: Story = {
+ args: { error: 'Choose the department this person reports to.', required: true },
+}
+
+export const Required: Story = {
+ args: { required: true, name: 'department' },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: 'eng' },
+}
+
+export const ReadOnly: Story = {
+ args: { readOnly: true, defaultValue: 'fin', description: 'Set by your HR system.' },
+}
+
+export const WithStartIcon: Story = {
+ render: (args) => (
+
+ } />
+ } defaultValue="sales" />
+
+ ),
+}
+
+export const Clearable: Story = {
+ args: { clearable: true, defaultValue: 'design' },
+}
+
+export const Loading: Story = {
+ args: { loading: true, options: [], defaultOpen: true },
+ decorators: [tall],
+}
+
+export const Grouped: Story = {
+ args: { label: 'Payroll currency', options: CURRENCIES, defaultValue: 'gbp' },
+}
+
+export const Multiple: Story = {
+ args: { label: 'Departments', multiple: true, clearable: true, defaultValue: ['eng', 'design', 'fin'] },
+}
+
+export const CustomOptionRendering: Story = {
+ args: {
+ label: 'Manager',
+ options: EMPLOYEES,
+ defaultValue: 'e4',
+ defaultOpen: true,
+ renderOption: (option, { selected }) => (
+
+ {option.label}
+
+ {option.description?.split(' · ')[1]}
+
+
+ ),
+ },
+ decorators: [tall],
+}
+
+/** `searchable` adds a search box to the popup. Arrow keys move through the matches. */
+export const Searchable: Story = {
+ args: {
+ label: 'Country of residence',
+ searchable: true,
+ options: COUNTRIES,
+ defaultOpen: true,
+ placeholder: 'Select a country',
+ searchPlaceholder: 'Search countries',
+ },
+ decorators: [tall],
+}
+
+export const SearchableMultiple: Story = {
+ args: {
+ label: 'Countries with employees',
+ searchable: true,
+ multiple: true,
+ clearable: true,
+ options: COUNTRIES,
+ defaultValue: ['ca', 'de', 'gb', 'in'],
+ },
+}
+
+export const SearchableGrouped: Story = {
+ args: { label: 'Payroll currency', searchable: true, options: CURRENCIES, defaultOpen: true },
+ decorators: [tall],
+}
+
+/** A footer button in the popup, for creating an option that isn't there yet. */
+export const WithActionButton: Story = {
+ args: {
+ searchable: true,
+ defaultOpen: true,
+ searchPlaceholder: 'Search departments',
+ actionButton: { label: 'Add department', icon: , onClick: fn() },
+ },
+ decorators: [tall],
+}
+
+/** 50 countries without search: the list scrolls and type-ahead jumps. */
+export const LongList: Story = {
+ args: { label: 'Country of residence', options: COUNTRIES, defaultValue: 'nl' },
+}
+
+function ControlledFeaturedSelect(args: Story['args']) {
+ const [value, setValue] = useState('hr')
+ return (
+
+
+
Value: {value ?? '(none)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) => ,
+}
+
+export const Uncontrolled: Story = {
+ args: { defaultValue: 'sales', name: 'department' },
+}
diff --git a/src/components/FeaturedSelect.test.tsx b/src/components/FeaturedSelect.test.tsx
new file mode 100644
index 0000000..6727dc0
--- /dev/null
+++ b/src/components/FeaturedSelect.test.tsx
@@ -0,0 +1,145 @@
+import { render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { FeaturedSelect } from './FeaturedSelect'
+import type { SelectOption } from './select.tokens'
+
+const departments: SelectOption[] = [
+ { value: 'eng', label: 'Engineering' },
+ { value: 'fin', label: 'Finance' },
+ { value: 'hr', label: 'People & Culture' },
+ { value: 'ops', label: 'Operations' },
+]
+
+describe('FeaturedSelect', () => {
+ it('links the floating label to the trigger', () => {
+ render( )
+ expect(screen.getByRole('combobox', { name: 'Department' })).toBeInTheDocument()
+ })
+
+ it('floats the label when a value is chosen', async () => {
+ render( )
+ const label = screen.getByText('Department')
+ expect(label.className).toContain('top-1/2')
+ await userEvent.click(screen.getByRole('combobox', { name: 'Department' }))
+ await userEvent.click(await screen.findByRole('option', { name: 'Finance' }))
+ expect(label.className).toContain('top-0')
+ expect(screen.getByRole('combobox', { name: 'Department' })).toHaveTextContent('Finance')
+ })
+
+ it('opens and chooses with the keyboard, and Escape returns focus to the trigger', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ const trigger = screen.getByRole('combobox', { name: 'Department' })
+ trigger.focus()
+ await userEvent.keyboard('{ArrowDown}')
+ await screen.findByRole('listbox')
+ await userEvent.keyboard('{ArrowDown}{Enter}')
+ expect(onValueChange).toHaveBeenCalledTimes(1)
+ await waitFor(() => expect(trigger).toHaveFocus())
+ await userEvent.keyboard('{ArrowDown}')
+ await screen.findByRole('listbox')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(trigger).toHaveFocus())
+ expect(trigger).toHaveAttribute('aria-expanded', 'false')
+ })
+
+ it('works controlled with multiple values', async () => {
+ function Controlled() {
+ const [value, setValue] = useState(['eng'])
+ return (
+ <>
+
+ {value.join(',')}
+ >
+ )
+ }
+ render( )
+ const trigger = screen.getByRole('combobox', { name: 'Departments' })
+ await userEvent.click(trigger)
+ await userEvent.click(await screen.findByRole('option', { name: 'Finance' }))
+ expect(screen.getByTestId('value')).toHaveTextContent('eng,fin')
+ expect(trigger).toHaveTextContent('Engineering, Finance')
+ })
+
+ it('clears with a labelled button', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Clear Department' }))
+ expect(onValueChange).toHaveBeenCalledWith(null)
+ expect(screen.getByText('Department').className).toContain('top-1/2')
+ })
+
+ it('runs the action button and closes the popup', async () => {
+ const onClick = vi.fn()
+ render(
+ ,
+ )
+ await userEvent.click(await screen.findByRole('button', { name: 'Add department' }))
+ expect(onClick).toHaveBeenCalledOnce()
+ await waitFor(() => expect(screen.getByRole('combobox', { name: 'Department' })).toHaveAttribute('aria-expanded', 'false'))
+ })
+
+ it('announces the description, and the error when invalid', () => {
+ render( )
+ const trigger = screen.getByRole('combobox', { name: 'Department' })
+ expect(trigger).toHaveAttribute('aria-invalid', 'true')
+ expect(trigger).toHaveAccessibleDescription('Choose a department.')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ ,
+ )
+ await expectNoA11yViolations(container)
+ })
+
+ describe('searchable', () => {
+ it('filters with the search box, shows the empty state and chooses with the keyboard', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ await userEvent.click(screen.getByRole('combobox', { name: 'Department' }))
+ const search = await screen.findByPlaceholderText('Search…')
+ await waitFor(() => expect(search).toHaveFocus())
+ await userEvent.type(search, 'fin')
+ const listbox = screen.getByRole('listbox')
+ expect(within(listbox).getAllByRole('option').map((o) => o.textContent)).toEqual(['Finance'])
+ await userEvent.keyboard('{ArrowDown}')
+ expect(search.getAttribute('aria-activedescendant')).toBeTruthy()
+ await userEvent.keyboard('{Enter}')
+ expect(onValueChange).toHaveBeenCalledWith('fin')
+ await waitFor(() => expect(screen.getByRole('combobox', { name: 'Department' })).toHaveTextContent('Finance'))
+ })
+
+ it('shows "No results" when nothing matches', async () => {
+ render( )
+ await userEvent.type(await screen.findByPlaceholderText('Search…'), 'zzz')
+ expect(await screen.findByText('No results')).toBeInTheDocument()
+ })
+
+ it('closes on Escape and returns focus to the trigger', async () => {
+ render( )
+ const trigger = screen.getByRole('combobox', { name: 'Department' })
+ await userEvent.click(trigger)
+ await screen.findByPlaceholderText('Search…')
+ await userEvent.keyboard('{Escape}')
+ await waitFor(() => expect(trigger).toHaveFocus())
+ })
+
+ it('has no axe violations when open', async () => {
+ render(
+ {} }}
+ />,
+ )
+ await screen.findByPlaceholderText('Search…')
+ await expectNoA11yViolations(document.body)
+ })
+ })
+})
diff --git a/src/components/FeaturedSelect.tsx b/src/components/FeaturedSelect.tsx
index 08e2908..b46a1ac 100644
--- a/src/components/FeaturedSelect.tsx
+++ b/src/components/FeaturedSelect.tsx
@@ -1,470 +1,330 @@
+import { Combobox as BaseCombobox } from '@base-ui/react/combobox'
+import { Select as BaseSelect } from '@base-ui/react/select'
+import { Search } from 'lucide-react'
+import { useRef, useState, type ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { useControllableState } from '../lib/useControllableState'
+import { Field, FieldLabel } from './Field'
+import type { SelectBaseProps } from './Select'
import {
- useEffect,
- useMemo,
- useRef,
- useState,
- forwardRef,
- type KeyboardEvent,
- type FocusEvent as ReactFocusEvent,
- type ReactNode,
-} from 'react'
-import { createPortal } from 'react-dom'
-import { ChevronDown, ChevronUp, X } from 'lucide-react'
-import { cn } from '@/lib/cn'
-import { omit } from '@/lib/omit'
-import { useClickOutside } from '@/lib/useClickOutside'
-import { useDropdownPosition, type DropdownPlacement } from '@/lib/useDropdownPosition'
-import { Spinner } from './Spinner'
-import { Tooltip } from './Tooltip'
-import type { SelectOption } from './NativeSelect'
+ ActionFooter,
+ Chevron,
+ ClearButton,
+ ComboboxOptions,
+ SelectOptions,
+ Spinner,
+ StatusRow,
+} from './SelectParts'
import {
- FLOATING_LABEL_SIZES,
- LABEL_SIZES,
- SELECT_SIZES,
- SELECT_THEME_CLASSES,
- SELECT_VARIANTS,
- SELECT_WIDTHS,
+ CLEAR_SPACER,
+ FLOATING_LABEL_BG,
+ comboboxItems,
+ hasGroups,
+ listClass,
+ popupClass,
+ summarize,
+ triggerClass,
+ type SelectOption,
type SelectSize,
- type SelectTheme,
+ type SelectValue,
type SelectVariant,
- type SelectWidth,
} from './select.tokens'
-/**
- * Custom select with a portalled dropdown, search, and a floating label.
- *
- * Ported from the source app's `Select/components/FeaturedSelect`.
- *
- * Two upstream bugs are corrected here, both flagged in comments at the point of
- * change: the themed classes were built as template strings (so Tailwind emitted
- * no rules for them), and a "cleared but still matching option" value kept the
- * control looking filled.
- */
-
-export type FeaturedSelectProps = Omit<
- React.HTMLAttributes,
- 'onChange' | 'onSelect' | 'defaultValue' | 'placeholder'
-> & {
- options?: SelectOption[]
- value?: string
- onChange?: (value: string) => void
- label?: string
- name?: string
- placeholder?: string
- size?: SelectSize
- theme?: SelectTheme
- variant?: SelectVariant
- width?: SelectWidth
- disabled?: boolean
- required?: boolean
- error?: string | { message?: string }
- isLoading?: boolean
- isClearable?: boolean
+export type FeaturedSelectProps = SelectBaseProps & {
+ /** Adds a search box to the popup that filters the options (Base UI Combobox). */
searchable?: boolean
- onSearchChange?: (term: string) => void
- /** Scrolls the selected option to the middle of the open list. */
- scrollToSelected?: boolean
- placement?: DropdownPlacement
- /** Stored label for a value whose option has not loaded yet. */
- initialSearchTerm?: string
- /** Floats the label even when the control is empty and unfocused. */
- shrink?: boolean
- floatinglabelClass?: string
- tooltip?: string
- tooltipIcon?: React.ComponentProps['icon']
- helpText?: string
- actionButton?: { label: string; onClick: () => void; icon?: ReactNode }
- renderOption?: (opt: SelectOption) => ReactNode
- onBlur?: (e: ReactFocusEvent) => void
+ /** Placeholder of the search box. */
+ searchPlaceholder?: string
+ /** Shown when the search matches no option. */
+ emptyText?: ReactNode
+ /** Fires as the user types in the search box. Use it to fetch options for an async search. */
+ onInputValueChange?: (inputValue: string) => void
+ /** Filters `options` by the search text. Turn off when the server filters them. */
+ filterOptions?: boolean
}
-export const FeaturedSelect = forwardRef(
- function FeaturedSelect(
- {
- options = [],
- value = '',
- onChange,
- label,
- name,
- placeholder = 'Select an option',
- size = 'md',
- theme = 'primary',
- variant = 'outlined',
- width = 'full',
- disabled = false,
- required = false,
- error,
- isLoading = false,
- isClearable = true,
- searchable = true,
- onSearchChange,
- scrollToSelected = false,
- placement = 'auto',
- initialSearchTerm = '',
- shrink = false,
- floatinglabelClass = '',
- tooltip,
- tooltipIcon,
- helpText,
- actionButton,
- renderOption,
- className = '',
- onBlur,
- ...props
- },
- ref,
- ) {
- const htmlProps = omit(props as Record, [
- 'shrink', 'hasMore', 'hasMoreKey', 'labelKey', 'valueKey', 'isMulti',
- 'staticOptions', 'endpoint', 'endpointParams', 'infiniteScroll',
- 'initialSearch', 'initialSearchTerm', 'initialQuery', 'searchBy',
- 'control', 'onMenuScroll', 'debounceTime', 'helpText', 'tooltip', 'tooltipIcon',
- 'isClearable', 'renderOption', 'onBlur',
- ])
+/** Resting left edge of the label, after the padding and any start icon. */
+const REST_LEFT: Record = {
+ sm: ['left-2.5', 'left-8'],
+ md: ['left-3', 'left-9'],
+ lg: ['left-4', 'left-11'],
+}
+/** Floated left edge: the padding minus the label chip's own padding. */
+const FLOAT_LEFT: Record = { sm: 'left-1.5', md: 'left-2', lg: 'left-3' }
- const [isOpen, setIsOpen] = useState(false)
- const [isFocused, setIsFocused] = useState(false)
- const [searchTerm, setSearchTerm] = useState(initialSearchTerm)
+function FloatingLabel({
+ floated,
+ open,
+ invalid,
+ size,
+ variant,
+ hasStartIcon,
+ required,
+ children,
+}: {
+ floated: boolean
+ open: boolean
+ invalid: boolean
+ size: SelectSize
+ variant: SelectVariant
+ hasStartIcon: boolean
+ required?: boolean
+ children: ReactNode
+}) {
+ return (
+
+ {children}
+
+ )
+}
- // `initialSearchTerm` is the stored label for the ONE value the field was
- // seeded with, so it stops being true the moment the user picks something
- // else. Tracking it beats comparing against `value`, because the seeded value
- // and its label arrive over several renders.
- const [hasUserSelected, setHasUserSelected] = useState(false)
+/**
+ * Select with a floating label inside the trigger: it rests where the value
+ * goes and floats onto the border when the popup opens or a value is chosen.
+ * Same API as Select, plus `searchable`, which filters the options through a
+ * search box in the popup (Base UI Combobox), and `actionButton`, a footer
+ * button such as "Add department".
+ */
+export function FeaturedSelect({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ readOnly,
+ size = 'md',
+ variant = 'outline',
+ placeholder = 'Select an option',
+ options,
+ multiple,
+ value: valueProp,
+ defaultValue,
+ onValueChange,
+ clearable,
+ loading,
+ loadingText = 'Loading options…',
+ renderOption,
+ startIcon,
+ name,
+ open: openProp,
+ defaultOpen = false,
+ onOpenChange,
+ side = 'bottom',
+ actionButton,
+ searchable,
+ searchPlaceholder = 'Search…',
+ emptyText = 'No results',
+ onInputValueChange,
+ filterOptions = true,
+ className,
+ triggerClassName,
+ ...props
+}: FeaturedSelectProps) {
+ const empty = (multiple ? [] : null) as SelectValue
+ const [value, setValue] = useControllableState>(
+ valueProp,
+ defaultValue ?? empty,
+ onValueChange,
+ )
+ const [open, setOpen] = useControllableState(openProp, defaultOpen, onOpenChange)
+ // Labels of chosen options, so the trigger keeps its text when async results change.
+ const [known, setKnown] = useState>({})
+ const wrapperRef = useRef(null)
- const containerRef = useRef(null)
- const dropdownRef = useRef(null)
+ const selectedValues: string[] = Array.isArray(value) ? value : value != null ? [value] : []
+ const selected = new Set(selectedValues)
+ const toOption = (v: string): SelectOption =>
+ options.find((o) => o.value === v) ?? { value: v, label: known[v] ?? v }
+ const selectedOptions = selectedValues.map(toOption)
+ const hasValue = selectedValues.length > 0
+ const floated = open || hasValue
+ const invalid = error != null && error !== false && error !== ''
+ const showClear = clearable && hasValue && !disabled && !readOnly && !loading
+ const grouped = hasGroups(options)
+ const display = hasValue ? summarize(selectedOptions.map((o) => o.label)) : placeholder
- useEffect(() => {
- if (initialSearchTerm) setSearchTerm(initialSearchTerm)
- // A new seed means a new record in the same mounted field (the next row
- // opened in a reused modal): the earlier pick no longer describes it.
- setHasUserSelected(false)
- }, [initialSearchTerm])
+ function clear() {
+ setValue(empty)
+ wrapperRef.current?.querySelector('button')?.focus()
+ }
- useEffect(() => {
- const node = containerRef.current
- if (typeof ref === 'function') ref(node)
- else if (ref) ref.current = node
- }, [ref])
+ const triggerProps = {
+ 'aria-invalid': invalid || undefined,
+ 'aria-busy': loading || undefined,
+ className: triggerClass(size, variant, triggerClassName),
+ ...props,
+ }
- // React's onBlur is focusout and bubbles. Opening the dropdown moves focus to
- // its autoFocus search input, which would otherwise read as a blur to the
- // consumer — validating a field the user has only just clicked into. The
- // dropdown is portalled, so it is not a descendant of containerRef: check
- // both roots.
- const handleContainerBlur = (event: ReactFocusEvent) => {
- if (!onBlur) return
- const next = event.relatedTarget
- if (
- next instanceof Node &&
- (containerRef.current?.contains(next) || dropdownRef.current?.contains(next))
- ) {
- return
- }
- onBlur(event)
- }
+ const triggerInner = (valueNode: ReactNode, icon: ReactNode) => (
+ <>
+ {startIcon != null && (
+
+ {startIcon}
+
+ )}
+ {valueNode}
+ {showClear && }
+ {icon}
+ >
+ )
- const safeOptions = Array.isArray(options) ? options : []
- const selectedOption = safeOptions.find((opt) => opt.value === value)
- const hasSelectedValue = value !== undefined && value !== null && value !== ''
+ const valueClass = cn('min-w-0 flex-1 truncate', !hasValue && 'text-fg-muted', !floated && 'invisible')
- // Prefer the resolved option; fall back to the caller-supplied label for a
- // value whose option has not been fetched yet.
- const displayLabel =
- selectedOption?.label || (hasSelectedValue && !hasUserSelected ? initialSearchTerm : '') || ''
+ const label_ = label != null && (
+
+ {label}
+
+ )
- const filteredOptions = useMemo(() => {
- // A server-side search hands us the filtered list; don't filter again.
- if (onSearchChange) return safeOptions
- return searchable && searchTerm
- ? safeOptions.filter((opt) => opt.label.toLowerCase().includes(searchTerm.toLowerCase()))
- : safeOptions
- }, [safeOptions, searchable, searchTerm, onSearchChange])
+ const clearButton = showClear && (
+
+ )
- // A long list opens at the top, leaving the current value scrolled out of
- // sight. Centred rather than 'nearest', which would pin the option to the
- // bottom edge with no surrounding years visible.
- useEffect(() => {
- if (!isOpen || !scrollToSelected) return
- const frame = requestAnimationFrame(() => {
- const list = dropdownRef.current
- const selected = list?.querySelector('[data-selected="true"]')
- selected?.scrollIntoView?.({ block: 'center' })
- })
- return () => cancelAnimationFrame(frame)
- }, [isOpen, scrollToSelected])
+ const footer = actionButton && setOpen(false)} />
- useClickOutside(
- [containerRef, dropdownRef],
- () => {
- setIsOpen(false)
- setIsFocused(false)
- },
- isOpen,
- )
+ const field = (children: ReactNode) => (
+
+ {children}
+
+ )
- const { dropdownPosition, calculateInitialPosition } = useDropdownPosition(
- isOpen,
- containerRef,
- { placement },
- )
-
- const handleToggle = () => {
- if (disabled) return
- if (!isOpen) calculateInitialPosition()
- setIsOpen((open) => !open)
- }
-
- const handleSelect = (val: string) => {
- onChange?.(val)
- setHasUserSelected(true)
- setIsOpen(false)
- setIsFocused(false)
- }
-
- // Derived from `value` alone. The source OR'd in the matched option, so an
- // option whose own value is '' (an "All departments" filter) kept the control
- // looking filled after the value was cleared — the field showed a label and a
- // clear button while the form held '', so a required field read as answered.
- const hasValue = hasSelectedValue
-
- // `displayLabel`, not `hasValue`: the all-pass option resolves to a label and
- // renders as text, so floating on hasValue alone left the label sitting on
- // top of that text. `required` floats too — a mandatory field's label carries
- // the asterisk and help icon, which read as content inside the box, and an
- // unfloated one leaves a column of required fields misaligned (Taiga #4140).
- const isFloating =
- shrink || hasValue || Boolean(displayLabel) || isFocused || isOpen || Boolean(error) || required
-
- const isUnderlined = variant === 'underlined'
- const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary
- const errorMessage = typeof error === 'string' ? error : error?.message
-
- // The floated label is a chip sitting on the border, which only reads against
- // a boxed outline. On the underlined variant there is no side border to punch
- // through, so lift it clear and drop the chip styling.
- const labelClass = isFloating
- ? cn(
- isUnderlined ? '-top-2.5 px-0 bg-transparent z-10' : 'top-[-0.6rem] px-1 bg-white z-10',
- FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md,
- errorMessage ? 'text-red-500' : themeClasses.label,
- floatinglabelClass,
- )
- : cn(
- 'top-1/2 -translate-y-1/2',
- LABEL_SIZES[size] ?? LABEL_SIZES.md,
- 'text-slate-400 pointer-events-none',
- )
-
- const dropdownContent = (
-
- {searchable && (
-
- {
- const next = e.target.value
- setSearchTerm(next)
- onSearchChange?.(next)
- }}
- onClick={(e) => e.stopPropagation()}
- />
-
- )}
-
- {filteredOptions.length > 0 ? (
- filteredOptions.map((opt) => {
- const isSelected = opt.value === value
- return (
-
!opt.disabled && handleSelect(opt.value)}
- >
- {renderOption ? renderOption(opt) : opt.label}
-
- )
- })
- ) : (
- !isLoading && (
-
No options found
+ if (searchable) {
+ return field(
+
{
+ const list = (Array.isArray(next) ? next : next ? [next] : []) as SelectOption[]
+ setKnown((prev) => ({ ...prev, ...Object.fromEntries(list.map((o) => [o.value, o.label])) }))
+ setValue(
+ (Array.isArray(next)
+ ? (next as SelectOption[]).map((o) => o.value)
+ : ((next as SelectOption | null)?.value ?? null)) as SelectValue,
)
- )}
-
- {isLoading && filteredOptions.length > 0 && (
-
-
-
- LOADING MORE...
-
-
- )}
-
- {actionButton && (
-
- {
- e.stopPropagation()
- actionButton.onClick()
- setIsOpen(false)
- }}
- className="w-full rounded bg-primary-600 px-2 py-1.5 text-xs font-semibold text-white"
- >
- {actionButton.label}
-
-
- )}
-
- )
-
- return (
- ) => {
- if (e.key === 'Enter') handleToggle()
- if (e.key === 'Escape') setIsOpen(false)
}}
- onBlur={handleContainerBlur}
- {...htmlProps}
+ isItemEqualToValue={(a: SelectOption, b: SelectOption) => a?.value === b?.value}
+ onInputValueChange={onInputValueChange ? (text) => onInputValueChange(text) : undefined}
+ filter={filterOptions ? undefined : null}
+ modal
+ open={open}
+ onOpenChange={setOpen}
+ name={name}
+ required={required}
+ disabled={disabled}
+ readOnly={readOnly}
>
-
- {/* Options load asynchronously (paginated + server-searched), so a saved
- value is often absent from `options` on first paint.
- `initialSearchTerm` carries the stored label for exactly that case —
- without it the field renders blank even though a value is set. */}
-
- {displayLabel || placeholder}
-
-
-
- {isLoading &&
}
- {isClearable && hasValue && !disabled && (
-
{
- e.stopPropagation()
- // onSearchChange first, so a consumer that sets its own term
- // inside onChange still wins.
- onSearchChange?.('')
- onChange?.('')
- setSearchTerm('')
- setHasUserSelected(true)
- }}
- />
+
+
+ {triggerInner(
+ {display} ,
+
+ {loading ? : }
+ ,
)}
- {isOpen ? (
-
- ) : (
-
- )}
-
-
- {label && (
-
-
-
- {label}
- {required && * }
-
- {(tooltip || helpText) && (
- e.stopPropagation()}
- onClick={(e) => e.preventDefault()}
- >
-
-
- )}
-
-
- )}
+
+ {label_}
+ {clearButton}
-
- {isOpen && !disabled && createPortal(dropdownContent, document.body)}
-
- {errorMessage && (
-
- {errorMessage}
-
- )}
-
+
+
+
+
+ {loading && {loadingText} }
+ {!loading && {emptyText} }
+ selected.has(v)} renderOption={renderOption} />
+ {footer}
+
+
+
+ ,
)
- },
-)
+ }
-export default FeaturedSelect
+ return field(
+
setValue(next as SelectValue)}
+ open={open}
+ onOpenChange={setOpen}
+ name={name}
+ required={required}
+ disabled={disabled}
+ readOnly={readOnly}
+ >
+
+
+ {triggerInner(
+ {() => display} ,
+
+ {loading ? : }
+ ,
+ )}
+
+ {label_}
+ {clearButton}
+
+
+ {/* Transparent: marks the modal popup's page as inert to pointers and to assistive checks. */}
+
+
+
+ {loading && {loadingText} }
+ {!loading && options.length === 0 && No options }
+
+ {!loading && (
+ selected.has(v)} renderOption={renderOption} />
+ )}
+
+ {footer}
+
+
+
+ ,
+ )
+}
diff --git a/src/components/FeaturedTextArea.stories.tsx b/src/components/FeaturedTextArea.stories.tsx
new file mode 100644
index 0000000..ba03021
--- /dev/null
+++ b/src/components/FeaturedTextArea.stories.tsx
@@ -0,0 +1,170 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { SIZES } from '../lib/styles'
+import { FeaturedTextArea } from './FeaturedTextArea'
+import { TEXT_FIELD_VARIANTS } from './featuredinput.tokens'
+
+const meta = {
+ title: 'Forms/FeaturedTextArea',
+ component: FeaturedTextArea,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'The floating-label version of `TextArea`, with the same props. The label rests where the first line of text goes and floats to the top of the box when the textarea is focused or filled (CSS only). The box reserves room for the floated label, so scrolled text never runs under it.',
+ },
+ },
+ },
+ argTypes: {
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ placeholder: { control: 'text', description: 'Shown once the label has floated, while the textarea is focused and empty.' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ variant: {
+ control: 'inline-radio',
+ options: TEXT_FIELD_VARIANTS,
+ table: { defaultValue: { summary: 'outline' } },
+ },
+ rows: { control: { type: 'number', min: 1, max: 12 }, table: { defaultValue: { summary: '3' } } },
+ resize: {
+ control: 'inline-radio',
+ options: ['none', 'vertical', 'both'],
+ table: { defaultValue: { summary: 'vertical' } },
+ },
+ autoResize: { control: 'boolean' },
+ maxRows: { control: { type: 'number', min: 1, max: 20 } },
+ maxLength: { control: { type: 'number', min: 1 } },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ readOnly: { control: 'boolean' },
+ value: { control: 'text' },
+ defaultValue: { control: 'text' },
+ name: { control: 'text' },
+ className: { control: 'text' },
+ textareaClassName: { control: 'text' },
+ onValueChange: { control: false },
+ onChange: { control: false },
+ },
+ args: {
+ label: 'Delivery instructions',
+ placeholder: 'Gate code, where to leave the parcel…',
+ size: 'md',
+ variant: 'outline',
+ rows: 3,
+ resize: 'vertical',
+ autoResize: false,
+ required: false,
+ disabled: false,
+ readOnly: false,
+ onValueChange: fn(),
+ onChange: fn(),
+ },
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+const note =
+ 'Leave the parcel with reception at Acme Corporation, 2nd floor. If nobody answers, call Jane Doe on the number in my profile.'
+
+export const Playground: Story = {}
+
+export const Filled: Story = {
+ args: { defaultValue: note },
+}
+
+export const WithDescription: Story = {
+ args: { description: 'Shared with the courier only.' },
+}
+
+export const WithError: Story = {
+ args: { required: true, error: 'Add instructions so the courier can find you.' },
+}
+
+export const Required: Story = {
+ args: { required: true },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: note },
+}
+
+export const ReadOnly: Story = {
+ args: { readOnly: true, defaultValue: note, description: 'The order has shipped, so this can’t change.' },
+}
+
+export const CharacterCounter: Story = {
+ args: { maxLength: 200, defaultValue: 'Ring the bell twice.' },
+}
+
+export const AutoResize: Story = {
+ args: { autoResize: true, rows: 2, maxRows: 5, defaultValue: `${note} ${note}` },
+}
+
+export const Variants: Story = {
+ render: (args) => (
+
+ {TEXT_FIELD_VARIANTS.map((variant) => (
+
+
+
+
+ ))}
+
+ ),
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+
+
+
+ ))}
+
+ ),
+}
+
+export const Uncontrolled: Story = {
+ args: { defaultValue: note, maxLength: 280 },
+}
+
+function ControlledFeaturedTextArea(args: Story['args']) {
+ const [value, setValue] = useState('Ring the bell twice.')
+ return (
+
+
{
+ setValue(next)
+ args?.onValueChange?.(next)
+ }}
+ />
+ Value: {value || '(empty)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) => ,
+}
diff --git a/src/components/FeaturedTextArea.test.tsx b/src/components/FeaturedTextArea.test.tsx
new file mode 100644
index 0000000..530d9d3
--- /dev/null
+++ b/src/components/FeaturedTextArea.test.tsx
@@ -0,0 +1,56 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { FeaturedTextArea } from './FeaturedTextArea'
+
+describe('FeaturedTextArea', () => {
+ it('uses the floating label as the accessible name', () => {
+ render( )
+ const textarea = screen.getByRole('textbox', { name: 'Delivery instructions' })
+ expect(textarea.tagName).toBe('TEXTAREA')
+ expect(textarea).toHaveAttribute('placeholder', ' ')
+ })
+
+ it('announces the description, then the error when invalid', () => {
+ const { rerender } = render( )
+ expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Shared with the courier.')
+ rerender( )
+ expect(screen.getByRole('textbox')).toHaveAttribute('aria-invalid', 'true')
+ expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Add instructions.')
+ })
+
+ it('shows the required mark without changing the name', () => {
+ render( )
+ expect(screen.getByRole('textbox', { name: 'Notes' })).toBeRequired()
+ })
+
+ it('works uncontrolled', async () => {
+ render( )
+ const textarea = screen.getByRole('textbox')
+ await userEvent.type(textarea, '{Enter}Thanks')
+ expect(textarea).toHaveValue('Ring twice\nThanks')
+ })
+
+ it('works controlled', async () => {
+ const onValueChange = vi.fn()
+ render( )
+ await userEvent.type(screen.getByRole('textbox'), '!')
+ expect(onValueChange).toHaveBeenLastCalledWith('Ring!')
+ expect(screen.getByRole('textbox')).toHaveValue('Ring')
+ })
+
+ it('counts characters', async () => {
+ render( )
+ expect(screen.getByText('0 / 200')).toBeInTheDocument()
+ await userEvent.type(screen.getByRole('textbox'), 'Hello')
+ expect(screen.getByText('5 / 200')).toBeInTheDocument()
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ ,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/FeaturedTextArea.tsx b/src/components/FeaturedTextArea.tsx
new file mode 100644
index 0000000..9ee1e04
--- /dev/null
+++ b/src/components/FeaturedTextArea.tsx
@@ -0,0 +1,12 @@
+import { TextAreaField, type TextAreaProps } from './TextArea'
+
+export type FeaturedTextAreaProps = TextAreaProps
+
+/**
+ * A multiline text field whose label sits inside the box and floats up when
+ * the textarea is focused or filled. Same props as TextArea. The label stays
+ * the accessible name.
+ */
+export function FeaturedTextArea(props: FeaturedTextAreaProps) {
+ return
+}
diff --git a/src/components/Field.stories.tsx b/src/components/Field.stories.tsx
new file mode 100644
index 0000000..da1d458
--- /dev/null
+++ b/src/components/Field.stories.tsx
@@ -0,0 +1,104 @@
+import { Input as BaseInput } from '@base-ui/react/input'
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { cn } from '../lib/cn'
+import { controlBox, controlHeight, focusRing } from '../lib/styles'
+import { Field } from './Field'
+
+/** A custom control: a Base UI Input with its own styling. Field links it to the label, description and error. */
+function HexInput({
+ required,
+ disabled,
+ defaultValue = '#4F46E5',
+ swatch = 'bg-primary-500',
+}: {
+ required?: boolean
+ disabled?: boolean
+ defaultValue?: string
+ swatch?: string
+}) {
+ return (
+
+
+
+
+ )
+}
+
+const meta = {
+ title: 'Forms/Field',
+ component: Field,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Wraps any Tansy or Base UI control with a label, description and error. The label is linked to the control, the description and error are added to `aria-describedby`, and `error` sets `aria-invalid`. Every form component uses it; use it directly to give a custom control the same wiring. Pass `required` to the control as well as to Field.',
+ },
+ },
+ },
+ argTypes: {
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ name: { control: 'text' },
+ nativeLabel: { control: 'boolean', table: { defaultValue: { summary: 'true' } } },
+ className: { control: 'text' },
+ children: { control: false },
+ },
+ args: {
+ label: 'Brand colour',
+ description: 'Used for buttons and links across Acme Corporation’s workspace.',
+ required: false,
+ disabled: false,
+ nativeLabel: true,
+ children: null,
+ },
+ render: (args) => (
+
+
+
+ ),
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const LabelOnly: Story = {
+ args: { description: undefined },
+}
+
+export const WithError: Story = {
+ args: { error: 'Enter a six-digit hex colour, like #4F46E5.' },
+}
+
+export const Required: Story = {
+ args: { required: true },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, description: 'Your plan doesn’t include custom branding.' },
+}
+
+/** Several custom controls in one form, each with its own Field. */
+export const Composition: Story = {
+ render: (args) => (
+
+
+
+
+
+
+
+
+ ),
+}
diff --git a/src/components/Field.tsx b/src/components/Field.tsx
new file mode 100644
index 0000000..94f8df9
--- /dev/null
+++ b/src/components/Field.tsx
@@ -0,0 +1,96 @@
+import { Field as BaseField } from '@base-ui/react/field'
+import type { ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { descriptionText, errorText, labelText, requiredMark } from '../lib/styles'
+
+export type FieldProps = {
+ /** Visible label. Base UI links it to the control inside. */
+ label?: ReactNode
+ /** Help text under the control, announced with it by screen readers. */
+ description?: ReactNode
+ /** Error message. When set, the field is marked invalid and the message is announced. */
+ error?: ReactNode
+ /** Adds the required mark to the label. Pass `required` to the control too. */
+ required?: boolean
+ disabled?: boolean
+ /** Identifies the field in a form. */
+ name?: string
+ /**
+ * Set to `false` when the control is a button (Select, Combobox trigger), so
+ * clicking the label focuses it without also pressing it.
+ */
+ nativeLabel?: boolean
+ className?: string
+ children: ReactNode
+}
+
+/**
+ * Wraps any Tansy or Base UI control with a label, description and error.
+ * Every form component uses it, so they all wire `aria-describedby`,
+ * `aria-invalid` and label association the same way.
+ */
+export function Field({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ name,
+ nativeLabel = true,
+ className,
+ children,
+}: FieldProps) {
+ const invalid = error != null && error !== false && error !== ''
+
+ return (
+
+ {label != null && (
+
+ {label}
+
+ )}
+ {children}
+ {description != null && !invalid && (
+ {description}
+ )}
+ {invalid && (
+
+ {error}
+
+ )}
+
+ )
+}
+
+/** The label on its own, for components that lay their field out differently. */
+export function FieldLabel({
+ required,
+ nativeLabel = true,
+ className,
+ children,
+}: {
+ required?: boolean
+ nativeLabel?: boolean
+ className?: string
+ children: ReactNode
+}) {
+ return (
+ }
+ className={cn(labelText, 'data-disabled:opacity-55', className)}
+ >
+ {children}
+ {required && (
+
+ *
+
+ )}
+
+ )
+}
diff --git a/src/components/Input.stories.tsx b/src/components/Input.stories.tsx
index 6ea9023..162cde6 100644
--- a/src/components/Input.stories.tsx
+++ b/src/components/Input.stories.tsx
@@ -1,143 +1,136 @@
-import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
+import { AtSign, Search } from 'lucide-react'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { SIZES } from '../lib/styles'
import { Input } from './Input'
const meta = {
title: 'Forms/Input',
component: Input,
tags: ['autodocs'],
+ // Fields read best at form width, not stretched across the canvas.
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
parameters: {
docs: {
description: {
component:
- 'Plain input with a label above. For a floating label, a built-in password toggle, and a Lucide icon slot, see the **FeaturedInput** story group — both are exported from here.',
+ 'A single-line text input with its label above. `description` and `error` are linked to the input for screen readers. For a floating label, use `FeaturedInput`.',
},
},
},
argTypes: {
- size: { control: 'select', options: ['sm', 'md', 'lg'] },
- theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
- type: { control: 'select', options: ['text', 'email', 'password', 'number', 'tel', 'url', 'date'] },
- iconPosition: { control: 'radio', options: ['left', 'right'] },
- roundedFull: { control: 'boolean' },
- dashedBorder: { control: 'boolean' },
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ placeholder: { control: 'text' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ variant: {
+ control: 'inline-radio',
+ options: ['outline', 'filled', 'underline'],
+ table: { defaultValue: { summary: 'outline' } },
+ },
+ type: { control: 'select', options: ['text', 'email', 'password', 'number', 'search', 'tel', 'url'] },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
- label: { control: 'text' },
- placeholder: { control: 'text' },
- error: { control: 'text' },
+ readOnly: { control: 'boolean' },
+ startAddon: { control: 'text' },
+ endAddon: { control: 'text' },
+ startIcon: { control: false },
+ endIcon: { control: false },
},
args: {
- label: 'Legal entity name',
- placeholder: 'Acme Corporation',
- type: 'text',
+ label: 'Work email',
+ placeholder: 'name@company.com',
+ type: 'email',
size: 'md',
- theme: 'primary',
- iconPosition: 'left',
- roundedFull: false,
- dashedBorder: false,
+ variant: 'outline',
required: false,
disabled: false,
- error: '',
+ readOnly: false,
+ onValueChange: fn(),
},
} satisfies Meta
export default meta
type Story = StoryObj
-function ControlledInput({
- initial = '',
- ...args
-}: React.ComponentProps & { initial?: string }) {
- const [value, setValue] = useState(initial)
- return setValue(e.target.value)} />
+export const Playground: Story = {}
+
+export const WithDescription: Story = {
+ args: { description: 'Payslips are sent to this address.' },
}
-export const Playground: Story = {
+export const WithError: Story = {
+ args: { defaultValue: 'jane.doe@', error: 'Enter a full email address, like name@example.com.' },
+}
+
+export const Required: Story = {
+ args: { required: true },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: 'jane@example.com' },
+}
+
+export const ReadOnly: Story = {
+ args: { readOnly: true, defaultValue: 'jane@example.com', description: 'Managed by your identity provider.' },
+}
+
+export const Variants: Story = {
render: (args) => (
-
-
-
- ),
-}
-
-export const Types: Story = {
- render: () => (
-
-
-
-
-
-
-
+
+
+
+
),
}
export const Sizes: Story = {
- render: () => (
-
- {(['sm', 'md', 'lg'] as const).map((size) => (
-
- ))}
-
- ),
-}
-
-export const Themes: Story = {
- render: () => (
-
- {(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
-
- ))}
-
- ),
-}
-
-export const WithError: Story = {
- render: () => (
-
-
-
- ),
-}
-
-export const Required: Story = {
- render: () => (
-
-
-
- ),
-}
-
-export const Disabled: Story = {
- render: () => (
-
- {}} />
-
- ),
-}
-
-export const BorderStyles: Story = {
- render: () => (
-
-
-
-
-
- ),
-}
-
-/** Requires the Remix Icon font; the `FeaturedInput` group below uses Lucide instead. */
-export const WithIconClass: Story = {
- args: { icon: 'ri-mail-line', placeholder: 'Email' },
render: (args) => (
-
-
+
+ {SIZES.map((size) => (
+
+ ))}
),
}
+
+export const WithIcons: Story = {
+ render: (args) => (
+
+ } />
+ } />
+
+ ),
+}
+
+export const WithAddons: Story = {
+ render: (args) => (
+
+
+
+
+ ),
+}
+
+function ControlledInput(args: Story['args']) {
+ const [value, setValue] = useState('Jane Doe')
+ return (
+
+
+
Value: {value || '(empty)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) =>
,
+}
diff --git a/src/components/Input.test.tsx b/src/components/Input.test.tsx
new file mode 100644
index 0000000..d517294
--- /dev/null
+++ b/src/components/Input.test.tsx
@@ -0,0 +1,64 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Input } from './Input'
+
+describe('Input', () => {
+ it('links the label to the input', () => {
+ render(
)
+ expect(screen.getByRole('textbox', { name: 'Work email' })).toBeInTheDocument()
+ })
+
+ it('announces the description with the input', () => {
+ render(
)
+ expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Payslips go here.')
+ })
+
+ it('marks the input invalid and announces the error', () => {
+ render(
)
+ const input = screen.getByRole('textbox')
+ expect(input).toHaveAttribute('aria-invalid', 'true')
+ expect(input).toHaveAccessibleDescription('Enter a full email address.')
+ })
+
+ it('works uncontrolled with defaultValue', async () => {
+ render(
)
+ const input = screen.getByRole('textbox')
+ expect(input).toHaveValue('Jane')
+ await userEvent.type(input, ' Doe')
+ expect(input).toHaveValue('Jane Doe')
+ })
+
+ it('works controlled and reports changes through onValueChange', async () => {
+ const onValueChange = vi.fn()
+ render(
)
+ await userEvent.type(screen.getByRole('textbox'), 'x')
+ expect(onValueChange).toHaveBeenLastCalledWith('Janex')
+ expect(screen.getByRole('textbox')).toHaveValue('Jane')
+ })
+
+ it('passes required and disabled to the input', () => {
+ render(
)
+ expect(screen.getByRole('textbox')).toBeRequired()
+ expect(screen.getByRole('textbox')).toBeDisabled()
+ })
+
+ it('gives each input a unique id without a name', () => {
+ render(
+ <>
+
+
+ >,
+ )
+ const [a, b] = screen.getAllByRole('textbox')
+ expect(a.id).not.toBe(b.id)
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+
} required />,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Input.tsx b/src/components/Input.tsx
index 9641ad0..c8a179c 100644
--- a/src/components/Input.tsx
+++ b/src/components/Input.tsx
@@ -1,145 +1,112 @@
-import { forwardRef, type InputHTMLAttributes, type ReactNode } from 'react'
-import { cn } from '@/lib/cn'
-import { omit } from '@/lib/omit'
-import {
- ICON_SIZES,
- INPUT_SIZES,
- INPUT_THEMES,
- LABEL_SIZES,
- type InputSize,
- type InputTheme,
-} from './input.tokens'
+import { Input as BaseInput } from '@base-ui/react/input'
+import type { ComponentProps, ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { controlBox, controlHeight, controlPaddingX, focusWithinRing, iconSize, type Size } from '../lib/styles'
+import { Field } from './Field'
-/**
- * Text input with a label above, optional icon, and error state.
- *
- * Ported from the original `Input` component.
- *
- * The source sets `opacity-90!` on the field, which dims the user's own typed
- * text; that is dropped here. `register` / `validation` (React Hook Form) are
- * not ported either — pass standard DOM props.
- *
- * `icon` is a class-name string (the source app uses Remix Icon, e.g.
- * `"ri-mail-line"`). Loading that font is a project-level choice, so the
- * showcase's stories use `FeaturedInput`'s Lucide slot instead where an icon is
- * really needed.
- */
-
-export type InputProps = Omit
, 'size'> & {
- label?: string
- size?: InputSize
- theme?: InputTheme
- /** Icon class name, e.g. `"ri-mail-line"`. Needs the icon font loaded. */
- icon?: string
- iconPosition?: 'left' | 'right'
- roundedFull?: boolean
- dashedBorder?: boolean
- error?: string | { message?: string }
- /** Rendered after the input, inside the field row. */
- trailing?: ReactNode
+export type InputProps = Omit, 'size' | 'value' | 'defaultValue'> & {
+ label?: ReactNode
+ /** Help text under the input. */
+ description?: ReactNode
+ /** Error message; marks the input invalid. */
+ error?: ReactNode
+ size?: Size
+ /** `outline` draws a box; `filled` a tinted box; `underline` a bottom rule. */
+ variant?: 'outline' | 'filled' | 'underline'
+ /** Icon inside the start of the input. */
+ startIcon?: ReactNode
+ /** Icon inside the end of the input. */
+ endIcon?: ReactNode
+ /** Text or element attached before the input, such as `https://`. */
+ startAddon?: ReactNode
+ /** Text or element attached after the input, such as `.com` or a button. */
+ endAddon?: ReactNode
+ value?: string | number
+ defaultValue?: string | number
+ /** Fires with the new value. Native `onChange` still works too. */
+ onValueChange?: (value: string) => void
+ /** Classes for the outer field wrapper. Use `inputClassName` for the input itself. */
+ className?: string
+ inputClassName?: string
}
-export const Input = forwardRef(function Input(
- {
- type = 'text',
- label = '',
- placeholder = '',
- disabled = false,
- required = false,
- icon,
- iconPosition = 'left',
- roundedFull = false,
- dashedBorder = false,
- size = 'md',
- theme = 'primary',
- className = '',
- name,
- error,
- trailing,
- ...props
- },
- ref,
-) {
- const htmlProps = omit(props as Record, ['hasMore', 'control', 'allValues', 'shrink'])
- const errorMessage = typeof error === 'string' ? error : error?.message
+const variants = {
+ outline: controlBox,
+ filled:
+ 'rounded-lg border border-transparent bg-surface-sunken text-fg transition-colors hover:bg-border/60 ' +
+ 'data-invalid:border-danger-500 has-[[aria-invalid=true]]:border-danger-500 has-disabled:opacity-55',
+ underline:
+ 'rounded-none border-0 border-b border-border-strong bg-transparent text-fg transition-colors hover:border-fg-subtle ' +
+ 'has-[[aria-invalid=true]]:border-danger-500 has-disabled:opacity-55',
+}
+const addon = 'flex items-center self-stretch bg-surface-muted px-3 text-fg-muted'
+
+/** A single-line text input with a label above it. For a floating label, use FeaturedInput. */
+export function Input({
+ label,
+ description,
+ error,
+ required,
+ disabled,
+ size = 'md',
+ variant = 'outline',
+ startIcon,
+ endIcon,
+ startAddon,
+ endAddon,
+ onValueChange,
+ className,
+ inputClassName,
+ name,
+ ...props
+}: InputProps) {
return (
-
- {label && (
-
- {label} {required && * }
-
- )}
-
-
- {icon && iconPosition === 'left' && (
-
+
+
-
- {icon && iconPosition === 'right' && (
-
- )}
-
- {trailing && (
-
- {trailing}
+ >
+ {startAddon != null && {startAddon} }
+ {startIcon != null && (
+
+ {startIcon}
)}
+ onValueChange(value) : undefined}
+ className={cn(
+ 'min-w-0 flex-1 bg-transparent text-fg outline-none placeholder:text-fg-subtle disabled:cursor-not-allowed',
+ variant === 'underline' ? 'px-0.5' : controlPaddingX[size],
+ startIcon != null && 'pl-2',
+ endIcon != null && 'pr-2',
+ inputClassName,
+ )}
+ {...props}
+ />
+ {endIcon != null && (
+
+ {endIcon}
+
+ )}
+ {endAddon != null && {endAddon} }
-
- {errorMessage && (
-
- {errorMessage}
-
- )}
-
+
)
-})
-
-export default Input
+}
diff --git a/src/components/Kbd.stories.tsx b/src/components/Kbd.stories.tsx
new file mode 100644
index 0000000..2672b1a
--- /dev/null
+++ b/src/components/Kbd.stories.tsx
@@ -0,0 +1,102 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { SIZES } from '../lib/styles'
+import { Kbd } from './Kbd'
+
+const meta = {
+ title: 'Display/Kbd',
+ component: Kbd,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Shows a key or a shortcut. Pass one key as `children`, or a combination as `keys` (`[\'⌘\', \'K\']`), which renders nested `` elements with a `separator`. Symbols such as ⌘ and ⇧ are announced by name.',
+ },
+ },
+ },
+ argTypes: {
+ keys: { control: 'object' },
+ separator: { control: 'text', table: { defaultValue: { summary: '+' } } },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ children: { control: 'text' },
+ },
+ args: {
+ keys: ['⌘', 'K'],
+ separator: '+',
+ size: 'md',
+ },
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const SingleKeys: Story = {
+ args: { keys: undefined },
+ render: (args) => (
+
+ {['Esc', 'Tab', '⇧', '⌘', '⌥', '↵', '⌫', '↑', '↓', 'A', '/'].map((k) => (
+
+ {k}
+
+ ))}
+
+ ),
+}
+
+export const Combinations: Story = {
+ render: (args) => (
+
+ ),
+}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+ ))}
+
+ ),
+}
+
+export const InContext: Story = {
+ parameters: { docs: { description: { story: 'Shortcut hints in a search field and a shortcut list.' } } },
+ render: () => (
+
+
+ Search components…
+
+
+
+ {[
+ ['Open command palette', ['⌘', 'K']],
+ ['Toggle dark mode', ['⌘', '⇧', 'L']],
+ ['Go to inbox', ['G', 'I']],
+ ['Close dialog', ['Esc']],
+ ].map(([action, keys]) => (
+
+
{action as string}
+
+
+
+
+ ))}
+
+
+ Press / to focus search, or ? to see every shortcut.
+
+
+ ),
+}
diff --git a/src/components/Kbd.test.tsx b/src/components/Kbd.test.tsx
new file mode 100644
index 0000000..995bf6b
--- /dev/null
+++ b/src/components/Kbd.test.tsx
@@ -0,0 +1,35 @@
+import { render, screen } from '@testing-library/react'
+import { describe, expect, it } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { Kbd } from './Kbd'
+
+describe('Kbd', () => {
+ it('renders a single key', () => {
+ const { container } = render(Esc )
+ expect(container.querySelector('kbd')).toHaveTextContent('Esc')
+ })
+
+ it('renders a combination as nested kbd elements with separators', () => {
+ const { container } = render( )
+ const outer = container.firstElementChild!
+ expect(outer.tagName).toBe('KBD')
+ expect(outer.querySelectorAll('kbd')).toHaveLength(2)
+ expect(outer).toHaveTextContent('⌘Command+K')
+ })
+
+ it('names symbols for screen readers', () => {
+ render( )
+ expect(screen.getByText('⇧')).toHaveAttribute('aria-hidden', 'true')
+ expect(screen.getByText('Shift')).toHaveClass('sr-only')
+ expect(screen.queryByText('+')).not.toBeInTheDocument()
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+
+ Press or /
+
,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/Kbd.tsx b/src/components/Kbd.tsx
new file mode 100644
index 0000000..195f817
--- /dev/null
+++ b/src/components/Kbd.tsx
@@ -0,0 +1,54 @@
+import { Fragment, type ComponentProps, type ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { KBD_GAP, KBD_SIZES, KBD_SYMBOL_NAMES, type KbdSize } from './kbd.tokens'
+
+export type KbdProps = ComponentProps<'kbd'> & {
+ /** A key combination, e.g. `['⌘', 'K']`. Symbols are announced by name ("Command"). Overrides `children`. */
+ keys?: string[]
+ /** Shown between keys. Pass `null` for none. */
+ separator?: ReactNode
+ size?: KbdSize
+}
+
+const keyCap =
+ 'inline-flex items-center justify-center border border-border-strong border-b-2 bg-surface-muted ' +
+ 'font-sans font-medium leading-none text-fg-muted shadow-[inset_0_-1px_0_var(--color-border)] whitespace-nowrap'
+
+function KeyLabel({ value }: { value: string }) {
+ const spoken = KBD_SYMBOL_NAMES[value]
+ if (!spoken) return <>{value}>
+ return (
+ <>
+ {value}
+ {spoken}
+ >
+ )
+}
+
+/** Displays a keyboard key or a shortcut such as ⌘ K. */
+export function Kbd({ keys, separator = '+', size = 'md', className, children, ...props }: KbdProps) {
+ if (!keys) {
+ return (
+
+ {typeof children === 'string' ? : children}
+
+ )
+ }
+
+ return (
+
+ {keys.map((key, i) => (
+
+ {i > 0 && separator != null && separator !== '' && (
+
+ {separator}
+
+ )}
+
+
+
+
+ ))}
+
+ )
+}
diff --git a/src/components/NativeSelect.stories.tsx b/src/components/NativeSelect.stories.tsx
new file mode 100644
index 0000000..9c4a150
--- /dev/null
+++ b/src/components/NativeSelect.stories.tsx
@@ -0,0 +1,161 @@
+import type { Meta, StoryObj } from '@storybook/react-vite'
+import { Globe } from 'lucide-react'
+import { useState } from 'react'
+import { fn } from 'storybook/test'
+import { SIZES } from '../lib/styles'
+import { Input } from './Input'
+import { NativeSelect } from './NativeSelect'
+import { COUNTRIES, CURRENCIES, DEPARTMENTS } from './select.fixtures'
+import { SELECT_VARIANTS } from './select.tokens'
+
+const meta = {
+ title: 'Forms/NativeSelect',
+ component: NativeSelect,
+ tags: ['autodocs'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ "A styled native `` with its label above. It opens the platform's own picker, which suits mobile and simple forms, and submits like any form field. Options with a `group` become ``s; `placeholder` adds an empty first option. For search, multiple values or rich options, use `Select`, `FeaturedSelect` or `Combobox`.",
+ },
+ },
+ },
+ argTypes: {
+ label: { control: 'text' },
+ description: { control: 'text' },
+ error: { control: 'text' },
+ placeholder: { control: 'text' },
+ size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
+ variant: { control: 'inline-radio', options: SELECT_VARIANTS, table: { defaultValue: { summary: 'outline' } } },
+ required: { control: 'boolean' },
+ disabled: { control: 'boolean' },
+ loading: { control: 'boolean' },
+ name: { control: 'text' },
+ options: { control: 'object' },
+ value: { control: 'text' },
+ defaultValue: { control: 'text' },
+ className: { control: 'text' },
+ selectClassName: { control: 'text' },
+ startIcon: { control: false },
+ onValueChange: { control: false },
+ onChange: { control: false },
+ },
+ args: {
+ label: 'Department',
+ placeholder: 'Select a department',
+ options: DEPARTMENTS,
+ size: 'md',
+ variant: 'outline',
+ required: false,
+ disabled: false,
+ loading: false,
+ onValueChange: fn(),
+ onChange: fn(),
+ },
+ decorators: [
+ // Forms sit on a surface, as they would in a card or dialog.
+ (Story, { parameters }) => (
+
+
+
+ ),
+ ],
+} satisfies Meta
+
+export default meta
+type Story = StoryObj
+
+export const Playground: Story = {}
+
+export const Sizes: Story = {
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+ ))}
+
+ ),
+}
+
+export const Variants: Story = {
+ render: (args) => (
+
+ {SELECT_VARIANTS.map((variant) => (
+
+ ))}
+
+ ),
+}
+
+/** NativeSelect and Input share control heights. */
+export const AlignedWithInput: Story = {
+ parameters: { wide: true },
+ render: (args) => (
+
+ {SIZES.map((size) => (
+
+
+
+
+ ))}
+
+ ),
+}
+
+export const WithDescription: Story = {
+ args: { description: 'Payroll reports are grouped by department.' },
+}
+
+export const WithError: Story = {
+ args: { error: 'Choose the department this person reports to.', required: true },
+}
+
+export const Required: Story = {
+ args: { required: true, name: 'department' },
+}
+
+export const Disabled: Story = {
+ args: { disabled: true, defaultValue: 'fin' },
+}
+
+export const Loading: Story = {
+ args: { loading: true, options: [], placeholder: 'Loading departments…' },
+}
+
+/** Grouped options become ``s. */
+export const Grouped: Story = {
+ args: { label: 'Payroll currency', placeholder: 'Select a currency', options: CURRENCIES },
+}
+
+export const WithStartIcon: Story = {
+ args: { label: 'Country', placeholder: 'Select a country', options: COUNTRIES, startIcon: },
+}
+
+/** 50 countries in the platform picker. */
+export const LongList: Story = {
+ args: { label: 'Country of residence', placeholder: 'Select a country', options: COUNTRIES, defaultValue: 'pt' },
+}
+
+function ControlledNativeSelect(args: Story['args']) {
+ const [value, setValue] = useState('ops')
+ return (
+
+
+
Value: {value || '(none)'}
+
+ )
+}
+
+export const Controlled: Story = {
+ render: (args) => ,
+}
+
+export const Uncontrolled: Story = {
+ args: { defaultValue: 'sales', name: 'department' },
+}
diff --git a/src/components/NativeSelect.test.tsx b/src/components/NativeSelect.test.tsx
new file mode 100644
index 0000000..445a383
--- /dev/null
+++ b/src/components/NativeSelect.test.tsx
@@ -0,0 +1,94 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+import { expectNoA11yViolations } from '../test/a11y'
+import { NativeSelect } from './NativeSelect'
+import type { SelectOption } from './select.tokens'
+
+const currencies: SelectOption[] = [
+ { value: 'usd', label: 'US Dollar', group: 'Americas' },
+ { value: 'cad', label: 'Canadian Dollar', group: 'Americas' },
+ { value: 'eur', label: 'Euro', group: 'Europe' },
+ { value: 'gbp', label: 'Pound Sterling', group: 'Europe', disabled: true },
+]
+
+const plain: SelectOption[] = [
+ { value: 'eng', label: 'Engineering' },
+ { value: 'fin', label: 'Finance' },
+]
+
+describe('NativeSelect', () => {
+ it('links the label to the select', () => {
+ render( )
+ expect(screen.getByRole('combobox', { name: 'Department' })).toBeInTheDocument()
+ })
+
+ it('renders groups as optgroups and a placeholder option', () => {
+ render( )
+ const select = screen.getByRole('combobox', { name: 'Currency' })
+ expect(select).toHaveValue('')
+ expect(screen.getAllByRole('group').map((g) => g.getAttribute('label'))).toEqual(['Americas', 'Europe'])
+ expect(screen.getByRole('option', { name: 'Pound Sterling' })).toBeDisabled()
+ })
+
+ it('works uncontrolled and fires onValueChange and onChange', async () => {
+ const onValueChange = vi.fn()
+ const onChange = vi.fn()
+ render( )
+ const select = screen.getByRole('combobox', { name: 'Department' })
+ expect(select).toHaveValue('eng')
+ await userEvent.selectOptions(select, 'fin')
+ expect(select).toHaveValue('fin')
+ expect(onValueChange).toHaveBeenCalledWith('fin')
+ expect(onChange).toHaveBeenCalled()
+ })
+
+ it('works controlled', async () => {
+ function Controlled() {
+ const [value, setValue] = useState('fin')
+ return (
+ <>
+
+ {value}
+ >
+ )
+ }
+ render( )
+ const select = screen.getByRole('combobox', { name: 'Department' })
+ expect(select).toHaveValue('fin')
+ await userEvent.selectOptions(select, 'eng')
+ expect(screen.getByTestId('value')).toHaveTextContent('eng')
+ expect(select).toHaveValue('eng')
+ })
+
+ it('announces the description, and the error when invalid', () => {
+ const { rerender } = render( )
+ expect(screen.getByRole('combobox')).toHaveAccessibleDescription('Where they report.')
+ rerender( )
+ expect(screen.getByRole('combobox')).toHaveAttribute('aria-invalid', 'true')
+ expect(screen.getByRole('combobox')).toHaveAccessibleDescription('Choose one.')
+ })
+
+ it('passes required, disabled and name to the select', () => {
+ render( )
+ const select = screen.getByRole('combobox', { name: /Department/ })
+ expect(select).toBeRequired()
+ expect(select).toBeDisabled()
+ expect(select).toHaveAttribute('name', 'department')
+ })
+
+ it('is disabled and busy while loading', () => {
+ render( )
+ const select = screen.getByRole('combobox', { name: 'Department' })
+ expect(select).toBeDisabled()
+ expect(select).toHaveAttribute('aria-busy', 'true')
+ })
+
+ it('has no axe violations', async () => {
+ const { container } = render(
+ ,
+ )
+ await expectNoA11yViolations(container)
+ })
+})
diff --git a/src/components/NativeSelect.tsx b/src/components/NativeSelect.tsx
index 92b5f67..1e28c3e 100644
--- a/src/components/NativeSelect.tsx
+++ b/src/components/NativeSelect.tsx
@@ -1,192 +1,147 @@
-import { forwardRef, useState, type ChangeEvent, type FocusEvent } from 'react'
-import { ChevronDown, X } from 'lucide-react'
-import { cn } from '@/lib/cn'
-import { omit } from '@/lib/omit'
-import { Spinner } from './Spinner'
-import {
- LABEL_SIZES,
- SELECT_SIZES,
- SELECT_THEME_CLASSES,
- SELECT_VARIANTS,
- SELECT_WIDTHS,
- type SelectSize,
- type SelectTheme,
- type SelectVariant,
- type SelectWidth,
-} from './select.tokens'
-
-/**
- * Select over a native ``.
- *
- * Ported from the source app's `Select/components/NativeSelect`, and used by
- * `Select` when `featured` is false.
- *
- * The source writes its themed border as `` `border-${themeColor}-500` ``, which
- * Tailwind's scanner cannot see — so the focused state had no styling. Here the
- * classes come from a static map, and `border` / `ring` colour utilities are set
- * per element so they survive Tailwind's tree.
- */
-
-export type SelectOption = { label: string; value: string; disabled?: boolean }
+import { Field as BaseField } from '@base-ui/react/field'
+import type { ComponentProps, ReactNode } from 'react'
+import { cn } from '../lib/cn'
+import { controlHeight, controlPaddingX, focusRing, iconSize } from '../lib/styles'
+import { Field } from './Field'
+import { Chevron, Spinner } from './SelectParts'
+import { FIELD_BOX, groupOptions, type SelectOption, type SelectSize, type SelectVariant } from './select.tokens'
export type NativeSelectProps = Omit<
- React.SelectHTMLAttributes,
- 'size' | 'value' | 'onChange'
+ ComponentProps<'select'>,
+ 'size' | 'value' | 'defaultValue' | 'multiple' | 'className' | 'children'
> & {
- options?: SelectOption[]
- value?: string
- onChange?: (value: string) => void
- label?: string
- name?: string
- placeholder?: string
+ /** Visible label, linked to the select. */
+ label?: ReactNode
+ /** Help text under the select, announced with it. */
+ description?: ReactNode
+ /** Error message. Marks the select invalid and replaces `description`. */
+ error?: ReactNode
size?: SelectSize
- theme?: SelectTheme
+ /** `outline` draws a bordered box; `filled` a tinted one. */
variant?: SelectVariant
- width?: SelectWidth
- disabled?: boolean
- required?: boolean
- error?: string | { message?: string }
- isLoading?: boolean
- isClearable?: boolean
+ /** The choices. Options sharing a `group` become an ``. */
+ options: SelectOption[]
+ /** A first, empty option shown while nothing is chosen. */
+ placeholder?: string
+ /** The selected value (controlled). `''` selects the placeholder. */
+ value?: string
+ /** The initial value (uncontrolled). */
+ defaultValue?: string
+ /** Fires with the new value. Native `onChange` still works too. */
+ onValueChange?: (value: string) => void
+ /** Disables the select and shows a spinner while options load. */
+ loading?: boolean
+ /** Icon before the value. */
+ startIcon?: ReactNode
+ /** Classes for the outer field wrapper. Use `selectClassName` for the select itself. */
+ className?: string
+ selectClassName?: string
}
-export const NativeSelect = forwardRef(
- function NativeSelect(
- {
- options = [],
- value = '',
- onChange,
- label,
- name,
- placeholder = 'Select an option',
- size = 'md',
- theme = 'primary',
- variant = 'outlined',
- width = 'full',
- disabled = false,
- required = false,
- error,
- isLoading = false,
- isClearable = true,
- className = '',
- onFocus,
- onBlur,
- ...props
- },
- ref,
- ) {
- const [isFocused, setIsFocused] = useState(false)
+const START_ICON_PAD: Record = { sm: 'pl-8', md: 'pl-9', lg: 'pl-11' }
+const END_PAD: Record