6 Commits
Author SHA1 Message Date
thekhalidsha 260bb7c1ca Show how to install Tansy UI on the landing page and docs
CI / check (push) Successful in 1m13s
The landing page had no install command anywhere, and the Storybook
welcome page only linked onward to Getting started. Add an Install
section to the site with the npm, pnpm, yarn and bun commands, the two
styling setups, and a link to the package on npmjs.com. Repeat the npm
command on the Storybook welcome page.

Also correct the roadmap, which still listed publishing the first
release and adding a public repository URL as pending. Both shipped in
0.4.0 and 0.4.1.
2026-09-29 11:38:46 +05:30
thekhalidsha 63fc279123 Release 0.4.1
CI / check (push) Successful in 1m24s
Cut the release that carries the repository and bugs links to npm, and
record them under 0.4.1 in the changelog. No component changes.
2026-09-29 11:20:02 +05:30
thekhalidsha 2edab3b8bc Link the package to its public repository
CI / check (push) Successful in 1m28s
The repo moved from a local Gitea to a public one at
git.openkhalix.com, renamed ui-showcase to tansy-ui. Add the
repository and bugs fields so the npm page links to the source and
its issue tracker, and record it under Unreleased for 0.4.1.
2026-09-29 11:15:01 +05:30
thekhalidsha 9255b255a6 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.
2026-09-29 09:24:03 +05:30
thekhalidsha 23e67006d3 Make every component and the landing page responsive (v0.3.1)
Every story and the landing page now fit from a 320px phone to a wide
desktop without scrolling sideways.

- Inputs in flex rows (Input, FeaturedInput, NumberInput, Combobox) shrink
  instead of holding their native width
- Tab rows and ToggleGroup scroll within themselves on narrow screens;
  vertical tabs stack above their panel on phones
- Positioned popups cap at Base UI's --available-width
- Landing page: tablet header no longer crowds; code sample fits at 1024px
- Storybook a11y panel skips page-level rules that can't apply to a story
- check-stories.mjs gains --width and fails on horizontal overflow; all
  423 stories pass at 320, 375, 768 and desktop widths in both modes
2026-09-28 22:47:26 +05:30
thekhalidsha f01de83733 Rebuild Tansy UI on Base UI with one API and dark mode (v0.3.0)
Every component is rebuilt on @base-ui/react with a single prop API,
token-only colours and dark mode, and 28 new components are added.

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

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

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

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

No files matched your search

+4 -8
View File
@@ -1,10 +1,6 @@
node_modules
npm-debug.log*
dist
storybook-static
**/node_modules
**/dist
apps/docs/storybook-static
.git
.gitignore
.dockerignore
Dockerfile
README.md
*.log
scripts/deploy.env
+25
View File
@@ -0,0 +1,25 @@
# Runs on every push and pull request. Gitea Actions uses GitHub Actions syntax.
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm test
# Package, landing page and Storybook.
- run: npm run build
# What `npm publish` would upload.
- run: npm pack -w @openkhalix/tansy-ui --dry-run
+34
View File
@@ -0,0 +1,34 @@
# Publishes @openkhalix/tansy-ui when a version tag (v0.4.0, v1.0.0 …) is pushed.
#
# Needs a repository secret NPM_TOKEN: an npm "Automation" (or granular
# publish) token for an account that belongs to the openkhalix npm org.
name: Release
on:
push:
tags: ['v*']
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
cache: npm
registry-url: https://registry.npmjs.org
- run: npm ci
- name: Tag must match the package version
run: |
version=$(node -p "require('./packages/ui/package.json').version")
if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then
echo "Tag ${GITHUB_REF_NAME} does not match package version v${version}" >&2
exit 1
fi
- run: npm run lint
- run: npm test
# prepublishOnly re-runs typecheck, tests and the library build.
- run: npm publish -w @openkhalix/tansy-ui --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+27 -2
View File
@@ -1,8 +1,33 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"plugins": [
"react",
"typescript",
"oxc"
],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
"react/only-export-components": [
"warn",
{
"allowConstantExport": true
}
]
},
"overrides": [
{
"files": [
"packages/ui/src/components/Card.tsx",
"packages/ui/src/components/Dialog.tsx",
"packages/ui/src/components/Drawer.tsx",
"packages/ui/src/components/DropdownMenu.tsx",
"packages/ui/src/components/Popover.tsx",
"packages/ui/src/components/Table.tsx",
"packages/ui/src/components/Tabs.tsx"
],
"rules": {
"react/only-export-components": "off"
}
}
]
}
-17
View File
@@ -1,17 +0,0 @@
import type { StorybookConfig } from '@storybook/react-vite'
const config: StorybookConfig = {
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(ts|tsx)'],
addons: ['@storybook/addon-docs', '@storybook/addon-a11y'],
framework: {
name: '@storybook/react-vite',
options: {},
},
// Serves the Tansy mark and favicon to the manager and the Welcome page.
staticDirs: ['../public'],
docs: {
defaultName: 'Documentation',
},
}
export default config
-92
View File
@@ -1,92 +0,0 @@
import { useEffect, useRef, type ReactElement } from 'react'
import type { Decorator, Preview } from '@storybook/react-vite'
import '../src/index.css'
import { applyPalette } from '../src/theme/applyPalette'
import { palettes, DEFAULT_PALETTE, type PaletteName } from '../src/theme/palettes'
import { tansyTheme } from './tansyTheme'
/**
* Wraps every story in a themed surface.
*
* The palette globals are set on this wrapper rather than on
* `document.documentElement` so a story can opt into a *different* palette on
* its own subtree without fighting the global one, and so the docs page keeps
* its own chrome.
*
* Declared as a named component (not an inline arrow) so the rules-of-hooks lint
* recognises the hook calls below.
*/
function PaletteSurface({ palette, children }: { palette: PaletteName; children: ReactElement }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current) applyPalette(ref.current, palette)
}, [palette])
return (
<div
ref={ref}
data-palette={palette}
style={{
padding: '1.5rem',
minHeight: '100%',
color: 'var(--color-gray-900)',
}}
>
{children}
</div>
)
}
const withPalette: Decorator = (Story, context) => {
const palette = (context.globals.palette ?? DEFAULT_PALETTE) as PaletteName
return <PaletteSurface palette={palette}><Story /></PaletteSurface>
}
const preview: Preview = {
title: 'Tansy UI / Component Workshop',
decorators: [withPalette],
globalTypes: {
palette: {
description: 'Brand palette applied to every element in the canvas.',
toolbar: {
title: 'Palette',
icon: 'paintbrush',
items: Object.values(palettes).map((p) => ({
value: p.name,
title: `${p.label} — ${p.note}`,
})),
dynamicTitle: true,
},
},
},
initialGlobals: {
palette: DEFAULT_PALETTE,
},
parameters: {
docs: {
theme: tansyTheme,
},
options: {
storySort: {
order: ['Welcome', 'Actions', 'Forms', 'Data entry', 'Feedback', 'Display', 'Layout', 'Navigation', 'Overlays'],
},
},
backgrounds: {
default: 'showcase',
values: [
{ name: 'showcase', value: '#f3f4f6' },
{ name: 'surface', value: '#ffffff' },
{ name: 'dark', value: '#12151c' },
],
},
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
}
export default preview
-30
View File
@@ -1,30 +0,0 @@
# 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.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.
+11 -6
View File
@@ -4,25 +4,30 @@ FROM node:26-alpine AS build
WORKDIR /app
# Workspace manifests first, so dependency installs cache between builds.
COPY package.json package-lock.json ./
COPY packages/ui/package.json packages/ui/
COPY packages/brand/package.json packages/brand/
COPY apps/site/package.json apps/site/
COPY apps/docs/package.json apps/docs/
RUN npm ci
COPY . .
RUN npm run lint \
&& npm run build \
&& npm run build-storybook
&& npm test \
&& npm run build
FROM nginx:1.29-alpine AS runtime
LABEL org.opencontainers.image.title="Tansy UI" \
org.opencontainers.image.description="Landing page and Storybook for the Tansy UI React component kit" \
org.opencontainers.image.source="local:ui-showcase" \
org.opencontainers.image.licenses="UNLICENSED"
org.opencontainers.image.source="https://git.openkhalix.com/thekhalidsha/tansy-ui" \
org.opencontainers.image.licenses="MIT"
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
COPY --from=build /app/storybook-static /usr/share/nginx/html/docs
COPY --from=build /app/apps/site/dist /usr/share/nginx/html
COPY --from=build /app/apps/docs/storybook-static /usr/share/nginx/html/docs
EXPOSE 80
+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.
+71 -117
View File
@@ -1,154 +1,108 @@
<p align="center">
<img src="public/tansy-mark.svg" width="88" height="88" alt="Tansy UI logo" />
<img src="packages/brand/public/tansy-mark.svg" width="88" height="88" alt="Tansy UI logo" />
</p>
<h1 align="center">Tansy UI</h1>
<p align="center">
A themeable React component kit, with every state documented in Storybook.<br />
By OpenKhalix.
A themeable, accessible React component kit by OpenKhalix.<br />
<a href="https://ui.openkhalix.com">Website</a> ·
<a href="https://ui.openkhalix.com/docs/">Storybook</a> ·
<a href="https://git.openkhalix.com/thekhalidsha/tansy-ui">Source</a> ·
<a href="packages/ui/README.md">Package README</a> ·
<a href="packages/ui/CHANGELOG.md">Changelog</a>
</p>
---
Tansy UI is named after the tansy flower, also called *golden buttons*: many small, round heads that together read as one bloom. The kit works the same way. It is a set of small, owned parts (buttons, fields, selects, feedback and overlays) that combine into a consistent interface.
Tansy UI is named after the tansy flower, also called *golden buttons*: many small, round heads that read
as one bloom. It is published to npm as **`@openkhalix/tansy-ui`**:
Every part ships with:
- **Named variants.** A short list of deliberate choices, such as `variant="outline"`, instead of one-off styling.
- **Its states.** Error, disabled, loading and required are part of the component, and each has its own story.
- **Tokens, not hex codes.** Colours come from a 50–900 palette ramp, so switching the palette re-themes every part without a code change.
> **Status:** pre-release (v0.2.0). Tansy UI is not published to npm yet. It is developed in this repository, with a landing page and a Storybook workshop as its showcase.
## Components
| Group | Components |
|---|---|
| Actions | `Button`, `LinkButton` |
| Forms | `Input`, `FeaturedInput`, `Select`, `Checkbox`, `Radio`, `Switch`, `TextArea` |
| Data entry | `TextField` |
| Feedback | `Alert`, `Spinner` |
| Display | `Badge` |
| Layout | `Card` (with `Card.Header`, `Card.Title`, `Card.Body`, `Card.Footer`) |
| Navigation | `Accordion` |
| Overlays | `Tooltip` |
Each component lives in `src/components/` with its style maps in a sibling `*.tokens.ts` and its stories in `*.stories.tsx`.
## Usage
```tsx
import { useState } from 'react'
import { Button } from './components/Button'
import { FeaturedInput } from './components/FeaturedInput'
import { Switch } from './components/Switch'
export function InviteForm() {
const [email, setEmail] = useState('')
return (
<form>
<FeaturedInput
label="Work email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<Switch label="Send a welcome email" defaultChecked />
<Button type="submit">Send invite</Button>
</form>
)
}
```bash
npm install @openkhalix/tansy-ui
```
## Theming
See the [package README](packages/ui/README.md) for setup and usage.
Tansy UI ships seven palettes: Classic Blue (default), Emerald, Violet, Amber, Crimson, Slate and Teal. Each defines full `primary`, `secondary`, `gray` and `zink` ramps plus semantic colours in `src/theme/palettes.ts`.
## Repository layout
`applyPalette(element, name)` writes a palette as CSS custom properties on any element. Tailwind v4 reads those properties, so a palette applies to one subtree and several palettes can appear on the same page:
This is an npm workspaces monorepo, laid out the way MUI and shadcn/ui lay out theirs:
```ts
import { applyPalette } from './theme/applyPalette'
| Path | Package | Published | What it is |
|---|---|---|---|
| [`packages/ui`](packages/ui) | `@openkhalix/tansy-ui` | yes | The components, their stories and tests, tokens, and the library build |
| [`packages/brand`](packages/brand) | `@tansy/brand` | no | The Tansy mark and the component catalogue, shared by both apps |
| [`apps/site`](apps/site) | `@tansy/site` | no | The landing page at ui.openkhalix.com |
| [`apps/docs`](apps/docs) | `@tansy/docs` | no | Storybook at ui.openkhalix.com/docs |
| [`docs`](docs) | | | [Conventions](docs/CONVENTIONS.md) and [roadmap](docs/ROADMAP.md) |
| [`scripts`](scripts) | | | Deploy, story checks, package install tests, catalogue generator |
applyPalette(document.getElementById('settings')!, 'emerald')
```
The apps depend on the package through its real `exports`. In this repo they resolve its `source` export
condition, so editing a component hot-reloads the landing page and Storybook without a rebuild. Outside
users get the built files in `dist/`.
Storybook's **Palette** toolbar and the landing page playground both use this function.
## Development
## Develop
```bash
npm install
npm run dev # landing page at http://localhost:5173
npm run storybook # component workshop at http://localhost:6006
npm run storybook # Storybook at http://localhost:6006
npm run lint
npm run build # landing page -> dist/
npm run build-storybook # workshop -> storybook-static/
npm run typecheck
npm test # unit, keyboard and axe tests for every component
npm run build # package, then landing page, then Storybook
```
### Adding a component
1. Add it under `src/components/`, with style maps in a sibling `*.tokens.ts`.
2. Add a colocated `ComponentName.stories.tsx` that covers every meaningful state.
3. Read colours from the palette ramps (`bg-primary-500`) so the palette switcher reaches it.
4. Run `npm run build-storybook && python3 scripts/gen_catalogue.py --patch` to refresh the landing page catalogue.
## Versioning
Tansy UI follows [Semantic Versioning](https://semver.org). While the version is `0.x`, a minor release may include breaking changes.
- `package.json` holds the version. The build injects it into the landing page and Storybook through `src/version.ts`, so it is never typed by hand.
- Every release gets an entry in [`CHANGELOG.md`](CHANGELOG.md) and an annotated git tag such as `v0.2.0`.
- Every deploy publishes `/version.json`, which records the version and commit that are live.
To cut a release:
### Checks before a release
```bash
# 1. Move the [Unreleased] notes in CHANGELOG.md under the new version, then:
npm version minor -m "Release v%s" # or patch / major; bumps package.json, commits and tags
git push origin main --follow-tags
python3 scripts/deploy.py # builds that commit and deploys it
npm run build:docs
node scripts/check-stories.mjs --mode light # every story in Chrome: errors and axe
node scripts/check-stories.mjs --mode dark
node scripts/check-stories.mjs --width 320 # nothing may scroll sideways on phones
npm run test:package # packs the package and installs it into Vite + Tailwind,
# plain React and Next.js apps; each must build and render
```
## Project structure
Adding a component: follow [`docs/CONVENTIONS.md`](docs/CONVENTIONS.md), export it from
`packages/ui/src/index.ts`, then run `python3 scripts/gen_catalogue.py --patch` after `npm run build:docs`
to refresh the landing page catalogue.
```text
src/
├── brand/TansyMark.tsx # Palette-aware logo
├── components/ # Components, their tokens and their stories
├── data/catalogue.ts # Landing page catalogue (regenerated by scripts/gen_catalogue.py)
├── theme/ # Palettes and applyPalette()
├── version.ts # VERSION, injected from package.json
├── Welcome.mdx # Storybook welcome page
├── App.tsx # Landing page, built only from Tansy components
└── index.css # Tailwind entry, palette tokens, landing styles
.storybook/ # Storybook config, Tansy theme, fonts
public/ # tansy-mark.svg and favicon.svg
scripts/ # Deploy and catalogue scripts
## Release
1. Move the **Unreleased** notes in [`packages/ui/CHANGELOG.md`](packages/ui/CHANGELOG.md) under the new
version and set `version` in `packages/ui/package.json`.
2. Run the checks above.
3. Commit, tag and push: `git tag -a v0.4.0 -m "Tansy UI v0.4.0" && git push origin main --follow-tags`.
4. The **Release** workflow (`.gitea/workflows/release.yml`) checks that the tag matches the package
version, re-runs the checks and publishes to npm. It needs an `NPM_TOKEN` repository secret for an
account in the `openkhalix` npm organisation.
To publish by hand instead: `npm login`, then `npm publish -w @openkhalix/tansy-ui` (the package's
`prepublishOnly` runs the type-check, tests and build first).
## Deploy the website
The landing page is served at `/` and Storybook at `/docs/`.
- **cPanel:** `python3 scripts/deploy.py` builds a committed tree, uploads it and removes files left over
from earlier builds. See [`scripts/README.md`](scripts/README.md).
- **Container:** the `Dockerfile` runs the checks, builds both apps and serves them from nginx with a
`/healthz` endpoint:
```bash
docker build -t tansy-ui .
docker run --rm -p 8041:80 tansy-ui
```
## Brand
The mark is a tansy flowerhead: six buttons in the palette's primary colour around a gold centre button.
`packages/brand/src/TansyMark.tsx` re-themes with the active palette; `packages/brand/public/` holds the
fixed-colour SVG and the favicon. Typefaces: Schibsted Grotesk, Instrument Sans and JetBrains Mono.
- `src/brand/TansyMark.tsx` re-themes with the active palette. The gold centre stays fixed.
- `public/tansy-mark.svg` is the fixed Classic Blue version, used by Storybook.
- `public/favicon.svg` is the mark on a dark tile, so it stays visible in both light and dark browser tabs.
## Licence
Typefaces: Schibsted Grotesk for headings, Instrument Sans for text and JetBrains Mono for code.
## Deployment
The build serves the landing page at `/` and Storybook at `/docs/`.
**Container.** The `Dockerfile` lints and builds both surfaces, then serves them from nginx with a `/healthz` endpoint:
```bash
docker build -t tansy-ui .
docker run --rm -p 8041:80 tansy-ui
curl http://127.0.0.1:8041/healthz
```
**cPanel.** `python3 scripts/deploy.py` builds, packages and uploads to a cPanel host, then removes files left over from earlier builds. See [`scripts/README.md`](scripts/README.md) for setup.
[MIT](LICENSE) © OpenKhalix. Free to use, fork and ship in commercial products; keep the copyright
notice in copies of the code. A visible credit ("UI by Tansy UI") is appreciated but not required.
Contributions are welcome.
+32
View File
@@ -0,0 +1,32 @@
import { useEffect, type ReactNode } from 'react'
import { applyPalette, type PaletteName } from '@openkhalix/tansy-ui'
/**
* Applies the toolbar's palette and light/dark mode to <html>.
*
* It has to be the root element, not a wrapper: Base UI renders popups (menus,
* selects, dialogs, toasts) into a portal on document.body, and they must pick
* up the same tokens as the story.
*/
export function ThemeSurface({
palette,
mode,
padded,
children,
}: {
palette: PaletteName
mode: 'light' | 'dark'
padded: boolean
children: ReactNode
}) {
useEffect(() => {
const root = document.documentElement
applyPalette(root, palette)
root.classList.toggle('dark', mode === 'dark')
root.dataset.palette = palette
document.body.style.background = 'var(--color-background)'
document.body.style.color = 'var(--color-fg)'
}, [palette, mode])
return <div style={{ padding: padded ? '1.5rem' : 0, minHeight: '100%' }}>{children}</div>
}
+25
View File
@@ -0,0 +1,25 @@
import type { StorybookConfig } from '@storybook/react-vite'
import remarkGfm from 'remark-gfm'
const config: StorybookConfig = {
stories: ['../src/**/*.mdx', '../../../packages/ui/src/**/*.stories.@(ts|tsx)'],
addons: [
{
name: '@storybook/addon-docs',
// GitHub-flavoured Markdown, so tables in the Introduction pages render.
options: { mdxPluginOptions: { mdxCompileOptions: { remarkPlugins: [remarkGfm] } } },
},
'@storybook/addon-a11y',
],
framework: {
name: '@storybook/react-vite',
options: {},
},
// Serves the Tansy mark and favicon to the manager and the Welcome page.
staticDirs: ['../../../packages/brand/public'],
docs: {
defaultName: 'Documentation',
},
}
export default config
File renamed without changes.
File renamed without changes.
File renamed without changes.
+90
View File
@@ -0,0 +1,90 @@
import type { Decorator, Preview } from '@storybook/react-vite'
import '../src/styles.css'
import { palettes, DEFAULT_PALETTE, type PaletteName } from '@openkhalix/tansy-ui'
import { tansyTheme } from './tansyTheme'
import { ThemeSurface } from './ThemeSurface'
const withTheme: Decorator = (Story, context) => {
const palette = (context.globals.palette ?? DEFAULT_PALETTE) as PaletteName
const mode = context.globals.mode === 'dark' ? 'dark' : 'light'
const padded = context.parameters.layout !== 'fullscreen'
return (
<ThemeSurface palette={palette} mode={mode} padded={padded}>
<Story />
</ThemeSurface>
)
}
const preview: Preview = {
title: 'Tansy UI / Component Workshop',
decorators: [withTheme],
globalTypes: {
mode: {
description: 'Light or dark mode for every component and popup.',
toolbar: {
title: 'Mode',
icon: 'contrast',
items: [
{ value: 'light', title: 'Light', icon: 'sun' },
{ value: 'dark', title: 'Dark', icon: 'moon' },
],
dynamicTitle: true,
},
},
palette: {
description: 'Brand palette applied to every element in the canvas.',
toolbar: {
title: 'Palette',
icon: 'paintbrush',
items: Object.values(palettes).map((p) => ({
value: p.name,
title: `${p.label} — ${p.note}`,
})),
dynamicTitle: true,
},
},
},
initialGlobals: {
mode: 'light',
palette: DEFAULT_PALETTE,
},
parameters: {
backgrounds: { disable: true },
a11y: {
// Page-level rules can't apply to an isolated component: a story has no
// <main>, no <h1> and no landmarks of its own. Everything else runs.
config: {
rules: [
{ id: 'landmark-one-main', enabled: false },
{ id: 'page-has-heading-one', enabled: false },
{ id: 'region', enabled: false },
],
},
},
docs: {
theme: tansyTheme,
},
options: {
storySort: {
order: [
'Introduction',
['Welcome', 'Getting started', 'Theming', 'Accessibility', 'Changelog', 'Roadmap'],
'Actions',
'Forms',
'Feedback',
'Display',
'Layout',
'Navigation',
'Overlays',
],
},
},
controls: {
matchers: {
date: /Date$/i,
},
},
},
}
export default preview
File renamed without changes.
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@tansy/docs",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "storybook dev -p 6006",
"build": "storybook build -o storybook-static"
},
"dependencies": {
"@openkhalix/tansy-ui": "*",
"@tansy/brand": "*",
"lucide-react": "^1.48.0",
"react": "^19.2.8",
"react-dom": "^19.2.8"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.6.0",
"@storybook/addon-docs": "^10.6.0",
"@storybook/react-vite": "^10.6.0",
"@tailwindcss/vite": "^4.3.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"remark-gfm": "^4.0.1",
"storybook": "^10.6.0",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.3.0"
}
}
+37
View File
@@ -0,0 +1,37 @@
import { Meta } from '@storybook/addon-docs/blocks'
import { DocHero } from './DocBlocks'
<Meta title="Introduction/Accessibility" />
<DocHero title="Accessibility">
What every Tansy UI component guarantees, how that's checked, and what to verify by hand when you compose them.
</DocHero>
## What every component guarantees
| Area | Guarantee |
|---|---|
| Behaviour | Interactive parts are built on [Base UI](https://base-ui.com), which implements the WAI-ARIA patterns: focus traps and focus return for dialogs, roving focus and type-ahead for menus and lists, and arrow keys for tabs, radios and sliders. |
| Keyboard focus | Every interactive element shows a visible focus ring (`focus-visible`), including the hidden inputs behind Checkbox, Radio and Switch. |
| Labels | Form fields sit in `Field`, which links the label, description and error to the control with `aria-labelledby`, `aria-describedby` and `aria-invalid`. Icon-only buttons require an `aria-label`. |
| Popups | Escape closes dialogs, menus, popovers, selects and tooltips, and focus returns to the trigger. Tooltips open on keyboard focus as well as hover. |
| Announcements | Alerts use `role="alert"` only for danger and warning; other colours use `role="status"`. Toasts announce through one polite live region. Spinners and progress bars carry an accessible name and value. |
| Colour | Text meets WCAG AA contrast (4.5:1) in light and dark mode, in every palette. Status is never shown by colour alone: errors have text, and badges and alerts have icons or labels. |
| Motion | Animations respect `prefers-reduced-motion`. |
## How it's checked
1. **Unit tests.** Every component has Vitest and Testing Library tests for roles, names, keyboard interaction and label wiring, plus an axe scan (`npm test`).
2. **Every story in a real browser.** `scripts/check-stories.mjs` loads each story in Chrome, in light and dark mode, and fails on runtime errors or any axe violation, colour contrast included.
3. **The Accessibility panel.** Below the canvas, axe re-checks the story you're looking at, including after you change controls.
## What to check by hand
Automated checks cover markup, names and contrast. When you compose components into a screen, also check:
1. **Tab** reaches every interactive part in visual order, and focus is always visible.
2. **Enter** and **Space** activate buttons, switches and checkboxes; **arrow keys** move within radio groups, menus, tabs and lists.
3. **Escape** closes anything that opened, and focus returns to what opened it.
4. A screen reader reads each field's label, help text and error when the field is focused.
5. Headings follow a logical order (`Card` and `Accordion` take a `headingLevel` prop).
6. The screen still works at 200% zoom and at phone width.
+11
View File
@@ -0,0 +1,11 @@
import { Meta, Markdown } from '@storybook/addon-docs/blocks'
import { DocHero } from './DocBlocks'
import changelog from '../../../packages/ui/CHANGELOG.md?raw'
<Meta title="Introduction/Changelog" />
<DocHero title="Changelog">
Every release of Tansy UI, rendered from CHANGELOG.md in the repository.
</DocHero>
<Markdown>{changelog.replace(/^# Changelog\s*/, '')}</Markdown>
+76
View File
@@ -0,0 +1,76 @@
import type { ReactNode } from 'react'
import { VERSION } from '@openkhalix/tansy-ui'
import { TansyMark } from '@tansy/brand'
/*
* Building blocks for the Storybook Introduction pages. They sit inside
* `sb-unstyled` so Storybook's docs typography does not restyle them, and use
* inline styles so they read the same in every palette.
*/
const ink = '#12151c'
const muted = '#6b7384'
const line = '#dde1e8'
const display = '"Schibsted Grotesk", "Instrument Sans", sans-serif'
const mono = '"JetBrains Mono", ui-monospace, monospace'
/** Page header: mark, title, one-line summary and the kit version. */
export function DocHero({ title, children }: { title: string; children: ReactNode }) {
return (
<div className="sb-unstyled" style={{ display: 'flex', gap: 18, alignItems: 'flex-start', margin: '4px 0 32px' }}>
<TansyMark size={52} style={{ flexShrink: 0, marginTop: 4 }} />
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<span style={{ fontFamily: mono, fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', color: muted }}>
Tansy UI · v{VERSION}
</span>
<h1 style={{ margin: 0, fontFamily: display, fontWeight: 800, fontSize: 38, lineHeight: 1.05, letterSpacing: '-0.035em', color: ink }}>
{title}
</h1>
<p style={{ margin: 0, maxWidth: 620, fontSize: 16, lineHeight: 1.6, color: '#4a5162' }}>{children}</p>
</div>
</div>
)
}
export type DocCard = {
title: string
body: string
/** A Storybook path such as `/docs/introduction-theming--documentation`. */
path: string
}
/**
* Links that navigate the whole Storybook, not just the preview frame.
* `./?path=` resolves next to iframe.html, so it works at `/` in dev and
* under `/docs/` in production.
*/
export function DocCards({ items }: { items: DocCard[] }) {
return (
<div
className="sb-unstyled"
style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))', gap: 12, margin: '16px 0 32px' }}
>
{items.map((item) => (
<a
key={item.path}
href={`./?path=${item.path}`}
target="_top"
style={{
display: 'flex',
flexDirection: 'column',
gap: 6,
padding: '16px 18px',
border: `1px solid ${line}`,
borderRadius: 10,
background: '#fff',
color: ink,
textDecoration: 'none',
}}
>
<strong style={{ fontFamily: display, fontSize: 16, fontWeight: 700 }}>{item.title} →</strong>
<span style={{ fontSize: 14, lineHeight: 1.5, color: muted }}>{item.body}</span>
</a>
))}
</div>
)
}
+89
View File
@@ -0,0 +1,89 @@
import { Meta, Source } from '@storybook/addon-docs/blocks'
import { DocHero } from './DocBlocks'
<Meta title="Introduction/Getting started" />
<DocHero title="Getting started">
Install one package, add one line of CSS, and every component is ready to use in any React 19 app, with or without Tailwind.
</DocHero>
## Requirements
| Dependency | Version | Why |
|---|---|---|
| React and React DOM | 19 | Peer dependency. Components take `ref` as a normal prop |
| Tailwind CSS | 4, optional | With Tailwind, your build generates the utilities; without it, use the prebuilt `styles.css` |
| `@base-ui/react` | 1.8+ | Accessible behaviour: focus management, keyboard navigation, popups. Installed with the package |
| `lucide-react` | 1.x | The icons components draw themselves (chevrons, close, status icons). Installed with the package |
| `clsx` + `tailwind-merge` | 2 and 3 | `cn()` merges class names so your `className` always wins |
## 1. Install
<Source language="bash" code={`npm install @openkhalix/tansy-ui`} />
## 2. Add the styles
**With Tailwind CSS v4** (recommended). Import the tokens after Tailwind, and let Tailwind scan the package for the classes it uses:
<Source
language="css"
code={`@import "tailwindcss";
@import "@openkhalix/tansy-ui/tokens.css";
@source "../node_modules/@openkhalix/tansy-ui/dist";`}
/>
**Without Tailwind.** Import the prebuilt stylesheet once. It includes the tokens, the utilities the components use, and a modern CSS reset the components rely on:
<Source language="ts" code={`import '@openkhalix/tansy-ui/styles.css'`} />
## 3. Render components
<Source
language="tsx"
code={`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>
)
}`}
/>
Every form component takes the same field props, `label`, `description`, `error` and `required`, and links them to the control for screen readers. Values work controlled (`value` and `onValueChange`) or uncontrolled (`defaultValue`).
## Next.js
Components are marked `"use client"`, so you can import them straight into Server Components. Helpers like `cn` and `applyPalette` stay server-safe.
## 4. Dark mode
Add the `dark` class to `<html>`. The surface, border and text tokens switch, and every component and popup follows:
<Source language="tsx" code={`document.documentElement.classList.toggle('dark', prefersDark)`} />
## 5. Pick a palette (optional)
Classic Blue is the default. Apply another palette to any element; everything inside it re-themes, including popups when you apply it to `<html>`:
<Source
language="tsx"
code={`import { applyPalette } from '@openkhalix/tansy-ui'
applyPalette(document.documentElement, 'emerald')`}
/>
## Fonts
The Tansy brand uses Schibsted Grotesk for headings, Instrument Sans for text and JetBrains Mono for code, all from Google Fonts. Components inherit your app's font, so these are optional.
+11
View File
@@ -0,0 +1,11 @@
import { Meta, Markdown } from '@storybook/addon-docs/blocks'
import { DocHero } from './DocBlocks'
import roadmap from '../../../docs/ROADMAP.md?raw'
<Meta title="Introduction/Roadmap" />
<DocHero title="Roadmap">
How Tansy UI compares with MUI and shadcn/ui, and the plan to get it ready to publish. Rendered from docs/ROADMAP.md.
</DocHero>
<Markdown>{roadmap.replace(/^# Roadmap\s*/, '')}</Markdown>
+66
View File
@@ -0,0 +1,66 @@
import { Meta, ColorPalette, ColorItem, Source } from '@storybook/addon-docs/blocks'
import { DocHero } from './DocBlocks'
import { palettes } from '@openkhalix/tansy-ui'
<Meta title="Introduction/Theming" />
export const STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
export const ramp = (r) => Object.fromEntries(STEPS.map((s) => [s, r[s]]))
<DocHero title="Theming">
Components never use hex codes. They read colour from four 50–900 ramps and a set of semantic colours, so swapping the
palette re-themes every part without touching component code.
</DocHero>
## How it works
1. `src/index.css` registers every colour in Tailwind's `@theme`, so utilities like `bg-primary-500` exist at build time. These are the Classic Blue defaults.
2. `applyPalette(element, name)` writes a palette's values as `--color-*` custom properties on an element. Everything inside that element picks them up.
3. Because the values are scoped to an element, one page can show several palettes at once. Storybook's **Palette** toolbar and the landing page playground both work this way.
<Source
language="tsx"
code={`import { applyPalette } from '@openkhalix/tansy-ui'
// Whole app
applyPalette(document.documentElement, 'violet')
// One subtree, e.g. a preview panel
applyPalette(previewRef.current, 'teal')`}
/>
## Token names
| Layer | Utilities | Used for |
|---|---|---|
| Surfaces | `bg-background`, `bg-surface`, `bg-surface-muted`, `bg-surface-sunken` | Page, cards, inputs and popups, hover fills |
| Borders | `border-border`, `border-border-strong` | Dividers and control outlines |
| Text | `text-fg`, `text-fg-muted`, `text-fg-subtle` | Body text, secondary text, placeholders |
| Brand | `primary-50` … `primary-900`, `secondary-*` | Actions, focus rings, selection. Set by the palette |
| Status | `success-*`, `warning-*`, `danger-*`, `info-*` (50 … 900) | The same in every palette, so danger is always red |
Components use only these tokens, never raw Tailwind colours or hex codes, which is why a palette or mode change reaches all of them.
## Dark mode
Add the `dark` class to `<html>`. The surface, border and text tokens switch to their dark values, and components adjust brand and status colours with `dark:` variants where contrast needs it. Every story is checked for contrast in both modes. Use the **Mode** toolbar button to switch this workshop.
<Source language="tsx" code={`document.documentElement.classList.toggle('dark', true)`} />
## Palettes
Each palette's primary ramp. The 500 step is the one bare `bg-primary` resolves to.
<ColorPalette>
{Object.values(palettes).map((p) => (
<ColorItem key={p.name} title={p.label} subtitle={p.note} colors={ramp(p.primary)} />
))}
</ColorPalette>
## Status colours
The same in every palette. Bare names such as `bg-success` resolve to these values; the full 50–900 scales are in `src/styles/tokens.css`.
<ColorPalette>
<ColorItem title="Status" subtitle="Shared by every palette" colors={palettes.classicBlue.semantic} />
</ColorPalette>
+46
View File
@@ -0,0 +1,46 @@
import { Meta, Source } from '@storybook/addon-docs/blocks'
import { DocHero, DocCards } from './DocBlocks'
import { documentation, totalStories } from '@tansy/brand'
<Meta title="Introduction/Welcome" />
<DocHero title="Welcome to Tansy UI">
A themeable React component kit by OpenKhalix. Every part is owned source code with its variants, states and tokens
documented here, one story per state.
</DocHero>
Tansy UI is named after the tansy flower, also called golden buttons: many small round heads that read as one bloom. The kit works the same way. It currently has **{documentation.length} components** and **{totalStories} stories**, built on Base UI with React 19, TypeScript and Tailwind CSS v4.
## Install
<Source language="bash" code={`npm install @openkhalix/tansy-ui`} />
Then add one line of CSS, either `@import "@openkhalix/tansy-ui/tokens.css"` for Tailwind v4 apps, or `import '@openkhalix/tansy-ui/styles.css'` for apps without Tailwind. Both setups are covered in [Getting started](/docs/introduction-getting-started--documentation).
## Start here
<DocCards
items={[
{ title: 'Getting started', body: 'Add Tansy UI to a Vite and Tailwind v4 project and render your first component.', path: '/docs/introduction-getting-started--documentation' },
{ title: 'Theming', body: 'The seven palettes, their 50–900 ramps, and how applyPalette() re-themes a subtree.', path: '/docs/introduction-theming--documentation' },
{ title: 'Accessibility', body: 'What each component guarantees today, and how the a11y panel checks every story.', path: '/docs/introduction-accessibility--documentation' },
{ title: 'Changelog', body: 'Every release, following Semantic Versioning.', path: '/docs/introduction-changelog--documentation' },
{ title: 'Roadmap', body: 'How Tansy UI compares with MUI and shadcn/ui, and what ships next.', path: '/docs/introduction-roadmap--documentation' },
{ title: 'Components', body: 'Browse every component, starting with Button.', path: '/docs/actions-button--documentation' },
]}
/>
## How to read this workshop
- **Documentation** pages list every prop, with controls you can change live.
- **Stories** show one state each: defaults, errors, disabled and loading states all get their own.
- **Mode** in the toolbar switches every component, popup included, between light and dark.
- **Palette** in the toolbar re-themes every component from the brand ramps.
- **Accessibility** runs axe checks against the open story in the panel below the canvas.
## Adding a component
1. Put the component in `src/components/` and keep its style maps in a sibling `*.tokens.ts`.
2. Add a colocated `ComponentName.stories.tsx` with a story for every meaningful state.
3. Read colours from the palette ramps (`bg-primary-500`), never from hex codes.
4. Run `npm run build-storybook`, then `python3 scripts/gen_catalogue.py --patch` to update the landing page catalogue.
+6
View File
@@ -0,0 +1,6 @@
@import "tailwindcss";
@import "../../../packages/ui/src/styles/tokens.css";
/* Components and their stories live in the package. */
@source "../../../packages/ui/src";
@source not "../../../packages/ui/src/**/*.test.tsx";
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"moduleResolution": "bundler",
"customConditions": ["source"],
"types": ["vite/client"],
"jsx": "react-jsx",
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src", ".storybook"]
}
+13
View File
@@ -0,0 +1,13 @@
import { readFileSync } from 'node:fs'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { defaultClientConditions, defineConfig } from 'vite'
/** Storybook's Vite config: stories render the package from source. */
const ui = JSON.parse(readFileSync(new URL('../../packages/ui/package.json', import.meta.url), 'utf8')) as { version: string }
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: { conditions: ['source', ...defaultClientConditions] },
define: { __TANSY_VERSION__: JSON.stringify(ui.version) },
})
View File
File renamed without changes.
+27
View File
@@ -0,0 +1,27 @@
{
"name": "@tansy/site",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -p tsconfig.json --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"@openkhalix/tansy-ui": "*",
"@tansy/brand": "*",
"lucide-react": "^1.48.0",
"react": "^19.2.8",
"react-dom": "^19.2.8"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.3.0"
}
}
+669
View File
@@ -0,0 +1,669 @@
import { useEffect, useState, type FormEvent, type ReactNode } from 'react'
import { ArrowRight, Mail, UserRound } from 'lucide-react'
import {
Alert,
Badge,
Button,
Card,
Checkbox,
FeaturedInput,
FeaturedSelect,
LinkButton,
Radio,
Switch,
Tooltip,
applyPalette,
palettes,
DEFAULT_PALETTE,
VERSION,
type PaletteName,
} from '@openkhalix/tansy-ui'
import { TansyMark, documentation, featured, totalStories, type FeaturedName } from '@tansy/brand'
const STORYBOOK = '/docs/'
const NPM_PAGE = 'https://www.npmjs.com/package/@openkhalix/tansy-ui'
const PKG = '@openkhalix/tansy-ui'
/** The install command per package manager, most-used first. */
const INSTALL_COMMANDS = [
{ manager: 'npm', command: `npm install ${PKG}` },
{ manager: 'pnpm', command: `pnpm add ${PKG}` },
{ manager: 'yarn', command: `yarn add ${PKG}` },
{ manager: 'bun', command: `bun add ${PKG}` },
] as const
/** The two supported styling setups: with Tailwind v4, and without. */
const TAILWIND_SETUP = `@import "tailwindcss";
@import "${PKG}/tokens.css";
@source "../node_modules/${PKG}/dist";`
const PLAIN_SETUP = `import '${PKG}/styles.css'`
const RAMP_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900] as const
const DEPARTMENTS = [
{ value: 'engineering', label: 'Engineering' },
{ value: 'finance', label: 'Finance' },
{ value: 'people', label: 'People operations' },
{ value: 'sales', label: 'Sales' },
{ value: 'support', label: 'Customer support' },
]
const PAY_CYCLES = [
{ value: 'monthly', label: 'Monthly' },
{ value: 'semi-monthly', label: 'Twice a month' },
{ value: 'weekly', label: 'Weekly' },
]
/** Storybook pages the landing page links into. */
const DOCS = {
gettingStarted: `${STORYBOOK}?path=/docs/introduction-getting-started--documentation`,
theming: `${STORYBOOK}?path=/docs/introduction-theming--documentation`,
accessibility: `${STORYBOOK}?path=/docs/introduction-accessibility--documentation`,
changelog: `${STORYBOOK}?path=/docs/introduction-changelog--documentation`,
roadmap: `${STORYBOOK}?path=/docs/introduction-roadmap--documentation`,
}
const USAGE = `import {
Button,
Switch,
} from '@openkhalix/tansy-ui'
<Switch label="Welcome email" />
<Button>Send invite</Button>`
const STATES = ['Default', 'Error', 'Disabled', 'Loading', 'Required', 'Controlled']
/** Mirrors docs/ROADMAP.md; update both together. */
const roadmap = [
{
stage: 'Shipped',
title: `v${VERSION}`,
color: 'success',
items: [
`${documentation.length} accessible components on Base UI`,
'Dark mode, seven palettes, one consistent API',
'Tests and a real-browser check for every story',
],
},
{
stage: 'Next',
title: 'Data and dates',
color: 'warning',
items: ['Date Picker and Date Range Picker', 'Data Table with sorting and filtering', 'Command palette'],
},
{
stage: 'Planned',
title: 'v1',
color: 'neutral',
items: ['A shadcn-compatible registry', 'Palette builder with contrast checks'],
},
] as const
/** A small live instance of each featured part, sized to sit in a list row. */
const previews: Record<FeaturedName, ReactNode> = {
Button: <Button size="sm">Save</Button>,
Switch: <Switch size="sm" aria-label="Example switch" defaultChecked />,
Checkbox: <Checkbox aria-label="Example checkbox" defaultChecked />,
Badge: (
<span className="preview-badges">
<Badge color="success" dot>
Paid
</Badge>
<Badge color="warning" dot>
Pending
</Badge>
</span>
),
Tooltip: (
<Tooltip content="Explains a control without adding clutter." side="left">
<Button size="sm" variant="outline" color="neutral">
Hover me
</Button>
</Tooltip>
),
}
/** Highlights the few token kinds USAGE contains, without a syntax library. */
function highlight(code: string) {
return code.split(/('[^']*'|"[^"]*"|\bimport\b|\bfrom\b|<\/?[A-Z]\w*|\/>|>)/g).map((part, index) => {
if (!part) return null
let kind = ''
if (part === 'import' || part === 'from') kind = 'tok-key'
else if (/^['"]/.test(part)) kind = 'tok-str'
else if (/^<\/?[A-Z]|^\/?>$/.test(part)) kind = 'tok-tag'
return kind ? <span className={kind} key={index}>{part}</span> : part
})
}
/** Colours the bare package name in a shell command, e.g. `npm install @openkhalix/tansy-ui`. */
function highlightCommand(code: string) {
const escaped = PKG.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
return code
.split(new RegExp(`^(\\S+ (?:install|add) )(${escaped})$`))
.map((part, index) => {
if (index === 0) return part
return <span className={index === 1 ? 'tok-key' : 'tok-pkg'} key={index}>{part}</span>
})
}
function CodeSample() {
const [copied, setCopied] = useState(false)
async function copy() {
try {
await navigator.clipboard.writeText(USAGE)
setCopied(true)
window.setTimeout(() => setCopied(false), 1600)
} catch {
setCopied(false)
}
}
return (
<div className="code-sample">
<div className="code-sample-bar">
<span>InviteForm.tsx</span>
<Button size="sm" variant="ghost" onClick={copy} className="code-copy">
{copied ? 'Copied' : 'Copy'}
</Button>
</div>
<pre>
<code>{highlight(USAGE)}</code>
</pre>
</div>
)
}
/** A dark code panel with a copy button, reused by every install command. */
function CommandPanel({ label, code }: { label: string; code: string }) {
const [copied, setCopied] = useState(false)
async function copy() {
try {
await navigator.clipboard.writeText(code)
setCopied(true)
window.setTimeout(() => setCopied(false), 1600)
} catch {
setCopied(false)
}
}
return (
<div className="code-sample command-panel">
<div className="code-sample-bar">
<span>{label}</span>
<Button size="sm" variant="ghost" onClick={copy} className="code-copy" aria-label={`Copy the ${label} command`}>
{copied ? 'Copied' : 'Copy'}
</Button>
</div>
<pre>
<code>{highlightCommand(code)}</code>
</pre>
</div>
)
}
type FormErrors = Partial<Record<'name' | 'email' | 'department' | 'confirmed', string>>
function EmployeeForm() {
const [name, setName] = useState('Jane Doe')
const [email, setEmail] = useState('jane.doe@')
const [department, setDepartment] = useState('engineering')
const [cycle, setCycle] = useState('monthly')
const [welcome, setWelcome] = useState(true)
const [confirmed, setConfirmed] = useState(false)
const [errors, setErrors] = useState<FormErrors>({})
const [saving, setSaving] = useState(false)
const [added, setAdded] = useState<string | null>(null)
function validate(): FormErrors {
const next: FormErrors = {}
if (!name.trim()) next.name = "Enter the employee's full name."
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) next.email = 'Enter a full work email, like [email protected].'
if (!department) next.department = 'Choose a department.'
if (!confirmed) next.confirmed = 'Confirm the details before adding the employee.'
return next
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const next = validate()
setErrors(next)
if (Object.keys(next).length > 0) return
setSaving(true)
setAdded(null)
window.setTimeout(() => {
const dept = DEPARTMENTS.find((d) => d.value === department)?.label ?? department
const pay = PAY_CYCLES.find((c) => c.value === cycle)?.label.toLowerCase() ?? cycle
setAdded(`${name.trim()} joins ${dept}, paid ${pay}.${welcome ? ' A welcome email is on its way.' : ''}`)
setSaving(false)
}, 900)
}
function handleReset() {
setName('')
setEmail('')
setDepartment('')
setCycle('monthly')
setWelcome(true)
setConfirmed(false)
setErrors({})
setAdded(null)
}
return (
<form onSubmit={handleSubmit} noValidate>
<Card variant="elevated" padding="none" className="employee-card">
<Card.Header className="employee-card-header">
<Card.Title>Add an employee</Card.Title>
<p>They appear in the next payroll run.</p>
</Card.Header>
<Card.Body className="employee-card-body">
{added && (
<Alert key={added} color="success" title="Employee added" dismissible onOpenChange={(open) => !open && setAdded(null)}>
{added}
</Alert>
)}
<div className="form-row">
<FeaturedInput
name="employee-name"
label="Full name"
startIcon={<UserRound />}
value={name}
onValueChange={setName}
error={errors.name}
required
/>
<FeaturedInput
name="employee-email"
label="Work email"
type="email"
startIcon={<Mail />}
value={email}
onValueChange={setEmail}
error={errors.email}
required
/>
</div>
<FeaturedSelect
name="department"
label="Department"
options={DEPARTMENTS}
value={department || null}
onValueChange={(value) => setDepartment(value ?? '')}
clearable
error={errors.department}
required
/>
<Radio
name="pay-cycle"
label="Pay cycle"
options={PAY_CYCLES}
value={cycle}
onValueChange={setCycle}
orientation="horizontal"
description="How often this employee appears in a payroll run."
/>
<Switch
name="welcome-email"
label="Send a welcome email"
description="Includes the sign-in link and the first-day checklist."
checked={welcome}
onCheckedChange={setWelcome}
/>
<Checkbox
name="confirmed"
label="I checked these details against the signed offer letter"
checked={confirmed}
onCheckedChange={setConfirmed}
error={errors.confirmed}
/>
</Card.Body>
<Card.Footer className="employee-card-footer">
<Button variant="ghost" onClick={handleReset} disabled={saving}>
Clear form
</Button>
<Button type="submit" loading={saving} loadingText="Adding…">
Add employee
</Button>
</Card.Footer>
</Card>
</form>
)
}
function App() {
const [palette, setPalette] = useState<PaletteName>(DEFAULT_PALETTE)
const active = palettes[palette]
// On <html>, not the shell: select lists and tooltips portal to <body> and
// must wear the same palette.
useEffect(() => {
applyPalette(document.documentElement, palette)
}, [palette])
return (
<div className="site-shell" data-palette={palette}>
<header className="site-header">
<div className="container header-inner">
<a className="brand" href="#top" aria-label="Tansy UI home">
<TansyMark size={30} />
<span className="brand-name">
Tansy<span className="brand-ui">UI</span>
</span>
<span className="brand-by">by OpenKhalix</span>
</a>
<a className="version-pill" href={DOCS.changelog} aria-label={`Version ${VERSION}, see the changelog`}>
v{VERSION}
</a>
<nav className="header-nav" aria-label="Primary">
<a href="#install">Install</a>
<a href={DOCS.gettingStarted}>Docs</a>
<a href={STORYBOOK}>Components</a>
<a href="#playground">Theming</a>
<a href="#roadmap">Roadmap</a>
</nav>
<LinkButton href={STORYBOOK} size="sm" variant="outline" className="header-cta">
Storybook
</LinkButton>
</div>
</header>
<main id="top">
<section className="hero container" id="components">
<div className="hero-copy">
<p className="eyebrow">
<span>React component kit</span>
<span className="eyebrow-dim">v{VERSION} · {documentation.length} parts · {totalStories} stories</span>
</p>
<h1>
Small parts,
<br />
<em>one bloom.</em>
</h1>
<p className="lede">
Tansy UI is a React component kit named after the tansy flower, also called golden buttons. Every part
ships with its states, its tokens and a Storybook page, so screens come together from parts that
already work.
</p>
<div className="hero-actions">
<LinkButton href={STORYBOOK} size="lg" endIcon={<ArrowRight aria-hidden="true" />}>
Browse all components
</LinkButton>
<LinkButton href="#playground" size="lg" variant="outline">
Try the playground
</LinkButton>
</div>
<p className="stack">React 19 · TypeScript · Tailwind v4 · Storybook 10</p>
</div>
<Card variant="elevated" padding="none" className="featured-card" aria-labelledby="featured-title">
<Card.Header
className="featured-header"
action={
<Badge color="primary">
{featured.length} of {documentation.length}
</Badge>
}
>
<h2 id="featured-title">Featured parts</h2>
</Card.Header>
<Card.Body className="featured-body">
<ul className="featured-list">
{featured.map((item) => (
<li className="featured-row" key={item.name}>
<div className="featured-text">
<a href={item.href}>{item.name}</a>
<span>
{item.group} · {item.detail}
</span>
</div>
<div className="featured-preview">{previews[item.name]}</div>
</li>
))}
</ul>
</Card.Body>
<Card.Footer className="featured-footer">
<LinkButton
href={STORYBOOK}
variant="soft"
color="neutral"
fullWidth
endIcon={<ArrowRight aria-hidden="true" />}
>
See all {documentation.length} components
</LinkButton>
</Card.Footer>
</Card>
</section>
<section className="container install" id="install" aria-labelledby="install-title">
<div className="section-head">
<p className="kicker">Install</p>
<h2 id="install-title">One command from the npm registry.</h2>
<p className="section-lede">
Tansy UI is published as <code className="inline-code">{PKG}</code> under the OpenKhalix organisation.
It ships type declarations and one module per component, so your bundle only carries what you import.
</p>
</div>
<div className="install-grid">
<div className="install-main">
<CommandPanel label="Install with npm" code={INSTALL_COMMANDS[0].command} />
<p className="install-meta">
v{VERSION} · MIT · React 19 peer dependency ·{' '}
<a href={NPM_PAGE} rel="noreferrer noopener" target="_blank">
view on npmjs.com
</a>
</p>
<ul className="install-alt" aria-label="Other package managers">
{INSTALL_COMMANDS.slice(1).map(({ manager, command }) => (
<li key={manager}>
<CommandPanel label={manager} code={command} />
</li>
))}
</ul>
</div>
<div className="install-setup">
<h3>Then add the styles</h3>
<p className="install-setup-note">
Pick one. With Tailwind v4, import the tokens and let Tailwind scan the package. Without Tailwind,
import the prebuilt stylesheet, which carries its own reset.
</p>
<div className="install-panels">
<CommandPanel label="With Tailwind CSS v4" code={TAILWIND_SETUP} />
<CommandPanel label="Without Tailwind" code={PLAIN_SETUP} />
</div>
<LinkButton href={DOCS.gettingStarted} variant="outline" endIcon={<ArrowRight aria-hidden="true" />}>
Full getting started
</LinkButton>
</div>
</div>
</section>
<section className="container why" aria-labelledby="why-title">
<div className="section-head">
<p className="kicker">Why Tansy</p>
<h2 id="why-title">Built to be owned, themed and trusted.</h2>
</div>
<div className="why-grid">
<article className="why-card">
<div className="why-visual why-visual-code">
<CodeSample />
</div>
<h3>Source you own</h3>
<p>
Components live in your repository, like shadcn/ui. Read them, change them, and keep the variants your
product needs.
</p>
<a href={DOCS.gettingStarted}>Getting started →</a>
</article>
<article className="why-card">
<div className="why-visual">
<div className="why-swatches" role="group" aria-label="Try a palette">
{Object.values(palettes).map((p) => (
<button
key={p.name}
type="button"
aria-label={p.label}
aria-pressed={p.name === palette}
title={p.label}
style={{ background: p.primary[500] }}
onClick={() => setPalette(p.name)}
/>
))}
</div>
<div className="why-buttons">
<Button size="sm">Primary</Button>
<Button size="sm" variant="outline">Outline</Button>
</div>
</div>
<h3>Palettes scoped anywhere</h3>
<p>
Seven palettes, each a full 50–900 ramp. Apply one to the whole app or to a single panel, at runtime,
without a rebuild.
</p>
<a href={DOCS.theming}>Theming →</a>
</article>
<article className="why-card">
<div className="why-visual">
<div className="why-states">
{STATES.map((state) => (
<Badge key={state} color={state === 'Error' ? 'danger' : 'neutral'}>
{state}
</Badge>
))}
</div>
<p className="why-stat">
<strong>{totalStories}</strong> stories across <strong>{documentation.length}</strong> components
</p>
</div>
<h3>Every state documented</h3>
<p>
Each state gets its own Storybook story with axe accessibility checks, so reviews cover more than the
default look.
</p>
<a href={DOCS.accessibility}>Accessibility →</a>
</article>
</div>
</section>
<section className="playground" id="playground" aria-labelledby="playground-title">
<div className="container playground-grid">
<div className="playground-intro">
<p className="kicker">Playground</p>
<h2 id="playground-title">A working form, built only from Tansy parts.</h2>
<p>
Pick a palette and every part on this page re-themes from the same tokens. Storybook's Palette toolbar
does the same thing.
</p>
<fieldset className="palette-picker">
<legend>Palette</legend>
<div className="palette-options">
{Object.values(palettes).map((p) => (
<button
key={p.name}
type="button"
aria-pressed={p.name === palette}
onClick={() => setPalette(p.name)}
>
<span className="swatch" style={{ background: p.primary[500] }} aria-hidden="true" />
{p.label}
</button>
))}
</div>
<p className="palette-note">{active.note}</p>
</fieldset>
<div className="ramp" aria-label={`${active.label} primary ramp`}>
{RAMP_STEPS.map((step) => (
<div className="ramp-step" key={step}>
<span className="ramp-chip" style={{ background: active.primary[step] }} />
<span className="ramp-label">{step}</span>
</div>
))}
</div>
<p className="ramp-caption">
<code>primary-500</code> = <code>{active.primary[500].toLowerCase()}</code>
</p>
</div>
<EmployeeForm />
</div>
</section>
<section className="container roadmap" id="roadmap" aria-labelledby="roadmap-title">
<div className="section-head section-head-row">
<div>
<p className="kicker">Roadmap</p>
<h2 id="roadmap-title">From a kit to a package.</h2>
</div>
<LinkButton href={DOCS.roadmap} variant="outline" color="neutral" endIcon={<ArrowRight aria-hidden="true" />}>
Read the full roadmap
</LinkButton>
</div>
<ol className="roadmap-grid">
{roadmap.map((step) => (
<li className="roadmap-step" key={step.stage}>
<Badge color={step.color} dot>
{step.stage}
</Badge>
<h3>{step.title}</h3>
<ul>
{step.items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
</li>
))}
</ol>
</section>
</main>
<footer className="site-footer">
<div className="container footer-grid">
<div className="footer-brand">
<div className="footer-logo">
<TansyMark size={26} />
<strong>
Tansy<span className="brand-ui">UI</span>
</strong>
</div>
<p>A themeable React component kit by OpenKhalix.</p>
<p className="footer-version">
v{VERSION} · <a href={DOCS.changelog}>Changelog</a>
</p>
</div>
<nav className="footer-col" aria-label="Documentation">
<h2>Docs</h2>
<a href={DOCS.gettingStarted}>Getting started</a>
<a href={DOCS.theming}>Theming</a>
<a href={DOCS.accessibility}>Accessibility</a>
</nav>
<nav className="footer-col" aria-label="Components">
<h2>Components</h2>
{featured.slice(0, 3).map((item) => (
<a href={item.href} key={item.name}>
{item.name}
</a>
))}
<a href={STORYBOOK}>All {documentation.length} components</a>
</nav>
<nav className="footer-col" aria-label="Project">
<h2>Project</h2>
<a href={DOCS.roadmap}>Roadmap</a>
<a href={DOCS.changelog}>Changelog</a>
<a href="#playground">Playground</a>
</nav>
</div>
</footer>
</div>
)
}
export default App
+424 -107
View File
@@ -1,69 +1,11 @@
@import "tailwindcss";
@theme {
--font-sans: "Instrument Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
--font-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", monospace;
--font-display: "Schibsted Grotesk", "Instrument Sans", "Helvetica Neue", Arial, sans-serif;
--shadow-doc: 0 18px 46px -34px rgba(23, 25, 29, 0.38);
/* ------------------------------------------------------------------
Palette token registration.
Tailwind v4 only *generates* a utility class if its colour token is
declared here. The ported components reference `bg-primary-500`,
`text-primary-600`, `border-zink-700` and so on; without these
declarations the build silently emits no rules and those elements
render with no colour at all.
The values below are the Classic Blue defaults. They exist so the
utility classes are generated at build time. The Storybook palette
switcher overrides them at runtime on a wrapper element (see
src/theme/applyPalette.ts), which re-themes without a rebuild.
------------------------------------------------------------------ */
--color-primary-50: #eff6ff;
--color-primary-100: #dbeafe;
--color-primary-200: #bfdbfe;
--color-primary-300: #93c5fd;
--color-primary-400: #60a5fa;
--color-primary-500: #305ddd;
--color-primary-600: #274bc4;
--color-primary-700: #1e3a8a;
--color-primary-800: #1e40af;
--color-primary-900: #1e3a8a;
--color-primary: #305ddd;
--color-secondary-50: #f5f3ff;
--color-secondary-100: #ede9fe;
--color-secondary-200: #ddd6fe;
--color-secondary-300: #c4b5fd;
--color-secondary-400: #a78bfa;
--color-secondary-500: #8b5cf6;
--color-secondary-600: #7c3aed;
--color-secondary-700: #6d28d9;
--color-secondary-800: #5b21b6;
--color-secondary-900: #4c1d95;
--color-secondary: #8b5cf6;
--color-zink-50: #f8f8f9;
--color-zink-100: #f1f2f3;
--color-zink-200: #e4e6e8;
--color-zink-300: #cfd3d6;
--color-zink-400: #9aa2a9;
--color-zink-500: #6b7680;
--color-zink-600: #4d5761;
--color-zink-700: #313a43;
--color-zink-800: #1f262c;
--color-zink-900: #12171b;
--color-zink: #6b7680;
/* Semantic colours used by Alert, Badge and the status components. */
--color-success: #10b981;
--color-warning: #f59e0b;
--color-error: #ef4444;
--color-info: #3b82f6;
--color-danger: #ef4444;
}
@import "../../../packages/ui/src/styles/tokens.css";
/* The landing page renders package components: generate their utilities. */
@source "../../../packages/ui/src";
@source not "../../../packages/ui/src/**/*.stories.tsx";
@source not "../../../packages/ui/src/**/*.test.tsx";
/* ------------------------------------------------------------------
Tansy UI landing page.
@@ -160,6 +102,8 @@
color: var(--accent);
}
/* Element defaults stay in the base layer so component utilities (text-*, font-*) win. */
@layer base {
h1,
h2,
h3 {
@@ -173,6 +117,7 @@ code {
font-family: var(--font-mono);
font-size: 0.8125rem;
}
}
/* ---------- Header ---------- */
@@ -188,7 +133,7 @@ code {
.header-inner {
display: flex;
align-items: center;
gap: 2rem;
gap: 1rem;
min-height: 4rem;
}
@@ -212,16 +157,34 @@ code {
}
.brand-by {
white-space: nowrap;
padding-left: 0.6rem;
border-left: 1px solid var(--line-strong);
font-size: 0.8125rem;
color: var(--ink-muted);
}
.version-pill {
padding: 0.15rem 0.55rem;
border: 1px solid var(--line-strong);
border-radius: 999px;
font-family: var(--font-mono);
font-size: 0.75rem;
color: var(--ink-soft);
font-variant-numeric: tabular-nums;
transition: border-color 150ms, color 150ms;
}
.version-pill:hover {
border-color: var(--accent);
color: var(--accent);
}
.header-nav {
display: flex;
gap: 1.5rem;
margin-left: auto;
margin-right: 0.75rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--ink-soft);
@@ -391,8 +354,7 @@ code {
gap: 1.25rem;
}
.playground-intro h2,
.principles-head h2 {
.playground-intro h2 {
font-size: clamp(1.75rem, 3.2vw, 2.4rem);
font-weight: 800;
line-height: 1.08;
@@ -536,55 +498,357 @@ code {
padding: 1rem 1.5rem;
}
/* ---------- Principles ---------- */
/* ---------- Shared section heading ---------- */
.principles {
.section-head {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.section-head h2 {
max-width: 32rem;
font-size: clamp(1.75rem, 3.2vw, 2.4rem);
font-weight: 800;
line-height: 1.08;
letter-spacing: -0.035em;
}
.section-head-row {
flex-direction: row;
flex-wrap: wrap;
align-items: flex-end;
justify-content: space-between;
gap: 1.5rem;
}
.section-head-row > div {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
/* ---------- Why Tansy ---------- */
.why,
.roadmap {
display: flex;
flex-direction: column;
gap: 2.5rem;
padding-block: 5rem;
}
.principles-head {
display: flex;
flex-direction: column;
gap: 0.75rem;
/* The hero above already ends with generous padding. */
.why {
padding-top: 1rem;
}
.principle-grid {
.why-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 2.5rem;
gap: 1.25rem;
}
.principle {
.why-card {
display: flex;
flex-direction: column;
gap: 0.6rem;
padding-top: 1.25rem;
border-top: 2px solid var(--ink);
padding: 1.25rem;
border: 1px solid var(--line);
border-radius: 1rem;
background: var(--surface);
}
.principle h3 {
.why-card h3 {
margin-top: 0.6rem;
font-size: 1.125rem;
font-weight: 700;
letter-spacing: -0.015em;
}
.principle p {
margin: 0;
.why-card > p {
flex: 1;
margin: 0;
font-size: 0.9375rem;
color: var(--ink-soft);
}
.principle code {
.why-card > a {
width: fit-content;
padding: 0.2rem 0.5rem;
font-size: 0.875rem;
font-weight: 600;
color: var(--accent);
}
.why-card > a:hover {
text-decoration: underline;
text-underline-offset: 3px;
}
.why-visual {
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
min-height: 10.5rem;
padding: 1.1rem;
border-radius: 0.75rem;
background: var(--surface-sunk);
}
.why-visual-code {
padding: 0;
background: none;
}
.why-swatches {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.why-swatches button {
width: 1.75rem;
height: 1.75rem;
border: 2px solid var(--surface);
border-radius: 999px;
box-shadow: 0 0 0 1px var(--line-strong);
cursor: pointer;
transition: transform 150ms;
}
.why-swatches button:hover {
transform: scale(1.1);
}
.why-swatches button[aria-pressed="true"] {
box-shadow: 0 0 0 2px var(--ink);
}
.why-buttons {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.why-states {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
}
.why-stat {
margin: 0;
font-size: 0.875rem;
color: var(--ink-soft);
font-variant-numeric: tabular-nums;
}
.why-stat strong {
color: var(--ink);
}
/* Code sample: a dark panel so it reads as code in any palette. */
.code-sample {
display: flex;
flex-direction: column;
min-height: 10.5rem;
overflow: hidden;
border-radius: 0.75rem;
background: #151923;
color: #d7dce5;
}
.code-sample-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.35rem 0.4rem 0.35rem 0.9rem;
border-bottom: 1px solid rgb(255 255 255 / 0.08);
font-family: var(--font-mono);
font-size: 0.6875rem;
color: #8a93a6;
}
.code-copy {
min-height: 1.75rem;
color: #c3cad6;
}
.code-copy:hover {
background: rgb(255 255 255 / 0.08);
color: #ffffff;
}
.code-sample pre {
margin: 0;
padding: 0.85rem 0.9rem 1rem;
overflow-x: auto;
font-family: var(--font-mono);
font-size: 0.75rem;
line-height: 1.65;
}
.tok-key {
color: #c792ea;
}
.tok-str {
color: #a5d6a7;
}
.tok-tag {
color: #82aaff;
}
.tok-pkg {
color: #a5d6a7;
font-weight: 600;
}
/* ---------- Install ---------- */
.install {
display: flex;
flex-direction: column;
gap: 2.5rem;
padding-block: 1rem 5rem;
}
.section-lede {
max-width: 40rem;
color: var(--ink-soft);
font-size: 1.0625rem;
line-height: 1.6;
}
.inline-code {
padding: 0.1em 0.4em;
border-radius: 0.3rem;
background: var(--accent-soft);
background: var(--surface-sunk);
font-family: var(--font-mono);
font-size: 0.9em;
color: var(--ink);
overflow-wrap: anywhere;
}
.install-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 2.5rem;
align-items: start;
}
.install-main {
display: flex;
flex-direction: column;
gap: 0.85rem;
min-width: 0;
}
.command-panel {
min-height: 0;
}
.install-main > .command-panel pre {
font-size: 0.8125rem;
}
.install-meta {
font-family: var(--font-mono);
font-size: 0.75rem;
color: var(--ink-muted);
}
.install-meta a {
color: var(--accent);
text-decoration: underline;
text-underline-offset: 0.2em;
}
.install-meta a:hover {
color: var(--accent-strong);
}
.install-alt {
display: grid;
gap: 0.6rem;
margin: 0.25rem 0 0;
padding: 0;
list-style: none;
}
.install-setup {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.85rem;
min-width: 0;
}
.install-setup h3 {
font-size: 1.25rem;
font-weight: 700;
letter-spacing: -0.02em;
}
.install-setup-note {
color: var(--ink-soft);
font-size: 0.9375rem;
line-height: 1.6;
}
.install-panels {
display: grid;
gap: 0.6rem;
width: 100%;
min-width: 0;
}
.install-panels pre {
font-size: 0.75rem;
}
/* ---------- Roadmap ---------- */
.roadmap {
border-top: 1px solid var(--line);
}
.roadmap-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 1.25rem;
margin: 0;
padding: 0;
list-style: none;
}
.roadmap-step {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
padding-top: 1.25rem;
border-top: 2px solid var(--ink);
}
.roadmap-step h3 {
font-size: 1.25rem;
font-weight: 800;
letter-spacing: -0.02em;
}
.roadmap-step ul {
display: flex;
flex-direction: column;
gap: 0.4rem;
margin: 0;
padding-left: 1.1rem;
list-style: disc;
color: var(--ink-soft);
}
/* ---------- Footer ---------- */
.site-footer {
@@ -592,39 +856,83 @@ code {
background: var(--surface);
}
.footer-inner {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding-block: 1.75rem;
.footer-grid {
display: grid;
grid-template-columns: minmax(0, 1.6fr) repeat(3, minmax(0, 1fr));
gap: 2rem;
padding-block: 3rem;
font-size: 0.875rem;
color: var(--ink-soft);
}
.footer-brand {
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.footer-brand p {
max-width: 18rem;
margin: 0;
}
.footer-logo {
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
.footer-brand strong {
font-family: var(--font-display);
font-size: 1.125rem;
font-weight: 800;
letter-spacing: -0.03em;
color: var(--ink);
}
.footer-nav {
display: flex;
gap: 1.25rem;
.footer-version {
font-family: var(--font-mono);
font-size: 0.75rem;
color: var(--ink-muted);
}
.footer-nav a:hover {
.footer-version a {
color: var(--accent);
}
.footer-col {
display: flex;
flex-direction: column;
gap: 0.55rem;
}
.footer-col h2 {
margin-bottom: 0.25rem;
font-family: var(--font-mono);
font-size: 0.75rem;
font-weight: 500;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ink-muted);
}
.footer-col a:hover {
color: var(--ink);
}
/* ---------- Responsive ---------- */
/* Tablets: the nav needs the room the tagline was using. */
@media (max-width: 900px) {
.brand-by {
display: none;
}
}
/* Three narrow "Why" cards: keep the longest code line inside its card. */
@media (min-width: 961px) and (max-width: 1199px) {
.code-sample pre {
font-size: 0.6875rem;
}
}
@media (max-width: 960px) {
.hero,
.playground-grid {
@@ -636,9 +944,18 @@ code {
padding-block: 3rem 4rem;
}
.principle-grid {
.why-grid,
.roadmap-grid,
.install-grid {
grid-template-columns: minmax(0, 1fr);
gap: 2rem;
}
.footer-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.footer-brand {
grid-column: 1 / -1;
}
}
@@ -652,13 +969,8 @@ code {
}
.header-nav,
.brand-ui {
margin-left: 0.22em;
font-weight: 700;
color: var(--ink-muted);
}
.brand-by {
.brand-by,
.version-pill {
display: none;
}
@@ -671,10 +983,15 @@ code {
}
.playground,
.principles {
.why,
.roadmap {
padding-block: 3.5rem;
}
.footer-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.employee-card-body,
.employee-card-header,
.employee-card-footer {
File renamed without changes.
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"moduleResolution": "bundler",
"customConditions": ["source"],
"types": ["vite/client"],
"jsx": "react-jsx",
"skipLibCheck": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"allowImportingTsExtensions": true,
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}
+15
View File
@@ -0,0 +1,15 @@
import { readFileSync } from 'node:fs'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { defaultClientConditions, defineConfig } from 'vite'
const ui = JSON.parse(readFileSync(new URL('../../packages/ui/package.json', import.meta.url), 'utf8')) as { version: string }
export default defineConfig({
plugins: [react(), tailwindcss()],
// Resolve @openkhalix/tansy-ui to its source (the "source" export condition),
// so edits to components hot-reload without rebuilding the package.
resolve: { conditions: ['source', ...defaultClientConditions] },
define: { __TANSY_VERSION__: JSON.stringify(ui.version) },
publicDir: '../../packages/brand/public',
})
+146
View File
@@ -0,0 +1,146 @@
# Component conventions
Every Tansy UI component follows these rules, so the kit reads as one API. The
reference implementations are `packages/ui/src/components/Button.tsx`,
`Input.tsx` and `Field.tsx`, with their stories and tests. When in doubt, copy them.
## Foundation
- **Headless base:** interactive parts are built on [Base UI](https://base-ui.com)
(`@base-ui/react`). Its docs ship in the package at
`node_modules/@base-ui/react/docs/react/components/*.md`, with Tailwind examples
and full API tables. Use Base UI for anything with focus management, keyboard
navigation, popups or ARIA state: Dialog, Popover, Menu, Select, Combobox,
Tooltip, Tabs, Accordion, Checkbox, Radio, Switch, Slider, Toast, Field and more.
Never hand-roll focus traps, dismissal or roving focus.
- **Styling:** Tailwind v4 utilities only. Shared class strings live in
`src/lib/styles.ts` (`focusRing`, `controlHeight`, `controlBox`, `popupSurface`,
`popupMotion`, `listItem`, `labelText`, `descriptionText`, `errorText`).
Use them instead of repeating utilities. (Paths in this document are relative
to `packages/ui`.)
- **Class merging:** always `cn(...)` from `src/lib/cn.ts`, with the consumer's
`className` last so it wins.
- **Refs:** React 19 passes `ref` as a normal prop. Type props from
`ComponentProps<'element'>` and spread `...props` onto the root element (or
the main control for form fields). No `forwardRef`, and never copy refs in an effect.
- **Ids:** from `useId()` or Base UI. Never derive an `id` from `name`.
- **Files:** `Name.tsx` exports only components (Vite fast refresh). Style maps,
types and constants go in `name.tokens.ts`. Stories in `Name.stories.tsx`,
tests in `Name.test.tsx`.
## Tokens and theming
Use only these colour utilities, never Tailwind's built-in hues (`slate`, `gray`,
`red`, `blue`…) or hex codes:
| Purpose | Utilities |
|---|---|
| Neutral surfaces | `bg-background`, `bg-surface`, `bg-surface-muted`, `bg-surface-sunken` |
| Borders | `border-border`, `border-border-strong` |
| Text | `text-fg`, `text-fg-muted`, `text-fg-subtle` |
| Brand | `primary-50` … `primary-900` (re-themed by the palette) |
| Status | `success-*`, `warning-*`, `danger-*`, `info-*` (50 … 900, fixed across palettes) |
| Overlay | `bg-overlay`; popup shadow `shadow-popup` |
**Dark mode** is the `dark` class on `<html>`. Surface, border and text tokens
switch automatically. Brand and status colours need `dark:` variants where
contrast demands it. Patterns that work:
- soft fill: `bg-{c}-50 text-{c}-700 dark:bg-{c}-500/15 dark:text-{c}-300`
- outline: `border-{c}-300 text-{c}-700 dark:border-{c}-500/50 dark:text-{c}-300`
- text on light surfaces: `-700`, and `-800` for warning. White text on fills:
primary `500`, danger `600`, success and info `700`. Warning fills take
`text-warning-900`.
Every story must pass axe **colour contrast** in both light and dark mode.
## Props
| Concept | Prop | Values |
|---|---|---|
| Semantic colour | `color` | `'primary' \| 'neutral' \| 'success' \| 'warning' \| 'danger' \| 'info'` (type `Color` in `lib/styles.ts`) |
| Visual style | `variant` | Per component, e.g. Button `solid \| soft \| outline \| ghost \| link`; Alert and Badge `soft \| solid \| outline` |
| Size | `size` | `'sm' \| 'md' \| 'lg'`, default `md`. Control heights come from `controlHeight`: 32, 40 and 48 px |
| Icons | `startIcon`, `endIcon`, `icon` | `ReactNode`. Callers pass `<Mail />`. Never icon names as strings, never icon fonts |
| Field text | `label`, `description`, `error` | `ReactNode`. `error` marks the control invalid and replaces `description` |
| Required | `required` | Shows the mark and sets `required` on the control |
| Value | `value`, `defaultValue`, `onValueChange(value)` | Every component works both controlled and uncontrolled |
| Boolean state | `checked`, `defaultChecked`, `onCheckedChange(checked)` | Checkbox, Switch |
| Open state | `open`, `defaultOpen`, `onOpenChange(open)` | Dialog, Popover, Menu, Tooltip, Drawer, Alert (dismissible) |
| Disabled | `disabled` | Native `disabled` or Base UI's, with `data-disabled` styling |
Text inputs also keep the native `onChange`. Document every prop with a JSDoc
comment; Storybook's docs table reads them.
## Accessibility
- A visible focus ring on every interactive element (`focusRing`, or
`focusWithinRing` on wrappers around an input).
- Form controls sit in `Field` (or Base UI `Field.Root`), so the label,
description and error are linked (`aria-labelledby`, `aria-describedby`,
`aria-invalid`).
- Icon-only controls require `aria-label`. Decorative icons get `aria-hidden`.
- Popups: Escape closes, focus returns to the trigger, and the keyboard works
as the WAI-ARIA pattern describes. Base UI does this when used as documented.
- Respect `motion-reduce:` for animations.
## Responsive
Every component must work from a 320px phone up without making the page
scroll sideways:
- Inputs inside flex rows use `w-0 min-w-0 flex-1` so they can shrink.
- Rows of items (tabs, segmented controls) scroll within themselves on narrow
screens rather than widening the page.
- Positioned popups cap at `max-w-(--available-width)`; never give them a
`min-width` larger than that.
- Story layouts wrap (`flex-wrap`) instead of assuming a wide canvas.
Check with `node scripts/check-stories.mjs --width 320` (and 375 and 768).
## Stories
- `title`: `Group/Name`. Groups: `Actions`, `Forms`, `Overlays`, `Navigation`,
`Feedback`, `Display`, `Layout`.
- `tags: ['autodocs']`, a component description in
`parameters.docs.description.component`, and `argTypes` for **every public
prop** with a matching control (`inline-radio` for short enums, `select`
for long ones, `text`, `boolean`, `number`; `control: false` for nodes and
functions).
- Callbacks use `fn()` from `storybook/test`, so they appear in the Actions panel.
- Stories: `Playground` (args-driven), plus one per variant, colour, size and
state (disabled, error, required, loading, read-only, empty), `Controlled`
and `Uncontrolled` where values exist, and realistic compositions. Popups
should have a story that renders them **open** (`defaultOpen`), so they can
be reviewed without clicking.
- Realistic, generic sample content (Jane Doe, Acme Corporation,
name@example.com). No real people or companies.
## Tests
Every component has `Name.test.tsx` (Vitest, Testing Library, user-event):
- renders with the right role and accessible name,
- label, description and error wiring for form controls,
- controlled and uncontrolled behaviour,
- keyboard interaction for the component's pattern (Escape, arrows, Enter/Space),
- `await expectNoA11yViolations(container)` from `src/test/a11y.ts`.
Run `npx vitest run src/components/Name.test.tsx` inside `packages/ui`, or
`npm test` from the root. Export every public component from `src/index.ts`.
## Checking in a real browser
```bash
npm run build:docs
node scripts/check-stories.mjs --filter forms-input --mode light
node scripts/check-stories.mjs --filter forms-input --mode dark
python3 scripts/contact-sheet.py /tmp/tansy-story-check/light --prefix forms-input
```
Before a release, also run it with `--palette <name>` for each of the seven
palettes: a colour that passes in Classic Blue can fail in Amber.
`check-stories.mjs` reports runtime errors, failed requests and axe violations,
including contrast, and saves a screenshot of every story. Look at the contact
sheet, not just the report.
+105
View File
@@ -0,0 +1,105 @@
# Roadmap
Where Tansy UI stands against MUI and shadcn/ui, what's done, and what comes
before v1.
Last reviewed: 2026-09-29, at v0.4.0.
## Where things stand
| | Tansy UI (v0.3) | shadcn/ui | MUI (Material UI + Base UI) |
|---|---|---|---|
| Distribution | npm package `@openkhalix/tansy-ui` (ES modules, types, Tailwind or prebuilt CSS) | CLI and registries. CLI v4 installs a whole design system in one payload | npm packages |
| Components | 38 | 50+, plus blocks and charts | Material UI's full set; Base UI v1 has 35 unstyled parts; MUI X adds Data Grid, Charts, Date Pickers, Tree View |
| Accessibility base | Base UI primitives | Radix and Base UI primitives | Base UI primitives |
| Theming | Seven runtime palettes, scoped to any element; semantic tokens | CSS variables | `createTheme`, CSS variables |
| Dark mode | Yes, token-based | Yes | Yes |
| Tests | Unit and axe tests per component; every story checked in a real browser in both modes | Per primitive | Unit, visual and a11y suites |
| Docs | Storybook: a story per state, full controls, Introduction guides | Docs site, examples, blocks | Docs site, demos, templates |
Sources: [shadcn/ui changelog](https://ui.shadcn.com/docs/changelog),
[shadcn CLI v4](https://ui.shadcn.com/docs/changelog/2026-03-cli-v4),
[MUI: 2026 and beyond](https://mui.com/blog/2026-and-beyond/),
[Base UI v1](https://infoq.com/news/2026/02/baseui-v1-accessible/).
## Phase 0: Foundations (done in v0.3.0)
- [x] Visible keyboard focus on every interactive element
- [x] Labels, help text and errors linked to every field (`Field`)
- [x] Overlays, selects and menus on Base UI: focus traps, focus return,
Escape, roving focus, type-ahead, a real ARIA combobox
- [x] Alert roles by severity; tooltips on keyboard focus
- [x] One API: `color`, `variant`, `size`, `startIcon`/`endIcon` as nodes,
`value`/`defaultValue`/`onValueChange`, `label`/`description`/`error`
- [x] Controlled and uncontrolled use everywhere; ids from `useId`
- [x] Token-only colours, fixed Classic Blue ramp, semantic status ramps
- [x] Dark mode
- [x] Tests for every component, and a browser check of every story in both modes
- [x] Icons imported individually (no full `lucide-react` bundle)
- [x] Library build with per-component modules, types and `tokens.css`
## Phase 1: Components
Shipped in v0.3.0: Field, Input, FeaturedInput, TextArea, FeaturedTextArea,
NumberInput, Select, FeaturedSelect, Combobox, NativeSelect, Checkbox,
CheckboxGroup, Radio, Switch, Slider, ToggleGroup, Button, IconButton,
LinkButton, Dialog, AlertDialog, Drawer, Popover, Tooltip, InfoTip,
DropdownMenu, Tabs, Accordion, Breadcrumb, Pagination, Alert, Toast, Spinner,
Progress, Meter, Skeleton, Badge, CountBadge, Avatar, AvatarGroup, Card, Kbd,
Separator and Table.
Still to come:
1. Date Picker and Date Range Picker
2. Data Table (sorting, filtering, selection and pagination on top of Table)
3. Command palette
4. File upload with drag and drop
5. OTP / verification code input (Base UI OTPField)
6. Context menu, Menubar and Navigation menu (Base UI primitives exist)
7. Stepper and Timeline
Each ships with stories for every state, keyboard and a11y tests, tokens only,
and a docs page.
## Phase 2: Distribution
Done in v0.4.0:
- [x] Monorepo: `packages/ui` (published), `apps/site`, `apps/docs`
- [x] Package `@openkhalix/tansy-ui`: ES modules per component, types,
`"use client"` for Next.js, `tokens.css` for Tailwind apps and a
prebuilt `styles.css` for apps without Tailwind
- [x] MIT licence
- [x] Install tests: the packed tarball must build and render in Vite +
Tailwind, plain React and Next.js apps (`npm run test:package`)
- [x] CI and tag-triggered publishing (Gitea Actions)
Done in v0.4.1:
- [x] The `openkhalix` npm organisation, and the first published releases
(0.4.0 and 0.4.1 on the `latest` tag)
- [x] Public repository at `git.openkhalix.com/thekhalidsha/tansy-ui`, with
`repository` and `bugs` in `package.json` so the npm page links to the
source and its issue tracker
Still to do:
- [ ] Serve the same components as a shadcn-compatible registry, so
`npx shadcn add <url>` copies a Tansy component into a project.
- [ ] Ship the palettes as a registry base item (tokens, fonts and CSS
variables in one install).
- [ ] An npm automation token, so releasing is a tag push with no browser
step. Today `npm publish` needs web 2FA, which blocks unattended
releases.
## Phase 3: Where Tansy can lead
- **Scoped runtime palettes.** `applyPalette()` already themes any subtree at
runtime. Next: a palette builder that makes a full, contrast-checked 50–900
ramp from one brand colour and exports `tokens.css`.
- **Form-heavy business apps.** Floating labels, inline help, required marks,
validation states, currency and number inputs are built in, where shadcn
leaves them to the app. Extend with masked inputs and date ranges.
- **Owned or installed.** One source, as an npm package or registry code.
- **Every state verified.** Every story is rendered and checked in light and
dark mode on each release. Publish that report with the docs.
+2656 -36
View File
File diff suppressed because it is too large. Load diff
+22 -28
View File
@@ -1,37 +1,31 @@
{
"name": "tansy-ui",
"name": "tansy-ui-monorepo",
"private": true,
"version": "0.2.0",
"version": "0.0.0",
"type": "module",
"description": "Tansy UI: the @openkhalix/tansy-ui package, its Storybook and its landing page.",
"license": "MIT",
"workspaces": [
"packages/*",
"apps/*"
],
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint src .storybook",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"dependencies": {
"clsx": "^2.1.1",
"lucide-react": "^0.460.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.1"
"dev": "npm run dev -w @tansy/site",
"storybook": "npm run dev -w @tansy/docs",
"build": "npm run build -w @openkhalix/tansy-ui && npm run build -w @tansy/site && npm run build -w @tansy/docs",
"build:lib": "npm run build -w @openkhalix/tansy-ui",
"build:site": "npm run build -w @tansy/site",
"build:docs": "npm run build -w @tansy/docs",
"test": "npm test -w @openkhalix/tansy-ui",
"typecheck": "npm run typecheck -w @openkhalix/tansy-ui && tsc -p apps/site/tsconfig.json --noEmit",
"lint": "oxlint packages apps",
"check:stories": "node scripts/check-stories.mjs",
"test:package": "node scripts/test-package.mjs"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.6.0",
"@storybook/addon-docs": "^10.6.0",
"@storybook/react-vite": "^10.6.0",
"@tailwindcss/vite": "^4.3.3",
"@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",
"oxlint": "^1.81.0",
"storybook": "^10.6.0",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.3.0"
"playwright": "^1.63.0",
"typescript": "~6.0.2"
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@tansy/brand",
"private": true,
"version": "0.0.0",
"type": "module",
"description": "Tansy UI logo and catalogue data, shared by the landing page and Storybook. Not published.",
"exports": {
".": "./src/index.ts",
"./public/*": "./public/*"
},
"peerDependencies": {
"react": "^19.0.0"
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
+338
View File
@@ -0,0 +1,338 @@
/**
* The component catalogue shown on the landing page.
*
* `documentation` and `storyCounts` are regenerated from the built Storybook
* index by `scripts/gen_catalogue.py --patch`; edit the generator's tables,
* not these blocks. `featuredNames` is hand-picked and left alone.
*/
export type CatalogueEntry = {
number: string
group: string
name: string
detail: string
href: string
}
export const documentation: CatalogueEntry[] = [
{
number: '01',
group: 'Actions',
name: 'Button',
detail: 'Variants · colours · loading · icons',
href: '/docs/?path=/docs/actions-button--documentation',
},
{
number: '02',
group: 'Actions',
name: 'ToggleGroup',
detail: 'Segmented · multiple · icon-only',
href: '/docs/?path=/docs/actions-togglegroup--documentation',
},
{
number: '03',
group: 'Forms',
name: 'Checkbox',
detail: 'Indeterminate · colours · sizes',
href: '/docs/?path=/docs/forms-checkbox--documentation',
},
{
number: '04',
group: 'Forms',
name: 'CheckboxGroup',
detail: 'Select all · horizontal',
href: '/docs/?path=/docs/forms-checkboxgroup--documentation',
},
{
number: '05',
group: 'Forms',
name: 'Combobox',
detail: 'Search · chips · async',
href: '/docs/?path=/docs/forms-combobox--documentation',
},
{
number: '06',
group: 'Forms',
name: 'FeaturedInput',
detail: 'Floating label · password · clearable',
href: '/docs/?path=/docs/forms-featuredinput--documentation',
},
{
number: '07',
group: 'Forms',
name: 'FeaturedSelect',
detail: 'Floating label · searchable · actions',
href: '/docs/?path=/docs/forms-featuredselect--documentation',
},
{
number: '08',
group: 'Forms',
name: 'FeaturedTextArea',
detail: 'Floating label · auto-resize',
href: '/docs/?path=/docs/forms-featuredtextarea--documentation',
},
{
number: '09',
group: 'Forms',
name: 'Field',
detail: 'Label · description · error wiring',
href: '/docs/?path=/docs/forms-field--documentation',
},
{
number: '10',
group: 'Forms',
name: 'Input',
detail: 'Addons · icons · filled · underline',
href: '/docs/?path=/docs/forms-input--documentation',
},
{
number: '11',
group: 'Forms',
name: 'NativeSelect',
detail: 'Native menu · groups',
href: '/docs/?path=/docs/forms-nativeselect--documentation',
},
{
number: '12',
group: 'Forms',
name: 'NumberInput',
detail: 'Steppers · currency · min/max',
href: '/docs/?path=/docs/forms-numberinput--documentation',
},
{
number: '13',
group: 'Forms',
name: 'Radio',
detail: 'Cards · horizontal · descriptions',
href: '/docs/?path=/docs/forms-radio--documentation',
},
{
number: '14',
group: 'Forms',
name: 'Select',
detail: 'Single · multiple · grouped · clearable',
href: '/docs/?path=/docs/forms-select--documentation',
},
{
number: '15',
group: 'Forms',
name: 'Slider',
detail: 'Range · marks · formatted',
href: '/docs/?path=/docs/forms-slider--documentation',
},
{
number: '16',
group: 'Forms',
name: 'Switch',
detail: 'Icons · label position · colours',
href: '/docs/?path=/docs/forms-switch--documentation',
},
{
number: '17',
group: 'Forms',
name: 'TextArea',
detail: 'Auto-resize · character count',
href: '/docs/?path=/docs/forms-textarea--documentation',
},
{
number: '18',
group: 'Overlays',
name: 'AlertDialog',
detail: 'Destructive · async confirm',
href: '/docs/?path=/docs/overlays-alertdialog--documentation',
},
{
number: '19',
group: 'Overlays',
name: 'Dialog',
detail: 'Sizes · scrolling body · forms',
href: '/docs/?path=/docs/overlays-dialog--documentation',
},
{
number: '20',
group: 'Overlays',
name: 'Drawer',
detail: 'Four sides · sizes',
href: '/docs/?path=/docs/overlays-drawer--documentation',
},
{
number: '21',
group: 'Overlays',
name: 'DropdownMenu',
detail: 'Shortcuts · submenus · checkable',
href: '/docs/?path=/docs/overlays-dropdownmenu--documentation',
},
{
number: '22',
group: 'Overlays',
name: 'Popover',
detail: 'Sides · arrow · rich content',
href: '/docs/?path=/docs/overlays-popover--documentation',
},
{
number: '23',
group: 'Overlays',
name: 'Tooltip',
detail: 'Sides · colours · InfoTip',
href: '/docs/?path=/docs/overlays-tooltip--documentation',
},
{
number: '24',
group: 'Navigation',
name: 'Accordion',
detail: 'Multiple · variants · heading level',
href: '/docs/?path=/docs/navigation-accordion--documentation',
},
{
number: '25',
group: 'Navigation',
name: 'Breadcrumb',
detail: 'Collapse · icons',
href: '/docs/?path=/docs/navigation-breadcrumb--documentation',
},
{
number: '26',
group: 'Navigation',
name: 'Pagination',
detail: 'Siblings · boundaries · sizes',
href: '/docs/?path=/docs/navigation-pagination--documentation',
},
{
number: '27',
group: 'Navigation',
name: 'Tabs',
detail: 'Underline · pills · vertical',
href: '/docs/?path=/docs/navigation-tabs--documentation',
},
{
number: '28',
group: 'Feedback',
name: 'Alert',
detail: 'Soft · solid · outline · dismissible',
href: '/docs/?path=/docs/feedback-alert--documentation',
},
{
number: '29',
group: 'Feedback',
name: 'Progress',
detail: 'Indeterminate · meter · formatted',
href: '/docs/?path=/docs/feedback-progress--documentation',
},
{
number: '30',
group: 'Feedback',
name: 'Skeleton',
detail: 'Text · circle · card loading',
href: '/docs/?path=/docs/feedback-skeleton--documentation',
},
{
number: '31',
group: 'Feedback',
name: 'Spinner',
detail: 'Sizes · colours',
href: '/docs/?path=/docs/feedback-spinner--documentation',
},
{
number: '32',
group: 'Feedback',
name: 'Toast',
detail: 'Promise · actions · placement',
href: '/docs/?path=/docs/feedback-toast--documentation',
},
{
number: '33',
group: 'Display',
name: 'Avatar',
detail: 'Initials · status · groups',
href: '/docs/?path=/docs/display-avatar--documentation',
},
{
number: '34',
group: 'Display',
name: 'Badge',
detail: 'Colours · dot · removable · count',
href: '/docs/?path=/docs/display-badge--documentation',
},
{
number: '35',
group: 'Display',
name: 'Kbd',
detail: 'Key combinations',
href: '/docs/?path=/docs/display-kbd--documentation',
},
{
number: '36',
group: 'Display',
name: 'Table',
detail: 'Sortable · striped · sticky header',
href: '/docs/?path=/docs/display-table--documentation',
},
{
number: '37',
group: 'Layout',
name: 'Card',
detail: 'Outline · elevated · media · link',
href: '/docs/?path=/docs/layout-card--documentation',
},
{
number: '38',
group: 'Layout',
name: 'Separator',
detail: 'Labelled · dashed · vertical',
href: '/docs/?path=/docs/layout-separator--documentation',
},
]
export const storyCounts: Record<string, number> = {
Button: 11,
ToggleGroup: 15,
Checkbox: 14,
CheckboxGroup: 12,
Combobox: 22,
FeaturedInput: 17,
FeaturedSelect: 23,
FeaturedTextArea: 13,
Field: 6,
Input: 11,
NativeSelect: 14,
NumberInput: 13,
Radio: 18,
Select: 23,
Slider: 16,
Switch: 15,
TextArea: 14,
AlertDialog: 7,
Dialog: 12,
Drawer: 9,
DropdownMenu: 7,
Popover: 6,
Tooltip: 14,
Accordion: 7,
Breadcrumb: 5,
Pagination: 9,
Tabs: 10,
Alert: 9,
Progress: 9,
Skeleton: 5,
Spinner: 4,
Toast: 5,
Avatar: 8,
Badge: 13,
Kbd: 5,
Table: 9,
Card: 8,
Separator: 5,
}
export const totalStories = Object.values(storyCounts).reduce((sum, n) => sum + n, 0)
/** The five parts the hero shows. Each has a live preview in App.tsx. */
export const featuredNames = ['Button', 'Switch', 'Checkbox', 'Badge', 'Tooltip'] as const
export type FeaturedName = (typeof featuredNames)[number]
export const featured = featuredNames.map((name) => {
const entry = documentation.find((item) => item.name === name)
if (!entry) throw new Error(`Featured component "${name}" is missing from the catalogue`)
return { ...entry, name, stories: storyCounts[name] ?? 0 }
})
+10
View File
@@ -0,0 +1,10 @@
export { TansyMark, type TansyMarkProps } from './TansyMark'
export {
documentation,
featured,
featuredNames,
storyCounts,
totalStories,
type CatalogueEntry,
type FeaturedName,
} from './catalogue'
+169
View File
@@ -0,0 +1,169 @@
# 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.1] - 2026-09-29
### Added
- **Repository links:** `repository` and `bugs` are set, so the npm page links
to the source at `git.openkhalix.com/thekhalidsha/tansy-ui` and to its issue
tracker. The repository is public and MIT, so anyone can read, fork and open
an issue.
## [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.
+85
View File
@@ -0,0 +1,85 @@
{
"name": "@openkhalix/tansy-ui",
"version": "0.4.1",
"description": "A themeable, accessible React component kit built on Base UI and Tailwind CSS v4.",
"license": "MIT",
"author": "OpenKhalix",
"homepage": "https://ui.openkhalix.com",
"repository": {
"type": "git",
"url": "git+https://git.openkhalix.com/thekhalidsha/tansy-ui.git"
},
"bugs": {
"url": "https://git.openkhalix.com/thekhalidsha/tansy-ui/issues"
},
"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 />
}
Loaded 100 of 266 files, more files were not shown because too many files have changed in this diff. Show more