# Glyph

> Glyph is a React 19 component library on Tailwind CSS v4, built for AI coding agents: an MCP server, this file and a Markdown version of every docs page give agents the real API for one exact version. One typed theme file sets color, type, shape, depth, motion and per-component defaults. Beyond components it ships solved patterns: schema-validated forms, a data table with server mode and URL state, app layout, charts, authentication with protected routes, and file viewers.

Current version: 0.8.2. Packages: @glyphui/ui, @glyphui/blocks, @glyphui/auth, @glyphui/viewers, @glyphui/tokens, @glyphui/mcp (released together; keep them on the same version).

Install: `npm install @glyphui/ui`, then import `@glyphui/ui/fonts.css`, `tailwindcss` and `@glyphui/ui/styles.css` in your CSS and wrap the app in `<GlyphProvider>`.

Coding agents: the MCP server `@glyphui/mcp` serves these docs as tools (component props, examples, setup, theming, search). Claude Code: `claude mcp add glyph -- npx -y @glyphui/mcp`. Cursor, VS Code, Codex, Windsurf and Claude Desktop: https://glyphui.xyz/docs/ai.md. Any docs URL returns Markdown when requested with `Accept: text/markdown`.

When writing code with Glyph:

- Look up a component before using it (`get_component` in the MCP server, or its `.md` page below). Don't guess props.
- Import from the entry each component page lists, such as `@glyphui/ui/form` or `@glyphui/ui/data-table`, not always `@glyphui/ui`.
- Style through the theme file and token utilities (`bg-primary`, `text-muted-foreground`), not hard-coded colors.
- Prefer an existing pattern or block (Form, DataTable, AppShell, `@glyphui/blocks`) over rebuilding it from primitives.
- Keep labels, `aria-label` on icon-only buttons, and keyboard behavior.

## Guides

- [Getting started](https://glyphui.xyz/docs/getting-started.md): Install Glyph, add a theme file, and wrap your app.
- [Use with AI agents](https://glyphui.xyz/docs/ai.md): Give Claude Code, Cursor, Codex, VS Code and other coding agents Glyph's real API.
- [Theming](https://glyphui.xyz/docs/theming.md): One typed theme file: colors, type, shape, depth, motion and component recipes.
- [Motion](https://glyphui.xyz/docs/motion.md): Motion levels, springs, reduced motion and the animation primitives.
- [Routing](https://glyphui.xyz/docs/routing.md): Connect React Router, TanStack Router or Next.js for links and active items.
- [Forms](https://glyphui.xyz/docs/forms.md): Schema-validated forms with server errors, in pages and modals.
- [Data tables](https://glyphui.xyz/docs/data-tables.md): Sorting, filters, server mode, URL state, bulk actions and virtualization.
- [Authentication](https://glyphui.xyz/docs/auth.md): Sessions, protected routes and sign-in screens against your own API.
- [File viewers](https://glyphui.xyz/docs/viewers.md): PDF, CSV, spreadsheets, JSON, code, Markdown, diffs and media.
- [Accessibility](https://glyphui.xyz/docs/accessibility.md): What Glyph handles for you, and what each app still has to do.
- [Testing your app](https://glyphui.xyz/docs/testing.md): Unit and end-to-end tests for screens built with Glyph.
- [Upgrading](https://glyphui.xyz/docs/migration.md): Breaking changes and how to move between versions.

## Actions

- [Button](https://glyphui.xyz/components/button.md): Triggers an action. Six variants, three sizes, icons, a loading state, and asChild for links.
- [CopyButton](https://glyphui.xyz/components/copy-button.md): Copies a value to the clipboard and confirms it with a check and a screen-reader announcement.
- [Toggle](https://glyphui.xyz/components/toggle.md): A two-state button, and ToggleGroup for toolbars: single choice like alignment or multiple like bold and italic.

## Forms

- [Calendar](https://glyphui.xyz/components/calendar.md): A month grid for picking one date, several dates or a range. The building block behind DatePicker.
- [Checkbox](https://glyphui.xyz/components/checkbox.md): A checkbox with checked, unchecked and indeterminate states.
- [Combobox](https://glyphui.xyz/components/combobox.md): A select with search for long option lists. Single or multiple values; the value type comes from your options.
- [DatePicker](https://glyphui.xyz/components/date-picker.md): A date field that opens a calendar, plus DateRangePicker with presets like “Last 7 days”.
- [Field](https://glyphui.xyz/components/field.md): Wraps one control with its label, description and error, and wires the ARIA attributes between them.
- [FileUpload](https://glyphui.xyz/components/file-upload.md): Drag-and-drop or click to choose files, with type, size and count checks and a file list with progress.
- [Input](https://glyphui.xyz/components/input.md): A single-line text field with optional prefix and suffix content.
- [InputOTP](https://glyphui.xyz/components/input-otp.md): One-time code input with a box per character, paste support and SMS autofill on mobile.
- [Label](https://glyphui.xyz/components/label.md): An accessible label for a form control. Field renders one for you.
- [NumberInput](https://glyphui.xyz/components/number-input.md): A number field with − / + steppers, arrow-key stepping, min/max clamping and locale formatting.
- [PasswordInput](https://glyphui.xyz/components/password-input.md): A password field with a show/hide toggle and an optional strength meter.
- [RadioGroup](https://glyphui.xyz/components/radio-group.md): Pick exactly one option from a short visible list. The card variant makes each option a selectable card.
- [SegmentedControl](https://glyphui.xyz/components/segmented-control.md): Pick exactly one of a few options. The value type is inferred from the options.
- [Select](https://glyphui.xyz/components/select.md): A dropdown for choosing one option from a short list. The value type is generic.
- [Slider](https://glyphui.xyz/components/slider.md): Choose a number, or a range with two thumbs, by dragging or with the arrow keys.
- [Switch](https://glyphui.xyz/components/switch.md): An on/off toggle for settings that apply immediately.
- [TagInput](https://glyphui.xyz/components/tag-input.md): A free-form multi-value input: Enter or a comma turns text into removable tags. Good for labels, emails and keywords.
- [Textarea](https://glyphui.xyz/components/textarea.md): A multi-line text field that grows with its content.

## Overlays

- [Alert Dialog](https://glyphui.xyz/components/alert-dialog.md): Interrupts to ask for a decision, such as confirming a destructive action. useConfirm() turns it into one awaited line.
- [ContextMenu](https://glyphui.xyz/components/context-menu.md): A menu opened by right-click or long-press on an area, with the same items as DropdownMenu.
- [Dialog](https://glyphui.xyz/components/dialog.md): A modal window for focused tasks such as editing a record or filling a short form.
- [Dropdown Menu](https://glyphui.xyz/components/dropdown-menu.md): A menu of actions opened from a button: row actions, account menus and "more" buttons.
- [HoverCard](https://glyphui.xyz/components/hover-card.md): A rich preview shown while hovering or focusing a link, such as a user or repository card.
- [Modal](https://glyphui.xyz/components/modal.md): The everyday modal in one component: pass a title, description, body and footer. Built on Dialog.
- [Popover](https://glyphui.xyz/components/popover.md): Floating content anchored to a trigger, for quick settings, details or a small form.
- [Sheet](https://glyphui.xyz/components/sheet.md): A panel that slides in from any edge for filters, record details, settings or navigation.
- [Tooltip](https://glyphui.xyz/components/tooltip.md): A short hint shown on hover or keyboard focus.

## Navigation

- [Breadcrumb](https://glyphui.xyz/components/breadcrumb.md): Shows where the current page sits in the hierarchy, with links back up the trail.
- [CommandMenu](https://glyphui.xyz/components/command-menu.md): A ⌘K command palette: search, grouped actions and keyboard navigation in a modal dialog.
- [Link](https://glyphui.xyz/components/link.md): A text link with an animated underline. Internal links use your router; external ones open safely in a new tab.
- [NavigationMenu](https://glyphui.xyz/components/navigation-menu.md): Site navigation with dropdown panels for marketing headers, including mega-menu link cards.
- [Pagination](https://glyphui.xyz/components/pagination.md): Moves between pages of a long list. Controlled, with buttons or real links.
- [Stepper](https://glyphui.xyz/components/stepper.md): Progress through a multi-step flow such as onboarding or checkout, horizontal or vertical.
- [Tabs](https://glyphui.xyz/components/tabs.md): Switches between related panels of content. Underline and pill variants.

## Feedback

- [Alert](https://glyphui.xyz/components/alert.md): An inline message about the content around it, in five tones, with optional actions and dismissal.
- [Banner](https://glyphui.xyz/components/banner.md): A full-width announcement bar for the top of a page or section, optionally dismissible and remembered.
- [Progress](https://glyphui.xyz/components/progress.md): A bar or ring showing how far a task has got, or an indeterminate bar while the length is unknown.
- [Skeleton](https://glyphui.xyz/components/skeleton.md): A placeholder block shown while content loads. Size it with utility classes.
- [Spinner](https://glyphui.xyz/components/spinner.md): An indeterminate loading indicator that inherits the current text color.
- [Toast](https://glyphui.xyz/components/toast.md): Brief notifications sent from anywhere with toast(). Built on Sonner and styled entirely by the theme.

## Data display

- [Accordion](https://glyphui.xyz/components/accordion.md): Stacked sections that expand one at a time or independently. Good for FAQs and dense settings.
- [Avatar](https://glyphui.xyz/components/avatar.md): A person or team image with an initials fallback in a stable color per name.
- [Badge](https://glyphui.xyz/components/badge.md): A short status or label. Six tones, three variants, and an optional status dot.
- [Carousel](https://glyphui.xyz/components/carousel.md): Swipeable, keyboard-accessible slides for testimonials, media and onboarding.
- [Chart](https://glyphui.xyz/components/chart.md): Line, area, bar and composed charts with interactive legends, reference lines, zoom, and loading, error and empty states, all colored by the theme.
- [ChartCard](https://glyphui.xyz/components/chart-card.md): A card for one chart with a period selector, a “view as table” toggle and PNG or SVG download. exportChart downloads any chart.
- [Collapsible](https://glyphui.xyz/components/collapsible.md): Shows and hides one region, such as advanced options or the rest of a long list.
- [DescriptionList](https://glyphui.xyz/components/description-list.md): Label–value pairs such as account details, order metadata or settings summaries.
- [FunnelChart](https://glyphui.xyz/components/funnel-chart.md): How many make it through each step of a flow, with the conversion from the previous step or from the start.
- [Gauge](https://glyphui.xyz/components/gauge.md): A single value against a range, with optional colored bands such as healthy, slow and failing.
- [Heatmap](https://glyphui.xyz/components/heatmap.md): Activity per day over months, like a contribution calendar. Every day is a keyboard-reachable cell with a tooltip.
- [Kbd](https://glyphui.xyz/components/kbd.md): A keyboard key or shortcut hint.
- [PieChart](https://glyphui.xyz/components/pie-chart.md): Parts of a whole as a pie or donut, with slice labels, a highlighted slice on hover and a legend that hides slices.
- [RadarChart](https://glyphui.xyz/components/radar-chart.md): Compare a few items across several measures on a radar, or show progress toward goals as radial bars.
- [SankeyChart](https://glyphui.xyz/components/sankey-chart.md): Where a quantity flows between stages, e.g. traffic sources to pages to signups. Links are given by node name.
- [ScatterChart](https://glyphui.xyz/components/scatter-chart.md): How two measures relate, one dot per item. Add size for a bubble chart and groupBy for colored groups.
- [Sparkline](https://glyphui.xyz/components/sparkline.md): A tiny trend without axes, for stat cards and table cells: area, line or bars, with optional high and low marks.
- [StatCard](https://glyphui.xyz/components/stat-card.md): A key metric with its change versus the previous period, an optional icon and a small chart.
- [Table](https://glyphui.xyz/components/table.md): Semantic table primitives styled by the theme. For sorting, search and paging use DataTable.
- [Timeline](https://glyphui.xyz/components/timeline.md): A vertical list of events in order, for activity feeds, changelogs and order tracking.
- [Treemap](https://glyphui.xyz/components/treemap.md): Sizes of many parts of a whole as nested rectangles, grouped and colored by category.
- [TreeView](https://glyphui.xyz/components/tree-view.md): A nested, expandable list for file trees and hierarchies, with full keyboard navigation.

## Typography

- [Blockquote](https://glyphui.xyz/components/blockquote.md): A quotation set in the display font, with an accent rule and optional attribution.
- [Code](https://glyphui.xyz/components/code.md): Inline code for running text, and CodeBlock for snippets with a file name and a copy button.
- [Eyebrow](https://glyphui.xyz/components/eyebrow.md): A small uppercase label that sits above a heading.
- [Heading](https://glyphui.xyz/components/heading.md): A heading whose document level and visual size are set independently, using the theme type scale.
- [Prose](https://glyphui.xyz/components/prose.md): Styles raw HTML or MDX for long-form reading: headings, lists, links, quotes, code, tables and images.
- [Text](https://glyphui.xyz/components/text.md): Body copy in the theme type scale, with tones, weights, mono and truncation.

## Layout

- [AspectRatio](https://glyphui.xyz/components/aspect-ratio.md): Keeps images, video and embeds at a fixed width-to-height ratio so layouts do not shift while loading.
- [Card](https://glyphui.xyz/components/card.md): A surface that groups related content. Compose with CardHeader, CardTitle, CardBody and CardFooter.
- [Container](https://glyphui.xyz/components/container.md): Centers content at a readable maximum width with consistent side gutters.
- [Grid](https://glyphui.xyz/components/grid.md): Responsive equal-width columns, set per breakpoint, with gaps from the spacing scale.
- [Resizable](https://glyphui.xyz/components/resizable.md): Panels separated by draggable dividers, for editors, inboxes and split views.
- [ScrollArea](https://glyphui.xyz/components/scroll-area.md): A scrollable region with slim scrollbars colored by the theme, consistent across browsers.
- [Section](https://glyphui.xyz/components/section.md): A full-width page band with consistent vertical rhythm. Put a Container inside.
- [Separator](https://glyphui.xyz/components/separator.md): A thin divider between groups of content, horizontal or vertical.
- [Stack](https://glyphui.xyz/components/stack.md): Flex layout with gaps from the spacing scale. Column by default; direction="row" for horizontal.
- [VisuallyHidden](https://glyphui.xyz/components/visually-hidden.md): Hides content visually while keeping it available to screen readers, such as labels for icon-only controls.

## Patterns

- [AppShell](https://glyphui.xyz/components/app-shell.md): App layout with a sidebar and main area: desktop collapse to an icon rail, a mobile drawer, and a mobile top bar.
- [Async](https://glyphui.xyz/components/async.md): One convention for loading, error, empty and ready states. Works with TanStack Query results or useAsync.
- [DataTable](https://glyphui.xyz/components/data-table.md): The table every app needs: search, filter chips, multi-column sorting, pagination, selection with bulk actions, column controls, row links and details, inline editing and CSV export, in client or server mode.
- [Form](https://glyphui.xyz/components/form.md): Schema-validated forms: typed field names, wired labels and errors, server errors on the right field, submit progress.
- [Motion](https://glyphui.xyz/components/motion.md): Animation on by default and controlled from the theme: overlays spring out of their triggers, active indicators slide, lists animate, and sections reveal on scroll.
- [Navbar](https://glyphui.xyz/components/navbar.md): Site header built from data: brand, links and actions. Responsive, with a menu panel on small screens.
- [PageHeader](https://glyphui.xyz/components/page-header.md): The title block at the top of a page: optional eyebrow, title, description and actions.
- [Router integration](https://glyphui.xyz/components/router.md): Connect Glyph to your router once: links navigate client-side and navigation items mark the current page automatically.
- [Sidebar](https://glyphui.xyz/components/sidebar.md): Bordered navigation sidebar with sections, icons, counts and an accent bar on the active item.
- [Theming](https://glyphui.xyz/components/theme.md): One typed theme file controls color, type, shape, depth, motion and component defaults. Providers apply it and handle color mode.
- [Utilities](https://glyphui.xyz/components/utilities.md): The helpers Glyph components are built with, for building your own themed components.
- [Virtual rows](https://glyphui.xyz/components/data-table-virtual.md): Virtualization for DataTable: only the rows in view are rendered, so tables with tens of thousands of rows scroll smoothly.
- [Vite plugin](https://glyphui.xyz/components/vite-plugin.md): Injects the color-mode script into index.html, so dark-mode visitors never see a light flash before React loads.

## Auth

- [Auth provider](https://glyphui.xyz/components/auth.md): Session state for the whole app: who is signed in, their roles and permissions, and every sign-in action, from any backend.
- [AuthLayout](https://glyphui.xyz/components/auth-layout.md): A full-page frame for auth screens: the form on one half, a brand panel on the other; the panel hides on mobile.
- [Clerk bridge](https://glyphui.xyz/components/auth-clerk.md): Use Glyph’s guards, useAuth() and screens with Clerk: the bridge mirrors Clerk’s session into Glyph.
- [Code forms](https://glyphui.xyz/components/verify-email-form.md): Six-digit code steps: confirm an email after sign-up, or a second factor at sign-in. SignInForm and SignUpForm show them for you.
- [Firebase adapter](https://glyphui.xyz/components/auth-firebase.md): Glyph auth on Firebase Authentication: email and password, Google, GitHub, Apple and Microsoft, reset and verification emails.
- [MagicLinkCallback](https://glyphui.xyz/components/magic-link-callback.md): The page a sign-in link opens: trades the link’s token for a session, then continues where the user was going.
- [Memory adapter](https://glyphui.xyz/components/auth-memory.md): A complete auth backend in the browser for prototypes, demos and tests: sign-up, email codes, two-step, magic links, organizations.
- [Password reset](https://glyphui.xyz/components/password-reset.md): Request a reset email, then choose a new password from the link’s token or an emailed code.
- [Protected routes](https://glyphui.xyz/components/protected-routes.md): Guards and loaders for React Router: signed-out users go to sign-in and come back to where they were going.
- [REST adapter](https://glyphui.xyz/components/auth-rest.md): Connect Glyph auth to your own API: httpOnly cookie sessions or bearer tokens with refresh rotation.
- [Session dialogs](https://glyphui.xyz/components/session-dialogs.md): Sign back in when a session expires mid-task without losing the page, and warn before an idle sign-out.
- [SignInForm](https://glyphui.xyz/components/sign-in-form.md): The whole sign-in flow in one component: password, OAuth, email link, and the code steps the backend asks for.
- [SignUpForm](https://glyphui.xyz/components/sign-up-form.md): Account creation with name, email and a password strength meter, then the email-code step, ending signed in.
- [SocialButtons](https://glyphui.xyz/components/social-buttons.md): “Continue with …” buttons for the adapter’s OAuth providers, with brand marks drawn to each provider’s guidelines.
- [UserMenu](https://glyphui.xyz/components/user-menu.md): The signed-in user’s avatar menu, and an organization switcher for multi-workspace apps.

## Blocks

- [AuthCard](https://glyphui.xyz/components/auth-card.md): Sign-in or sign-up card with a ready email and password form, social buttons and a footer link.
- [Cta](https://glyphui.xyz/components/cta.md): The closing call to action near the end of a page, as a raised card or an open band.
- [Faq](https://glyphui.xyz/components/faq.md): Frequently asked questions as an accordion, stacked or with the header beside the questions.
- [FeatureGrid](https://glyphui.xyz/components/feature-grid.md): A grid of features or benefits, each with an icon, a title and a short description.
- [FeatureSplit](https://glyphui.xyz/components/feature-split.md): Feature rows that alternate text and media, for explaining a product in more depth than a grid allows.
- [Hero](https://glyphui.xyz/components/hero.md): The opening section of a page: headline, supporting text, actions, and optional media beside or below.
- [LogoCloud](https://glyphui.xyz/components/logo-cloud.md): A row of customer or partner logos, muted so they support the page rather than compete with it.
- [Newsletter](https://glyphui.xyz/components/newsletter.md): Email signup with validation and loading, success and error states built in.
- [Pricing](https://glyphui.xyz/components/pricing.md): Plan comparison with features, call-to-action buttons and an optional monthly / yearly switch.
- [SectionHeader](https://glyphui.xyz/components/section-header.md): Eyebrow, title and description at the top of a section. Most blocks use it; use it for your own sections too.
- [SiteFooter](https://glyphui.xyz/components/site-footer.md): Site-wide footer with brand, link columns, copyright and social links.
- [Stats](https://glyphui.xyz/components/stats.md): Headline numbers that back up a claim: customers, uptime, money saved.
- [Testimonials](https://glyphui.xyz/components/testimonials.md): Customer quotes with names and roles, as a grid or with one featured quote on top.

## Viewers

- [AudioPlayer](https://glyphui.xyz/components/audio-player.md): Audio with a waveform you can click to seek, plus play, time, volume and speed controls.
- [CodeViewer](https://glyphui.xyz/components/code-viewer.md): Source code with syntax colors from your theme, line numbers, highlighted lines, a wrap toggle and copy.
- [CsvViewer](https://glyphui.xyz/components/csv-viewer.md): Open a CSV as a table: typed columns, search, sort, filters from the data, column controls and export of the filtered rows.
- [DiffViewer](https://glyphui.xyz/components/diff-viewer.md): Compare two versions of a text, unified or side by side, with changed words highlighted and unchanged lines folded.
- [FilePreview](https://glyphui.xyz/components/file-preview.md): Show any file with the right viewer, picked from its name or type, with a download fallback. Pairs with FileUpload.
- [ImageViewer](https://glyphui.xyz/components/image-viewer.md): An image you can zoom, pan, rotate and download, with keyboard and touch support.
- [JsonViewer](https://glyphui.xyz/components/json-viewer.md): Explore JSON as a collapsible tree: search keys and values, expand to any depth, copy a value or its JSONPath, or read the raw text.
- [MarkdownViewer](https://glyphui.xyz/components/markdown-viewer.md): Render Markdown with your theme’s typography: GitHub tables, task lists, highlighted code blocks and heading links.
- [PdfViewer](https://glyphui.xyz/components/pdf-viewer.md): Read PDFs in the page: thumbnails, zoom, rotation, search with highlights, selectable text, download, print and fullscreen.
- [SpreadsheetViewer](https://glyphui.xyz/components/spreadsheet-viewer.md): Open an Excel workbook (.xlsx) as tabs of tables, with the cells’ numbers, dates and booleans kept as types.
- [VideoPlayer](https://glyphui.xyz/components/video-player.md): Video with themed controls: scrubbing with the buffered range, volume, speed, captions, picture in picture and fullscreen.

## Optional

- [Changelog](https://glyphui.xyz/changelog.md): every release, newest first
- [Everything in one file](https://glyphui.xyz/llms-full.txt)

---

# Getting started

> Install Glyph, add a theme file, and wrap your app.

Glyph needs React 19 and Tailwind CSS 4.1 or later. This guide uses Vite; the [Next.js section](#nextjs) covers the differences for server rendering.

## Install

```sh
npm install @glyphui/ui
```

Add the other packages only for what you use:

| Package | For | Also install |
|---|---|---|
| `@glyphui/blocks` | Page sections: Hero, Pricing, FAQ, AuthCard and more | |
| `@glyphui/ui/form` | Schema-validated forms | `react-hook-form @hookform/resolvers` and a validator such as `zod` |
| `@glyphui/ui/data-table` | Tables with server mode and URL state | `@tanstack/react-table@8` |
| `@glyphui/ui/chart` | Charts colored by your theme | `recharts` |
| `@glyphui/auth` | Sessions, protected routes, sign-in screens | `react-router` for the route guards |
| `@glyphui/viewers` | PDF, CSV, JSON, code, media and more | Depends on the viewer; see [File viewers](https://glyphui.xyz/docs/viewers) |

Every `@glyphui/*` package is released under one version number. Keep them on the same version: `blocks`, `auth` and `viewers` use your app's `@glyphui/ui` as a peer dependency rather than bringing their own copy.

## Import the styles

In your main CSS file, in this order:

```css title="src/index.css"
@import "@glyphui/ui/fonts.css";       /* Geist and Geist Mono, used by the default theme */
@import "tailwindcss";
@import "@glyphui/ui/styles.css";
@import "@glyphui/blocks/styles.css";  /* only with @glyphui/blocks */
@import "@glyphui/auth/styles.css";    /* only with @glyphui/auth screens */
@import "@glyphui/viewers/styles.css"; /* only with @glyphui/viewers */
```

Each Glyph stylesheet tells Tailwind which classes its components use. Leave one out and those components render partly unstyled; in development they warn in the console. Skip `fonts.css` when your theme uses other fonts, and load those instead.

## Prevent the dark-mode flash

The color mode has to be set before React loads, or dark-mode visitors see a light page for a moment. With Vite, add the plugin:

```ts title="vite.config.ts"
import { glyphColorMode } from '@glyphui/ui/vite'
import tailwindcss from '@tailwindcss/vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

export default defineConfig({
  plugins: [react(), tailwindcss(), glyphColorMode({ defaultMode: 'system' })],
})
```

Pass the same `defaultMode` and `storageKey` as `GlyphProvider`. With server rendering, render `<ColorModeScript />` in the document head instead.

## Create your theme

Start from a preset and override what differs. Everything is type-checked, including per-component defaults.

```ts title="src/glyph.theme.ts"
import { defineTheme, presets } from '@glyphui/ui'

export default defineTheme({
  name: 'acme',
  extends: presets.glyph, // glyph · brutalist · editorial · playful
  colors: { dark: { primary: 'oklch(70% 0.19 45)' } },
  radius: { md: '6px' },
  components: { Button: { defaultVariants: { size: 'lg' } } },
})
```

[Theming](https://glyphui.xyz/docs/theming) covers every option, and the [theme studio](https://glyphui.xyz/themes) builds a theme file on live components.

## Wrap your app

`GlyphProvider` goes outermost, once. Give it your theme and, with React Router, `reactRouter`:

```tsx title="src/main.tsx"
import { GlyphProvider } from '@glyphui/ui'
import { reactRouter } from '@glyphui/ui/react-router'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { createBrowserRouter, RouterProvider } from 'react-router'
import { App } from './app'
import theme from './glyph.theme'
import './index.css'

const router = createBrowserRouter([{ path: '/', element: <App /> }])

createRoot(document.getElementById('root') as HTMLElement).render(
  <StrictMode>
    <GlyphProvider theme={theme} defaultMode="system" router={reactRouter} toaster>
      <RouterProvider router={router} />
    </GlyphProvider>
  </StrictMode>,
)
```

- `router` makes every Glyph link navigate client-side and marks the current Sidebar, Navbar and NavigationMenu item. Other routers are in [Routing](https://glyphui.xyz/docs/routing).
- `toaster` mounts the toast container, so `toast()` works anywhere. `useConfirm()` needs no setup.

Now use a component:

```tsx title="src/app.tsx"
import { Button, toast } from '@glyphui/ui'

export function App() {
  return <Button onClick={() => toast.success('Glyph is working')}>Say hello</Button>
}
```

## Next.js

Glyph's components are client components, and every built file starts with `'use client'`, so they work inside the App Router's server components. Put the providers in a client component and the color-mode script in the document head:

```tsx title="app/providers.tsx"
'use client'
import { GlyphProvider } from '@glyphui/ui'
import theme from '../glyph.theme'
import { nextRouter } from './glyph-router'

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <GlyphProvider theme={theme} defaultMode="system" router={nextRouter} toaster>
      {children}
    </GlyphProvider>
  )
}
```

```tsx title="app/layout.tsx"
import { ColorModeScript } from '@glyphui/ui'
import { Providers } from './providers'
import './globals.css'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <ColorModeScript defaultMode="system" />
      </head>
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  )
}
```

`suppressHydrationWarning` is needed because the script sets `data-mode` on `<html>` before React hydrates. The `nextRouter` object is in [Routing](https://glyphui.xyz/docs/routing#nextjs).

## Next steps

- [Theming](https://glyphui.xyz/docs/theming): colors, type, shape and component recipes in one file.
- [Forms](https://glyphui.xyz/docs/forms) and [Data tables](https://glyphui.xyz/docs/data-tables): the two patterns most apps need first.
- [All components](https://glyphui.xyz/components), each with live examples and props.

Live page: https://glyphui.xyz/docs/getting-started

---

# Use with AI agents

> Give Claude Code, Cursor, Codex, VS Code and other coding agents Glyph's real API.

Glyph is built for coding agents. They write better code when they can look up the real API instead of recalling it from training data, which is often a version or two behind. Glyph gives them three ways in: an MCP server for agents that call tools, Markdown versions of every page for agents that read the web, and a short block for your project's agent instructions.

## Set up with one prompt

Pick your agent, copy the prompt and paste it into a chat in your project. It connects the MCP server, installs and wires up Glyph, and adds the project instructions. The sections below cover each step by hand.

Prompt for Claude Code:

```text
Set up Glyph (https://glyphui.xyz), a React + Tailwind CSS v4 UI library, in this project.

1. If there is no React app here yet, create one with Vite (React + TypeScript) first.
2. Add Glyph's MCP server for this project: run `claude mcp add --scope project glyph -- npx -y @glyphui/mcp`.
3. Install and wire up Glyph. If the glyph MCP tools are available, call `get_setup` for this project's framework and follow it. Otherwise (they load after a restart) follow https://glyphui.xyz/docs/getting-started.md. That means: install @glyphui/ui, add its CSS imports, create the theme file and wrap the app in GlyphProvider.
4. Add this section to CLAUDE.md at the project root, creating the file if needed:

   ## UI

   This app uses Glyph (@glyphui/ui and friends) for all UI. Before using a component, look it up with the glyph MCP server (get_component, search_docs) or at https://glyphui.xyz/llms.txt. Don't guess props.

   - Import from the entry each component lists, such as @glyphui/ui/form.
   - Style through the theme file and token utilities (bg-primary, text-muted-foreground), not hard-coded colors.
   - Prefer an existing block or pattern over building from primitives.
   - Keep labels, aria-label on icon-only buttons, and keyboard behavior.
5. Run the app (or its build) to check it works, then tell me what you changed.
```

Prompts for Cursor, VS Code, Codex, Windsurf and other agents: https://glyphui.xyz/docs/ai

## MCP server

`@glyphui/mcp` is a [Model Context Protocol](https://modelcontextprotocol.io) server. Your editor starts it on demand with `npx`; there is nothing to install in your project. Everything it serves is bundled in the package and generated from these docs for that release, so it works offline and answers for one exact Glyph version.

### Claude Code

```sh
claude mcp add glyph -- npx -y @glyphui/mcp
```

To share it with your team, add it to the project's `.mcp.json` instead: `claude mcp add --scope project glyph -- npx -y @glyphui/mcp`. Run `/mcp` in Claude Code to check that it's connected.

### Cursor

```json title=".cursor/mcp.json"
{
  "mcpServers": {
    "glyph": { "command": "npx", "args": ["-y", "@glyphui/mcp"] }
  }
}
```

### VS Code

For GitHub Copilot's agent mode:

```json title=".vscode/mcp.json"
{
  "servers": {
    "glyph": { "type": "stdio", "command": "npx", "args": ["-y", "@glyphui/mcp"] }
  }
}
```

### Codex

```toml title="~/.codex/config.toml"
[mcp_servers.glyph]
command = "npx"
args = ["-y", "@glyphui/mcp"]
```

### Windsurf

```json title="~/.codeium/windsurf/mcp_config.json"
{
  "mcpServers": {
    "glyph": { "command": "npx", "args": ["-y", "@glyphui/mcp"] }
  }
}
```

### Claude Desktop

Settings → Developer → Edit Config, then add the server to `claude_desktop_config.json` and restart the app:

```json title="claude_desktop_config.json"
{
  "mcpServers": {
    "glyph": { "command": "npx", "args": ["-y", "@glyphui/mcp"] }
  }
}
```

### Match your Glyph version

`npx -y @glyphui/mcp` runs the latest release. If your project is on an older version, pin the server to it, such as `npx -y @glyphui/mcp@0.9.0`. Or add it as a dev dependency, so it upgrades with the rest of Glyph, and run its `glyphui-mcp` command instead of `npx`.

## What the server provides

| Tool | Use it to |
|---|---|
| `get_setup` | Add Glyph to a Vite, Next.js or other app: install commands with the peers you need, CSS imports, color mode, a theme file and the provider tree. |
| `list_components` | Browse components by category, status or package. |
| `search_docs` | Search components, props, guide sections and release notes, such as "server side pagination". |
| `get_component` | Get one component's import, peer dependencies, props for each export, theme slots and variants, keyboard behavior and examples. |
| `get_example` | Read the full source of one example. |
| `list_guides`, `get_guide` | Read a guide, such as [Forms](https://glyphui.xyz/docs/forms) or [Data tables](https://glyphui.xyz/docs/data-tables), as Markdown. |
| `get_theming` | See the presets, every token a theme sets, and a complete theme file. |

It also serves the docs as resources (`glyph://llms-full`, `glyph://components/button`, `glyph://guides/forms`), which some clients let you attach to a chat, and a `build-with-glyph` prompt that asks the agent to check each API before using it.

You don't need to name the tools. Ask for what you want ("add a settings page with a profile form") and the agent calls them as it goes.

## llms.txt and Markdown pages

For agents that read the web instead of calling tools:

- [glyphui.xyz/llms.txt](https://glyphui.xyz/llms.txt) is an index of every guide and component, following the [llms.txt](https://llmstxt.org) convention.
- [glyphui.xyz/llms-full.txt](https://glyphui.xyz/llms-full.txt) is all of it in one file, for pasting into a chat or a project's knowledge.
- Every docs page has a Markdown version at the same URL plus `.md`, such as [glyphui.xyz/components/button.md](https://glyphui.xyz/components/button.md) or [glyphui.xyz/docs/forms.md](https://glyphui.xyz/docs/forms.md).
- Agents that send `Accept: text/markdown` get that Markdown from the page's own URL, so `glyphui.xyz/docs/forms` works as well as `glyphui.xyz/docs/forms.md`. The home page answers with llms.txt.

```sh
curl -H "Accept: text/markdown" https://glyphui.xyz/components/data-table
```

## Project instructions

Agents read a project file before they start: `AGENTS.md` (Codex, Cursor, VS Code and others), `CLAUDE.md` (Claude Code) or `.cursor/rules`. A few lines there keep them on Glyph's conventions:

```md title="AGENTS.md"
## UI

This app uses Glyph (@glyphui/ui and friends) for all UI. Before using a component,
look it up with the glyph MCP server (get_component, search_docs) or at
https://glyphui.xyz/llms.txt. Don't guess props.

- Import from the entry each component lists, such as @glyphui/ui/form.
- Style through src/glyph.theme.ts and the token utilities (bg-primary,
  text-muted-foreground), not hard-coded colors.
- Prefer an existing block or pattern over building from primitives.
- Keep labels, aria-label on icon-only buttons, and keyboard behavior.
```

Live page: https://glyphui.xyz/docs/ai

---

# Theming

> One typed theme file: colors, type, shape, depth, motion and component recipes.

A Glyph theme is one TypeScript file. It decides every color, the type scale, corner radius, shadows, border width, motion and control height, plus defaults and extra classes for individual components. Components never hardcode a color or size, so changing the theme changes the whole app.

## A theme file

Start from one of the four presets with `extends` and override only what differs:

```ts title="src/glyph.theme.ts"
import { defineTheme, presets } from '@glyphui/ui'

export default defineTheme({
  name: 'acme',
  extends: presets.glyph,
  colors: {
    light: { primary: 'oklch(55% 0.2 30)' },
    dark: { primary: 'oklch(70% 0.19 45)' },
  },
  radius: { md: '6px', lg: '10px' },
  font: { sans: '"Inter Variable", system-ui, sans-serif' },
  motion: { level: 'subtle' },
  control: { md: '38px' },
  components: {
    Button: { defaultVariants: { size: 'lg' }, className: { base: 'tracking-tight' } },
    Card: { className: { root: 'shadow-md' } },
  },
})
```

Pass it to `<GlyphProvider theme={theme}>`. Without `extends`, a theme must set every token; TypeScript lists what's missing.

| Key | What it sets |
|---|---|
| `colors.light`, `colors.dark` | Every color token, separately per mode |
| `radius` | `xs`, `sm`, `md`, `lg`, `xl`, `pill` |
| `shadow` | `xs` to `lg`, once or per mode |
| `font` | `sans`, `display`, `serif`, `mono`, plus OpenType `features` |
| `text` | Nine steps from `display` to `caption`, each with size, line height, tracking and weight |
| `border.width` | The width of every themed border |
| `motion` | Durations, easings, the motion level and the spring; see [Motion](https://glyphui.xyz/docs/motion) |
| `control` | Heights of buttons, inputs and selects (`sm`, `md`, `lg`): the theme's density |
| `components` | Per-component `defaultVariants` and `className` slots, typed per component |

## Color tokens

Colors are semantic: you set what `primary` or `muted-foreground` means, and components use the role, not a hue.

| Tokens | Used for |
|---|---|
| `background`, `foreground`, `subtle`, `surface`, `raised`, `muted` | Page, cards and raised layers |
| `muted-foreground`, `faint-foreground` | Secondary and tertiary text |
| `border`, `border-strong`, `input`, `ring` | Lines, field borders and focus rings |
| `primary`, `secondary`, `success`, `warning`, `danger`, `info` | Fills, each with a `-foreground` for text on it |
| `primary-text`, `success-text`, `warning-text`, `danger-text`, `info-text` | The same tones as readable text |
| `overlay` | Behind dialogs and sheets |
| `chart-1` to `chart-5` | Series in charts, in order |

Change a fill like `primary` without its `-foreground` and `defineTheme` picks white or dark text, whichever is readable on it. The `*-text` tokens are derived the same way: links, field errors and tinted badges stay at WCAG AA contrast even when you pick a light brand color. Set any of them explicitly to opt out.

## Check contrast

In development, `GlyphProvider` warns in the console when the active theme still fails WCAG contrast somewhere. `auditContrast` lists every failing pair, so you can test it:

```ts title="src/glyph.theme.test.ts"
import { auditContrast } from '@glyphui/ui'
import { expect, it } from 'vitest'
import theme from './glyph.theme'

it('meets WCAG AA in light and dark', () => {
  expect(auditContrast(theme)).toEqual([])
})
```

Each issue names the mode, the two tokens, the ratio found and the ratio required.

## Component recipes

`components` sets defaults and classes for one component everywhere. The keys are typed from each component's styles: a Button size or Card slot that doesn't exist is a compile error.

- `defaultVariants` changes props' defaults, such as every Button being `lg`.
- `className` adds classes to named parts (slots) of a component. Each component page lists its slots under Theming.

A `className` passed to one component instance always wins over the theme.

## Tokens in your own markup

The tokens are Tailwind utilities, so your own components follow the theme too:

```tsx title="src/plan-badge.tsx"
export function PlanBadge({ plan }: { plan: string }) {
  return (
    <span className="rounded-pill border border-border bg-muted px-2 py-0.5 text-caption text-muted-foreground">
      {plan}
    </span>
  )
}
```

Colors are `bg-*`, `text-*` and `border-*` with token names (`bg-primary`, `text-danger-text`). Type steps are `text-h2`, `text-small`; fonts are `font-display`, `font-mono`; shapes are `rounded-lg` and `shadow-md`. Raw values are CSS variables: `var(--glyph-primary)`.

## Dark mode

Every theme has both modes. `useColorMode()` reads and changes the visitor's choice:

```tsx title="src/mode-toggle.tsx"
import { SegmentedControl, useColorMode } from '@glyphui/ui'

export function ModeToggle() {
  const { mode, setMode } = useColorMode()
  return (
    <SegmentedControl
      aria-label="Color mode"
      value={mode}
      onValueChange={setMode}
      options={[
        { value: 'light', label: 'Light' },
        { value: 'dark', label: 'Dark' },
        { value: 'system', label: 'System' },
      ]}
    />
  )
}
```

The choice is stored in `localStorage` (`storageKey` on the provider, `null` to turn storage off) and kept in sync across tabs. `resolvedMode` is what's on screen: `system` resolved against the OS setting. To avoid a light flash on load, add the [Vite plugin or ColorModeScript](https://glyphui.xyz/docs/getting-started#prevent-the-dark-mode-flash).

## Several themes on one page

`ThemeScope` renders part of the page with another theme, for previews, embedded widgets or a white-labelled area:

```tsx
import { Badge, Button, presets, ThemeScope, useColorMode } from '@glyphui/ui'

export default function Example() {
  const { resolvedMode } = useColorMode()
  return (
    <div className="grid gap-3 sm:grid-cols-2">
      {Object.values(presets).map((theme) => (
        <ThemeScope
          key={theme.name}
          theme={theme}
          mode={resolvedMode}
          className="grid gap-3 rounded-lg border border-border p-4"
        >
          <div className="flex items-center justify-between">
            <span className="font-display text-h4 capitalize">{theme.name}</span>
            <Badge tone="primary">Preset</Badge>
          </div>
          <div className="flex gap-2">
            <Button size="sm">Primary</Button>
            <Button size="sm" variant="outline">
              Outline
            </Button>
          </div>
        </ThemeScope>
      ))}
    </div>
  )
}
```

Live example: https://glyphui.xyz/components/theme

Pass `mode` to force light or dark inside the scope. Dialogs, menus and popovers render at the end of the document, outside the scope, so they use the page's theme; wrap their content in its own `ThemeScope` to theme them too.

## Themes from data

Themes are plain objects, so they can come from a database for per-customer branding: pass the parsed object to `defineTheme` with `extends`. Values are escaped when written to CSS, so a value containing `;`, braces or `</style>` can't break out of its declaration. Still validate tenant input: an unreadable color passes escaping but fails contrast, which `auditContrast` catches.

## The four presets

| Preset | Character |
|---|---|
| `glyph` | Precise and dark-first, Geist, an electric-blue accent, layered soft shadows |
| `brutalist` | Zero radius, heavy borders, hard offset shadows, loud color, snappy motion |
| `editorial` | Serif display type, warm paper neutrals, hairlines instead of shadows |
| `playful` | Pill shapes, pastel color, chunky type, springy motion |

Try them on this site with the theme picker in the header, or design your own in the [theme studio](https://glyphui.xyz/themes).

Live page: https://glyphui.xyz/docs/theming

---

# Motion

> Motion levels, springs, reduced motion and the animation primitives.

Glyph animates by default, and the theme decides how much. Overlays spring out of the element that opened them, active indicators slide between tabs, list items enter and leave, and page sections reveal as they scroll into view. None of it needs code in your app.

## Motion levels

`theme.motion.level` is one of three values:

| Level | What it does |
|---|---|
| `none` | Renders everything instantly. Exit events still fire, so overlays close normally. |
| `subtle` | The default: short, purposeful movement. |
| `expressive` | Travels further and overshoots slightly on a soft spring. |

```tsx
import {
  AnimatedNumber,
  Card,
  Checkbox,
  defineTheme,
  type MotionLevel,
  SegmentedControl,
  Stagger,
  Switch,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  Text,
  ThemeScope,
  useGlyph,
} from '@glyphui/ui'
import { useMemo, useState } from 'react'

export default function Example() {
  const { theme } = useGlyph()
  const [level, setLevel] = useState<MotionLevel>('subtle')
  const [replay, setReplay] = useState(0)
  const [seats, setSeats] = useState(12)
  const scoped = useMemo(
    () => defineTheme({ name: `${theme.name}-motion-${level}`, extends: theme, motion: { level } }),
    [theme, level],
  )

  return (
    <div className="grid w-full gap-4">
      <SegmentedControl<MotionLevel>
        aria-label="Motion level"
        className="justify-self-start"
        value={level}
        onValueChange={(next) => {
          setLevel(next)
          setReplay((n) => n + 1)
        }}
        options={[
          { value: 'none', label: 'None' },
          { value: 'subtle', label: 'Subtle' },
          { value: 'expressive', label: 'Expressive' },
        ]}
      />
      <ThemeScope theme={scoped} className="grid gap-5 rounded-lg p-5">
        <div className="flex flex-wrap items-center gap-6">
          <Tabs defaultValue="overview">
            <TabsList>
              <TabsTrigger value="overview">Overview</TabsTrigger>
              <TabsTrigger value="activity">Activity</TabsTrigger>
              <TabsTrigger value="settings">Settings</TabsTrigger>
            </TabsList>
            <TabsContent value="overview" className="sr-only" tabIndex={-1}>
              Overview
            </TabsContent>
            <TabsContent value="activity" className="sr-only" tabIndex={-1}>
              Activity
            </TabsContent>
            <TabsContent value="settings" className="sr-only" tabIndex={-1}>
              Settings
            </TabsContent>
          </Tabs>
          <SegmentedControl
            aria-label="View"
            size="sm"
            defaultValue="list"
            options={[
              { value: 'list', label: 'List' },
              { value: 'board', label: 'Board' },
              { value: 'timeline', label: 'Timeline' },
            ]}
          />
          <Switch aria-label="Notifications" defaultChecked />
          <Checkbox aria-label="Done" />
        </div>
        <Stagger key={replay} className="grid gap-3 sm:grid-cols-3">
          {['Revenue', 'Seats', 'Uptime'].map((label, i) => (
            <Card key={label} padding="sm">
              <Text size="small" tone="muted">
                {label}
              </Text>
              <p className="font-display text-h3">
                {i === 1 ? (
                  <button
                    type="button"
                    className="cursor-pointer"
                    onClick={() => setSeats((n) => n + 7)}
                  >
                    <AnimatedNumber value={seats} />
                  </button>
                ) : i === 0 ? (
                  '$48k'
                ) : (
                  '99.98%'
                )}
              </p>
            </Card>
          ))}
        </Stagger>
      </ThemeScope>
    </div>
  )
}
```

Live example: https://glyphui.xyz/components/motion

The spring behind overlays, indicators and reveals is also part of the theme:

```ts title="src/glyph.theme.ts"
import { defineTheme, presets } from '@glyphui/ui'

export default defineTheme({
  name: 'acme',
  extends: presets.glyph,
  motion: {
    level: 'expressive',
    // Lower damping bounces more; higher stiffness is faster.
    spring: { stiffness: 380, damping: 22 },
    duration: { fast: '120ms', base: '180ms', slow: '280ms' },
  },
})
```

The presets differ here too: brutalist snaps with no bounce, playful is expressive.

## Reduced motion

Visitors who ask their operating system for reduced motion never get animation, whatever the theme says. Content never depends on an animation to become visible: server-rendered HTML, tests and reduced-motion visitors see everything at once.

To turn motion off for everyone, for example from a user setting or in tests, override the theme on the provider:

```tsx title="src/root.tsx"
import { GlyphProvider } from '@glyphui/ui'
import type { ReactNode } from 'react'

export function Root({ calm, children }: { calm: boolean; children: ReactNode }) {
  return <GlyphProvider motion={calm ? 'none' : undefined}>{children}</GlyphProvider>
}
```

## Reveal and Stagger

`Reveal` fades and lifts its child in when it scrolls into view. `Stagger` does the same for each direct child in turn: card grids, feature lists, pricing tiers.

```tsx
import { Button, Card, Reveal, Stagger, Text } from '@glyphui/ui'
import { RotateCcw } from 'lucide-react'
import { useState } from 'react'

const features = ['Automatic retries', 'Revenue reports', 'Audit logs', 'Usage billing']

export default function Example() {
  const [run, setRun] = useState(0)
  return (
    <div className="grid w-full gap-6">
      <Button
        variant="outline"
        size="sm"
        leftIcon={<RotateCcw />}
        className="justify-self-start"
        onClick={() => setRun((n) => n + 1)}
      >
        Replay
      </Button>
      <div key={run} className="grid gap-6">
        <Reveal className="grid gap-1">
          <p className="font-display text-h3">Billing that keeps up</p>
          <Text tone="muted">Reveal fades and lifts a block in when it scrolls into view.</Text>
        </Reveal>
        <Stagger as="ul" className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {features.map((feature) => (
            <li key={feature}>
              <Card padding="sm" className="h-full">
                <Text weight="medium">{feature}</Text>
              </Card>
            </li>
          ))}
        </Stagger>
      </div>
    </div>
  )
}
```

Live example: https://glyphui.xyz/components/motion

```tsx title="src/features.tsx"
import { Card, Reveal, Stagger } from '@glyphui/ui'

export function Features({ items }: { items: { title: string; body: string }[] }) {
  return (
    <>
      <Reveal>
        <h2 className="font-display text-h2">Why teams switch</h2>
      </Reveal>
      <Stagger as="ul" className="grid gap-4 sm:grid-cols-3">
        {items.map((item) => (
          <li key={item.title}>
            <Card>
              <h3 className="font-display text-h4">{item.title}</h3>
              <p className="text-small text-muted-foreground">{item.body}</p>
            </Card>
          </li>
        ))}
      </Stagger>
    </>
  )
}
```

Every block in `@glyphui/blocks` already uses them. Pass `animate={false}` to a block to turn its entrance off.

## Animated numbers

`AnimatedNumber` counts to its value on a spring and formats it with `Intl.NumberFormat`. Screen readers get the final value, not every step.

```tsx
import { AnimatedNumber, Button, Card, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [mrr, setMrr] = useState(48210)
  return (
    <Card className="w-full max-w-sm gap-3">
      <Text size="small" tone="muted">
        Monthly recurring revenue
      </Text>
      <p className="font-display text-h1">
        <AnimatedNumber
          value={mrr}
          locale="en-US"
          format={{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }}
        />
      </p>
      <div className="flex gap-2">
        <Button size="sm" onClick={() => setMrr((n) => n + 1840)}>
          New customer
        </Button>
        <Button size="sm" variant="outline" onClick={() => setMrr((n) => Math.max(0, n - 920))}>
          Churn
        </Button>
      </div>
    </Card>
  )
}
```

Live example: https://glyphui.xyz/components/motion

## Page transitions

Wrap your router's outlet and key it by path. Only the new page animates in; the old one leaves at once, so pages never overlap:

```tsx title="src/layout.tsx"
import { PageTransition } from '@glyphui/ui'
import { Outlet, useLocation } from 'react-router'

export function Layout() {
  const { pathname } = useLocation()
  return (
    <PageTransition transitionKey={pathname}>
      <Outlet />
    </PageTransition>
  )
}
```

The first page renders without an entrance.

## Custom animations

For your own enter and exit animations, use `Presence` and `m.*` elements from the [motion](https://motion.dev) library, re-exported by Glyph. They share the theme's spring and turn off with reduced motion:

```tsx
import { Button, m, Presence, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(true)
  return (
    <div className="grid w-full max-w-sm gap-4">
      <Button variant="outline" className="justify-self-start" onClick={() => setOpen((o) => !o)}>
        {open ? 'Dismiss' : 'Show'} banner
      </Button>
      <Presence>
        {open && (
          <m.div
            key="banner"
            initial={{ opacity: 0, y: -8, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -8, scale: 0.98 }}
            className="rounded-lg border border-border bg-surface p-4 shadow-sm"
          >
            <Text weight="medium">Your trial ends in 3 days</Text>
            <Text size="small" tone="muted">
              Pick a plan to keep your invoices sending.
            </Text>
          </m.div>
        )}
      </Presence>
    </div>
  )
}
```

Live example: https://glyphui.xyz/components/motion

In plain CSS, the spring is available as an easing: `ease-spring duration-(--glyph-duration-spring)` in Tailwind, or `var(--glyph-ease-spring)` and `var(--glyph-duration-spring)`.

## Cost

Buttons and other CSS-only components never load the motion library. The library's animation features load after the first render, so they don't delay the page. [`useMotionSettings()`](https://glyphui.xyz/components/motion) tells your own components the current level and spring.

Live page: https://glyphui.xyz/docs/motion

---

# Routing

> Connect React Router, TanStack Router or Next.js for links and active items.

Glyph doesn't depend on a router. Connect yours once on `GlyphProvider` and two things follow everywhere:

- Glyph's links (`Link`, `SidebarItem`, Navbar links, `NavigationMenuLink`, table rows with `getRowHref`) navigate client-side.
- Sidebar, Navbar and NavigationMenu items mark the current page with `aria-current="page"`, without an `active` prop.

## React Router

React Router 7 or later works out of the box:

```tsx title="src/providers.tsx"
import { GlyphProvider } from '@glyphui/ui'
import { reactRouter } from '@glyphui/ui/react-router'
import type { ReactNode } from 'react'

export function Providers({ children }: { children: ReactNode }) {
  return <GlyphProvider router={reactRouter}>{children}</GlyphProvider>
}
```

`GlyphProvider` goes outside the router: with a data router, wrap `<RouterProvider>`; with `<BrowserRouter>`, either side works.

## Active items

An item is active on its own path and every path below it, like React Router's `NavLink`. Pass `end` on index items, or `/app` would stay active on every page:

```tsx title="src/app-sidebar.tsx"
import { Sidebar, SidebarContent, SidebarItem } from '@glyphui/ui'
import { FileText, Home, Settings } from 'lucide-react'

export function AppSidebar() {
  return (
    <Sidebar>
      <SidebarContent aria-label="Main">
        <SidebarItem href="/app" icon={<Home />} end>
          Dashboard
        </SidebarItem>
        <SidebarItem href="/app/invoices" icon={<FileText />}>
          Invoices
        </SidebarItem>
        <SidebarItem href="/app/settings" icon={<Settings />}>
          Settings
        </SidebarItem>
      </SidebarContent>
    </Sidebar>
  )
}
```

An explicit `active` prop always wins. Hash links, external URLs and `mailto:` render as plain anchors and are never active.

```tsx
import { AppShell, Sidebar, SidebarContent, SidebarItem, SidebarSection, Text } from '@glyphui/ui'
import { BookOpen, LayoutGrid, PanelLeft, Route } from 'lucide-react'

export default function Example() {
  return (
    <div className="h-72 overflow-hidden rounded-lg border border-border">
      <AppShell
        layout="embedded"
        sidebar={
          <Sidebar>
            <SidebarContent>
              <SidebarSection label="Docs">
                <SidebarItem href="/components" end icon={<LayoutGrid />}>
                  All components
                </SidebarItem>
                <SidebarItem href="/components/router" icon={<Route />}>
                  Router integration
                </SidebarItem>
                <SidebarItem href="/components/sidebar" icon={<PanelLeft />}>
                  Sidebar
                </SidebarItem>
                <SidebarItem href="/getting-started" icon={<BookOpen />}>
                  Getting started
                </SidebarItem>
              </SidebarSection>
            </SidebarContent>
          </Sidebar>
        }
      >
        <div className="p-5">
          <Text tone="muted">
            No item sets active. “Router integration” is highlighted because it matches this page.
          </Text>
        </div>
      </AppShell>
    </div>
  )
}
```

Live example: https://glyphui.xyz/components/router

Your own components can use the same matching with `useIsActive(href, { end })`.

## TanStack Router

Pass an object with your router's `Link` and a `useIsActive` hook:

```tsx title="src/glyph-router.tsx"
import type { GlyphRouter } from '@glyphui/ui'
import { Link, useLocation } from '@tanstack/react-router'

export const tanstackRouter: GlyphRouter = {
  Link: ({ href, ...props }) => <Link to={href} {...props} />,
  useIsActive: (href, { end } = {}) => {
    const pathname = useLocation({ select: (location) => location.pathname })
    return end ? pathname === href : pathname === href || pathname.startsWith(`${href}/`)
  },
}

// <GlyphProvider router={tanstackRouter}>
```

## Next.js

The same object, built from `next/link` and `usePathname`, in a client component:

```tsx title="app/glyph-router.tsx"
'use client'
import type { GlyphRouter } from '@glyphui/ui'
import NextLink from 'next/link'
import { usePathname } from 'next/navigation'

export const nextRouter: GlyphRouter = {
  Link: NextLink,
  useIsActive: (href, { end } = {}) => {
    const pathname = usePathname()
    return end ? pathname === href : pathname === href || pathname.startsWith(`${href}/`)
  },
}
```

Use it in the providers component from [Getting started](https://glyphui.xyz/docs/getting-started#nextjs).

## Tables with URL state

`useTableUrlState` keeps a DataTable's page, sort, search and filters in the URL. It uses the History API by default; with React Router, pass `useRouterUrlAdapter()` so the router's location and `useSearchParams` always agree with the table:

```tsx title="src/use-invoice-view.ts"
import { useTableUrlState } from '@glyphui/ui/data-table'
import { useRouterUrlAdapter } from '@glyphui/ui/react-router'

export function useInvoiceView() {
  return useTableUrlState({ prefix: 'invoices', adapter: useRouterUrlAdapter() })
}
```

[Data tables](https://glyphui.xyz/docs/data-tables#state-in-the-url) has the rest.

## Navigation and tests

React Router 7 renders the next page inside a transition: the URL changes a moment before the new page appears. In end-to-end tests, wait for the new page's content, not the URL, before interacting. [Testing your app](https://glyphui.xyz/docs/testing#end-to-end-tests) has examples.

Live page: https://glyphui.xyz/docs/routing

---

# Forms

> Schema-validated forms with server errors, in pages and modals.

`@glyphui/ui/form` wraps [react-hook-form](https://react-hook-form.com) with a schema and Glyph's fields. You describe the data once; field names, values and errors are typed from it, and labels, descriptions, error messages and `aria-*` attributes are wired for you.

```sh
npm install react-hook-form @hookform/resolvers zod
```

Any [Standard Schema](https://standardschema.dev) validator works: zod, valibot, arktype.

## A form

```tsx title="src/signup-form.tsx"
import { Input } from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { z } from 'zod'

const schema = z.object({
  name: z.string().trim().min(2, 'Use at least 2 characters'),
  email: z.email('Enter a valid email address'),
})

async function createAccount(values: z.infer<typeof schema>) {
  const res = await fetch('/api/accounts', { method: 'POST', body: JSON.stringify(values) })
  return res.status === 409 ? 'taken' : 'ok'
}

export function SignupForm() {
  const form = useForm({ schema, defaultValues: { name: '', email: '' } })
  return (
    <Form
      form={form}
      className="grid max-w-sm gap-4"
      onSubmit={async (values) => {
        if ((await createAccount(values)) === 'taken')
          return { errors: { email: 'That email is already registered.' } }
      }}
    >
      <FormError />
      <FormField control={form.control} name="name" label="Name" required>
        {(field) => <Input autoComplete="name" {...field} />}
      </FormField>
      <FormField control={form.control} name="email" label="Email" required>
        {(field) => <Input type="email" autoComplete="email" {...field} />}
      </FormField>
      <FormSubmit>Create account</FormSubmit>
    </Form>
  )
}
```

```tsx
import { Input, Text } from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { useState } from 'react'
import { z } from 'zod'

const schema = z.object({
  name: z.string().trim().min(2, 'Use at least 2 characters'),
  email: z.email('Enter a valid email address'),
})

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  const [done, setDone] = useState<string | null>(null)
  const form = useForm({ schema, defaultValues: { name: '', email: '' } })

  if (done) return <Text>Welcome aboard, {done}.</Text>

  return (
    <Form
      form={form}
      className="grid max-w-sm gap-4"
      onSubmit={async (values) => {
        await wait(700)
        if (values.email === 'taken@acme.dev')
          return { errors: { email: 'That email is already registered.' } }
        setDone(values.name)
      }}
    >
      <FormError />
      <FormField control={form.control} name="name" label="Name" required>
        {(field) => <Input autoComplete="name" {...field} />}
      </FormField>
      <FormField control={form.control} name="email" label="Email" required>
        {(field) => <Input type="email" autoComplete="email" {...field} />}
      </FormField>
      <FormSubmit className="justify-self-start">Create account</FormSubmit>
    </Form>
  )
}
```

Live example: https://glyphui.xyz/components/form

- `name` is checked against the schema: a typo is a compile error.
- `onSubmit` only runs with valid values, already parsed by the schema.
- `FormSubmit` shows a spinner and blocks double submits until `onSubmit` settles.

## Server errors

What `onSubmit` returns or throws decides what the user sees:

| From `onSubmit` | Shown |
|---|---|
| `{ errors: { email: '…' } }` | Under the matching field |
| `{ errors: { root: '…' } }` | In `FormError`, above the form |
| A thrown error | Its message in `FormError` |
| Nothing | Nothing; reset or navigate as you like |

A field's server error clears as soon as the user edits that field.

## Other field types

`FormField` passes react-hook-form's field (`{ value, onChange, onBlur, name, ref }`) to its child. Glyph inputs inside a field pick up its label, description and error wiring on their own. Text inputs take the field with `{...field}`; controls with a `value` / `onValueChange` API map it explicitly:

```tsx title="src/plan-fields.tsx"
import { DatePicker, NumberInput, Select, SelectItem } from '@glyphui/ui'
import { Form, FormField, useForm } from '@glyphui/ui/form'
import { z } from 'zod'

const schema = z.object({
  plan: z.enum(['starter', 'growth']),
  seats: z.number().int().min(1),
  startsOn: z.date('Choose a start date'),
})

export function PlanFields() {
  const form = useForm({ schema, defaultValues: { plan: 'starter', seats: 5 } })
  return (
    <Form form={form} onSubmit={() => {}} className="grid gap-4">
      <FormField control={form.control} name="plan" label="Plan">
        {(field) => (
          <Select value={field.value} onValueChange={field.onChange}>
            <SelectItem value="starter">Starter</SelectItem>
            <SelectItem value="growth">Growth</SelectItem>
          </Select>
        )}
      </FormField>
      <FormField control={form.control} name="seats" label="Seats">
        {(field) => (
          <NumberInput
            value={field.value ?? null}
            onValueChange={(v) => field.onChange(v ?? undefined)}
            min={1}
          />
        )}
      </FormField>
      <FormField control={form.control} name="startsOn" label="Starts on">
        {(field) => <DatePicker value={field.value} onValueChange={field.onChange} />}
      </FormField>
    </Form>
  )
}
```

NumberInput reports the value while you type, so a field error clears before you reach the submit button.

## Forms in a Modal

A Modal's `footer` sits outside the form element, so give `FormSubmit` the form explicitly:

```tsx
import {
  Button,
  DatePicker,
  Input,
  Modal,
  ModalClose,
  NumberInput,
  Select,
  SelectItem,
  toast,
} from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { z } from 'zod'

const customers = ['Northwind', 'Globex', 'Initech', 'Umbrella']

const schema = z.object({
  customer: z.string().min(1, 'Choose a customer'),
  amount: z.number('Enter an amount').positive('Must be more than zero'),
  due: z.date('Choose a due date'),
  memo: z.string().max(140, 'Keep it under 140 characters'),
})

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

export default function Example() {
  const [open, setOpen] = useState(false)
  const form = useForm({
    schema,
    defaultValues: { customer: '', amount: undefined, due: undefined, memo: '' },
  })

  return (
    <Modal
      open={open}
      onOpenChange={(next) => {
        if (!next) form.reset()
        setOpen(next)
      }}
      title="New invoice"
      description="The customer gets an email with a payment link."
      trigger={<Button leftIcon={<Plus />}>New invoice</Button>}
      footer={
        <>
          <ModalClose asChild>
            <Button variant="outline">Cancel</Button>
          </ModalClose>
          {/* Outside <Form>, so it gets the form explicitly. */}
          <FormSubmit form={form}>Create invoice</FormSubmit>
        </>
      }
    >
      <Form
        form={form}
        className="grid gap-4"
        onSubmit={async (values) => {
          await new Promise((resolve) => setTimeout(resolve, 600))
          if (values.amount > 50_000) {
            return { errors: { amount: 'Invoices over $50,000 need approval.' } }
          }
          toast.success('Invoice created', {
            description: `${values.customer} · ${usd.format(values.amount)}`,
          })
          setOpen(false)
          form.reset()
        }}
      >
        <FormError />
        <FormField control={form.control} name="customer" label="Customer" required>
          {(field) => (
            <Select
              placeholder="Choose a customer"
              value={field.value}
              onValueChange={field.onChange}
            >
              {customers.map((name) => (
                <SelectItem key={name} value={name}>
                  {name}
                </SelectItem>
              ))}
            </Select>
          )}
        </FormField>
        <div className="grid gap-4 sm:grid-cols-2">
          <FormField control={form.control} name="amount" label="Amount" required>
            {(field) => (
              <NumberInput
                value={field.value ?? null}
                onValueChange={(value) => field.onChange(value ?? undefined)}
                min={0}
                locale="en-US"
                formatOptions={{ style: 'currency', currency: 'USD' }}
              />
            )}
          </FormField>
          <FormField control={form.control} name="due" label="Due date" required>
            {(field) => (
              <DatePicker value={field.value} onValueChange={field.onChange} minDate={new Date()} />
            )}
          </FormField>
        </div>
        <FormField
          control={form.control}
          name="memo"
          label="Memo"
          description="Shown on the invoice."
        >
          {(field) => <Input placeholder="October usage" {...field} />}
        </FormField>
      </Form>
    </Modal>
  )
}
```

Live example: https://glyphui.xyz/components/modal

For a plain form without the form pattern, pass `onSubmit` to `Modal` instead: its body and footer become one `<form>`, and a `type="submit"` button in the footer works.

## Confirmations

For "are you sure?" questions, skip the form: `useConfirm()` opens a themed confirmation dialog and resolves to `true` or `false`.

```tsx title="src/delete-button.tsx"
import { Button, useConfirm } from '@glyphui/ui'

export function DeleteButton({ onDelete }: { onDelete: () => void }) {
  const confirm = useConfirm()
  return (
    <Button
      variant="danger"
      onClick={async () => {
        if (await confirm({ title: 'Delete project?', tone: 'danger' })) onDelete()
      }}
    >
      Delete
    </Button>
  )
}
```

Live page: https://glyphui.xyz/docs/forms

---

# Data tables

> Sorting, filters, server mode, URL state, bulk actions and virtualization.

`DataTable` from `@glyphui/ui/data-table` is the table most apps end up building by hand: search, filter chips, multi-column sorting, pagination, selection with bulk actions, column controls, clickable and expandable rows, inline editing and CSV export, with loading, empty and error states. It runs on [TanStack Table](https://tanstack.com/table) version 8.

```sh
npm install @tanstack/react-table@8
```

## Columns and rows

Columns are typed from your row type with `createColumnHelper`. `getRowId` keeps selections stable across pages and data changes.

```tsx title="src/invoices-table.tsx"
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'

interface Invoice {
  id: string
  customer: string
  status: 'paid' | 'open' | 'overdue'
  total: number
}

const tone = { paid: 'success', open: 'info', overdue: 'danger' } as const
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={tone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
    meta: {
      filter: {
        type: 'multi',
        options: [
          { value: 'paid', label: 'Paid' },
          { value: 'open', label: 'Open' },
          { value: 'overdue', label: 'Overdue' },
        ],
      },
    },
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export function InvoicesTable({ invoices }: { invoices: Invoice[] }) {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      search={{ placeholder: 'Search invoices…' }}
      selectable
      columnControls
    />
  )
}
```

Define `columns` outside the component (or memoize them) so the table doesn't rebuild on every render. Set `meta: { align: 'right' }` on numeric columns.

## Filters

`meta.filter` on a column adds it to the Filter menu, and active filters show as chips above the table. Types: `select`, `multi` (with match counts), `range`, `date-range` and `text`. Shift-click column headers to sort by several columns.

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusOptions, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const daysAgo = (n: number) => new Date(Date.now() - n * 86_400_000)

const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', {
    header: 'Customer',
    meta: { filter: { type: 'text', placeholder: 'Company name' } },
  }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
    // Faceted counts appear beside each option, from the other active filters.
    meta: { filter: { type: 'multi', options: statusOptions } },
  }),
  col.accessor('plan', {
    header: 'Plan',
    meta: {
      filter: {
        type: 'select',
        options: [
          { value: 'Starter', label: 'Starter' },
          { value: 'Growth', label: 'Growth' },
          { value: 'Enterprise', label: 'Enterprise' },
        ],
      },
    },
  }),
  col.accessor('issued', {
    header: 'Issued',
    cell: (info) => formatDay(info.getValue()),
    meta: {
      filter: {
        type: 'date-range',
        presets: [
          { label: 'Last 7 days', range: () => ({ from: daysAgo(6), to: new Date() }) },
          { label: 'Last 30 days', range: () => ({ from: daysAgo(29), to: new Date() }) },
        ],
      },
    },
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: {
      align: 'right',
      filter: { type: 'range', min: 0, step: 100, format: (n) => usd.format(n) },
    },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={8}
      defaultState={{ columnFilters: [{ id: 'status', value: ['open', 'overdue'] }] }}
    />
  )
}
```

Live example: https://glyphui.xyz/components/data-table

## Server mode

With `mode="server"`, the table hands paging, sorting, search and filters to you through `onStateChange`. Pass the current page as `data`, the total as `rowCount`, and `loading` while you fetch; the previous rows stay on screen under a progress bar until the new page arrives.

```tsx title="src/server-invoices.tsx"
import {
  createColumnHelper,
  DataTable,
  type DataTableState,
  getFilterList,
} from '@glyphui/ui/data-table'
import { useEffect, useState } from 'react'

interface Invoice {
  id: string
  customer: string
  total: number
}

interface Page {
  rows: Invoice[]
  total: number
}

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('total', { header: 'Total', meta: { align: 'right' } }),
]

type Query = Pick<DataTableState, 'pagination' | 'sorting' | 'search' | 'columnFilters'>

async function fetchInvoices(query: Query): Promise<Page> {
  const params = new URLSearchParams({
    page: String(query.pagination.pageIndex),
    size: String(query.pagination.pageSize),
    q: query.search,
  })
  for (const status of getFilterList(query.columnFilters, 'status')) params.append('status', status)
  const sort = query.sorting[0]
  if (sort) params.set('sort', `${sort.id}.${sort.desc ? 'desc' : 'asc'}`)
  return (await fetch(`/api/invoices?${params}`)).json()
}

export function ServerInvoices() {
  const [query, setQuery] = useState<Query>({
    pagination: { pageIndex: 0, pageSize: 25 },
    sorting: [],
    search: '',
    columnFilters: [],
  })
  const [page, setPage] = useState<Page>()
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let current = true
    setLoading(true)
    fetchInvoices(query).then((next) => {
      // Ignore responses that arrive after a newer query.
      if (!current) return
      setPage(next)
      setLoading(false)
    })
    return () => {
      current = false
    }
  }, [query])

  return (
    <DataTable
      aria-label="Invoices"
      mode="server"
      data={page?.rows}
      rowCount={page?.total}
      loading={loading}
      columns={columns}
      getRowId={(row) => row.id}
      state={query}
      onStateChange={(next) =>
        setQuery({
          pagination: next.pagination,
          sorting: next.sorting,
          search: next.search,
          columnFilters: next.columnFilters,
        })
      }
      search
    />
  )
}
```

- `getFilterList(state.columnFilters, 'status')` always returns an array, even when a shared link held a single value.
- APIs without a total pass `hasNextPage` for cursor paging, or `onLoadMore` for a "Load more" list.
- In `multi` filters, give options a `count` from your server and the menu shows it.

With TanStack Query, keep the previous page while the next one loads:

```tsx
const { data, isFetching } = useQuery({
  queryKey: ['invoices', query],
  queryFn: () => fetchInvoices(query),
  placeholderData: keepPreviousData,
})

<DataTable mode="server" data={data?.rows} rowCount={data?.total} loading={isFetching} … />
```

## State in the URL

`useTableUrlState` stores the page, sort, search, filters and hidden columns in the URL, so a view can be shared and the back button works. Spread what it returns onto the table:

```tsx
import { Badge, Button } from '@glyphui/ui'
import { createColumnHelper, DataTable, useTableUrlState } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusOptions, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
    meta: { filter: { type: 'multi', options: statusOptions } },
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  // Page, sort, search, filters and hidden columns live in the URL as `orders.*` params.
  const url = useTableUrlState({ prefix: 'orders', pageSize: 5 })
  return (
    <DataTable
      aria-label="Orders"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={5}
      search={{ placeholder: 'Search orders…' }}
      columnControls={{ hide: true }}
      toolbar={
        <Button variant="ghost" size="sm" onClick={url.reset}>
          Reset view
        </Button>
      }
      {...url}
    />
  )
}
```

Live example: https://glyphui.xyz/components/data-table

- `prefix` keeps several tables on one page apart (`orders.page`, `orders.sort`).
- Pass `columns` so filters decode by type: a shared link with one status still gives a `multi` filter an array.
- With React Router, pass `adapter: useRouterUrlAdapter()` from `@glyphui/ui/react-router`.

The format is readable: `page` (from 1) and `size`, `sort=column` or `column.desc` (comma-separated for several), `q` for search, one `f.<column>` parameter per filter value, and `hide=col,col`. Build links to a view, for example from a command menu, with `tableSearch`:

```ts title="src/links.ts"
import { tableSearch } from '@glyphui/ui/data-table'

// "?q=INV-1043&f.status=overdue"
export const overdueInvoice = `/invoices${tableSearch({
  search: 'INV-1043',
  columnFilters: [{ id: 'status', value: ['overdue'] }],
})}`
```

## Selection and bulk actions

`selectable` adds checkboxes. Select every row on the page and a banner offers to select every matching row; `bulkActions` renders your actions in a floating bar.

```tsx
import {
  Badge,
  Button,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  IconButton,
  toast,
  useConfirm,
} from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { Copy, MoreHorizontal, Send, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { type Invoice, invoices as seed, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()

export default function Example() {
  const [rows, setRows] = useState(seed)
  const confirm = useConfirm()

  async function remove(ids: string[]) {
    const ok = await confirm({
      title: ids.length === 1 ? `Delete ${ids[0]}?` : `Delete ${ids.length} invoices?`,
      description: 'Customers keep any PDFs already sent.',
      tone: 'danger',
    })
    if (!ok) return false
    setRows((current) => current.filter((row) => !ids.includes(row.id)))
    toast.success(ids.length === 1 ? 'Invoice deleted' : `${ids.length} invoices deleted`)
    return true
  }

  const columns = [
    col.accessor('id', { header: 'Invoice' }),
    col.accessor('customer', { header: 'Customer' }),
    col.accessor('status', {
      header: 'Status',
      cell: (info) => (
        <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
          {info.getValue()}
        </Badge>
      ),
    }),
    col.accessor('total', {
      header: 'Total',
      cell: (info) => usd.format(info.getValue()),
      meta: { align: 'right' },
    }),
    col.display({
      id: 'actions',
      header: () => <span className="sr-only">Actions</span>,
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <IconButton
              icon={<MoreHorizontal />}
              aria-label={`Actions for ${row.original.id}`}
              size="sm"
            />
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              icon={<Send />}
              onSelect={() => toast.success(`Reminder sent to ${row.original.email}`)}
            >
              Send reminder
            </DropdownMenuItem>
            <DropdownMenuItem
              icon={<Copy />}
              onSelect={() => navigator.clipboard?.writeText(row.original.id)}
            >
              Copy ID
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              icon={<Trash2 />}
              tone="danger"
              onSelect={() => remove([row.original.id])}
            >
              Delete
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
      meta: { align: 'right', className: 'w-12' },
    }),
  ]

  return (
    <DataTable
      aria-label="Invoices"
      data={rows}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={8}
      selectable
      exportCsv={{ fileName: 'invoices.csv' }}
      bulkActions={(selection) => (
        <>
          <Button
            size="sm"
            variant="outline"
            leftIcon={<Send />}
            onClick={() => toast.success(`Sent ${selection.count} reminders`)}
          >
            Remind
          </Button>
          <Button
            size="sm"
            variant="danger"
            leftIcon={<Trash2 />}
            onClick={async () => {
              if (await remove(selection.ids)) selection.clear()
            }}
          >
            Delete
          </Button>
        </>
      )}
    />
  )
}
```

Live example: https://glyphui.xyz/components/data-table

In server mode, "select all" sets `allMatchingSelected` in the state instead of listing ids. Act on the query, not the ids, when it's set.

## Rows

- `onRowClick(row)` opens details, for example in a Sheet. Clicks on buttons, links, checkboxes and menus inside the row act on themselves.
- `getRowHref(row)` renders the first column as a real link, so keyboard users, middle-click and "open in new tab" work.
- `renderSubRow(row)` adds an expander with any content below the row.

## Inline editing

`editableCell()` edits text, numbers or choices in place. `onCellEdit` saves: the new value shows at once and rolls back if your promise rejects.

```tsx
import { toast } from '@glyphui/ui'
import { createColumnHelper, DataTable, editableCell } from '@glyphui/ui/data-table'
import { useState } from 'react'

interface Seat {
  id: string
  name: string
  role: 'admin' | 'member' | 'billing'
  seats: number
}

const roles = [
  { value: 'admin', label: 'Admin' },
  { value: 'member', label: 'Member' },
  { value: 'billing', label: 'Billing' },
]

const col = createColumnHelper<Seat>()
const columns = [
  col.accessor('name', {
    header: 'Team',
    cell: editableCell<Seat, string>({
      validate: (value) => (value.trim().length < 2 ? 'Use at least 2 characters' : null),
    }),
  }),
  col.accessor('role', {
    header: 'Default role',
    cell: editableCell<Seat, string>({ type: 'select', options: roles }),
  }),
  col.accessor('seats', {
    header: 'Seats',
    cell: editableCell<Seat, number>({
      type: 'number',
      validate: (value) => (value === null || value < 1 ? 'At least 1 seat' : null),
    }),
    meta: { align: 'right' },
  }),
]

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  const [rows, setRows] = useState<Seat[]>([
    { id: 't1', name: 'Design', role: 'member', seats: 8 },
    { id: 't2', name: 'Engineering', role: 'member', seats: 24 },
    { id: 't3', name: 'Finance', role: 'billing', seats: 3 },
  ])
  return (
    <DataTable
      aria-label="Teams"
      data={rows}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={false}
      onCellEdit={async ({ rowId, columnId, value }) => {
        await wait(500)
        // The server refuses more than 50 seats: the cell rolls back and explains why.
        if (columnId === 'seats' && Number(value) > 50) {
          toast.error('Plans include up to 50 seats per team')
          throw new Error('Plans include up to 50 seats per team')
        }
        setRows((current) =>
          current.map((row) => (row.id === rowId ? { ...row, [columnId]: value } : row)),
        )
      }}
    />
  )
}
```

Live example: https://glyphui.xyz/components/data-table

## Export, density and columns

- `exportCsv` adds an Export menu: this page, the selected rows, or every row (in server mode, pass `fetchAll`). Fields are quoted per RFC 4180, and text that starts like a formula (`=`, `+`, `-`, `@`) is neutralized so spreadsheets don't run it. `exportTableCsv()` and `toCsv()` export without a table.
- `densityToggle` adds compact, default and comfortable rows. A theme can set the default for every table.
- `columnControls` adds hiding, drag and keyboard resizing, pinning and reordering.

## Phones

`mobile="cards"` turns each row into a card below 640px, using the column headers as labels. The default scrolls the table sideways.

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
  // Kept out of the cards to save space.
  col.accessor('email', { header: 'Billing email', meta: { mobile: 'hidden' } }),
]

export default function Example() {
  // Narrow your window below 640px: each row becomes a card, the first column leads it.
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={4}
      selectable
      mobile="cards"
    />
  )
}
```

Live example: https://glyphui.xyz/components/data-table

## Ten thousand rows

For large client-side tables, render only the visible rows with `virtualRows` from `@glyphui/ui/data-table/virtual`:

```sh
npm install @tanstack/react-virtual
```

```tsx title="src/all-events.tsx"
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { virtualRows } from '@glyphui/ui/data-table/virtual'

interface LogEvent {
  id: string
  name: string
}

const col = createColumnHelper<LogEvent>()
const columns = [col.accessor('id', { header: 'ID' }), col.accessor('name', { header: 'Event' })]

// Create the virtualizer once, outside the component.
const virtual = virtualRows({ height: 480 })

export function AllEvents({ events }: { events: LogEvent[] }) {
  return (
    <DataTable
      aria-label="Events"
      data={events}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={false}
      virtualize={virtual}
    />
  )
}
```

Search, sort and select still work across every row, and screen readers get the full row count. Expandable rows aren't virtualized; use pages for tables with row details.

Live page: https://glyphui.xyz/docs/data-tables

---

# Authentication

> Sessions, protected routes and sign-in screens against your own API.

`@glyphui/auth` handles the client side of authentication: the session and its refresh, route protection with redirect-back, roles and permissions, and ready screens for sign-in, sign-up, password reset, email codes and two-factor sign-in. Your server stays the authority; Glyph talks to it through an adapter.

```sh
npm install @glyphui/auth @glyphui/blocks react-hook-form @hookform/resolvers react-router
```

```css title="src/index.css"
@import "tailwindcss";
@import "@glyphui/ui/styles.css";
@import "@glyphui/blocks/styles.css";
@import "@glyphui/auth/styles.css";
```

## How it fits together

| Piece | Job |
|---|---|
| `createAuthClient(adapter)` | One client per app. It holds the session, refreshes it, syncs tabs and wraps `fetch`. |
| Adapters | Talk to your backend: `/rest` (your API), `/firebase`, `/clerk`, `/memory` (demos and tests). |
| `AuthProvider` and `useAuth()` | The client in React: `status`, `user`, `signIn`, `signOut`, `can`, `fetch` and more. |
| `/react-router` | `RequireAuth`, `GuestOnly`, `RequireRole`, and loaders that redirect before render. |
| `/ui` | `SignInForm`, `SignUpForm`, reset and code screens, `UserMenu`, session dialogs. |

## Set up

Create the client once. Route loaders and `AuthProvider` share it:

```tsx title="src/auth.ts"
import { createAuthClient } from '@glyphui/auth'
import { restAdapter } from '@glyphui/auth/rest'

export const auth = createAuthClient(
  restAdapter({
    baseUrl: '/api',
    // Your server sets an httpOnly cookie; a readable CSRF cookie is echoed on writes.
    csrf: { header: 'X-CSRF-Token', cookie: 'csrf_token' },
  }),
  { idleTimeout: 30 * 60_000 }, // optional: sign out after 30 idle minutes
)
```

Then the providers, outermost first: Glyph, auth, the router.

```tsx title="src/main.tsx"
import { AuthProvider } from '@glyphui/auth'
import { AuthRevalidator, guestLoader, protectedLoader } from '@glyphui/auth/react-router'
import { SessionExpiredDialog } from '@glyphui/auth/ui'
import { GlyphProvider, LoadingState } from '@glyphui/ui'
import { reactRouter } from '@glyphui/ui/react-router'
import { createRoot } from 'react-dom/client'
import { createBrowserRouter, Outlet, RouterProvider } from 'react-router'
import { auth } from './auth'
import { AppLayout, SignInPage } from './pages'

const router = createBrowserRouter([
  {
    element: (
      <>
        <AuthRevalidator />
        <Outlet />
      </>
    ),
    hydrateFallbackElement: <LoadingState label="Loading" />,
    children: [
      { path: 'sign-in', loader: guestLoader(auth, { redirectTo: '/app' }), element: <SignInPage /> },
      { path: 'app', loader: protectedLoader(auth), element: <AppLayout /> },
    ],
  },
])

createRoot(document.getElementById('root') as HTMLElement).render(
  <GlyphProvider router={reactRouter} toaster>
    <AuthProvider client={auth}>
      <RouterProvider router={router} />
      <SessionExpiredDialog />
    </AuthProvider>
  </GlyphProvider>,
)
```

- `protectedLoader` sends signed-out visitors to `/sign-in?next=/where/they/were` before the page renders.
- `guestLoader` sends signed-in visitors away from the sign-in page.
- `AuthRevalidator` re-runs loaders when the session changes, so a sign-out in another tab or after the idle timeout leaves protected pages.
- `SessionExpiredDialog` asks for the password again when the session expires mid-task, without leaving the page.

## Type your user

Declare your user's shape once; `useAuth().user`, guards and screens follow it:

```ts title="src/auth-types.ts"
declare module '@glyphui/auth' {
  interface Register {
    user: { id: string; email: string; name: string; plan: 'free' | 'pro' }
  }
}

export {}
```

## Sign-in and sign-up pages

The screens hide what your backend doesn't support, so set the adapter's `capabilities` to match your server (OAuth providers, magic links, organizations).

```tsx title="src/pages.tsx"
import { RequireAuth, useRedirectAfterSignIn } from '@glyphui/auth/react-router'
import { AuthLayout, SignInForm, UserMenu } from '@glyphui/auth/ui'
import { Outlet } from 'react-router'

export function SignInPage() {
  // Back to ?next= after signing in. Only same-origin paths are followed.
  const continueToApp = useRedirectAfterSignIn('/app')
  return (
    <AuthLayout>
      <SignInForm signUpHref="/sign-up" forgotPasswordHref="/forgot-password" onSuccess={continueToApp} />
    </AuthLayout>
  )
}

export function AppLayout() {
  return (
    <RequireAuth>
      <header className="flex justify-end p-4">
        <UserMenu />
      </header>
      <Outlet />
    </RequireAuth>
  )
}
```

`SignInForm` covers the whole flow: password, OAuth buttons, email links, then any email-verification or two-factor step the server asks for. `SignUpForm` takes `extraFields` for things like an invite code or workspace name; they're validated with the form and sent with the request.

## Your REST API

`restAdapter` expects these endpoints under `baseUrl`; rename any of them with `endpoints`.

| Endpoint | Body | Returns |
|---|---|---|
| `GET /auth/session` | | `200 { user, … }`, or `200 { user: null }` when signed out |
| `POST /auth/sign-in` | `{ email, password }` | `200` with the session, or `202` for a next step |
| `POST /auth/sign-up` | `{ email, password, name?, …extra }` | Like sign-in |
| `POST /auth/sign-out` | `{ refreshToken }` in bearer mode | `204` |
| `POST /auth/refresh` | `{ refreshToken }` in bearer mode | The new tokens or session |
| `POST /auth/password/forgot` | `{ email }` | `2xx`, whether or not the account exists |
| `POST /auth/password/reset` | `{ token, password }`, plus `{ email }` for codes | `2xx` |
| `POST /auth/verify` | `{ email, code, challenge? }` | Like sign-in |
| `POST /auth/verify/resend` | `{ email }` | `2xx` |
| `POST /auth/two-factor` | `{ code, challenge }` | Like sign-in |
| `POST /auth/magic-link` | `{ email }` | `202 { status: 'magic-link-sent' }` |
| `POST /auth/magic-link/verify` | `{ token }` | Like sign-in |
| `POST /auth/organization` | `{ organizationId }` | The session for that organization |
| `PATCH /auth/user` | Profile fields | The updated session |

A session is `{ user, expiresAt?, roles?, permissions?, organizations?, activeOrganizationId? }`, plus `accessToken` and `refreshToken` in bearer mode. Your API returns another shape? Map it with `mapSession`.

- **Errors.** A JSON body with `message` shows above the form; `errors: { email: '…' }` shows next to the matching fields. Without a message, each status gets a friendly default, and `429` honors `Retry-After`.
- **Next steps.** Answer `202 { status: 'needs-verification' }` or `202 { status: 'needs-second-factor', challenge, method }` and the screens show the code form. The `challenge` comes back with the code, so your server knows which sign-in it completes; `method` (`totp`, `email`, `sms`) sets the wording.
- **Reset codes.** For code-based resets, check the code against the given `email` only.

Signed-out session checks should return `200 { user: null }`: a 401 works too, but browsers log every 401 as a console error.

## Cookies or bearer tokens

| | Cookie mode (default) | Bearer mode |
|---|---|---|
| Where the session lives | An httpOnly cookie your server sets; JavaScript can't read it | `accessToken` and `refreshToken` in storage you choose |
| Best for | API on the same site as the app | API on another domain |
| Extra work | A CSRF header on writes (`csrf` option) | Refresh-token rotation and CORS on your server |

In bearer mode, `storage: 'local'` (the default) survives reloads and syncs tabs, `'session'` lasts per tab, and `'memory'` keeps tokens out of web storage at the cost of signing in again after a reload. Rotate refresh tokens on every refresh and revoke the whole token family if an old one is reused; the client never sends two refreshes at once, even across tabs. A separate API origin must answer CORS preflights and allow the `Authorization` header.

## Sessions

- The session is re-checked when the tab regains focus and every 5 minutes (`refreshInterval`), and refreshed shortly before `expiresAt`.
- Signing in or out in one tab updates every other tab.
- `idleTimeout` signs people out after inactivity in all tabs; `IdleWarningDialog` warns them first.
- `fetch` from `useAuth()` sends the session to your API. On a 401 it refreshes once and retries; if that fails, `SessionExpiredDialog` takes over.

```tsx title="src/use-invoices.ts"
import { useAuth } from '@glyphui/auth'
import { useEffect, useState } from 'react'

export function useInvoices() {
  const { fetch } = useAuth()
  const [invoices, setInvoices] = useState<{ id: string; total: number }[]>([])
  useEffect(() => {
    fetch('/api/invoices')
      .then((res) => (res.ok ? res.json() : []))
      .then(setInvoices)
  }, [fetch])
  return invoices
}
```

## Roles and permissions

```tsx title="src/billing-button.tsx"
import { Can, useCan } from '@glyphui/auth'
import { Button } from '@glyphui/ui'

export function BillingButton() {
  const canExport = useCan('invoices:export')
  return (
    <Can permission="billing:manage" fallback={null}>
      <Button disabled={!canExport}>Manage billing</Button>
    </Can>
  )
}
```

`RequireRole` does the same for routes, with a "no access" page by default. These only shape the UI: your API must check the same permissions on every request.

## Firebase and Clerk

- `@glyphui/auth/firebase` wraps Firebase Authentication: email and password, OAuth providers, and the reset and verification emails Firebase sends.
- `@glyphui/auth/clerk` renders `<ClerkAuthBridge>` inside `<ClerkProvider>`, so Glyph's guards, `UserMenu` and dialogs work on a Clerk session. Passkeys, enterprise SSO and CAPTCHA stay with Clerk's own components.

Their pages have setup code: [Firebase](https://glyphui.xyz/components/auth-firebase), [Clerk](https://glyphui.xyz/components/auth-clerk). For prototypes and tests, [`memoryAdapter`](https://glyphui.xyz/components/auth-memory) is a complete backend in the browser.

Live page: https://glyphui.xyz/docs/auth

---

# File viewers

> PDF, CSV, spreadsheets, JSON, code, Markdown, diffs and media.

`@glyphui/viewers` shows files inside your app, themed like the rest of it in light and dark: PDFs, CSV and Excel files, JSON, source code, Markdown, diffs, images, video and audio. Each viewer is its own entry point, and the heavy library behind it is an optional peer dependency, so you only ship what you use.

```sh
npm install @glyphui/viewers
```

```css title="src/index.css"
@import "tailwindcss";
@import "@glyphui/ui/styles.css";
@import "@glyphui/viewers/styles.css";
```

## Pick your viewers

| Import | Shows | Also install |
|---|---|---|
| `@glyphui/viewers/pdf` | `PdfViewer` | `pdfjs-dist` |
| `@glyphui/viewers/csv` | `CsvViewer` | `papaparse @tanstack/react-table@8 @tanstack/react-virtual` |
| `@glyphui/viewers/spreadsheet` | `SpreadsheetViewer` (.xlsx) | `read-excel-file @tanstack/react-table@8 @tanstack/react-virtual` |
| `@glyphui/viewers/json` | `JsonViewer` | Nothing |
| `@glyphui/viewers/code` | `CodeViewer` | `shiki` |
| `@glyphui/viewers/markdown` | `MarkdownViewer` | `react-markdown remark-gfm shiki` |
| `@glyphui/viewers/diff` | `DiffViewer` | `diff` |
| `@glyphui/viewers/media` | `ImageViewer`, `VideoPlayer`, `AudioPlayer`, `Waveform` | Nothing |
| `@glyphui/viewers` | `FilePreview`, `FilePreviewDialog` | The viewers you allow |

Every viewer takes a `source`: a URL, a `File` or `Blob` (for example from `FileUpload`), or bytes. Most also take the content directly (`content`, `code` or `data`).

## PDF

```tsx
import { PdfViewer } from '@glyphui/viewers/pdf'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <PdfViewer source={fixture('report.pdf')} height={560} className="w-full" />
}
```

Live example: https://glyphui.xyz/components/pdf-viewer

`PdfViewer` has page thumbnails, zoom (fit width, fit page or a percentage), rotation, search with highlights, selectable text, download, print and fullscreen. Only pages near the visible area render, so long documents stay fast.

pdf.js parses files in a Web Worker. By default the worker loads from jsDelivr, matching your installed `pdfjs-dist` version, so it works in Vite, webpack and Next.js without setup. To serve the worker from your own site:

```ts title="src/pdf-worker.ts"
import { setPdfWorker } from '@glyphui/viewers/pdf'
import workerSrc from 'pdfjs-dist/build/pdf.worker.min.mjs?url'

// Vite. With webpack 5 or Next.js:
// setPdfWorker(new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url))
setPdfWorker(workerSrc)
```

## CSV and spreadsheets

`CsvViewer` detects the delimiter and header row, infers each column's type (number, date, yes/no or text), and shows the rows in a [DataTable](https://glyphui.xyz/docs/data-tables) with search, filters, column controls and CSV export of the filtered rows. Files of 1 MB or more parse in a worker and render virtualized, so 50,000 rows scroll smoothly.

```tsx
import { CsvViewer } from '@glyphui/viewers/csv'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <CsvViewer source={fixture('customers.csv')} height={420} className="w-full" />
}
```

Live example: https://glyphui.xyz/components/csv-viewer

`SpreadsheetViewer` does the same for `.xlsx` files, with a tab per sheet.

## Any file

`FilePreview` picks the right viewer from a file's type or extension. Images, video, audio, JSON and plain text work without setup; heavier viewers load only if you pass their loader, which keeps the others out of your bundle:

```tsx title="src/attachment.tsx"
import { FilePreview, type ViewerLoaders } from '@glyphui/viewers'

const loaders: ViewerLoaders = {
  pdf: () => import('@glyphui/viewers/pdf'),
  csv: () => import('@glyphui/viewers/csv'),
}

export function Attachment({ file }: { file: File }) {
  return <FilePreview file={file} loaders={loaders} height={560} />
}
```

Files without a matching viewer show their name, size and a download button. `FilePreviewDialog` shows the same preview full-screen, for attachment lists:

```tsx
import { Button, type FileItem, FileUpload } from '@glyphui/ui'
import { FilePreviewDialog, formatBytes, type ViewerLoaders } from '@glyphui/viewers'
import { Eye } from 'lucide-react'
import { useState } from 'react'

const loaders: ViewerLoaders = {
  pdf: () => import('@glyphui/viewers/pdf'),
  csv: () => import('@glyphui/viewers/csv'),
  spreadsheet: () => import('@glyphui/viewers/spreadsheet'),
  code: () => import('@glyphui/viewers/code'),
  markdown: () => import('@glyphui/viewers/markdown'),
}

export default function Example() {
  const [files, setFiles] = useState<FileItem[]>([])
  return (
    <div className="grid w-full max-w-lg gap-4">
      <FileUpload
        files={files}
        onFilesChange={setFiles}
        maxFiles={6}
        hint="Any files. They stay on your device."
      />
      {files.length > 0 && (
        <ul className="grid gap-2">
          {files.map(({ id, file }) => (
            <li
              key={id}
              className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-small"
            >
              <span className="min-w-0 truncate">
                {file.name}{' '}
                <span className="text-muted-foreground">· {formatBytes(file.size)}</span>
              </span>
              <FilePreviewDialog
                file={file}
                loaders={loaders}
                trigger={
                  <Button size="sm" variant="outline" leftIcon={<Eye />}>
                    Preview
                  </Button>
                }
              />
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
```

Live example: https://glyphui.xyz/components/file-preview

## Code, JSON, Markdown and diffs

- `CodeViewer` highlights code with your theme's colors (shiki, loading one language at a time), with line numbers, highlighted lines, wrapping and copy.
- `JsonViewer` is a keyboard-navigable tree with search, expand to any depth, copy a value or its JSONPath, and a raw view. Huge documents stay fast.
- `MarkdownViewer` renders GitHub-flavored Markdown with your theme's typography. It's safe by default: raw HTML isn't rendered, and `javascript:` links are removed.
- `DiffViewer` shows changes unified or side by side, with changed words highlighted and unchanged lines folded. Line-ending differences between operating systems are ignored.

```tsx
import { JsonViewer } from '@glyphui/viewers/json'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <JsonViewer source={fixture('workspace.json')} label="workspace.json" className="w-full" />
}
```

Live example: https://glyphui.xyz/components/json-viewer

## Images and media

`ImageViewer` zooms with the wheel, pinch or buttons, pans by dragging, and rotates. `VideoPlayer` and `AudioPlayer` replace the browser's controls with themed ones: scrubbing with the buffered range, speed, captions, fullscreen and keyboard shortcuts. `Waveform` draws an audio file you can seek on.

## Bundle size

Each viewer's own code is under 9 kB gzipped. The libraries behind them aren't: pdf.js alone is about 130 kB plus its worker. Load viewers where they're used, with `FilePreview` loaders or `React.lazy`, rather than in your app's entry.

Live page: https://glyphui.xyz/docs/viewers

---

# Accessibility

> What Glyph handles for you, and what each app still has to do.

Glyph's interactive components are built on [Radix UI](https://www.radix-ui.com) primitives, which follow the WAI-ARIA authoring practices for keyboard support, focus and screen readers. Glyph adds the parts Radix leaves to you: labels and errors wired to fields, contrast-checked themes, visible focus, and motion that respects user settings. Every docs page is tested with [axe](https://github.com/dequelabs/axe-core) in light and dark mode.

## What Glyph does

- **Keyboard.** Menus, selects, comboboxes, tabs, dialogs, date pickers, sliders, the data table's headers and filters, the tree view and the calendar heatmap all work without a mouse. Dialogs and sheets trap focus and return it when they close.
- **Focus.** Every interactive element has a visible focus ring drawn from the theme's `ring` color, including in themes that remove shadows.
- **Labels.** Inside a `Field`, inputs get their label, description and error through `aria-labelledby`, `aria-describedby` and `aria-invalid`, so screen readers read all three.
- **Contrast.** Every preset passes WCAG AA, and `defineTheme` derives readable text colors when you change a brand color. In development, the provider warns when your theme fails; see [Check contrast](https://glyphui.xyz/docs/theming#check-contrast).
- **Announcements.** Toasts are announced politely; danger and warning alerts immediately. Charts include a visually hidden data table, so screen-reader users get the numbers.
- **Motion.** Visitors who ask their system for reduced motion get none. See [Motion](https://glyphui.xyz/docs/motion#reduced-motion).

## What your app still has to do

- **Name icon-only buttons.** `IconButton` requires an `aria-label`, and TypeScript enforces it. Do the same for links that only contain an icon.
- **Label every field.** Use `Field` or `FormField` with a `label`, or give the control an `aria-label`. A placeholder isn't a label.
- **Write alt text.** Describe images that carry meaning; pass `alt=""` for decorative ones.
- **Keep one `h1` per page** and don't skip heading levels. `Heading` separates the level from the visual size: `<Heading level={2} size="h4">`.
- **Don't rely on color alone.** Pair status colors with text or an icon, as Glyph's badges and alerts do.
- **Name your tables.** Pass `aria-label` to `DataTable` so screen-reader users know which table they're in.
- **Enforce permissions on the server.** Hiding a button with `Can` isn't access control.

## Test with axe

Run axe in your end-to-end tests to catch regressions. With Playwright:

```sh
npm install -D @playwright/test @axe-core/playwright
```

```ts title="e2e/a11y.spec.ts"
import AxeBuilder from '@axe-core/playwright'
import { expect, test } from '@playwright/test'

for (const path of ['/', '/app', '/app/settings']) {
  test(`${path} has no accessibility violations`, async ({ page }) => {
    await page.goto(path)
    const results = await new AxeBuilder({ page })
      .withTags(['wcag2a', 'wcag2aa', 'wcag21aa'])
      .analyze()
    expect(results.violations).toEqual([])
  })
}
```

Check both color modes and any open overlays (menus, dialogs), since they add content to the page.

## Keyboard checklist

Automated checks catch about a third of accessibility problems. Before a release, go through your main flows with the keyboard only:

1. Tab reaches every control, in a sensible order, and the focus ring is always visible.
2. Enter and Space activate buttons; arrow keys move within menus, tabs, radio groups and lists.
3. Escape closes dialogs, menus and popovers, and focus returns to what opened them.
4. Forms can be filled and submitted, and errors are reachable and read out.
5. Nothing traps focus except an open dialog.

Then try a screen reader (VoiceOver on macOS, NVDA on Windows) on the same flows.

Live page: https://glyphui.xyz/docs/accessibility

---

# Testing your app

> Unit and end-to-end tests for screens built with Glyph.

Glyph components are ordinary React components with accessible roles and names, so you test them the way users find them: by role, label and text. This guide covers [Vitest](https://vitest.dev) with Testing Library for components, and [Playwright](https://playwright.dev) for whole flows.

## Unit tests

```sh
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
```

Render screens inside a `GlyphProvider`, as your app does. Two props make tests faster and steadier: `motion="none"` turns animation off, and `storageKey={null}` keeps the color mode out of `localStorage`.

```tsx title="src/test/render.tsx"
import { GlyphProvider } from '@glyphui/ui'
import { render } from '@testing-library/react'
import type { ReactElement } from 'react'

export function renderWithGlyph(ui: ReactElement) {
  return render(
    <GlyphProvider motion="none" storageKey={null}>
      {ui}
    </GlyphProvider>,
  )
}
```

jsdom lacks a few browser APIs that Radix and Glyph use. Stub them once in your setup file:

```ts title="src/test/setup.ts"
import '@testing-library/jest-dom/vitest'

window.matchMedia ??= (query: string) =>
  ({
    matches: false,
    media: query,
    onchange: null,
    addEventListener: () => {},
    removeEventListener: () => {},
    addListener: () => {},
    removeListener: () => {},
    dispatchEvent: () => false,
  }) as MediaQueryList
window.HTMLElement.prototype.scrollIntoView ??= () => {}
window.HTMLElement.prototype.hasPointerCapture ??= () => false
window.HTMLElement.prototype.releasePointerCapture ??= () => {}
globalThis.ResizeObserver ??= class {
  observe() {}
  unobserve() {}
  disconnect() {}
}
```

```ts title="vitest.config.ts"
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: { environment: 'jsdom', setupFiles: ['./src/test/setup.ts'] },
})
```

Then test behavior, not markup. Use `userEvent` rather than `fireEvent`, so focus and pointer events happen in the order a browser sends them:

```tsx title="src/delete-button.test.tsx"
import { Button, useConfirm } from '@glyphui/ui'
import { screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, it, vi } from 'vitest'
import { renderWithGlyph } from './test/render'

function DeleteButton({ onDelete }: { onDelete: () => void }) {
  const confirm = useConfirm()
  return (
    <Button
      onClick={async () => {
        if (await confirm({ title: 'Delete project?', tone: 'danger' })) onDelete()
      }}
    >
      Delete
    </Button>
  )
}

it('deletes only after confirming', async () => {
  const onDelete = vi.fn()
  renderWithGlyph(<DeleteButton onDelete={onDelete} />)
  await userEvent.click(screen.getByRole('button', { name: 'Delete' }))
  // The confirm dialog loads on first use, so find it rather than get it.
  const dialog = await screen.findByRole('alertdialog', { name: 'Delete project?' })
  await userEvent.click(within(dialog).getByRole('button', { name: 'Delete' }))
  expect(onDelete).toHaveBeenCalledOnce()
})
```

Overlays (dialogs, menus, selects, toasts) render at the end of `document.body`, so query them through `screen`, not the container your component rendered into.

## Forms

Test what users see: fill fields by label, submit, and look for the message.

```tsx title="src/signup-form.test.tsx"
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, it } from 'vitest'
import { SignupForm } from './signup-form'
import { renderWithGlyph } from './test/render'

it('shows a field error for an invalid email', async () => {
  renderWithGlyph(<SignupForm />)
  await userEvent.type(screen.getByRole('textbox', { name: /email/i }), 'not-an-email')
  await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
  expect(await screen.findByText('Enter a valid email address')).toBeInTheDocument()
})
```

## End-to-end tests

Playwright runs your built app in real browsers. A few things specific to apps built with Glyph and React Router:

- **Wait for content, not URLs.** React Router 7 renders the next page in a transition, so the URL changes a moment before the page does. Typing right after `toHaveURL` can land in the previous page's field.
- **Find overlays by role.** Menus are `menu`, dialogs `dialog`, confirmations `alertdialog`. Find toasts by their text.
- **Turn motion off for screenshots.** Use `reducedMotion: 'reduce'` in the Playwright config; Glyph then skips every animation.

```ts title="e2e/invoices.spec.ts"
import { expect, test } from '@playwright/test'

test('creates an invoice', async ({ page }) => {
  await page.goto('/app')
  await page.getByRole('link', { name: 'Invoices' }).click()
  // The page itself, not just its URL, before interacting.
  await expect(page.getByRole('heading', { name: 'Invoices' })).toBeVisible()

  await page.getByRole('button', { name: 'New invoice' }).click()
  const dialog = page.getByRole('dialog', { name: 'New invoice' })
  await dialog.getByRole('spinbutton', { name: 'Amount' }).fill('1250')
  await dialog.getByRole('button', { name: 'Create invoice' }).click()

  await expect(page.getByText('Invoice created')).toBeVisible()
  await expect(dialog).toBeHidden()
})
```

Add axe checks to the same suite; [Accessibility](https://glyphui.xyz/docs/accessibility#test-with-axe) has the setup.

Live page: https://glyphui.xyz/docs/testing

---

# Upgrading

> Breaking changes and how to move between versions.

Glyph is in its 0.x series: minor versions (0.7 → 0.8) can change behavior, and this page lists every change you may need to act on. Patch versions only fix bugs. The [changelog](https://glyphui.xyz/changelog) has the full release notes.

## Keep packages in step

Every `@glyphui/*` package is released together under one version number. Upgrade them together:

```sh
npm install @glyphui/ui@latest @glyphui/blocks@latest @glyphui/auth@latest @glyphui/viewers@latest
```

## 0.8

**Peer dependencies.** `@glyphui/auth`, `@glyphui/blocks` and `@glyphui/viewers` now take `@glyphui/ui` (and `blocks`, `tokens`) as peer dependencies, so your app and Glyph share one copy. Install `@glyphui/ui` yourself if you only listed `blocks` or `auth`. Before, a version mismatch installed a second copy and components such as `UserMenu` crashed with "must be used inside GlyphProvider".

**Menus are non-modal.** `DropdownMenu` and `ContextMenu` no longer hide the rest of the page from screen readers while open; focus still moves into the menu, and Escape or an outside click closes it. Pass `modal` for the old behavior.

**Password reset by code sends the email.** `ForgotPasswordForm` and `ResetPasswordForm` now send `{ email }` with the code. Update your server to check the code against that account only, not on its own.

**Bearer sign-out sends the refresh token** (`{ refreshToken }`), so your server can revoke it. A `401` or `403` from sign-out counts as already signed out.

**Number inputs report while typing.** `NumberInput` calls `onValueChange` as you type a valid number, not only on blur. Rounding and clamping to `min` and `max` still happen on blur.

**StaggerItem's `index` is optional.** Items follow document order; existing `index` props keep working.

New: `@glyphui/viewers`, `completeMagicLink` and `MagicLinkCallback`, `SignUpForm` `extraFields`, `AuthRevalidator`, `tableSearch()`, and contrast-safe foregrounds in `defineTheme`.

## 0.7

New package: `@glyphui/auth`. No changes needed in existing code.

## 0.6

DataTable v2 is a drop-in for the 0.5 API. Two things to know:

- TanStack Table must be version 8: install `@tanstack/react-table@8`. Version 9 is a rewrite and isn't supported yet.
- Pass `getRowId` if you haven't: selections now survive data changes, which needs stable row ids.

## 0.5

**Motion is on by default.** Overlays, indicators and blocks animate. To keep 0.4's stillness, set `motion: { level: 'none' }` in your theme or `motion="none"` on `GlyphProvider`; visitors with reduced motion get none either way.

**One file per module.** `@glyphui/ui` is published as separate modules, so bundlers keep only what you import. No code changes, but deep imports of internal chunk files (never supported) no longer resolve.

## 0.4

- Connect your router with `<GlyphProvider router={reactRouter}>` from `@glyphui/ui/react-router`. `linkComponent` still works but doesn't mark active items.
- `FormSubmit` outside `<Form>` needs `form={form}`; it used to crash.
- Load Geist with `@import "@glyphui/ui/fonts.css"` if you use the default theme; it was never loaded for you.
- Import `@glyphui/blocks/styles.css` if you use blocks; without it they render partly unstyled.

Live page: https://glyphui.xyz/docs/migration

---

# Accordion

> Stacked sections that expand one at a time or independently. Good for FAQs and dense settings.

Status: beta. Category: Data display.

```ts
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@glyphui/ui'
```

Exports: `Accordion`, `AccordionItem`, `AccordionTrigger`, `AccordionContent`, `accordionStyles`.

## Notes

- Triggers are buttons inside headings, with aria-expanded and arrow-key navigation between them.
- Opening fades the content in; it respects reduced-motion settings.

## Example: FAQ

type="single" collapsible: one section open at a time.

```tsx
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@glyphui/ui'

const faq = [
  { q: 'Is Glyph free?', a: 'Yes. Both packages are MIT licensed and published on npm.' },
  {
    q: 'Does it work without Tailwind?',
    a: 'No. Glyph is built on Tailwind CSS v4 and ships a stylesheet that maps theme tokens to utilities.',
  },
  {
    q: 'Can I use my own fonts?',
    a: 'Set font.sans, font.display and font.mono in your theme file and load the fonts in your app.',
  },
]

export default function Example() {
  return (
    <Accordion type="single" collapsible defaultValue="item-0" className="max-w-xl">
      {faq.map((item, i) => (
        <AccordionItem key={item.q} value={`item-${i}`}>
          <AccordionTrigger>{item.q}</AccordionTrigger>
          <AccordionContent>{item.a}</AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  )
}
```

## Example: Separated cards

variant="separated" with type="multiple".

```tsx
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Switch } from '@glyphui/ui'

export default function Example() {
  return (
    <Accordion type="multiple" variant="separated" className="max-w-xl">
      <AccordionItem value="notifications">
        <AccordionTrigger>Notifications</AccordionTrigger>
        <AccordionContent className="flex items-center justify-between gap-4">
          Email me when I'm mentioned
          <Switch defaultChecked aria-label="Email me when I'm mentioned" />
        </AccordionContent>
      </AccordionItem>
      <AccordionItem value="privacy">
        <AccordionTrigger>Privacy</AccordionTrigger>
        <AccordionContent>
          Your profile is visible to members of your workspace only.
        </AccordionContent>
      </AccordionItem>
    </Accordion>
  )
}
```

Live page: https://glyphui.xyz/components/accordion

---

# Alert

> An inline message about the content around it, in five tones, with optional actions and dismissal.

Status: beta. Category: Feedback.

```ts
import { Alert } from '@glyphui/ui'
```

Exports: `Alert`, `alertStyles`.

## Notes

- Danger and warning alerts use role="alert" and are announced immediately; other tones use role="status".
- For page-wide announcements use Banner; for messages that disappear on their own use a toast.

## Example: Tones

```tsx
import { Alert } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3">
      <Alert title="Heads up">Workspace settings now live under your profile.</Alert>
      <Alert tone="info" title="Scheduled maintenance">
        The API will be read-only on Sunday from 02:00 to 03:00 UTC.
      </Alert>
      <Alert tone="success" title="Domain verified">
        acme.dev now serves your workspace.
      </Alert>
      <Alert tone="warning" title="Trial ends in 3 days">
        Add a payment method to keep your projects.
      </Alert>
      <Alert tone="danger" title="Payment failed">
        Your card was declined. Update it to avoid losing access.
      </Alert>
    </div>
  )
}
```

## Example: Actions and dismiss

Pass onDismiss to show a close button.

```tsx
import { Alert, Button } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(true)
  if (!open) {
    return (
      <Button variant="outline" onClick={() => setOpen(true)}>
        Show alert again
      </Button>
    )
  }
  return (
    <Alert
      tone="info"
      title="A new version is available"
      action={
        <Button size="sm" variant="outline">
          Update
        </Button>
      }
      onDismiss={() => setOpen(false)}
    >
      Version 2.4 adds keyboard shortcuts.
    </Alert>
  )
}
```

## Example: Outline

```tsx
import { Alert } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3">
      <Alert variant="outline" tone="success" title="Backup complete">
        12,481 files saved at 09:41.
      </Alert>
      <Alert variant="outline" tone="danger" title="Build failed" icon={false}>
        3 type errors in <code>src/app.tsx</code>.
      </Alert>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/alert

---

# Alert Dialog

> Interrupts to ask for a decision, such as confirming a destructive action. useConfirm() turns it into one awaited line.

Status: beta. Category: Overlays.

```ts
import { AlertDialog, AlertDialogTrigger, AlertDialogContent, AlertDialogHeader, AlertDialogTitle, AlertDialogDescription } from '@glyphui/ui'
```

Exports: `AlertDialog`, `AlertDialogTrigger`, `AlertDialogContent`, `AlertDialogHeader`, `AlertDialogTitle`, `AlertDialogDescription`, `AlertDialogFooter`, `AlertDialogCancel`, `AlertDialogAction`, `alertDialogStyles`, `ConfirmProvider`, `useConfirm`.

## Notes

- Cancel receives focus when it opens, so pressing Enter never confirms by accident.
- Clicking the backdrop does not close it; the user has to choose.
- Mount ConfirmProvider once near the root to use useConfirm() anywhere below it.

## Example: useConfirm

Resolves true when confirmed, false when cancelled or dismissed.

```tsx
import { Button, ConfirmProvider, toast, useConfirm } from '@glyphui/ui'

function DeleteProjectButton() {
  const confirm = useConfirm()

  async function handleDelete() {
    const confirmed = await confirm({
      title: 'Delete “Website redesign”?',
      description: 'Its 48 issues and all comments are deleted. This can’t be undone.',
      tone: 'danger',
    })
    if (confirmed) toast.success('Project deleted')
  }

  return (
    <Button variant="danger" onClick={handleDelete}>
      Delete project
    </Button>
  )
}

// Mount ConfirmProvider once at the root of your app.
export default function Example() {
  return (
    <ConfirmProvider>
      <DeleteProjectButton />
    </ConfirmProvider>
  )
}
```

## Example: Composed

Build the dialog yourself when it needs custom content.

```tsx
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
  Button,
} from '@glyphui/ui'

export default function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <Button variant="outline">Leave page</Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Discard unsaved changes?</AlertDialogTitle>
          <AlertDialogDescription>
            You edited 3 fields. Leaving now discards those edits.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Keep editing</AlertDialogCancel>
          <AlertDialogAction tone="danger">Discard changes</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
```

Live page: https://glyphui.xyz/components/alert-dialog

---

# AppShell

> App layout with a sidebar and main area: desktop collapse to an icon rail, a mobile drawer, and a mobile top bar.

Status: stable. Category: Patterns.

```ts
import { AppShell } from '@glyphui/ui'
```

Exports: `AppShell`, `useAppShell`, `appShellStyles`.

## Notes

- The mobile drawer traps focus and closes when a SidebarItem is chosen.
- useAppShell exposes collapsed and mobileOpen state to your own components.

## AppShell props

| Prop | Type | Default | Description |
|---|---|---|---|
| `sidebar` (required) | `ReactNode` |  | A `<Sidebar>`. Shown fixed on desktop and in a drawer on mobile. |
| `collapsed` | `boolean` |  |  |
| `defaultCollapsed` | `boolean` |  |  |
| `layout` | `"page" \| "embedded"` |  |  |
| `mobileBrand` | `ReactNode` |  | Shown next to the menu button in the mobile top bar. |
| `onCollapsedChange` | `((collapsed: boolean) => void)` |  |  |

## Example: Embedded layout

layout="page" fills the viewport; "embedded" fills its parent.

```tsx
import {
  AppShell,
  PageHeader,
  Sidebar,
  SidebarContent,
  SidebarHeader,
  SidebarItem,
  SidebarTrigger,
  Text,
} from '@glyphui/ui'
import { CircleDot, Inbox, SquareKanban } from 'lucide-react'

export default function Example() {
  return (
    <div className="h-96 overflow-hidden rounded-lg border border-border">
      <AppShell
        layout="embedded"
        mobileBrand={<span className="text-small font-semibold">Acme</span>}
        sidebar={
          <Sidebar>
            <SidebarHeader>
              <span className="truncate text-small font-semibold">Acme Inc.</span>
            </SidebarHeader>
            <SidebarContent>
              <SidebarItem icon={<Inbox />} badge={3}>
                Inbox
              </SidebarItem>
              <SidebarItem icon={<CircleDot />} active>
                Issues
              </SidebarItem>
              <SidebarItem icon={<SquareKanban />}>Projects</SidebarItem>
            </SidebarContent>
          </Sidebar>
        }
      >
        <div className="grid gap-4 p-5">
          <div className="hidden md:block">
            <SidebarTrigger />
          </div>
          <PageHeader title="Issues" description="12 open, 3 due this week." />
          <Text tone="muted">Your page content goes here.</Text>
        </div>
      </AppShell>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/app-shell

---

# AspectRatio

> Keeps images, video and embeds at a fixed width-to-height ratio so layouts do not shift while loading.

Status: beta. Category: Layout.

```ts
import { AspectRatio } from '@glyphui/ui'
```

Exports: `AspectRatio`, `aspectRatioStyles`.

## Example: Ratios

placeholder fills the box while media loads.

```tsx
import { AspectRatio, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-2xl gap-4 sm:grid-cols-2">
      {[
        { ratio: 16 / 9, label: '16 : 9' },
        { ratio: 1, label: '1 : 1' },
      ].map(({ ratio, label }) => (
        <div key={label} className="grid gap-2">
          <AspectRatio ratio={ratio} rounded placeholder>
            <div className="flex size-full items-center justify-center bg-gradient-to-br from-primary/25 to-transparent">
              <span className="font-display text-h3">{label}</span>
            </div>
          </AspectRatio>
          <Text size="small" tone="muted">
            ratio={'{'}
            {label.replace(' : ', ' / ')}
            {'}'}
          </Text>
        </div>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/aspect-ratio

---

# Async

> One convention for loading, error, empty and ready states. Works with TanStack Query results or useAsync.

Status: stable. Category: Patterns.

```ts
import { Async, EmptyState, ErrorState, LoadingState } from '@glyphui/ui'
```

Exports: `Async`, `useAsync`, `EmptyState`, `ErrorState`, `LoadingState`, `stateStyles`.

## Notes

- Any object with status, data, error and refetch works, including useQuery() results.
- ErrorState has role="alert"; LoadingState has role="status".

## Async props

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` (required) | `(data: NonNullable<T>) => ReactNode` |  | Rendered once data is ready and not empty. |
| `result` (required) | `AsyncResult<T>` |  |  |
| `empty` | `ReactNode` |  |  |
| `error` | `ReactNode \| ((error: unknown, retry: (() => unknown)) => ReactNode)` |  |  |
| `isEmpty` | `((data: NonNullable<T>) => boolean)` | `(data: unknown) => Array.isArray(data) && data.length === 0` | Treat ready data as empty. Defaults to: an empty array. |
| `loading` | `ReactNode` |  |  |

## Example: With useAsync

```tsx
import { Async, Button, useAsync } from '@glyphui/ui'
import { useState } from 'react'

const projects = ['Website redesign', 'Billing v2', 'Mobile onboarding']

function fetchProjects(fail: boolean): Promise<string[]> {
  return new Promise((resolve, reject) =>
    setTimeout(
      () => (fail ? reject(new Error('The projects service timed out.')) : resolve(projects)),
      900,
    ),
  )
}

export default function Example() {
  const [fail, setFail] = useState(false)
  const result = useAsync(() => fetchProjects(fail), [fail])
  return (
    <div className="grid gap-3">
      <Button
        variant="outline"
        size="sm"
        className="justify-self-start"
        onClick={() => setFail((f) => !f)}
      >
        {fail ? 'Load successfully' : 'Simulate an error'}
      </Button>
      <Async result={result}>
        {(items) => (
          <ul className="grid gap-1 text-small">
            {items.map((name) => (
              <li key={name}>{name}</li>
            ))}
          </ul>
        )}
      </Async>
    </div>
  )
}
```

## Example: State components

Use them directly anywhere a screen can be empty or fail.

```tsx
import { Button, EmptyState, ErrorState, LoadingState } from '@glyphui/ui'
import { FolderPlus } from 'lucide-react'

export default function Example() {
  return (
    <div className="grid gap-4 sm:grid-cols-3">
      <EmptyState
        icon={<FolderPlus />}
        title="No projects yet"
        description="Create a project to start tracking work."
        action={<Button size="sm">New project</Button>}
      />
      <ErrorState error={new Error('Network request failed.')} onRetry={() => {}} />
      <LoadingState label="Loading projects…" />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/async

---

# AudioPlayer

> Audio with a waveform you can click to seek, plus play, time, volume and speed controls.

Status: beta. Category: Viewers.

```ts
import { AudioPlayer, Waveform } from '@glyphui/viewers/media'
```

Exports: `AudioPlayer`, `audioPlayerStyles`, `Waveform`, `waveformStyles`, `computePeaks`.

## Notes

- No extra packages needed. Waveforms decode the file with the Web Audio API; pass peaks to skip that.
- The waveform is a slider: click or drag to seek, or use the arrow keys.

## AudioPlayer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `source` (required) | `ViewerSource` |  | The audio: a URL, a File/Blob, or bytes. |
| `artwork` | `ReactNode` |  | Cover art. |
| `bordered` | `boolean` |  | Draw the player as a bordered card. Default true. |
| `className` | `string` |  |  |
| `description` | `ReactNode` |  | A second line, e.g. the artist or a date. |
| `loop` | `boolean` |  |  |
| `peaks` | `readonly number[]` |  | Precomputed peaks for the waveform, instead of decoding the file. |
| `title` | `string` |  | Title shown above the controls. Defaults to the file name. |
| `waveform` | `boolean` |  | Draw a waveform you can click to seek. Default true. |

## Example: Voice note

The waveform is decoded in the browser.

```tsx
import { AudioPlayer } from '@glyphui/viewers/media'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return (
    <AudioPlayer
      source={fixture('chime.wav')}
      title="Standup notes"
      description="Recorded Oct 17 · 6 seconds"
      className="w-full max-w-lg"
    />
  )
}
```

## Example: Waveform alone

Precomputed peaks, e.g. from your server, with your own playback state.

```tsx
import { Waveform } from '@glyphui/viewers/media'
import { useState } from 'react'

const peaks = Array.from(
  { length: 80 },
  (_, i) => 0.25 + 0.75 * Math.abs(Math.sin(i / 6)) * (1 - i / 120),
)

export default function Example() {
  const [time, setTime] = useState(12)
  return (
    <div className="grid w-full max-w-lg gap-2 text-primary">
      <Waveform
        peaks={peaks}
        currentTime={time}
        duration={40}
        onSeek={setTime}
        label="Call recording position"
      />
      <span className="text-caption text-muted-foreground tabular-nums">
        {Math.round(time)}s of 40s
      </span>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/audio-player

---

# Auth provider

> Session state for the whole app: who is signed in, their roles and permissions, and every sign-in action, from any backend.

Status: beta. Category: Auth.

```ts
import { AuthProvider, Can, AuthError, NEXT_PARAM } from '@glyphui/auth'
```

Exports: `AuthProvider`, `useAuth`, `useUser`, `useSession`, `useCan`, `useHasRole`, `Can`, `useAuthClient`, `createAuthClient`, `AuthError`, `isAuthError`, `can`, `hasRole`, `NEXT_PARAM`, `safeRedirectPath`, `signInPathFor`.

## Notes

- Status is loading until the adapter answers, then authenticated or unauthenticated. Guards show a spinner while loading.
- The session is re-checked when the tab regains focus and every 5 minutes (refreshInterval), and refreshed just before expiresAt.
- Signing in or out in one tab updates every other tab (syncTabs). Pass a name when two apps share an origin.
- idleTimeout signs users out after inactivity; IdleWarningDialog warns them first.
- Can and RequireRole only shape the UI. Your API must check the same permissions.
- Adapter errors are AuthError instances; fieldErrors holds messages for individual form fields.

## AuthProvider props

| Prop | Type | Default | Description |
|---|---|---|---|
| `adapter` | `AuthAdapter` |  | An adapter; the provider creates the client. Use `client` when loaders need it. |
| `client` | `AuthClient` |  | A client from `createAuthClient`, shared with route loaders. |
| `idleTimeout` | `number` |  | Sign the user out after this long without activity (ms). Off by default. |
| `idleWarning` | `number` |  | How long before the idle sign-out to warn (ms). Default 60 seconds. |
| `onSignOut` | `((reason: SignOutReason) => void)` |  | Called after any sign-out, with why it happened. |
| `refreshInterval` | `number \| false` |  | Re-check the session this often while the tab is open. Default 5 minutes; `false` to disable. |
| `refreshOnFocus` | `boolean` |  | Re-check the session when the tab regains focus. Default true. |
| `syncTabs` | `string \| boolean` |  | Keep tabs in sync: signing in or out in one tab updates the others. Pass a string to name the channel (useful when two apps share an origin). Default true. |

## Example: Session state

useAuth() gives the status, the user and every action. This demo uses the in-memory adapter.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { Avatar, Badge, Button, Card, Text } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 400,
  users: [{ email: 'ada@example.com', password: 'correct horse', name: 'Ada Lovelace' }],
})

function SessionCard() {
  const { status, user, signIn, signOut } = useAuth()
  return (
    <Card className="w-full max-w-sm gap-4">
      <div className="flex items-center justify-between gap-3">
        <Text weight="medium">Session</Text>
        <Badge tone={status === 'authenticated' ? 'success' : 'neutral'} dot>
          {status}
        </Badge>
      </div>
      {user ? (
        <div className="flex items-center gap-3">
          <Avatar name={user.name ?? user.email} />
          <div className="grid">
            <Text weight="medium">{user.name}</Text>
            <Text size="small" tone="muted">
              {user.email}
            </Text>
          </div>
        </div>
      ) : (
        <Text size="small" tone="muted">
          Nobody is signed in.
        </Text>
      )}
      {user ? (
        <Button variant="outline" onClick={() => signOut()}>
          Sign out
        </Button>
      ) : (
        <Button
          disabled={status === 'loading'}
          onClick={() => signIn({ email: 'ada@example.com', password: 'correct horse' })}
        >
          Sign in as Ada
        </Button>
      )}
    </Card>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SessionCard />
    </AuthProvider>
  )
}
```

## Example: Roles and permissions

Can and useCan read permissions such as invoices:write; invoices:* is a wildcard.

```tsx
import { AuthProvider, Can, useAuth, useCan } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { Button, Card, SegmentedControl, Text } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 0,
  users: [
    {
      email: 'owner@acme.dev',
      password: 'pw',
      name: 'Owner',
      permissions: ['invoices:*', 'billing:manage'],
    },
    { email: 'viewer@acme.dev', password: 'pw', name: 'Viewer', permissions: ['invoices:read'] },
  ],
})

function Invoices() {
  const { user, signIn } = useAuth()
  const canEdit = useCan('invoices:write')
  return (
    <Card className="w-full max-w-md gap-4">
      <SegmentedControl
        aria-label="Signed in as"
        value={user?.email ?? ''}
        onValueChange={(email) => signIn({ email, password: 'pw' })}
        options={[
          { value: 'owner@acme.dev', label: 'Owner' },
          { value: 'viewer@acme.dev', label: 'Viewer' },
        ]}
      />
      <Text size="small" tone="muted">
        {user ? `${user.name} can ${canEdit ? 'edit' : 'only read'} invoices.` : 'Pick a user.'}
      </Text>
      <div className="flex flex-wrap gap-2">
        <Button variant="outline" disabled={!canEdit}>
          Edit invoice
        </Button>
        <Can permission="billing:manage" fallback={<Button disabled>Billing (owners only)</Button>}>
          <Button>Manage billing</Button>
        </Can>
      </div>
    </Card>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Invoices />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/auth

---

# AuthCard

> Sign-in or sign-up card with a ready email and password form, social buttons and a footer link.

Status: beta. Category: Blocks.

```ts
import { AuthCard } from '@glyphui/blocks'
```

Exports: `AuthCard`.

## Notes

- The built-in form validates email and password before calling onSubmit; throw to show a form-level error.
- Pass children to replace the built-in form with your own fields, for example a Form from @glyphui/ui/form.

## AuthCard props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  |  |
| `children` | `ReactNode` |  | Replaces the built-in form with your own fields. |
| `description` | `ReactNode` |  |  |
| `dividerLabel` | `ReactNode` | `or` | Label of the divider between social buttons and the form. |
| `footer` | `ReactNode` |  | Bottom line, e.g. "Don't have an account? Sign up". |
| `headingLevel` | `HeadingLevel` | `1` |  |
| `mode` | `"sign-in" \| "sign-up"` | `sign-in` | `sign-in` uses current-password autocomplete; `sign-up` uses new-password and a minimum length. |
| `onSubmit` | `((credentials: AuthCredentials) => void \| Promise<void>)` |  | Built-in email + password form. Throw to show the error's message above the form. |
| `passwordHint` | `ReactNode` |  | Shown beside the password label, e.g. a "Forgot password?" link. |
| `social` | `ReactNode` |  | Social sign-in buttons, shown above the form with a divider. |
| `submitLabel` | `ReactNode` |  |  |

## Example: Sign in

Use any email and the password “wrong” to see the error state.

```tsx
import { AuthCard } from '@glyphui/blocks'
import { Link } from '@glyphui/ui'

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  return (
    <AuthCard
      title="Welcome back"
      description="Sign in to your Ledgerline workspace."
      headingLevel={2}
      passwordHint={<Link href="#reset">Forgot password?</Link>}
      onSubmit={async ({ password }) => {
        await wait(700)
        if (password === 'wrong') throw new Error('That email and password don’t match.')
      }}
      footer={
        <>
          New here? <Link href="#signup">Create an account</Link>
        </>
      }
    />
  )
}
```

## Example: Sign up with social buttons

```tsx
import { AuthCard } from '@glyphui/blocks'
import { Button, Link } from '@glyphui/ui'
import { Github } from 'lucide-react'

export default function Example() {
  return (
    <AuthCard
      mode="sign-up"
      title="Create your account"
      description="Free for 14 days. No credit card required."
      headingLevel={2}
      social={
        <Button variant="outline" fullWidth leftIcon={<Github />}>
          Continue with GitHub
        </Button>
      }
      dividerLabel="or with email"
      onSubmit={() => new Promise((resolve) => setTimeout(resolve, 700))}
      footer={
        <>
          Already have an account? <Link href="#signin">Sign in</Link>
        </>
      }
    />
  )
}
```

Live page: https://glyphui.xyz/components/auth-card

---

# AuthLayout

> A full-page frame for auth screens: the form on one half, a brand panel on the other; the panel hides on mobile.

Status: beta. Category: Auth.

```ts
import { AuthLayout, AuthNotice } from '@glyphui/auth/ui'
```

Exports: `AuthLayout`, `AuthNotice`, `authLayoutStyles`, `authNoticeStyles`.

## Notes

- The panel gets a soft glow in your theme’s primary color; put a testimonial, product shot or illustration in it.
- AuthNotice is the confirmation card the screens use ("Check your email", "Password updated"); use it for your own steps.
- side="left" puts the panel first on large screens.

## AuthLayout props

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` (required) | `ReactNode` |  | The screen: SignInForm, SignUpForm, ... |
| `aside` | `ReactNode` |  | The side panel on large screens: a testimonial, product shot or brand art. Hidden on mobile. |
| `brand` | `ReactNode` |  | Logo or product name, top left. |
| `className` | `string` |  |  |
| `footer` | `ReactNode` |  | Small print under the form: legal links, copyright. |
| `side` | `"left" \| "right"` |  | Which side the panel sits on. Default right. |

## Example: Split screen

Shown in a frame here; in an app it fills the page.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { AuthLayout, SignInForm } from '@glyphui/auth/ui'
import { Text } from '@glyphui/ui'

const adapter = memoryAdapter({ latency: 400, oauthProviders: [] })

export default function Example() {
  return (
    <div className="w-full overflow-hidden rounded-lg border border-border [&_[data-slot=auth-layout]]:min-h-[34rem]">
      <AuthProvider adapter={adapter} syncTabs={false}>
        <AuthLayout
          brand="Ledgerline"
          footer="© 2026 Ledgerline, Inc."
          aside={
            <figure className="grid max-w-sm gap-3">
              <blockquote className="font-display text-h4 text-balance">
                “We closed the books two days faster the first month.”
              </blockquote>
              <Text size="small" tone="muted">
                Priya Raman, Controller at Northwind
              </Text>
            </figure>
          }
        >
          <SignInForm headingLevel={3} magicLink={false} />
        </AuthLayout>
      </AuthProvider>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/auth-layout

---

# Avatar

> A person or team image with an initials fallback in a stable color per name.

Status: stable. Category: Data display.

```ts
import { Avatar, AvatarGroup } from '@glyphui/ui'
```

Exports: `Avatar`, `AvatarGroup`, `avatarStyles`.

## Notes

- The name is used for the image alt text and the initials, so it is required.

## Avatar props

| Prop | Type | Default | Description |
|---|---|---|---|
| `name` (required) | `string` |  | Used for the image alt text and the initials fallback. |
| `asChild` | `boolean` |  |  |
| `size` | `"sm" \| "md" \| "lg" \| "xs"` |  |  |
| `src` | `string` |  |  |

## Example: Sizes

```tsx
import { Avatar } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-3">
      <Avatar name="Ada Lovelace" size="xs" />
      <Avatar name="Ada Lovelace" size="sm" />
      <Avatar name="Ada Lovelace" size="md" />
      <Avatar name="Ada Lovelace" size="lg" />
    </div>
  )
}
```

## Example: With an image

Falls back to initials while loading or if the image fails.

```tsx
import { Avatar } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-3">
      <Avatar
        name="Grace Hopper"
        src="https://avatars.githubusercontent.com/u/9919?s=96"
        size="lg"
      />
      <Avatar name="Broken Image" src="https://example.invalid/missing.png" size="lg" />
    </div>
  )
}
```

## Example: Group

```tsx
import { Avatar, AvatarGroup, Text } from '@glyphui/ui'

const team = ['Ada Lovelace', 'Grace Hopper', 'Alan Kay', 'Radia Perlman', 'Ken Thompson']

export default function Example() {
  return (
    <div className="flex items-center gap-3">
      <AvatarGroup>
        {team.map((name) => (
          <Avatar key={name} name={name} />
        ))}
      </AvatarGroup>
      <Text size="small" tone="muted">
        5 people on Design
      </Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/avatar

---

# Badge

> A short status or label. Six tones, three variants, and an optional status dot.

Status: stable. Category: Data display.

```ts
import { Badge } from '@glyphui/ui'
```

Exports: `Badge`, `badgeStyles`.

## Notes

- Tinted text is mixed toward the foreground color so it stays readable in light and dark mode.
- Color alone should not carry meaning; keep the label text descriptive.

## Badge props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `dot` | `boolean` |  | Leading status dot in the badge's color. |
| `tone` | `"neutral" \| "primary" \| "info" \| "success" \| "warning" \| "danger"` |  |  |
| `variant` | `"soft" \| "outline" \| "solid"` |  |  |

## Example: Tones

```tsx
import { Badge } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex flex-wrap gap-2">
      <Badge>Neutral</Badge>
      <Badge tone="primary">Primary</Badge>
      <Badge tone="info">Info</Badge>
      <Badge tone="success">Success</Badge>
      <Badge tone="warning">Warning</Badge>
      <Badge tone="danger">Danger</Badge>
    </div>
  )
}
```

## Example: Variants

Soft is the default; solid for emphasis, outline for quiet labels.

```tsx
import { Badge } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3">
      <div className="flex flex-wrap gap-2">
        <Badge tone="primary" variant="soft">
          Soft
        </Badge>
        <Badge tone="primary" variant="solid">
          Solid
        </Badge>
        <Badge tone="primary" variant="outline">
          Outline
        </Badge>
      </div>
      <div className="flex flex-wrap gap-2">
        <Badge tone="danger" variant="soft">
          Overdue
        </Badge>
        <Badge tone="danger" variant="solid">
          Overdue
        </Badge>
        <Badge tone="danger" variant="outline">
          Overdue
        </Badge>
      </div>
    </div>
  )
}
```

## Example: Status with dot

```tsx
import { Badge } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex flex-wrap gap-2">
      <Badge dot>Backlog</Badge>
      <Badge tone="warning" dot>
        In progress
      </Badge>
      <Badge tone="info" dot>
        In review
      </Badge>
      <Badge tone="success" dot>
        Deployed
      </Badge>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/badge

---

# Banner

> A full-width announcement bar for the top of a page or section, optionally dismissible and remembered.

Status: beta. Category: Feedback.

```ts
import { Banner } from '@glyphui/ui'
```

Exports: `Banner`, `bannerStyles`.

## Notes

- Rendered as a labelled region ("Announcement") so screen-reader users can find or skip it.

## Example: Tones

```tsx
import { Banner } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3">
      <Banner tone="primary">Glyph 1.0 is out. Read what changed in the release notes.</Banner>
      <Banner>You're viewing a shared workspace in read-only mode.</Banner>
      <Banner tone="warning">Scheduled maintenance Sunday 02:00–03:00 UTC.</Banner>
      <Banner tone="danger">We couldn't reach your payment provider. Retrying in 5 minutes.</Banner>
    </div>
  )
}
```

## Example: Dismissible

With storageKey, a dismissed banner stays hidden on later visits.

```tsx
import { Banner, Button } from '@glyphui/ui'

export default function Example() {
  return (
    <Banner
      tone="info"
      dismissible
      storageKey="docs-banner-webinar"
      action={
        <Button size="sm" variant="outline">
          Register
        </Button>
      }
    >
      Live walkthrough of the theme engine on Thursday at 17:00 CET.
    </Banner>
  )
}
```

Live page: https://glyphui.xyz/components/banner

---

# Blockquote

> A quotation set in the display font, with an accent rule and optional attribution.

Status: beta. Category: Typography.

```ts
import { Blockquote } from '@glyphui/ui'
```

Exports: `Blockquote`, `blockquoteStyles`.

## Example: With attribution

```tsx
import { Blockquote } from '@glyphui/ui'

export default function Example() {
  return (
    <Blockquote author="Ada Lovelace" source="Notes on the Analytical Engine, 1843">
      The Analytical Engine weaves algebraic patterns just as the Jacquard loom weaves flowers and
      leaves.
    </Blockquote>
  )
}
```

## Example: Sizes

```tsx
import { Blockquote } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-8">
      <Blockquote size="sm" author="Support ticket #2210">
        The new export saved our finance team a full day each month.
      </Blockquote>
      <Blockquote size="lg" author="Head of Design, Acme">
        We swapped one file and the whole product looked like ours.
      </Blockquote>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/blockquote

---

# Breadcrumb

> Shows where the current page sits in the hierarchy, with links back up the trail.

Status: beta. Category: Navigation.

```ts
import { Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator } from '@glyphui/ui'
```

Exports: `Breadcrumb`, `BreadcrumbList`, `BreadcrumbItem`, `BreadcrumbLink`, `BreadcrumbPage`, `BreadcrumbSeparator`, `breadcrumbStyles`.

## Notes

- Renders a nav landmark named "Breadcrumb" and marks the last item with aria-current="page".
- Links go through the linkComponent you pass to GlyphProvider, so client-side routing works.

## Example: From data

Pass items; the last one is the current page.

```tsx
import { Breadcrumb } from '@glyphui/ui'

export default function Example() {
  return (
    <Breadcrumb
      items={[
        { label: 'Acme', href: '#' },
        { label: 'Projects', href: '#' },
        { label: 'Glyph', href: '#' },
        { label: 'Settings' },
      ]}
    />
  )
}
```

## Example: Composed

Use the parts for custom separators or extra content.

```tsx
import {
  Badge,
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@glyphui/ui'

export default function Example() {
  return (
    <Breadcrumb>
      <BreadcrumbList>
        <BreadcrumbItem>
          <BreadcrumbLink href="#">Engineering</BreadcrumbLink>
          <BreadcrumbSeparator>/</BreadcrumbSeparator>
        </BreadcrumbItem>
        <BreadcrumbItem>
          <BreadcrumbPage>GLY-142</BreadcrumbPage>
          <Badge tone="warning" dot>
            In progress
          </Badge>
        </BreadcrumbItem>
      </BreadcrumbList>
    </Breadcrumb>
  )
}
```

Live page: https://glyphui.xyz/components/breadcrumb

---

# Button

> Triggers an action. Six variants, three sizes, icons, a loading state, and asChild for links.

Status: stable. Category: Actions.

```ts
import { Button, IconButton } from '@glyphui/ui'
```

Exports: `Button`, `IconButton`, `buttonStyles`.

## Notes

- Defaults to type="button", so it never submits a form by accident. Use FormSubmit inside forms.
- IconButton requires aria-label because it has no visible text.

## Button props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  | Render the child element (e.g. a router link) with button styles instead of a `<button>`. |
| `fullWidth` | `boolean` |  |  |
| `iconOnly` | `boolean` |  |  |
| `leftIcon` | `ReactNode` |  |  |
| `loading` | `boolean` |  | Shows a spinner, disables the button and sets `aria-busy`. |
| `rightIcon` | `ReactNode` |  |  |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `variant` | `"link" \| "primary" \| "danger" \| "outline" \| "secondary" \| "ghost"` |  |  |

## Example: Variants

```tsx
import { Button } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Button>Primary</Button>
      <Button variant="secondary">Secondary</Button>
      <Button variant="outline">Outline</Button>
      <Button variant="ghost">Ghost</Button>
      <Button variant="danger">Delete</Button>
      <Button variant="link">Link</Button>
    </div>
  )
}
```

## Example: Sizes and icons

```tsx
import { Button, IconButton } from '@glyphui/ui'
import { Plus, Settings2 } from 'lucide-react'

export default function Example() {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Button size="sm" leftIcon={<Plus />}>
        Small
      </Button>
      <Button size="md" leftIcon={<Plus />}>
        Medium
      </Button>
      <Button size="lg" leftIcon={<Plus />}>
        Large
      </Button>
      <IconButton icon={<Settings2 />} aria-label="Settings" variant="outline" />
    </div>
  )
}
```

## Example: Loading

Disables the button, shows a spinner and sets aria-busy.

```tsx
import { Button } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [saving, setSaving] = useState(false)
  return (
    <Button
      loading={saving}
      onClick={() => {
        setSaving(true)
        setTimeout(() => setSaving(false), 1500)
      }}
    >
      {saving ? 'Saving…' : 'Save changes'}
    </Button>
  )
}
```

## Example: As a link

asChild renders your router link with button styles.

```tsx
import { Button } from '@glyphui/ui'
import { ArrowUpRight } from 'lucide-react'

export default function Example() {
  return (
    <Button variant="outline" rightIcon={<ArrowUpRight />} asChild>
      <a href="https://github.com/khalmohak/glyph">View on GitHub</a>
    </Button>
  )
}
```

Live page: https://glyphui.xyz/components/button

---

# Calendar

> A month grid for picking one date, several dates or a range. The building block behind DatePicker.

Status: beta. Category: Forms.

```ts
import { Calendar } from '@glyphui/ui'
```

Exports: `Calendar`, `calendarStyles`.

## Notes

- Built on react-day-picker v9; every DayPicker prop works, including locale and weekStartsOn.
- Arrow keys move between days, Page Up/Down change month, and Enter selects.

## Example: Single date

```tsx
import { Calendar } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [date, setDate] = useState<Date | undefined>(new Date())
  return (
    <div className="grid justify-items-center gap-2">
      <Calendar
        mode="single"
        selected={date}
        onSelect={setDate}
        className="rounded-lg border border-border"
      />
      <p className="text-small text-muted-foreground">
        {date ? `Selected ${date.toDateString()}` : 'No date selected'}
      </p>
    </div>
  )
}
```

## Example: Range across two months

```tsx
import { Calendar, type DateRange } from '@glyphui/ui'
import { useState } from 'react'

const inDays = (n: number) => new Date(Date.now() + n * 86_400_000)

export default function Example() {
  const [range, setRange] = useState<DateRange | undefined>({
    from: new Date(),
    to: inDays(6),
  })
  return (
    <Calendar
      mode="range"
      numberOfMonths={2}
      selected={range}
      onSelect={setRange}
      className="rounded-lg border border-border"
    />
  )
}
```

## Example: Disabled dates

Pass react-day-picker matchers: weekends, before today, specific days.

```tsx
import { Calendar } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [date, setDate] = useState<Date | undefined>()
  return (
    <Calendar
      mode="single"
      selected={date}
      onSelect={setDate}
      disabled={[{ before: new Date() }, { dayOfWeek: [0, 6] }]}
      className="rounded-lg border border-border"
    />
  )
}
```

Live page: https://glyphui.xyz/components/calendar

---

# Card

> A surface that groups related content. Compose with CardHeader, CardTitle, CardBody and CardFooter.

Status: stable. Category: Layout.

```ts
import { Card, CardHeader, CardTitle, CardDescription, CardBody, CardFooter } from '@glyphui/ui'
```

Exports: `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardBody`, `CardFooter`, `cardStyles`.

## Card props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `padding` | `"none" \| "sm" \| "md" \| "lg"` |  |  |
| `variant` | `"outline" \| "ghost" \| "elevated" \| "interactive"` |  |  |

## Example: Composed card

```tsx
import {
  Button,
  Card,
  CardBody,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
  Text,
} from '@glyphui/ui'

export default function Example() {
  return (
    <Card className="max-w-sm">
      <CardHeader>
        <CardTitle>Upgrade to Pro</CardTitle>
        <CardDescription>Unlimited projects and priority support.</CardDescription>
      </CardHeader>
      <CardBody>
        <Text size="small" tone="muted">
          You are using 3 of 3 projects on the Free plan.
        </Text>
      </CardBody>
      <CardFooter>
        <Button>Upgrade</Button>
        <Button variant="ghost">Compare plans</Button>
      </CardFooter>
    </Card>
  )
}
```

## Example: Variants

Themes can change the default variant; the editorial preset uses outline.

```tsx
import { Card, CardDescription, CardTitle } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3 sm:grid-cols-3">
      {(['outline', 'elevated', 'ghost'] as const).map((variant) => (
        <Card key={variant} variant={variant} padding="sm">
          <CardTitle>{variant}</CardTitle>
          <CardDescription>variant="{variant}"</CardDescription>
        </Card>
      ))}
    </div>
  )
}
```

## Example: Interactive

Lifts on hover. Use asChild to make the whole card a link.

```tsx
import { Card, CardDescription, CardTitle } from '@glyphui/ui'

export default function Example() {
  return (
    <Card variant="interactive" asChild className="max-w-sm">
      <a href="#card">
        <CardTitle>Getting started</CardTitle>
        <CardDescription>
          Install Glyph and write your first theme file in five minutes.
        </CardDescription>
      </a>
    </Card>
  )
}
```

Live page: https://glyphui.xyz/components/card

---

# Carousel

> Swipeable, keyboard-accessible slides for testimonials, media and onboarding.

Status: beta. Category: Data display.

```ts
import { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext, CarouselDots } from '@glyphui/ui'
```

Exports: `Carousel`, `CarouselContent`, `CarouselItem`, `CarouselPrevious`, `CarouselNext`, `CarouselDots`, `carouselStyles`.

## Notes

- Built on Embla. Swipe on touch, drag with a mouse, or use the arrow keys while focus is inside.
- Uses the WAI-ARIA carousel pattern: the region is labelled and each slide announces “n of total”.
- Pass setApi to build custom controls on the Embla API.

## Carousel props

| Prop | Type | Default | Description |
|---|---|---|---|
| `aria-label` (required) | `string` |  | Required: describes the content, e.g. "Customer stories". |
| `loop` | `boolean` |  | Shortcut for `opts.loop`. |
| `opts` | `Partial<OptionsType>` |  | Embla options, e.g. `{ align: 'start', loop: true }`. |
| `orientation` | `"horizontal" \| "vertical"` |  |  |
| `plugins` | `CreatePluginType<LoosePluginType, {}>[]` |  |  |
| `setApi` | `((api: EmblaCarouselType) => void)` |  | Receives the Embla API for custom controls. |

## Example: Testimonials

One slide at a time, with dots.

```tsx
import {
  Avatar,
  Card,
  Carousel,
  CarouselContent,
  CarouselDots,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  Text,
} from '@glyphui/ui'

const quotes = [
  {
    name: 'Ada Lovelace',
    role: 'Staff engineer, Acme',
    quote: 'We swapped our whole design language by editing one theme file. Nothing else changed.',
  },
  {
    name: 'Grace Hopper',
    role: 'Founder, Compile',
    quote: 'Forms with server errors used to take a day. Now it is ten lines.',
  },
  {
    name: 'Alan Kay',
    role: 'Design lead, Smalltalk Labs',
    quote: 'The defaults are already good. We mostly delete code now.',
  },
]

export default function Example() {
  return (
    <Carousel aria-label="Customer stories" loop className="w-full max-w-md">
      <CarouselContent>
        {quotes.map((q) => (
          <CarouselItem key={q.name}>
            <Card className="h-full px-14">
              <Text size="lead">“{q.quote}”</Text>
              <div className="flex items-center gap-3">
                <Avatar name={q.name} size="sm" />
                <div>
                  <Text size="small" weight="medium">
                    {q.name}
                  </Text>
                  <Text size="caption" tone="muted">
                    {q.role}
                  </Text>
                </div>
              </div>
            </Card>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselPrevious />
      <CarouselNext />
      <CarouselDots />
    </Carousel>
  )
}
```

## Example: Several per view

Size items with basis classes; align and loop through opts.

```tsx
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from '@glyphui/ui'

const covers = ['Theming', 'Forms', 'Data tables', 'Layouts', 'Charts', 'Blocks']

export default function Example() {
  return (
    <Carousel aria-label="Guides" opts={{ align: 'start' }} className="w-full max-w-lg">
      <CarouselContent>
        {covers.map((title, i) => (
          <CarouselItem key={title} className="basis-1/2 sm:basis-1/3">
            <div className="flex aspect-[4/5] flex-col justify-end rounded-md border border-border bg-subtle p-4">
              <span className="font-mono text-caption text-faint-foreground">Guide {i + 1}</span>
              <span className="font-display text-h4">{title}</span>
            </div>
          </CarouselItem>
        ))}
      </CarouselContent>
      <CarouselPrevious />
      <CarouselNext />
    </Carousel>
  )
}
```

Live page: https://glyphui.xyz/components/carousel

---

# Chart

> Line, area, bar and composed charts with interactive legends, reference lines, zoom, and loading, error and empty states, all colored by the theme.

Status: beta. Category: Data display.

```ts
import { LineChart, AreaChart, BarChart, ComposedChart, ChartLegend, ChartTooltipCard } from '@glyphui/ui/chart'
```

Exports: `LineChart`, `AreaChart`, `BarChart`, `ComposedChart`, `ChartLegend`, `ChartTooltipCard`, `chartStyles`.

## Notes

- Install the optional peer dependency first: npm install recharts.
- Series colors default to the theme chart palette (chart-1 to chart-5), in order; pass a theme color name or any CSS color to override. Keep the same color for the same thing across charts.
- Set the palette in your theme file: colors: { light: { "chart-1": "oklch(55% 0.2 30)" } }. A theme without chart colors falls back to primary, info, success, warning and danger.
- With more than one series the legend is interactive: click or press Enter on an entry to hide its series. hiddenSeries and onHiddenSeriesChange control it.
- Entry and update animations follow the theme motion level and turn off for visitors who prefer reduced motion.
- Every chart is a labelled figure with a visually hidden data table, so screen-reader users get the numbers. Wrap a chart in ChartCard to let everyone switch to the table.
- The brush is a pointer control. Keyboard and screen-reader users get every row from the data table; wrap the chart in ChartCard to make that table visible.
- ComposedChart can put a series on a right-hand axis (axis: "right"). Two scales on one plot are easy to misread; prefer two charts with the same syncId when you can.

## LineChart props

| Prop | Type | Default | Description |
|---|---|---|---|
| `data` (required) | `readonly T[]` |  |  |
| `index` (required) | `string` |  | Field used for the x axis, e.g. `"month"`. |
| `series` (required) | `readonly ChartSeries<T>[]` |  |  |
| `title` (required) | `string` |  | Accessible name; also shown as the caption unless `hideTitle` is set. |
| `brush` | `boolean \| ChartBrushOptions` |  | Adds a range slider under the plot to zoom into part of the data. |
| `className` | `string` |  |  |
| `curve` | `"step" \| "monotone" \| "linear"` |  |  |
| `defaultHiddenSeries` | `readonly Extract<keyof T, string>[]` |  |  |
| `description` | `ReactNode` |  |  |
| `dots` | `boolean` |  | Show a dot on every data point. Default false. |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `height` | `number` |  | Plot height in pixels. Default 240. |
| `hiddenSeries` | `readonly Extract<keyof T, string>[]` |  | Series hidden through the legend (controlled). |
| `hideTitle` | `boolean` |  |  |
| `labelFormatter` | `((label: ReactNode) => ReactNode)` |  | Formats the x value at the top of the tooltip. |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `onHiddenSeriesChange` | `((hidden: Extract<keyof T, string>[]) => void)` |  |  |
| `onPointClick` | `((row: T, seriesKey?: Extract<keyof T, string>) => void)` |  | Called with the row (and series, when known) the user clicked. |
| `onRetry` | `(() => unknown)` |  |  |
| `referenceAreas` | `readonly ChartReferenceArea[]` |  | Shaded ranges, e.g. a launch window or an incident. |
| `referenceLines` | `readonly ChartReferenceLine[]` |  | Targets, limits, averages... drawn across the plot. |
| `showGrid` | `boolean` |  |  |
| `showLegend` | `boolean` |  | Defaults to true when there is more than one series. |
| `showYAxis` | `boolean` |  | Shorthand for `yAxis={{ hide: !showYAxis }}`. |
| `syncId` | `string` |  | Charts with the same `syncId` share their tooltip and brush position. |
| `valueFormatter` | `((value: number) => string)` |  | Formats values on the y axis, in tooltips and in the accessible table. |
| `xAxis` | `ChartAxisOptions` |  |  |
| `yAxis` | `ChartAxisOptions` |  |  |

## Example: Line

Two series with a value formatter.

```tsx
import { LineChart } from '@glyphui/ui/chart'

const data = [
  { month: 'Jan', revenue: 18200, costs: 12100 },
  { month: 'Feb', revenue: 21400, costs: 12800 },
  { month: 'Mar', revenue: 20100, costs: 13400 },
  { month: 'Apr', revenue: 26800, costs: 14100 },
  { month: 'May', revenue: 31200, costs: 15000 },
  { month: 'Jun', revenue: 34900, costs: 15600 },
]

const usd = (v: number) => `$${(v / 1000).toFixed(0)}k`

export default function Example() {
  return (
    <LineChart
      className="w-full"
      title="Revenue and costs, first half"
      data={data}
      index="month"
      series={[
        { key: 'revenue', label: 'Revenue' },
        { key: 'costs', label: 'Costs', color: 'muted-foreground' },
      ]}
      valueFormatter={usd}
    />
  )
}
```

## Example: Stacked area

Stacked charts add a total row to the tooltip.

```tsx
import { AreaChart } from '@glyphui/ui/chart'

const data = [
  { week: 'W1', organic: 1200, paid: 640, referral: 310 },
  { week: 'W2', organic: 1380, paid: 720, referral: 290 },
  { week: 'W3', organic: 1510, paid: 690, referral: 380 },
  { week: 'W4', organic: 1720, paid: 810, referral: 420 },
  { week: 'W5', organic: 1890, paid: 760, referral: 470 },
]

export default function Example() {
  return (
    <AreaChart
      className="w-full"
      title="Signups by source"
      description="Weekly, last 5 weeks"
      data={data}
      index="week"
      stacked
      series={[
        { key: 'organic', label: 'Organic' },
        { key: 'paid', label: 'Paid' },
        { key: 'referral', label: 'Referral' },
      ]}
    />
  )
}
```

## Example: Bar

```tsx
import { BarChart } from '@glyphui/ui/chart'

const data = [
  { day: 'Mon', opened: 42, closed: 38 },
  { day: 'Tue', opened: 51, closed: 47 },
  { day: 'Wed', opened: 39, closed: 44 },
  { day: 'Thu', opened: 58, closed: 50 },
  { day: 'Fri', opened: 33, closed: 41 },
]

export default function Example() {
  return (
    <BarChart
      className="w-full"
      title="Issues opened and closed"
      data={data}
      index="day"
      height={220}
      series={[
        { key: 'opened', label: 'Opened' },
        { key: 'closed', label: 'Closed', color: 'success' },
      ]}
    />
  )
}
```

## Example: Horizontal bars

layout="vertical" for long category names.

```tsx
import { BarChart } from '@glyphui/ui/chart'

const data = [
  { page: '/pricing', views: 18420 },
  { page: '/docs/getting-started', views: 12950 },
  { page: '/blog/usage-billing', views: 8730 },
  { page: '/changelog', views: 5210 },
  { page: '/integrations/stripe', views: 3980 },
]

export default function Example() {
  return (
    <BarChart
      className="w-full"
      title="Top pages"
      description="Views, last 30 days"
      data={data}
      index="page"
      layout="vertical"
      height={230}
      xAxis={{ width: 168 }}
      series={[{ key: 'views', label: 'Views' }]}
    />
  )
}
```

## Example: Composed

Bars and a line on one plot. Click a legend entry to hide its series.

```tsx
import { ComposedChart } from '@glyphui/ui/chart'

const data = [
  { month: 'May', revenue: 18200, target: 20000 },
  { month: 'Jun', revenue: 21400, target: 22000 },
  { month: 'Jul', revenue: 23100, target: 24000 },
  { month: 'Aug', revenue: 26800, target: 26000 },
  { month: 'Sep', revenue: 31200, target: 28000 },
  { month: 'Oct', revenue: 34900, target: 30000 },
]

const usd = (v: number) => `$${(v / 1000).toFixed(0)}k`

export default function Example() {
  return (
    <ComposedChart
      className="w-full"
      title="Revenue against plan"
      data={data}
      index="month"
      valueFormatter={usd}
      series={[
        { key: 'revenue', label: 'Revenue', type: 'bar' },
        { key: 'target', label: 'Plan', type: 'line', color: 'muted-foreground' },
      ]}
    />
  )
}
```

## Example: Targets and annotations

referenceLines for goals and limits, referenceAreas for periods.

```tsx
import { LineChart } from '@glyphui/ui/chart'

const data = [
  { day: 'Oct 1', p95: 182 },
  { day: 'Oct 2', p95: 176 },
  { day: 'Oct 3', p95: 210 },
  { day: 'Oct 4', p95: 334 },
  { day: 'Oct 5', p95: 298 },
  { day: 'Oct 6', p95: 191 },
  { day: 'Oct 7', p95: 168 },
  { day: 'Oct 8', p95: 172 },
]

export default function Example() {
  return (
    <LineChart
      className="w-full"
      title="API latency"
      description="p95 response time, milliseconds"
      data={data}
      index="day"
      dots
      valueFormatter={(v) => `${v} ms`}
      series={[{ key: 'p95', label: 'p95' }]}
      referenceLines={[{ y: 250, label: 'SLO 250 ms', color: 'danger' }]}
      referenceAreas={[{ x1: 'Oct 4', x2: 'Oct 5', label: 'Incident #4182' }]}
    />
  )
}
```

## Example: Zoom with a brush

Drag the handles under the plot to focus on a range.

```tsx
import { AreaChart } from '@glyphui/ui/chart'

// Ninety days of signups with a weekly rhythm and steady growth.
const data = Array.from({ length: 90 }, (_, i) => {
  const date = new Date(2026, 6, 18 + i)
  const weekday = date.getDay()
  const weekend = weekday === 0 || weekday === 6 ? 0.55 : 1
  return {
    date: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
    signups: Math.round((120 + i * 1.6 + 18 * Math.sin(i / 3)) * weekend),
  }
})

export default function Example() {
  return (
    <AreaChart
      className="w-full"
      title="Daily signups"
      description="Last 90 days"
      data={data}
      index="date"
      height={260}
      series={[{ key: 'signups', label: 'Signups' }]}
      brush={{ startIndex: 60 }}
    />
  )
}
```

## Example: Loading, error and empty

The same props as every Glyph data component.

```tsx
import { SegmentedControl } from '@glyphui/ui'
import { LineChart } from '@glyphui/ui/chart'
import { useState } from 'react'

const data = [
  { month: 'Jul', mrr: 23100 },
  { month: 'Aug', mrr: 26800 },
  { month: 'Sep', mrr: 31200 },
  { month: 'Oct', mrr: 34900 },
]

type State = 'loading' | 'error' | 'empty' | 'ready'

export default function Example() {
  const [state, setState] = useState<State>('loading')
  return (
    <div className="grid w-full gap-4">
      <SegmentedControl<State>
        aria-label="State"
        size="sm"
        className="justify-self-start"
        value={state}
        onValueChange={setState}
        options={[
          { value: 'loading', label: 'Loading' },
          { value: 'error', label: 'Error' },
          { value: 'empty', label: 'Empty' },
          { value: 'ready', label: 'Ready' },
        ]}
      />
      <LineChart
        title="Monthly recurring revenue"
        data={state === 'empty' ? [] : data}
        index="month"
        series={[{ key: 'mrr', label: 'MRR' }]}
        valueFormatter={(v) => `$${(v / 1000).toFixed(1)}k`}
        height={200}
        loading={state === 'loading'}
        error={state === 'error' ? new Error('The metrics service timed out.') : undefined}
        onRetry={() => setState('ready')}
      />
    </div>
  )
}
```

## Example: Live data

Pass new data and the series animate to it, at the theme’s motion level.

```tsx
import { Button } from '@glyphui/ui'
import { LineChart } from '@glyphui/ui/chart'
import { useEffect, useState } from 'react'

const start = [42, 45, 44, 48, 51, 49, 53, 56, 55, 58, 61, 59]

function next(points: { t: number; rps: number }[]) {
  const last = points[points.length - 1]!
  const drift = Math.sin(last.t / 2) * 3
  return [...points.slice(1), { t: last.t + 1, rps: Math.max(20, Math.round(last.rps + drift)) }]
}

export default function Example() {
  const [running, setRunning] = useState(false)
  const [points, setPoints] = useState(() => start.map((rps, t) => ({ t, rps })))

  useEffect(() => {
    if (!running) return
    const timer = setInterval(() => setPoints(next), 1200)
    return () => clearInterval(timer)
  }, [running])

  return (
    <div className="grid w-full gap-3">
      <Button
        variant="outline"
        size="sm"
        className="justify-self-start"
        onClick={() => setRunning((r) => !r)}
      >
        {running ? 'Pause stream' : 'Start stream'}
      </Button>
      <LineChart
        title="Requests per second"
        data={points.map((p) => ({ ...p, label: `${p.t}s` }))}
        index="label"
        height={200}
        series={[{ key: 'rps', label: 'Requests/s' }]}
        yAxis={{ domain: [0, 'auto'] }}
      />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/chart

---

# ChartCard

> A card for one chart with a period selector, a “view as table” toggle and PNG or SVG download. exportChart downloads any chart.

Status: beta. Category: Data display.

```ts
import { ChartCard } from '@glyphui/ui/chart'
```

Exports: `ChartCard`, `chartCardStyles`, `exportChart`, `serializeChart`.

## Notes

- The chart inside hides its caption (the card shows the title) but keeps it as its accessible name.
- The table view is a real, visible table of the same rows the chart plots, for anyone who wants exact numbers.
- Exports resolve every theme variable, so the PNG or SVG looks the same outside your app. Web fonts fall back to system fonts in PNGs.

## ChartCard props

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` (required) | `ReactNode` |  | One chart from `@glyphui/ui/chart`. Its own title becomes the accessible name only. |
| `title` (required) | `ReactNode` |  |  |
| `actions` | `ReactNode` |  | Extra controls in the header, before the built-in buttons. |
| `defaultView` | `"table" \| "chart"` |  |  |
| `description` | `ReactNode` |  |  |
| `exportable` | `boolean \| { fileName?: string; }` |  | Adds a download menu (PNG and SVG). Default true. |
| `onExportError` | `((error: unknown) => void)` |  | Called when a download fails, e.g. to show a toast. Logs to the console by default. |
| `onViewChange` | `((view: "table" \| "chart") => void)` |  |  |
| `period` | `ChartPeriod<P>` |  | A period selector in the header, e.g. 7d / 30d / 90d. |
| `tableToggle` | `boolean` |  | Adds a button that shows the chart's data as a table. Default true. |
| `view` | `"table" \| "chart"` |  |  |

## Example: Dashboard card

Switch the period, view the numbers as a table, or download the chart.

```tsx
import { ChartCard, LineChart } from '@glyphui/ui/chart'
import { useState } from 'react'

type Period = '7d' | '30d' | '90d'

const lengths: Record<Period, number> = { '7d': 7, '30d': 30, '90d': 90 }

function series(days: number) {
  return Array.from({ length: days }, (_, i) => {
    const date = new Date(2026, 9, 16 - days + 1 + i)
    return {
      date: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
      active: Math.round(2400 + i * (900 / days) + 160 * Math.sin(i / 2)),
      new: Math.round(310 + 60 * Math.cos(i / 3)),
    }
  })
}

export default function Example() {
  const [period, setPeriod] = useState<Period>('30d')
  return (
    <ChartCard
      className="w-full"
      title="Active users"
      description="Daily, compared with new signups"
      period={{
        value: period,
        onValueChange: setPeriod,
        options: [
          { value: '7d', label: '7d' },
          { value: '30d', label: '30d' },
          { value: '90d', label: '90d' },
        ],
      }}
    >
      <LineChart
        title="Active users"
        data={series(lengths[period])}
        index="date"
        height={220}
        series={[
          { key: 'active', label: 'Active' },
          { key: 'new', label: 'New' },
        ]}
      />
    </ChartCard>
  )
}
```

## Example: Export without a card

exportChart(element, { format }) bakes the theme’s colors into the file.

```tsx
import { Button } from '@glyphui/ui'
import { BarChart, exportChart } from '@glyphui/ui/chart'
import { Download } from 'lucide-react'
import { useRef } from 'react'

const data = [
  { quarter: 'Q1', bookings: 182000 },
  { quarter: 'Q2', bookings: 214000 },
  { quarter: 'Q3', bookings: 268000 },
  { quarter: 'Q4', bookings: 311000 },
]

export default function Example() {
  const chart = useRef<HTMLDivElement>(null)
  return (
    <div className="grid w-full gap-3">
      <div ref={chart}>
        <BarChart
          title="Bookings by quarter"
          data={data}
          index="quarter"
          height={200}
          valueFormatter={(v) => `$${Math.round(v / 1000)}k`}
          series={[{ key: 'bookings', label: 'Bookings' }]}
        />
      </div>
      <div className="flex gap-2">
        <Button
          variant="outline"
          size="sm"
          leftIcon={<Download />}
          onClick={() => exportChart(chart, { format: 'svg', fileName: 'bookings' })}
        >
          SVG
        </Button>
        <Button
          variant="outline"
          size="sm"
          leftIcon={<Download />}
          onClick={() => exportChart(chart, { format: 'png', fileName: 'bookings' })}
        >
          PNG
        </Button>
      </div>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/chart-card

---

# Checkbox

> A checkbox with checked, unchecked and indeterminate states.

Status: stable. Category: Forms.

```ts
import { Checkbox } from '@glyphui/ui'
```

Exports: `Checkbox`, `checkboxStyles`.

## Checkbox props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |

## Example: With a label

```tsx
import { Checkbox, Field } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3">
      <Field orientation="horizontal" label="Send a copy to my email">
        <Checkbox defaultChecked />
      </Field>
      <Field
        orientation="horizontal"
        label="Archived projects"
        description="Only admins can include these."
        disabled
      >
        <Checkbox />
      </Field>
    </div>
  )
}
```

## Example: Select all

Indeterminate when some, not all, items are checked.

```tsx
import { Checkbox, Label } from '@glyphui/ui'
import { useState } from 'react'

const channels = ['Email', 'Slack', 'SMS'] as const

export default function Example() {
  const [checked, setChecked] = useState<string[]>(['Email'])
  const all = checked.length === channels.length
  const some = checked.length > 0 && !all
  return (
    <div className="grid gap-2">
      <div className="flex items-center gap-2">
        <Checkbox
          id="all-channels"
          checked={all ? true : some ? 'indeterminate' : false}
          onCheckedChange={(value) => setChecked(value === true ? [...channels] : [])}
        />
        <Label htmlFor="all-channels">All channels</Label>
      </div>
      {channels.map((channel) => (
        <div key={channel} className="flex items-center gap-2 pl-6">
          <Checkbox
            id={`channel-${channel}`}
            checked={checked.includes(channel)}
            onCheckedChange={(value) =>
              setChecked((prev) =>
                value === true ? [...prev, channel] : prev.filter((c) => c !== channel),
              )
            }
          />
          <Label htmlFor={`channel-${channel}`}>{channel}</Label>
        </div>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/checkbox

---

# Clerk bridge

> Use Glyph’s guards, useAuth() and screens with Clerk: the bridge mirrors Clerk’s session into Glyph.

Status: beta. Category: Auth.

```ts
import { ClerkAuthBridge } from '@glyphui/auth/clerk'
```

Exports: `ClerkAuthBridge`, `createClerkBridge`.

## Notes

- Glyph’s forms handle email and password, sign-up email codes, authenticator codes and reset codes through Clerk.
- OAuth redirects through Clerk: render Clerk’s <AuthenticateWithRedirectCallback /> at oauthCallbackUrl (default /sso-callback).
- Passkeys, enterprise SSO and bot protection need Clerk’s own components; use them alongside Glyph’s guards.
- Roles come from publicMetadata.roles plus the active organization role; permissions from publicMetadata.permissions.
- Clerk refreshes tokens and syncs tabs itself, so the bridge turns those Glyph timers off.
- auth.fetch sends Clerk’s session token as a bearer token.

## ClerkAuthBridge props

| Prop | Type | Default | Description |
|---|---|---|---|
| `afterOAuthUrl` | `string` |  | Where to land after OAuth completes. Default `/`. |
| `idleTimeout` | `number` |  | Sign the user out after this long without activity (ms). Off by default. |
| `idleWarning` | `number` |  | How long before the idle sign-out to warn (ms). Default 60 seconds. |
| `mapUser` | `((user: ClerkUserLike) => DefaultUser)` |  | Turns a Clerk user into your app's user type. |
| `oauthCallbackUrl` | `string` |  | Where Clerk returns after OAuth. Render Clerk's `<AuthenticateWithRedirectCallback />` there. |
| `oauthProviders` | `OAuthProvider[]` |  | Social buttons to offer. Default Google and GitHub. |
| `onSignOut` | `((reason: SignOutReason) => void)` |  | Called after any sign-out, with why it happened. |
| `refreshInterval` | `number \| false` |  | Re-check the session this often while the tab is open. Default 5 minutes; `false` to disable. |
| `refreshOnFocus` | `boolean` |  | Re-check the session when the tab regains focus. Default true. |
| `syncTabs` | `string \| boolean` |  | Keep tabs in sync: signing in or out in one tab updates the others. Pass a string to name the channel (useful when two apps share an origin). Default true. |

Live page: https://glyphui.xyz/components/auth-clerk

---

# Code

> Inline code for running text, and CodeBlock for snippets with a file name and a copy button.

Status: beta. Category: Typography.

```ts
import { Code, CodeBlock } from '@glyphui/ui'
```

Exports: `Code`, `CodeBlock`, `codeStyles`, `codeBlockStyles`.

## Notes

- CodeBlock does not highlight syntax, so it adds no dependency. Bring your own highlighter if you need one.
- If the clipboard is blocked, the copy button does nothing and the code stays selectable.

## Example: Inline

```tsx
import { Code, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Text>
      Run <Code>pnpm dev</Code> to start the docs, then edit <Code>glyph.theme.ts</Code>.
    </Text>
  )
}
```

## Example: Code block

```tsx
import { CodeBlock } from '@glyphui/ui'

const code = `import { defineTheme, presets } from '@glyphui/ui'

export default defineTheme({
  name: 'acme',
  extends: presets.glyph,
  radius: { md: '6px' },
})`

export default function Example() {
  return (
    <div className="grid gap-4">
      <CodeBlock title="glyph.theme.ts" code={code} />
      <CodeBlock code="pnpm add @glyphui/ui" />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/code

---

# Code forms

> Six-digit code steps: confirm an email after sign-up, or a second factor at sign-in. SignInForm and SignUpForm show them for you.

Status: beta. Category: Auth.

```ts
import { VerifyEmailForm, TwoFactorForm } from '@glyphui/auth/ui'
```

Exports: `VerifyEmailForm`, `TwoFactorForm`, `secondFactorDescription`.

## Notes

- The input uses autocomplete="one-time-code", so phones offer the code from SMS or email.
- Resend waits 30 seconds between sends.
- A wrong code clears the input and shows the server’s message.
- TwoFactorForm words its step from method: "totp" (an authenticator app, the default), "email" (with the address) or "sms". SignInForm passes the method your server sends; override the text with twoFactor={{ title, description }}.

## VerifyEmailForm props

| Prop | Type | Default | Description |
|---|---|---|---|
| `email` (required) | `string` |  | The address the code was sent to. |
| `className` | `string` |  |  |
| `description` | `ReactNode` |  |  |
| `footer` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` |  | Heading level of the title. Default 1, for a page whose main content is the form. |
| `onBack` | `(() => void)` |  | Shows a "Use a different email" button. |
| `onSuccess` | `((session: AuthSession) => void)` |  |  |
| `title` | `ReactNode` | `Check your email` |  |

## Example: Verify an email

Paste or type the code from the toast; it submits on the sixth digit.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { VerifyEmailForm } from '@glyphui/auth/ui'
import { Button, toast } from '@glyphui/ui'
import { useState } from 'react'

const adapter = memoryAdapter({
  latency: 400,
  onCode: ({ email, code }) => toast(`Email to ${email}`, { description: `Your code: ${code}` }),
})

function Demo() {
  const { signUp, signOut, user } = useAuth()
  const [email, setEmail] = useState<string | null>(null)
  if (user)
    return (
      <Button
        variant="outline"
        onClick={async () => {
          await signOut()
          setEmail(null)
        }}
      >
        Verified {user.email}. Start over
      </Button>
    )
  if (!email)
    return (
      <Button
        onClick={async () => {
          const address = `new.${Date.now()}@example.com`
          await signUp({ email: address, password: 'long password' })
          setEmail(address)
        }}
      >
        Create a demo account
      </Button>
    )
  return <VerifyEmailForm headingLevel={3} email={email} onBack={() => setEmail(null)} />
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Demo />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/verify-email-form

---

# CodeViewer

> Source code with syntax colors from your theme, line numbers, highlighted lines, a wrap toggle and copy.

Status: beta. Category: Viewers.

```ts
import { CodeViewer } from '@glyphui/viewers/code'
```

Exports: `CodeViewer`, `codeViewerStyles`, `parseLineRanges`, `highlightCode`, `languageFromFileName`, `resolveLanguage`.

## Notes

- Install the optional peer dependency first: npm install shiki.
- Colors are CSS variables (--shiki-token-*) mapped to your theme in @glyphui/viewers/styles.css, so code follows light and dark mode and every preset.
- Grammars load on first use, one language at a time, with Shiki’s JavaScript engine (no WebAssembly).

## CodeViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `bordered` | `boolean` |  | Draw the viewer as a bordered card. Default true. |
| `className` | `string` |  |  |
| `code` | `string` |  | The code to show. |
| `fileName` | `string` |  | Shown in the header; also used to guess the language. |
| `height` | `string \| number` |  | Height of the viewer; content scrolls inside. Grows with the code by default. |
| `hideHeader` | `boolean` |  | Hide the header bar (file name, language, wrap and copy). |
| `highlightLines` | `string \| readonly (number \| readonly [number, number])[]` |  | Line numbers to highlight, e.g. `[3, [6, 9]]` or `"3,6-9"`. |
| `language` | `string` |  | Language id or file extension: `tsx`, `python`, `sql`… Guessed from `fileName` when unset. |
| `lineMarks` | `Readonly<Record<number, LineMark>>` |  | Marks for individual lines, by line number. Wins over `highlightLines`. |
| `lineNumbers` | `boolean` |  | Show line numbers. Default true. |
| `source` | `ViewerSource` |  | A source file to load instead of `code`: a URL, a File/Blob, or bytes. |
| `startLine` | `number` |  | Number of the first line. Default 1. |
| `wrap` | `boolean` |  | Wrap long lines instead of scrolling sideways. Users can toggle it. Default false. |

## Example: A source file

The language comes from the file name; lines 14–16 are highlighted.

```tsx
import { CodeViewer } from '@glyphui/viewers/code'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <CodeViewer source={fixture('reminders.ts')} highlightLines="14-16" className="w-full" />
}
```

## Example: A snippet

Pass code as a string, with wrapping on.

```tsx
import { CodeViewer } from '@glyphui/viewers/code'

const code = `def monthly_recurring_revenue(subscriptions):
    """Sum active subscriptions, normalizing annual plans to a monthly amount."""
    total = 0
    for sub in subscriptions:
        if sub.status != "active":
            continue
        total += sub.amount / 12 if sub.interval == "year" else sub.amount
    return round(total, 2)`

export default function Example() {
  return <CodeViewer code={code} language="python" fileName="metrics.py" wrap className="w-full" />
}
```

## Example: Without the header

Just the code, for embedding in your own layout.

```tsx
import { CodeViewer } from '@glyphui/viewers/code'

export default function Example() {
  return (
    <CodeViewer
      code={
        "SELECT customer, SUM(total) AS revenue\nFROM invoices\nWHERE status = 'paid'\nGROUP BY customer\nORDER BY revenue DESC;"
      }
      language="sql"
      hideHeader
      className="w-full max-w-xl"
    />
  )
}
```

Live page: https://glyphui.xyz/components/code-viewer

---

# Collapsible

> Shows and hides one region, such as advanced options or the rest of a long list.

Status: beta. Category: Data display.

```ts
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@glyphui/ui'
```

Exports: `Collapsible`, `CollapsibleTrigger`, `CollapsibleContent`, `collapsibleStyles`.

## Notes

- The content animates its height open and closed and stays mounted until the closing animation ends.
- For several expandable sections where one opens at a time, use Accordion.

## Collapsible props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |

## Example: Advanced options

```tsx
import {
  Button,
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
  Field,
  Input,
  Switch,
} from '@glyphui/ui'
import { ChevronDown } from 'lucide-react'

export default function Example() {
  return (
    <Collapsible className="grid w-full max-w-sm gap-3">
      <Field label="Webhook URL">
        <Input defaultValue="https://api.acme.com/hooks/glyph" />
      </Field>
      <CollapsibleTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="group justify-self-start"
          rightIcon={
            <ChevronDown className="transition-transform group-data-[state=open]:rotate-180" />
          }
        >
          Advanced options
        </Button>
      </CollapsibleTrigger>
      <CollapsibleContent>
        <div className="grid gap-4 pt-1">
          <Field label="Signing secret" description="Used to verify that requests come from Glyph.">
            <Input type="password" defaultValue="whsec_7f3a91" />
          </Field>
          <Field
            orientation="horizontal"
            label="Retry failed deliveries"
            description="Up to 5 times over 24 hours."
          >
            <Switch defaultChecked />
          </Field>
        </div>
      </CollapsibleContent>
    </Collapsible>
  )
}
```

## Example: Show more

Reveal the rest of a list without leaving the page.

```tsx
import { Button, Collapsible, CollapsibleContent, CollapsibleTrigger } from '@glyphui/ui'
import { useState } from 'react'

const releases = [
  '0.2.0 · 25 new components',
  '0.1.1 · Signed releases',
  '0.1.0 · First public release',
  '0.0.3 · Theme engine',
  '0.0.2 · Presets',
  '0.0.1 · Initial commit',
]

export default function Example() {
  const [open, setOpen] = useState(false)
  return (
    <Collapsible open={open} onOpenChange={setOpen} className="w-full max-w-sm">
      <ul className="grid divide-y divide-border rounded-lg border border-border text-small">
        {releases.slice(0, 3).map((r) => (
          <li key={r} className="px-4 py-2.5">
            {r}
          </li>
        ))}
      </ul>
      <CollapsibleContent>
        <ul className="mt-2 grid divide-y divide-border rounded-lg border border-border text-small text-muted-foreground">
          {releases.slice(3).map((r) => (
            <li key={r} className="px-4 py-2.5">
              {r}
            </li>
          ))}
        </ul>
      </CollapsibleContent>
      <CollapsibleTrigger asChild>
        <Button variant="link" size="sm" className="mt-2">
          {open ? 'Show fewer releases' : `Show ${releases.length - 3} older releases`}
        </Button>
      </CollapsibleTrigger>
    </Collapsible>
  )
}
```

Live page: https://glyphui.xyz/components/collapsible

---

# Combobox

> A select with search for long option lists. Single or multiple values; the value type comes from your options.

Status: beta. Category: Forms.

```ts
import { Combobox } from '@glyphui/ui'
```

Exports: `Combobox`, `comboboxStyles`.

## Notes

- Built on cmdk and Radix Popover: type to filter, arrow keys to move, Enter to choose, Escape to close.
- Search matches the label and any keywords you add to an option.
- Pass name to submit the value with a native form.

## Example: Searchable select

```tsx
import { Combobox, Field } from '@glyphui/ui'
import { useState } from 'react'

const timezones = [
  { value: 'utc', label: 'UTC', keywords: ['gmt'] },
  {
    value: 'america-new-york',
    label: 'New York',
    description: 'UTC−5',
    keywords: ['est', 'eastern'],
  },
  {
    value: 'america-los-angeles',
    label: 'Los Angeles',
    description: 'UTC−8',
    keywords: ['pst', 'pacific'],
  },
  { value: 'europe-berlin', label: 'Berlin', description: 'UTC+1', keywords: ['cet'] },
  { value: 'asia-kolkata', label: 'Kolkata', description: 'UTC+5:30', keywords: ['ist', 'india'] },
  { value: 'asia-tokyo', label: 'Tokyo', description: 'UTC+9', keywords: ['jst'] },
] as const

type Timezone = (typeof timezones)[number]['value']

export default function Example() {
  const [zone, setZone] = useState<Timezone | null>('europe-berlin')
  return (
    <Field label="Timezone" description="Try “ist” or “pacific”." className="max-w-xs">
      <Combobox
        options={timezones}
        value={zone}
        onValueChange={setZone}
        placeholder="Pick a timezone"
      />
    </Field>
  )
}
```

## Example: Multiple

Selected values show as chips; the list stays open.

```tsx
import { Combobox, Field } from '@glyphui/ui'

const labels = [
  { value: 'bug', label: 'Bug' },
  { value: 'feature', label: 'Feature' },
  { value: 'design', label: 'Design' },
  { value: 'docs', label: 'Documentation' },
  { value: 'performance', label: 'Performance' },
  { value: 'a11y', label: 'Accessibility', keywords: ['a11y'] },
]

export default function Example() {
  return (
    <Field label="Labels" className="max-w-xs">
      <Combobox
        multiple
        options={labels}
        defaultValue={['bug', 'design']}
        searchPlaceholder="Filter labels…"
      />
    </Field>
  )
}
```

Live page: https://glyphui.xyz/components/combobox

---

# CommandMenu

> A ⌘K command palette: search, grouped actions and keyboard navigation in a modal dialog.

Status: beta. Category: Navigation.

```ts
import { CommandMenu, Command, CommandInput, CommandList, CommandEmpty, CommandGroup } from '@glyphui/ui'
```

Exports: `CommandMenu`, `Command`, `CommandInput`, `CommandList`, `CommandEmpty`, `CommandGroup`, `CommandItem`, `CommandSeparator`, `useCommandMenuShortcut`, `commandMenuStyles`.

## Notes

- Items close the menu after onSelect by default; pass closeOnSelect={false} to keep it open.
- Shortcuts on items are display-only hints; bind the keys yourself if they should work globally.

## Example: Command palette

Press ⌘K (or Ctrl+K) anywhere on the page.

```tsx
import {
  Button,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandMenu,
  CommandSeparator,
  Kbd,
  useCommandMenuShortcut,
} from '@glyphui/ui'
import { CircleDot, FilePlus, Moon, Search, Settings2, Users } from 'lucide-react'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(false)
  const [last, setLast] = useState<string | null>(null)
  useCommandMenuShortcut(setOpen)

  return (
    <div className="flex flex-wrap items-center gap-3">
      <Button variant="outline" leftIcon={<Search />} onClick={() => setOpen(true)}>
        Search
        <Kbd className="ml-1">⌘K</Kbd>
      </Button>
      {last && <span className="text-small text-muted-foreground">Ran: {last}</span>}

      <CommandMenu open={open} onOpenChange={setOpen}>
        <CommandInput placeholder="Type a command or search…" />
        <CommandList>
          <CommandEmpty>No commands match.</CommandEmpty>
          <CommandGroup heading="Issues">
            <CommandItem icon={<FilePlus />} shortcut="C" onSelect={() => setLast('New issue')}>
              New issue
            </CommandItem>
            <CommandItem icon={<CircleDot />} onSelect={() => setLast('My issues')}>
              My issues
            </CommandItem>
          </CommandGroup>
          <CommandSeparator />
          <CommandGroup heading="Workspace">
            <CommandItem icon={<Users />} onSelect={() => setLast('Invite people')}>
              Invite people
            </CommandItem>
            <CommandItem
              icon={<Moon />}
              shortcut={['⌘', 'J']}
              onSelect={() => setLast('Toggle dark mode')}
            >
              Toggle dark mode
            </CommandItem>
            <CommandItem
              icon={<Settings2 />}
              shortcut={['⌘', ',']}
              onSelect={() => setLast('Settings')}
            >
              Settings
            </CommandItem>
          </CommandGroup>
        </CommandList>
      </CommandMenu>
    </div>
  )
}
```

## Example: Inline

Command without the dialog, for search panels.

```tsx
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from '@glyphui/ui'

const docs = ['Button', 'Card', 'Combobox', 'DataTable', 'Form', 'Sidebar', 'Tabs']

export default function Example() {
  return (
    <Command className="max-w-sm rounded-lg border border-border shadow-md">
      <CommandInput placeholder="Search components…" />
      <CommandList>
        <CommandEmpty>No components found.</CommandEmpty>
        {docs.map((name) => (
          <CommandItem key={name}>{name}</CommandItem>
        ))}
      </CommandList>
    </Command>
  )
}
```

Live page: https://glyphui.xyz/components/command-menu

---

# Container

> Centers content at a readable maximum width with consistent side gutters.

Status: stable. Category: Layout.

```ts
import { Container } from '@glyphui/ui'
```

Exports: `Container`, `containerStyles`.

## Container props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `size` | `"sm" \| "md" \| "lg" \| "xl" \| "full"` |  |  |

## Example: Sizes

```tsx
import { Container } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-2">
      {(['sm', 'md', 'lg', 'xl'] as const).map((size) => (
        <Container key={size} size={size}>
          <div className="rounded-md border border-dashed border-border-strong bg-muted px-3 py-2 font-mono text-caption text-muted-foreground">
            size="{size}"
          </div>
        </Container>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/container

---

# ContextMenu

> A menu opened by right-click or long-press on an area, with the same items as DropdownMenu.

Status: beta. Category: Overlays.

```ts
import { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioGroup } from '@glyphui/ui'
```

Exports: `ContextMenu`, `ContextMenuTrigger`, `ContextMenuContent`, `ContextMenuItem`, `ContextMenuCheckboxItem`, `ContextMenuRadioGroup`, `ContextMenuRadioItem`, `ContextMenuLabel`, `ContextMenuSeparator`, `ContextMenuShortcut`, `ContextMenuGroup`, `ContextMenuSub`, `ContextMenuSubTrigger`, `ContextMenuSubContent`, `contextMenuStyles`.

## Notes

- Context menus are hard to discover. Offer the same actions in a visible place too, such as a DropdownMenu on a "more" button.
- Items take icon, shortcut, tone="danger" and inset, exactly like DropdownMenuItem.

## ContextMenuItem props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `icon` | `ReactNode` |  |  |
| `inset` | `boolean` |  | Indent to line up with checkbox and radio items. |
| `shortcut` | `ReactNode` |  | Keyboard hint shown at the end, e.g. "⌘C". Display only. |
| `tone` | `"default" \| "danger"` |  | `danger` for destructive actions. |

## Example: File actions

Right-click (or long-press on touch) the card.

```tsx
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuTrigger,
} from '@glyphui/ui'
import { Copy, Download, FileText, Pencil, Share2, Trash2 } from 'lucide-react'

export default function Example() {
  return (
    <ContextMenu>
      <ContextMenuTrigger asChild>
        <div className="flex w-72 select-none items-center gap-3 rounded-lg border border-dashed border-border-strong p-4">
          <FileText className="size-8 text-muted-foreground" aria-hidden="true" />
          <div className="grid">
            <span className="text-small font-medium">Q3 board update.pdf</span>
            <span className="text-caption text-muted-foreground">2.4 MB · Right-click me</span>
          </div>
        </div>
      </ContextMenuTrigger>
      <ContextMenuContent>
        <ContextMenuItem icon={<Pencil />} shortcut="F2">
          Rename
        </ContextMenuItem>
        <ContextMenuItem icon={<Copy />} shortcut="⌘D">
          Duplicate
        </ContextMenuItem>
        <ContextMenuItem icon={<Download />}>Download</ContextMenuItem>
        <ContextMenuSub>
          <ContextMenuSubTrigger icon={<Share2 />}>Share</ContextMenuSubTrigger>
          <ContextMenuSubContent>
            <ContextMenuItem>Copy link</ContextMenuItem>
            <ContextMenuItem>Email</ContextMenuItem>
            <ContextMenuItem>Slack</ContextMenuItem>
          </ContextMenuSubContent>
        </ContextMenuSub>
        <ContextMenuSeparator />
        <ContextMenuItem icon={<Trash2 />} tone="danger" shortcut="⌫">
          Move to trash
        </ContextMenuItem>
      </ContextMenuContent>
    </ContextMenu>
  )
}
```

## Example: Checkbox and radio items

```tsx
import {
  ContextMenu,
  ContextMenuCheckboxItem,
  ContextMenuContent,
  ContextMenuLabel,
  ContextMenuRadioGroup,
  ContextMenuRadioItem,
  ContextMenuSeparator,
  ContextMenuTrigger,
} from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [grid, setGrid] = useState(true)
  const [rulers, setRulers] = useState(false)
  const [zoom, setZoom] = useState('100')
  return (
    <ContextMenu>
      <ContextMenuTrigger asChild>
        <div className="flex h-40 w-80 items-center justify-center rounded-lg border border-dashed border-border-strong bg-subtle text-small text-muted-foreground">
          Canvas · zoom {zoom}% · right-click
        </div>
      </ContextMenuTrigger>
      <ContextMenuContent>
        <ContextMenuLabel inset>View</ContextMenuLabel>
        <ContextMenuCheckboxItem checked={grid} onCheckedChange={setGrid}>
          Show grid
        </ContextMenuCheckboxItem>
        <ContextMenuCheckboxItem checked={rulers} onCheckedChange={setRulers}>
          Show rulers
        </ContextMenuCheckboxItem>
        <ContextMenuSeparator />
        <ContextMenuLabel inset>Zoom</ContextMenuLabel>
        <ContextMenuRadioGroup value={zoom} onValueChange={setZoom}>
          <ContextMenuRadioItem value="50">50%</ContextMenuRadioItem>
          <ContextMenuRadioItem value="100">100%</ContextMenuRadioItem>
          <ContextMenuRadioItem value="200">200%</ContextMenuRadioItem>
        </ContextMenuRadioGroup>
      </ContextMenuContent>
    </ContextMenu>
  )
}
```

Live page: https://glyphui.xyz/components/context-menu

---

# CopyButton

> Copies a value to the clipboard and confirms it with a check and a screen-reader announcement.

Status: beta. Category: Actions.

```ts
import { CopyButton } from '@glyphui/ui'
```

Exports: `CopyButton`, `copyButtonStyles`.

## Notes

- Without children it is icon-only and labelled "Copy"; pass aria-label to say what is copied.
- If the browser blocks clipboard access, nothing changes, so keep the value visible and selectable.
- Accepts Button variants and sizes; defaults to outline.

## CopyButton props

| Prop | Type | Default | Description |
|---|---|---|---|
| `value` (required) | `string` |  | Text written to the clipboard. |
| `children` | `ReactNode` |  | Visible label. Without it the button is icon-only, labelled "Copy". |
| `copiedLabel` | `string` |  | Announced and shown after copying. Default "Copied". |
| `fullWidth` | `boolean` |  |  |
| `loading` | `boolean` |  | Shows a spinner, disables the button and sets `aria-busy`. |
| `onCopy` | `((value: string) => void)` |  |  |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `timeout` | `number` |  | How long the copied state lasts, in ms. Default 1500. |
| `variant` | `"link" \| "primary" \| "danger" \| "outline" \| "secondary" \| "ghost"` |  |  |

## Example: Next to a value

```tsx
import { CopyButton, Field, Input } from '@glyphui/ui'

export default function Example() {
  const key = 'gk_live_51Hx9Q2eZvKYlo2C8a7P'
  return (
    <Field
      label="Publishable key"
      description="Safe to use in your frontend."
      className="w-full max-w-md"
    >
      <div className="flex gap-2">
        <Input readOnly value={key} className="font-mono" />
        <CopyButton value={key} aria-label="Copy publishable key" />
      </div>
    </Field>
  )
}
```

## Example: With a label

```tsx
import { CopyButton } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <CopyButton value="npm install @glyphui/ui">Copy install command</CopyButton>
      <CopyButton value="https://glyphui.xyz/" variant="ghost" size="sm" copiedLabel="Link copied">
        Copy link
      </CopyButton>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/copy-button

---

# CsvViewer

> Open a CSV as a table: typed columns, search, sort, filters from the data, column controls and export of the filtered rows.

Status: beta. Category: Viewers.

```ts
import { CsvViewer } from '@glyphui/viewers/csv'
```

Exports: `CsvViewer`, `csvViewerStyles`, `parseCsv`, `buildTable`, `inferColumnType`.

## Notes

- Install the optional peer dependencies first: npm install papaparse @tanstack/react-table @tanstack/react-virtual.
- Quotes, escaped quotes, line breaks inside quoted cells and a byte-order mark are all handled. Rows that can’t be read cleanly are listed with their row numbers.
- A column is typed when 95% of its values agree, so one “n/a” doesn’t turn numbers into text. Columns with a few repeating values get a multi-select filter.
- The header row is detected; people can turn it off, and change the delimiter, from the toolbar.

## CsvViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `content` | `string` |  | CSV text, instead of `source`. |
| `delimiter` | `string` |  | Starting delimiter. Detected by default. |
| `fileName` | `string` |  | Name used for the export file and the table label. |
| `header` | `boolean \| "auto"` |  | Whether the first row names the columns. `auto` (default) guesses. |
| `height` | `string \| number` |  | Height of the table area. Default 480. |
| `maxRows` | `number` |  | Stops reading after this many rows. Default 1,000,000. |
| `onParsed` | `((result: CsvParseResult) => void)` |  | Called after each successful parse. |
| `source` | `ViewerSource` |  | The CSV file: a URL, a File/Blob, or bytes. |

## Example: Customers

Numbers, dates and yes/no columns are detected, each with a matching filter.

```tsx
import { CsvViewer } from '@glyphui/viewers/csv'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <CsvViewer source={fixture('customers.csv')} height={420} className="w-full" />
}
```

## Example: 50,000 rows

Big files parse in a worker with progress and render only the rows in view.

```tsx
import { CsvViewer } from '@glyphui/viewers/csv'
import { useMemo } from 'react'

const regions = ['North America', 'Europe', 'Asia Pacific', 'Latin America']

/** 50,000 rows of order data, generated in the browser. */
function generate(rows: number): string {
  const lines = ['order_id,region,amount,shipped,created']
  for (let i = 0; i < rows; i++) {
    const day = String((i % 28) + 1).padStart(2, '0')
    const month = String((i % 12) + 1).padStart(2, '0')
    lines.push(
      `${100000 + i},${regions[i % 4]},${((i * 7919) % 50000) / 100},${i % 3 !== 0},2026-${month}-${day}`,
    )
  }
  return lines.join('\n')
}

export default function Example() {
  const csv = useMemo(() => generate(50_000), [])
  return <CsvViewer content={csv} fileName="orders.csv" height={420} className="w-full" />
}
```

## Example: Pasted text

Semicolon-separated data, detected automatically.

```tsx
import { Field, Textarea } from '@glyphui/ui'
import { CsvViewer } from '@glyphui/viewers/csv'
import { useState } from 'react'

const sample = `country;capital;population_millions;eu_member
France;Paris;68.4;true
Germany;Berlin;84.5;true
Norway;Oslo;5.5;false
Spain;Madrid;48.6;true
Switzerland;Bern;8.9;false`

export default function Example() {
  const [text, setText] = useState(sample)
  return (
    <div className="grid w-full gap-4">
      <Field label="Paste CSV">
        <Textarea
          rows={4}
          value={text}
          onChange={(event) => setText(event.target.value)}
          className="font-mono"
        />
      </Field>
      <CsvViewer content={text} fileName="countries.csv" height={280} />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/csv-viewer

---

# Cta

> The closing call to action near the end of a page, as a raised card or an open band.

Status: beta. Category: Blocks.

```ts
import { Cta } from '@glyphui/blocks'
```

Exports: `Cta`, `ctaStyles`.

## Cta props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  |  |
| `actions` | `ReactNode` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `description` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `variant` | `"band" \| "card"` | `card` | `card` (default) is a raised panel; `band` is open text across the page. |

## Example: Card

```tsx
import { Cta } from '@glyphui/blocks'
import { Button } from '@glyphui/ui'

export default function Example() {
  return (
    <Cta
      title="Send your next invoice in five minutes"
      description="Connect your payment provider, pick a template, and you’re done."
      actions={
        <>
          <Button size="lg">Start free</Button>
          <Button size="lg" variant="ghost">
            Talk to sales
          </Button>
        </>
      }
    />
  )
}
```

## Example: Band

```tsx
import { Cta } from '@glyphui/blocks'
import { Button } from '@glyphui/ui'

export default function Example() {
  return (
    <Cta variant="band" title="Ready when you are" actions={<Button>Create an account</Button>} />
  )
}
```

Live page: https://glyphui.xyz/components/cta

---

# DataTable

> The table every app needs: search, filter chips, multi-column sorting, pagination, selection with bulk actions, column controls, row links and details, inline editing and CSV export, in client or server mode.

Status: stable. Category: Patterns.

```ts
import { DataTable } from '@glyphui/ui/data-table'
```

Exports: `DataTable`, `dataTableStyles`, `filterChipStyles`, `createColumnHelper`, `useTableUrlState`, `getFilterList`, `parseTableSearch`, `tableSearch`, `writeTableSearch`, `historyAdapter`, `editableCell`, `exportTableCsv`, `toCsv`.

## Notes

- URL state format: page (1-based) and size, sort=column or column.desc (comma-separated for several), q for search, one f.<column> parameter per filter value (f.status=open&f.status=pending), and hide=col,col. Build links with tableSearch(state); a prefix keeps several tables apart.
- Columns are typed from your row type via createColumnHelper<T>(). Set meta: { align: "right" } on numeric columns.
- Requires @tanstack/react-table version 8 as a peer dependency (install @tanstack/react-table@8; version 9 is not supported yet).
- Pass columns to useTableUrlState so filters decode by type: a shared link with one status still gives a multi filter an array. In server code, getFilterList(state.columnFilters, "status") always returns an array.
- Every piece of state (page, sort, search, filters, visibility, sizes, pinning, order, selection, expanded rows, density) can be controlled through state and onStateChange, or left to the table. Pass getRowId so selections survive paging and data changes.
- Server mode: pass the current page as data, the total as rowCount (or hasNextPage for cursor APIs), and keep loading true while fetching. With TanStack Query, use placeholderData: keepPreviousData so the old page stays until the new one arrives.
- Select-all across pages sets allMatchingSelected in state; in server mode act on the query rather than the row ids.
- Clicks on buttons, links, checkboxes and menus inside a clickable row act on themselves. getRowHref renders the first column as a real link, so keyboard and middle-click work.
- CSV exports quote fields as RFC 4180 requires and prefix text starting with =, +, - or @ so spreadsheets don’t run it as a formula.
- For 10,000+ rows, pass virtualize from @glyphui/ui/data-table/virtual.

## DataTable props

| Prop | Type | Default | Description |
|---|---|---|---|
| `columns` (required) | `ColumnDef<T, any>[]` |  | Build with `createColumnHelper<T>()` for typed accessors. |
| `data` (required) | `T[] \| undefined` |  |  |
| `aria-label` | `string` |  |  |
| `bulkActions` | `((selection: TableSelection<T>) => ReactNode)` |  | Actions for the selected rows, in a floating bar while any are selected. |
| `className` | `string` |  |  |
| `columnControls` | `boolean \| Partial<ColumnControls>` |  | Column features: `true` turns on hiding (a View menu and each column's menu), resizing, pinning and reordering; or pick some. |
| `defaultState` | `Partial<DataTableState>` |  | Starting values for slices you don't control. |
| `density` | `"default" \| "compact" \| "comfortable"` |  |  |
| `densityToggle` | `boolean` |  | Adds compact / default / comfortable to the View menu. |
| `empty` | `ReactNode` |  | Shown when there are no rows at all (not when a search matches nothing). |
| `error` | `unknown` |  | Shows an error state with a retry button when `onRetry` is set. |
| `exportCsv` | `boolean \| { fileName?: string; bom?: boolean; fetchAll?: (() => T[] \| Promise<T[]>) \| undefined; } \| undefined` |  | Adds an Export menu: this page, selected rows or all rows as CSV. In server mode pass `fetchAll` so "All rows" can load every page. |
| `getRowCanExpand` | `((row: T) => boolean)` |  |  |
| `getRowCanSelect` | `((row: T) => boolean)` |  | Rows this returns false for get a disabled checkbox. |
| `getRowHref` | `((row: T) => string)` |  | Makes each row a link: the first data column links there and the row is clickable. |
| `getRowId` | `((row: T, index: number) => string)` |  | Stable row ids. Needed to keep selections across pages and data changes. |
| `hasNextPage` | `boolean` |  | Cursor paging (APIs without totals): whether a next page exists. |
| `initialSorting` | `SortingState` |  |  |
| `loading` | `boolean` |  | Shows skeleton rows. In server mode the current rows stay, under a progress bar. |
| `maxHeight` | `string \| number` |  | Scrolls inside the table past this height, with the header pinned. |
| `mobile` | `"scroll" \| "cards"` |  | Below the `sm` breakpoint: scroll sideways (default) or show each row as a card. |
| `mode` | `"client" \| "server"` |  | `client` (default) sorts, filters and pages `data` in the browser. `server` hands every change to you through `onStateChange`: pass the current page as `data` and the total as `rowCount`. |
| `onCellEdit` | `((edit: CellEdit<T>) => unknown)` |  | Saves edits from `editableCell()` columns. Reject to roll the cell back. |
| `onColumnFiltersChange` | `((filters: ColumnFiltersState) => void)` |  |  |
| `onLoadMore` | `(() => void)` |  | Shows "Load more" instead of pages; append rows to `data` when it's called. |
| `onPaginationChange` | `((pagination: PaginationState) => void)` |  |  |
| `onRetry` | `(() => unknown)` |  |  |
| `onRowClick` | `((row: T, event: MouseEvent<HTMLElement, MouseEvent>) => void)` |  | Makes rows clickable. Clicks on buttons, links and checkboxes inside are left alone. |
| `onSearchChange` | `((search: string) => void)` |  |  |
| `onSelectionChange` | `((rows: T[]) => void)` |  |  |
| `onSortingChange` | `((sorting: SortingState) => void)` |  |  |
| `onStateChange` | `((state: DataTableState, changed: keyof DataTableState) => void)` |  | Called with the whole next state, and the slice that changed, on every change. |
| `pageSize` | `number \| false` |  | Rows per page, or `false` to show every row. Default 10. |
| `pageSizeOptions` | `readonly number[]` |  | Choices in "Rows per page". Default 10, 20, 50, 100. |
| `renderSubRow` | `((row: T) => ReactNode)` |  | Adds an expand button to each row; this content opens below it. |
| `rowCount` | `number` |  | Server mode: rows across all pages. Omit it and pass `hasNextPage` for cursor paging. |
| `search` | `boolean \| { placeholder?: string; }` |  | Adds a search box. In client mode it matches every column. |
| `selectable` | `boolean` |  | Adds a checkbox column. |
| `state` | `Partial<DataTableState>` |  | Controlled state: any slice you pass is yours to update from `onStateChange`. |
| `toolbar` | `ReactNode` |  | Extra controls at the end of the toolbar. |
| `variant` | `"card" \| "plain"` |  |  |
| `virtualize` | `DataTableVirtualizer` |  | Renders only rows in view. Create with `virtualRows()` from `@glyphui/ui/data-table/virtual`. |

## Example: Sorting, search and selection

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'

interface Invoice {
  id: string
  customer: string
  status: 'paid' | 'open' | 'overdue'
  total: number
}

const invoices: Invoice[] = [
  { id: 'INV-1042', customer: 'Northwind', status: 'paid', total: 1240 },
  { id: 'INV-1043', customer: 'Globex', status: 'open', total: 86.5 },
  { id: 'INV-1044', customer: 'Initech', status: 'overdue', total: 12900.75 },
  { id: 'INV-1045', customer: 'Umbrella', status: 'paid', total: 410 },
  { id: 'INV-1046', customer: 'Hooli', status: 'open', total: 2380 },
]

const tone = { paid: 'success', open: 'info', overdue: 'danger' } as const
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', {
    header: 'Invoice',
    cell: (info) => <span className="font-mono text-caption">{info.getValue()}</span>,
  }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={tone[info.getValue()]} dot>
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      search={{ placeholder: 'Search invoices…' }}
      selectable
      pageSize={4}
    />
  )
}
```

## Example: Filter chips

Declare meta.filter on a column: select, multi (with counts), range, date range or text. Shift-click headers to sort by more than one column.

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusOptions, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const daysAgo = (n: number) => new Date(Date.now() - n * 86_400_000)

const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', {
    header: 'Customer',
    meta: { filter: { type: 'text', placeholder: 'Company name' } },
  }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
    // Faceted counts appear beside each option, from the other active filters.
    meta: { filter: { type: 'multi', options: statusOptions } },
  }),
  col.accessor('plan', {
    header: 'Plan',
    meta: {
      filter: {
        type: 'select',
        options: [
          { value: 'Starter', label: 'Starter' },
          { value: 'Growth', label: 'Growth' },
          { value: 'Enterprise', label: 'Enterprise' },
        ],
      },
    },
  }),
  col.accessor('issued', {
    header: 'Issued',
    cell: (info) => formatDay(info.getValue()),
    meta: {
      filter: {
        type: 'date-range',
        presets: [
          { label: 'Last 7 days', range: () => ({ from: daysAgo(6), to: new Date() }) },
          { label: 'Last 30 days', range: () => ({ from: daysAgo(29), to: new Date() }) },
        ],
      },
    },
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: {
      align: 'right',
      filter: { type: 'range', min: 0, step: 100, format: (n) => usd.format(n) },
    },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={8}
      defaultState={{ columnFilters: [{ id: 'status', value: ['open', 'overdue'] }] }}
    />
  )
}
```

## Example: Server mode

mode="server" hands paging, sorting, search and filters to your API through onStateChange. Rows stay on screen while the next page loads.

```tsx
import { Badge, Button, toast } from '@glyphui/ui'
import {
  createColumnHelper,
  DataTable,
  type DataTableState,
  getFilterList,
} from '@glyphui/ui/data-table'
import { Archive } from 'lucide-react'
import { useEffect, useState } from 'react'
import { fetchInvoices, formatDay, type Invoice, statusOptions, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()

export default function Example() {
  const [query, setQuery] = useState<
    Pick<DataTableState, 'pagination' | 'sorting' | 'search' | 'columnFilters'>
  >({
    pagination: { pageIndex: 0, pageSize: 10 },
    sorting: [{ id: 'issued', desc: true }],
    search: '',
    columnFilters: [],
  })
  const [result, setResult] = useState<Awaited<ReturnType<typeof fetchInvoices>>>()
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let current = true
    setLoading(true)
    // Always an array, even when a shared link held a single status.
    const statuses = getFilterList(query.columnFilters, 'status')
    fetchInvoices({
      page: query.pagination.pageIndex,
      pageSize: query.pagination.pageSize,
      sort: query.sorting[0],
      search: query.search,
      ...(statuses.length > 0 && { statuses }),
    }).then((next) => {
      if (!current) return
      setResult(next)
      setLoading(false)
    })
    return () => {
      current = false
    }
  }, [query])

  const columns = [
    col.accessor('id', {
      header: 'Invoice',
      cell: (info) => <span className="font-mono text-caption">{info.getValue()}</span>,
    }),
    col.accessor('customer', { header: 'Customer' }),
    col.accessor('status', {
      header: 'Status',
      enableSorting: false,
      cell: (info) => (
        <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
          {info.getValue()}
        </Badge>
      ),
      meta: {
        // The server sends counts, so the filter shows them without loading every row.
        filter: {
          type: 'multi',
          options: statusOptions.map((o) => ({ ...o, count: result?.statusCounts[o.value] ?? 0 })),
        },
      },
    }),
    col.accessor('issued', { header: 'Issued', cell: (info) => formatDay(info.getValue()) }),
    col.accessor('total', {
      header: 'Total',
      cell: (info) => usd.format(info.getValue()),
      meta: { align: 'right' },
    }),
  ]

  return (
    <DataTable
      aria-label="Invoices"
      mode="server"
      data={result?.rows}
      rowCount={result?.total}
      loading={loading}
      columns={columns}
      getRowId={(row) => row.id}
      state={query}
      onStateChange={(next) =>
        setQuery({
          pagination: next.pagination,
          sorting: next.sorting,
          search: next.search,
          columnFilters: next.columnFilters,
        })
      }
      search={{ placeholder: 'Search 312 invoices…' }}
      selectable
      bulkActions={(selection) => (
        <Button
          size="sm"
          variant="outline"
          leftIcon={<Archive />}
          onClick={() => {
            toast.success(`Archived ${selection.count} invoices`)
            selection.clear()
          }}
        >
          Archive
        </Button>
      )}
    />
  )
}
```

## Example: State in the URL

useTableUrlState keeps the view shareable and the back button working, with any router.

```tsx
import { Badge, Button } from '@glyphui/ui'
import { createColumnHelper, DataTable, useTableUrlState } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusOptions, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
    meta: { filter: { type: 'multi', options: statusOptions } },
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  // Page, sort, search, filters and hidden columns live in the URL as `orders.*` params.
  const url = useTableUrlState({ prefix: 'orders', pageSize: 5 })
  return (
    <DataTable
      aria-label="Orders"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={5}
      search={{ placeholder: 'Search orders…' }}
      columnControls={{ hide: true }}
      toolbar={
        <Button variant="ghost" size="sm" onClick={url.reset}>
          Reset view
        </Button>
      }
      {...url}
    />
  )
}
```

## Example: Row actions and bulk actions

Select rows (or every matching row) and act on them from the floating bar.

```tsx
import {
  Badge,
  Button,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  IconButton,
  toast,
  useConfirm,
} from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { Copy, MoreHorizontal, Send, Trash2 } from 'lucide-react'
import { useState } from 'react'
import { type Invoice, invoices as seed, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()

export default function Example() {
  const [rows, setRows] = useState(seed)
  const confirm = useConfirm()

  async function remove(ids: string[]) {
    const ok = await confirm({
      title: ids.length === 1 ? `Delete ${ids[0]}?` : `Delete ${ids.length} invoices?`,
      description: 'Customers keep any PDFs already sent.',
      tone: 'danger',
    })
    if (!ok) return false
    setRows((current) => current.filter((row) => !ids.includes(row.id)))
    toast.success(ids.length === 1 ? 'Invoice deleted' : `${ids.length} invoices deleted`)
    return true
  }

  const columns = [
    col.accessor('id', { header: 'Invoice' }),
    col.accessor('customer', { header: 'Customer' }),
    col.accessor('status', {
      header: 'Status',
      cell: (info) => (
        <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
          {info.getValue()}
        </Badge>
      ),
    }),
    col.accessor('total', {
      header: 'Total',
      cell: (info) => usd.format(info.getValue()),
      meta: { align: 'right' },
    }),
    col.display({
      id: 'actions',
      header: () => <span className="sr-only">Actions</span>,
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <IconButton
              icon={<MoreHorizontal />}
              aria-label={`Actions for ${row.original.id}`}
              size="sm"
            />
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              icon={<Send />}
              onSelect={() => toast.success(`Reminder sent to ${row.original.email}`)}
            >
              Send reminder
            </DropdownMenuItem>
            <DropdownMenuItem
              icon={<Copy />}
              onSelect={() => navigator.clipboard?.writeText(row.original.id)}
            >
              Copy ID
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              icon={<Trash2 />}
              tone="danger"
              onSelect={() => remove([row.original.id])}
            >
              Delete
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
      meta: { align: 'right', className: 'w-12' },
    }),
  ]

  return (
    <DataTable
      aria-label="Invoices"
      data={rows}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={8}
      selectable
      exportCsv={{ fileName: 'invoices.csv' }}
      bulkActions={(selection) => (
        <>
          <Button
            size="sm"
            variant="outline"
            leftIcon={<Send />}
            onClick={() => toast.success(`Sent ${selection.count} reminders`)}
          >
            Remind
          </Button>
          <Button
            size="sm"
            variant="danger"
            leftIcon={<Trash2 />}
            onClick={async () => {
              if (await remove(selection.ids)) selection.clear()
            }}
          >
            Delete
          </Button>
        </>
      )}
    />
  )
}
```

## Example: Column controls and density

Hide, resize, pin and reorder columns; pinned columns stay put while the table scrolls sideways.

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', {
    header: 'Invoice',
    size: 150,
    cell: (info) => <span className="font-mono text-caption">{info.getValue()}</span>,
  }),
  col.accessor('customer', { header: 'Customer', size: 180 }),
  col.accessor('email', { header: 'Billing email', size: 240 }),
  col.accessor('plan', { header: 'Plan', size: 120 }),
  col.accessor('status', {
    header: 'Status',
    size: 120,
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('issued', {
    header: 'Issued',
    size: 120,
    cell: (info) => formatDay(info.getValue()),
  }),
  col.accessor('total', {
    header: 'Total',
    size: 130,
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={20}
      // Hide, resize, pin and reorder from each column's ⋯ menu; drag headers to reorder.
      columnControls
      densityToggle
      maxHeight={380}
      defaultState={{ columnPinning: { left: ['id'] }, density: 'compact' }}
    />
  )
}
```

## Example: Clickable rows

Open details from a row.

```tsx
import {
  Badge,
  DescriptionItem,
  DescriptionList,
  Sheet,
  SheetBody,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { useState } from 'react'
import { formatDay, type Invoice, invoices, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  const [open, setOpen] = useState<Invoice | null>(null)
  return (
    <>
      <DataTable
        aria-label="Invoices"
        data={invoices}
        columns={columns}
        getRowId={(row) => row.id}
        pageSize={5}
        selectable
        // Click a row (or focus it and press Enter). Checkboxes and buttons keep their own clicks.
        onRowClick={(row) => setOpen(row)}
      />
      <Sheet open={open !== null} onOpenChange={(next) => !next && setOpen(null)}>
        <SheetContent>
          {open && (
            <>
              <SheetHeader>
                <SheetTitle>{open.id}</SheetTitle>
                <SheetDescription>{open.customer}</SheetDescription>
              </SheetHeader>
              <SheetBody>
                <DescriptionList>
                  <DescriptionItem term="Status">{open.status}</DescriptionItem>
                  <DescriptionItem term="Total">{usd.format(open.total)}</DescriptionItem>
                  <DescriptionItem term="Issued">{formatDay(open.issued)}</DescriptionItem>
                  <DescriptionItem term="Billing email">{open.email}</DescriptionItem>
                </DescriptionList>
              </SheetBody>
            </>
          )}
        </SheetContent>
      </Sheet>
    </>
  )
}
```

## Example: Expandable rows

```tsx
import { Badge, DescriptionItem, DescriptionList } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { formatDay, type Invoice, invoices, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices.slice(0, 6)}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={false}
      // Drafts have nothing to show yet.
      getRowCanExpand={(row) => row.status !== 'draft'}
      renderSubRow={(row) => (
        <DescriptionList className="grid-cols-2 gap-x-10 px-14 py-4 sm:grid-cols-4">
          <DescriptionItem term="Billing email">{row.email}</DescriptionItem>
          <DescriptionItem term="Plan">{row.plan}</DescriptionItem>
          <DescriptionItem term="Issued">{formatDay(row.issued)}</DescriptionItem>
          <DescriptionItem term="Tax (20%)">{usd.format(row.total * 0.2)}</DescriptionItem>
        </DescriptionList>
      )}
    />
  )
}
```

## Example: Inline editing

editableCell() edits in place. The new value shows at once and rolls back if saving fails: try more than 50 seats.

```tsx
import { toast } from '@glyphui/ui'
import { createColumnHelper, DataTable, editableCell } from '@glyphui/ui/data-table'
import { useState } from 'react'

interface Seat {
  id: string
  name: string
  role: 'admin' | 'member' | 'billing'
  seats: number
}

const roles = [
  { value: 'admin', label: 'Admin' },
  { value: 'member', label: 'Member' },
  { value: 'billing', label: 'Billing' },
]

const col = createColumnHelper<Seat>()
const columns = [
  col.accessor('name', {
    header: 'Team',
    cell: editableCell<Seat, string>({
      validate: (value) => (value.trim().length < 2 ? 'Use at least 2 characters' : null),
    }),
  }),
  col.accessor('role', {
    header: 'Default role',
    cell: editableCell<Seat, string>({ type: 'select', options: roles }),
  }),
  col.accessor('seats', {
    header: 'Seats',
    cell: editableCell<Seat, number>({
      type: 'number',
      validate: (value) => (value === null || value < 1 ? 'At least 1 seat' : null),
    }),
    meta: { align: 'right' },
  }),
]

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  const [rows, setRows] = useState<Seat[]>([
    { id: 't1', name: 'Design', role: 'member', seats: 8 },
    { id: 't2', name: 'Engineering', role: 'member', seats: 24 },
    { id: 't3', name: 'Finance', role: 'billing', seats: 3 },
  ])
  return (
    <DataTable
      aria-label="Teams"
      data={rows}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={false}
      onCellEdit={async ({ rowId, columnId, value }) => {
        await wait(500)
        // The server refuses more than 50 seats: the cell rolls back and explains why.
        if (columnId === 'seats' && Number(value) > 50) {
          toast.error('Plans include up to 50 seats per team')
          throw new Error('Plans include up to 50 seats per team')
        }
        setRows((current) =>
          current.map((row) => (row.id === rowId ? { ...row, [columnId]: value } : row)),
        )
      }}
    />
  )
}
```

## Example: CSV export

```tsx
import { Button } from '@glyphui/ui'
import { createColumnHelper, DataTable, exportTableCsv } from '@glyphui/ui/data-table'
import { Download } from 'lucide-react'
import { type Invoice, invoices, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('email', { header: 'Billing email' }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    // Spreadsheets want plain numbers, not "$1,240.00".
    meta: { align: 'right', csv: (value) => value.toFixed(2) },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={5}
      selectable
      // This page, selected rows, or every row that matches the search.
      exportCsv={{ fileName: 'invoices.csv' }}
      search
      toolbar={
        <Button
          variant="ghost"
          size="sm"
          leftIcon={<Download />}
          // Export without a table, e.g. after fetching everything from your API.
          onClick={() => exportTableCsv({ data: invoices, columns, fileName: 'all-invoices.csv' })}
        >
          All, without the table
        </Button>
      }
    />
  )
}
```

## Example: Cards on small screens

mobile="cards" turns each row into a card below 640px.

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusTone, usd } from '../data'

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
  // Kept out of the cards to save space.
  col.accessor('email', { header: 'Billing email', meta: { mobile: 'hidden' } }),
]

export default function Example() {
  // Narrow your window below 640px: each row becomes a card, the first column leads it.
  return (
    <DataTable
      aria-label="Invoices"
      data={invoices}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={4}
      selectable
      mobile="cards"
    />
  )
}
```

## Example: Loading and error

```tsx
import { SegmentedControl } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { useState } from 'react'

interface Deploy {
  id: string
  branch: string
}

const col = createColumnHelper<Deploy>()
const columns = [
  col.accessor('id', { header: 'Deploy' }),
  col.accessor('branch', { header: 'Branch' }),
]

export default function Example() {
  const [state, setState] = useState<'loading' | 'error' | 'empty'>('loading')
  return (
    <div className="grid gap-3">
      <SegmentedControl
        aria-label="State"
        size="sm"
        value={state}
        onValueChange={setState}
        options={[
          { value: 'loading', label: 'Loading' },
          { value: 'error', label: 'Error' },
          { value: 'empty', label: 'Empty' },
        ]}
      />
      <DataTable
        aria-label="Deploys"
        data={state === 'empty' ? [] : undefined}
        columns={columns}
        loading={state === 'loading'}
        error={state === 'error' ? new Error('Could not reach the deploy service.') : undefined}
        onRetry={() => setState('empty')}
      />
    </div>
  )
}
```

## Example: Theme recipe

Set variant, density and slot classes for every DataTable from the theme file.

```tsx
import { Badge, defineTheme, presets, ThemeScope } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { type Invoice, invoices, statusTone, usd } from '../data'

// In your theme file: every DataTable becomes compact and borderless, with a tinted header.
const theme = defineTheme({
  name: 'ledger',
  extends: presets.glyph,
  components: {
    DataTable: {
      defaultVariants: { variant: 'plain', density: 'compact' },
      className: {
        head: 'bg-subtle text-[0.6875rem] tracking-wide [&_button]:uppercase',
        row: 'odd:bg-subtle/40',
      },
    },
  },
})

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  return (
    <ThemeScope theme={theme} className="w-full bg-transparent">
      <DataTable aria-label="Invoices" data={invoices} columns={columns} pageSize={6} />
    </ThemeScope>
  )
}
```

Live page: https://glyphui.xyz/components/data-table

---

# DatePicker

> A date field that opens a calendar, plus DateRangePicker with presets like “Last 7 days”.

Status: beta. Category: Forms.

```ts
import { DatePicker, DateRangePicker } from '@glyphui/ui'
```

Exports: `DatePicker`, `DateRangePicker`, `datePickerStyles`.

## Notes

- Values are Date objects (or { from, to } for ranges), never strings. Pass name to submit ISO dates with a native form.
- Format the trigger with any date-fns pattern through the format prop.

## DatePicker props

| Prop | Type | Default | Description |
|---|---|---|---|
| `aria-describedby` | `string` |  |  |
| `aria-invalid` | `boolean` |  |  |
| `aria-label` | `string` |  |  |
| `className` | `string` |  |  |
| `clearable` | `boolean` |  | Show a button that clears the value. |
| `contentClassName` | `string` |  |  |
| `defaultValue` | `Date` |  |  |
| `disabled` | `boolean` |  |  |
| `disabledDates` | `Matcher \| Matcher[]` |  | Extra disabled dates, in react-day-picker matcher form. |
| `format` | `string` |  | date-fns format string for the trigger. Default `"MMM d, yyyy"`. |
| `id` | `string` |  |  |
| `maxDate` | `Date` |  | Latest selectable date. |
| `minDate` | `Date` |  | Earliest selectable date. |
| `name` | `string` |  | Submits the ISO date (yyyy-MM-dd) with a native form. |
| `onValueChange` | `((date: Date) => void)` |  |  |
| `placeholder` | `ReactNode` |  |  |
| `required` | `boolean` |  |  |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `value` | `Date` |  |  |

## Example: Date

In a Field, with a minimum date and a clear button.

```tsx
import { DatePicker, Field } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [date, setDate] = useState<Date | undefined>()
  return (
    <Field label="Launch date" description="Weekdays from today onward." className="w-72">
      <DatePicker
        value={date}
        onValueChange={setDate}
        minDate={new Date()}
        disabledDates={{ dayOfWeek: [0, 6] }}
        clearable
      />
    </Field>
  )
}
```

## Example: Date range with presets

```tsx
import { type DateRange, DateRangePicker, Field } from '@glyphui/ui'
import { useState } from 'react'

const daysAgo = (n: number) => new Date(Date.now() - n * 86_400_000)
const startOfMonth = () => new Date(new Date().getFullYear(), new Date().getMonth(), 1)

export default function Example() {
  const [range, setRange] = useState<DateRange | undefined>({ from: daysAgo(6), to: new Date() })
  return (
    <Field label="Report period" className="w-80">
      <DateRangePicker
        value={range}
        onValueChange={setRange}
        maxDate={new Date()}
        presets={[
          { label: 'Today', range: () => ({ from: new Date(), to: new Date() }) },
          { label: 'Last 7 days', range: () => ({ from: daysAgo(6), to: new Date() }) },
          { label: 'Last 30 days', range: () => ({ from: daysAgo(29), to: new Date() }) },
          { label: 'Month to date', range: () => ({ from: startOfMonth(), to: new Date() }) },
        ]}
      />
    </Field>
  )
}
```

## Example: In a form

Value and onValueChange map straight to FormField.

```tsx
import { DatePicker } from '@glyphui/ui'
import { Form, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { z } from 'zod'

const schema = z.object({
  dueDate: z.date('Choose a due date'),
})

export default function Example() {
  const form = useForm({ schema })
  return (
    <Form form={form} onSubmit={() => {}} className="grid w-72 gap-4">
      <FormField control={form.control} name="dueDate" label="Due date" required>
        {(field) => <DatePicker value={field.value} onValueChange={field.onChange} />}
      </FormField>
      <FormSubmit className="justify-self-start">Save</FormSubmit>
    </Form>
  )
}
```

Live page: https://glyphui.xyz/components/date-picker

---

# DescriptionList

> Label–value pairs such as account details, order metadata or settings summaries.

Status: beta. Category: Data display.

```ts
import { DescriptionList, DescriptionItem } from '@glyphui/ui'
```

Exports: `DescriptionList`, `DescriptionItem`, `descriptionListStyles`.

## Notes

- Renders a real <dl> with <dt>/<dd> pairs, so assistive tech reads each term with its value.

## Example: Inline with dividers

```tsx
import { Badge, DescriptionItem, DescriptionList } from '@glyphui/ui'

export default function Example() {
  return (
    <DescriptionList layout="inline" dividers className="max-w-xl">
      <DescriptionItem term="Workspace">Acme Inc.</DescriptionItem>
      <DescriptionItem term="Plan">
        <Badge tone="primary">Pro</Badge>
      </DescriptionItem>
      <DescriptionItem term="Billing email">billing@acme.com</DescriptionItem>
      <DescriptionItem term="Next invoice">Nov 1, 2026 · $192.00</DescriptionItem>
    </DescriptionList>
  )
}
```

## Example: Stacked

Terms above details; works in narrow cards.

```tsx
import { Card, DescriptionItem, DescriptionList } from '@glyphui/ui'

export default function Example() {
  return (
    <Card className="max-w-xs">
      <DescriptionList>
        <DescriptionItem term="Order">#10482</DescriptionItem>
        <DescriptionItem term="Shipping to">221B Baker Street, London</DescriptionItem>
        <DescriptionItem term="Delivery">Tuesday, between 9:00 and 12:00</DescriptionItem>
      </DescriptionList>
    </Card>
  )
}
```

Live page: https://glyphui.xyz/components/description-list

---

# Dialog

> A modal window for focused tasks such as editing a record or filling a short form.

Status: beta. Category: Overlays.

```ts
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@glyphui/ui'
```

Exports: `Dialog`, `DialogTrigger`, `DialogContent`, `DialogHeader`, `DialogTitle`, `DialogDescription`, `DialogBody`, `DialogFooter`, `DialogClose`, `dialogStyles`.

## Notes

- Focus moves into the dialog on open, is trapped while open, and returns to the trigger on close.
- Always render a DialogTitle; it becomes the dialog’s accessible name.
- Escape and clicking the backdrop close it. For decisions that must not be dismissed by accident, use AlertDialog.

## Example: Edit form

```tsx
import {
  Button,
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  Field,
  Input,
} from '@glyphui/ui'

export default function Example() {
  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button variant="outline">Edit profile</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Edit profile</DialogTitle>
          <DialogDescription>
            Your name and handle are visible to everyone in the workspace.
          </DialogDescription>
        </DialogHeader>
        <DialogBody className="grid gap-4">
          <Field label="Name">
            <Input defaultValue="Ada Lovelace" />
          </Field>
          <Field label="Handle">
            <Input prefix="@" defaultValue="ada" />
          </Field>
        </DialogBody>
        <DialogFooter>
          <DialogClose asChild>
            <Button variant="outline">Cancel</Button>
          </DialogClose>
          <DialogClose asChild>
            <Button>Save changes</Button>
          </DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
```

## Example: Sizes

sm, md (default), lg and xl set the maximum width.

```tsx
import {
  Button,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@glyphui/ui'

const sizes = ['sm', 'md', 'lg', 'xl'] as const

export default function Example() {
  return (
    <div className="flex flex-wrap gap-2">
      {sizes.map((size) => (
        <Dialog key={size}>
          <DialogTrigger asChild>
            <Button variant="outline">{size}</Button>
          </DialogTrigger>
          <DialogContent size={size}>
            <DialogHeader>
              <DialogTitle>Size {size}</DialogTitle>
              <DialogDescription>
                The panel never grows past the viewport and scrolls when content is tall.
              </DialogDescription>
            </DialogHeader>
          </DialogContent>
        </Dialog>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/dialog

---

# DiffViewer

> Compare two versions of a text, unified or side by side, with changed words highlighted and unchanged lines folded.

Status: beta. Category: Viewers.

```ts
import { DiffViewer } from '@glyphui/viewers/diff'
```

Exports: `DiffViewer`, `diffViewerStyles`, `computeDiff`, `toSplitRows`.

## Notes

- Install the optional peer dependency first: npm install diff.
- Each changed line says whether it was added or removed to screen readers; the header announces the totals.
- Lines that were mostly rewritten are shown whole rather than word by word, which reads better.

## DiffViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `newValue` (required) | `string` |  | The text after the change. |
| `oldValue` (required) | `string` |  | The text before the change. |
| `bordered` | `boolean` |  | Draw the viewer as a bordered card. Default true. |
| `className` | `string` |  |  |
| `context` | `number` |  | Unchanged lines kept around each change; longer stretches fold. Default 3. |
| `defaultView` | `"split" \| "unified"` |  | `unified` (one column) or `split` (side by side). Users can switch. Default unified. |
| `fileName` | `string` |  | Shown in the header, e.g. the file path. |
| `height` | `string \| number` |  | Height of the viewer; content scrolls inside. |
| `wrap` | `boolean` |  | Wrap long lines. Default false. |

## Example: A code change

Unified view with folded context.

```tsx
import { DiffViewer } from '@glyphui/viewers/diff'

const before = `export async function remind(invoice: Invoice) {
  const days = Math.round((Date.now() - invoice.dueDate.getTime()) / 86_400_000)
  if (days > 0) {
    await sendEmail(invoice.id, \`Your invoice is \${days} days overdue\`)
  }
}

export function isOverdue(invoice: Invoice) {
  return invoice.dueDate.getTime() < Date.now()
}

export function label(invoice: Invoice) {
  return invoice.id
}
`

const after = `export async function remind(invoice: Invoice): Promise<boolean> {
  if (!invoice.remindersEnabled) return false
  const days = Math.round((Date.now() - invoice.dueDate.getTime()) / DAY)
  if (days <= 0) return false
  await sendEmail(invoice.id, \`Your invoice is \${days} days overdue\`)
  return true
}

export function isOverdue(invoice: Invoice) {
  return invoice.dueDate.getTime() < Date.now()
}

export function label(invoice: Invoice) {
  return \`\${invoice.id} · \${invoice.customer}\`
}
`

export default function Example() {
  return (
    <DiffViewer
      oldValue={before}
      newValue={after}
      fileName="src/reminders.ts"
      context={1}
      className="w-full"
    />
  )
}
```

## Example: Side by side

Edits to a policy, compared in two columns.

```tsx
import { DiffViewer } from '@glyphui/viewers/diff'

const before = `Refunds
Customers can ask for a refund within 14 days of payment.
Refunds go back to the original payment method.
Annual plans are refunded in full.`

const after = `Refunds
Customers can ask for a refund within 30 days of payment.
Refunds go back to the original payment method within 5 business days.
Annual plans are refunded for the unused months.`

export default function Example() {
  return (
    <DiffViewer
      oldValue={before}
      newValue={after}
      fileName="refund-policy.md"
      defaultView="split"
      wrap
      className="w-full"
    />
  )
}
```

Live page: https://glyphui.xyz/components/diff-viewer

---

# Dropdown Menu

> A menu of actions opened from a button: row actions, account menus and "more" buttons.

Status: beta. Category: Overlays.

```ts
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioGroup } from '@glyphui/ui'
```

Exports: `DropdownMenu`, `DropdownMenuTrigger`, `DropdownMenuContent`, `DropdownMenuItem`, `DropdownMenuCheckboxItem`, `DropdownMenuRadioGroup`, `DropdownMenuRadioItem`, `DropdownMenuLabel`, `DropdownMenuSeparator`, `DropdownMenuShortcut`, `DropdownMenuGroup`, `DropdownMenuSub`, `DropdownMenuSubTrigger`, `DropdownMenuSubContent`, `dropdownMenuStyles`.

## Notes

- Full keyboard support: arrow keys move, typing jumps to an item, Escape closes.
- shortcut only displays the hint; bind the key yourself.

## Example: Actions

Icons, keyboard hints and a destructive item.

```tsx
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  IconButton,
} from '@glyphui/ui'
import { Copy, MoreHorizontal, Pencil, Share2, Trash2 } from 'lucide-react'

export default function Example() {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <IconButton icon={<MoreHorizontal />} aria-label="Project actions" variant="outline" />
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        <DropdownMenuItem icon={<Pencil />} shortcut="⌘R">
          Rename
        </DropdownMenuItem>
        <DropdownMenuItem icon={<Copy />} shortcut="⌘D">
          Duplicate
        </DropdownMenuItem>
        <DropdownMenuItem icon={<Share2 />}>Share</DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem icon={<Trash2 />} tone="danger" shortcut="⌫">
          Delete
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
```

## Example: Checkbox and radio items

```tsx
import {
  Button,
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@glyphui/ui'
import { SlidersHorizontal } from 'lucide-react'
import { useState } from 'react'

export default function Example() {
  const [showDone, setShowDone] = useState(true)
  const [showEmpty, setShowEmpty] = useState(false)
  const [order, setOrder] = useState('updated')
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" leftIcon={<SlidersHorizontal />}>
          View
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        <DropdownMenuLabel inset>Show</DropdownMenuLabel>
        <DropdownMenuCheckboxItem checked={showDone} onCheckedChange={setShowDone}>
          Completed issues
        </DropdownMenuCheckboxItem>
        <DropdownMenuCheckboxItem checked={showEmpty} onCheckedChange={setShowEmpty}>
          Empty groups
        </DropdownMenuCheckboxItem>
        <DropdownMenuSeparator />
        <DropdownMenuLabel inset>Order by</DropdownMenuLabel>
        <DropdownMenuRadioGroup value={order} onValueChange={setOrder}>
          <DropdownMenuRadioItem value="updated">Last updated</DropdownMenuRadioItem>
          <DropdownMenuRadioItem value="created">Created</DropdownMenuRadioItem>
          <DropdownMenuRadioItem value="priority">Priority</DropdownMenuRadioItem>
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
```

## Example: Submenu

```tsx
import {
  Button,
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from '@glyphui/ui'
import { FolderInput, UserPlus } from 'lucide-react'

export default function Example() {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline">Issue options</Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        <DropdownMenuItem icon={<UserPlus />}>Assign to me</DropdownMenuItem>
        <DropdownMenuSub>
          <DropdownMenuSubTrigger icon={<FolderInput />}>Move to</DropdownMenuSubTrigger>
          <DropdownMenuSubContent>
            <DropdownMenuItem>Design</DropdownMenuItem>
            <DropdownMenuItem>Engineering</DropdownMenuItem>
            <DropdownMenuItem>Growth</DropdownMenuItem>
          </DropdownMenuSubContent>
        </DropdownMenuSub>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
```

Live page: https://glyphui.xyz/components/dropdown-menu

---

# Eyebrow

> A small uppercase label that sits above a heading.

Status: stable. Category: Typography.

```ts
import { Eyebrow } from '@glyphui/ui'
```

Exports: `Eyebrow`, `eyebrowStyles`.

## Eyebrow props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `tone` | `"primary" \| "muted"` |  |  |

## Example: Above a heading

```tsx
import { Eyebrow, Heading, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-lg gap-2">
      <Eyebrow tone="primary">Changelog</Eyebrow>
      <Heading level={2}>Faster tables, calmer forms</Heading>
      <Text tone="muted">Everything we shipped in October.</Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/eyebrow

---

# Faq

> Frequently asked questions as an accordion, stacked or with the header beside the questions.

Status: beta. Category: Blocks.

```ts
import { Faq } from '@glyphui/blocks'
```

Exports: `Faq`.

## Notes

- One answer is open at a time by default. Set multiple to allow several.

## Faq props

| Prop | Type | Default | Description |
|---|---|---|---|
| `items` (required) | `readonly FaqItem[]` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `layout` | `"stacked" \| "split"` | `stacked` | `stacked` (default) puts the header above; `split` puts it beside the questions on large screens. |
| `multiple` | `boolean` | `false` | Allow several answers open at once. |
| `title` | `ReactNode` |  |  |

## Example: Stacked

```tsx
import { Faq } from '@glyphui/blocks'

export default function Example() {
  return (
    <Faq
      title="Questions, answered"
      items={[
        {
          question: 'Can I import my existing customers?',
          answer:
            'Yes. Upload a CSV or connect Stripe and we import customers, plans and payment methods.',
        },
        {
          question: 'Do you charge per invoice?',
          answer: 'No. Plans are flat monthly prices; Starter includes 50 invoices a month.',
        },
        {
          question: 'Which currencies do you support?',
          answer: '135 currencies, with local payment methods in 46 countries.',
        },
      ]}
    />
  )
}
```

## Example: Split layout

```tsx
import { Faq } from '@glyphui/blocks'
import { Link } from '@glyphui/ui'

export default function Example() {
  return (
    <Faq
      layout="split"
      eyebrow="Support"
      title="Before you start"
      description={
        <>
          Can’t find what you need? <Link href="#contact">Talk to us</Link>.
        </>
      }
      multiple
      items={[
        {
          question: 'Is there a free trial?',
          answer: 'Growth comes with a 14-day trial. Starter is free forever.',
        },
        {
          question: 'Can I cancel anytime?',
          answer: 'Yes. You keep access until the end of the billing period.',
        },
        {
          question: 'Where is my data stored?',
          answer: 'In the EU or US, your choice, on SOC 2 audited infrastructure.',
        },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/faq

---

# FeatureGrid

> A grid of features or benefits, each with an icon, a title and a short description.

Status: beta. Category: Blocks.

```ts
import { FeatureGrid } from '@glyphui/blocks'
```

Exports: `FeatureGrid`, `featureGridStyles`.

## FeatureGrid props

| Prop | Type | Default | Description |
|---|---|---|---|
| `features` (required) | `readonly Feature[]` |  |  |
| `align` | `"center" \| "left"` | `left` |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `columns` | `2 \| 3 \| 4` | `3` |  |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `title` | `ReactNode` |  |  |
| `variant` | `"cards" \| "plain"` | `cards` | `cards` (default) puts each feature on a card; `plain` lists them without surfaces. |

## Example: Cards

Give a feature an href and its whole card becomes a link.

```tsx
import { FeatureGrid } from '@glyphui/blocks'
import { BarChart3, Lock, RefreshCw } from 'lucide-react'

export default function Example() {
  return (
    <FeatureGrid
      eyebrow="Why Ledgerline"
      title="Billing that keeps up with your product"
      description="Price by seats, usage or both. Change plans without touching code."
      features={[
        {
          icon: <RefreshCw />,
          title: 'Automatic retries',
          description: 'Failed payments retry on a smart schedule and email the right person.',
          href: '#retries',
        },
        {
          icon: <BarChart3 />,
          title: 'Revenue reports',
          description: 'MRR, churn and expansion, reconciled with your bank every night.',
          href: '#reports',
        },
        {
          icon: <Lock />,
          title: 'SOC 2 Type II',
          description: 'Audited controls, SSO and audit logs on every plan.',
          href: '#security',
        },
      ]}
    />
  )
}
```

## Example: Plain, four columns

```tsx
import { FeatureGrid } from '@glyphui/blocks'
import { Gauge, Globe, Plug, Shield } from 'lucide-react'

export default function Example() {
  return (
    <FeatureGrid
      variant="plain"
      columns={4}
      features={[
        {
          icon: <Gauge />,
          title: 'Fast',
          description: 'Edge-cached pages load in under 100 ms worldwide.',
        },
        {
          icon: <Shield />,
          title: 'Secure',
          description: 'Encryption at rest and in transit, by default.',
        },
        { icon: <Plug />, title: 'Connected', description: 'Webhooks and 40 native integrations.' },
        { icon: <Globe />, title: 'Global', description: 'Data residency in the EU, US and APAC.' },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/feature-grid

---

# FeatureSplit

> Feature rows that alternate text and media, for explaining a product in more depth than a grid allows.

Status: beta. Category: Blocks.

```ts
import { FeatureSplit } from '@glyphui/blocks'
```

Exports: `FeatureSplit`.

## FeatureSplit props

| Prop | Type | Default | Description |
|---|---|---|---|
| `items` (required) | `readonly FeatureSplitItem[]` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `mediaFirst` | `boolean` | `false` | Put media on the left for the first row. Rows alternate after that. |
| `title` | `ReactNode` |  |  |

## Example: Alternating rows

```tsx
import { FeatureSplit } from '@glyphui/blocks'
import { Button, Card, Text } from '@glyphui/ui'

function Mock({ label }: { label: string }) {
  return (
    <Card variant="ghost" className="aspect-[4/3] items-center justify-center">
      <Text size="small" tone="faint">
        {label}
      </Text>
    </Card>
  )
}

export default function Example() {
  return (
    <FeatureSplit
      items={[
        {
          eyebrow: 'Collect',
          title: 'Usage data in, invoices out',
          description:
            'Send events from your app and Ledgerline meters them against each customer’s plan.',
          points: [
            'Idempotent event API',
            'Backfill from your warehouse',
            'Real-time usage dashboards',
          ],
          media: <Mock label="Usage chart" />,
        },
        {
          eyebrow: 'Recover',
          title: 'Late payments, handled',
          description: 'Dunning emails, card updaters and payment links run on their own.',
          actions: <Button variant="outline">See the dunning flow</Button>,
          media: <Mock label="Dunning timeline" />,
        },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/feature-split

---

# Field

> Wraps one control with its label, description and error, and wires the ARIA attributes between them.

Status: stable. Category: Forms.

```ts
import { Field, FieldContext } from '@glyphui/ui'
```

Exports: `Field`, `FieldContext`, `useFieldControl`, `fieldStyles`.

## Notes

- Glyph controls call useFieldControl, so id, required, disabled and aria attributes flow from Field automatically.
- Use useFieldControl in your own controls to get the same wiring.

## Field props

| Prop | Type | Default | Description |
|---|---|---|---|
| `controlId` | `string` |  | Id for the control. Generated when omitted. |
| `description` | `ReactNode` |  |  |
| `disabled` | `boolean` |  |  |
| `error` | `ReactNode` |  | Error message. Marks the control invalid and is announced to screen readers. |
| `label` | `ReactNode` |  |  |
| `labelAction` | `ReactNode` |  | Shown at the end of the label row, outside the label, so it is not part of the control's accessible name. For example a "Forgot password?" link. |
| `orientation` | `"horizontal" \| "vertical"` |  |  |
| `required` | `boolean` |  |  |

## Example: Label and description

```tsx
import { Field, Input } from '@glyphui/ui'

export default function Example() {
  return (
    <Field
      label="Display name"
      description="Shown on your profile and in comments."
      className="max-w-sm"
    >
      <Input defaultValue="Ada Lovelace" />
    </Field>
  )
}
```

## Example: Error

Marks the control aria-invalid and links the message with aria-describedby.

```tsx
import { Field, Input } from '@glyphui/ui'

export default function Example() {
  return (
    <Field
      label="Email"
      required
      description="We send receipts here."
      error="Enter an email address like name@company.com"
      className="max-w-sm"
    >
      <Input type="email" defaultValue="ada@" />
    </Field>
  )
}
```

## Example: Horizontal

Control first, text beside it. For checkboxes and switches.

```tsx
import { Checkbox, Field, Switch } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-sm gap-4">
      <Field
        orientation="horizontal"
        label="Email me about mentions"
        description="At most one email a day."
      >
        <Switch defaultChecked />
      </Field>
      <Field orientation="horizontal" label="I accept the terms of service">
        <Checkbox />
      </Field>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/field

---

# FilePreview

> Show any file with the right viewer, picked from its name or type, with a download fallback. Pairs with FileUpload.

Status: beta. Category: Viewers.

```ts
import { FilePreview, FilePreviewDialog } from '@glyphui/viewers'
```

Exports: `FilePreview`, `filePreviewStyles`, `FilePreviewDialog`, `detectFileKind`, `formatBytes`.

## Notes

- Images, video, audio, JSON and plain text work with no extra packages.
- PDF, CSV, spreadsheets, code and Markdown need their viewer’s packages. Pass loaders for the ones you use, e.g. loaders={{ pdf: () => import("@glyphui/viewers/pdf") }}, so your bundle only includes what you can show.
- Files without a viewer get a clear message and a download button.

## FilePreview props

| Prop | Type | Default | Description |
|---|---|---|---|
| `file` (required) | `ViewerSource` |  | The file: a File/Blob (e.g. from FileUpload), a URL, or bytes. |
| `bordered` | `boolean` |  | Draw the preview as a bordered card. Default true. |
| `className` | `string` |  |  |
| `header` | `boolean` |  | Show the header with name, size and download. Default true. |
| `height` | `string \| number` |  | Height of the preview. Default 520. |
| `loaders` | `ViewerLoaders` |  | Viewers that need extra packages (PDF, CSV, spreadsheets, code, Markdown). |
| `name` | `string` |  | File name, when `file` isn't a File. Used to pick the viewer and for downloads. |
| `type` | `string` |  | MIME type, when the name doesn't tell. |

## Example: Every kind of file

Pick a sample file; the matching viewer loads on demand.

```tsx
import { Select, SelectItem } from '@glyphui/ui'
import { FilePreview, type ViewerLoaders } from '@glyphui/viewers'
import { useState } from 'react'
import { fixture } from '../../../lib/fixtures'

// Viewers with extra dependencies load only when a file needs them.
const loaders: ViewerLoaders = {
  pdf: () => import('@glyphui/viewers/pdf'),
  csv: () => import('@glyphui/viewers/csv'),
  spreadsheet: () => import('@glyphui/viewers/spreadsheet'),
  code: () => import('@glyphui/viewers/code'),
  markdown: () => import('@glyphui/viewers/markdown'),
}

const files = [
  'report.pdf',
  'customers.csv',
  'sales.xlsx',
  'workspace.json',
  'reminders.ts',
  'README.md',
  'aurora.jpg',
  'clip.webm',
  'chime.wav',
  'archive.zip',
]

export default function Example() {
  const [name, setName] = useState('report.pdf')
  return (
    <div className="grid w-full gap-3">
      <Select value={name} onValueChange={setName} aria-label="Sample file" className="w-56">
        {files.map((file) => (
          <SelectItem key={file} value={file}>
            {file}
          </SelectItem>
        ))}
      </Select>
      <FilePreview key={name} file={fixture(name)} name={name} loaders={loaders} height={520} />
    </div>
  )
}
```

## Example: Previews for uploads

Add files, then open any of them in a dialog.

```tsx
import { Button, type FileItem, FileUpload } from '@glyphui/ui'
import { FilePreviewDialog, formatBytes, type ViewerLoaders } from '@glyphui/viewers'
import { Eye } from 'lucide-react'
import { useState } from 'react'

const loaders: ViewerLoaders = {
  pdf: () => import('@glyphui/viewers/pdf'),
  csv: () => import('@glyphui/viewers/csv'),
  spreadsheet: () => import('@glyphui/viewers/spreadsheet'),
  code: () => import('@glyphui/viewers/code'),
  markdown: () => import('@glyphui/viewers/markdown'),
}

export default function Example() {
  const [files, setFiles] = useState<FileItem[]>([])
  return (
    <div className="grid w-full max-w-lg gap-4">
      <FileUpload
        files={files}
        onFilesChange={setFiles}
        maxFiles={6}
        hint="Any files. They stay on your device."
      />
      {files.length > 0 && (
        <ul className="grid gap-2">
          {files.map(({ id, file }) => (
            <li
              key={id}
              className="flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2 text-small"
            >
              <span className="min-w-0 truncate">
                {file.name}{' '}
                <span className="text-muted-foreground">· {formatBytes(file.size)}</span>
              </span>
              <FilePreviewDialog
                file={file}
                loaders={loaders}
                trigger={
                  <Button size="sm" variant="outline" leftIcon={<Eye />}>
                    Preview
                  </Button>
                }
              />
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/file-preview

---

# FileUpload

> Drag-and-drop or click to choose files, with type, size and count checks and a file list with progress.

Status: beta. Category: Forms.

```ts
import { FileUpload } from '@glyphui/ui'
```

Exports: `FileUpload`, `formatBytes`, `matchesAccept`, `fileUploadStyles`.

## Notes

- The dropzone is a button: Enter or Space opens the file picker.
- Rejected files are reported in a live region and through onReject with a reason: too-large, wrong-type or too-many.

## FileUpload props

| Prop | Type | Default | Description |
|---|---|---|---|
| `accept` | `string` |  | Allowed types, as for `<input type="file" accept>`. |
| `aria-describedby` | `string` |  |  |
| `aria-invalid` | `boolean` |  |  |
| `className` | `string` |  |  |
| `defaultFiles` | `FileItem[]` |  |  |
| `disabled` | `boolean` |  |  |
| `files` | `FileItem[]` |  |  |
| `hint` | `ReactNode` |  | Secondary dropzone text. Defaults to a summary of `accept` and `maxSize`. |
| `id` | `string` |  |  |
| `label` | `ReactNode` |  | Main dropzone text. |
| `maxFiles` | `number` |  | Maximum number of files in the list. |
| `maxSize` | `number` |  | Maximum size per file, in bytes. |
| `multiple` | `boolean` |  | Allow several files. Default true. |
| `onFilesChange` | `((files: FileItem[]) => void)` |  |  |
| `onReject` | `((rejections: FileRejection[]) => void)` |  | Called with files that were not added and why. |

## Example: Images up to 5 MB

```tsx
import { FileUpload } from '@glyphui/ui'

export default function Example() {
  return (
    <FileUpload
      className="w-full max-w-md"
      accept="image/png,image/jpeg,.webp"
      maxSize={5 * 1024 * 1024}
      maxFiles={4}
    />
  )
}
```

## Example: Uploading with progress

FileUpload never uploads; set progress and error on items from your own upload code.

```tsx
import { type FileItem, FileUpload } from '@glyphui/ui'
import { useState } from 'react'

/** Simulates an upload: progress ticks to 100, and files over 2 MB fail. */
function fakeUpload(item: FileItem, update: (id: string, patch: Partial<FileItem>) => void) {
  let progress = 0
  const timer = setInterval(() => {
    progress += 12
    if (item.file.size > 2 * 1024 * 1024 && progress > 50) {
      clearInterval(timer)
      update(item.id, {
        progress: undefined,
        error: 'Upload failed: the server rejected files over 2 MB.',
      })
      return
    }
    update(item.id, { progress: Math.min(progress, 100) })
    if (progress >= 100) clearInterval(timer)
  }, 250)
}

export default function Example() {
  const [files, setFiles] = useState<FileItem[]>([])
  const update = (id: string, patch: Partial<FileItem>) =>
    setFiles((current) => current.map((f) => (f.id === id ? { ...f, ...patch } : f)))

  return (
    <FileUpload
      className="w-full max-w-md"
      files={files}
      onFilesChange={(next) => {
        const added = next.filter((f) => !files.some((old) => old.id === f.id))
        setFiles(next.map((f) => (added.includes(f) ? { ...f, progress: 0 } : f)))
        for (const item of added) fakeUpload(item, update)
      }}
    />
  )
}
```

Live page: https://glyphui.xyz/components/file-upload

---

# Firebase adapter

> Glyph auth on Firebase Authentication: email and password, Google, GitHub, Apple and Microsoft, reset and verification emails.

Status: beta. Category: Auth.

```ts
import { Firebase adapter } from '@glyphui/auth/firebase'
```

Exports: `firebaseAdapter`, `firebaseError`.

## Notes

- Firebase verifies emails and resets passwords with emailed links, so the screens show "check your inbox" steps instead of code inputs.
- Unverified email/password accounts count as signed out until they open the link (requireEmailVerification: false to allow them).
- auth.fetch sends the Firebase ID token as a bearer token; verify it on your server with the Admin SDK.
- oauthFlow: "redirect" works better than popups on mobile Safari.
- Firebase multi-factor and email-link sign-in are not wired yet.

Live page: https://glyphui.xyz/components/auth-firebase

---

# Form

> Schema-validated forms: typed field names, wired labels and errors, server errors on the right field, submit progress.

Status: stable. Category: Patterns.

```ts
import { Form, FormField, FormSubmit, FormError } from '@glyphui/ui/form'
```

Exports: `Form`, `FormField`, `FormSubmit`, `FormError`, `useForm`, `formErrorStyles`.

## Notes

- Works with any Standard Schema validator: zod, valibot, arktype.
- Return { errors } from onSubmit for field errors; throw to show a form-level error in FormError.
- FormSubmit outside <Form>, such as in a Modal footer, needs the form: <FormSubmit form={form}>.
- Requires react-hook-form and @hookform/resolvers as peer dependencies.

## FormField props

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` (required) | `(field: ControllerRenderProps<TInput, TName>) => ReactNode` |  | Render the control and spread `field` onto it: `{(field) => <Input {...field} />}`. |
| `control` (required) | `Control<TInput, unknown, any>` |  |  |
| `name` (required) | `string` |  | Typed from the schema: a misspelled name is a compile error. |
| `controlId` | `string` |  | Id for the control. Generated when omitted. |
| `description` | `ReactNode` |  |  |
| `disabled` | `boolean` |  |  |
| `label` | `ReactNode` |  |  |
| `labelAction` | `ReactNode` |  | Shown at the end of the label row, outside the label, so it is not part of the control's accessible name. For example a "Forgot password?" link. |
| `orientation` | `"horizontal" \| "vertical"` |  |  |
| `required` | `boolean` |  |  |

## Example: Validation and server errors

Try an invalid email, or "taken@acme.dev" for a server error.

```tsx
import { Input, Text } from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { useState } from 'react'
import { z } from 'zod'

const schema = z.object({
  name: z.string().trim().min(2, 'Use at least 2 characters'),
  email: z.email('Enter a valid email address'),
})

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  const [done, setDone] = useState<string | null>(null)
  const form = useForm({ schema, defaultValues: { name: '', email: '' } })

  if (done) return <Text>Welcome aboard, {done}.</Text>

  return (
    <Form
      form={form}
      className="grid max-w-sm gap-4"
      onSubmit={async (values) => {
        await wait(700)
        if (values.email === 'taken@acme.dev')
          return { errors: { email: 'That email is already registered.' } }
        setDone(values.name)
      }}
    >
      <FormError />
      <FormField control={form.control} name="name" label="Name" required>
        {(field) => <Input autoComplete="name" {...field} />}
      </FormField>
      <FormField control={form.control} name="email" label="Email" required>
        {(field) => <Input type="email" autoComplete="email" {...field} />}
      </FormField>
      <FormSubmit className="justify-self-start">Create account</FormSubmit>
    </Form>
  )
}
```

Live page: https://glyphui.xyz/components/form

---

# FunnelChart

> How many make it through each step of a flow, with the conversion from the previous step or from the start.

Status: beta. Category: Data display.

```ts
import { FunnelChart } from '@glyphui/ui/chart'
```

Exports: `FunnelChart`.

## Notes

- Rows are stages in order. Bar widths are relative to the first stage.
- One measure, one color: later stages are tints of the same hue.

## FunnelChart props

| Prop | Type | Default | Description |
|---|---|---|---|
| `category` (required) | `string` |  | Field naming each stage, e.g. `"stage"`. |
| `data` (required) | `readonly T[]` |  | One row per stage, in order. |
| `title` (required) | `string` |  |  |
| `value` (required) | `string` |  | Field holding how many reached the stage. |
| `className` | `string` |  |  |
| `color` | `ChartColorValue` |  | Default `chart-1`. Later stages are lighter tints of it. |
| `conversion` | `"none" \| "previous" \| "first"` |  | Under each value: share of the first stage or of the previous one. Default `previous`. |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `hideTitle` | `boolean` |  |  |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `onRetry` | `(() => unknown)` |  |  |
| `valueFormatter` | `((value: number) => string)` |  |  |

## Example: Signup funnel

Step-to-step conversion.

```tsx
import { FunnelChart } from '@glyphui/ui/chart'

const stages = [
  { stage: 'Visited pricing', people: 18420 },
  { stage: 'Started signup', people: 6210 },
  { stage: 'Verified email', people: 4870 },
  { stage: 'Created invoice', people: 2310 },
  { stage: 'Paid', people: 940 },
]

export default function Example() {
  return (
    <FunnelChart
      className="w-full"
      title="Signup to paid"
      description="Last 30 days"
      data={stages}
      category="stage"
      value="people"
    />
  )
}
```

## Example: Share of the first step

conversion="first" measures every step against the top of the funnel.

```tsx
import { FunnelChart } from '@glyphui/ui/chart'

const steps = [
  { step: 'Opened checkout', sessions: 3200 },
  { step: 'Entered card', sessions: 2140 },
  { step: 'Confirmed', sessions: 1890 },
]

export default function Example() {
  return (
    <FunnelChart
      className="w-full"
      title="Checkout completion"
      data={steps}
      category="step"
      value="sessions"
      conversion="first"
      color="chart-2"
    />
  )
}
```

Live page: https://glyphui.xyz/components/funnel-chart

---

# Gauge

> A single value against a range, with optional colored bands such as healthy, slow and failing.

Status: beta. Category: Data display.

```ts
import { Gauge } from '@glyphui/ui/chart'
```

Exports: `Gauge`.

## Notes

- Renders as role="meter" with the value, range and band name, e.g. “240 ms, Slow”.
- The arc sweeps in on mount and when the value changes, at the theme’s motion level.

## Gauge props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `string` |  | Accessible name, also the caption. |
| `value` (required) | `number` |  |  |
| `bands` | `readonly GaugeBand[]` |  | Colored ranges, e.g. healthy / slow / failing. The value arc takes its band's color. |
| `className` | `string` |  |  |
| `color` | `ChartColorValue` |  | Color of the value arc when there are no bands. Default `chart-1`. |
| `description` | `ReactNode` |  |  |
| `hideTitle` | `boolean` |  |  |
| `label` | `ReactNode` |  | Small text under the value, e.g. "p95 latency". |
| `max` | `number` | `100` |  |
| `min` | `number` | `0` |  |
| `size` | `number` | `220` | Width in pixels. Default 220. |
| `valueFormatter` | `((value: number) => string)` | `(value: number) =>   typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString() : String(value)` |  |

## Example: With bands

The arc takes the color of its band.

```tsx
import { Gauge } from '@glyphui/ui/chart'

export default function Example() {
  return (
    <Gauge
      title="API latency"
      description="p95, last 15 minutes"
      value={238}
      max={600}
      valueFormatter={(v) => `${v} ms`}
      bands={[
        { to: 200, color: 'success', label: 'Healthy' },
        { to: 400, color: 'warning', label: 'Slow' },
        { to: 600, color: 'danger', label: 'Failing' },
      ]}
    />
  )
}
```

## Example: Quota used

```tsx
import { Button } from '@glyphui/ui'
import { Gauge } from '@glyphui/ui/chart'
import { useState } from 'react'

export default function Example() {
  const [used, setUsed] = useState(7.4)
  return (
    <div className="grid justify-items-center gap-3">
      <Gauge
        title="Storage"
        value={used}
        max={10}
        valueFormatter={(v) => `${v.toFixed(1)} GB`}
        label="of 10 GB used"
        size={200}
      />
      <Button variant="outline" size="sm" onClick={() => setUsed((v) => (v > 9 ? 2.1 : v + 0.8))}>
        Upload files
      </Button>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/gauge

---

# Grid

> Responsive equal-width columns, set per breakpoint, with gaps from the spacing scale.

Status: beta. Category: Layout.

```ts
import { Grid } from '@glyphui/ui'
```

Exports: `Grid`, `gridStyles`.

## Example: Responsive columns

Resize the window to see columns change.

```tsx
import { Card, Grid, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Grid cols={{ base: 1, sm: 2, lg: 4 }} gap={4}>
      {['Projects', 'Issues', 'Members', 'Integrations'].map((label) => (
        <Card key={label} padding="sm">
          <Text size="small" tone="muted">
            {label}
          </Text>
        </Card>
      ))}
    </Grid>
  )
}
```

Live page: https://glyphui.xyz/components/grid

---

# Heading

> A heading whose document level and visual size are set independently, using the theme type scale.

Status: stable. Category: Typography.

```ts
import { Heading } from '@glyphui/ui'
```

Exports: `Heading`, `headingStyles`.

## Notes

- level sets the h1–h6 element; size sets the look. Choose level for the document outline.
- Headings use font-display and text-wrap: balance.

## Heading props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `level` | `Level` |  | Document outline level (h1–h6). Visual size follows it unless `size` is set. |
| `size` | `"h2" \| "h3" \| "h1" \| "h4" \| "display"` |  |  |

## Example: Type scale

```tsx
import { Heading } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-3">
      <Heading level={1} size="display">
        Ship the details
      </Heading>
      <Heading level={1}>Design is how it works</Heading>
      <Heading level={2}>Type sets the tone</Heading>
      <Heading level={3}>Cards, navbars and sidebars</Heading>
      <Heading level={4}>Section heading</Heading>
    </div>
  )
}
```

## Example: Level and size

Keep the outline correct while choosing any visual size.

```tsx
import { Heading, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-2">
      <Heading level={2} size="h4">
        Billing
      </Heading>
      <Text size="small" tone="muted">
        An h2 in the outline, sized like an h4 for a dense settings page.
      </Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/heading

---

# Heatmap

> Activity per day over months, like a contribution calendar. Every day is a keyboard-reachable cell with a tooltip.

Status: beta. Category: Data display.

```ts
import { Heatmap } from '@glyphui/ui/chart'
```

Exports: `Heatmap`.

## Notes

- Tab moves into the grid once; the arrow keys move by day and week, Home and End jump to the first and last day.
- Each cell is read as “12 deploys on Mon, Oct 6, 2026”. Set unit to name what is counted.
- Busier days get stronger tints of one color, from the muted surface up to the full color.

## Heatmap props

| Prop | Type | Default | Description |
|---|---|---|---|
| `data` (required) | `readonly T[]` |  | One row per day. Missing days count as zero. |
| `date` (required) | `string` |  | Field holding the day: a Date, a timestamp or a `YYYY-MM-DD` string. |
| `title` (required) | `string` |  |  |
| `value` (required) | `string` |  | Field holding the day's value. |
| `className` | `string` |  |  |
| `color` | `ChartColorValue` |  | Default `chart-1`. Busier days get stronger tints of it. |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `from` | `Date` |  | First day shown. Defaults to 52 weeks before `to`. |
| `hideTitle` | `boolean` |  |  |
| `levels` | `number` |  | Number of tint steps above zero. Default 4. |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `locale` | `string` |  | Locale for month and day names. Defaults to the browser's. |
| `onCellClick` | `((date: Date, value: number) => void)` |  |  |
| `onRetry` | `(() => unknown)` |  |  |
| `to` | `Date` |  | Last day shown. Defaults to the latest day in `data`, or today. |
| `unit` | `string` |  | Noun read after the value, e.g. `"deploys"` → "12 deploys on Mon, Oct 6". |
| `valueFormatter` | `((value: number) => string)` |  |  |
| `weekStart` | `0 \| 1` |  | 0 starts weeks on Sunday, 1 on Monday. Default 0. |

## Example: Deploys per day

A year of activity.

```tsx
import { Heatmap } from '@glyphui/ui/chart'

// A year of deploys: busy mid-week, quiet weekends, a holiday freeze in late December.
const end = new Date(2026, 9, 16)
const data = Array.from({ length: 364 }, (_, i) => {
  const day = new Date(end.getFullYear(), end.getMonth(), end.getDate() - 363 + i)
  const weekday = day.getDay()
  const freeze = day.getMonth() === 11 && day.getDate() > 20
  const base = weekday === 0 || weekday === 6 ? 0.4 : 3 + ((i * 7919) % 5)
  return { day, deploys: freeze ? 0 : Math.max(0, Math.round(base + Math.sin(i / 9) * 2)) }
})

export default function Example() {
  return (
    <Heatmap
      className="w-full"
      title="Deploys per day"
      data={data}
      date="day"
      value="deploys"
      unit="deploys"
      to={end}
      locale="en-US"
    />
  )
}
```

## Example: One quarter, Monday first

from, to and weekStart set the range; onCellClick opens a day.

```tsx
import { Text } from '@glyphui/ui'
import { Heatmap } from '@glyphui/ui/chart'
import { useState } from 'react'

const data = Array.from({ length: 92 }, (_, i) => ({
  date: new Date(2026, 6, 1 + i),
  tickets: (i * 37) % 11,
}))

export default function Example() {
  const [picked, setPicked] = useState<string | null>(null)
  return (
    <div className="grid w-full gap-2">
      <Heatmap
        title="Support tickets, Q3"
        data={data}
        date="date"
        value="tickets"
        unit="tickets"
        from={new Date(2026, 6, 1)}
        to={new Date(2026, 8, 30)}
        weekStart={1}
        color="chart-2"
        locale="en-US"
        onCellClick={(date, value) =>
          setPicked(`${date.toLocaleDateString('en-US', { dateStyle: 'medium' })}: ${value}`)
        }
      />
      <Text size="small" tone="muted">
        {picked ? `Opened ${picked}` : 'Click a day or press Enter on it.'}
      </Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/heatmap

---

# Hero

> The opening section of a page: headline, supporting text, actions, and optional media beside or below.

Status: beta. Category: Blocks.

```ts
import { Hero } from '@glyphui/blocks'
```

Exports: `Hero`, `heroStyles`.

## Notes

- The title is an h1 by default. Set headingLevel when the hero is not the first heading on the page.
- The section is labeled by its title, so screen readers can jump to it.

## Hero props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  |  |
| `actions` | `ReactNode` |  | Buttons or links. |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  | Small label above the title, e.g. a Badge announcing a release. |
| `footnote` | `ReactNode` |  | Small print under the actions, e.g. "No credit card required". |
| `glow` | `boolean` | `true` | Soft glow from the primary color behind the hero. Default true. |
| `headingLevel` | `HeadingLevel` | `1` | Document outline level of the title. Default 1. |
| `media` | `ReactNode` |  | Screenshot, illustration or video. Below the text, or beside it with `split`. |
| `variant` | `"split" \| "left" \| "centered"` | `centered` | `centered` (default), `left`, or `split` with media beside the text on large screens. |

## Example: Centered

The default: everything centered over a soft glow from the primary color.

```tsx
import { Hero } from '@glyphui/blocks'
import { Badge, Button } from '@glyphui/ui'
import { ArrowRight } from 'lucide-react'

export default function Example() {
  return (
    <Hero
      eyebrow={
        <Badge tone="primary" dot>
          New · Usage-based billing
        </Badge>
      }
      title="Invoices that send themselves"
      description="Ledgerline turns usage data into accurate invoices, chases late payments, and syncs everything to your books."
      actions={
        <>
          <Button size="lg" rightIcon={<ArrowRight />}>
            Start free trial
          </Button>
          <Button size="lg" variant="outline">
            Book a demo
          </Button>
        </>
      }
      footnote="14-day trial. No credit card required."
    />
  )
}
```

## Example: Split with media

Text on the left, media on the right on large screens.

```tsx
import { Hero } from '@glyphui/blocks'
import { Button, Card, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Hero
      variant="split"
      title="Every on-call shift, calmer"
      description="Pagerline groups related alerts, drafts the incident timeline, and hands off cleanly at the end of the shift."
      actions={<Button size="lg">Try it with your alerts</Button>}
      media={
        <Card className="gap-3">
          <Text size="small" tone="muted">
            Incident #4182 · API latency
          </Text>
          <Text weight="medium">3 alerts grouped · p95 back under 200 ms at 09:41</Text>
          <div className="h-24 rounded-md bg-muted" />
        </Card>
      }
    />
  )
}
```

Live page: https://glyphui.xyz/components/hero

---

# HoverCard

> A rich preview shown while hovering or focusing a link, such as a user or repository card.

Status: beta. Category: Overlays.

```ts
import { HoverCard, HoverCardTrigger, HoverCardContent } from '@glyphui/ui'
```

Exports: `HoverCard`, `HoverCardTrigger`, `HoverCardContent`, `hoverCardStyles`.

## Notes

- Touch and screen-reader users may never see a hover card. Keep it a preview of information that is also available on the linked page.
- Use Tooltip for a short text label and Popover for interactive content opened by click.

## HoverCardContent props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |

## Example: User preview

```tsx
import { Avatar, Badge, HoverCard, HoverCardContent, HoverCardTrigger, Text } from '@glyphui/ui'
import { CalendarDays } from 'lucide-react'

export default function Example() {
  return (
    <Text>
      Reviewed by{' '}
      <HoverCard>
        <HoverCardTrigger
          href="#ada"
          className="font-medium text-primary-text underline decoration-primary-text/40 underline-offset-4 hover:decoration-primary-text"
        >
          @ada
        </HoverCardTrigger>
        <HoverCardContent>
          <div className="flex gap-3">
            <Avatar name="Ada Lovelace" size="lg" />
            <div className="grid gap-1">
              <div className="flex items-center gap-2">
                <span className="font-medium">Ada Lovelace</span>
                <Badge tone="primary">Admin</Badge>
              </div>
              <Text size="small" tone="muted">
                Engineering lead. Owns the analytics engine and the design system.
              </Text>
              <span className="flex items-center gap-1.5 text-caption text-faint-foreground">
                <CalendarDays className="size-3.5" aria-hidden="true" />
                Joined March 2021
              </span>
            </div>
          </div>
        </HoverCardContent>
      </HoverCard>{' '}
      2 hours ago.
    </Text>
  )
}
```

## Example: Delays

openDelay and closeDelay tune how eager it is.

```tsx
import { HoverCard, HoverCardContent, HoverCardTrigger, Text } from '@glyphui/ui'
import { GitPullRequest } from 'lucide-react'

export default function Example() {
  return (
    <Text>
      Fixed in{' '}
      <HoverCard openDelay={150} closeDelay={100}>
        <HoverCardTrigger
          href="#pr-482"
          className="font-mono text-primary-text underline decoration-primary-text/40 underline-offset-4 hover:decoration-primary-text"
        >
          #482
        </HoverCardTrigger>
        <HoverCardContent side="top" className="w-80">
          <div className="flex gap-3">
            <GitPullRequest className="mt-0.5 size-4 shrink-0 text-success" aria-hidden="true" />
            <div className="grid gap-1">
              <span className="text-small font-medium">
                Keep badges at content width in flex columns
              </span>
              <span className="text-caption text-muted-foreground">
                khalmohak merged 3 commits into main
              </span>
            </div>
          </div>
        </HoverCardContent>
      </HoverCard>
      .
    </Text>
  )
}
```

Live page: https://glyphui.xyz/components/hover-card

---

# ImageViewer

> An image you can zoom, pan, rotate and download, with keyboard and touch support.

Status: beta. Category: Viewers.

```ts
import { ImageViewer } from '@glyphui/viewers/media'
```

Exports: `ImageViewer`, `imageViewerStyles`.

## Notes

- No extra packages needed.
- Zoom with the buttons, ⌘ or Ctrl + scroll, a trackpad pinch or two fingers. Plain scrolling still scrolls the page.
- Keyboard: + and − zoom, 0 fits, 1 shows actual size, R rotates, arrow keys pan.

## ImageViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `alt` (required) | `string` |  | Alternative text. Required for meaningful images. |
| `source` (required) | `ViewerSource` |  | The image: a URL, a File/Blob, or bytes. |
| `bordered` | `boolean` |  | Draw the viewer as a bordered card. Default true. |
| `className` | `string` |  |  |
| `downloadable` | `boolean` |  | Show a download button. Default true. |
| `height` | `string \| number` |  | Height of the viewer. Default 420. |
| `maxZoom` | `number` |  |  |
| `minZoom` | `number` |  | Zoom limits, as a scale of the natural size. Default 0.05–16. |

## Example: Zoom and pan

Double-click to zoom in, drag to pan.

```tsx
import { ImageViewer } from '@glyphui/viewers/media'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return (
    <ImageViewer
      source={fixture('aurora.jpg')}
      alt="A blue-to-green gradient with a faint grid"
      height={400}
      className="w-full"
    />
  )
}
```

Live page: https://glyphui.xyz/components/image-viewer

---

# Input

> A single-line text field with optional prefix and suffix content.

Status: stable. Category: Forms.

```ts
import { Input } from '@glyphui/ui'
```

Exports: `Input`, `inputStyles`, `fieldControl`.

## Notes

- className styles the outer frame; use inputClassName for the <input> element itself.
- fieldControl is the shared class list used by Input, Textarea and the Select trigger.

## Input props

| Prop | Type | Default | Description |
|---|---|---|---|
| `inputClassName` | `string` |  | Classes for the `<input>` element itself. `className` styles the outer frame. |
| `prefix` | `ReactNode` |  | Content before the text, e.g. an icon or `https://`. |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `suffix` | `ReactNode` |  | Content after the text, e.g. a unit or a Kbd hint. |

## Example: Basic

```tsx
import { Input } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-sm gap-3">
      <Input aria-label="Project name" placeholder="Project name" />
      <Input aria-label="Disabled" placeholder="Disabled" disabled />
    </div>
  )
}
```

## Example: Prefix and suffix

```tsx
import { Input, Kbd } from '@glyphui/ui'
import { Globe, Search } from 'lucide-react'

export default function Example() {
  return (
    <div className="grid max-w-sm gap-3">
      <Input aria-label="Workspace URL" prefix="glyph.app/" defaultValue="acme" />
      <Input aria-label="Domain" prefix={<Globe />} placeholder="acme.dev" />
      <Input aria-label="Search" prefix={<Search />} placeholder="Search" suffix={<Kbd>/</Kbd>} />
      <Input aria-label="Price" type="number" defaultValue="24" suffix="USD / month" />
    </div>
  )
}
```

## Example: Sizes

```tsx
import { Input } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-sm gap-3">
      <Input size="sm" aria-label="Small" placeholder="Small" />
      <Input size="md" aria-label="Medium" placeholder="Medium" />
      <Input size="lg" aria-label="Large" placeholder="Large" />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/input

---

# InputOTP

> One-time code input with a box per character, paste support and SMS autofill on mobile.

Status: beta. Category: Forms.

```ts
import { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator, REGEXP_ONLY_DIGITS, REGEXP_ONLY_CHARS } from '@glyphui/ui'
```

Exports: `InputOTP`, `InputOTPGroup`, `InputOTPSlot`, `InputOTPSeparator`, `inputOtpStyles`, `REGEXP_ONLY_DIGITS`, `REGEXP_ONLY_CHARS`, `REGEXP_ONLY_DIGITS_AND_CHARS`.

## Notes

- It is one real input under the boxes, so paste, autofill and screen readers work as with a normal field.
- Restrict characters with pattern, e.g. REGEXP_ONLY_DIGITS.

## InputOTP props

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` | `ReactNode` |  | Custom slot layout (InputOTPGroup, InputOTPSlot, InputOTPSeparator). Defaults to one group of `length` slots. |
| `containerClassName` | `string` |  |  |
| `length` | `number` |  | Number of characters. Default 6. |
| `nonce` | `string` |  |  |
| `noScriptCSSFallback` | `string \| null` |  |  |
| `onChange` | `((newValue: string) => unknown)` |  |  |
| `onComplete` | `((...args: any[]) => unknown)` |  |  |
| `pasteTransformer` | `((pasted: string) => string)` |  |  |
| `pushPasswordManagerStrategy` | `"none" \| "increase-width"` |  |  |
| `textAlign` | `"center" \| "right" \| "left"` |  |  |
| `value` | `string` |  |  |

## Example: Six digits

Verifies once the last digit is typed.

```tsx
import { Field, InputOTP, REGEXP_ONLY_DIGITS } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [status, setStatus] = useState<'idle' | 'checking' | 'done'>('idle')
  return (
    <Field
      label="Verification code"
      description={
        status === 'done'
          ? 'Verified.'
          : status === 'checking'
            ? 'Checking…'
            : 'We sent a code to •••• 4821.'
      }
    >
      <InputOTP
        pattern={REGEXP_ONLY_DIGITS}
        onComplete={() => {
          setStatus('checking')
          setTimeout(() => setStatus('done'), 800)
        }}
      />
    </Field>
  )
}
```

## Example: Custom groups

Compose groups and separators yourself.

```tsx
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
  REGEXP_ONLY_DIGITS_AND_CHARS,
} from '@glyphui/ui'

export default function Example() {
  return (
    <InputOTP aria-label="Recovery code" length={8} pattern={REGEXP_ONLY_DIGITS_AND_CHARS}>
      <InputOTPGroup>
        <InputOTPSlot index={0} />
        <InputOTPSlot index={1} />
        <InputOTPSlot index={2} />
        <InputOTPSlot index={3} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot index={4} />
        <InputOTPSlot index={5} />
        <InputOTPSlot index={6} />
        <InputOTPSlot index={7} />
      </InputOTPGroup>
    </InputOTP>
  )
}
```

Live page: https://glyphui.xyz/components/input-otp

---

# JsonViewer

> Explore JSON as a collapsible tree: search keys and values, expand to any depth, copy a value or its JSONPath, or read the raw text.

Status: beta. Category: Viewers.

```ts
import { JsonViewer } from '@glyphui/viewers/json'
```

Exports: `JsonViewer`, `jsonViewerStyles`, `indexJson`, `parseJson`, `searchJson`, `childPath`.

## Notes

- No extra packages needed.
- The tree is keyboard navigable: arrow keys move and expand, Home and End jump, Enter toggles.
- Only rows in view are rendered, so documents with tens of thousands of nodes stay responsive.
- Select a row to see its JSONPath in the footer, with buttons to copy the path or the value.

## JsonViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `bordered` | `boolean` |  | Draw the viewer as a bordered card. Default true. |
| `className` | `string` |  |  |
| `content` | `string` |  | JSON text, instead of `source`. |
| `data` | `unknown` |  | An already parsed value, instead of `source` or `content`. |
| `defaultExpandDepth` | `number` |  | Levels expanded at first. Default 2. Use `Infinity` to expand everything. |
| `height` | `string \| number` |  | Height of the viewer. Default 420. |
| `label` | `string` |  | Accessible name for the tree. Default "JSON". |
| `source` | `ViewerSource` |  | A JSON file: a URL, a File/Blob, or bytes. |

## Example: A JSON file

Search for “invoice”, then step through the matches.

```tsx
import { JsonViewer } from '@glyphui/viewers/json'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <JsonViewer source={fixture('workspace.json')} label="workspace.json" className="w-full" />
}
```

## Example: A value from your app

Pass parsed data directly, here an API response.

```tsx
import { JsonViewer } from '@glyphui/viewers/json'

const response = {
  data: [
    { id: 'evt_1', type: 'invoice.paid', amount: 1250, livemode: true },
    { id: 'evt_2', type: 'invoice.overdue', amount: 86.5, livemode: true },
  ],
  has_more: false,
  next_cursor: null,
}

export default function Example() {
  return (
    <JsonViewer
      data={response}
      defaultExpandDepth={3}
      height={300}
      label="Events response"
      className="w-full"
    />
  )
}
```

## Example: Invalid JSON

Syntax errors point at the line and column.

```tsx
import { JsonViewer } from '@glyphui/viewers/json'

const broken = `{
  "name": "Ledgerline",
  "plan": "growth",
  "seats": 25,
}`

export default function Example() {
  return <JsonViewer content={broken} height={260} className="w-full" />
}
```

Live page: https://glyphui.xyz/components/json-viewer

---

# Kbd

> A keyboard key or shortcut hint.

Status: stable. Category: Data display.

```ts
import { Kbd } from '@glyphui/ui'
```

Exports: `Kbd`, `kbdStyles`.

## Example: Shortcuts

```tsx
import { Kbd, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-2">
      <Text size="small">
        Open the command menu with <Kbd>⌘</Kbd> <Kbd>K</Kbd>
      </Text>
      <Text size="small">
        Save with <Kbd>Ctrl</Kbd> + <Kbd>S</Kbd>
      </Text>
    </div>
  )
}
```

## Example: Inside an input

```tsx
import { Input, Kbd } from '@glyphui/ui'
import { Search } from 'lucide-react'

export default function Example() {
  return (
    <Input
      aria-label="Search docs"
      placeholder="Search docs"
      prefix={<Search />}
      suffix={<Kbd>/</Kbd>}
      className="max-w-xs"
    />
  )
}
```

Live page: https://glyphui.xyz/components/kbd

---

# Label

> An accessible label for a form control. Field renders one for you.

Status: stable. Category: Forms.

```ts
import { Label } from '@glyphui/ui'
```

Exports: `Label`, `labelStyles`.

## Notes

- Prefer Field, which also wires descriptions, errors and aria attributes.

## Label props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |

## Example: With a control

```tsx
import { Checkbox, Label } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-2">
      <Checkbox id="remember" />
      <Label htmlFor="remember">Remember this device</Label>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/label

---

# Link

> A text link with an animated underline. Internal links use your router; external ones open safely in a new tab.

Status: beta. Category: Navigation.

```ts
import { Link } from '@glyphui/ui'
```

Exports: `Link`, `linkStyles`.

## Notes

- External links announce "(opens in a new tab)" to screen readers.

## Example: Tones and underline

```tsx
import { Link, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-2">
      <Text>
        Read the <Link href="#">theme guide</Link> before you start.
      </Text>
      <Text tone="muted">
        <Link href="#" tone="muted" underline="always">
          Privacy policy
        </Link>{' '}
        ·{' '}
        <Link href="#" tone="default">
          Terms
        </Link>
      </Text>
    </div>
  )
}
```

## Example: External

Adds target, rel, an arrow and a screen-reader hint.

```tsx
import { Link } from '@glyphui/ui'

export default function Example() {
  return (
    <Link href="https://www.radix-ui.com" external>
      Radix UI primitives
    </Link>
  )
}
```

Live page: https://glyphui.xyz/components/link

---

# LogoCloud

> A row of customer or partner logos, muted so they support the page rather than compete with it.

Status: beta. Category: Blocks.

```ts
import { LogoCloud } from '@glyphui/blocks'
```

Exports: `LogoCloud`.

## Notes

- Pass { name, logo } so each logo gets an accessible name, even when the logo is an SVG.

## LogoCloud props

| Prop | Type | Default | Description |
|---|---|---|---|
| `logos` (required) | `readonly (ReactNode \| LogoItem)[]` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `title` | `ReactNode` |  | Short line above the logos, e.g. "Trusted by teams at". |

## Example: Customer logos

```tsx
import { LogoCloud } from '@glyphui/blocks'

const names = ['Northwind', 'Contoso', 'Initech', 'Umbrella', 'Hooli', 'Vandelay']

export default function Example() {
  return (
    <LogoCloud
      title="Trusted by finance teams at"
      logos={names.map((name) => ({
        name,
        logo: <span className="font-display text-h4 tracking-tight">{name}</span>,
      }))}
    />
  )
}
```

Live page: https://glyphui.xyz/components/logo-cloud

---

# MagicLinkCallback

> The page a sign-in link opens: trades the link’s token for a session, then continues where the user was going.

Status: beta. Category: Auth.

```ts
import { MagicLinkCallback } from '@glyphui/auth/ui'
```

Exports: `MagicLinkCallback`.

## Notes

- By default it reads ?token= from the URL; pass token (or param) when your link differs.
- With React Router: onSuccess={useRedirectAfterSignIn("/app")} continues to ?next= or your default.
- Accounts with two-step sign-in continue to the code step on the same page.
- Needs an adapter with capabilities.magicLink. The REST adapter posts the token to /auth/magic-link/verify.
- A link works once: React’s development double effects don’t spend it twice.

## MagicLinkCallback props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `description` | `ReactNode` |  |  |
| `footer` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` |  | Heading level of the title. Default 1, for a page whose main content is the form. |
| `onSuccess` | `((session: AuthSession) => void)` |  | Called once the user is signed in, e.g. to continue to `?next=`. |
| `param` | `string` | `token` | Query parameter that carries the token. Default `token`. |
| `signInHref` | `string` |  | Adds "Back to sign in" when the link can't be used. |
| `title` | `ReactNode` |  |  |
| `token` | `string \| null` |  | The token from the sign-in link. Default: the `param` query parameter of the current URL. |

## Example: Open a sign-in link

Send a link to ada@example.com, then open it: the callback signs in and reports success. Opening it twice shows the expired state.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { MagicLinkCallback } from '@glyphui/auth/ui'
import { Button } from '@glyphui/ui'
import { useState } from 'react'

const adapter = memoryAdapter({
  latency: 400,
  users: [{ email: 'ada@example.com', password: 'correct horse', name: 'Ada Lovelace' }],
  onCode: () => {},
})

function Demo() {
  const { signIn, signOut, user } = useAuth()
  const [token, setToken] = useState<string | null>(null)
  const [opened, setOpened] = useState(0)

  if (opened > 0 && token)
    return (
      <div className="grid w-full max-w-sm gap-3">
        <MagicLinkCallback key={opened} token={token} headingLevel={3} />
        <div className="flex flex-wrap justify-center gap-2">
          {user && (
            <Button variant="outline" size="sm" onClick={() => setOpened((n) => n + 1)}>
              Open the same link again
            </Button>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={async () => {
              if (user) await signOut()
              setToken(null)
              setOpened(0)
            }}
          >
            Start over
          </Button>
        </div>
      </div>
    )

  return (
    <div className="grid justify-items-center gap-3">
      <Button
        onClick={async () => {
          await signIn({ email: 'ada@example.com', magicLink: true })
          setToken(adapter.lastCode('ada@example.com', 'magic-link') ?? null)
        }}
      >
        Email me a sign-in link
      </Button>
      {token && (
        <Button variant="outline" onClick={() => setOpened(1)}>
          Open the link from the email
        </Button>
      )}
    </div>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Demo />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/magic-link-callback

---

# MarkdownViewer

> Render Markdown with your theme’s typography: GitHub tables, task lists, highlighted code blocks and heading links.

Status: beta. Category: Viewers.

```ts
import { MarkdownViewer } from '@glyphui/viewers/markdown'
```

Exports: `MarkdownViewer`, `markdownViewerStyles`, `slugify`.

## Notes

- Install the optional peer dependencies first: npm install react-markdown remark-gfm shiki.
- Safe by default: raw HTML in the Markdown shows as text. If you need HTML, add rehype-raw to rehypePlugins and rehype-sanitize after it.
- Code blocks render with CodeViewer, so they follow your theme too.

## MarkdownViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `components` | `Components` |  | Override how elements render, as in react-markdown. |
| `content` | `string` |  | Markdown text. |
| `headingAnchors` | `boolean` |  | Adds `#` links to headings so readers can share them. Default true. |
| `rehypePlugins` | `PluggableList \| null` |  | Extra rehype plugins. Raw HTML in the Markdown is never rendered unless you add `rehype-raw` here, and then you should add `rehype-sanitize` after it. |
| `source` | `ViewerSource` |  | A Markdown file to load instead: a URL, a File/Blob, or bytes. |

## Example: A README

Hover a heading for its link.

```tsx
import { MarkdownViewer } from '@glyphui/viewers/markdown'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <MarkdownViewer source={fixture('README.md')} className="w-full max-w-2xl" />
}
```

Live page: https://glyphui.xyz/components/markdown-viewer

---

# Memory adapter

> A complete auth backend in the browser for prototypes, demos and tests: sign-up, email codes, two-step, magic links, organizations.

Status: beta. Category: Auth.

```ts
import { Memory adapter } from '@glyphui/auth/memory'
```

Exports: `memoryAdapter`.

## Notes

- Passwords are stored in plain text. Never use it in production.
- persist: "local" keeps users and the session in localStorage, shared between tabs.
- fail lets an operation throw, to see error states: fail: (op) => op === "signIn" ? new AuthError("Down") : undefined.
- expireSession() revokes the session server-side, to try SessionExpiredDialog.

## Example: Prototype a full flow

Every screen works against it. "Emailed" codes appear as toasts here; by default they are logged to the console.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SignInForm } from '@glyphui/auth/ui'
import { Button, Text, toast } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 500,
  users: [
    { email: 'ada@example.com', password: 'correct horse', name: 'Ada Lovelace' },
    { email: 'grace@example.com', password: 'cobol rules', name: 'Grace Hopper', twoFactor: true },
  ],
  onCode: ({ kind, email, code }) =>
    toast(`Email to ${email}`, { description: `${kind}: ${code}` }),
})

function Demo() {
  const { user, signOut } = useAuth()
  if (user)
    return (
      <div className="grid justify-items-center gap-3">
        <Text>Signed in as {user.name}.</Text>
        <Button variant="outline" onClick={() => signOut()}>
          Sign out
        </Button>
      </div>
    )
  return (
    <SignInForm
      headingLevel={3}
      description="Try ada@example.com / correct horse, or grace@example.com / cobol rules for two steps."
    />
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Demo />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/auth-memory

---

# Modal

> The everyday modal in one component: pass a title, description, body and footer. Built on Dialog.

Status: beta. Category: Overlays.

```ts
import { Modal, ModalClose } from '@glyphui/ui'
```

Exports: `Modal`, `ModalClose`, `modalStyles`.

## Notes

- Use Modal for most cases. Reach for the Dialog parts when you need a custom layout, AlertDialog or useConfirm() for yes/no decisions, and Sheet for side panels.
- The title is required: it becomes the modal’s accessible name.
- The footer sits outside the body, so a FormSubmit there needs form={form}; a plain submit button needs onSubmit on the Modal.
- Set closeOnOverlayClick={false} for forms where a stray click would lose input; Escape still closes.

## Modal props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  | Heading of the modal. Also its accessible name. |
| `asChild` | `boolean` |  |  |
| `closeOnOverlayClick` | `boolean` |  | Close when the backdrop is clicked. Default true. |
| `defaultOpen` | `boolean` |  |  |
| `description` | `ReactNode` |  |  |
| `footer` | `ReactNode` |  | Actions at the bottom. Wrap a button in `ModalClose` to close on click. |
| `onOpenChange` | `((open: boolean) => void)` |  |  |
| `onSubmit` | `((event: FormEvent<HTMLFormElement>) => void)` |  | Turns the body and footer into one `<form>`, so a `type="submit"` button in the footer submits the fields in the body. The page does not reload. With `@glyphui/ui/form`, use `<Form>` in the body and `<FormSubmit form={form}>` in the footer instead. |
| `open` | `boolean` |  |  |
| `overlayClassName` | `string` |  |  |
| `showClose` | `boolean` |  | Show the close button in the corner. Default true. |
| `size` | `"sm" \| "md" \| "lg" \| "xl"` |  |  |
| `trigger` | `ReactNode` |  | Element that opens the modal, e.g. a Button. Optional when you control `open`. |

## Example: With a trigger

Pass the opening button as trigger; wrap footer buttons in ModalClose.

```tsx
import { Button, Field, Input, Modal, ModalClose } from '@glyphui/ui'
import { UserPlus } from 'lucide-react'

export default function Example() {
  return (
    <Modal
      title="Invite teammates"
      description="They get access to every project in Acme Inc."
      trigger={<Button leftIcon={<UserPlus />}>Invite</Button>}
      footer={
        <>
          <ModalClose asChild>
            <Button variant="outline">Cancel</Button>
          </ModalClose>
          <ModalClose asChild>
            <Button>Send invites</Button>
          </ModalClose>
        </>
      }
    >
      <Field label="Email addresses" description="Separate addresses with commas.">
        <Input placeholder="grace@acme.com, alan@acme.com" />
      </Field>
    </Modal>
  )
}
```

## Example: Controlled

Open it from code, e.g. after a row action or a keyboard shortcut.

```tsx
import { Button, Modal, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(false)
  return (
    <div className="flex flex-col items-center gap-3">
      <Button variant="outline" onClick={() => setOpen(true)}>
        View keyboard shortcuts
      </Button>
      <Text size="small" tone="muted">
        Modal is {open ? 'open' : 'closed'}
      </Text>
      <Modal
        open={open}
        onOpenChange={setOpen}
        size="sm"
        title="Keyboard shortcuts"
        footer={<Button onClick={() => setOpen(false)}>Got it</Button>}
      >
        <dl className="grid grid-cols-[1fr_auto] gap-y-2 text-small">
          <dt>Search</dt>
          <dd className="font-mono text-muted-foreground">⌘K</dd>
          <dt>New issue</dt>
          <dd className="font-mono text-muted-foreground">C</dd>
          <dt>Go to inbox</dt>
          <dd className="font-mono text-muted-foreground">G then I</dd>
        </dl>
      </Modal>
    </div>
  )
}
```

## Example: With a form

onSubmit turns the body and footer into one form, so a submit button in the footer works.

```tsx
import { Button, Field, Input, Modal, Textarea, toast } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(false)
  const [saving, setSaving] = useState(false)

  return (
    <Modal
      open={open}
      onOpenChange={setOpen}
      closeOnOverlayClick={false}
      title="New project"
      description="You can change these details later."
      trigger={<Button>New project</Button>}
      onSubmit={async () => {
        setSaving(true)
        await new Promise((resolve) => setTimeout(resolve, 800))
        setSaving(false)
        setOpen(false)
        toast.success('Project created')
      }}
      footer={
        <Button type="submit" loading={saving}>
          Create project
        </Button>
      }
    >
      <Field label="Name" required>
        <Input name="name" placeholder="Website redesign" required />
      </Field>
      <Field label="Description">
        <Textarea name="description" placeholder="What is this project about?" />
      </Field>
    </Modal>
  )
}
```

## Example: With a validated form

Schema validation with @glyphui/ui/form: <Form> in the body, <FormSubmit form={form}> in the footer.

```tsx
import {
  Button,
  DatePicker,
  Input,
  Modal,
  ModalClose,
  NumberInput,
  Select,
  SelectItem,
  toast,
} from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { z } from 'zod'

const customers = ['Northwind', 'Globex', 'Initech', 'Umbrella']

const schema = z.object({
  customer: z.string().min(1, 'Choose a customer'),
  amount: z.number('Enter an amount').positive('Must be more than zero'),
  due: z.date('Choose a due date'),
  memo: z.string().max(140, 'Keep it under 140 characters'),
})

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

export default function Example() {
  const [open, setOpen] = useState(false)
  const form = useForm({
    schema,
    defaultValues: { customer: '', amount: undefined, due: undefined, memo: '' },
  })

  return (
    <Modal
      open={open}
      onOpenChange={(next) => {
        if (!next) form.reset()
        setOpen(next)
      }}
      title="New invoice"
      description="The customer gets an email with a payment link."
      trigger={<Button leftIcon={<Plus />}>New invoice</Button>}
      footer={
        <>
          <ModalClose asChild>
            <Button variant="outline">Cancel</Button>
          </ModalClose>
          {/* Outside <Form>, so it gets the form explicitly. */}
          <FormSubmit form={form}>Create invoice</FormSubmit>
        </>
      }
    >
      <Form
        form={form}
        className="grid gap-4"
        onSubmit={async (values) => {
          await new Promise((resolve) => setTimeout(resolve, 600))
          if (values.amount > 50_000) {
            return { errors: { amount: 'Invoices over $50,000 need approval.' } }
          }
          toast.success('Invoice created', {
            description: `${values.customer} · ${usd.format(values.amount)}`,
          })
          setOpen(false)
          form.reset()
        }}
      >
        <FormError />
        <FormField control={form.control} name="customer" label="Customer" required>
          {(field) => (
            <Select
              placeholder="Choose a customer"
              value={field.value}
              onValueChange={field.onChange}
            >
              {customers.map((name) => (
                <SelectItem key={name} value={name}>
                  {name}
                </SelectItem>
              ))}
            </Select>
          )}
        </FormField>
        <div className="grid gap-4 sm:grid-cols-2">
          <FormField control={form.control} name="amount" label="Amount" required>
            {(field) => (
              <NumberInput
                value={field.value ?? null}
                onValueChange={(value) => field.onChange(value ?? undefined)}
                min={0}
                locale="en-US"
                formatOptions={{ style: 'currency', currency: 'USD' }}
              />
            )}
          </FormField>
          <FormField control={form.control} name="due" label="Due date" required>
            {(field) => (
              <DatePicker value={field.value} onValueChange={field.onChange} minDate={new Date()} />
            )}
          </FormField>
        </div>
        <FormField
          control={form.control}
          name="memo"
          label="Memo"
          description="Shown on the invoice."
        >
          {(field) => <Input placeholder="October usage" {...field} />}
        </FormField>
      </Form>
    </Modal>
  )
}
```

Live page: https://glyphui.xyz/components/modal

---

# Motion

> Animation on by default and controlled from the theme: overlays spring out of their triggers, active indicators slide, lists animate, and sections reveal on scroll.

Status: beta. Category: Patterns.

```ts
import { Reveal, Stagger, StaggerItem, AnimatedNumber, PageTransition, Presence } from '@glyphui/ui'
```

Exports: `Reveal`, `Stagger`, `StaggerItem`, `AnimatedNumber`, `PageTransition`, `Presence`, `ActiveIndicator`, `m`, `useMotionSettings`.

## Notes

- StaggerItem orders itself by document order when you leave out index; pass index only to override the cascade.
- Set theme.motion.level to none, subtle or expressive, and theme.motion.spring to { stiffness, damping, mass? } — overlays, indicators and reveals all follow it. Brutalist snaps with no bounce; Playful is expressive.
- GlyphProvider motion="none" overrides the theme for the whole app, e.g. in tests or from a user setting. Visitors who ask their system for reduced motion never get animation.
- The spring is compiled to a CSS linear() easing (--glyph-ease-spring, with --glyph-duration-spring), so plain CSS can use it: ease-spring duration-(--glyph-duration-spring).
- Content never depends on JavaScript to become visible: server HTML, tests and reduced-motion visitors see it immediately; only browsers that can animate it hide it first.
- The motion library loads its animation features lazily on first render; Button and other CSS-only components never import it.
- Blocks animate by default; pass animate={false} to any block to turn its entrance off.

## Reveal props

| Prop | Type | Default | Description |
|---|---|---|---|
| `amount` | `number` |  | Share of the element that must be visible, 0–1. Default 0.15. |
| `asChild` | `boolean` |  |  |
| `delay` | `number` |  | Delay before the entrance starts, in milliseconds. |
| `enabled` | `boolean` |  | Set false to show the content without animating. |
| `once` | `boolean` |  | Animate only the first time it scrolls into view. Default true. |
| `scale` | `boolean` |  | Start slightly smaller, for cards and media. |
| `y` | `string \| number` |  | Distance it rises from, in px or any CSS length. Defaults to the motion level's. |

## Example: Motion levels

The same components at each level. `subtle` is the default; `expressive` travels further and bounces with a soft spring; `none` renders everything instantly.

```tsx
import {
  AnimatedNumber,
  Card,
  Checkbox,
  defineTheme,
  type MotionLevel,
  SegmentedControl,
  Stagger,
  Switch,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
  Text,
  ThemeScope,
  useGlyph,
} from '@glyphui/ui'
import { useMemo, useState } from 'react'

export default function Example() {
  const { theme } = useGlyph()
  const [level, setLevel] = useState<MotionLevel>('subtle')
  const [replay, setReplay] = useState(0)
  const [seats, setSeats] = useState(12)
  const scoped = useMemo(
    () => defineTheme({ name: `${theme.name}-motion-${level}`, extends: theme, motion: { level } }),
    [theme, level],
  )

  return (
    <div className="grid w-full gap-4">
      <SegmentedControl<MotionLevel>
        aria-label="Motion level"
        className="justify-self-start"
        value={level}
        onValueChange={(next) => {
          setLevel(next)
          setReplay((n) => n + 1)
        }}
        options={[
          { value: 'none', label: 'None' },
          { value: 'subtle', label: 'Subtle' },
          { value: 'expressive', label: 'Expressive' },
        ]}
      />
      <ThemeScope theme={scoped} className="grid gap-5 rounded-lg p-5">
        <div className="flex flex-wrap items-center gap-6">
          <Tabs defaultValue="overview">
            <TabsList>
              <TabsTrigger value="overview">Overview</TabsTrigger>
              <TabsTrigger value="activity">Activity</TabsTrigger>
              <TabsTrigger value="settings">Settings</TabsTrigger>
            </TabsList>
            <TabsContent value="overview" className="sr-only" tabIndex={-1}>
              Overview
            </TabsContent>
            <TabsContent value="activity" className="sr-only" tabIndex={-1}>
              Activity
            </TabsContent>
            <TabsContent value="settings" className="sr-only" tabIndex={-1}>
              Settings
            </TabsContent>
          </Tabs>
          <SegmentedControl
            aria-label="View"
            size="sm"
            defaultValue="list"
            options={[
              { value: 'list', label: 'List' },
              { value: 'board', label: 'Board' },
              { value: 'timeline', label: 'Timeline' },
            ]}
          />
          <Switch aria-label="Notifications" defaultChecked />
          <Checkbox aria-label="Done" />
        </div>
        <Stagger key={replay} className="grid gap-3 sm:grid-cols-3">
          {['Revenue', 'Seats', 'Uptime'].map((label, i) => (
            <Card key={label} padding="sm">
              <Text size="small" tone="muted">
                {label}
              </Text>
              <p className="font-display text-h3">
                {i === 1 ? (
                  <button
                    type="button"
                    className="cursor-pointer"
                    onClick={() => setSeats((n) => n + 7)}
                  >
                    <AnimatedNumber value={seats} />
                  </button>
                ) : i === 0 ? (
                  '$48k'
                ) : (
                  '99.98%'
                )}
              </p>
            </Card>
          ))}
        </Stagger>
      </ThemeScope>
    </div>
  )
}
```

## Example: Reveal and Stagger

Entrances on scroll. Every Glyph block uses them, so landing pages come alive with no code.

```tsx
import { Button, Card, Reveal, Stagger, Text } from '@glyphui/ui'
import { RotateCcw } from 'lucide-react'
import { useState } from 'react'

const features = ['Automatic retries', 'Revenue reports', 'Audit logs', 'Usage billing']

export default function Example() {
  const [run, setRun] = useState(0)
  return (
    <div className="grid w-full gap-6">
      <Button
        variant="outline"
        size="sm"
        leftIcon={<RotateCcw />}
        className="justify-self-start"
        onClick={() => setRun((n) => n + 1)}
      >
        Replay
      </Button>
      <div key={run} className="grid gap-6">
        <Reveal className="grid gap-1">
          <p className="font-display text-h3">Billing that keeps up</p>
          <Text tone="muted">Reveal fades and lifts a block in when it scrolls into view.</Text>
        </Reveal>
        <Stagger as="ul" className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          {features.map((feature) => (
            <li key={feature}>
              <Card padding="sm" className="h-full">
                <Text weight="medium">{feature}</Text>
              </Card>
            </li>
          ))}
        </Stagger>
      </div>
    </div>
  )
}
```

## Example: AnimatedNumber

```tsx
import { AnimatedNumber, Button, Card, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [mrr, setMrr] = useState(48210)
  return (
    <Card className="w-full max-w-sm gap-3">
      <Text size="small" tone="muted">
        Monthly recurring revenue
      </Text>
      <p className="font-display text-h1">
        <AnimatedNumber
          value={mrr}
          locale="en-US"
          format={{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }}
        />
      </p>
      <div className="flex gap-2">
        <Button size="sm" onClick={() => setMrr((n) => n + 1840)}>
          New customer
        </Button>
        <Button size="sm" variant="outline" onClick={() => setMrr((n) => Math.max(0, n - 920))}>
          Churn
        </Button>
      </div>
    </Card>
  )
}
```

## Example: Page transitions

Wrap your router outlet and key it by path. With React Router: <PageTransition transitionKey={useLocation().pathname}><Outlet /></PageTransition>.

```tsx
import { PageTransition, SegmentedControl, Text } from '@glyphui/ui'
import { useState } from 'react'

const pages = {
  inbox: 'Three unread conversations, one waiting on you.',
  issues: '12 open issues, 3 due this week.',
  reports: 'Revenue is up 11.9% month over month.',
} as const
type Page = keyof typeof pages

export default function Example() {
  const [page, setPage] = useState<Page>('inbox')
  return (
    <div className="grid w-full max-w-md gap-4">
      <SegmentedControl<Page>
        aria-label="Page"
        value={page}
        onValueChange={setPage}
        options={[
          { value: 'inbox', label: 'Inbox' },
          { value: 'issues', label: 'Issues' },
          { value: 'reports', label: 'Reports' },
        ]}
      />
      {/* With a router: transitionKey={useLocation().pathname} around <Outlet />. */}
      <PageTransition
        transitionKey={page}
        className="grid gap-1 rounded-lg border border-border p-5"
      >
        <p className="font-display text-h4 capitalize">{page}</p>
        <Text tone="muted">{pages[page]}</Text>
      </PageTransition>
    </div>
  )
}
```

## Example: Custom enter and exit

Presence and m.* elements from motion, sharing the theme’s spring.

```tsx
import { Button, m, Presence, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(true)
  return (
    <div className="grid w-full max-w-sm gap-4">
      <Button variant="outline" className="justify-self-start" onClick={() => setOpen((o) => !o)}>
        {open ? 'Dismiss' : 'Show'} banner
      </Button>
      <Presence>
        {open && (
          <m.div
            key="banner"
            initial={{ opacity: 0, y: -8, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: -8, scale: 0.98 }}
            className="rounded-lg border border-border bg-surface p-4 shadow-sm"
          >
            <Text weight="medium">Your trial ends in 3 days</Text>
            <Text size="small" tone="muted">
              Pick a plan to keep your invoices sending.
            </Text>
          </m.div>
        )}
      </Presence>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/motion

---

# Navbar

> Site header built from data: brand, links and actions. Responsive, with a menu panel on small screens.

Status: stable. Category: Patterns.

```ts
import { Navbar } from '@glyphui/ui'
```

Exports: `Navbar`, `navbarStyles`.

## Notes

- By default it is sticky and transparent, gaining a blurred background and border once the page scrolls.
- Links render through GlyphProvider linkComponent, so router navigation works.

## Navbar props

| Prop | Type | Default | Description |
|---|---|---|---|
| `brand` (required) | `ReactNode` |  |  |
| `actions` | `ReactNode` |  | Right side on desktop; bottom of the menu panel on mobile. |
| `blurOnScroll` | `boolean` |  | Transparent at the top; translucent with blur and a border once scrolled. Default true. |
| `containerSize` | `"sm" \| "md" \| "lg" \| "xl" \| "full"` |  |  |
| `links` | `readonly NavLink[]` |  |  |
| `sticky` | `boolean` |  | Stick to the top of the viewport. Default true. |

## Example: Basic

```tsx
import { Button, Navbar } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="overflow-hidden rounded-lg border border-border">
      <Navbar
        sticky={false}
        blurOnScroll={false}
        brand={<span className="font-display">acme</span>}
        links={[
          { label: 'Product', href: '#product', active: true },
          { label: 'Pricing', href: '#pricing' },
          { label: 'Docs', href: '#docs' },
        ]}
        actions={
          <>
            <Button variant="ghost" size="sm">
              Sign in
            </Button>
            <Button size="sm">Get started</Button>
          </>
        }
      />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/navbar

---

# NavigationMenu

> Site navigation with dropdown panels for marketing headers, including mega-menu link cards.

Status: beta. Category: Navigation.

```ts
import { NavigationMenu, NavigationMenuList, NavigationMenuItem, NavigationMenuTrigger, NavigationMenuContent, NavigationMenuLink } from '@glyphui/ui'
```

Exports: `NavigationMenu`, `NavigationMenuList`, `NavigationMenuItem`, `NavigationMenuTrigger`, `NavigationMenuContent`, `NavigationMenuLink`, `NavigationMenuViewport`, `NavigationMenuCard`, `navigationMenuStyles`.

## Notes

- Links render through the provider’s linkComponent, so they use your router.
- For app navigation use Sidebar; for a simple site header use Navbar. NavigationMenu is for headers with rich dropdown panels.
- Mark the current page with active on NavigationMenuLink; it sets aria-current="page".

## NavigationMenuCard props

| Prop | Type | Default | Description |
|---|---|---|---|
| `href` (required) | `string` |  |  |
| `title` (required) | `ReactNode` |  |  |
| `className` | `string` |  |  |
| `description` | `ReactNode` |  |  |
| `icon` | `ReactNode` |  |  |

## Example: Mega menu

Panels share one animated viewport that resizes between them.

```tsx
import {
  NavigationMenu,
  NavigationMenuCard,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
} from '@glyphui/ui'
import { BookOpen, Boxes, LayoutTemplate, Palette, Rocket, Users } from 'lucide-react'

export default function Example() {
  return (
    <div className="flex h-80 w-full justify-center pt-2">
      <NavigationMenu>
        <NavigationMenuList>
          <NavigationMenuItem>
            <NavigationMenuTrigger>Product</NavigationMenuTrigger>
            <NavigationMenuContent>
              <div className="grid w-[min(34rem,calc(100vw-3rem))] gap-1 sm:grid-cols-2">
                <NavigationMenuCard
                  href="#components"
                  icon={<Boxes />}
                  title="Components"
                  description="Themed parts for every screen."
                />
                <NavigationMenuCard
                  href="#themes"
                  icon={<Palette />}
                  title="Themes"
                  description="One file sets the whole look."
                />
                <NavigationMenuCard
                  href="#blocks"
                  icon={<LayoutTemplate />}
                  title="Blocks"
                  description="Hero, pricing, FAQ and more."
                />
                <NavigationMenuCard
                  href="#start"
                  icon={<Rocket />}
                  title="Get started"
                  description="Install and ship in minutes."
                />
              </div>
            </NavigationMenuContent>
          </NavigationMenuItem>
          <NavigationMenuItem>
            <NavigationMenuTrigger>Resources</NavigationMenuTrigger>
            <NavigationMenuContent>
              <div className="grid w-72 gap-1">
                <NavigationMenuCard
                  href="#docs"
                  icon={<BookOpen />}
                  title="Documentation"
                  description="Guides and API reference."
                />
                <NavigationMenuCard
                  href="#community"
                  icon={<Users />}
                  title="Community"
                  description="Discussions on GitHub."
                />
              </div>
            </NavigationMenuContent>
          </NavigationMenuItem>
          <NavigationMenuItem>
            <NavigationMenuLink href="#pricing" active>
              Pricing
            </NavigationMenuLink>
          </NavigationMenuItem>
        </NavigationMenuList>
      </NavigationMenu>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/navigation-menu

---

# Newsletter

> Email signup with validation and loading, success and error states built in.

Status: beta. Category: Blocks.

```ts
import { Newsletter } from '@glyphui/blocks'
```

Exports: `Newsletter`.

## Notes

- Throw from onSubscribe to show an error; its message is used unless you pass errorMessage.

## Newsletter props

| Prop | Type | Default | Description |
|---|---|---|---|
| `onSubscribe` (required) | `(email: string) => void \| Promise<void>` |  | Called with the email. Reject (throw) to show `errorMessage` or the error's message. |
| `title` (required) | `ReactNode` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `buttonLabel` | `ReactNode` | `Subscribe` |  |
| `description` | `ReactNode` |  |  |
| `errorMessage` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `invalidMessage` | `ReactNode` | `Enter a valid email address.` |  |
| `layout` | `"split" \| "centered"` | `centered` | `centered` (default) or `split` with text beside the form on large screens. |
| `placeholder` | `string` | `you@company.com` |  |
| `privacyNote` | `ReactNode` |  | Small print under the form, e.g. how often you send and how to unsubscribe. |
| `successMessage` | `ReactNode` | `You’re subscribed. Check your inbox to confirm.` |  |

## Example: Centered

Try an address ending in @fail.dev to see the error state.

```tsx
import { Newsletter } from '@glyphui/blocks'

const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

export default function Example() {
  return (
    <Newsletter
      title="The Ledgerline letter"
      description="One email a month on billing, pricing and getting paid faster."
      privacyNote="No spam. Unsubscribe with one click."
      onSubscribe={async (email) => {
        await wait(800)
        if (email.endsWith('@fail.dev'))
          throw new Error('We couldn’t reach the mailing service. Try again.')
      }}
    />
  )
}
```

## Example: Split

```tsx
import { Newsletter } from '@glyphui/blocks'

export default function Example() {
  return (
    <Newsletter
      layout="split"
      title="Get the changelog"
      description="Release notes for every version, straight to your inbox."
      buttonLabel="Notify me"
      onSubscribe={() => new Promise((resolve) => setTimeout(resolve, 600))}
    />
  )
}
```

Live page: https://glyphui.xyz/components/newsletter

---

# NumberInput

> A number field with − / + steppers, arrow-key stepping, min/max clamping and locale formatting.

Status: beta. Category: Forms.

```ts
import { NumberInput } from '@glyphui/ui'
```

Exports: `NumberInput`, `numberInputStyles`.

## Notes

- The value is number | null (empty), never a string.
- Typed values outside min/max are clamped when the field loses focus.
- Home and End jump to min and max.

## NumberInput props

| Prop | Type | Default | Description |
|---|---|---|---|
| `defaultValue` | `number \| null` |  |  |
| `formatOptions` | `NumberFormatOptions` |  | Display formatting when the field isn't focused, e.g. `{ style: 'currency', currency: 'USD' }`. |
| `hideSteppers` | `boolean` |  | Hide the − / + buttons. |
| `inputClassName` | `string` |  | Classes for the `<input>` element. `className` styles the outer frame. |
| `locale` | `string` |  | Locale for formatting. Defaults to the browser's. |
| `max` | `number` |  |  |
| `min` | `number` |  |  |
| `onValueChange` | `((value: number \| null) => void)` |  |  |
| `prefix` | `ReactNode` |  |  |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `step` | `number` |  | Amount added or removed by the steppers and arrow keys. Shift multiplies by 10. Default 1. |
| `suffix` | `ReactNode` |  | Content after the number, before the steppers, e.g. a unit. |
| `value` | `number \| null` |  | `null` means empty. |

## Example: Quantity

Min, max and step. Shift + arrow steps by 10.

```tsx
import { Field, NumberInput } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [seats, setSeats] = useState<number | null>(5)
  return (
    <Field
      label="Seats"
      description={`${seats ?? 0} × $16 = $${(seats ?? 0) * 16} per month`}
      className="w-56"
    >
      <NumberInput value={seats} onValueChange={setSeats} min={1} max={250} />
    </Field>
  )
}
```

## Example: Currency

Formatted while idle, raw while editing; the value stays a number.

```tsx
import { Field, NumberInput } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid w-full max-w-md gap-4 sm:grid-cols-2">
      <Field label="Monthly budget">
        <NumberInput
          defaultValue={2500}
          min={0}
          step={50}
          locale="en-US"
          formatOptions={{ style: 'currency', currency: 'USD', maximumFractionDigits: 0 }}
        />
      </Field>
      <Field label="Discount">
        <NumberInput defaultValue={15} min={0} max={100} step={5} suffix="%" />
      </Field>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/number-input

---

# PageHeader

> The title block at the top of a page: optional eyebrow, title, description and actions.

Status: stable. Category: Patterns.

```ts
import { PageHeader } from '@glyphui/ui'
```

Exports: `PageHeader`, `pageHeaderStyles`.

## Notes

- Renders the title as an h1; use one PageHeader per page.

## PageHeader props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  |  |
| `actions` | `ReactNode` |  | Buttons aligned to the end on desktop. |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |

## Example: With actions

```tsx
import { Button, PageHeader } from '@glyphui/ui'
import { ListFilter, Plus } from 'lucide-react'

export default function Example() {
  return (
    <PageHeader
      eyebrow="Engineering"
      title="Issues"
      description="Everything the team is working on this cycle."
      actions={
        <>
          <Button variant="outline" size="sm" leftIcon={<ListFilter />}>
            Filter
          </Button>
          <Button size="sm" leftIcon={<Plus />}>
            New issue
          </Button>
        </>
      }
    />
  )
}
```

Live page: https://glyphui.xyz/components/page-header

---

# Pagination

> Moves between pages of a long list. Controlled, with buttons or real links.

Status: beta. Category: Navigation.

```ts
import { Pagination } from '@glyphui/ui'
```

Exports: `Pagination`, `paginationRange`, `paginationStyles`.

## Notes

- The number of items stays constant while paging, so the control never jumps in width.
- The current page is marked with aria-current="page"; ellipses are hidden from screen readers.

## Example: Controlled

```tsx
import { Pagination, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [page, setPage] = useState(6)
  return (
    <div className="grid justify-items-start gap-3">
      <Pagination page={page} pageCount={20} onPageChange={setPage} />
      <Text size="small" tone="muted">
        Page {page} of 20
      </Text>
    </div>
  )
}
```

## Example: As links

getHref renders links, so each page has a URL and works without JavaScript.

```tsx
import { Pagination } from '@glyphui/ui'

export default function Example() {
  return (
    <Pagination
      page={3}
      pageCount={8}
      size="sm"
      showEdges={false}
      getHref={(page) => `?page=${page}`}
    />
  )
}
```

## Example: Range helper

paginationRange is exported for custom pagers.

```tsx
import { paginationRange } from '@glyphui/ui'

export default function Example() {
  return (
    <pre className="font-mono text-small text-muted-foreground">
      {[1, 6, 20]
        .map((page) => `page ${page}: ${JSON.stringify(paginationRange(page, 20))}`)
        .join('\n')}
    </pre>
  )
}
```

Live page: https://glyphui.xyz/components/pagination

---

# Password reset

> Request a reset email, then choose a new password from the link’s token or an emailed code.

Status: beta. Category: Auth.

```ts
import { ForgotPasswordForm, ResetPasswordForm } from '@glyphui/auth/ui'
```

Exports: `ForgotPasswordForm`, `ResetPasswordForm`.

## Notes

- The confirmation never says whether an account exists, so emails can’t be probed.
- On your reset page, read the token from the URL: <ResetPasswordForm token={params.get("token")} />.
- For code-based backends (Clerk), ForgotPasswordForm continues straight to a code and new-password form.
- A hidden username field helps password managers update the right saved login.

## ResetPasswordForm props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `description` | `ReactNode` |  |  |
| `email` | `string` |  | For code-based resets: the address the code went to. Shows a code field. |
| `footer` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` |  | Heading level of the title. Default 1, for a page whose main content is the form. |
| `minPasswordLength` | `number` | `8` |  |
| `onSuccess` | `(() => void)` |  | Called after the password changes. |
| `signInHref` | `string` |  | Adds "Back to sign in" and the success screen's button. |
| `title` | `ReactNode` | `Choose a new password` |  |
| `token` | `string` |  | The token from the reset link, usually read from the URL. |

## Example: Forgot, then reset

Request a reset for ada@example.com; the toast shows the link token, which this demo passes straight to the reset form.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { ForgotPasswordForm, ResetPasswordForm } from '@glyphui/auth/ui'
import { Button, toast } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [token, setToken] = useState<string | null>(null)
  const [adapter] = useState(() =>
    memoryAdapter({
      latency: 400,
      users: [{ email: 'ada@example.com', password: 'correct horse' }],
      onCode: ({ kind, code }) => {
        if (kind !== 'reset-password') return
        toast('Reset email sent', { description: 'Opening the link for you…' })
        setToken(code)
      },
    }),
  )
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <div className="grid w-full justify-items-center gap-3">
        {token ? (
          <>
            <ResetPasswordForm headingLevel={3} token={token} />
            <Button variant="ghost" size="sm" onClick={() => setToken(null)}>
              Start over
            </Button>
          </>
        ) : (
          <ForgotPasswordForm headingLevel={3} defaultEmail="ada@example.com" />
        )}
      </div>
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/password-reset

---

# PasswordInput

> A password field with a show/hide toggle and an optional strength meter.

Status: beta. Category: Forms.

```ts
import { PasswordInput } from '@glyphui/ui'
```

Exports: `PasswordInput`, `passwordStrength`, `passwordInputStyles`.

## Notes

- The toggle is a real button with aria-pressed, so screen readers announce whether the password is visible.
- The strength meter is a hint for people. Enforce password rules on the server.

## PasswordInput props

| Prop | Type | Default | Description |
|---|---|---|---|
| `defaultVisible` | `boolean` |  | Start with the password visible. |
| `inputClassName` | `string` |  | Classes for the `<input>` element itself. `className` styles the outer frame. |
| `prefix` | `ReactNode` |  | Content before the text, e.g. an icon or `https://`. |
| `showStrength` | `boolean` |  | Show a strength meter under the field once the user starts typing. |
| `size` | `"sm" \| "md" \| "lg"` |  |  |

## Example: Sign in

```tsx
import { Field, PasswordInput } from '@glyphui/ui'

export default function Example() {
  return (
    <Field label="Password" className="w-72">
      <PasswordInput placeholder="Your password" />
    </Field>
  )
}
```

## Example: New password with strength

passwordStrength() is exported too.

```tsx
import { Field, PasswordInput } from '@glyphui/ui'

export default function Example() {
  return (
    <Field
      label="New password"
      description="At least 12 characters, mixing letters, numbers and symbols."
      className="w-80"
    >
      <PasswordInput autoComplete="new-password" showStrength />
    </Field>
  )
}
```

Live page: https://glyphui.xyz/components/password-input

---

# PdfViewer

> Read PDFs in the page: thumbnails, zoom, rotation, search with highlights, selectable text, download, print and fullscreen.

Status: beta. Category: Viewers.

```ts
import { PdfViewer } from '@glyphui/viewers/pdf'
```

Exports: `PdfViewer`, `pdfViewerStyles`, `setPdfWorker`, `cdnWorkerUrl`.

## Notes

- Install the optional peer dependency first: npm install pdfjs-dist.
- pdf.js parses in a Web Worker. By default it loads from jsDelivr, matching your pdfjs-dist version. To serve it yourself, call setPdfWorker once at startup: with Vite, import workerSrc from "pdfjs-dist/build/pdf.worker.min.mjs?url"; with webpack or Next.js, pass new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).
- Only pages near the view are rendered, so long documents stay fast; the page size you see comes from each page, so mixed sizes and orientations lay out correctly.
- Keyboard: Page Up/Down change pages, + and − zoom, 0 fits the width, R rotates, and ⌘F or Ctrl+F jumps to search.
- Each page is a labelled group with its text layer, so screen readers can read the document.
- pdf.js adds about 130 kB gzipped, plus a 365 kB worker that downloads in the background; both load only when a PdfViewer mounts.

## PdfViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `source` (required) | `ViewerSource` |  | The PDF: a URL, a File/Blob, or bytes. |
| `bordered` | `boolean` |  | Draw the viewer as a bordered card. Default true. |
| `className` | `string` |  |  |
| `defaultPage` | `number` |  | Page to open on, from 1. |
| `defaultZoom` | `PdfZoom` |  | Starting zoom: `fit-width` (default), `fit-page`, or a scale where 1 is actual size. |
| `fileName` | `string` |  | Name for downloads. Defaults to the file or URL name. |
| `height` | `string \| number` |  | Height of the viewer. Default 640. |
| `onLoad` | `((info: { pages: number; }) => void)` |  |  |
| `onPageChange` | `((page: number) => void)` |  |  |
| `thumbnails` | `boolean` |  | Show the thumbnails sidebar at first (wide screens). Default true. |
| `workerSrc` | `PdfWorkerSource` |  | pdf.js worker for this viewer. See `setPdfWorker` to set it once for the app. |

## Example: A report

Search for “revenue”: matches highlight on every page.

```tsx
import { PdfViewer } from '@glyphui/viewers/pdf'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <PdfViewer source={fixture('report.pdf')} height={560} className="w-full" />
}
```

## Example: A file the user picks

Works with File objects from FileUpload, without uploading anything.

```tsx
import { type FileItem, FileUpload } from '@glyphui/ui'
import { PdfViewer } from '@glyphui/viewers/pdf'
import { useState } from 'react'

export default function Example() {
  const [files, setFiles] = useState<FileItem[]>([])
  const file = files[0]?.file
  return (
    <div className="grid w-full gap-4">
      <FileUpload
        accept="application/pdf,.pdf"
        maxFiles={1}
        files={files}
        onFilesChange={setFiles}
        hint="A PDF, up to 50 MB. It stays on your device."
        maxSize={50 * 1024 * 1024}
      />
      {file && <PdfViewer source={file} height={480} />}
    </div>
  )
}
```

## Example: Start page and zoom

Open on page 3, fitting the whole page, without thumbnails.

```tsx
import { PdfViewer } from '@glyphui/viewers/pdf'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return (
    <PdfViewer
      source={fixture('report.pdf')}
      defaultPage={3}
      defaultZoom="fit-page"
      thumbnails={false}
      height={520}
      className="w-full"
    />
  )
}
```

Live page: https://glyphui.xyz/components/pdf-viewer

---

# PieChart

> Parts of a whole as a pie or donut, with slice labels, a highlighted slice on hover and a legend that hides slices.

Status: beta. Category: Data display.

```ts
import { PieChart, DonutChart } from '@glyphui/ui/chart'
```

Exports: `PieChart`, `DonutChart`.

## Notes

- Use five slices or fewer; fold the rest into “Other”. People compare angles poorly, so for exact comparisons use a bar chart.
- Hiding a slice in the legend keeps every slice’s color, so colors keep meaning the same thing.
- DonutChart is PieChart with innerRadius 0.68. The center label only shows on a donut.

## PieChart props

| Prop | Type | Default | Description |
|---|---|---|---|
| `category` (required) | `string` |  | Field naming each slice. |
| `data` (required) | `readonly T[]` |  |  |
| `title` (required) | `string` |  |  |
| `value` (required) | `string` |  | Field holding each slice's value. |
| `centerLabel` | `ReactNode` |  | Content in the middle of a donut, e.g. the total. |
| `className` | `string` |  |  |
| `colors` | `readonly ChartColorValue[]` |  | One color per slice, in order. Defaults follow the theme palette. |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `hiddenSlices` | `readonly string[]` |  | Slices hidden through the legend (controlled), by category name. |
| `hideTitle` | `boolean` |  |  |
| `innerRadius` | `number` |  | Hole size as a share of the radius, from 0 (pie) to 0.9. Default 0 for PieChart. |
| `labels` | `"none" \| "value" \| "name" \| "percent"` |  | Text drawn next to each slice. Default `none`. |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `onHiddenSlicesChange` | `((hidden: string[]) => void)` |  |  |
| `onRetry` | `(() => unknown)` |  |  |
| `onSliceClick` | `((row: T) => void)` |  |  |
| `showLegend` | `boolean` |  |  |
| `size` | `number` |  | Diameter in pixels. Default 200. |
| `valueFormatter` | `((value: number) => string)` |  |  |

## Example: Donut

A headline number in the middle.

```tsx
import { DonutChart } from '@glyphui/ui/chart'

const plans = [
  { plan: 'Free', seats: 1840 },
  { plan: 'Pro', seats: 960 },
  { plan: 'Team', seats: 410 },
  { plan: 'Enterprise', seats: 230 },
]

export default function Example() {
  return (
    <DonutChart
      title="Seats by plan"
      data={plans}
      category="plan"
      value="seats"
      size={200}
      centerLabel={
        <>
          <span className="font-display text-h3 tabular-nums">3,440</span>
          <span className="text-caption text-muted-foreground">seats</span>
        </>
      }
    />
  )
}
```

## Example: Pie with labels

labels="percent" shows each share.

```tsx
import { PieChart } from '@glyphui/ui/chart'

const sources = [
  { source: 'Organic search', visits: 48200 },
  { source: 'Direct', visits: 21900 },
  { source: 'Referral', visits: 12400 },
  { source: 'Paid', visits: 9100 },
]

export default function Example() {
  return (
    <PieChart
      title="Traffic by source"
      description="Last 30 days"
      data={sources}
      category="source"
      value="visits"
      labels="percent"
      size={220}
    />
  )
}
```

Live page: https://glyphui.xyz/components/pie-chart

---

# Popover

> Floating content anchored to a trigger, for quick settings, details or a small form.

Status: beta. Category: Overlays.

```ts
import { Popover, PopoverTrigger, PopoverAnchor, PopoverContent, PopoverClose } from '@glyphui/ui'
```

Exports: `Popover`, `PopoverTrigger`, `PopoverAnchor`, `PopoverContent`, `PopoverClose`, `popoverStyles`.

## Notes

- Opens on click, closes on Escape or an outside click, and returns focus to the trigger.
- For a hint on hover, use Tooltip. For a list of actions, use DropdownMenu.

## Example: Share link

```tsx
import { Button, Input, Popover, PopoverContent, PopoverTrigger, Text } from '@glyphui/ui'
import { Link2 } from 'lucide-react'

export default function Example() {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="outline" leftIcon={<Link2 />}>
          Share
        </Button>
      </PopoverTrigger>
      <PopoverContent align="start" className="grid w-80 gap-3">
        <div className="grid gap-1">
          <p className="font-medium">Share this view</p>
          <Text size="small" tone="muted">
            Anyone in the workspace with the link can see it.
          </Text>
        </div>
        <div className="flex gap-2">
          <Input readOnly defaultValue="glyph.app/acme/views/q3" aria-label="Link" />
          <Button size="md">Copy</Button>
        </div>
      </PopoverContent>
    </Popover>
  )
}
```

## Example: With arrow

showArrow points the panel at its trigger.

```tsx
import { Button, Popover, PopoverContent, PopoverTrigger, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="secondary">What’s new?</Button>
      </PopoverTrigger>
      <PopoverContent showArrow side="top">
        <Text size="small">Glyph 0.2 adds overlays, toasts and a confirm hook.</Text>
      </PopoverContent>
    </Popover>
  )
}
```

Live page: https://glyphui.xyz/components/popover

---

# Pricing

> Plan comparison with features, call-to-action buttons and an optional monthly / yearly switch.

Status: beta. Category: Blocks.

```ts
import { Pricing } from '@glyphui/blocks'
```

Exports: `Pricing`.

## Notes

- Numeric prices go through formatPrice; strings such as “Custom” are shown as they are.
- A tier with cta.href renders a link through your router’s link component.

## Pricing props

| Prop | Type | Default | Description |
|---|---|---|---|
| `tiers` (required) | `readonly PricingTier[]` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `billingLabels` | `Record<Billing, ReactNode>` | `{ monthly: 'Monthly', yearly: 'Yearly' }` | Labels for the billing switch. |
| `defaultBilling` | `Billing` | `monthly` |  |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `formatPrice` | `((amount: number) => string)` |  | Turns numeric prices into text. Default: US dollars, with cents only when there are some. |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `periodLabels` | `Record<Billing, ReactNode>` | `{   monthly: 'per month',   yearly: 'per month, billed yearly', }` | Shown after each numeric price above zero, per billing period. |
| `title` | `ReactNode` |  |  |

## Example: Three tiers

The billing switch appears when any tier has per-period prices.

```tsx
import { Pricing } from '@glyphui/blocks'

export default function Example() {
  return (
    <Pricing
      eyebrow="Pricing"
      title="Simple plans that grow with you"
      description="Start free. Upgrade when you send more than 50 invoices a month."
      defaultBilling="yearly"
      billingLabels={{ monthly: 'Monthly', yearly: 'Yearly · save 20%' }}
      tiers={[
        {
          name: 'Starter',
          description: 'For freelancers and side projects.',
          price: 0,
          features: ['50 invoices a month', 'Card and bank payments', 'Email support'],
          cta: { label: 'Start free', href: '#signup' },
        },
        {
          name: 'Growth',
          description: 'For teams billing on usage.',
          price: { monthly: 49, yearly: 39 },
          features: [
            'Unlimited invoices',
            'Usage-based pricing',
            'Dunning and retries',
            'Revenue reports',
          ],
          cta: { label: 'Start 14-day trial', href: '#trial' },
          highlighted: true,
          badge: 'Most popular',
        },
        {
          name: 'Enterprise',
          description: 'For finance teams with custom needs.',
          price: 'Custom',
          features: ['SSO and SCIM', 'Custom contracts', 'Dedicated support engineer'],
          cta: { label: 'Talk to sales', href: '#sales' },
        },
      ]}
    />
  )
}
```

## Example: Two tiers, custom format

```tsx
import { Pricing } from '@glyphui/blocks'

const euros = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
  maximumFractionDigits: 0,
})

export default function Example() {
  return (
    <Pricing
      formatPrice={(amount) => euros.format(amount)}
      periodLabels={{ monthly: 'pro Monat', yearly: 'pro Monat, jährlich' }}
      billingLabels={{ monthly: 'Monatlich', yearly: 'Jährlich' }}
      tiers={[
        {
          name: 'Team',
          price: { monthly: 12, yearly: 10 },
          features: ['Bis zu 10 Personen', 'Unbegrenzte Projekte'],
          cta: { label: 'Testen', onClick: () => {} },
        },
        {
          name: 'Business',
          price: { monthly: 24, yearly: 20 },
          features: ['Unbegrenzte Personen', 'SSO', 'Prioritäts-Support'],
          cta: { label: 'Testen', onClick: () => {} },
          highlighted: true,
        },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/pricing

---

# Progress

> A bar or ring showing how far a task has got, or an indeterminate bar while the length is unknown.

Status: beta. Category: Feedback.

```ts
import { Progress, ProgressCircle } from '@glyphui/ui'
```

Exports: `Progress`, `ProgressCircle`, `progressStyles`, `progressCircleStyles`.

## Notes

- The visible label becomes the accessible name. Without one, pass aria-label.
- aria-valuetext uses formatValue, so screen readers hear "3 of 5 files" if that is what you show.

## Example: Bar with label

```tsx
import { Button, Progress } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [value, setValue] = useState(3)
  return (
    <div className="grid max-w-md gap-4">
      <Progress
        label="Uploading files"
        value={value}
        max={5}
        showValue
        formatValue={(v, max) => `${v} of ${max}`}
      />
      <Button
        size="sm"
        variant="outline"
        className="w-fit"
        onClick={() => setValue((v) => (v >= 5 ? 0 : v + 1))}
      >
        Advance
      </Button>
    </div>
  )
}
```

## Example: Sizes and tones

```tsx
import { Progress } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-md gap-4">
      <Progress aria-label="Storage" value={32} size="sm" />
      <Progress aria-label="Seats" value={64} tone="success" />
      <Progress aria-label="API quota" value={86} tone="warning" size="lg" />
      <Progress aria-label="Disk" value={97} tone="danger" />
    </div>
  )
}
```

## Example: Ring

ProgressCircle for compact spaces such as table cells and cards.

```tsx
import { ProgressCircle } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-6">
      <ProgressCircle aria-label="Profile complete" value={40} size="sm" />
      <ProgressCircle aria-label="Onboarding" value={68} showValue />
      <ProgressCircle aria-label="Storage used" value={92} tone="warning" size="lg" showValue />
    </div>
  )
}
```

## Example: Indeterminate

Omit value while the total is unknown.

```tsx
import { Progress } from '@glyphui/ui'

export default function Example() {
  return <Progress label="Preparing export" className="max-w-md" />
}
```

Live page: https://glyphui.xyz/components/progress

---

# Prose

> Styles raw HTML or MDX for long-form reading: headings, lists, links, quotes, code, tables and images.

Status: beta. Category: Typography.

```ts
import { Prose } from '@glyphui/ui'
```

Exports: `Prose`, `proseStyles`.

## Notes

- Wrap rendered Markdown, MDX or CMS HTML. Every style comes from theme tokens.
- Width defaults to about 65 characters for comfortable reading; pass fullWidth to remove the limit.

## Example: Article

Switch to the editorial theme to see it at its best.

```tsx
import { Prose } from '@glyphui/ui'

export default function Example() {
  return (
    <Prose asChild>
      <article>
        <h2>Why one theme file</h2>
        <p>
          Most design systems scatter decisions across config files, CSS variables and component
          props. Glyph keeps them in <code>glyph.theme.ts</code>, so a rebrand is{' '}
          <strong>one diff</strong>, not a migration.
        </p>
        <h3>What a theme controls</h3>
        <ul>
          <li>Color for light and dark mode</li>
          <li>A nine-step type scale with tracking and weight</li>
          <li>Radius, shadows, motion and control density</li>
        </ul>
        <blockquote>Good design is as little design as possible.</blockquote>
        <pre>
          <code>{"export default defineTheme({ name: 'acme', extends: presets.editorial })"}</code>
        </pre>
        <table>
          <thead>
            <tr>
              <th>Preset</th>
              <th>Character</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>glyph</td>
              <td>Precise, dark-first</td>
            </tr>
            <tr>
              <td>editorial</td>
              <td>Serif, warm paper</td>
            </tr>
          </tbody>
        </table>
        <p>
          Read the <a href="https://github.com/khalmohak/glyph">source on GitHub</a>.
        </p>
      </article>
    </Prose>
  )
}
```

Live page: https://glyphui.xyz/components/prose

---

# Protected routes

> Guards and loaders for React Router: signed-out users go to sign-in and come back to where they were going.

Status: beta. Category: Auth.

```ts
import { RequireAuth, GuestOnly, RequireRole, AuthRevalidator, NEXT_PARAM } from '@glyphui/auth/react-router'
```

Exports: `RequireAuth`, `GuestOnly`, `RequireRole`, `protectedLoader`, `guestLoader`, `useRedirectAfterSignIn`, `AuthRevalidator`, `useAuthRevalidation`, `NEXT_PARAM`, `safeRedirectPath`, `signInPathFor`.

## Notes

- The current path and query go into ?next=, and after sign-in useRedirectAfterSignIn (or GuestOnly) returns there.
- Only same-origin paths are followed: https://evil.com, //evil.com and javascript: in ?next= fall back to your default.
- RequireRole takes roles (any of several) and/or permission; give it a fallback or get a "no access" message.
- Guards render a spinner while the session loads; pass loading to change it.
- With loaders, render <AuthRevalidator /> once in your root route (or call useAuthRevalidation()): it re-runs loaders on sign-in and sign-out, so protectedLoader pages redirect after an idle or cross-tab sign-out.
- Requires react-router 7 or later.

## RequireAuth props

| Prop | Type | Default | Description |
|---|---|---|---|
| `children` | `ReactNode` |  | The protected content. Default `<Outlet />`, so it works as a layout route. |
| `loading` | `ReactNode` | `<LoadingState label="Checking your session…" className="min-h-48" />` | Shown while the session loads. |
| `redirectTo` | `string` | `/sign-in` | Where signed-out users go. The current path is added as `?next=`. Default `/sign-in`. |

## Example: Role-gated content

RequireRole shows its fallback to users without the role. Switch users to see both.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { RequireRole } from '@glyphui/auth/react-router'
import { Card, SegmentedControl, Text } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 0,
  users: [
    { email: 'admin@acme.dev', password: 'pw', name: 'Admin', roles: ['admin'] },
    { email: 'member@acme.dev', password: 'pw', name: 'Member', roles: ['member'] },
  ],
})

function AdminArea() {
  const { user, signIn } = useAuth()
  return (
    <div className="grid w-full max-w-md gap-4">
      <SegmentedControl
        aria-label="Signed in as"
        value={user?.email ?? ''}
        onValueChange={(email) => signIn({ email, password: 'pw' })}
        options={[
          { value: 'admin@acme.dev', label: 'Admin' },
          { value: 'member@acme.dev', label: 'Member' },
        ]}
      />
      {user && (
        <RequireRole roles="admin">
          <Card>
            <Text weight="medium">Audit log</Text>
            <Text size="small" tone="muted">
              Only admins see this card.
            </Text>
          </Card>
        </RequireRole>
      )}
    </div>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <AdminArea />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/protected-routes

---

# RadarChart

> Compare a few items across several measures on a radar, or show progress toward goals as radial bars.

Status: beta. Category: Data display.

```ts
import { RadarChart, RadialBarChart } from '@glyphui/ui/chart'
```

Exports: `RadarChart`, `RadialBarChart`.

## Notes

- Keep radars to two or three series and five to eight spokes; more becomes unreadable.
- RadialBarChart rings run to max, or to the largest value when max is not set.

## RadarChart props

| Prop | Type | Default | Description |
|---|---|---|---|
| `data` (required) | `readonly T[]` |  |  |
| `index` (required) | `string` |  | Field naming each spoke, e.g. `"skill"`. |
| `series` (required) | `readonly ChartSeries<T>[]` |  |  |
| `title` (required) | `string` |  |  |
| `className` | `string` |  |  |
| `defaultHiddenSeries` | `readonly Extract<keyof T, string>[]` |  |  |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `height` | `number` |  | Plot height in pixels. Default 280. |
| `hiddenSeries` | `readonly Extract<keyof T, string>[]` |  |  |
| `hideTitle` | `boolean` |  |  |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `max` | `number` |  | Upper bound of the radial axis. Defaults to the largest value. |
| `onHiddenSeriesChange` | `((hidden: Extract<keyof T, string>[]) => void)` |  |  |
| `onRetry` | `(() => unknown)` |  |  |
| `showLegend` | `boolean` |  |  |
| `valueFormatter` | `((value: number) => string)` |  |  |

## Example: Radar

Two plans scored on five measures.

```tsx
import { RadarChart } from '@glyphui/ui/chart'

const scores = [
  { measure: 'Speed', glyph: 9, legacy: 6 },
  { measure: 'Accessibility', glyph: 9, legacy: 5 },
  { measure: 'Theming', glyph: 10, legacy: 4 },
  { measure: 'Bundle size', glyph: 7, legacy: 6 },
  { measure: 'Docs', glyph: 8, legacy: 7 },
]

export default function Example() {
  return (
    <RadarChart
      className="w-full max-w-md"
      title="Library comparison"
      description="Scored out of 10"
      data={scores}
      index="measure"
      max={10}
      series={[
        { key: 'glyph', label: 'Glyph' },
        { key: 'legacy', label: 'Legacy kit' },
      ]}
    />
  )
}
```

## Example: Radial bars

Quarterly goals as rings.

```tsx
import { RadialBarChart } from '@glyphui/ui/chart'

const goals = [
  { goal: 'New MRR', progress: 82 },
  { goal: 'Activation', progress: 64 },
  { goal: 'NPS responses', progress: 47 },
]

export default function Example() {
  return (
    <RadialBarChart
      title="Q4 goals"
      data={goals}
      category="goal"
      value="progress"
      max={100}
      valueFormatter={(v) => `${v}%`}
      centerLabel={
        <>
          <span className="font-display text-h4 tabular-nums">64%</span>
          <span className="text-caption text-muted-foreground">average</span>
        </>
      }
    />
  )
}
```

Live page: https://glyphui.xyz/components/radar-chart

---

# RadioGroup

> Pick exactly one option from a short visible list. The card variant makes each option a selectable card.

Status: beta. Category: Forms.

```ts
import { RadioGroup, RadioGroupItem } from '@glyphui/ui'
```

Exports: `RadioGroup`, `RadioGroupItem`, `radioGroupStyles`.

## Notes

- Arrow keys move between options; the value type is inferred, so onValueChange receives your union type.
- Wrap in Field to get a label, description and error wired to the group.

## Example: Basic

```tsx
import { Field, RadioGroup, RadioGroupItem } from '@glyphui/ui'

export default function Example() {
  return (
    <Field label="Notify me about">
      <RadioGroup defaultValue="mentions">
        <RadioGroupItem value="all" label="All activity" />
        <RadioGroupItem
          value="mentions"
          label="Mentions only"
          description="When someone @mentions you."
        />
        <RadioGroupItem value="none" label="Nothing" />
      </RadioGroup>
    </Field>
  )
}
```

## Example: Option cards

variant="card" for plans, shipping methods and other rich choices.

```tsx
import { RadioGroup, RadioGroupItem } from '@glyphui/ui'
import { useState } from 'react'

type Plan = 'free' | 'pro' | 'team'

export default function Example() {
  const [plan, setPlan] = useState<Plan>('pro')
  return (
    <RadioGroup<Plan>
      aria-label="Plan"
      variant="card"
      orientation="horizontal"
      value={plan}
      onValueChange={setPlan}
    >
      <RadioGroupItem value="free" label="Free" description="3 projects, community support" />
      <RadioGroupItem
        value="pro"
        label="Pro · $16"
        description="Unlimited projects, priority support"
      />
      <RadioGroupItem value="team" label="Team · $28" description="SSO, audit log, shared themes" />
    </RadioGroup>
  )
}
```

Live page: https://glyphui.xyz/components/radio-group

---

# Resizable

> Panels separated by draggable dividers, for editors, inboxes and split views.

Status: beta. Category: Layout.

```ts
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@glyphui/ui'
```

Exports: `ResizablePanelGroup`, `ResizablePanel`, `ResizableHandle`, `resizableStyles`.

## Notes

- Built on react-resizable-panels. Sizes are percentages; set defaultSize, minSize and maxSize on each panel.
- Handles are focusable separators: use the arrow keys to resize, Home and End to collapse or expand.
- Pass autoSaveId to the group to remember sizes across visits.

## ResizableHandle props

| Prop | Type | Default | Description |
|---|---|---|---|
| `disabled` | `boolean` |  |  |
| `hitAreaMargins` | `PointerHitAreaMargins` |  |  |
| `id` | `string \| null` |  |  |
| `onBlur` | `(() => void)` |  |  |
| `onClick` | `(() => void)` |  |  |
| `onDragging` | `PanelResizeHandleOnDragging` |  |  |
| `onFocus` | `(() => void)` |  |  |
| `onPointerDown` | `(() => void)` |  |  |
| `onPointerUp` | `(() => void)` |  |  |
| `tagName` | `keyof HTMLElementTagNameMap` |  |  |
| `withHandle` | `boolean` |  | Show a visible grip on the divider. |

## Example: Sidebar and content

```tsx
import { ResizableHandle, ResizablePanel, ResizablePanelGroup, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <ResizablePanelGroup
      direction="horizontal"
      className="min-h-56 max-w-xl rounded-lg border border-border"
    >
      <ResizablePanel defaultSize={30} minSize={20} className="bg-subtle p-4">
        <Text size="small" weight="medium">
          Inbox
        </Text>
        <Text size="caption" tone="muted">
          24 conversations
        </Text>
      </ResizablePanel>
      <ResizableHandle withHandle />
      <ResizablePanel defaultSize={70} minSize={40} className="p-4">
        <Text size="small" weight="medium">
          Re: Q4 roadmap
        </Text>
        <Text size="small" tone="muted">
          Drag the divider or focus it and use the arrow keys.
        </Text>
      </ResizablePanel>
    </ResizablePanelGroup>
  )
}
```

## Example: Nested groups

A vertical group inside a horizontal one, like an editor with a terminal.

```tsx
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from '@glyphui/ui'

export default function Example() {
  return (
    <ResizablePanelGroup
      direction="horizontal"
      className="min-h-64 max-w-xl rounded-lg border border-border font-mono text-caption"
    >
      <ResizablePanel defaultSize={25} className="bg-subtle p-3 text-muted-foreground">
        explorer
      </ResizablePanel>
      <ResizableHandle />
      <ResizablePanel defaultSize={75}>
        <ResizablePanelGroup direction="vertical">
          <ResizablePanel defaultSize={70} className="p-3">
            editor.tsx
          </ResizablePanel>
          <ResizableHandle withHandle />
          <ResizablePanel defaultSize={30} className="bg-subtle p-3 text-muted-foreground">
            $ pnpm dev
          </ResizablePanel>
        </ResizablePanelGroup>
      </ResizablePanel>
    </ResizablePanelGroup>
  )
}
```

Live page: https://glyphui.xyz/components/resizable

---

# REST adapter

> Connect Glyph auth to your own API: httpOnly cookie sessions or bearer tokens with refresh rotation.

Status: beta. Category: Auth.

```ts
import { REST adapter } from '@glyphui/auth/rest'
```

Exports: `restAdapter`, `defaultEndpoints`.

## Notes

- Endpoints default to /auth/session, /auth/sign-in, /auth/sign-up, /auth/sign-out, /auth/refresh, /auth/password/forgot, /auth/password/reset and /auth/verify; override any with endpoints.
- When signed out, GET session should return 200 with { user: null }. A 401 also works, but browsers log it as an error on every signed-out page view. A 401 while holding a refresh token tries one refresh first.
- Return 202 with { status: "needs-verification" } or "needs-second-factor" and the screens show the next step. Add a challenge to tie the code to its sign-in, and method ("email", "sms", "totp") to word the code step.
- Sign-in links need capabilities.magicLink and POST /auth/magic-link/verify; render MagicLinkCallback on the page the link opens.
- Error bodies with { errors: { email: "…" } } show next to the matching form fields.
- storage: "memory" keeps bearer tokens out of web storage, at the cost of signing in again after a reload.
- Set capabilities to match what your server implements, e.g. { oauthProviders: ["google"], organizations: true }.

Live page: https://glyphui.xyz/components/auth-rest

---

# Router integration

> Connect Glyph to your router once: links navigate client-side and navigation items mark the current page automatically.

Status: beta. Category: Patterns.

```ts
import { RouterLink } from '@glyphui/ui/react-router'
```

Exports: `reactRouter`, `RouterLink`, `useRouterIsActive`, `matchPath`, `useRouterUrlAdapter`.

## Notes

- Pass it once: <GlyphProvider router={reactRouter}>. Sidebar, Navbar and NavigationMenu items then set aria-current="page" from the URL.
- Matching works like React Router’s NavLink: an item is active on its path and every path below it. Pass end on index items such as /app.
- An explicit active prop always wins, so you can still mark items yourself.
- Hash links, external URLs and mailto: render as plain anchors and are never marked active.
- Other routers: pass { Link, useIsActive } yourself. The getting-started guide has TanStack Router and Next.js versions.
- Requires react-router 7 or later as a peer dependency.
- useRouterUrlAdapter() connects DataTable’s useTableUrlState to React Router: useTableUrlState({ adapter: useRouterUrlAdapter() }), so the router’s location and useSearchParams always match the table.

## Example: Automatic active items

These items use the docs’ own router: the current page is marked without an active prop.

```tsx
import { AppShell, Sidebar, SidebarContent, SidebarItem, SidebarSection, Text } from '@glyphui/ui'
import { BookOpen, LayoutGrid, PanelLeft, Route } from 'lucide-react'

export default function Example() {
  return (
    <div className="h-72 overflow-hidden rounded-lg border border-border">
      <AppShell
        layout="embedded"
        sidebar={
          <Sidebar>
            <SidebarContent>
              <SidebarSection label="Docs">
                <SidebarItem href="/components" end icon={<LayoutGrid />}>
                  All components
                </SidebarItem>
                <SidebarItem href="/components/router" icon={<Route />}>
                  Router integration
                </SidebarItem>
                <SidebarItem href="/components/sidebar" icon={<PanelLeft />}>
                  Sidebar
                </SidebarItem>
                <SidebarItem href="/getting-started" icon={<BookOpen />}>
                  Getting started
                </SidebarItem>
              </SidebarSection>
            </SidebarContent>
          </Sidebar>
        }
      >
        <div className="p-5">
          <Text tone="muted">
            No item sets active. “Router integration” is highlighted because it matches this page.
          </Text>
        </div>
      </AppShell>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/router

---

# SankeyChart

> Where a quantity flows between stages, e.g. traffic sources to pages to signups. Links are given by node name.

Status: beta. Category: Data display.

```ts
import { SankeyChart } from '@glyphui/ui/chart'
```

Exports: `SankeyChart`.

## Notes

- Nodes are created from the names in links; pass nodes to fix their order or colors.
- Each link takes its source’s color. Hover a link or node to see its value.

## SankeyChart props

| Prop | Type | Default | Description |
|---|---|---|---|
| `links` (required) | `readonly SankeyLink[]` |  |  |
| `title` (required) | `string` |  |  |
| `className` | `string` |  |  |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `height` | `number` |  | Plot height in pixels. Default 300. |
| `hideTitle` | `boolean` |  |  |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `nodes` | `readonly (string \| SankeyNode)[]` |  | Node order and colors. Defaults to every name in `links`, in order of appearance. |
| `onRetry` | `(() => unknown)` |  |  |
| `valueFormatter` | `((value: number) => string)` |  |  |

## Example: Traffic to signups

```tsx
import { SankeyChart } from '@glyphui/ui/chart'

const links = [
  { source: 'Search', target: 'Pricing', value: 4200 },
  { source: 'Search', target: 'Docs', value: 2600 },
  { source: 'Social', target: 'Pricing', value: 1300 },
  { source: 'Social', target: 'Blog', value: 2100 },
  { source: 'Referral', target: 'Pricing', value: 900 },
  { source: 'Docs', target: 'Signup', value: 700 },
  { source: 'Blog', target: 'Signup', value: 300 },
  { source: 'Pricing', target: 'Signup', value: 2400 },
]

export default function Example() {
  return (
    <SankeyChart
      className="w-full"
      title="How visitors reach signup"
      description="Sessions, last 7 days"
      links={links}
      height={300}
    />
  )
}
```

Live page: https://glyphui.xyz/components/sankey-chart

---

# ScatterChart

> How two measures relate, one dot per item. Add size for a bubble chart and groupBy for colored groups.

Status: beta. Category: Data display.

```ts
import { ScatterChart } from '@glyphui/ui/chart'
```

Exports: `ScatterChart`.

## Notes

- Always name both axes with xAxis.label and yAxis.label: a scatter has no other labels.
- Click a legend entry to hide a group. Set name to show each point’s name in the tooltip.

## ScatterChart props

| Prop | Type | Default | Description |
|---|---|---|---|
| `data` (required) | `readonly T[]` |  |  |
| `title` (required) | `string` |  |  |
| `x` (required) | `string` |  | Field for the horizontal position. |
| `y` (required) | `string` |  | Field for the vertical position. |
| `className` | `string` |  |  |
| `colors` | `readonly ChartColorValue[]` |  | One color per group, in order. |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `groupBy` | `string` |  | Field that splits points into colored groups with a legend. |
| `height` | `number` |  | Plot height in pixels. Default 280. |
| `hiddenGroups` | `readonly string[]` |  |  |
| `hideTitle` | `boolean` |  |  |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `name` | `string` |  | Field naming each point, shown in the tooltip. |
| `onHiddenGroupsChange` | `((hidden: string[]) => void)` |  |  |
| `onPointClick` | `((row: T) => void)` |  |  |
| `onRetry` | `(() => unknown)` |  |  |
| `referenceAreas` | `readonly ChartReferenceArea[]` |  |  |
| `referenceLines` | `readonly ChartReferenceLine[]` |  |  |
| `showGrid` | `boolean` |  |  |
| `showLegend` | `boolean` |  |  |
| `size` | `string` |  | Field for the point size. Turns the scatter into a bubble chart. |
| `sizeFormatter` | `((value: number) => string)` |  | Formats `size` in the tooltip. |
| `sizeRange` | `readonly [number, number]` |  | Smallest and largest bubble area in pixels. Default `[40, 600]`. |
| `xAxis` | `ChartAxisOptions` |  | Axis titles and tick formatters. Name the axes: a scatter has no other labels. |
| `yAxis` | `ChartAxisOptions` |  |  |

## Example: Bubble chart

Accounts by seats and MRR, sized by open tickets and grouped by segment.

```tsx
import { ScatterChart } from '@glyphui/ui/chart'

const accounts = [
  { name: 'Northwind', seats: 42, mrr: 1240, tickets: 3, segment: 'SMB' },
  { name: 'Initech', seats: 18, mrr: 420, tickets: 1, segment: 'SMB' },
  { name: 'Vandelay', seats: 35, mrr: 910, tickets: 6, segment: 'SMB' },
  { name: 'Umbrella', seats: 96, mrr: 2380, tickets: 4, segment: 'Mid-market' },
  { name: 'Contoso', seats: 140, mrr: 3900, tickets: 9, segment: 'Mid-market' },
  { name: 'Soylent', seats: 120, mrr: 2600, tickets: 2, segment: 'Mid-market' },
  { name: 'Globex', seats: 260, mrr: 8200, tickets: 12, segment: 'Enterprise' },
  { name: 'Hooli', seats: 340, mrr: 12900, tickets: 7, segment: 'Enterprise' },
  { name: 'Wayne', seats: 410, mrr: 11200, tickets: 15, segment: 'Enterprise' },
]

export default function Example() {
  return (
    <ScatterChart
      className="w-full"
      title="Accounts by size and revenue"
      description="Bubble size is open support tickets"
      data={accounts}
      x="seats"
      y="mrr"
      size="tickets"
      name="name"
      groupBy="segment"
      xAxis={{ label: 'Seats' }}
      yAxis={{ label: 'MRR', formatter: (v: number) => `$${(v / 1000).toFixed(0)}k` }}
    />
  )
}
```

Live page: https://glyphui.xyz/components/scatter-chart

---

# ScrollArea

> A scrollable region with slim scrollbars colored by the theme, consistent across browsers.

Status: beta. Category: Layout.

```ts
import { ScrollArea } from '@glyphui/ui'
```

Exports: `ScrollArea`, `scrollAreaStyles`.

## Notes

- Give the root a height (or width for horizontal) with className, e.g. h-72.

## Example: Vertical list

```tsx
import { ScrollArea, Separator } from '@glyphui/ui'

const releases = Array.from({ length: 40 }, (_, i) => `v0.${40 - i}.0`)

export default function Example() {
  return (
    <ScrollArea className="h-64 w-56 rounded-md border border-border">
      <div className="p-4">
        <p className="mb-3 text-small font-medium">Releases</p>
        {releases.map((tag) => (
          <div key={tag}>
            <p className="py-1.5 font-mono text-small text-muted-foreground">{tag}</p>
            <Separator />
          </div>
        ))}
      </div>
    </ScrollArea>
  )
}
```

## Example: Horizontal

```tsx
import { ScrollArea } from '@glyphui/ui'

const swatches = [
  'Glyph',
  'Brutalist',
  'Editorial',
  'Playful',
  'Acme',
  'Nord',
  'Sand',
  'Forest',
  'Ink',
]

export default function Example() {
  return (
    <ScrollArea
      orientation="horizontal"
      className="w-full max-w-lg rounded-md border border-border"
    >
      <div className="flex w-max gap-3 p-4">
        {swatches.map((name) => (
          <div
            key={name}
            className="flex h-24 w-36 shrink-0 items-end rounded-md bg-muted p-3 text-small font-medium"
          >
            {name}
          </div>
        ))}
      </div>
    </ScrollArea>
  )
}
```

Live page: https://glyphui.xyz/components/scroll-area

---

# Section

> A full-width page band with consistent vertical rhythm. Put a Container inside.

Status: stable. Category: Layout.

```ts
import { Section } from '@glyphui/ui'
```

Exports: `Section`, `sectionStyles`.

## Section props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `divided` | `boolean` |  |  |
| `spacing` | `"none" \| "sm" \| "md" \| "lg"` |  |  |
| `tone` | `"default" \| "subtle"` |  |  |

## Example: Page bands

```tsx
import { Container, Heading, Section, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="overflow-hidden rounded-lg border border-border">
      <Section spacing="sm">
        <Container size="md">
          <Heading level={3}>Default band</Heading>
          <Text tone="muted">spacing="sm" for compact pages.</Text>
        </Container>
      </Section>
      <Section spacing="sm" tone="subtle" divided>
        <Container size="md">
          <Heading level={3}>Subtle, divided band</Heading>
          <Text tone="muted">Alternate tones to separate page sections.</Text>
        </Container>
      </Section>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/section

---

# SectionHeader

> Eyebrow, title and description at the top of a section. Most blocks use it; use it for your own sections too.

Status: beta. Category: Blocks.

```ts
import { SectionHeader } from '@glyphui/blocks'
```

Exports: `SectionHeader`.

## SectionHeader props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  |  |
| `align` | `"center" \| "left"` | `left` |  |
| `animate` | `boolean` | `true` | Cascade the eyebrow, title and description in. Default true. |
| `className` | `string` |  |  |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` | Document outline level of the title. Default 2. |
| `titleId` | `string` |  | Id for the title, so the section can reference it with aria-labelledby. |

## Example: Left and centered

```tsx
import { SectionHeader } from '@glyphui/blocks'

export default function Example() {
  return (
    <div className="grid w-full gap-12">
      <SectionHeader
        eyebrow="Integrations"
        title="Works with the tools you already use"
        description="Accounting, CRM and data warehouse connectors, maintained by us."
      />
      <SectionHeader align="center" eyebrow="Security" title="Built for audits" headingLevel={3} />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/section-header

---

# SegmentedControl

> Pick exactly one of a few options. The value type is inferred from the options.

Status: stable. Category: Forms.

```ts
import { SegmentedControl } from '@glyphui/ui'
```

Exports: `SegmentedControl`, `segmentedControlStyles`.

## Notes

- Never deselects: clicking the active option keeps it selected.

## SegmentedControl props

| Prop | Type | Default | Description |
|---|---|---|---|
| `options` (required) | `readonly SegmentedOption<T>[]` |  |  |
| `aria-label` | `string` |  | Required unless the control sits in a `<Field label>`, which labels it. |
| `aria-labelledby` | `string` |  |  |
| `className` | `string` |  |  |
| `defaultValue` | `string` |  |  |
| `fullWidth` | `boolean` |  |  |
| `id` | `string` |  |  |
| `onValueChange` | `((value: T) => void)` |  |  |
| `size` | `"sm" \| "md"` |  |  |
| `value` | `string` |  |  |

## Example: Basic

```tsx
import { SegmentedControl } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [view, setView] = useState<'list' | 'board' | 'timeline'>('board')
  return (
    <SegmentedControl
      aria-label="View"
      value={view}
      onValueChange={setView}
      options={[
        { value: 'list', label: 'List' },
        { value: 'board', label: 'Board' },
        { value: 'timeline', label: 'Timeline' },
      ]}
    />
  )
}
```

## Example: Full width

```tsx
import { SegmentedControl } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="max-w-sm">
      <SegmentedControl
        aria-label="Billing period"
        fullWidth
        defaultValue="yearly"
        options={[
          { value: 'monthly', label: 'Monthly' },
          { value: 'yearly', label: 'Yearly · save 20%' },
        ]}
      />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/segmented-control

---

# Select

> A dropdown for choosing one option from a short list. The value type is generic.

Status: stable. Category: Forms.

```ts
import { Select, SelectItem } from '@glyphui/ui'
```

Exports: `Select`, `SelectItem`, `selectStyles`.

## Notes

- For long lists or search, use Combobox.

## Select props

| Prop | Type | Default | Description |
|---|---|---|---|
| `aria-describedby` | `string` |  |  |
| `aria-invalid` | `boolean` |  |  |
| `aria-label` | `string` |  |  |
| `className` | `string` |  |  |
| `contentClassName` | `string` |  |  |
| `defaultValue` | `string` |  |  |
| `id` | `string` |  |  |
| `onValueChange` | `((value: T) => void)` |  |  |
| `placeholder` | `ReactNode` |  |  |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `value` | `string` |  |  |

## Example: In a field

```tsx
import { Field, Select, SelectItem } from '@glyphui/ui'

export default function Example() {
  return (
    <Field label="Region" className="max-w-xs">
      <Select placeholder="Choose a region" defaultValue="eu">
        <SelectItem value="us">United States</SelectItem>
        <SelectItem value="eu">Europe (Frankfurt)</SelectItem>
        <SelectItem value="ap">Asia Pacific (Tokyo)</SelectItem>
      </Select>
    </Field>
  )
}
```

## Example: Typed values

Select<Plan> only accepts and emits Plan values.

```tsx
import { Select, SelectItem, Text } from '@glyphui/ui'
import { useState } from 'react'

type Plan = 'free' | 'pro' | 'team'

export default function Example() {
  const [plan, setPlan] = useState<Plan>('pro')
  return (
    <div className="grid max-w-xs gap-2">
      <Select<Plan> value={plan} onValueChange={setPlan} aria-label="Plan">
        <SelectItem value="free">Free</SelectItem>
        <SelectItem value="pro">Pro</SelectItem>
        <SelectItem value="team">Team</SelectItem>
      </Select>
      <Text size="small" tone="muted">
        Selected: <span className="font-mono">{plan}</span>
      </Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/select

---

# Separator

> A thin divider between groups of content, horizontal or vertical.

Status: stable. Category: Layout.

```ts
import { Separator } from '@glyphui/ui'
```

Exports: `Separator`, `separatorStyles`.

## Notes

- Decorative by default. Set decorative={false} when the divider separates meaningful sections.

## Separator props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |

## Example: Horizontal and vertical

```tsx
import { Separator, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-sm gap-3">
      <Text weight="medium">Acme Inc.</Text>
      <Separator />
      <div className="flex h-5 items-center gap-3 text-small text-muted-foreground">
        <span>Docs</span>
        <Separator orientation="vertical" />
        <span>Changelog</span>
        <Separator orientation="vertical" />
        <span>Status</span>
      </div>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/separator

---

# Session dialogs

> Sign back in when a session expires mid-task without losing the page, and warn before an idle sign-out.

Status: beta. Category: Auth.

```ts
import { SessionExpiredDialog, IdleWarningDialog } from '@glyphui/auth/ui'
```

Exports: `SessionExpiredDialog`, `IdleWarningDialog`.

## Notes

- Render both once near the root, inside AuthProvider.
- SessionExpiredDialog opens when auth.fetch gets a 401 that a refresh can’t fix, or when you call auth.markExpired().
- It can’t be dismissed by Escape or clicking outside: the user signs in again or signs out.
- IdleWarningDialog needs idleTimeout on the client; activity before the warning resets the timer.

## SessionExpiredDialog props

| Prop | Type | Default | Description |
|---|---|---|---|
| `onSignOut` | `(() => void)` |  | Called after the user chooses to sign out instead of signing back in. |

## Example: Expired session

Revoke the session “on the server”, then call the API: the dialog asks for the password (pw).

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SessionExpiredDialog } from '@glyphui/auth/ui'
import { Button, Text, toast } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 300,
  users: [{ email: 'ada@example.com', password: 'pw', name: 'Ada Lovelace' }],
})

function Demo() {
  const { user, signIn, refresh } = useAuth()
  if (!user)
    return (
      <Button onClick={() => signIn({ email: 'ada@example.com', password: 'pw' })}>
        Sign in as Ada
      </Button>
    )
  return (
    <div className="grid justify-items-center gap-3">
      <Text tone="muted">Signed in as {user.name}.</Text>
      <div className="flex flex-wrap gap-2">
        <Button
          variant="outline"
          onClick={() => {
            adapter.expireSession()
            toast('Session revoked on the server')
          }}
        >
          Revoke session
        </Button>
        {/* Any API call through auth.fetch would do the same; refresh() asks the server directly. */}
        <Button onClick={() => refresh()}>Call the API</Button>
      </div>
    </div>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Demo />
      <SessionExpiredDialog />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/session-dialogs

---

# Sheet

> A panel that slides in from any edge for filters, record details, settings or navigation.

Status: beta. Category: Overlays.

```ts
import { Sheet, SheetTrigger, SheetContent, SheetHeader, SheetTitle, SheetDescription } from '@glyphui/ui'
```

Exports: `Sheet`, `SheetTrigger`, `SheetContent`, `SheetHeader`, `SheetTitle`, `SheetDescription`, `SheetBody`, `SheetFooter`, `SheetClose`, `sheetStyles`.

## Notes

- It is a modal dialog: focus is trapped inside and returns to the trigger on close.
- SheetBody scrolls on its own, so the header and footer stay in view.

## Example: Filters panel

```tsx
import {
  Button,
  Checkbox,
  Field,
  Select,
  SelectItem,
  Sheet,
  SheetBody,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@glyphui/ui'
import { ListFilter } from 'lucide-react'

export default function Example() {
  return (
    <Sheet>
      <SheetTrigger asChild>
        <Button variant="outline" leftIcon={<ListFilter />}>
          Filters
        </Button>
      </SheetTrigger>
      <SheetContent size="sm">
        <SheetHeader>
          <SheetTitle>Filter issues</SheetTitle>
          <SheetDescription>Showing 48 of 312 issues.</SheetDescription>
        </SheetHeader>
        <SheetBody className="grid content-start gap-5">
          <Field label="Assignee">
            <Select placeholder="Anyone">
              <SelectItem value="me">Me</SelectItem>
              <SelectItem value="unassigned">Unassigned</SelectItem>
            </Select>
          </Field>
          <Field orientation="horizontal" label="Include archived">
            <Checkbox />
          </Field>
        </SheetBody>
        <SheetFooter>
          <SheetClose asChild>
            <Button variant="outline">Reset</Button>
          </SheetClose>
          <SheetClose asChild>
            <Button>Apply filters</Button>
          </SheetClose>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}
```

## Example: Sides

side sets the edge; size sets the width of left and right sheets.

```tsx
import {
  Button,
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@glyphui/ui'

const sides = ['left', 'right', 'top', 'bottom'] as const

export default function Example() {
  return (
    <div className="flex flex-wrap gap-2">
      {sides.map((side) => (
        <Sheet key={side}>
          <SheetTrigger asChild>
            <Button variant="outline" className="capitalize">
              {side}
            </Button>
          </SheetTrigger>
          <SheetContent side={side}>
            <SheetHeader>
              <SheetTitle className="capitalize">{side} sheet</SheetTitle>
              <SheetDescription>Slides in from the {side} edge.</SheetDescription>
            </SheetHeader>
          </SheetContent>
        </Sheet>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/sheet

---

# Sidebar

> Bordered navigation sidebar with sections, icons, counts and an accent bar on the active item.

Status: stable. Category: Patterns.

```ts
import { Sidebar, SidebarHeader, SidebarContent, SidebarSection, SidebarItem, SidebarFooter } from '@glyphui/ui'
```

Exports: `Sidebar`, `SidebarHeader`, `SidebarContent`, `SidebarSection`, `SidebarItem`, `SidebarFooter`, `SidebarTrigger`, `sidebarStyles`.

## Notes

- SidebarItem renders a link through GlyphProvider linkComponent when href is set, otherwise a button.
- The active item gets aria-current="page".

## SidebarItem props

| Prop | Type | Default | Description |
|---|---|---|---|
| `active` | `boolean` |  | Marks the current page. Computed from the provider's `router` when not set. |
| `badge` | `ReactNode` |  | Count or short status shown at the end. |
| `className` | `string` |  |  |
| `end` | `boolean` |  | With automatic matching, only the exact path is active (not its children). |
| `href` | `string` |  | Renders a link through the provider's `linkComponent`. Without it, renders a button. |
| `icon` | `ReactNode` |  |  |
| `onClick` | `((event: MouseEvent<HTMLElement, MouseEvent>) => void)` |  |  |

## Example: Sections and footer

```tsx
import {
  AppShell,
  Avatar,
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarItem,
  SidebarSection,
  Text,
} from '@glyphui/ui'
import { CircleDot, Inbox, Layers, Users } from 'lucide-react'
import { useState } from 'react'

export default function Example() {
  const [active, setActive] = useState('issues')
  const item = (id: string) => ({ active: active === id, onClick: () => setActive(id) })
  return (
    <div className="h-[26rem] overflow-hidden rounded-lg border border-border">
      <AppShell
        layout="embedded"
        sidebar={
          <Sidebar>
            <SidebarHeader>
              <span className="text-small font-semibold">Acme Inc.</span>
            </SidebarHeader>
            <SidebarContent>
              <SidebarSection>
                <SidebarItem icon={<Inbox />} badge={3} {...item('inbox')}>
                  Inbox
                </SidebarItem>
                <SidebarItem icon={<CircleDot />} badge={12} {...item('issues')}>
                  Issues
                </SidebarItem>
                <SidebarItem icon={<Layers />} {...item('views')}>
                  Views
                </SidebarItem>
              </SidebarSection>
              <SidebarSection label="Teams">
                <SidebarItem icon={<Users />} {...item('design')}>
                  Design
                </SidebarItem>
                <SidebarItem icon={<Users />} {...item('engineering')}>
                  Engineering
                </SidebarItem>
              </SidebarSection>
            </SidebarContent>
            <SidebarFooter>
              <Avatar name="Ada Lovelace" size="sm" />
              <span className="truncate text-small font-medium">Ada Lovelace</span>
            </SidebarFooter>
          </Sidebar>
        }
      >
        <div className="p-5">
          <Text tone="muted">Selected: {active}</Text>
        </div>
      </AppShell>
    </div>
  )
}
```

## Example: Collapsed rail

Labels become tooltips when the sidebar is collapsed.

```tsx
import { AppShell, Sidebar, SidebarContent, SidebarItem, SidebarTrigger, Text } from '@glyphui/ui'
import { CircleDot, Inbox, SquareKanban } from 'lucide-react'

export default function Example() {
  return (
    <div className="h-72 overflow-hidden rounded-lg border border-border">
      <AppShell
        layout="embedded"
        defaultCollapsed
        sidebar={
          <Sidebar>
            <SidebarContent>
              <SidebarItem icon={<Inbox />} badge={3}>
                Inbox
              </SidebarItem>
              <SidebarItem icon={<CircleDot />} active>
                Issues
              </SidebarItem>
              <SidebarItem icon={<SquareKanban />}>Projects</SidebarItem>
            </SidebarContent>
          </Sidebar>
        }
      >
        <div className="flex items-center gap-2 p-4">
          <SidebarTrigger />
          <Text size="small" tone="muted">
            Toggle the rail
          </Text>
        </div>
      </AppShell>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/sidebar

---

# SignInForm

> The whole sign-in flow in one component: password, OAuth, email link, and the code steps the backend asks for.

Status: beta. Category: Auth.

```ts
import { SignInForm, MagicLinkSent } from '@glyphui/auth/ui'
```

Exports: `SignInForm`, `MagicLinkSent`.

## Notes

- OAuth buttons appear for every provider the adapter supports; pass providers={[]} to hide them.
- Passwords and emails use autocomplete hints so password managers fill and save them.
- onSuccess runs once the user is fully signed in; with React Router, pass useRedirectAfterSignIn().
- Errors with fieldErrors show next to the field; anything else shows above the form.

## SignInForm props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `defaultEmail` | `string` |  |  |
| `description` | `ReactNode` | `Sign in to continue.` |  |
| `footer` | `ReactNode` |  |  |
| `forgotPasswordHref` | `string` |  | Adds a "Forgot password?" link beside the password label. |
| `headingLevel` | `HeadingLevel` |  | Heading level of the title. Default 1, for a page whose main content is the form. |
| `magicLink` | `boolean` | `true` | Offer "Email me a sign-in link" when the adapter supports it. Default true. |
| `onSuccess` | `((session: AuthSession) => void)` |  | Called once the user is fully signed in (after any code steps). |
| `providers` | `readonly OAuthProvider[]` |  | OAuth buttons to show. Default: every provider the adapter supports; `[]` for none. |
| `signUpHref` | `string` |  | Adds "New here? Create an account" linking here. |
| `title` | `ReactNode` | `Welcome back` |  |
| `twoFactor` | `{ title?: ReactNode; description?: ReactNode; }` |  | Wording for the two-step code screen. By default it follows how the server sends codes. |

## Example: Sign in

ada@example.com / correct horse signs in; a wrong password shows the server’s message. Codes appear as toasts.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SignInForm } from '@glyphui/auth/ui'
import { toast } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 500,
  oauthProviders: ['google', 'github'],
  users: [{ email: 'ada@example.com', password: 'correct horse', name: 'Ada Lovelace' }],
})

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SignInForm
        headingLevel={3}
        magicLink={false}
        signUpHref="#sign-up"
        forgotPasswordHref="#forgot-password"
        onSuccess={(session) => toast.success(`Signed in as ${session.user.name}`)}
      />
    </AuthProvider>
  )
}
```

## Example: Two-step and email links

grace@example.com / cobol rules continues to a code. "Email me a sign-in link" switches to passwordless.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SignInForm } from '@glyphui/auth/ui'
import { toast } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 500,
  oauthProviders: [],
  users: [
    { email: 'grace@example.com', password: 'cobol rules', name: 'Grace Hopper', twoFactor: true },
  ],
  onCode: ({ email, code }) => toast(`Email to ${email}`, { description: `Your code: ${code}` }),
})

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SignInForm
        headingLevel={3}
        onSuccess={(session) => toast.success(`Signed in as ${session.user.name}`)}
      />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/sign-in-form

---

# SignUpForm

> Account creation with name, email and a password strength meter, then the email-code step, ending signed in.

Status: beta. Category: Auth.

```ts
import { SignUpForm } from '@glyphui/auth/ui'
```

Exports: `SignUpForm`.

## Notes

- An "email taken" error from the server shows on the email field.
- For link-based verification (Firebase), it shows "Confirm your email" instead of a code input.
- terms renders above the button, e.g. links to your terms and privacy policy.

## SignUpForm props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `collectName` | `boolean` | `true` | Ask for the user's name. Default true. |
| `description` | `ReactNode` |  |  |
| `extraFields` | `readonly SignUpExtraField[]` | `[]` | More fields your sign-up needs, such as an invite code or a workspace name. Values are validated with the form and passed to `signUp` as `extra` (the REST adapter sends them in the request body). Server errors keyed by a field's `name` show beside it. |
| `footer` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` |  | Heading level of the title. Default 1, for a page whose main content is the form. |
| `minPasswordLength` | `number` | `8` | Minimum password length. Default 8. |
| `onSuccess` | `((session: AuthSession) => void)` |  | Called once the account exists and the user is signed in (after the email code). |
| `providers` | `readonly OAuthProvider[]` |  |  |
| `signInHref` | `string` |  | Adds "Already have an account? Sign in" linking here. |
| `terms` | `ReactNode` |  | Shown above the button, e.g. "By signing up you agree to our Terms." |
| `title` | `ReactNode` | `Create your account` |  |

## Example: Sign up and verify

The 6-digit code arrives as a toast; it submits itself once all digits are in. ada@example.com is taken.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SignUpForm } from '@glyphui/auth/ui'
import { Link, toast } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 500,
  oauthProviders: ['google'],
  users: [{ email: 'ada@example.com', password: 'correct horse' }],
  onCode: ({ email, code }) => toast(`Email to ${email}`, { description: `Your code: ${code}` }),
})

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SignUpForm
        headingLevel={3}
        description="Free for 14 days. No credit card required."
        signInHref="#sign-in"
        terms={
          <>
            By signing up you agree to the <Link href="#terms">Terms</Link> and{' '}
            <Link href="#privacy">Privacy Policy</Link>.
          </>
        }
        onSuccess={(session) => toast.success(`Welcome, ${session.user.name}`)}
      />
    </AuthProvider>
  )
}
```

## Example: Invite code and workspace

extraFields adds validated fields; their values reach signUp as extra, and the REST adapter sends them with the request.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SignUpForm } from '@glyphui/auth/ui'
import { toast } from '@glyphui/ui'

const adapter = memoryAdapter({ latency: 500, requireEmailVerification: false })

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SignUpForm
        headingLevel={3}
        title="Join your team"
        collectName={false}
        providers={[]}
        extraFields={[
          {
            name: 'inviteCode',
            label: 'Invite code',
            description: 'From the invitation email.',
            required: 'Enter your invite code.',
            validate: (value) =>
              /^INV-\d+$/.test(value) ? undefined : 'Codes look like INV-1234.',
          },
          { name: 'workspace', label: 'Workspace name', placeholder: 'Acme Inc.' },
        ]}
        onSuccess={(session) => toast.success(`Welcome, ${session.user.email}`)}
      />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/sign-up-form

---

# SiteFooter

> Site-wide footer with brand, link columns, copyright and social links.

Status: beta. Category: Blocks.

```ts
import { SiteFooter } from '@glyphui/blocks'
```

Exports: `SiteFooter`.

## Notes

- Each column is a navigation landmark named by its title.

## SiteFooter props

| Prop | Type | Default | Description |
|---|---|---|---|
| `brand` (required) | `ReactNode` |  | Logo or product name. |
| `bottom` | `ReactNode` |  | Extra content in the bottom row, e.g. a theme switch or status link. |
| `columns` | `readonly FooterColumn[]` | `[]` |  |
| `copyright` | `ReactNode` |  | e.g. "© 2026 Acme Inc." |
| `socials` | `ReactNode` |  | Social icon links, shown at the end of the bottom row. |
| `tagline` | `ReactNode` |  | One line about the product under the brand. |

## Example: Columns and socials

```tsx
import { SiteFooter } from '@glyphui/blocks'
import { Button } from '@glyphui/ui'
import { Github, Linkedin } from 'lucide-react'

export default function Example() {
  return (
    <SiteFooter
      brand={<span className="font-display text-h4">Ledgerline</span>}
      tagline="Billing and invoicing for software companies."
      columns={[
        {
          title: 'Product',
          links: [
            { label: 'Pricing', href: '#pricing' },
            { label: 'Changelog', href: '#changelog' },
            { label: 'Status', href: '#status' },
          ],
        },
        {
          title: 'Company',
          links: [
            { label: 'About', href: '#about' },
            { label: 'Careers', href: '#careers' },
          ],
        },
        {
          title: 'Resources',
          links: [
            { label: 'Docs', href: '#docs' },
            { label: 'API reference', href: '#api' },
          ],
        },
        {
          title: 'Legal',
          links: [
            { label: 'Privacy', href: '#privacy' },
            { label: 'Terms', href: '#terms' },
          ],
        },
      ]}
      copyright="© 2026 Ledgerline, Inc."
      socials={
        <>
          <Button variant="ghost" size="sm" iconOnly asChild>
            <a href="#github" aria-label="GitHub">
              <Github className="size-4" />
            </a>
          </Button>
          <Button variant="ghost" size="sm" iconOnly asChild>
            <a href="#linkedin" aria-label="LinkedIn">
              <Linkedin className="size-4" />
            </a>
          </Button>
        </>
      }
    />
  )
}
```

Live page: https://glyphui.xyz/components/site-footer

---

# Skeleton

> A placeholder block shown while content loads. Size it with utility classes.

Status: stable. Category: Feedback.

```ts
import { Skeleton } from '@glyphui/ui'
```

Exports: `Skeleton`, `skeletonStyles`.

## Notes

- Skeletons are aria-hidden; mark the loading region with aria-busy so screen readers know.

## Example: Loading a card

```tsx
import { Card, Skeleton } from '@glyphui/ui'

export default function Example() {
  return (
    <Card className="max-w-sm" aria-busy="true">
      <div className="flex items-center gap-3">
        <Skeleton className="size-10 rounded-pill" />
        <div className="grid flex-1 gap-2">
          <Skeleton className="h-4 w-2/3" />
          <Skeleton className="h-3 w-1/3" />
        </div>
      </div>
      <Skeleton className="h-24 w-full" />
    </Card>
  )
}
```

Live page: https://glyphui.xyz/components/skeleton

---

# Slider

> Choose a number, or a range with two thumbs, by dragging or with the arrow keys.

Status: beta. Category: Forms.

```ts
import { Slider } from '@glyphui/ui'
```

Exports: `Slider`, `sliderStyles`.

## Notes

- Use onValueCommit for expensive work such as network requests; it fires once when the thumb is released.
- Range thumbs are named "Minimum" and "Maximum" by default; change them with thumbLabels.

## Example: Single value

showValue displays the value above the thumb.

```tsx
import { Field, Slider } from '@glyphui/ui'

export default function Example() {
  return (
    <Field label="Volume" className="max-w-sm">
      <Slider defaultValue={60} showValue={(v) => `${v}%`} marks={[0, 50, 100]} />
    </Field>
  )
}
```

## Example: Range

Pass a [min, max] tuple; onValueChange returns a tuple.

```tsx
import { Slider, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [price, setPrice] = useState<readonly [number, number]>([200, 800])
  return (
    <div className="grid max-w-sm gap-3">
      <Slider<readonly [number, number]>
        value={price}
        onValueChange={setPrice}
        min={0}
        max={1000}
        step={50}
        minStepsBetweenThumbs={1}
        thumbLabels={['Minimum price', 'Maximum price']}
      />
      <Text size="small" tone="muted">
        ${price[0]} – ${price[1]}
      </Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/slider

---

# SocialButtons

> “Continue with …” buttons for the adapter’s OAuth providers, with brand marks drawn to each provider’s guidelines.

Status: beta. Category: Auth.

```ts
import { SocialButtons } from '@glyphui/auth/ui'
```

Exports: `SocialButtons`, `socialButtonsStyles`.

## Notes

- Google and Microsoft keep their brand colors; GitHub and Apple follow the text color, as their guidelines allow.
- Unknown providers get a text-only button with their capitalized name.
- Popup flows call onSuccess; redirect flows leave the page.

## SocialButtons props

| Prop | Type | Default | Description |
|---|---|---|---|
| `className` | `string` |  |  |
| `label` | `((name: string) => string)` |  | Button text. Default "Continue with Google". |
| `layout` | `"stack" \| "row"` |  | `stack` (default) is full-width buttons; `row` puts them side by side, icon and name. |
| `onSuccess` | `((session: AuthSession) => void)` |  | Called after a popup sign-in completes. Redirect flows leave the page instead. |
| `providers` | `readonly OAuthProvider[]` |  | Default: every provider the adapter supports. |

## Example: Stacked

The default: one full-width button per provider.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SocialButtons } from '@glyphui/auth/ui'
import { toast } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 600,
  oauthProviders: ['google', 'github', 'apple', 'microsoft'],
})

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SocialButtons
        className="w-full max-w-xs"
        onSuccess={(session) => toast.success(`Signed in as ${session.user.email}`)}
      />
    </AuthProvider>
  )
}
```

## Example: Side by side

layout="row" fits several providers in one line.

```tsx
import { AuthProvider } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { SocialButtons } from '@glyphui/auth/ui'

const adapter = memoryAdapter({ latency: 600 })

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SocialButtons
        layout="row"
        providers={['google', 'github', 'microsoft']}
        className="w-full max-w-md"
      />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/social-buttons

---

# Sparkline

> A tiny trend without axes, for stat cards and table cells: area, line or bars, with optional high and low marks.

Status: beta. Category: Data display.

```ts
import { Sparkline } from '@glyphui/ui/chart'
```

Exports: `Sparkline`.

## Notes

- title is the accessible description, so say what the trend shows: “Signups over 12 weeks, rising”.
- Pass a Sparkline to StatCard’s chart prop for a metric tile.

## Sparkline props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `string` |  | Accessible description, e.g. "Revenue over the last 12 months, rising". |
| `values` (required) | `readonly number[]` |  |  |
| `area` | `boolean` |  | @deprecated Use `variant="line"` for no fill. |
| `className` | `string` |  |  |
| `color` | `ChartColorValue` |  |  |
| `height` | `number` | `36` | Height in pixels. Default 36. |
| `showMinMax` | `boolean` | `false` | Mark the highest and lowest points. |
| `variant` | `"area" \| "line" \| "bar"` |  | `area` (default) fills under the line, `line` is just the stroke, `bar` draws columns. |

## Example: Variants

Area, line with extremes, and bars.

```tsx
import { Card, Text } from '@glyphui/ui'
import { Sparkline } from '@glyphui/ui/chart'

const signups = [8, 9, 9, 10, 9, 11, 11, 12, 11, 12, 13, 12.5]
const churn = [4.1, 3.8, 4.4, 3.2, 3.6, 2.9, 3.1, 2.7, 3.4, 2.5, 2.8, 2.4]
const deploys = [12, 18, 9, 22, 17, 25, 14, 19, 23, 16, 21, 28]

export default function Example() {
  return (
    <div className="grid w-full gap-4 sm:grid-cols-3">
      {[
        {
          label: 'Weekly signups',
          value: '12,480',
          chart: <Sparkline title="Signups over 12 weeks, rising" values={signups} />,
        },
        {
          label: 'Churn',
          value: '2.4%',
          chart: (
            <Sparkline
              title="Churn over 12 months, falling, low of 2.4%"
              values={churn}
              variant="line"
              showMinMax
              color="chart-2"
            />
          ),
        },
        {
          label: 'Deploys',
          value: '28',
          chart: (
            <Sparkline
              title="Deploys per week, highest this week"
              values={deploys}
              variant="bar"
              showMinMax
              color="chart-3"
            />
          ),
        },
      ].map((item) => (
        <Card key={item.label} padding="sm" className="gap-1">
          <Text size="small" tone="muted">
            {item.label}
          </Text>
          <p className="font-display text-h3 tabular-nums">{item.value}</p>
          {item.chart}
        </Card>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/sparkline

---

# Spinner

> An indeterminate loading indicator that inherits the current text color.

Status: stable. Category: Feedback.

```ts
import { Spinner } from '@glyphui/ui'
```

Exports: `Spinner`, `spinnerStyles`.

## Spinner props

| Prop | Type | Default | Description |
|---|---|---|---|
| `label` | `string` |  | Accessible label. Omit when the spinner sits inside an element that already says it's busy. |
| `size` | `"sm" \| "md" \| "lg"` |  |  |

## Example: Sizes

```tsx
import { Spinner } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-4 text-muted-foreground">
      <Spinner size="sm" />
      <Spinner size="md" />
      <Spinner size="lg" className="text-primary" />
    </div>
  )
}
```

## Example: With a label

Pass label when the spinner is the only signal that something is loading.

```tsx
import { Spinner, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-2 text-muted-foreground">
      <Spinner label="Syncing invoices" />
      <Text size="small" tone="muted" aria-hidden="true">
        Syncing invoices…
      </Text>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/spinner

---

# SpreadsheetViewer

> Open an Excel workbook (.xlsx) as tabs of tables, with the cells’ numbers, dates and booleans kept as types.

Status: beta. Category: Viewers.

```ts
import { SpreadsheetViewer } from '@glyphui/viewers/spreadsheet'
```

Exports: `SpreadsheetViewer`, `spreadsheetViewerStyles`.

## Notes

- Install the optional peer dependencies first: npm install read-excel-file @tanstack/react-table @tanstack/react-virtual.
- It reads .xlsx files (Office Open XML). The old binary .xls format isn’t supported.
- Merged cells show their value in the first cell and leave the rest blank.
- Files over 20 MB ask before opening, since the whole workbook is read in memory; change it with maxBytes.

## SpreadsheetViewer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `source` (required) | `ViewerSource` |  | An `.xlsx` file: a URL, a File/Blob, or bytes. |
| `className` | `string` |  |  |
| `defaultSheet` | `string \| number` |  | Sheet to open first, by name or index. Default the first. |
| `fileName` | `string` |  | Name used for export files and the table label. |
| `header` | `boolean \| "auto"` |  | Whether the first row names the columns. `auto` (default) guesses per sheet. |
| `height` | `string \| number` |  | Height of the table area. Default 480. |
| `maxBytes` | `number` |  | Files larger than this ask before opening, since the whole workbook is read in memory. Default 20 MB. |

## Example: Two sheets

Switch sheets with the tabs; each has its own filters.

```tsx
import { SpreadsheetViewer } from '@glyphui/viewers/spreadsheet'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return <SpreadsheetViewer source={fixture('sales.xlsx')} height={420} className="w-full" />
}
```

Live page: https://glyphui.xyz/components/spreadsheet-viewer

---

# Stack

> Flex layout with gaps from the spacing scale. Column by default; direction="row" for horizontal.

Status: stable. Category: Layout.

```ts
import { Stack } from '@glyphui/ui'
```

Exports: `Stack`, `stackStyles`.

## Stack props

| Prop | Type | Default | Description |
|---|---|---|---|
| `align` | `"center" \| "baseline" \| "start" \| "end" \| "stretch"` |  |  |
| `asChild` | `boolean` |  |  |
| `direction` | `"row" \| "column"` |  |  |
| `gap` | `0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 \| 8 \| 10 \| 12` |  |  |
| `justify` | `"center" \| "start" \| "end" \| "between"` |  |  |
| `wrap` | `boolean` |  |  |

## Example: Column

```tsx
import { Heading, Stack, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Stack gap={2} className="max-w-md">
      <Heading level={3}>Invite your team</Heading>
      <Text tone="muted">Everyone you invite joins as a member. You can change roles later.</Text>
    </Stack>
  )
}
```

## Example: Row

```tsx
import { Button, Stack, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Stack direction="row" align="center" justify="between" gap={3} wrap className="max-w-md">
      <Text size="small" tone="muted">
        3 unsaved changes
      </Text>
      <Stack direction="row" gap={2}>
        <Button variant="ghost" size="sm">
          Discard
        </Button>
        <Button size="sm">Save</Button>
      </Stack>
    </Stack>
  )
}
```

Live page: https://glyphui.xyz/components/stack

---

# StatCard

> A key metric with its change versus the previous period, an optional icon and a small chart.

Status: beta. Category: Data display.

```ts
import { StatCard } from '@glyphui/ui'
```

Exports: `StatCard`, `statCardStyles`.

## Notes

- trend sets the arrow and color. Use invertTrend for metrics where down is good, such as churn or latency.

## Example: Dashboard row

```tsx
import { StatCard } from '@glyphui/ui'
import { DollarSign, Timer, Users } from 'lucide-react'

export default function Example() {
  return (
    <div className="grid gap-4 sm:grid-cols-3">
      <StatCard
        label="Revenue"
        value="$48,210"
        delta="12.4%"
        trend="up"
        icon={<DollarSign />}
        description="vs. last month"
      />
      <StatCard label="Active users" value="3,912" delta="4.1%" trend="up" icon={<Users />} />
      <StatCard
        label="p95 latency"
        value="182 ms"
        delta="9%"
        trend="down"
        invertTrend
        icon={<Timer />}
      />
    </div>
  )
}
```

## Example: With a chart

Pass any chart or sparkline to `chart`; it is colored with the primary color.

```tsx
import { StatCard } from '@glyphui/ui'
import { Sparkline } from '@glyphui/ui/chart'

const values = [12, 14, 13, 17, 16, 19, 18, 22, 21, 25, 27, 30]

export default function Example() {
  return (
    <StatCard
      className="max-w-xs"
      label="Monthly recurring revenue"
      value="$30,400"
      delta="8.2%"
      trend="up"
      chart={<Sparkline title="Monthly recurring revenue over 12 months, rising" values={values} />}
    />
  )
}
```

Live page: https://glyphui.xyz/components/stat-card

---

# Stats

> Headline numbers that back up a claim: customers, uptime, money saved.

Status: beta. Category: Blocks.

```ts
import { Stats } from '@glyphui/blocks'
```

Exports: `Stats`.

## Notes

- Values render as a description list, so each number is read with its label.

## Stats props

| Prop | Type | Default | Description |
|---|---|---|---|
| `items` (required) | `readonly StatItem[]` |  |  |
| `align` | `"center" \| "left"` | `left` |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `title` | `ReactNode` |  |  |
| `variant` | `"cards" \| "plain"` | `plain` | `plain` (default) separates numbers with rules; `cards` puts each on a surface. |

## Example: Plain

```tsx
import { Stats } from '@glyphui/blocks'

export default function Example() {
  return (
    <Stats
      title="Numbers our customers see"
      items={[
        { label: 'Invoices sent last month', value: '1.2M' },
        { label: 'Average days to get paid', value: '9', description: 'Down from 31' },
        { label: 'Uptime, trailing 12 months', value: '99.99%' },
        { label: 'Countries with local payments', value: '46' },
      ]}
    />
  )
}
```

## Example: Cards, centered

```tsx
import { Stats } from '@glyphui/blocks'

export default function Example() {
  return (
    <Stats
      variant="cards"
      align="center"
      items={[
        { label: 'Teams', value: '4,200' },
        { label: 'Hours saved per month', value: '38k' },
        { label: 'Customer rating', value: '4.9/5' },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/stats

---

# Stepper

> Progress through a multi-step flow such as onboarding or checkout, horizontal or vertical.

Status: beta. Category: Navigation.

```ts
import { Stepper } from '@glyphui/ui'
```

Exports: `Stepper`, `stepperStyles`.

## Notes

- Renders an ordered list; the current step has aria-current="step" and every step announces its status.
- Statuses come from current: earlier steps are complete, later ones upcoming. Set status on a step to override.

## Stepper props

| Prop | Type | Default | Description |
|---|---|---|---|
| `current` (required) | `number` |  | Index of the current step. Earlier steps are complete, later ones upcoming. |
| `steps` (required) | `readonly StepperStep[]` |  |  |
| `onStepClick` | `((index: number) => void)` |  | Makes completed steps clickable, e.g. to go back in a wizard. |
| `orientation` | `"horizontal" \| "vertical"` |  |  |

## Example: Wizard

Completed steps are clickable when onStepClick is set.

```tsx
import { Button, Stepper, Text } from '@glyphui/ui'
import { useState } from 'react'

const steps = [
  { title: 'Account' },
  { title: 'Workspace' },
  { title: 'Invite team' },
  { title: 'Done' },
]

export default function Example() {
  const [current, setCurrent] = useState(1)
  return (
    <div className="grid w-full max-w-xl gap-6">
      <Stepper steps={steps} current={current} onStepClick={setCurrent} aria-label="Onboarding" />
      <div className="flex items-center justify-between gap-3">
        <Text size="small" tone="muted">
          Step {current + 1} of {steps.length}
        </Text>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={current === 0}
            onClick={() => setCurrent((c) => c - 1)}
          >
            Back
          </Button>
          <Button
            size="sm"
            disabled={current === steps.length - 1}
            onClick={() => setCurrent((c) => c + 1)}
          >
            Continue
          </Button>
        </div>
      </div>
    </div>
  )
}
```

## Example: Vertical with descriptions

```tsx
import { Stepper } from '@glyphui/ui'

export default function Example() {
  return (
    <Stepper
      orientation="vertical"
      current={2}
      aria-label="Order status"
      className="max-w-sm"
      steps={[
        { title: 'Order placed', description: 'Oct 14, 09:12' },
        { title: 'Payment confirmed', description: 'Oct 14, 09:13' },
        { title: 'Packed', description: 'Ships from Frankfurt' },
        { title: 'Shipped' },
        { title: 'Delivered' },
      ]}
    />
  )
}
```

## Example: Error state

Override a step’s status to flag a problem.

```tsx
import { Stepper } from '@glyphui/ui'

export default function Example() {
  return (
    <Stepper
      className="max-w-xl"
      current={2}
      aria-label="Checkout"
      steps={[
        { title: 'Cart' },
        { title: 'Shipping' },
        { title: 'Payment', description: 'Card declined', status: 'error' },
        { title: 'Review' },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/stepper

---

# Switch

> An on/off toggle for settings that apply immediately.

Status: stable. Category: Forms.

```ts
import { Switch } from '@glyphui/ui'
```

Exports: `Switch`, `switchStyles`.

## Notes

- Use a Switch for instant settings and a Checkbox for choices submitted with a form.

## Switch props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `size` | `"sm" \| "md"` |  |  |

## Example: Settings list

```tsx
import { Field, Switch } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-sm gap-4">
      <Field
        orientation="horizontal"
        label="Product updates"
        description="A short email when we ship."
      >
        <Switch defaultChecked />
      </Field>
      <Field orientation="horizontal" label="Weekly digest" description="Every Monday at 9:00.">
        <Switch />
      </Field>
    </div>
  )
}
```

## Example: Sizes

```tsx
import { Switch } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex items-center gap-4">
      <Switch size="sm" aria-label="Small switch" defaultChecked />
      <Switch size="md" aria-label="Medium switch" defaultChecked />
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/switch

---

# Table

> Semantic table primitives styled by the theme. For sorting, search and paging use DataTable.

Status: stable. Category: Data display.

```ts
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from '@glyphui/ui'
```

Exports: `Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell`, `TableCaption`, `tableStyles`.

## Notes

- The table scrolls horizontally inside its wrapper instead of widening the page.

## Example: Basic

```tsx
import { Badge, Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@glyphui/ui'

const members = [
  { name: 'Ada Lovelace', email: 'ada@acme.dev', role: 'Owner' },
  { name: 'Grace Hopper', email: 'grace@acme.dev', role: 'Admin' },
  { name: 'Alan Kay', email: 'alan@acme.dev', role: 'Member' },
]

export default function Example() {
  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Name</TableHead>
          <TableHead>Email</TableHead>
          <TableHead>Role</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {members.map((m) => (
          <TableRow key={m.email}>
            <TableCell className="font-medium">{m.name}</TableCell>
            <TableCell className="text-muted-foreground">{m.email}</TableCell>
            <TableCell>
              <Badge>{m.role}</Badge>
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  )
}
```

## Example: Numeric columns

Figures are tabular by default, so digits line up.

```tsx
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@glyphui/ui'

const invoices = [
  { id: 'INV-1042', date: 'Oct 2', amount: 1240.0 },
  { id: 'INV-1043', date: 'Oct 9', amount: 86.5 },
  { id: 'INV-1044', date: 'Oct 14', amount: 12900.75 },
]

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

export default function Example() {
  return (
    <Table>
      <TableCaption>Invoices for October 2026</TableCaption>
      <TableHeader>
        <TableRow>
          <TableHead>Invoice</TableHead>
          <TableHead>Date</TableHead>
          <TableHead className="text-right">Amount</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {invoices.map((inv) => (
          <TableRow key={inv.id}>
            <TableCell className="font-mono text-caption">{inv.id}</TableCell>
            <TableCell>{inv.date}</TableCell>
            <TableCell className="text-right">{usd.format(inv.amount)}</TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  )
}
```

Live page: https://glyphui.xyz/components/table

---

# Tabs

> Switches between related panels of content. Underline and pill variants.

Status: stable. Category: Navigation.

```ts
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@glyphui/ui'
```

Exports: `Tabs`, `TabsList`, `TabsTrigger`, `TabsContent`, `tabsStyles`.

## Notes

- Arrow keys move between tabs; the panel is linked to its tab for screen readers.

## Tabs props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `variant` | `"underline" \| "pill"` |  |  |

## Example: Underline

```tsx
import { Tabs, TabsContent, TabsList, TabsTrigger, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Tabs defaultValue="overview">
      <TabsList>
        <TabsTrigger value="overview">Overview</TabsTrigger>
        <TabsTrigger value="activity">Activity</TabsTrigger>
        <TabsTrigger value="settings">Settings</TabsTrigger>
      </TabsList>
      <TabsContent value="overview">
        <Text tone="muted">12 open issues, 3 due this week.</Text>
      </TabsContent>
      <TabsContent value="activity">
        <Text tone="muted">Grace closed GLY-131 two hours ago.</Text>
      </TabsContent>
      <TabsContent value="settings">
        <Text tone="muted">Only admins can change project settings.</Text>
      </TabsContent>
    </Tabs>
  )
}
```

## Example: Pill

```tsx
import { Tabs, TabsContent, TabsList, TabsTrigger, Text } from '@glyphui/ui'

export default function Example() {
  return (
    <Tabs defaultValue="monthly" variant="pill">
      <TabsList>
        <TabsTrigger value="monthly">Monthly</TabsTrigger>
        <TabsTrigger value="yearly">Yearly</TabsTrigger>
      </TabsList>
      <TabsContent value="monthly">
        <Text>$20 per seat, billed monthly.</Text>
      </TabsContent>
      <TabsContent value="yearly">
        <Text>$16 per seat, billed yearly.</Text>
      </TabsContent>
    </Tabs>
  )
}
```

Live page: https://glyphui.xyz/components/tabs

---

# TagInput

> A free-form multi-value input: Enter or a comma turns text into removable tags. Good for labels, emails and keywords.

Status: beta. Category: Forms.

```ts
import { TagInput } from '@glyphui/ui'
```

Exports: `TagInput`, `tagInputStyles`.

## Notes

- Backspace in an empty input removes the last tag.
- Each remove button is labelled “Remove <tag>” for screen readers.

## TagInput props

| Prop | Type | Default | Description |
|---|---|---|---|
| `allowDuplicates` | `boolean` |  | Allow the same tag more than once. Default false. |
| `aria-describedby` | `string` |  |  |
| `aria-invalid` | `boolean` |  |  |
| `aria-label` | `string` |  |  |
| `className` | `string` |  |  |
| `defaultValue` | `string[]` |  |  |
| `disabled` | `boolean` |  |  |
| `id` | `string` |  |  |
| `maxTags` | `number` |  | Stop accepting tags after this many. |
| `name` | `string` |  | Submits each tag as its own hidden input with this name. |
| `onValueChange` | `((tags: string[]) => void)` |  |  |
| `placeholder` | `string` |  |  |
| `separators` | `readonly string[]` |  | Keys (besides Enter) that turn the typed text into a tag. Default `[',']`. |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `validate` | `((tag: string, tags: readonly string[]) => string \| true)` |  | Return an error message to reject a tag, or `true` to accept it. |
| `value` | `string[]` |  |  |

## Example: Keywords

```tsx
import { Field, TagInput } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [tags, setTags] = useState(['design-system', 'react'])
  return (
    <Field label="Keywords" description="Press Enter or comma to add." className="w-full max-w-md">
      <TagInput value={tags} onValueChange={setTags} placeholder="Add a keyword…" />
    </Field>
  )
}
```

## Example: Validation and limits

Reject tags with validate; stop at maxTags. Paste a comma-separated list to add several.

```tsx
import { Field, TagInput } from '@glyphui/ui'

const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export default function Example() {
  return (
    <Field
      label="Invite teammates"
      description="Up to 5 email addresses."
      className="w-full max-w-md"
    >
      <TagInput
        placeholder="name@company.com"
        maxTags={5}
        validate={(tag) => (email.test(tag) ? true : `“${tag}” isn't a valid email address.`)}
      />
    </Field>
  )
}
```

Live page: https://glyphui.xyz/components/tag-input

---

# Testimonials

> Customer quotes with names and roles, as a grid or with one featured quote on top.

Status: beta. Category: Blocks.

```ts
import { Testimonials } from '@glyphui/blocks'
```

Exports: `Testimonials`.

## Testimonials props

| Prop | Type | Default | Description |
|---|---|---|---|
| `items` (required) | `readonly Testimonial[]` |  |  |
| `animate` | `boolean` | `true` | Entrance animations as the block scrolls into view. They follow the theme's motion level and the visitor's reduced-motion setting; `false` turns them off for this block. Default true. |
| `description` | `ReactNode` |  |  |
| `eyebrow` | `ReactNode` |  |  |
| `headingLevel` | `HeadingLevel` | `2` |  |
| `title` | `ReactNode` |  |  |
| `variant` | `"grid" \| "featured"` | `grid` | `grid` (default) shows cards in columns; `featured` shows the first quote large. |

## Example: Grid

```tsx
import { Testimonials } from '@glyphui/blocks'

export default function Example() {
  return (
    <Testimonials
      title="Finance teams sleep better"
      items={[
        {
          quote: 'We closed the books two days faster the first month.',
          author: { name: 'Priya Raman', title: 'Controller, Northwind' },
        },
        {
          quote: 'Usage billing used to be a spreadsheet. Now it is a webhook.',
          author: { name: 'Tomás Ortega', title: 'CTO, Initech' },
        },
        {
          quote: 'Our late payments dropped by a third without a single awkward email.',
          author: { name: 'Hannah Becker', title: 'COO, Contoso' },
        },
      ]}
    />
  )
}
```

## Example: Featured

```tsx
import { Testimonials } from '@glyphui/blocks'

export default function Example() {
  return (
    <Testimonials
      variant="featured"
      items={[
        {
          quote: 'Ledgerline replaced three tools and a part-time contractor. It just runs.',
          author: { name: 'Marcus Lee', title: 'Head of Finance, Hooli' },
        },
        {
          quote: 'Setup took an afternoon.',
          author: { name: 'Ines Duarte', title: 'Founder, Umbrella' },
        },
        {
          quote: 'The revenue reports are the best part.',
          author: { name: 'Kenji Watanabe', title: 'CFO, Vandelay' },
        },
      ]}
    />
  )
}
```

Live page: https://glyphui.xyz/components/testimonials

---

# Text

> Body copy in the theme type scale, with tones, weights, mono and truncation.

Status: stable. Category: Typography.

```ts
import { Text } from '@glyphui/ui'
```

Exports: `Text`, `textStyles`.

## Text props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  | Render the child element (e.g. `<span>`, `<label>`) with text styles instead of a `<p>`. |
| `mono` | `boolean` |  |  |
| `size` | `"body" \| "caption" \| "small" \| "lead"` |  |  |
| `tone` | `"default" \| "primary" \| "success" \| "warning" \| "danger" \| "muted" \| "faint"` |  |  |
| `truncate` | `boolean` |  |  |
| `weight` | `"regular" \| "medium" \| "semibold"` |  |  |

## Example: Sizes

```tsx
import { Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid max-w-xl gap-3">
      <Text size="lead">A lead paragraph introduces a page in one or two calm sentences.</Text>
      <Text>Body text is tuned for long reading, with comfortable line height.</Text>
      <Text size="small">Small text for helper copy, metadata and table cells.</Text>
      <Text size="caption" mono>
        CAPTION · $48,210.00 · 12.4%
      </Text>
    </div>
  )
}
```

## Example: Tones

```tsx
import { Text } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="grid gap-1">
      <Text>Default foreground</Text>
      <Text tone="muted">Muted, for secondary text</Text>
      <Text tone="faint">Faint, for hints and placeholders</Text>
      <Text tone="primary" weight="medium">
        Primary
      </Text>
      <Text tone="success">Payment received</Text>
      <Text tone="danger">Card declined</Text>
    </div>
  )
}
```

## Example: Other elements

Renders a <p> by default; asChild styles a span, label or anything else.

```tsx
import { Text } from '@glyphui/ui'

export default function Example() {
  return (
    <p className="text-body">
      Signed in as{' '}
      <Text asChild weight="semibold">
        <span>ada@acme.dev</span>
      </Text>
      .
    </p>
  )
}
```

Live page: https://glyphui.xyz/components/text

---

# Textarea

> A multi-line text field that grows with its content.

Status: stable. Category: Forms.

```ts
import { Textarea } from '@glyphui/ui'
```

Exports: `Textarea`, `textareaStyles`.

## Example: In a field

```tsx
import { Field, Textarea } from '@glyphui/ui'

export default function Example() {
  return (
    <Field label="Release notes" description="Markdown is supported." className="max-w-md">
      <Textarea placeholder="What changed in this release?" rows={4} />
    </Field>
  )
}
```

Live page: https://glyphui.xyz/components/textarea

---

# Theming

> One typed theme file controls color, type, shape, depth, motion and component defaults. Providers apply it and handle color mode.

Status: stable. Category: Patterns.

```ts
import { GlyphProvider, ThemeScope, ColorModeProvider, ColorModeScript } from '@glyphui/ui'
```

Exports: `GlyphProvider`, `ThemeScope`, `ColorModeProvider`, `ColorModeScript`, `getColorModeScript`, `useColorMode`, `useGlyph`, `useLinkComponent`, `useIsActive`, `defineTheme`, `themeToCss`, `tokenVar`, `auditContrast`, `contrastRatio`, `presets`, `glyph`, `brutalist`, `editorial`, `playful`.

## Notes

- Render GlyphProvider once at the root. Prevent the dark-mode flash with the Vite plugin (@glyphui/ui/vite), <ColorModeScript /> with SSR, or getColorModeScript() in <head>.
- Pass router to connect your router: links navigate client-side and navigation items mark the current page. useIsActive(href) exposes the same matching to your own components.
- theme.components is typed per component: a Button size that does not exist is a compile error.
- Change a solid color like primary without its foreground and defineTheme picks readable text for it. In development, GlyphProvider warns when a theme still fails WCAG contrast; auditContrast(theme) lists every failing pair.
- theme.motion sets durations, easings, the motion level (none, subtle or expressive) and the spring ({ stiffness, damping, mass? }) behind overlays, indicators and reveals. See Motion.

## GlyphProvider props

| Prop | Type | Default | Description |
|---|---|---|---|
| `defaultMode` | `ColorModePreference` |  | Color mode used until the user picks one. |
| `linkComponent` | `LinkComponent` |  | Your router's link only. Prefer `router`, which also handles active items. |
| `motion` | `"none" \| "subtle" \| "expressive"` |  | Overrides the theme's motion level everywhere, e.g. `"none"` in tests or for a user setting. Visitors who ask for reduced motion never get animation either way. |
| `router` | `GlyphRouter` |  | Your router: its link component, plus an optional `useIsActive` hook that marks the current page in Sidebar, Navbar and NavigationMenu. React Router: `import { reactRouter } from '@glyphui/ui/react-router'`. |
| `storageKey` | `string \| null` |  | localStorage key for the user's color mode. `null` disables persistence. |
| `theme` | `Theme` | `tokenPresets.glyph` | The theme for the whole app. Defaults to the `glyph` preset. |
| `toaster` | `boolean \| (ToasterProps & RefAttributes<HTMLElement>)` | `false` | Mounts a themed `<Toaster />` so `toast()` works anywhere. `true` for defaults, or pass Toaster props (e.g. `{ position: 'top-center' }`). Off by default. |

## Example: Presets side by side

ThemeScope renders a subtree with a different theme.

```tsx
import { Badge, Button, presets, ThemeScope, useColorMode } from '@glyphui/ui'

export default function Example() {
  const { resolvedMode } = useColorMode()
  return (
    <div className="grid gap-3 sm:grid-cols-2">
      {Object.values(presets).map((theme) => (
        <ThemeScope
          key={theme.name}
          theme={theme}
          mode={resolvedMode}
          className="grid gap-3 rounded-lg border border-border p-4"
        >
          <div className="flex items-center justify-between">
            <span className="font-display text-h4 capitalize">{theme.name}</span>
            <Badge tone="primary">Preset</Badge>
          </div>
          <div className="flex gap-2">
            <Button size="sm">Primary</Button>
            <Button size="sm" variant="outline">
              Outline
            </Button>
          </div>
        </ThemeScope>
      ))}
    </div>
  )
}
```

## Example: Color mode

```tsx
import { type ColorModePreference, SegmentedControl, Text, useColorMode } from '@glyphui/ui'

export default function Example() {
  const { mode, resolvedMode, setMode } = useColorMode()
  return (
    <div className="grid gap-2">
      <SegmentedControl<ColorModePreference>
        aria-label="Color mode"
        value={mode}
        onValueChange={setMode}
        options={[
          { value: 'light', label: 'Light' },
          { value: 'dark', label: 'Dark' },
          { value: 'system', label: 'System' },
        ]}
      />
      <Text size="small" tone="muted">
        Showing {resolvedMode} mode.
      </Text>
    </div>
  )
}
```

## Example: Extending a preset

```tsx
import { Button, defineTheme, presets, ThemeScope, useColorMode } from '@glyphui/ui'

const acme = defineTheme({
  name: 'acme',
  extends: presets.glyph,
  colors: {
    light: { primary: 'oklch(55% 0.19 45)', ring: 'oklch(55% 0.19 45)' },
    // A bright orange needs dark text on top to stay readable.
    dark: {
      primary: 'oklch(72% 0.17 45)',
      'primary-foreground': 'oklch(20% 0.04 45)',
      ring: 'oklch(72% 0.17 45)',
    },
  },
  radius: { md: '9999px' },
  components: { Button: { defaultVariants: { size: 'lg' } } },
})

export default function Example() {
  const { resolvedMode } = useColorMode()
  return (
    <ThemeScope
      theme={acme}
      mode={resolvedMode}
      className="flex flex-wrap gap-2 rounded-lg border border-border p-4"
    >
      <Button>Orange, pill, large</Button>
      <Button variant="outline">Same theme file</Button>
    </ThemeScope>
  )
}
```

Live page: https://glyphui.xyz/components/theme

---

# Timeline

> A vertical list of events in order, for activity feeds, changelogs and order tracking.

Status: beta. Category: Data display.

```ts
import { Timeline, TimelineItem } from '@glyphui/ui'
```

Exports: `Timeline`, `TimelineItem`, `timelineStyles`.

## Notes

- Renders an ordered list, so screen readers announce the number of events.
- Pass dateTime alongside time so the <time> element carries a machine-readable date.

## TimelineItem props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  |  |
| `children` | `ReactNode` |  | Description below the title. |
| `dateTime` | `string` |  | Machine-readable date for the `<time>` element, e.g. "2026-10-12T09:41". |
| `icon` | `ReactNode` |  | Replaces the dot in the marker. |
| `time` | `ReactNode` |  | Display text for when it happened, e.g. "2h ago" or "Oct 12". |
| `tone` | `"neutral" \| "primary" \| "info" \| "success" \| "warning" \| "danger"` |  |  |

## Example: Activity feed

Data-driven with the items prop.

```tsx
import { Timeline } from '@glyphui/ui'
import { GitCommitHorizontal, GitPullRequest, MessageSquare, Rocket } from 'lucide-react'

export default function Example() {
  return (
    <Timeline
      aria-label="Recent activity"
      className="max-w-md"
      items={[
        {
          title: 'Deployed v2.4.0 to production',
          time: '12 min ago',
          dateTime: '2026-10-17T09:41',
          icon: <Rocket />,
          tone: 'success',
          description: 'All 214 checks passed.',
        },
        {
          title: 'Merged “Add Combobox multi-select”',
          time: '1h ago',
          icon: <GitPullRequest />,
          tone: 'primary',
        },
        {
          title: 'Grace Hopper commented on #142',
          time: '3h ago',
          icon: <MessageSquare />,
          description: '“Keyboard support looks right, ship it.”',
        },
        { title: 'Pushed 3 commits to main', time: 'Yesterday', icon: <GitCommitHorizontal /> },
      ]}
    />
  )
}
```

## Example: Order tracking

Composed TimelineItem children with tones and icons.

```tsx
import { Timeline, TimelineItem } from '@glyphui/ui'
import { Check, Package, Truck } from 'lucide-react'

export default function Example() {
  return (
    <Timeline aria-label="Order #4821" className="max-w-sm">
      <TimelineItem title="Order placed" time="Oct 12, 09:14" icon={<Check />} tone="success">
        3 items · $148.00
      </TimelineItem>
      <TimelineItem title="Packed" time="Oct 12, 16:02" icon={<Package />} tone="success" />
      <TimelineItem title="Out for delivery" time="Today, 08:30" icon={<Truck />} tone="primary">
        Arrives between 2 pm and 4 pm.
      </TimelineItem>
      <TimelineItem title="Delivered" />
    </Timeline>
  )
}
```

Live page: https://glyphui.xyz/components/timeline

---

# Toast

> Brief notifications sent from anywhere with toast(). Built on Sonner and styled entirely by the theme.

Status: beta. Category: Feedback.

```ts
import { Toaster } from '@glyphui/ui'
```

Exports: `Toaster`, `toast`, `toastStyles`.

## Notes

- Mount one <Toaster /> near the root; call toast() from anywhere, including outside React.
- Toasts are announced to screen readers and pause while hovered.

## Example: Types

```tsx
import { Button, toast } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex flex-wrap gap-2">
      <Button variant="outline" onClick={() => toast('Draft saved')}>
        Default
      </Button>
      <Button
        variant="outline"
        onClick={() =>
          toast.success('Invoice sent', { description: 'Acme Inc. will get it by email.' })
        }
      >
        Success
      </Button>
      <Button variant="outline" onClick={() => toast.info('Sync runs every 15 minutes')}>
        Info
      </Button>
      <Button variant="outline" onClick={() => toast.warning('Your trial ends in 3 days')}>
        Warning
      </Button>
      <Button
        variant="outline"
        onClick={() =>
          toast.error('Couldn’t upload logo.png', { description: 'Files must be under 2 MB.' })
        }
      >
        Error
      </Button>
    </div>
  )
}
```

## Example: Promise

One toast that follows a request from loading to success or error.

```tsx
import { Button, toast } from '@glyphui/ui'

function publish() {
  return new Promise<{ version: string }>((resolve) =>
    setTimeout(() => resolve({ version: '0.2.0' }), 1500),
  )
}

export default function Example() {
  return (
    <Button
      onClick={() =>
        toast.promise(publish(), {
          loading: 'Publishing…',
          success: (result) => `Published ${result.version}`,
          error: 'Publishing failed. Try again.',
        })
      }
    >
      Publish release
    </Button>
  )
}
```

## Example: With an action

Offer an undo instead of a confirmation dialog.

```tsx
import { Button, toast } from '@glyphui/ui'

export default function Example() {
  return (
    <Button
      variant="outline"
      onClick={() =>
        toast('Issue archived', {
          action: { label: 'Undo', onClick: () => toast.success('Issue restored') },
        })
      }
    >
      Archive issue
    </Button>
  )
}
```

Live page: https://glyphui.xyz/components/toast

---

# Toggle

> A two-state button, and ToggleGroup for toolbars: single choice like alignment or multiple like bold and italic.

Status: beta. Category: Actions.

```ts
import { Toggle, ToggleGroup, ToggleGroupItem } from '@glyphui/ui'
```

Exports: `Toggle`, `ToggleGroup`, `ToggleGroupItem`, `toggleStyles`.

## Notes

- Icon-only toggles need an aria-label.
- Use Switch for settings that apply immediately and SegmentedControl for switching views; Toggle fits editor toolbars.

## Toggle props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |
| `size` | `"sm" \| "md" \| "lg"` |  |  |
| `variant` | `"default" \| "outline"` |  |  |

## Example: Formatting toolbar

type="multiple" for independent options, type="single" for one choice.

```tsx
import { Separator, ToggleGroup, ToggleGroupItem } from '@glyphui/ui'
import { AlignCenter, AlignLeft, AlignRight, Bold, Italic, Underline } from 'lucide-react'

export default function Example() {
  return (
    <div className="flex items-center gap-2 rounded-lg border border-border bg-surface p-1 shadow-xs">
      <ToggleGroup type="multiple" size="sm" defaultValue={['bold']} aria-label="Text style">
        <ToggleGroupItem value="bold" aria-label="Bold">
          <Bold />
        </ToggleGroupItem>
        <ToggleGroupItem value="italic" aria-label="Italic">
          <Italic />
        </ToggleGroupItem>
        <ToggleGroupItem value="underline" aria-label="Underline">
          <Underline />
        </ToggleGroupItem>
      </ToggleGroup>
      <Separator orientation="vertical" className="h-5" />
      <ToggleGroup type="single" size="sm" defaultValue="left" aria-label="Alignment">
        <ToggleGroupItem value="left" aria-label="Align left">
          <AlignLeft />
        </ToggleGroupItem>
        <ToggleGroupItem value="center" aria-label="Align center">
          <AlignCenter />
        </ToggleGroupItem>
        <ToggleGroupItem value="right" aria-label="Align right">
          <AlignRight />
        </ToggleGroupItem>
      </ToggleGroup>
    </div>
  )
}
```

## Example: Single toggle

```tsx
import { Text, Toggle } from '@glyphui/ui'
import { Star } from 'lucide-react'
import { useState } from 'react'

export default function Example() {
  const [starred, setStarred] = useState(false)
  return (
    <div className="flex items-center gap-3">
      <Toggle
        variant="outline"
        pressed={starred}
        onPressedChange={setStarred}
        aria-label="Star repository"
      >
        <Star className={starred ? 'fill-current text-warning' : undefined} />
        {starred ? 'Starred' : 'Star'}
      </Toggle>
      <Text size="small" tone="muted">
        {starred ? '1,205' : '1,204'} stars
      </Text>
    </div>
  )
}
```

## Example: Variants and sizes

```tsx
import { Toggle } from '@glyphui/ui'
import { Pin } from 'lucide-react'

export default function Example() {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Toggle size="sm" aria-label="Pin small">
        <Pin />
      </Toggle>
      <Toggle size="md" aria-label="Pin medium" defaultPressed>
        <Pin />
      </Toggle>
      <Toggle size="lg" aria-label="Pin large">
        <Pin />
      </Toggle>
      <Toggle variant="outline" size="sm">
        Small
      </Toggle>
      <Toggle variant="outline" defaultPressed>
        Medium
      </Toggle>
      <Toggle variant="outline" size="lg">
        Large
      </Toggle>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/toggle

---

# Tooltip

> A short hint shown on hover or keyboard focus.

Status: stable. Category: Overlays.

```ts
import { Tooltip } from '@glyphui/ui'
```

Exports: `Tooltip`, `tooltipStyles`.

## Notes

- The child must be focusable (a button or link) so keyboard users see the hint too.
- Never put essential information only in a tooltip; touch screens cannot hover.

## Tooltip props

| Prop | Type | Default | Description |
|---|---|---|---|
| `content` (required) | `ReactNode` |  |  |
| `asChild` | `boolean` |  |  |
| `delayDuration` | `number` |  |  |
| `disabled` | `boolean` |  | Skip the tooltip entirely, e.g. when the label is already visible. |

## Example: On an icon button

```tsx
import { IconButton, Tooltip } from '@glyphui/ui'
import { Bell, Settings2 } from 'lucide-react'

export default function Example() {
  return (
    <div className="flex gap-2">
      <Tooltip content="Notifications">
        <IconButton icon={<Bell />} aria-label="Notifications" variant="outline" />
      </Tooltip>
      <Tooltip content="Settings">
        <IconButton icon={<Settings2 />} aria-label="Settings" variant="outline" />
      </Tooltip>
    </div>
  )
}
```

## Example: Placement

```tsx
import { Button, Tooltip } from '@glyphui/ui'

export default function Example() {
  return (
    <div className="flex flex-wrap gap-2">
      {(['top', 'right', 'bottom', 'left'] as const).map((side) => (
        <Tooltip key={side} content={`Shown on the ${side}`} side={side}>
          <Button variant="outline" size="sm">
            {side}
          </Button>
        </Tooltip>
      ))}
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/tooltip

---

# Treemap

> Sizes of many parts of a whole as nested rectangles, grouped and colored by category.

Status: beta. Category: Data display.

```ts
import { Treemap } from '@glyphui/ui/chart'
```

Exports: `Treemap`.

## Notes

- Tiles too small for text show it in the tooltip and the accessible table instead.
- Each group gets one palette color; after five groups, colors are blended rather than repeated.

## Treemap props

| Prop | Type | Default | Description |
|---|---|---|---|
| `category` (required) | `string` |  | Field naming each rectangle. |
| `data` (required) | `readonly T[]` |  | One row per rectangle. Rows sharing a `group` are colored and nested together. |
| `title` (required) | `string` |  |  |
| `value` (required) | `string` |  | Field holding each rectangle's size. |
| `className` | `string` |  |  |
| `colors` | `readonly ChartColorValue[]` |  |  |
| `description` | `ReactNode` |  |  |
| `empty` | `ReactNode` |  | Shown when there is no data. Defaults to a short "No data" message. |
| `error` | `unknown` |  | Shows an error message in place of the plot, with a retry button when `onRetry` is set. |
| `group` | `string` |  | Field grouping rectangles, e.g. a team or product line. Each group gets one color. |
| `height` | `number` |  | Plot height in pixels. Default 280. |
| `hideTitle` | `boolean` |  |  |
| `loading` | `boolean` |  | Shows a skeleton in place of the plot. |
| `onRetry` | `(() => unknown)` |  |  |
| `showLegend` | `boolean` |  |  |
| `valueFormatter` | `((value: number) => string)` |  |  |

## Example: Cloud spend

Vendors grouped by team.

```tsx
import { Treemap } from '@glyphui/ui/chart'

const spend = [
  { vendor: 'AWS', team: 'Platform', cost: 42800 },
  { vendor: 'Datadog', team: 'Platform', cost: 9400 },
  { vendor: 'Cloudflare', team: 'Platform', cost: 3100 },
  { vendor: 'Snowflake', team: 'Data', cost: 18600 },
  { vendor: 'Fivetran', team: 'Data', cost: 5200 },
  { vendor: 'Figma', team: 'Design', cost: 2900 },
  { vendor: 'Linear', team: 'Product', cost: 1400 },
  { vendor: 'Notion', team: 'Product', cost: 1100 },
]

const usd = (v: number) => `$${(v / 1000).toFixed(1)}k`

export default function Example() {
  return (
    <Treemap
      className="w-full"
      title="Software spend by team"
      description="October, USD"
      data={spend}
      category="vendor"
      value="cost"
      group="team"
      valueFormatter={usd}
    />
  )
}
```

Live page: https://glyphui.xyz/components/treemap

---

# TreeView

> A nested, expandable list for file trees and hierarchies, with full keyboard navigation.

Status: beta. Category: Data display.

```ts
import { TreeView } from '@glyphui/ui'
```

Exports: `TreeView`, `treeViewStyles`.

## Notes

- Follows the WAI-ARIA tree pattern: one tab stop, arrow keys to move, Right and Left to expand and collapse, Home and End to jump, a letter to find the next match.
- Enter or Space selects. Clicking a parent also expands or collapses it.
- Give the tree an aria-label that says what it contains.

## TreeView props

| Prop | Type | Default | Description |
|---|---|---|---|
| `aria-label` (required) | `string` |  | Required: describes the tree, e.g. "Project files". |
| `nodes` (required) | `readonly TreeNode[]` |  |  |
| `defaultExpanded` | `readonly string[]` |  |  |
| `defaultSelected` | `string \| null` |  |  |
| `expanded` | `readonly string[]` |  | Ids of expanded nodes (controlled). |
| `onExpandedChange` | `((expanded: string[]) => void)` |  |  |
| `onSelect` | `((id: string, node: TreeNode) => void)` |  |  |
| `selected` | `string \| null` |  | Id of the selected node (controlled). `null` for none. |
| `size` | `"sm" \| "md"` |  |  |

## Example: File tree

```tsx
import { type TreeNode, TreeView } from '@glyphui/ui'
import { FileCode2, FileJson, FileText, Folder } from 'lucide-react'

const nodes: TreeNode[] = [
  {
    id: 'src',
    label: 'src',
    icon: <Folder />,
    children: [
      {
        id: 'components',
        label: 'components',
        icon: <Folder />,
        children: [
          { id: 'button', label: 'button.tsx', icon: <FileCode2 /> },
          { id: 'card', label: 'card.tsx', icon: <FileCode2 /> },
        ],
      },
      { id: 'main', label: 'main.tsx', icon: <FileCode2 /> },
    ],
  },
  { id: 'package', label: 'package.json', icon: <FileJson /> },
  { id: 'readme', label: 'README.md', icon: <FileText /> },
]

export default function Example() {
  return (
    <TreeView
      aria-label="Project files"
      nodes={nodes}
      defaultExpanded={['src', 'components']}
      defaultSelected="button"
      className="w-64"
    />
  )
}
```

## Example: Controlled selection

Drive expanded and selected from your own state.

```tsx
import { Button, Text, type TreeNode, TreeView } from '@glyphui/ui'
import { useState } from 'react'

const nodes: TreeNode[] = [
  {
    id: 'workspace',
    label: 'Workspace',
    children: [
      { id: 'general', label: 'General' },
      { id: 'members', label: 'Members' },
      {
        id: 'billing',
        label: 'Billing',
        children: [
          { id: 'plans', label: 'Plans' },
          { id: 'invoices', label: 'Invoices' },
        ],
      },
    ],
  },
  { id: 'account', label: 'Account', children: [{ id: 'profile', label: 'Profile' }] },
]

export default function Example() {
  const [expanded, setExpanded] = useState<string[]>(['workspace'])
  const [selected, setSelected] = useState<string | null>('general')
  return (
    <div className="grid w-64 gap-3">
      <TreeView
        aria-label="Settings"
        nodes={nodes}
        expanded={expanded}
        onExpandedChange={setExpanded}
        selected={selected}
        onSelect={setSelected}
      />
      <Text size="small" tone="muted">
        Selected: <span className="font-mono text-foreground">{selected ?? 'none'}</span>
      </Text>
      <Button
        variant="outline"
        size="sm"
        onClick={() => setExpanded(['workspace', 'billing', 'account'])}
      >
        Expand all
      </Button>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/tree-view

---

# UserMenu

> The signed-in user’s avatar menu, and an organization switcher for multi-workspace apps.

Status: beta. Category: Auth.

```ts
import { UserMenu, OrganizationSwitcher } from '@glyphui/auth/ui'
```

Exports: `UserMenu`, `OrganizationSwitcher`, `userMenuStyles`.

## Notes

- Items with href navigate through your router (GlyphProvider router).
- OrganizationSwitcher takes label and createLabel, so it can say Workspaces or Teams instead of Organizations.
- The Theme submenu sets light, dark or system mode; turn it off with colorMode={false}.
- compact shows only the avatar; the name stays available to screen readers.
- OrganizationSwitcher renders nothing unless the adapter supports organizations and the user has one.

## UserMenu props

| Prop | Type | Default | Description |
|---|---|---|---|
| `align` | `"center" \| "start" \| "end"` |  |  |
| `className` | `string` |  |  |
| `colorMode` | `boolean` |  | Adds a Theme submenu (light, dark, system). Default true. |
| `compact` | `boolean` |  | Avatar only, with the name and email kept for screen readers. |
| `items` | `readonly UserMenuItem[]` |  | Links such as Profile and Settings, above Sign out. |
| `onSignOut` | `(() => void)` |  | Called after signing out, e.g. to navigate to the landing page. |
| `side` | `"left" \| "right" \| "top" \| "bottom"` |  | Which side the menu opens on. Default `bottom`; use `top` in a sidebar footer. |

## Example: In a sidebar

OrganizationSwitcher at the top, UserMenu at the bottom, opening upward.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { OrganizationSwitcher, UserMenu } from '@glyphui/auth/ui'
import { Button, Card, toast } from '@glyphui/ui'
import { CreditCard, Settings } from 'lucide-react'

const adapter = memoryAdapter({
  latency: 300,
  users: [
    {
      email: 'ada@example.com',
      password: 'pw',
      name: 'Ada Lovelace',
      organizations: [
        { id: 'engines', name: 'Analytical Engines', role: 'owner' },
        { id: 'difference', name: 'Difference Ltd', role: 'member' },
      ],
    },
  ],
})

function Panel() {
  const { user, signIn } = useAuth()
  if (!user)
    return (
      <Button onClick={() => signIn({ email: 'ada@example.com', password: 'pw' })}>
        Sign in as Ada
      </Button>
    )
  return (
    <Card padding="sm" className="flex h-72 w-64 flex-col justify-between">
      <OrganizationSwitcher onSwitch={(org) => toast.success(`Switched to ${org.name}`)} />
      <UserMenu
        side="top"
        align="start"
        className="w-full"
        items={[
          { label: 'Settings', href: '#settings', icon: <Settings /> },
          { label: 'Billing', href: '#billing', icon: <CreditCard /> },
        ]}
      />
    </Card>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Panel />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/user-menu

---

# Utilities

> The helpers Glyph components are built with, for building your own themed components.

Status: stable. Category: Patterns.

```ts
import { Utilities } from '@glyphui/ui'
```

Exports: `cn`, `tv`, `useComponentConfig`, `useControllableState`, `useMediaQuery`, `useScrolled`.

## Notes

- tv is tailwind-variants preconfigured with Glyph merge rules; use it for your own component styles.
- useComponentConfig applies a theme's per-component defaults and classes to your component.

## Example: cn

Joins classes and resolves Tailwind conflicts, including Glyph type tokens.

```tsx
import { cn } from '@glyphui/ui'

export default function Example() {
  const merged = cn(
    'text-h1 text-muted-foreground px-2',
    'text-small text-foreground',
    false && 'hidden',
  )
  return (
    <div className="grid gap-2">
      <code className="font-mono text-caption text-muted-foreground">{merged}</code>
      <p className={merged}>Later classes win: small, foreground text.</p>
    </div>
  )
}
```

## Example: Hooks

```tsx
import { Text, useControllableState, useMediaQuery } from '@glyphui/ui'

export default function Example() {
  const wide = useMediaQuery('(min-width: 48rem)')
  const [count, setCount] = useControllableState({ defaultValue: 0 })
  return (
    <div className="grid gap-2">
      <Text size="small">Viewport is {wide ? 'wide' : 'narrow'} (useMediaQuery).</Text>
      <button
        type="button"
        className="justify-self-start rounded-md border border-border px-3 py-1.5 text-small"
        onClick={() => setCount((c) => c + 1)}
      >
        Clicked {count} times (useControllableState)
      </button>
    </div>
  )
}
```

Live page: https://glyphui.xyz/components/utilities

---

# VideoPlayer

> Video with themed controls: scrubbing with the buffered range, volume, speed, captions, picture in picture and fullscreen.

Status: beta. Category: Viewers.

```ts
import { VideoPlayer } from '@glyphui/viewers/media'
```

Exports: `VideoPlayer`, `videoPlayerStyles`, `formatTime`.

## Notes

- No extra packages needed: it’s the browser’s video element with Glyph controls.
- Keyboard: Space or K plays, ←/→ seek 5 seconds, J/L seek 10, ↑/↓ change volume, M mutes, C toggles captions, F goes fullscreen.
- The position and volume sliders are real sliders for assistive technology, with spoken times.

## VideoPlayer props

| Prop | Type | Default | Description |
|---|---|---|---|
| `source` (required) | `ViewerSource` |  | The video: a URL, a File/Blob, or bytes. |
| `aspectRatio` | `string` |  | CSS aspect ratio of the frame. Default `16 / 9`. |
| `autoPlay` | `boolean` |  |  |
| `className` | `string` |  |  |
| `loop` | `boolean` |  |  |
| `muted` | `boolean` |  | Starts muted (needed for autoplay in most browsers). |
| `poster` | `string` |  |  |
| `title` | `string` |  | Accessible name, also used in control labels. Default "Video". |
| `tracks` | `readonly MediaTrack[]` |  | Subtitle and caption files (WebVTT). |

## Example: With captions

Turn captions on from the control bar or press C.

```tsx
import { VideoPlayer } from '@glyphui/viewers/media'
import { fixture } from '../../../lib/fixtures'

export default function Example() {
  return (
    <VideoPlayer
      source={fixture('clip.webm')}
      title="Product tour"
      tracks={[{ src: fixture('clip.vtt'), srcLang: 'en', label: 'English' }]}
      className="w-full max-w-2xl"
    />
  )
}
```

Live page: https://glyphui.xyz/components/video-player

---

# Virtual rows

> Virtualization for DataTable: only the rows in view are rendered, so tables with tens of thousands of rows scroll smoothly.

Status: beta. Category: Patterns.

```ts
import { Virtual rows } from '@glyphui/ui/data-table/virtual'
```

Exports: `virtualRows`.

## Notes

- Install the optional peer dependency first: npm install @tanstack/react-virtual.
- Create the virtualizer once (outside your component or with useMemo) and pass it to DataTable’s virtualize prop with pageSize={false}.
- The table scrolls inside a fixed height (default 480px) with its header pinned; screen readers get the full row count from aria-rowcount and each row’s position from aria-rowindex.
- Expandable rows are not virtualized; use pagination for tables with row details.

## Example: 10,000 rows

Search, sort and select still work across every row.

```tsx
import { Badge } from '@glyphui/ui'
import { createColumnHelper, DataTable } from '@glyphui/ui/data-table'
import { virtualRows } from '@glyphui/ui/data-table/virtual'
import { formatDay, type Invoice, makeInvoices, statusTone, usd } from '../../data-table/data'

const rows = makeInvoices(10_000)
// Create the virtualizer once, outside the component.
const virtual = virtualRows({ height: 420 })

const col = createColumnHelper<Invoice>()
const columns = [
  col.accessor('id', { header: 'Invoice' }),
  col.accessor('customer', { header: 'Customer' }),
  col.accessor('status', {
    header: 'Status',
    cell: (info) => (
      <Badge tone={statusTone[info.getValue()]} dot className="capitalize">
        {info.getValue()}
      </Badge>
    ),
  }),
  col.accessor('issued', { header: 'Issued', cell: (info) => formatDay(info.getValue()) }),
  col.accessor('total', {
    header: 'Total',
    cell: (info) => usd.format(info.getValue()),
    meta: { align: 'right' },
  }),
]

export default function Example() {
  return (
    <DataTable
      aria-label="10,000 invoices"
      data={rows}
      columns={columns}
      getRowId={(row) => row.id}
      pageSize={false}
      search={{ placeholder: 'Search 10,000 invoices…' }}
      selectable
      virtualize={virtual}
    />
  )
}
```

Live page: https://glyphui.xyz/components/data-table-virtual

---

# VisuallyHidden

> Hides content visually while keeping it available to screen readers, such as labels for icon-only controls.

Status: beta. Category: Layout.

```ts
import { VisuallyHidden } from '@glyphui/ui'
```

Exports: `VisuallyHidden`.

## Notes

- Prefer aria-label on the control itself when it is a single element; use VisuallyHidden when the text is part of richer content.

## VisuallyHidden props

| Prop | Type | Default | Description |
|---|---|---|---|
| `asChild` | `boolean` |  |  |

## Example: Labelling icons

```tsx
import { Text, VisuallyHidden } from '@glyphui/ui'
import { Check, X } from 'lucide-react'

const plans = [
  { feature: 'Unlimited projects', free: false, pro: true },
  { feature: 'Custom themes', free: true, pro: true },
]

export default function Example() {
  return (
    <table className="text-small">
      <thead>
        <tr className="text-left text-muted-foreground">
          <th className="py-2 pr-8 font-medium">Feature</th>
          <th className="px-4 py-2 font-medium">Free</th>
          <th className="px-4 py-2 font-medium">Pro</th>
        </tr>
      </thead>
      <tbody>
        {plans.map((row) => (
          <tr key={row.feature} className="border-t border-border">
            <td className="py-2 pr-8">{row.feature}</td>
            {[row.free, row.pro].map((included, i) => (
              <td key={i} className="px-4 py-2">
                {included ? (
                  <Check className="size-4 text-success" aria-hidden="true" />
                ) : (
                  <X className="size-4 text-faint-foreground" aria-hidden="true" />
                )}
                <VisuallyHidden>{included ? 'Included' : 'Not included'}</VisuallyHidden>
              </td>
            ))}
          </tr>
        ))}
      </tbody>
      <caption className="mt-3 caption-bottom">
        <Text size="caption" tone="faint">
          Icons are announced as “Included” or “Not included”.
        </Text>
      </caption>
    </table>
  )
}
```

Live page: https://glyphui.xyz/components/visually-hidden

---

# Vite plugin

> Injects the color-mode script into index.html, so dark-mode visitors never see a light flash before React loads.

Status: beta. Category: Patterns.

```ts
import { Vite plugin } from '@glyphui/ui/vite'
```

Exports: `glyphColorMode`.

## Notes

- Add it to vite.config.ts: plugins: [react(), tailwindcss(), glyphColorMode({ defaultMode: "system" })].
- Pass the same defaultMode and storageKey as GlyphProvider, so the script and the provider agree.
- The script runs before anything else in <head>, sets data-mode on <html>, and is under 400 bytes.
- With an SSR framework, render <ColorModeScript /> in the document head instead.

Live page: https://glyphui.xyz/components/vite-plugin
