1 Commits
Author SHA1 Message Date
thekhalidsha f01de83733 Rebuild Tansy UI on Base UI with one API and dark mode (v0.3.0)
Every component is rebuilt on @base-ui/react with a single prop API,
token-only colours and dark mode, and 28 new components are added.

Components
- New: Field, FeaturedTextArea, NumberInput, Combobox, CheckboxGroup,
  Slider, ToggleGroup/Toggle, IconButton, Dialog/Modal, AlertDialog,
  Drawer/Sheet, Popover, InfoTip, DropdownMenu, Tabs, Breadcrumb,
  Pagination, Toast (Toaster, useToast), Progress, Meter, Skeleton,
  CountBadge, Avatar/AvatarGroup, Kbd, Separator, Table
- Rewritten: Button, Input, FeaturedInput, TextArea, Select,
  FeaturedSelect (real ARIA combobox), NativeSelect, Checkbox, Radio,
  Switch, Tooltip, Accordion, Alert, Spinner, Badge, Card
- Removed TextField (use Input) and sonner (use Toast)

Foundations
- Semantic tokens (surfaces, text, borders, status ramps) in
  src/styles/tokens.css, with class-based dark mode
- Visible focus rings, linked labels/descriptions/errors, alert roles by
  severity, keyboard support from Base UI
- Fixed the Classic Blue ramp; Emerald, Amber and Teal 500 steps now
  carry white text at AA
- Library build (per-component ES modules, types, tokens.css, exports)

Quality
- Vitest, Testing Library and axe tests for every component (289 tests)
- scripts/check-stories.mjs renders every story in Chrome and fails on
  errors or axe violations, including contrast; all 423 stories pass in
  light and dark mode and in all seven palettes
- Storybook: controls for every prop, open states for every popup,
  light/dark toolbar, Introduction guides, docs/CONVENTIONS.md

BREAKING CHANGE: component props changed across the kit; see CHANGELOG.md.
2026-09-28 21:12:11 +05:30
185 changed files with 22542 additions and 5182 deletions

No files matched your search

+1
View File
@@ -1,6 +1,7 @@
node_modules
dist
dist-ssr
dist-lib
storybook-static
*.local
.DS_Store
+28 -3
View File
@@ -1,8 +1,33 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"plugins": [
"react",
"typescript",
"oxc"
],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
"react/only-export-components": [
"warn",
{
"allowConstantExport": true
}
]
},
"overrides": [
{
"files": [
"src/components/Card.tsx",
"src/components/Dialog.tsx",
"src/components/Drawer.tsx",
"src/components/DropdownMenu.tsx",
"src/components/Popover.tsx",
"src/components/Table.tsx",
"src/components/Tabs.tsx"
],
"rules": {
"react/only-export-components": "off"
}
}
]
}
+33
View File
@@ -0,0 +1,33 @@
import { useEffect, type ReactNode } from 'react'
import { applyPalette } from '../src/theme/applyPalette'
import type { PaletteName } from '../src/theme/palettes'
/**
* Applies the toolbar's palette and light/dark mode to <html>.
*
* It has to be the root element, not a wrapper: Base UI renders popups (menus,
* selects, dialogs, toasts) into a portal on document.body, and they must pick
* up the same tokens as the story.
*/
export function ThemeSurface({
palette,
mode,
padded,
children,
}: {
palette: PaletteName
mode: 'light' | 'dark'
padded: boolean
children: ReactNode
}) {
useEffect(() => {
const root = document.documentElement
applyPalette(root, palette)
root.classList.toggle('dark', mode === 'dark')
root.dataset.palette = palette
document.body.style.background = 'var(--color-background)'
document.body.style.color = 'var(--color-fg)'
}, [palette, mode])
return <div style={{ padding: padded ? '1.5rem' : 0, minHeight: '100%' }}>{children}</div>
}
+9 -1
View File
@@ -1,8 +1,16 @@
import type { StorybookConfig } from '@storybook/react-vite'
import remarkGfm from 'remark-gfm'
const config: StorybookConfig = {
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(ts|tsx)'],
addons: ['@storybook/addon-docs', '@storybook/addon-a11y'],
addons: [
{
name: '@storybook/addon-docs',
// GitHub-flavoured Markdown, so tables in the Introduction pages render.
options: { mdxPluginOptions: { mdxCompileOptions: { remarkPlugins: [remarkGfm] } } },
},
'@storybook/addon-a11y',
],
framework: {
name: '@storybook/react-vite',
options: {},
+35 -48
View File
@@ -1,52 +1,36 @@
import { useEffect, useRef, type ReactElement } from 'react'
import type { Decorator, Preview } from '@storybook/react-vite'
import '../src/index.css'
import { applyPalette } from '../src/theme/applyPalette'
import { palettes, DEFAULT_PALETTE, type PaletteName } from '../src/theme/palettes'
import { tansyTheme } from './tansyTheme'
import { ThemeSurface } from './ThemeSurface'
/**
* Wraps every story in a themed surface.
*
* The palette globals are set on this wrapper rather than on
* `document.documentElement` so a story can opt into a *different* palette on
* its own subtree without fighting the global one, and so the docs page keeps
* its own chrome.
*
* Declared as a named component (not an inline arrow) so the rules-of-hooks lint
* recognises the hook calls below.
*/
function PaletteSurface({ palette, children }: { palette: PaletteName; children: ReactElement }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current) applyPalette(ref.current, palette)
}, [palette])
return (
<div
ref={ref}
data-palette={palette}
style={{
padding: '1.5rem',
minHeight: '100%',
color: 'var(--color-gray-900)',
}}
>
{children}
</div>
)
}
const withPalette: Decorator = (Story, context) => {
const withTheme: Decorator = (Story, context) => {
const palette = (context.globals.palette ?? DEFAULT_PALETTE) as PaletteName
return <PaletteSurface palette={palette}><Story /></PaletteSurface>
const mode = context.globals.mode === 'dark' ? 'dark' : 'light'
const padded = context.parameters.layout !== 'fullscreen'
return (
<ThemeSurface palette={palette} mode={mode} padded={padded}>
<Story />
</ThemeSurface>
)
}
const preview: Preview = {
title: 'Tansy UI / Component Workshop',
decorators: [withPalette],
decorators: [withTheme],
globalTypes: {
mode: {
description: 'Light or dark mode for every component and popup.',
toolbar: {
title: 'Mode',
icon: 'contrast',
items: [
{ value: 'light', title: 'Light', icon: 'sun' },
{ value: 'dark', title: 'Dark', icon: 'moon' },
],
dynamicTitle: true,
},
},
palette: {
description: 'Brand palette applied to every element in the canvas.',
toolbar: {
@@ -61,28 +45,31 @@ const preview: Preview = {
},
},
initialGlobals: {
mode: 'light',
palette: DEFAULT_PALETTE,
},
parameters: {
backgrounds: { disable: true },
docs: {
theme: tansyTheme,
},
options: {
storySort: {
order: ['Welcome', 'Actions', 'Forms', 'Data entry', 'Feedback', 'Display', 'Layout', 'Navigation', 'Overlays'],
order: [
'Introduction',
['Welcome', 'Getting started', 'Theming', 'Accessibility', 'Changelog', 'Roadmap'],
'Actions',
'Forms',
'Feedback',
'Display',
'Layout',
'Navigation',
'Overlays',
],
},
},
backgrounds: {
default: 'showcase',
values: [
{ name: 'showcase', value: '#f3f4f6' },
{ name: 'surface', value: '#ffffff' },
{ name: 'dark', value: '#12151c' },
],
},
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
+74
View File
@@ -7,6 +7,80 @@ All notable changes to Tansy UI are recorded here. The format follows
## [Unreleased]
## [0.3.0] - 2026-09-28
A rebuild on Base UI with one consistent API, dark mode, and 28 new components.
This release changes most component props; see **Breaking** below.
### Added
- **New components:** Field, FeaturedTextArea, NumberInput, Combobox,
CheckboxGroup, Slider, ToggleGroup and Toggle, IconButton, Dialog (also
`Modal`), AlertDialog, Drawer (also `Sheet`), Popover, InfoTip,
DropdownMenu, Tabs, Breadcrumb, Pagination, Toast (`Toaster` and
`useToast`), Progress, Meter, Skeleton, CountBadge, Avatar and AvatarGroup,
Kbd, Separator and Table.
- **Dark mode:** add the `dark` class to `<html>`. Surface, border and text
tokens switch, and every story is checked for contrast in both modes.
- **Semantic tokens:** surfaces (`bg-surface`, `text-fg`, `border-border`…)
and 50–900 status scales for success, warning, danger and info.
- **Library build:** `npm run build:lib` produces per-component ES modules,
type declarations and `tokens.css`, with `exports` in package.json.
- **Tests:** Vitest, Testing Library and axe tests for every component
(`npm test`), and `scripts/check-stories.mjs`, which renders every story in
Chrome in light and dark mode and fails on errors or axe violations.
- **Storybook:** Introduction section (Welcome, Getting started, Theming,
Accessibility, Changelog, Roadmap), a light/dark Mode toolbar, controls for
every prop, and "open" stories for every popup.
- **Landing page:** version pill, "Why Tansy" section, roadmap section and a
full footer.
- `docs/CONVENTIONS.md` (component rules) and `docs/ROADMAP.md`.
### Changed
- Interactive components are built on `@base-ui/react`: focus management,
keyboard navigation and ARIA come from its WAI-ARIA patterns.
- Every interactive element shows a visible focus ring.
- Form fields link their label, description and error for screen readers.
- The Classic Blue ramp is monotonic (700, 800 and 900 were out of order).
- Status colours are the same in every palette.
- Emerald, Amber and Teal: the 500 step is one shade darker, so white text on
solid buttons and checked controls meets WCAG AA (it was 3.2–3.8:1).
- Alert uses `role="alert"` only for danger and warning.
- The landing page bundle is 35% smaller: icons are imported individually.
### Breaking
- **Colour and style props:** `color` is the semantic colour
(`primary | neutral | success | warning | danger | info`) and `variant` is
the visual style. The old `theme` props and colour names (`blue`, `red`) are
gone. Button variants are now `solid | soft | outline | ghost | link`.
- **Icons** are `ReactNode` props (`startIcon`, `endIcon`, `icon`). Lucide
component references, icon-name strings and Remix Icon class strings are
no longer accepted.
- **Values:** Select, Radio, Slider and friends use `value`, `defaultValue`
and `onValueChange(value)`. Checkbox and Switch use `checked`,
`defaultChecked` and `onCheckedChange(checked)`.
- **Field text:** `label`, `description` and `error` (a node) everywhere,
replacing `hint`, `helpText` and `{ message }` objects. Inline help
tooltips are replaced by `description` or `InfoTip`.
- **Badge:** content is `children`; the floating count is `CountBadge`.
- **Card:** `variant` and `padding` replace `theme`, `shadow` and `rounded`.
- **Alert:** content is `children`; `dismissible` and `onOpenChange` replace
`showCloseButton` and `onClose`; `icon` replaces `iconName`.
- **Tooltip:** wraps its trigger (`children`); `side` replaces `position`.
Icon-only help triggers are `InfoTip`.
- **Removed:** TextField (use Input), and the `featured` prop on Select and
TextArea (use FeaturedSelect and FeaturedTextArea).
- `sonner` is no longer a dependency; use Toast.
### Fixed
- Tables in Storybook docs pages render (GitHub-flavoured Markdown).
- The landing page's mobile header rules, which a stray edit had broken.
- TextField ignored `value`; Switch ignored `defaultChecked`; several fields
broke without a `name` or when two shared one.
## [0.2.0] - 2026-09-28
First tagged release.
+64 -32
View File
@@ -19,42 +19,53 @@ Every part ships with:
- **Its states.** Error, disabled, loading and required are part of the component, and each has its own story.
- **Tokens, not hex codes.** Colours come from a 50–900 palette ramp, so switching the palette re-themes every part without a code change.
> **Status:** pre-release (v0.2.0). Tansy UI is not published to npm yet. It is developed in this repository, with a landing page and a Storybook workshop as its showcase.
> **Status:** pre-release (v0.3.0). Tansy UI builds as a library (`npm run build:lib`) but is not published to npm yet. It is developed in this repository, with a landing page and a Storybook workshop as its showcase.
## Components
Built on [Base UI](https://base-ui.com) for accessible behaviour, styled with Tailwind CSS v4.
| Group | Components |
|---|---|
| Actions | `Button`, `LinkButton` |
| Forms | `Input`, `FeaturedInput`, `Select`, `Checkbox`, `Radio`, `Switch`, `TextArea` |
| Data entry | `TextField` |
| Feedback | `Alert`, `Spinner` |
| Display | `Badge` |
| Layout | `Card` (with `Card.Header`, `Card.Title`, `Card.Body`, `Card.Footer`) |
| Navigation | `Accordion` |
| Overlays | `Tooltip` |
| Actions | `Button`, `IconButton`, `LinkButton`, `ToggleGroup`, `Toggle` |
| Forms | `Field`, `Input`, `FeaturedInput`, `TextArea`, `FeaturedTextArea`, `NumberInput`, `Select`, `FeaturedSelect`, `Combobox`, `NativeSelect`, `Checkbox`, `CheckboxGroup`, `Radio`, `Switch`, `Slider` |
| Overlays | `Dialog` (`Modal`), `AlertDialog`, `Drawer` (`Sheet`), `Popover`, `Tooltip`, `InfoTip`, `DropdownMenu` |
| Navigation | `Tabs`, `Accordion`, `Breadcrumb`, `Pagination` |
| Feedback | `Alert`, `Toast` (`Toaster`, `useToast`), `Spinner`, `Progress`, `Meter`, `Skeleton` |
| Display | `Badge`, `CountBadge`, `Avatar`, `AvatarGroup`, `Kbd`, `Table` |
| Layout | `Card`, `Separator` |
Each component lives in `src/components/` with its style maps in a sibling `*.tokens.ts` and its stories in `*.stories.tsx`.
Every component follows one API (see [`docs/CONVENTIONS.md`](docs/CONVENTIONS.md)):
- `color` for meaning and `variant` for style;
- `size` of `sm`, `md` or `lg`;
- `startIcon` and `endIcon` as React nodes;
- `label`, `description` and `error` on every field;
- `value`, `defaultValue` and `onValueChange` for anything with a value.
## Usage
```css
/* app.css */
@import "tailwindcss";
@import "tansy-ui/tokens.css";
@source "../node_modules/tansy-ui/dist-lib";
```
```tsx
import { useState } from 'react'
import { Button } from './components/Button'
import { FeaturedInput } from './components/FeaturedInput'
import { Switch } from './components/Switch'
import { Mail } from 'lucide-react'
import { Button, FeaturedInput, Select, Switch } from 'tansy-ui'
export function InviteForm() {
const [email, setEmail] = useState('')
return (
<form>
<FeaturedInput
label="Work email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
<form className="grid max-w-sm gap-5">
<FeaturedInput label="Work email" type="email" startIcon={<Mail />} required />
<Select
label="Team"
options={[
{ value: 'design', label: 'Design' },
{ value: 'engineering', label: 'Engineering' },
]}
/>
<Switch label="Send a welcome email" defaultChecked />
<Button type="submit">Send invite</Button>
@@ -63,6 +74,8 @@ export function InviteForm() {
}
```
**Dark mode:** add the `dark` class to `<html>`.
## Theming
Tansy UI ships seven palettes: Classic Blue (default), Emerald, Violet, Amber, Crimson, Slate and Teal. Each defines full `primary`, `secondary`, `gray` and `zink` ramps plus semantic colours in `src/theme/palettes.ts`.
@@ -84,16 +97,30 @@ npm install
npm run dev # landing page at http://localhost:5173
npm run storybook # component workshop at http://localhost:6006
npm run lint
npm test # unit, keyboard and axe tests for every component
npm run build # landing page -> dist/
npm run build-storybook # workshop -> storybook-static/
npm run build:lib # library -> dist-lib/ (ES modules, types, tokens.css)
```
To check every story in a real browser (runtime errors and axe, including colour contrast):
```bash
npm run build-storybook
node scripts/check-stories.mjs --mode light
node scripts/check-stories.mjs --mode dark
python3 scripts/contact-sheet.py /tmp/tansy-story-check/light # screenshots to review
```
### Adding a component
1. Add it under `src/components/`, with style maps in a sibling `*.tokens.ts`.
2. Add a colocated `ComponentName.stories.tsx` that covers every meaningful state.
3. Read colours from the palette ramps (`bg-primary-500`) so the palette switcher reaches it.
4. Run `npm run build-storybook && python3 scripts/gen_catalogue.py --patch` to refresh the landing page catalogue.
Follow [`docs/CONVENTIONS.md`](docs/CONVENTIONS.md). In short:
1. Build it on Base UI where it has behaviour, in `src/components/`, with style maps in a sibling `*.tokens.ts`.
2. Use only the tokens (`bg-surface`, `text-fg`, `primary-*`, `danger-*` …), and check it in dark mode.
3. Add `Name.stories.tsx` with controls for every prop and a story for every state, and `Name.test.tsx` with keyboard and axe checks.
4. Export it from `src/index.ts`.
5. Run `npm test`, the story check in both modes, then `python3 scripts/gen_catalogue.py --patch` to refresh the landing page catalogue.
## Versioning
@@ -117,16 +144,21 @@ python3 scripts/deploy.py # builds that commit and deploys it
```text
src/
├── brand/TansyMark.tsx # Palette-aware logo
├── components/ # Components, their tokens and their stories
├── components/ # Components, their tokens, stories and tests
├── data/catalogue.ts # Landing page catalogue (regenerated by scripts/gen_catalogue.py)
├── docs/ # Storybook Introduction pages (MDX)
├── lib/ # cn(), shared styles, useControllableState
├── styles/tokens.css # Design tokens (shipped as tansy-ui/tokens.css)
├── test/ # Vitest setup and the axe helper
├── theme/ # Palettes and applyPalette()
├── index.ts # Public API
├── version.ts # VERSION, injected from package.json
├── Welcome.mdx # Storybook welcome page
├── App.tsx # Landing page, built only from Tansy components
└── index.css # Tailwind entry, palette tokens, landing styles
.storybook/ # Storybook config, Tansy theme, fonts
└── index.css # Tailwind entry and landing styles
.storybook/ # Storybook config, Tansy theme, light/dark and palette toolbars
docs/ # CONVENTIONS.md, ROADMAP.md
scripts/ # Deploy, catalogue, story check and contact sheets
public/ # tansy-mark.svg and favicon.svg
scripts/ # Deploy and catalogue scripts
```
## Brand
+130
View File
@@ -0,0 +1,130 @@
# Component conventions
Every Tansy UI component follows these rules, so the kit reads as one API. The
reference implementations are `src/components/Button.tsx`, `Input.tsx` and
`Field.tsx`, with their stories and tests. When in doubt, copy them.
## Foundation
- **Headless base:** interactive parts are built on [Base UI](https://base-ui.com)
(`@base-ui/react`). Its docs ship in the package at
`node_modules/@base-ui/react/docs/react/components/*.md`, with Tailwind examples
and full API tables. Use Base UI for anything with focus management, keyboard
navigation, popups or ARIA state: Dialog, Popover, Menu, Select, Combobox,
Tooltip, Tabs, Accordion, Checkbox, Radio, Switch, Slider, Toast, Field and more.
Never hand-roll focus traps, dismissal or roving focus.
- **Styling:** Tailwind v4 utilities only. Shared class strings live in
`src/lib/styles.ts` (`focusRing`, `controlHeight`, `controlBox`, `popupSurface`,
`popupMotion`, `listItem`, `labelText`, `descriptionText`, `errorText`).
Use them instead of repeating utilities.
- **Class merging:** always `cn(...)` from `src/lib/cn.ts`, with the consumer's
`className` last so it wins.
- **Refs:** React 19 passes `ref` as a normal prop. Type props from
`ComponentProps<'element'>` and spread `...props` onto the root element (or
the main control for form fields). No `forwardRef`, and never copy refs in an effect.
- **Ids:** from `useId()` or Base UI. Never derive an `id` from `name`.
- **Files:** `Name.tsx` exports only components (Vite fast refresh). Style maps,
types and constants go in `name.tokens.ts`. Stories in `Name.stories.tsx`,
tests in `Name.test.tsx`.
## Tokens and theming
Use only these colour utilities, never Tailwind's built-in hues (`slate`, `gray`,
`red`, `blue`…) or hex codes:
| Purpose | Utilities |
|---|---|
| Neutral surfaces | `bg-background`, `bg-surface`, `bg-surface-muted`, `bg-surface-sunken` |
| Borders | `border-border`, `border-border-strong` |
| Text | `text-fg`, `text-fg-muted`, `text-fg-subtle` |
| Brand | `primary-50` … `primary-900` (re-themed by the palette) |
| Status | `success-*`, `warning-*`, `danger-*`, `info-*` (50 … 900, fixed across palettes) |
| Overlay | `bg-overlay`; popup shadow `shadow-popup` |
**Dark mode** is the `dark` class on `<html>`. Surface, border and text tokens
switch automatically. Brand and status colours need `dark:` variants where
contrast demands it. Patterns that work:
- soft fill: `bg-{c}-50 text-{c}-700 dark:bg-{c}-500/15 dark:text-{c}-300`
- outline: `border-{c}-300 text-{c}-700 dark:border-{c}-500/50 dark:text-{c}-300`
- text on light surfaces: `-700`, and `-800` for warning. White text on fills:
primary `500`, danger `600`, success and info `700`. Warning fills take
`text-warning-900`.
Every story must pass axe **colour contrast** in both light and dark mode.
## Props
| Concept | Prop | Values |
|---|---|---|
| Semantic colour | `color` | `'primary' \| 'neutral' \| 'success' \| 'warning' \| 'danger' \| 'info'` (type `Color` in `lib/styles.ts`) |
| Visual style | `variant` | Per component, e.g. Button `solid \| soft \| outline \| ghost \| link`; Alert and Badge `soft \| solid \| outline` |
| Size | `size` | `'sm' \| 'md' \| 'lg'`, default `md`. Control heights come from `controlHeight`: 32, 40 and 48 px |
| Icons | `startIcon`, `endIcon`, `icon` | `ReactNode`. Callers pass `<Mail />`. Never icon names as strings, never icon fonts |
| Field text | `label`, `description`, `error` | `ReactNode`. `error` marks the control invalid and replaces `description` |
| Required | `required` | Shows the mark and sets `required` on the control |
| Value | `value`, `defaultValue`, `onValueChange(value)` | Every component works both controlled and uncontrolled |
| Boolean state | `checked`, `defaultChecked`, `onCheckedChange(checked)` | Checkbox, Switch |
| Open state | `open`, `defaultOpen`, `onOpenChange(open)` | Dialog, Popover, Menu, Tooltip, Drawer, Alert (dismissible) |
| Disabled | `disabled` | Native `disabled` or Base UI's, with `data-disabled` styling |
Text inputs also keep the native `onChange`. Document every prop with a JSDoc
comment; Storybook's docs table reads them.
## Accessibility
- A visible focus ring on every interactive element (`focusRing`, or
`focusWithinRing` on wrappers around an input).
- Form controls sit in `Field` (or Base UI `Field.Root`), so the label,
description and error are linked (`aria-labelledby`, `aria-describedby`,
`aria-invalid`).
- Icon-only controls require `aria-label`. Decorative icons get `aria-hidden`.
- Popups: Escape closes, focus returns to the trigger, and the keyboard works
as the WAI-ARIA pattern describes. Base UI does this when used as documented.
- Respect `motion-reduce:` for animations.
## Stories
- `title`: `Group/Name`. Groups: `Actions`, `Forms`, `Overlays`, `Navigation`,
`Feedback`, `Display`, `Layout`.
- `tags: ['autodocs']`, a component description in
`parameters.docs.description.component`, and `argTypes` for **every public
prop** with a matching control (`inline-radio` for short enums, `select`
for long ones, `text`, `boolean`, `number`; `control: false` for nodes and
functions).
- Callbacks use `fn()` from `storybook/test`, so they appear in the Actions panel.
- Stories: `Playground` (args-driven), plus one per variant, colour, size and
state (disabled, error, required, loading, read-only, empty), `Controlled`
and `Uncontrolled` where values exist, and realistic compositions. Popups
should have a story that renders them **open** (`defaultOpen`), so they can
be reviewed without clicking.
- Realistic, generic sample content (Jane Doe, Acme Corporation,
name@example.com). No real people or companies.
## Tests
Every component has `Name.test.tsx` (Vitest, Testing Library, user-event):
- renders with the right role and accessible name,
- label, description and error wiring for form controls,
- controlled and uncontrolled behaviour,
- keyboard interaction for the component's pattern (Escape, arrows, Enter/Space),
- `await expectNoA11yViolations(container)` from `src/test/a11y.ts`.
Run `npx vitest run src/components/Name.test.tsx`.
## Checking in a real browser
```bash
npm run build-storybook
node scripts/check-stories.mjs --filter forms-input --mode light
node scripts/check-stories.mjs --filter forms-input --mode dark
python3 scripts/contact-sheet.py /tmp/tansy-story-check/light --prefix forms-input
```
Before a release, also run it with `--palette <name>` for each of the seven
palettes: a colour that passes in Classic Blue can fail in Amber.
`check-stories.mjs` reports runtime errors, failed requests and axe violations,
including contrast, and saves a screenshot of every story. Look at the contact
sheet, not just the report.
+84
View File
@@ -0,0 +1,84 @@
# Roadmap
Where Tansy UI stands against MUI and shadcn/ui, what's done, and what comes
before v1.
Last reviewed: 2026-09-28, at v0.3.0.
## Where things stand
| | Tansy UI (v0.3) | shadcn/ui | MUI (Material UI + Base UI) |
|---|---|---|---|
| Distribution | Library build (ES modules, types, tokens.css); not yet on npm | CLI and registries. CLI v4 installs a whole design system in one payload | npm packages |
| Components | 38 | 50+, plus blocks and charts | Material UI's full set; Base UI v1 has 35 unstyled parts; MUI X adds Data Grid, Charts, Date Pickers, Tree View |
| Accessibility base | Base UI primitives | Radix and Base UI primitives | Base UI primitives |
| Theming | Seven runtime palettes, scoped to any element; semantic tokens | CSS variables | `createTheme`, CSS variables |
| Dark mode | Yes, token-based | Yes | Yes |
| Tests | Unit and axe tests per component; every story checked in a real browser in both modes | Per primitive | Unit, visual and a11y suites |
| Docs | Storybook: a story per state, full controls, Introduction guides | Docs site, examples, blocks | Docs site, demos, templates |
Sources: [shadcn/ui changelog](https://ui.shadcn.com/docs/changelog),
[shadcn CLI v4](https://ui.shadcn.com/docs/changelog/2026-03-cli-v4),
[MUI: 2026 and beyond](https://mui.com/blog/2026-and-beyond/),
[Base UI v1](https://infoq.com/news/2026/02/baseui-v1-accessible/).
## Phase 0: Foundations (done in v0.3.0)
- [x] Visible keyboard focus on every interactive element
- [x] Labels, help text and errors linked to every field (`Field`)
- [x] Overlays, selects and menus on Base UI: focus traps, focus return,
Escape, roving focus, type-ahead, a real ARIA combobox
- [x] Alert roles by severity; tooltips on keyboard focus
- [x] One API: `color`, `variant`, `size`, `startIcon`/`endIcon` as nodes,
`value`/`defaultValue`/`onValueChange`, `label`/`description`/`error`
- [x] Controlled and uncontrolled use everywhere; ids from `useId`
- [x] Token-only colours, fixed Classic Blue ramp, semantic status ramps
- [x] Dark mode
- [x] Tests for every component, and a browser check of every story in both modes
- [x] Icons imported individually (no full `lucide-react` bundle)
- [x] Library build with per-component modules, types and `tokens.css`
## Phase 1: Components
Shipped in v0.3.0: Field, Input, FeaturedInput, TextArea, FeaturedTextArea,
NumberInput, Select, FeaturedSelect, Combobox, NativeSelect, Checkbox,
CheckboxGroup, Radio, Switch, Slider, ToggleGroup, Button, IconButton,
LinkButton, Dialog, AlertDialog, Drawer, Popover, Tooltip, InfoTip,
DropdownMenu, Tabs, Accordion, Breadcrumb, Pagination, Alert, Toast, Spinner,
Progress, Meter, Skeleton, Badge, CountBadge, Avatar, AvatarGroup, Card, Kbd,
Separator and Table.
Still to come:
1. Date Picker and Date Range Picker
2. Data Table (sorting, filtering, selection and pagination on top of Table)
3. Command palette
4. File upload with drag and drop
5. OTP / verification code input (Base UI OTPField)
6. Context menu, Menubar and Navigation menu (Base UI primitives exist)
7. Stepper and Timeline
Each ships with stories for every state, keyboard and a11y tests, tokens only,
and a docs page.
## Phase 2: Distribution
- [ ] Claim the npm scope and publish the library build.
- [ ] Serve the same components as a shadcn-compatible registry, so
`npx shadcn add <url>` copies a Tansy component into a project: the
same code as a dependency or as source you own.
- [ ] Ship the palettes as a registry base item (tokens, fonts and CSS
variables in one install).
- [ ] Automate releases (Changesets) from `CHANGELOG.md`.
## Phase 3: Where Tansy can lead
- **Scoped runtime palettes.** `applyPalette()` already themes any subtree at
runtime. Next: a palette builder that makes a full, contrast-checked 50–900
ramp from one brand colour and exports `tokens.css`.
- **Form-heavy business apps.** Floating labels, inline help, required marks,
validation states, currency and number inputs are built in, where shadcn
leaves them to the app. Extend with masked inputs and date ranges.
- **Owned or installed.** One source, as an npm package or registry code.
- **Every state verified.** Every story is rendered and checked in light and
dark mode on each release. Publish that report with the docs.
+2096 -28
View File
File diff suppressed because it is too large. Load diff
+41 -6
View File
@@ -1,37 +1,72 @@
{
"name": "tansy-ui",
"private": true,
"version": "0.2.0",
"version": "0.3.0",
"description": "A themeable, accessible React component kit built on Base UI and Tailwind CSS v4.",
"type": "module",
"sideEffects": [
"*.css"
],
"module": "./dist-lib/index.js",
"types": "./dist-lib/index.d.ts",
"exports": {
".": {
"types": "./dist-lib/index.d.ts",
"import": "./dist-lib/index.js"
},
"./tokens.css": "./dist-lib/tokens.css",
"./package.json": "./package.json"
},
"files": [
"dist-lib",
"README.md",
"CHANGELOG.md"
],
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"build:lib": "vite build --config vite.lib.config.ts && tsc -p tsconfig.lib.json && cp src/styles/tokens.css dist-lib/tokens.css",
"lint": "oxlint src .storybook",
"test": "vitest run",
"test:watch": "vitest",
"check:stories": "node scripts/check-stories.mjs",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"peerDependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"dependencies": {
"@base-ui/react": "^1.8.0",
"clsx": "^2.1.1",
"lucide-react": "^0.460.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.1"
"tailwind-merge": "^3.7.0"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.6.0",
"@storybook/addon-docs": "^10.6.0",
"@storybook/react-vite": "^10.6.0",
"@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.7",
"@types/node": "^24.13.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"axe-core": "^4.13.0",
"jsdom": "^30.1.1",
"oxlint": "^1.81.0",
"playwright": "^1.63.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"remark-gfm": "^4.0.1",
"storybook": "^10.6.0",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.3.0"
"vite": "^8.3.0",
"vitest": "^5.0.2"
}
}
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env node
/**
* Render every story in a real browser and report what's broken.
*
* For each story in storybook-static/index.json it:
* - loads the story in Chrome (light or dark mode),
* - records page errors and console errors,
* - runs axe, including colour contrast (jsdom tests can't check that),
* - saves a screenshot.
*
* npm run build-storybook
* node scripts/check-stories.mjs [--filter forms-] [--mode dark] [--palette emerald] [--out dir] [--no-shots]
*
* Exits non-zero when any story has an error or an axe violation.
* Uses the system Chrome (CHROME_PATH, default /usr/bin/google-chrome).
*/
import { createServer } from 'node:http'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { extname, join, resolve } from 'node:path'
import { chromium } from 'playwright'
const args = process.argv.slice(2)
const opt = (name, fallback) => {
const i = args.indexOf(`--${name}`)
return i === -1 ? fallback : args[i + 1]
}
const DIR = resolve(opt('dir', 'storybook-static'))
const FILTER = opt('filter', '')
const MODE = opt('mode', 'light')
const PALETTE = opt('palette', '')
const OUT = resolve(opt('out', `/tmp/tansy-story-check/${MODE}${PALETTE ? `-${PALETTE}` : ''}`))
const SHOTS = !args.includes('--no-shots')
const CONCURRENCY = Number(opt('concurrency', 4))
const require = createRequire(import.meta.url)
const AXE = await readFile(require.resolve('axe-core/axe.min.js'), 'utf8')
const TYPES = {
'.html': 'text/html',
'.js': 'text/javascript',
'.mjs': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.svg': 'image/svg+xml',
'.woff2': 'font/woff2',
'.png': 'image/png',
}
const server = createServer(async (req, res) => {
const path = decodeURIComponent(new URL(req.url, 'http://x').pathname)
const file = join(DIR, path.endsWith('/') ? `${path}index.html` : path)
try {
const body = await readFile(file)
res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' })
res.end(body)
} catch {
res.writeHead(404)
res.end()
}
})
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
const base = `http://127.0.0.1:${server.address().port}`
const index = JSON.parse(await readFile(join(DIR, 'index.json'), 'utf8'))
const stories = Object.values(index.entries).filter(
(e) => e.type === 'story' && (!FILTER || e.id.startsWith(FILTER)),
)
await mkdir(OUT, { recursive: true })
const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? '/usr/bin/google-chrome' })
// Each story gets its own context: shared contexts leaked theme state and
// axe runs between parallel pages.
const newContext = () => browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: 'reduce' })
const results = []
async function check(story, attempt = 1) {
const context = await newContext()
const page = await context.newPage()
const errors = []
page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`))
page.on('console', (m) => {
// Failed requests are reported with their URL by the response handler below.
if (m.type() === 'error' && !m.text().startsWith('Failed to load resource'))
errors.push(`console: ${m.text().slice(0, 300)}`)
})
page.on('response', (r) => {
if (r.status() >= 400) errors.push(`http ${r.status()}: ${r.url().replace(base, '')}`)
})
page.on('requestfailed', (r) => {
if (!r.url().startsWith(base)) return
errors.push(`request failed: ${r.url().replace(base, '')}`)
})
// a11y.manual stops Storybook's own axe run, which would race ours on window.axe.
const url = `${base}/iframe.html?id=${story.id}&viewMode=story&globals=mode:${MODE};a11y.manual:!true${PALETTE ? `;palette:${PALETTE}` : ''}`
let axe = []
try {
await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 })
await page.waitForFunction(() => document.querySelector('#storybook-root')?.childElementCount > 0, null, {
timeout: 10000,
})
await page.waitForFunction((dark) => document.documentElement.classList.contains('dark') === dark, MODE === 'dark', {
timeout: 10000,
})
// Globals from the URL (mode) trigger a re-render; wait for the DOM to settle.
await page.evaluate(() => document.fonts.ready)
await page.waitForFunction(
() =>
new Promise((done) => {
let last = document.body.innerHTML.length
let stable = 0
const tick = setInterval(() => {
const now = document.body.innerHTML.length
stable = now === last ? stable + 1 : 0
last = now
if (stable >= 3) {
clearInterval(tick)
done(true)
}
}, 100)
}),
null,
{ timeout: 10000 },
)
await page.waitForTimeout(250)
const sbError = await page.evaluate(() => {
const el = document.querySelector('.sb-show-errordisplay #error-message')
return el ? el.textContent : null
})
if (sbError) errors.push(`storybook: ${sbError.slice(0, 300)}`)
await page.addScriptTag({ content: AXE })
axe = await page.evaluate(async () => {
const r = await window.axe.run(document.body, {
rules: {
region: { enabled: false },
'landmark-one-main': { enabled: false },
'page-has-heading-one': { enabled: false },
},
})
return r.violations.map((v) => ({
id: v.id,
impact: v.impact,
help: v.help,
nodes: v.nodes.slice(0, 4).map((n) => n.target.join(' ')),
}))
})
if (SHOTS) await page.screenshot({ path: join(OUT, `${story.id}.png`) })
} catch (e) {
errors.push(`load: ${e.message.split('\n')[0]}`)
}
await context.close()
// The local file server can drop requests under load. If nothing but
// network loading failed, the story never ran: try it once more.
const infraOnly = errors.length > 0 && !axe.length && errors.every((e) => /^(request failed|load:|console: TypeError: Failed to fetch)/.test(e))
if (infraOnly && attempt === 1) return check(story, 2)
results.push({ id: story.id, title: story.title, name: story.name, errors, axe })
}
const queue = [...stories]
await Promise.all(
Array.from({ length: CONCURRENCY }, async () => {
while (queue.length) await check(queue.shift())
}),
)
await browser.close()
server.close()
results.sort((a, b) => a.id.localeCompare(b.id))
await writeFile(join(OUT, 'report.json'), JSON.stringify(results, null, 2))
const bad = results.filter((r) => r.errors.length || r.axe.length)
for (const r of bad) {
console.log(`\n✗ ${r.id}`)
for (const e of r.errors) console.log(` ${e}`)
for (const v of r.axe) console.log(` axe ${v.impact} ${v.id}: ${v.help} → ${v.nodes.join(' | ')}`)
}
console.log(
`\n${results.length} stories checked in ${MODE} mode${PALETTE ? `, ${PALETTE} palette` : ''}: ${results.length - bad.length} clean, ${bad.length} with problems.`,
)
console.log(`Screenshots and report.json in ${OUT}`)
process.exit(bad.length ? 1 : 0)
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""
Tile story screenshots into labelled contact sheets for quick visual review.
python3 scripts/contact-sheet.py /tmp/tansy-story-check/light [--prefix forms-] [--per 12]
Each screenshot is trimmed to its content (plus a margin) before tiling, so a
small component isn't lost in an empty 1100x760 frame.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from PIL import Image, ImageChops, ImageDraw
def trim(img: Image.Image, margin: int = 16) -> Image.Image:
rgb = img.convert("RGB")
bg = Image.new("RGB", rgb.size, rgb.getpixel((2, 2)))
box = ImageChops.difference(rgb, bg).getbbox()
if not box:
return rgb.crop((0, 0, 400, 120))
l, t, r, b = box
return rgb.crop((max(l - margin, 0), max(t - margin, 0), min(r + margin, rgb.width), min(b + margin, rgb.height)))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("dir")
ap.add_argument("--prefix", default="")
ap.add_argument("--per", type=int, default=12)
ap.add_argument("--cols", type=int, default=3)
ap.add_argument("--cell", type=int, default=560, help="cell width in px")
args = ap.parse_args()
src = Path(args.dir)
shots = sorted(p for p in src.glob("*.png") if p.name.startswith(args.prefix) and not p.name.startswith("sheet-"))
if not shots:
sys.exit("no screenshots matched")
out = []
for n in range(0, len(shots), args.per):
batch = shots[n : n + args.per]
cells = []
for p in batch:
img = trim(Image.open(p))
scale = min(1.0, (args.cell - 16) / img.width)
img = img.resize((int(img.width * scale), int(img.height * scale)))
cells.append((p.stem, img))
rows = [cells[i : i + args.cols] for i in range(0, len(cells), args.cols)]
heights = [max(c[1].height for c in row) + 34 for row in rows]
sheet = Image.new("RGB", (args.cell * args.cols, sum(heights)), "#8a8f99")
draw = ImageDraw.Draw(sheet)
y = 0
for row, h in zip(rows, heights):
for i, (name, img) in enumerate(row):
x = i * args.cell
draw.rectangle([x + 2, y + 2, x + args.cell - 2, y + h - 2], fill="#ffffff")
draw.text((x + 10, y + 8), name, fill="#b00020")
sheet.paste(img, (x + 8, y + 26))
y += h
path = src / f"sheet-{args.prefix or 'all'}-{n // args.per + 1:02d}.png"
sheet.save(path)
out.append(str(path))
print("\n".join(out))
if __name__ == "__main__":
main()
+63 -117
View File
@@ -10,10 +10,8 @@ src/data/catalogue.ts and writes /tmp/component_catalogue.json.
python3 scripts/gen_catalogue.py # print entries
python3 scripts/gen_catalogue.py --patch # also rewrite src/data/catalogue.ts
Story ids are `<group>-<component>--<story>`, but the group is not always
a single segment: TextField publishes as `data-entry-text-field--*`. So
components are matched by longest known name against `base` or
`base.endswith("-" + name)`, with aliases for the hyphenated spellings.
Components are read from story titles (`Group/Name`), so a new component
appears here without editing this script; only DETAIL is hand-written.
"""
from __future__ import annotations
@@ -28,92 +26,50 @@ IDX = REPO / "storybook-static" / "index.json"
CATALOGUE = REPO / "src" / "data" / "catalogue.ts"
OUT = Path("/tmp/component_catalogue.json")
# component id -> group slug
GROUPS = {
"button": "actions",
"accordion": "navigation",
"text-field": "data-entry",
"textfield": "data-entry",
"input": "forms",
"featuredinput": "forms",
"featured-input": "forms",
"select": "forms",
"checkbox": "forms",
"radio": "forms",
"switch": "forms",
"textarea": "forms",
"text-area": "forms",
"alert": "feedback",
"spinner": "feedback",
"badge": "display",
"card": "layout",
"tooltip": "overlays",
}
# Group order on the landing page; matches the Storybook sidebar.
GROUP_ORDER = ["Actions", "Forms", "Overlays", "Navigation", "Feedback", "Display", "Layout"]
# alias id key -> canonical component key
CANON = {
"text-field": "textfield",
"featured-input": "featuredinput",
"text-area": "textarea",
}
SPECIAL = {
"textfield": "Text field",
"featuredinput": "FeaturedInput",
"textarea": "TextArea",
"checkbox": "Checkbox",
"spinner": "Spinner",
"accordion": "Accordion",
"tooltip": "Tooltip",
"button": "Button",
"select": "Select",
"radio": "Radio",
"switch": "Switch",
"alert": "Alert",
"badge": "Badge",
"card": "Card",
"input": "Input",
}
GROUP_LABEL = {
"actions": "Actions",
"navigation": "Navigation",
"data": "Data entry",
"data-entry": "Data entry",
"forms": "Forms",
"feedback": "Feedback",
"display": "Display",
"layout": "Layout",
"overlays": "Overlays",
"misc": "Other",
}
# display order on the landing page
ORDER = [
"button", "accordion", "textfield",
"input", "featuredinput", "select", "checkbox", "radio", "switch", "textarea",
"alert", "spinner",
"badge", "card",
"tooltip",
]
# one-line coverage summary shown in the index row
# One-line coverage summary per component. Anything missing falls back to
# its story count, so a new component never breaks the generator.
DETAIL = {
"button": "Variants · sizes · disabled",
"accordion": "Disclosure · multiple",
"textfield": "Labels · hints · errors",
"input": "Plain · themed · icon slot",
"featuredinput": "Floating label · password · number",
"select": "Searchable · featured · async",
"checkbox": "Themes · tooltip · uncontrolled",
"radio": "Themes · horizontal · required",
"switch": "Themes · required · described",
"textarea": "Resize · featured · prefilled",
"alert": "Variants · colors · auto-close",
"spinner": "Sizes · variants · dark",
"badge": "Colors · floating · pulse",
"card": "Themes · shadows · horizontal",
"tooltip": "Positions · rich content · sizes",
"Button": "Variants · colours · loading · icons",
"ToggleGroup": "Segmented · multiple · icon-only",
"Input": "Addons · icons · filled · underline",
"FeaturedInput": "Floating label · password · clearable",
"TextArea": "Auto-resize · character count",
"FeaturedTextArea": "Floating label · auto-resize",
"NumberInput": "Steppers · currency · min/max",
"Field": "Label · description · error wiring",
"Select": "Single · multiple · grouped · clearable",
"FeaturedSelect": "Floating label · searchable · actions",
"Combobox": "Search · chips · async",
"NativeSelect": "Native menu · groups",
"Checkbox": "Indeterminate · colours · sizes",
"CheckboxGroup": "Select all · horizontal",
"Radio": "Cards · horizontal · descriptions",
"Switch": "Icons · label position · colours",
"Slider": "Range · marks · formatted",
"Dialog": "Sizes · scrolling body · forms",
"AlertDialog": "Destructive · async confirm",
"Drawer": "Four sides · sizes",
"Popover": "Sides · arrow · rich content",
"Tooltip": "Sides · colours · InfoTip",
"DropdownMenu": "Shortcuts · submenus · checkable",
"Tabs": "Underline · pills · vertical",
"Accordion": "Multiple · variants · heading level",
"Breadcrumb": "Collapse · icons",
"Pagination": "Siblings · boundaries · sizes",
"Alert": "Soft · solid · outline · dismissible",
"Toast": "Promise · actions · placement",
"Spinner": "Sizes · colours",
"Progress": "Indeterminate · meter · formatted",
"Skeleton": "Text · circle · card loading",
"Badge": "Colours · dot · removable · count",
"Avatar": "Initials · status · groups",
"Kbd": "Key combinations",
"Table": "Sortable · striped · sticky header",
"Card": "Outline · elevated · media · link",
"Separator": "Labelled · dashed · vertical",
}
@@ -121,41 +77,31 @@ def collect():
if not IDX.is_file():
sys.exit(f"{IDX} not found - run: npm run build-storybook")
entries = json.loads(IDX.read_text())["entries"]
ids = [v.get("id", k) if isinstance(v, dict) else k for k, v in entries.items()]
entries = json.loads(IDX.read_text())["entries"].values()
comps: dict[str, dict] = {}
for sid in ids:
if "--" not in sid:
continue
base, story = sid.split("--", 1)
comp = next(
(CANON.get(c, c) for c in sorted(GROUPS, key=len, reverse=True)
if base == c or base.endswith("-" + c)),
None,
)
if comp is None:
print(f" WARN unmapped story id: {sid}", file=sys.stderr)
continue
g = comps.setdefault(comp, {"group": GROUPS[comp], "doc": None,
"count": 0})
g["count"] += 1
if story in ("documentation", "docs"):
g["doc"] = sid
for e in entries:
group, _, name = e["title"].partition("/")
if not name or group not in GROUP_ORDER:
continue # Introduction pages and anything outside the component groups
c = comps.setdefault(name, {"group": group, "doc": None, "count": 0})
if e["type"] == "docs":
c["doc"] = e["id"]
else:
c["count"] += 1
ordered = sorted(comps.items(), key=lambda kv: (GROUP_ORDER.index(kv[1]["group"]), kv[0].lower()))
out = []
for i, comp in enumerate(ORDER, start=1):
g = comps.get(comp)
if not g or not g["doc"]:
print(f" WARN {comp}: no documentation story, skipped", file=sys.stderr)
for i, (name, c) in enumerate(ordered, start=1):
if not c["doc"]:
print(f" WARN {name}: no documentation page, skipped", file=sys.stderr)
continue
out.append({
"number": f"{i:02d}",
"group": GROUP_LABEL.get(g["group"], g["group"].title()),
"name": SPECIAL.get(comp, comp.title()),
"detail": DETAIL.get(comp, f"{g['count']} stories"),
"href": f"/docs/?path=/docs/{g['doc']}",
"count": g["count"],
"group": c["group"],
"name": name,
"detail": DETAIL.get(name, f"{c['count']} stories"),
"href": f"/docs/?path=/docs/{c['doc']}",
"count": c["count"],
})
return out
+255 -75
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
import { useEffect, useState, type FormEvent, type ReactNode } from 'react'
import { ArrowRight, Mail, UserRound } from 'lucide-react'
import { TansyMark } from './brand/TansyMark'
import { Alert } from './components/Alert'
@@ -7,9 +7,8 @@ import { Button, LinkButton } from './components/Button'
import { Card } from './components/Card'
import { Checkbox } from './components/Checkbox'
import { FeaturedInput } from './components/FeaturedInput'
import { FeaturedSelect } from './components/FeaturedSelect'
import { Radio } from './components/Radio'
import { Select } from './components/Select'
import { Spinner } from './components/Spinner'
import { Switch } from './components/Switch'
import { Tooltip } from './components/Tooltip'
import { documentation, featured, totalStories, type FeaturedName } from './data/catalogue'
@@ -35,23 +34,48 @@ const PAY_CYCLES = [
{ value: 'weekly', label: 'Weekly' },
]
const principles = [
/** Storybook pages the landing page links into. */
const DOCS = {
gettingStarted: `${STORYBOOK}?path=/docs/introduction-getting-started--documentation`,
theming: `${STORYBOOK}?path=/docs/introduction-theming--documentation`,
accessibility: `${STORYBOOK}?path=/docs/introduction-accessibility--documentation`,
changelog: `${STORYBOOK}?path=/docs/introduction-changelog--documentation`,
roadmap: `${STORYBOOK}?path=/docs/introduction-roadmap--documentation`,
}
const USAGE = `import { Button } from './Button'
import { Switch } from './Switch'
<Switch label="Welcome email" />
<Button>Send invite</Button>`
const STATES = ['Default', 'Error', 'Disabled', 'Loading', 'Required', 'Controlled']
/** Mirrors docs/ROADMAP.md; update both together. */
const roadmap = [
{
title: 'Named variants',
body: 'Each part offers a short list of deliberate choices. Screens pick one instead of inventing a new style.',
sample: 'variant="outline"',
stage: 'Shipped',
title: `v${VERSION}`,
color: 'success',
items: [
`${documentation.length} accessible components on Base UI`,
'Dark mode, seven palettes, one consistent API',
'Tests and a real-browser check for every story',
],
},
{
title: 'States included',
body: 'Error, disabled, loading and required ship with the part and have their own stories, so nobody has to guess.',
sample: 'error · disabled · loading',
stage: 'Next',
title: 'Data and dates',
color: 'warning',
items: ['Date Picker and Date Range Picker', 'Data Table with sorting and filtering', 'Command palette'],
},
{
title: 'Tokens, not hex codes',
body: 'Parts read colour from a 50–900 ramp. Swap the palette and every part follows without a code change.',
sample: 'bg-primary-500',
stage: 'Planned',
title: 'v1',
color: 'neutral',
items: ['Publish to npm', 'A shadcn-compatible registry', 'Palette builder with contrast checks'],
},
]
] as const
/** A small live instance of each featured part, sized to sit in a list row. */
const previews: Record<FeaturedName, ReactNode> = {
@@ -60,11 +84,61 @@ const previews: Record<FeaturedName, ReactNode> = {
Checkbox: <Checkbox aria-label="Example checkbox" defaultChecked />,
Badge: (
<span className="preview-badges">
<Badge type="default" color="success" content="Paid" />
<Badge type="default" color="warning" content="Pending" />
<Badge color="success" dot>
Paid
</Badge>
<Badge color="warning" dot>
Pending
</Badge>
</span>
),
Tooltip: <Tooltip content="Explains a field without adding clutter." position="left" size="sm" theme="primary" />,
Tooltip: (
<Tooltip content="Explains a control without adding clutter." side="left">
<Button size="sm" variant="outline" color="neutral">
Hover me
</Button>
</Tooltip>
),
}
/** Highlights the few token kinds USAGE contains, without a syntax library. */
function highlight(code: string) {
return code.split(/('[^']*'|"[^"]*"|\bimport\b|\bfrom\b|<\/?[A-Z]\w*|\/>|>)/g).map((part, index) => {
if (!part) return null
let kind = ''
if (part === 'import' || part === 'from') kind = 'tok-key'
else if (/^['"]/.test(part)) kind = 'tok-str'
else if (/^<\/?[A-Z]|^\/?>$/.test(part)) kind = 'tok-tag'
return kind ? <span className={kind} key={index}>{part}</span> : part
})
}
function CodeSample() {
const [copied, setCopied] = useState(false)
async function copy() {
try {
await navigator.clipboard.writeText(USAGE)
setCopied(true)
window.setTimeout(() => setCopied(false), 1600)
} catch {
setCopied(false)
}
}
return (
<div className="code-sample">
<div className="code-sample-bar">
<span>InviteForm.tsx</span>
<Button size="sm" variant="ghost" onClick={copy} className="code-copy">
{copied ? 'Copied' : 'Copy'}
</Button>
</div>
<pre>
<code>{highlight(USAGE)}</code>
</pre>
</div>
)
}
type FormErrors = Partial<Record<'name' | 'email' | 'department' | 'confirmed', string>>
@@ -118,53 +192,45 @@ function EmployeeForm() {
return (
<form onSubmit={handleSubmit} noValidate>
<Card shadow="sm" rounded="xl" className="employee-card">
<Card variant="elevated" padding="none" className="employee-card">
<Card.Header className="employee-card-header">
<Card.Title>Add an employee</Card.Title>
<p>They appear in the next payroll run.</p>
</Card.Header>
<Card.Body className="employee-card-body">
{added && (
<Alert
key={added}
title="Employee added"
message={added}
iconName="CheckCircle2"
color="success"
onClose={() => setAdded(null)}
/>
<Alert key={added} color="success" title="Employee added" dismissible onOpenChange={(open) => !open && setAdded(null)}>
{added}
</Alert>
)}
<div className="form-row">
<FeaturedInput
id="employee-name"
name="employee-name"
label="Full name"
icon={UserRound}
startIcon={<UserRound />}
value={name}
onChange={(e) => setName(e.target.value)}
onValueChange={setName}
error={errors.name}
required
/>
<FeaturedInput
id="employee-email"
name="employee-email"
label="Work email"
type="email"
icon={Mail}
startIcon={<Mail />}
value={email}
onChange={(e) => setEmail(e.target.value)}
onValueChange={setEmail}
error={errors.email}
required
/>
</div>
<Select
featured
<FeaturedSelect
name="department"
label="Department"
placeholder="Choose a department"
options={DEPARTMENTS}
value={department}
onChange={setDepartment}
value={department || null}
onValueChange={(value) => setDepartment(value ?? '')}
clearable
error={errors.department}
required
/>
@@ -173,21 +239,22 @@ function EmployeeForm() {
label="Pay cycle"
options={PAY_CYCLES}
value={cycle}
onChange={setCycle}
tooltip="Sets how often this employee appears in a payroll run."
onValueChange={setCycle}
orientation="horizontal"
description="How often this employee appears in a payroll run."
/>
<Switch
name="welcome-email"
label="Send a welcome email"
description="Includes the sign-in link and the first-day checklist."
checked={welcome}
onChange={(e) => setWelcome(e.target.checked)}
onCheckedChange={setWelcome}
/>
<Checkbox
name="confirmed"
label="I checked these details against the signed offer letter"
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
onCheckedChange={setConfirmed}
error={errors.confirmed}
/>
</Card.Body>
@@ -195,8 +262,8 @@ function EmployeeForm() {
<Button variant="ghost" onClick={handleReset} disabled={saving}>
Clear form
</Button>
<Button type="submit" disabled={saving} icon={saving ? <Spinner size="xs" variant="white" /> : undefined}>
{saving ? 'Adding…' : 'Add employee'}
<Button type="submit" loading={saving} loadingText="Adding…">
Add employee
</Button>
</Card.Footer>
</Card>
@@ -205,16 +272,17 @@ function EmployeeForm() {
}
function App() {
const shellRef = useRef<HTMLDivElement>(null)
const [palette, setPalette] = useState<PaletteName>(DEFAULT_PALETTE)
const active = palettes[palette]
// On <html>, not the shell: select lists and tooltips portal to <body> and
// must wear the same palette.
useEffect(() => {
if (shellRef.current) applyPalette(shellRef.current, palette)
applyPalette(document.documentElement, palette)
}, [palette])
return (
<div className="site-shell" ref={shellRef} data-palette={palette}>
<div className="site-shell" data-palette={palette}>
<header className="site-header">
<div className="container header-inner">
<a className="brand" href="#top" aria-label="Tansy UI home">
@@ -224,10 +292,14 @@ function App() {
</span>
<span className="brand-by">by OpenKhalix</span>
</a>
<a className="version-pill" href={DOCS.changelog} aria-label={`Version ${VERSION}, see the changelog`}>
v{VERSION}
</a>
<nav className="header-nav" aria-label="Primary">
<a href="#components">Components</a>
<a href="#playground">Playground</a>
<a href="#principles">Principles</a>
<a href={DOCS.gettingStarted}>Docs</a>
<a href={STORYBOOK}>Components</a>
<a href="#playground">Theming</a>
<a href="#roadmap">Roadmap</a>
</nav>
<LinkButton href={STORYBOOK} size="sm" variant="outline" className="header-cta">
Storybook
@@ -253,7 +325,7 @@ function App() {
already work.
</p>
<div className="hero-actions">
<LinkButton href={STORYBOOK} size="lg" icon={<ArrowRight size={18} aria-hidden="true" />}>
<LinkButton href={STORYBOOK} size="lg" endIcon={<ArrowRight aria-hidden="true" />}>
Browse all components
</LinkButton>
<LinkButton href="#playground" size="lg" variant="outline">
@@ -263,10 +335,16 @@ function App() {
<p className="stack">React 19 · TypeScript · Tailwind v4 · Storybook 10</p>
</div>
<Card shadow="sm" rounded="xl" className="featured-card" aria-labelledby="featured-title">
<Card.Header className="featured-header">
<Card variant="elevated" padding="none" className="featured-card" aria-labelledby="featured-title">
<Card.Header
className="featured-header"
action={
<Badge color="primary">
{featured.length} of {documentation.length}
</Badge>
}
>
<h2 id="featured-title">Featured parts</h2>
<Badge type="default" color="primary" content={`${featured.length} of ${documentation.length}`} />
</Card.Header>
<Card.Body className="featured-body">
<ul className="featured-list">
@@ -286,9 +364,10 @@ function App() {
<Card.Footer className="featured-footer">
<LinkButton
href={STORYBOOK}
variant="secondary"
className="w-full"
icon={<ArrowRight size={16} aria-hidden="true" />}
variant="soft"
color="neutral"
fullWidth
endIcon={<ArrowRight aria-hidden="true" />}
>
See all {documentation.length} components
</LinkButton>
@@ -296,6 +375,73 @@ function App() {
</Card>
</section>
<section className="container why" aria-labelledby="why-title">
<div className="section-head">
<p className="kicker">Why Tansy</p>
<h2 id="why-title">Built to be owned, themed and trusted.</h2>
</div>
<div className="why-grid">
<article className="why-card">
<div className="why-visual why-visual-code">
<CodeSample />
</div>
<h3>Source you own</h3>
<p>
Components live in your repository, like shadcn/ui. Read them, change them, and keep the variants your
product needs.
</p>
<a href={DOCS.gettingStarted}>Getting started →</a>
</article>
<article className="why-card">
<div className="why-visual">
<div className="why-swatches" role="group" aria-label="Try a palette">
{Object.values(palettes).map((p) => (
<button
key={p.name}
type="button"
aria-label={p.label}
aria-pressed={p.name === palette}
title={p.label}
style={{ background: p.primary[500] }}
onClick={() => setPalette(p.name)}
/>
))}
</div>
<div className="why-buttons">
<Button size="sm">Primary</Button>
<Button size="sm" variant="outline">Outline</Button>
</div>
</div>
<h3>Palettes scoped anywhere</h3>
<p>
Seven palettes, each a full 50–900 ramp. Apply one to the whole app or to a single panel, at runtime,
without a rebuild.
</p>
<a href={DOCS.theming}>Theming →</a>
</article>
<article className="why-card">
<div className="why-visual">
<div className="why-states">
{STATES.map((state) => (
<Badge key={state} color={state === 'Error' ? 'danger' : 'neutral'}>
{state}
</Badge>
))}
</div>
<p className="why-stat">
<strong>{totalStories}</strong> stories across <strong>{documentation.length}</strong> components
</p>
</div>
<h3>Every state documented</h3>
<p>
Each state gets its own Storybook story with axe accessibility checks, so reviews cover more than the
default look.
</p>
<a href={DOCS.accessibility}>Accessibility →</a>
</article>
</div>
</section>
<section className="playground" id="playground" aria-labelledby="playground-title">
<div className="container playground-grid">
<div className="playground-intro">
@@ -341,33 +487,67 @@ function App() {
</div>
</section>
<section className="container principles" id="principles" aria-labelledby="principles-title">
<div className="principles-head">
<p className="kicker">Principles</p>
<h2 id="principles-title">What every part has to ship with.</h2>
<section className="container roadmap" id="roadmap" aria-labelledby="roadmap-title">
<div className="section-head section-head-row">
<div>
<p className="kicker">Roadmap</p>
<h2 id="roadmap-title">From a kit to a package.</h2>
</div>
<LinkButton href={DOCS.roadmap} variant="outline" color="neutral" endIcon={<ArrowRight aria-hidden="true" />}>
Read the full roadmap
</LinkButton>
</div>
<div className="principle-grid">
{principles.map((item) => (
<div className="principle" key={item.title}>
<h3>{item.title}</h3>
<p>{item.body}</p>
<code>{item.sample}</code>
</div>
<ol className="roadmap-grid">
{roadmap.map((step) => (
<li className="roadmap-step" key={step.stage}>
<Badge color={step.color} dot>
{step.stage}
</Badge>
<h3>{step.title}</h3>
<ul>
{step.items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</li>
))}
</div>
</ol>
</section>
</main>
<footer className="site-footer">
<div className="container footer-inner">
<div className="container footer-grid">
<div className="footer-brand">
<TansyMark size={24} />
<span>
<strong>Tansy UI</strong> v{VERSION} · a React component kit by OpenKhalix
</span>
<div className="footer-logo">
<TansyMark size={26} />
<strong>
Tansy<span className="brand-ui">UI</span>
</strong>
</div>
<p>A themeable React component kit by OpenKhalix.</p>
<p className="footer-version">
v{VERSION} · <a href={DOCS.changelog}>Changelog</a>
</p>
</div>
<nav className="footer-nav" aria-label="Footer">
<a href={STORYBOOK}>Storybook</a>
<nav className="footer-col" aria-label="Documentation">
<h2>Docs</h2>
<a href={DOCS.gettingStarted}>Getting started</a>
<a href={DOCS.theming}>Theming</a>
<a href={DOCS.accessibility}>Accessibility</a>
</nav>
<nav className="footer-col" aria-label="Components">
<h2>Components</h2>
{featured.slice(0, 3).map((item) => (
<a href={item.href} key={item.name}>
{item.name}
</a>
))}
<a href={STORYBOOK}>All {documentation.length} components</a>
</nav>
<nav className="footer-col" aria-label="Project">
<h2>Project</h2>
<a href={DOCS.roadmap}>Roadmap</a>
<a href={DOCS.changelog}>Changelog</a>
<a href="#playground">Playground</a>
</nav>
</div>
-32
View File
@@ -1,32 +0,0 @@
import { Meta } from '@storybook/addon-docs/blocks'
import { TansyMark } from './brand/TansyMark'
import { documentation, totalStories } from './data/catalogue'
import { VERSION } from './version'
<Meta title="Welcome" />
<div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '8px 0 28px' }}>
<TansyMark size={56} />
<div>
<div style={{ fontFamily: '"Schibsted Grotesk", sans-serif', fontWeight: 800, fontSize: 40, letterSpacing: '-0.04em', lineHeight: 1 }}>Tansy <span style={{ fontSize: 40, fontWeight: 700, color: '#6b7384' }}>UI</span></div>
<div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#6b7384', marginTop: 6 }}>
v{VERSION} · React component kit · {documentation.length} parts · {totalStories} stories
</div>
</div>
</div>
Tansy UI is a React component kit by OpenKhalix. It's named after the tansy flower, also called golden buttons: many small round heads that read as one bloom. Every part here is owned source code: Tailwind classes, variants, validation rules and theme tokens all live in this repository.
## How to read this workshop
- **Documentation** pages list every prop, with controls you can change live.
- **Stories** show one state each. Defaults, errors, disabled and loading states all get their own.
- **Palette** in the toolbar re-themes every part from the `primary`, `secondary`, `gray` and `zink` ramps. The same switch is in the landing page playground.
- **Accessibility** runs axe checks against each story in the panel below the canvas.
## Adding a part
1. Put the component in `src/components/` and keep its style maps in a sibling `*.tokens.ts`.
2. Add a colocated `ComponentName.stories.tsx` with a story for every meaningful state.
3. Read colours from the palette ramps (`bg-primary-500`), never from hex codes.
4. Run `npm run build-storybook`, then `python3 scripts/gen_catalogue.py --patch` to update the landing page catalogue.
+112 -20
View File
@@ -1,5 +1,32 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Accordion } from './Accordion'
import { fn } from 'storybook/test'
import { Accordion, type AccordionItem } from './Accordion'
import { ACCORDION_VARIANTS } from './accordion.tokens'
const FAQ: AccordionItem[] = [
{
value: 'billing',
title: 'When will I be charged?',
content: 'Plans are billed monthly on the date you subscribed. Annual plans are billed once a year and include two months free.',
},
{
value: 'cancel',
title: 'Can I cancel at any time?',
content: 'Yes. Cancel from Settings → Billing and you keep access until the end of the current period. No questions asked.',
},
{
value: 'seats',
title: 'How do seats work?',
content: 'Each member of your workspace uses one seat. Guests with view-only access are free, and you can add seats whenever you need them.',
},
{
value: 'sso',
title: 'Do you support single sign-on?',
content: 'SAML single sign-on is available on the Enterprise plan.',
disabled: true,
},
]
const meta = {
title: 'Navigation/Accordion',
@@ -8,35 +35,100 @@ const meta = {
parameters: {
docs: {
description: {
component: 'A controlled-friendly disclosure primitive for showing related content without overwhelming the page.',
component:
'A stack of collapsible sections, built on Base UI Accordion. Each trigger is a button inside a heading (`headingLevel`, default 3) whose `aria-controls` points at its panel. Closed panels stay in the DOM as `hidden="until-found"`, so find-in-page opens them. Set `multiple` to let several sections stay open.',
},
},
},
args: {
items: [
{
title: 'What is a component story?',
content: 'A focused example of one component with specific props, states, and surrounding context.',
},
{
title: 'Why document states?',
content: 'A component is only complete when its loading, empty, error, and success states are clear.',
},
{
title: 'How do I add my own?',
content: 'Create a .stories.tsx file beside the component and use the same Meta and StoryObj patterns.',
},
],
argTypes: {
items: { control: false },
multiple: { control: 'boolean' },
variant: { control: 'inline-radio', options: ACCORDION_VARIANTS, table: { defaultValue: { summary: 'bordered' } } },
headingLevel: { control: 'inline-radio', options: [2, 3, 4, 5, 6], table: { defaultValue: { summary: '3' } } },
disabled: { control: 'boolean' },
value: { control: 'object' },
defaultValue: { control: 'object' },
onValueChange: { control: false },
},
args: {
items: FAQ,
multiple: false,
variant: 'bordered',
headingLevel: 3,
disabled: false,
defaultValue: ['billing'],
onValueChange: fn(),
},
decorators: [
(Story) => (
<div className="max-w-2xl">
<Story />
</div>
),
],
} satisfies Meta<typeof Accordion>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {}
export const Playground: Story = {}
const ACCOUNT: AccordionItem[] = [
{ value: 'email', title: 'How do I change my email address?', content: 'Go to Settings → Profile, enter the new address and confirm it from the email we send to [email protected].' },
{ value: 'export', title: 'Can I export my data?', content: 'Yes. Settings → Data lets you download everything as CSV or JSON.' },
{ value: 'delete', title: 'How do I delete my account?', content: 'Workspace owners can delete the account from Settings → Danger zone. This cannot be undone.' },
]
const SECURITY: AccordionItem[] = [
{ value: '2fa', title: 'Is two-factor authentication available?', content: 'Every plan supports authenticator apps and security keys.' },
{ value: 'encryption', title: 'Is my data encrypted?', content: 'Data is encrypted in transit with TLS 1.3 and at rest with AES-256.' },
{ value: 'audit', title: 'Do you keep an audit log?', content: 'Business and Enterprise plans keep a searchable audit log for 12 months.' },
]
const GROUPS = { bordered: FAQ, separated: ACCOUNT, ghost: SECURITY }
export const Variants: Story = {
parameters: { docs: { description: { story: 'The three variants, each with its own questions.' } } },
render: (args) => (
<div className="grid gap-10">
{ACCORDION_VARIANTS.map((variant) => (
<div key={variant} className="grid gap-2">
<p className="text-xs font-medium uppercase tracking-wide text-fg-muted">{variant}</p>
<Accordion {...args} variant={variant} items={GROUPS[variant]} defaultValue={[GROUPS[variant][0].value]} />
</div>
))}
</div>
),
}
export const Separated: Story = { args: { variant: 'separated', defaultValue: ['cancel'] } }
export const Ghost: Story = { args: { variant: 'ghost' } }
export const Multiple: Story = {
args: {
allowMultiple: true,
args: { multiple: true, defaultValue: ['billing', 'seats'] },
}
export const AllClosed: Story = { args: { defaultValue: [] } }
export const Controlled: Story = {
render: function Render(args) {
const [value, setValue] = useState<string[]>(['seats'])
return (
<div className="grid gap-3">
<Accordion
{...args}
multiple
value={value}
onValueChange={(next) => {
setValue(next)
args.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">
Open: <code className="text-fg">{value.length ? value.join(', ') : 'none'}</code>
</p>
</div>
)
},
}
+87
View File
@@ -0,0 +1,87 @@
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 { Accordion, type AccordionItem } from './Accordion'
const items: AccordionItem[] = [
{ value: 'a', title: 'Billing', content: 'Billing answer' },
{ value: 'b', title: 'Cancelling', content: 'Cancel answer' },
{ value: 'c', title: 'SSO', content: 'SSO answer', disabled: true },
]
describe('Accordion', () => {
it('toggles a section and keeps aria-controls pointing at an existing panel', async () => {
const onValueChange = vi.fn()
render(<Accordion items={items} onValueChange={onValueChange} />)
const trigger = screen.getByRole('button', { name: 'Billing' })
expect(trigger).toHaveAttribute('aria-expanded', 'false')
const controlsExisting = () => {
const id = trigger.getAttribute('aria-controls')
// Base UI only sets aria-controls while the panel is open; when set, it must resolve.
return id == null || document.getElementById(id) != null
}
expect(controlsExisting()).toBe(true)
await userEvent.click(trigger)
expect(trigger).toHaveAttribute('aria-expanded', 'true')
expect(onValueChange).toHaveBeenLastCalledWith(['a'])
expect(document.getElementById(trigger.getAttribute('aria-controls')!)).toHaveTextContent('Billing answer')
await userEvent.click(trigger)
expect(trigger).toHaveAttribute('aria-expanded', 'false')
expect(controlsExisting()).toBe(true)
})
it('closes the other section unless multiple', async () => {
const { unmount } = render(<Accordion items={items} defaultValue={['a']} />)
await userEvent.click(screen.getByRole('button', { name: 'Cancelling' }))
expect(screen.getByRole('button', { name: 'Billing' })).toHaveAttribute('aria-expanded', 'false')
unmount()
render(<Accordion items={items} defaultValue={['a']} multiple />)
await userEvent.click(screen.getByRole('button', { name: 'Cancelling' }))
expect(screen.getByRole('button', { name: 'Billing' })).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByRole('button', { name: 'Cancelling' })).toHaveAttribute('aria-expanded', 'true')
})
it('works with the keyboard', async () => {
render(<Accordion items={items} />)
await userEvent.tab()
expect(screen.getByRole('button', { name: 'Billing' })).toHaveFocus()
await userEvent.keyboard('{Enter}')
expect(screen.getByRole('button', { name: 'Billing' })).toHaveAttribute('aria-expanded', 'true')
await userEvent.tab()
await userEvent.keyboard(' ')
expect(screen.getByRole('button', { name: 'Cancelling' })).toHaveAttribute('aria-expanded', 'true')
})
it('renders headings at the requested level', () => {
const { rerender } = render(<Accordion items={items} />)
expect(screen.getAllByRole('heading', { level: 3 })).toHaveLength(3)
rerender(<Accordion items={items} headingLevel={5} />)
expect(screen.getAllByRole('heading', { level: 5 })).toHaveLength(3)
expect(screen.getByRole('heading', { level: 5, name: 'Billing' })).toContainElement(
screen.getByRole('button', { name: 'Billing' }),
)
})
it('disables items', () => {
render(<Accordion items={items} />)
const sso = screen.getByRole('button', { name: 'SSO' })
expect(sso).toHaveAttribute('aria-disabled', 'true')
})
it('works controlled', async () => {
const onValueChange = vi.fn()
render(<Accordion items={items} value={['b']} onValueChange={onValueChange} />)
await userEvent.click(screen.getByRole('button', { name: 'Billing' }))
expect(onValueChange).toHaveBeenCalledWith(['a'])
expect(screen.getByRole('button', { name: 'Cancelling' })).toHaveAttribute('aria-expanded', 'true')
})
it('has no axe violations', async () => {
const { container } = render(<Accordion items={items} defaultValue={['a']} variant="separated" />)
await expectNoA11yViolations(container)
})
})
+79 -75
View File
@@ -1,87 +1,91 @@
import { useId, useState, type ReactNode } from 'react'
import { createElement, type ComponentProps, type ReactNode } from 'react'
import { Accordion as BaseAccordion } from '@base-ui/react/accordion'
import { ChevronDown } from 'lucide-react'
import { cn } from '../lib/cn'
import {
ACCORDION_ITEM_STYLES,
ACCORDION_PANEL_INNER,
ACCORDION_ROOT_STYLES,
ACCORDION_TRIGGER_STYLES,
accordionChevron,
accordionPanel,
accordionTrigger,
type AccordionHeadingLevel,
type AccordionVariant,
} from './accordion.tokens'
export type AccordionItem = {
title: string
/** Unique id for the item; used in `value`. */
value: string
title: ReactNode
content: ReactNode
disabled?: boolean
}
export type AccordionProps = {
export type AccordionProps = Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & {
items: AccordionItem[]
defaultOpenIndex?: number
allowMultiple?: boolean
/** Allows several items to be open at once. */
multiple?: boolean
/** Open items (controlled). */
value?: string[]
/** Initially open items (uncontrolled). */
defaultValue?: string[]
/** Called with the open items whenever one opens or closes. */
onValueChange?: (value: string[]) => void
/** `bordered` groups items in one box, `separated` gives each its own card, `ghost` only divides them. */
variant?: AccordionVariant
/** Heading level of each trigger, to fit the page outline. */
headingLevel?: AccordionHeadingLevel
/** Disables every item. */
disabled?: boolean
}
function Chevron() {
/**
* A stack of collapsible sections. Closed panels stay in the DOM as
* `hidden="until-found"`, so the browser's find-in-page can open them.
*/
export function Accordion({
items,
multiple = false,
value,
defaultValue,
onValueChange,
variant = 'bordered',
headingLevel = 3,
disabled,
className,
...props
}: AccordionProps) {
const heading = `h${headingLevel}`
return (
<svg
aria-hidden="true"
className="size-4 shrink-0 transition-transform duration-200"
fill="none"
viewBox="0 0 20 20"
<BaseAccordion.Root
multiple={multiple}
value={value}
defaultValue={defaultValue}
onValueChange={onValueChange ? (next) => onValueChange(next as string[]) : undefined}
disabled={disabled}
hiddenUntilFound
className={cn(ACCORDION_ROOT_STYLES[variant], className)}
{...props}
>
<path
d="m5 7.5 5 5 5-5"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="1.8"
/>
</svg>
)
}
export function Accordion({ items, defaultOpenIndex = 0, allowMultiple = false }: AccordionProps) {
const [openItems, setOpenItems] = useState<number[]>(
defaultOpenIndex < 0 ? [] : [defaultOpenIndex],
)
const baseId = useId()
function toggle(index: number) {
setOpenItems((current) => {
if (allowMultiple) {
return current.includes(index)
? current.filter((item) => item !== index)
: [...current, index]
}
return current.includes(index) ? [] : [index]
})
}
return (
<div className="divide-y divide-slate-200 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
{items.map((item, index) => {
const isOpen = openItems.includes(index)
const triggerId = `${baseId}-trigger-${index}`
const panelId = `${baseId}-panel-${index}`
return (
<div key={item.title}>
<h3>
<button
id={triggerId}
type="button"
aria-expanded={isOpen}
aria-controls={panelId}
onClick={() => toggle(index)}
className="flex w-full items-center justify-between gap-5 px-5 py-4 text-left text-sm font-bold text-slate-900 transition hover:bg-slate-50"
>
<span>{item.title}</span>
<span className={isOpen ? 'rotate-180 text-primary-500' : 'text-slate-400'}>
<Chevron />
</span>
</button>
</h3>
{isOpen && (
<div id={panelId} role="region" aria-labelledby={triggerId} className="px-5 pb-5">
<div className="border-l-2 border-primary-100 pl-4 text-sm leading-6 text-slate-600">
{item.content}
</div>
</div>
)}
</div>
)
})}
</div>
{items.map((item) => (
<BaseAccordion.Item
key={item.value}
value={item.value}
disabled={item.disabled}
className={ACCORDION_ITEM_STYLES[variant]}
>
<BaseAccordion.Header render={(headerProps) => createElement(heading, headerProps)} className="m-0">
<BaseAccordion.Trigger className={cn(accordionTrigger, ACCORDION_TRIGGER_STYLES[variant])}>
<span className="min-w-0">{item.title}</span>
<ChevronDown aria-hidden="true" className={accordionChevron} />
</BaseAccordion.Trigger>
</BaseAccordion.Header>
<BaseAccordion.Panel className={accordionPanel}>
<div className={ACCORDION_PANEL_INNER[variant]}>{item.content}</div>
</BaseAccordion.Panel>
</BaseAccordion.Item>
))}
</BaseAccordion.Root>
)
}
+199 -83
View File
@@ -1,6 +1,19 @@
import { useState, type ReactElement } from 'react'
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { CloudUpload } from 'lucide-react'
import { fn } from 'storybook/test'
import { Alert } from './Alert'
import { ALERT_COLORS, ALERT_VARIANTS, type AlertColor } from './alert.tokens'
import { Button } from './Button'
const MESSAGES: Record<AlertColor, { title: string; body: string }> = {
info: { title: 'Scheduled maintenance', body: 'The workspace will be read-only on Saturday from 02:00 to 04:00 UTC.' },
success: { title: 'Invoice sent', body: 'Invoice INV-2048 was emailed to [email protected].' },
warning: { title: 'Your trial ends in 3 days', body: 'Add a payment method to keep access to your projects.' },
danger: { title: 'Payment failed', body: 'We could not charge the card ending in 4242. Update it to avoid interruption.' },
neutral: { title: 'Draft saved', body: 'Changes to “Quarterly report” were saved 2 minutes ago.' },
primary: { title: 'New: shared workspaces', body: 'Invite teammates from Acme Corporation to collaborate in real time.' },
}
const meta = {
title: 'Feedback/Alert',
@@ -10,112 +23,215 @@ const meta = {
docs: {
description: {
component:
'Inline, dismissible status message. `iconName` takes any Lucide icon name as a string, so the icon is controllable without importing the module.',
'An inline status message. `danger` and `warning` use `role="alert"` so screen readers announce them at once; the other colours use a polite `role="status"`. Alerts can carry actions, be dismissed (`dismissible`, with `open`/`onOpenChange`), or close themselves after `autoClose` ms. The countdown pauses while the alert is hovered or focused.',
},
},
},
argTypes: {
color: { control: 'select', options: ['success', 'info', 'warning', 'error'] },
variant: { control: 'select', options: ['default', 'filled', 'outlined', 'gradient'] },
iconName: {
control: 'text',
description: 'Lucide icon name, e.g. "Info", "CheckCircle2", "TriangleAlert".',
},
showCloseButton: { control: 'boolean' },
showMessage: { control: 'boolean' },
closeOnOutsideClick: { control: 'boolean' },
autoClose: {
control: { type: 'number', min: 0, step: 500 },
description: 'Auto-close delay in ms. 0 disables.',
},
width: { control: 'text' },
height: { control: 'text' },
color: { control: 'select', options: ALERT_COLORS, table: { defaultValue: { summary: 'info' } } },
variant: { control: 'inline-radio', options: ALERT_VARIANTS, table: { defaultValue: { summary: 'soft' } } },
title: { control: 'text' },
children: { control: 'text' },
icon: { control: false },
hideIcon: { control: 'boolean' },
actions: { control: false },
dismissible: { control: 'boolean' },
open: { control: 'boolean' },
defaultOpen: { control: 'boolean' },
onOpenChange: { control: false },
autoClose: { control: { type: 'number', min: 0, step: 1000 }, table: { defaultValue: { summary: '0' } } },
},
args: {
title: 'Payroll run approved',
message: 'March 2026 payroll was approved and queued for disbursement.',
iconName: 'CheckCircle2',
variant: 'default',
color: 'success',
showCloseButton: true,
showMessage: true,
closeOnOutsideClick: false,
color: 'info',
variant: 'soft',
title: MESSAGES.info.title,
children: MESSAGES.info.body,
hideIcon: false,
dismissible: false,
autoClose: 0,
width: 'w-full',
height: 'h-auto',
onOpenChange: fn(),
},
decorators: [
(Story) => (
<div className="max-w-2xl">
<Story />
</div>
),
],
} satisfies Meta<typeof Alert>
export default meta
type Story = StoryObj<typeof meta>
/**
* Dismissing unmounts the Alert, so this wrapper remounts it via a changing key.
* Declared as a named component so the rules-of-hooks lint accepts the hook call.
*/
function Remountable({ children, note }: { children: ReactElement; note?: string }) {
const [key, setKey] = useState(0)
return (
<div className="space-y-3">
<div key={key}>{children}</div>
<button
type="button"
onClick={() => setKey((k) => k + 1)}
className="text-xs font-semibold text-primary-600 underline"
>
Remount
</button>
{note && <p className="text-xs text-gray-500">{note}</p>}
</div>
)
}
export const Playground: Story = {
render: (args) => <Remountable><Alert {...args} /></Remountable>,
}
export const Playground: Story = {}
export const Colors: Story = {
render: () => (
<div className="space-y-3">
<Alert color="success" title="Approved" message="Queued for disbursement." iconName="CheckCircle2" />
<Alert color="info" title="Processing" message="Validating statutory contributions." iconName="Info" />
<Alert color="warning" title="Review needed" message="2 employees have incomplete bank details." iconName="TriangleAlert" />
<Alert color="error" title="Failed" message="Bank rejected the transfer file." iconName="XCircle" />
parameters: { docs: { description: { story: 'Every colour in the default `soft` variant.' } } },
render: (args) => (
<div className="grid gap-3">
{ALERT_COLORS.map((color) => (
<Alert key={color} {...args} color={color} title={MESSAGES[color].title}>
{MESSAGES[color].body}
</Alert>
))}
</div>
),
}
export const Variants: Story = {
render: () => (
<div className="space-y-3">
<Alert variant="default" color="info" title="Default" message="Tinted surface, semantic text." />
<Alert variant="filled" color="info" title="Filled" message="Solid semantic background." />
<Alert variant="outlined" color="info" title="Outlined" message="Transparent with a border." />
<Alert variant="gradient" title="Gradient" message="Green-to-primary gradient, brand moment." />
</div>
),
export const Solid: Story = {
args: { variant: 'solid' },
render: Colors.render,
}
export const WithoutCloseButton: Story = {
render: () => (
<Alert
color="info"
title="Persistent notice"
message="This alert cannot be dismissed."
showCloseButton={false}
/>
),
export const Outline: Story = {
args: { variant: 'outline' },
render: Colors.render,
}
export const TitleOnly: Story = {
render: () => <Alert color="warning" title="12 items need attention" showCloseButton={false} />,
}
/** Auto-closes after 2s; the Remount button brings it back. */
export const AutoClose: Story = {
render: (args) => (
<Remountable note="Dismisses itself after 2000ms.">
<Alert {...args} autoClose={2000} />
</Remountable>
<div className="grid gap-3">
{ALERT_VARIANTS.map((variant) => (
<Alert key={variant} {...args} variant={variant} color="success" title={`Settings saved (${variant})`}>
{null}
</Alert>
))}
</div>
),
}
export const WithActions: Story = {
render: (args) => (
<div className="grid gap-3">
<Alert
{...args}
color="warning"
title={MESSAGES.warning.title}
actions={
<>
<Button size="sm" color="warning">
Add payment method
</Button>
<Button size="sm" variant="ghost" color="warning">
Compare plans
</Button>
</>
}
>
{MESSAGES.warning.body}
</Alert>
<Alert
{...args}
color="danger"
variant="outline"
title={MESSAGES.danger.title}
dismissible
actions={
<Button size="sm" variant="outline" color="danger">
Update card
</Button>
}
>
{MESSAGES.danger.body}
</Alert>
<Alert
{...args}
color="primary"
variant="solid"
title={MESSAGES.primary.title}
icon={<CloudUpload />}
dismissible
actions={
<Button size="sm" variant="outline" color="neutral" className="border-white/40 bg-transparent text-white hover:bg-white/15">
Invite teammates
</Button>
}
>
{MESSAGES.primary.body}
</Alert>
</div>
),
}
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 (
<div className="grid gap-3">
<Alert
{...args}
open={open}
onOpenChange={(next) => {
setOpen(next)
args.onOpenChange?.(next)
}}
/>
{!open && (
<div>
<Button size="sm" variant="outline" color="neutral" onClick={() => setOpen(true)}>
Show the alert again
</Button>
</div>
)}
</div>
)
},
}
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 (
<div className="grid gap-3">
<Alert
key={key}
{...args}
actions={
<Button size="sm" variant="soft" color="neutral">
View changes
</Button>
}
onOpenChange={(next) => {
setOpen(next)
args.onOpenChange?.(next)
}}
/>
{!open && (
<div>
<Button
size="sm"
variant="outline"
color="neutral"
onClick={() => {
setKey((k) => k + 1)
setOpen(true)
}}
>
Restart
</Button>
</div>
)}
</div>
)
},
}
export const WithoutIcon: Story = {
args: { hideIcon: true, color: 'neutral', title: undefined, children: 'You are viewing an archived project. Restore it to make changes.' },
}
+109
View File
@@ -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(<Alert color={color} title="Heads up">Body</Alert>)
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(<Alert>Message</Alert>)
expect(container.querySelector('svg')).not.toBeNull()
rerender(<Alert icon={<svg data-testid="custom" />}>Message</Alert>)
expect(screen.getByTestId('custom')).toBeInTheDocument()
rerender(<Alert hideIcon>Message</Alert>)
expect(container.querySelector('svg')).toBeNull()
})
it('dismisses (uncontrolled) and calls onOpenChange', async () => {
const onOpenChange = vi.fn()
render(
<Alert dismissible onOpenChange={onOpenChange} title="Saved">
Done
</Alert>,
)
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(
<Alert dismissible open onOpenChange={onOpenChange}>
Done
</Alert>,
)
await userEvent.click(screen.getByRole('button', { name: 'Dismiss' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(screen.getByRole('status')).toBeInTheDocument()
rerender(
<Alert dismissible open={false} onOpenChange={onOpenChange}>
Done
</Alert>,
)
expect(screen.queryByRole('status')).toBeNull()
})
it('auto-closes after the delay', () => {
vi.useFakeTimers()
const onOpenChange = vi.fn()
render(<Alert autoClose={3000} onOpenChange={onOpenChange}>Saved</Alert>)
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(<Alert autoClose={3000}>Saved</Alert>)
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(
<Alert autoClose={1000} dismissible>
Saved
</Alert>,
)
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(
<div>
{ALERT_VARIANTS.map((variant) =>
ALERT_COLORS.map((color) => (
<Alert key={variant + color} variant={variant} color={color} title="Title" dismissible actions={<button type="button">Act</button>}>
Message
</Alert>
)),
)}
</div>,
)
await expectNoA11yViolations(container)
}, 20000)
})
+122 -128
View File
@@ -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<HTMLDivElement> & {
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<ComponentProps<'div'>, '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<HTMLDivElement, AlertProps>(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<HTMLDivElement>(null)
const DEFAULT_ICONS: Record<AlertColor, ReactNode> = {
info: <Info />,
success: <CircleCheck />,
warning: <TriangleAlert />,
danger: <CircleX />,
neutral: <Info />,
primary: <CircleAlert />,
}
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<string, Icons.LucideIcon>
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 (
<div
ref={internalRef}
role="alert"
role={urgent ? 'alert' : 'status'}
className={cn(
'rounded-md p-3 transition-all duration-300',
width,
height,
variantClasses,
'flex w-full items-start gap-3 rounded-xl border p-4 text-sm leading-5',
ALERT_STYLES[variant][color],
className,
)}
onMouseEnter={(e) => {
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}
>
<div className="flex justify-between gap-3">
<div className="flex items-start gap-3 w-full">
{LucideIcon && <LucideIcon className="w-5 h-5 mt-0.5 shrink-0" aria-hidden="true" />}
<div className="flex flex-col gap-1 w-full">
{title && <h5 className="font-semibold text-sm leading-tight">{title}</h5>}
{showMessage && message && <p className="text-sm opacity-90 leading-normal">{message}</p>}
</div>
</div>
{showCloseButton && (
<button
onClick={handleClose}
className="shrink-0 p-1 rounded-md hover:bg-black/10 transition-colors cursor-pointer"
type="button"
aria-label="Close alert"
>
{customClose ?? <Icons.X className="w-4 h-4" />}
</button>
)}
{!hideIcon && (
<span aria-hidden="true" className={cn('flex shrink-0 [&_svg]:size-5', ALERT_ICON_STYLES[variant][color])}>
{icon ?? DEFAULT_ICONS[color]}
</span>
)}
<div className="min-w-0 flex-1">
{title != null && <p className="font-semibold">{title}</p>}
{children != null && <div className={cn(title != null && 'mt-1')}>{children}</div>}
{actions != null && <div className="mt-3 flex flex-wrap items-center gap-2">{actions}</div>}
</div>
{dismissible && (
<IconButton
size="sm"
aria-label="Dismiss"
icon={<X />}
onClick={() => setOpen(false)}
className={cn('-my-1.5 -mr-1.5 size-8', ALERT_CLOSE_STYLES[variant])}
/>
)}
</div>
)
})
export default Alert
}
+150
View File
@@ -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<void>((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: <Trash2 />,
trigger: (
<Button color="danger" variant="outline" startIcon={<Trash2 aria-hidden="true" />}>
Delete project
</Button>
),
onConfirm: fn(),
onCancel: fn(),
onOpenChange: fn(),
},
} satisfies Meta<typeof AlertDialog>
export default meta
type Story = StoryObj<typeof meta>
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: <Button startIcon={<Send aria-hidden="true" />}>Publish</Button>,
},
parameters: ownFrame(),
}
export const Warning: Story = {
args: {
defaultOpen: true,
color: 'warning',
icon: <AlertTriangle />,
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: (
<Button variant="outline" color="neutral" startIcon={<LogOut aria-hidden="true" />}>
Sign out everywhere
</Button>
),
},
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: (
<ul className="m-0 list-disc space-y-1 pl-5 text-fg-muted">
<li>Jane Doe (name@example.com)</li>
<li>John Smith (john@example.com)</li>
<li>Alex Kim (alex@example.com)</li>
</ul>
),
},
parameters: ownFrame(560),
}
export const Colors: Story = {
render: (args) => (
<div className="flex flex-wrap gap-3">
{ALERT_DIALOG_COLORS.map((color) => (
<AlertDialog
key={color}
{...args}
color={color}
confirmLabel="Confirm"
trigger={
<Button variant="outline" color="neutral">
{color[0].toUpperCase() + color.slice(1)}
</Button>
}
/>
))}
</div>
),
}
+83
View File
@@ -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: <Button color="danger">Delete project</Button>,
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(<AlertDialog {...base} />)
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(<AlertDialog {...base} onConfirm={onConfirm} />)
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(<AlertDialog {...base} onConfirm={onConfirm} onCancel={onCancel} />)
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(<AlertDialog {...base} defaultOpen />)
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<void>((r) => (resolve = r)))
render(<AlertDialog {...base} defaultOpen onConfirm={onConfirm} loadingLabel="Deleting…" />)
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(<AlertDialog {...base} defaultOpen onConfirm={onConfirm} />)
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(<AlertDialog {...base} defaultOpen icon={<svg />} />)
await screen.findByRole('alertdialog')
await expectNoA11yViolations(document.body)
})
})
+149
View File
@@ -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 `<Button>`. */
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<unknown>
/** 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<unknown> {
return typeof (value as Promise<unknown> | 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 (
<BaseAlertDialog.Root open={open} onOpenChange={handleOpenChange}>
{trigger && <BaseAlertDialog.Trigger render={trigger} />}
<BaseAlertDialog.Portal>
<BaseAlertDialog.Backdrop className={cn(backdropClass, 'z-50')} />
<BaseAlertDialog.Viewport className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
<BaseAlertDialog.Popup className={cn(dialogPanelClass, 'max-w-md', className)}>
<div className="flex flex-col gap-4 p-5 sm:flex-row sm:items-start sm:p-6">
{icon != null && (
<span
aria-hidden="true"
className={cn(
'flex size-10 shrink-0 items-center justify-center rounded-full [&_svg]:size-5',
ALERT_ICON_STYLES[color],
)}
>
{icon}
</span>
)}
<div className="flex min-w-0 flex-col gap-1.5">
<BaseAlertDialog.Title className={dialogTitleClass}>{title}</BaseAlertDialog.Title>
{description != null && (
<BaseAlertDialog.Description className={dialogDescriptionClass}>
{description}
</BaseAlertDialog.Description>
)}
{children != null && <div className="mt-2 text-sm leading-6 text-fg">{children}</div>}
</div>
</div>
<div className="flex flex-col-reverse gap-2 border-t border-border bg-surface-muted px-5 py-4 sm:flex-row sm:justify-end sm:gap-3 sm:px-6">
<BaseAlertDialog.Close disabled={pending} render={<Button variant="outline" color="neutral" />}>
{cancelLabel}
</BaseAlertDialog.Close>
<Button color={color} loading={pending} loadingText={loadingLabel} onClick={handleConfirm}>
{confirmLabel}
</Button>
</div>
</BaseAlertDialog.Popup>
</BaseAlertDialog.Viewport>
</BaseAlertDialog.Portal>
</BaseAlertDialog.Root>
)
}
+185
View File
@@ -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<typeof Avatar>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-4">
<div className="flex items-end gap-4">
{AVATAR_SIZES_LIST.map((size) => (
<Avatar key={size} {...args} size={size} />
))}
</div>
<div className="flex items-end gap-4">
{AVATAR_SIZES_LIST.map((size) => (
<Avatar key={size} {...args} src={undefined} size={size} />
))}
</div>
</div>
),
}
export const Shapes: Story = {
render: (args) => (
<div className="flex items-center gap-4">
{AVATAR_SHAPES.map((shape) => (
<Avatar key={shape} {...args} shape={shape} />
))}
{AVATAR_SHAPES.map((shape) => (
<Avatar key={`${shape}-fallback`} {...args} src={undefined} name="Acme Corporation" shape={shape} />
))}
</div>
),
}
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) => (
<div className="flex flex-wrap items-center gap-3">
{['Jane Doe', 'John Smith', 'Maya Chen', 'Carlos Mendez', 'Aiko Tanaka', 'Samuel Okafor', 'Lena Fischer', 'Acme'].map(
(name) => (
<Avatar key={name} size={args.size} shape={args.shape} name={name} />
),
)}
<Avatar size={args.size} shape={args.shape} alt="Unknown user" />
<Avatar size={args.size} shape={args.shape} name="Marcus Reed" src="data:image/png;base64,broken" />
</div>
),
}
export const WithStatus: Story = {
render: (args) => (
<div className="grid gap-5">
<div className="flex items-center gap-5">
{AVATAR_STATUSES.map((status) => (
<div key={status} className="flex flex-col items-center gap-2">
<Avatar {...args} status={status} />
<span className="text-xs capitalize text-fg-muted">{status}</span>
</div>
))}
</div>
<div className="flex items-end gap-4">
{AVATAR_SIZES_LIST.map((size) => (
<Avatar key={size} name="John Smith" src={PORTRAITS.john} size={size} status="online" />
))}
{AVATAR_SIZES_LIST.map((size) => (
<Avatar key={`sq-${size}`} name="Maya Chen" shape="square" size={size} status="busy" />
))}
</div>
</div>
),
}
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: () => (
<div className="grid gap-6">
{(['sm', 'md', 'lg'] as const).map((size) => (
<AvatarGroup key={size} size={size} max={4} aria-label="Project members">
<Avatar name="Jane Doe" src={PORTRAITS.jane} />
<Avatar name="John Smith" src={PORTRAITS.john} />
<Avatar name="Maya Chen" src={PORTRAITS.maya} />
<Avatar name="Carlos Mendez" />
<Avatar name="Aiko Tanaka" src={PORTRAITS.aiko} />
<Avatar name="Samuel Okafor" />
<Avatar name="Lena Fischer" />
</AvatarGroup>
))}
<AvatarGroup size="md" shape="square" max={3} aria-label="Reviewers">
<Avatar name="Acme Corporation" />
<Avatar name="Jane Doe" src={PORTRAITS.jane} />
<Avatar name="Marcus Reed" />
<Avatar name="Lena Fischer" />
<Avatar name="Samuel Okafor" />
</AvatarGroup>
</div>
),
}
export const InContext: Story = {
render: () => (
<div className="flex w-full max-w-sm items-center gap-3 rounded-xl border border-border bg-surface p-4">
<Avatar name="Jane Doe" src={PORTRAITS.jane} size="lg" status="online" />
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold text-fg">Jane Doe</p>
<p className="truncate text-sm text-fg-muted">jane.doe@example.com</p>
</div>
<AvatarGroup size="xs" max={2} aria-label="Shared with">
<Avatar name="John Smith" src={PORTRAITS.john} />
<Avatar name="Maya Chen" src={PORTRAITS.maya} />
<Avatar name="Carlos Mendez" />
<Avatar name="Aiko Tanaka" />
</AvatarGroup>
</div>
),
}
export const GroupPlayground: StoryObj<typeof AvatarGroup> = {
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) => (
<AvatarGroup {...args}>
<Avatar name="Jane Doe" src={PORTRAITS.jane} />
<Avatar name="John Smith" src={PORTRAITS.john} />
<Avatar name="Maya Chen" src={PORTRAITS.maya} />
<Avatar name="Carlos Mendez" />
<Avatar name="Aiko Tanaka" src={PORTRAITS.aiko} />
<Avatar name="Samuel Okafor" />
</AvatarGroup>
),
}
+65
View File
@@ -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(<Avatar name="Jane Doe" />)
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(<Avatar name="John Smith" src="data:image/png;base64,x" />)
expect(screen.getByText('JS')).toBeInTheDocument()
})
it('labels the status dot', () => {
render(<Avatar name="Jane Doe" status="online" />)
expect(screen.getByRole('img', { name: 'Online' })).toBeInTheDocument()
})
it('accepts a custom status label', () => {
render(<Avatar name="Jane Doe" status="busy" statusLabel="In a meeting" />)
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(
<AvatarGroup max={2} aria-label="Team">
<Avatar name="Jane Doe" />
<Avatar name="John Smith" />
<Avatar name="Maya Chen" />
<Avatar name="Carlos Mendez" />
</AvatarGroup>,
)
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(
<div>
<Avatar name="Jane Doe" status="away" />
<Avatar alt="Unknown user" />
<AvatarGroup max={1} aria-label="Reviewers">
<Avatar name="Jane Doe" />
<Avatar name="John Smith" />
</AvatarGroup>
</div>,
)
await expectNoA11yViolations(container)
})
})
+133
View File
@@ -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<ComponentProps<'span'>, '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 (
<span className={cn('relative inline-flex shrink-0 align-middle', className)} {...props}>
<BaseAvatar.Root
className={cn(
'inline-flex select-none items-center justify-center overflow-hidden font-semibold leading-none',
AVATAR_SIZES[size],
shapeClass,
name ? AVATAR_COLORS[colorFromName(name)] : AVATAR_COLORS.neutral,
group && 'ring-2 ring-surface',
)}
>
{src && <BaseAvatar.Image src={src} alt={label ?? ''} className="size-full object-cover" />}
<BaseAvatar.Fallback className="flex size-full items-center justify-center">
{initials ? <span aria-hidden="true">{initials}</span> : <User aria-hidden="true" />}
{label && <span className="sr-only">{label}</span>}
</BaseAvatar.Fallback>
</BaseAvatar.Root>
{status && (
<span
role="img"
aria-label={statusLabel ?? AVATAR_STATUS_LABELS[status]}
className={cn(
'absolute rounded-full ring-surface',
shape === 'circle' ? 'right-0 bottom-0' : '-right-0.5 -bottom-0.5',
AVATAR_STATUS_SIZES[size],
AVATAR_STATUS_STYLES[status],
)}
/>
)}
</span>
)
}
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 (
<AvatarGroupContext value={{ size, shape }}>
<div role="group" className={cn('flex items-center', AVATAR_GROUP_OVERLAP[size], className)} {...props}>
{visible}
{hidden > 0 && (
<span
className={cn(
'relative inline-flex shrink-0 select-none items-center justify-center bg-surface-sunken font-semibold leading-none text-fg-muted ring-2 ring-surface',
AVATAR_SIZES[size],
radius(shape, size),
)}
>
<span aria-hidden="true">+{hidden}</span>
<span className="sr-only">and {hidden} more</span>
</span>
)}
</div>
</AvatarGroupContext>
)
}
+284 -95
View File
@@ -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<typeof Badge>
export default meta
type Story = StoryObj<typeof meta>
const BellIcon = () => <Bell className="h-6 w-6 text-gray-600" />
const title = (s: string) => s[0].toUpperCase() + s.slice(1)
export const Playground: Story = {
export const Playground: Story = {}
export const Variants: Story = {
render: (args) => (
<Badge {...args}>
<BellIcon />
</Badge>
),
}
export const FloatingPositions: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-10">
{(['top_right', 'top_left', 'bottom_right', 'bottom_left'] as const).map((pos) => (
<div key={pos} className="flex flex-col items-center gap-2">
<Badge content="9" floatingPosition={pos} color="primary">
<BellIcon />
</Badge>
<code className="text-[10px] text-gray-500">{pos}</code>
</div>
))}
</div>
),
}
export const FloatingSizes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-10">
{(['xs', 'sm', 'md', 'lg'] as const).map((size) => (
<div key={size} className="flex flex-col items-center gap-2">
<Badge content={12} floatingSize={size} color="danger">
<Inbox className="h-6 w-6 text-gray-600" />
</Badge>
<code className="text-[10px] text-gray-500">{size}</code>
</div>
))}
</div>
),
}
export const Colors: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-3">
{(['primary', 'info', 'gray', 'danger', 'success', 'warning'] as const).map((color) => (
<Badge key={color} type="default" color={color}>
{color}
{BADGE_VARIANTS.map((variant) => (
<Badge key={variant} {...args} variant={variant}>
{title(variant)}
</Badge>
))}
</div>
),
}
/** 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 (
<div className="flex flex-wrap items-center gap-6">
{[1, 5, 12].map((n) => (
<div key={n} className="flex flex-col items-center gap-2">
<Badge content={n} colorRanges={ranges}>
<Inbox className="h-6 w-6 text-gray-600" />
export const Colors: Story = {
parameters: { docs: { description: { story: 'Every colour in every variant, with and without a dot.' } } },
render: (args) => (
<div className="grid gap-3">
{BADGE_VARIANTS.map((variant) => (
<div key={variant} className="flex flex-wrap items-center gap-2">
<span className="w-16 text-xs font-medium text-fg-muted">{title(variant)}</span>
{COLORS.map((color) => (
<Badge key={color} {...args} variant={variant} color={color}>
{title(color)}
</Badge>
<code className="text-[10px] text-gray-500">{n} pending</code>
</div>
))}
{COLORS.map((color) => (
<Badge key={`${color}-dot`} {...args} variant={variant} color={color} dot>
{title(color)}
</Badge>
))}
</div>
))}
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-wrap items-center gap-3">
{SIZES.map((size) => (
<Badge key={size} {...args} size={size} dot>
Size {size}
</Badge>
))}
</div>
),
}
export const WithIcons: Story = {
render: (args) => (
<div className="flex flex-wrap items-center gap-2">
<Badge {...args} color="success" icon={<Check aria-hidden="true" />}>
Approved
</Badge>
<Badge {...args} color="warning" icon={<Clock aria-hidden="true" />}>
Pending review
</Badge>
<Badge {...args} color="primary" variant="solid" icon={<Sparkles aria-hidden="true" />}>
New
</Badge>
<Badge {...args} color="neutral" variant="outline" icon={<Mail aria-hidden="true" />}>
Invited
</Badge>
</div>
),
}
export const StatusDots: Story = {
parameters: { docs: { description: { story: 'A leading dot reads as live status.' } } },
render: () => (
<div className="flex flex-wrap items-center gap-2">
<Badge color="success" dot>
Operational
</Badge>
<Badge color="warning" dot>
Degraded
</Badge>
<Badge color="danger" dot>
Outage
</Badge>
<Badge color="neutral" dot>
Paused
</Badge>
<Badge color="info" variant="outline" dot>
Scheduled
</Badge>
</div>
),
}
function FilterChips() {
const [filters, setFilters] = useState(['Engineering', 'Full-time', 'Remote', 'Started 2024'])
return (
<div className="flex max-w-lg flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium text-fg">Filters</span>
{filters.map((f) => (
<Badge key={f} color="primary" onRemove={() => setFilters((all) => all.filter((x) => x !== f))}>
{f}
</Badge>
))}
{filters.length === 0 && <span className="text-sm text-fg-muted">No filters applied.</span>}
</div>
<div className="flex flex-wrap gap-2">
{SIZES.map((size) => (
<Badge key={size} size={size} variant="outline" color="neutral" onRemove={fn()}>
Acme Corporation
</Badge>
))}
</div>
)
</div>
)
}
export const RemovableFilters: Story = {
parameters: {
docs: {
description: { story: '`onRemove` adds a labelled remove button ("Remove Engineering"). Press one to remove the filter.' },
},
},
render: () => <FilterChips />,
}
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: () => (
<Badge content="Live" color="danger" pulse>
<BellIcon />
</Badge>
<div className="flex flex-wrap items-center gap-2">
{[0, 3, 5, 8, 12, 42].map((n) => (
<Badge key={n} colorRanges={APPROVAL_RANGES} variant="solid">
{n}
</Badge>
))}
{[2, 7, 15].map((n) => (
<Badge key={`soft-${n}`} colorRanges={APPROVAL_RANGES}>
{n}
</Badge>
))}
</div>
),
}
/** `default` type renders a standalone chip; children take precedence over content. */
export const ChipWithIcon: Story = {
export const InContext: Story = {
render: () => (
<Badge type="default" color="primary" defaultBorder="full" defaultSize="md">
<Settings className="mr-1.5 h-3.5 w-3.5" aria-hidden="true" />
Configured
</Badge>
<ul className="w-full max-w-md divide-y divide-border rounded-xl border border-border bg-surface">
{[
{ name: 'Q3 invoice run', meta: 'Acme Corporation · 142 invoices', status: <Badge color="success" dot>Paid</Badge> },
{ name: 'Vendor onboarding', meta: 'Globex Ltd · 3 documents', status: <Badge color="warning" dot>In review</Badge> },
{ name: 'Card payment', meta: 'Initech · Declined twice', status: <Badge color="danger" dot>Failed</Badge> },
{ name: 'Annual renewal', meta: 'Umbrella Group · Due 12 Oct', status: <Badge color="info" dot>Scheduled</Badge> },
].map((row) => (
<li key={row.name} className="flex items-center justify-between gap-4 px-4 py-3">
<div className="min-w-0">
<p className="truncate text-sm font-medium text-fg">{row.name}</p>
<p className="truncate text-xs text-fg-muted">{row.meta}</p>
</div>
{row.status}
</li>
))}
</ul>
),
}
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: () => (
<div className="flex flex-wrap items-center gap-8">
<CountBadge count={3} label={(n) => `${n} unread notifications`}>
<IconButton variant="outline" aria-label="Notifications" icon={<Bell />} />
</CountBadge>
<CountBadge count={128} max={99} label={(n) => `${n} unread messages`}>
<IconButton variant="outline" aria-label="Inbox" icon={<Inbox />} />
</CountBadge>
<CountBadge count={0} showZero color="neutral" label="Cart is empty">
<IconButton variant="outline" aria-label="Cart" icon={<ShoppingCart />} />
</CountBadge>
<CountBadge count={0} label="No new notifications">
<IconButton variant="outline" aria-label="Notifications, none new" icon={<Bell />} />
</CountBadge>
<CountBadge dot label="New activity" color="primary">
<IconButton variant="outline" aria-label="Activity" icon={<Sparkles />} />
</CountBadge>
<CountBadge dot pulse label="Live" color="success" placement="bottom-end">
<Avatar name="Jane Doe" src={PORTRAITS.jane} />
</CountBadge>
<CountBadge count={7} colorRanges={APPROVAL_RANGES} label={(n) => `${n} pending approvals`}>
<Avatar name="John Smith" shape="square" />
</CountBadge>
</div>
),
}
export const CountBadgePlacements: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-10">
{COUNT_BADGE_PLACEMENTS.map((placement) => (
<div key={placement} className="flex flex-col items-center gap-3">
<CountBadge count={4} placement={placement} label={(n) => `${n} new`}>
<Avatar name="Aiko Tanaka" src={PORTRAITS.aiko} size="lg" shape="square" />
</CountBadge>
<span className="text-xs text-fg-muted">{placement}</span>
</div>
))}
</div>
),
}
export const CountBadgeColors: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-6">
{COLORS.map((color) => (
<CountBadge key={color} count={12} color={color} label={`12 ${color} items`}>
<span className="flex size-10 items-center justify-center rounded-lg border border-border bg-surface text-fg-muted">
<Mail aria-hidden="true" className="size-5" />
</span>
</CountBadge>
))}
<CountBadge count={5} size="sm" label="5 new">
<span className="flex size-8 items-center justify-center rounded-lg border border-border bg-surface text-fg-muted">
<Mail aria-hidden="true" className="size-4" />
</span>
</CountBadge>
<CountBadge count={2} pulse label="2 alerts">
<span className="flex size-10 items-center justify-center rounded-lg border border-border bg-surface text-fg-muted">
<Bell aria-hidden="true" className="size-5" />
</span>
</CountBadge>
</div>
),
}
export const CountBadgePlayground: StoryObj<typeof CountBadge> = {
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) => (
<CountBadge {...args}>
<IconButton variant="outline" aria-label="Notifications" icon={<Bell />} />
</CountBadge>
),
}
+110
View File
@@ -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(<Badge color="success">Active</Badge>)
expect(screen.getByText('Active')).toBeInTheDocument()
})
it('renders a labelled remove button that calls onRemove', async () => {
const onRemove = vi.fn()
render(<Badge onRemove={onRemove}>Engineering</Badge>)
const button = screen.getByRole('button', { name: 'Remove Engineering' })
await userEvent.click(button)
expect(onRemove).toHaveBeenCalledOnce()
})
it('accepts a custom remove label', () => {
render(
<Badge onRemove={() => {}} removeLabel="Clear department filter">
Engineering
</Badge>,
)
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(
<>
<Badge colorRanges={ranges}>{2}</Badge>
<Badge colorRanges={ranges}>{12}</Badge>
</>,
)
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(<Badge className="h-10">Big</Badge>)
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(
<CountBadge count={3} label={(n) => `${n} unread notifications`}>
<button type="button">Notifications</button>
</CountBadge>,
)
expect(screen.getByRole('status', { name: '3 unread notifications' })).toHaveTextContent('3')
})
it('caps the count at max', () => {
render(
<CountBadge count={150} max={99}>
<span>Inbox</span>
</CountBadge>,
)
expect(screen.getByRole('status', { name: '99+' })).toHaveTextContent('99+')
})
it('hides a zero count unless showZero', () => {
const { rerender } = render(
<CountBadge count={0}>
<span>Inbox</span>
</CountBadge>,
)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
rerender(
<CountBadge count={0} showZero>
<span>Inbox</span>
</CountBadge>,
)
expect(screen.getByRole('status', { name: '0' })).toBeInTheDocument()
})
it('renders a dot without a number', () => {
render(
<CountBadge dot label="New activity">
<span>Activity</span>
</CountBadge>,
)
const dot = screen.getByRole('status', { name: 'New activity' })
expect(dot).toHaveTextContent('')
})
it('has no axe violations', async () => {
const { container } = render(
<div>
<Badge dot color="success">
Active
</Badge>
<Badge onRemove={() => {}}>Remote</Badge>
<CountBadge count={4} label="4 new messages">
<button type="button">Inbox</button>
</CountBadge>
</div>,
)
await expectNoA11yViolations(container)
})
})
+158 -99
View File
@@ -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<HTMLAttributes<HTMLDivElement>, '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<ComponentProps<'span'>, '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. `<Check />`. */
icon?: ReactNode
/** Renders a remove button after the label, e.g. for filter chips. */
onRemove?: (event: MouseEvent<HTMLButtonElement>) => 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<HTMLDivElement, BadgeProps>(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 (
<div
ref={ref}
className={cn(
'inline-flex items-center justify-center font-medium transition-colors',
BADGE_ROUNDED[defaultBorder] ?? BADGE_ROUNDED.lg,
DEFAULT_BADGE_SIZES[defaultSize] ?? DEFAULT_BADGE_SIZES.sm,
theme,
className,
)}
{...props}
>
{defaultIcon && <i className={cn(defaultIcon, 'mr-1.5')} aria-hidden="true" />}
{children ?? content}
</div>
)
}
/** 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 (
<span className="relative inline-flex">
<span
className={cn(
'inline-flex shrink-0 items-center whitespace-nowrap rounded-full border font-medium leading-none tabular-nums',
'[&_svg]:shrink-0',
BADGE_STYLES[variant][resolved],
BADGE_SIZES[size],
onRemove && 'pr-0.5',
className,
)}
{...props}
>
{dot && (
<span
aria-hidden="true"
className={cn('shrink-0 rounded-full', BADGE_DOT_SIZES[size], variant === 'solid' ? 'bg-current' : BADGE_DOT[resolved])}
/>
)}
{icon}
{children}
<div
ref={ref}
className={cn(
'absolute z-10 inline-flex items-center justify-center rounded-full font-semibold',
BADGE_POSITIONS[floatingPosition] ?? BADGE_POSITIONS.top_right,
BADGE_SIZES[floatingSize] ?? BADGE_SIZES.sm,
theme,
pulse && 'animate-pulse',
className,
)}
{...props}
>
{content}
</div>
{onRemove && (
<button
type="button"
aria-label={removeLabel ?? (text ? `Remove ${text}` : 'Remove')}
onClick={onRemove}
className={cn(
'inline-flex shrink-0 items-center justify-center rounded-full opacity-70 transition-[opacity,background-color]',
'hover:bg-current/15 hover:opacity-100',
size === 'sm' ? 'size-4' : size === 'md' ? 'size-5' : 'size-6',
focusRing,
)}
>
<X aria-hidden="true" strokeWidth={2.5} />
</button>
)}
</span>
)
})
}
export default Badge
export type CountBadgeProps = Omit<ComponentProps<'span'>, '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 (
<span className={cn('relative inline-flex shrink-0 align-middle', className)} {...props}>
{children}
{visible && (
<span
role="status"
aria-label={name}
className={cn(
'pointer-events-none absolute z-10 inline-flex items-center justify-center rounded-full font-semibold leading-none tabular-nums ring-2 ring-surface',
COUNT_BADGE_PLACEMENT[placement],
COUNT_BADGE_STYLES[resolved],
dot ? sizes.dot : sizes.count,
)}
>
{pulse && (
<span
aria-hidden="true"
className={cn(
'absolute inset-0 -z-10 animate-ping rounded-full opacity-60 motion-reduce:hidden',
COUNT_BADGE_PING[resolved],
)}
/>
)}
{!dot && <span aria-hidden={name ? true : undefined}>{display}</span>}
</span>
)}
</span>
)
}
+61
View File
@@ -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: <House /> },
{ 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<typeof Breadcrumb>
export default meta
type Story = StoryObj<typeof meta>
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: <Slash /> },
}
export const WithIcons: Story = {
args: {
items: [
{ label: 'Home', href: '#', icon: <House /> },
{ label: 'Documents', href: '#', icon: <Folder /> },
{ label: 'Contracts', href: '#', icon: <Folder /> },
{ label: 'Service agreement.pdf' },
],
},
}
+49
View File
@@ -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(<Breadcrumb items={items.slice(0, 3)} />)
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(<Breadcrumb items={items} maxItems={4} />)
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(<Breadcrumb items={items.slice(0, 4)} maxItems={4} />)
expect(screen.queryByRole('button')).toBeNull()
})
it('has no axe violations', async () => {
const { container } = render(<Breadcrumb items={items} maxItems={4} />)
await expectNoA11yViolations(container)
})
})
+113
View File
@@ -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<ComponentProps<'nav'>, '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<HTMLOListElement>(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<HTMLElement>('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 = (
<span aria-hidden="true" className="flex text-fg-subtle [&_svg]:size-3.5">
{separator ?? <ChevronRight />}
</span>
)
return (
<nav aria-label={ariaLabel} className={className} {...props}>
<ol ref={listRef} className="flex flex-wrap items-center gap-1.5 text-sm">
{visible.map((entry, i) => {
const last = i === visible.length - 1
if (entry === 'ellipsis') {
return (
<li key="ellipsis" className="flex items-center gap-1.5">
<button
type="button"
aria-label="Show all breadcrumbs"
onClick={() => 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,
)}
>
…
</button>
{sep}
</li>
)
}
const { item, index } = entry
return (
<li key={index} className="flex min-w-0 items-center gap-1.5">
{last ? (
<span aria-current="page" className="inline-flex items-center gap-1.5 font-medium text-fg [&_svg]:size-4 [&_svg]:shrink-0">
{item.icon}
{item.label}
</span>
) : item.href != null ? (
<a href={item.href} className={cn(linkClass, focusRing)}>
{item.icon}
{item.label}
</a>
) : (
<span className="inline-flex items-center gap-1.5 text-fg-muted [&_svg]:size-4 [&_svg]:shrink-0">
{item.icon}
{item.label}
</span>
)}
{!last && sep}
</li>
)
})}
</ol>
</nav>
)
}
+116 -30
View File
@@ -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<typeof Button>
@@ -35,46 +48,119 @@ type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Variants: Story = {
render: () => (
<div className="flex flex-wrap gap-3">
<Button>Primary</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="outline">Outline</Button>
<Button variant="ghost">Ghost</Button>
<Button variant="danger">Danger</Button>
render: (args) => (
<div className="flex flex-wrap items-center gap-3">
{BUTTON_VARIANTS.map((variant) => (
<Button key={variant} {...args} variant={variant}>
{variant[0].toUpperCase() + variant.slice(1)}
</Button>
))}
</div>
),
}
export const Colors: Story = {
parameters: { docs: { description: { story: 'Every colour in every variant.' } } },
render: (args) => (
<div className="grid gap-3">
{BUTTON_VARIANTS.map((variant) => (
<div key={variant} className="flex flex-wrap items-center gap-3">
{COLORS.map((color) => (
<Button key={color} {...args} variant={variant} color={color}>
{color[0].toUpperCase() + color.slice(1)}
</Button>
))}
</div>
))}
</div>
),
}
export const Sizes: Story = {
render: () => (
render: (args) => (
<div className="flex flex-wrap items-center gap-3">
<Button size="sm">Small</Button>
<Button size="md">Medium</Button>
<Button size="lg">Large</Button>
{SIZES.map((size) => (
<Button key={size} {...args} size={size}>
Size {size}
</Button>
))}
</div>
),
}
export const WithIcons: Story = {
render: (args) => (
<div className="flex flex-wrap items-center gap-3">
<Button {...args} startIcon={<Plus aria-hidden="true" />}>
New employee
</Button>
<Button {...args} variant="outline" endIcon={<ArrowRight aria-hidden="true" />}>
Continue
</Button>
<Button {...args} variant="soft" color="neutral" startIcon={<Download aria-hidden="true" />}>
Export CSV
</Button>
</div>
),
}
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: <Trash2 aria-hidden="true" /> },
}
export const FullWidth: Story = {
args: { fullWidth: true },
render: (args) => (
<div className="max-w-sm">
<Button {...args} />
</div>
),
}
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: () => (
<div className="flex flex-wrap gap-3">
<div className="flex flex-wrap items-center gap-3">
<LinkButton href="#">Browse components</LinkButton>
<LinkButton href="#" variant="outline">Read the guide</LinkButton>
<LinkButton href="#" variant="outline" endIcon={<ArrowRight aria-hidden="true" />}>
Read the guide
</LinkButton>
<LinkButton href="#" variant="link">
Link style
</LinkButton>
<LinkButton href="#" disabled>
Disabled link
</LinkButton>
</div>
),
}
export const IconOnly: Story = {
parameters: {
docs: { description: { story: '`IconButton` is square and requires an `aria-label`.' } },
},
render: () => (
<div className="flex flex-wrap items-center gap-3">
{SIZES.map((size) => (
<IconButton key={size} size={size} aria-label="Add employee" icon={<Plus />} />
))}
<IconButton variant="solid" color="primary" aria-label="Add employee" icon={<Plus />} />
<IconButton variant="outline" color="danger" aria-label="Delete" icon={<Trash2 />} />
<IconButton variant="soft" color="neutral" aria-label="Download" icon={<Download />} loading />
</div>
),
}
+80
View File
@@ -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(<Button onClick={onClick}>Save</Button>)
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(<Button>Save</Button>)
expect(screen.getByRole('button')).toHaveAttribute('type', 'button')
})
it('is disabled and busy while loading', async () => {
const onClick = vi.fn()
render(
<Button loading loadingText="Saving…" onClick={onClick}>
Save
</Button>,
)
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(<Button onClick={onClick}>Save</Button>)
await userEvent.tab()
expect(screen.getByRole('button')).toHaveFocus()
await userEvent.keyboard('{Enter}')
expect(onClick).toHaveBeenCalledOnce()
})
it('merges className so consumer classes win', () => {
render(<Button className="h-20">Save</Button>)
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(
<div>
<Button>Save</Button>
<IconButton aria-label="Delete" icon={<svg />} />
<LinkButton href="/docs">Docs</LinkButton>
</div>,
)
await expectNoA11yViolations(container)
})
})
describe('LinkButton', () => {
it('renders a link', () => {
render(<LinkButton href="/docs">Docs</LinkButton>)
expect(screen.getByRole('link', { name: 'Docs' })).toHaveAttribute('href', '/docs')
})
it('is inert when disabled', async () => {
const onClick = vi.fn()
render(
<LinkButton href="/docs" disabled onClick={onClick}>
Docs
</LinkButton>,
)
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()
})
})
+138 -42
View File
@@ -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<HTMLButtonElement> & ButtonStyleProps
export type ButtonProps = Omit<ComponentProps<'button'>, '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<HTMLAnchorElement> & ButtonStyleProps & {
href: string
export type LinkButtonProps = Omit<ComponentProps<'a'>, 'color'> &
ButtonStyleProps & {
href: string
/** Renders the link inert and announces it as disabled. */
disabled?: boolean
}
export type IconButtonProps = Omit<ComponentProps<'button'>, 'color' | 'children'> &
Pick<ButtonStyleProps, 'variant' | 'color' | 'size'> & {
/** 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<ButtonVariant, string> = {
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<ButtonSize, string> = {
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 (
<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" className="animate-spin motion-reduce:animate-none">
<circle cx="12" cy="12" r="9" stroke="currentColor" strokeOpacity=".25" strokeWidth="3" />
<path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
</svg>
)
}
/** 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 (
<button type={type} className={buttonClasses(variant, size, className)} {...props}>
{icon}
{children}
<button
type={type}
disabled={disabled || loading}
aria-busy={loading || undefined}
className={cn(styles(variant, color, size, fullWidth), className)}
{...props}
>
{loading ? <Spinner /> : startIcon}
{loading && loadingText != null ? loadingText : children}
{!loading && endIcon}
</button>
)
}
/** 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<HTMLAnchorElement>) {
if (disabled) {
event.preventDefault()
return
}
onClick?.(event)
}
return (
<a className={buttonClasses(variant, size, className)} {...props}>
<a
href={disabled ? undefined : href}
aria-disabled={disabled || undefined}
role={disabled ? 'link' : undefined}
tabIndex={disabled ? -1 : undefined}
onClick={handleClick}
className={cn(styles(variant, color, size, fullWidth), className)}
{...props}
>
{startIcon}
{children}
{icon}
{endIcon}
</a>
)
}
/** 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 (
<button
type={type}
disabled={disabled || loading}
aria-busy={loading || undefined}
className={cn(base, focusRing, BUTTON_STYLES[variant][color], ICON_BUTTON_SIZES[size], className)}
{...props}
>
{loading ? <Spinner /> : icon}
</button>
)
}
+235 -55
View File
@@ -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={<button />}`) 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<typeof Card>
export default meta
type Story = StoryObj<typeof meta>
const title = (s: string) => s[0].toUpperCase() + s.slice(1)
export const Playground: Story = {
render: (args) => (
<Card {...args} className="max-w-sm">
<Card.Header>
<Card.Title>Payroll run</Card.Title>
<Card.Title>Quarterly review</Card.Title>
<Card.Description>Acme Corporation · Due 14 October</Card.Description>
</Card.Header>
<Card.Body>March 2026 · 148 employees · ₹42,10,550 net</Card.Body>
<Card.Footer>Processed 2 hours ago</Card.Footer>
<Card.Body>
Collect the self-assessments from your team and schedule a 30-minute conversation with each person before the
end of the month.
</Card.Body>
<Card.Footer>
<Button size="sm" onClick={fn()}>
Start review
</Button>
<Button size="sm" variant="ghost" color="neutral" onClick={fn()}>
Later
</Button>
</Card.Footer>
</Card>
),
}
export const Themes: Story = {
render: () => (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
{(['primary', 'secondary', 'success', 'danger'] as const).map((theme) => (
<Card key={theme} theme={theme}>
export const Variants: Story = {
render: (args) => (
<div className="grid max-w-4xl gap-5 sm:grid-cols-3">
{CARD_VARIANTS.map((variant) => (
<Card key={variant} {...args} variant={variant}>
<Card.Header>
<Card.Title className="text-base capitalize">{theme}</Card.Title>
<Card.Title>{title(variant)}</Card.Title>
<Card.Description>
{variant === 'outline'
? 'A bordered surface for most content.'
: variant === 'elevated'
? 'A soft shadow lifts it off the page.'
: 'A quiet fill for secondary content.'}
</Card.Description>
</Card.Header>
<Card.Body className="text-sm">Surface tinted for the {theme} state.</Card.Body>
<Card.Body>Cards group related content and actions about a single subject.</Card.Body>
</Card>
))}
</div>
),
}
export const Shadows: Story = {
render: () => (
<div className="flex flex-wrap items-start gap-6">
{(['none', 'sm', 'md', 'lg', 'xl'] as const).map((shadow) => (
<div key={shadow} className="flex flex-col items-center gap-2">
<Card shadow={shadow} className="w-40 p-6 text-center text-sm">
{shadow}
</Card>
<code className="text-[10px] text-gray-500">{shadow}</code>
</div>
export const Padding: Story = {
render: (args) => (
<div className="grid max-w-5xl items-start gap-5 sm:grid-cols-4">
{CARD_PADDINGS.map((padding) => (
<Card key={padding} {...args} padding={padding}>
<Card.Header>
<Card.Title>padding=&quot;{padding}&quot;</Card.Title>
</Card.Header>
<Card.Body>Spacing shared by every section.</Card.Body>
</Card>
))}
</div>
),
}
export const Rounded: Story = {
render: () => (
<div className="flex flex-wrap items-start gap-6">
{(['none', 'sm', 'md', 'lg', 'xl', 'full'] as const).map((rounded) => (
<div key={rounded} className="flex flex-col items-center gap-2">
<Card rounded={rounded} className="w-32 p-6 text-center text-sm">
{rounded}
</Card>
<code className="text-[10px] text-gray-500">{rounded}</code>
export const ProfileCard: Story = {
render: (args) => (
<Card {...args} className="max-w-sm">
<Card.Header
action={<IconButton size="sm" aria-label="More actions for Jane Doe" icon={<MoreHorizontal />} onClick={fn()} />}
>
<div className="flex items-center gap-3">
<Avatar name="Jane Doe" src={PORTRAITS.jane} size="lg" status="online" />
<div className="min-w-0">
<Card.Title>Jane Doe</Card.Title>
<Card.Description>Senior Product Engineer</Card.Description>
</div>
</div>
))}
</div>
),
}
/** `horizontal` splits into a 2-column grid; `fullRow` makes a child span both. */
export const HorizontalLayout: Story = {
render: () => (
<Card layout="horizontal" className="max-w-lg">
<Card.Header>
<Card.Title>Employee breakdown</Card.Title>
</Card.Header>
<Card.Body>
<div className="grid gap-1 text-sm">
<span>Full-time · 132</span>
<span>Part-time · 11</span>
<span>Contract · 5</span>
<Card.Body className="grid gap-3">
<div className="flex flex-wrap gap-1.5">
<Badge color="primary">Engineering</Badge>
<Badge color="neutral">Full-time</Badge>
<Badge color="success" dot>
Available
</Badge>
</div>
<p className="flex items-center gap-1.5 text-sm text-fg-muted">
<MapPin aria-hidden="true" className="size-4" /> Lisbon, Portugal · jane.doe@example.com
</p>
</Card.Body>
<Card.Footer className="text-xs text-gray-500">As of 31 Mar 2026</Card.Footer>
<Card.Footer divider>
<Button size="sm" variant="outline" color="neutral" className="flex-1" onClick={fn()}>
Message
</Button>
<Button size="sm" className="flex-1" onClick={fn()}>
View profile
</Button>
</Card.Footer>
</Card>
),
}
export const StatCards: Story = {
parameters: { docs: { description: { story: 'Compact stat cards in a dashboard row.' } } },
render: (args) => (
<div className="grid max-w-4xl gap-4 sm:grid-cols-3">
{[
{ 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) => (
<Card key={s.label} {...args} variant="elevated" padding="sm">
<Card.Header
action={
<span className="flex size-8 items-center justify-center rounded-lg bg-surface-sunken text-fg-muted">
<s.icon aria-hidden="true" className="size-4" />
</span>
}
>
<Card.Description className="font-medium">{s.label}</Card.Description>
<p className="text-2xl font-semibold tracking-tight text-fg tabular-nums">{s.value}</p>
</Card.Header>
<Card.Body className="flex items-center gap-2 text-xs">
<Badge size="sm" color={s.color}>
{s.delta}
</Badge>
<span>{s.note}</span>
</Card.Body>
</Card>
))}
</div>
),
}
export const HorizontalMedia: Story = {
args: { layout: 'horizontal' },
render: (args) => (
<Card {...args} className="max-w-2xl">
<Card.Media>
<img src={landscape('#bfd2fd', '#305ddd')} alt="Illustration of blue hills under a pale sky" />
</Card.Media>
<Card.Header>
<Badge size="sm" color="primary" className="self-start">
Offsite
</Badge>
<Card.Title>Team offsite in the Sintra hills</Card.Title>
<Card.Description>12–14 November · 24 attending</Card.Description>
</Card.Header>
<Card.Body>
Three days of planning, workshops and long walks. Travel and accommodation are booked; bring layers, the
evenings get cold.
</Card.Body>
<Card.Footer className="justify-between">
<AvatarGroup size="sm" max={3} aria-label="Attendees">
<Avatar name="Jane Doe" src={PORTRAITS.jane} />
<Avatar name="John Smith" src={PORTRAITS.john} />
<Avatar name="Maya Chen" src={PORTRAITS.maya} />
<Avatar name="Carlos Mendez" />
<Avatar name="Aiko Tanaka" />
</AvatarGroup>
<Button size="sm" variant="soft" endIcon={<ArrowRight aria-hidden="true" />} onClick={fn()}>
Details
</Button>
</Card.Footer>
</Card>
),
}
export const VerticalMedia: Story = {
render: (args) => (
<div className="grid max-w-3xl gap-5 sm:grid-cols-2">
{[
{ 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) => (
<Card key={p.t} {...args}>
<Card.Media className="aspect-[16/9]">
<img src={landscape(p.sky, p.hills)} alt="" />
</Card.Media>
<Card.Header>
<Card.Title>{p.t}</Card.Title>
<Card.Description>{p.d}</Card.Description>
</Card.Header>
<Card.Footer>
<Badge size="sm" variant="outline">
{p.tag}
</Badge>
<span className="text-xs text-fg-muted">6 min read</span>
</Card.Footer>
</Card>
))}
</div>
),
}
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={<button type="button" />}` makes a button card.',
},
},
},
render: (args) => (
<div className="grid max-w-3xl gap-4 sm:grid-cols-3">
<Card {...args} href="#getting-started">
<Card.Header>
<span className="mb-2 flex size-9 items-center justify-center rounded-lg bg-primary-50 text-primary-700 dark:bg-primary-500/15 dark:text-primary-300">
<BookOpen aria-hidden="true" className="size-5" />
</span>
<Card.Title>Getting started</Card.Title>
<Card.Description>Install the kit and render your first component.</Card.Description>
</Card.Header>
</Card>
<Card {...args} variant="elevated" href="#theming">
<Card.Header>
<span className="mb-2 flex size-9 items-center justify-center rounded-lg bg-info-50 text-info-700 dark:bg-info-500/15 dark:text-info-300">
<TrendingUp aria-hidden="true" className="size-5" />
</span>
<Card.Title>Theming</Card.Title>
<Card.Description>Swap palettes and switch to dark mode.</Card.Description>
</Card.Header>
</Card>
<Card {...args} variant="filled" render={<button type="button" onClick={fn()} />}>
<Card.Header>
<span className="mb-2 flex size-9 items-center justify-center rounded-lg bg-success-50 text-success-700 dark:bg-success-500/15 dark:text-success-300">
<Users aria-hidden="true" className="size-5" />
</span>
<Card.Title>Invite your team</Card.Title>
<Card.Description>A button card that opens a dialog.</Card.Description>
</Card.Header>
</Card>
</div>
),
}
+82
View File
@@ -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<typeof Card>[0]) {
return (
<Card {...props}>
<Card.Header>
<Card.Title>Quarterly review</Card.Title>
<Card.Description>Due 14 October</Card.Description>
</Card.Header>
<Card.Body>Collect the self-assessments.</Card.Body>
<Card.Footer>Footer</Card.Footer>
</Card>
)
}
describe('Card', () => {
it('renders the title as an h3 by default', () => {
render(<Sample />)
expect(screen.getByRole('heading', { level: 3, name: 'Quarterly review' })).toBeInTheDocument()
})
it('uses headingLevel for the title', () => {
render(<Sample headingLevel={2} />)
expect(screen.getByRole('heading', { level: 2, name: 'Quarterly review' })).toBeInTheDocument()
})
it('renders an interactive link with href', async () => {
render(<Sample href="/reviews/q3" />)
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(
<Card render={<button type="button" onClick={onClick} />}>
<Card.Body>Invite your team</Card.Body>
</Card>,
)
await userEvent.click(screen.getByRole('button', { name: 'Invite your team' }))
expect(onClick).toHaveBeenCalledOnce()
})
it('is not interactive by default', () => {
const { container } = render(<Sample />)
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(
<Card layout="horizontal">
<Card.Header>
<Card.Title>Offsite</Card.Title>
</Card.Header>
<Card.Media>
<img src="data:," alt="Hills" />
</Card.Media>
</Card>,
)
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(
<div>
<Sample />
<Sample href="/x" variant="elevated" />
</div>,
)
await expectNoA11yViolations(container)
})
})
+141 -152
View File
@@ -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={<button type="button" />}`. */
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}
<div className="flex min-w-0 flex-1 flex-col">{rest}</div>
</>
)
}
return 'col-span-1'
const element = useRender({
defaultTagName: 'div',
render: render ?? (href != null ? <a href={href} /> : 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 <CardContext value={{ padding, layout, headingLevel }}>{element}</CardContext>
}
export type CardProps = HTMLAttributes<HTMLDivElement> & {
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<CardProps & RefAttributes<HTMLDivElement>> & {
Header: typeof CardHeader
Title: typeof CardTitle
Body: typeof CardBody
Content: typeof CardBody
Footer: typeof CardFooter
}
const CardBase = forwardRef<HTMLDivElement, CardProps>(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 (
<div
ref={ref}
className={cn('flex items-start gap-3', CARD_SECTION_PADDING[padding], className)}
{...props}
>
<div className="flex min-w-0 flex-1 flex-col gap-1">{children}</div>
{action && <div className="-my-0.5 flex shrink-0 items-center gap-2">{action}</div>}
</div>
)
}
export type CardTitleProps = ComponentProps<'h3'>
function CardTitle({ className, ...props }: CardTitleProps) {
const { headingLevel } = use(CardContext)
const Heading = `h${headingLevel}` as 'h3'
return <Heading className={cn('text-base font-semibold leading-6 tracking-tight text-fg', className)} {...props} />
}
function CardDescription({ className, ...props }: ComponentProps<'p'>) {
return <p className={cn('text-sm leading-5 text-fg-muted', className)} {...props} />
}
function CardBody({ className, ...props }: ComponentProps<'div'>) {
const { padding } = use(CardContext)
return <div className={cn('flex-1 text-sm leading-6 text-fg-muted', CARD_SECTION_PADDING[padding], className)} {...props} />
}
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 (
<div
data-card-divider={divider || undefined}
className={cn(
'grid overflow-hidden relative',
gridCols,
SHADOW_SIZES[shadow] ?? SHADOW_SIZES.md,
ROUNDED_SIZES[rounded] ?? ROUNDED_SIZES.lg,
themeData.card,
'mt-auto flex items-center gap-2',
CARD_FOOTER_PADDING[padding],
divider && CARD_FOOTER_DIVIDER[padding],
className,
)}
{...props}
>
{/* 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<Record<string, unknown>>, {
theme: childProps.theme ?? theme,
layout: childProps.layout ?? layout,
})
})}
</div>
/>
)
})
}
export function CardHeader({
children,
className = '',
theme = 'primary',
layout = 'vertical',
fullRow = false,
fullCol = false,
...props
}: HTMLAttributes<HTMLDivElement> & 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 `<img>` inside; it's cropped to fill. */
function CardMedia({ className, ...props }: CardMediaProps) {
const { layout } = use(CardContext)
return (
<div
className={cn(themeData.header, spanClasses({ layout, fullRow, fullCol }), className)}
className={cn(
'relative shrink-0 overflow-hidden bg-surface-sunken [&>img]:size-full [&>img]:object-cover',
layout === 'horizontal' && 'aspect-video sm:aspect-auto sm:w-2/5',
className,
)}
{...props}
>
{children}
</div>
/>
)
}
export function CardTitle({ children, className = '', ...props }: HTMLAttributes<HTMLHeadingElement>) {
return (
<h3 className={cn('text-lg font-bold leading-none tracking-tight', className)} {...props}>
{children}
</h3>
)
}
export function CardBody({
children,
className = '',
theme = 'primary',
layout = 'vertical',
fullRow = false,
fullCol = false,
...props
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
return (
<div
className={cn(themeData.body, spanClasses({ layout, fullRow, fullCol }), className)}
{...props}
>
{children}
</div>
)
}
export const CardContent = CardBody
export function CardFooter({
children,
className = '',
theme = 'primary',
layout = 'vertical',
fullRow = false,
fullCol = false,
...props
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
return (
<div
className={cn(themeData.footer, spanClasses({ layout, fullRow, fullCol }), className)}
{...props}
>
{children}
</div>
)
}
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,
})
+143 -68
View File
@@ -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 [email protected] 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<typeof Checkbox>
export default meta
type Story = StoryObj<typeof meta>
/** 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<typeof Checkbox> & { initial?: boolean }) {
const [checked, setChecked] = useState(initial)
return <Checkbox {...args} checked={checked} onChange={(e) => setChecked(e.target.checked)} />
export const Playground: Story = {}
export const Unchecked: Story = {
args: { description: undefined },
}
export const Playground: Story = {
render: (args) => <ControlledCheckbox {...args} />,
export const Checked: Story = {
args: { defaultChecked: true },
}
export const Uncontrolled: Story = {
render: (args) => <Checkbox {...args} defaultChecked />,
export const Indeterminate: Story = {
args: { label: 'All departments', description: '3 of 7 departments selected.', indeterminate: true },
}
export const Disabled: Story = {
render: (args) => (
<div className="grid gap-4">
<Checkbox {...args} disabled label="Disabled, unchecked" description="Your admin has locked this setting." />
<Checkbox {...args} disabled defaultChecked label="Disabled, checked" description={undefined} />
<Checkbox {...args} disabled indeterminate label="Disabled, indeterminate" description={undefined} />
</div>
),
}
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) => (
<div className="flex flex-col gap-4">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledCheckbox key={size} {...args} size={size} label={`Size ${size}`} />
<div className="grid gap-5">
{SIZES.map((size) => (
<Checkbox key={size} {...args} size={size} defaultChecked label={`Size ${size}`} />
))}
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{(['primary', 'secondary', 'success', 'danger', 'warning', 'info'] as const).map((theme) => (
<ControlledCheckbox key={theme} theme={theme} label={theme} initial />
export const Colors: Story = {
render: (args) => (
<div className="grid max-w-2xl gap-4 sm:grid-cols-3">
{COLORS.map((color) => (
<div key={color} className="flex gap-6">
<Checkbox {...args} color={color} defaultChecked label={color} description={undefined} />
<Checkbox {...args} color={color} indeterminate label="Mixed" description={undefined} />
</div>
))}
</div>
),
}
export const WithTooltip: Story = {
args: { tooltip: 'Recipients can be configured per entity in Settings → Notifications.' },
render: (args) => <ControlledCheckbox {...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) => <ControlledCheckbox {...args} />,
}
/** Error accepts an object too, matching a form-library error shape. */
export const ErrorAsObject: Story = {
render: () => (
<Checkbox
label="Acknowledge policy"
error={{ message: 'This field is required' }}
/>
),
}
export const Disabled: Story = {
render: () => (
<div className="flex flex-col gap-3">
<Checkbox label="Unchecked and disabled" disabled />
<Checkbox label="Checked and disabled" defaultChecked disabled />
function ControlledCheckbox(args: Story['args']) {
const [checked, setChecked] = useState(false)
return (
<div className="grid gap-3">
<Checkbox
{...args}
label="Subscribe to the product newsletter"
description="One email a month. Unsubscribe any time."
checked={checked}
onCheckedChange={(next) => {
setChecked(next)
args?.onCheckedChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Subscribed: {checked ? 'yes' : 'no'}</p>
</div>
),
)
}
/** No label — a bare control for use inside a table row or toolbar. */
export const WithoutLabel: Story = {
render: () => <ControlledCheckbox label="" />
export const Controlled: Story = {
render: (args) => <ControlledCheckbox {...args} />,
}
function SignUpForm() {
const [terms, setTerms] = useState(false)
const [submitted, setSubmitted] = useState(false)
return (
<form
className="grid max-w-md gap-4 rounded-xl border border-border bg-surface p-5"
onSubmit={(event) => {
event.preventDefault()
setSubmitted(true)
}}
>
<div>
<p className="text-base font-semibold text-fg">Create your account</p>
<p className="text-sm text-fg-muted">Jane Doe · jane@example.com</p>
</div>
<Checkbox
name="terms"
label="I agree to the Terms of Service and Privacy Policy"
required
checked={terms}
onCheckedChange={setTerms}
error={submitted && !terms ? 'Accept the terms to continue.' : undefined}
/>
<Checkbox
name="updates"
label="Send me product updates"
description="Around two emails a month. You can opt out at any time."
defaultChecked
/>
<Checkbox name="remember" label="Keep me signed in on this device" />
<Button type="submit" className="justify-self-start">
Create account
</Button>
</form>
)
}
/** Consent checkboxes in a sign-up form. Submit without ticking the terms to see the error. */
export const SignUpConsent: Story = {
render: () => <SignUpForm />,
}
+89
View File
@@ -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(<Checkbox label="Remember me" />)
expect(screen.getByRole('checkbox', { name: 'Remember me' })).not.toBeChecked()
})
it('toggles when the label is clicked', async () => {
render(<Checkbox label="Remember me" />)
await userEvent.click(screen.getByText('Remember me'))
expect(screen.getByRole('checkbox')).toBeChecked()
})
it('toggles with Space', async () => {
const onCheckedChange = vi.fn()
render(<Checkbox label="Remember me" onCheckedChange={onCheckedChange} />)
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(<Checkbox label="Remember me" defaultChecked />)
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(<Checkbox label="Remember me" checked={false} onCheckedChange={onCheckedChange} />)
await userEvent.click(screen.getByRole('checkbox'))
expect(onCheckedChange).toHaveBeenCalledWith(true)
expect(screen.getByRole('checkbox')).not.toBeChecked()
})
it('shows the indeterminate state', () => {
render(<Checkbox label="All departments" indeterminate />)
expect(screen.getByRole('checkbox')).toHaveAttribute('aria-checked', 'mixed')
})
it('announces the description', () => {
render(<Checkbox label="Updates" description="Two emails a month." />)
expect(screen.getByRole('checkbox')).toHaveAccessibleDescription('Two emails a month.')
})
it('marks itself invalid and announces the error instead of the description', () => {
render(<Checkbox label="Terms" description="Hidden while invalid" error="Accept the terms." required />)
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(
<>
<Checkbox label="Disabled" disabled onCheckedChange={onCheckedChange} />
<Checkbox label="Read only" readOnly onCheckedChange={onCheckedChange} />
</>,
)
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(
<>
<Checkbox label="Remember me" description="For 30 days." defaultChecked />
<Checkbox label="Terms" error="Required" required />
<Checkbox label="Mixed" indeterminate />
</>,
)
await expectNoA11yViolations(container)
})
})
+139 -93
View File
@@ -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<BaseCheckbox.Root.Props, 'className' | 'onCheckedChange' | 'render' | 'nativeButton' | 'style'>
// `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<InputHTMLAttributes<HTMLInputElement>, '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<HTMLInputElement, CheckboxProps>(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 (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round" strokeLinejoin="round">
<path d="m3.5 8.5 3 3 6-7" />
</svg>
)
}
function DashIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.25" strokeLinecap="round">
<path d="M4 8h8" />
</svg>
)
}
/**
* The bare checkbox box, with no label or field wiring. Use it inside your own
* `<label>` 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 (
<BaseCheckbox.Root
onCheckedChange={onCheckedChange ? (checked) => 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}
>
<BaseCheckbox.Indicator
className="flex data-unchecked:hidden"
render={(indicatorProps, state) => (
<span {...indicatorProps}>{state.indeterminate ? <DashIcon /> : <CheckIcon />}</span>
)}
/>
</BaseCheckbox.Root>
)
}
/**
* 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 (
<div className={cn('flex flex-col items-start space-y-1', className)}>
<label
htmlFor={name ? `checkbox-${name}` : undefined}
className={cn(
'inline-flex items-center space-x-2',
disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer',
)}
>
<input
id={name ? `checkbox-${name}` : undefined}
name={name}
type="checkbox"
disabled={disabled}
className={cn(
'peer rounded border-gray-300',
'focus:ring-0 focus:ring-offset-0',
themeClass,
sizeClass,
)}
checked={checked}
onChange={onChange}
ref={ref}
<BaseField.Root name={name} disabled={disabled} invalid={invalid} className={cn('flex', className)}>
<div className={cn('flex items-start', CHECKBOX_GAP[size])}>
<CheckboxControl
size={size}
required={required}
className={cn(CHECKBOX_BOX_OFFSET[size], controlClassName)}
{...props}
/>
{label && (
<div className="flex items-center gap-1.5 ml-2">
<span className="text-sm text-slate-600 select-none">{label}</span>
{(tooltip || helpText) && (
<span className="inline-flex" onClick={(e) => e.preventDefault()}>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
{(label != null || description != null || invalid) && (
<div className="flex min-w-0 flex-col gap-0.5">
{label != null && (
<FieldLabel
required={required}
className={cn(
CHECKBOX_LABEL_SIZES[size],
'cursor-pointer select-none data-disabled:cursor-not-allowed',
)}
>
{label}
</FieldLabel>
)}
{description != null && !invalid && (
<BaseField.Description className={descriptionText}>{description}</BaseField.Description>
)}
{invalid && (
<BaseField.Error match className={errorText}>
{error}
</BaseField.Error>
)}
</div>
)}
</label>
{errorMessage && (
<p className="text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
</div>
</BaseField.Root>
)
})
export default Checkbox
}
+203
View File
@@ -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 [email protected].' },
{ 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<typeof CheckboxGroup>
export default meta
type Story = StoryObj<typeof meta>
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) => (
<div className="grid gap-8 sm:grid-cols-3">
{SIZES.map((size) => (
<CheckboxGroup
key={size}
{...args}
size={size}
label={`Size ${size}`}
description={undefined}
options={channels.slice(0, 3).map(({ value, label }) => ({ value, label }))}
defaultValue={['email', 'sms']}
/>
))}
</div>
),
}
export const Colors: Story = {
render: (args) => (
<div className="grid gap-8 sm:grid-cols-3">
{COLORS.map((color) => (
<CheckboxGroup
key={color}
{...args}
color={color}
label={color}
description={undefined}
selectAll
options={channels.slice(0, 3).map(({ value, label }) => ({ value, label }))}
defaultValue={['email']}
/>
))}
</div>
),
}
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<string[]>(['email'])
return (
<div className="grid gap-3">
<CheckboxGroup
{...args}
options={channels}
selectAll
value={value}
onValueChange={(next) => {
setValue(next)
args?.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Value: {value.length ? value.join(', ') : '(none)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledGroup {...args} />,
}
/** A permissions editor, grouped by area, with a select-all per area. */
export const RolePermissions: Story = {
render: () => (
<div className="grid max-w-2xl gap-6 rounded-xl border border-border bg-surface p-5 sm:grid-cols-2">
<div className="sm:col-span-2">
<p className="text-base font-semibold text-fg">Role: Billing manager</p>
<p className="text-sm text-fg-muted">Acme Corporation · 4 members</p>
</div>
<CheckboxGroup
label="Invoices"
selectAll="All invoice permissions"
options={[
{ value: 'invoices.view', label: 'View invoices' },
{ value: 'invoices.create', label: 'Create and send' },
{ value: 'invoices.refund', label: 'Issue refunds' },
]}
defaultValue={['invoices.view', 'invoices.create']}
/>
<CheckboxGroup
label="Payment methods"
selectAll="All payment permissions"
options={[
{ value: 'cards.view', label: 'View saved cards' },
{ value: 'cards.add', label: 'Add a card' },
{ value: 'cards.remove', label: 'Remove a card', disabled: true },
]}
defaultValue={['cards.view']}
/>
</div>
),
}
+84
View File
@@ -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(<CheckboxGroup label="Channels" options={options} />)
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(<CheckboxGroup label="Channels" options={options} defaultValue={['email']} onValueChange={onValueChange} />)
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(<CheckboxGroup label="Channels" options={options} value={['sms']} onValueChange={onValueChange} />)
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(<CheckboxGroup label="Channels" options={options} />)
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(
<CheckboxGroup
label="Channels"
selectAll
options={[...options, { value: 'fax', label: 'Fax', disabled: true }]}
defaultValue={['email']}
onValueChange={onValueChange}
/>,
)
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(<CheckboxGroup label="Channels" options={options} error="Choose at least one." required />)
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(<CheckboxGroup label="Channels" options={options} disabled />)
for (const box of screen.getAllByRole('checkbox')) expect(box).toHaveAttribute('aria-disabled', 'true')
})
it('has no axe violations', async () => {
const { container } = render(
<CheckboxGroup label="Channels" description="Where we reach you." options={options} selectAll defaultValue={['sms']} required />,
)
await expectNoA11yViolations(container)
})
})
+186
View File
@@ -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<CheckboxGroupOption, 'value'> & {
value?: string
size: CheckboxSize
color: CheckboxColor
parent?: boolean
}) {
return (
<BaseField.Item disabled={disabled} className={cn('flex items-start', CHECKBOX_GAP[size])}>
<CheckboxControl
value={value}
parent={parent}
size={size}
color={color}
className={CHECKBOX_BOX_OFFSET[size]}
/>
<div className="flex min-w-0 flex-col gap-0.5">
<BaseField.Label
className={cn(
CHECKBOX_LABEL_SIZES[size],
'cursor-pointer select-none text-fg data-disabled:cursor-not-allowed data-disabled:opacity-55',
parent && 'font-medium',
)}
>
{label}
</BaseField.Label>
{description != null && (
<BaseField.Description className={descriptionText}>
{description}
</BaseField.Description>
)}
</div>
</BaseField.Item>
)
}
/**
* 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 (
<BaseField.Root name={name} disabled={disabled} invalid={invalid} className={className}>
<Fieldset.Root
render={
<BaseCheckboxGroup
value={value}
onValueChange={(next) => setValue(next)}
allValues={hasSelectAll ? allValues : undefined}
disabled={disabled}
/>
}
className="flex flex-col gap-3"
>
{(label != null || description != null || invalid) && (
<div className="flex flex-col gap-0.5">
{label != null && (
<Fieldset.Legend className={cn(labelText, 'data-disabled:opacity-55')}>
{label}
{required && (
<span aria-hidden="true" className={requiredMark}>
*
</span>
)}
</Fieldset.Legend>
)}
{description != null && !invalid && (
<BaseField.Description className={descriptionText}>{description}</BaseField.Description>
)}
</div>
)}
{hasSelectAll && (
<div className="-mb-0.5">
<Option label={selectAll === true ? 'Select all' : selectAll} size={size} color={color} parent />
</div>
)}
<div
className={cn(
orientation === 'horizontal' ? 'flex flex-wrap gap-x-6 gap-y-3' : 'flex flex-col gap-3',
hasSelectAll && orientation === 'vertical' && CHECKBOX_INDENT[size],
)}
>
{options.map((option) => (
<Option key={option.value} {...option} size={size} color={color} />
))}
</div>
{invalid && (
<BaseField.Error match className={errorText}>
{error}
</BaseField.Error>
)}
</Fieldset.Root>
</BaseField.Root>
)
}
+310
View File
@@ -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 }) => (
<div
className={
parameters.wide
? 'max-w-3xl rounded-xl border border-border bg-surface p-6'
: 'max-w-sm rounded-xl border border-border bg-surface p-6'
}
>
<Story />
</div>
),
],
} satisfies Meta<typeof Combobox>
export default meta
type Story = StoryObj<typeof meta>
const tall = (Story: () => React.JSX.Element) => (
<div className="min-h-[26rem]">
<Story />
</div>
)
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) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<Combobox key={size} {...args} size={size} label={`Size ${size}`} defaultValue="ca" clearable />
))}
</div>
),
}
export const Variants: Story = {
render: (args) => (
<div className="grid gap-5">
{SELECT_VARIANTS.map((variant) => (
<Combobox key={variant} {...args} variant={variant} label={variant === 'outline' ? 'Outline' : 'Filled'} />
))}
</div>
),
}
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: <Search />, 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) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<Combobox
key={size}
{...withoutValue(args)}
size={size}
label={`Size ${size}`}
multiple
options={DEPARTMENTS}
defaultValue={['eng', 'fin']}
clearable
/>
))}
</div>
),
}
export const CustomOptionRendering: Story = {
args: {
label: 'Employee',
placeholder: 'Search people',
options: EMPLOYEES,
startIcon: <UserRound />,
defaultOpen: true,
renderOption: (option) => (
<span className="flex items-center gap-2.5">
<span
aria-hidden="true"
className="flex size-7 shrink-0 items-center justify-center rounded-full bg-primary-50 text-xs font-semibold text-primary-700 dark:bg-primary-500/15 dark:text-primary-300"
>
{option.label
.split(' ')
.map((part) => part[0])
.join('')}
</span>
<span className="flex min-w-0 flex-col">
<span className="truncate">{option.label}</span>
<span className="truncate text-xs font-normal text-fg-muted">{option.description}</span>
</span>
</span>
),
},
decorators: [tall],
}
function AsyncCombobox(args: Story['args']) {
const [query, setQuery] = useState('')
const [options, setOptions] = useState<SelectOption[]>(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 (
<Combobox
{...withoutValue(args)}
label="Employee"
placeholder="Search by name"
description="Results come from a simulated server search."
options={options}
loading={loading}
filterOptions={false}
emptyText="No employees found"
onInputValueChange={(value) => {
setQuery(value)
setLoading(true)
}}
/>
)
}
/** `onInputValueChange` drives a (simulated) server search; `loading` shows while it runs. */
export const AsyncSearch: Story = {
render: (args) => <AsyncCombobox {...args} />,
decorators: [tall],
}
function ControlledCombobox(args: Story['args']) {
const [value, setValue] = useState<string[]>(['eng', 'hr'])
return (
<div className="grid gap-2">
<Combobox
{...withoutValue(args)}
label="Departments"
placeholder="Add a department"
options={DEPARTMENTS}
multiple
value={value}
onValueChange={setValue}
/>
<p className="text-sm text-fg-muted">Value: {value.length ? value.join(', ') : '(none)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledCombobox {...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],
}
+161
View File
@@ -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(<Combobox label="Country" options={countries} />)
expect(screen.getByRole('combobox', { name: 'Country' })).toBeInTheDocument()
})
it('filters as you type and shows the empty state', async () => {
render(<Combobox label="Country" options={countries} emptyText="No countries found" />)
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(<Combobox label="Country" options={countries} onValueChange={onValueChange} />)
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(<Combobox label="Country" options={countries} />)
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(<Combobox label="Country" options={countries} defaultValue="de" />)
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<string | null>('ca')
return (
<>
<Combobox label="Country" options={countries} value={value} onValueChange={setValue} />
<p data-testid="value">{String(value)}</p>
</>
)
}
render(<Controlled />)
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(<Combobox label="Country" clearable options={countries} defaultValue="gb" onValueChange={onValueChange} />)
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(
<Combobox
label="Countries"
multiple
options={countries}
defaultValue={['ca', 'de']}
onValueChange={onValueChange}
/>,
)
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(
<Combobox label="Employee" options={[]} loading filterOptions={false} onInputValueChange={onInputValueChange} />,
)
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(<Combobox label="Country" description="Where you pay tax." options={countries} />)
expect(screen.getByRole('combobox')).toHaveAccessibleDescription('Where you pay tax.')
rerender(<Combobox label="Country" description="Where you pay tax." error="Choose a country." options={countries} />)
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(<Combobox label="Country" required disabled options={countries} />)
const input = screen.getByRole('combobox', { name: /Country/ })
expect(input).toBeDisabled()
})
it('has no axe violations, closed and open', async () => {
const { container } = render(
<Combobox label="Countries" multiple clearable description="Pick any." defaultValue={['ca']} options={countries} />,
)
await expectNoA11yViolations(container)
await userEvent.click(screen.getByRole('combobox', { name: 'Countries' }))
await screen.findByRole('listbox')
await expectNoA11yViolations(document.body)
})
})
+267
View File
@@ -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<Multiple extends boolean | undefined = false> = 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<Multiple>
/** The initial value (uncontrolled). */
defaultValue?: SelectValue<Multiple>
/** Fires with the new value. */
onValueChange?: (value: SelectValue<Multiple>) => 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<SelectSize, string> = { 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<Multiple extends boolean | undefined = false>({
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<Multiple>) {
const empty = (multiple ? [] : null) as SelectValue<Multiple>
const [value, setValue] = useControllableState<SelectValue<Multiple>>(
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<Record<string, string>>({})
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<Multiple>)
}
const input = (
<BaseCombobox.Input
placeholder={multiple && selectedValues.length > 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 (
<Field
label={label}
description={description}
error={error}
required={required}
disabled={disabled}
name={name}
className={className}
>
<BaseCombobox.Root
items={comboboxItems(options, grouped)}
multiple={multiple}
value={(multiple ? selectedOptions : (selectedOptions[0] ?? null)) as never}
onValueChange={(next) => 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}
>
<BaseCombobox.InputGroup
className={cn(
'flex w-full cursor-text items-center',
multiple ? CHIPS_MIN_HEIGHT[size] : controlHeight[size],
iconSize[size],
FIELD_BOX[variant],
focusWithinRing,
'data-disabled:cursor-not-allowed data-disabled:opacity-55',
)}
>
{startIcon != null && (
<span aria-hidden="true" className={cn('flex shrink-0 text-fg-muted', size === 'lg' ? 'pl-4' : 'pl-3')}>
{startIcon}
</span>
)}
{multiple ? (
<BaseCombobox.Chips className="flex min-w-0 flex-1 flex-wrap items-center gap-1 py-1 pl-1.5">
{selectedOptions.map((option) => (
<BaseCombobox.Chip
key={option.value}
aria-label={option.label}
className={cn(
'inline-flex max-w-full cursor-default items-center gap-0.5 rounded-md bg-primary-50 pr-0.5 pl-2 font-medium text-primary-700 outline-none',
'dark:bg-primary-500/15 dark:text-primary-300',
'focus-within:ring-2 focus-within:ring-primary-500 data-highlighted:ring-2 data-highlighted:ring-primary-500',
CHIP_SIZE[size],
)}
>
<span className="truncate">{option.label}</span>
<BaseCombobox.ChipRemove
aria-label={`Remove ${option.label}`}
className="flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-primary-100 dark:hover:bg-primary-500/25 [&_svg]:size-3"
>
<X aria-hidden="true" />
</BaseCombobox.ChipRemove>
</BaseCombobox.Chip>
))}
{input}
</BaseCombobox.Chips>
) : (
input
)}
<div className={cn('flex shrink-0 items-center gap-0.5 self-center', size === 'lg' ? 'pr-2' : 'pr-1.5')}>
{loading && (
<span className="flex size-6 items-center justify-center text-fg-muted">
<Spinner />
</span>
)}
{clearable && !readOnly && (
<BaseCombobox.Clear aria-label="Clear selection" className={iconButton}>
<X aria-hidden="true" />
</BaseCombobox.Clear>
)}
<BaseCombobox.Trigger aria-label="Show options" className={iconButton}>
<Chevron />
</BaseCombobox.Trigger>
</div>
</BaseCombobox.InputGroup>
<BaseCombobox.Portal>
<BaseCombobox.Positioner side={side} sideOffset={6} className="z-50 outline-none">
<BaseCombobox.Popup className={popupClass()}>
<BaseCombobox.Status>{loading && <StatusRow loading>{loadingText}</StatusRow>}</BaseCombobox.Status>
<BaseCombobox.Empty>{!loading && <StatusRow>{emptyText}</StatusRow>}</BaseCombobox.Empty>
<ComboboxOptions
grouped={grouped}
isSelected={(v) => selected.has(v)}
renderOption={renderOption}
/>
</BaseCombobox.Popup>
</BaseCombobox.Positioner>
</BaseCombobox.Portal>
</BaseCombobox.Root>
</Field>
)
}
+278
View File
@@ -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 = (
<>
<Dialog.Close render={<Button variant="outline" color="neutral" />}>Cancel</Dialog.Close>
<Button>Save changes</Button>
</>
)
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: <Button>Edit workspace</Button>,
footer,
onOpenChange: fn(),
},
} satisfies Meta<typeof Dialog>
export default meta
type Story = StoryObj<typeof meta>
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) => (
<div className="flex flex-wrap gap-3">
{DIALOG_SIZES_LIST.map((size) => (
<Dialog
key={size}
{...args}
size={size}
title={`Size ${size}`}
trigger={
<Button variant="outline" color="neutral">
Open {size}
</Button>
}
/>
))}
</div>
),
}
export const Small: Story = {
args: {
defaultOpen: true,
size: 'sm',
title: 'Rename file',
description: undefined,
children: <Input label="File name" defaultValue="Q3 report.pdf" />,
footer: (
<>
<Dialog.Close render={<Button variant="outline" color="neutral" />}>Cancel</Dialog.Close>
<Button>Rename</Button>
</>
),
},
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 [email protected].',
]
export const LongContent: Story = {
args: {
defaultOpen: true,
title: 'Terms of service',
description: 'Last updated 1 September 2026.',
children: (
<div className="flex flex-col gap-4">
{[...paragraphs, ...paragraphs].map((text, index) => (
<p key={index} className="m-0">
{text}
</p>
))}
</div>
),
footer: (
<>
<Dialog.Close render={<Button variant="outline" color="neutral" />}>Decline</Dialog.Close>
<Dialog.Close render={<Button />}>Accept</Dialog.Close>
</>
),
},
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: (
<form
id="invite-form"
className="flex flex-col gap-4"
onSubmit={(event) => event.preventDefault()}
>
<Input label="Full name" name="name" placeholder="Jane Doe" required />
<Input label="Work email" name="email" type="email" placeholder="[email protected]" startIcon={<Mail />} required />
<Input label="Team" name="team" defaultValue="Design" description="You can change this later." />
</form>
),
footer: (
<>
<Dialog.Close render={<Button variant="outline" color="neutral" />}>Cancel</Dialog.Close>
<Button type="submit" form="invite-form" startIcon={<UserPlus aria-hidden="true" />}>
Send invite
</Button>
</>
),
},
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: (
<>
<Dialog.Close render={<Button variant="outline" color="neutral" />}>Sign out</Dialog.Close>
<Dialog.Close render={<Button />}>Stay signed in</Dialog.Close>
</>
) },
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 (
<div className="flex items-center gap-3">
<Button onClick={() => setOpen(true)}>Open from state</Button>
<span className="text-sm text-fg-muted">open: {String(open)}</span>
<Dialog
{...args}
trigger={undefined}
open={open}
onOpenChange={(next) => {
setOpen(next)
args.onOpenChange?.(next)
}}
footer={
<>
<Button variant="outline" color="neutral" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button onClick={() => setOpen(false)}>Save changes</Button>
</>
}
/>
</div>
)
},
}
export const CustomLayout: Story = {
parameters: {
...ownFrame(),
docs: { ...ownFrame().docs, description: { story: 'Compound parts for a layout the props don’t cover.' } },
},
render: () => (
<Dialog.Root defaultOpen>
<Dialog.Trigger render={<Button>Upgrade plan</Button>} />
<Dialog.Content size="sm">
<div className="bg-primary-50 px-6 pb-5 pt-8 text-center dark:bg-primary-500/15">
<p className="m-0 text-sm font-semibold text-primary-700 dark:text-primary-300">Team plan</p>
<p className="m-0 mt-1 text-4xl font-semibold text-fg">
$12<span className="text-base font-medium text-fg-muted"> / member / month</span>
</p>
</div>
<Dialog.Header className="pt-5 pr-5 text-center sm:pt-5 sm:pr-6">
<Dialog.Title>Upgrade to Team</Dialog.Title>
<Dialog.Description>Unlimited projects, shared templates and priority support.</Dialog.Description>
</Dialog.Header>
<Dialog.Body>
<ul className="m-0 list-none space-y-2 p-0">
{['Unlimited projects', 'Shared templates', 'Audit log', 'Priority support'].map((feature) => (
<li key={feature} className="flex items-center gap-2">
<span aria-hidden="true" className="size-1.5 rounded-full bg-primary-500" />
{feature}
</li>
))}
</ul>
</Dialog.Body>
<Dialog.Footer>
<Dialog.Close render={<Button variant="ghost" color="neutral" />}>Not now</Dialog.Close>
<Button>Upgrade</Button>
</Dialog.Footer>
</Dialog.Content>
</Dialog.Root>
),
}
+94
View File
@@ -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<React.ComponentProps<typeof Dialog>>) {
return (
<Dialog
trigger={<Button>Edit profile</Button>}
title="Edit profile"
description="Changes are visible to your team."
footer={
<>
<Dialog.Close render={<Button variant="outline" color="neutral" />}>Cancel</Dialog.Close>
<Button>Save</Button>
</>
}
{...props}
>
<Input label="Full name" defaultValue="Jane Doe" />
</Dialog>
)
}
describe('Dialog', () => {
it('opens from the trigger as a named dialog', async () => {
render(<Example />)
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(<Example />)
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(<Example />)
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(<Example defaultOpen hideCloseButton />)
await screen.findByRole('dialog')
expect(screen.queryByRole('button', { name: 'Close' })).not.toBeInTheDocument()
})
it('works controlled', async () => {
const onOpenChange = vi.fn()
const { rerender } = render(<Example open={false} onOpenChange={onOpenChange} />)
await userEvent.click(screen.getByRole('button', { name: 'Edit profile' }))
expect(onOpenChange).toHaveBeenCalledWith(true)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
rerender(<Example open onOpenChange={onOpenChange} />)
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(
<Modal.Root defaultOpen>
<Modal.Content size="sm">
<Modal.Header>
<Modal.Title>Invite people</Modal.Title>
</Modal.Header>
<Modal.Body>Body text</Modal.Body>
</Modal.Content>
</Modal.Root>,
)
expect(await screen.findByRole('dialog', { name: 'Invite people' })).toHaveTextContent('Body text')
})
it('has no axe violations when open', async () => {
render(<Example defaultOpen />)
await screen.findByRole('dialog')
await expectNoA11yViolations(document.body)
})
})
+245
View File
@@ -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 (
<BaseDialog.Root
{...props}
modal={modal}
disablePointerDismissal={!closeOnOutsideClick}
onOpenChange={onOpenChange ? (open) => onOpenChange(open) : undefined}
>
{children}
</BaseDialog.Root>
)
}
/**
* Opens the dialog. Pass your button as `render` (`<Dialog.Trigger render={<Button>Edit</Button>} />`)
* so it keeps the Tansy styles.
*/
function DialogTrigger(props: BaseDialog.Trigger.Props) {
return <BaseDialog.Trigger {...props} />
}
export type DialogContentProps = Omit<BaseDialog.Popup.Props, 'className'> & {
/** 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 (
<BaseDialog.Portal>
<BaseDialog.Backdrop className={cn(backdropClass, 'z-50')} />
<BaseDialog.Viewport
className={cn(
'fixed inset-0 z-50 flex items-center justify-center',
size === 'full' ? 'p-0 sm:p-6' : 'p-4 sm:p-6',
)}
>
<BaseDialog.Popup className={cn(dialogPanelClass, DIALOG_SIZES[size], className)} {...props}>
{children}
{!hideCloseButton && (
<BaseDialog.Close
render={<IconButton aria-label="Close" size="sm" icon={<X aria-hidden="true" />} />}
className="absolute right-3 top-3 sm:right-4 sm:top-4"
/>
)}
</BaseDialog.Popup>
</BaseDialog.Viewport>
</BaseDialog.Portal>
)
}
/** Title and description block at the top. It stays put while the body scrolls. */
export function DialogHeader({ className, ...props }: ComponentProps<'div'>) {
return <div className={cn('flex shrink-0 flex-col gap-1 px-5 pt-5 pr-14 sm:px-6 sm:pt-6 sm:pr-16', className)} {...props} />
}
/** The dialog's accessible name. Renders an `<h2>`. */
function DialogTitle({ className, ...props }: Omit<BaseDialog.Title.Props, 'className'> & { className?: string }) {
return <BaseDialog.Title className={cn(dialogTitleClass, className)} {...props} />
}
/** Supporting text, announced with the title. */
function DialogDescription({
className,
...props
}: Omit<BaseDialog.Description.Props, 'className'> & { className?: string }) {
return <BaseDialog.Description className={cn(dialogDescriptionClass, className)} {...props} />
}
/**
* 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<HTMLDivElement | null>(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 (
<div
ref={setRefs}
tabIndex={scrollable ? 0 : undefined}
data-scrollable={scrollable || undefined}
className={cn(
'min-h-0 flex-1 overflow-y-auto overscroll-contain px-5 pb-5 pt-4 text-sm leading-6 text-fg first:pt-5 sm:px-6 sm:pb-6 sm:first:pt-6',
'data-scrollable:mt-4 data-scrollable:border-t data-scrollable:border-border data-scrollable:first:mt-0 data-scrollable:first:border-t-0',
focusRing,
'focus-visible:-outline-offset-2',
className,
)}
{...props}
/>
)
}
/** Actions at the bottom, right-aligned. Stacks full-width on phones, primary action on top. */
export function DialogFooter({ className, ...props }: ComponentProps<'div'>) {
return (
<div
className={cn(
'flex shrink-0 flex-col-reverse gap-2 border-t border-border bg-surface-muted px-5 py-4 sm:flex-row sm:items-center sm:justify-end sm:gap-3 sm:px-6',
className,
)}
{...props}
/>
)
}
/** Closes the dialog. Pass a Button as `render`. */
function DialogClose(props: BaseDialog.Close.Props) {
return <BaseDialog.Close {...props} />
}
export type DialogProps = DialogRootProps & {
/** Element that opens the dialog, usually a `<Button>`. 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 (
<DialogRoot {...rootProps}>
{trigger && <DialogTrigger render={trigger} />}
<DialogContent size={size} hideCloseButton={hideCloseButton} className={className} aria-label={ariaLabel}>
{(title != null || description != null) && (
<DialogHeader>
{title != null && <DialogTitle>{title}</DialogTitle>}
{description != null && <DialogDescription>{description}</DialogDescription>}
</DialogHeader>
)}
{children != null && <DialogBody>{children}</DialogBody>}
{footer != null && <DialogFooter>{footer}</DialogFooter>}
</DialogContent>
</DialogRoot>
)
}
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
+213
View File
@@ -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 [email protected]', '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 }) => (
<ul className="m-0 list-none divide-y divide-border p-0">
{Array.from({ length: repeat }, () => activity)
.flat()
.map(([who, what, when], index) => (
<li key={index} className="flex flex-col gap-0.5 py-3 first:pt-0 last:pb-0">
<span>
<span className="font-semibold">{who}</span> {what}
</span>
<span className="text-xs text-fg-muted">{when}</span>
</li>
))}
</ul>
)
const footer = (
<>
<Drawer.Close render={<Button variant="outline" color="neutral" />}>Cancel</Drawer.Close>
<Button>Apply filters</Button>
</>
)
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: <Button variant="outline" color="neutral">Show activity</Button>,
children: <ActivityList />,
onOpenChange: fn(),
},
} satisfies Meta<typeof Drawer>
export default meta
type Story = StoryObj<typeof meta>
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: (
<nav aria-label="Workspace">
<ul className="m-0 flex list-none flex-col gap-1 p-0">
{['Dashboard', 'Projects', 'Team', 'Billing', 'Settings'].map((item, index) => (
<li key={item}>
<a
href="#"
aria-current={index === 1 ? 'page' : undefined}
className="block rounded-md px-3 py-2 text-fg hover:bg-surface-sunken aria-[current=page]:bg-primary-50 aria-[current=page]:font-semibold aria-[current=page]:text-primary-700 dark:aria-[current=page]:bg-primary-500/15 dark:aria-[current=page]:text-primary-300"
>
{item}
</a>
</li>
))}
</ul>
</nav>
),
},
parameters: ownFrame(),
}
export const Top: Story = {
args: {
defaultOpen: true,
side: 'top',
size: 'sm',
title: 'Search',
description: undefined,
children: <Input aria-label="Search projects" placeholder="Search projects, files and people" startIcon={<Search />} />,
},
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: (
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<Input label="Invite by email" placeholder="[email protected]" className="flex-1" />
<Button>Send invite</Button>
</div>
),
},
parameters: ownFrame(),
}
export const WithFooter: Story = {
args: {
defaultOpen: true,
title: 'Filter employees',
description: 'Show only the people who match.',
footer,
children: (
<div className="flex flex-col gap-4">
<Input label="Team" defaultValue="Design" />
<Input label="Location" placeholder="Any location" />
<Input label="Started after" type="date" />
</div>
),
trigger: (
<Button variant="outline" color="neutral" startIcon={<Filter aria-hidden="true" />}>
Filters
</Button>
),
},
parameters: ownFrame(),
}
export const LongContent: Story = {
args: { defaultOpen: true, children: <ActivityList repeat={4} />, footer: <Button variant="outline" color="neutral">Load more</Button> },
parameters: ownFrame(),
}
export const Sides: Story = {
render: (args) => (
<div className="flex flex-wrap gap-3">
{DRAWER_SIDES.map((side) => (
<Drawer
key={side}
{...args}
side={side}
size="sm"
trigger={
<Button variant="outline" color="neutral">
From {side}
</Button>
}
/>
))}
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-wrap gap-3">
{DRAWER_SIZES_LIST.map((size) => (
<Drawer
key={size}
{...args}
size={size}
trigger={
<Button variant="outline" color="neutral">
Size {size}
</Button>
}
/>
))}
</div>
),
}
+55
View File
@@ -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<React.ComponentProps<typeof Drawer>>) {
return (
<Drawer
trigger={<Button>Filters</Button>}
title="Filter employees"
description="Narrow the list by team and status."
footer={<Button>Apply</Button>}
{...props}
>
<p>Team, status and location filters.</p>
</Drawer>
)
}
describe('Drawer', () => {
it('opens from the trigger as a named dialog', async () => {
render(<Example />)
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(<Example onOpenChange={onOpenChange} />)
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(<Sheet {...{ title: 'Details', side: 'left' }} defaultOpen />)
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(<Example defaultOpen side="bottom" />)
await screen.findByRole('dialog')
await expectNoA11yViolations(document.body)
})
})
+138
View File
@@ -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 `<Button>`. */
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 (
<BaseDrawer.Root
open={open}
defaultOpen={defaultOpen}
onOpenChange={onOpenChange ? (next) => onOpenChange(next) : undefined}
swipeDirection={DRAWER_SWIPE[side]}
disablePointerDismissal={!closeOnOutsideClick}
>
{trigger && <BaseDrawer.Trigger render={trigger} />}
<BaseDrawer.Portal>
<BaseDrawer.Backdrop
className={cn(
backdropClass,
'z-50 opacity-[calc(1-var(--drawer-swipe-progress,0))] data-swiping:duration-0',
)}
/>
<BaseDrawer.Viewport className={cn('fixed inset-0 z-50 flex', DRAWER_VIEWPORT[side])}>
<BaseDrawer.Popup
aria-label={ariaLabel}
className={cn(
'relative flex flex-col overflow-hidden border-border bg-surface text-fg shadow-popup outline-none',
'transition-transform duration-300 ease-[cubic-bezier(0.32,0.72,0,1)] data-swiping:select-none data-swiping:duration-0',
'motion-reduce:transition-none',
DRAWER_PANEL[side],
vertical ? DRAWER_HEIGHTS[size] : DRAWER_WIDTHS[size],
className,
)}
>
{side === 'bottom' && size !== 'full' && (
<div aria-hidden="true" className="mx-auto mt-2.5 h-1.5 w-10 shrink-0 rounded-full bg-border-strong" />
)}
<BaseDrawer.Content className={cn('flex min-h-0 w-full flex-1 flex-col', vertical && size !== 'full' && 'mx-auto max-w-3xl')}>
{(title != null || description != null) && (
<DialogHeader>
{title != null && <BaseDrawer.Title className={dialogTitleClass}>{title}</BaseDrawer.Title>}
{description != null && (
<BaseDrawer.Description className={dialogDescriptionClass}>{description}</BaseDrawer.Description>
)}
</DialogHeader>
)}
{children != null && <DialogBody>{children}</DialogBody>}
{footer != null && <DialogFooter>{footer}</DialogFooter>}
</BaseDrawer.Content>
{!hideCloseButton && (
<BaseDrawer.Close
render={<IconButton aria-label="Close" size="sm" icon={<X aria-hidden="true" />} />}
className={cn('absolute right-3 sm:right-4', side === 'bottom' && size !== 'full' ? 'top-5 sm:top-6' : 'top-3 sm:top-4')}
/>
)}
</BaseDrawer.Popup>
</BaseDrawer.Viewport>
</BaseDrawer.Portal>
</BaseDrawer.Root>
)
}
/** Closes the drawer. Pass a Button as `render`: `<Drawer.Close render={<Button>Cancel</Button>} />`. */
function DrawerClose(props: BaseDrawer.Close.Props) {
return <BaseDrawer.Close {...props} />
}
export const Drawer = Object.assign(DrawerComponent, { Close: DrawerClose })
/** Alias of `Drawer`. */
export const Sheet = Drawer
+242
View File
@@ -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: <Pencil />, shortcut: '⌘R', onSelect: fn() },
{ label: 'Duplicate', icon: <Copy />, shortcut: '⌘D', onSelect: fn() },
{ label: 'Share', icon: <Share2 />, shortcut: '⇧⌘S', onSelect: fn() },
{
type: 'submenu',
label: 'Move to',
icon: <FolderInput />,
items: [
{ label: 'Design', onSelect: fn() },
{ label: 'Marketing', onSelect: fn() },
{ label: 'Engineering', onSelect: fn() },
{ type: 'separator' },
{ label: 'New folder…', onSelect: fn() },
],
},
{ label: 'Download', icon: <Download />, disabled: true },
{ type: 'separator' },
{ label: 'Archive', icon: <Archive />, onSelect: fn() },
{ label: 'Delete', icon: <Trash2 />, 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: (
<Button variant="outline" color="neutral" endIcon={<ChevronDown aria-hidden="true" />}>
Actions
</Button>
),
onOpenChange: fn(),
},
decorators: [
(Story) => (
<div className="min-h-96">
<Story />
</div>
),
],
} satisfies Meta<typeof DropdownMenu>
export default meta
type Story = StoryObj<typeof meta>
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: (
<Button variant="outline" color="neutral" endIcon={<ChevronDown aria-hidden="true" />}>
View
</Button>
),
},
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: <IconButton variant="outline" aria-label="More actions" icon={<MoreHorizontal />} />,
},
decorators: [
(Story) => (
<div className="flex justify-end pr-8">
<Story />
</div>
),
],
parameters: ownFrame(),
}
export const OpenSubmenu: Story = {
parameters: {
...ownFrame(),
docs: { ...ownFrame().docs, description: { story: 'Built from compound parts, with the submenu open.' } },
},
render: () => (
<DropdownMenu.Root defaultOpen>
<DropdownMenu.Trigger
render={
<Button variant="outline" color="neutral" startIcon={<User aria-hidden="true" />} endIcon={<ChevronDown aria-hidden="true" />}>
Jane Doe
</Button>
}
/>
<DropdownMenu.Content className="w-60">
<DropdownMenu.Group>
<DropdownMenu.Label>name@example.com</DropdownMenu.Label>
<DropdownMenu.Item icon={<User />} shortcut="⇧⌘P">
Profile
</DropdownMenu.Item>
<DropdownMenu.Item icon={<Settings />} shortcut="⌘,">
Settings
</DropdownMenu.Item>
</DropdownMenu.Group>
<DropdownMenu.Sub defaultOpen>
<DropdownMenu.SubTrigger icon={<Users />}>Switch workspace</DropdownMenu.SubTrigger>
<DropdownMenu.SubContent>
<DropdownMenu.RadioGroup defaultValue="acme">
<DropdownMenu.RadioItem value="acme">Acme Corporation</DropdownMenu.RadioItem>
<DropdownMenu.RadioItem value="globex">Globex Studio</DropdownMenu.RadioItem>
<DropdownMenu.RadioItem value="initech">Initech Labs</DropdownMenu.RadioItem>
</DropdownMenu.RadioGroup>
</DropdownMenu.SubContent>
</DropdownMenu.Sub>
<DropdownMenu.Separator />
<DropdownMenu.Item icon={<LogOut />} color="danger">
Sign out
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
),
}
export const Controlled: Story = {
render: function Render(args) {
const [compact, setCompact] = useState(false)
const [density, setDensity] = useState('comfortable')
return (
<div className="flex items-start gap-4">
<DropdownMenu
{...args}
items={[
{ type: 'checkbox', label: 'Compact sidebar', checked: compact, onCheckedChange: setCompact },
{ type: 'separator' },
{
type: 'radio',
label: 'Density',
value: density,
onValueChange: setDensity,
items: [
{ value: 'comfortable', label: 'Comfortable' },
{ value: 'cozy', label: 'Cozy' },
{ value: 'compact', label: 'Compact' },
],
},
]}
trigger={
<Button variant="outline" color="neutral" endIcon={<ChevronDown aria-hidden="true" />}>
Display
</Button>
}
/>
<p className="m-0 text-sm text-fg-muted">
compact sidebar: {String(compact)}, density: {density}
</p>
</div>
)
},
}
export const Placement: Story = {
args: { side: 'right', align: 'start', defaultOpen: true, items: projectItems.slice(1, 4) },
parameters: ownFrame(),
}
+128
View File
@@ -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<Record<string, () => 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(<DropdownMenu trigger={<Button>Actions</Button>} 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(<DropdownMenu trigger={<Button>Actions</Button>} 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(<DropdownMenu trigger={<Button>Actions</Button>} 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(<DropdownMenu trigger={<Button>Actions</Button>} 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(<DropdownMenu trigger={<Button>Actions</Button>} 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(
<DropdownMenu
trigger={<Button>Actions</Button>}
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(
<DropdownMenu.Root defaultOpen>
<DropdownMenu.Trigger render={<Button>Options</Button>} />
<DropdownMenu.Content>
<DropdownMenu.Group>
<DropdownMenu.Label>Account</DropdownMenu.Label>
<DropdownMenu.Item onSelect={onSelect}>Profile</DropdownMenu.Item>
</DropdownMenu.Group>
<DropdownMenu.Separator />
<DropdownMenu.CheckboxItem defaultChecked>Notifications</DropdownMenu.CheckboxItem>
</DropdownMenu.Content>
</DropdownMenu.Root>,
)
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(
<DropdownMenu
defaultOpen
trigger={<Button>Actions</Button>}
items={[{ type: 'label', label: 'Project' }, ...items()]}
/>,
)
await screen.findByRole('menu')
await expectNoA11yViolations(document.body)
})
})
+357
View File
@@ -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 (
<BaseMenu.Root {...props} modal={modal} onOpenChange={onOpenChange ? (open) => onOpenChange(open) : undefined}>
{children}
</BaseMenu.Root>
)
}
/** Opens the menu. Pass your button as `render`: `<DropdownMenu.Trigger render={<Button>Actions</Button>} />`. */
function MenuTrigger(props: BaseMenu.Trigger.Props) {
return <BaseMenu.Trigger {...props} />
}
export type DropdownMenuContentProps = Omit<BaseMenu.Popup.Props, 'className'> & {
/** 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 (
<BaseMenu.Portal>
<BaseMenu.Positioner side={side} align={align} sideOffset={sideOffset} className="z-50 outline-none">
<BaseMenu.Popup className={cn(popupSurface, popupMotion, menuPopupClass, className)} {...props} />
</BaseMenu.Positioner>
</BaseMenu.Portal>
)
}
function ItemIcon({ children }: { children: ReactNode }) {
return (
<span data-slot="icon" aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center text-fg-muted [&_svg]:size-4">
{children}
</span>
)
}
function Shortcut({ children }: { children: ReactNode }) {
return <kbd className={menuShortcut}>{children}</kbd>
}
export type DropdownMenuItemProps = Omit<BaseMenu.Item.Props, 'className' | 'onSelect'> & {
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 (
<BaseMenu.Item
className={cn(listItem, color === 'danger' && menuDangerItem, className)}
onClick={(event) => {
onClick?.(event)
onSelect?.()
}}
{...props}
>
{icon != null && <ItemIcon>{icon}</ItemIcon>}
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut && <Shortcut>{shortcut}</Shortcut>}
</BaseMenu.Item>
)
}
export type DropdownMenuCheckboxItemProps = Omit<BaseMenu.CheckboxItem.Props, 'className'> & {
shortcut?: string
className?: string
}
/** A setting that toggles on and off. The menu stays open. */
function MenuCheckboxItem({ shortcut, className, children, ...props }: DropdownMenuCheckboxItemProps) {
return (
<BaseMenu.CheckboxItem className={cn(listItem, className)} {...props}>
<span className="flex size-4 shrink-0 items-center justify-center">
<BaseMenu.CheckboxItemIndicator className="flex text-primary-600 dark:text-primary-400">
<Check aria-hidden="true" className="size-4" strokeWidth={2.5} />
</BaseMenu.CheckboxItemIndicator>
</span>
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut && <Shortcut>{shortcut}</Shortcut>}
</BaseMenu.CheckboxItem>
)
}
/** Groups RadioItems; only one can be chosen. */
function MenuRadioGroup(props: BaseMenu.RadioGroup.Props) {
return <BaseMenu.RadioGroup {...props} />
}
export type DropdownMenuRadioItemProps = Omit<BaseMenu.RadioItem.Props, 'className'> & {
icon?: ReactNode
className?: string
}
/** One option in a RadioGroup. */
function MenuRadioItem({ icon, className, children, ...props }: DropdownMenuRadioItemProps) {
return (
<BaseMenu.RadioItem className={cn(listItem, className)} {...props}>
<span className="flex size-4 shrink-0 items-center justify-center">
<BaseMenu.RadioItemIndicator className="size-2 rounded-full bg-primary-600 dark:bg-primary-400" />
</span>
{icon != null && <ItemIcon>{icon}</ItemIcon>}
<span className="min-w-0 flex-1 truncate">{children}</span>
</BaseMenu.RadioItem>
)
}
function MenuSeparator({ className, ...props }: Omit<BaseMenu.Separator.Props, 'className'> & { className?: string }) {
return <BaseMenu.Separator className={cn('-mx-1 my-1 h-px bg-border', className)} {...props} />
}
/** Groups items under a Label. */
function MenuGroup(props: BaseMenu.Group.Props) {
return <BaseMenu.Group {...props} />
}
/** A heading for a Group or RadioGroup. Must sit inside one of them. */
function MenuLabel({ className, ...props }: Omit<BaseMenu.GroupLabel.Props, 'className'> & { className?: string }) {
return <BaseMenu.GroupLabel className={cn(menuLabel, className)} {...props} />
}
/** A nested menu. Holds a SubTrigger and a SubContent. */
function MenuSub(props: BaseMenu.SubmenuRoot.Props) {
return <BaseMenu.SubmenuRoot {...props} />
}
export type DropdownMenuSubTriggerProps = Omit<BaseMenu.SubmenuTrigger.Props, 'className'> & {
icon?: ReactNode
className?: string
}
/** The item that opens a submenu, on hover, click or ArrowRight. */
function MenuSubTrigger({ icon, className, children, ...props }: DropdownMenuSubTriggerProps) {
return (
<BaseMenu.SubmenuTrigger className={cn(listItem, 'data-popup-open:bg-surface-sunken', className)} {...props}>
{icon != null && <ItemIcon>{icon}</ItemIcon>}
<span className="min-w-0 flex-1 truncate">{children}</span>
<ChevronRight aria-hidden="true" className="-mr-1 ml-4 size-4 text-fg-muted" />
</BaseMenu.SubmenuTrigger>
)
}
/** The submenu's list. */
function MenuSubContent({ className, ...props }: Omit<BaseMenu.Popup.Props, 'className'> & { className?: string }) {
return (
<BaseMenu.Portal>
<BaseMenu.Positioner sideOffset={4} alignOffset={-5} className="z-50 outline-none">
<BaseMenu.Popup className={cn(popupSurface, popupMotion, menuPopupClass, className)} {...props} />
</BaseMenu.Positioner>
</BaseMenu.Portal>
)
}
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 <MenuSeparator key={key} />
case 'label':
return <MenuLabel key={key}>{item.label}</MenuLabel>
case 'checkbox':
return (
<MenuCheckboxItem
key={key}
label={textOf(item.label, item.textValue)}
disabled={item.disabled}
checked={item.checked}
defaultChecked={item.defaultChecked}
onCheckedChange={item.onCheckedChange ? (checked) => item.onCheckedChange?.(checked) : undefined}
shortcut={item.shortcut}
>
{item.label}
</MenuCheckboxItem>
)
case 'radio':
return (
<MenuRadioGroup
key={key}
value={item.value}
defaultValue={item.defaultValue}
onValueChange={item.onValueChange ? (value: string) => item.onValueChange?.(value) : undefined}
>
{item.label != null && <MenuLabel>{item.label}</MenuLabel>}
{item.items.map((option) => (
<MenuRadioItem
key={option.value}
value={option.value}
label={textOf(option.label, option.textValue)}
disabled={option.disabled}
icon={option.icon}
>
{option.label}
</MenuRadioItem>
))}
</MenuRadioGroup>
)
case 'submenu':
return (
<MenuSub key={key} disabled={item.disabled}>
<MenuSubTrigger icon={item.icon} label={textOf(item.label, item.textValue)}>
{item.label}
</MenuSubTrigger>
<MenuSubContent>{renderItems(item.items)}</MenuSubContent>
</MenuSub>
)
default:
return (
<MenuItem
key={key}
icon={item.icon}
shortcut={item.shortcut}
color={item.color}
disabled={item.disabled}
label={textOf(item.label, item.textValue)}
onSelect={item.onSelect}
>
{item.label}
</MenuItem>
)
}
}
/** 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(<MenuGroup key={groupKey}>{groupChildren}</MenuGroup>)
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 <Fragment>{out}</Fragment>
}
export type DropdownMenuProps = OpenProps & {
/** The element that opens the menu, usually a `<Button>` or `<IconButton>`. */
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 (
<MenuRoot {...rootProps}>
<MenuTrigger render={trigger} />
<MenuContent side={side} align={align} sideOffset={sideOffset} className={className}>
{items && renderItems(items)}
{children}
</MenuContent>
</MenuRoot>
)
}
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,
})
+168 -132
View File
@@ -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<typeof FeaturedInput> = {
const meta = {
title: 'Forms/FeaturedInput',
component: FeaturedInput,
tags: ['autodocs'],
@@ -11,159 +14,192 @@ const meta: Meta<typeof FeaturedInput> = {
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) => (
<div className="max-w-sm">
<Story />
</div>
),
],
} satisfies Meta<typeof FeaturedInput>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Filled: Story = {
args: { defaultValue: '[email protected]' },
}
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 [email protected].' },
}
export const Required: Story = {
args: { required: true, description: 'We never share your email.' },
}
export const Disabled: Story = {
args: { disabled: true, defaultValue: '[email protected]' },
}
export const ReadOnly: Story = {
args: { readOnly: true, defaultValue: '[email protected]', 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: <Search /> },
}
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<typeof FeaturedInput> & { initial?: string }) {
const [value, setValue] = useState(initial)
return (
<FeaturedInput {...args} value={value} onChange={(e) => setValue(e.target.value)} />
)
}
export const FeaturedPlayground: StoryObj<typeof FeaturedInput> = {
export const Variants: Story = {
render: (args) => (
<div className="max-w-md">
<ControlledFeatured {...args} />
</div>
),
}
export const FloatingStates: StoryObj<typeof FeaturedInput> = {
name: 'Floating states',
render: () => (
<div className="flex max-w-md flex-col gap-8 pb-4">
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Resting (empty)</p>
<ControlledFeatured label="Full name" placeholder="Jane Doe" />
</div>
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Floated (has value)</p>
<ControlledFeatured label="Full name" initial="Jane Doe" />
</div>
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Forced (shrink)</p>
<ControlledFeatured label="Full name" shrink placeholder="Jane Doe" />
</div>
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Error</p>
<ControlledFeatured label="Full name" error="This field is required." />
</div>
</div>
),
}
export const PasswordWithToggle: StoryObj<typeof FeaturedInput> = {
render: () => (
<div className="max-w-md">
<ControlledFeatured type="password" label="SMTP password" placeholder="••••••••" />
</div>
),
}
export const PasswordToggleDisabled: StoryObj<typeof FeaturedInput> = {
render: () => (
<div className="max-w-md">
<ControlledFeatured
type="password"
label="Locked field"
showPasswordToggle={false}
initial="stored-secret"
/>
</div>
),
}
export const WithLucideIcon: StoryObj<typeof FeaturedInput> = {
render: () => (
<div className="flex max-w-md flex-col gap-6">
<ControlledFeatured label="Email" icon={Mail} placeholder="[email protected]" />
<ControlledFeatured label="Username" icon={User} iconPosition="right" placeholder="jane" />
<ControlledFeatured label="Search" icon={Search} placeholder="Search employees" />
<ControlledFeatured label="API key" icon={Lock} type="password" placeholder="sk_live_…" />
</div>
),
}
export const NumberHardening: StoryObj<typeof FeaturedInput> = {
name: 'Number hardening',
render: () => (
<div className="max-w-md">
<ControlledFeatured
type="number"
label="Annual CTC"
placeholder="1200000"
helpText="Blocks e, +, - and wheel scrolling."
/>
</div>
),
}
export const FeaturedThemes: StoryObj<typeof FeaturedInput> = {
name: 'Themes',
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
<ControlledFeatured key={theme} theme={theme} label={theme} initial="Filled" />
<div className="grid gap-5">
{TEXT_FIELD_VARIANTS.map((variant) => (
<div key={variant} className="grid gap-3">
<FeaturedInput {...args} variant={variant} label={`${variant[0].toUpperCase()}${variant.slice(1)}, empty`} />
<FeaturedInput
{...args}
variant={variant}
label={`${variant[0].toUpperCase()}${variant.slice(1)}, filled`}
defaultValue="[email protected]"
/>
</div>
))}
</div>
),
}
export const FeaturedVariants: StoryObj<typeof FeaturedInput> = {
name: 'Variants',
render: () => (
<div className="flex max-w-lg flex-col gap-8 pb-4">
<ControlledFeatured variant="outlined" label="Outlined" initial="Value" />
<ControlledFeatured variant="underlined" label="Underlined" initial="Value" />
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<div key={size} className="grid grid-cols-2 gap-3">
<FeaturedInput {...args} size={size} label={`Size ${size}`} />
<FeaturedInput {...args} size={size} label={`Size ${size}`} defaultValue="[email protected]" />
</div>
))}
</div>
),
}
export const FeaturedDisabled: StoryObj<typeof FeaturedInput> = {
name: 'Disabled',
render: () => (
<div className="flex max-w-md flex-col gap-6">
<ControlledFeatured label="Locked" initial="Cannot edit" disabled />
<ControlledFeatured label="Locked password" type="password" initial="secret" disabled />
export const WithIcons: Story = {
render: (args) => (
<div className="grid gap-5">
<FeaturedInput {...args} label="Email" startIcon={<Mail />} />
<FeaturedInput {...args} label="Full name" type="text" startIcon={<UserRound />} defaultValue="Jane Doe" />
<FeaturedInput {...args} label="Username" type="text" endIcon={<AtSign />} defaultValue="janedoe" />
<FeaturedInput {...args} label="API key" type="password" startIcon={<Lock />} defaultValue="sk_test_4eC39HqLyjWDarjtT1" clearable />
</div>
),
}
export const AllStates: Story = {
render: (args) => (
<div className="grid gap-5">
<FeaturedInput {...args} label="Empty" />
<FeaturedInput {...args} label="Filled" defaultValue="[email protected]" />
<FeaturedInput {...args} label="Required" required />
<FeaturedInput {...args} label="Invalid" defaultValue="jane.doe@" error="Enter a full email address." />
<FeaturedInput {...args} label="Disabled" disabled defaultValue="[email protected]" />
<FeaturedInput {...args} label="Read-only" readOnly defaultValue="[email protected]" />
<FeaturedInput {...args} label="Loading" loading defaultValue="[email protected]" />
</div>
),
}
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 (
<div className="grid gap-2">
<FeaturedInput {...args} label="Full name" type="text" clearable
value={value}
onValueChange={(next) => {
setValue(next)
args?.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Value: {value || '(empty)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledFeaturedInput {...args} />,
}
export const SignInForm: Story = {
render: (args) => (
<form className="grid gap-4 rounded-xl border border-border bg-surface p-5" onSubmit={(e) => e.preventDefault()}>
<FeaturedInput {...args} label="Email" type="email" autoComplete="email" required startIcon={<Mail />} />
<FeaturedInput {...args} label="Password" type="password" autoComplete="current-password" required startIcon={<Lock />} />
</form>
),
}
+132
View File
@@ -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(<FeaturedInput label="Work email" />)
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(<FeaturedInput label="Work email" placeholder="[email protected]" />)
expect(screen.getByRole('textbox')).toHaveAttribute('placeholder', '[email protected]')
})
it('announces the description with the input', () => {
render(<FeaturedInput label="Work email" description="Invoices go here." />)
expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Invoices go here.')
})
it('marks the input invalid and announces the error instead of the description', () => {
render(<FeaturedInput label="Work email" error="Enter a full email address." description="Hidden while invalid" />)
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(<FeaturedInput label="Name" required disabled />)
expect(screen.getByRole('textbox')).toBeRequired()
expect(screen.getByRole('textbox')).toBeDisabled()
rerender(<FeaturedInput label="Name" readOnly />)
expect(screen.getByRole('textbox')).toHaveAttribute('readonly')
})
it('works uncontrolled with defaultValue', async () => {
const onValueChange = vi.fn()
render(<FeaturedInput label="Name" defaultValue="Jane" onValueChange={onValueChange} />)
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(<FeaturedInput label="Name" value="Jane" onValueChange={onValueChange} onChange={onChange} />)
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<HTMLInputElement>()
render(<FeaturedInput label="Name" ref={ref} />)
expect(ref.current).toBe(screen.getByRole('textbox'))
})
it('reveals and hides the password with a pressed toggle', async () => {
const user = userEvent.setup()
render(<FeaturedInput label="Password" type="password" defaultValue="secret" />)
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(<FeaturedInput label="Search" clearable defaultValue="Jane Doe" onValueChange={onValueChange} />)
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(<FeaturedInput label="Search" clearable defaultValue="Acme" />)
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(<FeaturedInput label="Search" clearable />)
expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument()
rerender(<FeaturedInput label="Search" clearable defaultValue="x" disabled />)
expect(screen.queryByRole('button', { name: 'Clear' })).not.toBeInTheDocument()
})
it('marks the input busy while loading', () => {
render(<FeaturedInput label="Username" loading />)
expect(screen.getByRole('textbox')).toHaveAttribute('aria-busy', 'true')
})
it('has no axe violations', async () => {
const { container } = render(
<>
<FeaturedInput label="Email" description="We never share it." required startIcon={<svg />} clearable defaultValue="[email protected]" />
<FeaturedInput label="Password" type="password" error="Too short." loading />
</>,
)
await expectNoA11yViolations(container)
})
})
+188 -307
View File
@@ -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<HTMLInputElement>,
'size' | 'value' | 'defaultValue'
> & {
label?: string
value?: string
size?: InputSize
theme?: InputTheme
variant?: InputVariant
name?: string
onChange?: (e: ChangeEvent<HTMLInputElement>) => void
onBlur?: (e: FocusEvent<HTMLInputElement>) => void
onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => 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<ComponentProps<'input'>, '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<HTMLInputElement, FeaturedInputProps>(
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<HTMLInputElement | null>(null)
const [current, setCurrent] = useControllableState<string>(
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<HTMLDivElement>(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<string, unknown>, [
'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<HTMLInputElement>) => {
onBlur?.(e)
// An empty field drops back to the resting label position.
if (e.target.value === '' && !shrink) setIsFocused(false)
}
const handleChange = (e: ChangeEvent<HTMLInputElement>) => 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<HTMLInputElement>) => {
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<HTMLInputElement>) => {
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 (
<div ref={wrapperRef} className={cn('relative w-full', isUnderlined && 'mt-4', className)}>
<div
className={cn(
'relative flex items-center transition-all duration-200',
disabled ? 'cursor-not-allowed' : 'cursor-text',
INPUT_SIZES[size] ?? INPUT_SIZES.md,
variantTokens.wrapper,
roundedFull ? 'rounded-full' : 'rounded',
dashedBorder ? 'border-dashed' : 'border',
isUnderlined ? '' : 'border',
(isFocused || shouldFloat) && !errorMessage
? cn(
'border',
INPUT_THEMES[theme] ?? INPUT_THEMES.primary,
'focus:border-primary-500',
)
: 'border border-slate-300',
!disabled && !isFocused && !errorMessage && INPUT_HOVER_THEMES[theme],
errorMessage && 'border-red-500 focus:border-red-500 focus:ring-red-500',
disabled && 'bg-gray-100 opacity-60',
// The floated label chip needs the field's own background behind it.
shouldFloat && !isUnderlined && FLOATING_CONTENT_PADDING[size],
)}
>
{Icon && iconPosition === 'left' && (
<Icon
aria-hidden="true"
className={cn(
'absolute left-3 text-gray-500 pointer-events-none',
ICON_SIZES[size],
shouldFloat && 'top-2 -translate-y-0',
)}
size={16}
/>
)}
<input
id={name}
ref={ref}
name={name}
type={resolvedType}
disabled={disabled}
return (
<Field description={description} error={error} required={required} disabled={disabled} name={name} className={className}>
<div
className={cn(
'flex w-full items-stretch',
controlHeight[size],
iconSize[size],
FIELD_BOX[variant],
FIELD_BOX_DISABLED_INPUT,
FIELD_BOX_RING_INPUT,
variant === 'underline' && FIELD_BOX_RING_UNDERLINE,
)}
>
{startIcon != null && (
<span aria-hidden="true" className={cn('flex items-center text-fg-subtle', variant === 'underline' ? 'pl-0.5' : 'pl-3')}>
{startIcon}
</span>
)}
<div className="relative min-w-0 flex-1">
<BaseInput
ref={setRefs}
type={isPassword && revealed ? 'text' : type}
required={required}
value={value}
placeholder={placeholder}
autoComplete="off"
aria-invalid={Boolean(errorMessage)}
onFocus={(e) => {
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}
/>
<div className="absolute right-3 flex items-center gap-1.5">
{isLoading && <span className="text-[10px] text-gray-400">…</span>}
{trailing}
{hasRevealToggle && (
<button
type="button"
onClick={() => setIsRevealed((v) => !v)}
aria-label={isRevealed ? 'Hide password' : 'Show password'}
className="text-gray-400 hover:text-gray-600"
>
{isRevealed ? <EyeOff size={15} /> : <Eye size={15} />}
</button>
)}
</div>
{Icon && iconPosition === 'right' && (
<Icon aria-hidden="true" size={16} className="absolute right-8 text-gray-500 pointer-events-none" />
)}
{label && (
<label
htmlFor={name}
{label != null && (
<FieldLabel
required={required}
className={cn(
'absolute transition-all duration-200 pointer-events-none',
isUnderlined ? 'left-0' : 'left-3',
shouldFloat
? cn(
'-top-2.5 z-10',
variantTokens.labelFloating,
FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md,
labelColor,
)
: cn(
'top-1/2 -translate-y-1/2',
LABEL_SIZES[size] ?? LABEL_SIZES.md,
'text-slate-400',
),
FLOAT_LABEL_BASE,
'top-1/2 -translate-y-1/2',
geometry.rest,
geometry.float,
variant === 'underline' ? 'right-0.5 left-0.5' : inset.label,
startIcon != null && 'left-2',
hasEnd && 'right-1.5',
invalid ? FLOAT_LABEL_COLOR.invalid : cn(FLOAT_LABEL_COLOR.base, FLOAT_LABEL_COLOR.focus),
)}
>
<span className="flex items-center gap-1.5">
<span className="truncate">
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</span>
{(tooltip || helpText) && (
<span
className="pointer-events-auto inline-flex shrink-0"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.preventDefault()}
>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
</label>
{label}
</FieldLabel>
)}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
{hasEnd && (
<div className={cn('flex shrink-0 items-center gap-0.5', variant === 'underline' ? 'pr-0' : 'pr-1.5')}>
{loading && (
<span aria-hidden="true" className="flex items-center px-1 text-fg-subtle">
<LoaderCircle className="animate-spin motion-reduce:animate-none" />
</span>
)}
{showClear && (
<IconButton
aria-label="Clear"
icon={<X />}
onClick={clear}
className={INNER_BUTTON[size]}
/>
)}
{isPassword && (
<IconButton
aria-label={revealed ? 'Hide password' : 'Show password'}
aria-pressed={revealed}
icon={revealed ? <EyeOff /> : <Eye />}
disabled={disabled}
onClick={() => setRevealed((r) => !r)}
className={INNER_BUTTON[size]}
/>
)}
{endIcon != null && (
<span aria-hidden="true" className="flex items-center px-1.5 text-fg-subtle">
{endIcon}
</span>
)}
</div>
)}
</div>
)
},
)
</Field>
)
}
export default FeaturedInput
function assignRef<T>(ref: Ref<T> | undefined, node: T | null) {
if (typeof ref === 'function') ref(node)
else if (ref) ref.current = node
}
+275
View File
@@ -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 }) => (
<div
className={
parameters.wide
? 'max-w-3xl rounded-xl border border-border bg-surface p-6'
: 'max-w-sm rounded-xl border border-border bg-surface p-6'
}
>
<Story />
</div>
),
],
} satisfies Meta<typeof FeaturedSelect>
export default meta
type Story = StoryObj<typeof meta>
const tall = (Story: () => React.JSX.Element) => (
<div className="min-h-[26rem]">
<Story />
</div>
)
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) => (
<div className="grid gap-6">
<FeaturedSelect {...args} label="Empty" />
<FeaturedSelect {...args} label="With a value" defaultValue="fin" />
<FeaturedSelect {...args} label="Invalid" error="Choose a department." />
<FeaturedSelect {...args} label="Invalid with a value" defaultValue="eng" error="Engineering is full." />
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-6">
{SIZES.map((size) => (
<div key={size} className="grid grid-cols-2 gap-4">
<FeaturedSelect {...args} size={size} label={`Size ${size}`} />
<FeaturedSelect {...args} size={size} label={`Size ${size}`} defaultValue="eng" />
</div>
))}
</div>
),
parameters: { wide: true },
}
export const Variants: Story = {
render: (args) => (
<div className="grid gap-6">
{SELECT_VARIANTS.map((variant) => (
<div key={variant} className="grid grid-cols-2 gap-4">
<FeaturedSelect {...args} variant={variant} label={variant === 'outline' ? 'Outline' : 'Filled'} />
<FeaturedSelect
{...args}
variant={variant}
label={variant === 'outline' ? 'Outline' : 'Filled'}
defaultValue="ops"
/>
</div>
))}
</div>
),
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) => (
<div className="grid gap-6">
<FeaturedSelect {...args} startIcon={<Briefcase />} />
<FeaturedSelect {...args} startIcon={<Briefcase />} defaultValue="sales" />
</div>
),
}
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 }) => (
<span className="flex items-center justify-between gap-3">
<span className="truncate">{option.label}</span>
<span className={selected ? 'text-xs text-primary-700 dark:text-primary-300' : 'text-xs text-fg-muted'}>
{option.description?.split(' · ')[1]}
</span>
</span>
),
},
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: <Plus />, 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<string | null>('hr')
return (
<div className="grid gap-2">
<FeaturedSelect {...withoutValue(args)} options={DEPARTMENTS} value={value} onValueChange={setValue} clearable />
<p className="text-sm text-fg-muted">Value: {value ?? '(none)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledFeaturedSelect {...args} />,
}
export const Uncontrolled: Story = {
args: { defaultValue: 'sales', name: 'department' },
}
+145
View File
@@ -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(<FeaturedSelect label="Department" options={departments} />)
expect(screen.getByRole('combobox', { name: 'Department' })).toBeInTheDocument()
})
it('floats the label when a value is chosen', async () => {
render(<FeaturedSelect label="Department" options={departments} />)
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(<FeaturedSelect label="Department" options={departments} onValueChange={onValueChange} />)
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<string[]>(['eng'])
return (
<>
<FeaturedSelect label="Departments" multiple options={departments} value={value} onValueChange={setValue} />
<p data-testid="value">{value.join(',')}</p>
</>
)
}
render(<Controlled />)
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(<FeaturedSelect label="Department" clearable defaultValue="fin" options={departments} onValueChange={onValueChange} />)
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(
<FeaturedSelect label="Department" options={departments} defaultOpen actionButton={{ label: 'Add department', onClick }} />,
)
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(<FeaturedSelect label="Department" error="Choose a department." options={departments} />)
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(
<FeaturedSelect label="Department" description="Where they report." required clearable defaultValue="eng" options={departments} />,
)
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(<FeaturedSelect label="Department" searchable options={departments} onValueChange={onValueChange} />)
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(<FeaturedSelect label="Department" searchable options={departments} defaultOpen />)
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(<FeaturedSelect label="Department" searchable options={departments} />)
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(
<FeaturedSelect
label="Department"
searchable
options={departments}
defaultOpen
actionButton={{ label: 'Add department', onClick: () => {} }}
/>,
)
await screen.findByPlaceholderText('Search…')
await expectNoA11yViolations(document.body)
})
})
})
+302 -442
View File
@@ -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<HTMLDivElement>,
'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<Multiple extends boolean | undefined = false> = SelectBaseProps<Multiple> & {
/** 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<typeof Tooltip>['icon']
helpText?: string
actionButton?: { label: string; onClick: () => void; icon?: ReactNode }
renderOption?: (opt: SelectOption) => ReactNode
onBlur?: (e: ReactFocusEvent<HTMLDivElement>) => 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<HTMLDivElement, FeaturedSelectProps>(
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<string, unknown>, [
'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<SelectSize, [string, string]> = {
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<SelectSize, string> = { 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 (
<FieldLabel
nativeLabel={false}
required={required}
className={cn(
'pointer-events-none absolute z-10 max-w-[calc(100%-4rem)] truncate font-normal text-fg-muted',
'transition-[top,left,font-size,color] duration-150 ease-out motion-reduce:transition-none',
floated
? cn('top-0 -translate-y-1/2 px-1 text-xs leading-4 font-medium', FLOAT_LEFT[size], FLOATING_LABEL_BG[variant])
: cn('top-1/2 -translate-y-1/2', size === 'lg' ? 'text-base' : 'text-sm', REST_LEFT[size][hasStartIcon ? 1 : 0]),
floated && open && !invalid && 'text-primary-700 dark:text-primary-300',
invalid && 'text-danger-600 dark:text-danger-400',
)}
>
{children}
</FieldLabel>
)
}
// `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<Multiple extends boolean | undefined = false>({
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<Multiple>) {
const empty = (multiple ? [] : null) as SelectValue<Multiple>
const [value, setValue] = useControllableState<SelectValue<Multiple>>(
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<Record<string, string>>({})
const wrapperRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const dropdownRef = useRef<HTMLDivElement>(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<HTMLElement>('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<HTMLDivElement>) => {
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 && (
<span aria-hidden="true" className="flex shrink-0 text-fg-muted">
{startIcon}
</span>
)}
{valueNode}
{showClear && <span aria-hidden="true" className={cn('shrink-0', CLEAR_SPACER[size])} />}
{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 && (
<FloatingLabel
floated={floated}
open={open}
invalid={invalid}
size={size}
variant={variant}
hasStartIcon={startIcon != null}
required={required}
>
{label}
</FloatingLabel>
)
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 && (
<ClearButton
size={size}
label={typeof label === 'string' ? `Clear ${label}` : 'Clear selection'}
onClear={clear}
/>
)
// 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 && <ActionFooter action={actionButton} onDone={() => setOpen(false)} />
useClickOutside(
[containerRef, dropdownRef],
() => {
setIsOpen(false)
setIsFocused(false)
},
isOpen,
)
const field = (children: ReactNode) => (
<Field
description={description}
error={error}
required={required}
disabled={disabled}
name={name}
nativeLabel={false}
className={className}
>
{children}
</Field>
)
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 = (
<div
ref={dropdownRef}
style={{
position: 'fixed',
top: dropdownPosition.top,
bottom: dropdownPosition.bottom,
left: dropdownPosition.left,
width: dropdownPosition.width,
maxHeight: dropdownPosition.maxHeight,
zIndex: 10000,
}}
className="bg-white border border-gray-200 rounded-lg shadow-xl overflow-auto"
role="listbox"
aria-expanded={isOpen}
>
{searchable && (
<div className="sticky top-0 z-10 p-2 bg-white border-b border-gray-200">
<input
autoFocus
type="text"
className={cn(
'w-full px-2 py-1 text-sm border rounded focus:outline-none',
themeClasses.searchFocus,
)}
placeholder="Search..."
value={searchTerm}
onChange={(e) => {
const next = e.target.value
setSearchTerm(next)
onSearchChange?.(next)
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
{filteredOptions.length > 0 ? (
filteredOptions.map((opt) => {
const isSelected = opt.value === value
return (
<div
key={opt.value}
role="option"
aria-selected={isSelected}
data-selected={scrollToSelected && isSelected ? 'true' : undefined}
className={cn(
'px-3 py-2 text-sm transition-colors',
opt.disabled
? 'text-slate-300 cursor-not-allowed bg-slate-50/30'
: 'cursor-pointer',
isSelected && !opt.disabled
? themeClasses.selected
: !opt.disabled && 'text-gray-700 hover:bg-gray-50',
)}
onClick={() => !opt.disabled && handleSelect(opt.value)}
>
{renderOption ? renderOption(opt) : opt.label}
</div>
)
})
) : (
!isLoading && (
<div className="px-3 py-4 text-sm text-center text-gray-500">No options found</div>
if (searchable) {
return field(
<BaseCombobox.Root
items={comboboxItems(options, grouped)}
multiple={multiple}
value={(multiple ? selectedOptions : (selectedOptions[0] ?? null)) as never}
onValueChange={(next) => {
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<Multiple>,
)
)}
{isLoading && filteredOptions.length > 0 && (
<div className="px-3 py-3 text-center border-t border-gray-200 bg-gray-50/50 flex items-center justify-center gap-2">
<Spinner size="xs" />
<span className="text-[11px] text-gray-500 font-medium tracking-wide">
LOADING MORE...
</span>
</div>
)}
{actionButton && (
<div className="p-2">
<button
type="button"
onClick={(e) => {
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}
</button>
</div>
)}
</div>
)
return (
<div
ref={containerRef}
className={cn(
'relative outline-none',
// Matches the underlined variant's need for room for the floated label.
isUnderlined && 'mt-4',
SELECT_WIDTHS[width] ?? SELECT_WIDTHS.full,
className,
)}
tabIndex={disabled ? -1 : 0}
onKeyDown={(e: KeyboardEvent<HTMLDivElement>) => {
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}
>
<div
onClick={handleToggle}
className={cn(
'relative flex items-center justify-between transition-all duration-200',
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
SELECT_SIZES[size] ?? SELECT_SIZES.md,
SELECT_VARIANTS[variant] ?? SELECT_VARIANTS.outlined,
'bg-transparent',
isUnderlined ? '' : 'rounded',
(isFocused || isOpen)
? cn('border', isUnderlined ? themeClasses.focus.split(' ')[0] : themeClasses.focus,
isUnderlined ? '' : 'ring-1')
: 'border border-slate-300',
!disabled && !isOpen && !isFocused && themeClasses.hover,
errorMessage && 'border-red-500 ring-red-500',
disabled && 'bg-gray-100 cursor-not-allowed opacity-60',
)}
>
{/* 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. */}
<span className={cn('block truncate px-0.5', !displayLabel && 'text-transparent')}>
{displayLabel || placeholder}
</span>
<div className="flex items-center gap-2">
{isLoading && <Spinner size="xs" />}
{isClearable && hasValue && !disabled && (
<X
className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-pointer z-20"
onClick={(e) => {
e.stopPropagation()
// onSearchChange first, so a consumer that sets its own term
// inside onChange still wins.
onSearchChange?.('')
onChange?.('')
setSearchTerm('')
setHasUserSelected(true)
}}
/>
<div ref={wrapperRef} className="relative">
<BaseCombobox.Trigger {...triggerProps}>
{triggerInner(
<span className={valueClass}>{display}</span>,
<BaseCombobox.Icon className="flex shrink-0 text-fg-muted">
{loading ? <Spinner /> : <Chevron />}
</BaseCombobox.Icon>,
)}
{isOpen ? (
<ChevronUp className="h-4 w-4 text-gray-500" />
) : (
<ChevronDown className="h-4 w-4 text-gray-500" />
)}
</div>
{label && (
<label
className={cn(
'absolute transition-all duration-200',
// Only `left` is set, so the label shrink-wraps to the field and a
// long one wraps to a second line — floated, that line carries the
// label's own opaque background over the selected value. Keep it on
// one line and ellipsize.
'max-w-[calc(100%-1.5rem)] truncate',
isUnderlined ? 'left-0' : 'left-2',
labelClass,
)}
>
<span className="flex items-center gap-1.5">
<span className="truncate">
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</span>
{(tooltip || helpText) && (
<span
className="pointer-events-auto inline-flex shrink-0"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.preventDefault()}
>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
</label>
)}
</BaseCombobox.Trigger>
{label_}
{clearButton}
</div>
{isOpen && !disabled && createPortal(dropdownContent, document.body)}
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
<BaseCombobox.Portal>
<BaseCombobox.Positioner side={side} sideOffset={6} className="z-50 outline-none">
<BaseCombobox.Popup
aria-label={typeof label === 'string' ? label : 'Options'}
className={popupClass()}
>
<div className="shrink-0 border-b border-border p-1.5">
<div className="relative flex items-center">
<Search aria-hidden="true" className="pointer-events-none absolute left-2.5 size-4 text-fg-muted" />
<BaseCombobox.Input
placeholder={searchPlaceholder}
className="h-8 w-full rounded-md bg-surface-sunken pr-2.5 pl-8 text-sm text-fg outline-hidden placeholder:text-fg-muted focus-visible:outline-2 focus-visible:outline-offset-0 focus-visible:outline-primary-500"
/>
</div>
</div>
<BaseCombobox.Status>{loading && <StatusRow loading>{loadingText}</StatusRow>}</BaseCombobox.Status>
<BaseCombobox.Empty>{!loading && <StatusRow>{emptyText}</StatusRow>}</BaseCombobox.Empty>
<ComboboxOptions grouped={grouped} isSelected={(v) => selected.has(v)} renderOption={renderOption} />
{footer}
</BaseCombobox.Popup>
</BaseCombobox.Positioner>
</BaseCombobox.Portal>
</BaseCombobox.Root>,
)
},
)
}
export default FeaturedSelect
return field(
<BaseSelect.Root
items={options}
multiple={multiple}
value={value as never}
onValueChange={(next) => setValue(next as SelectValue<Multiple>)}
open={open}
onOpenChange={setOpen}
name={name}
required={required}
disabled={disabled}
readOnly={readOnly}
>
<div ref={wrapperRef} className="relative">
<BaseSelect.Trigger {...triggerProps}>
{triggerInner(
<BaseSelect.Value className={valueClass}>{() => display}</BaseSelect.Value>,
<BaseSelect.Icon className="flex shrink-0 text-fg-muted">
{loading ? <Spinner /> : <Chevron />}
</BaseSelect.Icon>,
)}
</BaseSelect.Trigger>
{label_}
{clearButton}
</div>
<BaseSelect.Portal>
{/* Transparent: marks the modal popup's page as inert to pointers and to assistive checks. */}
<BaseSelect.Backdrop className="fixed inset-0 z-50" />
<BaseSelect.Positioner side={side} sideOffset={6} alignItemWithTrigger={false} className="z-50 outline-none">
<BaseSelect.Popup className={popupClass()}>
{loading && <StatusRow loading>{loadingText}</StatusRow>}
{!loading && options.length === 0 && <StatusRow>No options</StatusRow>}
<BaseSelect.List aria-busy={loading || undefined} className={listClass}>
{!loading && (
<SelectOptions options={options} isSelected={(v) => selected.has(v)} renderOption={renderOption} />
)}
</BaseSelect.List>
{footer}
</BaseSelect.Popup>
</BaseSelect.Positioner>
</BaseSelect.Portal>
</BaseSelect.Root>,
)
}
+170
View File
@@ -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) => (
<div className="max-w-md">
<Story />
</div>
),
],
} satisfies Meta<typeof FeaturedTextArea>
export default meta
type Story = StoryObj<typeof meta>
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) => (
<div className="grid gap-5">
{TEXT_FIELD_VARIANTS.map((variant) => (
<div key={variant} className="grid gap-3">
<FeaturedTextArea {...args} variant={variant} rows={2} label={`${variant[0].toUpperCase()}${variant.slice(1)}, empty`} />
<FeaturedTextArea
{...args}
variant={variant}
rows={2}
label={`${variant[0].toUpperCase()}${variant.slice(1)}, filled`}
defaultValue="Ring the bell twice."
/>
</div>
))}
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<div key={size} className="grid grid-cols-2 gap-3">
<FeaturedTextArea {...args} size={size} rows={2} label={`Size ${size}`} />
<FeaturedTextArea {...args} size={size} rows={2} label={`Size ${size}`} defaultValue="Jane Doe" />
</div>
))}
</div>
),
}
export const Uncontrolled: Story = {
args: { defaultValue: note, maxLength: 280 },
}
function ControlledFeaturedTextArea(args: Story['args']) {
const [value, setValue] = useState('Ring the bell twice.')
return (
<div className="grid gap-2">
<FeaturedTextArea
{...args}
maxLength={200}
value={value}
onValueChange={(next) => {
setValue(next)
args?.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Value: {value || '(empty)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledFeaturedTextArea {...args} />,
}
+56
View File
@@ -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(<FeaturedTextArea label="Delivery instructions" />)
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(<FeaturedTextArea label="Notes" description="Shared with the courier." />)
expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Shared with the courier.')
rerender(<FeaturedTextArea label="Notes" description="Shared with the courier." error="Add instructions." />)
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(<FeaturedTextArea label="Notes" required />)
expect(screen.getByRole('textbox', { name: 'Notes' })).toBeRequired()
})
it('works uncontrolled', async () => {
render(<FeaturedTextArea label="Notes" defaultValue="Ring twice" />)
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(<FeaturedTextArea label="Notes" value="Ring" onValueChange={onValueChange} />)
await userEvent.type(screen.getByRole('textbox'), '!')
expect(onValueChange).toHaveBeenLastCalledWith('Ring!')
expect(screen.getByRole('textbox')).toHaveValue('Ring')
})
it('counts characters', async () => {
render(<FeaturedTextArea label="Notes" maxLength={200} />)
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(
<FeaturedTextArea label="Notes" description="Optional." required maxLength={100} defaultValue="Hi" />,
)
await expectNoA11yViolations(container)
})
})
+12
View File
@@ -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 <TextAreaField {...props} floating />
}
+104
View File
@@ -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 (
<div className="flex items-center gap-2">
<span aria-hidden="true" className={cn('size-8 shrink-0 rounded-md border border-border', swatch, disabled && 'opacity-55')} />
<BaseInput
defaultValue={defaultValue}
required={required}
disabled={disabled}
spellCheck={false}
className={cn(controlBox, controlHeight.md, focusRing, 'w-32 px-3 font-mono uppercase focus-visible:outline-solid')}
/>
</div>
)
}
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) => (
<Field {...args} className={cn('max-w-sm', args.className)}>
<HexInput required={args.required} disabled={args.disabled} />
</Field>
),
} satisfies Meta<typeof Field>
export default meta
type Story = StoryObj<typeof meta>
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) => (
<div className="grid max-w-sm gap-5">
<Field {...args} label="Primary colour" description="Buttons and links." required>
<HexInput required />
</Field>
<Field {...args} label="Accent colour" description={undefined} error="Enter a six-digit hex colour, like #F59E0B.">
<HexInput defaultValue="#F59E0" swatch="bg-warning-400" />
</Field>
</div>
),
}
+96
View File
@@ -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 (
<BaseField.Root
name={name}
disabled={disabled}
invalid={invalid}
className={cn('flex flex-col gap-1.5', className)}
>
{label != null && (
<FieldLabel required={required} nativeLabel={nativeLabel}>
{label}
</FieldLabel>
)}
{children}
{description != null && !invalid && (
<BaseField.Description className={descriptionText}>{description}</BaseField.Description>
)}
{invalid && (
<BaseField.Error match className={errorText}>
{error}
</BaseField.Error>
)}
</BaseField.Root>
)
}
/** 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 (
<BaseField.Label
nativeLabel={nativeLabel}
render={nativeLabel ? undefined : <div />}
className={cn(labelText, 'data-disabled:opacity-55', className)}
>
{children}
{required && (
<span aria-hidden="true" className={requiredMark}>
*
</span>
)}
</BaseField.Label>
)
}
+96 -103
View File
@@ -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) => (
<div className="max-w-sm">
<Story />
</div>
),
],
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: '[email protected]',
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<typeof Input>
export default meta
type Story = StoryObj<typeof meta>
function ControlledInput({
initial = '',
...args
}: React.ComponentProps<typeof Input> & { initial?: string }) {
const [value, setValue] = useState(initial)
return <Input {...args} value={value} onChange={(e) => 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 [email protected].' },
}
export const Required: Story = {
args: { required: true },
}
export const Disabled: Story = {
args: { disabled: true, defaultValue: '[email protected]' },
}
export const ReadOnly: Story = {
args: { readOnly: true, defaultValue: '[email protected]', description: 'Managed by your identity provider.' },
}
export const Variants: Story = {
render: (args) => (
<div className="max-w-md">
<ControlledInput {...args} />
</div>
),
}
export const Types: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
<Input label="Full name" placeholder="Jane Doe" />
<Input label="Email" type="email" placeholder="[email protected]" />
<Input label="Phone" type="tel" placeholder="+91 98450 00000" />
<Input label="Annual CTC" type="number" placeholder="1200000" />
<Input label="Website" type="url" placeholder="https://example.com" />
<Input label="Joining date" type="date" />
<div className="grid gap-5">
<Input {...args} variant="outline" label="Outline" />
<Input {...args} variant="filled" label="Filled" />
<Input {...args} variant="underline" label="Underline" />
</div>
),
}
export const Sizes: Story = {
render: () => (
<div className="flex max-w-md flex-col gap-5">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledInput key={size} size={size} label={`Size ${size}`} placeholder="Enter a value" />
))}
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
<ControlledInput key={theme} theme={theme} label={theme} placeholder="Focus me" />
))}
</div>
),
}
export const WithError: Story = {
render: () => (
<div className="max-w-md">
<Input
label="PAN number"
placeholder="ABCDE1234F"
error="Enter a valid PAN number."
/>
</div>
),
}
export const Required: Story = {
render: () => (
<div className="max-w-md">
<Input label="Entity name" required placeholder="Required field" />
</div>
),
}
export const Disabled: Story = {
render: () => (
<div className="max-w-md">
<Input label="Entity ID" value="ENT-000142" disabled onChange={() => {}} />
</div>
),
}
export const BorderStyles: Story = {
render: () => (
<div className="grid max-w-xl gap-5 sm:grid-cols-3">
<Input label="Default" placeholder="Solid" />
<Input label="Dashed" placeholder="Dashed" dashedBorder />
<Input label="Pill" placeholder="Rounded" roundedFull />
</div>
),
}
/** 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) => (
<div className="max-w-md">
<Input {...args} label="Email" />
<div className="grid gap-5">
{SIZES.map((size) => (
<Input key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const WithIcons: Story = {
render: (args) => (
<div className="grid gap-5">
<Input {...args} label="Search" type="search" placeholder="Search employees" startIcon={<Search />} />
<Input {...args} label="Username" type="text" placeholder="jane" endIcon={<AtSign />} />
</div>
),
}
export const WithAddons: Story = {
render: (args) => (
<div className="grid gap-5">
<Input {...args} label="Website" type="text" placeholder="example" startAddon="https://" endAddon=".com" />
<Input {...args} label="Amount" type="number" placeholder="0.00" startAddon="$" endAddon="USD" />
</div>
),
}
function ControlledInput(args: Story['args']) {
const [value, setValue] = useState('Jane Doe')
return (
<div className="grid gap-2">
<Input {...args} label="Full name" type="text" value={value} onValueChange={setValue} />
<p className="text-sm text-fg-muted">Value: {value || '(empty)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledInput {...args} />,
}
+64
View File
@@ -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(<Input label="Work email" />)
expect(screen.getByRole('textbox', { name: 'Work email' })).toBeInTheDocument()
})
it('announces the description with the input', () => {
render(<Input label="Work email" description="Payslips go here." />)
expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Payslips go here.')
})
it('marks the input invalid and announces the error', () => {
render(<Input label="Work email" error="Enter a full email address." description="Hidden while invalid" />)
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(<Input label="Name" defaultValue="Jane" />)
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(<Input label="Name" value="Jane" onValueChange={onValueChange} />)
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(<Input label="Name" required disabled />)
expect(screen.getByRole('textbox')).toBeRequired()
expect(screen.getByRole('textbox')).toBeDisabled()
})
it('gives each input a unique id without a name', () => {
render(
<>
<Input label="First" />
<Input label="Second" />
</>,
)
const [a, b] = screen.getAllByRole('textbox')
expect(a.id).not.toBe(b.id)
})
it('has no axe violations', async () => {
const { container } = render(
<Input label="Website" description="Your public site." startAddon="https://" endIcon={<svg />} required />,
)
await expectNoA11yViolations(container)
})
})
+102 -135
View File
@@ -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<InputHTMLAttributes<HTMLInputElement>, '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<ComponentProps<'input'>, '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<HTMLInputElement, InputProps>(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<string, unknown>, ['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 (
<div className="flex flex-col w-full">
{label && (
<label
htmlFor={name}
className={cn('inline-block text-left w-full text-gray-800', LABEL_SIZES[size] ?? LABEL_SIZES.md)}
>
{label} {required && <span className="text-red-500">*</span>}
</label>
)}
<div className="relative flex items-center">
{icon && iconPosition === 'left' && (
<i
aria-hidden="true"
className={cn(
'absolute left-3 top-1/2 text-gray-900 transform -translate-y-1/2 pointer-events-none',
ICON_SIZES[size],
icon,
)}
/>
<Field
label={label}
description={description}
error={error}
required={required}
disabled={disabled}
name={name}
className={className}
>
<div
className={cn(
'flex w-full items-stretch overflow-hidden',
controlHeight[size],
iconSize[size],
variant === 'outline' ? cn(controlBox, 'has-[[aria-invalid=true]]:border-danger-500') : variants[variant],
focusWithinRing,
variant === 'underline' && 'has-[:focus-visible]:outline-offset-0',
)}
<input
id={name}
ref={ref}
type={type}
name={name}
autoComplete="off"
required={required}
disabled={disabled}
placeholder={placeholder}
aria-invalid={Boolean(errorMessage)}
className={cn(
'w-full bg-white text-gray-800 placeholder:text-slate-400 placeholder:font-medium',
'focus:outline-none transition duration-150',
'disabled:bg-gray-200 disabled:border-slate-300 disabled:text-slate-400 disabled:cursor-not-allowed',
// Indent to clear a leading icon.
icon ? (iconPosition === 'left' ? 'pl-9' : 'pr-10') : 'pl-3',
roundedFull ? 'rounded-full' : 'rounded',
dashedBorder ? 'border-dashed' : 'border',
'border',
INPUT_SIZES[size] ?? INPUT_SIZES.md,
// Error wins over the theme's focus colours.
errorMessage
? 'border-red-500 focus:border-red-500 focus:ring-red-500'
: cn('border-slate-300', INPUT_THEMES[theme] ?? INPUT_THEMES.primary),
className,
)}
{...htmlProps}
/>
{icon && iconPosition === 'right' && (
<i
aria-hidden="true"
className={cn(
'absolute right-3 top-1/2 text-gray-900 transform -translate-y-1/2 pointer-events-none',
ICON_SIZES[size],
icon,
)}
/>
)}
{trailing && (
<span className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center">
{trailing}
>
{startAddon != null && <span className={cn(addon, 'border-r border-border')}>{startAddon}</span>}
{startIcon != null && (
<span aria-hidden="true" className="flex items-center pl-3 text-fg-subtle">
{startIcon}
</span>
)}
<BaseInput
required={required}
disabled={disabled}
onValueChange={onValueChange ? (value) => 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 && (
<span aria-hidden="true" className="flex items-center pr-3 text-fg-subtle">
{endIcon}
</span>
)}
{endAddon != null && <span className={cn(addon, 'border-l border-border')}>{endAddon}</span>}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-start text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
</Field>
)
})
export default Input
}
+102
View File
@@ -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 `<kbd>` 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<typeof Kbd>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const SingleKeys: Story = {
args: { keys: undefined },
render: (args) => (
<div className="flex flex-wrap items-center gap-2">
{['Esc', 'Tab', '⇧', '⌘', '⌥', '↵', '⌫', '↑', '↓', 'A', '/'].map((k) => (
<Kbd key={k} size={args.size}>
{k}
</Kbd>
))}
</div>
),
}
export const Combinations: Story = {
render: (args) => (
<div className="grid gap-3">
<div className="flex flex-wrap items-center gap-4">
<Kbd {...args} keys={['⌘', 'K']} />
<Kbd {...args} keys={['⌘', '⇧', 'P']} />
<Kbd {...args} keys={['Ctrl', 'Alt', 'Delete']} />
</div>
<div className="flex flex-wrap items-center gap-4">
<Kbd {...args} keys={['⌘', 'K']} separator={null} />
<Kbd {...args} keys={['G', 'I']} separator="then" />
</div>
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-wrap items-center gap-4">
{SIZES.map((size) => (
<Kbd key={size} {...args} size={size} />
))}
</div>
),
}
export const InContext: Story = {
parameters: { docs: { description: { story: 'Shortcut hints in a search field and a shortcut list.' } } },
render: () => (
<div className="grid max-w-md gap-5">
<div className="flex h-10 items-center justify-between rounded-lg border border-border-strong bg-surface px-3 text-sm text-fg-muted">
Search components…
<Kbd keys={['⌘', 'K']} separator={null} size="sm" />
</div>
<dl className="divide-y divide-border rounded-xl border border-border bg-surface text-sm">
{[
['Open command palette', ['⌘', 'K']],
['Toggle dark mode', ['⌘', '⇧', 'L']],
['Go to inbox', ['G', 'I']],
['Close dialog', ['Esc']],
].map(([action, keys]) => (
<div key={action as string} className="flex items-center justify-between px-4 py-2.5">
<dt className="text-fg">{action as string}</dt>
<dd>
<Kbd keys={keys as string[]} size="sm" />
</dd>
</div>
))}
</dl>
<p className="text-sm text-fg-muted">
Press <Kbd size="sm">/</Kbd> to focus search, or <Kbd size="sm">?</Kbd> to see every shortcut.
</p>
</div>
),
}
+35
View File
@@ -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(<Kbd>Esc</Kbd>)
expect(container.querySelector('kbd')).toHaveTextContent('Esc')
})
it('renders a combination as nested kbd elements with separators', () => {
const { container } = render(<Kbd keys={['⌘', 'K']} />)
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(<Kbd keys={['⇧', 'P']} separator={null} />)
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(
<p>
Press <Kbd keys={['⌘', 'K']} /> or <Kbd>/</Kbd>
</p>,
)
await expectNoA11yViolations(container)
})
})
+54
View File
@@ -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 (
<>
<span aria-hidden="true">{value}</span>
<span className="sr-only">{spoken}</span>
</>
)
}
/** Displays a keyboard key or a shortcut such as ⌘ K. */
export function Kbd({ keys, separator = '+', size = 'md', className, children, ...props }: KbdProps) {
if (!keys) {
return (
<kbd className={cn(keyCap, KBD_SIZES[size], className)} {...props}>
{typeof children === 'string' ? <KeyLabel value={children} /> : children}
</kbd>
)
}
return (
<kbd className={cn('inline-flex items-center font-sans', KBD_GAP[size], className)} {...props}>
{keys.map((key, i) => (
<Fragment key={`${key}-${i}`}>
{i > 0 && separator != null && separator !== '' && (
<span className="text-xs text-fg-muted">
{separator}
</span>
)}
<kbd className={cn(keyCap, KBD_SIZES[size])}>
<KeyLabel value={key} />
</kbd>
</Fragment>
))}
</kbd>
)
}
+161
View File
@@ -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 `<select>` 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 `<optgroup>`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 }) => (
<div
className={
parameters.wide
? 'max-w-3xl rounded-xl border border-border bg-surface p-6'
: 'max-w-sm rounded-xl border border-border bg-surface p-6'
}
>
<Story />
</div>
),
],
} satisfies Meta<typeof NativeSelect>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<NativeSelect key={size} {...args} size={size} label={`Size ${size}`} defaultValue="eng" />
))}
</div>
),
}
export const Variants: Story = {
render: (args) => (
<div className="grid gap-5">
{SELECT_VARIANTS.map((variant) => (
<NativeSelect key={variant} {...args} variant={variant} label={variant === 'outline' ? 'Outline' : 'Filled'} />
))}
</div>
),
}
/** NativeSelect and Input share control heights. */
export const AlignedWithInput: Story = {
parameters: { wide: true },
render: (args) => (
<div className="grid gap-4">
{SIZES.map((size) => (
<div key={size} className="flex items-end gap-3">
<Input label={`Name (${size})`} size={size} placeholder="Jane Doe" className="w-56" />
<NativeSelect {...args} size={size} className="w-56" />
</div>
))}
</div>
),
}
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 `<optgroup>`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: <Globe /> },
}
/** 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 (
<div className="grid gap-2">
<NativeSelect {...args} options={DEPARTMENTS} value={value} onValueChange={setValue} />
<p className="text-sm text-fg-muted">Value: {value || '(none)'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledNativeSelect {...args} />,
}
export const Uncontrolled: Story = {
args: { defaultValue: 'sales', name: 'department' },
}
+94
View File
@@ -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(<NativeSelect label="Department" options={plain} />)
expect(screen.getByRole('combobox', { name: 'Department' })).toBeInTheDocument()
})
it('renders groups as optgroups and a placeholder option', () => {
render(<NativeSelect label="Currency" placeholder="Choose a currency" options={currencies} />)
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(<NativeSelect label="Department" options={plain} onValueChange={onValueChange} onChange={onChange} />)
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 (
<>
<NativeSelect label="Department" options={plain} value={value} onValueChange={setValue} />
<p data-testid="value">{value}</p>
</>
)
}
render(<Controlled />)
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(<NativeSelect label="Department" description="Where they report." options={plain} />)
expect(screen.getByRole('combobox')).toHaveAccessibleDescription('Where they report.')
rerender(<NativeSelect label="Department" description="Where they report." error="Choose one." options={plain} />)
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(<NativeSelect label="Department" name="department" required disabled options={plain} />)
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(<NativeSelect label="Department" loading options={plain} />)
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(
<NativeSelect label="Currency" description="Used on payslips." placeholder="Choose" required options={currencies} />,
)
await expectNoA11yViolations(container)
})
})
+134 -179
View File
@@ -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 `<select>`.
*
* 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<HTMLSelectElement>,
'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 `<optgroup>`. */
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<HTMLSelectElement, NativeSelectProps>(
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<SelectSize, string> = { sm: 'pl-8', md: 'pl-9', lg: 'pl-11' }
const END_PAD: Record<SelectSize, string> = { sm: 'pr-8', md: 'pr-9', lg: 'pr-11' }
const ICON_LEFT: Record<SelectSize, string> = { sm: 'left-2.5', md: 'left-3', lg: 'left-4' }
const ICON_RIGHT: Record<SelectSize, string> = { sm: 'right-2.5', md: 'right-3', lg: 'right-4' }
// Strip props that must not reach the DOM node.
const htmlProps = omit(props as Record<string, unknown>, [
'shrink', 'helpText', 'helperText', 'tooltip', 'tooltipIcon', 'control', 'allValues',
'isDynamic', 'valueKey', 'labelKey', 'endpoint', 'endpointParams',
'isMulti', 'searchable', 'infiniteScroll', 'hasMore', 'hasMoreKey',
'onMenuScroll', 'onSearchChange', 'initialSearch', 'initialSearchTerm',
'initialQuery', 'debounceTime', 'actionButton', 'isEditMode', 'isClearable',
'themeColor', 'sizeClass', 'variantClass', 'widthClass', 'floatinglabelClass',
'renderOption', 'placement', 'scrollToSelected',
])
/**
* A styled native `<select>`, with its label above. It uses the platform's
* own picker, which suits mobile and simple forms. For search, multiple
* values or rich options, use Select, FeaturedSelect or Combobox.
*/
export function NativeSelect({
label,
description,
error,
required,
disabled,
size = 'md',
variant = 'outline',
options,
placeholder,
value,
defaultValue,
onValueChange,
loading,
startIcon,
name,
className,
selectClassName,
...props
}: NativeSelectProps) {
const invalid = error != null && error !== false && error !== ''
// Without a placeholder, an uncontrolled select starts on its first option.
const initial = defaultValue ?? (placeholder != null && value === undefined ? '' : undefined)
const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary
const errorMessage = typeof error === 'string' ? error : error?.message
const handleChange = (e: ChangeEvent<HTMLSelectElement>) => onChange?.(e.target.value)
const handleClear = (e: React.MouseEvent) => {
e.stopPropagation()
e.preventDefault()
onChange?.('')
}
// Deliberately explicit rather than `isClearable && value && ...`: a numeric 0
// is a legitimate selection, and `&&` on a falsy number yields the number
// itself, which React renders as stray text in the icon slot (IP-3617).
const showClear =
isClearable && !disabled && value !== '' && value !== null && value !== undefined
return (
<div className={cn('relative w-full', SELECT_WIDTHS[width] ?? SELECT_WIDTHS.full, className)}>
{label && (
<label
htmlFor={name}
className={cn('block text-gray-800 font-medium mb-1', LABEL_SIZES[size] ?? LABEL_SIZES.md)}
return (
<Field
label={label}
description={description}
error={error}
required={required}
disabled={disabled || loading}
name={name}
className={className}
>
<div className={cn('relative w-full', iconSize[size])}>
{startIcon != null && (
<span
aria-hidden="true"
className={cn('pointer-events-none absolute top-1/2 flex -translate-y-1/2 text-fg-muted', ICON_LEFT[size])}
>
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</label>
{startIcon}
</span>
)}
<div className="relative">
<select
id={name}
name={name}
value={value}
disabled={disabled}
required={required}
aria-invalid={Boolean(errorMessage)}
onChange={handleChange}
onFocus={(e: FocusEvent<HTMLSelectElement>) => {
setIsFocused(true)
onFocus?.(e)
}}
onBlur={(e: FocusEvent<HTMLSelectElement>) => {
setIsFocused(false)
onBlur?.(e)
}}
ref={ref}
className={cn(
'appearance-none block w-full pl-3 pr-10 bg-white text-gray-700 font-medium',
'focus:outline-none transition duration-150 ease-in-out',
SELECT_SIZES[size] ?? SELECT_SIZES.md,
SELECT_VARIANTS[variant] ?? SELECT_VARIANTS.outlined,
// Border/ring colour utilities are written per element: a `border-red-500`
// class would otherwise be stripped by Tailwind's tree as redundant.
isFocused
? ['border', themeClasses.focus]
: 'border border-slate-300',
isFocused && 'ring-1',
disabled && 'bg-gray-200 cursor-not-allowed opacity-70',
errorMessage && 'border-red-500 ring-red-500 focus:border-red-500 focus:ring-red-500',
variant !== 'underlined' && 'rounded',
)}
{...htmlProps}
>
<option value="" disabled hidden>
{placeholder}
</option>
{options.map((opt) => (
<option key={opt.value} value={opt.value} disabled={opt.disabled}>
{opt.label}
</option>
))}
</select>
<div className="absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
{showClear && (
<X
className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-pointer z-20 mr-1"
onClick={handleClear}
/>
)}
<div className="pointer-events-none flex items-center">
{isLoading ? (
<Spinner size="xs" />
) : (
<ChevronDown className={cn('h-4 w-4', !isFocused && 'opacity-50')} />
<BaseField.Control
value={value}
defaultValue={initial}
onValueChange={onValueChange ? (next) => onValueChange(next) : undefined}
required={required}
aria-invalid={invalid || undefined}
aria-busy={loading || undefined}
render={(controlProps) => (
<select {...controlProps}>
{placeholder != null && (
<option value="" disabled={required}>
{placeholder}
</option>
)}
</div>
</div>
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
{groupOptions(options).map((group) => {
const items = group.items.map((option) => (
<option key={option.value} value={option.value} disabled={option.disabled}>
{option.label}
</option>
))
return group.label === null ? (
items
) : (
<optgroup key={group.label} label={group.label}>
{items}
</optgroup>
)
})}
</select>
)}
className={cn(
'w-full cursor-pointer appearance-none truncate',
controlHeight[size],
controlPaddingX[size],
FIELD_BOX[variant],
focusRing,
END_PAD[size],
startIcon != null && START_ICON_PAD[size],
'has-[option[value=""]:checked]:text-fg-muted [&_optgroup]:bg-surface [&_optgroup]:text-fg-muted [&_option]:bg-surface [&_option]:text-fg',
'disabled:cursor-not-allowed disabled:opacity-55',
selectClassName,
)}
{...(props as ComponentProps<typeof BaseField.Control>)}
/>
<span
aria-hidden="true"
className={cn('pointer-events-none absolute top-1/2 flex -translate-y-1/2 text-fg-muted', ICON_RIGHT[size])}
>
{loading ? <Spinner /> : <Chevron />}
</span>
</div>
)
},
)
export default NativeSelect
</Field>
)
}
+161
View File
@@ -0,0 +1,161 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { useState } from 'react'
import { fn } from 'storybook/test'
import { SIZES } from '../lib/styles'
import { NumberInput } from './NumberInput'
const meta = {
title: 'Forms/NumberInput',
component: NumberInput,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'A number field built on Base UI NumberField. Typing is parsed and formatted with `Intl.NumberFormat` (`format`), ↑ / ↓ step by `step` (Shift for 10×), Home / End jump to `min` / `max`, and the − / + buttons do the same with a pointer. Values clamp to `min` and `max`. The value is a `number`, or `null` when empty.',
},
},
},
argTypes: {
label: { control: 'text' },
description: { control: 'text' },
error: { control: 'text' },
size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
min: { control: 'number' },
max: { control: 'number' },
step: { control: 'number', table: { defaultValue: { summary: '1' } } },
value: { control: 'number' },
defaultValue: { control: 'number' },
format: { control: 'object' },
locale: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
readOnly: { control: 'boolean' },
startAddon: { control: 'text' },
endAddon: { control: 'text' },
name: { control: 'text' },
className: { control: 'text' },
inputClassName: { control: 'text' },
onValueChange: { control: false },
},
args: {
label: 'Seats',
defaultValue: 5,
min: 1,
max: 100,
step: 1,
size: 'md',
required: false,
disabled: false,
readOnly: false,
onValueChange: fn(),
},
decorators: [
(Story) => (
<div className="max-w-xs">
<Story />
</div>
),
],
} satisfies Meta<typeof NumberInput>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const WithDescription: Story = {
args: { description: 'Acme Corporation’s plan includes up to 100 seats.' },
}
export const WithError: Story = {
args: { defaultValue: 0, min: 0, error: 'Add at least one seat.' },
}
export const Required: Story = {
args: { required: true, defaultValue: null },
}
export const Disabled: Story = {
args: { disabled: true },
}
export const ReadOnly: Story = {
args: { readOnly: true, description: 'Seats are managed by your billing admin.' },
}
export const Empty: Story = {
args: { defaultValue: null, label: 'Quantity' },
}
export const CurrencyFormatting: Story = {
args: {
label: 'Monthly budget',
defaultValue: 1250.5,
min: 0,
max: 1000000,
step: 50,
format: { style: 'currency', currency: 'USD' },
locale: 'en-US',
description: 'Steps by $50. Shift + ↑ steps by $500.',
},
}
export const PercentFormatting: Story = {
args: {
label: 'Discount',
defaultValue: 0.15,
min: 0,
max: 1,
step: 0.05,
format: { style: 'percent' },
locale: 'en-US',
},
}
export const WithAddons: Story = {
render: (args) => (
<div className="grid gap-5">
<NumberInput {...args} label="Price" startAddon="$" endAddon="USD" defaultValue={49} min={0} max={10000} />
<NumberInput {...args} label="Weight" endAddon="kg" defaultValue={2.5} step={0.5} min={0} max={50} />
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<NumberInput key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const Uncontrolled: Story = {
args: { label: 'Guests', defaultValue: 2, min: 1, max: 12 },
}
function ControlledNumberInput(args: Story['args']) {
const [value, setValue] = useState<number | null>(12)
return (
<div className="grid gap-2">
<NumberInput
{...args}
label="Licences"
value={value}
min={0}
max={50}
onValueChange={(next) => {
setValue(next)
args?.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Value: {value === null ? '(empty)' : value}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledNumberInput {...args} />,
}
+84
View File
@@ -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 { NumberInput } from './NumberInput'
describe('NumberInput', () => {
it('names the input from its label', () => {
render(<NumberInput label="Seats" />)
expect(screen.getByRole('textbox', { name: 'Seats' })).toBeInTheDocument()
})
it('announces the description, then the error when invalid', () => {
const { rerender } = render(<NumberInput label="Seats" description="Up to 100." />)
expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Up to 100.')
rerender(<NumberInput label="Seats" description="Up to 100." error="Add at least one seat." />)
expect(screen.getByRole('textbox')).toHaveAttribute('aria-invalid', 'true')
expect(screen.getByRole('textbox')).toHaveAccessibleDescription('Add at least one seat.')
})
it('has labelled increment and decrement buttons', async () => {
const onValueChange = vi.fn()
render(<NumberInput label="Seats" defaultValue={5} onValueChange={onValueChange} />)
await userEvent.click(screen.getByRole('button', { name: 'Increase' }))
expect(screen.getByRole('textbox')).toHaveValue('6')
expect(onValueChange).toHaveBeenLastCalledWith(6)
await userEvent.click(screen.getByRole('button', { name: 'Decrease' }))
await userEvent.click(screen.getByRole('button', { name: 'Decrease' }))
expect(screen.getByRole('textbox')).toHaveValue('4')
})
it('steps with the arrow keys and clamps to min and max', async () => {
const user = userEvent.setup()
render(<NumberInput label="Seats" defaultValue={9} min={1} max={10} step={1} />)
const input = screen.getByRole('textbox')
await user.click(input)
await user.keyboard('{ArrowUp}')
expect(input).toHaveValue('10')
await user.keyboard('{ArrowUp}')
expect(input).toHaveValue('10')
await user.keyboard('{Home}')
expect(input).toHaveValue('1')
})
it('uses the step size', async () => {
render(<NumberInput label="Weight" defaultValue={2} step={0.5} />)
await userEvent.click(screen.getByRole('button', { name: 'Increase' }))
expect(screen.getByRole('textbox')).toHaveValue('2.5')
})
it('works controlled', async () => {
const onValueChange = vi.fn()
render(<NumberInput label="Seats" value={3} onValueChange={onValueChange} />)
await userEvent.click(screen.getByRole('button', { name: 'Increase' }))
expect(onValueChange).toHaveBeenLastCalledWith(4)
expect(screen.getByRole('textbox')).toHaveValue('3')
})
it('reports null when cleared', async () => {
const onValueChange = vi.fn()
render(<NumberInput label="Seats" defaultValue={3} onValueChange={onValueChange} />)
await userEvent.clear(screen.getByRole('textbox'))
expect(onValueChange).toHaveBeenLastCalledWith(null)
})
it('formats currency', () => {
render(<NumberInput label="Budget" defaultValue={1250.5} locale="en-US" format={{ style: 'currency', currency: 'USD' }} />)
expect(screen.getByRole('textbox')).toHaveValue('$1,250.50')
})
it('passes required and disabled', () => {
render(<NumberInput label="Seats" required disabled />)
expect(screen.getByRole('textbox')).toBeRequired()
expect(screen.getByRole('textbox')).toBeDisabled()
expect(screen.getByRole('button', { name: 'Increase' })).toBeDisabled()
})
it('has no axe violations', async () => {
const { container } = render(
<NumberInput label="Price" description="Before tax." required defaultValue={49} startAddon="$" endAddon="USD" />,
)
await expectNoA11yViolations(container)
})
})
+129
View File
@@ -0,0 +1,129 @@
import { NumberField } from '@base-ui/react/number-field'
import { Minus, Plus } from 'lucide-react'
import type { ReactNode } from 'react'
import { cn } from '../lib/cn'
import { controlBox, controlHeight, controlPaddingX, iconSize, type Size } from '../lib/styles'
import { Field } from './Field'
import { FIELD_BOX_DISABLED_INPUT, FIELD_BOX_RING_INPUT } from './featuredinput.tokens'
import { NUMBER_ADDON, NUMBER_STEPPER, NUMBER_STEPPER_WIDTH } from './numberinput.tokens'
export type NumberInputProps = {
/** Visible label, linked to the input. */
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 requires a value. */
required?: boolean
disabled?: boolean
/** Shows the value but blocks changes. */
readOnly?: boolean
size?: Size
/** Lowest allowed value. Stepping clamps to it. */
min?: number
/** Highest allowed value. Stepping clamps to it. */
max?: number
/** Amount the buttons and arrow keys change the value by. Shift steps by 10×. */
step?: number
value?: number | null
defaultValue?: number | null
/** Fires with the new number, or `null` when the input is cleared. */
onValueChange?: (value: number | null) => void
/** How the value is displayed, e.g. `{ style: 'currency', currency: 'USD' }`. */
format?: Intl.NumberFormatOptions
/** Locale for formatting and parsing. Defaults to the user's. */
locale?: Intl.LocalesArgument
/** Text or element attached before the input, such as `$`. */
startAddon?: ReactNode
/** Text or element attached after the input, such as `kg`. */
endAddon?: ReactNode
/** Identifies the field in a form. */
name?: string
/** Classes for the outer field wrapper. */
className?: string
/** Classes for the input itself. */
inputClassName?: string
}
/**
* A number field on Base UI NumberField: typing is parsed and formatted,
* arrow keys and the − / + buttons step the value, and min / max clamp it.
*/
export function NumberInput({
label,
description,
error,
required,
disabled,
readOnly,
size = 'md',
min,
max,
step = 1,
value,
defaultValue,
onValueChange,
format,
locale,
startAddon,
endAddon,
name,
className,
inputClassName,
}: NumberInputProps) {
return (
<Field
label={label}
description={description}
error={error}
required={required}
disabled={disabled}
name={name}
className={className}
>
<NumberField.Root
value={value}
defaultValue={defaultValue ?? undefined}
onValueChange={onValueChange ? (next) => onValueChange(next) : undefined}
min={min}
max={max}
step={step}
format={format}
locale={locale}
required={required}
disabled={disabled}
readOnly={readOnly}
className="w-full"
>
<NumberField.Group
className={cn(
'flex w-full items-stretch overflow-hidden',
controlHeight[size],
iconSize[size],
controlBox,
'has-[[aria-invalid=true]]:border-danger-500',
FIELD_BOX_DISABLED_INPUT,
FIELD_BOX_RING_INPUT,
)}
>
{startAddon != null && <span className={cn(NUMBER_ADDON, 'border-r')}>{startAddon}</span>}
<NumberField.Input
className={cn(
'min-w-0 flex-1 bg-transparent text-fg tabular-nums outline-none placeholder:text-fg-subtle disabled:cursor-not-allowed',
controlPaddingX[size],
inputClassName,
)}
/>
{endAddon != null && <span className={cn(NUMBER_ADDON, 'border-l')}>{endAddon}</span>}
<NumberField.Decrement aria-label="Decrease" className={cn(NUMBER_STEPPER, NUMBER_STEPPER_WIDTH[size])}>
<Minus aria-hidden="true" />
</NumberField.Decrement>
<NumberField.Increment aria-label="Increase" className={cn(NUMBER_STEPPER, NUMBER_STEPPER_WIDTH[size])}>
<Plus aria-hidden="true" />
</NumberField.Increment>
</NumberField.Group>
</NumberField.Root>
</Field>
)
}
+97
View File
@@ -0,0 +1,97 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { fn } from 'storybook/test'
import { SIZES } from '../lib/styles'
import { Pagination } from './Pagination'
const meta = {
title: 'Navigation/Pagination',
component: Pagination,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Moves between pages of a long list: a `nav` labelled "Pagination" with labelled previous and next buttons, ellipses for skipped ranges, and `aria-current="page"` on the current page. Give it `totalPages`, or `totalItems` and `pageSize`. Works controlled (`page`) or uncontrolled (`defaultPage`).',
},
},
},
argTypes: {
page: { control: 'number' },
defaultPage: { control: 'number', table: { defaultValue: { summary: '1' } } },
totalPages: { control: 'number' },
totalItems: { control: 'number' },
pageSize: { control: 'number', table: { defaultValue: { summary: '10' } } },
siblingCount: { control: { type: 'number', min: 0, max: 3 }, table: { defaultValue: { summary: '1' } } },
boundaryCount: { control: { type: 'number', min: 0, max: 3 }, table: { defaultValue: { summary: '1' } } },
size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
disabled: { control: 'boolean' },
onPageChange: { control: false },
},
args: {
defaultPage: 1,
totalPages: 20,
siblingCount: 1,
boundaryCount: 1,
size: 'md',
disabled: false,
onPageChange: fn(),
},
} satisfies Meta<typeof Pagination>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const AtStart: Story = { args: { defaultPage: 1 } }
export const InTheMiddle: Story = { args: { defaultPage: 10 } }
export const AtEnd: Story = { args: { defaultPage: 20 } }
export const FewPages: Story = { args: { totalPages: 5, defaultPage: 2 } }
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-4">
{SIZES.map((size) => (
<Pagination key={size} {...args} size={size} defaultPage={6} aria-label={`Pagination (${size})`} />
))}
</div>
),
}
export const MoreSiblings: Story = { args: { defaultPage: 10, siblingCount: 2 } }
export const Disabled: Story = { args: { defaultPage: 4, disabled: true } }
export const Controlled: Story = {
parameters: { docs: { description: { story: 'Driven by `totalItems` and `pageSize`, with the range shown beside it.' } } },
render: function Render(args) {
const [page, setPage] = useState(3)
const total = 248
const size = 25
return (
<div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border border-border bg-surface px-4 py-3">
<p className="text-sm text-fg-muted">
Showing <span className="font-medium text-fg">{(page - 1) * size + 1}</span>–
<span className="font-medium text-fg">{Math.min(page * size, total)}</span> of{' '}
<span className="font-medium text-fg">{total}</span> invoices
</p>
<Pagination
{...args}
totalPages={undefined}
totalItems={total}
pageSize={size}
page={page}
size="sm"
onPageChange={(next) => {
setPage(next)
args.onPageChange?.(next)
}}
/>
</div>
)
},
}
+61
View File
@@ -0,0 +1,61 @@
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 { Pagination } from './Pagination'
import { getPageRange } from './pagination.tokens'
describe('getPageRange', () => {
it('shows ellipses around the current page', () => {
expect(getPageRange(1, 20)).toEqual([1, 2, 3, 4, 5, 'end-ellipsis', 20])
expect(getPageRange(10, 20)).toEqual([1, 'start-ellipsis', 9, 10, 11, 'end-ellipsis', 20])
expect(getPageRange(20, 20)).toEqual([1, 'start-ellipsis', 16, 17, 18, 19, 20])
expect(getPageRange(2, 5)).toEqual([1, 2, 3, 4, 5])
expect(getPageRange(1, 1)).toEqual([1])
})
})
describe('Pagination', () => {
it('is a labelled nav with the current page marked', () => {
render(<Pagination totalPages={10} defaultPage={4} />)
expect(screen.getByRole('navigation', { name: 'Pagination' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Page 4' })).toHaveAttribute('aria-current', 'page')
expect(screen.getByRole('button', { name: 'Page 3' })).not.toHaveAttribute('aria-current')
})
it('changes page by number, next and previous (uncontrolled)', async () => {
const onPageChange = vi.fn()
render(<Pagination totalPages={10} onPageChange={onPageChange} />)
await userEvent.click(screen.getByRole('button', { name: 'Page 3' }))
expect(onPageChange).toHaveBeenLastCalledWith(3)
expect(screen.getByRole('button', { name: 'Page 3' })).toHaveAttribute('aria-current', 'page')
await userEvent.click(screen.getByRole('button', { name: 'Next page' }))
expect(onPageChange).toHaveBeenLastCalledWith(4)
await userEvent.click(screen.getByRole('button', { name: 'Previous page' }))
expect(onPageChange).toHaveBeenLastCalledWith(3)
})
it('disables previous on the first page and next on the last', () => {
const { rerender } = render(<Pagination totalPages={5} page={1} />)
expect(screen.getByRole('button', { name: 'Previous page' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled()
rerender(<Pagination totalPages={5} page={5} />)
expect(screen.getByRole('button', { name: 'Previous page' })).toBeEnabled()
expect(screen.getByRole('button', { name: 'Next page' })).toBeDisabled()
})
it('works controlled and from totalItems/pageSize', async () => {
const onPageChange = vi.fn()
render(<Pagination totalItems={95} pageSize={10} page={2} onPageChange={onPageChange} />)
expect(screen.getByRole('button', { name: 'Page 10' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Page 11' })).toBeNull()
await userEvent.click(screen.getByRole('button', { name: 'Page 3' }))
expect(onPageChange).toHaveBeenCalledWith(3)
expect(screen.getByRole('button', { name: 'Page 2' })).toHaveAttribute('aria-current', 'page')
})
it('has no axe violations', async () => {
const { container } = render(<Pagination totalPages={20} defaultPage={10} />)
await expectNoA11yViolations(container)
})
})
+108
View File
@@ -0,0 +1,108 @@
import type { ComponentProps } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '../lib/cn'
import { useControllableState } from '../lib/useControllableState'
import { Button, IconButton } from './Button'
import { PAGE_BUTTON_SIZES, PAGE_ELLIPSIS_SIZES, getPageRange, type PaginationSize } from './pagination.tokens'
export type PaginationProps = Omit<ComponentProps<'nav'>, 'children' | 'onChange'> & {
/** The current page, starting at 1 (controlled). */
page?: number
/** The initial page (uncontrolled). */
defaultPage?: number
/** Called with the new page number. */
onPageChange?: (page: number) => void
/** Number of pages. Or pass `totalItems` and `pageSize`. */
totalPages?: number
/** Total number of items, used with `pageSize` to work out `totalPages`. */
totalItems?: number
/** Items per page, used with `totalItems`. */
pageSize?: number
/** Pages shown either side of the current page. */
siblingCount?: number
/** Pages always shown at the start and end. */
boundaryCount?: number
size?: PaginationSize
/** Disables every control. */
disabled?: boolean
}
/** Moves between pages of a long list. */
export function Pagination({
page: pageProp,
defaultPage = 1,
onPageChange,
totalPages: totalPagesProp,
totalItems,
pageSize = 10,
siblingCount = 1,
boundaryCount = 1,
size = 'md',
disabled = false,
className,
'aria-label': ariaLabel = 'Pagination',
...props
}: PaginationProps) {
const totalPages = Math.max(
1,
totalPagesProp ?? (totalItems != null ? Math.ceil(totalItems / Math.max(1, pageSize)) : 1),
)
const [rawPage, setPage] = useControllableState(pageProp, defaultPage, onPageChange)
const page = Math.min(Math.max(1, rawPage), totalPages)
const go = (next: number) => {
if (next !== page && next >= 1 && next <= totalPages) setPage(next)
}
return (
<nav aria-label={ariaLabel} className={className} {...props}>
<ul className="flex flex-wrap items-center gap-1">
<li>
<IconButton
size={size}
variant="ghost"
aria-label="Previous page"
icon={<ChevronLeft />}
disabled={disabled || page <= 1}
onClick={() => go(page - 1)}
/>
</li>
{getPageRange(page, totalPages, siblingCount, boundaryCount).map((entry) =>
typeof entry === 'number' ? (
<li key={entry}>
<Button
size={size}
variant={entry === page ? 'solid' : 'ghost'}
color={entry === page ? 'primary' : 'neutral'}
aria-label={`Page ${entry}`}
aria-current={entry === page ? 'page' : undefined}
disabled={disabled}
onClick={() => go(entry)}
className={cn(PAGE_BUTTON_SIZES[size], entry !== page && 'font-medium')}
>
{entry}
</Button>
</li>
) : (
<li
key={entry}
aria-hidden="true"
className={cn('flex select-none items-center justify-center text-fg-subtle', PAGE_ELLIPSIS_SIZES[size])}
>
…
</li>
),
)}
<li>
<IconButton
size={size}
variant="ghost"
aria-label="Next page"
icon={<ChevronRight />}
disabled={disabled || page >= totalPages}
onClick={() => go(page + 1)}
/>
</li>
</ul>
</nav>
)
}
+204
View File
@@ -0,0 +1,204 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Bell, CalendarDays, Link2, SlidersHorizontal } from 'lucide-react'
import { useState } from 'react'
import { fn } from 'storybook/test'
import { Button, IconButton } from './Button'
import { Input } from './Input'
import { Popover } from './Popover'
import { POPUP_ALIGNS, POPUP_SIDES } from './popover.tokens'
const ownFrame = (height = 420) => ({ docs: { story: { inline: false, iframeHeight: height } } })
const meta = {
title: 'Overlays/Popover',
component: Popover,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Interactive content anchored to a trigger, on Base UI Popover. Opens on click, flips to stay on screen, and closes on Escape or an outside click with focus returning to the trigger. Use it for small forms, filters and details; for short non-interactive hints use Tooltip.',
},
},
},
argTypes: {
title: { control: 'text' },
description: { control: 'text' },
label: { control: 'text' },
side: { control: 'inline-radio', options: POPUP_SIDES, table: { defaultValue: { summary: 'bottom' } } },
align: { control: 'inline-radio', options: POPUP_ALIGNS, table: { defaultValue: { summary: 'center' } } },
sideOffset: { control: { type: 'number', min: 0, max: 32 }, table: { defaultValue: { summary: '8' } } },
arrow: { control: 'boolean' },
width: { control: 'number', table: { defaultValue: { summary: '320' } } },
open: { control: 'boolean' },
defaultOpen: { control: 'boolean' },
modal: { control: 'boolean' },
className: { control: 'text' },
trigger: { control: false },
children: { control: false },
onOpenChange: { control: false },
},
args: {
title: 'Notifications',
description: 'You’re all caught up.',
side: 'bottom',
align: 'center',
sideOffset: 8,
arrow: false,
width: 320,
trigger: (
<Button variant="outline" color="neutral" startIcon={<Bell aria-hidden="true" />}>
Notifications
</Button>
),
onOpenChange: fn(),
},
decorators: [
(Story) => (
<div className="flex min-h-80 items-start justify-center pt-4">
<Story />
</div>
),
],
} satisfies Meta<typeof Popover>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Open: Story = {
args: {
defaultOpen: true,
arrow: true,
width: 380,
title: 'Share link',
description: 'Anyone at Acme Corporation with the link can view this project.',
trigger: (
<Button variant="outline" color="neutral" startIcon={<Link2 aria-hidden="true" />}>
Share
</Button>
),
children: (
<div className="flex gap-2">
<Input aria-label="Project link" readOnly defaultValue="https://example.com/p/acme-website" className="min-w-0 flex-1" />
<Popover.Close render={<Button />}>Copy</Popover.Close>
</div>
),
},
parameters: ownFrame(),
}
export const WithForm: Story = {
args: {
defaultOpen: true,
align: 'start',
title: 'Dimensions',
description: 'Set the size of the selected layer.',
width: 300,
trigger: <IconButton variant="outline" aria-label="Layer dimensions" icon={<SlidersHorizontal />} />,
children: (
<form className="flex flex-col gap-3" onSubmit={(event) => event.preventDefault()}>
<div className="grid grid-cols-2 gap-3">
<Input label="Width" defaultValue="1280" endAddon="px" size="sm" />
<Input label="Height" defaultValue="720" endAddon="px" size="sm" />
</div>
<div className="flex justify-end gap-2">
<Popover.Close render={<Button size="sm" variant="ghost" color="neutral" />}>Cancel</Popover.Close>
<Popover.Close render={<Button size="sm" type="submit" />}>Apply</Popover.Close>
</div>
</form>
),
},
parameters: ownFrame(),
}
export const Sides: Story = {
parameters: {
...ownFrame(460),
docs: { ...ownFrame(460).docs, description: { story: 'Each side, open. A popover flips when the preferred side has no room.' } },
},
render: (args) => (
<div className="mx-auto grid w-fit grid-cols-3 grid-rows-3 place-items-center gap-x-56 gap-y-24 py-6">
{POPUP_SIDES.map((side) => (
<div
key={side}
className={
{ top: 'col-start-2 row-start-1', left: 'col-start-1 row-start-2', right: 'col-start-3 row-start-2', bottom: 'col-start-2 row-start-3' }[side]
}
>
<Popover
{...args}
side={side}
arrow
width={170}
defaultOpen
title={undefined}
description={undefined}
label={`Popover on the ${side}`}
trigger={
<Button variant="outline" color="neutral">
{side}
</Button>
}
>
<p className="m-0">Placed on the {side}.</p>
</Popover>
</div>
))}
</div>
),
}
export const Alignment: Story = {
parameters: ownFrame(360),
render: (args) => (
<div className="flex w-full max-w-4xl justify-between pb-32">
{POPUP_ALIGNS.map((align) => (
<Popover
key={align}
{...args}
align={align}
defaultOpen
width={200}
title={`align="${align}"`}
description={undefined}
trigger={
<Button variant="outline" color="neutral">
{align}
</Button>
}
>
<p className="m-0 text-fg-muted">Lines up with the trigger’s {align}.</p>
</Popover>
))}
</div>
),
}
export const Controlled: Story = {
render: function Render(args) {
const [open, setOpen] = useState(false)
return (
<div className="flex items-center gap-3">
<Popover
{...args}
open={open}
onOpenChange={setOpen}
title="Schedule"
description="Publish on Monday 6 October at 9:00."
trigger={
<Button variant="outline" color="neutral" startIcon={<CalendarDays aria-hidden="true" />}>
Schedule
</Button>
}
>
<Button size="sm" onClick={() => setOpen(false)}>
Confirm
</Button>
</Popover>
<span className="text-sm text-fg-muted">open: {String(open)}</span>
</div>
)
},
}
+55
View File
@@ -0,0 +1,55 @@
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { describe, expect, it } from 'vitest'
import { expectNoA11yViolations } from '../test/a11y'
import { Button } from './Button'
import { Popover } from './Popover'
describe('Popover', () => {
it('opens on click as a named dialog', async () => {
render(
<Popover trigger={<Button>Share</Button>} title="Share document" description="Anyone with the link can view.">
<Button>Copy link</Button>
</Popover>,
)
const trigger = screen.getByRole('button', { name: 'Share' })
await userEvent.click(trigger)
expect(trigger).toHaveAttribute('aria-expanded', 'true')
const popup = await screen.findByRole('dialog', { name: 'Share document' })
expect(popup).toContainElement(screen.getByRole('button', { name: 'Copy link' }))
})
it('closes on Escape and returns focus to the trigger', async () => {
render(
<Popover trigger={<Button>Share</Button>} label="Share options">
<Button>Copy link</Button>
</Popover>,
)
const trigger = screen.getByRole('button', { name: 'Share' })
await userEvent.click(trigger)
await screen.findByRole('dialog', { name: 'Share options' })
await userEvent.keyboard('{Escape}')
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await waitFor(() => expect(trigger).toHaveFocus())
})
it('closes from Popover.Close', async () => {
render(
<Popover trigger={<Button>Share</Button>} title="Share" defaultOpen>
<Popover.Close render={<Button />}>Done</Popover.Close>
</Popover>,
)
await userEvent.click(await screen.findByRole('button', { name: 'Done' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('has no axe violations when open', async () => {
render(
<Popover trigger={<Button>Share</Button>} title="Share document" arrow defaultOpen>
<p>Content</p>
</Popover>,
)
await screen.findByRole('dialog')
await expectNoA11yViolations(document.body)
})
})
+112
View File
@@ -0,0 +1,112 @@
import { Popover as BasePopover } from '@base-ui/react/popover'
import type { CSSProperties, ReactElement, ReactNode } from 'react'
import { cn } from '../lib/cn'
import { popupMotion, popupSurface } from '../lib/styles'
import { arrowBase, arrowBordered, type PopupAlign, type PopupSide } from './popover.tokens'
export type PopoverProps = {
/** The element that toggles the popover, usually a `<Button>`. */
trigger: ReactElement
/** Heading; also the popover's accessible name. */
title?: ReactNode
/** Supporting text under the title. */
description?: ReactNode
/** Accessible name when there is no `title`. */
label?: string
/** Popover content. It can hold interactive elements such as inputs and buttons. */
children?: ReactNode
/** Preferred side of the trigger. It flips when there's no room. */
side?: PopupSide
/** Alignment along that side. */
align?: PopupAlign
/** Gap between trigger and popover, in px. */
sideOffset?: number
/** Show a small arrow pointing at the trigger. */
arrow?: boolean
/** Width in px, or any CSS width. Never wider than the screen. */
width?: number | string
/** 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
/** Trap focus inside and lock page scroll while open. */
modal?: boolean
/** Classes for the popup. */
className?: string
}
/**
* Rich, interactive content anchored to a trigger (Base UI Popover). Opens on
* click; Escape or an outside click closes it and focus returns to the
* trigger. For short, non-interactive hints use Tooltip.
*/
function PopoverComponent({
trigger,
title,
description,
label,
children,
side = 'bottom',
align = 'center',
sideOffset = 8,
arrow = false,
width = 320,
open,
defaultOpen,
onOpenChange,
modal = false,
className,
}: PopoverProps) {
const style: CSSProperties = { width }
return (
<BasePopover.Root
open={open}
defaultOpen={defaultOpen}
onOpenChange={onOpenChange ? (next) => onOpenChange(next) : undefined}
modal={modal}
>
<BasePopover.Trigger render={trigger} />
<BasePopover.Portal>
<BasePopover.Positioner side={side} align={align} sideOffset={sideOffset} className="z-50">
<BasePopover.Popup
aria-label={title == null ? label : undefined}
style={style}
className={cn(
popupSurface,
popupMotion,
'relative max-w-[min(var(--available-width),calc(100vw-1.5rem))] p-4 text-sm leading-6',
className,
)}
>
{arrow && <BasePopover.Arrow className={cn(arrowBase, arrowBordered)} />}
{(title != null || description != null) && (
<div className="mb-3 flex flex-col gap-0.5 last:mb-0">
{title != null && (
<BasePopover.Title className="m-0 font-sans text-sm font-semibold leading-5 text-fg">
{title}
</BasePopover.Title>
)}
{description != null && (
<BasePopover.Description className="m-0 text-sm leading-5 text-fg-muted">
{description}
</BasePopover.Description>
)}
</div>
)}
{children}
</BasePopover.Popup>
</BasePopover.Positioner>
</BasePopover.Portal>
</BasePopover.Root>
)
}
/** Closes the popover. Pass a Button as `render`: `<Popover.Close render={<Button>Done</Button>} />`. */
function PopoverClose(props: BasePopover.Close.Props) {
return <BasePopover.Close {...props} />
}
export const Popover = Object.assign(PopoverComponent, { Close: PopoverClose })
+107
View File
@@ -0,0 +1,107 @@
import { useEffect, useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { COLORS, SIZES } from '../lib/styles'
import { Meter, Progress } from './Progress'
const meta = {
title: 'Feedback/Progress',
component: Progress,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Progress shows how far a task has got, built on Base UI Progress (`role="progressbar"`). Pass `value={null}` when the amount of work is unknown. **Meter** (Base UI Meter, `role="meter"`) is for a measurement in a known range, such as storage used or a password score. Both take a `label` (or `aria-label`), `showValue`, and `format` as `Intl.NumberFormat` options or a function.',
},
},
},
argTypes: {
value: { control: { type: 'range', min: 0, max: 100, step: 1 } },
min: { control: 'number', table: { defaultValue: { summary: '0' } } },
max: { control: 'number', table: { defaultValue: { summary: '100' } } },
label: { control: 'text' },
showValue: { control: 'boolean' },
format: { control: 'object' },
size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'primary' } } },
},
args: { value: 62, min: 0, max: 100, label: 'Exporting contacts', showValue: true, size: 'md', color: 'primary' },
decorators: [
(Story) => (
<div className="max-w-md">
<Story />
</div>
),
],
} satisfies Meta<typeof Progress>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Indeterminate: Story = {
args: { value: null, label: 'Preparing download', showValue: true },
}
export const Colors: Story = {
render: (args) => (
<div className="grid gap-5">
{COLORS.map((color, i) => (
<Progress key={color} {...args} color={color} value={20 + i * 14} label={color[0].toUpperCase() + color.slice(1)} />
))}
</div>
),
}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<Progress key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const CustomFormat: Story = {
parameters: { docs: { description: { story: '`format` as a function, for units other than percent.' } } },
args: { value: 3, max: 8, label: 'Uploading files', format: (value: number, max: number) => `${value} of ${max} files` },
}
export const WithoutLabel: Story = {
args: { label: undefined, showValue: false, 'aria-label': 'Profile completion', value: 40 },
}
export const Complete: Story = {
args: { value: 100, color: 'success', label: 'Backup complete' },
}
export const Animated: Story = {
render: function Render(args) {
const [value, setValue] = useState(10)
useEffect(() => {
const id = setInterval(() => setValue((v) => (v >= 100 ? 10 : Math.min(100, v + 15))), 900)
return () => clearInterval(id)
}, [])
return <Progress {...args} value={value} label="Installing updates" />
},
}
export const Meters: Story = {
parameters: { docs: { description: { story: 'Meters for gauges. Pick the colour from the reading: warning near a limit, danger over it.' } } },
render: () => (
<div className="grid gap-5">
<Meter
label="Storage used"
value={7.4}
max={10}
showValue
format={(value, max) => `${value} GB of ${max} GB`}
/>
<Meter label="Monthly API requests" value={92} showValue color="warning" />
<Meter label="Seats used" value={25} max={25} showValue color="danger" format={(v, max) => `${v} / ${max}`} />
<Meter label="Password strength" value={3} max={4} showValue color="success" size="sm" format={() => 'Strong'} />
</div>
),
}
+45
View File
@@ -0,0 +1,45 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { expectNoA11yViolations } from '../test/a11y'
import { Meter, Progress } from './Progress'
describe('Progress', () => {
it('exposes the value on a labelled progressbar', () => {
render(<Progress value={40} label="Exporting" showValue />)
const bar = screen.getByRole('progressbar', { name: 'Exporting' })
expect(bar).toHaveAttribute('aria-valuenow', '40')
expect(bar).toHaveAttribute('aria-valuemax', '100')
expect(screen.getByText('40%')).toBeInTheDocument()
})
it('is indeterminate with value null', () => {
render(<Progress value={null} aria-label="Preparing" />)
const bar = screen.getByRole('progressbar', { name: 'Preparing' })
expect(bar).not.toHaveAttribute('aria-valuenow')
})
it('formats with a function', () => {
render(<Progress value={3} max={8} label="Uploading" showValue format={(v, max) => `${v} of ${max} files`} />)
expect(screen.getByText('3 of 8 files')).toBeInTheDocument()
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuetext', '3 of 8 files')
})
it('has no axe violations', async () => {
const { container } = render(
<div>
<Progress value={40} label="Exporting" showValue />
<Progress value={null} aria-label="Loading" />
<Meter value={7} max={10} label="Storage used" showValue />
</div>,
)
await expectNoA11yViolations(container)
})
})
describe('Meter', () => {
it('is a labelled meter with its value', () => {
render(<Meter value={92} label="API requests" showValue />)
const meter = screen.getByRole('meter', { name: 'API requests' })
expect(meter).toHaveAttribute('aria-valuenow', '92')
})
})
+164
View File
@@ -0,0 +1,164 @@
import type { ComponentProps, ReactNode } from 'react'
import { Meter as BaseMeter } from '@base-ui/react/meter'
import { Progress as BaseProgress } from '@base-ui/react/progress'
import { cn } from '../lib/cn'
import {
PROGRESS_INDICATOR_COLORS,
PROGRESS_TEXT_SIZES,
PROGRESS_TRACK_SIZES,
progressIndicator,
progressTrack,
type ProgressColor,
type ProgressSize,
} from './progress.tokens'
type ValueFormat = Intl.NumberFormatOptions | ((value: number, max: number) => string)
type SharedProps = {
/** Visible label. Without one, pass `aria-label`. */
label?: ReactNode
/** Shows the formatted value to the right of the label. */
showValue?: boolean
/** The lower bound. */
min?: number
/** The upper bound. */
max?: number
/**
* How the value is shown and announced: `Intl.NumberFormat` options, or a
* function returning text such as "3 of 5 files". Defaults to a percentage.
*/
format?: ValueFormat
size?: ProgressSize
/** Colour of the filled part. */
color?: ProgressColor
className?: string
'aria-label'?: string
}
export type ProgressProps = SharedProps &
Omit<ComponentProps<'div'>, 'color' | 'children' | keyof SharedProps> & {
/** Current value. `null` shows an indeterminate bar. */
value: number | null
}
export type MeterProps = SharedProps &
Omit<ComponentProps<'div'>, 'color' | 'children' | keyof SharedProps> & {
/** Current value. */
value: number
}
/** Slides the indeterminate bar with the Web Animations API, so no global keyframes are needed. */
function animateIndeterminate(element: HTMLElement | null) {
if (!element || typeof element.animate !== 'function') return
const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
const animation = reduce
? element.animate([{ opacity: 1 }, { opacity: 0.45 }, { opacity: 1 }], { duration: 2000, iterations: Infinity })
: element.animate([{ transform: 'translateX(-100%)' }, { transform: 'translateX(250%)' }], {
duration: 1400,
iterations: Infinity,
easing: 'cubic-bezier(0.65, 0, 0.35, 1)',
})
return () => animation.cancel()
}
function split(format: ValueFormat | undefined, max: number) {
if (typeof format === 'function') {
return {
format: undefined,
getAriaValueText: (_: string | null, value: number | null) => (value == null ? 'Loading' : format(value, max)),
render: (_: string | null, value: number | null) => (value == null ? null : format(value, max)),
}
}
return { format, getAriaValueText: undefined, render: undefined }
}
function Header({ label, value, size }: { label?: ReactNode; value?: ReactNode; size: ProgressSize }) {
if (label == null && value == null) return null
return <div className={cn('col-span-2 flex items-baseline justify-between gap-3', PROGRESS_TEXT_SIZES[size])}>{label}{value}</div>
}
/** Shows how far a task has got. Pass `value={null}` when the amount of work is unknown. */
export function Progress({
value,
min = 0,
max = 100,
label,
showValue = false,
format,
size = 'md',
color = 'primary',
className,
...props
}: ProgressProps) {
const f = split(format, max)
const indeterminate = value == null
return (
<BaseProgress.Root
value={value}
min={min}
max={max}
format={f.format}
getAriaValueText={f.getAriaValueText}
className={cn('grid w-full grid-cols-2 gap-y-2', className)}
{...props}
>
<Header
size={size}
label={label != null ? <BaseProgress.Label className="font-medium text-fg">{label}</BaseProgress.Label> : undefined}
value={
showValue && !indeterminate ? (
<BaseProgress.Value className="ml-auto tabular-nums text-fg-muted">{f.render}</BaseProgress.Value>
) : undefined
}
/>
<BaseProgress.Track className={cn(progressTrack, PROGRESS_TRACK_SIZES[size])}>
<BaseProgress.Indicator
ref={indeterminate ? animateIndeterminate : undefined}
className={cn(progressIndicator, PROGRESS_INDICATOR_COLORS[color], indeterminate && 'w-2/5')}
/>
</BaseProgress.Track>
</BaseProgress.Root>
)
}
/** A gauge for a measurement within a known range, such as storage used. Not for task progress. */
export function Meter({
value,
min = 0,
max = 100,
label,
showValue = false,
format,
size = 'md',
color = 'primary',
className,
...props
}: MeterProps) {
const f = split(format, max)
return (
<BaseMeter.Root
value={value}
min={min}
max={max}
format={f.format}
getAriaValueText={f.getAriaValueText as ((formatted: string, value: number) => string) | undefined}
className={cn('grid w-full grid-cols-2 gap-y-2', className)}
{...props}
>
<Header
size={size}
label={label != null ? <BaseMeter.Label className="font-medium text-fg">{label}</BaseMeter.Label> : undefined}
value={
showValue ? (
<BaseMeter.Value className="ml-auto tabular-nums text-fg-muted">
{f.render as ((formatted: string, value: number) => ReactNode) | undefined}
</BaseMeter.Value>
) : undefined
}
/>
<BaseMeter.Track className={cn(progressTrack, PROGRESS_TRACK_SIZES[size])}>
<BaseMeter.Indicator className={cn(progressIndicator, PROGRESS_INDICATOR_COLORS[color])} />
</BaseMeter.Track>
</BaseMeter.Root>
)
}
+192 -87
View File
@@ -1,6 +1,16 @@
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 { Radio } from './Radio'
import { RADIO_VARIANTS } from './radio.tokens'
const plans = [
{ value: 'starter', label: 'Starter · $0/month', description: 'For individuals. 3 projects and 1 GB of storage.' },
{ value: 'team', label: 'Team · $12/user/month', description: 'Unlimited projects, shared workspaces and priority email support.' },
{ value: 'business', label: 'Business · $29/user/month', description: 'Single sign-on, audit logs and a 99.9% uptime SLA.' },
]
const meta = {
title: 'Forms/Radio',
@@ -10,134 +20,229 @@ const meta = {
docs: {
description: {
component:
'Radio group. The native input is visually hidden and the ring + dot are drawn in CSS, so the selected state follows the palette. A real radio input is still used underneath, so keyboard and form semantics are intact.',
'A radio **group**: one choice from a short list given as `options` (strings, or `{ value, label, description?, disabled? }`). Tab moves into the group and the arrow keys move between options. `variant="card"` renders each option as a bordered, selectable card, as in plan pickers.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: {
control: 'select',
options: ['blue', 'green', 'red', 'yellow', 'teal', 'purple', 'amber', 'gray'],
},
label: { control: 'text' },
description: { control: 'text' },
error: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
readOnly: { control: 'boolean' },
options: { control: 'object' },
value: { control: 'text' },
helpText: { control: 'text' },
error: { control: 'text' },
defaultValue: { control: 'text' },
orientation: {
control: 'inline-radio',
options: ['vertical', 'horizontal'],
table: { defaultValue: { summary: 'vertical' } },
},
size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'primary' } } },
variant: { control: 'inline-radio', options: RADIO_VARIANTS, table: { defaultValue: { summary: 'default' } } },
name: { control: 'text' },
className: { control: 'text' },
onValueChange: { control: false },
},
args: {
name: 'payroll_frequency',
options: ['Monthly', 'Fortnightly', 'Weekly'],
label: 'Pay cycle',
description: 'How often employees on this contract are paid.',
options: ['Monthly', 'Twice a month', 'Every two weeks', 'Weekly'],
defaultValue: 'Monthly',
orientation: 'vertical',
size: 'md',
theme: 'blue',
label: 'Payroll frequency',
color: 'primary',
variant: 'default',
required: false,
disabled: false,
value: 'Monthly',
helpText: '',
error: '',
readOnly: false,
onValueChange: fn(),
},
} satisfies Meta<typeof Radio>
export default meta
type Story = StoryObj<typeof meta>
/**
* Wraps Radio with local state so the group is interactive.
*
* `initial` selects the starting option. The themes grid needs one selected to
* show the ring and dot in each colour, so it passes a value rather than ''.
*/
function ControlledRadio({
initial = '',
...args
}: React.ComponentProps<typeof Radio> & { initial?: string }) {
const [value, setValue] = useState(args.value ?? initial)
return <Radio {...args} value={value} onChange={setValue} />
export const Playground: Story = {}
export const WithDescriptions: Story = {
args: {
label: 'Delivery speed',
description: undefined,
options: [
{ value: 'standard', label: 'Standard', description: '4–6 business days. Free.' },
{ value: 'express', label: 'Express', description: '2–3 business days. $9.00.' },
{ value: 'overnight', label: 'Overnight', description: 'Next business day. $24.00.' },
],
defaultValue: 'standard',
},
}
export const Playground: Story = {
render: (args) => <ControlledRadio {...args} />,
export const Horizontal: Story = {
args: { orientation: 'horizontal', label: 'Theme', description: undefined, options: ['System', 'Light', 'Dark'], defaultValue: 'System' },
}
/** No `value` or `onChange` — the component tracks its own selection. */
export const Uncontrolled: Story = {
render: (args) => <Radio {...args} />,
export const Unselected: Story = {
args: { defaultValue: undefined },
}
export const DisabledOption: Story = {
args: {
label: 'Leave type',
description: undefined,
options: [
{ value: 'annual', label: 'Annual leave' },
{ value: 'sick', label: 'Sick leave' },
{ value: 'parental', label: 'Parental leave', description: 'Available after 6 months of service.', disabled: true },
],
defaultValue: 'annual',
},
}
export const Disabled: Story = {
args: { disabled: true },
}
export const ReadOnly: Story = {
args: { readOnly: true, description: 'Set by your payroll administrator.' },
}
export const WithError: Story = {
args: {
required: true,
label: 'Employment type',
description: undefined,
options: ['Full-time', 'Part-time', 'Contractor'],
defaultValue: undefined,
error: 'Choose an employment type to continue.',
},
}
export const Required: Story = {
args: { required: true },
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-col gap-6">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledRadio key={size} {...args} size={size} label={`Size ${size}`} />
<div className="grid gap-8 sm:grid-cols-3">
{SIZES.map((size) => (
<Radio key={size} {...args} size={size} label={`Size ${size}`} description={undefined} options={['Monthly', 'Weekly', 'Daily']} defaultValue="Monthly" />
))}
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="grid gap-5 sm:grid-cols-2">
{(['blue', 'green', 'red', 'yellow', 'teal', 'purple', 'amber', 'gray'] as const).map((theme) => (
<ControlledRadio
key={theme}
name={`theme-${theme}`}
theme={theme}
options={['Option A', 'Option B']}
label={theme}
initial="Option A"
export const Colors: Story = {
render: (args) => (
<div className="grid gap-8 sm:grid-cols-3">
{COLORS.map((color) => (
<Radio key={color} {...args} color={color} label={color} description={undefined} options={['Selected', 'Other']} defaultValue="Selected" />
))}
</div>
),
}
export const Cards: Story = {
args: {
variant: 'card',
label: 'Plan',
description: 'You can change plans at any time.',
options: plans,
defaultValue: 'team',
},
decorators: [(Story) => <div className="max-w-md">{Story()}</div>],
}
export const CardsHorizontal: Story = {
args: {
variant: 'card',
orientation: 'horizontal',
label: 'Billing period',
description: undefined,
options: [
{ value: 'monthly', label: 'Monthly', description: '$12 per user, billed each month.' },
{ value: 'yearly', label: 'Yearly', description: '$120 per user. Two months free.' },
],
defaultValue: 'yearly',
},
decorators: [(Story) => <div className="max-w-xl">{Story()}</div>],
}
export const CardSizesAndColors: Story = {
render: (args) => (
<div className="grid max-w-3xl gap-8 sm:grid-cols-3">
{SIZES.map((size, i) => (
<Radio
key={size}
{...args}
variant="card"
size={size}
color={(['primary', 'success', 'neutral'] as const)[i]}
label={`Size ${size}`}
description={undefined}
options={plans.slice(0, 2).map((p) => ({ ...p, label: p.label.split(' · ')[0] }))}
defaultValue="team"
/>
))}
</div>
),
}
/** Options may carry their own disabled state. */
export const DisabledOptions: Story = {
render: () => (
<ControlledRadio
name="leave_type"
label="Leave type"
options={[
{ label: 'Casual leave', value: 'casual' },
{ label: 'Sick leave', value: 'sick' },
{ label: 'Parental leave (unavailable)', value: 'parental', disabled: true },
]}
/>
),
export const CardsWithError: Story = {
args: { variant: 'card', label: 'Plan', options: plans, defaultValue: undefined, required: true, error: 'Choose a plan to continue.' },
decorators: [(Story) => <div className="max-w-md">{Story()}</div>],
}
export const RequiredWithError: Story = {
render: () => (
<ControlledRadio
name="employment_type"
label="Employment type"
required
options={['Full-time', 'Part-time', 'Contract']}
error="Select an employment type to continue."
/>
),
export const Uncontrolled: Story = {
args: { defaultValue: 'Weekly', description: 'Starts with a default and keeps its own state.' },
}
export const WithTooltip: Story = {
render: () => (
<ControlledRadio
name="pay_cycle"
label="Pay cycle"
options={['Monthly', 'Fortnightly', 'Weekly']}
helpText="Changing this affects every future payroll run in the entity."
/>
),
function ControlledRadio(args: Story['args']) {
const [value, setValue] = useState('Every two weeks')
return (
<div className="grid gap-3">
<Radio
{...args}
options={args?.options ?? []}
value={value}
onValueChange={(next) => {
setValue(next)
args?.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Value: {value}</p>
</div>
)
}
export const Horizontal: Story = {
render: () => (
<ControlledRadio
name="invoice_type"
options={['Standard', 'Proforma', 'Credit note']}
/>
),
export const Controlled: Story = {
render: (args) => <ControlledRadio {...args} />,
}
function PlanPicker() {
const [plan, setPlan] = useState('team')
const chosen = plans.find((p) => p.value === plan)
return (
<div className="grid max-w-lg gap-5 rounded-xl border border-border bg-surface p-6">
<div>
<p className="text-lg font-semibold text-fg">Choose a plan for Acme Corporation</p>
<p className="text-sm text-fg-muted">All plans include a 14-day free trial. No card needed.</p>
</div>
<Radio variant="card" label="Plan" name="plan" options={plans} value={plan} onValueChange={setPlan} />
<div className="flex items-center justify-between gap-4 border-t border-border pt-4">
<p className="text-sm text-fg-muted">
Selected: <span className="font-medium text-fg">{chosen?.label.split(' · ')[0]}</span>
</p>
<Button>Continue</Button>
</div>
</div>
)
}
/** A realistic plan picker built from card radios. */
export const PlanPickerExample: Story = {
name: 'Plan picker',
render: () => <PlanPicker />,
}
+90
View File
@@ -0,0 +1,90 @@
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 { Radio } from './Radio'
const options = ['Monthly', 'Weekly', { value: 'daily', label: 'Daily', description: 'Contractors only.' }]
describe('Radio', () => {
it('renders a radiogroup named by its legend', () => {
render(<Radio label="Pay cycle" options={options} />)
expect(screen.getByRole('radiogroup', { name: 'Pay cycle' })).toBeInTheDocument()
expect(screen.getAllByRole('radio')).toHaveLength(3)
expect(screen.getByRole('radio', { name: 'Daily' })).toHaveAccessibleDescription('Contractors only.')
})
it('selects an option when its label is clicked', async () => {
const onValueChange = vi.fn()
render(<Radio label="Pay cycle" options={options} onValueChange={onValueChange} />)
await userEvent.click(screen.getByText('Weekly'))
expect(screen.getByRole('radio', { name: 'Weekly' })).toBeChecked()
expect(onValueChange).toHaveBeenCalledWith('Weekly')
})
it('moves the selection with arrow keys', async () => {
render(<Radio label="Pay cycle" options={options} defaultValue="Monthly" />)
await userEvent.tab()
expect(screen.getByRole('radio', { name: 'Monthly' })).toHaveFocus()
await userEvent.keyboard('{ArrowDown}')
expect(screen.getByRole('radio', { name: 'Weekly' })).toBeChecked()
expect(screen.getByRole('radio', { name: 'Weekly' })).toHaveFocus()
await userEvent.keyboard('{ArrowUp}')
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked()
})
it('works controlled', async () => {
const onValueChange = vi.fn()
render(<Radio label="Pay cycle" options={options} value="Monthly" onValueChange={onValueChange} />)
await userEvent.click(screen.getByRole('radio', { name: 'Daily' }))
expect(onValueChange).toHaveBeenCalledWith('daily')
expect(screen.getByRole('radio', { name: 'Monthly' })).toBeChecked()
})
it('card variant selects when the card title is clicked', async () => {
render(
<Radio
variant="card"
label="Plan"
options={[
{ value: 'starter', label: 'Starter', description: 'For individuals.' },
{ value: 'team', label: 'Team', description: 'For teams.' },
]}
/>,
)
await userEvent.click(screen.getByText('Team'))
expect(screen.getByRole('radio', { name: 'Team' })).toBeChecked()
expect(screen.getByRole('radio', { name: 'Team' })).toHaveAccessibleDescription('For teams.')
})
it('marks the group invalid and required, and shows the error', () => {
render(<Radio label="Type" options={options} required error="Choose a type." />)
const group = screen.getByRole('radiogroup')
expect(group).toHaveAttribute('aria-invalid', 'true')
expect(group).toHaveAttribute('aria-required', 'true')
expect(group).toHaveAccessibleDescription('Choose a type.')
})
it('skips disabled options and ignores a disabled group', async () => {
const onValueChange = vi.fn()
render(
<>
<Radio label="One" options={[{ value: 'a', label: 'A', disabled: true }, 'B']} onValueChange={onValueChange} />
<Radio label="Two" options={['C']} disabled onValueChange={onValueChange} />
</>,
)
await userEvent.click(screen.getByText('A'))
await userEvent.click(screen.getByText('C'))
expect(onValueChange).not.toHaveBeenCalled()
})
it('has no axe violations', async () => {
const { container } = render(
<>
<Radio label="Pay cycle" description="How often." options={options} defaultValue="Weekly" required />
<Radio variant="card" label="Plan" options={[{ value: 'a', label: 'A', description: 'First' }]} error="Pick one" />
</>,
)
await expectNoA11yViolations(container)
})
})
+206 -143
View File
@@ -1,155 +1,218 @@
import { useEffect, useState, type HTMLAttributes, type ReactNode } from 'react'
import type { LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import { Tooltip } from './Tooltip'
import { RADIO_COLORS, RADIO_SIZES, type RadioSize, type RadioTheme } from './radio.tokens'
import { Field as BaseField } from '@base-ui/react/field'
import { Fieldset } from '@base-ui/react/fieldset'
import { Radio as BaseRadio } from '@base-ui/react/radio'
import { RadioGroup } from '@base-ui/react/radio-group'
import type { ReactNode } from 'react'
import { cn } from '../lib/cn'
import { descriptionText, errorText, focusRing, focusWithinRing, labelText, requiredMark } from '../lib/styles'
import {
RADIO_CARD_COLORS,
RADIO_CARD_SIZES,
RADIO_CIRCLE_SIZES,
RADIO_COLORS,
RADIO_DOT_SIZES,
RADIO_GAP,
RADIO_LABEL_SIZES,
RADIO_OFFSET,
type RadioColor,
type RadioOption,
type RadioOptionObject,
type RadioOrientation,
type RadioSize,
type RadioVariant,
} from './radio.tokens'
/**
* Radio group with a generated ring + dot indicator.
*
* Ported from the original `Radio` component.
*
* The native input is visually hidden; the ring and dot are drawn in CSS, which
* is what lets the selected state follow palette tokens. A real `radio` input is
* still used underneath, so keyboard and form semantics are intact.
*
* `register` / `validation` (React Hook Form) are intentionally not ported —
* pass `value` and `onChange` directly.
*/
export type RadioOption = string | { label: ReactNode; value: string; disabled?: boolean }
export type RadioProps = Omit<HTMLAttributes<HTMLDivElement>, 'onChange' | 'defaultValue'> & {
name?: string
options?: RadioOption[]
size?: RadioSize
theme?: RadioTheme
/** Disables every option in the group. */
disabled?: boolean
export type RadioProps = {
/** The group's legend. */
label?: ReactNode
/** Appends the mandatory asterisk to the group label. */
/** Help text under the legend. */
description?: ReactNode
/** Error message. Marks the group invalid and replaces `description`. */
error?: ReactNode
/** Adds the required mark and requires a choice before the form submits. */
required?: boolean
/** Controlled selection. */
/** Disables every option. */
disabled?: boolean
/** Shows the choice but ignores clicks and keys. */
readOnly?: boolean
/** Strings, or `{ value, label, description?, disabled? }`. */
options: RadioOption[]
/** The chosen value (controlled). */
value?: string
onChange?: (value: string) => void
error?: string | { message?: string }
/** Icon class name shown in place of the dot when selected, e.g. `"ri-check"`. */
icon?: string
tooltip?: string
tooltipIcon?: LucideIcon
helpText?: string
/** The initially chosen value (uncontrolled). */
defaultValue?: string
/** Fires with the newly chosen value. */
onValueChange?: (value: string) => void
/** Stack options (`vertical`) or lay them out in a row. */
orientation?: RadioOrientation
size?: RadioSize
/** Fill colour of the chosen option. */
color?: RadioColor
/** `card` renders each option as a bordered, selectable card with a title and description. */
variant?: RadioVariant
/** Identifies the group in a form. */
name?: string
className?: string
}
export const Radio = function Radio({
name = '',
options = [],
size = 'md',
theme = 'blue',
disabled = false,
icon,
error,
label,
required = false,
helpText,
tooltip,
tooltipIcon,
value,
onChange,
className = '',
...props
}: RadioProps) {
const [localValue, setLocalValue] = useState(value ?? '')
useEffect(() => {
if (value !== undefined) setLocalValue(value)
}, [value])
const sizeData = RADIO_SIZES[size] ?? RADIO_SIZES.md
const themeData = RADIO_COLORS[theme] ?? RADIO_COLORS.blue
const handleChange = (next: string) => {
setLocalValue(next)
onChange?.(next)
}
const errorMessage =
error == null ? null : typeof error === 'string' ? error : (error.message ?? 'This field is required')
function normalise(option: RadioOption): RadioOptionObject {
return typeof option === 'string' ? { value: option, label: option } : option
}
function Circle({ value, disabled, size, color, card }: { value: string; disabled?: boolean; size: RadioSize; color: RadioColor; card?: boolean }) {
return (
<div className={cn('flex flex-col gap-2', className)} role="radiogroup" {...props}>
{label && (
<div className="flex items-center gap-1.5">
<span className={cn('font-medium', sizeData.label)}>
{label} {required && <span className="text-red-500">*</span>}
</span>
{(tooltip || helpText) && (
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
)}
</div>
<BaseRadio.Root
value={value}
disabled={disabled}
className={cn(
'inline-flex shrink-0 cursor-pointer items-center justify-center rounded-full border border-border-strong bg-surface transition-colors dark:not-data-checked: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',
RADIO_CIRCLE_SIZES[size],
RADIO_OFFSET[size],
RADIO_COLORS[color].circle,
// In a card the whole card shows the focus ring.
card ? 'outline-none' : focusRing,
)}
<div className="flex flex-wrap gap-4">
{options.map((opt, index) => {
const option = typeof opt === 'string' ? { label: opt, value: opt } : opt
const isChecked = localValue === option.value
const isDisabled = disabled || Boolean(option.disabled)
return (
<label
key={option.value || index}
htmlFor={`${name}-${option.value}`}
className={cn(
'inline-flex items-center space-x-2 mr-4',
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
)}
>
<input
type="radio"
id={`${name}-${option.value}`}
name={name}
value={option.value}
className="peer sr-only"
checked={isChecked}
onChange={() => handleChange(option.value)}
disabled={isDisabled}
/>
{/* Decorative ring + dot; the input above carries the semantics. */}
<span
aria-hidden="true"
className={cn(
'relative flex items-center justify-center rounded-full border transition-all duration-200',
sizeData.container,
isChecked ? cn(themeData.border, 'border-2') : 'border-gray-300',
!isDisabled && 'hover:border-gray-400',
)}
>
{isChecked &&
(icon ? (
<i className={cn(icon, themeData.text)} />
) : (
<span className={cn('absolute rounded-full', sizeData.dot, themeData.bg)} />
))}
</span>
<span className={cn('text-gray-700', sizeData.label)}>{option.label}</span>
</label>
)
})}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
>
<BaseRadio.Indicator className={cn('rounded-full data-unchecked:hidden', RADIO_DOT_SIZES[size], RADIO_COLORS[color].dot)} />
</BaseRadio.Root>
)
}
export default Radio
/**
* A radio group driven by `options`: one choice from a short list, with a
* legend, help text and error. Arrow keys move between options. The `card`
* variant suits plan and shipping pickers. Built on Base UI RadioGroup and
* Fieldset.
*/
export function Radio({
label,
description,
error,
required,
disabled,
readOnly,
options,
value,
defaultValue,
onValueChange,
orientation = 'vertical',
size = 'md',
color = 'primary',
variant = 'default',
name,
className,
}: RadioProps) {
const invalid = error != null && error !== false && error !== ''
const card = variant === 'card'
return (
<BaseField.Root name={name} disabled={disabled} invalid={invalid} className={className}>
<Fieldset.Root
render={
<RadioGroup
value={value}
defaultValue={defaultValue}
onValueChange={onValueChange ? (next) => onValueChange(next as string) : undefined}
disabled={disabled}
readOnly={readOnly}
required={required}
aria-orientation={orientation}
/>
}
className="flex flex-col gap-3"
>
{(label != null || (description != null && !invalid)) && (
<div className="flex flex-col gap-0.5">
{label != null && (
<Fieldset.Legend className={cn(labelText, 'data-disabled:opacity-55')}>
{label}
{required && (
<span aria-hidden="true" className={requiredMark}>
*
</span>
)}
</Fieldset.Legend>
)}
{description != null && !invalid && (
<BaseField.Description className={descriptionText}>{description}</BaseField.Description>
)}
</div>
)}
<div
className={cn(
card
? orientation === 'horizontal'
? 'grid gap-3 sm:auto-cols-fr sm:grid-flow-col'
: 'grid gap-3'
: orientation === 'horizontal'
? 'flex flex-wrap gap-x-6 gap-y-3'
: 'flex flex-col gap-3',
)}
>
{options.map(normalise).map((option) =>
card ? (
<BaseField.Item
key={option.value}
disabled={option.disabled}
className={cn(
'relative flex items-start rounded-xl border border-border bg-surface transition-colors',
'hover:border-border-strong has-[[data-disabled]]:cursor-not-allowed has-[[data-disabled]]:bg-surface-muted has-[[data-disabled]]:hover:border-border',
'has-[[data-invalid]]:border-danger-500',
RADIO_GAP[size],
RADIO_CARD_SIZES[size],
RADIO_CARD_COLORS[color],
focusWithinRing,
)}
>
<Circle value={option.value} disabled={option.disabled} size={size} color={color} card />
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<BaseField.Label
className={cn(
RADIO_LABEL_SIZES[size],
'cursor-pointer font-semibold text-fg select-none data-disabled:cursor-not-allowed',
// Stretch the label over the whole card, so a click anywhere selects it.
'after:absolute after:inset-0 after:rounded-xl',
)}
>
{option.label}
</BaseField.Label>
{option.description != null && (
<BaseField.Description className="text-sm leading-5 text-fg-muted">
{option.description}
</BaseField.Description>
)}
</div>
</BaseField.Item>
) : (
<BaseField.Item key={option.value} disabled={option.disabled} className={cn('flex items-start', RADIO_GAP[size])}>
<Circle value={option.value} disabled={option.disabled} size={size} color={color} />
<div className="flex min-w-0 flex-col gap-0.5">
<BaseField.Label
className={cn(
RADIO_LABEL_SIZES[size],
'cursor-pointer text-fg select-none data-disabled:cursor-not-allowed data-disabled:opacity-55',
)}
>
{option.label}
</BaseField.Label>
{option.description != null && (
<BaseField.Description className={descriptionText}>
{option.description}
</BaseField.Description>
)}
</div>
</BaseField.Item>
),
)}
</div>
{invalid && (
<BaseField.Error match className={errorText}>
{error}
</BaseField.Error>
)}
</Fieldset.Root>
</BaseField.Root>
)
}
+221 -178
View File
@@ -1,25 +1,13 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Select, type SelectOption } from './Select'
const COUNTRIES: SelectOption[] = [
{ label: 'India', value: 'in' },
{ label: 'United Kingdom', value: 'gb' },
{ label: 'United States', value: 'us' },
{ label: 'Germany', value: 'de' },
{ label: 'Singapore', value: 'sg' },
{ label: 'United Arab Emirates', value: 'ae' },
{ label: 'Australia', value: 'au' },
{ label: 'Canada', value: 'ca' },
]
const DEPARTMENTS: SelectOption[] = [
{ label: 'Engineering', value: 'eng' },
{ label: 'Finance', value: 'fin' },
{ label: 'People & Culture', value: 'hr' },
{ label: 'Operations', value: 'ops' },
{ label: 'Sales', value: 'sales' },
]
import { Building2, Globe, Plus } from 'lucide-react'
import { useState } from 'react'
import { fn } from 'storybook/test'
import { SIZES } from '../lib/styles'
import { Button } from './Button'
import { Input } from './Input'
import { Select } from './Select'
import { COUNTRIES, CURRENCIES, DEPARTMENTS, DEPARTMENTS_DESCRIBED, EMPLOYEES, withoutValue } from './select.fixtures'
import { SELECT_VARIANTS } from './select.tokens'
const meta = {
title: 'Forms/Select',
@@ -29,212 +17,267 @@ const meta = {
docs: {
description: {
component:
'Dispatches to a native `<select>` by default, or a searchable portalled dropdown with a floating label when `featured` is set. The source built its themed classes as template strings, which Tailwind cannot scan; here they come from a static map so every theme actually renders.',
'A dropdown for choosing one or several values from a short list, with its label above. Built on Base UI Select: arrow keys, Home/End, type-ahead, Enter to choose and Escape to close all work, and focus returns to the trigger. Options can carry a `description` and a `group`. For long lists, use `Combobox` or `FeaturedSelect` with `searchable`; for a floating label, `FeaturedSelect`.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
variant: { control: 'select', options: ['outlined', 'filled', 'standard', 'underlined'] },
width: { control: 'select', options: ['full', 'half', 'small', 'xs', 'large'] },
featured: { 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: SELECT_VARIANTS, table: { defaultValue: { summary: 'outline' } } },
side: { control: 'inline-radio', options: ['bottom', 'top'], table: { defaultValue: { summary: 'bottom' } } },
multiple: { control: 'boolean' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
isLoading: { control: 'boolean' },
isClearable: { control: 'boolean' },
searchable: { control: 'boolean' },
value: { control: 'text' },
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 },
},
args: {
options: COUNTRIES,
value: '',
label: 'Country of registration',
placeholder: 'Select a country',
label: 'Department',
placeholder: 'Select a department',
options: DEPARTMENTS,
size: 'md',
theme: 'primary',
variant: 'outlined',
width: 'full',
featured: false,
variant: 'outline',
side: 'bottom',
multiple: false,
required: false,
disabled: false,
isLoading: false,
isClearable: true,
searchable: true,
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 }) => (
<div
className={
parameters.wide
? 'max-w-3xl rounded-xl border border-border bg-surface p-6'
: 'max-w-sm rounded-xl border border-border bg-surface p-6'
}
>
<Story />
</div>
),
],
} satisfies Meta<typeof Select>
export default meta
type Story = StoryObj<typeof meta>
/**
* Select is a controlled component: it reports a value, it does not hold one.
*/
function ControlledSelect({
initial = '',
...args
}: React.ComponentProps<typeof Select> & { initial?: string }) {
const [value, setValue] = useState(initial)
return (
<div className="max-w-md">
<Select {...args} value={value} onChange={setValue} />
<p className="mt-2 text-xs text-gray-500">value = {JSON.stringify(value)}</p>
</div>
)
}
export const Playground: Story = {}
export const Playground: Story = {
render: (args) => <ControlledSelect {...args} />,
}
export const Featured: Story = {
args: { featured: true },
render: (args) => <ControlledSelect {...args} />,
}
export const FeaturedWithValue: Story = {
args: { featured: true },
render: (args) => <ControlledSelect {...args} initial="in" />,
}
export const FeaturedRequired: Story = {
args: { featured: true, required: true },
render: (args) => <ControlledSelect {...args} />,
/** The popup rendered open, for review without clicking. */
export const Open: Story = {
args: { defaultOpen: true, defaultValue: 'fin', options: DEPARTMENTS_DESCRIBED },
decorators: [
(Story) => (
<div className="min-h-96">
<Story />
</div>
),
],
}
export const Sizes: Story = {
render: () => (
<div className="flex max-w-md flex-col gap-5">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledSelect key={size} size={size} label={`Size ${size}`} options={DEPARTMENTS} />
))}
</div>
),
}
/**
* The themed states are the point of this story: the source could not render
* them because its classes were built dynamically.
*/
export const Themes: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info', 'error'] as const).map((theme) => (
<ControlledSelect
key={theme}
featured
theme={theme}
label={theme}
options={DEPARTMENTS}
initial="eng"
/>
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<Select key={size} {...args} size={size} label={`Size ${size}`} defaultValue="eng" />
))}
</div>
),
}
export const Variants: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['outlined', 'filled', 'standard', 'underlined'] as const).map((variant) => (
<ControlledSelect
key={variant}
featured
variant={variant}
label={variant}
options={DEPARTMENTS}
initial="fin"
/>
render: (args) => (
<div className="grid gap-5">
{SELECT_VARIANTS.map((variant) => (
<Select key={variant} {...args} variant={variant} label={variant === 'outline' ? 'Outline' : 'Filled'} />
))}
</div>
),
}
export const Widths: Story = {
render: () => (
<div className="flex flex-wrap items-end gap-4">
{(['xs', 'small', 'large', 'half'] as const).map((width) => (
<ControlledSelect key={width} width={width} label={width} options={DEPARTMENTS} />
/** Select, Input and Button share control heights, so they line up in a row. */
export const AlignedWithInput: Story = {
parameters: { wide: true },
render: (args) => (
<div className="grid gap-4">
{SIZES.map((size) => (
<div key={size} className="flex items-end gap-3">
<Input label={`Search (${size})`} size={size} placeholder="Jane Doe" className="w-56" />
<Select {...args} size={size} label="Department" className="w-56" />
<Button size={size}>Filter</Button>
</div>
))}
</div>
),
}
export const Loading: Story = {
args: { isLoading: true },
render: (args) => <ControlledSelect {...args} />,
}
export const Disabled: Story = {
args: { disabled: true, value: 'in' },
render: () => (
<div className="max-w-md">
<Select label="Country" options={COUNTRIES} value="in" disabled onChange={() => {}} />
</div>
),
export const WithDescription: Story = {
args: { description: 'Payroll reports are grouped by department.' },
}
export const WithError: Story = {
args: { error: 'Select the country where the entity is registered.' },
render: (args) => <ControlledSelect {...args} />,
args: { error: 'Choose the department this person reports to.', required: true },
}
/** An empty filter list, where the "all" option has an empty value. */
export const AllOptionsFilter: Story = {
render: () => (
<ControlledSelect
featured
searchable
label="Department filter"
options={[{ label: 'All departments', value: '' }, ...DEPARTMENTS]}
/>
),
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 = {
args: { startIcon: <Building2 />, defaultValue: 'ops' },
}
export const Clearable: Story = {
args: { clearable: true, defaultValue: 'design' },
}
export const Loading: Story = {
args: { loading: true, options: [] },
}
/** Options with a `group` are listed under headings. */
export const Grouped: Story = {
args: { label: 'Payroll currency', placeholder: 'Select a currency', options: CURRENCIES, defaultValue: 'eur' },
}
export const OptionDescriptions: Story = {
args: { options: DEPARTMENTS_DESCRIBED, defaultValue: 'eng' },
}
/** `multiple` keeps the popup open while choosing; the trigger lists up to two, then counts. */
export const Multiple: Story = {
args: {
label: 'Departments',
placeholder: 'Select departments',
multiple: true,
clearable: true,
defaultValue: ['eng', 'design', 'fin'],
},
}
export const MultipleTwoSelected: Story = {
args: { label: 'Departments', multiple: true, defaultValue: ['eng', 'fin'] },
}
/** `renderOption` draws each option. Here: an avatar with the employee's initials. */
export const CustomOptionRendering: Story = {
args: {
label: 'Manager',
placeholder: 'Select a manager',
options: EMPLOYEES,
defaultValue: 'e1',
defaultOpen: true,
renderOption: (option) => (
<span className="flex items-center gap-2.5">
<span
aria-hidden="true"
className="flex size-7 shrink-0 items-center justify-center rounded-full bg-primary-50 text-xs font-semibold text-primary-700 dark:bg-primary-500/15 dark:text-primary-300"
>
{option.label
.split(' ')
.map((part) => part[0])
.join('')}
</span>
<span className="flex min-w-0 flex-col">
<span className="truncate">{option.label}</span>
<span className="truncate text-xs font-normal text-fg-muted">{option.description}</span>
</span>
</span>
),
},
decorators: [
(Story) => (
<div className="min-h-[26rem]">
<Story />
</div>
),
],
}
export const WithActionButton: Story = {
render: () => (
<div className="max-w-md">
<Select
featured
label="Department"
options={DEPARTMENTS}
actionButton={{ label: '+ Create department', onClick: () => {} }}
/>
args: {
defaultOpen: true,
actionButton: { label: 'Add department', icon: <Plus />, onClick: fn() },
},
decorators: [
(Story) => (
<div className="min-h-96">
<Story />
</div>
),
],
}
/** 50 countries. Type a letter to jump; the list scrolls inside the popup. */
export const LongList: Story = {
args: {
label: 'Country of residence',
placeholder: 'Select a country',
options: COUNTRIES,
startIcon: <Globe />,
defaultValue: 'gb',
},
}
export const OpensUpward: Story = {
args: { side: 'top', defaultOpen: true },
decorators: [
(Story) => (
<div className="flex min-h-96 items-end">
<div className="w-full">
<Story />
</div>
</div>
),
],
}
function ControlledSelect(args: Story['args']) {
const [value, setValue] = useState<string | null>('hr')
return (
<div className="grid gap-2">
<Select {...withoutValue(args)} options={DEPARTMENTS} value={value} onValueChange={setValue} clearable />
<p className="text-sm text-fg-muted">Value: {value ?? '(none)'}</p>
</div>
),
)
}
/** Renders each option with a custom node. */
export const CustomOptionRenderer: Story = {
render: () => (
<ControlledSelect
featured
label="Department"
options={DEPARTMENTS}
renderOption={(opt) => (
<span className="flex items-center gap-2">
<span className="h-2 w-2 rounded-full bg-primary-500" />
{opt.label}
</span>
)}
/>
),
}
export const WithTooltip: Story = {
render: () => (
<ControlledSelect
featured
label="Country of registration"
options={COUNTRIES}
helpText="Determines the statutory rules applied to payroll in this entity."
/>
),
}
export const NonSearchable: Story = {
args: { featured: true, searchable: false },
export const Controlled: Story = {
render: (args) => <ControlledSelect {...args} />,
}
export const Uncontrolled: Story = {
args: { defaultValue: 'sales', name: 'department' },
}
+179
View File
@@ -0,0 +1,179 @@
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 { Select } from './Select'
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', disabled: true },
]
const grouped: SelectOption[] = [
{ value: 'usd', label: 'US Dollar', group: 'Americas' },
{ value: 'eur', label: 'Euro', group: 'Europe' },
{ value: 'cad', label: 'Canadian Dollar', group: 'Americas' },
]
describe('Select', () => {
it('links the label to the trigger', () => {
render(<Select label="Department" options={departments} />)
expect(screen.getByRole('combobox', { name: 'Department' })).toBeInTheDocument()
})
it('shows the placeholder, then the chosen label', async () => {
render(<Select label="Department" placeholder="Choose one" options={departments} />)
const trigger = screen.getByRole('combobox', { name: 'Department' })
expect(trigger).toHaveTextContent('Choose one')
await userEvent.click(trigger)
await userEvent.click(await screen.findByRole('option', { name: 'Finance' }))
expect(trigger).toHaveTextContent('Finance')
})
it('opens and chooses with the keyboard, then returns focus to the trigger', async () => {
const onValueChange = vi.fn()
render(<Select label="Department" options={departments} onValueChange={onValueChange} />)
const trigger = screen.getByRole('combobox', { name: 'Department' })
trigger.focus()
await userEvent.keyboard('{ArrowDown}')
const listbox = await screen.findByRole('listbox')
expect(listbox).toBeVisible()
await userEvent.keyboard('{ArrowDown}')
await userEvent.keyboard('{Enter}')
expect(onValueChange).toHaveBeenCalledTimes(1)
expect(typeof onValueChange.mock.calls[0][0]).toBe('string')
await waitFor(() => expect(trigger).toHaveFocus())
})
it('closes on Escape and returns focus to the trigger', async () => {
render(<Select label="Department" options={departments} />)
const trigger = screen.getByRole('combobox', { name: 'Department' })
await userEvent.click(trigger)
expect(await screen.findByRole('listbox')).toBeInTheDocument()
await userEvent.keyboard('{Escape}')
expect(trigger).toHaveAttribute('aria-expanded', 'false')
await waitFor(() => expect(trigger).toHaveFocus())
})
it('marks the selected option and disables disabled ones', async () => {
render(<Select label="Department" options={departments} defaultValue="hr" defaultOpen />)
expect(await screen.findByRole('option', { name: 'People & Culture' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('option', { name: 'Operations' })).toHaveAttribute('aria-disabled', 'true')
})
it('works controlled', async () => {
function Controlled() {
const [value, setValue] = useState<string | null>('eng')
return (
<>
<Select label="Department" options={departments} value={value} onValueChange={setValue} />
<output>{value}</output>
</>
)
}
render(<Controlled />)
const trigger = screen.getByRole('combobox', { name: 'Department' })
expect(trigger).toHaveTextContent('Engineering')
await userEvent.click(trigger)
await userEvent.click(await screen.findByRole('option', { name: 'Finance' }))
expect(screen.getByRole('status')).toHaveTextContent('fin')
expect(trigger).toHaveTextContent('Finance')
})
it('keeps a controlled value when the parent ignores changes', async () => {
const onValueChange = vi.fn()
render(<Select label="Department" options={departments} value="eng" onValueChange={onValueChange} />)
const trigger = screen.getByRole('combobox', { name: 'Department' })
await userEvent.click(trigger)
await userEvent.click(await screen.findByRole('option', { name: 'Finance' }))
expect(onValueChange).toHaveBeenCalledWith('fin')
expect(trigger).toHaveTextContent('Engineering')
})
it('selects several values with `multiple` and summarises them', async () => {
const onValueChange = vi.fn()
render(
<Select label="Departments" multiple options={departments} defaultValue={['eng']} onValueChange={onValueChange} />,
)
const trigger = screen.getByRole('combobox', { name: 'Departments' })
expect(trigger).toHaveTextContent('Engineering')
await userEvent.click(trigger)
await userEvent.click(await screen.findByRole('option', { name: 'Finance' }))
expect(onValueChange).toHaveBeenLastCalledWith(['eng', 'fin'])
expect(trigger).toHaveTextContent('Engineering, Finance')
await userEvent.click(screen.getByRole('option', { name: 'People & Culture' }))
expect(trigger).toHaveTextContent('3 selected')
})
it('clears with a labelled button and refocuses the trigger', async () => {
const onValueChange = vi.fn()
render(
<Select label="Department" clearable options={departments} defaultValue="fin" onValueChange={onValueChange} />,
)
await userEvent.click(screen.getByRole('button', { name: 'Clear Department' }))
expect(onValueChange).toHaveBeenCalledWith(null)
const trigger = screen.getByRole('combobox', { name: 'Department' })
expect(trigger).toHaveTextContent('Select an option')
expect(trigger).toHaveFocus()
expect(screen.queryByRole('button', { name: 'Clear Department' })).not.toBeInTheDocument()
})
it('renders groups with headings', async () => {
render(<Select label="Currency" options={grouped} defaultOpen />)
const groups = await screen.findAllByRole('group')
expect(groups).toHaveLength(2)
expect(within(groups[0]).getByText('Americas')).toBeInTheDocument()
expect(within(groups[0]).getAllByRole('option')).toHaveLength(2)
})
it('shows a loading row and marks the trigger busy', async () => {
render(<Select label="Department" options={[]} loading defaultOpen />)
expect(screen.getByRole('combobox', { name: 'Department' })).toHaveAttribute('aria-busy', 'true')
expect(await screen.findByText('Loading options…')).toBeInTheDocument()
})
it('uses renderOption for option content', async () => {
render(
<Select
label="Department"
options={departments}
defaultOpen
renderOption={(option) => <span data-testid="custom">{option.label.toUpperCase()}</span>}
/>,
)
expect((await screen.findAllByTestId('custom'))[0]).toHaveTextContent('ENGINEERING')
})
it('announces the description, and the error when invalid', () => {
const { rerender } = render(<Select label="Department" description="Where they report." options={departments} />)
expect(screen.getByRole('combobox')).toHaveAccessibleDescription('Where they report.')
rerender(<Select label="Department" description="Where they report." error="Choose a department." options={departments} />)
const trigger = screen.getByRole('combobox')
expect(trigger).toHaveAttribute('aria-invalid', 'true')
expect(trigger).toHaveAccessibleDescription('Choose a department.')
})
it('submits its value under `name`', () => {
const { container } = render(<Select label="Department" name="department" options={departments} defaultValue="eng" />)
expect(container.querySelector('input[name="department"]')).toHaveValue('eng')
})
it('is disabled', () => {
render(<Select label="Department" disabled options={departments} />)
expect(screen.getByRole('combobox', { name: 'Department' })).toHaveAttribute('data-disabled')
})
it('has no axe violations, closed and open', async () => {
const { container } = render(
<Select label="Department" description="Where they report." required clearable defaultValue="eng" options={grouped} />,
)
await expectNoA11yViolations(container)
await userEvent.click(screen.getByRole('combobox', { name: /Department/ }))
await screen.findByRole('listbox')
await expectNoA11yViolations(document.body)
})
})
+207 -63
View File
@@ -1,75 +1,219 @@
import { forwardRef } from 'react'
import { cn } from '@/lib/cn'
import { NativeSelect, type SelectOption } from './NativeSelect'
import { FeaturedSelect } from './FeaturedSelect'
import type { DropdownPlacement } from '@/lib/useDropdownPosition'
import type {
SelectSize,
SelectTheme,
SelectVariant,
SelectWidth,
import { Select as BaseSelect } from '@base-ui/react/select'
import { useRef, type ComponentProps, type ReactNode } from 'react'
import { cn } from '../lib/cn'
import { useControllableState } from '../lib/useControllableState'
import { Field } from './Field'
import { ActionFooter, Chevron, ClearButton, SelectOptions, Spinner, StatusRow } from './SelectParts'
import {
CLEAR_SPACER,
listClass,
popupClass,
summarize,
triggerClass,
type RenderOption,
type SelectActionButton,
type SelectOption,
type SelectSide,
type SelectSize,
type SelectValue,
type SelectVariant,
} from './select.tokens'
/**
* Select dispatcher: a native `<select>` by default, or the custom searchable
* dropdown when `featured` is set.
*
* Ported from the original `Select` component.
*
* Form-library props (`register`, `validation`) are not ported — pass `value`
* and `onChange` directly.
*/
export type { SelectOption } from './select.tokens'
export type SelectProps = {
options?: SelectOption[]
value?: string
onChange?: (value: string) => void
/** Renders the custom dropdown with a floating label instead of a native select. */
featured?: boolean
label?: string
name?: string
placeholder?: string
size?: SelectSize
theme?: SelectTheme
variant?: SelectVariant
width?: SelectWidth
disabled?: boolean
/** Props every select-like component shares (Select and FeaturedSelect). */
export type SelectBaseProps<Multiple extends boolean | undefined = false> = Omit<
ComponentProps<'button'>,
'value' | 'defaultValue' | 'onChange' | 'children' | 'type' | 'className'
> & {
/** Visible label, linked to the trigger. */
label?: ReactNode
/** Help text under the trigger, announced with it. */
description?: ReactNode
/** Error message. Marks the select invalid and replaces `description`. */
error?: ReactNode
/** Shows the required mark and requires a value in forms. */
required?: boolean
error?: string | { message?: string }
isLoading?: boolean
isClearable?: 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 when nothing is selected. */
placeholder?: string
/** The choices. Options sharing a `group` are listed under that heading. */
options: SelectOption[]
/** Allows several values. `value` is then a `string[]`. */
multiple?: Multiple
/** The selected value (controlled): a string or null, or a string array with `multiple`. */
value?: SelectValue<Multiple>
/** The initial value (uncontrolled). */
defaultValue?: SelectValue<Multiple>
/** Fires with the new value. */
onValueChange?: (value: SelectValue<Multiple>) => void
/** Shows a button that clears the value. */
clearable?: boolean
/** Shows a spinner and a loading row while options load. */
loading?: boolean
/** Text of the loading row. */
loadingText?: ReactNode
/** Custom content for each option in the list. */
renderOption?: RenderOption
/** Icon before the value. */
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
/** A footer button in the popup, such as "Add department". */
actionButton?: SelectActionButton
/** Classes for the outer field wrapper. Use `triggerClassName` for the trigger. */
className?: string
floatinglabelClass?: string
shrink?: boolean
searchable?: boolean
onSearchChange?: (term: string) => void
scrollToSelected?: boolean
placement?: DropdownPlacement
initialSearchTerm?: string
actionButton?: { label: string; onClick: () => void; icon?: React.ReactNode }
renderOption?: (opt: SelectOption) => React.ReactNode
tooltip?: string
tooltipIcon?: React.ComponentProps<typeof import('./Tooltip').Tooltip>['icon']
helpText?: string
triggerClassName?: string
}
export const Select = forwardRef<HTMLDivElement, SelectProps>(function Select({
featured = false,
className = '',
export type SelectProps<Multiple extends boolean | undefined = false> = SelectBaseProps<Multiple>
/**
* A dropdown for choosing one or several values from a short list, with its
* label above. Built on Base UI Select, so keyboard navigation, type-ahead
* and focus return come for free. For long lists, use Combobox or
* FeaturedSelect with `searchable`.
*/
export function Select<Multiple extends boolean | undefined = false>({
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,
className,
triggerClassName,
...props
}, ref) {
if (featured) {
return <FeaturedSelect ref={ref} {...props} className={className} />
}: SelectProps<Multiple>) {
const empty = (multiple ? [] : null) as SelectValue<Multiple>
const [value, setValue] = useControllableState<SelectValue<Multiple>>(
valueProp,
defaultValue ?? empty,
onValueChange,
)
const [open, setOpen] = useControllableState(openProp, defaultOpen, onOpenChange)
const wrapperRef = useRef<HTMLDivElement>(null)
const selected = new Set<string>(Array.isArray(value) ? value : value != null ? [value] : [])
const hasValue = selected.size > 0
const invalid = error != null && error !== false && error !== ''
const showClear = clearable && hasValue && !disabled && !readOnly && !loading
const labelOf = (v: string) => options.find((o) => o.value === v)?.label ?? v
function clear() {
setValue(empty)
wrapperRef.current?.querySelector<HTMLElement>('[role="combobox"]')?.focus()
}
return (
<NativeSelect
ref={ref as React.Ref<HTMLSelectElement>}
{...props}
className={cn(className)}
/>
<Field
label={label}
description={description}
error={error}
required={required}
disabled={disabled}
name={name}
nativeLabel={false}
className={className}
>
<BaseSelect.Root
items={options}
multiple={multiple}
value={value as never}
onValueChange={(next) => setValue(next as SelectValue<Multiple>)}
open={open}
onOpenChange={setOpen}
name={name}
required={required}
disabled={disabled}
readOnly={readOnly}
>
<div ref={wrapperRef} className="relative">
<BaseSelect.Trigger
aria-invalid={invalid || undefined}
aria-busy={loading || undefined}
className={triggerClass(size, variant, triggerClassName)}
{...props}
>
{startIcon != null && (
<span aria-hidden="true" className="flex shrink-0 text-fg-muted">
{startIcon}
</span>
)}
<BaseSelect.Value
placeholder={placeholder}
className="min-w-0 flex-1 truncate data-placeholder:text-fg-muted"
>
{multiple
? (current: string[]) => (current.length ? summarize(current.map(labelOf)) : placeholder)
: undefined}
</BaseSelect.Value>
{showClear && <span aria-hidden="true" className={cn('shrink-0', CLEAR_SPACER[size])} />}
<BaseSelect.Icon className="flex shrink-0 text-fg-muted">
{loading ? <Spinner /> : <Chevron />}
</BaseSelect.Icon>
</BaseSelect.Trigger>
{showClear && (
<ClearButton
size={size}
label={typeof label === 'string' ? `Clear ${label}` : 'Clear selection'}
onClear={clear}
/>
)}
</div>
<BaseSelect.Portal>
{/* Transparent: marks the modal popup's page as inert to pointers and to assistive checks. */}
<BaseSelect.Backdrop className="fixed inset-0 z-50" />
<BaseSelect.Positioner
side={side}
sideOffset={6}
alignItemWithTrigger={false}
className="z-50 outline-none"
>
<BaseSelect.Popup className={popupClass()}>
{loading && <StatusRow loading>{loadingText}</StatusRow>}
{!loading && options.length === 0 && <StatusRow>No options</StatusRow>}
<BaseSelect.List aria-busy={loading || undefined} className={listClass}>
{!loading && (
<SelectOptions options={options} isSelected={(v) => selected.has(v)} renderOption={renderOption} />
)}
</BaseSelect.List>
{actionButton && <ActionFooter action={actionButton} onDone={() => setOpen(false)} />}
</BaseSelect.Popup>
</BaseSelect.Positioner>
</BaseSelect.Portal>
</BaseSelect.Root>
</Field>
)
})
export type { SelectOption }
export default Select
}
+275
View File
@@ -0,0 +1,275 @@
/**
* Internal building blocks shared by Select, FeaturedSelect and Combobox:
* the option rows, group headings, loading and empty rows, the clear button
* and the popup footer action. Not part of the public API.
*/
import { Combobox as BaseCombobox } from '@base-ui/react/combobox'
import { Select as BaseSelect } from '@base-ui/react/select'
import { Check, ChevronDown, LoaderCircle, X } from 'lucide-react'
import { Fragment, useId, type ReactNode } from 'react'
import { cn } from '../lib/cn'
import { focusRing, listItem } from '../lib/styles'
import {
groupOptions,
listClass,
type ComboboxGroup,
type RenderOption,
type SelectActionButton,
type SelectOption,
type SelectSize,
} from './select.tokens'
const itemClass = cn(listItem, 'scroll-my-1 py-2 data-selected:font-medium')
const groupLabelClass = 'px-2.5 pt-2 pb-1 text-xs font-semibold text-fg-muted select-none'
const separatorClass = 'mx-1 my-1 h-px bg-border'
const indicatorClass = 'ml-auto flex shrink-0 text-primary-600 dark:text-primary-400 [&_svg]:size-4'
export function Chevron() {
return <ChevronDown aria-hidden="true" />
}
export function Spinner({ className }: { className?: string }) {
return <LoaderCircle aria-hidden="true" className={cn('animate-spin motion-reduce:animate-none', className)} />
}
/** Right offset of the clear button, so it sits in the spacer left of the chevron. */
const CLEAR_RIGHT: Record<SelectSize, string> = { sm: 'right-8', md: 'right-9', lg: 'right-11' }
const CLEAR_BOX: Record<SelectSize, string> = {
sm: 'size-5 [&_svg]:size-3.5',
md: 'size-6 [&_svg]:size-4',
lg: 'size-7 [&_svg]:size-4.5',
}
/** A real, labelled button that clears the value. Positioned over the trigger's spacer. */
export function ClearButton({
size,
label,
onClear,
className,
}: {
size: SelectSize
label: string
onClear: () => void
className?: string
}) {
return (
<button
type="button"
aria-label={label}
onClick={onClear}
className={cn(
'absolute top-1/2 z-10 flex -translate-y-1/2 items-center justify-center rounded-md text-fg-muted transition-colors hover:bg-surface-sunken hover:text-fg',
focusRing,
'focus-visible:outline-offset-0',
CLEAR_RIGHT[size],
CLEAR_BOX[size],
className,
)}
>
<X aria-hidden="true" />
</button>
)
}
/** Label, description and custom rendering of one option. */
function OptionBody({
option,
selected,
renderOption,
descriptionId,
}: {
option: SelectOption
selected: boolean
renderOption?: RenderOption
descriptionId: string
}) {
if (renderOption) return <span className="min-w-0 flex-1">{renderOption(option, { selected })}</span>
return (
<span className="flex min-w-0 flex-1 flex-col">
<span className="truncate">{option.label}</span>
{option.description && (
<span id={descriptionId} className="truncate text-xs font-normal leading-5 text-fg-muted">
{option.description}
</span>
)}
</span>
)
}
function SelectItem({
option,
selected,
renderOption,
}: {
option: SelectOption
selected: boolean
renderOption?: RenderOption
}) {
const descriptionId = useId()
const described = option.description && !renderOption
return (
<BaseSelect.Item
value={option.value}
label={option.label}
disabled={option.disabled}
aria-label={renderOption ? undefined : option.label}
aria-describedby={described ? descriptionId : undefined}
className={itemClass}
>
<OptionBody option={option} selected={selected} renderOption={renderOption} descriptionId={descriptionId} />
<BaseSelect.ItemIndicator className={indicatorClass}>
<Check aria-hidden="true" />
</BaseSelect.ItemIndicator>
</BaseSelect.Item>
)
}
/** Items for a Base UI Select list, grouped by `group` when any option has one. */
export function SelectOptions({
options,
isSelected,
renderOption,
}: {
options: SelectOption[]
isSelected: (value: string) => boolean
renderOption?: RenderOption
}) {
return groupOptions(options).map((group, index) => {
const items = group.items.map((option) => (
<SelectItem
key={option.value}
option={option}
selected={isSelected(option.value)}
renderOption={renderOption}
/>
))
if (group.label === null) return <Fragment key="__ungrouped">{items}</Fragment>
return (
<Fragment key={group.label}>
{index > 0 && <BaseSelect.Separator className={separatorClass} />}
<BaseSelect.Group>
<BaseSelect.GroupLabel className={groupLabelClass}>{group.label}</BaseSelect.GroupLabel>
{items}
</BaseSelect.Group>
</Fragment>
)
})
}
export function ComboboxItem({
option,
selected,
renderOption,
index,
}: {
option: SelectOption
selected: boolean
renderOption?: RenderOption
index?: number
}) {
const descriptionId = useId()
const described = option.description && !renderOption
return (
<BaseCombobox.Item
value={option}
index={index}
disabled={option.disabled}
aria-label={renderOption ? undefined : option.label}
aria-describedby={described ? descriptionId : undefined}
className={itemClass}
>
<OptionBody option={option} selected={selected} renderOption={renderOption} descriptionId={descriptionId} />
<BaseCombobox.ItemIndicator className={indicatorClass}>
<Check aria-hidden="true" />
</BaseCombobox.ItemIndicator>
</BaseCombobox.Item>
)
}
/** The list inside a Base UI Combobox popup, grouped or flat. */
export function ComboboxOptions({
grouped,
isSelected,
renderOption,
}: {
grouped: boolean
isSelected: (value: string) => boolean
renderOption?: RenderOption
}) {
if (!grouped) {
return (
<BaseCombobox.List className={cn(listClass, 'data-empty:hidden')}>
{(option: SelectOption, index: number) => (
<ComboboxItem
key={option.value}
option={option}
index={index}
selected={isSelected(option.value)}
renderOption={renderOption}
/>
)}
</BaseCombobox.List>
)
}
return (
<BaseCombobox.List className={cn(listClass, 'data-empty:hidden')}>
{(group: ComboboxGroup, index: number) => (
<Fragment key={group.value || '__ungrouped'}>
{index > 0 && <BaseCombobox.Separator className={separatorClass} />}
<BaseCombobox.Group items={group.items}>
{group.value && (
<BaseCombobox.GroupLabel className={groupLabelClass}>{group.value}</BaseCombobox.GroupLabel>
)}
<BaseCombobox.Collection>
{(option: SelectOption) => (
<ComboboxItem
key={option.value}
option={option}
selected={isSelected(option.value)}
renderOption={renderOption}
/>
)}
</BaseCombobox.Collection>
</BaseCombobox.Group>
</Fragment>
)}
</BaseCombobox.List>
)
}
/** A muted row for loading, empty and status messages. */
export function StatusRow({ loading, children }: { loading?: boolean; children: ReactNode }) {
return (
<div className="flex items-center gap-2 px-3 py-2.5 text-sm text-fg-muted [&_svg]:size-4">
{loading && <Spinner />}
{children}
</div>
)
}
/** Footer button in a popup, such as "Add department". */
export function ActionFooter({ action, onDone }: { action: SelectActionButton; onDone: () => void }) {
return (
<div className="shrink-0 border-t border-border p-1">
<button
type="button"
onClick={() => {
onDone()
action.onClick()
}}
className={cn(
listItem,
focusRing,
'w-full py-2 font-medium text-primary-700 hover:bg-surface-sunken focus-visible:outline-offset-0 dark:text-primary-300 [&_svg]:size-4',
)}
>
{action.icon != null && (
<span aria-hidden="true" className="flex">
{action.icon}
</span>
)}
{action.label}
</button>
</div>
)
}
+112
View File
@@ -0,0 +1,112 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Button } from './Button'
import { Separator } from './Separator'
const meta = {
title: 'Layout/Separator',
component: Separator,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'A thin rule between groups of content, built on Base UI Separator (`role="separator"` with `aria-orientation`). Add a `label` such as "or" in the middle, and use `dashed` for a lighter break. Vertical separators stretch to the height of their flex row.',
},
},
},
argTypes: {
orientation: { control: 'inline-radio', options: ['horizontal', 'vertical'], table: { defaultValue: { summary: 'horizontal' } } },
variant: { control: 'inline-radio', options: ['solid', 'dashed'], table: { defaultValue: { summary: 'solid' } } },
label: { control: 'text' },
className: { control: 'text' },
},
args: {
orientation: 'horizontal',
variant: 'solid',
},
} satisfies Meta<typeof Separator>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {
render: (args) => (
<div className={args.orientation === 'vertical' ? 'flex h-16 items-center gap-4 text-sm text-fg' : 'grid max-w-md gap-4 text-sm text-fg'}>
<span>Account</span>
<Separator {...args} />
<span>Billing</span>
</div>
),
}
export const Horizontal: Story = {
render: () => (
<div className="grid max-w-md gap-4 text-sm">
<div>
<p className="font-medium text-fg">Jane Doe</p>
<p className="text-fg-muted">jane.doe@example.com</p>
</div>
<Separator />
<p className="text-fg-muted">Member of Acme Corporation since March 2021.</p>
<Separator variant="dashed" />
<p className="text-fg-muted">Dashed separators work well inside forms and lists.</p>
</div>
),
}
export const Vertical: Story = {
render: () => (
<div className="grid gap-5 text-sm">
<nav aria-label="Footer" className="flex h-5 items-center gap-4 text-fg-muted">
<a href="#privacy" className="hover:text-fg">
Privacy
</a>
<Separator orientation="vertical" />
<a href="#terms" className="hover:text-fg">
Terms
</a>
<Separator orientation="vertical" />
<a href="#status" className="hover:text-fg">
Status
</a>
</nav>
<div className="flex h-10 items-center gap-3">
<Button size="sm" variant="ghost" color="neutral">
Bold
</Button>
<Button size="sm" variant="ghost" color="neutral">
Italic
</Button>
<Separator orientation="vertical" variant="dashed" />
<Button size="sm" variant="ghost" color="neutral">
Link
</Button>
</div>
</div>
),
}
export const WithLabel: Story = {
parameters: { docs: { description: { story: 'A label in the middle, e.g. between two sign-in methods.' } } },
render: () => (
<div className="grid max-w-sm gap-5 rounded-xl border border-border bg-surface p-6">
<Button variant="outline" color="neutral" fullWidth>
Continue with SSO
</Button>
<Separator label="or" />
<Button fullWidth>Continue with email</Button>
<Separator label="Recent activity" variant="dashed" />
<p className="text-sm text-fg-muted">Last signed in 2 hours ago from Lisbon.</p>
</div>
),
}
export const VerticalWithLabel: Story = {
render: () => (
<div className="flex h-40 max-w-md items-stretch gap-4 text-sm">
<div className="flex flex-1 items-center justify-center rounded-lg bg-surface-sunken text-fg-muted">Upload a file</div>
<Separator orientation="vertical" label="or" />
<div className="flex flex-1 items-center justify-center rounded-lg bg-surface-sunken text-fg-muted">Paste a link</div>
</div>
),
}
+32
View File
@@ -0,0 +1,32 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { expectNoA11yViolations } from '../test/a11y'
import { Separator } from './Separator'
describe('Separator', () => {
it('has the separator role, horizontal by default', () => {
render(<Separator />)
expect(screen.getByRole('separator')).toHaveAttribute('aria-orientation', 'horizontal')
})
it('sets a vertical orientation', () => {
render(<Separator orientation="vertical" />)
expect(screen.getByRole('separator')).toHaveAttribute('aria-orientation', 'vertical')
})
it('renders a label in the middle', () => {
render(<Separator label="or" variant="dashed" />)
expect(screen.getByRole('separator')).toHaveTextContent('or')
})
it('has no axe violations', async () => {
const { container } = render(
<div>
<Separator />
<Separator label="or" />
<Separator orientation="vertical" />
</div>,
)
await expectNoA11yViolations(container)
})
})
+48
View File
@@ -0,0 +1,48 @@
import type { ReactNode } from 'react'
import { Separator as BaseSeparator } from '@base-ui/react/separator'
import { cn } from '../lib/cn'
export type SeparatorProps = Omit<BaseSeparator.Props, 'className'> & {
/** Direction of the line. Vertical separators stretch to the height of a flex row. */
orientation?: 'horizontal' | 'vertical'
/** Text in the middle of the line, e.g. "or". */
label?: ReactNode
/** Line style. */
variant?: 'solid' | 'dashed'
className?: string
}
/** A thin rule between groups of content, with an optional label such as "or". */
export function Separator({ orientation = 'horizontal', label, variant = 'solid', className, ...props }: SeparatorProps) {
const horizontal = orientation === 'horizontal'
const line = cn(
variant === 'dashed' ? 'border-dashed border-border-strong' : 'border-solid border-border',
horizontal ? 'w-full border-t' : 'h-full min-h-4 border-l',
)
if (label == null) {
return (
<BaseSeparator
orientation={orientation}
className={cn('shrink-0', line, horizontal ? '' : 'self-stretch', className)}
{...props}
/>
)
}
return (
<BaseSeparator
orientation={orientation}
className={cn(
'flex shrink-0 items-center gap-3',
horizontal ? 'w-full flex-row' : 'flex-col self-stretch',
className,
)}
{...props}
>
<span aria-hidden="true" className={cn(line, 'flex-1')} />
<span className="shrink-0 text-xs font-medium text-fg-muted">{label}</span>
<span aria-hidden="true" className={cn(line, 'flex-1')} />
</BaseSeparator>
)
}
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more