Package Tansy UI as @openkhalix/tansy-ui in a monorepo (v0.4.0)
CI / check (push) Successful in 3m9s
Release / publish (push) Failing after 1m22s

Restructure the repo into npm workspaces so the component kit publishes as
its own package, like MUI and shadcn/ui:

- packages/ui: @openkhalix/tansy-ui (published), with components, stories,
  tests, tokens and the library build
- packages/brand: private logo and catalogue data shared by both apps
- apps/site: the landing page
- apps/docs: Storybook

The package:
- MIT licence (copyright OpenKhalix)
- per-component ES modules and type declarations
- "use client" on component modules so they import into Next.js Server
  Components; helpers stay server-safe
- tokens.css for Tailwind v4 apps, and a prebuilt styles.css for apps
  without Tailwind
- lucide-react 1.x, whose types compile against current React 19 types

The apps resolve the package through a "source" export condition, so they
hot-reload component edits, while outside users get dist/.

scripts/test-package.mjs packs the package and installs the tarball into
Vite + Tailwind (strict types), plain React and Next.js apps; each must
build and render correctly. Gitea workflows run CI on push and publish to
npm when a vX.Y.Z tag matching the package version is pushed.
This commit is contained in:
thekhalidsha committed 2026-09-29 09:24:03 +05:30
1 parent 23e67006d3
commit 9255b255a6
214 files changed
+1521 -389

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
# Changelog
All notable changes to Tansy UI are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[Semantic Versioning](https://semver.org/spec/v2.0.0.html). While the version is
`0.x`, a minor release may include breaking changes.
## [Unreleased]
## [0.4.0] - 2026-09-29
Tansy UI is now a publishable npm package: **`@openkhalix/tansy-ui`**.
### Added
- **Package:** `npm install @openkhalix/tansy-ui`. One ES module per component
(tree-shakeable), TypeScript declarations, and MIT licence.
- **Two ways to style:** `@openkhalix/tansy-ui/tokens.css` for Tailwind v4
apps, or the prebuilt `@openkhalix/tansy-ui/styles.css` for apps without
Tailwind (tokens, the utilities the components use, and a modern reset).
- **Next.js:** component modules are marked `"use client"`, so they import
directly into Server Components; helpers stay server-safe.
- **Install tests:** `npm run test:package` installs the packed tarball into
Vite + Tailwind (strict types), plain React and Next.js apps and checks each
builds and renders correctly.
- **Release workflow:** tag `vX.Y.Z` to publish from CI.
### Changed
- **Monorepo:** the package lives in `packages/ui`, the landing page in
`apps/site` and Storybook in `apps/docs`.
- `lucide-react` 1.x (0.460's types don't compile against current React 19
types when an app type-checks its dependencies).
### Breaking
- The package name is `@openkhalix/tansy-ui` (it was the unpublished
`tansy-ui`), and its build output moved from `dist-lib/` to `dist/`.
## [0.3.1] - 2026-09-28
Every component and the landing page now work from 320px phones to wide
desktops without scrolling sideways.
### Fixed
- **Inputs:** Input, FeaturedInput, NumberInput and Combobox shrink to fit
narrow containers. Inputs no longer hold their ~20-character native width
inside flex rows.
- **Tabs:** a row of tabs that doesn't fit scrolls sideways within itself, and
vertical tabs stack above their panel on phones.
- **ToggleGroup:** scrolls within itself when wider than the screen; its focus
ring is drawn inset so scrolling can't clip it.
- **Popups:** menus, selects, popovers and tooltips never grow past the screen
edge (they cap at Base UI's `--available-width`).
- **Landing page:** the header no longer crowds at tablet widths, and the code
sample fits its card at 1024px.
- **Storybook:** the Accessibility panel no longer counts page-level rules
(`<main>`, `<h1>`, landmarks) that can't apply to an isolated component.
### Added
- `scripts/check-stories.mjs --width <px>` fails any story that makes the page
scroll sideways at that width.
## [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.
### Added
- 15 components with colocated tokens and stories: Button, LinkButton, Accordion,
TextField, Input, FeaturedInput, Select, Checkbox, Radio, Switch, TextArea,
Alert, Spinner, Badge, Card and Tooltip.
- Seven palettes (Classic Blue, Emerald, Violet, Amber, Crimson, Slate, Teal)
applied at runtime with `applyPalette()`.
- Landing page built only from Tansy components, with five featured parts and a
palette-switching playground form.
- Storybook workshop with Tansy branding, a Welcome page and a palette toolbar.
- Tansy mark and favicon.
- `version.json` on every deploy, recording the version and commit that were shipped.
### Fixed
- `Switch` now honours `defaultChecked`, including after a form reset.
- Button, Accordion and TextField follow the active palette.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 OpenKhalix
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+115
View File
@@ -0,0 +1,115 @@
# Tansy UI
A themeable, accessible React component kit by [OpenKhalix](https://ui.openkhalix.com), built on
[Base UI](https://base-ui.com) and Tailwind CSS v4.
- **38 components:** forms with floating labels, selects and comboboxes, dialogs, drawers, menus, tabs,
toasts, tables and more.
- **Accessible:** keyboard support and screen-reader wiring from Base UI, visible focus rings, and every
story checked with axe in light and dark mode.
- **Themeable:** seven palettes switchable at runtime, class-based dark mode, and one semantic token set.
- **One API:** `color`, `variant` and `size` on everything; `label`, `description` and `error` on every
field; controlled or uncontrolled values.
**Docs and live examples:** https://ui.openkhalix.com/docs/
## Install
```bash
npm install @openkhalix/tansy-ui
```
Needs React 19. `@base-ui/react`, `lucide-react`, `clsx` and `tailwind-merge` install with it.
## Add the styles
Pick one of the two setups.
### With Tailwind CSS v4 (recommended)
Import the tokens after Tailwind, and let Tailwind scan the package for the classes it uses:
```css
/* app.css */
@import "tailwindcss";
@import "@openkhalix/tansy-ui/tokens.css";
@source "../node_modules/@openkhalix/tansy-ui/dist";
```
Your own Tailwind utilities can then use the same tokens (`bg-surface`, `text-fg`, `bg-primary-500`).
### Without Tailwind
Import the prebuilt stylesheet once, for example in your entry file:
```ts
import '@openkhalix/tansy-ui/styles.css'
```
It contains the tokens, only the utilities the components use, and a modern CSS reset (Tailwind's
preflight), which the components rely on, much as MUI relies on `CssBaseline`. The reset normalises
margins, borders and form controls across your app. If you already use Tailwind, use the setup above
instead.
## Use
```tsx
import { Mail } from 'lucide-react'
import { Button, FeaturedInput, Select, Switch } from '@openkhalix/tansy-ui'
export function InviteForm() {
return (
<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>
</form>
)
}
```
### Next.js
Components are marked `"use client"`, so you can import them straight into Server Components. Helpers such
as `cn` and `applyPalette` stay server-safe.
## Dark mode and palettes
```ts
import { applyPalette } from '@openkhalix/tansy-ui'
document.documentElement.classList.toggle('dark', true) // dark mode
applyPalette(document.documentElement, 'emerald') // classicBlue, emerald, violet, amber, crimson, slate, teal
```
Apply a palette to `<html>` so popups, which render in a portal, pick it up too.
## Components
| Group | Components |
|---|---|
| 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` |
Every component has a Storybook page with its props, controls and a story for each state:
https://ui.openkhalix.com/docs/
## Licence and credit
MIT © OpenKhalix. Use it, fork it, and ship it in commercial products, free. The licence's only condition
is that you keep the copyright notice in copies of the code.
If Tansy UI helps you, a visible credit such as "UI by [Tansy UI](https://ui.openkhalix.com)" in your
README or site footer is much appreciated. It isn't required.
+78
View File
@@ -0,0 +1,78 @@
{
"name": "@openkhalix/tansy-ui",
"version": "0.4.0",
"description": "A themeable, accessible React component kit built on Base UI and Tailwind CSS v4.",
"license": "MIT",
"author": "OpenKhalix",
"homepage": "https://ui.openkhalix.com",
"keywords": [
"react",
"components",
"ui",
"design-system",
"tailwindcss",
"base-ui",
"accessible",
"dark-mode"
],
"type": "module",
"sideEffects": [
"*.css"
],
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"source": "./src/index.ts",
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./tokens.css": "./dist/tokens.css",
"./styles.css": "./dist/styles.css",
"./package.json": "./package.json"
},
"files": [
"dist",
"README.md",
"CHANGELOG.md",
"LICENSE"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "vite build --config vite.lib.config.ts && tsc -p tsconfig.lib.json && cp src/styles/tokens.css dist/tokens.css && tailwindcss -i src/styles/styles.css -o dist/styles.css --minify",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"prepublishOnly": "npm run typecheck && npm test && npm run build"
},
"peerDependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"dependencies": {
"@base-ui/react": "^1.8.0",
"clsx": "^2.1.1",
"lucide-react": "^1.48.0",
"tailwind-merge": "^3.7.0"
},
"devDependencies": {
"@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",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.3.0",
"vitest": "^5.0.2",
"@tailwindcss/cli": "^4.3.3"
}
}
@@ -0,0 +1,134 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
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',
component: Accordion,
tags: ['autodocs'],
parameters: {
docs: {
description: {
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.',
},
},
},
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 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: { 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>
)
},
}
@@ -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)
})
})
+91
View File
@@ -0,0 +1,91 @@
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 = {
/** Unique id for the item; used in `value`. */
value: string
title: ReactNode
content: ReactNode
disabled?: boolean
}
export type AccordionProps = Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & {
items: AccordionItem[]
/** 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
}
/**
* 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 (
<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}
>
{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>
)
}
@@ -0,0 +1,237 @@
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',
component: Alert,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'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: 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: {
color: 'info',
variant: 'soft',
title: MESSAGES.info.title,
children: MESSAGES.info.body,
hideIcon: false,
dismissible: false,
autoClose: 0,
onOpenChange: fn(),
},
decorators: [
(Story) => (
<div className="max-w-2xl">
<Story />
</div>
),
],
} satisfies Meta<typeof Alert>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Colors: Story = {
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 Solid: Story = {
args: { variant: 'solid' },
render: Colors.render,
}
export const Outline: Story = {
args: { variant: 'outline' },
render: Colors.render,
}
export const TitleOnly: Story = {
render: (args) => (
<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)
})
+150
View File
@@ -0,0 +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 {
ALERT_CLOSE_STYLES,
ALERT_ICON_STYLES,
ALERT_STYLES,
ALERT_URGENT_COLORS,
type AlertColor,
type AlertVariant,
} from './alert.tokens'
export type AlertProps = Omit<ComponentProps<'div'>, 'color' | 'title'> & {
/** Semantic colour. `danger` and `warning` use `role="alert"`; the rest are polite `role="status"`. */
color?: AlertColor
/** 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
}
const DEFAULT_ICONS: Record<AlertColor, ReactNode> = {
info: <Info />,
success: <CircleCheck />,
warning: <TriangleAlert />,
danger: <CircleX />,
neutral: <Info />,
primary: <CircleAlert />,
}
/** 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(() => {
onDoneRef.current = onDone
})
useEffect(() => {
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))
}
}, [active, delay, paused])
}
/** 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)
useAutoClose(autoClose, hovered || focused, open, () => setOpen(false))
if (!open) return null
const urgent = ALERT_URGENT_COLORS.includes(color)
return (
<div
role={urgent ? 'alert' : 'status'}
className={cn(
'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}
>
{!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>
)
}
@@ -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>
),
}
@@ -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>
)
}
@@ -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 flex-wrap 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 flex-wrap 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>
),
}
@@ -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>
)
}
@@ -0,0 +1,328 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
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:
'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: {
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: {
children: 'Active',
color: 'success',
variant: 'soft',
size: 'md',
dot: false,
},
} satisfies Meta<typeof Badge>
export default meta
type Story = StoryObj<typeof meta>
const title = (s: string) => s[0].toUpperCase() + s.slice(1)
export const Playground: Story = {}
export const Variants: Story = {
render: (args) => (
<div className="flex flex-wrap items-center gap-3">
{BADGE_VARIANTS.map((variant) => (
<Badge key={variant} {...args} variant={variant}>
{title(variant)}
</Badge>
))}
</div>
),
}
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>
))}
{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 ColorByValue: Story = {
parameters: {
docs: { description: { story: '`colorRanges`: 0–4 success, 5–9 warning, 10+ danger. The colour follows the number.' } },
},
render: () => (
<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>
),
}
export const InContext: Story = {
render: () => (
<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)
})
})
+172
View File
@@ -0,0 +1,172 @@
import type { ComponentProps, MouseEvent, ReactNode } from 'react'
import { X } from 'lucide-react'
import { cn } from '../lib/cn'
import { focusRing } from '../lib/styles'
import {
BADGE_DOT,
BADGE_DOT_SIZES,
BADGE_SIZES,
BADGE_STYLES,
COUNT_BADGE_PING,
COUNT_BADGE_PLACEMENT,
COUNT_BADGE_SIZES,
COUNT_BADGE_STYLES,
colorForValue,
type BadgeColor,
type BadgeSize,
type BadgeVariant,
type ColorRange,
type CountBadgePlacement,
type CountBadgeSize,
} from './badge.tokens'
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[]
}
/** 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={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}
{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 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>
)
}
@@ -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' },
],
},
}
@@ -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>
)
}
@@ -0,0 +1,166 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
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',
component: Button,
tags: ['autodocs'],
parameters: {
docs: {
description: {
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: '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: 'Save changes',
variant: 'solid',
color: 'primary',
size: 'md',
loading: false,
disabled: false,
fullWidth: false,
onClick: fn(),
},
} satisfies Meta<typeof Button>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Variants: Story = {
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: (args) => (
<div className="flex flex-wrap items-center gap-3">
{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 },
}
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 styles. A disabled link is inert and announced as disabled.',
},
},
},
render: () => (
<div className="flex flex-wrap items-center gap-3">
<LinkButton href="#">Browse components</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>
),
}
@@ -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()
})
})
+169
View File
@@ -0,0 +1,169 @@
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 before the label. */
startIcon?: ReactNode
/** Icon after the label. */
endIcon?: ReactNode
/** Stretch to the width of the container. */
fullWidth?: boolean
}
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
}
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',
)
}
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 = 'solid',
color = 'primary',
size = 'md',
startIcon,
endIcon,
fullWidth,
loading = false,
loadingText,
disabled,
type = 'button',
className,
children,
...props
}: ButtonProps) {
return (
<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 = 'solid',
color = 'primary',
size = 'md',
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
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}
{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>
)
}
+285
View File
@@ -0,0 +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:
'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: {
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,
},
} 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>Quarterly review</Card.Title>
<Card.Description>Acme Corporation · Due 14 October</Card.Description>
</Card.Header>
<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 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>{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>Cards group related content and actions about a single subject.</Card.Body>
</Card>
))}
</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 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>
</Card.Header>
<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 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)
})
})
+172
View File
@@ -0,0 +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 {
CARD_FOOTER_DIVIDER,
CARD_FOOTER_PADDING,
CARD_INTERACTIVE,
CARD_SECTION_PADDING,
CARD_VARIANT_STYLES,
CardContext,
type CardHeadingLevel,
type CardLayout,
type CardPadding,
type CardVariant,
} from './card.tokens'
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
/** 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
}
/** 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') {
// 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>
</>
)
}
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 CardHeaderProps = ComponentProps<'div'> & {
/** Content aligned to the top-right corner, e.g. a menu button or a badge. */
action?: ReactNode
}
function CardHeader({ action, className, children, ...props }: CardHeaderProps) {
const { padding } = use(CardContext)
return (
<div
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(
'mt-auto flex items-center gap-2',
CARD_FOOTER_PADDING[padding],
divider && CARD_FOOTER_DIVIDER[padding],
className,
)}
{...props}
/>
)
}
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(
'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}
/>
)
}
export const Card = Object.assign(CardRoot, {
Header: CardHeader,
Title: CardTitle,
Description: CardDescription,
Body: CardBody,
Footer: CardFooter,
Media: CardMedia,
})
@@ -0,0 +1,194 @@
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 = {
title: 'Forms/Checkbox',
component: Checkbox,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'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: {
label: { control: 'text' },
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: 'Email me when a payslip is ready',
description: 'Sent to [email protected] on each pay day.',
size: 'md',
color: 'primary',
defaultChecked: false,
indeterminate: false,
required: false,
disabled: false,
readOnly: false,
onCheckedChange: fn(),
},
} satisfies Meta<typeof Checkbox>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Unchecked: Story = {
args: { description: undefined },
}
export const Checked: Story = {
args: { defaultChecked: true },
}
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="grid gap-5">
{SIZES.map((size) => (
<Checkbox key={size} {...args} size={size} defaultChecked label={`Size ${size}`} />
))}
</div>
),
}
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 Uncontrolled: Story = {
args: { defaultChecked: true, label: 'Show weekends on the calendar', description: 'Starts ticked and keeps its own state.' },
}
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>
)
}
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 />,
}
@@ -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)
})
})
+152
View File
@@ -0,0 +1,152 @@
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'
type BaseRootProps = Omit<BaseCheckbox.Root.Props, 'className' | 'onCheckedChange' | 'render' | 'nativeButton' | 'style'>
export type CheckboxControlProps = BaseRootProps & {
size?: CheckboxSize
/** Fill colour when ticked or indeterminate. */
color?: CheckboxColor
/** Fires with the new ticked state. */
onCheckedChange?: (checked: boolean) => void
className?: string
}
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 (
<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 != 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>
)}
</div>
</BaseField.Root>
)
}
@@ -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>
),
}
@@ -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)
})
})
@@ -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>
)
}
@@ -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],
}
@@ -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(
'w-0 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 w-0 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>
)
}
@@ -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>
),
}
@@ -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
@@ -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>
),
}
@@ -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
@@ -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(),
}
@@ -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,
})
@@ -0,0 +1,205 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
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 = {
title: 'Forms/FeaturedInput',
component: FeaturedInput,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'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: {
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' },
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: 'Work email',
type: 'email',
size: 'md',
variant: 'outline',
required: false,
disabled: false,
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 const Variants: Story = {
render: (args) => (
<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 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 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>
),
}
@@ -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)
})
})
@@ -0,0 +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 {
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'
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
}
/**
* 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 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]
function clear() {
setCurrent('')
inputRef.current?.focus()
}
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 w-0 min-w-0 flex-1">
<BaseInput
ref={setRefs}
type={isPassword && revealed ? 'text' : type}
required={required}
disabled={disabled}
readOnly={readOnly}
value={current}
onValueChange={(next) => setCurrent(next)}
placeholder={placeholder || ' '}
aria-busy={loading || undefined}
className={cn(
'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,
)}
{...props}
/>
{label != null && (
<FieldLabel
required={required}
className={cn(
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),
)}
>
{label}
</FieldLabel>
)}
</div>
{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>
)
}
function assignRef<T>(ref: Ref<T> | undefined, node: T | null) {
if (typeof ref === 'function') ref(node)
else if (ref) ref.current = node
}
@@ -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' },
}
@@ -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)
})
})
})
@@ -0,0 +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 {
ActionFooter,
Chevron,
ClearButton,
ComboboxOptions,
SelectOptions,
Spinner,
StatusRow,
} from './SelectParts'
import {
CLEAR_SPACER,
FLOATING_LABEL_BG,
comboboxItems,
hasGroups,
listClass,
popupClass,
summarize,
triggerClass,
type SelectOption,
type SelectSize,
type SelectValue,
type SelectVariant,
} from './select.tokens'
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
/** 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
}
/** 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' }
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>
)
}
/**
* 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 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
function clear() {
setValue(empty)
wrapperRef.current?.querySelector<HTMLElement>('button')?.focus()
}
const triggerProps = {
'aria-invalid': invalid || undefined,
'aria-busy': loading || undefined,
className: triggerClass(size, variant, triggerClassName),
...props,
}
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 valueClass = cn('min-w-0 flex-1 truncate', !hasValue && 'text-fg-muted', !floated && 'invisible')
const label_ = label != null && (
<FloatingLabel
floated={floated}
open={open}
invalid={invalid}
size={size}
variant={variant}
hasStartIcon={startIcon != null}
required={required}
>
{label}
</FloatingLabel>
)
const clearButton = showClear && (
<ClearButton
size={size}
label={typeof label === 'string' ? `Clear ${label}` : 'Clear selection'}
onClear={clear}
/>
)
const footer = actionButton && <ActionFooter action={actionButton} onDone={() => setOpen(false)} />
const field = (children: ReactNode) => (
<Field
description={description}
error={error}
required={required}
disabled={disabled}
name={name}
nativeLabel={false}
className={className}
>
{children}
</Field>
)
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>,
)
}}
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 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>,
)}
</BaseCombobox.Trigger>
{label_}
{clearButton}
</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>,
)
}
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>,
)
}
@@ -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} />,
}
@@ -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)
})
})
@@ -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 />
}
@@ -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>
)
}
@@ -0,0 +1,136 @@
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:
'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: {
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' },
readOnly: { control: 'boolean' },
startAddon: { control: 'text' },
endAddon: { control: 'text' },
startIcon: { control: false },
endIcon: { control: false },
},
args: {
label: 'Work email',
placeholder: '[email protected]',
type: 'email',
size: 'md',
variant: 'outline',
required: false,
disabled: false,
readOnly: false,
onValueChange: fn(),
},
} satisfies Meta<typeof Input>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const WithDescription: Story = {
args: { description: 'Payslips are sent to this address.' },
}
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="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: (args) => (
<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)
})
})
+112
View File
@@ -0,0 +1,112 @@
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'
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
}
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 (
<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',
)}
>
{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(
'w-0 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>
</Field>
)
}
+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>
)
}
@@ -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 flex-wrap 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' },
}
@@ -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)
})
})
+147
View File
@@ -0,0 +1,147 @@
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<
ComponentProps<'select'>,
'size' | 'value' | 'defaultValue' | 'multiple' | 'className' | 'children'
> & {
/** 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
/** `outline` draws a bordered box; `filled` a tinted one. */
variant?: SelectVariant
/** 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
}
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' }
/**
* 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)
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])}
>
{startIcon}
</span>
)}
<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>
)}
{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>
</Field>
)
}
@@ -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} />,
}
@@ -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(
'w-0 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>
)
}
@@ -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>
)
},
}
@@ -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>
)
}
@@ -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-12 gap-y-24 py-6 sm:gap-x-56">
{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>
)
},
}
@@ -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 })
@@ -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>
),
}
@@ -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>
)
}
@@ -0,0 +1,248 @@
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',
component: Radio,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'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: {
label: { control: 'text' },
description: { control: 'text' },
error: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
readOnly: { control: 'boolean' },
options: { control: 'object' },
value: { 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: {
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',
color: 'primary',
variant: 'default',
required: false,
disabled: false,
readOnly: false,
onValueChange: fn(),
},
} satisfies Meta<typeof Radio>
export default meta
type Story = StoryObj<typeof meta>
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 Horizontal: Story = {
args: { orientation: 'horizontal', label: 'Theme', description: undefined, options: ['System', 'Light', 'Dark'], defaultValue: 'System' },
}
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="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 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>
),
}
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 Uncontrolled: Story = {
args: { defaultValue: 'Weekly', description: 'Starts with a default and keeps its own state.' },
}
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 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)
})
})
+218
View File
@@ -0,0 +1,218 @@
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'
export type RadioProps = {
/** The group's legend. */
label?: ReactNode
/** 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
/** 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
/** 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
}
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 (
<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,
)}
>
<BaseRadio.Indicator className={cn('rounded-full data-unchecked:hidden', RADIO_DOT_SIZES[size], RADIO_COLORS[color].dot)} />
</BaseRadio.Root>
)
}
/**
* 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>
)
}
@@ -0,0 +1,283 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
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',
component: Select,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'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: {
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' },
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: {
label: 'Department',
placeholder: 'Select a department',
options: DEPARTMENTS,
size: 'md',
variant: 'outline',
side: 'bottom',
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 Select>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
/** 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: (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: (args) => (
<div className="grid gap-5">
{SELECT_VARIANTS.map((variant) => (
<Select key={variant} {...args} variant={variant} label={variant === 'outline' ? 'Outline' : 'Filled'} />
))}
</div>
),
}
/** 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 flex-wrap 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 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 = {
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 = {
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>
)
}
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)
})
})
+219
View File
@@ -0,0 +1,219 @@
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'
export type { SelectOption } from './select.tokens'
/** 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
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
triggerClassName?: string
}
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
}: 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 (
<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>
)
}
+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>
)
}
@@ -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>
),
}
@@ -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>
)
}
@@ -0,0 +1,123 @@
import { useEffect, useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Button } from './Button'
import { Skeleton, SkeletonGroup, SkeletonText } from './Skeleton'
import { SKELETON_VARIANTS } from './skeleton.tokens'
const meta = {
title: 'Feedback/Skeleton',
component: Skeleton,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Placeholder shapes shown while content loads, so the layout does not jump. `Skeleton` draws one block (`rectangle`, `circle` for avatars, `text` for a line); `SkeletonText` draws a paragraph. The shapes are `aria-hidden`; wrap a loading region in `SkeletonGroup`, which sets `aria-busy` and gives screen readers one "Loading" message. The pulse stops under reduced motion.',
},
},
},
argTypes: {
variant: { control: 'inline-radio', options: SKELETON_VARIANTS, table: { defaultValue: { summary: 'rectangle' } } },
width: { control: 'text' },
height: { control: 'text' },
},
args: { variant: 'rectangle', width: '16rem', height: '1rem' },
} satisfies Meta<typeof Skeleton>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Shapes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-6">
<Skeleton variant="circle" />
<Skeleton variant="circle" width={56} height={56} />
<Skeleton width={160} height={96} className="rounded-xl" />
<div className="grid w-48 gap-2">
<Skeleton variant="text" />
<Skeleton variant="text" width="70%" />
</div>
</div>
),
}
export const Text: Story = {
render: () => (
<div className="max-w-md">
<SkeletonText lines={4} />
</div>
),
}
function CardSkeleton() {
return (
<div className="rounded-xl border border-border bg-surface p-5">
<div className="flex items-center gap-3">
<Skeleton variant="circle" />
<div className="grid flex-1 gap-2">
<Skeleton variant="text" width="45%" />
<Skeleton variant="text" width="30%" className="h-2.5" />
</div>
</div>
<Skeleton height={140} className="mt-5 rounded-lg" />
<SkeletonText lines={3} className="mt-5" />
<div className="mt-5 flex gap-2">
<Skeleton width={88} height={32} className="rounded-md" />
<Skeleton width={72} height={32} className="rounded-md" />
</div>
</div>
)
}
export const CardLoading: Story = {
parameters: { docs: { description: { story: 'A card placeholder inside a `SkeletonGroup` that marks the region busy.' } } },
render: () => (
<SkeletonGroup label="Loading posts" className="grid max-w-3xl gap-4 sm:grid-cols-2">
<CardSkeleton />
<CardSkeleton />
</SkeletonGroup>
),
}
export const LoadingThenContent: Story = {
render: function Render() {
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!loading) return
const id = setTimeout(() => setLoading(false), 2000)
return () => clearTimeout(id)
}, [loading])
return (
<div className="grid max-w-sm gap-3">
<SkeletonGroup loading={loading} label="Loading profile" className="rounded-xl border border-border bg-surface p-5">
{loading ? (
<div className="flex items-center gap-3">
<Skeleton variant="circle" />
<div className="grid flex-1 gap-2">
<Skeleton variant="text" width="50%" />
<Skeleton variant="text" width="70%" />
</div>
</div>
) : (
<div className="flex items-center gap-3">
<span className="flex size-10 items-center justify-center rounded-full bg-primary-100 text-sm font-semibold text-primary-700 dark:bg-primary-500/20 dark:text-primary-200">
JD
</span>
<div>
<p className="text-sm font-semibold text-fg">Jane Doe</p>
<p className="text-sm text-fg-muted">name@example.com</p>
</div>
</div>
)}
</SkeletonGroup>
<div>
<Button size="sm" variant="outline" color="neutral" onClick={() => setLoading(true)} disabled={loading}>
Reload
</Button>
</div>
</div>
)
},
}
@@ -0,0 +1,46 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { expectNoA11yViolations } from '../test/a11y'
import { Skeleton, SkeletonGroup, SkeletonText } from './Skeleton'
describe('Skeleton', () => {
it('hides shapes from assistive technology', () => {
const { container } = render(
<div>
<Skeleton />
<Skeleton variant="circle" />
<SkeletonText lines={4} />
</div>,
)
const roots = container.firstElementChild!.children
for (const el of Array.from(roots)) expect(el).toHaveAttribute('aria-hidden', 'true')
expect(roots[2].children).toHaveLength(4)
})
it('marks a loading region busy with one message', () => {
const { rerender } = render(
<SkeletonGroup label="Loading posts" data-testid="group">
<Skeleton />
</SkeletonGroup>,
)
expect(screen.getByTestId('group')).toHaveAttribute('aria-busy', 'true')
expect(screen.getByText('Loading posts')).toBeInTheDocument()
rerender(
<SkeletonGroup loading={false} label="Loading posts" data-testid="group">
Content
</SkeletonGroup>,
)
expect(screen.getByTestId('group')).toHaveAttribute('aria-busy', 'false')
expect(screen.queryByText('Loading posts')).toBeNull()
})
it('has no axe violations', async () => {
const { container } = render(
<SkeletonGroup>
<Skeleton variant="circle" />
<SkeletonText />
</SkeletonGroup>,
)
await expectNoA11yViolations(container)
})
})
+69
View File
@@ -0,0 +1,69 @@
import type { ComponentProps, CSSProperties, ReactNode } from 'react'
import { cn } from '../lib/cn'
import { SKELETON_VARIANT_STYLES, skeletonBase, type SkeletonVariant } from './skeleton.tokens'
export type SkeletonProps = Omit<ComponentProps<'span'>, 'children'> & {
/** `rectangle` for blocks, `circle` for avatars, `text` for a single line. */
variant?: SkeletonVariant
/** Width as a CSS length or pixels. Defaults to the full width (or 40px for circles). */
width?: number | string
/** Height as a CSS length or pixels. */
height?: number | string
}
export type SkeletonTextProps = Omit<ComponentProps<'span'>, 'children'> & {
/** Number of lines. The last one is shorter, like a paragraph. */
lines?: number
}
export type SkeletonGroupProps = ComponentProps<'div'> & {
/** While true, the region is marked `aria-busy` and announces `label`. */
loading?: boolean
/** Screen-reader text while loading. */
label?: string
children?: ReactNode
}
function size(width?: number | string, height?: number | string, style?: CSSProperties): CSSProperties | undefined {
if (width == null && height == null) return style
return { width, height, ...style }
}
/** A placeholder shape shown while content loads. Hidden from assistive technology. */
export function Skeleton({ variant = 'rectangle', width, height, className, style, ...props }: SkeletonProps) {
return (
<span
aria-hidden="true"
className={cn(skeletonBase, SKELETON_VARIANT_STYLES[variant], className)}
style={size(width, height, style)}
{...props}
/>
)
}
/** Placeholder lines for a paragraph. */
export function SkeletonText({ lines = 3, className, ...props }: SkeletonTextProps) {
return (
<span aria-hidden="true" className={cn('flex w-full flex-col gap-2.5', className)} {...props}>
{Array.from({ length: lines }, (_, i) => (
<span
key={i}
className={cn(skeletonBase, SKELETON_VARIANT_STYLES.text, lines > 1 && i === lines - 1 && 'w-3/5')}
/>
))}
</span>
)
}
/**
* Wraps a loading region: sets `aria-busy` and gives screen readers a single
* "Loading" message in place of the hidden skeleton shapes.
*/
export function SkeletonGroup({ loading = true, label = 'Loading', className, children, ...props }: SkeletonGroupProps) {
return (
<div aria-busy={loading} className={className} {...props}>
{loading && <span className="sr-only">{label}</span>}
{children}
</div>
)
}
@@ -0,0 +1,233 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { useState } from 'react'
import { fn } from 'storybook/test'
import { COLORS, SIZES } from '../lib/styles'
import { Slider } from './Slider'
const usd = { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } as const
const meta = {
title: 'Forms/Slider',
component: Slider,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Picks a number, or a range when the value is a `[low, high]` pair. Arrow keys move by `step`, Page Up/Down and Shift+Arrow by `largeStep`, Home/End jump to the ends. `format` (Intl.NumberFormat options) formats the value display, mark labels and each thumb’s `aria-valuetext`.',
},
},
},
argTypes: {
label: { control: 'text' },
description: { control: 'text' },
error: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
min: { control: 'number' },
max: { control: 'number' },
step: { control: 'number' },
largeStep: { control: 'number' },
value: { control: 'object' },
defaultValue: { control: 'object' },
marks: { control: 'object' },
showValue: { control: 'boolean' },
format: { control: 'object' },
locale: { control: 'text' },
thumbLabels: { control: 'object' },
size: { control: 'inline-radio', options: SIZES, table: { defaultValue: { summary: 'md' } } },
color: { control: 'select', options: COLORS, table: { defaultValue: { summary: 'primary' } } },
orientation: {
control: 'inline-radio',
options: ['horizontal', 'vertical'],
table: { defaultValue: { summary: 'horizontal' } },
},
name: { control: 'text' },
'aria-label': { control: 'text' },
className: { control: 'text' },
onValueChange: { control: false },
onValueCommitted: { control: false },
},
args: {
label: 'Volume',
defaultValue: 40,
min: 0,
max: 100,
step: 1,
showValue: true,
size: 'md',
color: 'primary',
orientation: 'horizontal',
required: false,
disabled: false,
onValueChange: fn(),
onValueCommitted: fn(),
},
decorators: [(Story) => <div className="max-w-sm">{Story()}</div>],
} satisfies Meta<typeof Slider>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const WithDescription: Story = {
args: { label: 'Session timeout', description: 'Sign members out after this many minutes of inactivity.', min: 5, max: 120, step: 5, defaultValue: 30 },
}
export const Percent: Story = {
args: { label: 'Opacity', defaultValue: 0.8, min: 0, max: 1, step: 0.05, format: { style: 'percent' } },
}
export const Currency: Story = {
args: {
label: 'Monthly budget',
description: 'We pause campaigns when spending reaches this amount.',
defaultValue: 2500,
min: 0,
max: 10000,
step: 100,
largeStep: 1000,
format: usd,
locale: 'en-US',
marks: [0, 2500, 5000, 7500, 10000],
},
}
export const RangeWithMarks: Story = {
args: {
label: 'Price range',
defaultValue: [200, 650],
min: 0,
max: 1000,
step: 10,
format: usd,
locale: 'en-US',
marks: [0, 250, 500, 750, 1000],
},
}
export const LabelledMarks: Story = {
args: {
label: 'Image quality',
defaultValue: 2,
min: 0,
max: 3,
step: 1,
showValue: false,
marks: [
{ value: 0, label: 'Low' },
{ value: 1, label: 'Medium' },
{ value: 2, label: 'High' },
{ value: 3, label: 'Original' },
],
},
}
export const Disabled: Story = {
args: { disabled: true, description: 'Upgrade to adjust playback volume.' },
}
export const WithError: Story = {
args: { label: 'Team size', required: true, defaultValue: 2, min: 1, max: 50, error: 'Teams need at least 3 members.' },
}
export const Required: Story = {
args: { required: true, label: 'Seats', min: 1, max: 50, defaultValue: 10 },
}
export const WithoutVisibleLabel: Story = {
args: { label: undefined, showValue: false, 'aria-label': 'Volume' },
}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-6">
{SIZES.map((size) => (
<Slider key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const Colors: Story = {
render: (args) => (
<div className="grid gap-5">
{COLORS.map((color, i) => (
<Slider key={color} {...args} color={color} label={color} defaultValue={20 + i * 12} />
))}
</div>
),
}
export const Vertical: Story = {
render: (args) => (
<div className="flex gap-10">
<Slider {...args} orientation="vertical" label="Bass" defaultValue={60} />
<Slider {...args} orientation="vertical" label="Treble" defaultValue={35} color="info" />
<Slider
{...args}
orientation="vertical"
label="Temperature"
defaultValue={[18, 23]}
min={10}
max={30}
format={{ style: 'unit', unit: 'celsius' }}
marks={[10, 20, 30]}
/>
</div>
),
}
export const Uncontrolled: Story = {
args: { defaultValue: 65, description: 'Starts at a default and keeps its own state.' },
}
function ControlledSlider(args: Story['args']) {
const [value, setValue] = useState<[number, number]>([25, 60])
return (
<div className="grid gap-3">
<Slider
{...args}
label="Age range"
value={value}
min={18}
max={80}
format={undefined}
marks={[18, 30, 40, 50, 60, 70, 80]}
onValueChange={(next) => {
setValue(next as [number, number])
args?.onValueChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">
Value: {value[0]}–{value[1]}
</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledSlider {...args} />,
}
/** Search filters in a sidebar: a price range and a minimum rating. */
export const SearchFilters: Story = {
render: () => (
<aside className="grid gap-6 rounded-xl border border-border bg-surface p-5">
<p className="text-base font-semibold text-fg">Filter results</p>
<Slider label="Nightly price" defaultValue={[80, 240]} min={0} max={500} step={10} format={usd} locale="en-US" showValue marks={[0, 250, 500]} />
<Slider
label="Minimum guest rating"
defaultValue={8}
min={5}
max={10}
step={0.5}
showValue
format={{ minimumFractionDigits: 1 }}
color="success"
/>
<Slider label="Distance from centre" description="In kilometres." defaultValue={5} min={1} max={25} showValue format={{ style: 'unit', unit: 'kilometer' }} />
</aside>
),
}
@@ -0,0 +1,98 @@
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 { Slider } from './Slider'
describe('Slider', () => {
it('renders a slider named by its label, with a value', () => {
render(<Slider label="Volume" defaultValue={40} />)
const thumb = screen.getByRole('slider', { name: 'Volume' })
expect(thumb).toHaveAttribute('aria-valuenow', '40')
expect(thumb).toHaveAttribute('min', '0')
expect(thumb).toHaveAttribute('max', '100')
})
it('moves with the arrow keys, Home and End', async () => {
const onValueChange = vi.fn()
render(<Slider label="Volume" defaultValue={40} step={5} onValueChange={onValueChange} />)
const thumb = screen.getByRole('slider')
thumb.focus()
await userEvent.keyboard('{ArrowRight}')
expect(thumb).toHaveAttribute('aria-valuenow', '45')
expect(onValueChange).toHaveBeenLastCalledWith(45)
await userEvent.keyboard('{ArrowLeft}{ArrowLeft}')
expect(thumb).toHaveAttribute('aria-valuenow', '35')
await userEvent.keyboard('{End}')
expect(thumb).toHaveAttribute('aria-valuenow', '100')
await userEvent.keyboard('{Home}')
expect(thumb).toHaveAttribute('aria-valuenow', '0')
})
it('formats aria-valuetext and the visible value', () => {
render(
<Slider
label="Budget"
defaultValue={2500}
min={0}
max={10000}
showValue
format={{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }}
locale="en-US"
/>,
)
expect(screen.getByRole('slider')).toHaveAttribute('aria-valuetext', '$2,500')
expect(screen.getByText('$2,500', { selector: 'output' })).toBeInTheDocument()
})
it('renders a named thumb for each end of a range', async () => {
const onValueChange = vi.fn()
render(<Slider label="Price" defaultValue={[20, 80]} onValueChange={onValueChange} />)
const low = screen.getByRole('slider', { name: 'Price minimum' })
const high = screen.getByRole('slider', { name: 'Price maximum' })
expect(low).toHaveAttribute('aria-valuenow', '20')
expect(high).toHaveAttribute('aria-valuenow', '80')
high.focus()
await userEvent.keyboard('{ArrowLeft}')
expect(onValueChange).toHaveBeenLastCalledWith([20, 79])
})
it('works controlled', async () => {
const onValueChange = vi.fn()
render(<Slider label="Volume" value={10} onValueChange={onValueChange} />)
const thumb = screen.getByRole('slider')
thumb.focus()
await userEvent.keyboard('{ArrowRight}')
expect(onValueChange).toHaveBeenCalledWith(11)
expect(thumb).toHaveAttribute('aria-valuenow', '10')
})
it('labels the marks with the formatted value', () => {
render(<Slider label="Size" defaultValue={50} marks={[0, 50, { value: 100, label: 'Max' }]} />)
expect(screen.getByText('50')).toBeInTheDocument()
expect(screen.getByText('Max')).toBeInTheDocument()
})
it('announces the description, or the error when invalid', () => {
const { rerender } = render(<Slider label="Seats" defaultValue={3} description="Per team." />)
expect(screen.getByRole('slider')).toHaveAccessibleDescription('Per team.')
rerender(<Slider label="Seats" defaultValue={3} description="Per team." error="At least 5." />)
expect(screen.getByRole('slider')).toHaveAccessibleDescription('At least 5.')
})
it('is disabled', () => {
render(<Slider label="Volume" defaultValue={10} disabled />)
expect(screen.getByRole('slider')).toBeDisabled()
})
it('has no axe violations', async () => {
const { container } = render(
<>
<Slider label="Volume" defaultValue={40} showValue description="System volume." />
<Slider label="Price" defaultValue={[20, 80]} marks={[0, 50, 100]} showValue />
<Slider aria-label="Balance" defaultValue={50} />
</>,
)
await expectNoA11yViolations(container)
})
})
+241
View File
@@ -0,0 +1,241 @@
import { Field as BaseField } from '@base-ui/react/field'
import { Slider as BaseSlider } from '@base-ui/react/slider'
import { useMemo, type ReactNode } from 'react'
import { cn } from '../lib/cn'
import { descriptionText, errorText, labelText, requiredMark } from '../lib/styles'
import {
SLIDER_COLORS,
SLIDER_SIZES,
type SliderColor,
type SliderMark,
type SliderOrientation,
type SliderSize,
} from './slider.tokens'
type SliderValue = number | [number, number]
export type SliderProps<V extends SliderValue = SliderValue> = {
/** Visible label. It names the thumb (or both thumbs, with `thumbLabels`). */
label?: ReactNode
/** Help text under the slider, announced with the thumbs. */
description?: ReactNode
/** Error message. Marks the slider invalid and replaces `description`. */
error?: ReactNode
/** Adds the required mark to the label. */
required?: boolean
disabled?: boolean
min?: number
max?: number
/** Distance between allowed values. */
step?: number
/** Step for Page Up/Down and Shift+Arrow. Defaults to 10 steps. */
largeStep?: number
/** Current value (controlled). A `[low, high]` pair makes a range slider. */
value?: V
/** Initial value (uncontrolled). A `[low, high]` pair makes a range slider. */
defaultValue?: V
/** Fires while the value changes, with a number or a `[low, high]` pair. */
onValueChange?: (value: V) => void
/** Fires once the user lets go (pointer up or key press). */
onValueCommitted?: (value: V) => void
/** Ticks on the track: numbers, or `{ value, label }`. Numbers are labelled with the formatted value. */
marks?: SliderMark[]
/** Shows the formatted value beside the label. */
showValue?: boolean
/** How values are formatted, for the value display, mark labels and screen readers. */
format?: Intl.NumberFormatOptions
/** Locale for `format`. Defaults to the browser's. */
locale?: Intl.LocalesArgument
/**
* Accessible names for the two thumbs of a range slider. Defaults to
* "<label> minimum" and "<label> maximum" when `label` is a string.
*/
thumbLabels?: [string, string]
size?: SliderSize
/** Colour of the filled track and the thumb ring. */
color?: SliderColor
orientation?: SliderOrientation
/** Identifies the slider in a form. */
name?: string
/** Accessible name when there is no visible `label`. */
'aria-label'?: string
className?: string
}
function percent(value: number, min: number, max: number) {
return ((value - min) / (max - min)) * 100
}
/**
* Picks a number, or a range with two thumbs, by dragging or with the arrow
* keys. Built on Base UI Slider and Field: the label names the thumbs and
* each thumb announces its formatted value through `aria-valuetext`.
*/
export function Slider<V extends SliderValue = SliderValue>({
label,
description,
error,
required,
disabled,
min = 0,
max = 100,
step = 1,
largeStep,
value,
defaultValue,
onValueChange,
onValueCommitted,
marks,
showValue = false,
format,
locale,
thumbLabels,
size = 'md',
color = 'primary',
orientation = 'horizontal',
name,
'aria-label': ariaLabel,
className,
}: SliderProps<V>) {
const invalid = error != null && error !== false && error !== ''
const initial = value ?? defaultValue
const range = Array.isArray(initial)
const vertical = orientation === 'vertical'
const sizes = SLIDER_SIZES[size]
const colors = SLIDER_COLORS[color]
const formatter = useMemo(() => new Intl.NumberFormat(locale, format), [locale, format])
const markList = (marks ?? []).map((mark) => (typeof mark === 'number' ? { value: mark, label: undefined } : mark))
const hasMarkLabels = markList.length > 0
const rangeLabels =
thumbLabels ?? (typeof label === 'string' ? [`${label} minimum`, `${label} maximum`] : ['Minimum', 'Maximum'])
const thumbClass = cn(
'block rounded-full border-2 bg-white shadow-sm outline-none transition-[box-shadow] select-none',
'has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-primary-500',
'data-dragging:shadow-md data-disabled:cursor-not-allowed',
sizes.thumb,
colors.thumb,
)
const thumb = (index: number) => (
<BaseSlider.Thumb
key={index}
index={index}
aria-label={range ? rangeLabels[index] : ariaLabel}
getAriaValueText={(formatted) => formatted}
className={thumbClass}
/>
)
return (
<BaseField.Root
name={name}
disabled={disabled}
invalid={invalid}
className={cn('flex flex-col gap-1.5', vertical ? 'w-fit' : 'w-full', className)}
>
<BaseSlider.Root
value={value}
defaultValue={defaultValue}
onValueChange={onValueChange ? (next) => onValueChange(next as V) : undefined}
onValueCommitted={onValueCommitted ? (next) => onValueCommitted(next as V) : undefined}
min={min}
max={max}
step={step}
largeStep={largeStep}
format={format}
locale={locale}
disabled={disabled}
orientation={orientation}
className={cn('flex gap-1.5', vertical ? 'flex-col items-center' : 'flex-col')}
>
{(label != null || showValue) && (
<div className={cn('flex items-baseline gap-3', vertical ? 'flex-col items-center gap-0.5' : 'justify-between')}>
{label != null && (
<BaseSlider.Label className={cn(labelText, 'data-disabled:text-fg-muted')}>
{label}
{required && (
<span aria-hidden="true" className={requiredMark}>
*
</span>
)}
</BaseSlider.Label>
)}
{showValue && (
<BaseSlider.Value className="text-sm font-medium tabular-nums text-fg-muted">
{(formatted) => formatted.join(' – ')}
</BaseSlider.Value>
)}
</div>
)}
<BaseSlider.Control
className={cn(
'relative flex touch-none items-center select-none data-disabled:cursor-not-allowed data-disabled:opacity-55',
'data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-44 data-[orientation=vertical]:justify-center',
sizes.control,
)}
>
<BaseSlider.Track
className={cn(
'relative rounded-full bg-border-strong/70 select-none dark:bg-border-strong data-invalid:bg-danger-100 dark:data-invalid:bg-danger-500/25',
'data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full',
sizes.track,
)}
>
<BaseSlider.Indicator className={cn('rounded-full select-none', colors.indicator)} />
{markList.map((mark) => (
<span
key={mark.value}
aria-hidden="true"
className={cn(
'absolute size-1 rounded-full bg-fg-subtle/60',
vertical ? 'left-1/2 -translate-x-1/2 translate-y-1/2' : 'top-1/2 -translate-x-1/2 -translate-y-1/2',
)}
style={vertical ? { bottom: `${percent(mark.value, min, max)}%` } : { left: `${percent(mark.value, min, max)}%` }}
/>
))}
{range ? [thumb(0), thumb(1)] : thumb(0)}
</BaseSlider.Track>
{vertical && hasMarkLabels && (
<div aria-hidden="true" className="relative ml-3 h-full w-10 select-none">
{markList.map((mark) => (
<span
key={mark.value}
className="absolute left-0 translate-y-1/2 text-xs whitespace-nowrap text-fg-muted"
style={{ bottom: `${percent(mark.value, min, max)}%` }}
>
{mark.label ?? formatter.format(mark.value)}
</span>
))}
</div>
)}
</BaseSlider.Control>
{!vertical && hasMarkLabels && (
<div aria-hidden="true" className="relative h-4 select-none">
{markList.map((mark, i) => (
<span
key={mark.value}
className={cn(
'absolute top-0 text-xs whitespace-nowrap text-fg-muted',
// Keep the end labels inside the slider's box.
i === 0 && mark.value === min ? '' : i === markList.length - 1 && mark.value === max ? '-translate-x-full' : '-translate-x-1/2',
)}
style={{ left: `${percent(mark.value, min, max)}%` }}
>
{mark.label ?? formatter.format(mark.value)}
</span>
))}
</div>
)}
</BaseSlider.Root>
{description != null && !invalid && (
<BaseField.Description className={descriptionText}>{description}</BaseField.Description>
)}
{invalid && (
<BaseField.Error match className={errorText}>
{error}
</BaseField.Error>
)}
</BaseField.Root>
)
}
@@ -0,0 +1,80 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Button } from './Button'
import { Spinner } from './Spinner'
import { SPINNER_COLORS, SPINNER_SIZES_LIST } from './spinner.tokens'
const meta = {
title: 'Feedback/Spinner',
component: Spinner,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'An indeterminate loading indicator. It renders `role="status"` with one accessible name from `label` (default "Loading"). Under reduced motion it turns slowly instead of stopping, so it still reads as busy. Use `color="current"` inside buttons and coloured surfaces.',
},
},
},
argTypes: {
size: { control: 'inline-radio', options: SPINNER_SIZES_LIST, table: { defaultValue: { summary: 'md' } } },
color: { control: 'select', options: SPINNER_COLORS, table: { defaultValue: { summary: 'primary' } } },
label: { control: 'text', table: { defaultValue: { summary: 'Loading' } } },
},
args: { size: 'md', color: 'primary', label: 'Loading' },
} satisfies Meta<typeof Spinner>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Sizes: Story = {
render: (args) => (
<div className="flex items-end gap-6">
{SPINNER_SIZES_LIST.map((size) => (
<div key={size} className="flex flex-col items-center gap-2">
<Spinner {...args} size={size} />
<span className="text-xs text-fg-muted">{size}</span>
</div>
))}
</div>
),
}
export const Colors: Story = {
render: (args) => (
<div className="flex flex-wrap items-center gap-6">
{SPINNER_COLORS.filter((c) => c !== 'current').map((color) => (
<div key={color} className="flex flex-col items-center gap-2">
<Spinner {...args} color={color} size="lg" label={`Loading (${color})`} />
<span className="text-xs text-fg-muted">{color}</span>
</div>
))}
</div>
),
}
export const InContext: Story = {
parameters: { docs: { description: { story: 'Inline with text, inside a loading panel, and in a button via `Button loading`.' } } },
render: () => (
<div className="grid max-w-md gap-4">
<p className="flex items-center gap-2 text-sm text-fg-muted">
<Spinner size="sm" color="neutral" label="Syncing" />
Syncing 12 files…
</p>
<div className="flex h-32 flex-col items-center justify-center gap-3 rounded-xl border border-border bg-surface">
<Spinner size="lg" label="Loading invoices" />
<span className="text-sm text-fg-muted">Loading invoices…</span>
</div>
<div className="flex gap-3">
<Button loading loadingText="Saving…">
Save
</Button>
<span className="inline-flex items-center gap-2 rounded-lg bg-primary-500 px-4 text-sm font-semibold text-white">
<Spinner size="sm" color="current" label="Publishing" />
Publishing
</span>
</div>
</div>
),
}
@@ -0,0 +1,25 @@
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { expectNoA11yViolations } from '../test/a11y'
import { Spinner } from './Spinner'
describe('Spinner', () => {
it('is a status named "Loading" by default', () => {
render(<Spinner />)
const status = screen.getByRole('status', { name: 'Loading' })
expect(status).toHaveAttribute('aria-label', 'Loading')
// One accessible name, no duplicate visually hidden text.
expect(status).toHaveTextContent('')
expect(status.querySelector('svg')).toHaveAttribute('aria-hidden', 'true')
})
it('uses a custom label', () => {
render(<Spinner label="Saving invoice" size="xl" color="success" />)
expect(screen.getByRole('status', { name: 'Saving invoice' })).toBeInTheDocument()
})
it('has no axe violations', async () => {
const { container } = render(<Spinner />)
await expectNoA11yViolations(container)
})
})
+37
View File
@@ -0,0 +1,37 @@
import type { ComponentProps } from 'react'
import { cn } from '../lib/cn'
import { SPINNER_COLOR_STYLES, SPINNER_SIZES, type SpinnerColor, type SpinnerSize } from './spinner.tokens'
export type SpinnerProps = Omit<ComponentProps<'span'>, 'color' | 'children'> & {
/** `xs` to `xl`; `sm`, `md` and `lg` match the icon sizes of the shared control scale. */
size?: SpinnerSize
/** Semantic colour, or `current` to inherit the surrounding text colour. */
color?: SpinnerColor
/** Accessible name announced to screen readers. */
label?: string
}
/**
* An indeterminate loading indicator. It is a `role="status"` element named by
* `label`; the drawing itself is hidden from assistive technology.
*/
export function Spinner({ size = 'md', color = 'primary', label = 'Loading', className, ...props }: SpinnerProps) {
return (
<span
role="status"
aria-label={label}
className={cn('inline-flex shrink-0', SPINNER_SIZES[size], SPINNER_COLOR_STYLES[color], className)}
{...props}
>
<svg
aria-hidden="true"
viewBox="0 0 24 24"
fill="none"
className="size-full animate-spin motion-reduce:animate-[spin_1.5s_linear_infinite]"
>
<circle cx="12" cy="12" r="9.5" stroke="currentColor" strokeOpacity=".2" strokeWidth="3" />
<path d="M21.5 12A9.5 9.5 0 0 0 12 2.5" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
</svg>
</span>
)
}
@@ -0,0 +1,205 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Check, Moon, Sun, X } from 'lucide-react'
import { useState } from 'react'
import { fn } from 'storybook/test'
import { COLORS, SIZES } from '../lib/styles'
import { Switch } from './Switch'
const meta = {
title: 'Forms/Switch',
component: Switch,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'An on/off switch for settings that take effect straight away. Clicking the label flips it, and Space toggles it from the keyboard. `labelPosition="start"` puts the label first and the switch at the far edge, as in a settings list. Optional `checkedIcon` / `uncheckedIcon` sit inside the thumb.',
},
},
},
argTypes: {
label: { control: 'text' },
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' } } },
labelPosition: { control: 'inline-radio', options: ['end', 'start'], table: { defaultValue: { summary: 'end' } } },
checked: { control: 'boolean' },
defaultChecked: { control: 'boolean' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
readOnly: { control: 'boolean' },
name: { control: 'text' },
value: { control: 'text' },
className: { control: 'text' },
checkedIcon: { control: false },
uncheckedIcon: { control: false },
onCheckedChange: { control: false },
},
args: {
label: 'Automatic payslip delivery',
description: 'Emails a PDF payslip to each employee on pay day.',
size: 'md',
color: 'primary',
labelPosition: 'end',
defaultChecked: false,
required: false,
disabled: false,
readOnly: false,
onCheckedChange: fn(),
},
} satisfies Meta<typeof Switch>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Off: Story = {}
export const On: Story = {
args: { defaultChecked: true },
}
export const LabelOnly: Story = {
args: { description: undefined, label: 'Wi-Fi' },
}
export const LabelAtStart: Story = {
args: { labelPosition: 'start', defaultChecked: true },
decorators: [(Story) => <div className="max-w-md">{Story()}</div>],
}
export const Disabled: Story = {
render: (args) => (
<div className="grid gap-4">
<Switch {...args} disabled label="Disabled, off" description="Available on the Business plan." />
<Switch {...args} disabled defaultChecked label="Disabled, on" description={undefined} />
</div>
),
}
export const ReadOnly: Story = {
args: { readOnly: true, defaultChecked: true, label: 'Single sign-on', description: 'Enforced by Acme Corporation. Contact IT to change it.' },
}
export const WithError: Story = {
args: {
required: true,
label: 'Share usage data',
description: undefined,
error: 'Turn this on to use the analytics dashboard.',
},
}
export const Required: Story = {
args: { required: true },
}
export const Sizes: Story = {
render: (args) => (
<div className="grid gap-6 sm:grid-cols-3">
{SIZES.map((size) => (
<div key={size} className="grid gap-3">
<Switch {...args} size={size} label={`Size ${size}, off`} description={undefined} />
<Switch {...args} size={size} defaultChecked label={`Size ${size}, on`} description="Thumb travels to the far edge." />
</div>
))}
</div>
),
}
export const Colors: Story = {
render: (args) => (
<div className="grid gap-4 sm:grid-cols-3">
{COLORS.map((color) => (
<Switch key={color} {...args} color={color} defaultChecked label={color} description={undefined} />
))}
</div>
),
}
export const WithIcons: Story = {
render: (args) => (
<div className="grid gap-5">
{SIZES.map((size) => (
<div key={size} className="flex flex-wrap gap-8">
<Switch {...args} size={size} description={undefined} label="Off" checkedIcon={<Check />} uncheckedIcon={<X />} />
<Switch {...args} size={size} description={undefined} label="On" defaultChecked checkedIcon={<Check />} uncheckedIcon={<X />} />
<Switch
{...args}
size={size}
color="neutral"
description={undefined}
label="Dark mode"
defaultChecked
checkedIcon={<Moon />}
uncheckedIcon={<Sun />}
/>
</div>
))}
</div>
),
}
export const Uncontrolled: Story = {
args: { defaultChecked: true, description: 'Starts on and keeps its own state.' },
}
function ControlledSwitch(args: Story['args']) {
const [on, setOn] = useState(true)
return (
<div className="grid gap-3">
<Switch
{...args}
label="Out of office"
description="Auto-replies to new messages until you turn it off."
checked={on}
onCheckedChange={(next) => {
setOn(next)
args?.onCheckedChange?.(next)
}}
/>
<p className="text-sm text-fg-muted">Out of office: {on ? 'on' : 'off'}</p>
</div>
)
}
export const Controlled: Story = {
render: (args) => <ControlledSwitch {...args} />,
}
const notificationRows = [
{ id: 'comments', label: 'Comments', description: 'When someone comments on a document you own.', on: true },
{ id: 'mentions', label: 'Mentions', description: 'When someone @mentions you.', on: true },
{ id: 'assign', label: 'Assignments', description: 'When a task is assigned to you.', on: false },
{ id: 'digest', label: 'Weekly digest', description: 'A Monday summary of activity in your workspaces.', on: false },
]
/** A settings panel: labels on the left, switches aligned to the right edge. */
export const NotificationSettings: Story = {
render: () => (
<section className="max-w-lg rounded-xl border border-border bg-surface">
<header className="border-b border-border px-5 py-4">
<p className="text-base font-semibold text-fg">Email notifications</p>
<p className="text-sm text-fg-muted">Sent to jane.doe@example.com</p>
</header>
<div className="divide-y divide-border">
{notificationRows.map((row) => (
<div key={row.id} className="px-5 py-4">
<Switch name={row.id} label={row.label} description={row.description} defaultChecked={row.on} labelPosition="start" />
</div>
))}
<div className="px-5 py-4">
<Switch
name="marketing"
label="Product announcements"
description="Managed by your workspace admin."
labelPosition="start"
disabled
/>
</div>
</div>
</section>
),
}
@@ -0,0 +1,94 @@
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 { Switch } from './Switch'
describe('Switch', () => {
it('renders a switch named by its label', () => {
render(<Switch label="Wi-Fi" />)
expect(screen.getByRole('switch', { name: 'Wi-Fi' })).not.toBeChecked()
})
it('flips when the label is clicked, in either label position', async () => {
render(
<>
<Switch label="End" />
<Switch label="Start" labelPosition="start" />
</>,
)
await userEvent.click(screen.getByText('End'))
await userEvent.click(screen.getByText('Start'))
expect(screen.getByRole('switch', { name: 'End' })).toBeChecked()
expect(screen.getByRole('switch', { name: 'Start' })).toBeChecked()
})
it('toggles with Space', async () => {
const onCheckedChange = vi.fn()
render(<Switch label="Wi-Fi" onCheckedChange={onCheckedChange} />)
await userEvent.tab()
expect(screen.getByRole('switch')).toHaveFocus()
await userEvent.keyboard(' ')
expect(screen.getByRole('switch')).toBeChecked()
expect(onCheckedChange).toHaveBeenLastCalledWith(true)
})
it('works uncontrolled and controlled', async () => {
const onCheckedChange = vi.fn()
render(
<>
<Switch label="Uncontrolled" defaultChecked />
<Switch label="Controlled" checked onCheckedChange={onCheckedChange} />
</>,
)
await userEvent.click(screen.getByRole('switch', { name: 'Uncontrolled' }))
expect(screen.getByRole('switch', { name: 'Uncontrolled' })).not.toBeChecked()
await userEvent.click(screen.getByRole('switch', { name: 'Controlled' }))
expect(onCheckedChange).toHaveBeenCalledWith(false)
expect(screen.getByRole('switch', { name: 'Controlled' })).toBeChecked()
})
it('announces the description, or the error when invalid', () => {
render(
<>
<Switch label="A" description="Help text" />
<Switch label="B" description="Hidden" error="Turn this on." required />
</>,
)
expect(screen.getByRole('switch', { name: 'A' })).toHaveAccessibleDescription('Help text')
const b = screen.getByRole('switch', { name: 'B' })
expect(b).toHaveAccessibleDescription('Turn this on.')
expect(b).toHaveAttribute('data-invalid')
})
it('renders the icon for the current state', async () => {
render(<Switch label="Theme" checkedIcon={<svg data-testid="on" />} uncheckedIcon={<svg data-testid="off" />} />)
expect(screen.getByTestId('off')).toBeInTheDocument()
await userEvent.click(screen.getByRole('switch'))
expect(screen.getByTestId('on')).toBeInTheDocument()
expect(screen.queryByTestId('off')).not.toBeInTheDocument()
})
it('ignores clicks when disabled or read-only', async () => {
const onCheckedChange = vi.fn()
render(
<>
<Switch label="Disabled" disabled onCheckedChange={onCheckedChange} />
<Switch label="Read only" readOnly onCheckedChange={onCheckedChange} />
</>,
)
await userEvent.click(screen.getByRole('switch', { name: 'Disabled' }))
await userEvent.click(screen.getByRole('switch', { name: 'Read only' }))
expect(onCheckedChange).not.toHaveBeenCalled()
})
it('has no axe violations', async () => {
const { container } = render(
<>
<Switch label="Wi-Fi" description="Join known networks." defaultChecked />
<Switch label="Share data" labelPosition="start" error="Required" required />
</>,
)
await expectNoA11yViolations(container)
})
})
+141
View File
@@ -0,0 +1,141 @@
import { Field as BaseField } from '@base-ui/react/field'
import { Switch as BaseSwitch } from '@base-ui/react/switch'
import type { ReactNode } from 'react'
import { cn } from '../lib/cn'
import { descriptionText, errorText, focusRing } from '../lib/styles'
import { FieldLabel } from './Field'
import {
SWITCH_COLORS,
SWITCH_LABEL_OFFSET,
SWITCH_LABEL_SIZES,
SWITCH_SIZES,
type SwitchColor,
type SwitchLabelPosition,
type SwitchSize,
} from './switch.tokens'
type BaseRootProps = Omit<BaseSwitch.Root.Props, 'className' | 'onCheckedChange' | 'render' | 'nativeButton' | 'style'>
export type SwitchProps = BaseRootProps & {
/** Text beside the switch. Clicking it flips the switch. */
label?: ReactNode
/** Help text under the label, announced with the switch. */
description?: ReactNode
/** Error message. Marks the switch invalid and replaces `description`. */
error?: ReactNode
/** Adds the required mark and requires the switch on before the form submits. */
required?: boolean
disabled?: boolean
/** Shows the state but ignores clicks and keys. */
readOnly?: boolean
size?: SwitchSize
/** Track colour when on. */
color?: SwitchColor
checked?: boolean
defaultChecked?: boolean
/** Fires with the new on/off state. */
onCheckedChange?: (checked: boolean) => void
/** Identifies the switch in a form. */
name?: string
/**
* `end` puts the switch first and the label after it. `start` puts the label
* first and pushes the switch to the far edge, as in a settings list.
*/
labelPosition?: SwitchLabelPosition
/** Icon inside the thumb while on, such as `<Check />`. */
checkedIcon?: ReactNode
/** Icon inside the thumb while off, such as `<X />`. */
uncheckedIcon?: ReactNode
/** Classes for the outer wrapper. */
className?: string
}
/**
* An on/off switch for settings that apply straight away. Built on Base UI
* Switch and Field, so the label, description and error are linked for
* screen readers. For choices submitted with a form, prefer a Checkbox.
*/
export function Switch({
label,
description,
error,
required,
disabled,
size = 'md',
color = 'primary',
onCheckedChange,
name,
labelPosition = 'end',
checkedIcon,
uncheckedIcon,
className,
...props
}: SwitchProps) {
const invalid = error != null && error !== false && error !== ''
const sizes = SWITCH_SIZES[size]
const colors = SWITCH_COLORS[color]
const hasText = label != null || description != null || invalid
const start = labelPosition === 'start'
const control = (
<BaseSwitch.Root
required={required}
onCheckedChange={onCheckedChange ? (checked) => onCheckedChange(checked) : undefined}
className={cn(
'relative inline-flex shrink-0 cursor-pointer items-center rounded-full bg-border-strong p-0.5 transition-colors duration-200',
'motion-reduce:transition-none not-data-checked:not-data-disabled:hover:bg-fg-subtle',
'data-invalid:ring-2 data-invalid:ring-danger-500',
'data-disabled:cursor-not-allowed data-disabled:opacity-55 data-readonly:cursor-default',
sizes.track,
colors.track,
focusRing,
)}
{...props}
>
<BaseSwitch.Thumb
className={cn(
'flex items-center justify-center rounded-full bg-white text-fg-subtle shadow-sm',
'transition-[translate] duration-200 ease-out motion-reduce:transition-none',
sizes.thumb,
sizes.icon,
colors.icon,
colors.thumb,
)}
render={(thumbProps, state) => (
<span {...thumbProps}>
{state.checked ? checkedIcon : uncheckedIcon}
</span>
)}
/>
</BaseSwitch.Root>
)
return (
<BaseField.Root name={name} disabled={disabled} invalid={invalid} className={cn('flex', className)}>
<div className={cn('flex items-start gap-3', start && 'w-full justify-between gap-4')}>
{!start && control}
{hasText && (
<div className={cn('flex min-w-0 flex-col gap-0.5', SWITCH_LABEL_OFFSET[size])}>
{label != null && (
<FieldLabel
required={required}
className={cn(SWITCH_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>
)}
{start && control}
</div>
</BaseField.Root>
)
}
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff. Show more