Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ui): component lib debug, update components, add coverage tooling (#6304)

Seamuse5e8eee20607
diff --git a/.github/workflows/web-app-check-main.yml b/.github/workflows/web-app-check-main.yml
index 4a822d5aec..9b00519e24 100644
--- a/.github/workflows/web-app-check-main.yml
+++ b/.github/workflows/web-app-check-main.yml
@@ -142,33 +142,6 @@ jobs:
- name: Teardown Nix
if: always()
uses: './.github/actions/teardown-nix'
- tailwind:
- needs:
- - path-check
- if: needs.path-check.outputs.should_run == 'true'
- name: Theme Hygiene Inspector
- runs-on: namespace-profile-linux-small;overrides.cache-tag=web-ci
- steps:
- - name: Checkout Repo
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
- with:
- fetch-depth: '0'
- - name: Mount Namespace cache volume
- uses: namespacelabs/nscloud-cache-action@15799a6b54e5765f85b2aac25b3f0df43ed571c0
- with:
- cache: nix
- path: /home/runner/.bun/install/cache
- continue-on-error: true
- - name: Setup Nix
- uses: './.github/actions/setup-nix'
- - name: Setup Prereqs
- uses: './.github/actions/setup-reqs-web'
- - name: Check Tailwind Classes
- run: just check-tailwind
- working-directory: apps/web
- - name: Teardown Nix
- if: always()
- uses: './.github/actions/teardown-nix'
test:
needs:
- path-check
@@ -253,7 +226,6 @@ jobs:
- path-check
- typescript
- biome-check
- - tailwind
- test
- cycles
- build
@@ -266,7 +238,6 @@ jobs:
echo "path-check: ${{ needs.path-check.result }}"
echo "typescript: ${{ needs.typescript.result }}"
echo "biome-check: ${{ needs.biome-check.result }}"
- echo "tailwind: ${{ needs.tailwind.result }}"
echo "test: ${{ needs.test.result }}"
echo "cycles: ${{ needs.cycles.result }}"
echo "build: ${{ needs.build.result }}"
@@ -275,7 +246,6 @@ jobs:
if [[ "${{ needs.path-check.result }}" == "failure" ]] || \
[[ "${{ needs.typescript.result }}" == "failure" ]] || \
[[ "${{ needs.biome-check.result }}" == "failure" ]] || \
- [[ "${{ needs.tailwind.result }}" == "failure" ]] || \
[[ "${{ needs.test.result }}" == "failure" ]] || \
[[ "${{ needs.cycles.result }}" == "failure" ]] || \
[[ "${{ needs.build.result }}" == "failure" ]]; then
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index a1db1d2954..47d410681f 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -81,6 +81,14 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
- Composed primitives must not depend on use-case-specific context — a RecipientsSelector should never require an EmailComposeContext.
- New features and feature restructures use the layered layout in [docs/FRONTEND_FEATURE_ARCHITECTURE.md](../../docs/FRONTEND_FEATURE_ARCHITECTURE.md), summarized by FE-33 (`core / queries / primitives / components / views` plus an injected `context/`). Keep production wiring in an app-facing entry point and give reactive logic narrow feature-owned contracts. `src/features/activity` illustrates the layers but still has documented composition and contract migration gaps.
+### Porting shadcn-solid primitives
+- Use the upstream structure and behavior as a starting point, then reshape exports to match the local slot-based, compound-component API.
+- Replace upstream palette, surface, border, and status classes with the existing semantic tokens; inputs normally use `bg-input`, `border-edge-muted`, `text-ink`, and `text-ink-placeholder`.
+- Preserve Kobalte semantics, state attributes, and polymorphic prop types. Keep accessibility relationships inside the primitive instead of recreating them at call sites.
+- Add a co-located `*.docs.tsx` gallery page and focused `*.test.tsx` coverage for every ported component.
+- Keep `Input` a thin native control. Use `InputGroup` for icons, clear actions, inline Buttons, and shared ButtonGroup framing instead of adding composition props to `Input`.
+- In `InputGroup`, keep the input as the single control and place surrounding content in `Addon` slots. Use `align` for visual placement so accessible DOM order stays independent of layout.
+
## Styling
- Use semantic color tokens, not raw Tailwind color classes.
- Do not add cursor-pointer to clickable elements.
diff --git a/apps/web/justfile b/apps/web/justfile
index e6b5b57acb..e099e88ead 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -158,9 +158,6 @@ gen-dcs-models:
clean-env:
bun scripts/clean-env.js
-check-tailwind:
- bun scripts/check-tailwind.ts
-
fix-lock:
cd {{ justfile_directory() }}/../.. && git fetch origin dev:dev && git checkout dev -- bun.lock && bun i && git add bun.lock
diff --git a/apps/web/package.json b/apps/web/package.json
index 01defc8589..d4f7afc8ab 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -17,6 +17,7 @@
"gen-graphql-cache-schema": "bun scripts/generate-graphql-cache-entity-resolver-schema.ts",
"check-graphql-cache-schema": "bun scripts/generate-graphql-cache-entity-resolver-schema.ts --check",
"gen-tools": "bun scripts/generate-dcs-tools.ts",
+ "ui-audit": "bun scripts/ui-audit.ts",
"gen-agent-fold-types": "just gen-agent-fold-types",
"type-check": "tsc --noEmit --skipLibCheck --project tsconfig.json",
"check": "bun check-graphql-cache-schema && bun type-check && bun biome check",
@@ -59,6 +60,7 @@
"@inkibra/tauri-plugins": "git+https://github.com/macro-inc/tauri-plugins.git#6ddd6600e20436388f169e936b610fe93944b7b0",
"@kobalte/core": "^0.13.11",
"@leeoniya/ufuzzy": "^1.0.19",
+ "@lezer/highlight": "^1.2.3",
"@lexical/history": "0.45.0",
"@lexical/html": "0.45.0",
"@lexical/link": "0.45.0",
diff --git a/apps/web/scripts/check-tailwind.ts b/apps/web/scripts/check-tailwind.ts
deleted file mode 100755
index 9d0280a5bd..0000000000
--- a/apps/web/scripts/check-tailwind.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-#!/usr/bin/env bun
-import { execFileSync } from 'child_process';
-import { extname } from 'path';
-
-interface Violation {
- file: string;
- line: number;
- column: number;
- className: string;
- lineContent: string;
-}
-
-interface ChangedLine {
- file: string;
- lineNumber: number;
- content: string;
-}
-
-const PROHIBITED_TAILWIND_REGEX =
- /\b((bg|border|text|fill|caret|outline|shadow|ring|stroke)(-(white|black|(?:red|blue|green|yellow|purple|pink|indigo|gray|grey|orange|teal|cyan|emerald|lime|amber|violet|fuchsia|rose|sky|slate|zinc|neutral|stone)-\d{2,3}))|font-(berkeley|inter))\b/g;
-
-const FILE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];
-
-function getChangedLines(baseBranch: string = 'origin/dev'): ChangedLine[] {
- // Limit the diff at the source so a large repository migration cannot fill
- // Node's output buffer before the relevant app lines are parsed. Using an
- // argument array also keeps the CI-provided base branch out of a shell.
- const output = execFileSync(
- 'git',
- ['diff', '--unified=0', `${baseBranch}...HEAD`, '--', 'apps/web/src'],
- {
- cwd: execFileSync('git', ['rev-parse', '--show-toplevel'], {
- encoding: 'utf8',
- }).trim(),
- encoding: 'utf8',
- maxBuffer: 128 * 1024 * 1024,
- stdio: ['ignore', 'pipe', 'pipe'],
- }
- );
-
- const changedLines: ChangedLine[] = [];
- const lines = output.split('\n');
- let currentFile = '';
- let currentLineNumber = 0;
-
- for (const line of lines) {
- // Parse file headers
- if (line.startsWith('diff --git')) {
- const match = line.match(/diff --git a\/(.*) b\/(.*)/);
- if (match) {
- const filePath = match[2];
- const ext = extname(filePath);
- if (
- FILE_EXTENSIONS.includes(ext) &&
- filePath.startsWith('apps/web/src/')
- ) {
- currentFile = filePath;
- } else {
- currentFile = '';
- }
- }
- continue;
- }
-
- // Skip if we're not in a relevant file
- if (!currentFile) continue;
-
- // Parse hunk headers to get line numbers
- if (line.startsWith('@@')) {
- const match = line.match(/@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
- if (match) {
- currentLineNumber = parseInt(match[1], 10);
- }
- continue;
- }
-
- // Check added lines (lines starting with +, but not +++)
- if (line.startsWith('+') && !line.startsWith('+++')) {
- const content = line.slice(1); // Remove the + prefix
- changedLines.push({
- file: currentFile,
- lineNumber: currentLineNumber,
- content: content,
- });
- currentLineNumber++;
- } else if (line.startsWith(' ')) {
- // Context line, increment line number
- currentLineNumber++;
- }
- // Lines starting with - are deletions, don't increment currentLineNumber
- }
-
- return changedLines;
-}
-
-function checkChangedLines(changedLines: ChangedLine[]): Violation[] {
- const violations: Violation[] = [];
-
- for (const changedLine of changedLines) {
- const matches = [
- ...changedLine.content.matchAll(PROHIBITED_TAILWIND_REGEX),
- ];
-
- for (const match of matches) {
- if (match.index !== undefined) {
- violations.push({
- file: changedLine.file,
- line: changedLine.lineNumber,
- column: match.index + 1,
- className: match[0],
- lineContent: changedLine.content.trim(),
- });
- }
- }
- }
-
- return violations;
-}
-
-function formatViolations(
- violations: Violation[]
-): void {
- if (violations.length === 0) {
- console.log('✅ No prohibited Tailwind classes found in changed lines!');
- return;
- }
-
- console.log(
- `❌ Found ${violations.length} prohibited Tailwind class${violations.length === 1 ? '' : 'es'} in changed lines:\n`
- );
-
- const groupedByFile = violations.reduce(
- (acc, violation) => {
- if (!acc[violation.file]) {
- acc[violation.file] = [];
- }
- acc[violation.file].push(violation);
- return acc;
- },
- {} as Record<string, Violation[]>
- );
-
- for (const [file, fileViolations] of Object.entries(groupedByFile)) {
- console.log(`📄 ${file}`);
-
- for (const violation of fileViolations) {
- console.log(
- ` ${violation.line}:${violation.column} - "${violation.className}"`
- );
- console.log(` ${violation.lineContent}`);
- console.log('');
- }
- }
-
- console.log('💡 Tip: Replace these with semantic classes.');
- console.log(' Example: bg-red-500 → bg-failure, bg-white → bg-surface, font-berkely → font-mono, etc');
-}
-
-async function main(): Promise<void> {
- console.log(
- '🔍 Checking for prohibited Tailwind classes in changed lines...\n'
- );
-
- try {
- // Get the base branch from environment variable (for CI) or default to origin/dev
- const baseBranch = process.env.GITHUB_BASE_REF
- ? `origin/${process.env.GITHUB_BASE_REF}`
- : 'origin/dev';
- const changedLines = getChangedLines(baseBranch);
-
- if (changedLines.length === 0) {
- console.log('✅ No relevant lines changed!');
- return;
- }
-
- const fileCount = new Set(changedLines.map((line) => line.file)).size;
- console.log(
- `📁 Scanning ${changedLines.length} changed line${changedLines.length === 1 ? '' : 's'} across ${fileCount} file${fileCount === 1 ? '' : 's'}...`
- );
-
- const violations = checkChangedLines(changedLines);
-
- console.log('');
- formatViolations(violations);
-
- if (violations.length > 0) {
- process.exit(1);
- }
- } catch (error) {
- console.error(`Error: ${error}`);
- process.exit(1);
- }
-}
-
-// Run the main function
-main();
diff --git a/apps/web/scripts/ui-audit.test.ts b/apps/web/scripts/ui-audit.test.ts
new file mode 100644
index 0000000000..976ac380f2
--- /dev/null
+++ b/apps/web/scripts/ui-audit.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+import { baseUtility, classifyToken } from './ui-audit';
+
+describe('baseUtility', () => {
+ it('strips a variant prefix', () => {
+ expect(baseUtility('hover:bg-hover')).toBe('bg-hover');
+ expect(baseUtility('data-checked:text-ink')).toBe('text-ink');
+ });
+
+ it('strips stacked variants', () => {
+ expect(baseUtility('md:hover:px-3')).toBe('px-3');
+ });
+
+ it('ignores colons inside an arbitrary variant selector', () => {
+ expect(baseUtility('[&:hover]:bg-x')).toBe('bg-x');
+ expect(baseUtility("[&>svg:not([class*='size-'])]:size-3")).toBe('size-3');
+ });
+
+ it('keeps an arbitrary value intact', () => {
+ expect(baseUtility('h-[min(900px,calc(100vh-32px))]')).toBe(
+ 'h-[min(900px,calc(100vh-32px))]'
+ );
+ });
+
+ it('drops the important prefix', () => {
+ expect(baseUtility('!p-0')).toBe('p-0');
+ });
+});
+
+describe('classifyToken', () => {
+ it.each([
+ 'bg-surface',
+ 'text-sm',
+ 'rounded-xs',
+ 'border-edge-muted',
+ 'shadow-menu',
+ 'px-2',
+ 'h-7',
+ 'size-full',
+ 'gap-2',
+ 'font-semibold',
+ 'opacity-50',
+ ])('treats %s as a visual override', (token) => {
+ expect(classifyToken(token)).toBe('override');
+ });
+
+ it.each([
+ 'flex',
+ 'absolute',
+ 'items-center',
+ 'justify-between',
+ 'w-full',
+ 'max-h-80',
+ 'min-w-0',
+ 'mt-2',
+ '-ml-1',
+ 'z-10',
+ 'overflow-x-auto',
+ 'shrink-0',
+ 'truncate',
+ 'transition-colors',
+ 'pointer-events-none',
+ 'sr-only',
+ ])('treats %s as layout', (token) => {
+ expect(classifyToken(token)).toBe('layout');
+ });
+
+ // Width is parent-driven layout; height sets the control's own size. The two
+ // must not collapse, or every `w-full` would read as a misfit.
+ it('separates width from height', () => {
+ expect(classifyToken('w-32')).toBe('layout');
+ expect(classifyToken('h-32')).toBe('override');
+ expect(classifyToken('max-h-32')).toBe('layout');
+ });
+
+ it('classifies through a variant prefix', () => {
+ expect(classifyToken('hover:bg-hover')).toBe('override');
+ expect(classifyToken('md:flex')).toBe('layout');
+ });
+
+ it('reports project CSS classes as unknown rather than guessing', () => {
+ expect(classifyToken('split-panel-inactive')).toBe('unknown');
+ });
+});
diff --git a/apps/web/scripts/ui-audit.ts b/apps/web/scripts/ui-audit.ts
new file mode 100644
index 0000000000..43535eb0a9
--- /dev/null
+++ b/apps/web/scripts/ui-audit.ts
@@ -0,0 +1,475 @@
+#!/usr/bin/env bun
+/**
+ * Adoption audit for the `@ui` component library.
+ *
+ * Answers three questions across `apps/web/src`:
+ * 1. How much is each component actually used?
+ * 2. How often is a usage reskinned with utility classes? Layout classes are
+ * expected; classes that repaint or resize a component mean its own API
+ * did not cover the need, and that is the signal worth chasing.
+ * 3. How many primitives are still hand-rolled (`<button>`) instead of taken
+ * from the library (`<Button>`)?
+ *
+ * Parses with the TypeScript compiler rather than matching text: JSX is
+ * routinely formatted across several lines and imports get renamed
+ * (`Calendar as MiniCalendar`), both of which quietly wreck regex counts.
+ *
+ * Raw Tailwind palette classes are deliberately not checked here — the
+ * repository's FE-25 ast-grep convention is the enforcement point.
+ *
+ * bun run ui-audit # ranked report
+ * bun run ui-audit --sites Button # call sites for one component
+ * bun run ui-audit --explain # unclassified class-token frequencies
+ */
+import { readdirSync, readFileSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import ts from 'typescript';
+
+const SRC = 'src';
+/** The library's own source: usage inside it is implementation, not adoption. */
+const LIBRARY_DIR = join('src', 'components', 'ui');
+
+/**
+ * Intrinsic elements the library either covers or ought to. `component: null`
+ * means no library primitive exists yet, which is a gap in the library rather
+ * than call sites ignoring it — the report says so instead of implying 100%
+ * non-adoption.
+ */
+const HAND_ROLLED: Record<string, string | null> = {
+ button: 'Button',
+ input: null,
+ textarea: null,
+ select: 'Select',
+};
+
+/**
+ * Utility prefixes that change a component's own appearance or control size.
+ * A component carrying these is being reskinned at the call site.
+ */
+const OVERRIDE = [
+ /^bg-/, /^text-/, /^font-/, /^border(-|$)/, /^rounded(-|$)/, /^ring(-|$)/,
+ /^shadow(-|$)/, /^divide-/, /^outline(-|$)/, /^opacity-/,
+ /^p[xytblr]?-/, /^gap(-|$)/, /^h-/, /^size-/, /^leading-/, /^tracking-/,
+];
+
+/**
+ * Utility prefixes that position a component within its parent. These are the
+ * call site's business, not the component's, so they are not misfit signals.
+ */
+const LAYOUT = [
+ /^(flex|grid|block|inline|inline-flex|inline-block|contents|hidden|table)$/,
+ /^(absolute|relative|fixed|sticky|static)$/,
+ /^(items|justify|self|place|content|order|col|row|basis|grow|shrink)(-|$)/,
+ /^m[xytblr]?-/, /^-m[xytblr]?-/, /^(top|left|right|bottom|inset)-/,
+ /^-?(top|left|right|bottom|inset)-/, /^z-/, /^w-/, /^(min|max)-[wh]-/,
+ /^(overflow|whitespace|break|truncate)(-|$)/, /^aspect-/,
+ /^(translate|rotate|scale|transform|transition|duration|ease|delay|animate)(-|$)/,
+ /^-?(translate|rotate|scale)-/,
+ /^(pointer-events|select|cursor|touch)-/, /^(group|peer)(-|$)/,
+ /^sr-only$/, /^(space)-[xy]-/, /^flex-/, /^(float|clear)-/, /^(list|align)-/,
+];
+
+type Site = { file: string; line: number; classes: string };
+
+type ComponentStat = {
+ name: string;
+ files: Set<string>;
+ usages: number;
+ withClass: number;
+ withOverride: number;
+ overrideTokens: Map<string, number>;
+ sites: Site[];
+};
+
+type HandRolledStat = {
+ element: string;
+ suggested: string | null;
+ usages: number;
+ files: Set<string>;
+ sites: Site[];
+};
+
+const components = new Map<string, ComponentStat>();
+const handRolled = new Map<string, HandRolledStat>();
+const unclassified = new Map<string, number>();
+let scannedFiles = 0;
+
+function statFor(name: string): ComponentStat {
+ let stat = components.get(name);
+ if (!stat) {
+ stat = {
+ name,
+ files: new Set(),
+ usages: 0,
+ withClass: 0,
+ withOverride: 0,
+ overrideTokens: new Map(),
+ sites: [],
+ };
+ components.set(name, stat);
+ }
+ return stat;
+}
+
+/** Collects every `.tsx` worth scanning, skipping the library and test/doc files. */
+function collectFiles(dir: string, out: string[] = []): string[] {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const path = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name === 'node_modules') continue;
+ collectFiles(path, out);
+ } else if (
+ entry.name.endsWith('.tsx') &&
+ !entry.name.endsWith('.test.tsx') &&
+ !entry.name.endsWith('.spec.tsx') &&
+ !entry.name.endsWith('.docs.tsx') &&
+ !path.startsWith(LIBRARY_DIR)
+ ) {
+ out.push(path);
+ }
+ }
+ return out;
+}
+
+/**
+ * Strips Tailwind variant prefixes to get the underlying utility, respecting
+ * brackets so an arbitrary variant like `[&:hover]:bg-x` is not split inside
+ * its own selector.
+ */
+export function baseUtility(token: string): string {
+ let depth = 0;
+ let lastColon = -1;
+ for (let i = 0; i < token.length; i++) {
+ const char = token[i]!;
+ if (char === '[' || char === '(') depth++;
+ else if (char === ']' || char === ')') depth--;
+ else if (char === ':' && depth === 0) lastColon = i;
+ }
+ return token.slice(lastColon + 1).replace(/^!/, '');
+}
+
+export type ClassKind = 'override' | 'layout' | 'unknown';
+
+export function classifyToken(token: string): ClassKind {
+ const base = baseUtility(token);
+ if (!base) return 'unknown';
+ // Layout is checked first: `w-` and `max-h-` would otherwise be caught by
+ // the `h-` override rule.
+ if (LAYOUT.some((pattern) => pattern.test(base))) return 'layout';
+ if (OVERRIDE.some((pattern) => pattern.test(base))) return 'override';
+ return 'unknown';
+}
+
+/**
+ * The leftmost identifier of a tag name (`Panel.Body` -> `Panel`), used to
+ * resolve the import, plus the full path used as the reported name. Slots are
+ * reported separately because the same class means different things on each:
+ * `rounded-xl` on `Panel` is a reskin, `p-3` on `Panel.Body` is content
+ * spacing the caller owns.
+ */
+function tagNames(
+ tag: ts.JsxTagNameExpression
+): { root: string; full: string } | undefined {
+ if (ts.isIdentifier(tag)) return { root: tag.text, full: tag.text };
+ if (ts.isPropertyAccessExpression(tag)) {
+ const parts: string[] = [];
+ let current: ts.Expression = tag;
+ while (ts.isPropertyAccessExpression(current)) {
+ parts.unshift(current.name.text);
+ current = current.expression;
+ }
+ if (!ts.isIdentifier(current)) return undefined;
+ parts.unshift(current.text);
+ return { root: current.text, full: parts.join('.') };
+ }
+ return undefined;
+}
+
+/** Every string literal reachable from a class attribute, so `cn('a', x && 'b')` is covered. */
+function classStrings(attributes: ts.JsxAttributes): string[] {
+ const found: string[] = [];
+
+ for (const attribute of attributes.properties) {
+ if (!ts.isJsxAttribute(attribute)) continue;
+ const name = ts.isIdentifier(attribute.name)
+ ? attribute.name.text
+ : attribute.name.getText();
+ if (name !== 'class' && name !== 'className') continue;
+
+ const initializer = attribute.initializer;
+ if (!initializer) continue;
+ if (ts.isStringLiteral(initializer)) {
+ found.push(initializer.text);
+ continue;
+ }
+ if (ts.isJsxExpression(initializer) && initializer.expression) {
+ const visit = (node: ts.Node) => {
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
+ found.push(node.text);
+ } else if (ts.isTemplateExpression(node)) {
+ found.push(node.head.text);
+ for (const span of node.templateSpans) found.push(span.literal.text);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(initializer.expression);
+ }
+ }
+
+ return found;
+}
+
+function scan(file: string) {
+ const text = readFileSync(file, 'utf8');
+ const source = ts.createSourceFile(
+ file,
+ text,
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX
+ );
+ scannedFiles++;
+
+ /** Local binding name -> canonical `@ui` export. */
+ const localToCanonical = new Map<string, string>();
+
+ const collectImports = (node: ts.Node) => {
+ if (
+ ts.isImportDeclaration(node) &&
+ ts.isStringLiteral(node.moduleSpecifier)
+ ) {
+ const module = node.moduleSpecifier.text;
+ if (module === '@ui' || module.startsWith('@ui/components/')) {
+ const bindings = node.importClause?.namedBindings;
+ if (bindings && ts.isNamedImports(bindings)) {
+ for (const element of bindings.elements) {
+ const canonical = (element.propertyName ?? element.name).text;
+ localToCanonical.set(element.name.text, canonical);
+ }
+ }
+ }
+ }
+ ts.forEachChild(node, collectImports);
+ };
+ collectImports(source);
+
+ // `cn` and friends are utilities, not components.
+ for (const helper of ['cn', 'buttonClasses', 'badgeClasses', 'badgeTriggerClasses']) {
+ localToCanonical.delete(helper);
+ }
+
+ const lineOf = (node: ts.Node) =>
+ source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
+
+ const record = (
+ tag: { root: string; full: string },
+ attributes: ts.JsxAttributes,
+ node: ts.Node
+ ) => {
+ const line = lineOf(node);
+
+ if (tag.root === tag.root.toLowerCase() && tag.root in HAND_ROLLED) {
+ let stat = handRolled.get(tag.root);
+ if (!stat) {
+ stat = {
+ element: tag.root,
+ suggested: HAND_ROLLED[tag.root] ?? null,
+ usages: 0,
+ files: new Set(),
+ sites: [],
+ };
+ handRolled.set(tag.root, stat);
+ }
+ stat.usages++;
+ stat.files.add(file);
+ stat.sites.push({ file, line, classes: classStrings(attributes).join(' ') });
+ return;
+ }
+
+ const canonical = localToCanonical.get(tag.root);
+ if (!canonical) return;
+
+ // Report under the slot actually used, with the import's canonical name as
+ // the root so a renamed import still lands on the right component.
+ const reported =
+ tag.full === tag.root
+ ? canonical
+ : `${canonical}.${tag.full.split('.').slice(1).join('.')}`;
+ const stat = statFor(reported);
+ stat.usages++;
+ stat.files.add(file);
+
+ const classes = classStrings(attributes).join(' ').trim();
+ if (!classes) return;
+ stat.withClass++;
+
+ const tokens = classes.split(/\s+/).filter(Boolean);
+ const overrides: string[] = [];
+ for (const token of tokens) {
+ const kind = classifyToken(token);
+ if (kind === 'override') overrides.push(baseUtility(token));
+ else if (kind === 'unknown') {
+ unclassified.set(
+ baseUtility(token),
+ (unclassified.get(baseUtility(token)) ?? 0) + 1
+ );
+ }
+ }
+
+ if (overrides.length > 0) {
+ stat.withOverride++;
+ stat.sites.push({ file, line, classes });
+ for (const token of overrides) {
+ stat.overrideTokens.set(token, (stat.overrideTokens.get(token) ?? 0) + 1);
+ }
+ }
+ };
+
+ const visit = (node: ts.Node) => {
+ if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
+ const tag = tagNames(node.tagName);
+ if (tag) record(tag, node.attributes, node);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+}
+
+// --- report -----------------------------------------------------------------
+
+/** Plain text throughout: the report is meant to be piped to a file, diffed,
+ * and pasted into a PR, so no ANSI escapes anywhere. */
+const pad = (value: string | number, width: number) =>
+ String(value).padEnd(width);
+const padStart = (value: string | number, width: number) =>
+ String(value).padStart(width);
+
+const RULE = '-'.repeat(78);
+
+/** Inline meter. The percentage is printed beside it, so the bar is a scanning
+ * aid rather than the only reading of the number. */
+function meter(rate: number, width = 10): string {
+ const filled = Math.min(width, Math.round(rate * width));
+ return '#'.repeat(filled) + '.'.repeat(width - filled);
+}
+
+function heading(text: string): string {
+ return `\n${text}\n${RULE}`;
+}
+
+function percent(rate: number): string {
+ return `${Math.round(rate * 100)}%`;
+}
+
+if (import.meta.main) {
+ const args = process.argv.slice(2);
+ const explain = args.includes('--explain');
+ const sitesIndex = args.indexOf('--sites');
+ const sitesFor = sitesIndex >= 0 ? args[sitesIndex + 1] : undefined;
+
+ for (const file of collectFiles(SRC)) scan(file);
+
+ const ranked = [...components.values()].sort((a, b) => b.usages - a.usages);
+ const rateOf = (stat: ComponentStat) =>
+ stat.usages === 0 ? 0 : stat.withOverride / stat.usages;
+
+ // --sites turns the report into the call-site list for one component, which
+ // is what you actually want open while fixing them.
+ if (sitesFor) {
+ const stat = components.get(sitesFor);
+ if (!stat) {
+ console.error(
+ `No usages recorded for "${sitesFor}". Run without --sites to see the list.`
+ );
+ process.exit(1);
+ }
+ console.log(
+ heading(`${sitesFor} - ${stat.sites.length} call sites overriding visuals`)
+ );
+ for (const site of stat.sites) {
+ console.log(`${relative(SRC, site.file)}:${site.line}`);
+ console.log(` ${site.classes}`);
+ }
+ console.log();
+ process.exit(0);
+ }
+
+ const totalUsages = ranked.reduce((sum, stat) => sum + stat.usages, 0);
+ const totalOverride = ranked.reduce((sum, stat) => sum + stat.withOverride, 0);
+ const overallRate = totalOverride / Math.max(totalUsages, 1);
+
+ console.log(heading('@ui adoption'));
+ console.log(`scanned ${scannedFiles} files under apps/web/${SRC}, library excluded`);
+ console.log(`usages ${totalUsages} across ${ranked.length} components and slots`);
+ console.log(
+ `restyled ${percent(overallRate)} (${totalOverride} usages carry classes that repaint or resize the component)`
+ );
+
+ console.log(heading('By component'));
+ console.log(
+ pad('COMPONENT', 24) +
+ padStart('files', 6) +
+ padStart('uses', 6) +
+ ' ' +
+ pad('RESTYLED', 12) +
+ padStart('', 5) +
+ ' TOP OVERRIDES'
+ );
+
+ for (const stat of ranked) {
+ const rate = rateOf(stat);
+ const top = [...stat.overrideTokens.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 3)
+ .map(([token, count]) => `${token} (${count})`)
+ .join(', ');
+
+ console.log(
+ pad(stat.name, 24) +
+ padStart(stat.files.size, 6) +
+ padStart(stat.usages, 6) +
+ ' ' +
+ meter(rate) +
+ padStart(percent(rate), 6) +
+ ' ' +
+ top
+ );
+ }
+
+ console.log(heading('Hand-rolled primitives'));
+ for (const stat of [...handRolled.values()].sort(
+ (a, b) => b.usages - a.usages
+ )) {
+ const label = pad(`<${stat.element}>`, 24) + padStart(stat.usages, 6);
+
+ if (!stat.suggested) {
+ console.log(
+ `${label} ${pad('', 10)}${padStart('', 6)} no library component exists yet, ${stat.files.size} files`
+ );
+ continue;
+ }
+
+ const libraryUses = components.get(stat.suggested)?.usages ?? 0;
+ const share = stat.usages / Math.max(stat.usages + libraryUses, 1);
+ console.log(
+ `${label} ${meter(share)}${padStart(percent(share), 6)}` +
+ ` hand-rolled vs ${libraryUses} <${stat.suggested}>, ${stat.files.size} files`
+ );
+ }
+
+ if (explain) {
+ console.log(heading('Unclassified class tokens'));
+ console.log('Neither layout nor override - tune the rule lists with these.\n');
+ for (const [token, count] of [...unclassified.entries()]
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 40)) {
+ console.log(pad(token, 36) + padStart(count, 5));
+ }
+ }
+
+ console.log(
+ `\n${RULE}\n` +
+ 'bun run ui-audit --sites <Component> list the call sites for one component\n' +
+ 'bun run ui-audit --explain show unclassified class tokens\n'
+ );
+}
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index bebb9e1e14..492a47581f 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -532,7 +532,7 @@ function LayoutInner(props: RouteSectionProps) {
/>
</Show>
- <div class="flex-1 w-full min-h-0 font-sans text-ink caret-accent">
+ <div class="flex-1 w-full min-h-0 font-sans text-ink caret-current">
{props.children}
</div>
</ItemDndProvider>
diff --git a/apps/web/src/components/app/split-layout/componentRegistry.tsx b/apps/web/src/components/app/split-layout/componentRegistry.tsx
index d0f7f23f0d..77092d7534 100644
--- a/apps/web/src/components/app/split-layout/componentRegistry.tsx
+++ b/apps/web/src/components/app/split-layout/componentRegistry.tsx
@@ -889,3 +889,11 @@ registerComponent(
'icon-gallery',
lazy(() => import('@core/internal/IconGallery'))
);
+
+// Component library. Registered outside LOCAL_ONLY so design can browse it on
+// preview deploys; the whole gallery is one lazy chunk the app never loads
+// unless the route is opened.
+registerComponent(
+ 'ui',
+ lazy(() => import('@app/features/ui-gallery/UiGallery'))
+);
diff --git a/apps/web/src/components/ui/components/Avatar.docs.tsx b/apps/web/src/components/ui/components/Avatar.docs.tsx
new file mode 100644
index 0000000000..e32d625cdf
--- /dev/null
+++ b/apps/web/src/components/ui/components/Avatar.docs.tsx
@@ -0,0 +1,223 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { For } from 'solid-js';
+import { Avatar, AvatarGroup } from './Avatar';
+
+/**
+ * Sample portrait, served from `public/`. Built off `BASE_URL` rather than a
+ * bare `/teo.png` because the app is served from `/` in dev and `/app` in a
+ * build, and a hardcoded root path 404s in the latter.
+ */
+const TEO = `${import.meta.env.BASE_URL}teo.png`;
+
+// #region demo:sizes
+function SizesDemo() {
+ return (
+ <div class="flex flex-wrap items-end gap-6">
+ <For each={['sm', 'md', 'lg'] as const}>
+ {(size) => (
+ <div class="flex flex-col items-center gap-1.5">
+ <Avatar size={size}>
+ <Avatar.Fallback>TC</Avatar.Fallback>
+ </Avatar>
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ </div>
+ )}
+ </For>
+ <div class="flex flex-col items-center gap-1.5">
+ <div class="size-16">
+ <Avatar size="fill">
+ <Avatar.Fallback>TC</Avatar.Fallback>
+ </Avatar>
+ </div>
+ <span class="font-mono text-xs text-ink-subtle">fill</span>
+ </div>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:image-and-fallback
+function ImageAndFallbackDemo() {
+ return (
+ <div class="flex flex-wrap items-end gap-6">
+ <div class="flex flex-col items-center gap-2">
+ <Avatar size="lg">
+ <Avatar.Image src={TEO} alt="Teo" />
+ <Avatar.Fallback>TC</Avatar.Fallback>
+ </Avatar>
+ <span class="text-xs text-ink-subtle">Image loads</span>
+ </div>
+ <div class="flex flex-col items-center gap-2">
+ <Avatar size="lg">
+ <Avatar.Fallback>TC</Avatar.Fallback>
+ </Avatar>
+ <span class="text-xs text-ink-subtle">No image</span>
+ </div>
+ <div class="flex flex-col items-center gap-2">
+ <Avatar size="lg">
+ <Avatar.Image src="/does-not-exist.png" alt="Teo" />
+ <Avatar.Fallback>TC</Avatar.Fallback>
+ </Avatar>
+ <span class="text-xs text-ink-subtle">Image 404s</span>
+ </div>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:edge
+function EdgeDemo() {
+ return (
+ <div class="flex flex-wrap items-center gap-8">
+ <div class="flex flex-col items-center gap-2">
+ <div class="size-20">
+ <Avatar size="fill" highlightEdge>
+ <Avatar.Image src={TEO} alt="" />
+ </Avatar>
+ </div>
+ <span class="text-xs text-ink-subtle">With hairline</span>
+ </div>
+ <div class="flex flex-col items-center gap-2">
+ <div class="size-20">
+ <Avatar size="fill">
+ <Avatar.Image src={TEO} alt="" />
+ </Avatar>
+ </div>
+ <span class="text-xs text-ink-subtle">Without</span>
+ </div>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:shape
+function ShapeDemo() {
+ return (
+ <div class="flex flex-col gap-6">
+ <For each={['rounded', 'square'] as const}>
+ {(shape) => (
+ <div class="flex items-end gap-4">
+ <span class="w-16 font-mono text-xs text-ink-subtle">{shape}</span>
+ <For each={['sm', 'md', 'lg'] as const}>
+ {(size) => (
+ <div class="flex flex-col items-center gap-1.5">
+ <Avatar size={size} shape={shape} highlightEdge>
+ <Avatar.Image src={TEO} alt="Teo" />
+ </Avatar>
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ </div>
+ )}
+ </For>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:group
+function GroupDemo() {
+ return (
+ <div class="flex flex-col gap-6">
+ <For each={['sm', 'md', 'lg'] as const}>
+ {(size) => (
+ <div class="flex items-center gap-3">
+ <span class="w-8 font-mono text-xs text-ink-subtle">{size}</span>
+ <AvatarGroup size={size}>
+ <Avatar size={size}>
+ <Avatar.Image src={TEO} alt="Teo" />
+ </Avatar>
+ <Avatar size={size}>
+ <Avatar.Image src={TEO} alt="Teo" />
+ </Avatar>
+ <Avatar size={size}>
+ <Avatar.Image src={TEO} alt="Teo" />
+ </Avatar>
+ <AvatarGroup.Count size={size}>+3</AvatarGroup.Count>
+ </AvatarGroup>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:group-on-hover
+function GroupOnHoverDemo() {
+ return (
+ <div class="flex w-full max-w-sm flex-col gap-1">
+ <For each={['Design review', 'Launch checklist']}>
+ {(label) => (
+ <div class="flex items-center justify-between gap-3 rounded-md px-2 py-1.5 hover:bg-hover hover:[--avatar-group-separator:var(--color-hover)]">
+ <span class="text-sm text-ink">{label}</span>
+ <AvatarGroup size="sm">
+ <Avatar size="sm">
+ <Avatar.Image src={TEO} alt="Teo" />
+ </Avatar>
+ <Avatar size="sm">
+ <Avatar.Image src={TEO} alt="Teo" />
+ </Avatar>
+ </AvatarGroup>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Avatar',
+ category: 'Data Display',
+ description:
+ 'A circular representation of a person. Takes an image, initials, or an icon, and carries a 1px inset hairline so a photo edge reads cleanly against any surface.',
+ status: 'stable',
+ exports: ['Avatar', 'AvatarGroup'],
+ import: "import { Avatar, AvatarGroup } from '@ui';",
+ demos: [
+ {
+ id: 'sizes',
+ title: 'Sizes',
+ description:
+ '`sm` (16px) is the list and inline default, `md` (24px) suits rows with more room, `lg` (40px) is for profile headers. `fill` takes the size of its container — give that container the dimensions.',
+ render: SizesDemo,
+ },
+ {
+ id: 'image-and-fallback',
+ title: 'Image and fallback',
+ description:
+ 'Render both children together. `Avatar.Image` covers the fallback while it loads cleanly, and hides itself if the source 404s so the fallback shows through instead of the browser’s broken-image glyph. Fallback text scales with the avatar size automatically.',
+ render: ImageAndFallbackDemo,
+ },
+ {
+ id: 'edge',
+ title: 'Edge hairline',
+ description:
+ 'A 1px inset ring — black on dark surfaces, white on light ones — so the avatar settles into the page rather than being outlined against it. It is inset, so it never changes the avatar’s footprint. Switch themes in the toolbar to see it follow the surface, and it is off by default — pass `highlightEdge` to draw it.',
+ render: EdgeDemo,
+ },
+ {
+ id: 'shape',
+ title: 'Shape',
+ description:
+ '`rounded` is the default circle. `square` steps its corner radius with the size — `rounded-sm` at `sm` through `rounded-lg` at `lg` — so the corner stays proportional instead of looking sharp when small and soft when large.',
+ render: ShapeDemo,
+ },
+ {
+ id: 'group',
+ title: 'Avatar group',
+ description:
+ '`AvatarGroup` overlaps its children and adds a separator ring sized to match. `AvatarGroup.Count` closes out the overflow. Pass the same `size` to the group and to every child.',
+ render: GroupDemo,
+ },
+ {
+ id: 'group-on-hover',
+ title: 'Groups on a changing background',
+ description:
+ 'The separator ring defaults to `--color-surface`. When the row behind it changes color, point `--avatar-group-separator` at the new background so the ring keeps disappearing into it.',
+ render: GroupOnHoverDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Avatar.tsx b/apps/web/src/components/ui/components/Avatar.tsx
index ba07b56df1..2140df1730 100644
--- a/apps/web/src/components/ui/components/Avatar.tsx
+++ b/apps/web/src/components/ui/components/Avatar.tsx
@@ -1,56 +1,177 @@
-import { type JSX, type ParentProps, splitProps } from 'solid-js';
+import {
+ type Accessor,
+ createContext,
+ createSignal,
+ type JSX,
+ type ParentProps,
+ splitProps,
+ useContext,
+} from 'solid-js';
import { cn } from '../utils/classname';
+import { createVariants, type VariantProps } from '../utils/variants';
-export type AvatarSize = 'sm' | 'md' | 'lg' | 'fill';
+/**
+ * Corner radius for a square avatar, stepped to match its size. Circles do not
+ * vary, so this only covers `shape="square"`. Kept outside `avatarVariants`
+ * because it depends on two groups at once, which `createVariants` does not
+ * express.
+ */
+const SQUARE_RADIUS = {
+ sm: 'rounded-sm',
+ md: 'rounded-md',
+ lg: 'rounded-lg',
+ fill: 'rounded-lg',
+} as const;
+
+/** Canonical variant classes for the avatar root. */
+export const avatarVariants = createVariants(
+ cn(
+ 'group/avatar relative flex shrink-0 select-none items-center justify-center overflow-hidden',
+ 'bg-ink-extra-muted has-[img:not([data-failed])]:bg-transparent text-surface'
+ ),
+ {
+ size: {
+ sm: 'size-4 [&>svg]:size-2',
+ md: 'size-6 [&>svg]:size-3',
+ lg: 'size-10 [&>svg]:size-5',
+ fill: 'size-full @container [&>svg]:size-1/2',
+ },
+ shape: {
+ rounded: 'rounded-full',
+ // Square radius is size-dependent, so `avatarClasses` adds it.
+ square: '',
+ },
+ },
+ { size: 'sm', shape: 'rounded' }
+);
+
+/** Variant props inferred from the canonical avatar variant definition. */
+export type AvatarVariantProps = VariantProps<typeof avatarVariants>;
+export type AvatarSize = NonNullable<AvatarVariantProps['size']>;
+export type AvatarShape = NonNullable<AvatarVariantProps['shape']>;
+
+export type AvatarClassOptions = AvatarVariantProps & {
+ highlightEdge?: boolean;
+ class?: string;
+};
+
+/** Radius alone, for anything that has to trace the avatar's silhouette. */
+export function avatarShapeClasses(
+ size: AvatarSize = 'sm',
+ shape: AvatarShape = 'rounded'
+): string {
+ return shape === 'rounded' ? 'rounded-full' : SQUARE_RADIUS[size];
+}
+
+/** Returns the canonical classes for the avatar root. */
+export function avatarClasses(options: AvatarClassOptions = {}): string {
+ const {
+ size = 'sm',
+ shape = 'rounded',
+ highlightEdge = false,
+ class: className,
+ } = options;
+
+ return cn(
+ avatarVariants({ size, shape }),
+ shape === 'square' && SQUARE_RADIUS[size],
+ // Only the root draws the edge. `avatar-edge` is an outline, which paints
+ // after every descendant and is not clipped by `overflow`, so it lands on
+ // top of a covering image without the image needing one of its own.
+ highlightEdge && 'avatar-edge',
+ className
+ );
+}
+
+type AvatarContextValue = {
+ size: Accessor<AvatarSize>;
+ shape: Accessor<AvatarShape>;
+};
+
+const AvatarContext = createContext<AvatarContextValue>();
+
+/**
+ * Lets the slots pick up the root's size and shape without every call site
+ * repeating them. Falls back to the root's own defaults so a slot rendered
+ * outside an `Avatar` still looks right.
+ */
+function useAvatarContext(): AvatarContextValue {
+ return (
+ useContext(AvatarContext) ?? {
+ size: () => 'sm' as const,
+ shape: () => 'rounded' as const,
+ }
+ );
+}
export type AvatarProps = ParentProps<
JSX.HTMLAttributes<HTMLDivElement> & {
size?: AvatarSize;
+ /** `rounded` is a circle; `square` uses a radius stepped to the size. */
+ shape?: AvatarShape;
+ /** Draws the edge hairline. Off by default. */
+ highlightEdge?: boolean;
class?: string;
}
>;
-const AVATAR_SIZE_CLASSES = cn(
- 'size-4',
- 'data-[size=md]:size-6',
- 'data-[size=lg]:size-10',
- 'data-[size=fill]:size-full'
-);
-
-const AVATAR_SVG_CLASSES = cn(
- '[&>svg]:size-2',
- 'data-[size=md]:[&>svg]:size-3',
- 'data-[size=lg]:[&>svg]:size-5',
- 'data-[size=fill]:[&>svg]:size-1/2'
-);
-
/**
* Avatar root. Provides sizing and styling context for children.
* @example
- * <Avatar size="lg">
+ * <Avatar size="lg" shape="square" highlightEdge>
* <Avatar.Image src={url} alt="User" />
* <Avatar.Fallback>JD</Avatar.Fallback>
* </Avatar>
+ *
+ * @do Set `size` and `shape` on the `Avatar` root — the slots inherit them, so
+ * the props do not need repeating on `Avatar.Image`.
+ * @do Always render an `Avatar.Fallback` beside `Avatar.Image` — it is what
+ * shows when the source 404s.
+ * @do Give `Avatar.Image` an `alt`, or `alt=""` when the name is already
+ * beside it.
+ * @do Match the `size` on `AvatarGroup`, every child `Avatar`, and
+ * `AvatarGroup.Count`.
+ * @do Override `--avatar-group-separator` when the background behind a group
+ * changes.
+ * @dont Do not gate `Avatar.Image` behind a `Show` whose fallback is the
+ * `Avatar.Fallback` — that only covers a missing URL, not a broken one.
+ * Render both.
+ * @dont Do not add a `ring-*` class to an Avatar — that slot belongs to
+ * AvatarGroup's separator. The edge hairline is an outline for this reason.
+ * @dont Do not use `size="fill"` without giving the parent a size; the avatar
+ * collapses.
+ * @dont Do not hand-roll a circular image; the hairline and fallback behavior
+ * are the reason this component exists.
*/
export function Avatar(props: AvatarProps) {
- const [local, rest] = splitProps(props, ['size', 'class', 'children']);
+ const [local, rest] = splitProps(props, [
+ 'size',
+ 'shape',
+ 'highlightEdge',
+ 'class',
+ 'children',
+ ]);
const size = () => local.size ?? 'sm';
+ const shape = () => local.shape ?? 'rounded';
+ const highlightEdge = () => local.highlightEdge ?? false;
return (
- <div
- data-slot="avatar"
- data-size={size()}
- class={cn(
- 'group/avatar relative flex shrink-0 select-none items-center justify-center overflow-hidden rounded-full bg-ink-extra-muted has-[img]:bg-transparent text-surface',
- size() === 'fill' && '@container',
- AVATAR_SIZE_CLASSES,
- AVATAR_SVG_CLASSES,
- local.class
- )}
- {...rest}
- >
- {local.children}
- </div>
+ <AvatarContext.Provider value={{ size, shape }}>
+ <div
+ data-slot="avatar"
+ data-size={size()}
+ data-shape={shape()}
+ class={avatarClasses({
+ size: size(),
+ shape: shape(),
+ highlightEdge: highlightEdge(),
+ class: local.class,
+ })}
+ {...rest}
+ >
+ {local.children}
+ </div>
+ </AvatarContext.Provider>
);
}
@@ -58,18 +179,46 @@ type AvatarImageProps = {
src: string;
alt?: string;
class?: string;
+ /** Overrides the size inherited from the enclosing `Avatar`. */
+ size?: AvatarSize;
+ /** Overrides the shape inherited from the enclosing `Avatar`. */
+ shape?: AvatarShape;
onError?: JSX.EventHandler<HTMLImageElement, Event>;
ref?: (el: HTMLImageElement) => void;
};
/**
- * Avatar image. Fills the avatar container.
+ * Avatar image. Fills the avatar container, inheriting its size and shape
+ * unless given its own. The edge hairline stays on the root, whose outline
+ * paints over this image.
+ *
+ * A source that fails to load hides itself so the fallback shows through
+ * instead of the browser's broken-image glyph. The element stays mounted while
+ * hidden, so an `onError` handler that retries by reassigning
+ * `currentTarget.src` still works — a successful retry clears the failure.
*/
function AvatarImage(props: AvatarImageProps) {
+ const [failed, setFailed] = createSignal(false);
+ const context = useAvatarContext();
+
+ const size = () => props.size ?? context.size();
+ const shape = () => props.shape ?? context.shape();
+
return (
<img
- class={cn('size-full object-cover', props.class)}
- onError={props.onError}
+ class={cn(
+ 'absolute inset-0 size-full object-cover',
+ avatarShapeClasses(size(), shape()),
+ failed() && 'hidden',
+ props.class
+ )}
+ data-failed={failed() ? '' : undefined}
+ onError={(event) => {
+ // Caller first: it may swap in another URL, which onLoad then accepts.
+ props.onError?.(event);
+ setFailed(true);
+ }}
+ onLoad={() => setFailed(false)}
alt={props.alt}
ref={props.ref}
src={props.src}
@@ -77,23 +226,33 @@ function AvatarImage(props: AvatarImageProps) {
);
}
+/** Fallback text scale per avatar size. */
+const FALLBACK_TEXT = {
+ sm: 'text-[8px]',
+ md: 'text-xs',
+ lg: 'text-lg',
+ fill: 'text-[min(50cqw,3rem)]',
+} as const;
+
type AvatarFallbackProps = ParentProps<{
class?: string;
+ /** Overrides the size inherited from the enclosing `Avatar`. */
+ size?: AvatarSize;
}>;
/**
- * Avatar fallback content (typically initials or an icon).
- * Automatically sizes text based on parent avatar's data-size.
+ * Avatar fallback content (typically initials or an icon). Text scales with the
+ * size inherited from the enclosing `Avatar`.
*/
function AvatarFallback(props: AvatarFallbackProps) {
+ const context = useAvatarContext();
+ const size = () => props.size ?? context.size();
+
return (
<span
class={cn(
'leading-none select-none flex items-center justify-center',
- 'text-[8px]',
- 'group-data-[size=md]/avatar:text-xs',
- 'group-data-[size=lg]/avatar:text-lg',
- 'group-data-[size=fill]/avatar:text-[min(50cqw,3rem)]',
+ FALLBACK_TEXT[size()],
props.class
)}
>
diff --git a/apps/web/src/components/ui/components/Badge.docs.tsx b/apps/web/src/components/ui/components/Badge.docs.tsx
new file mode 100644
index 0000000000..4e3f1cfdfd
--- /dev/null
+++ b/apps/web/src/components/ui/components/Badge.docs.tsx
@@ -0,0 +1,106 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import CheckIcon from '@phosphor/check.svg';
+import { For } from 'solid-js';
+import { Badge, type BadgeVariant } from './Badge';
+
+const VARIANTS: BadgeVariant[] = ['ghost', 'outline'];
+
+// #region demo:variants
+function VariantsDemo() {
+ return (
+ <div class="flex w-full flex-col gap-3">
+ <For each={VARIANTS}>
+ {(variant) => (
+ <div class="flex items-center gap-3">
+ <span class="w-16 shrink-0 font-mono text-xs text-ink-subtle">
+ {variant}
+ </span>
+ <Badge variant={variant}>Badge</Badge>
+ <Badge variant={variant}>
+ <CheckIcon />
+ With icon
+ </Badge>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:sizes
+function SizesDemo() {
+ return (
+ <div class="flex flex-wrap items-end gap-3">
+ <For each={['sm', 'md', 'lg'] as const}>
+ {(size) => (
+ <div class="flex flex-col items-start gap-1.5">
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ <Badge variant="outline" size={size}>
+ Badge
+ </Badge>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:content
+function ContentDemo() {
+ return (
+ <div class="flex flex-wrap items-center gap-2">
+ <Badge variant="outline" size="sm">
+ <span aria-hidden="true" class="size-2 rounded-full bg-blue" />
+ design
+ </Badge>
+ <Badge variant="outline" size="sm">
+ <span aria-hidden="true" class="size-2 rounded-full bg-pink" />
+ tags-ux
+ </Badge>
+ <Badge variant="outline" size="sm">
+ <span class="inline-flex size-[1em] items-center justify-center rounded-full bg-green text-surface-4">
+ <CheckIcon aria-hidden="true" class="size-[0.65em]" />
+ </span>
+ Completed
+ <CaretDownIcon aria-hidden="true" />
+ </Badge>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Badge',
+ category: 'Data Display',
+ description:
+ 'A small, non-interactive label for status, counts, and tags. Shares Button’s size scale so a badge and a button of the same size sit on the same line cleanly.',
+ status: 'stable',
+ exports: ['Badge'],
+ import: "import { Badge } from '@ui';",
+ demos: [
+ {
+ id: 'variants',
+ title: 'Variants',
+ description:
+ '`ghost` when the surrounding container already provides separation, `outline` when the badge needs its own edge.',
+ render: VariantsDemo,
+ fill: true,
+ },
+ {
+ id: 'sizes',
+ title: 'Sizes',
+ description: 'Matches the Button `sm` / `md` / `lg` control sizes.',
+ render: SizesDemo,
+ },
+ {
+ id: 'content',
+ title: 'Composed content',
+ description:
+ 'Badges take arbitrary children — a color dot for a tag, a status glyph, a caret when the badge is the visible half of a menu trigger.',
+ render: ContentDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Badge.test.tsx b/apps/web/src/components/ui/components/Badge.test.tsx
deleted file mode 100644
index 5342540b83..0000000000
--- a/apps/web/src/components/ui/components/Badge.test.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it } from 'vitest';
-import { Badge, badgeClasses, badgeTriggerClasses } from './Badge';
-import { buttonClasses } from './Button';
-
-describe('badgeClasses', () => {
- it('provides ghost and outline variants', () => {
- expect(badgeClasses({ variant: 'ghost' })).toContain('bg-transparent');
- expect(badgeClasses({ variant: 'outline' })).toContain('border-edge-muted');
- });
-
- it.each(['sm', 'md', 'lg'] as const)(
- 'mirrors the %s Button size classes',
- (size) => {
- const badge = badgeClasses({ size }).split(' ');
- const button = buttonClasses({ size, noTouchResize: true }).split(' ');
-
- for (const sizeClass of badge) {
- if (
- sizeClass.startsWith('h-') ||
- sizeClass.startsWith('px-') ||
- sizeClass.startsWith('gap-') ||
- sizeClass.startsWith('text-') ||
- sizeClass.startsWith('[&>svg')
- ) {
- expect(button).toContain(sizeClass);
- }
- }
- }
- );
-
- it('merges caller overrides without allowing a non-pill shape', () => {
- const classes = badgeClasses({ size: 'md', class: 'h-5 rounded-md' });
-
- expect(classes).toContain('h-5');
- expect(classes).not.toContain('h-8');
- expect(classes).toContain('rounded-full');
- expect(classes).not.toContain('rounded-md');
- });
-
- it.each(['sm', 'md', 'lg'] as const)('is rounded-full at size %s', (size) => {
- expect(badgeClasses({ size })).toContain('rounded-full');
- });
-});
-
-describe('Badge', () => {
- afterEach(cleanup);
-
- it('renders a span with resolved variant and size metadata', () => {
- render(() => (
- <Badge variant="outline" size="sm" title="Status">
- Ready
- </Badge>
- ));
-
- const badge = screen.getByText('Ready');
- expect(badge.tagName).toBe('SPAN');
- expect(badge.getAttribute('title')).toBe('Status');
- expect(badge.dataset.slot).toBe('badge');
- expect(badge.dataset.variant).toBe('outline');
- expect(badge.dataset.size).toBe('sm');
- });
-});
-
-describe('badgeTriggerClasses', () => {
- it('adds Button interaction states without changing the pill shape', () => {
- const passive = badgeClasses({ variant: 'outline', size: 'sm' });
- const interactive = badgeTriggerClasses({
- variant: 'outline',
- size: 'sm',
- });
-
- expect(passive).not.toContain('not-disabled:hover:bg-hover');
- expect(interactive).toContain('not-disabled:hover:bg-hover');
- expect(interactive).toContain('not-disabled:active:bg-active');
- expect(interactive).toContain('focus-visible:ring-2');
- expect(interactive).toContain('rounded-full');
- expect(interactive).toContain('h-6');
- });
-});
diff --git a/apps/web/src/components/ui/components/Badge.tsx b/apps/web/src/components/ui/components/Badge.tsx
index dac9f5f035..55b52dea97 100644
--- a/apps/web/src/components/ui/components/Badge.tsx
+++ b/apps/web/src/components/ui/components/Badge.tsx
@@ -56,7 +56,16 @@ export function badgeTriggerClasses(options: BadgeClassOptions = {}): string {
);
}
-/** A non-interactive label with Button-aligned sizing. */
+/** A non-interactive label with Button-aligned sizing.
+ *
+ * @do Keep badge text to a word or two.
+ * @do Use `badgeTriggerClasses` when a badge needs to behave like a button.
+ * @do Use a palette color for identity (tags, calendars) and a semantic color
+ * for state.
+ * @dont Do not attach a click handler to `Badge` directly — it renders a
+ * `span`.
+ * @dont Do not use a badge where a Tooltip would carry the information better.
+ */
export function Badge(props: BadgeProps) {
const [local, others] = splitProps(props, ['variant', 'size', 'class']);
const variant = () => local.variant ?? 'ghost';
diff --git a/apps/web/src/components/ui/components/Button.docs.tsx b/apps/web/src/components/ui/components/Button.docs.tsx
new file mode 100644
index 0000000000..48b3966352
--- /dev/null
+++ b/apps/web/src/components/ui/components/Button.docs.tsx
@@ -0,0 +1,171 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import ArrowRightIcon from '@phosphor/arrow-right.svg';
+import PlusIcon from '@phosphor/plus.svg';
+import TrashIcon from '@phosphor/trash.svg';
+import { For } from 'solid-js';
+import { Button, type ButtonVariant } from './Button';
+import { ButtonGroup } from './ButtonGroup';
+
+const VARIANTS: ButtonVariant[] = [
+ 'ghost',
+ 'outline',
+ 'accent',
+ 'success',
+ 'danger',
+ 'strong',
+ 'cta',
+];
+
+// #region demo:variants
+function VariantsDemo() {
+ return (
+ <div class="flex w-full flex-col gap-3">
+ <For each={VARIANTS}>
+ {(variant) => (
+ <div class="flex items-center gap-3">
+ <span class="w-20 shrink-0 font-mono text-xs text-ink-subtle">
+ {variant}
+ </span>
+ <Button variant={variant}>Button</Button>
+ <Button variant={variant}>
+ <PlusIcon />
+ With icon
+ </Button>
+ <Button variant={variant} disabled>
+ Disabled
+ </Button>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:sizes
+function SizesDemo() {
+ return (
+ <div class="flex flex-wrap items-end gap-3">
+ <For each={['xs', 'sm', 'md', 'lg', 'xl'] as const}>
+ {(size) => (
+ <div class="flex flex-col items-start gap-1.5">
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ <Button variant="outline" size={size}>
+ Button
+ </Button>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:icon-only
+function IconOnlyDemo() {
+ return (
+ <div class="flex flex-wrap items-end gap-3">
+ <For each={['icon-xs', 'icon-sm', 'icon-md', 'icon-lg'] as const}>
+ {(size) => (
+ <div class="flex flex-col items-start gap-1.5">
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ <Button variant="outline" size={size} label="Add item">
+ <PlusIcon />
+ </Button>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:group
+function GroupDemo() {
+ return (
+ <div class="flex flex-col gap-4 items-center">
+ <For each={['sm', 'md', 'lg'] as const}>
+ {(size) => (
+ <ButtonGroup variant="outline" size={size}>
+ <Button>
+ <TrashIcon />
+ Delete
+ </Button>
+ <ButtonGroup.Divider />
+ <Button>Duplicate</Button>
+ <ButtonGroup.Divider />
+ <Button>
+ Next
+ <ArrowRightIcon />
+ </Button>
+ </ButtonGroup>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:tooltip
+function TooltipDemo() {
+ return (
+ <div class="flex flex-wrap items-center gap-3">
+ <Button variant="outline" label="Create document" shortcut="⌘N">
+ <PlusIcon />
+ </Button>
+ <Button variant="ghost" tooltip="Permanently deletes the selection">
+ <TrashIcon />
+ Delete
+ </Button>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Button',
+ category: 'Actions',
+ description:
+ 'The standard way to trigger an action. Variant carries emphasis, size carries density, and both are shared with Badge so button-like elements line up.',
+ status: 'stable',
+ exports: ['Button', 'ButtonGroup'],
+ import: "import { Button, ButtonGroup } from '@ui';",
+ demos: [
+ {
+ id: 'variants',
+ title: 'Variants',
+ description:
+ '`ghost` for low-emphasis actions in dense chrome, `outline` for standard actions, `accent` for the primary action in a group, `cta` for the single most important action on a screen. `danger` is reserved for destructive work.',
+ render: VariantsDemo,
+ fill: true,
+ },
+ {
+ id: 'sizes',
+ title: 'Sizes',
+ description:
+ '`md` is the default. `sm` suits toolbars and inline chrome; `lg` and `xl` are for marketing and empty-state surfaces.',
+ render: SizesDemo,
+ },
+ {
+ id: 'icon-only',
+ title: 'Icon-only',
+ description:
+ 'Use an `icon-*` size for square buttons. `label` is required — it names the button for screen readers and becomes its tooltip.',
+ render: IconOnlyDemo,
+ },
+ {
+ id: 'group',
+ title: 'Button group',
+ description:
+ '`ButtonGroup` joins related actions into a single segmented control. Add `ButtonGroup.Divider` between segments; the group owns the shared border and corner radius.',
+ render: GroupDemo,
+ },
+ {
+ id: 'tooltip',
+ title: 'Tooltips and shortcuts',
+ description:
+ '`label` doubles as the tooltip; `tooltip` overrides it when the accessible name and the hint should differ. `hotkey` renders a registered shortcut, `shortcut` a raw string.',
+ render: TooltipDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Button.test.tsx b/apps/web/src/components/ui/components/Button.test.tsx
deleted file mode 100644
index 941bd73511..0000000000
--- a/apps/web/src/components/ui/components/Button.test.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it } from 'vitest';
-import { Button, buttonClasses, buttonVariants } from './Button';
-import { ButtonGroup } from './ButtonGroup';
-
-describe('buttonClasses', () => {
- it('exposes the underlying variant helper', () => {
- const classes = buttonVariants({ variant: 'outline', size: 'sm' });
-
- expect(classes).toContain('border-edge-muted');
- expect(classes).toContain('h-6');
- });
-
- it('returns reusable variant and size classes with caller overrides', () => {
- const classes = buttonClasses({
- variant: 'outline',
- size: 'icon-sm',
- noTouchResize: true,
- class: 'size-8 rounded-full',
- });
-
- expect(classes).toContain('border-edge-muted');
- expect(classes).toContain('size-8');
- expect(classes).not.toContain('size-6');
- expect(classes).toContain('rounded-full');
- expect(classes).not.toContain('touch:min-h-9');
- });
-
- it('includes the complete CTA contrast treatment', () => {
- const classes = buttonClasses({ variant: 'cta' });
-
- expect(classes).toContain('text-accent-contrast');
- expect(classes).toContain(
- '[--color-edge:var(--color-accent-contrast-muted)]'
- );
- });
-
- it('includes the inverted strong treatment', () => {
- const classes = buttonClasses({ variant: 'strong' });
-
- expect(classes).toContain('bg-ink');
- expect(classes).toContain('text-surface-4');
- expect(classes).toContain('focus-visible:ring-surface-4/70');
- });
-
- it.each([
- ['sm', 'h-6', 'px-2', 'text-xs', 'size-3'],
- ['md', 'h-8', 'px-2', 'text-sm', 'size-3.5'],
- ['lg', 'h-9', 'px-3', 'text-base', 'size-[1em]'],
- ['xl', 'h-12', 'px-4', 'text-base', 'size-5'],
- ] as const)(
- 'gives %s buttons the intended height, padding, text size, and icon size',
- (size, heightClass, paddingClass, textClass, iconClass) => {
- const classes = buttonClasses({ size });
-
- expect(classes).toContain(heightClass);
- expect(classes).toContain(paddingClass);
- expect(classes).toContain(textClass);
- expect(classes).toContain(`[&>svg:not([class*='size-'])]:${iconClass}`);
- expect(classes).not.toContain('aspect-square');
- expect(classes).not.toContain('p-0');
- }
- );
-
- it('applies icon-only geometry explicitly without changing the size', () => {
- const classes = buttonClasses({ size: 'md', square: true });
-
- expect(classes).toContain('h-8');
- expect(classes).toContain('aspect-square');
- expect(classes).toContain('p-0');
- expect(classes).not.toContain('px-2');
- });
-
- it('keeps large-button horizontal padding restrained', () => {
- const classes = buttonClasses({ size: 'lg' });
-
- expect(classes).toContain('px-3');
- expect(classes).not.toContain('px-6');
- });
-});
-
-describe('Button', () => {
- afterEach(cleanup);
-
- it('uses label as its accessible name and default tooltip content', () => {
- render(() => (
- <Button size="icon-sm" label="Close">
- <svg aria-hidden="true" />
- </Button>
- ));
-
- expect(screen.getByRole('button', { name: 'Close' })).toBeTruthy();
- });
-
- it('uses an icon button tooltip as an accessible-name fallback', () => {
- render(() => (
- <Button size="icon-sm" tooltip="Search">
- <svg aria-hidden="true" />
- </Button>
- ));
-
- expect(screen.getByRole('button', { name: 'Search' })).toBeTruthy();
- });
-
- it('uses a square button tooltip as an accessible-name fallback', () => {
- render(() => (
- <Button size="sm" square tooltip="Search">
- <svg aria-hidden="true" />
- </Button>
- ));
-
- expect(screen.getByRole('button', { name: 'Search' })).toBeTruthy();
- });
-
- it('does not replace visible text with tooltip content', () => {
- render(() => <Button tooltip="Save the current draft">Save</Button>);
-
- expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy();
- });
-
- it('does not leak custom props and preserves CTA inline styles', () => {
- render(() => (
- <Button variant="cta" noTouchResize style={{ color: 'rgb(1, 2, 3)' }}>
- Continue
- </Button>
- ));
-
- const button = screen.getByRole('button', { name: 'Continue' });
- expect(button.hasAttribute('notouchresize')).toBe(false);
- expect(button.style.color).toBe('rgb(1, 2, 3)');
- });
-
- it('exposes its resolved variant and size as data attributes', () => {
- render(() => (
- <ButtonGroup variant="accent" size="icon-xs">
- <Button label="Pinned">
- <svg aria-hidden="true" />
- </Button>
- </ButtonGroup>
- ));
-
- const button = screen.getByRole('button', { name: 'Pinned' });
- expect(button.dataset.slot).toBe('button');
- expect(button.dataset.variant).toBe('accent');
- expect(button.dataset.size).toBe('icon-xs');
- });
-});
diff --git a/apps/web/src/components/ui/components/Button.tsx b/apps/web/src/components/ui/components/Button.tsx
index 0f6ad01c4e..35b7451e4e 100644
--- a/apps/web/src/components/ui/components/Button.tsx
+++ b/apps/web/src/components/ui/components/Button.tsx
@@ -24,7 +24,7 @@ const BUTTON_TOUCH_STYLES =
export const buttonVariants = createVariants(
cn(
'relative inline-flex shrink-0 items-center justify-center whitespace-nowrap text-sm',
- 'rounded-md border border-transparent font-medium outline-none select-none transition-colors',
+ 'rounded-md border-1 border-transparent font-medium outline-none select-none transition-colors',
'data-disabled:cursor-not-allowed data-disabled:opacity-30',
'[&_svg]:pointer-events-none [&_svg]:shrink-0'
),
@@ -136,6 +136,19 @@ function isIconSize(size: ButtonSize): boolean {
return size.startsWith('icon-');
}
+/**
+ * The standard way to trigger an action. `variant` carries emphasis and
+ * `size` carries density; both are shared with Badge so button-like elements
+ * line up.
+ *
+ * @do Give every screen at most one `cta` or `accent` button.
+ * @do Always set `label` on icon-only buttons; it is the accessible name.
+ * @do Use `danger` only for destructive actions, paired with a confirmation.
+ * @dont Do not restyle a button with utility classes when a variant already
+ * covers it.
+ * @dont Do not use a Button for navigation that should be a link.
+ * @dont Do not put two `danger` buttons next to each other.
+ */
export const Button = (props: ButtonProps) => {
const [local, others] = splitProps(props, [
'tooltipPlacement',
diff --git a/apps/web/src/components/ui/components/ButtonGroup.tsx b/apps/web/src/components/ui/components/ButtonGroup.tsx
index 8a8bdea6b4..bdd3ff80db 100644
--- a/apps/web/src/components/ui/components/ButtonGroup.tsx
+++ b/apps/web/src/components/ui/components/ButtonGroup.tsx
@@ -72,14 +72,26 @@ const groupVerticalSize: Record<ButtonSize, string> = {
'icon-sm': 'w-6',
};
+const groupRadius: Record<ButtonSize, string> = {
+ xs: 'rounded-md',
+ 'icon-xs': 'rounded-md',
+ sm: 'rounded-md',
+ 'icon-sm': 'rounded-md',
+ md: 'rounded-md',
+ 'icon-md': 'rounded-md',
+ lg: 'rounded-lg',
+ 'icon-lg': 'rounded-md',
+ xl: 'rounded-lg',
+};
+
export const ButtonGroup = (props: ButtonGroupProps) => {
const orientation = () => props.orientation ?? 'horizontal';
const variant = () => props.variant ?? 'ghost';
+ const size = () => props.size ?? 'md';
const sizeClass = () => {
- if (!props.size) return '';
return orientation() === 'horizontal'
- ? groupHorizontalSize[props.size]
- : groupVerticalSize[props.size];
+ ? groupHorizontalSize[size()]
+ : groupVerticalSize[size()];
};
const ctx: ButtonGroupContextValue = {
@@ -87,7 +99,7 @@ export const ButtonGroup = (props: ButtonGroupProps) => {
return props.variant;
},
get size() {
- return props.size;
+ return size();
},
get orientation() {
return orientation();
@@ -100,14 +112,18 @@ export const ButtonGroup = (props: ButtonGroupProps) => {
<div
data-slot="button-group"
data-orientation={orientation()}
+ data-size={size()}
class={cn(
'data-[orientation=horizontal]:flex-row items-center',
'data-[orientation=vertical]:flex-col justify-center',
- 'inline-flex overflow-hidden rounded-sm',
+ 'inline-flex overflow-hidden',
/* strip per-button rounding + borders so the group owns the frame */
'**:data-button:rounded-none',
'**:data-button:border-0',
groupVariantStyles[variant()],
+ variant() !== 'ghost' &&
+ 'has-[[data-slot=input-group-control]:focus-visible]:border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] has-[[data-slot=input-group-control]:focus-visible]:ring-2 has-[[data-slot=input-group-control]:focus-visible]:ring-edge-muted',
+ groupRadius[size()],
sizeClass(),
props.class
)}
diff --git a/apps/web/src/components/ui/components/Checkbox.docs.tsx b/apps/web/src/components/ui/components/Checkbox.docs.tsx
new file mode 100644
index 0000000000..a13cb89579
--- /dev/null
+++ b/apps/web/src/components/ui/components/Checkbox.docs.tsx
@@ -0,0 +1,125 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { createSignal, For } from 'solid-js';
+import { Checkbox, InlineCheckbox, SingleSelectCheck } from './Checkbox';
+
+// #region demo:basic
+function BasicDemo() {
+ const [checked, setChecked] = createSignal(true);
+
+ return (
+ <div class="flex flex-col gap-3">
+ <Checkbox checked={checked()} onChange={setChecked}>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink">
+ Notify me about replies
+ </Checkbox.Label>
+ </Checkbox>
+ <Checkbox defaultChecked={false}>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink">Unchecked</Checkbox.Label>
+ </Checkbox>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:states
+function StatesDemo() {
+ return (
+ <div class="flex flex-col gap-3">
+ <Checkbox indeterminate>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink">Indeterminate</Checkbox.Label>
+ </Checkbox>
+ <Checkbox disabled defaultChecked>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink-disabled">
+ Disabled, checked
+ </Checkbox.Label>
+ </Checkbox>
+ <Checkbox disabled>
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink-disabled">
+ Disabled
+ </Checkbox.Label>
+ </Checkbox>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:list-affordances
+function ListAffordancesDemo() {
+ const [selected, setSelected] = createSignal('Inbox');
+ const rows = ['Inbox', 'Drafts', 'Sent'];
+
+ return (
+ <div class="flex w-full max-w-sm flex-col gap-4">
+ <div class="flex flex-col">
+ <span class="mb-1 font-mono text-xs text-ink-subtle">
+ SingleSelectCheck
+ </span>
+ <For each={rows}>
+ {(row) => (
+ <button
+ type="button"
+ class="flex items-center justify-between rounded-sm px-2 py-1.5 text-sm text-ink hover:bg-hover"
+ onClick={() => setSelected(row)}
+ >
+ {row}
+ <SingleSelectCheck active={selected() === row} />
+ </button>
+ )}
+ </For>
+ </div>
+
+ <div class="flex flex-col">
+ <span class="mb-1 font-mono text-xs text-ink-subtle">
+ InlineCheckbox
+ </span>
+ <For each={rows}>
+ {(row) => (
+ <div class="flex items-center gap-2 rounded-sm px-2 py-1.5 text-sm text-ink">
+ <InlineCheckbox checked={row !== 'Sent'} />
+ {row}
+ </div>
+ )}
+ </For>
+ </div>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Checkbox',
+ category: 'Inputs',
+ description:
+ 'A Kobalte checkbox with the app’s control styling. Composed from slots, so the label, description, and error message are yours to place.',
+ status: 'stable',
+ exports: ['Checkbox', 'InlineCheckbox', 'SingleSelectCheck'],
+ import: "import { Checkbox, InlineCheckbox, SingleSelectCheck } from '@ui';",
+ demos: [
+ {
+ id: 'basic',
+ title: 'Basic',
+ description:
+ 'Pass `checked` and `onChange` for a controlled checkbox, or `defaultChecked` to let it manage itself. `Checkbox.Control` renders the hidden input as well as the box.',
+ render: BasicDemo,
+ },
+ {
+ id: 'states',
+ title: 'States',
+ description:
+ '`indeterminate` shows a dash instead of a check — use it for a parent whose children are partially selected.',
+ render: StatesDemo,
+ },
+ {
+ id: 'list-affordances',
+ title: 'List affordances',
+ description:
+ 'Two visual-only helpers for rows that are themselves the hit target: `SingleSelectCheck` for pick-one menus, `InlineCheckbox` for multi-select lists. Neither handles input — the row does.',
+ render: ListAffordancesDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Checkbox.tsx b/apps/web/src/components/ui/components/Checkbox.tsx
index 588eb4cb16..d723e5f11e 100644
--- a/apps/web/src/components/ui/components/Checkbox.tsx
+++ b/apps/web/src/components/ui/components/Checkbox.tsx
@@ -27,7 +27,7 @@ type LabelProps = ComponentProps<typeof KobalteCheckbox.Label>;
const CONTROL_CLASS = cn(
'inline-flex items-center justify-center size-4 shrink-0 rounded-sm text-surface',
- 'bg-surface border border-edge',
+ 'bg-surface border-1 border-edge',
'data-checked:bg-accent data-checked:border-accent',
'data-indeterminate:bg-accent data-indeterminate:border-accent',
'data-disabled:opacity-50 data-disabled:cursor-not-allowed',
@@ -69,6 +69,19 @@ function CheckboxLabel(props: LabelProps) {
return <KobalteCheckbox.Label class={cn(local.class)} {...rest} />;
}
+/**
+ * A Kobalte checkbox with the app's control styling, composed from slots so
+ * the label, description, and error message are yours to place.
+ *
+ * @do Always render a `Checkbox.Label`, even when the visible text sits
+ * elsewhere.
+ * @do Use `indeterminate` on a select-all that only covers part of its group.
+ * @do Use `InlineCheckbox` when the whole row is already clickable.
+ * @dont Do not use a checkbox for an immediate action — that is a ToggleSwitch
+ * or a Button.
+ * @dont Do not add `Checkbox.Input` yourself; `Checkbox.Control` already
+ * renders one.
+ */
export const Checkbox = Object.assign(
(props: CheckboxProps) => {
const [local, rest] = splitProps(props, ['class']);
@@ -110,7 +123,7 @@ export const InlineCheckbox = (props: { checked: boolean }) => (
'inline-flex items-center justify-center size-3.5 shrink-0 rounded-sm',
props.checked
? 'bg-accent text-surface'
- : 'bg-transparent border border-edge-muted text-transparent'
+ : 'bg-transparent border-1 border-edge-muted text-transparent'
)}
>
<CheckIcon class="size-2.5" />
diff --git a/apps/web/src/components/ui/components/ImperativeDialog.test.tsx b/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
deleted file mode 100644
index cf43334828..0000000000
--- a/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
+++ /dev/null
@@ -1,250 +0,0 @@
-import { cleanup, render, screen, waitFor } from '@solidjs/testing-library';
-import userEvent from '@testing-library/user-event';
-import {
- type Component,
- createContext,
- createSignal,
- Show,
- useContext,
-} from 'solid-js';
-import { createStore } from 'solid-js/store';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { Dialog } from './Dialog';
-import {
- type ImperativeDialogController,
- ImperativeDialogHost,
- type ManagedDialogProps,
- openDialog,
- useImperativeDialog,
-} from './ImperativeDialog';
-
-function ManagedTestDialog(
- props: ManagedDialogProps & {
- label: string;
- }
-) {
- return (
- <Dialog open={props.open} onOpenChange={props.onOpenChange}>
- <div>
- <Dialog.Title>{props.label}</Dialog.Title>
- <button type="button" onClick={() => props.onOpenChange(false)}>
- Dismiss {props.label}
- </button>
- </div>
- </Dialog>
- );
-}
-
-function PlainManagedDialog(
- props: ManagedDialogProps & {
- label: string;
- }
-) {
- return (
- <div data-testid="managed-dialog" data-open={String(props.open)}>
- <span>{props.label}</span>
- <button type="button" onClick={() => props.onOpenChange(false)}>
- Dismiss {props.label}
- </button>
- </div>
- );
-}
-
-function typeAssertions() {
- openDialog(ManagedTestDialog, { label: 'valid' });
- openDialog(ManagedTestDialog, () => ({ label: 'reactive' }));
-
- // @ts-expect-error label is required by the supplied dialog component.
- openDialog(ManagedTestDialog, {});
- openDialog(ManagedTestDialog, {
- label: 'invalid',
- // @ts-expect-error managed props cannot be supplied by callers.
- open: false,
- // @ts-expect-error managed props cannot be supplied by callers.
- onOpenChange: () => undefined,
- });
-}
-void typeAssertions;
-
-function hookTypeAssertions() {
- const dialog = useImperativeDialog(ManagedTestDialog);
- dialog.open({ label: 'valid' });
- dialog.open(() => ({ label: 'reactive' }));
-
- // @ts-expect-error label is required by the supplied dialog component.
- dialog.open({});
-}
-void hookTypeAssertions;
-
-beforeEach(() => {
- window.scrollTo = vi.fn();
- if (!globalThis.CSS) {
- Object.defineProperty(globalThis, 'CSS', {
- configurable: true,
- value: { escape: (value: string) => value },
- });
- }
-});
-
-afterEach(() => cleanup());
-
-describe('openDialog', () => {
- it('renders a complete dialog and reports dismissals', async () => {
- render(() => <ImperativeDialogHost />);
- const handle = openDialog(ManagedTestDialog, { label: 'Complete dialog' });
-
- await screen.findByText('Complete dialog');
- expect(handle.isOpen()).toBe(true);
-
- await userEvent.click(
- screen.getByRole('button', { name: 'Dismiss Complete dialog' })
- );
-
- await expect(handle.closed).resolves.toEqual({
- id: handle.id,
- reason: 'dismissed',
- });
- expect(handle.isOpen()).toBe(false);
- });
-
- it('keeps accessor and store props reactive', async () => {
- render(() => <ImperativeDialogHost />);
- const [accessorLabel, setAccessorLabel] = createSignal('Accessor one');
- const [store, setStore] = createStore({ label: 'Store one' });
-
- const accessorHandle = openDialog(PlainManagedDialog, () => ({
- label: accessorLabel(),
- }));
- const storeHandle = openDialog(PlainManagedDialog, store);
-
- await screen.findByText('Accessor one');
- expect(screen.getByText('Store one')).toBeTruthy();
-
- setAccessorLabel('Accessor two');
- setStore('label', 'Store two');
-
- expect(await screen.findByText('Accessor two')).toBeTruthy();
- expect(screen.getByText('Store two')).toBeTruthy();
-
- accessorHandle.close();
- storeHandle.close();
- });
-
- it('dismisses stacked dialogs in LIFO order with idempotent handles', async () => {
- render(() => <ImperativeDialogHost />);
- const first = openDialog(ManagedTestDialog, { label: 'First stacked' });
- const second = openDialog(ManagedTestDialog, { label: 'Second stacked' });
- await screen.findByText('Second stacked');
-
- await userEvent.keyboard('{Escape}');
-
- await expect(second.closed).resolves.toMatchObject({ reason: 'dismissed' });
- expect(second.close()).toBe(false);
- expect(first.isOpen()).toBe(true);
- expect(screen.getByText('First stacked')).toBeTruthy();
-
- expect(first.close()).toBe(true);
- expect(first.close()).toBe(false);
- await expect(first.closed).resolves.toEqual({
- id: first.id,
- reason: 'programmatic',
- });
- });
-
- it('uses one owner-scoped slot and replaces its current dialog', async () => {
- const LocalContext = createContext('host');
- const [showOwner, setShowOwner] = createSignal(true);
- let controller!: ImperativeDialogController<
- ManagedDialogProps & { label: string }
- >;
-
- const ContextDialog: Component<ManagedDialogProps & { label: string }> = (
- props
- ) => (
- <div>
- {useContext(LocalContext)} {props.label}
- </div>
- );
-
- function OwnerScopedController() {
- controller = useImperativeDialog(ContextDialog);
- return null;
- }
-
- render(() => (
- <>
- <Show when={showOwner()}>
- <LocalContext.Provider value="caller-local">
- <OwnerScopedController />
- </LocalContext.Provider>
- </Show>
- <ImperativeDialogHost />
- </>
- ));
-
- const first = controller.open({ label: 'first' });
- expect(await screen.findByText('caller-local first')).toBeTruthy();
-
- const second = controller.open({ label: 'second' });
- await expect(first.closed).resolves.toMatchObject({ reason: 'replaced' });
- expect(controller.handle()).toBe(second);
- expect(controller.isOpen()).toBe(true);
- expect(await screen.findByText('caller-local second')).toBeTruthy();
-
- expect(controller.close()).toBe(true);
- await expect(second.closed).resolves.toMatchObject({
- reason: 'programmatic',
- });
- expect(controller.handle()).toBeUndefined();
- expect(controller.isOpen()).toBe(false);
-
- const third = controller.open({ label: 'third' });
- expect(await screen.findByText('caller-local third')).toBeTruthy();
- setShowOwner(false);
- await expect(third.closed).resolves.toMatchObject({
- reason: 'owner-disposed',
- });
- expect(screen.queryByText('caller-local third')).toBeNull();
- });
-
- it('returns focus only after the final managed dialog closes', async () => {
- const trigger = document.createElement('button');
- document.body.append(trigger);
- trigger.focus();
-
- render(() => <ImperativeDialogHost />);
- const first = openDialog(PlainManagedDialog, {
- label: 'First focus owner',
- });
- const second = openDialog(PlainManagedDialog, {
- label: 'Second focus owner',
- });
- await screen.findByText('Second focus owner');
-
- first.close();
- expect(document.activeElement).toBe(trigger);
-
- const dialogButton = screen.getByRole('button', {
- name: 'Dismiss Second focus owner',
- });
- dialogButton.focus();
- second.close();
-
- await waitFor(() => expect(document.activeElement).toBe(trigger));
- trigger.remove();
- });
-
- it('finalizes active entries when the host is disposed', async () => {
- const rendered = render(() => <ImperativeDialogHost />);
- const handle = openDialog(PlainManagedDialog, { label: 'Host owned' });
- await screen.findByText('Host owned');
-
- rendered.unmount();
-
- await expect(handle.closed).resolves.toEqual({
- id: handle.id,
- reason: 'host-disposed',
- });
- expect(handle.isOpen()).toBe(false);
- });
-});
diff --git a/apps/web/src/components/ui/components/Input.docs.tsx b/apps/web/src/components/ui/components/Input.docs.tsx
new file mode 100644
index 0000000000..e450a9e3d8
--- /dev/null
+++ b/apps/web/src/components/ui/components/Input.docs.tsx
@@ -0,0 +1,79 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { For } from 'solid-js';
+import { Input, type InputSize } from './Input';
+
+// #region demo:basic
+function BasicDemo() {
+ return (
+ <Input
+ class="max-w-sm"
+ type="email"
+ placeholder="[email protected]"
+ aria-label="Email address"
+ />
+ );
+}
+// #endregion
+
+// #region demo:sizes
+function SizesDemo() {
+ const sizes: InputSize[] = ['xs', 'sm', 'md', 'lg', 'xl'];
+
+ return (
+ <div class="flex w-full max-w-sm flex-col gap-3">
+ <For each={sizes}>
+ {(size) => (
+ <div class="grid grid-cols-[2rem_1fr] items-center gap-3">
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ <Input size={size} placeholder={`${size} input`} />
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:variants
+function VariantsDemo() {
+ return (
+ <div class="flex w-full max-w-sm flex-col gap-3 rounded-md bg-inset p-3">
+ <Input variant="outline" placeholder="Outline" />
+ <Input variant="bare" placeholder="Bare" />
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Input',
+ category: 'Inputs',
+ description:
+ 'A thin shadcn-style native input with semantic tokens and Button-compatible visual sizes. Compose icons and actions with InputGroup.',
+ status: 'stable',
+ exports: ['Input'],
+ import: "import { Input } from '@ui';",
+ demos: [
+ {
+ id: 'basic',
+ title: 'Basic',
+ description:
+ 'All normal native input props are forwarded. The default visual size is `md` and the default variant is `outline`.',
+ render: BasicDemo,
+ },
+ {
+ id: 'sizes',
+ title: 'Button sizes',
+ description:
+ 'String sizes share heights, padding, and typography with text Buttons. A numeric `size` remains the native HTML attribute.',
+ render: SizesDemo,
+ },
+ {
+ id: 'variants',
+ title: 'Variants',
+ description:
+ '`bare` stays transparent without hover or focus chrome. It is intended for a composed parent such as InputGroup.',
+ render: VariantsDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Input.tsx b/apps/web/src/components/ui/components/Input.tsx
new file mode 100644
index 0000000000..c46dd4c63f
--- /dev/null
+++ b/apps/web/src/components/ui/components/Input.tsx
@@ -0,0 +1,101 @@
+import type { ComponentProps } from 'solid-js';
+import { splitProps } from 'solid-js';
+import { cn } from '../utils/classname';
+import { createVariants, type VariantProps } from '../utils/variants';
+import type { ButtonSize } from './Button';
+
+type NativeInputSize = number;
+
+/** Text-bearing Button sizes that also make sense for an input. */
+export type InputSize = Exclude<ButtonSize, `icon-${string}`>;
+
+const INPUT_SIZE_VARIANTS: Record<InputSize, string> = {
+ xs: 'h-5 px-1 text-xs',
+ sm: 'h-6 px-2 text-xs',
+ md: 'h-8 px-2 text-sm',
+ lg: 'h-9 px-3 text-base',
+ xl: 'h-12 px-4 text-base',
+};
+
+/** Shared focus treatment for outlined text-entry controls. */
+export const inputOutlineFocusClasses =
+ 'focus-visible:border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] focus-visible:ring-2 focus-visible:ring-edge-muted';
+
+/** Canonical visual variants for standalone inputs. */
+export const inputVariants = createVariants(
+ cn(
+ 'w-full min-w-0 rounded-md border text-ink caret-current outline-none transition-[background-color,border-color,box-shadow]',
+ 'file:inline-flex file:border-0 file:bg-transparent file:text-[inherit] file:font-medium file:text-ink',
+ 'placeholder:text-ink-placeholder',
+ 'aria-invalid:border-failure aria-invalid:ring-2 aria-invalid:ring-failure/20',
+ 'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50'
+ ),
+ {
+ variant: {
+ outline: cn('border-edge-muted bg-input', inputOutlineFocusClasses),
+ bare: 'border-transparent bg-transparent',
+ },
+ size: INPUT_SIZE_VARIANTS,
+ },
+ {
+ variant: 'outline',
+ size: 'md',
+ }
+);
+
+export type InputVariantProps = VariantProps<typeof inputVariants>;
+export type InputVariant = NonNullable<InputVariantProps['variant']>;
+
+export type InputClassOptions = {
+ variant?: InputVariant;
+ size?: InputSize;
+ class?: string;
+};
+
+/** Returns canonical classes for a native input. */
+export function inputClasses(options: InputClassOptions = {}): string {
+ return cn(
+ inputVariants({ variant: options.variant, size: options.size }),
+ options.class
+ );
+}
+
+export type InputProps = Omit<ComponentProps<'input'>, 'size'> & {
+ /** A Button-compatible visual size, or the native numeric HTML input size. */
+ size?: InputSize | NativeInputSize;
+ variant?: InputVariant;
+};
+
+/**
+ * A thin shadcn-style native input using the app's tokens and control sizes.
+ *
+ * @do Use `TextField.Input` when the control needs a visible label,
+ * description, validation message, or controlled field value.
+ * @do Use `InputGroup` when the input needs an icon, clear action, or adjacent
+ * button inside a shared frame.
+ * @dont Do not use `variant="bare"` unless a composed parent owns the control
+ * boundary and focus treatment.
+ */
+export function Input(props: InputProps) {
+ const [local, rest] = splitProps(props, ['class', 'size', 'variant']);
+ const visualSize = (): InputSize =>
+ typeof local.size === 'string' ? local.size : 'md';
+ const nativeSize = () =>
+ typeof local.size === 'number' ? local.size : undefined;
+
+ return (
+ <input
+ data-input
+ data-slot="input"
+ data-variant={local.variant ?? 'outline'}
+ data-size={visualSize()}
+ size={nativeSize()}
+ class={inputClasses({
+ variant: local.variant,
+ size: visualSize(),
+ class: local.class,
+ })}
+ {...rest}
+ />
+ );
+}
diff --git a/apps/web/src/components/ui/components/InputGroup.docs.tsx b/apps/web/src/components/ui/components/InputGroup.docs.tsx
new file mode 100644
index 0000000000..2eabef1cff
--- /dev/null
+++ b/apps/web/src/components/ui/components/InputGroup.docs.tsx
@@ -0,0 +1,125 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import ArrowRightIcon from '@phosphor/arrow-right.svg';
+import CheckCircleIcon from '@phosphor/check-circle.svg';
+import EnvelopeIcon from '@phosphor/envelope.svg';
+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
+import { createSignal } from 'solid-js';
+import { Button } from './Button';
+import { ButtonGroup } from './ButtonGroup';
+import { InputGroup } from './InputGroup';
+
+// #region demo:search
+function SearchDemo() {
+ const [query, setQuery] = createSignal('Quarterly plan');
+
+ return (
+ <InputGroup class="max-w-sm">
+ <InputGroup.Input
+ type="search"
+ value={query()}
+ onInput={(event) => setQuery(event.currentTarget.value)}
+ placeholder="Search documents"
+ aria-label="Search documents"
+ />
+ <InputGroup.Addon align="inline-start">
+ <MagnifyingGlassIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ <InputGroup.Addon align="inline-end">
+ <InputGroup.ClearButton />
+ </InputGroup.Addon>
+ </InputGroup>
+ );
+}
+// #endregion
+
+// #region demo:addons
+function AddonsDemo() {
+ return (
+ <div class="flex w-full max-w-sm flex-col gap-3">
+ <InputGroup>
+ <InputGroup.Input
+ type="email"
+ aria-label="Team email"
+ />
+ <InputGroup.Addon align="inline-start">
+ <EnvelopeIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ <InputGroup.Addon align="inline-end">
+ <CheckCircleIcon class="text-success" aria-hidden="true" />
+ </InputGroup.Addon>
+ </InputGroup>
+
+ <InputGroup>
+ <InputGroup.Addon align="inline-start">https://</InputGroup.Addon>
+ <InputGroup.Input placeholder="macro.com" aria-label="Website" />
+ <InputGroup.Addon align="inline-end">
+ <InputGroup.Button aria-label="Open website" square>
+ <ArrowRightIcon />
+ </InputGroup.Button>
+ </InputGroup.Addon>
+ </InputGroup>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:button-group
+function ButtonGroupDemo() {
+ return (
+ <ButtonGroup
+ variant="outline"
+ size="md"
+ class="w-full max-w-sm"
+ aria-label="Search documents"
+ >
+ <InputGroup>
+ <InputGroup.Input
+ placeholder="Search documents"
+ aria-label="Search query"
+ />
+ <InputGroup.Addon align="inline-start">
+ <MagnifyingGlassIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ </InputGroup>
+ <ButtonGroup.Divider />
+ <Button aria-label="Submit search" square>
+ <ArrowRightIcon />
+ </Button>
+ </ButtonGroup>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'InputGroup',
+ category: 'Inputs',
+ description:
+ 'Composes an Input with decorative addons, standard Buttons, and a reactive clear action inside one shared frame.',
+ status: 'stable',
+ exports: ['InputGroup'],
+ import: "import { InputGroup } from '@ui';",
+ demos: [
+ {
+ id: 'search',
+ title: 'Search and clear',
+ description:
+ 'The clear slot follows the input value, dispatches the normal input event, and restores focus without a tooltip.',
+ render: SearchDemo,
+ },
+ {
+ id: 'addons',
+ title: 'Addons and actions',
+ description:
+ 'Addon alignment controls visual placement independently of DOM order. Use InputGroup.Button for an interactive action.',
+ render: AddonsDemo,
+ },
+ {
+ id: 'button-group',
+ title: 'Button group composition',
+ description:
+ 'When nested in ButtonGroup, InputGroup inherits its size and lets the outer group own the shared frame.',
+ render: ButtonGroupDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/InputGroup.tsx b/apps/web/src/components/ui/components/InputGroup.tsx
new file mode 100644
index 0000000000..f18bc91297
--- /dev/null
+++ b/apps/web/src/components/ui/components/InputGroup.tsx
@@ -0,0 +1,323 @@
+import XIcon from '@phosphor/x.svg';
+import { mergeRefs } from '@solid-primitives/refs';
+import {
+ type Accessor,
+ type ComponentProps,
+ createContext,
+ createSignal,
+ Show,
+ splitProps,
+ useContext,
+} from 'solid-js';
+import { cn } from '../utils/classname';
+import { createVariants, type VariantProps } from '../utils/variants';
+import { Button, type ButtonProps, type ButtonSize } from './Button';
+import { useButtonGroupContext } from './ButtonGroup';
+import {
+ Input,
+ type InputProps,
+ type InputSize,
+ type InputVariant,
+} from './Input';
+
+const INPUT_GROUP_SIZE_VARIANTS: Record<InputSize, string> = {
+ xs: 'h-5 text-xs',
+ sm: 'h-6 text-xs',
+ md: 'h-8 text-sm',
+ lg: 'h-9 text-base',
+ xl: 'h-12 text-base',
+};
+
+const INPUT_GROUP_ADDON_PADDING: Record<
+ InputSize,
+ { start: string; end: string; buttonEnd: string }
+> = {
+ xs: {
+ start: 'ps-1',
+ end: 'pe-1',
+ buttonEnd: '[&:has([data-button])]:pe-0',
+ },
+ sm: {
+ start: 'ps-2',
+ end: 'pe-2',
+ buttonEnd: '[&:has([data-button])]:pe-0',
+ },
+ md: {
+ start: 'ps-2',
+ end: 'pe-2',
+ buttonEnd: '[&:has([data-button])]:pe-1',
+ },
+ lg: {
+ start: 'ps-3',
+ end: 'pe-3',
+ buttonEnd: '[&:has([data-button])]:pe-0.5',
+ },
+ xl: {
+ start: 'ps-4',
+ end: 'pe-4',
+ buttonEnd: '[&:has([data-button])]:pe-1.5',
+ },
+};
+
+const INPUT_GROUP_BUTTON_SIZE: Record<InputSize, ButtonSize> = {
+ xs: 'icon-xs',
+ sm: 'icon-sm',
+ md: 'sm',
+ lg: 'md',
+ xl: 'lg',
+};
+
+/** Canonical variants for a framed input composition. */
+export const inputGroupVariants = createVariants(
+ cn(
+ 'group/input-group relative flex w-full min-w-0 items-center overflow-hidden rounded-md border transition-[background-color,border-color,box-shadow]',
+ 'has-[[data-slot=input-group-control]:disabled]:pointer-events-none has-[[data-slot=input-group-control]:disabled]:opacity-50',
+ 'has-[[data-slot=input-group-control][aria-invalid=true]]:border-failure has-[[data-slot=input-group-control][aria-invalid=true]]:ring-2 has-[[data-slot=input-group-control][aria-invalid=true]]:ring-failure/20'
+ ),
+ {
+ variant: {
+ outline: cn(
+ 'border-edge-muted bg-input',
+ 'has-[[data-slot=input-group-control]:focus-visible]:border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] has-[[data-slot=input-group-control]:focus-visible]:ring-2 has-[[data-slot=input-group-control]:focus-visible]:ring-edge-muted'
+ ),
+ bare: 'border-transparent bg-transparent',
+ },
+ size: INPUT_GROUP_SIZE_VARIANTS,
+ },
+ { variant: 'outline', size: 'md' }
+);
+
+export type InputGroupVariantProps = VariantProps<typeof inputGroupVariants>;
+export type InputGroupAddonAlign = 'inline-start' | 'inline-end';
+
+type InputGroupContextValue = {
+ readonly size: InputSize;
+ registerControl: (
+ control: HTMLInputElement,
+ hasValue: Accessor<boolean>,
+ canClear: Accessor<boolean>
+ ) => void;
+ hasValue: Accessor<boolean>;
+ canClear: Accessor<boolean>;
+ clear: () => void;
+ focus: () => void;
+};
+
+const InputGroupContext = createContext<InputGroupContextValue>();
+
+function useInputGroupContext(): InputGroupContextValue {
+ const context = useContext(InputGroupContext);
+ if (!context) {
+ throw new Error('InputGroup slots must be used inside InputGroup');
+ }
+ return context;
+}
+
+export type InputGroupProps = Omit<ComponentProps<'div'>, 'size'> & {
+ size?: InputSize;
+ variant?: InputVariant;
+};
+
+function InputGroupRoot(props: InputGroupProps) {
+ const [local, rest] = splitProps(props, [
+ 'children',
+ 'class',
+ 'size',
+ 'variant',
+ ]);
+ const buttonGroup = useButtonGroupContext();
+ const [control, setControl] = createSignal<HTMLInputElement>();
+ const [hasValueReader, setHasValueReader] = createSignal<Accessor<boolean>>(
+ () => false
+ );
+ const [canClearReader, setCanClearReader] = createSignal<Accessor<boolean>>(
+ () => false
+ );
+ const inheritedSize = (): InputSize | undefined => {
+ const size = buttonGroup?.size;
+ return size && !size.startsWith('icon-') ? (size as InputSize) : undefined;
+ };
+ const size = (): InputSize => local.size ?? inheritedSize() ?? 'md';
+ const variant = (): InputVariant =>
+ local.variant ?? (buttonGroup?.variant === 'ghost' ? 'bare' : 'outline');
+ const grouped = () => buttonGroup !== undefined;
+
+ const context: InputGroupContextValue = {
+ get size() {
+ return size();
+ },
+ registerControl(element, hasValue, canClear) {
+ setControl(element);
+ setHasValueReader(() => hasValue);
+ setCanClearReader(() => canClear);
+ },
+ hasValue: () => hasValueReader()(),
+ canClear: () => canClearReader()(),
+ clear() {
+ const element = control();
+ if (!element) return;
+ element.value = '';
+ element.dispatchEvent(new Event('input', { bubbles: true }));
+ queueMicrotask(() => element.focus());
+ },
+ focus: () => control()?.focus(),
+ };
+
+ return (
+ <InputGroupContext.Provider value={context}>
+ <div
+ data-slot="input-group"
+ data-size={size()}
+ data-variant={variant()}
+ data-grouped={grouped() ? '' : undefined}
+ role="group"
+ class={cn(
+ inputGroupVariants({ size: size(), variant: variant() }),
+ grouped() &&
+ 'flex-1 rounded-none border-0 bg-transparent has-[[data-slot=input-group-control]:focus-visible]:ring-0',
+ local.class
+ )}
+ {...rest}
+ >
+ {local.children}
+ </div>
+ </InputGroupContext.Provider>
+ );
+}
+
+export type InputGroupInputProps = Omit<InputProps, 'size' | 'variant'>;
+
+function InputGroupInput(props: InputGroupInputProps) {
+ const [local, rest] = splitProps(props, [
+ 'class',
+ 'disabled',
+ 'readOnly',
+ 'ref',
+ 'value',
+ ]);
+ const group = useInputGroupContext();
+ const [hasUncontrolledValue, setHasUncontrolledValue] = createSignal(false);
+ const hasValue = () =>
+ local.value === undefined
+ ? hasUncontrolledValue()
+ : String(local.value).length > 0;
+ const canClear = () => !local.disabled && !local.readOnly;
+ const attach = (element: HTMLInputElement) => {
+ setHasUncontrolledValue(element.value.length > 0);
+ group.registerControl(element, hasValue, canClear);
+ };
+
+ return (
+ <Input
+ ref={mergeRefs(attach, local.ref)}
+ value={local.value}
+ disabled={local.disabled}
+ readOnly={local.readOnly}
+ size={group.size}
+ variant="bare"
+ data-slot="input-group-control"
+ class={cn(
+ 'h-full flex-1 rounded-none border-0 bg-transparent px-2 focus-visible:ring-0 aria-invalid:ring-0 [&::-webkit-search-cancel-button]:hidden',
+ local.class
+ )}
+ on:input={(event) =>
+ setHasUncontrolledValue(event.currentTarget.value.length > 0)
+ }
+ {...rest}
+ />
+ );
+}
+
+export type InputGroupAddonProps = ComponentProps<'div'> & {
+ align?: InputGroupAddonAlign;
+};
+
+function InputGroupAddon(props: InputGroupAddonProps) {
+ const [local, rest] = splitProps(props, ['align', 'children', 'class']);
+ const group = useInputGroupContext();
+ const align = () => local.align ?? 'inline-start';
+ const padding = () => INPUT_GROUP_ADDON_PADDING[group.size];
+
+ return (
+ <div
+ data-slot="input-group-addon"
+ data-align={align()}
+ class={cn(
+ 'flex shrink-0 items-center justify-center text-ink-subtle [&>svg]:pointer-events-none [&>svg]:shrink-0 [&>svg:not([class*=size-])]:size-[1em]',
+ align() === 'inline-start'
+ ? cn('order-first pe-0', padding().start)
+ : cn('order-last ps-0', padding().end, padding().buttonEnd),
+ local.class
+ )}
+ on:click={(event) => {
+ if ((event.target as HTMLElement).closest('button')) return;
+ group.focus();
+ }}
+ {...rest}
+ >
+ {local.children}
+ </div>
+ );
+}
+
+export type InputGroupButtonProps = ButtonProps;
+
+function InputGroupButton(props: InputGroupButtonProps) {
+ const [local, rest] = splitProps(props, [
+ 'class',
+ 'noTouchResize',
+ 'size',
+ 'square',
+ 'variant',
+ ]);
+ const group = useInputGroupContext();
+
+ return (
+ <Button
+ variant={local.variant ?? 'ghost'}
+ size={local.size ?? INPUT_GROUP_BUTTON_SIZE[group.size]}
+ square={local.square}
+ noTouchResize={local.noTouchResize ?? true}
+ class={cn('rounded-sm', local.class)}
+ {...rest}
+ />
+ );
+}
+
+export type InputGroupClearButtonProps = { class?: string };
+
+function InputGroupClearButton(props: InputGroupClearButtonProps) {
+ const group = useInputGroupContext();
+
+ return (
+ <Show when={group.hasValue() && group.canClear()}>
+ <InputGroupButton
+ type="button"
+ square
+ aria-label="Clear input"
+ class={props.class}
+ onPointerDown={(event) => event.preventDefault()}
+ onClick={() => group.clear()}
+ >
+ <XIcon />
+ </InputGroupButton>
+ </Show>
+ );
+}
+
+/**
+ * A shared input frame for icons, inline actions, and adjacent Buttons.
+ *
+ * @do Put exactly one `InputGroup.Input` inside the root.
+ * @do Put icons and actions in `InputGroup.Addon` and set their visual edge
+ * with `align`; DOM order does not determine placement.
+ * @do Use `InputGroup.ClearButton` for the standard reactive clear action.
+ * @do Nest the root in `ButtonGroup` when it must share a frame with sibling
+ * Buttons; size and framing are inherited by the group, not the input.
+ */
+export const InputGroup = Object.assign(InputGroupRoot, {
+ Addon: InputGroupAddon,
+ Button: InputGroupButton,
+ ClearButton: InputGroupClearButton,
+ Input: InputGroupInput,
+});
diff --git a/apps/web/src/components/ui/components/Pager/Pager.test.tsx b/apps/web/src/components/ui/components/Pager/Pager.test.tsx
deleted file mode 100644
index 8a787e29bc..0000000000
--- a/apps/web/src/components/ui/components/Pager/Pager.test.tsx
+++ /dev/null
@@ -1,219 +0,0 @@
-/**
- * @vitest-environment jsdom
- */
-
-import { render } from '@solidjs/testing-library';
-import { createSignal, For } from 'solid-js';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createPager, Pager, type PagerController, usePager } from '.';
-
-type PageId = 'a' | 'b' | 'c' | 'd';
-
-function finishTransition(container: HTMLElement) {
- const rail = container.querySelector<HTMLElement>('.pager-rail');
- if (!rail) throw new Error('Pager rail was not rendered');
- const event = new Event('transitionend', { bubbles: true });
- Object.defineProperty(event, 'propertyName', { value: 'transform' });
- rail.dispatchEvent(event);
-}
-
-function renderPager(options?: {
- canChangePage?: (page: PageId) => boolean;
- onChange?: (page: PageId) => void;
- pages?: PageId[];
-}) {
- let controller!: PagerController<PageId>;
- let contextController!: PagerController<PageId>;
- const pages = options?.pages ?? ['a', 'b', 'c'];
- const [pageOrder, setPageOrder] = createSignal<readonly PageId[]>(pages);
- const [activePage, setActivePage] = createSignal<PageId>(pages[1] ?? 'a');
-
- function Controls() {
- contextController = usePager<PageId>();
- return null;
- }
-
- const rendered = render(() => {
- controller = createPager({
- pageOrder,
- activePage,
- canChangePage: ({ to }) => options?.canChangePage?.(to) ?? true,
- onPageChange: (page) => {
- setActivePage(page);
- options?.onChange?.(page);
- },
- });
-
- return (
- <Pager.Root controller={controller}>
- <Controls />
- <Pager.Viewport>
- <For each={pages}>
- {(page) => <Pager.Page id={page}>{page}</Pager.Page>}
- </For>
- </Pager.Viewport>
- </Pager.Root>
- );
- });
-
- const viewport = rendered.container.querySelector<HTMLElement>('.pager');
- if (!viewport) throw new Error('Pager viewport was not rendered');
- Object.defineProperty(viewport, 'clientWidth', {
- configurable: true,
- value: 320,
- });
-
- return {
- ...rendered,
- activePage,
- contextController,
- controller,
- pageOrder,
- setPageOrder,
- };
-}
-
-beforeEach(() => {
- vi.stubGlobal('matchMedia', () => ({ matches: false }));
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- }
- );
-});
-
-describe('Pager', () => {
- it('provides its controller outside the viewport', () => {
- const rendered = renderPager();
- expect(rendered.contextController).toBe(rendered.controller);
- });
-
- it('animates to the next page and commits after transition end', async () => {
- const onChange = vi.fn();
- const rendered = renderPager({ onChange });
-
- const navigation = rendered.contextController.next();
- expect(rendered.controller.phase()).toBe('settling');
- expect(rendered.controller.targetPage()).toBe('c');
- expect(rendered.activePage()).toBe('b');
-
- finishTransition(rendered.container);
-
- await expect(navigation).resolves.toBe(true);
- expect(rendered.activePage()).toBe('c');
- expect(rendered.controller.phase()).toBe('idle');
- expect(onChange).toHaveBeenCalledWith('c');
- });
-
- it('supports any number of ordered pages', async () => {
- const rendered = renderPager({ pages: ['a', 'b', 'c', 'd'] });
-
- const navigation = rendered.controller.goTo('d');
- finishTransition(rendered.container);
-
- await expect(navigation).resolves.toBe(true);
- expect(rendered.activePage()).toBe('d');
- expect(rendered.controller.relativePosition('a')).toBe(-3);
- });
-
- it('finishes rapid arrow navigation without replaying the full animation', async () => {
- const rendered = renderPager({ pages: ['a', 'b', 'c', 'd'] });
-
- const firstNavigation = rendered.controller.next();
- const secondNavigation = rendered.controller.next();
-
- await expect(firstNavigation).resolves.toBe(true);
- await expect(secondNavigation).resolves.toBe(true);
- expect(rendered.activePage()).toBe('d');
- expect(rendered.controller.phase()).toBe('idle');
- });
-
- it('keeps repeated clicks immediate for longer than one animation', async () => {
- const now = vi.spyOn(Date, 'now').mockReturnValue(1_000);
- const rendered = renderPager({ pages: ['a', 'b', 'c', 'd'] });
-
- const firstNavigation = rendered.controller.next();
- finishTransition(rendered.container);
- await firstNavigation;
-
- now.mockReturnValue(1_400);
- await expect(rendered.controller.next()).resolves.toBe(true);
- expect(rendered.activePage()).toBe('d');
- expect(rendered.controller.phase()).toBe('idle');
-
- now.mockRestore();
- });
-
- it('supports rapid navigation while the consumer rotates a three-page buffer', async () => {
- let rendered!: ReturnType<typeof renderPager>;
- rendered = renderPager({
- onChange: () => {
- const [first, ...remaining] = rendered.pageOrder();
- rendered.setPageOrder([...remaining, first]);
- },
- });
-
- const firstNavigation = rendered.controller.next();
- const secondNavigation = rendered.controller.next();
-
- await expect(firstNavigation).resolves.toBe(true);
- await expect(secondNavigation).resolves.toBe(true);
- expect(rendered.activePage()).toBe('a');
- expect(rendered.pageOrder()).toEqual(['c', 'a', 'b']);
- expect(rendered.controller.relativePosition('a')).toBe(0);
- });
-
- it('leaves page reordering to the controlled consumer', async () => {
- let rendered!: ReturnType<typeof renderPager>;
- rendered = renderPager({
- onChange: (page) => {
- if (page === 'c') rendered.setPageOrder(['b', 'c', 'a']);
- },
- });
-
- const navigation = rendered.controller.next();
- finishTransition(rendered.container);
-
- await navigation;
- expect(rendered.activePage()).toBe('c');
- expect(rendered.pageOrder()).toEqual(['b', 'c', 'a']);
- expect(rendered.controller.relativePosition('b')).toBe(-1);
- expect(rendered.controller.relativePosition('a')).toBe(1);
- });
-
- it('does not start a disabled transition', async () => {
- const rendered = renderPager({
- canChangePage: (page) => page !== 'c',
- });
-
- await expect(rendered.controller.next()).resolves.toBe(false);
- expect(rendered.controller.phase()).toBe('idle');
- expect(rendered.activePage()).toBe('b');
- });
-
- it('supports externally controlled drag progress', async () => {
- const rendered = renderPager();
-
- expect(rendered.controller.beginDrag()).toBe(true);
- rendered.controller.updateDrag(-100);
- const navigation = rendered.controller.commitDrag('next');
- finishTransition(rendered.container);
-
- await expect(navigation).resolves.toBe(true);
- expect(rendered.activePage()).toBe('c');
- });
-
- it('resets synchronously when the viewport detaches', async () => {
- const rendered = renderPager();
- const navigation = rendered.controller.next();
- expect(rendered.controller.phase()).toBe('settling');
-
- rendered.unmount();
-
- expect(rendered.controller.phase()).toBe('idle');
- await expect(navigation).resolves.toBe(false);
- });
-});
diff --git a/apps/web/src/components/ui/components/Pager/PagerSwipeGestures.test.tsx b/apps/web/src/components/ui/components/Pager/PagerSwipeGestures.test.tsx
deleted file mode 100644
index 65b9b4e55d..0000000000
--- a/apps/web/src/components/ui/components/Pager/PagerSwipeGestures.test.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * @vitest-environment jsdom
- */
-
-import { fireEvent, render } from '@solidjs/testing-library';
-import { createSignal, For } from 'solid-js';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- createPager,
- Pager,
- type PagerController,
- PagerSwipeGestures,
-} from '.';
-
-type PageId = 'previous' | 'current' | 'next';
-
-function touchEvent(
- type: string,
- touches: Array<{ clientX: number; clientY: number }>,
- timeStamp: number,
- changedTouches = touches
-) {
- const event = new Event(type, { bubbles: true, cancelable: true });
- Object.defineProperties(event, {
- changedTouches: { value: changedTouches },
- timeStamp: { value: timeStamp },
- touches: { value: touches },
- });
- return event;
-}
-
-function finishTransition(container: HTMLElement) {
- const rail = container.querySelector<HTMLElement>('.pager-rail');
- if (!rail) throw new Error('Pager rail was not rendered');
- const event = new Event('transitionend', { bubbles: true });
- Object.defineProperty(event, 'propertyName', { value: 'transform' });
- rail.dispatchEvent(event);
-}
-
-function renderSwipePager() {
- let controller!: PagerController<PageId>;
- const pages: PageId[] = ['previous', 'current', 'next'];
- const [activePage, setActivePage] = createSignal<PageId>('current');
-
- const rendered = render(() => {
- controller = createPager({
- pageOrder: () => pages,
- activePage,
- onPageChange: (page) => setActivePage(page),
- });
-
- return (
- <Pager.Root controller={controller}>
- <Pager.Viewport>
- <For each={pages}>
- {(page) => <Pager.Page id={page}>{page}</Pager.Page>}
- </For>
- </Pager.Viewport>
- <PagerSwipeGestures />
- </Pager.Root>
- );
- });
-
- const viewport = rendered.container.querySelector<HTMLElement>('.pager');
- if (!viewport) throw new Error('Pager viewport was not rendered');
- Object.defineProperty(viewport, 'clientWidth', {
- configurable: true,
- value: 320,
- });
-
- return { ...rendered, activePage, controller, viewport };
-}
-
-beforeEach(() => {
- vi.stubGlobal('matchMedia', () => ({ matches: false }));
- vi.stubGlobal(
- 'ResizeObserver',
- class {
- observe() {}
- unobserve() {}
- disconnect() {}
- }
- );
-});
-
-describe('PagerSwipeGestures', () => {
- it('commits a horizontal touch gesture after crossing the threshold', () => {
- const rendered = renderSwipePager();
- fireEvent(
- rendered.viewport,
- touchEvent('touchstart', [{ clientX: 200, clientY: 100 }], 0)
- );
- const move = touchEvent('touchmove', [{ clientX: 100, clientY: 102 }], 30);
- fireEvent(rendered.viewport, move);
- fireEvent(
- rendered.viewport,
- touchEvent('touchend', [], 60, [{ clientX: 100, clientY: 102 }])
- );
-
- expect(move.defaultPrevented).toBe(true);
- expect(rendered.controller.targetPage()).toBe('next');
- finishTransition(rendered.container);
- expect(rendered.activePage()).toBe('next');
- });
-
- it('snaps back when a second touch interrupts the gesture', () => {
- const rendered = renderSwipePager();
- fireEvent(
- rendered.viewport,
- touchEvent('touchstart', [{ clientX: 200, clientY: 100 }], 0)
- );
- fireEvent(
- rendered.viewport,
- touchEvent('touchmove', [{ clientX: 150, clientY: 100 }], 20)
- );
- expect(rendered.controller.phase()).toBe('dragging');
-
- fireEvent(
- rendered.viewport,
- touchEvent(
- 'touchstart',
- [
- { clientX: 150, clientY: 100 },
- { clientX: 170, clientY: 100 },
- ],
- 30
- )
- );
- expect(rendered.controller.phase()).toBe('settling');
-
- finishTransition(rendered.container);
- expect(rendered.controller.phase()).toBe('idle');
- expect(rendered.activePage()).toBe('current');
- });
-
- it('leaves vertical touch movement available to the browser', () => {
- const rendered = renderSwipePager();
- fireEvent(
- rendered.viewport,
- touchEvent('touchstart', [{ clientX: 100, clientY: 100 }], 0)
- );
- const move = touchEvent('touchmove', [{ clientX: 102, clientY: 140 }], 20);
- fireEvent(rendered.viewport, move);
-
- expect(move.defaultPrevented).toBe(false);
- expect(rendered.controller.phase()).toBe('idle');
- });
-});
diff --git a/apps/web/src/components/ui/components/Panel.docs.tsx b/apps/web/src/components/ui/components/Panel.docs.tsx
new file mode 100644
index 0000000000..6318f93299
--- /dev/null
+++ b/apps/web/src/components/ui/components/Panel.docs.tsx
@@ -0,0 +1,116 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { For } from 'solid-js';
+import { Button } from './Button';
+import { Panel } from './Panel';
+
+// #region demo:slots
+function SlotsDemo() {
+ return (
+ <Panel depth={2} class="w-full max-w-md">
+ <Panel.Header class="px-3">
+ <span class="text-sm font-medium text-ink">Panel.Header</span>
+ </Panel.Header>
+ <Panel.Toolbar class="gap-2">
+ <Button variant="ghost" size="sm">
+ Toolbar
+ </Button>
+ <Button variant="ghost" size="sm">
+ Action
+ </Button>
+ </Panel.Toolbar>
+ <Panel.Body class="p-3">
+ <p class="text-sm text-ink-muted">
+ Panel.Body takes the remaining height and is the only slot that
+ shrinks.
+ </p>
+ </Panel.Body>
+ <Panel.Footer class="justify-end gap-2 px-3">
+ <Button variant="ghost" size="sm">
+ Cancel
+ </Button>
+ <Button variant="accent" size="sm">
+ Confirm
+ </Button>
+ </Panel.Footer>
+ </Panel>
+ );
+}
+// #endregion
+
+// #region demo:scroll
+function ScrollDemo() {
+ return (
+ <Panel depth={2} class="h-56 w-full max-w-md">
+ <Panel.Header class="px-3">
+ <span class="text-sm font-medium text-ink">Scrolling body</span>
+ </Panel.Header>
+ <Panel.Body scroll class="p-3">
+ <div class="flex flex-col gap-2">
+ <For each={Array.from({ length: 20 }, (_, i) => i + 1)}>
+ {(row) => (
+ <div class="rounded-sm bg-inset p-2 text-sm text-ink-muted">
+ Row {row}
+ </div>
+ )}
+ </For>
+ </div>
+ </Panel.Body>
+ </Panel>
+ );
+}
+// #endregion
+
+// #region demo:active
+function ActiveDemo() {
+ return (
+ <div class="grid w-full grid-cols-1 gap-4 md:grid-cols-2">
+ <Panel depth={2} class="min-h-24">
+ <Panel.Body class="p-3">
+ <p class="text-sm text-ink-muted">Default</p>
+ </Panel.Body>
+ </Panel>
+ <Panel active depth={2} class="min-h-24">
+ <Panel.Body class="p-3">
+ <p class="text-sm text-ink-muted">active</p>
+ </Panel.Body>
+ </Panel>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Panel',
+ category: 'Layout',
+ description:
+ 'A depth-aware container with fixed header, toolbar, and footer slots around a body that absorbs the remaining height. The layout is a CSS grid, so the body scrolls without the chrome moving.',
+ status: 'stable',
+ exports: ['Panel', 'Surface'],
+ import: "import { Panel } from '@ui';",
+ // PanelProps is a bare alias; the real surface is SurfaceProps.
+ propTypes: ['SurfaceProps'],
+ demos: [
+ {
+ id: 'slots',
+ title: 'Slots',
+ description:
+ 'Every slot is optional and renders nothing when empty, so a body-only Panel has no stray borders.',
+ render: SlotsDemo,
+ },
+ {
+ id: 'scroll',
+ title: 'Scrolling body',
+ description:
+ '`Panel.Body scroll` wraps the content in `Scroll`, keeping the header and footer pinned. Give the Panel a bounded height for this to take effect.',
+ render: ScrollDemo,
+ },
+ {
+ id: 'active',
+ title: 'Active state',
+ description:
+ '`active` draws the focus ring used for the panel holding keyboard focus in a split layout.',
+ render: ActiveDemo,
+ fill: true,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Panel.tsx b/apps/web/src/components/ui/components/Panel.tsx
index 154d2fb135..e25985a797 100644
--- a/apps/web/src/components/ui/components/Panel.tsx
+++ b/apps/web/src/components/ui/components/Panel.tsx
@@ -78,7 +78,14 @@ function PanelBody(props: BodyProps) {
when={props.scroll}
fallback={
<div
- class={cn('relative min-h-0 min-w-0 overflow-hidden', props.class)}
+ // `clip`, not `hidden`: both clip the overflow, but `hidden` still
+ // makes this a scroll container, so focusing anything below the
+ // fold — a switch, an input — lets the browser scroll the body to
+ // reveal it. With no scrollbar there is no way to scroll back, and
+ // the panel looks permanently broken. `clip` is not a scroll
+ // container, so it cannot be scrolled programmatically at all.
+ // Matches `Surface`, which already uses `overflow-clip`.
+ class={cn('relative min-h-0 min-w-0 overflow-clip', props.class)}
style={{ 'grid-area': 'body' }}
>
{resolved()}
@@ -110,6 +117,19 @@ function PanelFooter(props: SlotProps) {
);
}
+/**
+ * A depth-aware container with fixed header, toolbar, and footer slots around
+ * a body that absorbs the remaining height.
+ *
+ * @do Put controls in `Panel.Toolbar` and titles in `Panel.Header` so heights
+ * stay consistent across the app.
+ * @do Set `depth` on the Panel rather than a background class on its children.
+ * @do Use `Panel.Body scroll` instead of adding `overflow-auto` yourself.
+ * @dont Do not nest a Panel inside `Panel.Body` just to get padding — use the
+ * body's own class.
+ * @dont Do not give `Panel.Header` a custom height; the 40px minimum is what
+ * aligns panels side by side.
+ */
export const Panel = Object.assign(PanelRoot, {
Toolbar: PanelToolbar,
Header: PanelHeader,
diff --git a/apps/web/src/components/ui/components/Select.docs.tsx b/apps/web/src/components/ui/components/Select.docs.tsx
new file mode 100644
index 0000000000..bf9017e355
--- /dev/null
+++ b/apps/web/src/components/ui/components/Select.docs.tsx
@@ -0,0 +1,157 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import type { CollectionNode } from '@kobalte/core';
+import CaretDownIcon from '@phosphor/caret-down.svg';
+import CheckIcon from '@phosphor/check.svg';
+import { createSignal } from 'solid-js';
+import { Select } from './Select';
+
+type Option = { value: string; label: string; hint?: string };
+
+const OPTIONS: Option[] = [
+ { value: 'owner', label: 'Owner', hint: 'Full access, including billing' },
+ { value: 'admin', label: 'Admin', hint: 'Manage members and settings' },
+ { value: 'member', label: 'Member', hint: 'Create and edit content' },
+ { value: 'guest', label: 'Guest', hint: 'View shared items only' },
+];
+
+const ITEM_CLASS =
+ 'flex items-center justify-between gap-3 rounded-md px-2 py-1.5 text-sm outline-none data-highlighted:bg-hover';
+
+// #region demo:basic
+function BasicDemo() {
+ const [value, setValue] = createSignal<Option>(OPTIONS[2]!);
+
+ return (
+ <Select<Option>
+ options={OPTIONS}
+ value={value()}
+ onChange={(option) => option && setValue(option)}
+ optionValue="value"
+ optionTextValue="label"
+ gutter={4}
+ itemComponent={(props: { item: CollectionNode<Option> }) => (
+ <Select.Item item={props.item} class={ITEM_CLASS}>
+ <Select.ItemLabel>{props.item.rawValue.label}</Select.ItemLabel>
+ <Select.ItemIndicator>
+ <CheckIcon class="size-3" />
+ </Select.ItemIndicator>
+ </Select.Item>
+ )}
+ >
+ <Select.Trigger class="h-8 w-44 rounded-md border border-edge-muted px-2 text-sm text-ink-muted">
+ <Select.Value<Option>>
+ {(state) => state.selectedOption().label}
+ </Select.Value>
+ <CaretDownIcon class="size-3 shrink-0 text-ink-subtle" />
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Listbox />
+ </Select.Content>
+ </Select>
+ );
+}
+// #endregion
+
+// #region demo:rich-items
+function RichItemsDemo() {
+ const [value, setValue] = createSignal<Option>(OPTIONS[1]!);
+
+ return (
+ <Select<Option>
+ options={OPTIONS}
+ value={value()}
+ onChange={(option) => option && setValue(option)}
+ optionValue="value"
+ optionTextValue="label"
+ gutter={4}
+ itemComponent={(props: { item: CollectionNode<Option> }) => (
+ <Select.Item item={props.item} class={ITEM_CLASS}>
+ <span class="flex flex-col gap-0.5">
+ <Select.ItemLabel>{props.item.rawValue.label}</Select.ItemLabel>
+ <span class="text-xs text-ink-subtle">
+ {props.item.rawValue.hint}
+ </span>
+ </span>
+ <Select.ItemIndicator>
+ <CheckIcon class="size-3" />
+ </Select.ItemIndicator>
+ </Select.Item>
+ )}
+ >
+ <Select.Trigger class="h-8 w-56 rounded-md border border-edge-muted px-2 text-sm text-ink-muted">
+ <Select.Value<Option>>
+ {(state) => state.selectedOption().label}
+ </Select.Value>
+ <CaretDownIcon class="size-3 shrink-0 text-ink-subtle" />
+ </Select.Trigger>
+ <Select.Content class="min-w-56">
+ <Select.Listbox />
+ </Select.Content>
+ </Select>
+ );
+}
+// #endregion
+
+// #region demo:disabled
+function DisabledDemo() {
+ return (
+ <Select<Option>
+ options={OPTIONS}
+ value={OPTIONS[0]}
+ disabled
+ optionValue="value"
+ optionTextValue="label"
+ itemComponent={(props: { item: CollectionNode<Option> }) => (
+ <Select.Item item={props.item} class={ITEM_CLASS}>
+ <Select.ItemLabel>{props.item.rawValue.label}</Select.ItemLabel>
+ </Select.Item>
+ )}
+ >
+ <Select.Trigger class="h-8 w-44 rounded-md border border-edge-muted px-2 text-sm text-ink-disabled">
+ <Select.Value<Option>>
+ {(state) => state.selectedOption().label}
+ </Select.Value>
+ <CaretDownIcon class="size-3 shrink-0" />
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Listbox />
+ </Select.Content>
+ </Select>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Select',
+ category: 'Inputs',
+ description:
+ 'A Kobalte select, styled for the app. It is slot-based: you supply the trigger and the item renderer, while `Select.Content` handles portalling, popper sizing, menu chrome, and its own layer depth.',
+ status: 'stable',
+ exports: ['Select'],
+ import: "import { Select } from '@ui';",
+ // The root is generic over the option type, so it is not named SelectProps.
+ propTypes: ['SelectRootProps'],
+ demos: [
+ {
+ id: 'basic',
+ title: 'Basic',
+ description:
+ '`optionValue` and `optionTextValue` tell the collection which fields identify and label each option. `Select.Value` receives the selected option, so the trigger renders whatever you want.',
+ render: BasicDemo,
+ },
+ {
+ id: 'rich-items',
+ title: 'Rich items',
+ description:
+ '`itemComponent` renders arbitrary content. Keep `Select.ItemLabel` around the primary text so typeahead and the accessible name still work.',
+ render: RichItemsDemo,
+ },
+ {
+ id: 'disabled',
+ title: 'Disabled',
+ description:
+ 'A disabled select keeps its value visible but will not open.',
+ render: DisabledDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Select.tsx b/apps/web/src/components/ui/components/Select.tsx
index 7b98ad58c5..a502d2d9b1 100644
--- a/apps/web/src/components/ui/components/Select.tsx
+++ b/apps/web/src/components/ui/components/Select.tsx
@@ -222,7 +222,18 @@ function SelectRoot<Option, OptGroup = never>(
);
}
-/** Composable, styled single- or multi-value select built on Kobalte. */
+/** Composable, styled single- or multi-value select built on Kobalte.
+ *
+ * @do Let `Select.Content` own the menu chrome; pass only sizing classes to
+ * it.
+ * @do Include `Select.ItemIndicator` so the current selection is visible in
+ * the list.
+ * @do Use `portalScope="local"` when the select lives inside a dialog or other
+ * portal scope.
+ * @dont Do not wrap `Select.Content` in a Portal — it already portals itself.
+ * @dont Do not use Select for more than roughly a dozen options; use a command
+ * menu with search.
+ */
export const Select = Object.assign(SelectRoot, {
Content: SelectContent,
Icon: SelectIcon,
diff --git a/apps/web/src/components/ui/components/Surface.test.tsx b/apps/web/src/components/ui/components/Surface.test.tsx
deleted file mode 100644
index 3a38db4d14..0000000000
--- a/apps/web/src/components/ui/components/Surface.test.tsx
+++ /dev/null
@@ -1,21 +0,0 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it } from 'vitest';
-import { Surface } from './Surface';
-
-describe('Surface', () => {
- afterEach(cleanup);
-
- it('uses the layer-relative surface background by default', () => {
- render(() => <Surface data-testid="surface" />);
-
- expect(screen.getByTestId('surface').classList).toContain('bg-surface');
- });
-
- it('allows an explicit semantic background to override the default', () => {
- render(() => <Surface data-testid="surface" class="bg-panel" />);
-
- const surface = screen.getByTestId('surface');
- expect(surface.classList).toContain('bg-panel');
- expect(surface.classList).not.toContain('bg-surface');
- });
-});
diff --git a/apps/web/src/components/ui/components/TextField.docs.tsx b/apps/web/src/components/ui/components/TextField.docs.tsx
new file mode 100644
index 0000000000..1afab535b7
--- /dev/null
+++ b/apps/web/src/components/ui/components/TextField.docs.tsx
@@ -0,0 +1,99 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { createSignal } from 'solid-js';
+import { TextField } from './TextField';
+
+// #region demo:basic
+function BasicDemo() {
+ const [value, setValue] = createSignal('');
+
+ return (
+ <TextField
+ class="w-full max-w-sm"
+ value={value()}
+ onChange={setValue}
+ required
+ >
+ <TextField.Label>Project name</TextField.Label>
+ <TextField.Input placeholder="Quarterly planning" />
+ <TextField.Description>
+ A short name teammates will recognize.
+ </TextField.Description>
+ </TextField>
+ );
+}
+// #endregion
+
+// #region demo:textarea
+function TextAreaDemo() {
+ return (
+ <TextField class="w-full max-w-sm" defaultValue="">
+ <TextField.Label>Notes</TextField.Label>
+ <TextField.TextArea
+ autoResize
+ placeholder="Add context for your teammates…"
+ />
+ <TextField.Description>
+ This field grows as you type.
+ </TextField.Description>
+ </TextField>
+ );
+}
+// #endregion
+
+// #region demo:states
+function StatesDemo() {
+ return (
+ <div class="flex w-full max-w-sm flex-col gap-5">
+ <TextField disabled defaultValue="[email protected]">
+ <TextField.Label>Account email</TextField.Label>
+ <TextField.Input type="email" />
+ <TextField.Description>
+ Managed by your workspace administrator.
+ </TextField.Description>
+ </TextField>
+
+ <TextField validationState="invalid" defaultValue="macro">
+ <TextField.Label>Workspace URL</TextField.Label>
+ <TextField.Input />
+ <TextField.ErrorMessage>
+ Enter the full workspace URL.
+ </TextField.ErrorMessage>
+ </TextField>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Text Field',
+ category: 'Inputs',
+ description:
+ 'An accessible, slot-based text input and textarea. Kobalte connects labels, descriptions, and errors while the controls use the app’s layer-aware tokens.',
+ status: 'stable',
+ exports: ['TextField'],
+ import: "import { TextField } from '@ui';",
+ propTypes: ['TextFieldProps'],
+ demos: [
+ {
+ id: 'basic',
+ title: 'Basic',
+ description:
+ 'The root owns value state and automatically connects the label and description to the input.',
+ render: BasicDemo,
+ },
+ {
+ id: 'textarea',
+ title: 'Textarea',
+ description:
+ '`TextField.TextArea` shares the same root API. `autoResize` lets Kobalte grow it with its content.',
+ render: TextAreaDemo,
+ },
+ {
+ id: 'states',
+ title: 'Disabled and invalid',
+ description:
+ 'Root state flows to every slot. Invalid controls receive `aria-invalid`, and the error message is included in `aria-describedby`.',
+ render: StatesDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/TextField.tsx b/apps/web/src/components/ui/components/TextField.tsx
new file mode 100644
index 0000000000..5b9c588b21
--- /dev/null
+++ b/apps/web/src/components/ui/components/TextField.tsx
@@ -0,0 +1,176 @@
+import { TextField as KobalteTextField } from '@kobalte/core/text-field';
+import type { ComponentProps, ValidComponent } from 'solid-js';
+import { For, Match, Switch, splitProps } from 'solid-js';
+import { cn } from '../utils/classname';
+import { Input, type InputProps, inputOutlineFocusClasses } from './Input';
+
+// Adapted from hngngn/shadcn-solid's MIT-licensed TextField primitive.
+// The slot API follows our compound-component convention and the visual
+// treatment uses Macro's semantic, layer-aware tokens.
+
+export type TextFieldProps<T extends ValidComponent = 'div'> = ComponentProps<
+ typeof KobalteTextField<T>
+>;
+
+function TextFieldRoot<T extends ValidComponent = 'div'>(
+ props: TextFieldProps<T>
+) {
+ const [local, rest] = splitProps(props as TextFieldProps, ['class']);
+
+ return (
+ <KobalteTextField
+ data-slot="text-field"
+ class={cn('grid w-full gap-1.5', local.class)}
+ {...rest}
+ />
+ );
+}
+
+export type TextFieldInputProps = ComponentProps<
+ typeof KobalteTextField.Input<typeof Input>
+> &
+ InputProps;
+
+function TextFieldInput(props: TextFieldInputProps) {
+ const [local, rest] = splitProps(props as TextFieldInputProps, ['class']);
+
+ return (
+ <KobalteTextField.Input<typeof Input>
+ as={Input}
+ data-slot="text-field-input"
+ class={local.class}
+ {...rest}
+ />
+ );
+}
+
+export type TextFieldTextAreaProps<T extends ValidComponent = 'textarea'> =
+ ComponentProps<typeof KobalteTextField.TextArea<T>>;
+
+function TextFieldTextArea<T extends ValidComponent = 'textarea'>(
+ props: TextFieldTextAreaProps<T>
+) {
+ const [local, rest] = splitProps(props as TextFieldTextAreaProps, ['class']);
+
+ return (
+ <KobalteTextField.TextArea
+ data-slot="text-field-textarea"
+ class={cn(
+ 'flex min-h-20 w-full resize-none rounded-md border border-edge-muted bg-input px-2.5 py-2 text-sm text-ink caret-current outline-none transition-[border-color,box-shadow]',
+ 'placeholder:text-ink-placeholder',
+ inputOutlineFocusClasses,
+ 'aria-invalid:border-failure aria-invalid:ring-2 aria-invalid:ring-failure/20',
+ 'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
+ local.class
+ )}
+ {...rest}
+ />
+ );
+}
+
+export type TextFieldLabelProps<T extends ValidComponent = 'label'> =
+ ComponentProps<typeof KobalteTextField.Label<T>>;
+
+function TextFieldLabel<T extends ValidComponent = 'label'>(
+ props: TextFieldLabelProps<T>
+) {
+ const [local, rest] = splitProps(props as TextFieldLabelProps, ['class']);
+
+ return (
+ <KobalteTextField.Label
+ data-slot="text-field-label"
+ class={cn(
+ 'text-sm font-medium text-ink select-none',
+ 'data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-disabled:text-ink-disabled',
+ 'data-invalid:text-failure',
+ local.class
+ )}
+ {...rest}
+ />
+ );
+}
+
+export type TextFieldError = { message?: string } | undefined;
+
+export type TextFieldErrorMessageProps<T extends ValidComponent = 'div'> =
+ ComponentProps<typeof KobalteTextField.ErrorMessage<T>> & {
+ errors?: TextFieldError[];
+ };
+
+function TextFieldErrorMessage<T extends ValidComponent = 'div'>(
+ props: TextFieldErrorMessageProps<T>
+) {
+ const [local, rest] = splitProps(props as TextFieldErrorMessageProps, [
+ 'class',
+ 'errors',
+ 'children',
+ ]);
+ const uniqueErrors = () => [
+ ...new Map(local.errors?.map((error) => [error?.message, error])).values(),
+ ];
+
+ return (
+ <KobalteTextField.ErrorMessage
+ data-slot="text-field-error-message"
+ class={cn('text-xs text-failure', local.class)}
+ {...rest}
+ >
+ <Switch
+ fallback={
+ <ul class="ml-4 flex list-disc flex-col gap-1">
+ <For each={uniqueErrors()}>
+ {(error) => <li>{error?.message}</li>}
+ </For>
+ </ul>
+ }
+ >
+ <Match when={local.children}>{local.children}</Match>
+ <Match when={!local.errors?.length}>{null}</Match>
+ <Match when={uniqueErrors().length === 1}>
+ {uniqueErrors()[0]?.message}
+ </Match>
+ </Switch>
+ </KobalteTextField.ErrorMessage>
+ );
+}
+
+export type TextFieldDescriptionProps<T extends ValidComponent = 'div'> =
+ ComponentProps<typeof KobalteTextField.Description<T>>;
+
+function TextFieldDescription<T extends ValidComponent = 'div'>(
+ props: TextFieldDescriptionProps<T>
+) {
+ const [local, rest] = splitProps(props as TextFieldDescriptionProps, [
+ 'class',
+ ]);
+
+ return (
+ <KobalteTextField.Description
+ data-slot="text-field-description"
+ class={cn('text-xs text-ink-subtle', local.class)}
+ {...rest}
+ />
+ );
+}
+
+/**
+ * An accessible text input or textarea composed from Kobalte slots and styled
+ * with the app's layer-aware form-control tokens.
+ *
+ * @do Put `TextField.Label`, the control, and any description or error inside
+ * the same root so Kobalte wires their accessible relationships.
+ * @do Set `validationState="invalid"` on the root; `TextField.Input` and
+ * `TextField.TextArea` receive `aria-invalid` automatically.
+ * @do Use `TextField.TextArea autoResize` for growing multiline input.
+ * @dont Do not add manual `id`, `for`, or `aria-describedby` attributes when
+ * the slots share a root.
+ * @dont Do not use TextField for search with suggestions or fixed-choice
+ * values; use the appropriate combobox or Select primitive.
+ */
+export const TextField = Object.assign(TextFieldRoot, {
+ Description: TextFieldDescription,
+ ErrorMessage: TextFieldErrorMessage,
+ Input: TextFieldInput,
+ Label: TextFieldLabel,
+ TextArea: TextFieldTextArea,
+});
diff --git a/apps/web/src/components/ui/components/ToggleSwitch.docs.tsx b/apps/web/src/components/ui/components/ToggleSwitch.docs.tsx
new file mode 100644
index 0000000000..8ecec85fee
--- /dev/null
+++ b/apps/web/src/components/ui/components/ToggleSwitch.docs.tsx
@@ -0,0 +1,106 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { createSignal, For } from 'solid-js';
+import { ToggleSwitch } from './ToggleSwitch';
+
+// #region demo:basic
+function BasicDemo() {
+ const [enabled, setEnabled] = createSignal(true);
+
+ return (
+ <div class="flex flex-col gap-3">
+ <ToggleSwitch
+ checked={enabled()}
+ onChange={setEnabled}
+ label="Desktop notifications"
+ labelClass="text-sm text-ink"
+ />
+ <span class="text-xs text-ink-subtle">
+ Currently {enabled() ? 'on' : 'off'}
+ </span>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:sizes
+function SizesDemo() {
+ return (
+ <div class="flex flex-wrap items-center gap-6">
+ <For each={['xs', 'sm', 'md'] as const}>
+ {(size) => (
+ <div class="flex flex-col items-start gap-1.5">
+ <span class="font-mono text-xs text-ink-subtle">{size}</span>
+ <ToggleSwitch size={size} defaultChecked />
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:settings-row
+function SettingsRowDemo() {
+ const rows = [
+ {
+ label: 'Read receipts',
+ description: 'Let others see when you read a message.',
+ on: true,
+ },
+ {
+ label: 'Typing indicators',
+ description: 'Show when you are composing.',
+ on: false,
+ },
+ ];
+
+ return (
+ <div class="flex w-full max-w-md flex-col divide-y divide-edge-muted">
+ <For each={rows}>
+ {(row) => (
+ <div class="flex items-center justify-between gap-4 py-3">
+ <div class="flex flex-col gap-0.5">
+ <span class="text-sm text-ink">{row.label}</span>
+ <span class="text-xs text-ink-subtle">{row.description}</span>
+ </div>
+ <ToggleSwitch size="md" defaultChecked={row.on} />
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Toggle Switch',
+ category: 'Inputs',
+ description:
+ 'An on/off switch for a setting that applies immediately. If the change needs a save step, use a Checkbox instead.',
+ status: 'stable',
+ exports: ['ToggleSwitch'],
+ import: "import { ToggleSwitch } from '@ui';",
+ demos: [
+ {
+ id: 'basic',
+ title: 'Basic',
+ description:
+ 'Controlled via `checked` and `onChange`, or uncontrolled via `defaultChecked`. The whole component — including the gap between control and label — is one hit target.',
+ render: BasicDemo,
+ },
+ {
+ id: 'sizes',
+ title: 'Sizes',
+ description:
+ '`sm` is the default toolbar size; `md` is for settings rows; `xs` is for dense inline chrome.',
+ render: SizesDemo,
+ },
+ {
+ id: 'settings-row',
+ title: 'Settings row',
+ description:
+ 'The standard settings pattern: label and description on the left, switch on the right.',
+ render: SettingsRowDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/ToggleSwitch.tsx b/apps/web/src/components/ui/components/ToggleSwitch.tsx
index c4307e0528..e5ce5c93e8 100644
--- a/apps/web/src/components/ui/components/ToggleSwitch.tsx
+++ b/apps/web/src/components/ui/components/ToggleSwitch.tsx
@@ -38,6 +38,18 @@ const SWITCH_SIZES = {
},
} as const;
+/**
+ * An on/off switch for a setting that applies immediately. If the change
+ * needs a save step, use a Checkbox instead.
+ *
+ * @do Use a switch only when the change takes effect immediately.
+ * @do Label the setting in its on-state ("Read receipts", not "Disable read
+ * receipts").
+ * @do Use `size="md"` in settings and `size="sm"` in toolbars.
+ * @dont Do not put a switch in a form that has a Save button — use a Checkbox.
+ * @dont Do not pair a switch with an on/off text label; the control already
+ * says it.
+ */
export const ToggleSwitch = (props: ToggleSwitchProps): JSX.Element => {
const [local, others] = splitProps(props, [
'defaultChecked',
diff --git a/apps/web/src/components/ui/foundations/colors.docs.tsx b/apps/web/src/components/ui/foundations/colors.docs.tsx
new file mode 100644
index 0000000000..603bda0444
--- /dev/null
+++ b/apps/web/src/components/ui/foundations/colors.docs.tsx
@@ -0,0 +1,151 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { For } from 'solid-js';
+
+/** One labelled swatch. Local to this page so the docs stay self-contained. */
+function Swatch(props: { token: string; note?: string }) {
+ return (
+ <div class="flex flex-col gap-1.5">
+ <div
+ class="h-12 w-full rounded-md border border-edge-muted"
+ style={{ 'background-color': `var(--color-${props.token})` }}
+ />
+ <span class="font-mono text-xs text-ink">{props.token}</span>
+ <span class="text-xs text-ink-subtle">{props.note ?? ''}</span>
+ </div>
+ );
+}
+
+function SwatchGrid(props: { tokens: { token: string; note?: string }[] }) {
+ return (
+ <div class="grid w-full grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5">
+ <For each={props.tokens}>
+ {(entry) => <Swatch token={entry.token} note={entry.note} />}
+ </For>
+ </div>
+ );
+}
+
+// #region demo:surfaces
+function SurfacesDemo() {
+ return (
+ <SwatchGrid
+ tokens={[
+ { token: 'surface-0', note: 'Furthest back' },
+ { token: 'surface-1', note: 'Panels' },
+ { token: 'surface-2', note: 'Menus, dialogs' },
+ { token: 'surface-3', note: 'Raised chrome' },
+ { token: 'surface-4', note: 'Closest to viewer' },
+ ]}
+ />
+ );
+}
+// #endregion
+
+// #region demo:ink
+function InkDemo() {
+ return (
+ <SwatchGrid
+ tokens={[
+ { token: 'ink', note: 'Primary text' },
+ { token: 'ink-muted', note: 'Secondary text' },
+ { token: 'ink-subtle', note: 'Labels, captions' },
+ { token: 'ink-disabled', note: 'Disabled text' },
+ { token: 'ink-placeholder', note: 'Empty inputs' },
+ ]}
+ />
+ );
+}
+// #endregion
+
+// #region demo:semantic
+function SemanticDemo() {
+ return (
+ <SwatchGrid
+ tokens={[
+ { token: 'accent', note: 'Brand / selection' },
+ { token: 'success', note: 'Confirmed state' },
+ { token: 'warning', note: 'Needs attention' },
+ { token: 'failure', note: 'Errors, destructive' },
+ { token: 'edge', note: 'Strong borders' },
+ { token: 'edge-muted', note: 'Default borders' },
+ { token: 'hover', note: 'Hover scrim' },
+ { token: 'active', note: 'Pressed scrim' },
+ { token: 'selected', note: 'Selected rows' },
+ ]}
+ />
+ );
+}
+// #endregion
+
+// #region demo:palette
+function PaletteDemo() {
+ const palette = [
+ 'red',
+ 'orange',
+ 'amber',
+ 'yellow',
+ 'lime',
+ 'green',
+ 'teal',
+ 'cyan',
+ 'blue',
+ 'violet',
+ 'purple',
+ 'pink',
+ ];
+ return <SwatchGrid tokens={palette.map((token) => ({ token }))} />;
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Colors',
+ category: 'Foundations',
+ description:
+ 'Every color in the app comes from a semantic token, never a raw Tailwind color. Themes redefine the tokens; components never change.',
+ demos: [
+ {
+ id: 'surfaces',
+ title: 'Surfaces',
+ description:
+ 'The background ramp. Components read these through the layer system rather than naming a step directly — see Surfaces & Depth.',
+ render: SurfacesDemo,
+ fill: true,
+ },
+ {
+ id: 'ink',
+ title: 'Ink',
+ description:
+ 'Text colors, from primary down to placeholder. `ink-extra-muted` is a deprecated alias for `ink-subtle`; use `ink-subtle` in new code.',
+ render: InkDemo,
+ fill: true,
+ },
+ {
+ id: 'semantic',
+ title: 'Semantic',
+ description:
+ 'Meaning-carrying colors. Reach for these before the raw palette so intent survives a theme change.',
+ render: SemanticDemo,
+ fill: true,
+ },
+ {
+ id: 'palette',
+ title: 'Palette',
+ description:
+ 'Named hues for content that needs a color of its own — labels, calendars, avatars. Not for conveying state.',
+ render: PaletteDemo,
+ fill: true,
+ },
+ ],
+ guidelines: {
+ do: [
+ 'Use semantic tokens: `text-ink-muted`, `bg-surface`, `border-edge-muted`.',
+ 'Use `failure` / `success` / `warning` for state, so every theme stays legible.',
+ 'Pick from the named palette when content needs identity rather than meaning.',
+ ],
+ dont: [
+ 'Do not use raw Tailwind palette utilities — they ignore the theme.',
+ 'Do not hardcode hex or oklch values in components.',
+ 'Do not use `ink-extra-muted` in new code; it is a temporary compatibility alias.',
+ ],
+ },
+});
diff --git a/apps/web/src/components/ui/foundations/surfaces.docs.tsx b/apps/web/src/components/ui/foundations/surfaces.docs.tsx
new file mode 100644
index 0000000000..a195bfaa21
--- /dev/null
+++ b/apps/web/src/components/ui/foundations/surfaces.docs.tsx
@@ -0,0 +1,153 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { For } from 'solid-js';
+import { Button } from '../components/Button';
+import { Layer } from '../components/Layer';
+import { Panel } from '../components/Panel';
+
+// #region demo:depths
+function DepthsDemo() {
+ return (
+ <div class="grid w-full grid-cols-1 gap-4 md:grid-cols-3">
+ <For each={[0, 1, 2, 3, 4] as const}>
+ {(depth) => (
+ <Panel depth={depth} class="min-h-28 bg-surface">
+ <Panel.Header class="px-3">
+ <span class="font-mono text-xs text-ink-subtle">
+ depth={depth}
+ </span>
+ </Panel.Header>
+ <Panel.Body class="p-3">
+ <p class="text-sm text-ink-muted">Hello!</p>
+ </Panel.Body>
+ </Panel>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:nesting
+function NestingDemo() {
+ return (
+ <Panel depth={0} class="w-full p-3 bg-surface">
+ <p class="mb-2 font-mono text-xs text-ink-subtle">depth 0</p>
+ <Panel depth={1} class="p-3 bg-surface">
+ <p class="mb-2 font-mono text-xs text-ink-subtle">depth 1</p>
+ <Panel depth={2} class="p-3 bg-surface">
+ <p class="mb-2 font-mono text-xs text-ink-subtle">depth 2</p>
+ <Panel depth={3} class="p-3 bg-surface">
+ <p class="font-mono text-xs text-ink-subtle">depth 3</p>
+ </Panel>
+ </Panel>
+ </Panel>
+ </Panel>
+ );
+}
+// #endregion
+
+// #region demo:layer-tokens
+function LayerTokensDemo() {
+ return (
+ <div class="grid w-full grid-cols-1 gap-4 md:grid-cols-3">
+ <For each={[0, 1, 2] as const}>
+ {(depth) => (
+ <Panel depth={depth} class="p-3 bg-surface">
+ <p class="mb-3 font-mono text-xs text-ink-subtle">depth={depth}</p>
+ <div class="flex flex-col gap-2">
+ <For each={[-2, -1, 0, 1, 2] as const}>
+ {(offset) => (
+ <Layer offset={offset}>
+ <div class="rounded-sm bg-surface p-2 text-xs text-ink-muted">
+ Layer offset={offset > 0 ? `+${offset}` : offset}
+ </div>
+ </Layer>
+ )}
+ </For>
+ </div>
+ </Panel>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:controls-on-depth
+function ControlsOnDepthDemo() {
+ return (
+ <div class="grid w-full grid-cols-1 gap-4 md:grid-cols-2">
+ <For each={[1, 2, 3, 4] as const}>
+ {(depth) => (
+ <Panel depth={depth}>
+ <Panel.Body class="flex flex-wrap gap-2 p-3">
+ <Button variant="ghost">Ghost</Button>
+ <Button variant="outline">Outline</Button>
+ <Button variant="accent">Accent</Button>
+ <Button variant="danger">Danger</Button>
+ </Panel.Body>
+ </Panel>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Surfaces & Depth',
+ category: 'Foundations',
+ description:
+ 'Depth, not a chosen color, is how backgrounds are set. A container declares its depth and everything inside reads `bg-surface` and `bg-inset` relative to it — so the same component looks right wherever it is nested.',
+ exports: ['Layer', 'Surface'],
+ import: "import { Layer, Panel, Surface } from '@ui';",
+ demos: [
+ {
+ id: 'depths',
+ title: 'The depth scale',
+ description:
+ 'Depth 0 sits furthest back and 4 closest to the viewer. `Panel` and `Surface` take a `depth` prop; `Layer` marks a subtree without rendering a box.',
+ render: DepthsDemo,
+ fill: true,
+ depth: 0,
+ },
+ {
+ id: 'nesting',
+ title: 'Nesting',
+ description:
+ 'Each level steps forward, which is what makes nested containers legible without borders doing all the work.',
+ render: NestingDemo,
+ fill: true,
+ depth: 0,
+ },
+ {
+ id: 'layer-tokens',
+ title: 'Layer-relative tokens',
+ description:
+ '`bg-inset` sits one step back and `bg-surface` is the layer itself. To move content forward, wrap it in `Layer offset={1}` and continue using `bg-surface`.',
+ render: LayerTokensDemo,
+ fill: true,
+ depth: 0,
+ },
+ {
+ id: 'controls-on-depth',
+ title: 'Controls across depths',
+ description:
+ 'Check any new component here. Contrast that only works at one depth is the most common design-system regression in the app.',
+ render: ControlsOnDepthDemo,
+ fill: true,
+ depth: 0,
+ },
+ ],
+ guidelines: {
+ do: [
+ 'Set `depth` on the container and let children read `bg-surface`.',
+ 'Use `bg-inset` for wells (inputs and code blocks) and `Layer offset={1}` with `bg-surface` for raised items.',
+ 'Verify new components at several depths using the toolbar control.',
+ ],
+ dont: [
+ 'Do not reference `bg-surface-2` and friends directly in a component; that pins it to one depth.',
+ 'Do not nest more than about three depth steps — past that the steps stop reading.',
+ ],
+ },
+});
diff --git a/apps/web/src/components/ui/foundations/typography.docs.tsx b/apps/web/src/components/ui/foundations/typography.docs.tsx
new file mode 100644
index 0000000000..0882af1322
--- /dev/null
+++ b/apps/web/src/components/ui/foundations/typography.docs.tsx
@@ -0,0 +1,157 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import { For } from 'solid-js';
+
+const SAMPLE = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
+
+// #region demo:sizes
+function SizesDemo() {
+ const sizes = [
+ { class: 'text-xs', note: 'Labels, badges, captions' },
+ { class: 'text-sm', note: 'Default UI text' },
+ { class: 'text-base', note: 'Body copy, reading surfaces' },
+ { class: 'text-lg', note: 'Section headings' },
+ { class: 'text-xl', note: 'Page headings' },
+ { class: 'text-2xl', note: 'Page titles' },
+ ];
+
+ return (
+ <div class="flex w-full flex-col gap-4">
+ <For each={sizes}>
+ {(size) => (
+ <div class="flex flex-col gap-1">
+ <div class="flex items-baseline gap-2">
+ <span class="font-mono text-xs text-ink-subtle">
+ {size.class}
+ </span>
+ <span class="text-xs text-ink-subtle">{size.note}</span>
+ </div>
+ <p class={`${size.class} text-ink`}>{SAMPLE}</p>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:hierarchy
+function HierarchyDemo() {
+ const inks = [
+ { class: 'text-ink', note: 'Primary content' },
+ { class: 'text-ink-muted', note: 'Supporting content' },
+ { class: 'text-ink-subtle', note: 'Labels and metadata' },
+ { class: 'text-ink-disabled', note: 'Unavailable controls' },
+ { class: 'text-ink-placeholder', note: 'Empty input hints' },
+ ];
+
+ return (
+ <div class="flex w-full flex-col gap-4">
+ <For each={inks}>
+ {(ink) => (
+ <div class="flex flex-col gap-1">
+ <div class="flex items-baseline gap-2">
+ <span class="font-mono text-xs text-ink-subtle">{ink.class}</span>
+ <span class="text-xs text-ink-subtle">{ink.note}</span>
+ </div>
+ <p class={`text-base ${ink.class}`}>{SAMPLE}</p>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
+// #region demo:matrix
+function MatrixDemo() {
+ const sizes = ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl'];
+ const inks = [
+ 'text-ink',
+ 'text-ink-muted',
+ 'text-ink-subtle',
+ 'text-ink-disabled',
+ 'text-ink-placeholder',
+ ];
+
+ return (
+ <table class="w-full border-collapse">
+ <thead>
+ <tr>
+ <th class="border-b border-edge-muted p-2 text-left text-xs text-ink-subtle">
+ Size / Ink
+ </th>
+ <For each={inks}>
+ {(ink) => (
+ <th class="border-b border-edge-muted p-2 text-left font-mono text-xs text-ink-subtle">
+ {ink.replace('text-ink', '') || 'ink'}
+ </th>
+ )}
+ </For>
+ </tr>
+ </thead>
+ <tbody>
+ <For each={sizes}>
+ {(size) => (
+ <tr>
+ <td class="border-b border-edge-muted p-2 font-mono text-xs text-ink-subtle">
+ {size}
+ </td>
+ <For each={inks}>
+ {(ink) => (
+ <td class={`border-b border-edge-muted p-2 ${size} ${ink}`}>
+ Aa
+ </td>
+ )}
+ </For>
+ </tr>
+ )}
+ </For>
+ </tbody>
+ </table>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Typography',
+ category: 'Foundations',
+ description:
+ 'Size sets scale, ink sets hierarchy. Between them they cover nearly every text decision in the app — reach for a different weight only when both are already right.',
+ demos: [
+ {
+ id: 'sizes',
+ title: 'Sizes',
+ description:
+ '`text-sm` is the default for UI chrome; `text-base` is for reading surfaces such as documents and messages.',
+ render: SizesDemo,
+ fill: true,
+ },
+ {
+ id: 'hierarchy',
+ title: 'Hierarchy',
+ description:
+ 'Establish rank with ink before reaching for size or weight. Two ink steps read as a clear hierarchy at the same size.',
+ render: HierarchyDemo,
+ fill: true,
+ },
+ {
+ id: 'matrix',
+ title: 'Size × ink',
+ description:
+ 'Every combination at a glance. Check the lower-contrast inks stay legible when you change a theme with the toolbar above.',
+ render: MatrixDemo,
+ fill: true,
+ },
+ ],
+ guidelines: {
+ do: [
+ 'Default to `text-sm` for interface text and `text-base` for content.',
+ 'Signal hierarchy with ink first, then size, then weight.',
+ 'Keep metadata and labels at `text-xs text-ink-subtle`.',
+ ],
+ dont: [
+ 'Do not introduce sizes outside this scale.',
+ 'Do not stack low-contrast ink on a small size for anything a user must read.',
+ ],
+ },
+});
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index a134812674..5955cf406b 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -90,6 +90,29 @@ export {
openDialog,
useImperativeDialog,
} from './components/ImperativeDialog';
+export type {
+ InputClassOptions,
+ InputProps,
+ InputSize,
+ InputVariant,
+ InputVariantProps,
+} from './components/Input';
+export {
+ Input,
+ inputClasses,
+ inputOutlineFocusClasses,
+ inputVariants,
+} from './components/Input';
+export type {
+ InputGroupAddonAlign,
+ InputGroupAddonProps,
+ InputGroupButtonProps,
+ InputGroupClearButtonProps,
+ InputGroupInputProps,
+ InputGroupProps,
+ InputGroupVariantProps,
+} from './components/InputGroup';
+export { InputGroup, inputGroupVariants } from './components/InputGroup';
export { Layer } from './components/Layer';
export { LogoProgress } from './components/LogoProgress';
export type { NavRowProps } from './components/NavRow';
@@ -118,6 +141,16 @@ export { Surface } from './components/Surface';
export { TabbedControl } from './components/TabbedControl';
export type { TabItem, TabsProps } from './components/Tabs';
export { Tabs } from './components/Tabs';
+export type {
+ TextFieldDescriptionProps,
+ TextFieldError,
+ TextFieldErrorMessageProps,
+ TextFieldInputProps,
+ TextFieldLabelProps,
+ TextFieldProps,
+ TextFieldTextAreaProps,
+} from './components/TextField';
+export { TextField } from './components/TextField';
export type { ToggleSwitchProps } from './components/ToggleSwitch';
export { ToggleSwitch } from './components/ToggleSwitch';
export { Tooltip } from './components/Tooltip';
diff --git a/apps/web/src/components/ui/utils/palette.test.ts b/apps/web/src/components/ui/utils/palette.test.ts
deleted file mode 100644
index 9e3286b15d..0000000000
--- a/apps/web/src/components/ui/utils/palette.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { getHashedPaletteColor, PALETTE_COLORS } from './palette';
-
-describe('getHashedPaletteColor', () => {
- it('keeps the default palette mapping stable', () => {
- expect(getHashedPaletteColor('document-author-id')).toBe('purple');
- expect(getHashedPaletteColor('another-author-id')).toBe('teal');
- });
-
- it('supports a typed palette for a specific use case', () => {
- const palette = ['text-success', 'text-failure'] as const;
-
- expect(getHashedPaletteColor('custom-stage', { palette })).toBe(
- 'text-failure'
- );
- });
-
- it('always returns an authored palette color by default', () => {
- expect(PALETTE_COLORS).toContain(getHashedPaletteColor(''));
- });
-});
diff --git a/apps/web/src/components/ui/utils/variants.test.ts b/apps/web/src/components/ui/utils/variants.test.ts
deleted file mode 100644
index d22373923e..0000000000
--- a/apps/web/src/components/ui/utils/variants.test.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { describe, expect, expectTypeOf, it } from 'vitest';
-import { createVariants, type VariantProps } from './variants';
-
-const badgeVariants = createVariants(
- 'inline-flex rounded px-2',
- {
- tone: {
- neutral: 'bg-surface text-ink',
- positive: 'bg-success-bg text-success',
- },
- size: {
- sm: 'h-5 px-1 text-xs',
- md: 'h-7 px-3 text-sm',
- },
- },
- {
- tone: 'neutral',
- size: 'md',
- }
-);
-
-describe('createVariants', () => {
- it('combines the base with selected variant classes', () => {
- const classes = badgeVariants({ tone: 'positive', size: 'sm' });
-
- expect(classes).toContain('inline-flex');
- expect(classes).toContain('bg-success-bg');
- expect(classes).toContain('h-5');
- });
-
- it('uses defaults for omitted selections', () => {
- const classes = badgeVariants({ tone: 'positive' });
-
- expect(classes).toContain('bg-success-bg');
- expect(classes).toContain('h-7');
- });
-
- it('omits a group with no selection or default', () => {
- const withoutDefaults = createVariants('base', {
- emphasis: {
- quiet: 'opacity-60',
- },
- });
-
- expect(withoutDefaults()).toBe('base');
- });
-
- it('merges conflicting Tailwind classes in variant order', () => {
- const classes = badgeVariants({ size: 'sm' });
-
- expect(classes).toContain('px-1');
- expect(classes).not.toContain('px-2');
- expect(classes).not.toContain('px-3');
- });
-
- it('infers group names and their allowed string values', () => {
- type BadgeVariantProps = VariantProps<typeof badgeVariants>;
-
- expectTypeOf<BadgeVariantProps>().toEqualTypeOf<{
- tone?: 'neutral' | 'positive';
- size?: 'sm' | 'md';
- }>();
- });
-});
diff --git a/apps/web/src/features/theme/utils/__tests__/themeColorTokens.test.ts b/apps/web/src/features/theme/utils/__tests__/themeColorTokens.test.ts
index d5a84baf8c..a41da5de30 100644
--- a/apps/web/src/features/theme/utils/__tests__/themeColorTokens.test.ts
+++ b/apps/web/src/features/theme/utils/__tests__/themeColorTokens.test.ts
@@ -62,6 +62,7 @@ describe('legacyThemeToVNextTokens', () => {
expect(defaults).toMatchObject({
surface: 'var(--layer-surface)',
panel: 'var(--color-surface-1)',
+ input: 'transparent',
warning: 'var(--color-amber)',
message: 'var(--color-surface-1)',
});
diff --git a/apps/web/src/features/theme/utils/themeColorTokens.ts b/apps/web/src/features/theme/utils/themeColorTokens.ts
index 405755044a..a527593a46 100644
--- a/apps/web/src/features/theme/utils/themeColorTokens.ts
+++ b/apps/web/src/features/theme/utils/themeColorTokens.ts
@@ -5,6 +5,7 @@ import type {
ThemeColorTokens,
ThemeV2,
ThemeV2Tokens,
+ ThemeV3,
} from '../types/themeTypes';
/** Tailwind 500 hue angles used to project a legacy theme's accent color. */
@@ -192,3 +193,61 @@ export function isInputColorToken(token: string): token is InputColorToken {
token in PALETTE_HUES
);
}
+
+const LAYER_RELATIVE_TOKENS = {
+ surface: 'var(--layer-surface)',
+ inset: 'var(--layer-inset)',
+} as const;
+
+/** Tokens whose public `--color-*` var is owned by the layer CSS rather than
+ * written directly. */
+export function isStructuralThemeToken(token: string): boolean {
+ return token === 'panel' || token in LAYER_RELATIVE_TOKENS;
+}
+
+/**
+ * Maps one authored theme token to the CSS custom property that carries it.
+ * Returns null when CSS owns the public var and the authored value is already
+ * the default, i.e. there is nothing to write.
+ *
+ * Shared by the document-level renderer and by `themeCssVars`, so scoping a
+ * theme to a subtree resolves tokens exactly the way the root does.
+ */
+export function themeTokenCssVar(
+ token: string,
+ value: string
+): { name: string; value: string } | null {
+ if (token === 'panel') {
+ // Keep the authored structural value separate from the public semantic var
+ // so containers can scope --color-panel without losing the theme source.
+ return { name: '--theme-panel', value };
+ }
+
+ const layerDefault =
+ LAYER_RELATIVE_TOKENS[token as keyof typeof LAYER_RELATIVE_TOKENS];
+
+ if (layerDefault) {
+ // CSS owns the public --color-* mapping for layer-relative semantics.
+ // Only author an optional theme override when the assignment is custom.
+ return value === layerDefault ? null : { name: `--theme-${token}`, value };
+ }
+
+ return { name: `--color-${token}`, value };
+}
+
+/**
+ * All of a theme's tokens as inline CSS custom properties, for rendering a
+ * theme inside a subtree instead of on the document. Every authored value is
+ * either a literal color or a `var()`/`color-mix()` expression over other
+ * `--color-*` tokens, so the whole set resolves against whichever element it is
+ * set on.
+ */
+export function themeCssVars(theme: ThemeV3): Record<string, string> {
+ const tokens = normalizeThemeColorTokens(theme.colorTokens, theme.mode);
+ const vars: Record<string, string> = {};
+ for (const [token, value] of Object.entries(tokens)) {
+ const mapped = themeTokenCssVar(token, value);
+ if (mapped) vars[mapped.name] = mapped.value;
+ }
+ return vars;
+}
diff --git a/apps/web/src/features/theme/utils/themeUtils.ts b/apps/web/src/features/theme/utils/themeUtils.ts
index ce6e13c866..c244cb5715 100644
--- a/apps/web/src/features/theme/utils/themeUtils.ts
+++ b/apps/web/src/features/theme/utils/themeUtils.ts
@@ -28,7 +28,11 @@ import type {
ThemeV3,
} from '../types/themeTypes';
import { getOklch } from './colorUtil';
-import { normalizeThemeColorTokens } from './themeColorTokens';
+import {
+ isStructuralThemeToken,
+ normalizeThemeColorTokens,
+ themeTokenCssVar,
+} from './themeColorTokens';
import { convertThemev2v3 } from './themeMigrations';
import { isThemeV2, isThemeV3 } from './themeValidation';
@@ -132,36 +136,18 @@ function syncLegacyCompatibilityTokens(): void {
});
}
-const LAYER_RELATIVE_TOKENS = {
- surface: 'var(--layer-surface)',
- inset: 'var(--layer-inset)',
-} as const;
-
function renderThemeColorToken(token: string, value: string): void {
- if (token === 'panel') {
- // Keep the authored structural value separate from the public semantic var
- // so containers can scope --color-panel without losing the theme source.
- document.documentElement.style.removeProperty('--color-panel');
- document.documentElement.style.setProperty('--theme-panel', value);
- return;
- }
-
- const layerDefault =
- LAYER_RELATIVE_TOKENS[token as keyof typeof LAYER_RELATIVE_TOKENS];
+ const mapped = themeTokenCssVar(token, value);
- if (layerDefault) {
- // CSS owns the public --color-* mapping for layer-relative semantics.
- // Only author an optional theme override when the assignment is custom.
+ if (isStructuralThemeToken(token)) {
document.documentElement.style.removeProperty(`--color-${token}`);
- if (value === layerDefault) {
- document.documentElement.style.removeProperty(`--theme-${token}`);
- } else {
- document.documentElement.style.setProperty(`--theme-${token}`, value);
- }
- return;
}
- document.documentElement.style.setProperty(`--color-${token}`, value);
+ if (mapped) {
+ document.documentElement.style.setProperty(mapped.name, mapped.value);
+ } else {
+ document.documentElement.style.removeProperty(`--theme-${token}`);
+ }
}
/** Applies a color token for an editor drag without updating persisted state. */
diff --git a/apps/web/src/features/ui-gallery/UiGallery.test.tsx b/apps/web/src/features/ui-gallery/UiGallery.test.tsx
new file mode 100644
index 0000000000..d25cb3178d
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/UiGallery.test.tsx
@@ -0,0 +1,130 @@
+import { MemoryRouter, Route } from '@solidjs/router';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { type JSX, Suspense } from 'solid-js';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { CoveragePage } from './components/CoveragePage';
+import { DocPage } from './components/DocPage';
+import { coverageRows, DOC_ENTRIES } from './registry';
+import UiGallery from './UiGallery';
+
+vi.mock('@components/app/split-layout/components/SplitHeader', () => ({
+ SplitHeaderLeft: (props: { children: JSX.Element }) => props.children,
+ SplitHeaderRight: (props: { children: JSX.Element }) => props.children,
+}));
+
+vi.mock('@components/app/split-layout/components/SplitLabel', () => ({
+ StaticSplitLabel: (props: { label: string }) => <span>{props.label}</span>,
+}));
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeAll(() => {
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+});
+
+afterEach(cleanup);
+
+function renderGallery() {
+ return render(() => (
+ <MemoryRouter>
+ <Route path="/" component={UiGallery} />
+ </MemoryRouter>
+ ));
+}
+
+describe('UiGallery', () => {
+ it('renders the sidebar with every documented component', () => {
+ renderGallery();
+ const search = screen.getByRole('searchbox', {
+ name: 'Search components',
+ });
+ expect(search.dataset.slot).toBe('input-group-control');
+ const inputGroup = search.closest('[data-slot="input-group"]');
+ expect(inputGroup?.classList).toContain('bg-input');
+ expect(search.classList).toContain('bg-transparent');
+ expect(search.classList).toContain(
+ '[&::-webkit-search-cancel-button]:hidden'
+ );
+ for (const entry of DOC_ENTRIES) {
+ expect(screen.getAllByText(entry.doc.name).length).toBeGreaterThan(0);
+ }
+ });
+
+ it('shows Foundation Colors when no page is selected', () => {
+ renderGallery();
+ expect(
+ screen.getByRole('heading', { level: 1, name: 'Colors' })
+ ).toBeTruthy();
+ });
+
+ it('hides page code by default and toggles all examples from the header', async () => {
+ const { container } = renderGallery();
+ const toggle = screen.getByRole('switch', { name: 'Show code' });
+
+ expect((toggle as HTMLInputElement).checked).toBe(false);
+ expect(container.querySelectorAll('pre')).toHaveLength(0);
+
+ fireEvent.click(toggle);
+ await waitFor(() => {
+ expect(container.querySelectorAll('pre').length).toBeGreaterThan(0);
+ });
+
+ fireEvent.click(toggle);
+ await waitFor(() => {
+ expect(container.querySelectorAll('pre')).toHaveLength(0);
+ });
+ });
+
+ it('offers the coverage report', () => {
+ renderGallery();
+ expect(screen.getByText('Coverage')).toBeTruthy();
+ });
+});
+
+describe('CoveragePage', () => {
+ it('renders the coverage report', () => {
+ render(() => <CoveragePage onSelect={() => {}} />);
+ expect(
+ screen.getByRole('heading', { level: 1, name: 'Coverage' })
+ ).toBeTruthy();
+ });
+
+ it('lists every ui component with its documentation status', () => {
+ render(() => <CoveragePage onSelect={() => {}} />);
+ for (const row of coverageRows()) {
+ expect(screen.getAllByText(row.name).length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('DocPage suspense safety', () => {
+ // The split layout wraps panel content in a <Suspense> with no fallback
+ // (SplitLayout.tsx), so a resource read that is still pending detaches the
+ // whole pane and renders nothing — silently, with no console error. Every
+ // resource read in DocPage is gated on state for this reason.
+ it('renders without suspending while its resources are still pending', () => {
+ const entry = DOC_ENTRIES.find((e) => e.doc.name === 'Button');
+ if (!entry) throw new Error('Button page missing');
+
+ const { container } = render(() => (
+ <Suspense fallback={<span data-testid="suspended">suspended</span>}>
+ <DocPage entry={entry} showCode={false} />
+ </Suspense>
+ ));
+
+ expect(container.querySelector('[data-testid="suspended"]')).toBeNull();
+ expect(
+ screen.getByRole('heading', { level: 1, name: 'Button' })
+ ).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/features/ui-gallery/UiGallery.tsx b/apps/web/src/features/ui-gallery/UiGallery.tsx
new file mode 100644
index 0000000000..320247debc
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/UiGallery.tsx
@@ -0,0 +1,75 @@
+import { useSearchParams } from '@solidjs/router';
+import { Scroll, ToggleSwitch } from '@ui';
+import { createMemo, createSignal, Show } from 'solid-js';
+import './gallery.css';
+import {
+ SplitHeaderLeft,
+ SplitHeaderRight,
+} from '@components/app/split-layout/components/SplitHeader';
+import { StaticSplitLabel } from '@components/app/split-layout/components/SplitLabel';
+import { CoveragePage } from './components/CoveragePage';
+import { DocPage } from './components/DocPage';
+import { COVERAGE_SLUG, GallerySidebar } from './components/GallerySidebar';
+import { DOC_ENTRIES, findEntry, groupEntries } from './registry';
+
+/** Query param carrying the selected page, so a component is linkable. The
+ * split layout drops params from `component/<id>` URLs, so selection lives in
+ * the query string the same way the CRM's saved view does. */
+const PAGE_PARAM = 'ui';
+const DEFAULT_ENTRY = groupEntries(DOC_ENTRIES)[0]?.entries[0];
+
+/**
+ * Browsable documentation for the `@ui` library: a stable sidebar and page
+ * chrome around live component previews.
+ *
+ * Pages are `*.docs.tsx` files co-located with the components they document
+ * (see `registry.ts`), and each demo's code is read back out of its own source
+ * so the snippet can never drift from the preview above it.
+ */
+export default function UiGallery() {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [showCode, setShowCode] = createSignal(false);
+
+ const selected = () => {
+ const param = searchParams[PAGE_PARAM];
+ const slug = Array.isArray(param) ? param[0] : param;
+ return slug ?? DEFAULT_ENTRY?.slug ?? COVERAGE_SLUG;
+ };
+
+ const select = (slug: string) =>
+ setSearchParams({ [PAGE_PARAM]: slug }, { scroll: false });
+
+ const entry = createMemo(() => findEntry(selected()));
+
+ return (
+ <>
+ <SplitHeaderLeft>
+ <StaticSplitLabel label="UI Components" />
+ </SplitHeaderLeft>
+ <SplitHeaderRight>
+ <ToggleSwitch
+ checked={showCode()}
+ onChange={setShowCode}
+ label="Show code"
+ labelClass="text-xs text-ink-muted"
+ />
+ </SplitHeaderRight>
+
+ <div class="ui-gallery size-full flex min-h-0 border-t border-edge-muted">
+ <GallerySidebar
+ entries={DOC_ENTRIES}
+ selected={selected()}
+ onSelect={select}
+ />
+
+ <div class="flex-1 min-w-0 flex flex-col">
+ <Scroll class="flex-1 min-h-0 p-4 select-children">
+ <Show when={entry()} fallback={<CoveragePage onSelect={select} />}>
+ {(found) => <DocPage entry={found()} showCode={showCode()} />}
+ </Show>
+ </Scroll>
+ </div>
+ </div>
+ </>
+ );
+}
diff --git a/apps/web/src/features/ui-gallery/components/CodeBlock.tsx b/apps/web/src/features/ui-gallery/components/CodeBlock.tsx
new file mode 100644
index 0000000000..096f835d4f
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/components/CodeBlock.tsx
@@ -0,0 +1,108 @@
+import { tsxLanguage } from '@codemirror/lang-javascript';
+import { classHighlighter, highlightCode } from '@lezer/highlight';
+import CheckIcon from '@phosphor/check.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import { Button, cn } from '@ui';
+import { createMemo, createSignal, For, onCleanup, Show } from 'solid-js';
+
+type Token = { text: string; classes: string };
+
+/**
+ * Highlights TSX with the same Lezer grammar CodeMirror uses, but statically —
+ * the gallery renders many snippets per page and none of them are editable, so
+ * spinning up editor instances would be pure overhead.
+ */
+function tokenizeLines(code: string): Token[][] {
+ const lines: Token[][] = [[]];
+ const push = (text: string, classes: string) => {
+ lines[lines.length - 1]!.push({ text, classes });
+ };
+
+ try {
+ highlightCode(
+ code,
+ tsxLanguage.parser.parse(code),
+ classHighlighter,
+ push,
+ () => lines.push([])
+ );
+ } catch {
+ // A snippet that fails to parse is still worth reading unhighlighted.
+ return code.split('\n').map((line) => [{ text: line, classes: '' }]);
+ }
+
+ return lines;
+}
+
+function CopyButton(props: { code: string }) {
+ const [copied, setCopied] = createSignal(false);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ onCleanup(() => clearTimeout(timer));
+
+ const copy = async () => {
+ await navigator.clipboard.writeText(props.code);
+ setCopied(true);
+ clearTimeout(timer);
+ timer = setTimeout(() => setCopied(false), 1500);
+ };
+
+ return (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ label={copied() ? 'Copied' : 'Copy code'}
+ onClick={copy}
+ >
+ <Show when={copied()} fallback={<CopyIcon />}>
+ <CheckIcon class="text-success" />
+ </Show>
+ </Button>
+ );
+}
+
+export function CodeBlock(props: {
+ code: string;
+ class?: string;
+ /** Hides the gutter for one-liners like an import statement. */
+ compact?: boolean;
+}) {
+ const lines = createMemo(() => tokenizeLines(props.code));
+
+ return (
+ <div
+ class={cn(
+ 'group/code relative bg-code-buffer border border-edge-muted rounded-md overflow-hidden',
+ props.class
+ )}
+ >
+ <div class="absolute right-1 top-1 opacity-0 transition-opacity group-hover/code:opacity-100 focus-within:opacity-100">
+ <CopyButton code={props.code} />
+ </div>
+ <pre class="overflow-x-auto p-3 text-xs leading-5 font-mono text-ink">
+ <code>
+ <For each={lines()}>
+ {(tokens, index) => (
+ <div class="flex">
+ <Show when={!props.compact}>
+ <span
+ aria-hidden="true"
+ class="select-none shrink-0 w-8 pr-3 text-right text-ink-extra-muted"
+ >
+ {index() + 1}
+ </span>
+ </Show>
+ <span class="min-w-0">
+ <For each={tokens}>
+ {(token) => <span class={token.classes}>{token.text}</span>}
+ </For>
+ {/* Keeps empty lines from collapsing to zero height. */}
+ <Show when={tokens.length === 0}>{'​'}</Show>
+ </span>
+ </div>
+ )}
+ </For>
+ </code>
+ </pre>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/ui-gallery/components/CoveragePage.tsx b/apps/web/src/features/ui-gallery/components/CoveragePage.tsx
new file mode 100644
index 0000000000..b1a2a0c18e
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/components/CoveragePage.tsx
@@ -0,0 +1,77 @@
+import { Badge, Button } from '@ui';
+import { createMemo, For, Show } from 'solid-js';
+import { coverageRows } from '../registry';
+
+/**
+ * Which `@ui` components have a docs page and which do not.
+ *
+ * Usage and restyle data deliberately lives in the `ui-audit` CLI rather than
+ * here — it is a whole-codebase scan, and the terminal is where you act on it.
+ * Run `bun run ui-audit`.
+ */
+export function CoveragePage(props: { onSelect: (slug: string) => void }) {
+ const rows = createMemo(() => coverageRows());
+ const documented = createMemo(() => rows().filter((row) => row.entry).length);
+ const percent = createMemo(() =>
+ rows().length === 0 ? 0 : Math.round((documented() / rows().length) * 100)
+ );
+
+ return (
+ <article class="flex flex-col gap-6 max-w-3xl">
+ <header class="flex flex-col gap-2">
+ <h1 class="text-2xl font-semibold text-ink">Coverage</h1>
+ <p class="text-sm text-ink-muted">
+ {documented()} of {rows().length} components in{' '}
+ <code class="font-mono text-xs">src/components/ui/components</code>{' '}
+ have a page ({percent()}%). Add one by dropping a{' '}
+ <code class="font-mono text-xs">&lt;Name&gt;.docs.tsx</code> file
+ beside the component — the sidebar picks it up automatically.
+ </p>
+ <p class="text-xs text-ink-subtle">
+ For how much each component is actually used, and where call sites
+ have to reskin one, run{' '}
+ <code class="font-mono">bun run ui-audit</code>.
+ </p>
+ </header>
+
+ <div
+ class="h-1.5 w-full rounded-full bg-inset overflow-hidden"
+ role="progressbar"
+ aria-valuenow={percent()}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-label="Documentation coverage"
+ >
+ <div class="h-full bg-accent" style={{ width: `${percent()}%` }} />
+ </div>
+
+ <ul class="flex flex-col rounded-md border border-edge-muted overflow-hidden">
+ <For each={rows()}>
+ {(row) => (
+ <li class="flex items-center justify-between gap-3 px-3 py-2 border-b border-edge-muted last:border-b-0">
+ <span class="font-mono text-sm text-ink">{row.name}</span>
+ <Show
+ when={row.entry}
+ fallback={
+ <Badge variant="outline" size="sm" class="text-ink-subtle">
+ Undocumented
+ </Badge>
+ }
+ >
+ {(entry) => (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => props.onSelect(entry().slug)}
+ >
+ {entry().doc.name}
+ </Button>
+ )}
+ </Show>
+ </li>
+ )}
+ </For>
+ </ul>
+ </article>
+ );
+}
diff --git a/apps/web/src/features/ui-gallery/components/DemoPreview.tsx b/apps/web/src/features/ui-gallery/components/DemoPreview.tsx
new file mode 100644
index 0000000000..91a456ea77
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/components/DemoPreview.tsx
@@ -0,0 +1,35 @@
+import { cn, Layer } from '@ui';
+import type { JSX } from 'solid-js';
+
+/**
+ * The frame every demo renders inside.
+ */
+export function DemoPreview(props: {
+ /** Per-demo surface depth. */
+ depth?: 0 | 1 | 2 | 3 | 4;
+ fill?: boolean;
+ class?: string;
+ children: JSX.Element;
+}) {
+ return (
+ <div
+ class={cn(
+ 'rounded-md border border-edge-muted overflow-hidden',
+ props.class
+ )}
+ >
+ <Layer depth={props.depth ?? 1}>
+ <div
+ class={cn(
+ 'bg-surface p-6 min-h-32',
+ props.fill
+ ? 'block'
+ : 'flex flex-wrap items-center justify-center gap-3'
+ )}
+ >
+ {props.children}
+ </div>
+ </Layer>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/ui-gallery/components/DocPage.tsx b/apps/web/src/features/ui-gallery/components/DocPage.tsx
new file mode 100644
index 0000000000..41ef7e97e1
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/components/DocPage.tsx
@@ -0,0 +1,196 @@
+import { Badge } from '@ui';
+import { createResource, For, Show } from 'solid-js';
+import { type DocEntry, loadTypeSource } from '../registry';
+import { extractDemoSource, extractGuidelines } from '../source';
+import type { DocDemo, DocStatus } from '../types';
+import { CodeBlock } from './CodeBlock';
+import { DemoPreview } from './DemoPreview';
+
+const STATUS_LABEL: Record<DocStatus, string> = {
+ stable: 'Stable',
+ beta: 'Beta',
+ deprecated: 'Deprecated',
+ internal: 'Internal',
+};
+
+function DemoSection(props: {
+ demo: DocDemo;
+ source: string | undefined;
+ showCode: boolean;
+}) {
+ return (
+ <section class="flex flex-col gap-3">
+ <div class="flex flex-col gap-1">
+ <h3 class="text-base font-medium text-ink">{props.demo.title}</h3>
+ <Show when={props.demo.description}>
+ <p class="text-sm text-ink-muted">{props.demo.description}</p>
+ </Show>
+ </div>
+
+ <DemoPreview depth={props.demo.depth} fill={props.demo.fill}>
+ {props.demo.render()}
+ </DemoPreview>
+
+ <Show when={props.showCode}>
+ <Show
+ when={props.source}
+ fallback={
+ <p class="text-xs text-ink-subtle">
+ No source found. Wrap this demo in{' '}
+ <code class="font-mono text-ink-muted">
+ {`// #region demo:${props.demo.id}`}
+ </code>{' '}
+ / <code class="font-mono text-ink-muted">{'// #endregion'}</code>{' '}
+ to show its code here.
+ </p>
+ }
+ >
+ {(source) => <CodeBlock code={source()} />}
+ </Show>
+ </Show>
+ </section>
+ );
+}
+
+/** One component's page: header, demos with source, props, and guidelines. */
+export function DocPage(props: { entry: DocEntry; showCode: boolean }) {
+ // Raw file text is fetched per page rather than bundled with the registry, so
+ // the gallery chunk stays free of a second copy of every docs file.
+ const [source] = createResource(
+ () => (props.showCode ? props.entry : undefined),
+ (entry) => entry.loadSource()
+ );
+
+ // The implementation is the source of truth for guidance and prop types, so
+ // neither is restated in the docs file.
+ const [componentSource] = createResource(
+ () => props.entry,
+ (entry) => entry.loadComponentSource?.() ?? null
+ );
+
+ // Reading a resource value suspends the nearest <Suspense> while it is
+ // pending, and the split layout's boundary has no fallback (SplitLayout.tsx),
+ // so an unguarded read blanks the entire pane with no console error. Every
+ // read below is gated on state; reading `.state` itself never suspends.
+ const docText = () => (source.state === 'ready' ? source() : undefined);
+ const componentText = () =>
+ componentSource.state === 'ready' ? componentSource() : undefined;
+ const resolvedPropTypes = () =>
+ propTypes.state === 'ready' ? (propTypes() ?? []) : [];
+
+ const guidelines = () => {
+ const component = componentText();
+ const fromCode = component
+ ? extractGuidelines(component)
+ : { do: [], dont: [] };
+ if (fromCode.do.length || fromCode.dont.length) return fromCode;
+ // Foundations pages have no component to annotate.
+ const inline = props.entry.doc.guidelines;
+ return inline ? { do: inline.do ?? [], dont: inline.dont ?? [] } : null;
+ };
+
+ const [propTypes] = createResource(
+ () => (props.showCode ? props.entry : undefined),
+ async (entry) => {
+ const names = entry.doc.propTypes ?? [
+ `${entry.doc.name.replace(/\s+/g, '')}Props`,
+ ];
+ const found = await Promise.all(
+ names.map((name) => loadTypeSource(name))
+ );
+ return found.filter((value): value is string => Boolean(value));
+ }
+ );
+
+ const sourceFor = (demo: DocDemo) => {
+ const text = docText();
+ if (!text) return undefined;
+ return extractDemoSource(text, demo.id) ?? undefined;
+ };
+
+ return (
+ <article class="flex flex-col gap-10 max-w-3xl mx-auto">
+ <header class="flex flex-col gap-3">
+ <div class="flex items-center gap-2">
+ <h1 class="text-2xl font-semibold text-ink">
+ {props.entry.doc.name}
+ </h1>
+ <Show when={props.entry.doc.status}>
+ {(status) => (
+ <Badge variant="outline" size="sm">
+ {STATUS_LABEL[status()]}
+ </Badge>
+ )}
+ </Show>
+ </div>
+ <p class="text-sm text-ink-muted">{props.entry.doc.description}</p>
+ <Show when={props.showCode}>
+ <Show when={props.entry.doc.import}>
+ {(line) => <CodeBlock compact code={line()} />}
+ </Show>
+ </Show>
+ </header>
+
+ <div class="flex flex-col gap-10">
+ <For each={props.entry.doc.demos}>
+ {(demo) => (
+ <DemoSection
+ demo={demo}
+ source={sourceFor(demo)}
+ showCode={props.showCode}
+ />
+ )}
+ </For>
+ </div>
+
+ <Show when={props.showCode && resolvedPropTypes().length}>
+ <section class="flex flex-col gap-3">
+ <h2 class="text-lg font-semibold text-ink">Props</h2>
+ <p class="text-sm text-ink-muted">
+ Read straight from the component, so it cannot drift.
+ </p>
+ <For each={resolvedPropTypes()}>
+ {(declaration) => <CodeBlock code={declaration} />}
+ </For>
+ </section>
+ </Show>
+
+ <Show when={guidelines()}>
+ {(guidelines) => (
+ <section class="flex flex-col gap-3">
+ <h2 class="text-lg font-semibold text-ink">Guidelines</h2>
+ <div class="grid gap-4 sm:grid-cols-2">
+ <Show when={guidelines().do.length}>
+ <div class="flex flex-col gap-2 rounded-md border border-edge-muted p-3">
+ <span class="text-xs font-medium text-success">Do</span>
+ <ul class="flex flex-col gap-1.5">
+ <For each={guidelines().do}>
+ {(item) => <li class="text-sm text-ink-muted">{item}</li>}
+ </For>
+ </ul>
+ </div>
+ </Show>
+ <Show when={guidelines().dont.length}>
+ <div class="flex flex-col gap-2 rounded-md border border-edge-muted p-3">
+ <span class="text-xs font-medium text-failure">Don't</span>
+ <ul class="flex flex-col gap-1.5">
+ <For each={guidelines().dont}>
+ {(item) => <li class="text-sm text-ink-muted">{item}</li>}
+ </For>
+ </ul>
+ </div>
+ </Show>
+ </div>
+ </section>
+ )}
+ </Show>
+
+ <footer class="pt-2 border-t border-edge-muted">
+ <p class="text-xs text-ink-subtle">
+ Edit this page at{' '}
+ <code class="font-mono">apps/web/{props.entry.path}</code>
+ </p>
+ </footer>
+ </article>
+ );
+}
diff --git a/apps/web/src/features/ui-gallery/components/GallerySidebar.tsx b/apps/web/src/features/ui-gallery/components/GallerySidebar.tsx
new file mode 100644
index 0000000000..cb37a24284
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/components/GallerySidebar.tsx
@@ -0,0 +1,83 @@
+import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';
+import { Badge, InputGroup, Scroll, SideNav } from '@ui';
+import { createMemo, createSignal, For, Show } from 'solid-js';
+import { type DocEntry, filterEntries, groupEntries } from '../registry';
+
+export const COVERAGE_SLUG = '__coverage';
+
+/**
+ * Sections + component index. Deliberately built from `@ui` primitives so the
+ * gallery dogfoods the library it documents.
+ */
+export function GallerySidebar(props: {
+ entries: readonly DocEntry[];
+ selected: string;
+ onSelect: (slug: string) => void;
+}) {
+ const [query, setQuery] = createSignal('');
+ const matches = createMemo(() => filterEntries(props.entries, query()));
+ const groups = createMemo(() => groupEntries(matches()));
+
+ return (
+ <div class="w-60 shrink-0 flex flex-col border-r border-edge-muted">
+ <div class="p-3 pb-2">
+ <InputGroup>
+ <InputGroup.Input
+ type="search"
+ value={query()}
+ onInput={(event) => setQuery(event.currentTarget.value)}
+ placeholder="Search components"
+ aria-label="Search components"
+ />
+ <InputGroup.Addon align="inline-start">
+ <MagnifyingGlassIcon aria-hidden="true" />
+ </InputGroup.Addon>
+ <InputGroup.Addon align="inline-end">
+ <InputGroup.ClearButton />
+ </InputGroup.Addon>
+ </InputGroup>
+ </div>
+
+ <Scroll class="flex-1 min-h-0">
+ <SideNav class="w-full">
+ <For each={groups()}>
+ {(group) => (
+ <SideNav.Group label={group.category}>
+ <For each={group.entries}>
+ {(entry) => (
+ <SideNav.Item
+ active={entry.slug === props.selected}
+ onSelect={() => props.onSelect(entry.slug)}
+ >
+ {entry.doc.name}
+ </SideNav.Item>
+ )}
+ </For>
+ </SideNav.Group>
+ )}
+ </For>
+
+ <Show when={matches().length === 0}>
+ <p class="px-2 py-4 text-sm text-ink-subtle">
+ No components match “{query()}”.
+ </p>
+ </Show>
+
+ <SideNav.Group label="Meta">
+ <SideNav.Item
+ active={props.selected === COVERAGE_SLUG}
+ onSelect={() => props.onSelect(COVERAGE_SLUG)}
+ >
+ <span class="flex items-center gap-2">
+ Coverage
+ <Badge variant="outline" size="sm">
+ {props.entries.length}
+ </Badge>
+ </span>
+ </SideNav.Item>
+ </SideNav.Group>
+ </SideNav>
+ </Scroll>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/ui-gallery/gallery.css b/apps/web/src/features/ui-gallery/gallery.css
new file mode 100644
index 0000000000..3776b351eb
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/gallery.css
@@ -0,0 +1,53 @@
+/* Token classes emitted by Lezer's `classHighlighter`, mapped onto theme
+ palette tokens so snippets recolor with the rest of the app. Scoped to the
+ gallery so nothing here leaks into product surfaces. */
+.ui-gallery {
+ .tok-comment {
+ color: var(--color-ink-subtle);
+ font-style: italic;
+ }
+ .tok-keyword,
+ .tok-modifier,
+ .tok-controlKeyword,
+ .tok-operatorKeyword {
+ color: var(--color-purple);
+ }
+ .tok-string,
+ .tok-string2,
+ .tok-attributeValue {
+ color: var(--color-green);
+ }
+ .tok-number,
+ .tok-bool,
+ .tok-null,
+ .tok-atom {
+ color: var(--color-orange);
+ }
+ .tok-tagName,
+ .tok-typeName,
+ .tok-className,
+ .tok-namespace {
+ color: var(--color-blue);
+ }
+ .tok-attributeName,
+ .tok-propertyName {
+ color: var(--color-cyan);
+ }
+ .tok-variableName {
+ color: var(--color-ink);
+ }
+ .tok-function {
+ color: var(--color-yellow);
+ }
+ .tok-operator,
+ .tok-punctuation,
+ .tok-bracket,
+ .tok-angleBracket,
+ .tok-separator,
+ .tok-derefOperator {
+ color: var(--color-ink-subtle);
+ }
+ .tok-invalid {
+ color: var(--color-failure);
+ }
+}
diff --git a/apps/web/src/features/ui-gallery/registry.test.tsx b/apps/web/src/features/ui-gallery/registry.test.tsx
new file mode 100644
index 0000000000..0a7aeb5285
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/registry.test.tsx
@@ -0,0 +1,117 @@
+import { cleanup, render } from '@solidjs/testing-library';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import {
+ coverageRows,
+ DOC_ENTRIES,
+ filterEntries,
+ groupEntries,
+ loadTypeSource,
+} from './registry';
+import { extractDemoSource, extractGuidelines } from './source';
+
+/** jsdom has no ResizeObserver; `Scroll` (and so `Panel.Body scroll`) needs one
+ * to construct. Demos only have to mount here, not resize. */
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeAll(() => {
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+});
+
+afterEach(cleanup);
+
+describe('doc registry', () => {
+ it('discovers pages from the co-located .docs.tsx files', () => {
+ expect(DOC_ENTRIES.length).toBeGreaterThan(0);
+ });
+
+ it('gives every page a unique slug', () => {
+ const slugs = DOC_ENTRIES.map((entry) => entry.slug);
+ expect(new Set(slugs).size).toBe(slugs.length);
+ });
+
+ it('groups only into known categories', () => {
+ const grouped = groupEntries(DOC_ENTRIES).flatMap((group) => group.entries);
+ expect(grouped.length).toBe(DOC_ENTRIES.length);
+ });
+
+ it('filters on name, category, and exports', () => {
+ const byName = filterEntries(DOC_ENTRIES, 'button');
+ expect(byName.some((entry) => entry.doc.name === 'Button')).toBe(true);
+ expect(filterEntries(DOC_ENTRIES, '').length).toBe(DOC_ENTRIES.length);
+ expect(filterEntries(DOC_ENTRIES, 'zzzznope')).toHaveLength(0);
+ });
+
+ it('reports coverage for every ui component file', () => {
+ const rows = coverageRows();
+ expect(rows.length).toBeGreaterThan(0);
+ expect(rows.some((row) => row.name === 'Button' && row.entry)).toBe(true);
+ });
+});
+
+describe.each(DOC_ENTRIES.map((entry) => [entry.doc.name, entry] as const))(
+ '%s docs',
+ (_name, entry) => {
+ it('has at least one demo with a unique id', () => {
+ expect(entry.doc.demos.length).toBeGreaterThan(0);
+ const ids = entry.doc.demos.map((demo) => demo.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ // The whole point of the region markers is that the code shown is the code
+ // that ran. A typo'd or missing marker silently degrades a page to "no
+ // source found", so it fails here instead.
+ it('wraps every demo in a matching #region marker', async () => {
+ const source = await entry.loadSource();
+ for (const demo of entry.doc.demos) {
+ expect(
+ extractDemoSource(source, demo.id),
+ `${entry.path} is missing "// #region demo:${demo.id}"`
+ ).toBeTruthy();
+ }
+ });
+
+ // Guidance now lives as @do/@dont JSDoc on the component. A page that
+ // silently resolves none would render an empty Guidelines section.
+ it('resolves guidance from the component or declares its own', async () => {
+ const source = await entry.loadComponentSource?.();
+ const fromCode = source
+ ? extractGuidelines(source)
+ : { do: [], dont: [] };
+ const inline = entry.doc.guidelines;
+ const total =
+ fromCode.do.length +
+ fromCode.dont.length +
+ (inline?.do?.length ?? 0) +
+ (inline?.dont?.length ?? 0);
+ expect(total, `${entry.path} has no guidance`).toBeGreaterThan(0);
+ });
+
+ it('does not restate props the types already declare', () => {
+ expect(entry.doc).not.toHaveProperty('props');
+ });
+
+ // A page whose default `<Name>Props` guess misses (Select's root is
+ // generic, Panel's is a bare alias) must name the real type instead.
+ it('resolves the prop types it points at', async () => {
+ const names = entry.doc.propTypes ?? [
+ `${entry.doc.name.replace(/\s+/g, '')}Props`,
+ ];
+ if (!entry.loadComponentSource) return;
+ const found = await Promise.all(names.map((n) => loadTypeSource(n)));
+ expect(found.filter(Boolean).length, `${entry.doc.name}: ${names}`).toBe(
+ names.length
+ );
+ });
+
+ it.each(entry.doc.demos.map((demo) => [demo.id, demo] as const))(
+ 'renders the %s demo',
+ (_id, demo) => {
+ expect(() => render(() => demo.render())).not.toThrow();
+ }
+ );
+ }
+);
diff --git a/apps/web/src/features/ui-gallery/registry.ts b/apps/web/src/features/ui-gallery/registry.ts
new file mode 100644
index 0000000000..c84b751b4e
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/registry.ts
@@ -0,0 +1,182 @@
+import { extractTypeSource } from './source';
+import { type ComponentDoc, DOC_CATEGORIES, type DocCategory } from './types';
+
+/**
+ * Every `.docs.tsx` file under `components/ui`, discovered at build time.
+ * Adding a page is adding a file — there is no list to keep up to date.
+ *
+ * Modules load eagerly because the sidebar needs each doc's name and category
+ * up front; the whole gallery is behind a lazy route, so this all lands in one
+ * chunk that the app never loads unless you open it. Sources stay lazy since
+ * raw file text is pure page data.
+ *
+ * Note: `import.meta.glob` cannot resolve TS path aliases, so these patterns
+ * are relative (same constraint as IconGallery).
+ */
+const docModules = import.meta.glob<{ default: ComponentDoc }>(
+ '../../components/ui/**/*.docs.tsx',
+ { eager: true }
+);
+
+const docSources = import.meta.glob<string>(
+ '../../components/ui/**/*.docs.tsx',
+ { query: '?raw', import: 'default' }
+);
+
+/** Component files backing the `@ui` barrel, used by the coverage report. */
+const uiComponentModules = import.meta.glob(
+ '../../components/ui/components/*.tsx'
+);
+
+/**
+ * Raw text of the component files, so a page can read its guidance and prop
+ * types straight from the implementation instead of restating them. Lazy: only
+ * the page you open pays for it.
+ */
+const componentSources = import.meta.glob<string>(
+ '../../components/ui/components/*.tsx',
+ { query: '?raw', import: 'default' }
+);
+
+export type DocEntry = {
+ /** URL-safe id, derived from the filename. */
+ slug: string;
+ doc: ComponentDoc;
+ /** Path shown on the page so the file is easy to jump to. */
+ path: string;
+ loadSource: () => Promise<string>;
+ /**
+ * Raw text of the component this page sits beside, or null for a page with
+ * no implementation (the Foundations pages). Carries the `@do` / `@dont`
+ * guidance and the prop types.
+ */
+ loadComponentSource: (() => Promise<string>) | null;
+};
+
+/** `.../components/Button.docs.tsx` -> `button` */
+function slugFromPath(path: string): string {
+ const file = path.split('/').pop() ?? path;
+ return file
+ .replace(/\.docs\.tsx$/, '')
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
+ .toLowerCase();
+}
+
+/** `../../components/ui/components/Button.docs.tsx` -> `src/components/ui/...` */
+function displayPath(path: string): string {
+ return path.replace(/^(\.\.\/)+/, 'src/');
+}
+
+function buildEntries(): DocEntry[] {
+ const bySlug = new Map<string, DocEntry>();
+
+ for (const [path, module] of Object.entries(docModules)) {
+ const doc = module.default;
+ if (!doc) {
+ console.warn(`[ui-gallery] ${path} has no default export; skipping.`);
+ continue;
+ }
+
+ const slug = slugFromPath(path);
+ const existing = bySlug.get(slug);
+ if (existing) {
+ console.warn(
+ `[ui-gallery] ${path} and ${existing.path} both map to slug "${slug}"; keeping the first.`
+ );
+ continue;
+ }
+
+ const loadSource = docSources[path];
+ bySlug.set(slug, {
+ slug,
+ doc,
+ path: displayPath(path),
+ loadSource: loadSource ?? (() => Promise.resolve('')),
+ // `Button.docs.tsx` sits beside `Button.tsx`; deriving the sibling means
+ // a page never has to declare where its implementation lives.
+ loadComponentSource:
+ componentSources[path.replace(/\.docs\.tsx$/, '.tsx')] ?? null,
+ });
+ }
+
+ return [...bySlug.values()].sort((a, b) =>
+ a.doc.name.localeCompare(b.doc.name)
+ );
+}
+
+export const DOC_ENTRIES: DocEntry[] = buildEntries();
+
+export function findEntry(slug: string): DocEntry | undefined {
+ return DOC_ENTRIES.find((entry) => entry.slug === slug);
+}
+
+export type DocGroup = { category: DocCategory; entries: DocEntry[] };
+
+/** Entries grouped for the sidebar, in `DOC_CATEGORIES` order. */
+export function groupEntries(entries: readonly DocEntry[]): DocGroup[] {
+ return DOC_CATEGORIES.map((category) => ({
+ category,
+ entries: entries.filter((entry) => entry.doc.category === category),
+ })).filter((group) => group.entries.length > 0);
+}
+
+/** Case-insensitive match over each entry's name, category, and exports. */
+export function filterEntries(
+ entries: readonly DocEntry[],
+ query: string
+): DocEntry[] {
+ const needle = query.trim().toLowerCase();
+ if (!needle) return [...entries];
+ return entries.filter((entry) => {
+ const haystack = [
+ entry.doc.name,
+ entry.doc.category,
+ entry.doc.description,
+ ...(entry.doc.exports ?? []),
+ ]
+ .join(' ')
+ .toLowerCase();
+ return haystack.includes(needle);
+ });
+}
+
+export type CoverageRow = {
+ /** Component file basename, e.g. `Button`. */
+ name: string;
+ entry?: DocEntry;
+};
+
+/**
+ * Every component file in `ui/components` paired with the page documenting it,
+ * so the undocumented surface stays visible instead of assumed. A page claims a
+ * file by matching its name or by listing it in `exports`.
+ */
+export function coverageRows(): CoverageRow[] {
+ const names = Object.keys(uiComponentModules)
+ .map((path) => (path.split('/').pop() ?? '').replace(/\.tsx$/, ''))
+ .filter(
+ (name) => name && !name.endsWith('.test') && !name.endsWith('.docs')
+ )
+ .sort((a, b) => a.localeCompare(b));
+
+ return names.map((name) => ({
+ name,
+ entry: DOC_ENTRIES.find(
+ (entry) => entry.doc.name === name || entry.doc.exports?.includes(name)
+ ),
+ }));
+}
+
+/**
+ * Finds a type declaration anywhere in the `@ui` component sources. Not limited
+ * to the page's own sibling, so a page can surface a type it re-exports (Panel
+ * documents `SurfaceProps`, which lives in `Surface.tsx`).
+ */
+export async function loadTypeSource(name: string): Promise<string | null> {
+ for (const [path, load] of Object.entries(componentSources)) {
+ if (/\.(docs|test)\.tsx$/.test(path)) continue;
+ const found = extractTypeSource(await load(), name);
+ if (found) return found;
+ }
+ return null;
+}
diff --git a/apps/web/src/features/ui-gallery/source.test.ts b/apps/web/src/features/ui-gallery/source.test.ts
new file mode 100644
index 0000000000..699b8c22c9
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/source.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it } from 'vitest';
+import {
+ extractDemoSource,
+ extractGuidelines,
+ extractTypeSource,
+} from './source';
+
+const FILE = [
+ "import { Button } from '@ui';",
+ '',
+ '// #region demo:variants',
+ 'function VariantsDemo() {',
+ ' return (',
+ ' <div class="flex gap-2">',
+ ' <Button variant="ghost">Ghost</Button>',
+ ' </div>',
+ ' );',
+ '}',
+ '// #endregion',
+ '',
+ '// #region demo:sizes',
+ 'function SizesDemo() {',
+ ' return <Button size="sm">Small</Button>;',
+ '}',
+ '// #endregion',
+].join('\n');
+
+describe('extractDemoSource', () => {
+ it('returns the source between a demo region and its endregion', () => {
+ expect(extractDemoSource(FILE, 'variants')).toBe(
+ [
+ 'function VariantsDemo() {',
+ ' return (',
+ ' <div class="flex gap-2">',
+ ' <Button variant="ghost">Ghost</Button>',
+ ' </div>',
+ ' );',
+ '}',
+ ].join('\n')
+ );
+ });
+
+ it('picks the region matching the id, not the first one', () => {
+ expect(extractDemoSource(FILE, 'sizes')).toBe(
+ [
+ 'function SizesDemo() {',
+ ' return <Button size="sm">Small</Button>;',
+ '}',
+ ].join('\n')
+ );
+ });
+
+ it('does not match an id that is a prefix of another', () => {
+ const source = [
+ '// #region demo:size',
+ 'const a = 1;',
+ '// #endregion',
+ ].join('\n');
+ expect(extractDemoSource(source, 'sizes')).toBeNull();
+ });
+
+ it('dedents the block to its own left margin', () => {
+ const source = [
+ ' // #region demo:nested',
+ ' const value = {',
+ ' key: 1,',
+ ' };',
+ ' // #endregion',
+ ].join('\n');
+ expect(extractDemoSource(source, 'nested')).toBe(
+ ['const value = {', ' key: 1,', '};'].join('\n')
+ );
+ });
+
+ it('closes on the matching endregion when regions nest', () => {
+ const source = [
+ '// #region demo:outer',
+ 'const a = 1;',
+ '// #region detail',
+ 'const b = 2;',
+ '// #endregion',
+ 'const c = 3;',
+ '// #endregion',
+ 'const after = 4;',
+ ].join('\n');
+ expect(extractDemoSource(source, 'outer')).toBe(
+ [
+ 'const a = 1;',
+ '// #region detail',
+ 'const b = 2;',
+ '// #endregion',
+ 'const c = 3;',
+ ].join('\n')
+ );
+ });
+
+ it('trims blank lines at the edges but keeps interior spacing', () => {
+ const source = [
+ '// #region demo:spaced',
+ '',
+ 'const a = 1;',
+ '',
+ 'const b = 2;',
+ '',
+ '// #endregion',
+ ].join('\n');
+ expect(extractDemoSource(source, 'spaced')).toBe(
+ 'const a = 1;\n\nconst b = 2;'
+ );
+ });
+
+ it('returns null for a missing region', () => {
+ expect(extractDemoSource(FILE, 'nope')).toBeNull();
+ });
+
+ it('returns null for an unterminated region', () => {
+ const source = ['// #region demo:open', 'const a = 1;'].join('\n');
+ expect(extractDemoSource(source, 'open')).toBeNull();
+ });
+});
+
+describe('extractGuidelines', () => {
+ it('reads @do and @dont tags out of a doc block', () => {
+ const source = [
+ '/**',
+ ' * A button.',
+ ' *',
+ ' * @do Give every screen one primary action.',
+ ' * @dont Do not use it for navigation.',
+ ' */',
+ 'export function Button() {}',
+ ].join('\n');
+
+ expect(extractGuidelines(source)).toEqual({
+ do: ['Give every screen one primary action.'],
+ dont: ['Do not use it for navigation.'],
+ });
+ });
+
+ it('joins a tag that wraps onto following lines', () => {
+ const source = [
+ '/**',
+ ' * @do Always set `label` on icon-only buttons so the control',
+ ' * still has an accessible name.',
+ ' * @dont Do not nest them.',
+ ' */',
+ ].join('\n');
+
+ const { do: dos, dont } = extractGuidelines(source);
+ expect(dos).toEqual([
+ 'Always set `label` on icon-only buttons so the control still has an accessible name.',
+ ]);
+ expect(dont).toEqual(['Do not nest them.']);
+ });
+
+ it('collects tags from every doc block in the file', () => {
+ const source = [
+ '/** @do First. */',
+ 'export function A() {}',
+ '/** @do Second. */',
+ 'export function B() {}',
+ ].join('\n');
+ expect(extractGuidelines(source).do).toEqual(['First.', 'Second.']);
+ });
+
+ it('returns empty lists when the file has no tags', () => {
+ expect(extractGuidelines('/** Plain. */\nexport const a = 1;')).toEqual({
+ do: [],
+ dont: [],
+ });
+ });
+});
+
+describe('extractTypeSource', () => {
+ it('returns an exported type declaration', () => {
+ const source = [
+ 'const x = 1;',
+ 'export type ButtonProps = {',
+ ' variant?: string;',
+ '};',
+ 'const y = 2;',
+ ].join('\n');
+ expect(extractTypeSource(source, 'ButtonProps')).toBe(
+ 'export type ButtonProps = {\n variant?: string;\n};'
+ );
+ });
+
+ it('finds a non-exported declaration too', () => {
+ expect(
+ extractTypeSource('type PanelProps = SurfaceProps;', 'PanelProps')
+ ).toBe('type PanelProps = SurfaceProps;');
+ });
+
+ // The `>` in `=> void` has no opening partner; counting it would cut the
+ // declaration short at the next semicolon.
+ it('does not stop early on an arrow-function member', () => {
+ const source = [
+ 'export type ToggleSwitchProps = {',
+ ' onChange?: (checked: boolean) => void;',
+ ' size?: string;',
+ '};',
+ ].join('\n');
+ expect(extractTypeSource(source, 'ToggleSwitchProps')).toContain(
+ 'size?: string;'
+ );
+ });
+
+ it('handles a generic intersection', () => {
+ const source =
+ "export type P = Root<'button'> & Props<'button'> & { a?: string };\n";
+ expect(extractTypeSource(source, 'P')).toBe(
+ "export type P = Root<'button'> & Props<'button'> & { a?: string };"
+ );
+ });
+
+ it('does not match a similarly named type', () => {
+ const source = 'export type ButtonVariantProps = string;';
+ expect(extractTypeSource(source, 'ButtonProps')).toBeNull();
+ });
+
+ it('returns null when absent', () => {
+ expect(extractTypeSource('const a = 1;', 'Nope')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/ui-gallery/source.ts b/apps/web/src/features/ui-gallery/source.ts
new file mode 100644
index 0000000000..50b50d1a04
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/source.ts
@@ -0,0 +1,153 @@
+/**
+ * Pulls a demo's source out of its `.docs.tsx` file so the gallery shows the
+ * exact code that rendered the preview above it, with no second copy to keep in
+ * sync. Demos mark their span with fold-friendly region comments:
+ *
+ * ```tsx
+ * // #region demo:variants
+ * function VariantsDemo() { ... }
+ * // #endregion
+ * ```
+ */
+
+const REGION_START = /^[ \t]*\/\/\s*#region\s+demo:([A-Za-z0-9_-]+)[ \t]*$/;
+const ANY_REGION_START = /^[ \t]*\/\/\s*#region\b/;
+const REGION_END = /^[ \t]*\/\/\s*#endregion\b/;
+
+/** Removes the shared leading indentation from a block of lines. */
+function dedent(lines: string[]): string[] {
+ let common = Number.POSITIVE_INFINITY;
+ for (const line of lines) {
+ if (line.trim() === '') continue;
+ const indent = line.length - line.trimStart().length;
+ if (indent < common) common = indent;
+ }
+ if (!Number.isFinite(common) || common === 0) return lines;
+ return lines.map((line) => (line.trim() === '' ? line : line.slice(common)));
+}
+
+/** Drops blank lines from both ends without touching interior spacing. */
+function trimBlankEdges(lines: string[]): string[] {
+ let start = 0;
+ let end = lines.length;
+ while (start < end && lines[start]!.trim() === '') start++;
+ while (end > start && lines[end - 1]!.trim() === '') end--;
+ return lines.slice(start, end);
+}
+
+/**
+ * Returns the source between `// #region demo:<id>` and its matching
+ * `// #endregion`, dedented. Returns null when the region is absent or
+ * unterminated, which the gallery renders as a missing-source notice rather
+ * than failing the page.
+ */
+export function extractDemoSource(source: string, id: string): string | null {
+ const lines = source.split('\n');
+ const startIndex = lines.findIndex(
+ (line) => REGION_START.exec(line)?.[1] === id
+ );
+ if (startIndex === -1) return null;
+
+ const body: string[] = [];
+ // Regions can nest (a demo may fold sub-sections); only the matching
+ // `#endregion` at depth zero closes the demo.
+ let depth = 0;
+ for (let i = startIndex + 1; i < lines.length; i++) {
+ const line = lines[i]!;
+ if (REGION_END.test(line)) {
+ if (depth === 0) return trimBlankEdges(dedent(body)).join('\n');
+ depth--;
+ } else if (ANY_REGION_START.test(line)) {
+ depth++;
+ }
+ body.push(line);
+ }
+
+ return null;
+}
+
+/** A component's usage rules, authored as `@do` / `@dont` JSDoc tags. */
+export type Guidelines = { do: string[]; dont: string[] };
+
+const TAG = /^\s*(?:\/\*\*|\*)\s*@(do|dont)\b[ \t]*(.*)$/;
+const CONTINUATION = /^\s*\*[ \t]?(?!@)(.*)$/;
+const BLOCK_END = /^\s*\*\//;
+
+/**
+ * Reads `@do` / `@dont` tags out of a source file's JSDoc.
+ *
+ * Guidance lives on the component rather than in its docs page: it is the one
+ * part of a page that cannot be derived from the types, and both people and
+ * agents reliably read the implementation. The gallery renders these; it does
+ * not own them.
+ *
+ * Tags may wrap onto following comment lines, which are joined with a space.
+ * Scans the whole file rather than trying to pick the "main" doc block, so a
+ * component that splits guidance across exports still reports all of it.
+ */
+export function extractGuidelines(source: string): Guidelines {
+ const result: Guidelines = { do: [], dont: [] };
+ let open: { kind: 'do' | 'dont'; parts: string[] } | undefined;
+
+ const flush = () => {
+ if (!open) return;
+ // A single-line block (`/** @do ... *\/`) carries the terminator inline.
+ const text = open.parts
+ .join(' ')
+ .replace(/\*\/\s*$/, '')
+ .trim();
+ if (text) result[open.kind].push(text);
+ open = undefined;
+ };
+
+ for (const line of source.split('\n')) {
+ const tag = TAG.exec(line);
+ if (tag) {
+ flush();
+ open = { kind: tag[1] as 'do' | 'dont', parts: [tag[2] ?? ''] };
+ continue;
+ }
+ if (!open) continue;
+
+ if (BLOCK_END.test(line)) {
+ flush();
+ continue;
+ }
+ const continuation = CONTINUATION.exec(line);
+ if (continuation && continuation[1]?.trim()) {
+ open.parts.push(continuation[1].trim());
+ } else {
+ flush();
+ }
+ }
+ flush();
+
+ return result;
+}
+
+/**
+ * Returns the source of a top-level `type <name> = …` declaration, so the
+ * gallery can show a component's real prop type instead of a hand-copied table
+ * that drifts. Returns null when the type is not declared in this file.
+ */
+export function extractTypeSource(source: string, name: string): string | null {
+ const declaration = new RegExp(
+ `^(?:export\\s+)?type\\s+${name}\\b[^=]*=`,
+ 'm'
+ );
+ const start = declaration.exec(source);
+ if (!start) return null;
+
+ // Ends at the first semicolon outside any bracket pair. Angle brackets are
+ // deliberately not counted: the `>` in an arrow-function prop type
+ // (`(v: boolean) => void`) has no opening partner and would end the scan.
+ let depth = 0;
+ for (let i = start.index; i < source.length; i++) {
+ const char = source[i]!;
+ if (char === '{' || char === '(' || char === '[') depth++;
+ else if (char === '}' || char === ')' || char === ']') depth--;
+ else if (char === ';' && depth <= 0)
+ return source.slice(start.index, i + 1);
+ }
+ return null;
+}
diff --git a/apps/web/src/features/ui-gallery/types.ts b/apps/web/src/features/ui-gallery/types.ts
new file mode 100644
index 0000000000..40a65f94c9
--- /dev/null
+++ b/apps/web/src/features/ui-gallery/types.ts
@@ -0,0 +1,69 @@
+import type { JSX } from 'solid-js';
+
+/** Maturity of a documented component, surfaced as a badge on its page. */
+export type DocStatus = 'stable' | 'beta' | 'deprecated' | 'internal';
+
+/** Sidebar grouping. `Foundations` sorts first; the rest follow in this order. */
+export const DOC_CATEGORIES = [
+ 'Foundations',
+ 'Actions',
+ 'Inputs',
+ 'Layout',
+ 'Navigation',
+ 'Overlays',
+ 'Feedback',
+ 'Data Display',
+] as const;
+
+export type DocCategory = (typeof DOC_CATEGORIES)[number];
+
+export type DocDemo = {
+ /**
+ * Stable identifier that must match the `// #region demo:<id>` marker
+ * wrapping this demo's source, so the code shown is the code that ran.
+ */
+ id: string;
+ title: string;
+ description?: string;
+ render: () => JSX.Element;
+ /** Surface depth for this demo's preview, overriding the page-level control. */
+ depth?: 0 | 1 | 2 | 3 | 4;
+ /** Stretch the demo across the preview instead of centering it. */
+ fill?: boolean;
+};
+
+export type ComponentDoc = {
+ /** Display name, e.g. `Button`. */
+ name: string;
+ category: DocCategory;
+ /** One or two sentences on what the component is for. */
+ description: string;
+ status?: DocStatus;
+ /** Import line shown above the demos. */
+ import?: string;
+ /**
+ * Names this page documents, as exported from `@ui`. Drives the coverage
+ * report, so a page covering several exports should list all of them.
+ */
+ exports?: string[];
+ demos: DocDemo[];
+ /**
+ * Type names to show under Props, resolved from the `@ui` component sources.
+ * Defaults to `<name>Props`. Naming them is only needed when that default is
+ * unhelpful — `Panel` points at `SurfaceProps`, which is where its props
+ * actually live.
+ */
+ propTypes?: string[];
+ /**
+ * Usage rules for a page with no implementation to hang them on (the
+ * Foundations pages). A component page leaves this unset: its guidance is
+ * authored as `@do` / `@dont` JSDoc on the component itself, so it reaches
+ * anyone reading the source, and the gallery renders it from there.
+ */
+ guidelines?: { do?: string[]; dont?: string[] };
+};
+
+/** Identity helper that gives a `.docs.tsx` file its type checking. */
+export function defineDoc(doc: ComponentDoc): ComponentDoc {
+ return doc;
+}
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 0b92dfb13d..979706124d 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -319,6 +319,11 @@ body.tauri-ios {
--color-thread-rail: color-mix(in oklch, var(--color-surface) 90%, var(--color-ink));
--color-modal-overlay: oklch(0 0 0 / 0.25);
--color-drop-shadow: oklch(0.15 0 0 / 0.04);
+ /* Inset hairline that settles an avatar against the surface behind it. It
+ recedes toward the page tone rather than outlining against it, so a photo's
+ edge stops competing with the layout. Per-mode values are below; this
+ default covers first paint, before the mode attribute is written. */
+ --color-avatar-edge: oklch(0 0 0 / 0.4);
--color-skeleton: color-mix(in oklch, var(--color-ink) 10%, transparent);
--color-list-hover: color-mix(in oklch, var(--color-hover) 65%, transparent);
--color-list-highlighted: var(--color-hover);
@@ -469,8 +474,12 @@ body.tauri-ios {
}
}
-@custom-variant light-mode (&:where(html[data-theme-light="true"] *));
-@custom-variant dark-mode (&:where(html[data-theme-light="false"] *));
+/* Matched on any ancestor rather than `html` so a container can scope a mode to
+ its own subtree — the component gallery previews a light theme inside a dark
+ app that way. The theme feature only ever writes the attribute to `<html>`,
+ so app behavior is unchanged. */
+@custom-variant light-mode (&:where([data-theme-light="true"] *));
+@custom-variant dark-mode (&:where([data-theme-light="false"] *));
/* Dark surfaces need a larger ink step for the thread path to remain visible.
Both inputs stay opaque, so overlapping rail segments still render evenly. */
@@ -478,6 +487,22 @@ html[data-theme-light='false'] {
--color-thread-rail: color-mix(in oklch, var(--color-surface) 70%, var(--color-ink));
}
+/* The avatar hairline follows the surface it sits on: it darkens the edge on
+ dark surfaces and lightens it on light ones, so the avatar settles into the
+ page instead of being ringed against it. Ancestor-scoped for the same reason
+ as the variants above.
+
+ NOTE: turned up to 0.4 so the treatment is obvious while it is being
+ reviewed. The intended production value is 0.08 — change both alphas below
+ (and the @theme default) once the look is settled. */
+[data-theme-light='false'] {
+ --color-avatar-edge: oklch(0 0 0 / 0.4);
+}
+
+[data-theme-light='true'] {
+ --color-avatar-edge: oklch(1 0 0 / 0.4);
+}
+
/* Floating "island" chrome shared by the mobile dock buttons, header islands,
and other floating mobile controls. Consumers add their own shape classes
(e.g. `size-10 rounded-full` or `h-10 rounded-full px-3`). Defined as a
@@ -487,6 +512,21 @@ html[data-theme-light='false'] {
@apply min-h-[40px] min-w-[40px] bg-chrome text-ink ring dark-mode:ring-edge light-mode:ring-panel light-mode:shadow-[0_4px_20px_8px_oklch(0.15_0_0/0.07)];
}
+/* Hairline that settles a round image against the surface behind it, darkening
+ the edge on dark surfaces and lightening it on light ones (see
+ --color-avatar-edge). Applied by `Avatar`; anything drawing an image chip can
+ reuse it, whatever its shape.
+
+ An outline, not a ring: outlines paint after every descendant, so this shows
+ over a `size-full` image, where an inset box-shadow would sit underneath it.
+ A negative offset pulls it inside the border box so the footprint is
+ unchanged, outlines follow `border-radius` so it traces whatever shape the
+ host has, and it leaves box-shadow free for AvatarGroup's separator ring. */
+@utility avatar-edge {
+ outline: 1px solid var(--color-avatar-edge);
+ outline-offset: -1px;
+}
+
[data-press-pulse] {
transition: transform 100ms cubic-bezier(0.34, 1.56, 0.64, 1);
}
diff --git a/apps/web/st-tmp.mjs b/apps/web/st-tmp.mjs
new file mode 100644
index 0000000000..a3b326b95d
--- /dev/null
+++ b/apps/web/st-tmp.mjs
@@ -0,0 +1,45 @@
+import { chromium } from '@playwright/test';
+const browser = await chromium.launch({ channel: 'chrome' });
+const page = await browser.newPage({ viewport: { width: 791, height: 1014 } });
+
+const jumped = () => page.evaluate(() => {
+ const bad = [];
+ for (const el of document.querySelectorAll('*')) {
+ if (el.scrollTop > 0) {
+ const o = getComputedStyle(el).overflowY;
+ if (o === 'hidden' || o === 'clip') bad.push(`${(el.className||'').toString().slice(0,44)} top=${Math.round(el.scrollTop)}`);
+ }
+ }
+ return bad;
+});
+
+// Every focusable control across the pages that have them.
+for (const [slug, sel] of [
+ ['toggle-switch', '[id$="-control"]'],
+ ['checkbox', 'input[type=checkbox]'],
+ ['button', 'button'],
+ ['select', '[id$="-trigger"], button'],
+]) {
+ await page.goto(`http://localhost:3004/app/component/ui?ui=${slug}`, { waitUntil: 'networkidle' });
+ await page.waitForSelector('article', { timeout: 30000 });
+ const items = page.locator(sel);
+ const n = Math.min(await items.count(), 6);
+ for (let i = 0; i < n; i++) {
+ try {
+ await items.nth(i).scrollIntoViewIfNeeded();
+ await items.nth(i).click({ timeout: 3000 });
+ await page.waitForTimeout(120);
+ } catch {}
+ }
+ const bad = await jumped();
+ console.log(`${slug.padEnd(14)} clicked ${n} controls -> ${bad.length ? 'JUMPED: ' + bad.join(' | ') : 'no unscrollable container moved'}`);
+}
+
+// Keyboard tabbing is the other way focus lands off-screen.
+await page.goto('http://localhost:3004/app/component/ui?ui=toggle-switch', { waitUntil: 'networkidle' });
+await page.waitForSelector('article');
+for (let i = 0; i < 25; i++) await page.keyboard.press('Tab');
+await page.waitForTimeout(400);
+const bad = await jumped();
+console.log(`25x Tab -> ${bad.length ? 'JUMPED: ' + bad.join(' | ') : 'no unscrollable container moved'}`);
+await browser.close();
diff --git a/bun.lock b/bun.lock
index 507ffcfa7b..f3de10ffd9 100644
--- a/bun.lock
+++ b/bun.lock
@@ -44,6 +44,7 @@
"@lexical/selection": "0.45.0",
"@lexical/table": "0.45.0",
"@lexical/utils": "0.45.0",
+ "@lezer/highlight": "^1.2.3",
"@livekit/krisp-noise-filter": "^0.4.1",
"@livekit/track-processors": "^0.7.2",
"@lukemorales/query-key-factory": "^1.3.4",
@@ -964,7 +965,7 @@
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6ddd660", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6ddd660", "sha512-7+0ebEOYqedkOY67Clwu65Np3qJ3aJc/H/NjNxmjgA/7HIu0C+DSoKAArG7HTdTVpdcAtHyhrqsJujdEAyJf6Q=="],
+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#6ddd660", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-6ddd660"],
"@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q=="],
@@ -2826,7 +2827,7 @@
"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],
- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],
+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],
"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
index aad0b317d5..ece5a37641 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/web_app_check_main.rs
@@ -46,7 +46,6 @@ pub fn web_app_check_main() -> Workflow {
.add_job("path-check", path_check())
.add_job("typescript", typescript())
.add_job("biome-check", biome_check())
- .add_job("tailwind", tailwind())
.add_job("test", test())
.add_job("cycles", cycles())
.add_job("build", build())
@@ -96,16 +95,6 @@ fn biome_check() -> Job {
.add_step(steps::teardown_nix())
}
-fn tailwind() -> Job {
- gated_web_job("Theme Hygiene Inspector")
- .add_step(checkout("Checkout Repo", true))
- .add_step(steps::mount_web_cache_volume(false))
- .add_step(steps::setup_nix())
- .add_step(steps::setup_reqs_web("Setup Prereqs", false))
- .add_step(check_tailwind_classes())
- .add_step(steps::teardown_nix())
-}
-
fn test() -> Job {
gated_web_job("Test")
.add_step(checkout("Checkout Repo", false))
@@ -147,7 +136,6 @@ fn status_check() -> Job {
"path-check".to_string(),
"typescript".to_string(),
"biome-check".to_string(),
- "tailwind".to_string(),
"test".to_string(),
"cycles".to_string(),
"build".to_string(),
@@ -241,12 +229,6 @@ fn run_collaboration_biome() -> Step<Run> {
.working_directory(xtask_paths::repo_dir!("packages/collaboration"))
}
-fn check_tailwind_classes() -> Step<Run> {
- Step::new("Check Tailwind Classes")
- .run("just check-tailwind")
- .working_directory(xtask_paths::repo_dir!("apps/web"))
-}
-
fn run_tests() -> Step<Run> {
Step::new("Test")
.run("bunx vitest")
@@ -276,7 +258,6 @@ fn check_job_results() -> Step<Run> {
echo "path-check: ${{ needs.path-check.result }}"
echo "typescript: ${{ needs.typescript.result }}"
echo "biome-check: ${{ needs.biome-check.result }}"
- echo "tailwind: ${{ needs.tailwind.result }}"
echo "test: ${{ needs.test.result }}"
echo "cycles: ${{ needs.cycles.result }}"
echo "build: ${{ needs.build.result }}"
@@ -285,7 +266,6 @@ fn check_job_results() -> Step<Run> {
if [[ "${{ needs.path-check.result }}" == "failure" ]] || \
[[ "${{ needs.typescript.result }}" == "failure" ]] || \
[[ "${{ needs.biome-check.result }}" == "failure" ]] || \
- [[ "${{ needs.tailwind.result }}" == "failure" ]] || \
[[ "${{ needs.test.result }}" == "failure" ]] || \
[[ "${{ needs.cycles.result }}" == "failure" ]] || \
[[ "${{ needs.build.result }}" == "failure" ]]; then