Tansy UI: a themeable React component kit

Tansy UI is a React component kit by OpenKhalix, named after the tansy
flower ("golden buttons"). It has two surfaces:

- A landing page built entirely from the kit's own components, with
  five featured parts, a palette-switching playground form, and links
  into Storybook
- A Storybook workshop with Tansy branding, a Welcome page, palette
  toolbar and accessibility checks

Includes 15 components with colocated tokens and stories, seven brand
palettes, a palette-aware logo, a Docker/nginx image, a scripted
cPanel deploy, and a generator that keeps the landing page catalogue
in sync with Storybook.
This commit is contained in:
thekhalidsha committed 2026-09-28 17:09:57 +05:30
commit 9d406d6d2a
81 files changed
+14240

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
node_modules
npm-debug.log*
dist
storybook-static
.git
.gitignore
.dockerignore
Dockerfile
README.md
*.log
+11
View File
@@ -0,0 +1,11 @@
node_modules
dist
dist-ssr
storybook-static
*.local
.DS_Store
.idea
.vscode
# cPanel deploy credentials for scripts/deploy.py — never commit
scripts/deploy.env
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+17
View File
@@ -0,0 +1,17 @@
import type { StorybookConfig } from '@storybook/react-vite'
const config: StorybookConfig = {
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(ts|tsx)'],
addons: ['@storybook/addon-docs', '@storybook/addon-a11y'],
framework: {
name: '@storybook/react-vite',
options: {},
},
// Serves the Tansy mark and favicon to the manager and the Welcome page.
staticDirs: ['../public'],
docs: {
defaultName: 'Documentation',
},
}
export default config
+8
View File
@@ -0,0 +1,8 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Schibsted+Grotesk:wght@700;800&display=swap"
/>
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
<meta name="theme-color" content="#f3f4f6" />
+9
View File
@@ -0,0 +1,9 @@
import { addons } from 'storybook/manager-api'
import { tansyTheme } from './tansyTheme'
addons.setConfig({
theme: tansyTheme,
sidebar: {
showRoots: true,
},
})
+11
View File
@@ -0,0 +1,11 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Schibsted+Grotesk:wght@700;800&display=swap"
/>
<style>
/* Tailwind's preflight strips list markers; restore them on docs pages. */
.sbdocs ol { list-style: decimal; padding-left: 1.5rem; }
.sbdocs h2 { font-family: "Schibsted Grotesk", sans-serif; font-weight: 800; letter-spacing: -0.02em; }
</style>
+92
View File
@@ -0,0 +1,92 @@
import { useEffect, useRef, type ReactElement } from 'react'
import type { Decorator, Preview } from '@storybook/react-vite'
import '../src/index.css'
import { applyPalette } from '../src/theme/applyPalette'
import { palettes, DEFAULT_PALETTE, type PaletteName } from '../src/theme/palettes'
import { tansyTheme } from './tansyTheme'
/**
* Wraps every story in a themed surface.
*
* The palette globals are set on this wrapper rather than on
* `document.documentElement` so a story can opt into a *different* palette on
* its own subtree without fighting the global one, and so the docs page keeps
* its own chrome.
*
* Declared as a named component (not an inline arrow) so the rules-of-hooks lint
* recognises the hook calls below.
*/
function PaletteSurface({ palette, children }: { palette: PaletteName; children: ReactElement }) {
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (ref.current) applyPalette(ref.current, palette)
}, [palette])
return (
<div
ref={ref}
data-palette={palette}
style={{
padding: '1.5rem',
minHeight: '100%',
color: 'var(--color-gray-900)',
}}
>
{children}
</div>
)
}
const withPalette: Decorator = (Story, context) => {
const palette = (context.globals.palette ?? DEFAULT_PALETTE) as PaletteName
return <PaletteSurface palette={palette}><Story /></PaletteSurface>
}
const preview: Preview = {
title: 'Tansy UI / Component Workshop',
decorators: [withPalette],
globalTypes: {
palette: {
description: 'Brand palette applied to every element in the canvas.',
toolbar: {
title: 'Palette',
icon: 'paintbrush',
items: Object.values(palettes).map((p) => ({
value: p.name,
title: `${p.label} — ${p.note}`,
})),
dynamicTitle: true,
},
},
},
initialGlobals: {
palette: DEFAULT_PALETTE,
},
parameters: {
docs: {
theme: tansyTheme,
},
options: {
storySort: {
order: ['Welcome', 'Actions', 'Forms', 'Data entry', 'Feedback', 'Display', 'Layout', 'Navigation', 'Overlays'],
},
},
backgrounds: {
default: 'showcase',
values: [
{ name: 'showcase', value: '#f3f4f6' },
{ name: 'surface', value: '#ffffff' },
{ name: 'dark', value: '#12151c' },
],
},
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
}
export default preview
+46
View File
@@ -0,0 +1,46 @@
import { create } from 'storybook/theming'
/**
* Tansy UI branding for the Storybook manager and docs pages.
*
* `brandTitle` is HTML: the mark comes from `public/` (served via `staticDirs`)
* and is referenced relatively so it resolves both at `/` in dev and under
* `/docs/` in production.
*/
export const tansyTheme = create({
base: 'light',
brandTitle: `<span style="display:inline-flex;align-items:center;gap:8px;white-space:nowrap">
<img src="./tansy-mark.svg" width="28" height="28" alt="" />
<span style="font-family:'Schibsted Grotesk',sans-serif;font-weight:800;font-size:19px;letter-spacing:-0.03em;color:#12151c">Tansy <span style="font-weight:700;color:#6b7384">UI</span></span>
<span style="font-size:11px;color:#6b7384;padding-left:8px;border-left:1px solid #c5cad4">by OpenKhalix</span>
</span>`,
brandUrl: '/',
brandTarget: '_self',
colorPrimary: '#305ddd',
colorSecondary: '#305ddd',
appBg: '#f3f4f6',
appContentBg: '#ffffff',
appPreviewBg: '#ffffff',
appBorderColor: '#dde1e8',
appBorderRadius: 8,
fontBase: '"Instrument Sans", "Helvetica Neue", Arial, sans-serif',
fontCode: '"JetBrains Mono", "SFMono-Regular", Consolas, monospace',
textColor: '#12151c',
textInverseColor: '#ffffff',
textMutedColor: '#6b7384',
barBg: '#ffffff',
barTextColor: '#4a5162',
barSelectedColor: '#305ddd',
barHoverColor: '#305ddd',
inputBg: '#ffffff',
inputBorder: '#c5cad4',
inputTextColor: '#12151c',
inputBorderRadius: 6,
})
+32
View File
@@ -0,0 +1,32 @@
# syntax=docker/dockerfile:1
FROM node:26-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run lint \
&& npm run build \
&& npm run build-storybook
FROM nginx:1.29-alpine AS runtime
LABEL org.opencontainers.image.title="Tansy UI" \
org.opencontainers.image.description="Landing page and Storybook for the Tansy UI React component kit" \
org.opencontainers.image.source="local:ui-showcase" \
org.opencontainers.image.licenses="UNLICENSED"
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
COPY --from=build /app/storybook-static /usr/share/nginx/html/docs
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://127.0.0.1/ || exit 1
CMD ["nginx", "-g", "daemon off;"]
+136
View File
@@ -0,0 +1,136 @@
<p align="center">
<img src="public/tansy-mark.svg" width="88" height="88" alt="Tansy UI logo" />
</p>
<h1 align="center">Tansy UI</h1>
<p align="center">
A themeable React component kit, with every state documented in Storybook.<br />
By OpenKhalix.
</p>
---
Tansy UI is named after the tansy flower, also called *golden buttons*: many small, round heads that together read as one bloom. The kit works the same way. It is a set of small, owned parts (buttons, fields, selects, feedback and overlays) that combine into a consistent interface.
Every part ships with:
- **Named variants.** A short list of deliberate choices, such as `variant="outline"`, instead of one-off styling.
- **Its states.** Error, disabled, loading and required are part of the component, and each has its own story.
- **Tokens, not hex codes.** Colours come from a 50–900 palette ramp, so switching the palette re-themes every part without a code change.
> **Status:** pre-release (v0.2). Tansy UI is not published to npm yet. It is developed in this repository, with a landing page and a Storybook workshop as its showcase.
## Components
| Group | Components |
|---|---|
| Actions | `Button`, `LinkButton` |
| Forms | `Input`, `FeaturedInput`, `Select`, `Checkbox`, `Radio`, `Switch`, `TextArea` |
| Data entry | `TextField` |
| Feedback | `Alert`, `Spinner` |
| Display | `Badge` |
| Layout | `Card` (with `Card.Header`, `Card.Title`, `Card.Body`, `Card.Footer`) |
| Navigation | `Accordion` |
| Overlays | `Tooltip` |
Each component lives in `src/components/` with its style maps in a sibling `*.tokens.ts` and its stories in `*.stories.tsx`.
## Usage
```tsx
import { useState } from 'react'
import { Button } from './components/Button'
import { FeaturedInput } from './components/FeaturedInput'
import { Switch } from './components/Switch'
export function InviteForm() {
const [email, setEmail] = useState('')
return (
<form>
<FeaturedInput
label="Work email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
<Switch label="Send a welcome email" defaultChecked />
<Button type="submit">Send invite</Button>
</form>
)
}
```
## Theming
Tansy UI ships seven palettes: Classic Blue (default), Emerald, Violet, Amber, Crimson, Slate and Teal. Each defines full `primary`, `secondary`, `gray` and `zink` ramps plus semantic colours in `src/theme/palettes.ts`.
`applyPalette(element, name)` writes a palette as CSS custom properties on any element. Tailwind v4 reads those properties, so a palette applies to one subtree and several palettes can appear on the same page:
```ts
import { applyPalette } from './theme/applyPalette'
applyPalette(document.getElementById('settings')!, 'emerald')
```
Storybook's **Palette** toolbar and the landing page playground both use this function.
## Development
```bash
npm install
npm run dev # landing page at http://localhost:5173
npm run storybook # component workshop at http://localhost:6006
npm run lint
npm run build # landing page -> dist/
npm run build-storybook # workshop -> storybook-static/
```
### Adding a component
1. Add it under `src/components/`, with style maps in a sibling `*.tokens.ts`.
2. Add a colocated `ComponentName.stories.tsx` that covers every meaningful state.
3. Read colours from the palette ramps (`bg-primary-500`) so the palette switcher reaches it.
4. Run `npm run build-storybook && python3 scripts/gen_catalogue.py --patch` to refresh the landing page catalogue.
## Project structure
```text
src/
├── brand/TansyMark.tsx # Palette-aware logo
├── components/ # Components, their tokens and their stories
├── data/catalogue.ts # Landing page catalogue (regenerated by scripts/gen_catalogue.py)
├── theme/ # Palettes and applyPalette()
├── Welcome.mdx # Storybook welcome page
├── App.tsx # Landing page, built only from Tansy components
└── index.css # Tailwind entry, palette tokens, landing styles
.storybook/ # Storybook config, Tansy theme, fonts
public/ # tansy-mark.svg and favicon.svg
scripts/ # Deploy and catalogue scripts
```
## Brand
The mark is a tansy flowerhead: six buttons in the palette's primary colour around a gold centre button.
- `src/brand/TansyMark.tsx` re-themes with the active palette. The gold centre stays fixed.
- `public/tansy-mark.svg` is the fixed Classic Blue version, used by Storybook.
- `public/favicon.svg` is the mark on a dark tile, so it stays visible in both light and dark browser tabs.
Typefaces: Schibsted Grotesk for headings, Instrument Sans for text and JetBrains Mono for code.
## Deployment
The build serves the landing page at `/` and Storybook at `/docs/`.
**Container.** The `Dockerfile` lints and builds both surfaces, then serves them from nginx with a `/healthz` endpoint:
```bash
docker build -t tansy-ui .
docker run --rm -p 8041:80 tansy-ui
curl http://127.0.0.1:8041/healthz
```
**cPanel.** `python3 scripts/deploy.py` builds, packages and uploads to a cPanel host, then removes files left over from earlier builds. See [`scripts/README.md`](scripts/README.md) for setup.
+24
View File
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f3f4f6" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Schibsted+Grotesk:wght@700;800&display=swap"
/>
<meta
name="description"
content="Tansy UI is a themeable React component kit by OpenKhalix, with every state documented in Storybook."
/>
<title>Tansy UI · React component kit</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+41
View File
@@ -0,0 +1,41 @@
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
index index.html;
server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-Frame-Options "SAMEORIGIN" always;
location = /healthz {
access_log off;
default_type text/plain;
return 200 "ok\n";
}
location = /docs {
return 301 /docs/;
}
location /docs/ {
try_files $uri $uri/ /docs/index.html;
}
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(?:css|js|mjs|json|svg|png|jpg|jpeg|gif|webp|ico|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
location ~ /\. {
deny all;
}
}
+5257
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
{
"name": "tansy-ui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint src .storybook",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"dependencies": {
"clsx": "^2.1.1",
"lucide-react": "^0.460.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"sonner": "^1.7.4",
"tailwind-merge": "^2.6.1"
},
"devDependencies": {
"@storybook/addon-a11y": "^10.6.0",
"@storybook/addon-docs": "^10.6.0",
"@storybook/react-vite": "^10.6.0",
"@tailwindcss/vite": "^4.3.3",
"@types/node": "^24.13.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"oxlint": "^1.81.0",
"storybook": "^10.6.0",
"tailwindcss": "^4.3.3",
"typescript": "~6.0.2",
"vite": "^8.3.0"
}
}
+20
View File
@@ -0,0 +1,20 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-labelledby="t">
<title id="t">Tansy UI</title>
<rect width="32" height="32" rx="8" fill="#12151c"/>
<g transform="translate(16 16) scale(.9) translate(-16 -16)">
<circle cx="16.00" cy="16.00" r="3.6" fill="#f5b40b"/>
<circle cx="16.00" cy="16.00" r="1.45" fill="#fde68a"/>
<circle cx="24.20" cy="16.00" r="3.6" fill="#5b87f5"/>
<circle cx="24.20" cy="16.00" r="1.45" fill="#dbe7ff"/>
<circle cx="20.10" cy="23.10" r="3.6" fill="#5b87f5"/>
<circle cx="20.10" cy="23.10" r="1.45" fill="#dbe7ff"/>
<circle cx="11.90" cy="23.10" r="3.6" fill="#5b87f5"/>
<circle cx="11.90" cy="23.10" r="1.45" fill="#dbe7ff"/>
<circle cx="7.80" cy="16.00" r="3.6" fill="#5b87f5"/>
<circle cx="7.80" cy="16.00" r="1.45" fill="#dbe7ff"/>
<circle cx="11.90" cy="8.90" r="3.6" fill="#5b87f5"/>
<circle cx="11.90" cy="8.90" r="1.45" fill="#dbe7ff"/>
<circle cx="20.10" cy="8.90" r="3.6" fill="#5b87f5"/>
<circle cx="20.10" cy="8.90" r="1.45" fill="#dbe7ff"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

+17
View File
@@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-labelledby="t">
<title id="t">Tansy UI</title>
<circle cx="16.00" cy="16.00" r="3.6" fill="#f5b40b"/>
<circle cx="16.00" cy="16.00" r="1.45" fill="#fde68a"/>
<circle cx="24.20" cy="16.00" r="3.6" fill="#305ddd"/>
<circle cx="24.20" cy="16.00" r="1.45" fill="#bfdbfe"/>
<circle cx="20.10" cy="23.10" r="3.6" fill="#305ddd"/>
<circle cx="20.10" cy="23.10" r="1.45" fill="#bfdbfe"/>
<circle cx="11.90" cy="23.10" r="3.6" fill="#305ddd"/>
<circle cx="11.90" cy="23.10" r="1.45" fill="#bfdbfe"/>
<circle cx="7.80" cy="16.00" r="3.6" fill="#305ddd"/>
<circle cx="7.80" cy="16.00" r="1.45" fill="#bfdbfe"/>
<circle cx="11.90" cy="8.90" r="3.6" fill="#305ddd"/>
<circle cx="11.90" cy="8.90" r="1.45" fill="#bfdbfe"/>
<circle cx="20.10" cy="8.90" r="3.6" fill="#305ddd"/>
<circle cx="20.10" cy="8.90" r="1.45" fill="#bfdbfe"/>
</svg>

After

Width:  |  Height:  |  Size: 931 B

+80
View File
@@ -0,0 +1,80 @@
# Deploying Tansy UI to cPanel
One command replaces the old manual sequence. There is nothing to delete
first and no manual overwrite: the cPanel-side script treats the uploaded
archive as the complete truth for the docroot and prunes everything else.
## Use
```bash
python3 scripts/deploy.py # build + package + upload + verify
python3 scripts/deploy.py --deploy-only # upload the existing build
python3 scripts/deploy.py --build-only # build and package, upload nothing
python3 scripts/deploy.py --dry-run # package and report, upload nothing
```
## One-time setup
```bash
cp scripts/deploy.env.example scripts/deploy.env
$EDITOR scripts/deploy.env # fill in CPANEL_PASS
chmod 600 scripts/deploy.env
```
`scripts/deploy.env` is gitignored. Every value can also come from the
environment instead, which is what CI should do.
## How it works
1. `npm ci`, `npm run lint`, `npm run build`, `npm run build-storybook`
2. Stage `dist/` at the root and `storybook-static/` under `docs/`, zip with
Python's `zipfile` (there is no `zip` binary on the build host), base64 it
3. Upload `scripts/cpanel-deploy.php` to the docroot over the cPanel UAPI
4. POST the base64 payload to it with a `Host` header for the subdomain,
pointed at the origin IP so Cloudflare is bypassed
5. The PHP extracts, then deletes anything the archive did not contain
6. Rewrite the hardened `.htaccess` and verify the site
## Why the archive can be authoritative
Vite and Storybook both emit content-hashed filenames
(`index-DHOur7R8.js`, `Alert.stories-CL8ipgGJ.js`), so a new build never
overwrites an old file. Without pruning, every deploy leaves its previous
bundles behind. The prune step is what keeps the docroot at exactly one
build.
`KEEP_TOP` in `deploy.py` lists the names the prune must never touch:
`.htaccess`, `.user.ini`, `php.ini`, `cgi-bin`, `.well-known`. cPanel owns
those; removing `.htaccess` would take the site down.
## Traps this script works around
- **PHP is disabled in the hardened `.htaccess`.** The deployer cannot run
until it is lifted, so the script writes a PHP-enabled copy, deploys, then
restores the hardened one. It verifies PHP executes *before* trusting the
upload, and verifies PHP is off again afterwards.
- **A PHP parse error is nearly invisible.** The server returns an empty
body and leaves `_deploy.php` on disk, which looks identical to "the
upload was ignored". The real cause only shows up in
`/home/<CPANEL_USER>/logs/php.error.log`. The script therefore runs `php -l`
locally before uploading and aborts if it fails. This is why `php-cli` and
`php-zip` are required on the build host.
- **`protected` is a reserved PHP keyword.** `const PROTECTED = [...]` is a
parse error. The constant is `PRESERVE`.
- **The `Host` header is required.** Without it the request hits the
server's default vhost and cPanel answers with its own 404 page.
## Verifying a change to the prune logic
The prune step deletes files, so test it against a fixture rather than
production. Build a fake docroot containing a previous build plus cPanel's
files, run the real script under `php-cli`, and assert that current files
survive, stale ones are gone, and the preserved names are untouched.
## Wiring it into CI
`scripts/deploy.py` is the whole deploy; a workflow only has to supply
credentials and run it. Note that the Gitea runner's job timeout is 360 s
and `npm ci` plus a cold Storybook build is likely to exceed that, so either
raise `runner.timeout` in the runner config or run this from a machine that
already has `node_modules`.
+215
View File
@@ -0,0 +1,215 @@
<?php
/**
* cPanel static deployer: extract a base64 ZIP, then prune anything the
* upload did not bring with it.
*
* Post fields:
* data - base64 of a ZIP whose entries are relative paths
* keep - optional JSON array of extra top-level names to preserve
*
* The archive is authoritative for everything except the names in
* $keepNames. After extraction anything else is stale output from a
* previous build and is removed, so the docroot always matches exactly
* one build and old content-hashed assets do not accumulate.
*
* Self-deletes as its first action so it cannot be replayed.
*/
$self = __FILE__;
@unlink($self);
header('Content-Type: text/plain');
// Named PRESERVE, not PROTECTED - `protected` is a reserved PHP keyword
// and a const with that name is a parse error.
const PRESERVE = ['.', '..', '.htaccess', '.user.ini', 'php.ini', 'cgi-bin', '.well-known'];
function fail(string $msg): never {
echo "ERROR: {$msg}\n";
exit(1);
}
if (!isset($_POST['data'])) {
fail('no data payload');
}
$raw = base64_decode($_POST['data'], true);
if ($raw === false || $raw === '') {
fail('base64 decode failed');
}
$extraKeep = [];
if (isset($_POST['keep'])) {
$decoded = json_decode($_POST['keep'], true);
if (is_array($decoded)) {
$extraKeep = $decoded;
}
}
$keepNames = array_merge(PRESERVE, $extraKeep);
$tmp = tempnam(sys_get_temp_dir(), 'dep');
if ($tmp === false) {
fail('tempnam failed');
}
file_put_contents($tmp, $raw);
$zip = new ZipArchive();
if ($zip->open($tmp) !== TRUE) {
@unlink($tmp);
fail('zip open failed');
}
$root = __DIR__;
$writtenFiles = []; // every relative file path the archive produced
$writtenDirs = ['']; // every relative directory the archive produced
$extracted = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if ($name === false || $name === '' || str_ends_with($name, '/')) {
continue;
}
// Reject traversal and absolute paths outright.
if (str_contains($name, '..') || $name[0] === '/' || $name[0] === '\\') {
fail("refusing suspicious archive path: {$name}");
}
// Record every parent directory as part of the new build.
$parts = explode('/', $name);
array_pop($parts);
$acc = '';
foreach ($parts as $part) {
$acc = $acc === '' ? $part : $acc . '/' . $part;
$writtenDirs[$acc] = true;
}
$dest = $root . '/' . $name;
$writtenFiles[$name] = true;
$dir = dirname($dest);
if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
fail("mkdir failed: {$dir}");
}
$stream = $zip->getStream($name);
if ($stream === false) {
fail("getStream failed: {$name}");
}
$out = fopen($dest, 'wb');
if ($out === false) {
fclose($stream);
fail("fopen failed: {$dest}");
}
stream_copy_to_stream($stream, $out);
fclose($out);
fclose($stream);
$extracted++;
}
$zip->close();
@unlink($tmp);
if ($extracted === 0) {
fail('archive contained no files');
}
// --- prune stale output -------------------------------------------------
$removed = 0;
$prunedDirs = 0;
function rmTree(string $dir): void {
global $removed, $prunedDirs;
$items = @scandir($dir);
if ($items === false) {
return;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir . '/' . $item;
if (is_dir($path)) {
rmTree($path);
if (@rmdir($path)) {
$prunedDirs++;
}
} elseif (@unlink($path)) {
$removed++;
}
}
}
/**
* Delete everything inside $absDir that the new build did not write, then
* remove the directory itself if this build did not produce it.
*/
function pruneDir(string $absDir, string $relDir): void {
global $removed, $prunedDirs, $writtenFiles, $writtenDirs;
$items = @scandir($absDir);
if ($items === false) {
return;
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$rel = $relDir === '' ? $item : $relDir . '/' . $item;
$path = $absDir . '/' . $item;
if (is_dir($path)) {
pruneDir($path, $rel);
// Only remove the directory if this build did not put anything
// inside it - that is what makes assets/ and docs/ survive.
if (!isset($writtenDirs[$rel]) && @rmdir($path)) {
$prunedDirs++;
}
continue;
}
if (!isset($writtenFiles[$rel]) && @unlink($path)) {
$removed++;
}
}
}
$top = @scandir($root);
if ($top === false) {
fail('scandir failed on docroot');
}
foreach ($top as $entry) {
if (in_array($entry, $keepNames, true)) {
continue;
}
$path = $root . '/' . $entry;
if (is_dir($path)) {
pruneDir($path, $entry);
if (!isset($writtenDirs[$entry]) && @rmdir($path)) {
$prunedDirs++;
}
continue;
}
if (!isset($writtenFiles[$entry]) && @unlink($path)) {
$removed++;
}
}
$bytes = 0;
foreach (array_keys($writtenFiles) as $name) {
$bytes += @filesize($root . '/' . $name) ?: 0;
}
// Post-deploy sanity check: the docroot must still contain what was written.
if (!file_exists($root . '/index.html')) {
fail('post-deploy check failed: index.html is missing');
}
echo json_encode([
'ok' => true,
'extracted' => $extracted,
'pruned_files' => $removed,
'pruned_dirs' => $prunedDirs,
'bytes' => $bytes,
'docroot' => $root,
], JSON_PRETTY_PRINT) . "\n";
+21
View File
@@ -0,0 +1,21 @@
# cPanel deploy credentials for scripts/deploy.py
#
# This file is gitignored. Copy it to deploy.env, fill it in, and keep it at
# mode 600. The same values can come from the environment instead:
# CPANEL_HOST, CPANEL_USER, CPANEL_PASS, CPANEL_SUB, ORIGIN_IP
# Hostname the cPanel panel is served on (without :2083)
CPANEL_HOST=cpanel.example.com
# cPanel account username
CPANEL_USER=cpaneluser
# Account password
CPANEL_PASS=change-me
# Subdomain the build is served from; also the docroot's directory name
CPANEL_SUB=ui.example.com
# Origin IP of the cPanel server, used to POST the payload with a Host header
# that bypasses Cloudflare. DNS for the subdomain must point here, unproxied.
ORIGIN_IP=203.0.113.10
+427
View File
@@ -0,0 +1,427 @@
#!/usr/bin/env python3
"""
Deploy the Tansy UI build to the cPanel shared host.
Replaces the old manual flow: no manual deletion, no manual overwrite. The
cPanel-side PHP does the extraction and prunes whatever the new build did
not bring with it, so the docroot always matches exactly one build.
Usage:
python3 scripts/deploy.py # build + deploy
python3 scripts/deploy.py --build-only # just build + package
python3 scripts/deploy.py --deploy-only # deploy the existing /tmp payload
python3 scripts/deploy.py --dry-run # package, print, upload nothing
Credentials come from the environment, never from the repo:
CPANEL_HOST, CPANEL_USER, CPANEL_PASS, CPANEL_SUB, ORIGIN_IP
Fallbacks live in scripts/deploy.env (gitignored, chmod 600).
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
STAGE = Path("/tmp/tansy-stage")
ZIP = Path("/tmp/tansy-deploy.zip")
ENV_FILE = REPO / "scripts" / "deploy.env"
# The docroot must keep these regardless of what a build contains: cPanel
# writes them, and removing .htaccess would take the site offline.
KEEP_TOP = ["cgi-bin", ".well-known", "php.ini", ".user.ini", ".htaccess"]
# Set from --skip-php-lint in main().
SKIP_PHP_LINT = False
# PHP is disabled in the hardened .htaccess, so it has to be lifted for the
# duration of the upload and restored immediately afterwards.
# __CPANEL_USER__ is replaced with the configured account when written.
HTACCESS_DEPLOY = """<IfModule php8_module>
php_value error_log "/home/__CPANEL_USER__/logs/php.error.log"
php_flag log_errors On
</IfModule>
<IfModule lsapi_module>
php_value error_log "/home/__CPANEL_USER__/logs/php.error.log"
php_flag log_errors On
</IfModule>
Options -Indexes +FollowSymLinks
DirectoryIndex index.html
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^docs$ docs/ [R=301,L]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^docs/(.*) docs/index.html [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]
</IfModule>
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
"""
HTACCESS_HARDENED = HTACCESS_DEPLOY + """
# Deployment complete: static only.
<IfModule mod_php.c>
php_flag engine off
</IfModule>
RemoveHandler .php .phtml .php3 .php4 .php5 .php7 .php8
RemoveType .php
"""
def log(msg: str) -> None:
print(f"[deploy] {msg}", flush=True)
def die(msg: str, code: int = 1) -> None:
print(f"[deploy] ERROR: {msg}", file=sys.stderr, flush=True)
sys.exit(code)
# --------------------------------------------------------------------------
# config
# --------------------------------------------------------------------------
def load_config() -> dict:
cfg = dict(os.environ)
if ENV_FILE.exists():
for line in ENV_FILE.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, val = line.partition("=")
cfg.setdefault(key.strip(), val.strip().strip("'\""))
missing = [k for k in ("CPANEL_HOST", "CPANEL_USER", "CPANEL_PASS",
"CPANEL_SUB", "ORIGIN_IP") if not cfg.get(k)]
if missing:
die(f"missing config: {', '.join(missing)}\n"
f" set them in the environment or in {ENV_FILE}")
return cfg
# --------------------------------------------------------------------------
# build
# --------------------------------------------------------------------------
def run(cmd: list[str], cwd: Path = REPO, timeout: int = 900) -> None:
log("$ " + " ".join(cmd))
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout)
if r.returncode != 0:
die(f"{cmd[0]} failed ({r.returncode})\n{r.stdout[-2500:]}\n{r.stderr[-2500:]}")
tail = "\n".join(r.stdout.strip().splitlines()[-6:])
if tail:
print(tail, flush=True)
def build() -> None:
run(["npm", "ci"])
run(["npm", "run", "lint"])
run(["npm", "run", "build"])
if not (REPO / "storybook-static" / "index.json").exists():
die("storybook-static/index.json missing - run: npm run build-storybook")
run(["npm", "run", "build-storybook"])
def package() -> dict:
dist = REPO / "dist"
sb = REPO / "storybook-static"
for d in (dist, sb):
if not d.is_dir():
die(f"{d} does not exist - run: npm run build && npm run build-storybook")
if STAGE.exists():
shutil.rmtree(STAGE)
STAGE.mkdir(parents=True)
shutil.copytree(dist, STAGE, dirs_exist_ok=True)
(STAGE / "docs").mkdir(exist_ok=True)
shutil.copytree(sb, STAGE / "docs", dirs_exist_ok=True)
files = [p for p in STAGE.rglob("*") if p.is_file()]
if ZIP.exists():
ZIP.unlink()
with zipfile.ZipFile(ZIP, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z:
for p in files:
z.write(p, p.relative_to(STAGE).as_posix())
raw = ZIP.read_bytes()
b64 = base64.b64encode(raw).decode()
with zipfile.ZipFile(ZIP) as z:
if z.testzip() is not None:
die("zip integrity check failed")
entries = len(z.namelist())
info = {
"files": entries,
"zip_bytes": len(raw),
"b64_bytes": len(b64),
"sha256": hashlib.sha256(raw).hexdigest(),
}
log(f"packaged {entries} files, {len(raw)/1024/1024:.2f} MB zip, "
f"{len(b64)/1024/1024:.2f} MB base64")
log(f"sha256 {info['sha256'][:32]}")
(STAGE.parent / "tansy-payload.json").write_text(json.dumps(info, indent=2))
return info
# --------------------------------------------------------------------------
# cPanel session
# --------------------------------------------------------------------------
class Panel:
def __init__(self, cfg: dict):
import http.cookiejar
self.base = f"https://{cfg['CPANEL_HOST']}:2083"
self.sub = cfg["CPANEL_SUB"]
self.ip = cfg["ORIGIN_IP"]
self.token = ""
self.docroot = f"/home/{cfg['CPANEL_USER']}/{cfg['CPANEL_SUB']}"
self._jar = http.cookiejar.CookieJar()
self._opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(self._jar))
self._login(cfg)
def _http(self, url: str, data: dict | None = None, timeout: int = 240) -> str:
body = urllib.parse.urlencode(data).encode() if data else None
req = urllib.request.Request(url, data=body)
if body:
req.add_header("Content-Type", "application/x-www-form-urlencoded")
try:
return self._opener.open(req, timeout=timeout).read().decode(
"utf-8", "replace")
except urllib.error.HTTPError as e:
return e.read().decode("utf-8", "replace")
def _login(self, cfg: dict) -> None:
out = self._http(f"{self.base}/login/?login_only=1",
{"user": cfg["CPANEL_USER"], "pass": cfg["CPANEL_PASS"]})
try:
self.token = json.loads(out)["security_token"]
except Exception:
die(f"login failed: {out[:200]}")
log(f"logged in, token {self.token}")
def uapi(self, module: str, fn: str, params: dict | None = None) -> dict:
url = f"{self.base}{self.token}/execute/{module}/{fn}"
if params:
url += "?" + urllib.parse.urlencode(params)
return json.loads(self._http(url))
def write_file(self, name: str, content: str) -> None:
out = self._http(
f"{self.base}{self.token}/execute/Fileman/save_file_content",
{"dir": self.docroot, "file": name, "content": content})
try:
ok = json.loads(out).get("status") == 1
except Exception:
ok = False
if not ok:
die(f"failed to write {name}: {out[:200]}")
log(f"wrote {name} ({len(content)} bytes)")
def read_file(self, name: str) -> str:
out = self._http(f"{self.base}{self.token}/execute/Fileman/get_file_content",
{"dir": self.docroot, "file": name})
try:
return json.loads(out).get("data", {}).get("content", "") or ""
except Exception:
return ""
def get_from_origin(self, path: str, timeout: int = 300) -> str:
"""GET the docroot over plain HTTP, bypassing Cloudflare.
The Host header matters: without it the request lands on the server's
default vhost and cPanel answers with its own 404 page instead of the
site's document root.
"""
return self._origin(f"http://{self.ip}{path}", method="GET", timeout=timeout)
def post_to_origin(self, path: str, data: dict, timeout: int = 600) -> str:
"""POST to the docroot over plain HTTP, with the Host header set."""
return self._origin(f"http://{self.ip}{path}", method="POST",
data=data, timeout=timeout)
def _origin(self, url: str, method: str = "GET",
data: dict | None = None, timeout: int = 300) -> str:
body = urllib.parse.urlencode(data).encode() if data else None
req = urllib.request.Request(url, data=body, method=method)
req.add_header("Host", self.sub)
req.add_header("User-Agent", "tansy-deploy/1")
if body:
req.add_header("Content-Type", "application/x-www-form-urlencoded")
try:
return urllib.request.urlopen(req, timeout=timeout).read().decode(
"utf-8", "replace")
except urllib.error.HTTPError as e:
return e.read().decode("utf-8", "replace")
except urllib.error.URLError as e:
die(f"POST {url} failed: {e.reason}")
# --------------------------------------------------------------------------
# verify
# --------------------------------------------------------------------------
def verify(panel: Panel) -> None:
import hashlib as _h
log("verifying…")
idx = panel.get_from_origin("/index.html")
live_sha = _h.sha256(idx.encode()).hexdigest()
local_sha = _h.sha256((REPO / "dist" / "index.html").read_bytes()).hexdigest()
if live_sha != local_sha:
die(f"index.html mismatch\n live {live_sha[:32]}\n local {local_sha[:32]}")
log("index.html matches the local build")
sb = panel.get_from_origin("/docs/index.json")
sb_sha = _h.sha256(sb.encode()).hexdigest()
sb_local = _h.sha256((REPO / "storybook-static" / "index.json").read_bytes()).hexdigest()
if sb_sha != sb_local:
die("docs/index.json mismatch")
log("docs/index.json matches")
for path in ("/", "/docs/", "/docs/iframe.html"):
req = urllib.request.Request(f"http://{panel.ip}{path}",
headers={"Host": panel.sub})
with urllib.request.urlopen(req, timeout=30) as r:
status = r.status
if status != 200:
die(f"{path} returned {status}")
log(f" {path} -> 200")
entries = panel.uapi("Fileman", "list_files",
{"dir": panel.docroot, "show_hidden": 1})
names = sorted(f.get("file") for f in entries.get("data") or [])
leftovers = [n for n in names if n.startswith("_") and n.endswith(".php")]
if leftovers:
die(f"deploy scripts left in the docroot: {leftovers}")
log(f"docroot clean: {names}")
def check_php_syntax(path: Path) -> bool:
"""`php -l` the deployer. True if it parses (or the check was skipped)."""
if SKIP_PHP_LINT:
log("skipping php -l (--skip-php-lint)")
return True
php = shutil.which("php")
if php is None:
log("no local php binary; cannot lint the deployer")
return False
r = subprocess.run([php, "-l", str(path)], capture_output=True, text=True)
if r.returncode != 0:
log(f"php -l failed:\n{r.stdout}{r.stderr}")
return False
log("php -l ok")
return True
# --------------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--build-only", action="store_true")
ap.add_argument("--deploy-only", action="store_true")
ap.add_argument("--dry-run", action="store_true")
ap.add_argument("--skip-php-lint", action="store_true",
help="ship cpanel-deploy.php without `php -l`")
args = ap.parse_args()
global SKIP_PHP_LINT
SKIP_PHP_LINT = args.skip_php_lint
if not args.deploy_only:
build()
info = package()
if args.build_only:
log("build + package only; nothing uploaded")
return
if args.dry_run:
log(f"dry run: would POST {info['b64_bytes']/1024/1024:.2f} MB to cPanel")
return
cfg = load_config()
panel = Panel(cfg)
htaccess_deploy = HTACCESS_DEPLOY.replace("__CPANEL_USER__", cfg["CPANEL_USER"])
htaccess_hardened = HTACCESS_HARDENED.replace("__CPANEL_USER__", cfg["CPANEL_USER"])
# Guard against the failure that cost a whole deploy cycle: a PHP parse
# error makes the server return an empty body and leave _deploy.php on
# disk, which looks identical to "upload was ignored". `php -l` needs a
# local PHP binary, so when there is none, refuse to guess and require an
# explicit override rather than silently shipping a broken script.
if not check_php_syntax(Path(REPO / "scripts" / "cpanel-deploy.php")):
die("cpanel-deploy.php failed `php -l`, or no local PHP is available "
"to check it. Install php-cli or run the deploy with "
"--skip-php-lint if you are certain the file parses.")
# 1. PHP must be on for the uploader to run.
panel.write_file(".htaccess", htaccess_deploy)
time.sleep(2)
# 2. Prove PHP actually executes before relying on it.
panel.write_file("_probe.php", "<?php echo 'PHPEXEC-OK', PHP_VERSION;")
body = panel.get_from_origin("/_probe.php", timeout=30)
if "PHPEXEC-OK" not in body:
panel.write_file(".htaccess", htaccess_hardened)
die(f"PHP is not executing in the docroot (probe returned: {body[:80]!r})")
log("PHP execution confirmed")
# 3. Ship the self-pruning deployer and the payload.
deployer = (REPO / "scripts" / "cpanel-deploy.php").read_text()
panel.write_file("_deploy.php", deployer)
b64 = base64.b64encode(ZIP.read_bytes()).decode()
log(f"uploading {len(b64)/1024/1024:.2f} MB …")
out = panel.post_to_origin("/_deploy.php",
{"data": b64, "keep": json.dumps(KEEP_TOP)},
timeout=600)
log("server said: " + out.strip()[:300])
try:
result = json.loads(out)
except Exception:
panel.write_file(".htaccess", htaccess_hardened)
die("deployer did not return JSON - check the response above")
if not result.get("ok"):
panel.write_file(".htaccess", htaccess_hardened)
die(f"deploy failed: {result}")
log(f"extracted {result['extracted']} files, "
f"pruned {result['pruned_files']} stale files / {result['pruned_dirs']} dirs")
# 4. Re-harden, then confirm PHP is shut off again.
panel.write_file(".htaccess", htaccess_hardened)
time.sleep(2)
after = panel.get_from_origin("/_probe.php", timeout=30)
if "PHPEXEC-OK" in after:
die("PHP is still enabled after hardening - investigate the .htaccess")
log("PHP re-disabled")
verify(panel)
log("done")
if __name__ == "__main__":
main()
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""
Generate the landing page's component catalogue from the built Storybook
index, so it cannot drift from the stories again.
Run it after `npm run build-storybook` and before `npm run build` when you
add or remove a component. It prints the entries to paste into
src/data/catalogue.ts and writes /tmp/component_catalogue.json.
python3 scripts/gen_catalogue.py # print entries
python3 scripts/gen_catalogue.py --patch # also rewrite src/data/catalogue.ts
Story ids are `<group>-<component>--<story>`, but the group is not always
a single segment: TextField publishes as `data-entry-text-field--*`. So
components are matched by longest known name against `base` or
`base.endswith("-" + name)`, with aliases for the hyphenated spellings.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
IDX = REPO / "storybook-static" / "index.json"
CATALOGUE = REPO / "src" / "data" / "catalogue.ts"
OUT = Path("/tmp/component_catalogue.json")
# component id -> group slug
GROUPS = {
"button": "actions",
"accordion": "navigation",
"text-field": "data-entry",
"textfield": "data-entry",
"input": "forms",
"featuredinput": "forms",
"featured-input": "forms",
"select": "forms",
"checkbox": "forms",
"radio": "forms",
"switch": "forms",
"textarea": "forms",
"text-area": "forms",
"alert": "feedback",
"spinner": "feedback",
"badge": "display",
"card": "layout",
"tooltip": "overlays",
}
# alias id key -> canonical component key
CANON = {
"text-field": "textfield",
"featured-input": "featuredinput",
"text-area": "textarea",
}
SPECIAL = {
"textfield": "Text field",
"featuredinput": "FeaturedInput",
"textarea": "TextArea",
"checkbox": "Checkbox",
"spinner": "Spinner",
"accordion": "Accordion",
"tooltip": "Tooltip",
"button": "Button",
"select": "Select",
"radio": "Radio",
"switch": "Switch",
"alert": "Alert",
"badge": "Badge",
"card": "Card",
"input": "Input",
}
GROUP_LABEL = {
"actions": "Actions",
"navigation": "Navigation",
"data": "Data entry",
"data-entry": "Data entry",
"forms": "Forms",
"feedback": "Feedback",
"display": "Display",
"layout": "Layout",
"overlays": "Overlays",
"misc": "Other",
}
# display order on the landing page
ORDER = [
"button", "accordion", "textfield",
"input", "featuredinput", "select", "checkbox", "radio", "switch", "textarea",
"alert", "spinner",
"badge", "card",
"tooltip",
]
# one-line coverage summary shown in the index row
DETAIL = {
"button": "Variants · sizes · disabled",
"accordion": "Disclosure · multiple",
"textfield": "Labels · hints · errors",
"input": "Plain · themed · icon slot",
"featuredinput": "Floating label · password · number",
"select": "Searchable · featured · async",
"checkbox": "Themes · tooltip · uncontrolled",
"radio": "Themes · horizontal · required",
"switch": "Themes · required · described",
"textarea": "Resize · featured · prefilled",
"alert": "Variants · colors · auto-close",
"spinner": "Sizes · variants · dark",
"badge": "Colors · floating · pulse",
"card": "Themes · shadows · horizontal",
"tooltip": "Positions · rich content · sizes",
}
def collect():
if not IDX.is_file():
sys.exit(f"{IDX} not found - run: npm run build-storybook")
entries = json.loads(IDX.read_text())["entries"]
ids = [v.get("id", k) if isinstance(v, dict) else k for k, v in entries.items()]
comps: dict[str, dict] = {}
for sid in ids:
if "--" not in sid:
continue
base, story = sid.split("--", 1)
comp = next(
(CANON.get(c, c) for c in sorted(GROUPS, key=len, reverse=True)
if base == c or base.endswith("-" + c)),
None,
)
if comp is None:
print(f" WARN unmapped story id: {sid}", file=sys.stderr)
continue
g = comps.setdefault(comp, {"group": GROUPS[comp], "doc": None,
"count": 0})
g["count"] += 1
if story in ("documentation", "docs"):
g["doc"] = sid
out = []
for i, comp in enumerate(ORDER, start=1):
g = comps.get(comp)
if not g or not g["doc"]:
print(f" WARN {comp}: no documentation story, skipped", file=sys.stderr)
continue
out.append({
"number": f"{i:02d}",
"group": GROUP_LABEL.get(g["group"], g["group"].title()),
"name": SPECIAL.get(comp, comp.title()),
"detail": DETAIL.get(comp, f"{g['count']} stories"),
"href": f"/docs/?path=/docs/{g['doc']}",
"count": g["count"],
})
return out
def as_tsx(entries) -> str:
body = "".join(
" {\n"
f" number: '{e['number']}',\n"
f" group: '{e['group']}',\n"
f" name: '{e['name']}',\n"
f" detail: '{e['detail']}',\n"
f" href: '{e['href']}',\n"
" },\n"
for e in entries
)
return f"export const documentation: CatalogueEntry[] = [\n{body}]\n"
def as_counts(entries) -> str:
lines = []
for e in entries:
key = e["name"] if re.fullmatch(r"[A-Za-z][A-Za-z0-9]*", e["name"]) \
else f"'{e['name']}'"
lines.append(f" {key}: {e['count']},")
return ("export const storyCounts: Record<string, number> = {\n"
+ "\n".join(lines) + "\n}\n")
def patch_catalogue(entries) -> None:
src = CATALOGUE.read_text()
src, n = re.subn(r"export const documentation\b[^=]*= \[.*?\n\]\n",
lambda _: as_tsx(entries), src, count=1, flags=re.S)
if n == 0:
sys.exit(f"could not find the documentation array in {CATALOGUE}")
src, n2 = re.subn(r"export const storyCounts\b[^=]*= \{.*?\n\}\n",
lambda _: as_counts(entries), src, count=1, flags=re.S)
if n2 == 0:
sys.exit(f"could not find the storyCounts block in {CATALOGUE}")
CATALOGUE.write_text(src)
print(f"patched {CATALOGUE} with {len(entries)} components")
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--patch", action="store_true",
help="rewrite the catalogue and story counts in src/data/catalogue.ts")
args = ap.parse_args()
entries = collect()
if not entries:
sys.exit("no components with a documentation story were found")
total = sum(e["count"] for e in entries)
for e in entries:
print(f" {e['number']} {e['name']:<16} {e['group']:<12} "
f"{e['count']:>2} stories {e['href']}")
OUT.write_text(json.dumps(entries, indent=1))
print(f"\n{len(entries)} components, {total} stories -> {OUT}")
if args.patch:
patch_catalogue(entries)
print("now run: npm run build")
if __name__ == "__main__":
main()
+378
View File
@@ -0,0 +1,378 @@
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
import { ArrowRight, Mail, UserRound } from 'lucide-react'
import { TansyMark } from './brand/TansyMark'
import { Alert } from './components/Alert'
import { Badge } from './components/Badge'
import { Button, LinkButton } from './components/Button'
import { Card } from './components/Card'
import { Checkbox } from './components/Checkbox'
import { FeaturedInput } from './components/FeaturedInput'
import { Radio } from './components/Radio'
import { Select } from './components/Select'
import { Spinner } from './components/Spinner'
import { Switch } from './components/Switch'
import { Tooltip } from './components/Tooltip'
import { documentation, featured, totalStories, type FeaturedName } from './data/catalogue'
import { applyPalette } from './theme/applyPalette'
import { palettes, DEFAULT_PALETTE, type PaletteName } from './theme/palettes'
const STORYBOOK = '/docs/'
const RAMP_STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900] as const
const DEPARTMENTS = [
{ value: 'engineering', label: 'Engineering' },
{ value: 'finance', label: 'Finance' },
{ value: 'people', label: 'People operations' },
{ value: 'sales', label: 'Sales' },
{ value: 'support', label: 'Customer support' },
]
const PAY_CYCLES = [
{ value: 'monthly', label: 'Monthly' },
{ value: 'semi-monthly', label: 'Twice a month' },
{ value: 'weekly', label: 'Weekly' },
]
const principles = [
{
title: 'Named variants',
body: 'Each part offers a short list of deliberate choices. Screens pick one instead of inventing a new style.',
sample: 'variant="outline"',
},
{
title: 'States included',
body: 'Error, disabled, loading and required ship with the part and have their own stories, so nobody has to guess.',
sample: 'error · disabled · loading',
},
{
title: 'Tokens, not hex codes',
body: 'Parts read colour from a 50–900 ramp. Swap the palette and every part follows without a code change.',
sample: 'bg-primary-500',
},
]
/** A small live instance of each featured part, sized to sit in a list row. */
const previews: Record<FeaturedName, ReactNode> = {
Button: <Button size="sm">Save</Button>,
Switch: <Switch size="sm" aria-label="Example switch" defaultChecked />,
Checkbox: <Checkbox aria-label="Example checkbox" defaultChecked />,
Badge: (
<span className="preview-badges">
<Badge type="default" color="success" content="Paid" />
<Badge type="default" color="warning" content="Pending" />
</span>
),
Tooltip: <Tooltip content="Explains a field without adding clutter." position="left" size="sm" theme="primary" />,
}
type FormErrors = Partial<Record<'name' | 'email' | 'department' | 'confirmed', string>>
function EmployeeForm() {
const [name, setName] = useState('Jane Doe')
const [email, setEmail] = useState('jane.doe@')
const [department, setDepartment] = useState('engineering')
const [cycle, setCycle] = useState('monthly')
const [welcome, setWelcome] = useState(true)
const [confirmed, setConfirmed] = useState(false)
const [errors, setErrors] = useState<FormErrors>({})
const [saving, setSaving] = useState(false)
const [added, setAdded] = useState<string | null>(null)
function validate(): FormErrors {
const next: FormErrors = {}
if (!name.trim()) next.name = "Enter the employee's full name."
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) next.email = 'Enter a full work email, like [email protected].'
if (!department) next.department = 'Choose a department.'
if (!confirmed) next.confirmed = 'Confirm the details before adding the employee.'
return next
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const next = validate()
setErrors(next)
if (Object.keys(next).length > 0) return
setSaving(true)
setAdded(null)
window.setTimeout(() => {
const dept = DEPARTMENTS.find((d) => d.value === department)?.label ?? department
const pay = PAY_CYCLES.find((c) => c.value === cycle)?.label.toLowerCase() ?? cycle
setAdded(`${name.trim()} joins ${dept}, paid ${pay}.${welcome ? ' A welcome email is on its way.' : ''}`)
setSaving(false)
}, 900)
}
function handleReset() {
setName('')
setEmail('')
setDepartment('')
setCycle('monthly')
setWelcome(true)
setConfirmed(false)
setErrors({})
setAdded(null)
}
return (
<form onSubmit={handleSubmit} noValidate>
<Card shadow="sm" rounded="xl" className="employee-card">
<Card.Header className="employee-card-header">
<Card.Title>Add an employee</Card.Title>
<p>They appear in the next payroll run.</p>
</Card.Header>
<Card.Body className="employee-card-body">
{added && (
<Alert
key={added}
title="Employee added"
message={added}
iconName="CheckCircle2"
color="success"
onClose={() => setAdded(null)}
/>
)}
<div className="form-row">
<FeaturedInput
id="employee-name"
name="employee-name"
label="Full name"
icon={UserRound}
value={name}
onChange={(e) => setName(e.target.value)}
error={errors.name}
required
/>
<FeaturedInput
id="employee-email"
name="employee-email"
label="Work email"
type="email"
icon={Mail}
value={email}
onChange={(e) => setEmail(e.target.value)}
error={errors.email}
required
/>
</div>
<Select
featured
name="department"
label="Department"
placeholder="Choose a department"
options={DEPARTMENTS}
value={department}
onChange={setDepartment}
error={errors.department}
required
/>
<Radio
name="pay-cycle"
label="Pay cycle"
options={PAY_CYCLES}
value={cycle}
onChange={setCycle}
tooltip="Sets how often this employee appears in a payroll run."
/>
<Switch
name="welcome-email"
label="Send a welcome email"
description="Includes the sign-in link and the first-day checklist."
checked={welcome}
onChange={(e) => setWelcome(e.target.checked)}
/>
<Checkbox
name="confirmed"
label="I checked these details against the signed offer letter"
checked={confirmed}
onChange={(e) => setConfirmed(e.target.checked)}
error={errors.confirmed}
/>
</Card.Body>
<Card.Footer className="employee-card-footer">
<Button variant="ghost" onClick={handleReset} disabled={saving}>
Clear form
</Button>
<Button type="submit" disabled={saving} icon={saving ? <Spinner size="xs" variant="white" /> : undefined}>
{saving ? 'Adding…' : 'Add employee'}
</Button>
</Card.Footer>
</Card>
</form>
)
}
function App() {
const shellRef = useRef<HTMLDivElement>(null)
const [palette, setPalette] = useState<PaletteName>(DEFAULT_PALETTE)
const active = palettes[palette]
useEffect(() => {
if (shellRef.current) applyPalette(shellRef.current, palette)
}, [palette])
return (
<div className="site-shell" ref={shellRef} data-palette={palette}>
<header className="site-header">
<div className="container header-inner">
<a className="brand" href="#top" aria-label="Tansy UI home">
<TansyMark size={30} />
<span className="brand-name">
Tansy<span className="brand-ui">UI</span>
</span>
<span className="brand-by">by OpenKhalix</span>
</a>
<nav className="header-nav" aria-label="Primary">
<a href="#components">Components</a>
<a href="#playground">Playground</a>
<a href="#principles">Principles</a>
</nav>
<LinkButton href={STORYBOOK} size="sm" variant="outline" className="header-cta">
Storybook
</LinkButton>
</div>
</header>
<main id="top">
<section className="hero container" id="components">
<div className="hero-copy">
<p className="eyebrow">
<span>React component kit</span>
<span className="eyebrow-dim">v0.2 · {documentation.length} parts · {totalStories} stories</span>
</p>
<h1>
Small parts,
<br />
<em>one bloom.</em>
</h1>
<p className="lede">
Tansy UI is a React component kit named after the tansy flower, also called golden buttons. Every part
ships with its states, its tokens and a Storybook page, so screens come together from parts that
already work.
</p>
<div className="hero-actions">
<LinkButton href={STORYBOOK} size="lg" icon={<ArrowRight size={18} aria-hidden="true" />}>
Browse all components
</LinkButton>
<LinkButton href="#playground" size="lg" variant="outline">
Try the playground
</LinkButton>
</div>
<p className="stack">React 19 · TypeScript · Tailwind v4 · Storybook 10</p>
</div>
<Card shadow="sm" rounded="xl" className="featured-card" aria-labelledby="featured-title">
<Card.Header className="featured-header">
<h2 id="featured-title">Featured parts</h2>
<Badge type="default" color="primary" content={`${featured.length} of ${documentation.length}`} />
</Card.Header>
<Card.Body className="featured-body">
<ul className="featured-list">
{featured.map((item) => (
<li className="featured-row" key={item.name}>
<div className="featured-text">
<a href={item.href}>{item.name}</a>
<span>
{item.group} · {item.detail}
</span>
</div>
<div className="featured-preview">{previews[item.name]}</div>
</li>
))}
</ul>
</Card.Body>
<Card.Footer className="featured-footer">
<LinkButton
href={STORYBOOK}
variant="secondary"
className="w-full"
icon={<ArrowRight size={16} aria-hidden="true" />}
>
See all {documentation.length} components
</LinkButton>
</Card.Footer>
</Card>
</section>
<section className="playground" id="playground" aria-labelledby="playground-title">
<div className="container playground-grid">
<div className="playground-intro">
<p className="kicker">Playground</p>
<h2 id="playground-title">A working form, built only from Tansy parts.</h2>
<p>
Pick a palette and every part on this page re-themes from the same tokens. Storybook's Palette toolbar
does the same thing.
</p>
<fieldset className="palette-picker">
<legend>Palette</legend>
<div className="palette-options">
{Object.values(palettes).map((p) => (
<button
key={p.name}
type="button"
aria-pressed={p.name === palette}
onClick={() => setPalette(p.name)}
>
<span className="swatch" style={{ background: p.primary[500] }} aria-hidden="true" />
{p.label}
</button>
))}
</div>
<p className="palette-note">{active.note}</p>
</fieldset>
<div className="ramp" aria-label={`${active.label} primary ramp`}>
{RAMP_STEPS.map((step) => (
<div className="ramp-step" key={step}>
<span className="ramp-chip" style={{ background: active.primary[step] }} />
<span className="ramp-label">{step}</span>
</div>
))}
</div>
<p className="ramp-caption">
<code>primary-500</code> = <code>{active.primary[500].toLowerCase()}</code>
</p>
</div>
<EmployeeForm />
</div>
</section>
<section className="container principles" id="principles" aria-labelledby="principles-title">
<div className="principles-head">
<p className="kicker">Principles</p>
<h2 id="principles-title">What every part has to ship with.</h2>
</div>
<div className="principle-grid">
{principles.map((item) => (
<div className="principle" key={item.title}>
<h3>{item.title}</h3>
<p>{item.body}</p>
<code>{item.sample}</code>
</div>
))}
</div>
</section>
</main>
<footer className="site-footer">
<div className="container footer-inner">
<div className="footer-brand">
<TansyMark size={24} />
<span>
<strong>Tansy UI</strong> · a React component kit by OpenKhalix
</span>
</div>
<nav className="footer-nav" aria-label="Footer">
<a href={STORYBOOK}>Storybook</a>
<a href="#playground">Playground</a>
</nav>
</div>
</footer>
</div>
)
}
export default App
+31
View File
@@ -0,0 +1,31 @@
import { Meta } from '@storybook/addon-docs/blocks'
import { TansyMark } from './brand/TansyMark'
import { documentation, totalStories } from './data/catalogue'
<Meta title="Welcome" />
<div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '8px 0 28px' }}>
<TansyMark size={56} />
<div>
<div style={{ fontFamily: '"Schibsted Grotesk", sans-serif', fontWeight: 800, fontSize: 40, letterSpacing: '-0.04em', lineHeight: 1 }}>Tansy <span style={{ fontSize: 40, fontWeight: 700, color: '#6b7384' }}>UI</span></div>
<div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#6b7384', marginTop: 6 }}>
React component kit · {documentation.length} parts · {totalStories} stories
</div>
</div>
</div>
Tansy UI is a React component kit by OpenKhalix. It's named after the tansy flower, also called golden buttons: many small round heads that read as one bloom. Every part here is owned source code: Tailwind classes, variants, validation rules and theme tokens all live in this repository.
## How to read this workshop
- **Documentation** pages list every prop, with controls you can change live.
- **Stories** show one state each. Defaults, errors, disabled and loading states all get their own.
- **Palette** in the toolbar re-themes every part from the `primary`, `secondary`, `gray` and `zink` ramps. The same switch is in the landing page playground.
- **Accessibility** runs axe checks against each story in the panel below the canvas.
## Adding a part
1. Put the component in `src/components/` and keep its style maps in a sibling `*.tokens.ts`.
2. Add a colocated `ComponentName.stories.tsx` with a story for every meaningful state.
3. Read colours from the palette ramps (`bg-primary-500`), never from hex codes.
4. Run `npm run build-storybook`, then `python3 scripts/gen_catalogue.py --patch` to update the landing page catalogue.
+35
View File
@@ -0,0 +1,35 @@
import type { SVGAttributes } from 'react'
export type TansyMarkProps = SVGAttributes<SVGSVGElement> & {
size?: number
}
/** Head centres: one in the middle, six on a hex ring. Shared with `public/tansy-mark.svg`. */
const HEADS = [
[16, 16],
[24.2, 16],
[20.1, 23.1],
[11.9, 23.1],
[7.8, 16],
[11.9, 8.9],
[20.1, 8.9],
] as const
/**
* The Tansy mark: a tansy flowerhead, the plant folk-named "golden buttons".
* The outer heads draw from the palette's primary ramp so the mark re-themes
* with whatever palette is in scope; the gold centre is the fixed brand colour.
* `public/tansy-mark.svg` is the Classic Blue copy for favicons and Storybook.
*/
export function TansyMark({ size = 32, ...props }: TansyMarkProps) {
return (
<svg aria-hidden="true" width={size} height={size} viewBox="0 0 32 32" {...props}>
{HEADS.map(([cx, cy], index) => (
<g key={index}>
<circle cx={cx} cy={cy} r={3.6} fill={index === 0 ? '#f5b40b' : 'var(--color-primary-500)'} />
<circle cx={cx} cy={cy} r={1.45} fill={index === 0 ? '#fde68a' : 'var(--color-primary-200)'} />
</g>
))}
</svg>
)
}
+42
View File
@@ -0,0 +1,42 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Accordion } from './Accordion'
const meta = {
title: 'Navigation/Accordion',
component: Accordion,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component: 'A controlled-friendly disclosure primitive for showing related content without overwhelming the page.',
},
},
},
args: {
items: [
{
title: 'What is a component story?',
content: 'A focused example of one component with specific props, states, and surrounding context.',
},
{
title: 'Why document states?',
content: 'A component is only complete when its loading, empty, error, and success states are clear.',
},
{
title: 'How do I add my own?',
content: 'Create a .stories.tsx file beside the component and use the same Meta and StoryObj patterns.',
},
],
},
} satisfies Meta<typeof Accordion>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {}
export const Multiple: Story = {
args: {
allowMultiple: true,
},
}
+87
View File
@@ -0,0 +1,87 @@
import { useId, useState, type ReactNode } from 'react'
export type AccordionItem = {
title: string
content: ReactNode
}
export type AccordionProps = {
items: AccordionItem[]
defaultOpenIndex?: number
allowMultiple?: boolean
}
function Chevron() {
return (
<svg
aria-hidden="true"
className="size-4 shrink-0 transition-transform duration-200"
fill="none"
viewBox="0 0 20 20"
>
<path
d="m5 7.5 5 5 5-5"
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="1.8"
/>
</svg>
)
}
export function Accordion({ items, defaultOpenIndex = 0, allowMultiple = false }: AccordionProps) {
const [openItems, setOpenItems] = useState<number[]>(
defaultOpenIndex < 0 ? [] : [defaultOpenIndex],
)
const baseId = useId()
function toggle(index: number) {
setOpenItems((current) => {
if (allowMultiple) {
return current.includes(index)
? current.filter((item) => item !== index)
: [...current, index]
}
return current.includes(index) ? [] : [index]
})
}
return (
<div className="divide-y divide-slate-200 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
{items.map((item, index) => {
const isOpen = openItems.includes(index)
const triggerId = `${baseId}-trigger-${index}`
const panelId = `${baseId}-panel-${index}`
return (
<div key={item.title}>
<h3>
<button
id={triggerId}
type="button"
aria-expanded={isOpen}
aria-controls={panelId}
onClick={() => toggle(index)}
className="flex w-full items-center justify-between gap-5 px-5 py-4 text-left text-sm font-bold text-slate-900 transition hover:bg-slate-50"
>
<span>{item.title}</span>
<span className={isOpen ? 'rotate-180 text-primary-500' : 'text-slate-400'}>
<Chevron />
</span>
</button>
</h3>
{isOpen && (
<div id={panelId} role="region" aria-labelledby={triggerId} className="px-5 pb-5">
<div className="border-l-2 border-primary-100 pl-4 text-sm leading-6 text-slate-600">
{item.content}
</div>
</div>
)}
</div>
)
})}
</div>
)
}
+121
View File
@@ -0,0 +1,121 @@
import { useState, type ReactElement } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Alert } from './Alert'
const meta = {
title: 'Feedback/Alert',
component: Alert,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Inline, dismissible status message. `iconName` takes any Lucide icon name as a string, so the icon is controllable without importing the module.',
},
},
},
argTypes: {
color: { control: 'select', options: ['success', 'info', 'warning', 'error'] },
variant: { control: 'select', options: ['default', 'filled', 'outlined', 'gradient'] },
iconName: {
control: 'text',
description: 'Lucide icon name, e.g. "Info", "CheckCircle2", "TriangleAlert".',
},
showCloseButton: { control: 'boolean' },
showMessage: { control: 'boolean' },
closeOnOutsideClick: { control: 'boolean' },
autoClose: {
control: { type: 'number', min: 0, step: 500 },
description: 'Auto-close delay in ms. 0 disables.',
},
width: { control: 'text' },
height: { control: 'text' },
},
args: {
title: 'Payroll run approved',
message: 'March 2026 payroll was approved and queued for disbursement.',
iconName: 'CheckCircle2',
variant: 'default',
color: 'success',
showCloseButton: true,
showMessage: true,
closeOnOutsideClick: false,
autoClose: 0,
width: 'w-full',
height: 'h-auto',
},
} satisfies Meta<typeof Alert>
export default meta
type Story = StoryObj<typeof meta>
/**
* Dismissing unmounts the Alert, so this wrapper remounts it via a changing key.
* Declared as a named component so the rules-of-hooks lint accepts the hook call.
*/
function Remountable({ children, note }: { children: ReactElement; note?: string }) {
const [key, setKey] = useState(0)
return (
<div className="space-y-3">
<div key={key}>{children}</div>
<button
type="button"
onClick={() => setKey((k) => k + 1)}
className="text-xs font-semibold text-primary-600 underline"
>
Remount
</button>
{note && <p className="text-xs text-gray-500">{note}</p>}
</div>
)
}
export const Playground: Story = {
render: (args) => <Remountable><Alert {...args} /></Remountable>,
}
export const Colors: Story = {
render: () => (
<div className="space-y-3">
<Alert color="success" title="Approved" message="Queued for disbursement." iconName="CheckCircle2" />
<Alert color="info" title="Processing" message="Validating statutory contributions." iconName="Info" />
<Alert color="warning" title="Review needed" message="2 employees have incomplete bank details." iconName="TriangleAlert" />
<Alert color="error" title="Failed" message="Bank rejected the transfer file." iconName="XCircle" />
</div>
),
}
export const Variants: Story = {
render: () => (
<div className="space-y-3">
<Alert variant="default" color="info" title="Default" message="Tinted surface, semantic text." />
<Alert variant="filled" color="info" title="Filled" message="Solid semantic background." />
<Alert variant="outlined" color="info" title="Outlined" message="Transparent with a border." />
<Alert variant="gradient" title="Gradient" message="Green-to-primary gradient, brand moment." />
</div>
),
}
export const WithoutCloseButton: Story = {
render: () => (
<Alert
color="info"
title="Persistent notice"
message="This alert cannot be dismissed."
showCloseButton={false}
/>
),
}
export const TitleOnly: Story = {
render: () => <Alert color="warning" title="12 items need attention" showCloseButton={false} />,
}
/** Auto-closes after 2s; the Remount button brings it back. */
export const AutoClose: Story = {
render: (args) => (
<Remountable note="Dismisses itself after 2000ms.">
<Alert {...args} autoClose={2000} />
</Remountable>
),
}
+156
View File
@@ -0,0 +1,156 @@
import {
useCallback,
useEffect,
useRef,
useState,
forwardRef,
type HTMLAttributes,
type ReactNode,
} from 'react'
import * as Icons from 'lucide-react'
import { cn } from '@/lib/cn'
import {
ALERT_COLORS,
ALERT_GRADIENT,
type AlertColor,
type AlertVariant,
} from './alert.tokens'
/**
* Dismissible inline alert.
*
* Ported from the original `Alert` component.
*
* `iconName` takes a Lucide icon name as a string (looked up on the module), so
* the icon is controllable from Storybook without importing every icon.
*/
export type AlertProps = HTMLAttributes<HTMLDivElement> & {
title?: string
message?: ReactNode
/** Name of a Lucide icon, e.g. `"Info"`, `"CheckCircle2"`. Falls back to `Info`. */
iconName?: string
onClose?: () => void
variant?: AlertVariant
color?: AlertColor
showCloseButton?: boolean
width?: string
height?: string
closeOnOutsideClick?: boolean
/** Auto-close delay in ms. `0` disables. */
autoClose?: number
showMessage?: boolean
customClose?: ReactNode
}
export const Alert = forwardRef<HTMLDivElement, AlertProps>(function Alert(
{
title,
message,
iconName = 'Info',
onClose,
variant = 'default',
color = 'success',
className = '',
showCloseButton = true,
width = 'w-full',
height = 'h-auto',
closeOnOutsideClick = false,
autoClose = 0,
showMessage = true,
customClose,
...props
},
forwardedRef,
) {
const [visible, setVisible] = useState(true)
const internalRef = useRef<HTMLDivElement>(null)
const handleClose = useCallback(() => {
setVisible(false)
onClose?.()
}, [onClose])
// Mirror the internal node onto the forwarded ref.
useEffect(() => {
const node = internalRef.current
if (typeof forwardedRef === 'function') forwardedRef(node)
else if (forwardedRef) forwardedRef.current = node
}, [forwardedRef])
useEffect(() => {
if (autoClose > 0) {
const timer = setTimeout(handleClose, autoClose)
return () => clearTimeout(timer)
}
}, [autoClose, handleClose])
useEffect(() => {
if (!closeOnOutsideClick) return
const handleClickOutside = (event: MouseEvent) => {
if (internalRef.current && !internalRef.current.contains(event.target as Node)) {
handleClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [closeOnOutsideClick, handleClose])
if (!visible) return null
const iconMap = Icons as unknown as Record<string, Icons.LucideIcon>
const LucideIcon = (iconName && iconMap[iconName]) || Icons.Info
const theme = ALERT_COLORS[color] ?? ALERT_COLORS.success
let variantClasses: string
if (variant === 'filled') {
variantClasses = cn(theme.bg, 'text-white')
} else if (variant === 'outlined') {
variantClasses = cn('bg-transparent', theme.text, theme.border, 'border')
} else if (variant === 'gradient') {
variantClasses = ALERT_GRADIENT
} else {
variantClasses = cn(theme.lightBg, theme.text)
}
return (
<div
ref={internalRef}
role="alert"
className={cn(
'rounded-md p-3 transition-all duration-300',
width,
height,
variantClasses,
className,
)}
{...props}
>
<div className="flex justify-between gap-3">
<div className="flex items-start gap-3 w-full">
{LucideIcon && <LucideIcon className="w-5 h-5 mt-0.5 shrink-0" aria-hidden="true" />}
<div className="flex flex-col gap-1 w-full">
{title && <h5 className="font-semibold text-sm leading-tight">{title}</h5>}
{showMessage && message && <p className="text-sm opacity-90 leading-normal">{message}</p>}
</div>
</div>
{showCloseButton && (
<button
onClick={handleClose}
className="shrink-0 p-1 rounded-md hover:bg-black/10 transition-colors cursor-pointer"
type="button"
aria-label="Close alert"
>
{customClose ?? <Icons.X className="w-4 h-4" />}
</button>
)}
</div>
</div>
)
})
export default Alert
+139
View File
@@ -0,0 +1,139 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Bell, Inbox, Settings } from 'lucide-react'
import { Badge } from './Badge'
const meta = {
title: 'Display/Badge',
component: Badge,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Status count or label. `floating` pins to a corner of its child; `default` renders a standalone chip. `colorRanges` colours the badge by numeric value.',
},
},
},
argTypes: {
type: { control: 'radio', options: ['floating', 'default'] },
color: {
control: 'select',
options: ['primary', 'info', 'gray', 'danger', 'success', 'warning'],
},
floatingPosition: {
control: 'select',
options: ['top_right', 'top_left', 'bottom_right', 'bottom_left'],
},
floatingSize: { control: 'select', options: ['xs', 'sm', 'md', 'lg'] },
defaultSize: { control: 'select', options: ['sm', 'md', 'lg'] },
defaultBorder: { control: 'select', options: ['sm', 'md', 'lg', 'full'] },
pulse: { control: 'boolean' },
content: { control: 'text' },
},
args: {
type: 'floating',
color: 'danger',
content: '5',
floatingPosition: 'top_right',
floatingSize: 'sm',
defaultSize: 'sm',
defaultBorder: 'lg',
pulse: false,
},
} satisfies Meta<typeof Badge>
export default meta
type Story = StoryObj<typeof meta>
const BellIcon = () => <Bell className="h-6 w-6 text-gray-600" />
export const Playground: Story = {
render: (args) => (
<Badge {...args}>
<BellIcon />
</Badge>
),
}
export const FloatingPositions: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-10">
{(['top_right', 'top_left', 'bottom_right', 'bottom_left'] as const).map((pos) => (
<div key={pos} className="flex flex-col items-center gap-2">
<Badge content="9" floatingPosition={pos} color="primary">
<BellIcon />
</Badge>
<code className="text-[10px] text-gray-500">{pos}</code>
</div>
))}
</div>
),
}
export const FloatingSizes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-10">
{(['xs', 'sm', 'md', 'lg'] as const).map((size) => (
<div key={size} className="flex flex-col items-center gap-2">
<Badge content={12} floatingSize={size} color="danger">
<Inbox className="h-6 w-6 text-gray-600" />
</Badge>
<code className="text-[10px] text-gray-500">{size}</code>
</div>
))}
</div>
),
}
export const Colors: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-3">
{(['primary', 'info', 'gray', 'danger', 'success', 'warning'] as const).map((color) => (
<Badge key={color} type="default" color={color}>
{color}
</Badge>
))}
</div>
),
}
/** Colours by numeric content — the pending-approval pattern from the source app. */
export const ColorRanges: Story = {
render: () => {
const ranges = [
{ min: 0, max: 2, color: 'success' },
{ min: 3, max: 7, color: 'warning' },
{ min: 8, max: 99, color: 'danger' },
]
return (
<div className="flex flex-wrap items-center gap-6">
{[1, 5, 12].map((n) => (
<div key={n} className="flex flex-col items-center gap-2">
<Badge content={n} colorRanges={ranges}>
<Inbox className="h-6 w-6 text-gray-600" />
</Badge>
<code className="text-[10px] text-gray-500">{n} pending</code>
</div>
))}
</div>
)
},
}
export const Pulse: Story = {
render: () => (
<Badge content="Live" color="danger" pulse>
<BellIcon />
</Badge>
),
}
/** `default` type renders a standalone chip; children take precedence over content. */
export const ChipWithIcon: Story = {
render: () => (
<Badge type="default" color="primary" defaultBorder="full" defaultSize="md">
<Settings className="mr-1.5 h-3.5 w-3.5" aria-hidden="true" />
Configured
</Badge>
),
}
+113
View File
@@ -0,0 +1,113 @@
import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
import { cn } from '@/lib/cn'
import {
BADGE_COLORS,
BADGE_COLOR_ALIAS,
BADGE_POSITIONS,
BADGE_ROUNDED,
BADGE_SIZES,
DEFAULT_BADGE_SIZES,
resolveBadgeColor,
type BadgeBorder,
type BadgeColor,
type BadgeDefaultSize,
type BadgeFloatingPosition,
type BadgeFloatingSize,
type BadgeType,
type ColorRange,
} from './badge.tokens'
/**
* Status indicator / count badge.
*
* Ported from the original `Badge` component.
*
* Two shapes:
* - `floating` (default) — pins the badge to a corner of its child (an icon or
* avatar), so the child wraps it.
* - `default` — a standalone inline chip.
*
* `colorRanges` maps a numeric `content` onto a colour band, which is how the
* source app colours pending-approval counts without a per-row className.
*/
export type BadgeProps = Omit<HTMLAttributes<HTMLDivElement>, 'content'> & {
type?: BadgeType
/** The count or label. Accepts a number — counts arrive as numbers in the source app. */
content?: ReactNode | number
color?: BadgeColor | string
/** Colour the badge by numeric value, e.g. `[{min:5,max:9,color:'warning'}]`. */
colorRanges?: ColorRange[]
floatingPosition?: BadgeFloatingPosition
floatingSize?: BadgeFloatingSize
defaultSize?: BadgeDefaultSize
defaultBorder?: BadgeBorder
/** Remix-icon class name, e.g. `"ri-home-line"`. Needs the Remix font. */
defaultIcon?: string
pulse?: boolean
}
export const Badge = forwardRef<HTMLDivElement, BadgeProps>(function Badge(
{
type = 'floating',
content,
color = 'danger',
colorRanges,
children,
floatingPosition = 'top_right',
floatingSize = 'sm',
pulse = false,
className = '',
defaultSize = 'sm',
defaultBorder = 'lg',
defaultIcon,
...props
},
ref,
) {
const normalized = BADGE_COLOR_ALIAS[color] ?? (color as BadgeColor)
const computed =
type === 'floating' ? resolveBadgeColor(color, content, colorRanges) : normalized
const theme = BADGE_COLORS[computed] ?? BADGE_COLORS[normalized] ?? BADGE_COLORS.danger
if (type === 'default') {
return (
<div
ref={ref}
className={cn(
'inline-flex items-center justify-center font-medium transition-colors',
BADGE_ROUNDED[defaultBorder] ?? BADGE_ROUNDED.lg,
DEFAULT_BADGE_SIZES[defaultSize] ?? DEFAULT_BADGE_SIZES.sm,
theme,
className,
)}
{...props}
>
{defaultIcon && <i className={cn(defaultIcon, 'mr-1.5')} aria-hidden="true" />}
{children ?? content}
</div>
)
}
return (
<span className="relative inline-flex">
{children}
<div
ref={ref}
className={cn(
'absolute z-10 inline-flex items-center justify-center rounded-full font-semibold',
BADGE_POSITIONS[floatingPosition] ?? BADGE_POSITIONS.top_right,
BADGE_SIZES[floatingSize] ?? BADGE_SIZES.sm,
theme,
pulse && 'animate-pulse',
className,
)}
{...props}
>
{content}
</div>
</span>
)
})
export default Badge
+80
View File
@@ -0,0 +1,80 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Button, LinkButton } from './Button'
const meta = {
title: 'Actions/Button',
component: Button,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component: 'A reusable button with visual variants and size tokens. Use semantic variants rather than ad-hoc colors.',
},
},
},
argTypes: {
variant: {
control: 'select',
options: ['primary', 'secondary', 'outline', 'ghost', 'danger'],
},
size: {
control: 'select',
options: ['sm', 'md', 'lg'],
},
},
args: {
children: 'Continue',
variant: 'primary',
size: 'md',
},
} satisfies Meta<typeof Button>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Variants: Story = {
render: () => (
<div className="flex flex-wrap gap-3">
<Button>Primary</Button>
<Button variant="secondary">Secondary</Button>
<Button variant="outline">Outline</Button>
<Button variant="ghost">Ghost</Button>
<Button variant="danger">Danger</Button>
</div>
),
}
export const Sizes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-3">
<Button size="sm">Small</Button>
<Button size="md">Medium</Button>
<Button size="lg">Large</Button>
</div>
),
}
export const Disabled: Story = {
args: {
disabled: true,
children: 'Unavailable',
},
}
export const AsLink: Story = {
parameters: {
docs: {
description: {
story: '`LinkButton` renders an anchor with the same variants and sizes. Use it for navigation so the page keeps real links.',
},
},
},
render: () => (
<div className="flex flex-wrap gap-3">
<LinkButton href="#">Browse components</LinkButton>
<LinkButton href="#" variant="outline">Read the guide</LinkButton>
</div>
),
}
+73
View File
@@ -0,0 +1,73 @@
import type { AnchorHTMLAttributes, ButtonHTMLAttributes, ReactNode } from 'react'
export type ButtonVariant = 'primary' | 'secondary' | 'outline' | 'ghost' | 'danger'
export type ButtonSize = 'sm' | 'md' | 'lg'
type ButtonStyleProps = {
variant?: ButtonVariant
size?: ButtonSize
icon?: ReactNode
}
export type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & ButtonStyleProps
/** A navigation link that looks like a Button. Use it wherever the action is "go somewhere". */
export type LinkButtonProps = AnchorHTMLAttributes<HTMLAnchorElement> & ButtonStyleProps & {
href: string
}
const variantClasses: Record<ButtonVariant, string> = {
primary:
'border-primary-500 bg-primary-500 text-white shadow-sm hover:border-primary-600 hover:bg-primary-600',
secondary:
'border-slate-200 bg-slate-100 text-slate-800 hover:border-slate-300 hover:bg-slate-200',
outline:
'border-slate-300 bg-white text-slate-700 hover:border-primary-500 hover:bg-primary-50 hover:text-primary-700',
ghost:
'border-transparent bg-transparent text-slate-600 hover:bg-slate-100 hover:text-slate-950',
danger:
'border-red-600 bg-red-600 text-white shadow-sm shadow-red-200 hover:border-red-700 hover:bg-red-700',
}
const sizeClasses: Record<ButtonSize, string> = {
sm: 'min-h-9 gap-1.5 rounded-lg px-3 text-sm',
md: 'min-h-11 gap-2 rounded-xl px-4 text-sm',
lg: 'min-h-12 gap-2.5 rounded-xl px-5 text-base',
}
function buttonClasses(variant: ButtonVariant, size: ButtonSize, className: string) {
return `inline-flex items-center justify-center border font-semibold transition duration-200 disabled:cursor-not-allowed disabled:opacity-50 ${variantClasses[variant]} ${sizeClasses[size]} ${className}`
}
export function Button({
variant = 'primary',
size = 'md',
icon,
className = '',
children,
type = 'button',
...props
}: ButtonProps) {
return (
<button type={type} className={buttonClasses(variant, size, className)} {...props}>
{icon}
{children}
</button>
)
}
export function LinkButton({
variant = 'primary',
size = 'md',
icon,
className = '',
children,
...props
}: LinkButtonProps) {
return (
<a className={buttonClasses(variant, size, className)} {...props}>
{children}
{icon}
</a>
)
}
+105
View File
@@ -0,0 +1,105 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Card } from './Card'
const meta = {
title: 'Layout/Card',
component: Card,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Surface container with a compound API: `Card.Header`, `Card.Title`, `Card.Body`, `Card.Footer`. Theme and layout are passed down to children automatically.',
},
},
},
argTypes: {
theme: {
control: 'select',
options: ['primary', 'secondary', 'success', 'danger', 'no-preset'],
},
layout: { control: 'radio', options: ['vertical', 'horizontal'] },
shadow: { control: 'select', options: ['none', 'sm', 'md', 'lg', 'xl'] },
rounded: { control: 'select', options: ['none', 'sm', 'md', 'lg', 'xl', 'full'] },
},
args: { theme: 'primary', layout: 'vertical', shadow: 'md', rounded: 'lg' },
} satisfies Meta<typeof Card>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {
render: (args) => (
<Card {...args} className="max-w-sm">
<Card.Header>
<Card.Title>Payroll run</Card.Title>
</Card.Header>
<Card.Body>March 2026 · 148 employees · ₹42,10,550 net</Card.Body>
<Card.Footer>Processed 2 hours ago</Card.Footer>
</Card>
),
}
export const Themes: Story = {
render: () => (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
{(['primary', 'secondary', 'success', 'danger'] as const).map((theme) => (
<Card key={theme} theme={theme}>
<Card.Header>
<Card.Title className="text-base capitalize">{theme}</Card.Title>
</Card.Header>
<Card.Body className="text-sm">Surface tinted for the {theme} state.</Card.Body>
</Card>
))}
</div>
),
}
export const Shadows: Story = {
render: () => (
<div className="flex flex-wrap items-start gap-6">
{(['none', 'sm', 'md', 'lg', 'xl'] as const).map((shadow) => (
<div key={shadow} className="flex flex-col items-center gap-2">
<Card shadow={shadow} className="w-40 p-6 text-center text-sm">
{shadow}
</Card>
<code className="text-[10px] text-gray-500">{shadow}</code>
</div>
))}
</div>
),
}
export const Rounded: Story = {
render: () => (
<div className="flex flex-wrap items-start gap-6">
{(['none', 'sm', 'md', 'lg', 'xl', 'full'] as const).map((rounded) => (
<div key={rounded} className="flex flex-col items-center gap-2">
<Card rounded={rounded} className="w-32 p-6 text-center text-sm">
{rounded}
</Card>
<code className="text-[10px] text-gray-500">{rounded}</code>
</div>
))}
</div>
),
}
/** `horizontal` splits into a 2-column grid; `fullRow` makes a child span both. */
export const HorizontalLayout: Story = {
render: () => (
<Card layout="horizontal" className="max-w-lg">
<Card.Header>
<Card.Title>Employee breakdown</Card.Title>
</Card.Header>
<Card.Body>
<div className="grid gap-1 text-sm">
<span>Full-time · 132</span>
<span>Part-time · 11</span>
<span>Contract · 5</span>
</div>
</Card.Body>
<Card.Footer className="text-xs text-gray-500">As of 31 Mar 2026</Card.Footer>
</Card>
),
}
+183
View File
@@ -0,0 +1,183 @@
import {
Children,
cloneElement,
forwardRef,
isValidElement,
type ForwardRefExoticComponent,
type HTMLAttributes,
type ReactElement,
type RefAttributes,
} from 'react'
import { cn } from '@/lib/cn'
import {
CARD_THEMES,
ROUNDED_SIZES,
SHADOW_SIZES,
type CardLayout,
type CardRounded,
type CardShadow,
type CardTheme,
} from './card.tokens'
/**
* Surface container with a header / body / footer compound API.
*
* Ported from the original `Card` component.
*
* Note: the original used `dark:` variants throughout. Those are dropped here
* because this showcase renders on a light canvas and Storybook backgrounds are
* controlled independently — leaving them in produced dark rules that could
* never be inspected. Add them back per-component if dark mode returns.
*/
type SpanProps = {
layout?: CardLayout
fullRow?: boolean
fullCol?: boolean
}
/** Grid span helper shared by header / body / footer. */
function spanClasses({ layout, fullRow, fullCol }: SpanProps): string {
if (layout === 'horizontal') {
if (fullRow) return 'col-span-2'
if (fullCol) return 'row-span-2'
return 'col-span-1'
}
return 'col-span-1'
}
export type CardProps = HTMLAttributes<HTMLDivElement> & {
theme?: CardTheme
layout?: CardLayout
shadow?: CardShadow
rounded?: CardRounded
}
type CardComponent = ForwardRefExoticComponent<CardProps & RefAttributes<HTMLDivElement>> & {
Header: typeof CardHeader
Title: typeof CardTitle
Body: typeof CardBody
Content: typeof CardBody
Footer: typeof CardFooter
}
const CardBase = forwardRef<HTMLDivElement, CardProps>(function Card(
{
children,
theme = 'primary',
layout = 'vertical',
shadow = 'md',
rounded = 'lg',
className = '',
...props
},
ref,
) {
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
const gridCols = layout === 'horizontal' ? 'grid-cols-1 md:grid-cols-2' : 'grid-cols-1'
return (
<div
ref={ref}
className={cn(
'grid overflow-hidden relative',
gridCols,
SHADOW_SIZES[shadow] ?? SHADOW_SIZES.md,
ROUNDED_SIZES[rounded] ?? ROUNDED_SIZES.lg,
themeData.card,
className,
)}
{...props}
>
{/* Pass theme/layout down so nested header/body/footer stay in sync. */}
{Children.map(children, (child) => {
if (!isValidElement(child)) return null
const childProps = child.props as SpanProps & { theme?: CardTheme; layout?: CardLayout }
return cloneElement(child as ReactElement<Record<string, unknown>>, {
theme: childProps.theme ?? theme,
layout: childProps.layout ?? layout,
})
})}
</div>
)
})
export function CardHeader({
children,
className = '',
theme = 'primary',
layout = 'vertical',
fullRow = false,
fullCol = false,
...props
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
return (
<div
className={cn(themeData.header, spanClasses({ layout, fullRow, fullCol }), className)}
{...props}
>
{children}
</div>
)
}
export function CardTitle({ children, className = '', ...props }: HTMLAttributes<HTMLHeadingElement>) {
return (
<h3 className={cn('text-lg font-bold leading-none tracking-tight', className)} {...props}>
{children}
</h3>
)
}
export function CardBody({
children,
className = '',
theme = 'primary',
layout = 'vertical',
fullRow = false,
fullCol = false,
...props
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
return (
<div
className={cn(themeData.body, spanClasses({ layout, fullRow, fullCol }), className)}
{...props}
>
{children}
</div>
)
}
export const CardContent = CardBody
export function CardFooter({
children,
className = '',
theme = 'primary',
layout = 'vertical',
fullRow = false,
fullCol = false,
...props
}: HTMLAttributes<HTMLDivElement> & SpanProps & { theme?: CardTheme }) {
const themeData = CARD_THEMES[theme] ?? CARD_THEMES.primary
return (
<div
className={cn(themeData.footer, spanClasses({ layout, fullRow, fullCol }), className)}
{...props}
>
{children}
</div>
)
}
export const Card = Object.assign(CardBase, {
Header: CardHeader,
Title: CardTitle,
Body: CardBody,
Content: CardContent,
Footer: CardFooter,
}) as CardComponent
export default Card
+119
View File
@@ -0,0 +1,119 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Checkbox } from './Checkbox'
const meta = {
title: 'Forms/Checkbox',
component: Checkbox,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Checkbox with an optional label, help tooltip and error message. The checked colour uses the native `accent-*` property, so it follows the palette tokens rather than a fixed hex.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: {
control: 'select',
options: ['primary', 'secondary', 'success', 'danger', 'warning', 'info'],
},
label: { control: 'text' },
disabled: { control: 'boolean' },
tooltip: { control: 'text', description: 'Help text shown in a tooltip beside the label.' },
helpText: { control: 'text', description: 'Alias for tooltip; tooltip wins if both are set.' },
error: { control: 'text' },
},
args: {
label: 'Send payroll summary email',
size: 'md',
theme: 'primary',
disabled: false,
tooltip: '',
helpText: '',
error: '',
},
} satisfies Meta<typeof Checkbox>
export default meta
type Story = StoryObj<typeof meta>
/** Checkbox state lives with the caller, so it is controlled here. */
/**
* Wraps Checkbox with local state so it is interactive.
*
* `initial` matters: supplying `checked` at all makes the component controlled,
* so `defaultChecked` on the same element would be ignored. Stories that need to
* show the checked appearance set the initial value here.
*/
function ControlledCheckbox({
initial = false,
...args
}: React.ComponentProps<typeof Checkbox> & { initial?: boolean }) {
const [checked, setChecked] = useState(initial)
return <Checkbox {...args} checked={checked} onChange={(e) => setChecked(e.target.checked)} />
}
export const Playground: Story = {
render: (args) => <ControlledCheckbox {...args} />,
}
export const Uncontrolled: Story = {
render: (args) => <Checkbox {...args} defaultChecked />,
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-col gap-4">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledCheckbox key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{(['primary', 'secondary', 'success', 'danger', 'warning', 'info'] as const).map((theme) => (
<ControlledCheckbox key={theme} theme={theme} label={theme} initial />
))}
</div>
),
}
export const WithTooltip: Story = {
args: { tooltip: 'Recipients can be configured per entity in Settings → Notifications.' },
render: (args) => <ControlledCheckbox {...args} />,
}
export const WithError: Story = {
args: { error: 'You must acknowledge the policy before continuing.' },
render: (args) => <ControlledCheckbox {...args} />,
}
/** Error accepts an object too, matching a form-library error shape. */
export const ErrorAsObject: Story = {
render: () => (
<Checkbox
label="Acknowledge policy"
error={{ message: 'This field is required' }}
/>
),
}
export const Disabled: Story = {
render: () => (
<div className="flex flex-col gap-3">
<Checkbox label="Unchecked and disabled" disabled />
<Checkbox label="Checked and disabled" defaultChecked disabled />
</div>
),
}
/** No label — a bare control for use inside a table row or toolbar. */
export const WithoutLabel: Story = {
render: () => <ControlledCheckbox label="" />
}
+106
View File
@@ -0,0 +1,106 @@
import { forwardRef, type InputHTMLAttributes } from 'react'
import type { LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import { Tooltip } from './Tooltip'
import { CHECKBOX_SIZES, CHECKBOX_THEMES, type CheckboxSize, type CheckboxTheme } from './checkbox.tokens'
/**
* Checkbox with an optional label, error message and help tooltip.
*
* Ported from the original `Checkbox` component.
*
* The checked colour uses the native `accent-*` property, so the browser paints
* it — that means `theme` follows the CSS custom properties, not a hard-coded hex.
*
* The `register` / `validation` props are React Hook Form plumbing and are not
* part of a design-system component; they are left out here. Pass `name`,
* `checked` and `onChange` directly.
*/
// `size` and `type` are omitted from the DOM props: `InputHTMLAttributes` declares
// `size` as a number, which would collide with the visual-size token below.
export type CheckboxProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'size'> & {
label?: string
size?: CheckboxSize
theme?: CheckboxTheme
/** Error text, or an object carrying a `message`. */
error?: string | { message?: string }
tooltip?: string
tooltipIcon?: LucideIcon
helpText?: string
}
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(
{
name,
label,
size = 'md',
disabled = false,
theme = 'primary',
error,
className,
checked,
onChange,
tooltip,
tooltipIcon,
helpText,
...props
},
ref,
) {
const sizeClass = CHECKBOX_SIZES[size] ?? CHECKBOX_SIZES.md
const themeClass = CHECKBOX_THEMES[theme] ?? CHECKBOX_THEMES.primary
const errorMessage = typeof error === 'string' ? error : error?.message
return (
<div className={cn('flex flex-col items-start space-y-1', className)}>
<label
htmlFor={name ? `checkbox-${name}` : undefined}
className={cn(
'inline-flex items-center space-x-2',
disabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer',
)}
>
<input
id={name ? `checkbox-${name}` : undefined}
name={name}
type="checkbox"
disabled={disabled}
className={cn(
'peer rounded border-gray-300',
'focus:ring-0 focus:ring-offset-0',
themeClass,
sizeClass,
)}
checked={checked}
onChange={onChange}
ref={ref}
{...props}
/>
{label && (
<div className="flex items-center gap-1.5 ml-2">
<span className="text-sm text-slate-600 select-none">{label}</span>
{(tooltip || helpText) && (
<span className="inline-flex" onClick={(e) => e.preventDefault()}>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</div>
)}
</label>
{errorMessage && (
<p className="text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
})
export default Checkbox
+169
View File
@@ -0,0 +1,169 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Mail, Lock, User, Search } from 'lucide-react'
import { FeaturedInput } from './FeaturedInput'
const meta: Meta<typeof FeaturedInput> = {
title: 'Forms/FeaturedInput',
component: FeaturedInput,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Input with an animated floating label, a built-in password show/hide toggle, and number-input hardening (blocks `e`/`+`/`-` and blurs on wheel). The floated label gets extra top padding here — the source omits it, which renders the text underneath the label.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
variant: { control: 'select', options: ['outlined', 'underlined'] },
type: { control: 'select', options: ['text', 'email', 'password', 'number', 'tel'] },
shrink: { control: 'boolean' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
showPasswordToggle: { control: 'boolean' },
roundedFull: { control: 'boolean' },
dashedBorder: { control: 'boolean' },
label: { control: 'text' },
placeholder: { control: 'text' },
error: { control: 'text' },
},
args: {
label: 'Full name',
placeholder: 'Jane Doe',
type: 'text',
size: 'md',
theme: 'primary',
variant: 'outlined',
shrink: false,
required: false,
disabled: false,
showPasswordToggle: true,
roundedFull: false,
dashedBorder: false,
error: '',
},
}
export default meta
function ControlledFeatured({
initial = '',
...args
}: React.ComponentProps<typeof FeaturedInput> & { initial?: string }) {
const [value, setValue] = useState(initial)
return (
<FeaturedInput {...args} value={value} onChange={(e) => setValue(e.target.value)} />
)
}
export const FeaturedPlayground: StoryObj<typeof FeaturedInput> = {
render: (args) => (
<div className="max-w-md">
<ControlledFeatured {...args} />
</div>
),
}
export const FloatingStates: StoryObj<typeof FeaturedInput> = {
name: 'Floating states',
render: () => (
<div className="flex max-w-md flex-col gap-8 pb-4">
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Resting (empty)</p>
<ControlledFeatured label="Full name" placeholder="Jane Doe" />
</div>
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Floated (has value)</p>
<ControlledFeatured label="Full name" initial="Jane Doe" />
</div>
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Forced (shrink)</p>
<ControlledFeatured label="Full name" shrink placeholder="Jane Doe" />
</div>
<div>
<p className="mb-2 text-[10px] uppercase tracking-wider text-gray-400">Error</p>
<ControlledFeatured label="Full name" error="This field is required." />
</div>
</div>
),
}
export const PasswordWithToggle: StoryObj<typeof FeaturedInput> = {
render: () => (
<div className="max-w-md">
<ControlledFeatured type="password" label="SMTP password" placeholder="••••••••" />
</div>
),
}
export const PasswordToggleDisabled: StoryObj<typeof FeaturedInput> = {
render: () => (
<div className="max-w-md">
<ControlledFeatured
type="password"
label="Locked field"
showPasswordToggle={false}
initial="stored-secret"
/>
</div>
),
}
export const WithLucideIcon: StoryObj<typeof FeaturedInput> = {
render: () => (
<div className="flex max-w-md flex-col gap-6">
<ControlledFeatured label="Email" icon={Mail} placeholder="[email protected]" />
<ControlledFeatured label="Username" icon={User} iconPosition="right" placeholder="jane" />
<ControlledFeatured label="Search" icon={Search} placeholder="Search employees" />
<ControlledFeatured label="API key" icon={Lock} type="password" placeholder="sk_live_…" />
</div>
),
}
export const NumberHardening: StoryObj<typeof FeaturedInput> = {
name: 'Number hardening',
render: () => (
<div className="max-w-md">
<ControlledFeatured
type="number"
label="Annual CTC"
placeholder="1200000"
helpText="Blocks e, +, - and wheel scrolling."
/>
</div>
),
}
export const FeaturedThemes: StoryObj<typeof FeaturedInput> = {
name: 'Themes',
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
<ControlledFeatured key={theme} theme={theme} label={theme} initial="Filled" />
))}
</div>
),
}
export const FeaturedVariants: StoryObj<typeof FeaturedInput> = {
name: 'Variants',
render: () => (
<div className="flex max-w-lg flex-col gap-8 pb-4">
<ControlledFeatured variant="outlined" label="Outlined" initial="Value" />
<ControlledFeatured variant="underlined" label="Underlined" initial="Value" />
</div>
),
}
export const FeaturedDisabled: StoryObj<typeof FeaturedInput> = {
name: 'Disabled',
render: () => (
<div className="flex max-w-md flex-col gap-6">
<ControlledFeatured label="Locked" initial="Cannot edit" disabled />
<ControlledFeatured label="Locked password" type="password" initial="secret" disabled />
</div>
),
}
+327
View File
@@ -0,0 +1,327 @@
import {
forwardRef,
useEffect,
useRef,
useState,
type ChangeEvent,
type FocusEvent,
type InputHTMLAttributes,
type KeyboardEvent,
type ReactNode,
type WheelEvent,
} from 'react'
import { Eye, EyeOff, type LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import { omit } from '@/lib/omit'
import { Tooltip } from './Tooltip'
import {
FLOATING_CONTENT_PADDING,
FLOATING_LABEL_SIZES,
ICON_SIZES,
INPUT_HOVER_THEMES,
INPUT_SIZES,
INPUT_THEMES,
INPUT_VARIANTS,
LABEL_COLORS,
LABEL_SIZES,
type InputSize,
type InputTheme,
type InputVariant,
} from './input.tokens'
/**
* Input with an animated floating label.
*
* Ported from the original `Input/FeaturedInput` component.
*
* Upstream fixes kept:
* - a `password` field gets a built-in show/hide toggle (IP-4091: dots with no
* way to check what was typed);
* - `type="number"` blocks `e`/`E`/`+`/`-` and blurs on wheel scroll, so the
* value cannot change under the cursor.
*
* Fixes added here:
* - the floated label needs top padding on the field, or the text renders
* underneath it (see `FLOATING_CONTENT_PADDING`);
* - a `LucideIcon` slot replaces the Remix-icon class name, which needs a font
* this showcase does not load.
*/
export type FeaturedInputProps = Omit<
InputHTMLAttributes<HTMLInputElement>,
'size' | 'value' | 'defaultValue'
> & {
label?: string
value?: string
size?: InputSize
theme?: InputTheme
variant?: InputVariant
name?: string
onChange?: (e: ChangeEvent<HTMLInputElement>) => void
onBlur?: (e: FocusEvent<HTMLInputElement>) => void
onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => void
/** Keep the label floated even when the field is empty and unfocused. */
shrink?: boolean
roundedFull?: boolean
dashedBorder?: boolean
error?: string | { message?: string }
/** Lucide icon rendered inside the field. */
icon?: LucideIcon
iconPosition?: 'left' | 'right'
/** Adds a show/hide toggle when `type` is `password`. */
showPasswordToggle?: boolean
floatinglabelClass?: string
tooltip?: string
tooltipIcon?: LucideIcon
helpText?: string
isLoading?: boolean
/** Rendered inside the field, before the password toggle. */
trailing?: ReactNode
}
export const FeaturedInput = forwardRef<HTMLInputElement, FeaturedInputProps>(
function FeaturedInput(
{
type = 'text',
label = '',
disabled = false,
required = false,
icon: Icon,
iconPosition = 'left',
className = '',
roundedFull = false,
dashedBorder = false,
size = 'md',
variant = 'outlined',
onKeyDown,
onChange,
onBlur,
onFocus,
theme = 'primary',
name,
error,
value,
floatinglabelClass,
shrink = false,
placeholder,
showPasswordToggle = true,
tooltip,
tooltipIcon,
helpText,
isLoading = false,
trailing,
...props
},
ref,
) {
const [isFocused, setIsFocused] = useState(false)
const [isRevealed, setIsRevealed] = useState(false)
const wrapperRef = useRef<HTMLDivElement>(null)
const isPassword = type === 'password'
const hasRevealToggle = isPassword && showPasswordToggle
const resolvedType = isPassword && isRevealed ? 'text' : type
const htmlProps = omit(props as Record<string, unknown>, [
'isDynamic', 'valueKey', 'labelKey', 'endpoint', 'endpointParams', 'isMulti',
'searchable', 'infiniteScroll', 'options', 'tooltip', 'tooltipIcon', 'helpText',
'isLoading', 'showPasswordToggle', 'register', 'validation', 'floatinglabelClass',
])
const errorMessage = typeof error === 'string' ? error : error?.message
const handleFocus = () => setIsFocused(true)
const handleBlur = (e: FocusEvent<HTMLInputElement>) => {
onBlur?.(e)
// An empty field drops back to the resting label position.
if (e.target.value === '' && !shrink) setIsFocused(false)
}
const handleChange = (e: ChangeEvent<HTMLInputElement>) => onChange?.(e)
// A native number input still accepts e/E/+/-, so scientific notation can be
// typed into a field that only takes plain numbers. The caller's handler
// still runs.
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (type === 'number' && ['e', 'E', '+', '-'].includes(e.key)) e.preventDefault()
onKeyDown?.(e)
}
// Prevent a wheel scroll from silently changing a focused number field.
const handleWheel = (e: WheelEvent<HTMLInputElement>) => {
if (type === 'number') e.currentTarget.blur()
}
// A field rendered with a value is filled from the first paint, so the label
// has to start floated — otherwise it sits on top of the value.
useEffect(() => {
const el = name ? document.getElementById(name) : null
if (el && (el as HTMLInputElement).value) setIsFocused(true)
}, [name])
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
setTimeout(() => {
const el = name ? (document.getElementById(name) as HTMLInputElement | null) : null
if (el && !el.value) setIsFocused(false)
}, 300)
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [name])
const hasValue = value !== undefined && value !== null && value !== ''
const shouldFloat = shrink || hasValue || isFocused || Boolean(errorMessage)
const labelColor = errorMessage
? 'text-red-500'
: isFocused || hasValue
? (floatinglabelClass || LABEL_COLORS[theme] || LABEL_COLORS.primary)
: 'text-slate-400'
const isUnderlined = variant === 'underlined'
const variantTokens = INPUT_VARIANTS[variant] ?? INPUT_VARIANTS.outlined
return (
<div ref={wrapperRef} className={cn('relative w-full', isUnderlined && 'mt-4', className)}>
<div
className={cn(
'relative flex items-center transition-all duration-200',
disabled ? 'cursor-not-allowed' : 'cursor-text',
INPUT_SIZES[size] ?? INPUT_SIZES.md,
variantTokens.wrapper,
roundedFull ? 'rounded-full' : 'rounded',
dashedBorder ? 'border-dashed' : 'border',
isUnderlined ? '' : 'border',
(isFocused || shouldFloat) && !errorMessage
? cn(
'border',
INPUT_THEMES[theme] ?? INPUT_THEMES.primary,
'focus:border-primary-500',
)
: 'border border-slate-300',
!disabled && !isFocused && !errorMessage && INPUT_HOVER_THEMES[theme],
errorMessage && 'border-red-500 focus:border-red-500 focus:ring-red-500',
disabled && 'bg-gray-100 opacity-60',
// The floated label chip needs the field's own background behind it.
shouldFloat && !isUnderlined && FLOATING_CONTENT_PADDING[size],
)}
>
{Icon && iconPosition === 'left' && (
<Icon
aria-hidden="true"
className={cn(
'absolute left-3 text-gray-500 pointer-events-none',
ICON_SIZES[size],
shouldFloat && 'top-2 -translate-y-0',
)}
size={16}
/>
)}
<input
id={name}
ref={ref}
name={name}
type={resolvedType}
disabled={disabled}
required={required}
value={value}
placeholder={placeholder}
autoComplete="off"
aria-invalid={Boolean(errorMessage)}
onFocus={(e) => {
handleFocus()
onFocus?.(e)
}}
onBlur={handleBlur}
onChange={handleChange}
onKeyDown={handleKeyDown}
onWheel={handleWheel}
className={cn(
'w-full bg-transparent text-gray-800 placeholder:text-transparent',
'focus:outline-none transition-all duration-200',
'disabled:text-slate-400',
Icon && iconPosition === 'left' ? 'pl-9' : 'pl-3',
hasRevealToggle || Icon || trailing || isLoading ? 'pr-10' : 'pr-3',
)}
{...htmlProps}
/>
<div className="absolute right-3 flex items-center gap-1.5">
{isLoading && <span className="text-[10px] text-gray-400">…</span>}
{trailing}
{hasRevealToggle && (
<button
type="button"
onClick={() => setIsRevealed((v) => !v)}
aria-label={isRevealed ? 'Hide password' : 'Show password'}
className="text-gray-400 hover:text-gray-600"
>
{isRevealed ? <EyeOff size={15} /> : <Eye size={15} />}
</button>
)}
</div>
{Icon && iconPosition === 'right' && (
<Icon aria-hidden="true" size={16} className="absolute right-8 text-gray-500 pointer-events-none" />
)}
{label && (
<label
htmlFor={name}
className={cn(
'absolute transition-all duration-200 pointer-events-none',
isUnderlined ? 'left-0' : 'left-3',
shouldFloat
? cn(
'-top-2.5 z-10',
variantTokens.labelFloating,
FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md,
labelColor,
)
: cn(
'top-1/2 -translate-y-1/2',
LABEL_SIZES[size] ?? LABEL_SIZES.md,
'text-slate-400',
),
)}
>
<span className="flex items-center gap-1.5">
<span className="truncate">
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</span>
{(tooltip || helpText) && (
<span
className="pointer-events-auto inline-flex shrink-0"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.preventDefault()}
>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
</label>
)}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
},
)
export default FeaturedInput
+470
View File
@@ -0,0 +1,470 @@
import {
useEffect,
useMemo,
useRef,
useState,
forwardRef,
type KeyboardEvent,
type FocusEvent as ReactFocusEvent,
type ReactNode,
} from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, ChevronUp, X } from 'lucide-react'
import { cn } from '@/lib/cn'
import { omit } from '@/lib/omit'
import { useClickOutside } from '@/lib/useClickOutside'
import { useDropdownPosition, type DropdownPlacement } from '@/lib/useDropdownPosition'
import { Spinner } from './Spinner'
import { Tooltip } from './Tooltip'
import type { SelectOption } from './NativeSelect'
import {
FLOATING_LABEL_SIZES,
LABEL_SIZES,
SELECT_SIZES,
SELECT_THEME_CLASSES,
SELECT_VARIANTS,
SELECT_WIDTHS,
type SelectSize,
type SelectTheme,
type SelectVariant,
type SelectWidth,
} from './select.tokens'
/**
* Custom select with a portalled dropdown, search, and a floating label.
*
* Ported from the source app's `Select/components/FeaturedSelect`.
*
* Two upstream bugs are corrected here, both flagged in comments at the point of
* change: the themed classes were built as template strings (so Tailwind emitted
* no rules for them), and a "cleared but still matching option" value kept the
* control looking filled.
*/
export type FeaturedSelectProps = Omit<
React.HTMLAttributes<HTMLDivElement>,
'onChange' | 'onSelect' | 'defaultValue' | 'placeholder'
> & {
options?: SelectOption[]
value?: string
onChange?: (value: string) => void
label?: string
name?: string
placeholder?: string
size?: SelectSize
theme?: SelectTheme
variant?: SelectVariant
width?: SelectWidth
disabled?: boolean
required?: boolean
error?: string | { message?: string }
isLoading?: boolean
isClearable?: boolean
searchable?: boolean
onSearchChange?: (term: string) => void
/** Scrolls the selected option to the middle of the open list. */
scrollToSelected?: boolean
placement?: DropdownPlacement
/** Stored label for a value whose option has not loaded yet. */
initialSearchTerm?: string
/** Floats the label even when the control is empty and unfocused. */
shrink?: boolean
floatinglabelClass?: string
tooltip?: string
tooltipIcon?: React.ComponentProps<typeof Tooltip>['icon']
helpText?: string
actionButton?: { label: string; onClick: () => void; icon?: ReactNode }
renderOption?: (opt: SelectOption) => ReactNode
onBlur?: (e: ReactFocusEvent<HTMLDivElement>) => void
}
export const FeaturedSelect = forwardRef<HTMLDivElement, FeaturedSelectProps>(
function FeaturedSelect(
{
options = [],
value = '',
onChange,
label,
name,
placeholder = 'Select an option',
size = 'md',
theme = 'primary',
variant = 'outlined',
width = 'full',
disabled = false,
required = false,
error,
isLoading = false,
isClearable = true,
searchable = true,
onSearchChange,
scrollToSelected = false,
placement = 'auto',
initialSearchTerm = '',
shrink = false,
floatinglabelClass = '',
tooltip,
tooltipIcon,
helpText,
actionButton,
renderOption,
className = '',
onBlur,
...props
},
ref,
) {
const htmlProps = omit(props as Record<string, unknown>, [
'shrink', 'hasMore', 'hasMoreKey', 'labelKey', 'valueKey', 'isMulti',
'staticOptions', 'endpoint', 'endpointParams', 'infiniteScroll',
'initialSearch', 'initialSearchTerm', 'initialQuery', 'searchBy',
'control', 'onMenuScroll', 'debounceTime', 'helpText', 'tooltip', 'tooltipIcon',
'isClearable', 'renderOption', 'onBlur',
])
const [isOpen, setIsOpen] = useState(false)
const [isFocused, setIsFocused] = useState(false)
const [searchTerm, setSearchTerm] = useState(initialSearchTerm)
// `initialSearchTerm` is the stored label for the ONE value the field was
// seeded with, so it stops being true the moment the user picks something
// else. Tracking it beats comparing against `value`, because the seeded value
// and its label arrive over several renders.
const [hasUserSelected, setHasUserSelected] = useState(false)
const containerRef = useRef<HTMLDivElement>(null)
const dropdownRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (initialSearchTerm) setSearchTerm(initialSearchTerm)
// A new seed means a new record in the same mounted field (the next row
// opened in a reused modal): the earlier pick no longer describes it.
setHasUserSelected(false)
}, [initialSearchTerm])
useEffect(() => {
const node = containerRef.current
if (typeof ref === 'function') ref(node)
else if (ref) ref.current = node
}, [ref])
// React's onBlur is focusout and bubbles. Opening the dropdown moves focus to
// its autoFocus search input, which would otherwise read as a blur to the
// consumer — validating a field the user has only just clicked into. The
// dropdown is portalled, so it is not a descendant of containerRef: check
// both roots.
const handleContainerBlur = (event: ReactFocusEvent<HTMLDivElement>) => {
if (!onBlur) return
const next = event.relatedTarget
if (
next instanceof Node &&
(containerRef.current?.contains(next) || dropdownRef.current?.contains(next))
) {
return
}
onBlur(event)
}
const safeOptions = Array.isArray(options) ? options : []
const selectedOption = safeOptions.find((opt) => opt.value === value)
const hasSelectedValue = value !== undefined && value !== null && value !== ''
// Prefer the resolved option; fall back to the caller-supplied label for a
// value whose option has not been fetched yet.
const displayLabel =
selectedOption?.label || (hasSelectedValue && !hasUserSelected ? initialSearchTerm : '') || ''
const filteredOptions = useMemo(() => {
// A server-side search hands us the filtered list; don't filter again.
if (onSearchChange) return safeOptions
return searchable && searchTerm
? safeOptions.filter((opt) => opt.label.toLowerCase().includes(searchTerm.toLowerCase()))
: safeOptions
}, [safeOptions, searchable, searchTerm, onSearchChange])
// A long list opens at the top, leaving the current value scrolled out of
// sight. Centred rather than 'nearest', which would pin the option to the
// bottom edge with no surrounding years visible.
useEffect(() => {
if (!isOpen || !scrollToSelected) return
const frame = requestAnimationFrame(() => {
const list = dropdownRef.current
const selected = list?.querySelector('[data-selected="true"]')
selected?.scrollIntoView?.({ block: 'center' })
})
return () => cancelAnimationFrame(frame)
}, [isOpen, scrollToSelected])
useClickOutside(
[containerRef, dropdownRef],
() => {
setIsOpen(false)
setIsFocused(false)
},
isOpen,
)
const { dropdownPosition, calculateInitialPosition } = useDropdownPosition(
isOpen,
containerRef,
{ placement },
)
const handleToggle = () => {
if (disabled) return
if (!isOpen) calculateInitialPosition()
setIsOpen((open) => !open)
}
const handleSelect = (val: string) => {
onChange?.(val)
setHasUserSelected(true)
setIsOpen(false)
setIsFocused(false)
}
// Derived from `value` alone. The source OR'd in the matched option, so an
// option whose own value is '' (an "All departments" filter) kept the control
// looking filled after the value was cleared — the field showed a label and a
// clear button while the form held '', so a required field read as answered.
const hasValue = hasSelectedValue
// `displayLabel`, not `hasValue`: the all-pass option resolves to a label and
// renders as text, so floating on hasValue alone left the label sitting on
// top of that text. `required` floats too — a mandatory field's label carries
// the asterisk and help icon, which read as content inside the box, and an
// unfloated one leaves a column of required fields misaligned (Taiga #4140).
const isFloating =
shrink || hasValue || Boolean(displayLabel) || isFocused || isOpen || Boolean(error) || required
const isUnderlined = variant === 'underlined'
const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary
const errorMessage = typeof error === 'string' ? error : error?.message
// The floated label is a chip sitting on the border, which only reads against
// a boxed outline. On the underlined variant there is no side border to punch
// through, so lift it clear and drop the chip styling.
const labelClass = isFloating
? cn(
isUnderlined ? '-top-2.5 px-0 bg-transparent z-10' : 'top-[-0.6rem] px-1 bg-white z-10',
FLOATING_LABEL_SIZES[size] ?? FLOATING_LABEL_SIZES.md,
errorMessage ? 'text-red-500' : themeClasses.label,
floatinglabelClass,
)
: cn(
'top-1/2 -translate-y-1/2',
LABEL_SIZES[size] ?? LABEL_SIZES.md,
'text-slate-400 pointer-events-none',
)
const dropdownContent = (
<div
ref={dropdownRef}
style={{
position: 'fixed',
top: dropdownPosition.top,
bottom: dropdownPosition.bottom,
left: dropdownPosition.left,
width: dropdownPosition.width,
maxHeight: dropdownPosition.maxHeight,
zIndex: 10000,
}}
className="bg-white border border-gray-200 rounded-lg shadow-xl overflow-auto"
role="listbox"
aria-expanded={isOpen}
>
{searchable && (
<div className="sticky top-0 z-10 p-2 bg-white border-b border-gray-200">
<input
autoFocus
type="text"
className={cn(
'w-full px-2 py-1 text-sm border rounded focus:outline-none',
themeClasses.searchFocus,
)}
placeholder="Search..."
value={searchTerm}
onChange={(e) => {
const next = e.target.value
setSearchTerm(next)
onSearchChange?.(next)
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
{filteredOptions.length > 0 ? (
filteredOptions.map((opt) => {
const isSelected = opt.value === value
return (
<div
key={opt.value}
role="option"
aria-selected={isSelected}
data-selected={scrollToSelected && isSelected ? 'true' : undefined}
className={cn(
'px-3 py-2 text-sm transition-colors',
opt.disabled
? 'text-slate-300 cursor-not-allowed bg-slate-50/30'
: 'cursor-pointer',
isSelected && !opt.disabled
? themeClasses.selected
: !opt.disabled && 'text-gray-700 hover:bg-gray-50',
)}
onClick={() => !opt.disabled && handleSelect(opt.value)}
>
{renderOption ? renderOption(opt) : opt.label}
</div>
)
})
) : (
!isLoading && (
<div className="px-3 py-4 text-sm text-center text-gray-500">No options found</div>
)
)}
{isLoading && filteredOptions.length > 0 && (
<div className="px-3 py-3 text-center border-t border-gray-200 bg-gray-50/50 flex items-center justify-center gap-2">
<Spinner size="xs" />
<span className="text-[11px] text-gray-500 font-medium tracking-wide">
LOADING MORE...
</span>
</div>
)}
{actionButton && (
<div className="p-2">
<button
type="button"
onClick={(e) => {
e.stopPropagation()
actionButton.onClick()
setIsOpen(false)
}}
className="w-full rounded bg-primary-600 px-2 py-1.5 text-xs font-semibold text-white"
>
{actionButton.label}
</button>
</div>
)}
</div>
)
return (
<div
ref={containerRef}
className={cn(
'relative outline-none',
// Matches the underlined variant's need for room for the floated label.
isUnderlined && 'mt-4',
SELECT_WIDTHS[width] ?? SELECT_WIDTHS.full,
className,
)}
tabIndex={disabled ? -1 : 0}
onKeyDown={(e: KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter') handleToggle()
if (e.key === 'Escape') setIsOpen(false)
}}
onBlur={handleContainerBlur}
{...htmlProps}
>
<div
onClick={handleToggle}
className={cn(
'relative flex items-center justify-between transition-all duration-200',
disabled ? 'cursor-not-allowed' : 'cursor-pointer',
SELECT_SIZES[size] ?? SELECT_SIZES.md,
SELECT_VARIANTS[variant] ?? SELECT_VARIANTS.outlined,
'bg-transparent',
isUnderlined ? '' : 'rounded',
(isFocused || isOpen)
? cn('border', isUnderlined ? themeClasses.focus.split(' ')[0] : themeClasses.focus,
isUnderlined ? '' : 'ring-1')
: 'border border-slate-300',
!disabled && !isOpen && !isFocused && themeClasses.hover,
errorMessage && 'border-red-500 ring-red-500',
disabled && 'bg-gray-100 cursor-not-allowed opacity-60',
)}
>
{/* Options load asynchronously (paginated + server-searched), so a saved
value is often absent from `options` on first paint.
`initialSearchTerm` carries the stored label for exactly that case —
without it the field renders blank even though a value is set. */}
<span className={cn('block truncate px-0.5', !displayLabel && 'text-transparent')}>
{displayLabel || placeholder}
</span>
<div className="flex items-center gap-2">
{isLoading && <Spinner size="xs" />}
{isClearable && hasValue && !disabled && (
<X
className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-pointer z-20"
onClick={(e) => {
e.stopPropagation()
// onSearchChange first, so a consumer that sets its own term
// inside onChange still wins.
onSearchChange?.('')
onChange?.('')
setSearchTerm('')
setHasUserSelected(true)
}}
/>
)}
{isOpen ? (
<ChevronUp className="h-4 w-4 text-gray-500" />
) : (
<ChevronDown className="h-4 w-4 text-gray-500" />
)}
</div>
{label && (
<label
className={cn(
'absolute transition-all duration-200',
// Only `left` is set, so the label shrink-wraps to the field and a
// long one wraps to a second line — floated, that line carries the
// label's own opaque background over the selected value. Keep it on
// one line and ellipsize.
'max-w-[calc(100%-1.5rem)] truncate',
isUnderlined ? 'left-0' : 'left-2',
labelClass,
)}
>
<span className="flex items-center gap-1.5">
<span className="truncate">
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</span>
{(tooltip || helpText) && (
<span
className="pointer-events-auto inline-flex shrink-0"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.preventDefault()}
>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
</label>
)}
</div>
{isOpen && !disabled && createPortal(dropdownContent, document.body)}
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
},
)
export default FeaturedSelect
+143
View File
@@ -0,0 +1,143 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Input } from './Input'
const meta = {
title: 'Forms/Input',
component: Input,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Plain input with a label above. For a floating label, a built-in password toggle, and a Lucide icon slot, see the **FeaturedInput** story group — both are exported from here.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
type: { control: 'select', options: ['text', 'email', 'password', 'number', 'tel', 'url', 'date'] },
iconPosition: { control: 'radio', options: ['left', 'right'] },
roundedFull: { control: 'boolean' },
dashedBorder: { control: 'boolean' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
label: { control: 'text' },
placeholder: { control: 'text' },
error: { control: 'text' },
},
args: {
label: 'Legal entity name',
placeholder: 'Acme Corporation',
type: 'text',
size: 'md',
theme: 'primary',
iconPosition: 'left',
roundedFull: false,
dashedBorder: false,
required: false,
disabled: false,
error: '',
},
} satisfies Meta<typeof Input>
export default meta
type Story = StoryObj<typeof meta>
function ControlledInput({
initial = '',
...args
}: React.ComponentProps<typeof Input> & { initial?: string }) {
const [value, setValue] = useState(initial)
return <Input {...args} value={value} onChange={(e) => setValue(e.target.value)} />
}
export const Playground: Story = {
render: (args) => (
<div className="max-w-md">
<ControlledInput {...args} />
</div>
),
}
export const Types: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
<Input label="Full name" placeholder="Jane Doe" />
<Input label="Email" type="email" placeholder="[email protected]" />
<Input label="Phone" type="tel" placeholder="+91 98450 00000" />
<Input label="Annual CTC" type="number" placeholder="1200000" />
<Input label="Website" type="url" placeholder="https://example.com" />
<Input label="Joining date" type="date" />
</div>
),
}
export const Sizes: Story = {
render: () => (
<div className="flex max-w-md flex-col gap-5">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledInput key={size} size={size} label={`Size ${size}`} placeholder="Enter a value" />
))}
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info'] as const).map((theme) => (
<ControlledInput key={theme} theme={theme} label={theme} placeholder="Focus me" />
))}
</div>
),
}
export const WithError: Story = {
render: () => (
<div className="max-w-md">
<Input
label="PAN number"
placeholder="ABCDE1234F"
error="Enter a valid PAN number."
/>
</div>
),
}
export const Required: Story = {
render: () => (
<div className="max-w-md">
<Input label="Entity name" required placeholder="Required field" />
</div>
),
}
export const Disabled: Story = {
render: () => (
<div className="max-w-md">
<Input label="Entity ID" value="ENT-000142" disabled onChange={() => {}} />
</div>
),
}
export const BorderStyles: Story = {
render: () => (
<div className="grid max-w-xl gap-5 sm:grid-cols-3">
<Input label="Default" placeholder="Solid" />
<Input label="Dashed" placeholder="Dashed" dashedBorder />
<Input label="Pill" placeholder="Rounded" roundedFull />
</div>
),
}
/** Requires the Remix Icon font; the `FeaturedInput` group below uses Lucide instead. */
export const WithIconClass: Story = {
args: { icon: 'ri-mail-line', placeholder: 'Email' },
render: (args) => (
<div className="max-w-md">
<Input {...args} label="Email" />
</div>
),
}
+145
View File
@@ -0,0 +1,145 @@
import { forwardRef, type InputHTMLAttributes, type ReactNode } from 'react'
import { cn } from '@/lib/cn'
import { omit } from '@/lib/omit'
import {
ICON_SIZES,
INPUT_SIZES,
INPUT_THEMES,
LABEL_SIZES,
type InputSize,
type InputTheme,
} from './input.tokens'
/**
* Text input with a label above, optional icon, and error state.
*
* Ported from the original `Input` component.
*
* The source sets `opacity-90!` on the field, which dims the user's own typed
* text; that is dropped here. `register` / `validation` (React Hook Form) are
* not ported either — pass standard DOM props.
*
* `icon` is a class-name string (the source app uses Remix Icon, e.g.
* `"ri-mail-line"`). Loading that font is a project-level choice, so the
* showcase's stories use `FeaturedInput`'s Lucide slot instead where an icon is
* really needed.
*/
export type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & {
label?: string
size?: InputSize
theme?: InputTheme
/** Icon class name, e.g. `"ri-mail-line"`. Needs the icon font loaded. */
icon?: string
iconPosition?: 'left' | 'right'
roundedFull?: boolean
dashedBorder?: boolean
error?: string | { message?: string }
/** Rendered after the input, inside the field row. */
trailing?: ReactNode
}
export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
{
type = 'text',
label = '',
placeholder = '',
disabled = false,
required = false,
icon,
iconPosition = 'left',
roundedFull = false,
dashedBorder = false,
size = 'md',
theme = 'primary',
className = '',
name,
error,
trailing,
...props
},
ref,
) {
const htmlProps = omit(props as Record<string, unknown>, ['hasMore', 'control', 'allValues', 'shrink'])
const errorMessage = typeof error === 'string' ? error : error?.message
return (
<div className="flex flex-col w-full">
{label && (
<label
htmlFor={name}
className={cn('inline-block text-left w-full text-gray-800', LABEL_SIZES[size] ?? LABEL_SIZES.md)}
>
{label} {required && <span className="text-red-500">*</span>}
</label>
)}
<div className="relative flex items-center">
{icon && iconPosition === 'left' && (
<i
aria-hidden="true"
className={cn(
'absolute left-3 top-1/2 text-gray-900 transform -translate-y-1/2 pointer-events-none',
ICON_SIZES[size],
icon,
)}
/>
)}
<input
id={name}
ref={ref}
type={type}
name={name}
autoComplete="off"
required={required}
disabled={disabled}
placeholder={placeholder}
aria-invalid={Boolean(errorMessage)}
className={cn(
'w-full bg-white text-gray-800 placeholder:text-slate-400 placeholder:font-medium',
'focus:outline-none transition duration-150',
'disabled:bg-gray-200 disabled:border-slate-300 disabled:text-slate-400 disabled:cursor-not-allowed',
// Indent to clear a leading icon.
icon ? (iconPosition === 'left' ? 'pl-9' : 'pr-10') : 'pl-3',
roundedFull ? 'rounded-full' : 'rounded',
dashedBorder ? 'border-dashed' : 'border',
'border',
INPUT_SIZES[size] ?? INPUT_SIZES.md,
// Error wins over the theme's focus colours.
errorMessage
? 'border-red-500 focus:border-red-500 focus:ring-red-500'
: cn('border-slate-300', INPUT_THEMES[theme] ?? INPUT_THEMES.primary),
className,
)}
{...htmlProps}
/>
{icon && iconPosition === 'right' && (
<i
aria-hidden="true"
className={cn(
'absolute right-3 top-1/2 text-gray-900 transform -translate-y-1/2 pointer-events-none',
ICON_SIZES[size],
icon,
)}
/>
)}
{trailing && (
<span className="absolute right-3 top-1/2 -translate-y-1/2 flex items-center">
{trailing}
</span>
)}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-start text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
})
export default Input
+192
View File
@@ -0,0 +1,192 @@
import { forwardRef, useState, type ChangeEvent, type FocusEvent } from 'react'
import { ChevronDown, X } from 'lucide-react'
import { cn } from '@/lib/cn'
import { omit } from '@/lib/omit'
import { Spinner } from './Spinner'
import {
LABEL_SIZES,
SELECT_SIZES,
SELECT_THEME_CLASSES,
SELECT_VARIANTS,
SELECT_WIDTHS,
type SelectSize,
type SelectTheme,
type SelectVariant,
type SelectWidth,
} from './select.tokens'
/**
* Select over a native `<select>`.
*
* Ported from the source app's `Select/components/NativeSelect`, and used by
* `Select` when `featured` is false.
*
* The source writes its themed border as `` `border-${themeColor}-500` ``, which
* Tailwind's scanner cannot see — so the focused state had no styling. Here the
* classes come from a static map, and `border` / `ring` colour utilities are set
* per element so they survive Tailwind's tree.
*/
export type SelectOption = { label: string; value: string; disabled?: boolean }
export type NativeSelectProps = Omit<
React.SelectHTMLAttributes<HTMLSelectElement>,
'size' | 'value' | 'onChange'
> & {
options?: SelectOption[]
value?: string
onChange?: (value: string) => void
label?: string
name?: string
placeholder?: string
size?: SelectSize
theme?: SelectTheme
variant?: SelectVariant
width?: SelectWidth
disabled?: boolean
required?: boolean
error?: string | { message?: string }
isLoading?: boolean
isClearable?: boolean
}
export const NativeSelect = forwardRef<HTMLSelectElement, NativeSelectProps>(
function NativeSelect(
{
options = [],
value = '',
onChange,
label,
name,
placeholder = 'Select an option',
size = 'md',
theme = 'primary',
variant = 'outlined',
width = 'full',
disabled = false,
required = false,
error,
isLoading = false,
isClearable = true,
className = '',
onFocus,
onBlur,
...props
},
ref,
) {
const [isFocused, setIsFocused] = useState(false)
// Strip props that must not reach the DOM node.
const htmlProps = omit(props as Record<string, unknown>, [
'shrink', 'helpText', 'helperText', 'tooltip', 'tooltipIcon', 'control', 'allValues',
'isDynamic', 'valueKey', 'labelKey', 'endpoint', 'endpointParams',
'isMulti', 'searchable', 'infiniteScroll', 'hasMore', 'hasMoreKey',
'onMenuScroll', 'onSearchChange', 'initialSearch', 'initialSearchTerm',
'initialQuery', 'debounceTime', 'actionButton', 'isEditMode', 'isClearable',
'themeColor', 'sizeClass', 'variantClass', 'widthClass', 'floatinglabelClass',
'renderOption', 'placement', 'scrollToSelected',
])
const themeClasses = SELECT_THEME_CLASSES[theme] ?? SELECT_THEME_CLASSES.primary
const errorMessage = typeof error === 'string' ? error : error?.message
const handleChange = (e: ChangeEvent<HTMLSelectElement>) => onChange?.(e.target.value)
const handleClear = (e: React.MouseEvent) => {
e.stopPropagation()
e.preventDefault()
onChange?.('')
}
// Deliberately explicit rather than `isClearable && value && ...`: a numeric 0
// is a legitimate selection, and `&&` on a falsy number yields the number
// itself, which React renders as stray text in the icon slot (IP-3617).
const showClear =
isClearable && !disabled && value !== '' && value !== null && value !== undefined
return (
<div className={cn('relative w-full', SELECT_WIDTHS[width] ?? SELECT_WIDTHS.full, className)}>
{label && (
<label
htmlFor={name}
className={cn('block text-gray-800 font-medium mb-1', LABEL_SIZES[size] ?? LABEL_SIZES.md)}
>
{label}
{required && <span className="text-red-500 ml-1">*</span>}
</label>
)}
<div className="relative">
<select
id={name}
name={name}
value={value}
disabled={disabled}
required={required}
aria-invalid={Boolean(errorMessage)}
onChange={handleChange}
onFocus={(e: FocusEvent<HTMLSelectElement>) => {
setIsFocused(true)
onFocus?.(e)
}}
onBlur={(e: FocusEvent<HTMLSelectElement>) => {
setIsFocused(false)
onBlur?.(e)
}}
ref={ref}
className={cn(
'appearance-none block w-full pl-3 pr-10 bg-white text-gray-700 font-medium',
'focus:outline-none transition duration-150 ease-in-out',
SELECT_SIZES[size] ?? SELECT_SIZES.md,
SELECT_VARIANTS[variant] ?? SELECT_VARIANTS.outlined,
// Border/ring colour utilities are written per element: a `border-red-500`
// class would otherwise be stripped by Tailwind's tree as redundant.
isFocused
? ['border', themeClasses.focus]
: 'border border-slate-300',
isFocused && 'ring-1',
disabled && 'bg-gray-200 cursor-not-allowed opacity-70',
errorMessage && 'border-red-500 ring-red-500 focus:border-red-500 focus:ring-red-500',
variant !== 'underlined' && 'rounded',
)}
{...htmlProps}
>
<option value="" disabled hidden>
{placeholder}
</option>
{options.map((opt) => (
<option key={opt.value} value={opt.value} disabled={opt.disabled}>
{opt.label}
</option>
))}
</select>
<div className="absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
{showClear && (
<X
className="h-4 w-4 text-gray-400 hover:text-gray-600 cursor-pointer z-20 mr-1"
onClick={handleClear}
/>
)}
<div className="pointer-events-none flex items-center">
{isLoading ? (
<Spinner size="xs" />
) : (
<ChevronDown className={cn('h-4 w-4', !isFocused && 'opacity-50')} />
)}
</div>
</div>
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
},
)
export default NativeSelect
+143
View File
@@ -0,0 +1,143 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Radio } from './Radio'
const meta = {
title: 'Forms/Radio',
component: Radio,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Radio group. The native input is visually hidden and the ring + dot are drawn in CSS, so the selected state follows the palette. A real radio input is still used underneath, so keyboard and form semantics are intact.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: {
control: 'select',
options: ['blue', 'green', 'red', 'yellow', 'teal', 'purple', 'amber', 'gray'],
},
label: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
value: { control: 'text' },
helpText: { control: 'text' },
error: { control: 'text' },
},
args: {
name: 'payroll_frequency',
options: ['Monthly', 'Fortnightly', 'Weekly'],
size: 'md',
theme: 'blue',
label: 'Payroll frequency',
required: false,
disabled: false,
value: 'Monthly',
helpText: '',
error: '',
},
} satisfies Meta<typeof Radio>
export default meta
type Story = StoryObj<typeof meta>
/**
* Wraps Radio with local state so the group is interactive.
*
* `initial` selects the starting option. The themes grid needs one selected to
* show the ring and dot in each colour, so it passes a value rather than ''.
*/
function ControlledRadio({
initial = '',
...args
}: React.ComponentProps<typeof Radio> & { initial?: string }) {
const [value, setValue] = useState(args.value ?? initial)
return <Radio {...args} value={value} onChange={setValue} />
}
export const Playground: Story = {
render: (args) => <ControlledRadio {...args} />,
}
/** No `value` or `onChange` — the component tracks its own selection. */
export const Uncontrolled: Story = {
render: (args) => <Radio {...args} />,
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-col gap-6">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledRadio key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="grid gap-5 sm:grid-cols-2">
{(['blue', 'green', 'red', 'yellow', 'teal', 'purple', 'amber', 'gray'] as const).map((theme) => (
<ControlledRadio
key={theme}
name={`theme-${theme}`}
theme={theme}
options={['Option A', 'Option B']}
label={theme}
initial="Option A"
/>
))}
</div>
),
}
/** Options may carry their own disabled state. */
export const DisabledOptions: Story = {
render: () => (
<ControlledRadio
name="leave_type"
label="Leave type"
options={[
{ label: 'Casual leave', value: 'casual' },
{ label: 'Sick leave', value: 'sick' },
{ label: 'Parental leave (unavailable)', value: 'parental', disabled: true },
]}
/>
),
}
export const RequiredWithError: Story = {
render: () => (
<ControlledRadio
name="employment_type"
label="Employment type"
required
options={['Full-time', 'Part-time', 'Contract']}
error="Select an employment type to continue."
/>
),
}
export const WithTooltip: Story = {
render: () => (
<ControlledRadio
name="pay_cycle"
label="Pay cycle"
options={['Monthly', 'Fortnightly', 'Weekly']}
helpText="Changing this affects every future payroll run in the entity."
/>
),
}
export const Horizontal: Story = {
render: () => (
<ControlledRadio
name="invoice_type"
options={['Standard', 'Proforma', 'Credit note']}
/>
),
}
+155
View File
@@ -0,0 +1,155 @@
import { useEffect, useState, type HTMLAttributes, type ReactNode } from 'react'
import type { LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import { Tooltip } from './Tooltip'
import { RADIO_COLORS, RADIO_SIZES, type RadioSize, type RadioTheme } from './radio.tokens'
/**
* Radio group with a generated ring + dot indicator.
*
* Ported from the original `Radio` component.
*
* The native input is visually hidden; the ring and dot are drawn in CSS, which
* is what lets the selected state follow palette tokens. A real `radio` input is
* still used underneath, so keyboard and form semantics are intact.
*
* `register` / `validation` (React Hook Form) are intentionally not ported —
* pass `value` and `onChange` directly.
*/
export type RadioOption = string | { label: ReactNode; value: string; disabled?: boolean }
export type RadioProps = Omit<HTMLAttributes<HTMLDivElement>, 'onChange' | 'defaultValue'> & {
name?: string
options?: RadioOption[]
size?: RadioSize
theme?: RadioTheme
/** Disables every option in the group. */
disabled?: boolean
label?: ReactNode
/** Appends the mandatory asterisk to the group label. */
required?: boolean
/** Controlled selection. */
value?: string
onChange?: (value: string) => void
error?: string | { message?: string }
/** Icon class name shown in place of the dot when selected, e.g. `"ri-check"`. */
icon?: string
tooltip?: string
tooltipIcon?: LucideIcon
helpText?: string
}
export const Radio = function Radio({
name = '',
options = [],
size = 'md',
theme = 'blue',
disabled = false,
icon,
error,
label,
required = false,
helpText,
tooltip,
tooltipIcon,
value,
onChange,
className = '',
...props
}: RadioProps) {
const [localValue, setLocalValue] = useState(value ?? '')
useEffect(() => {
if (value !== undefined) setLocalValue(value)
}, [value])
const sizeData = RADIO_SIZES[size] ?? RADIO_SIZES.md
const themeData = RADIO_COLORS[theme] ?? RADIO_COLORS.blue
const handleChange = (next: string) => {
setLocalValue(next)
onChange?.(next)
}
const errorMessage =
error == null ? null : typeof error === 'string' ? error : (error.message ?? 'This field is required')
return (
<div className={cn('flex flex-col gap-2', className)} role="radiogroup" {...props}>
{label && (
<div className="flex items-center gap-1.5">
<span className={cn('font-medium', sizeData.label)}>
{label} {required && <span className="text-red-500">*</span>}
</span>
{(tooltip || helpText) && (
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
)}
</div>
)}
<div className="flex flex-wrap gap-4">
{options.map((opt, index) => {
const option = typeof opt === 'string' ? { label: opt, value: opt } : opt
const isChecked = localValue === option.value
const isDisabled = disabled || Boolean(option.disabled)
return (
<label
key={option.value || index}
htmlFor={`${name}-${option.value}`}
className={cn(
'inline-flex items-center space-x-2 mr-4',
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
)}
>
<input
type="radio"
id={`${name}-${option.value}`}
name={name}
value={option.value}
className="peer sr-only"
checked={isChecked}
onChange={() => handleChange(option.value)}
disabled={isDisabled}
/>
{/* Decorative ring + dot; the input above carries the semantics. */}
<span
aria-hidden="true"
className={cn(
'relative flex items-center justify-center rounded-full border transition-all duration-200',
sizeData.container,
isChecked ? cn(themeData.border, 'border-2') : 'border-gray-300',
!isDisabled && 'hover:border-gray-400',
)}
>
{isChecked &&
(icon ? (
<i className={cn(icon, themeData.text)} />
) : (
<span className={cn('absolute rounded-full', sizeData.dot, themeData.bg)} />
))}
</span>
<span className={cn('text-gray-700', sizeData.label)}>{option.label}</span>
</label>
)
})}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
}
export default Radio
+240
View File
@@ -0,0 +1,240 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Select, type SelectOption } from './Select'
const COUNTRIES: SelectOption[] = [
{ label: 'India', value: 'in' },
{ label: 'United Kingdom', value: 'gb' },
{ label: 'United States', value: 'us' },
{ label: 'Germany', value: 'de' },
{ label: 'Singapore', value: 'sg' },
{ label: 'United Arab Emirates', value: 'ae' },
{ label: 'Australia', value: 'au' },
{ label: 'Canada', value: 'ca' },
]
const DEPARTMENTS: SelectOption[] = [
{ label: 'Engineering', value: 'eng' },
{ label: 'Finance', value: 'fin' },
{ label: 'People & Culture', value: 'hr' },
{ label: 'Operations', value: 'ops' },
{ label: 'Sales', value: 'sales' },
]
const meta = {
title: 'Forms/Select',
component: Select,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Dispatches to a native `<select>` by default, or a searchable portalled dropdown with a floating label when `featured` is set. The source built its themed classes as template strings, which Tailwind cannot scan; here they come from a static map so every theme actually renders.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: { control: 'select', options: ['primary', 'secondary', 'success', 'error', 'warning', 'info'] },
variant: { control: 'select', options: ['outlined', 'filled', 'standard', 'underlined'] },
width: { control: 'select', options: ['full', 'half', 'small', 'xs', 'large'] },
featured: { control: 'boolean' },
label: { control: 'text' },
placeholder: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
isLoading: { control: 'boolean' },
isClearable: { control: 'boolean' },
searchable: { control: 'boolean' },
value: { control: 'text' },
},
args: {
options: COUNTRIES,
value: '',
label: 'Country of registration',
placeholder: 'Select a country',
size: 'md',
theme: 'primary',
variant: 'outlined',
width: 'full',
featured: false,
required: false,
disabled: false,
isLoading: false,
isClearable: true,
searchable: true,
},
} satisfies Meta<typeof Select>
export default meta
type Story = StoryObj<typeof meta>
/**
* Select is a controlled component: it reports a value, it does not hold one.
*/
function ControlledSelect({
initial = '',
...args
}: React.ComponentProps<typeof Select> & { initial?: string }) {
const [value, setValue] = useState(initial)
return (
<div className="max-w-md">
<Select {...args} value={value} onChange={setValue} />
<p className="mt-2 text-xs text-gray-500">value = {JSON.stringify(value)}</p>
</div>
)
}
export const Playground: Story = {
render: (args) => <ControlledSelect {...args} />,
}
export const Featured: Story = {
args: { featured: true },
render: (args) => <ControlledSelect {...args} />,
}
export const FeaturedWithValue: Story = {
args: { featured: true },
render: (args) => <ControlledSelect {...args} initial="in" />,
}
export const FeaturedRequired: Story = {
args: { featured: true, required: true },
render: (args) => <ControlledSelect {...args} />,
}
export const Sizes: Story = {
render: () => (
<div className="flex max-w-md flex-col gap-5">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledSelect key={size} size={size} label={`Size ${size}`} options={DEPARTMENTS} />
))}
</div>
),
}
/**
* The themed states are the point of this story: the source could not render
* them because its classes were built dynamically.
*/
export const Themes: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info', 'error'] as const).map((theme) => (
<ControlledSelect
key={theme}
featured
theme={theme}
label={theme}
options={DEPARTMENTS}
initial="eng"
/>
))}
</div>
),
}
export const Variants: Story = {
render: () => (
<div className="grid max-w-2xl gap-5 sm:grid-cols-2">
{(['outlined', 'filled', 'standard', 'underlined'] as const).map((variant) => (
<ControlledSelect
key={variant}
featured
variant={variant}
label={variant}
options={DEPARTMENTS}
initial="fin"
/>
))}
</div>
),
}
export const Widths: Story = {
render: () => (
<div className="flex flex-wrap items-end gap-4">
{(['xs', 'small', 'large', 'half'] as const).map((width) => (
<ControlledSelect key={width} width={width} label={width} options={DEPARTMENTS} />
))}
</div>
),
}
export const Loading: Story = {
args: { isLoading: true },
render: (args) => <ControlledSelect {...args} />,
}
export const Disabled: Story = {
args: { disabled: true, value: 'in' },
render: () => (
<div className="max-w-md">
<Select label="Country" options={COUNTRIES} value="in" disabled onChange={() => {}} />
</div>
),
}
export const WithError: Story = {
args: { error: 'Select the country where the entity is registered.' },
render: (args) => <ControlledSelect {...args} />,
}
/** An empty filter list, where the "all" option has an empty value. */
export const AllOptionsFilter: Story = {
render: () => (
<ControlledSelect
featured
searchable
label="Department filter"
options={[{ label: 'All departments', value: '' }, ...DEPARTMENTS]}
/>
),
}
export const WithActionButton: Story = {
render: () => (
<div className="max-w-md">
<Select
featured
label="Department"
options={DEPARTMENTS}
actionButton={{ label: '+ Create department', onClick: () => {} }}
/>
</div>
),
}
/** Renders each option with a custom node. */
export const CustomOptionRenderer: Story = {
render: () => (
<ControlledSelect
featured
label="Department"
options={DEPARTMENTS}
renderOption={(opt) => (
<span className="flex items-center gap-2">
<span className="h-2 w-2 rounded-full bg-primary-500" />
{opt.label}
</span>
)}
/>
),
}
export const WithTooltip: Story = {
render: () => (
<ControlledSelect
featured
label="Country of registration"
options={COUNTRIES}
helpText="Determines the statutory rules applied to payroll in this entity."
/>
),
}
export const NonSearchable: Story = {
args: { featured: true, searchable: false },
render: (args) => <ControlledSelect {...args} />,
}
+75
View File
@@ -0,0 +1,75 @@
import { forwardRef } from 'react'
import { cn } from '@/lib/cn'
import { NativeSelect, type SelectOption } from './NativeSelect'
import { FeaturedSelect } from './FeaturedSelect'
import type { DropdownPlacement } from '@/lib/useDropdownPosition'
import type {
SelectSize,
SelectTheme,
SelectVariant,
SelectWidth,
} from './select.tokens'
/**
* Select dispatcher: a native `<select>` by default, or the custom searchable
* dropdown when `featured` is set.
*
* Ported from the original `Select` component.
*
* Form-library props (`register`, `validation`) are not ported — pass `value`
* and `onChange` directly.
*/
export type SelectProps = {
options?: SelectOption[]
value?: string
onChange?: (value: string) => void
/** Renders the custom dropdown with a floating label instead of a native select. */
featured?: boolean
label?: string
name?: string
placeholder?: string
size?: SelectSize
theme?: SelectTheme
variant?: SelectVariant
width?: SelectWidth
disabled?: boolean
required?: boolean
error?: string | { message?: string }
isLoading?: boolean
isClearable?: boolean
className?: string
floatinglabelClass?: string
shrink?: boolean
searchable?: boolean
onSearchChange?: (term: string) => void
scrollToSelected?: boolean
placement?: DropdownPlacement
initialSearchTerm?: string
actionButton?: { label: string; onClick: () => void; icon?: React.ReactNode }
renderOption?: (opt: SelectOption) => React.ReactNode
tooltip?: string
tooltipIcon?: React.ComponentProps<typeof import('./Tooltip').Tooltip>['icon']
helpText?: string
}
export const Select = forwardRef<HTMLDivElement, SelectProps>(function Select({
featured = false,
className = '',
...props
}, ref) {
if (featured) {
return <FeaturedSelect ref={ref} {...props} className={className} />
}
return (
<NativeSelect
ref={ref as React.Ref<HTMLSelectElement>}
{...props}
className={cn(className)}
/>
)
})
export type { SelectOption }
export default Select
+67
View File
@@ -0,0 +1,67 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Spinner } from './Spinner'
const meta = {
title: 'Feedback/Spinner',
component: Spinner,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Loading indicator. The `primary` variant reads from the palette tokens, so it re-colours with the toolbar switcher.',
},
},
},
argTypes: {
size: { control: 'select', options: ['xs', 'sm', 'md', 'lg', 'xl'] },
variant: {
control: 'select',
options: ['primary', 'secondary', 'white', 'success', 'danger', 'warning'],
},
label: { control: 'text', description: 'Accessible label announced to screen readers.' },
},
args: { size: 'md', variant: 'primary', label: 'Loading' },
} satisfies Meta<typeof Spinner>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {}
export const Sizes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-6">
{(['xs', 'sm', 'md', 'lg', 'xl'] as const).map((size) => (
<div key={size} className="flex flex-col items-center gap-2">
<Spinner size={size} />
<code className="text-[10px] text-gray-500">{size}</code>
</div>
))}
</div>
),
}
export const Variants: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-6">
{(['primary', 'secondary', 'success', 'danger', 'warning'] as const).map((variant) => (
<div key={variant} className="flex flex-col items-center gap-2">
<Spinner variant={variant} />
<code className="text-[10px] text-gray-500">{variant}</code>
</div>
))}
</div>
),
}
/** The `white` variant is only legible on a dark surface. */
export const OnDarkSurface: Story = {
render: () => (
<div className="flex items-center gap-6 rounded-xl bg-zink-800 p-8">
<Spinner variant="white" size="lg" />
<Spinner variant="white" size="md" />
<Spinner variant="white" size="sm" />
</div>
),
}
+42
View File
@@ -0,0 +1,42 @@
import { forwardRef, type HTMLAttributes } from 'react'
import { cn } from '@/lib/cn'
import { SPINNER_SIZES, SPINNER_VARIANTS, type SpinnerSize, type SpinnerVariant } from './spinner.tokens'
/**
* Loading spinner.
*
* Ported from the original `Spinner` component.
* The colour token is a palette-driven `primary-500`, so it re-themes with the
* Storybook palette switcher.
*/
export type SpinnerProps = HTMLAttributes<HTMLDivElement> & {
size?: SpinnerSize
variant?: SpinnerVariant
/** Accessible label announced while loading. */
label?: string
}
export const Spinner = forwardRef<HTMLDivElement, SpinnerProps>(function Spinner(
{ size = 'md', variant = 'primary', label = 'Loading', className, ...props },
ref,
) {
return (
<div
ref={ref}
role="status"
aria-label={label}
className={cn(
'inline-block rounded-full animate-spin',
SPINNER_SIZES[size] ?? SPINNER_SIZES.md,
SPINNER_VARIANTS[variant] ?? SPINNER_VARIANTS.primary,
className,
)}
{...props}
>
<span className="sr-only">{label}...</span>
</div>
)
})
export default Spinner
+128
View File
@@ -0,0 +1,128 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Switch } from './Switch'
const meta = {
title: 'Forms/Switch',
component: Switch,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Toggle switch with an optional label, description and help tooltip. Works controlled (`checked` + `onChange`) or uncontrolled. When `checked` is supplied the prop always wins, so a parent re-render can never silently discard the toggle state.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
color: {
control: 'select',
options: ['blue', 'red', 'green', 'yellow', 'teal', 'indigo', 'purple', 'pink'],
},
label: { control: 'text' },
description: { control: 'text' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
tooltip: { control: 'text' },
helpText: { control: 'text' },
error: { control: 'text' },
},
args: {
label: 'Enable automatic payslip delivery',
description: 'Sends a PDF to each employee on disbursement.',
size: 'md',
color: 'blue',
required: false,
disabled: false,
tooltip: '',
helpText: '',
error: '',
},
} satisfies Meta<typeof Switch>
export default meta
type Story = StoryObj<typeof meta>
/**
* Wraps Switch with local state so the toggle is interactive.
*
* `initial` matters: passing `checked` at all makes the component controlled,
* so a `defaultChecked` on the same element is ignored. The Colors story needs
* the switch to start ON, so the initial value has to live here.
*/
function ControlledSwitch({
initial = false,
...args
}: React.ComponentProps<typeof Switch> & { initial?: boolean }) {
const [checked, setChecked] = useState(initial)
return <Switch {...args} checked={checked} onChange={(e) => setChecked(e.target.checked)} />
}
export const Playground: Story = {
render: (args) => <ControlledSwitch {...args} />,
}
export const Uncontrolled: Story = {
render: (args) => <Switch {...args} defaultChecked />,
}
export const Sizes: Story = {
render: () => (
<div className="flex flex-col gap-5">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledSwitch key={size} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const Colors: Story = {
render: () => (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{(['blue', 'red', 'green', 'yellow', 'teal', 'indigo', 'purple', 'pink'] as const).map((color) => (
<ControlledSwitch key={color} color={color} label={color} initial />
))}
</div>
),
}
export const WithDescription: Story = {
render: () => (
<ControlledSwitch
label="Enable automatic payslip delivery"
description="Sends a PDF to each employee on disbursement."
/>
),
}
export const Required: Story = {
render: () => <ControlledSwitch label="I accept the terms" required />,
}
export const WithTooltip: Story = {
render: () => (
<ControlledSwitch
label="Lock completed payroll runs"
tooltip="Prevents any edit to a run once it is marked disbursed."
/>
),
}
export const WithError: Story = {
render: () => (
<ControlledSwitch
label="Lock completed payroll runs"
error="This setting is required by your compliance policy."
/>
),
}
export const Disabled: Story = {
render: () => (
<div className="flex flex-col gap-4">
<Switch label="Off and disabled" disabled />
<Switch label="On and disabled" defaultChecked disabled />
</div>
),
}
+171
View File
@@ -0,0 +1,171 @@
import {
forwardRef,
useEffect,
useRef,
useState,
type ChangeEvent,
type InputHTMLAttributes,
type Ref,
} from 'react'
import type { LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import { Tooltip } from './Tooltip'
import { SWITCH_COLORS, SWITCH_SIZES, type SwitchColor, type SwitchSize } from './switch.tokens'
/**
* Toggle switch with an optional label, description and help tooltip.
*
* Ported from the original `Switch` component, keeping its
* controlled/uncontrolled handling: a duplicated internal copy of `checked`
* drifts from whatever the caller holds, so the prop wins whenever it is
* supplied and local state is used only for genuinely uncontrolled use.
*
* `register` / `validation` (React Hook Form) are intentionally not ported —
* pass `checked` and `onChange` directly.
*/
export type SwitchProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'size'> & {
name?: string
size?: SwitchSize
color?: SwitchColor
label?: string
description?: string
/** Appends the mandatory asterisk to the label. */
required?: boolean
error?: string | { message?: string }
tooltip?: string
tooltipIcon?: LucideIcon
helpText?: string
}
export const Switch = forwardRef(function Switch(
{
name,
size = 'md',
disabled = false,
color = 'blue',
label,
description,
checked,
defaultChecked,
required = false,
onChange,
error,
className = '',
value,
tooltip,
tooltipIcon,
helpText,
...props
}: SwitchProps & { ref?: Ref<HTMLInputElement> },
ref,
) {
// `checked` has a default below, so the destructured value cannot distinguish
// an omitted prop from an explicit `false` — read the raw props instead.
const isControlled = checked !== undefined
const [uncontrolledChecked, setUncontrolledChecked] = useState(Boolean(defaultChecked))
const internalRef = useRef<HTMLInputElement>(null)
const isChecked = isControlled ? Boolean(checked) : uncontrolledChecked
// Keep uncontrolled state in step with a native form reset, which restores
// `defaultChecked` just as it would on a plain checkbox.
useEffect(() => {
const form = internalRef.current?.form
if (!form) return
const handleReset = () => setUncontrolledChecked(Boolean(defaultChecked))
form.addEventListener('reset', handleReset)
return () => form.removeEventListener('reset', handleReset)
}, [defaultChecked])
const sizeData = SWITCH_SIZES[size] ?? SWITCH_SIZES.md
const colorClass = SWITCH_COLORS[color] ?? SWITCH_COLORS.blue
const errorMessage = typeof error === 'string' ? error : error?.message
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
if (!isControlled) setUncontrolledChecked(e.target.checked)
onChange?.(e)
}
const handleRef = (el: HTMLInputElement | null) => {
internalRef.current = el
if (typeof ref === 'function') ref(el)
else if (ref) ref.current = el
}
return (
<div className={cn('flex flex-col items-start space-y-1', className)}>
<label
htmlFor={name ? `switch-${name}` : undefined}
className={cn(
'relative inline-flex shrink-0 items-center',
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
)}
>
<input
id={name ? `switch-${name}` : undefined}
name={name}
type="checkbox"
role="switch"
aria-checked={isChecked}
className="sr-only peer"
disabled={disabled}
checked={isChecked}
onChange={handleChange}
value={value}
ref={handleRef}
{...props}
/>
{/* Track + knob are decorative; the input above carries the semantics. */}
<span className="relative shrink-0" aria-hidden="true">
<span
className={cn(
'block rounded-full shadow-inner transition-colors duration-300',
sizeData.toggle,
isChecked ? colorClass : 'bg-gray-300',
)}
/>
<span
className={cn(
'absolute top-1 left-[0.15rem] block rounded-full bg-white shadow-sm transition-transform duration-300',
sizeData.dot,
isChecked ? sizeData.translate : 'translate-x-0',
)}
/>
</span>
{(label || description) && (
<span className="ml-3 flex flex-col justify-center">
{label && (
<span className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-900">
{label} {required && <span className="text-red-500">*</span>}
</span>
{(tooltip || helpText) && (
<span onClick={(e) => e.preventDefault()}>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
)}
{description && <span className="text-xs text-gray-500">{description}</span>}
</span>
)}
</label>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
})
export default Switch
+159
View File
@@ -0,0 +1,159 @@
import { useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { TextArea } from './TextArea'
const meta = {
title: 'Forms/TextArea',
component: TextArea,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Multi-line input. `featured` renders the label inside the field and floats it above the border on focus, on value, or when `shrink` is set.',
},
},
},
argTypes: {
size: { control: 'select', options: ['sm', 'md', 'lg'] },
theme: {
control: 'select',
options: ['primary', 'secondary', 'success', 'warning', 'info', 'error'],
},
rows: { control: { type: 'number', min: 1, max: 12 } },
featured: { control: 'boolean' },
shrink: { control: 'boolean' },
roundedFull: { control: 'boolean' },
dashedBorder: { control: 'boolean' },
resize: { control: 'boolean' },
required: { control: 'boolean' },
disabled: { control: 'boolean' },
label: { control: 'text' },
placeholder: { control: 'text' },
helpText: { control: 'text' },
error: { control: 'text' },
},
args: {
label: 'Reason for adjustment',
placeholder: 'Describe why this payroll run needs a correction…',
rows: 4,
size: 'md',
theme: 'primary',
featured: false,
shrink: false,
roundedFull: false,
dashedBorder: false,
resize: true,
required: false,
disabled: false,
helpText: '',
error: '',
},
} satisfies Meta<typeof TextArea>
export default meta
type Story = StoryObj<typeof meta>
function ControlledTextArea(args: React.ComponentProps<typeof TextArea>) {
const [value, setValue] = useState(args.value ?? '')
return <TextArea {...args} value={value} onChange={(e) => setValue(e.target.value)} />
}
export const Playground: Story = {
render: (args) => <ControlledTextArea {...args} />,
}
export const Uncontrolled: Story = {
render: (args) => <TextArea {...args} defaultValue="March payroll was short by ₹1,240 due to a missing attendance import." />,
}
/** Floating label: floats on focus, on value, or immediately with `shrink`. */
export const Featured: Story = {
args: { featured: true },
render: (args) => <ControlledTextArea {...args} />,
}
export const FeaturedPrefilled: Story = {
args: { featured: true },
render: (args) => (
<TextArea
{...args}
defaultValue="Statutory contributions were recalculated after the FY update."
/>
),
}
export const FeaturedShrunk: Story = {
args: { featured: true, shrink: true },
render: (args) => <TextArea {...args} />,
}
export const Sizes: Story = {
render: (args) => (
<div className="flex flex-col gap-5">
{(['sm', 'md', 'lg'] as const).map((size) => (
<ControlledTextArea key={size} {...args} size={size} label={`Size ${size}`} />
))}
</div>
),
}
export const Themes: Story = {
render: (args) => (
<div className="grid gap-4 sm:grid-cols-2">
{(['primary', 'secondary', 'success', 'warning', 'info', 'error'] as const).map((theme) => (
<ControlledTextArea key={theme} {...args} theme={theme} label={theme} />
))}
</div>
),
}
export const BorderStyles: Story = {
render: (args) => (
<div className="grid gap-4 sm:grid-cols-3">
<ControlledTextArea {...args} label="Solid" />
<ControlledTextArea {...args} label="Dashed" dashedBorder />
<ControlledTextArea {...args} label="Pill" roundedFull />
</div>
),
}
export const Resize: Story = {
render: (args) => (
<div className="grid gap-4 sm:grid-cols-2">
<ControlledTextArea {...args} label="Resizable" resize />
<ControlledTextArea {...args} label="Fixed height" resize={false} rows={4} />
</div>
),
}
export const WithTooltip: Story = {
render: (args) => (
<ControlledTextArea
{...args}
helpText="Visible to approvers only. Never shown on the payslip itself."
/>
),
}
export const WithError: Story = {
render: (args) => (
<ControlledTextArea {...args} required error="A reason is required for every adjustment." />
),
}
export const FeaturedWithError: Story = {
render: (args) => (
<ControlledTextArea {...args} featured required error="A reason is required for every adjustment." />
),
}
export const Disabled: Story = {
render: (args) => (
<TextArea
{...args}
disabled
defaultValue="Locked after this run was approved."
/>
),
}
+230
View File
@@ -0,0 +1,230 @@
import { forwardRef, useState, type ChangeEvent, type FocusEvent, type TextareaHTMLAttributes } from 'react'
import type { LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import { omit } from '@/lib/omit'
import { Tooltip } from './Tooltip'
import {
FLOATING_CONTENT_PADDING,
FLOATING_LABEL_SIZES,
LABEL_SIZES,
TEXTAREA_SIZES,
TEXTAREA_THEMES,
type TextAreaSize,
type TextAreaTheme,
} from './textarea.tokens'
/**
* Multi-line text input, with an optional floating label.
*
* Ported from the original `TextArea` component.
*
* `featured` renders the label inside the field and floats it above the border
* once the field is focused, holds a value, or `shrink` is set. The floating
* label paints its own background so it cuts through the border cleanly.
*
* Form-library props are filtered out before spreading, so nothing internal
* leaks onto the DOM node.
*/
export type TextAreaProps = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'rows'> & {
label?: string
rows?: number
size?: TextAreaSize
theme?: TextAreaTheme
/** Render the label inside the field and float it on focus/value. */
featured?: boolean
/** Float the label even when the field is empty and unfocused. */
shrink?: boolean
roundedFull?: boolean
dashedBorder?: boolean
resize?: boolean
error?: string | { message?: string }
tooltip?: string
tooltipIcon?: LucideIcon
helpText?: string
}
export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(function TextArea(
{
label = '',
placeholder = '',
disabled = false,
required = false,
className = '',
roundedFull = false,
dashedBorder = false,
size = 'md',
theme = 'primary',
rows = 4,
name,
error,
onChange,
onBlur,
onFocus,
featured = false,
value,
resize = true,
shrink = false,
helpText,
tooltip,
tooltipIcon,
...props
},
ref,
) {
const [isFocused, setIsFocused] = useState(false)
// The floating label needs to know whether the field holds content. Track it
// locally so uncontrolled usage floats correctly too.
//
// `defaultValue` counts as content: an uncontrolled field rendered with
// `defaultValue` is visibly filled but `value` is undefined, so seeding only
// from `value` left the label sitting on top of the text. The source
// component has the same gap.
const [hasValue, setHasValue] = useState(
Boolean(value) || Boolean(props.defaultValue),
)
// Strip form-library plumbing that must not reach the DOM.
const htmlProps = omit(props as Record<string, unknown>, [
'control',
'allValues',
'isDynamic',
'valueKey',
'labelKey',
'endpoint',
'endpointParams',
'isMulti',
'searchable',
'infiniteScroll',
'register',
'validation',
])
const handleFocus = (e: FocusEvent<HTMLTextAreaElement>) => {
setIsFocused(true)
onFocus?.(e)
}
const handleBlur = (e: FocusEvent<HTMLTextAreaElement>) => {
setIsFocused(false)
onBlur?.(e)
}
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
setHasValue(Boolean(e.target.value))
onChange?.(e)
}
const shouldFloat = featured && (shrink || isFocused || hasValue || Boolean(value))
const themeClass = TEXTAREA_THEMES[theme] ?? TEXTAREA_THEMES.primary
const errorMessage = typeof error === 'string' ? error : error?.message
return (
<div className="w-full relative flex flex-col">
{!featured && label && (
<div className="mb-1 flex items-center gap-1.5">
<label htmlFor={name} className={cn('text-gray-800', LABEL_SIZES[size])}>
{label} {required && <span className="text-red-500">*</span>}
</label>
{(tooltip || helpText) && (
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
)}
</div>
)}
<div className="relative w-full">
<textarea
id={name}
ref={ref}
name={name}
rows={rows}
disabled={disabled}
required={required}
placeholder={featured && !shouldFloat ? '' : placeholder}
autoComplete="off"
aria-invalid={Boolean(errorMessage)}
className={cn(
'w-full outline-none transition-all duration-200 bg-white text-gray-800',
TEXTAREA_SIZES[size],
roundedFull ? 'rounded-3xl' : 'rounded-md',
dashedBorder ? 'border-dashed' : 'border-solid',
resize ? 'resize-y' : 'resize-none',
'border',
// Once the label floats it occupies the top ~1rem of the field, so
// the first line of text needs to clear it. The source component
// never adds this padding, which puts the label and the first line
// of text on top of each other — visible in any prefilled or
// focused featured textarea. Sized off the label's own height.
featured && shouldFloat && FLOATING_CONTENT_PADDING[size],
disabled
? 'bg-gray-100 border-slate-200 text-slate-400 cursor-not-allowed'
: cn(
isFocused ? themeClass : 'border-slate-300',
'hover:border-slate-400',
),
// Error wins over the theme's focus colours.
errorMessage && 'border-red-500 focus:border-red-500 focus:ring-red-500',
className,
)}
onFocus={handleFocus}
onBlur={handleBlur}
onChange={handleChange}
value={value}
{...htmlProps}
/>
{featured && label && (
<label
htmlFor={name}
className={cn(
'absolute pointer-events-none transition-all duration-200 left-3 px-1',
shouldFloat
? cn(
'-top-2 bg-white transform',
FLOATING_LABEL_SIZES[size],
errorMessage
? 'text-red-500'
: isFocused
? 'text-primary-500'
: 'text-slate-400',
)
: cn('top-3', LABEL_SIZES[size], 'text-slate-400'),
)}
>
<span className="flex items-center gap-1.5">
<span>
{label} {required && <span className="text-red-500">*</span>}
</span>
{(tooltip || helpText) && (
<span
className="pointer-events-auto inline-flex shrink-0"
onClick={(e) => e.preventDefault()}
>
<Tooltip
content={tooltip ?? helpText ?? ''}
size="sm"
position="top"
icon={tooltipIcon}
/>
</span>
)}
</span>
</label>
)}
</div>
{errorMessage && (
<p className="mt-1 text-sm text-red-500" role="alert">
{errorMessage}
</p>
)}
</div>
)
})
export default TextArea
+37
View File
@@ -0,0 +1,37 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { TextField } from './TextField'
const meta = {
title: 'Data entry/Text field',
component: TextField,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component: 'A labeled form field with optional help text and accessible validation feedback.',
},
},
},
argTypes: {
error: {
control: 'text',
},
},
args: {
label: 'Email address',
hint: 'Use an address you can check today.',
placeholder: '[email protected]',
},
} satisfies Meta<typeof TextField>
export default meta
type Story = StoryObj<typeof meta>
export const Default: Story = {}
export const WithError: Story = {
args: {
error: 'Enter a valid email address.',
defaultValue: 'not-an-email',
},
}
+51
View File
@@ -0,0 +1,51 @@
import { useId, useState, type InputHTMLAttributes } from 'react'
export type TextFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'size'> & {
label: string
hint?: string
error?: string
}
export function TextField({ label, hint, error, className = '', ...props }: TextFieldProps) {
const id = useId()
const descriptionId = `${id}-description`
const errorId = `${id}-error`
const [value, setValue] = useState(props.defaultValue ?? '')
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
setValue(event.target.value)
props.onChange?.(event)
}
return (
<div className={`space-y-2 ${className}`}>
<label htmlFor={id} className="block text-sm font-bold text-slate-800">
{label}
{props.required && <span className="ml-1 text-red-600">*</span>}
</label>
<input
{...props}
id={id}
value={value}
onChange={handleChange}
aria-invalid={Boolean(error)}
aria-describedby={
[hint ? descriptionId : null, error ? errorId : null].filter(Boolean).join(' ') || undefined
}
className={`min-h-11 w-full rounded-xl border bg-white px-3.5 text-sm text-slate-950 outline-none transition placeholder:text-slate-400 focus:border-primary-500 focus:ring-4 focus:ring-primary-100 ${
error ? 'border-red-300' : 'border-slate-200'
}`}
/>
{hint && !error && (
<p id={descriptionId} className="text-xs leading-5 text-slate-500">
{hint}
</p>
)}
{error && (
<p id={errorId} role="alert" className="text-xs font-semibold leading-5 text-red-600">
{error}
</p>
)}
</div>
)
}
+185
View File
@@ -0,0 +1,185 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
import { Tooltip } from './Tooltip'
const meta = {
title: 'Overlays/Tooltip',
component: Tooltip,
tags: ['autodocs'],
parameters: {
docs: {
description: {
component:
'Portal-rendered tooltip with viewport clamping. String content renders a themed bubble with an arrow; a React node renders an interactive panel that stays open while the pointer is over it.',
},
},
},
argTypes: {
position: {
control: 'select',
options: [
'top', 'top-start', 'top-end',
'bottom', 'bottom-start', 'bottom-end',
'left', 'left-start', 'left-end',
'right', 'right-start', 'right-end',
],
},
theme: {
control: 'select',
options: ['dark', 'light', 'primary', 'success', 'danger', 'warning', 'info', 'soft', 'custom', 'gradient'],
},
size: { control: 'select', options: ['sm', 'md', 'lg'] },
delay: { control: { type: 'number', min: 0, step: 100 }, description: 'Hover delay in ms.' },
arrow: { control: 'boolean' },
shadow: { control: 'boolean' },
rounded: { control: 'boolean' },
},
args: {
content: 'Employees are onboarded per country.',
position: 'top',
theme: 'dark',
size: 'md',
delay: 0,
arrow: true,
shadow: false,
rounded: true,
},
} satisfies Meta<typeof Tooltip>
export default meta
type Story = StoryObj<typeof meta>
export const Playground: Story = {
render: (args) => (
<div className="flex justify-center py-16">
<Tooltip {...args}>
<button type="button" className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-semibold text-gray-700 hover:border-gray-400">
Hover me
</button>
</Tooltip>
</div>
),
}
/** No children — falls back to the trigger icon. */
export const IconTrigger: Story = {
args: { content: 'This field is required for statutory reporting.' },
render: (args) => (
<div className="py-16">
<Tooltip {...args} />
</div>
),
}
export const Themes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-6 py-16">
{(['dark', 'light', 'primary', 'success', 'danger', 'warning', 'info', 'soft', 'custom', 'gradient'] as const).map(
(theme) => (
<div key={theme} className="flex flex-col items-center gap-2">
<Tooltip content={`${theme} tooltip`} theme={theme}>
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
{theme}
</span>
</Tooltip>
<code className="text-[10px] text-gray-500">{theme}</code>
</div>
),
)}
</div>
),
}
export const Positions: Story = {
render: () => (
<div className="flex items-center justify-center py-24">
<div className="relative h-40 w-96">
{(['top', 'top-start', 'top-end', 'bottom', 'bottom-start', 'bottom-end', 'left', 'left-start', 'left-end', 'right', 'right-start', 'right-end'] as const).map(
(position) => (
<Tooltip key={position} content={position} position={position} size="sm">
<span className="absolute cursor-pointer rounded bg-primary-500 px-2 py-1 text-[10px] font-semibold text-white">
{position}
</span>
</Tooltip>
),
)}
</div>
</div>
),
}
export const Sizes: Story = {
render: () => (
<div className="flex flex-wrap items-center gap-8 py-16">
{(['sm', 'md', 'lg'] as const).map((size) => (
<div key={size} className="flex flex-col items-center gap-2">
<Tooltip content={`${size} size tooltip`} size={size}>
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
{size}
</span>
</Tooltip>
<code className="text-[10px] text-gray-500">{size}</code>
</div>
))}
</div>
),
}
/** Node content renders an interactive light panel that survives hover travel. */
export const RichContent: Story = {
render: () => (
<div className="py-16">
<Tooltip
content={
<div className="space-y-1.5 p-1">
<p className="text-xs font-semibold text-gray-900">Statutory basis</p>
<p className="text-[11px] text-gray-600">
Applies to all entities registered in India.
</p>
<button
type="button"
className="mt-1 w-full rounded bg-primary-600 px-2 py-1 text-[11px] font-semibold text-white"
>
Open settings
</button>
</div>
}
>
<button
type="button"
className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm font-semibold text-gray-700 hover:border-gray-400"
>
Rich tooltip
</button>
</Tooltip>
</div>
),
}
export const NoArrow: Story = {
args: { arrow: false, content: 'Tooltip without an arrow.' },
render: (args) => (
<div className="flex justify-center py-16">
<Tooltip {...args}>
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
Hover
</span>
</Tooltip>
</div>
),
}
/** Long copy scrolls inside the bubble instead of stretching past the viewport. */
export const LongContent: Story = {
render: () => (
<div className="py-16">
<Tooltip
content="Payroll runs are computed in the tenant's base currency. Re-runs after approval are blocked unless a supervisor raises a correction request, which is recorded in the audit trail with the reason and the requesting user."
size="md"
>
<span className="cursor-pointer rounded-md bg-gray-100 px-3 py-1.5 text-xs font-semibold text-gray-700">
Hover for long copy
</span>
</Tooltip>
</div>
),
}
+277
View File
@@ -0,0 +1,277 @@
import {
isValidElement,
useCallback,
useEffect,
useRef,
useState,
forwardRef,
type CSSProperties,
type ReactNode,
type Ref,
} from 'react'
import { createPortal } from 'react-dom'
import { AlertCircle, type LucideIcon } from 'lucide-react'
import { cn } from '@/lib/cn'
import {
ARROW_POSITION_COLORS,
BASE_ARROW_CLASSES,
BASE_ARROW_CLASSES_OUTER,
TOOLTIP_COLORS,
TOOLTIP_SIZES,
WHITE_BORDER_MAP,
type TooltipPosition,
type TooltipSize,
type TooltipTheme,
} from './tooltip.tokens'
/**
* Portal-rendered tooltip with viewport clamping.
*
* Ported from the original `Tooltip` component.
* Every form control in the source app renders one of these for its help text,
* so it is ported first as a shared dependency.
*
* String content gets a themed bubble with an arrow. React-node content gets a
* light panel sized to fit its content (a wider arrow sits behind it) and
* stays open while the pointer is over it, so interactive menus work.
*/
const MAX_WIDTH = 280
function directionOf(position: TooltipPosition): 't' | 'b' | 'l' | 'r' {
if (position.startsWith('top')) return 't'
if (position.startsWith('bottom')) return 'b'
if (position.startsWith('left')) return 'l'
return 'r'
}
export type TooltipProps = {
/** String renders a themed bubble; a React node renders an interactive panel. */
content: ReactNode
position?: TooltipPosition
children?: ReactNode
size?: TooltipSize
theme?: TooltipTheme
rounded?: boolean
arrow?: boolean
shadow?: boolean
/** Hover delay in ms before the tooltip appears. */
delay?: number
className?: string
triggerClassName?: string
iconClassName?: string
/** Overrides the default `AlertCircle` trigger icon. */
icon?: LucideIcon
}
export const Tooltip = forwardRef(function Tooltip(
{
content,
position = 'top',
children,
size = 'md',
theme = 'dark',
rounded = true,
arrow = true,
shadow = false,
delay = 0,
className = '',
triggerClassName = '',
iconClassName = 'text-orange-500 cursor-pointer hover:text-orange-600 transition-colors',
icon,
}: TooltipProps,
ref: Ref<HTMLDivElement>,
) {
const [isHovered, setIsHovered] = useState(false)
const [showTooltip, setShowTooltip] = useState(false)
const [coords, setCoords] = useState({ x: 0, y: 0, width: 0, height: 0 })
const triggerRef = useRef<HTMLDivElement>(null)
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
const lastRectRef = useRef<DOMRect | null>(null)
useEffect(() => {
const node = triggerRef.current
if (typeof ref === 'function') ref(node)
else if (ref) ref.current = node
}, [ref])
const isStringContent = typeof content === 'string' && content.trim().length > 0
const isNodeContent = isValidElement(content)
const shouldShow = isStringContent || isNodeContent
const isShortText = typeof content === 'string' && content.length <= 33
const ResolvedIcon: LucideIcon = icon ?? AlertCircle
const updatePosition = useCallback(() => {
const node = triggerRef.current
if (!node) return
const rect = node.getBoundingClientRect()
const last = lastRectRef.current
// Skip a re-measure when nothing moved — otherwise hovering over a static
// trigger would keep resetting coords on every mouse event.
if (
last &&
Math.abs(last.top - rect.top) < 0.5 &&
Math.abs(last.left - rect.left) < 0.5
) {
return
}
lastRectRef.current = rect
setCoords({ x: rect.left, y: rect.top, width: rect.width, height: rect.height })
}, [])
const handleMouseEnter = () => {
updatePosition()
setIsHovered(true)
if (closeTimer.current) {
clearTimeout(closeTimer.current)
closeTimer.current = null
}
}
const handleMouseLeave = () => {
if (isNodeContent) {
// Grace period so the pointer can travel from trigger to panel.
closeTimer.current = setTimeout(() => setIsHovered(false), 200)
} else {
setIsHovered(false)
}
}
const handleMenuMouseEnter = () => {
if (closeTimer.current) {
clearTimeout(closeTimer.current)
closeTimer.current = null
}
}
const handleMenuMouseLeave = () => {
closeTimer.current = setTimeout(() => {
setIsHovered(false)
setShowTooltip(false)
}, 200)
}
useEffect(() => {
if (isHovered) {
const timer = setTimeout(() => setShowTooltip(true), delay)
return () => clearTimeout(timer)
}
setShowTooltip(false)
}, [isHovered, delay])
useEffect(() => {
if (!showTooltip) return
const reposition = () => updatePosition()
window.addEventListener('scroll', reposition, true)
window.addEventListener('resize', reposition)
return () => {
window.removeEventListener('scroll', reposition, true)
window.removeEventListener('resize', reposition)
}
}, [showTooltip, updatePosition])
const direction = directionOf(position)
const arrowColorClass = isNodeContent
? WHITE_BORDER_MAP[direction]
: ARROW_POSITION_COLORS[position]?.[theme] ?? ''
const positionStyle = (): CSSProperties => {
const { x, y, width, height } = coords
const viewportWidth = typeof window !== 'undefined' ? window.innerWidth : 0
const viewportHeight = typeof window !== 'undefined' ? window.innerHeight : 0
const clampX = (v: number) => (viewportWidth ? Math.min(Math.max(v, 8), viewportWidth - 8) : v)
const clampY = (v: number) => (viewportHeight ? Math.min(Math.max(v, 8), viewportHeight - 8) : v)
const base: CSSProperties = { position: 'fixed', zIndex: 9999, maxWidth: `${MAX_WIDTH}px` }
switch (position) {
case 'top':
return { ...base, top: clampY(y - 8), left: clampX(x + width / 2), transform: 'translateX(-50%) translateY(-100%)' }
case 'top-start':
return { ...base, top: clampY(y - 8), left: clampX(x), transform: 'translateY(-100%)' }
case 'top-end':
return { ...base, top: clampY(y - 8), left: clampX(x + width), transform: 'translateX(-100%) translateY(-100%)' }
case 'bottom':
return { ...base, top: clampY(y + height + 8), left: clampX(x + width / 2), transform: 'translateX(-50%)' }
case 'bottom-start':
return { ...base, top: clampY(y + height + 8), left: clampX(x) }
case 'bottom-end':
return { ...base, top: clampY(y + height + 8), left: clampX(x + width), transform: 'translateX(-100%)' }
case 'left':
return { ...base, top: clampY(y + height / 2), left: clampX(x - 8), transform: 'translateY(-50%) translateX(-100%)' }
case 'left-start':
return { ...base, top: clampY(y), left: clampX(x - 8), transform: 'translateX(-100%)' }
case 'left-end':
return { ...base, top: clampY(y + height), left: clampX(x - 8), transform: 'translateY(-100%) translateX(-100%)' }
case 'right':
return { ...base, top: clampY(y + height / 2), left: clampX(x + width + 8), transform: 'translateY(-50%)' }
case 'right-start':
return { ...base, top: clampY(y), left: clampX(x + width + 8) }
case 'right-end':
return { ...base, top: clampY(y + height), left: clampX(x + width + 8), transform: 'translateY(-100%)' }
default:
return { ...base, top: clampY(y), left: clampX(x) }
}
}
return (
<>
<div
ref={triggerRef}
className={cn('relative inline-block', triggerClassName)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
{children ?? <ResolvedIcon size={16} className={cn(iconClassName)} />}
</div>
{showTooltip &&
shouldShow &&
createPortal(
<div
role="tooltip"
onMouseEnter={isNodeContent ? handleMenuMouseEnter : undefined}
onMouseLeave={isNodeContent ? handleMenuMouseLeave : undefined}
style={positionStyle()}
className={cn(
TOOLTIP_SIZES[size] ?? TOOLTIP_SIZES.md,
isStringContent
? (TOOLTIP_COLORS[theme] ?? TOOLTIP_COLORS.dark)
: 'bg-white text-slate-700 border border-slate-200',
shadow && 'shadow-lg',
rounded ? 'rounded-lg' : 'rounded',
className,
)}
>
<div
className={cn(
'block text-start max-h-[250px] align-top overflow-auto',
isShortText && isStringContent ? 'max-w-[210px] w-auto whitespace-nowrap' : '',
!isStringContent ? 'min-w-[210px]' : '',
)}
>
{content}
</div>
{arrow && (
<>
{isNodeContent && (
<div
className={cn(
BASE_ARROW_CLASSES_OUTER[position],
ARROW_POSITION_COLORS[position]?.[theme] ?? '',
)}
/>
)}
<div className={cn(BASE_ARROW_CLASSES[position], arrowColorClass)} />
</>
)}
</div>,
document.body,
)}
</>
)
})
export default Tooltip
+45
View File
@@ -0,0 +1,45 @@
/**
* Alert style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type AlertColor = 'success' | 'info' | 'warning' | 'error'
export type AlertVariant = 'default' | 'filled' | 'outlined' | 'gradient'
export type AlertTheme = {
bg: string
text: string
border: string
lightBg: string
}
export const ALERT_COLORS: Record<AlertColor, AlertTheme> = {
success: {
bg: 'bg-green-600',
text: 'text-green-700',
border: 'border-green-600',
lightBg: 'bg-green-100',
},
info: {
bg: 'bg-sky-600',
text: 'text-sky-700',
border: 'border-sky-600',
lightBg: 'bg-sky-100',
},
warning: {
bg: 'bg-orange-500',
text: 'text-orange-700',
border: 'border-orange-500',
lightBg: 'bg-orange-100',
},
error: {
bg: 'bg-red-600',
text: 'text-red-700',
border: 'border-red-600',
lightBg: 'bg-red-100',
},
}
export const ALERT_GRADIENT = 'bg-gradient-to-r from-green-400 to-primary-500 text-white'
+82
View File
@@ -0,0 +1,82 @@
/**
* Badge style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
import type { ReactNode } from 'react'
export type BadgeColor = 'info' | 'gray' | 'danger' | 'success' | 'warning' | 'primary'
export type BadgeType = 'floating' | 'default'
export type BadgeFloatingPosition = 'top_right' | 'top_left' | 'bottom_right' | 'bottom_left'
export type BadgeFloatingSize = 'xs' | 'sm' | 'md' | 'lg'
export type BadgeDefaultSize = 'sm' | 'md' | 'lg'
export type BadgeBorder = 'sm' | 'md' | 'lg' | 'full'
export type ColorRange = { min: number; max: number; color: BadgeColor | string }
export const BADGE_SIZES: Record<BadgeFloatingSize, string> = {
xs: 'text-[10px] px-1.5 py-0.5 min-w-[16px] h-[16px]',
sm: 'text-xs px-1.5 py-0.5 min-w-[18px] h-[18px]',
md: 'text-sm px-2 py-0.5 min-w-[20px] h-[20px]',
lg: 'text-base px-2 py-1 min-w-[24px] h-[24px]',
}
export const DEFAULT_BADGE_SIZES: Record<BadgeDefaultSize, string> = {
sm: 'text-xs px-2 py-0.5',
md: 'text-sm px-2.5 py-1',
lg: 'text-base px-3 py-1.5',
}
export const BADGE_COLORS: Record<BadgeColor, string> = {
info: 'bg-cyan-100 text-cyan-800 border border-cyan-200',
gray: 'bg-gray-100 text-gray-800 border border-gray-200',
danger: 'bg-red-100 text-red-800 border border-red-200',
success: 'bg-green-100 text-green-800 border border-green-200',
warning: 'bg-yellow-100 text-yellow-800 border border-yellow-200',
primary: 'bg-primary-100 text-primary-700 border border-primary-200',
}
export const BADGE_POSITIONS: Record<BadgeFloatingPosition, string> = {
top_right: 'top-0 right-0 translate-x-1/2 -translate-y-1/2',
top_left: 'top-0 left-0 -translate-x-1/2 -translate-y-1/2',
bottom_right: 'bottom-0 right-0 translate-x-1/2 translate-y-1/2',
bottom_left: 'bottom-0 left-0 -translate-x-1/2 translate-y-1/2',
}
export const BADGE_ROUNDED: Record<BadgeBorder, string> = {
sm: 'rounded-sm',
md: 'rounded-md',
lg: 'rounded-lg',
full: 'rounded-full',
}
/** Legacy colour names the source app still passes through. */
export const BADGE_COLOR_ALIAS: Record<string, BadgeColor> = {
green: 'success',
red: 'danger',
default: 'gray',
blue: 'primary',
}
/** Colour the badge by numeric content, e.g. pending-approval counts. */
export function resolveBadgeColor(
color: string,
content: ReactNode | number,
ranges: ColorRange[] | undefined,
): BadgeColor {
const normalized = BADGE_COLOR_ALIAS[color] ?? (color as BadgeColor)
if (!ranges || !Array.isArray(ranges)) return normalized
const num = Number(content)
if (Number.isNaN(num)) return normalized
for (const range of ranges) {
if (num >= range.min && num <= range.max) {
return BADGE_COLOR_ALIAS[range.color] ?? (range.color as BadgeColor)
}
}
return normalized
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Card style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type CardTheme = 'primary' | 'secondary' | 'success' | 'danger' | 'no-preset'
export type CardLayout = 'vertical' | 'horizontal'
export type CardShadow = 'none' | 'sm' | 'md' | 'lg' | 'xl'
export type CardRounded = 'none' | 'sm' | 'md' | 'lg' | 'xl' | 'full'
export const SHADOW_SIZES: Record<CardShadow, string> = {
none: 'shadow-none',
sm: 'shadow-sm',
md: 'shadow-md',
lg: 'shadow-lg',
xl: 'shadow-xl',
}
export const ROUNDED_SIZES: Record<CardRounded, string> = {
none: 'rounded-none',
sm: 'rounded-sm',
md: 'rounded-md',
lg: 'rounded-lg',
xl: 'rounded-xl',
full: 'rounded-[2rem]',
}
export type CardThemeData = {
card: string
header: string
body: string
footer: string
}
export const CARD_THEMES: Record<CardTheme, CardThemeData> = {
primary: {
card: 'bg-white text-slate-800 border border-gray-200',
header: 'text-lg font-bold p-4 border-b border-gray-100',
body: 'p-4 text-gray-600',
footer: 'p-4 border-t border-gray-100 bg-gray-50/50',
},
secondary: {
card: 'bg-gray-50 text-gray-900 border border-gray-200',
header: 'text-lg font-bold p-4 text-gray-700 border-b border-gray-200',
body: 'p-4 text-gray-600',
footer: 'p-4 border-t border-gray-200',
},
success: {
card: 'bg-green-50 text-green-900 border border-green-200',
header: 'text-lg font-bold p-4 text-green-700 border-b border-green-100',
body: 'p-4 text-green-800',
footer: 'p-4 border-t border-green-100',
},
danger: {
card: 'bg-red-50 text-red-900 border border-red-200',
header: 'text-lg font-bold p-4 text-red-700 border-b border-red-100',
body: 'p-4 text-red-800',
footer: 'p-4 border-t border-red-100',
},
'no-preset': { card: '', header: '', body: '', footer: '' },
}
+46
View File
@@ -0,0 +1,46 @@
/**
* Checkbox style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type CheckboxSize = 'sm' | 'md' | 'lg'
export type CheckboxTheme =
| 'primary'
| 'secondary'
| 'success'
| 'danger'
| 'warning'
| 'info'
| 'amber'
| 'purple'
| 'blue'
| 'green'
| 'red'
| 'yellow'
| 'teal'
export const CHECKBOX_SIZES: Record<CheckboxSize, string> = {
sm: 'h-4 w-4',
md: 'h-5 w-5',
lg: 'h-6 w-6',
}
/** Uses the native `accent-*` property, so the browser paints the checked box. */
export const CHECKBOX_THEMES: Record<CheckboxTheme, string> = {
primary: 'accent-primary-500',
secondary: 'accent-gray-500',
success: 'accent-green-500',
danger: 'accent-red-500',
warning: 'accent-yellow-500',
info: 'accent-cyan-500',
// Legacy names the source app still passes through.
amber: 'accent-amber-500',
purple: 'accent-purple-500',
blue: 'accent-primary-500',
green: 'accent-green-500',
red: 'accent-red-500',
yellow: 'accent-yellow-500',
teal: 'accent-teal-500',
}
+87
View File
@@ -0,0 +1,87 @@
/**
* Input style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type InputSize = 'sm' | 'md' | 'lg'
export type InputTheme = 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info'
export type InputVariant = 'outlined' | 'underlined'
export const INPUT_SIZES: Record<InputSize, string> = {
sm: 'px-3 py-2 text-xs',
md: 'px-3 py-2 h-[2.5rem] text-sm',
lg: 'px-3 py-3 text-base',
}
export const ICON_SIZES: Record<InputSize, string> = {
sm: 'text-sm',
md: 'text-[1rem]',
lg: 'text-lg',
}
export const LABEL_SIZES: Record<InputSize, string> = {
sm: 'text-[0.7rem] font-medium leading-loose',
md: 'text-[0.8rem] font-medium leading-loose',
lg: 'text-base font-medium leading-loose',
}
/** Label type size once it has floated above the border. */
export const FLOATING_LABEL_SIZES: Record<InputSize, string> = {
sm: 'text-[0.6rem] font-medium leading-loose',
md: 'text-[0.65rem] font-medium leading-loose',
lg: 'text-sm',
}
/**
* Extra top padding for a `featured` input once its label floats.
*
* The floated label is a chip sitting on the top border; without this the text
* sits underneath it. The source never adds it, which is why a prefilled
* featured input renders its text under the label.
*/
export const FLOATING_CONTENT_PADDING: Record<InputSize, string> = {
sm: 'pt-5',
md: 'pt-6',
lg: 'pt-7',
}
export const INPUT_THEMES: Record<InputTheme, string> = {
primary: 'focus:border-primary-500 focus:ring-primary-500',
secondary: 'focus:border-purple-500 focus:ring-purple-500',
success: 'focus:border-green-500 focus:ring-green-500',
warning: 'focus:border-yellow-500 focus:ring-yellow-500',
info: 'focus:border-cyan-500 focus:ring-cyan-500',
error: 'border-red-500 focus:border-red-500 focus:ring-red-500',
}
export const INPUT_HOVER_THEMES: Record<InputTheme, string> = {
primary: 'hover:border-primary-500',
secondary: 'hover:border-purple-500',
success: 'hover:border-green-500',
// The error state owns its own hover behaviour.
error: '',
warning: 'hover:border-yellow-500',
info: 'hover:border-cyan-500',
}
export const LABEL_COLORS: Record<InputTheme, string> = {
primary: 'text-primary-500',
secondary: 'text-purple-500',
success: 'text-green-500',
warning: 'text-yellow-500',
info: 'text-cyan-500',
error: 'text-red-500',
}
export const INPUT_VARIANTS: Record<
InputVariant,
{ wrapper: string; labelFloating: string }
> = {
outlined: { wrapper: 'border bg-white', labelFloating: 'bg-white px-1' },
underlined: {
wrapper: 'border-b border-t-0 border-x-0 bg-transparent rounded-none',
labelFloating: 'bg-transparent px-0',
},
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Radio style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type RadioSize = 'sm' | 'md' | 'lg'
export type RadioTheme =
| 'blue'
| 'green'
| 'red'
| 'yellow'
| 'teal'
| 'purple'
| 'amber'
| 'gray'
export type RadioSizeData = {
/** Outer ring. */
container: string
label: string
/** Inner dot. */
dot: string
}
export const RADIO_SIZES: Record<RadioSize, RadioSizeData> = {
sm: { container: 'h-3.5 w-3.5', label: 'text-xs', dot: 'h-1.5 w-1.5' },
md: { container: 'h-4 w-4', label: 'text-sm', dot: 'h-2 w-2' },
lg: { container: 'h-5 w-5', label: 'text-base', dot: 'h-2.5 w-2.5' },
}
export type RadioColorData = {
/** Inner dot fill. */
bg: string
/** Ring border when selected. */
border: string
text: string
}
export const RADIO_COLORS: Record<RadioTheme, RadioColorData> = {
blue: { bg: 'bg-primary-600', border: 'border-primary-400', text: 'text-primary-500' },
green: { bg: 'bg-green-600', border: 'border-green-400', text: 'text-green-500' },
red: { bg: 'bg-red-600', border: 'border-red-400', text: 'text-red-500' },
yellow: { bg: 'bg-yellow-500', border: 'border-yellow-400', text: 'text-yellow-500' },
teal: { bg: 'bg-teal-600', border: 'border-teal-400', text: 'text-teal-500' },
purple: { bg: 'bg-purple-600', border: 'border-purple-400', text: 'text-purple-500' },
amber: { bg: 'bg-amber-500', border: 'border-amber-400', text: 'text-amber-500' },
gray: { bg: 'bg-gray-600', border: 'border-gray-400', text: 'text-gray-500' },
}
+111
View File
@@ -0,0 +1,111 @@
/**
* Select style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type SelectSize = 'sm' | 'md' | 'lg'
export type SelectTheme = 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info'
export type SelectVariant = 'outlined' | 'filled' | 'standard' | 'underlined'
export type SelectWidth = 'full' | 'half' | 'small' | 'xs' | 'large'
export const SELECT_SIZES: Record<SelectSize, string> = {
sm: 'px-3 py-2 text-xs',
md: 'px-3 py-2 h-[2.5rem] text-sm',
lg: 'px-3 py-3 text-base',
}
export const SELECT_VARIANTS: Record<SelectVariant, string> = {
outlined: 'border bg-white',
filled: 'border-b bg-gray-100',
standard: 'border-b bg-transparent',
underlined: 'border-b border-t-0 border-x-0 bg-transparent rounded-none',
}
export const SELECT_WIDTHS: Record<SelectWidth, string> = {
full: 'w-full',
half: 'w-1/2',
small: 'w-48',
xs: 'w-24',
large: 'w-64',
}
export const LABEL_SIZES: Record<SelectSize, string> = {
sm: 'text-[0.7rem] font-medium leading-loose',
md: 'text-[0.8rem] font-medium leading-loose',
lg: 'text-md',
}
export const FLOATING_LABEL_SIZES: Record<SelectSize, string> = {
sm: 'text-[0.6rem] font-medium leading-loose',
md: 'text-[0.7rem] font-medium leading-loose',
lg: 'text-sm',
}
/**
* Per-theme class maps, written out in full.
*
* The source builds these as template strings — `` `border-${themeColor}-500` `` —
* which Tailwind's scanner can never see, so the generated rules are missing and
* the themed states render unstyled. Every class here is a literal so it is
* picked up at build time.
*/
export type ThemeClasses = {
/** Border + ring while focused. */
focus: string
/** Label text while floated. */
label: string
/** Search input border while focused. */
searchFocus: string
/** Selected row in the dropdown. */
selected: string
/** Hover border on the control. */
hover: string
}
export const SELECT_THEME_CLASSES: Record<SelectTheme, ThemeClasses> = {
primary: {
focus: 'border-primary-500 ring-primary-500',
label: 'text-primary-500',
searchFocus: 'focus:border-primary-500',
selected: 'bg-primary-50 text-primary-600',
hover: 'hover:border-primary-500',
},
secondary: {
focus: 'border-purple-500 ring-purple-500',
label: 'text-purple-500',
searchFocus: 'focus:border-purple-500',
selected: 'bg-purple-50 text-purple-600',
hover: 'hover:border-purple-500',
},
success: {
focus: 'border-green-500 ring-green-500',
label: 'text-green-500',
searchFocus: 'focus:border-green-500',
selected: 'bg-green-50 text-green-600',
hover: 'hover:border-green-500',
},
error: {
focus: 'border-red-500 ring-red-500',
label: 'text-red-500',
searchFocus: 'focus:border-red-500',
selected: 'bg-red-50 text-red-600',
hover: 'hover:border-red-500',
},
warning: {
focus: 'border-yellow-500 ring-yellow-500',
label: 'text-yellow-500',
searchFocus: 'focus:border-yellow-500',
selected: 'bg-yellow-50 text-yellow-600',
hover: 'hover:border-yellow-500',
},
info: {
focus: 'border-cyan-500 ring-cyan-500',
label: 'text-cyan-500',
searchFocus: 'focus:border-cyan-500',
selected: 'bg-cyan-50 text-cyan-600',
hover: 'hover:border-cyan-500',
},
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Spinner style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type SpinnerSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl'
export type SpinnerVariant = 'primary' | 'secondary' | 'white' | 'success' | 'danger' | 'warning'
export const SPINNER_SIZES: Record<SpinnerSize, string> = {
xs: 'w-4 h-4 border-2',
sm: 'w-5 h-5 border-2',
md: 'w-8 h-8 border-4',
lg: 'w-12 h-12 border-4',
xl: 'w-16 h-16 border-4',
}
export const SPINNER_VARIANTS: Record<SpinnerVariant, string> = {
primary: 'border-gray-200 border-t-primary-500',
secondary: 'border-gray-200 border-t-secondary-500',
white: 'border-white/30 border-t-white',
success: 'border-green-200 border-t-green-500',
danger: 'border-red-200 border-t-red-500',
warning: 'border-yellow-200 border-t-yellow-500',
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Switch style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type SwitchSize = 'sm' | 'md' | 'lg'
export type SwitchColor = 'blue' | 'red' | 'green' | 'yellow' | 'teal' | 'indigo' | 'purple' | 'pink'
export type SwitchSizeData = {
/** Track pill. */
toggle: string
/** Knob, including its resting offset from the track edge. */
dot: string
/** Travel distance of the knob when checked. */
translate: string
}
/**
* Every knob sits on a fixed 0.25rem inset from the track edge, so it can never
* render outside the pill. Travel = trackWidth - knobWidth - (2 * inset).
*/
export const SWITCH_SIZES: Record<SwitchSize, SwitchSizeData> = {
sm: { toggle: 'w-10 h-6 shrink-0', dot: 'w-4 h-4 left-1', translate: 'translate-x-4' },
md: { toggle: 'w-12 h-7 shrink-0', dot: 'w-5 h-5 left-1', translate: 'translate-x-5' },
lg: { toggle: 'w-[3.75rem] h-8 shrink-0', dot: 'w-6 h-6 left-1', translate: 'translate-x-7' },
}
export const SWITCH_COLORS: Record<SwitchColor, string> = {
blue: 'bg-primary-500',
red: 'bg-red-500',
green: 'bg-green-500',
yellow: 'bg-yellow-500',
teal: 'bg-teal-500',
indigo: 'bg-indigo-500',
purple: 'bg-purple-500',
pink: 'bg-pink-500',
}
+50
View File
@@ -0,0 +1,50 @@
/**
* TextArea style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type TextAreaSize = 'sm' | 'md' | 'lg'
export type TextAreaTheme = 'primary' | 'secondary' | 'success' | 'error' | 'warning' | 'info'
export const TEXTAREA_SIZES: Record<TextAreaSize, string> = {
sm: 'px-3 py-1 text-xs',
md: 'px-4 py-2 text-sm',
lg: 'px-5 py-3 text-base',
}
export const LABEL_SIZES: Record<TextAreaSize, string> = {
sm: 'text-[0.7rem] font-medium leading-loose',
md: 'text-[0.8rem] font-medium leading-loose',
lg: 'text-base font-medium leading-loose',
}
/** Type size for the label once it has floated above the border. */
export const FLOATING_LABEL_SIZES: Record<TextAreaSize, string> = {
sm: 'text-[0.6rem]',
md: 'text-[0.65rem]',
lg: 'text-xs',
}
export const TEXTAREA_THEMES: Record<TextAreaTheme, string> = {
primary: 'focus:border-primary-500 focus:ring-primary-500 border-slate-300',
secondary: 'focus:border-purple-500 focus:ring-purple-500 border-slate-300',
success: 'focus:border-green-500 focus:ring-green-500 border-slate-300',
warning: 'focus:border-yellow-500 focus:ring-yellow-500 border-slate-300',
info: 'focus:border-cyan-500 focus:ring-cyan-500 border-slate-300',
error: 'focus:border-red-500 focus:ring-red-500 border-red-500',
}
/**
* Extra top padding applied to a `featured` TextArea once its label floats.
*
* Without it the floated label (which sits just above the top border) overlaps
* the first line of text. Present as a token so the correction is visible
* rather than buried in the class list.
*/
export const FLOATING_CONTENT_PADDING: Record<TextAreaSize, string> = {
sm: 'pt-5',
md: 'pt-6',
lg: 'pt-7',
}
+166
View File
@@ -0,0 +1,166 @@
/**
* Tooltip style tokens.
*
* Kept in a separate module from the component so the file only exports
* components — mixing the two breaks Vite's fast refresh.
*/
export type TooltipPosition =
| 'top'
| 'top-start'
| 'top-end'
| 'bottom'
| 'bottom-start'
| 'bottom-end'
| 'left'
| 'left-start'
| 'left-end'
| 'right'
| 'right-start'
| 'right-end'
export type TooltipTheme =
| 'custom'
| 'soft'
| 'primary'
| 'success'
| 'danger'
| 'warning'
| 'info'
| 'light'
| 'dark'
| 'gradient'
export type TooltipSize = 'sm' | 'md' | 'lg'
export const TOOLTIP_COLORS: Record<TooltipTheme, string> = {
custom: 'text-white bg-primary-600',
soft: 'bg-primary-200 text-primary-900',
primary: 'bg-primary-500 text-white',
success: 'bg-green-500 text-white',
danger: 'bg-red-500 text-white',
warning: 'bg-yellow-500 text-white',
info: 'bg-cyan-500 text-white',
light: 'bg-gray-200 text-gray-900 border-2',
dark: 'bg-gray-800 text-white',
gradient: 'bg-gradient-to-b from-purple-400 to-red-500 text-white',
}
type ArrowSet = Record<TooltipTheme, string>
const topArrows: ArrowSet = {
custom: 'border-t-primary-600',
soft: 'border-t-primary-200',
primary: 'border-t-primary-500',
success: 'border-t-green-500',
danger: 'border-t-red-500',
warning: 'border-t-yellow-500',
info: 'border-t-cyan-500',
light: 'border-t-gray-200',
dark: 'border-t-gray-800',
gradient: 'border-t-red-500',
}
const bottomArrows: ArrowSet = {
custom: 'border-b-primary-600',
soft: 'border-b-primary-200',
primary: 'border-b-primary-500',
success: 'border-b-green-500',
danger: 'border-b-red-500',
warning: 'border-b-yellow-500',
info: 'border-b-cyan-500',
light: 'border-b-gray-200',
dark: 'border-b-gray-800',
gradient: 'border-b-purple-400',
}
const rightArrows: ArrowSet = {
custom: 'border-r-primary-600',
soft: 'border-r-primary-200',
primary: 'border-r-primary-500',
success: 'border-r-green-500',
danger: 'border-r-red-500',
warning: 'border-r-yellow-500',
info: 'border-r-cyan-500',
light: 'border-r-gray-200',
dark: 'border-r-gray-800',
gradient: 'border-r-red-500',
}
const leftArrows: ArrowSet = {
custom: 'border-l-primary-600',
soft: 'border-l-primary-200',
primary: 'border-l-primary-500',
success: 'border-l-green-500',
danger: 'border-l-red-500',
warning: 'border-l-yellow-500',
info: 'border-l-cyan-500',
light: 'border-l-gray-200',
dark: 'border-l-gray-800',
gradient: 'border-l-red-500',
}
export const ARROW_POSITION_COLORS: Record<TooltipPosition, ArrowSet> = {
top: topArrows,
'top-start': topArrows,
'top-end': topArrows,
bottom: bottomArrows,
'bottom-start': bottomArrows,
'bottom-end': bottomArrows,
right: rightArrows,
'right-start': rightArrows,
'right-end': rightArrows,
left: leftArrows,
'left-start': leftArrows,
'left-end': leftArrows,
}
export const BASE_ARROW_CLASSES: Record<TooltipPosition, string> = {
top: 'absolute left-1/2 bottom-0 -translate-x-1/2 translate-y-full border-l-4 border-r-4 border-t-4 border-transparent',
'top-start': 'absolute left-4 bottom-0 translate-y-full border-l-4 border-r-4 border-t-4 border-transparent',
'top-end': 'absolute left-4 bottom-0 translate-y-full border-l-4 border-r-4 border-t-4 border-transparent',
bottom: 'absolute left-1/2 top-0 -translate-x-1/2 -translate-y-full border-l-4 border-r-4 border-b-4 border-transparent',
'bottom-start': 'absolute left-4 top-0 -translate-y-full border-l-4 border-r-4 border-b-4 border-transparent',
'bottom-end': 'absolute right-4 top-0 -translate-y-full border-l-4 border-r-4 border-b-4 border-transparent',
left: 'absolute right-0 top-1/2 -translate-y-1/2 translate-x-full border-t-4 border-b-4 border-l-4 border-transparent',
'left-start': 'absolute top-4 left-full bottom-2 mr-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
'left-end': 'absolute left-full bottom-4 mr-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
right: 'absolute left-0 top-1/2 -translate-y-1/2 -translate-x-full border-t-4 border-b-4 border-r-4 border-transparent',
'right-start': 'absolute right-full top-2 ml-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
'right-end': 'absolute right-full bottom-2 ml-2 w-0 h-0 border-t-4 border-l-4 border-r-4 border-b-4 border-transparent',
}
/** Wider arrow used behind rich (node) content. */
export const BASE_ARROW_CLASSES_OUTER: Record<TooltipPosition, string> = {
top: 'absolute left-1/2 bottom-0 -translate-x-1/2 translate-y-full border-l-8 border-r-8 border-t-8 border-transparent',
'top-start': 'absolute left-3 bottom-0 translate-y-full border-l-8 border-r-8 border-t-8 border-transparent',
'top-end': 'absolute left-3 bottom-0 translate-y-full border-l-8 border-r-8 border-t-8 border-transparent',
bottom: 'absolute left-1/2 top-0 -translate-x-1/2 -translate-y-full border-l-8 border-r-8 border-b-8 border-transparent',
'bottom-start': 'absolute left-3 top-0 -translate-y-full border-l-8 border-r-8 border-b-8 border-transparent',
'bottom-end': 'absolute right-3 top-0 -translate-y-full border-l-8 border-r-8 border-b-8 border-transparent',
left: 'absolute right-0 top-1/2 -translate-y-1/2 translate-x-full border-t-8 border-b-8 border-l-8 border-transparent',
'left-start': 'absolute top-3 left-full bottom-1 mr-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
'left-end': 'absolute left-full bottom-3 mr-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
right: 'absolute left-0 top-1/2 -translate-y-1/2 -translate-x-full border-t-8 border-b-8 border-r-8 border-transparent',
'right-start': 'absolute right-full top-1 ml-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
'right-end': 'absolute right-full bottom-1 ml-2 w-0 h-0 border-t-8 border-l-8 border-r-8 border-b-8 border-transparent',
}
export const WHITE_BORDER_MAP = {
t: 'border-t-white',
b: 'border-b-white',
l: 'border-l-white',
r: 'border-r-white',
}
export const TOOLTIP_SIZES: Record<TooltipSize, string> = {
sm: 'text-xs px-2 py-1',
md: 'text-sm px-3 py-1.5',
lg: 'text-base px-4 py-2',
}
+154
View File
@@ -0,0 +1,154 @@
/**
* The component catalogue shown on the landing page.
*
* `documentation` and `storyCounts` are regenerated from the built Storybook
* index by `scripts/gen_catalogue.py --patch`; edit the generator's tables,
* not these blocks. `featuredNames` is hand-picked and left alone.
*/
export type CatalogueEntry = {
number: string
group: string
name: string
detail: string
href: string
}
export const documentation: CatalogueEntry[] = [
{
number: '01',
group: 'Actions',
name: 'Button',
detail: 'Variants · sizes · disabled',
href: '/docs/?path=/docs/actions-button--documentation',
},
{
number: '02',
group: 'Navigation',
name: 'Accordion',
detail: 'Disclosure · multiple',
href: '/docs/?path=/docs/navigation-accordion--documentation',
},
{
number: '03',
group: 'Data entry',
name: 'Text field',
detail: 'Labels · hints · errors',
href: '/docs/?path=/docs/data-entry-text-field--documentation',
},
{
number: '04',
group: 'Forms',
name: 'Input',
detail: 'Plain · themed · icon slot',
href: '/docs/?path=/docs/forms-input--documentation',
},
{
number: '05',
group: 'Forms',
name: 'FeaturedInput',
detail: 'Floating label · password · number',
href: '/docs/?path=/docs/forms-featuredinput--documentation',
},
{
number: '06',
group: 'Forms',
name: 'Select',
detail: 'Searchable · featured · async',
href: '/docs/?path=/docs/forms-select--documentation',
},
{
number: '07',
group: 'Forms',
name: 'Checkbox',
detail: 'Themes · tooltip · uncontrolled',
href: '/docs/?path=/docs/forms-checkbox--documentation',
},
{
number: '08',
group: 'Forms',
name: 'Radio',
detail: 'Themes · horizontal · required',
href: '/docs/?path=/docs/forms-radio--documentation',
},
{
number: '09',
group: 'Forms',
name: 'Switch',
detail: 'Themes · required · described',
href: '/docs/?path=/docs/forms-switch--documentation',
},
{
number: '10',
group: 'Forms',
name: 'TextArea',
detail: 'Resize · featured · prefilled',
href: '/docs/?path=/docs/forms-textarea--documentation',
},
{
number: '11',
group: 'Feedback',
name: 'Alert',
detail: 'Variants · colors · auto-close',
href: '/docs/?path=/docs/feedback-alert--documentation',
},
{
number: '12',
group: 'Feedback',
name: 'Spinner',
detail: 'Sizes · variants · dark',
href: '/docs/?path=/docs/feedback-spinner--documentation',
},
{
number: '13',
group: 'Display',
name: 'Badge',
detail: 'Colors · floating · pulse',
href: '/docs/?path=/docs/display-badge--documentation',
},
{
number: '14',
group: 'Layout',
name: 'Card',
detail: 'Themes · shadows · horizontal',
href: '/docs/?path=/docs/layout-card--documentation',
},
{
number: '15',
group: 'Overlays',
name: 'Tooltip',
detail: 'Positions · rich content · sizes',
href: '/docs/?path=/docs/overlays-tooltip--documentation',
},
]
export const storyCounts: Record<string, number> = {
Button: 6,
Accordion: 3,
'Text field': 3,
Input: 10,
FeaturedInput: 10,
Select: 17,
Checkbox: 10,
Radio: 9,
Switch: 10,
TextArea: 14,
Alert: 7,
Spinner: 5,
Badge: 8,
Card: 6,
Tooltip: 9,
}
export const totalStories = Object.values(storyCounts).reduce((sum, n) => sum + n, 0)
/** The five parts the hero shows. Each has a live preview in App.tsx. */
export const featuredNames = ['Button', 'Switch', 'Checkbox', 'Badge', 'Tooltip'] as const
export type FeaturedName = (typeof featuredNames)[number]
export const featured = featuredNames.map((name) => {
const entry = documentation.find((item) => item.name === name)
if (!entry) throw new Error(`Featured component "${name}" is missing from the catalogue`)
return { ...entry, name, stories: storyCounts[name] ?? 0 }
})
+696
View File
@@ -0,0 +1,696 @@
@import "tailwindcss";
@theme {
--font-sans: "Instrument Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
--font-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", monospace;
--font-display: "Schibsted Grotesk", "Instrument Sans", "Helvetica Neue", Arial, sans-serif;
--shadow-doc: 0 18px 46px -34px rgba(23, 25, 29, 0.38);
/* ------------------------------------------------------------------
Palette token registration.
Tailwind v4 only *generates* a utility class if its colour token is
declared here. The ported components reference `bg-primary-500`,
`text-primary-600`, `border-zink-700` and so on; without these
declarations the build silently emits no rules and those elements
render with no colour at all.
The values below are the Classic Blue defaults. They exist so the
utility classes are generated at build time. The Storybook palette
switcher overrides them at runtime on a wrapper element (see
src/theme/applyPalette.ts), which re-themes without a rebuild.
------------------------------------------------------------------ */
--color-primary-50: #eff6ff;
--color-primary-100: #dbeafe;
--color-primary-200: #bfdbfe;
--color-primary-300: #93c5fd;
--color-primary-400: #60a5fa;
--color-primary-500: #305ddd;
--color-primary-600: #274bc4;
--color-primary-700: #1e3a8a;
--color-primary-800: #1e40af;
--color-primary-900: #1e3a8a;
--color-primary: #305ddd;
--color-secondary-50: #f5f3ff;
--color-secondary-100: #ede9fe;
--color-secondary-200: #ddd6fe;
--color-secondary-300: #c4b5fd;
--color-secondary-400: #a78bfa;
--color-secondary-500: #8b5cf6;
--color-secondary-600: #7c3aed;
--color-secondary-700: #6d28d9;
--color-secondary-800: #5b21b6;
--color-secondary-900: #4c1d95;
--color-secondary: #8b5cf6;
--color-zink-50: #f8f8f9;
--color-zink-100: #f1f2f3;
--color-zink-200: #e4e6e8;
--color-zink-300: #cfd3d6;
--color-zink-400: #9aa2a9;
--color-zink-500: #6b7680;
--color-zink-600: #4d5761;
--color-zink-700: #313a43;
--color-zink-800: #1f262c;
--color-zink-900: #12171b;
--color-zink: #6b7680;
/* Semantic colours used by Alert, Badge and the status components. */
--color-success: #10b981;
--color-warning: #f59e0b;
--color-error: #ef4444;
--color-info: #3b82f6;
--color-danger: #ef4444;
}
/* ------------------------------------------------------------------
Tansy UI landing page.
Page neutrals are cool greys biased toward the blue default. The
accent is never a literal: it reads the live palette ramp, so the
picker in the playground re-themes the page chrome with the parts.
------------------------------------------------------------------ */
:root {
--canvas: #f3f4f6;
--surface: #ffffff;
--surface-sunk: #eceef2;
--ink: #12151c;
--ink-soft: #4a5162;
--ink-muted: #6b7384;
--line: #dde1e8;
--line-strong: #c5cad4;
}
@layer base {
* {
box-sizing: border-box;
}
html {
background: var(--canvas);
scroll-behavior: smooth;
scroll-padding-top: 5rem;
}
body {
margin: 0;
min-height: 100vh;
background: var(--canvas);
color: var(--ink);
font-family: var(--font-sans);
font-size: 1rem;
line-height: 1.6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
}
button,
input,
select,
textarea {
font: inherit;
}
a {
color: inherit;
text-decoration: none;
-webkit-tap-highlight-color: transparent;
}
:focus-visible {
outline: 2px solid var(--color-primary-500);
outline-offset: 3px;
}
::selection {
color: #ffffff;
background: var(--color-primary-500);
}
}
/* Aliases are declared on the shell, where applyPalette writes the ramp, so
they resolve against the live palette instead of the :root defaults. */
.site-shell {
--accent: var(--color-primary-500);
--accent-strong: var(--color-primary-700);
--accent-soft: var(--color-primary-50);
--accent-line: var(--color-primary-200);
min-height: 100vh;
overflow-x: clip;
}
.container {
width: min(100%, 72rem);
margin-inline: auto;
padding-inline: 1.25rem;
}
.kicker,
.eyebrow {
margin: 0;
font-family: var(--font-mono);
font-size: 0.75rem;
font-weight: 500;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--accent);
}
h1,
h2,
h3 {
margin: 0;
font-family: var(--font-display);
color: var(--ink);
text-wrap: balance;
}
code {
font-family: var(--font-mono);
font-size: 0.8125rem;
}
/* ---------- Header ---------- */
.site-header {
position: sticky;
top: 0;
z-index: 20;
border-bottom: 1px solid var(--line);
background: color-mix(in srgb, var(--canvas) 88%, transparent);
backdrop-filter: blur(10px);
}
.header-inner {
display: flex;
align-items: center;
gap: 2rem;
min-height: 4rem;
}
.brand {
display: inline-flex;
align-items: center;
gap: 0.55rem;
}
.brand-name {
font-family: var(--font-display);
font-size: 1.3rem;
font-weight: 800;
letter-spacing: -0.03em;
}
.brand-ui {
margin-left: 0.22em;
font-weight: 700;
color: var(--ink-muted);
}
.brand-by {
padding-left: 0.6rem;
border-left: 1px solid var(--line-strong);
font-size: 0.8125rem;
color: var(--ink-muted);
}
.header-nav {
display: flex;
gap: 1.5rem;
margin-left: auto;
font-size: 0.875rem;
font-weight: 500;
color: var(--ink-soft);
}
.header-nav a:hover {
color: var(--ink);
}
/* ---------- Hero ---------- */
.hero {
display: grid;
grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr);
align-items: center;
gap: 4rem;
padding-block: 4.5rem 5rem;
}
.hero-copy {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.eyebrow {
display: flex;
flex-wrap: wrap;
gap: 0.35rem 0.9rem;
}
.eyebrow-dim {
color: var(--ink-muted);
font-variant-numeric: tabular-nums;
}
.hero-copy h1 {
font-size: clamp(2.75rem, 6vw, 4.6rem);
font-weight: 800;
line-height: 0.98;
letter-spacing: -0.045em;
}
.hero-copy h1 em {
font-style: normal;
color: var(--accent);
}
.lede {
max-width: 34rem;
margin: 0;
font-size: 1.125rem;
color: var(--ink-soft);
}
.hero-actions {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
}
.stack {
margin: 0;
font-family: var(--font-mono);
font-size: 0.75rem;
color: var(--ink-muted);
}
/* The featured card is a Tansy Card; these classes tune its slots. */
.featured-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.25rem;
}
.featured-header h2 {
font-size: 1rem;
font-weight: 700;
letter-spacing: -0.01em;
}
.featured-body {
padding: 0;
}
.featured-list {
margin: 0;
padding: 0;
list-style: none;
}
.featured-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
min-height: 4.25rem;
padding: 0.75rem 1.25rem;
border-bottom: 1px solid var(--line);
}
.featured-row:last-child {
border-bottom: 0;
}
.featured-text {
display: flex;
flex-direction: column;
min-width: 0;
}
.featured-text a {
width: fit-content;
font-family: var(--font-display);
font-size: 1rem;
font-weight: 700;
color: var(--ink);
}
.featured-text a:hover {
color: var(--accent);
text-decoration: underline;
text-underline-offset: 3px;
}
.featured-text span {
font-size: 0.8125rem;
color: var(--ink-muted);
}
.featured-preview {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: flex-end;
}
.preview-badges {
display: inline-flex;
gap: 0.375rem;
}
.featured-footer {
padding: 1rem 1.25rem;
}
/* ---------- Playground ---------- */
.playground {
padding-block: 5rem;
border-block: 1px solid var(--line);
background: var(--surface-sunk);
}
.playground-grid {
display: grid;
grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr);
align-items: start;
gap: 4rem;
}
.playground-intro {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.playground-intro h2,
.principles-head h2 {
font-size: clamp(1.75rem, 3.2vw, 2.4rem);
font-weight: 800;
line-height: 1.08;
letter-spacing: -0.035em;
}
.playground-intro > p:not(.kicker) {
max-width: 30rem;
margin: 0;
color: var(--ink-soft);
}
.palette-picker {
margin: 0.5rem 0 0;
padding: 0;
border: 0;
}
.palette-picker legend {
margin-bottom: 0.6rem;
font-size: 0.8125rem;
font-weight: 600;
color: var(--ink);
}
.palette-options {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.palette-options button {
display: inline-flex;
align-items: center;
gap: 0.45rem;
min-height: 2.25rem;
padding: 0 0.8rem 0 0.55rem;
border: 1px solid var(--line-strong);
border-radius: 999px;
background: var(--surface);
font-size: 0.8125rem;
font-weight: 500;
color: var(--ink-soft);
cursor: pointer;
transition: border-color 150ms, color 150ms;
}
.palette-options button:hover {
border-color: var(--ink-muted);
color: var(--ink);
}
.palette-options button[aria-pressed="true"] {
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent);
color: var(--ink);
}
.swatch {
width: 0.85rem;
height: 0.85rem;
border-radius: 999px;
}
.palette-note {
min-height: 1.5em;
margin: 0.6rem 0 0;
font-size: 0.8125rem;
color: var(--ink-muted);
}
.ramp {
display: grid;
grid-template-columns: repeat(10, minmax(0, 1fr));
gap: 0.25rem;
}
.ramp-step {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.ramp-chip {
height: 2.5rem;
border-radius: 0.3rem;
box-shadow: inset 0 0 0 1px rgb(18 21 28 / 0.06);
transition: background-color 250ms;
}
.ramp-label {
font-family: var(--font-mono);
font-size: 0.6875rem;
text-align: center;
color: var(--ink-muted);
font-variant-numeric: tabular-nums;
}
.ramp-caption {
margin: -0.5rem 0 0;
font-size: 0.8125rem;
color: var(--ink-muted);
}
.ramp-caption code {
color: var(--ink);
}
/* The form is a Tansy Card; these classes lay out its slots. */
.employee-card-header {
display: flex;
flex-direction: column;
gap: 0.35rem;
padding: 1.25rem 1.5rem;
}
.employee-card-header p {
margin: 0;
font-size: 0.875rem;
font-weight: 400;
color: var(--ink-muted);
}
.employee-card-body {
display: flex;
flex-direction: column;
gap: 1.35rem;
padding: 1.5rem;
}
.form-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1rem;
}
.employee-card-footer {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
padding: 1rem 1.5rem;
}
/* ---------- Principles ---------- */
.principles {
display: flex;
flex-direction: column;
gap: 2.5rem;
padding-block: 5rem;
}
.principles-head {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.principle-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 2.5rem;
}
.principle {
display: flex;
flex-direction: column;
gap: 0.6rem;
padding-top: 1.25rem;
border-top: 2px solid var(--ink);
}
.principle h3 {
font-size: 1.125rem;
font-weight: 700;
letter-spacing: -0.015em;
}
.principle p {
margin: 0;
flex: 1;
color: var(--ink-soft);
}
.principle code {
width: fit-content;
padding: 0.2rem 0.5rem;
border-radius: 0.3rem;
background: var(--accent-soft);
color: var(--accent-strong);
}
/* ---------- Footer ---------- */
.site-footer {
border-top: 1px solid var(--line);
background: var(--surface);
}
.footer-inner {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding-block: 1.75rem;
font-size: 0.875rem;
color: var(--ink-soft);
}
.footer-brand {
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
.footer-brand strong {
font-family: var(--font-display);
color: var(--ink);
}
.footer-nav {
display: flex;
gap: 1.25rem;
}
.footer-nav a:hover {
color: var(--ink);
}
/* ---------- Responsive ---------- */
@media (max-width: 960px) {
.hero,
.playground-grid {
grid-template-columns: minmax(0, 1fr);
gap: 3rem;
}
.hero {
padding-block: 3rem 4rem;
}
.principle-grid {
grid-template-columns: minmax(0, 1fr);
gap: 2rem;
}
}
@media (max-width: 640px) {
.container {
padding-inline: 1rem;
}
.header-inner {
gap: 1rem;
}
.header-nav,
.brand-ui {
margin-left: 0.22em;
font-weight: 700;
color: var(--ink-muted);
}
.brand-by {
display: none;
}
.header-cta {
margin-left: auto;
}
.form-row {
grid-template-columns: minmax(0, 1fr);
}
.playground,
.principles {
padding-block: 3.5rem;
}
.employee-card-body,
.employee-card-header,
.employee-card-footer {
padding-inline: 1.1rem;
}
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
/**
* Merge Tailwind class names safely.
*
* Ported verbatim in behaviour from the source app's
* `src/common/utils/classNames.js`, which every component imports. `clsx`
* handles conditional/array/object inputs; `twMerge` resolves conflicts so the
* last utility wins (e.g. `cn('px-2', 'px-4')` yields `px-4`).
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs))
}
+16
View File
@@ -0,0 +1,16 @@
/**
* Omit specific keys from an object.
*
* Ported from the source app's `src/common/utils/omit.js`, used by form
* components to strip internal-only props (form-library plumbing) before
* spreading the rest onto the DOM node.
*/
export function omit<T extends object, K extends keyof T>(
obj: T | null | undefined,
keys: readonly (K | string)[],
): Omit<T, K> {
if (!obj) return {} as Omit<T, K>
return Object.fromEntries(
Object.entries(obj).filter(([k]) => !keys.includes(k)),
) as Omit<T, K>
}
+29
View File
@@ -0,0 +1,29 @@
import { useEffect, type RefObject } from 'react'
/**
* Fire `callback` when a mousedown lands outside every one of `elements`.
*
* Ported from the source app's `Select/hooks/useClickOutside`.
* The dropdown is portalled to `document.body`, so both the control and the
* dropdown panel are passed in — checking one alone would close the menu the
* instant you clicked inside it.
*/
export function useClickOutside(
elements: RefObject<HTMLElement | null>[],
callback: (event: MouseEvent) => void,
enabled = true,
): void {
useEffect(() => {
if (!enabled) return
const handleClickOutside = (event: MouseEvent) => {
const isOutside = elements.every(
(ref) => !ref.current || !ref.current.contains(event.target as Node),
)
if (isOutside) callback(event)
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [elements, callback, enabled])
}
+101
View File
@@ -0,0 +1,101 @@
import { useCallback, useEffect, useState, type RefObject } from 'react'
export type DropdownPlacement = 'auto' | 'up' | 'down'
export type DropdownPosition = {
top?: number
bottom?: number
left: number
width: number
maxHeight: string
}
const STANDARD_MAX_HEIGHT = 240
const BUFFER = 12
/**
* Fixed-position coordinates for a portalled dropdown.
*
* Ported from the source app's `useDropdownPosition`. The menu is rendered into
* `document.body` so it escapes any `overflow: hidden` ancestor, which means its
* position has to be measured rather than flowed.
*
* `placement: 'auto'` opens upward when there is not enough room below and more
* room above.
*/
export function useDropdownPosition(
isOpen: boolean,
containerRef: RefObject<HTMLElement | null>,
options: { placement?: DropdownPlacement } = {},
): {
dropdownPosition: DropdownPosition
calculateInitialPosition: () => void
} {
const { placement = 'auto' } = options
const [dropdownPosition, setDropdownPosition] = useState<DropdownPosition>({
left: 0,
width: 0,
maxHeight: `${STANDARD_MAX_HEIGHT}px`,
})
const measure = useCallback(() => {
const node = containerRef.current
if (!node) return
const rect = node.getBoundingClientRect()
const spaceAbove = rect.top
const spaceBelow = window.innerHeight - rect.bottom
const shouldOpenUp =
placement === 'up' ||
(placement === 'auto' &&
spaceBelow < STANDARD_MAX_HEIGHT + BUFFER &&
spaceAbove > spaceBelow)
if (shouldOpenUp) {
const available = Math.max(spaceAbove - BUFFER, 50)
setDropdownPosition({
bottom: window.innerHeight - rect.top + 4,
left: rect.left,
width: rect.width,
maxHeight: `${Math.min(STANDARD_MAX_HEIGHT, available)}px`,
})
} else {
const available = Math.max(spaceBelow - BUFFER, 50)
setDropdownPosition({
top: rect.bottom + 4,
left: rect.left,
width: rect.width,
maxHeight: `${Math.min(STANDARD_MAX_HEIGHT, available)}px`,
})
}
}, [containerRef, placement])
/**
* Measure on a frame boundary, not synchronously.
*
* The panel is portalled to `document.body` and the control's ref is not yet
* attached at the moment the dropdown is switched on, so a synchronous read
* gets nothing and leaves the panel at its zero-initialised position —
* rendered off-screen at `left: 0; width: 0` while every DOM query still
* "succeeds". Measuring after layout also picks up a control that moves
* between the click and the paint.
*/
const calculateInitialPosition = useCallback(() => {
requestAnimationFrame(() => measure())
}, [measure])
useEffect(() => {
if (!isOpen) return
const reposition = () => measure()
reposition()
window.addEventListener('resize', reposition)
window.addEventListener('scroll', reposition, true)
return () => {
window.removeEventListener('resize', reposition)
window.removeEventListener('scroll', reposition, true)
}
}, [isOpen, measure])
return { dropdownPosition, calculateInitialPosition }
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+41
View File
@@ -0,0 +1,41 @@
import { palettes, DEFAULT_PALETTE, type PaletteName, type Ramp } from './palettes'
/** Emits one family as `--color-<name>-<step>` plus the bare `--color-<name>`. */
function rampVars(prefix: string, ramp: Ramp): Record<string, string> {
const vars: Record<string, string> = {}
for (const [step, value] of Object.entries(ramp)) {
vars[`--color-${prefix}-${step}`] = value
}
// Bare alias so `bg-primary` / `text-gray` resolve to the mid step.
vars[`--color-${prefix}`] = ramp[500]
return vars
}
/**
* Applies a brand palette by writing the `--color-*` custom properties that
* Tailwind v4's `@theme` reads.
*
* The ported components were written against `bg-primary-500`,
* `text-primary-600`, `border-primary` and friends. Those utilities do not
* resolve unless the matching custom properties are in scope, which is why an
* unthemed copy of those files renders black. Writing them on a wrapper element
* scopes the palette to one subtree, so a single canvas can show several at once.
*/
export function applyPalette(element: HTMLElement, palette: PaletteName): void {
const p = palettes[palette] ?? palettes[DEFAULT_PALETTE]
const props: Record<string, string> = {
...rampVars('primary', p.primary),
...rampVars('secondary', p.secondary),
...rampVars('gray', p.gray),
...rampVars('zink', p.zink),
}
for (const [name, value] of Object.entries(p.semantic)) {
props[`--color-${name}`] = value
}
for (const [key, value] of Object.entries(props)) {
element.style.setProperty(key, value)
}
}
+421
View File
@@ -0,0 +1,421 @@
/**
* Brand palettes for Tansy UI.
*
* Each palette defines the full token set the ported components rely on.
* The component code references these utility names, so swapping a palette
* re-themes every element in the canvas with no code change.
*
* Why the scale is deliberately wider than the source app's own `@theme`:
* components reference `primary-200`, `primary-300`, `primary-400`,
* `primary-800` and `primary-900`, none of which that file defines — so those
* utilities silently fall back to nothing there. The full 50..900 ramp is
* defined here so every reference resolves.
*
* `zink` is a second neutral ramp used by dark-mode rules in several components
* (Accordion, and others that were ported before this file existed). It is also
* undefined in the source app, so it is provided here as a real scale rather
* than left as a dead class.
*/
export type PaletteName =
| 'classicBlue'
| 'emerald'
| 'violet'
| 'amber'
| 'crimson'
| 'slate'
| 'teal'
/** Full numeric ramp. Keys are the Tailwind step names. */
export type Ramp = Record<50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900, string>
export type SemanticColors = {
success: string
warning: string
error: string
info: string
danger: string
}
export type Palette = {
name: PaletteName
label: string
/** Short description of the mood this palette conveys. */
note: string
primary: Ramp
/** Secondary brand ramp, available as `bg-secondary-*`. */
secondary: Ramp
gray: Ramp
/** Neutral ramp used by dark-mode rules ported from the source app. */
zink: Ramp
semantic: SemanticColors
}
const NEUTRAL_RAMP: Ramp = {
50: '#f9fafb',
100: '#f3f4f6',
200: '#e5e7eb',
300: '#d1d5db',
400: '#9ca3af',
500: '#6b7280',
600: '#4b5563',
700: '#374151',
800: '#1f2937',
900: '#111827',
}
export const palettes: Record<PaletteName, Palette> = {
classicBlue: {
name: 'classicBlue',
label: 'Classic Blue',
note: 'The default palette. Trustworthy, neutral, enterprise.',
primary: {
50: '#eff6ff',
100: '#dbeafe',
200: '#bfdbfe',
300: '#93c5fd',
400: '#60a5fa',
500: '#305DDD',
600: '#274bc4',
700: '#1e3a8a',
800: '#1e40af',
900: '#1e3a8a',
},
secondary: {
50: '#f5f3ff',
100: '#ede9fe',
200: '#ddd6fe',
300: '#c4b5fd',
400: '#a78bfa',
500: '#8b5cf6',
600: '#7c3aed',
700: '#6d28d9',
800: '#5b21b6',
900: '#4c1d95',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#10b981',
warning: '#f59e0b',
error: '#ef4444',
info: '#3b82f6',
danger: '#ef4444',
},
},
emerald: {
name: 'emerald',
label: 'Emerald',
note: 'Growth and money. Calm greens for finance-forward products.',
primary: {
50: '#ecfdf5',
100: '#d1fae5',
200: '#a7f3d0',
300: '#6ee7b7',
400: '#34d399',
500: '#059669',
600: '#047857',
700: '#065f46',
800: '#064e3b',
900: '#022c22',
},
secondary: {
50: '#f0fdfa',
100: '#ccfbf1',
200: '#99f6e4',
300: '#5eead4',
400: '#2dd4bf',
500: '#0d9488',
600: '#0f766e',
700: '#115e59',
800: '#134e4a',
900: '#042f2e',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#059669',
warning: '#d97706',
error: '#dc2626',
info: '#0891b2',
danger: '#dc2626',
},
},
violet: {
name: 'violet',
label: 'Violet',
note: 'Premium and creative. Good for AI-adjacent or HR tooling.',
primary: {
50: '#f5f3ff',
100: '#ede9fe',
200: '#ddd6fe',
300: '#c4b5fd',
400: '#a78bfa',
500: '#7c3aed',
600: '#6d28d9',
700: '#5b21b6',
800: '#4c1d95',
900: '#3b0f70',
},
secondary: {
50: '#ecfeff',
100: '#cffafe',
200: '#a5f3fc',
300: '#67e8f9',
400: '#22d3ee',
500: '#06b6d4',
600: '#0891b2',
700: '#0e7490',
800: '#155e75',
900: '#164e63',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#10b981',
warning: '#f59e0b',
error: '#ef4444',
info: '#8b5cf6',
danger: '#ef4444',
},
},
amber: {
name: 'amber',
label: 'Amber',
note: 'Warm and energetic. Reads well on light surfaces only.',
primary: {
50: '#fffbeb',
100: '#fef3c7',
200: '#fde68a',
300: '#fcd34d',
400: '#fbbf24',
500: '#d97706',
600: '#b45309',
700: '#92400e',
800: '#78350f',
900: '#451a03',
},
secondary: {
50: '#fff7ed',
100: '#ffedd5',
200: '#fed7aa',
300: '#fdba74',
400: '#fb923c',
500: '#f97316',
600: '#ea580c',
700: '#c2410c',
800: '#9a3412',
900: '#7c2d12',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#65a30d',
warning: '#f59e0b',
error: '#dc2626',
info: '#0284c7',
danger: '#dc2626',
},
},
crimson: {
name: 'crimson',
label: 'Crimson',
note: 'Urgent and high-contrast. Use for compliance-heavy surfaces.',
primary: {
50: '#fef2f2',
100: '#fee2e2',
200: '#fecaca',
300: '#fca5a5',
400: '#f87171',
500: '#dc2626',
600: '#b91c1c',
700: '#991b1b',
800: '#7f1d1d',
900: '#450a0a',
},
secondary: {
50: '#fdf4ff',
100: '#fae8ff',
200: '#f5d0fe',
300: '#f0abfc',
400: '#e879f9',
500: '#d946ef',
600: '#c026d3',
700: '#a21caf',
800: '#86198f',
900: '#701a75',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#16a34a',
warning: '#f59e0b',
error: '#b91c1c',
info: '#0284c7',
danger: '#b91c1c',
},
},
slate: {
name: 'slate',
label: 'Slate',
note: 'Nearly monochrome. The most restrained option here.',
primary: {
50: '#f8fafc',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cbd5e1',
400: '#94a3b8',
500: '#475569',
600: '#334155',
700: '#1e293b',
800: '#172033',
900: '#0f172a',
},
secondary: {
50: '#f8fafc',
100: '#f1f5f9',
200: '#e2e8f0',
300: '#cbd5e1',
400: '#94a3b8',
500: '#64748b',
600: '#475569',
700: '#334155',
800: '#1e293b',
900: '#0f172a',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#10b981',
warning: '#f59e0b',
error: '#ef4444',
info: '#0ea5e9',
danger: '#ef4444',
},
},
teal: {
name: 'teal',
label: 'Teal',
note: 'Cool and clinical. Distinct from Classic Blue at a glance.',
primary: {
50: '#f0fdfa',
100: '#ccfbf1',
200: '#99f6e4',
300: '#5eead4',
400: '#2dd4bf',
500: '#0d9488',
600: '#0f766e',
700: '#115e59',
800: '#134e4a',
900: '#042f2e',
},
secondary: {
50: '#eff6ff',
100: '#dbeafe',
200: '#bfdbfe',
300: '#93c5fd',
400: '#60a5fa',
500: '#3b82f6',
600: '#2563eb',
700: '#1d4ed8',
800: '#1e40af',
900: '#1e3a8a',
},
gray: NEUTRAL_RAMP,
zink: {
50: '#f8f8f9',
100: '#f1f2f3',
200: '#e4e6e8',
300: '#cfd3d6',
400: '#9aa2a9',
500: '#6b7680',
600: '#4d5761',
700: '#313a43',
800: '#1f262c',
900: '#12171b',
},
semantic: {
success: '#0d9488',
warning: '#f59e0b',
error: '#ef4444',
info: '#0284c7',
danger: '#ef4444',
},
},
}
export const paletteNames = Object.keys(palettes) as PaletteName[]
export const DEFAULT_PALETTE: PaletteName = 'classicBlue'
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"paths": {
"@/*": ["./src/*"]
},
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+13
View File
@@ -0,0 +1,13 @@
import { fileURLToPath, URL } from 'node:url'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})