From 70833c2088126d9e949cf7683ab5902cb2e7faef Mon Sep 17 00:00:00 2001 From: cunoe Date: Sat, 14 Nov 2026 17:13:36 -0800 Subject: [PATCH 1/8] feat(ui): pin Arc source and define complete platform migration --- packages/docs/design/uiarc-decisions.tsv | 2 + packages/docs/design/uiarc-migration.md | 55 +++++ packages/uiarc/package.json | 23 ++ packages/uiarc/source.json | 213 ++++++++++++++++++ packages/uiarc/src/alert/alert.module.css | 15 ++ packages/uiarc/src/alert/alert.tsx | 109 +++++++++ packages/uiarc/src/avatar/avatar.module.css | 60 +++++ packages/uiarc/src/avatar/avatar.tsx | 21 ++ packages/uiarc/src/badge/badge.module.css | 104 +++++++++ packages/uiarc/src/badge/badge.tsx | 93 ++++++++ packages/uiarc/src/button/button.module.css | 39 ++++ packages/uiarc/src/button/button.tsx | 132 +++++++++++ packages/uiarc/src/card/card.module.css | 51 +++++ packages/uiarc/src/card/card.tsx | 198 ++++++++++++++++ .../uiarc/src/checkbox/checkbox.module.css | 15 ++ packages/uiarc/src/checkbox/checkbox.tsx | 44 ++++ packages/uiarc/src/dialog/dialog.module.css | 36 +++ packages/uiarc/src/dialog/dialog.tsx | 72 ++++++ packages/uiarc/src/drawer/drawer.module.css | 97 ++++++++ packages/uiarc/src/drawer/drawer.tsx | 200 ++++++++++++++++ .../src/empty-state/empty-state.module.css | 13 ++ .../uiarc/src/empty-state/empty-state.tsx | 88 ++++++++ packages/uiarc/src/foundation.css | 211 +++++++++++++++++ packages/uiarc/src/input/input.module.css | 22 ++ packages/uiarc/src/input/input.tsx | 85 +++++++ packages/uiarc/src/lib/arc-provider.tsx | 94 ++++++++ packages/uiarc/src/lib/motion-tokens.ts | 2 + packages/uiarc/src/motion-tokens.ts | 25 ++ packages/uiarc/src/popover/popover.module.css | 32 +++ packages/uiarc/src/popover/popover.tsx | 37 +++ .../uiarc/src/progress/progress.module.css | 1 + packages/uiarc/src/progress/progress.tsx | 60 +++++ .../src/scroll-area/scroll-area.module.css | 79 +++++++ .../uiarc/src/scroll-area/scroll-area.tsx | 197 ++++++++++++++++ .../segmented-control.module.css | 15 ++ .../segmented-control/segmented-control.tsx | 73 ++++++ packages/uiarc/src/select/select.module.css | 34 +++ packages/uiarc/src/select/select.tsx | 91 ++++++++ .../uiarc/src/skeleton/skeleton.module.css | 11 + packages/uiarc/src/skeleton/skeleton.tsx | 70 ++++++ packages/uiarc/src/switch/switch.module.css | 12 + packages/uiarc/src/switch/switch.tsx | 74 ++++++ packages/uiarc/src/tabs/tabs.module.css | 27 +++ packages/uiarc/src/tabs/tabs.tsx | 139 ++++++++++++ .../uiarc/src/textarea/textarea.module.css | 22 ++ packages/uiarc/src/textarea/textarea.tsx | 64 ++++++ packages/uiarc/src/toast/toast.module.css | 100 ++++++++ packages/uiarc/src/toast/toast.tsx | 155 +++++++++++++ packages/uiarc/src/tooltip/tooltip.module.css | 18 ++ packages/uiarc/src/tooltip/tooltip.tsx | 82 +++++++ scripts/vendor-uiarc.py | 82 +++++++ 51 files changed, 3594 insertions(+) create mode 100644 packages/docs/design/uiarc-decisions.tsv create mode 100644 packages/docs/design/uiarc-migration.md create mode 100644 packages/uiarc/package.json create mode 100644 packages/uiarc/source.json create mode 100644 packages/uiarc/src/alert/alert.module.css create mode 100644 packages/uiarc/src/alert/alert.tsx create mode 100644 packages/uiarc/src/avatar/avatar.module.css create mode 100644 packages/uiarc/src/avatar/avatar.tsx create mode 100644 packages/uiarc/src/badge/badge.module.css create mode 100644 packages/uiarc/src/badge/badge.tsx create mode 100644 packages/uiarc/src/button/button.module.css create mode 100644 packages/uiarc/src/button/button.tsx create mode 100644 packages/uiarc/src/card/card.module.css create mode 100644 packages/uiarc/src/card/card.tsx create mode 100644 packages/uiarc/src/checkbox/checkbox.module.css create mode 100644 packages/uiarc/src/checkbox/checkbox.tsx create mode 100644 packages/uiarc/src/dialog/dialog.module.css create mode 100644 packages/uiarc/src/dialog/dialog.tsx create mode 100644 packages/uiarc/src/drawer/drawer.module.css create mode 100644 packages/uiarc/src/drawer/drawer.tsx create mode 100644 packages/uiarc/src/empty-state/empty-state.module.css create mode 100644 packages/uiarc/src/empty-state/empty-state.tsx create mode 100644 packages/uiarc/src/foundation.css create mode 100644 packages/uiarc/src/input/input.module.css create mode 100644 packages/uiarc/src/input/input.tsx create mode 100644 packages/uiarc/src/lib/arc-provider.tsx create mode 100644 packages/uiarc/src/lib/motion-tokens.ts create mode 100644 packages/uiarc/src/motion-tokens.ts create mode 100644 packages/uiarc/src/popover/popover.module.css create mode 100644 packages/uiarc/src/popover/popover.tsx create mode 100644 packages/uiarc/src/progress/progress.module.css create mode 100644 packages/uiarc/src/progress/progress.tsx create mode 100644 packages/uiarc/src/scroll-area/scroll-area.module.css create mode 100644 packages/uiarc/src/scroll-area/scroll-area.tsx create mode 100644 packages/uiarc/src/segmented-control/segmented-control.module.css create mode 100644 packages/uiarc/src/segmented-control/segmented-control.tsx create mode 100644 packages/uiarc/src/select/select.module.css create mode 100644 packages/uiarc/src/select/select.tsx create mode 100644 packages/uiarc/src/skeleton/skeleton.module.css create mode 100644 packages/uiarc/src/skeleton/skeleton.tsx create mode 100644 packages/uiarc/src/switch/switch.module.css create mode 100644 packages/uiarc/src/switch/switch.tsx create mode 100644 packages/uiarc/src/tabs/tabs.module.css create mode 100644 packages/uiarc/src/tabs/tabs.tsx create mode 100644 packages/uiarc/src/textarea/textarea.module.css create mode 100644 packages/uiarc/src/textarea/textarea.tsx create mode 100644 packages/uiarc/src/toast/toast.module.css create mode 100644 packages/uiarc/src/toast/toast.tsx create mode 100644 packages/uiarc/src/tooltip/tooltip.module.css create mode 100644 packages/uiarc/src/tooltip/tooltip.tsx create mode 100644 scripts/vendor-uiarc.py diff --git a/packages/docs/design/uiarc-decisions.tsv b/packages/docs/design/uiarc-decisions.tsv new file mode 100644 index 00000000..a4150a85 --- /dev/null +++ b/packages/docs/design/uiarc-decisions.tsv @@ -0,0 +1,2 @@ +ts phase decision why evidence result +2026-11-15T01:13:15Z frame Pin Arc and preserve the complete Web and native product scope The user selected a single library for both platforms; the upstream provides DOM components, so native controls need explicit ports packages/docs/design/uiarc-migration.md; packages/uiarc/source.json implementation active diff --git a/packages/docs/design/uiarc-migration.md b/packages/docs/design/uiarc-migration.md new file mode 100644 index 00000000..726a6799 --- /dev/null +++ b/packages/docs/design/uiarc-migration.md @@ -0,0 +1,55 @@ +# Arc UI migration + +The Web workspace and native mobile app use the Arc design system from +[WheatXie/uiarc-pro-reverse](https://github.com/WheatXie/uiarc-pro-reverse), pinned to +`859606819c68787b2dccb54adcb9b08bd3272d5d`. + +## Completion requirements + +- Every existing Web and Mobile route keeps its product operations, copy, data and recovery behavior. +- Web controls use Arc source components and Arc product compositions. Remove the old shadcn components, configuration and dependencies. +- Mobile controls are native ports of named Arc items. Remove the React Native Reusables implementations and configuration. Do not use a WebView. +- Both apps derive colors, typography, radii, control sizes and motion from the pinned Arc foundation. Do not maintain another hand-written palette. +- Rewrite the navigation, chat, tasks, settings, devices, joining and recovery compositions in the same system. Updating imports or a theme alone does not finish this migration. +- A committed guard rejects old UI imports, dependencies and theme roles, and verifies vendored source and generated token integrity. +- Run the relevant behavior tests, type checks and production builds on the final source. Keep the complete Web output and the mobile build evidence reviewable. +- Open one new PR. Merge and release require separate user authorization. + +## Implementation boundaries + +`packages/uiarc/src` holds unmodified, pinned Web component sources. `source.json` records upstream paths and SHA-256 hashes. Acquire further items with `python3 scripts/vendor-uiarc.py /path/to/pinned/upstream item ...`. Product data, routing and callback integration belong to each app, outside vendored source. + +`packages/theme` derives the Web and native token files from Arc's `foundation.css` and motion tokens. Web uses Arc's `data-theme` attribute. Mobile resolves the same light and dark values to native-compatible colors. Layout utilities are allowed; they must not define a second component style or palette. + +Native ports live under `apps/mobile/src/components/arc`. Each port names its upstream item and preserves Arc's semantic tokens, state model, control sizing and motion. Keep platform navigation, safe areas, Dynamic Type, keyboard behavior, Back and accessibility announcements. + +Product components compose Arc controls with real Vibeface state. Arc's showcase blocks contain demonstration people, model lists and simulated work. Those fixtures must not enter product flows; extract their layout and visual rules into data-driven compositions instead. + +## Work plan + +1. Record the route, component, action and import census. Pin and acquire the source. +2. Replace the shared foundation and generate native tokens. Establish migration checks. +3. Rewrite Web controls, navigation and all route compositions. Remove the old Web layer. +4. Rewrite Mobile controls, navigation and all route compositions. Remove the old native layer. +5. Integrate both apps, run behavior and build checks, and review remaining migration gaps. +6. Update durable instructions and design records, then deliver one PR and build artifacts. + +The Web and Mobile implementation workstreams own separate app directories. The root owns shared packages, source provenance, the lockfile, policy, verification and integration. + +## Region mapping + +| Product region | Arc sources | Integration requirements | +| --- | --- | --- | +| Actions and fields | button, input, textarea, select, checkbox, switch, segmented-control | Preserve labels, validation, loading, disabled states and submitted values | +| Navigation | sidebar, tabs, drawer | Real routes, unread counts, connection state, responsive navigation | +| Conversation | ai-chat, ai-composer, chat-thread | Real messages, streaming, attachments, cancel, approvals and preserved scroll | +| Work and decisions | agent-run, agent-approvals, badge, progress | Real task state, accept/reject, stop, retry and unknown-result reconciliation | +| Settings and devices | settings and security blocks, card, dialog | Preserve device identities, AI configuration, permissions and destructive consequences | +| Joining and recovery | stepper, input, button, alert | Preserve scanning, paste, network choice, safe-code checks and recovery | +| Feedback | empty-state, skeleton, alert, toast | Product state, accessible labels and inline errors | + +## Verification constraints + +Project instructions reserve e2e tests, screenshots and UI acceptance runs for an explicit request. This migration uses existing behavior tests, targeted component checks, source audits and production builds. Do not claim visual or native-device verification from compilation alone. + +The baseline census is 17 Web route files and 27 native route files, including layouts. The initial dependency census includes 339 internal component imports. Counts may change as components are reorganized; product routes and actions remain the acceptance scope. diff --git a/packages/uiarc/package.json b/packages/uiarc/package.json new file mode 100644 index 00000000..112339ab --- /dev/null +++ b/packages/uiarc/package.json @@ -0,0 +1,23 @@ +{ + "name": "@vibeface/uiarc", + "private": true, + "type": "module", + "exports": { + "./*": "./src/*" + }, + "peerDependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0" + }, + "dependencies": { + "@radix-ui/react-checkbox": "^1.4.1", + "@radix-ui/react-dialog": "^1.3.1", + "@radix-ui/react-popover": "^1.3.1", + "@radix-ui/react-select": "^2.4.1", + "@radix-ui/react-switch": "^1.4.1", + "@radix-ui/react-tabs": "^1.2.1", + "@radix-ui/react-tooltip": "^1.4.1", + "lucide-react": "^1.69.0", + "motion": "^14.9.1" + } +} diff --git a/packages/uiarc/source.json b/packages/uiarc/source.json new file mode 100644 index 00000000..c0e249e0 --- /dev/null +++ b/packages/uiarc/source.json @@ -0,0 +1,213 @@ +{ + "repository": "https://github.com/WheatXie/uiarc-pro-reverse", + "commit": "859606819c68787b2dccb54adcb9b08bd3272d5d", + "items": [ + "alert", + "avatar", + "badge", + "button", + "card", + "checkbox", + "dialog", + "drawer", + "empty-state", + "input", + "popover", + "progress", + "scroll-area", + "segmented-control", + "select", + "skeleton", + "switch", + "tabs", + "textarea", + "toast", + "tooltip" + ], + "files": { + "alert/alert.module.css": { + "path": "src/components/arc/alert/alert.module.css", + "sha256": "ce86d259fa778a5b1a7e0881285759fa35889b6cde73ea678e26a49f3122d439" + }, + "alert/alert.tsx": { + "path": "src/components/arc/alert/alert.tsx", + "sha256": "ddcd481e2ebc6a1cbf6f053d6de1817d5dfd40b347e0bea561cc9fda2ea54950" + }, + "avatar/avatar.module.css": { + "path": "src/components/arc/avatar/avatar.module.css", + "sha256": "7a24bd77c83d3c14ac2c90905dc7d64eea7b60e8bf6eddd2e5d30dd6c96bd816" + }, + "avatar/avatar.tsx": { + "path": "src/components/arc/avatar/avatar.tsx", + "sha256": "94c22aa1f558a72d3dae928b35516fe182c296636cc8c24ea9fee194718e166c" + }, + "badge/badge.module.css": { + "path": "src/components/arc/badge/badge.module.css", + "sha256": "31709106e0035932ef72eafc7a035c24e468d314e6bb64c5d65efe4df907718c" + }, + "badge/badge.tsx": { + "path": "src/components/arc/badge/badge.tsx", + "sha256": "c0927a45e77f340acc01d24b7b95b6097f81a4f9c2ddf99c79fa9de75fbe60b2" + }, + "button/button.module.css": { + "path": "src/components/arc/button/button.module.css", + "sha256": "77323140c3f9fbad7b08dddba0db7260aa233c34c39a9d24cfa646fea287e140" + }, + "button/button.tsx": { + "path": "src/components/arc/button/button.tsx", + "sha256": "d051d08351db8059c249ed92e8e5c8319ed812e1537d88b281815ffa4c17f1bb" + }, + "card/card.module.css": { + "path": "src/components/arc/card/card.module.css", + "sha256": "70bd80f3f6245f519691edf4e4c4217d99fb477cf9a1305ba1e3a5b1111f5dea" + }, + "card/card.tsx": { + "path": "src/components/arc/card/card.tsx", + "sha256": "1e82f064e152aefefb9b34e89e019cca31919ce9ddcd84b480a88775fd4ad638" + }, + "checkbox/checkbox.module.css": { + "path": "src/components/arc/checkbox/checkbox.module.css", + "sha256": "6cc8ae35edbd99dac2ea3768a6db0932429ecb06febab06e048a4b94974251b6" + }, + "checkbox/checkbox.tsx": { + "path": "src/components/arc/checkbox/checkbox.tsx", + "sha256": "4759251a0b2a83320cb4078e840f61481a23be0b38b9aa7c077c2e85e6dde00d" + }, + "dialog/dialog.module.css": { + "path": "src/components/arc/dialog/dialog.module.css", + "sha256": "a71ce7476732e9a996ddf6f765585cd2c7fab6168b8715bad464916c0a36168d" + }, + "dialog/dialog.tsx": { + "path": "src/components/arc/dialog/dialog.tsx", + "sha256": "eb84a7eb2ac864dc07f2825eab252eac78e9c6b889d0e9f00bf6b2b799975ade" + }, + "drawer/drawer.module.css": { + "path": "src/components/arc/drawer/drawer.module.css", + "sha256": "f0bbe416307a5203eefea97940c22952914d92f8a906ecc1e4b201da10f13e01" + }, + "drawer/drawer.tsx": { + "path": "src/components/arc/drawer/drawer.tsx", + "sha256": "eca310cb947c8da843f1128a77a2683c4e031519081da8c08d7ee405e5bbd87a" + }, + "empty-state/empty-state.module.css": { + "path": "src/components/arc/empty-state/empty-state.module.css", + "sha256": "e65e4c4b6e3bd31b8925cb6a5d58e8c4826ffca6efb100f786c70428f98afc1a" + }, + "empty-state/empty-state.tsx": { + "path": "src/components/arc/empty-state/empty-state.tsx", + "sha256": "e99e39c02b03e77738e8e8a69d12f24b6e9d5b3b66f12f1425cec32700fa69ef" + }, + "foundation.css": { + "path": "src/components/arc/foundation.css", + "sha256": "a30519d85c44722973cc328d3797800944396387d3c93a1a1297c18d1a4d3d86" + }, + "input/input.module.css": { + "path": "src/components/arc/input/input.module.css", + "sha256": "ef6716aa7b9f45898859735f416ac932517b94e66bed6b3d23d7aed180529bdf" + }, + "input/input.tsx": { + "path": "src/components/arc/input/input.tsx", + "sha256": "16a4e761b51482e9c066f284a38171085e71ae390e4b26f9f0c18dd8af21c8f2" + }, + "lib/arc-provider.tsx": { + "path": "src/components/arc/lib/arc-provider.tsx", + "sha256": "bcc7358163968a9508d81586134bf8d921d75783033182f81ca9015985815884" + }, + "lib/motion-tokens.ts": { + "path": "src/components/arc/lib/motion-tokens.ts", + "sha256": "bec65d2e1b180dd3c574edc60cf84e0fa336e7ff8640eba0c70bcf0ae765fb8a" + }, + "motion-tokens.ts": { + "path": "src/components/arc/motion-tokens.ts", + "sha256": "81235a2bf09738ff9ad8d49ab50631d6a31541838dbc84414f8d97544c2fde73" + }, + "popover/popover.module.css": { + "path": "src/components/arc/popover/popover.module.css", + "sha256": "6b92cdac211568a53a81b1d84bcbd0728cec93f741e64074f7e9f91f673702f6" + }, + "popover/popover.tsx": { + "path": "src/components/arc/popover/popover.tsx", + "sha256": "c564d1974bc55e805cb92e37ab0d5dbf48b46429353981985f50adab2c93ff4c" + }, + "progress/progress.module.css": { + "path": "src/components/arc/progress/progress.module.css", + "sha256": "f0e527c419a7ebd3f9dd7faf49244fe87ea47e5153fed9f8e50fd83fd61d11a7" + }, + "progress/progress.tsx": { + "path": "src/components/arc/progress/progress.tsx", + "sha256": "53f96b8e42315c9c261338bd96f74d74f6db22b5de935ae3ec02e20cfb64ae1e" + }, + "scroll-area/scroll-area.module.css": { + "path": "src/components/arc/scroll-area/scroll-area.module.css", + "sha256": "904fdc63e0f818ad95ea148637dcbdd3e1a7c29408928fae2126f26abdf21bbb" + }, + "scroll-area/scroll-area.tsx": { + "path": "src/components/arc/scroll-area/scroll-area.tsx", + "sha256": "82c53c56af335d0a6d808ecd4cbb3c97e8fa83ca56ccd35f71605ae8dd8b0891" + }, + "segmented-control/segmented-control.module.css": { + "path": "src/components/arc/segmented-control/segmented-control.module.css", + "sha256": "029f038c7f03762cf386554f5e59768a95e6f5c8eb8b459bf3ef56cef35d1788" + }, + "segmented-control/segmented-control.tsx": { + "path": "src/components/arc/segmented-control/segmented-control.tsx", + "sha256": "9e1a4bc135246c86ed2d8875a3a1266490aa38a3d7800759db630e700188e840" + }, + "select/select.module.css": { + "path": "src/components/arc/select/select.module.css", + "sha256": "f700250cfa39db22e974f417d6d776e70b037e031500ca85c3c94e0c558a2b04" + }, + "select/select.tsx": { + "path": "src/components/arc/select/select.tsx", + "sha256": "673dc0c887a255c87bfbabd1835606d87cfbf59ed6fd4909a28038f00f673eaa" + }, + "skeleton/skeleton.module.css": { + "path": "src/components/arc/skeleton/skeleton.module.css", + "sha256": "ba4b3fa1d7f9df341c4c3a5e302d43178015f15030715ddb3ced2116cecf0588" + }, + "skeleton/skeleton.tsx": { + "path": "src/components/arc/skeleton/skeleton.tsx", + "sha256": "73b97715698fa54f6f0eaeefb6a8d795977297dd998439d1e595361e5da6d3b5" + }, + "switch/switch.module.css": { + "path": "src/components/arc/switch/switch.module.css", + "sha256": "3793e7ee1a4c2db46fce615c3fd76212c3c78ea005e23ae07c24b53453c1b6f7" + }, + "switch/switch.tsx": { + "path": "src/components/arc/switch/switch.tsx", + "sha256": "6ab95cb9c0aaa80599cdc0605abf959a20f5030fe4ecdf57f6894274a9c5d73b" + }, + "tabs/tabs.module.css": { + "path": "src/components/arc/tabs/tabs.module.css", + "sha256": "573e4a572e884b5f184efe731f2955341bb56f7ff640d2d01e3a409456ce4469" + }, + "tabs/tabs.tsx": { + "path": "src/components/arc/tabs/tabs.tsx", + "sha256": "3b0aaf6f0c41ce486e697ee3c9c86ce874fb2a22b1dab433226027de7858af0a" + }, + "textarea/textarea.module.css": { + "path": "src/components/arc/textarea/textarea.module.css", + "sha256": "57a9294f6f7eea903296334bf1203982b41736aa1082a83af4dc2e8bbc6a144c" + }, + "textarea/textarea.tsx": { + "path": "src/components/arc/textarea/textarea.tsx", + "sha256": "1ed43b87e45b04180f1c6b8b3b7543e071bed3a6fcb2033e98015c77a8b7135a" + }, + "toast/toast.module.css": { + "path": "src/components/arc/toast/toast.module.css", + "sha256": "7c971d71804b5d4b10c876a08d8a5b3caa0ef19aa7d94d0ccfdb9e291d02fa1c" + }, + "toast/toast.tsx": { + "path": "src/components/arc/toast/toast.tsx", + "sha256": "cc68a59e0db6f1f1a0c1b8ec6aaa7638c08be7e13367b370f8d3f44accddba7f" + }, + "tooltip/tooltip.module.css": { + "path": "src/components/arc/tooltip/tooltip.module.css", + "sha256": "a6126eda83bbbc1164018ad9df811f437098167077ca493ec5c06538e7f901f4" + }, + "tooltip/tooltip.tsx": { + "path": "src/components/arc/tooltip/tooltip.tsx", + "sha256": "25ad5ea2b707da617e055f0c2fd9bcf8776775ad658e67f3e9176f3030855f9b" + } + } +} diff --git a/packages/uiarc/src/alert/alert.module.css b/packages/uiarc/src/alert/alert.module.css new file mode 100644 index 00000000..343f279b --- /dev/null +++ b/packages/uiarc/src/alert/alert.module.css @@ -0,0 +1,15 @@ +.presence { min-width: 0; } +.alert { display: flex; align-items: start; gap: var(--space-3); border: 1px solid var(--border); border-radius: var(--radius-control); padding: var(--space-4); background: var(--surface); box-shadow: var(--shadow-resting); } +.icon, .glyph { position: relative; display: grid; flex: 0 0 auto; place-items: center; } +.icon { width: 18px; height: 18px; margin-top: 1px; } +.icon svg { display: block; } +.copy { flex: 1; min-width: 0; } +.content { position: relative; } +.title { position: relative; display: block; font-size: var(--text-sm); font-weight: 500; } +.line { display: block; } +.description { position: relative; margin: var(--space-1) 0 0; color: var(--text-secondary); font-size: var(--text-xs); } +.info .icon { color: var(--info, var(--accent)); } .success .icon { color: var(--success); } .warning .icon { color: var(--warning); } .danger .icon { color: var(--danger); } +.dismiss { display: grid; width: 28px; height: 28px; flex: 0 0 auto; place-items: center; margin: -5px -6px -5px 0; border: 0; border-radius: var(--radius-pill); background: transparent; color: var(--text-muted); cursor: pointer; transition: transform var(--duration-spring) var(--ease-spring), background-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard); } +.dismiss:active { transform: scale(.96); transition-duration: var(--duration-instant); transition-timing-function: var(--ease-standard); } +@media (hover: hover) and (pointer: fine) { .dismiss:hover { background: var(--surface-muted); color: var(--foreground); } } +@media (prefers-reduced-motion: reduce) { .dismiss { transition: none; } .dismiss:active { transform: none; } } diff --git a/packages/uiarc/src/alert/alert.tsx b/packages/uiarc/src/alert/alert.tsx new file mode 100644 index 00000000..a05c954b --- /dev/null +++ b/packages/uiarc/src/alert/alert.tsx @@ -0,0 +1,109 @@ +"use client"; + +import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import type { HTMLAttributes, ReactNode } from "react"; +import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, useReducedMotion, type AnimationPlaybackControls, type HTMLMotionProps, type MotionProps, type TargetAndTransition, type Transition } from "motion/react"; +import { Check, Info as InfoCircle, TriangleAlert as WarningTriangle, CircleX as XmarkCircle, X } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./alert.module.css"; + +export type AlertTone = "info" | "success" | "warning" | "danger"; +export interface AlertProps extends HTMLAttributes { + tone?: AlertTone; + title: string; + children?: ReactNode; + /** Controls presence. Hiding the alert collapses its height and fades it out. */ + open?: boolean; + /** Shows a dismiss button. An uncontrolled alert collapses first, then calls this. */ + onDismiss?: () => void; +} +type AlertBoxProps = Omit & { reduce: boolean | null; animateIcon?: boolean }; + +const icons = { info: InfoCircle, success: Check, warning: WarningTriangle, danger: XmarkCircle }; +const exitFast: Transition = { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] }; +const textIn: TargetAndTransition = { opacity: 0, y: "0.3em", filter: `blur(${motionTokens.blur.soft}px)` }; +const textOut: TargetAndTransition = { opacity: 0, y: "-0.3em", filter: `blur(${motionTokens.blur.subtle}px)`, transition: exitFast }; +const iconIn: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` }; +const shown: TargetAndTransition = { opacity: 1, y: "0em", scale: 1, filter: "blur(0px)" }; +const fadeOut: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } }; + +/** Outgoing copies are hidden from assistive tech while they fade, so the live region reads only the current text. */ +function Swap(props: HTMLMotionProps<"span">) { + const present = useIsPresent(); + return ; +} + +/** Follows its content height. After `morphKey` changes, the height springs from the old size to the new one and then returns to auto, so passive reflows (a resize, a font swap) follow instantly. It clips only while moving, so focus rings stay visible at rest. */ +function HeightFrame({ className, reduce, morphKey, children }: { className?: string; reduce: boolean | null; morphKey: string; children: ReactNode }) { + const frame = useRef(null); + const content = useRef(null); + const height = useMotionValue("auto"); + const changedAt = useRef(0); + useLayoutEffect(() => { changedAt.current = performance.now(); }, [morphKey]); + useEffect(() => { + const node = content.current; + if (!node || typeof ResizeObserver === "undefined") return; + let last: number | undefined; + let controls: AnimationPlaybackControls | undefined; + const settle = () => { height.jump("auto"); if (frame.current) Object.assign(frame.current.style, { overflow: "", height: "auto" }); }; + const observer = new ResizeObserver(([entry]) => { + if (!entry) return; + const next = entry.borderBoxSize?.[0]?.blockSize ?? node.offsetHeight; + const current = height.get(); + const from = typeof current === "number" ? current : last; + last = next; + controls?.stop(); + if (reduce || from === undefined || from === next || performance.now() - changedAt.current > 120) return settle(); + // Pin the old height before this frame paints, then spring to the new one. + if (frame.current) Object.assign(frame.current.style, { overflow: "hidden", height: `${from}px` }); + controls = animate(height, [from, next], { ...motionTokens.spring.smooth, onComplete: settle }); + }); + observer.observe(node); + return () => { observer.disconnect(); controls?.stop(); }; + }, [height, reduce]); + return +
{children}
+
; +} + +function AlertBox({ tone = "info", title, children, className, reduce, onDismiss, animateIcon = false, ...props }: AlertBoxProps) { + const Icon = icons[tone]; + const text = typeof children === "string" || typeof children === "number" ? String(children) : null; + const hasDetails = children !== undefined && children !== null && children !== false && children !== ""; + const enter: Transition = reduce ? { duration: motionTokens.duration.instant } : { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }; + const swap: MotionProps = { initial: reduce ? { opacity: 0 } : textIn, animate: shown, exit: reduce ? fadeOut : textOut, transition: enter }; + return
+ {/* A new tone morphs its icon in place; a newly shown alert gives the icon a small settle. */} + + + + {/* The copy column follows its content height, so longer or shorter messages never snap the alert. */} + + {title} + {hasDetails && + {text === null ? children : {text}} + } + + {onDismiss && } +
; +} + +export function Alert({ open, onDismiss, ...props }: AlertProps) { + const reduce = useReducedMotion(); + const [dismissed, setDismissed] = useState(false); + const shell = useRef(null); + const setClip = (value: string) => { if (shell.current) shell.current.style.overflow = value; }; + if (open === undefined && !onDismiss) return ; + const isOpen = open ?? !dismissed; + const dismiss = onDismiss && (() => open === undefined ? setDismissed(true) : onDismiss()); + const presence: Transition = reduce ? { duration: 0 } : { height: motionTokens.spring.smooth, opacity: { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] } }; + const exit: TargetAndTransition = { height: 0, opacity: 0, transition: reduce ? { duration: 0 } : { height: motionTokens.spring.smooth, opacity: exitFast } }; + // Presence collapses the height with the fade, so the content below closes the gap instead of jumping. + return { if (open === undefined) onDismiss?.(); }}> + {isOpen && setClip("hidden")} onAnimationComplete={() => setClip("")}> + + } + ; +} + +export default Alert; diff --git a/packages/uiarc/src/avatar/avatar.module.css b/packages/uiarc/src/avatar/avatar.module.css new file mode 100644 index 00000000..570d42f2 --- /dev/null +++ b/packages/uiarc/src/avatar/avatar.module.css @@ -0,0 +1,60 @@ +.avatar { + position: relative; + display: inline-grid; + flex: 0 0 auto; + place-items: center; + overflow: visible; + border: 1px solid var(--border); + border-radius: var(--radius-pill); + background: var(--surface-muted); + color: var(--foreground); + font-size: var(--text-xs); + font-weight: 500; +} + +.avatar img { + pointer-events: none; + border-radius: inherit; + object-fit: cover; + transition: opacity var(--duration-standard) var(--ease-enter), filter var(--duration-standard) var(--ease-enter); +} + +/* Set only while a photo is still downloading after mount, so cached photos never fade. */ +.avatar img[data-loading] { + opacity: 0; + filter: blur(4px); + transition: none; +} + +.fallback { animation: avatar-fallback-in var(--duration-standard) var(--ease-enter) both; } + +.sm { width: 28px; height: 28px; font-size: 10px; } +.md { width: 36px; height: 36px; } +.lg { width: 48px; height: 48px; font-size: var(--text-sm); } +.xl { width: 88px; height: 88px; font-size: var(--text-xl); } + +.status { + position: absolute; + right: 0; + bottom: 0; + z-index: 2; + width: 10px; + height: 10px; + border: 2px solid var(--surface); + border-radius: var(--radius-pill); + box-shadow: 0 0 0 1px color-mix(in oklab, var(--border) 70%, transparent); +} + +.sm .status { width: 8px; height: 8px; border-width: 1.5px; } +.lg .status { width: 12px; height: 12px; } +.xl .status { width: 14px; height: 14px; right: 4px; bottom: 4px; } +.online { background: var(--success); } +.offline { background: var(--text-muted); } + +@keyframes avatar-fallback-in { from { opacity: 0; } to { opacity: 1; } } + +@media (prefers-reduced-motion: reduce) { + .avatar img { transition: none; } + .avatar img[data-loading] { filter: none; } + .fallback { animation: none; } +} diff --git a/packages/uiarc/src/avatar/avatar.tsx b/packages/uiarc/src/avatar/avatar.tsx new file mode 100644 index 00000000..84da5a4c --- /dev/null +++ b/packages/uiarc/src/avatar/avatar.tsx @@ -0,0 +1,21 @@ +"use client"; + +import { useLayoutEffect, useRef, useState, type HTMLAttributes } from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; +import { ArcImage } from "../lib/arc-provider"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./avatar.module.css"; +export interface AvatarProps extends HTMLAttributes { name: string; src?: string; size?: "sm" | "md" | "lg" | "xl"; status?: "online" | "offline" } +export function Avatar({ name, src, size = "md", status, className, ...props }: AvatarProps) { + const initials = name.trim().split(/\s+/).slice(0, 2).map(part => part[0]?.toUpperCase()).join(""); + const reduceMotion = !!useReducedMotion(); + const image = useRef(null); + const [failedSrc, setFailedSrc] = useState(); + // A photo that is already decoded shows at once. One that is still loading waits, then fades in from a soft blur. + useLayoutEffect(() => { const node = image.current; if (node && !node.complete) node.dataset.loading = ""; }, [src]); + const showImage = src && failedSrc !== src; + return + {showImage ? { delete event.currentTarget.dataset.loading; }} onError={() => setFailedSrc(src)} /> : } + {status && + ; +} diff --git a/packages/uiarc/src/badge/badge.module.css b/packages/uiarc/src/badge/badge.module.css new file mode 100644 index 00000000..85d0aeb8 --- /dev/null +++ b/packages/uiarc/src/badge/badge.module.css @@ -0,0 +1,104 @@ +/* + * One formula tints every tone and colour from the shared --tone-* family, so they read as one set in both themes: + * background the tone mixed into the surface (10% light, a barely tinted 12% dark) + * text the tone, deepened toward the foreground in light (AA on the tint) and the bright pastel itself in dark + * mark the icon or dot, closer to the pure tone + * ring transparent by default; `outline` draws a hairline of the tone + * All mixes run in oklab: oklch tints turn pink after the production build. + */ +.badge { + --badge-tone: var(--text-secondary); + --badge-tint: 10%; + --badge-ink: 84%; + --badge-background: color-mix(in oklab, var(--badge-tone) var(--badge-tint), var(--surface)); + --badge-foreground: color-mix(in oklab, var(--badge-tone) var(--badge-ink), var(--foreground)); + --badge-color: color-mix(in oklab, var(--badge-tone) 88%, var(--foreground)); + --badge-border: transparent; + --badge-radius: 6px; + --badge-height: 24px; + --badge-pad: 10px; + --badge-gap: 5px; + --badge-icon: 14px; + --badge-dot: 6px; + box-sizing: border-box; + display: inline-flex; + min-height: var(--badge-height); + flex: none; + align-items: center; + justify-content: center; + vertical-align: middle; + border: 1px solid var(--badge-border); + border-radius: var(--badge-radius); + padding: 0 var(--badge-pad); + color: var(--badge-foreground); + background: var(--badge-background); + font-family: var(--font-body); + font-size: var(--text-xs); + font-weight: 500; + font-variant-numeric: tabular-nums; + letter-spacing: -.005em; + line-height: 1; + white-space: nowrap; + /* Clip keeps the corners clean while the badge morphs around swapped text. */ + overflow: clip; + transition: border-color var(--duration-standard) var(--ease-standard), background-color var(--duration-standard) var(--ease-standard), color var(--duration-standard) var(--ease-standard); +} + +:global(:root[data-theme="dark"]) .badge { --badge-tint: 12%; --badge-ink: 94%; } +.outline { --badge-border: color-mix(in oklab, var(--badge-tone) 14%, var(--border)); } +:global(:root[data-theme="dark"]) .outline { --badge-border: color-mix(in oklab, var(--badge-tone) 22%, var(--border)); } + +/* Sizes on the four point grid. The leading edge tightens beside a mark so the visual padding matches the trailing edge. */ +.sm { --badge-height: 20px; --badge-radius: 5px; --badge-pad: 8px; --badge-gap: 4px; --badge-icon: 12px; --badge-dot: 5px; font-size: 11px; } +.md { --badge-height: 24px; --badge-radius: 6px; --badge-pad: 10px; --badge-gap: 5px; --badge-icon: 14px; --badge-dot: 6px; } +.lg { --badge-height: 28px; --badge-radius: 7px; --badge-pad: 12px; --badge-gap: 6px; --badge-icon: 16px; --badge-dot: 7px; font-size: var(--text-sm); } +/* Full round ends, the original look. Declared after the sizes so it wins over their radius. */ +.pill { --badge-radius: var(--radius-pill); } +.withIcon { padding-inline-start: calc(var(--badge-pad) - 2px); } +.withDot { padding-inline-start: calc(var(--badge-pad) - 1px); } + +/* Flex all the way down: an inline box here would sit on a text baseline and push the label off centre. */ +.body { display: flex; align-items: center; } +.content { position: relative; display: flex; width: max-content; align-items: center; gap: var(--badge-gap); } +.label, .glyph { position: relative; display: inline-flex; align-items: center; } +/* Trim the line box to cap height and baseline, so flex centring puts the letters on the badge's optical centre at every size. */ +.text { display: block; text-box: trim-both cap alphabetic; } + +.icon { + position: relative; + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + color: var(--badge-color); + line-height: 0; +} +.glyph > svg { display: block; width: var(--badge-icon); height: var(--badge-icon); } + +.dot { + display: block; + width: var(--badge-dot); + height: var(--badge-dot); + flex: none; + border-radius: 50%; + background: var(--badge-color); +} + +.neutral { --badge-tone: var(--text-secondary); } +.info { --badge-tone: var(--info, var(--tone-sky)); } +.success { --badge-tone: var(--success); } +.warning { --badge-tone: var(--warning); } +.danger { --badge-tone: var(--danger); } +/* Categorical colours (method tags, labels) override the tone. */ +.teal { --badge-tone: var(--tone-teal); } +.sky { --badge-tone: var(--tone-sky); } +.orchid { --badge-tone: var(--tone-orchid); } +.violet { --badge-tone: var(--tone-violet); } +.rose { --badge-tone: var(--tone-rose); } +.amber { --badge-tone: var(--tone-amber); } +/* Amber is the lightest hue, so light mode deepens its text a little further. */ +.warning, .amber { --badge-ink: 76%; } + +@media (prefers-reduced-motion: reduce) { + .badge { transition-duration: var(--duration-instant); } +} diff --git a/packages/uiarc/src/badge/badge.tsx b/packages/uiarc/src/badge/badge.tsx new file mode 100644 index 00000000..05345987 --- /dev/null +++ b/packages/uiarc/src/badge/badge.tsx @@ -0,0 +1,93 @@ +"use client"; + +import { isValidElement, useEffect, useLayoutEffect, useRef } from "react"; +import type { HTMLAttributes, ReactNode } from "react"; +import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, useReducedMotion, type AnimationPlaybackControls, type HTMLMotionProps, type TargetAndTransition, type Transition } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./badge.module.css"; + +export type BadgeTone = "neutral" | "success" | "info" | "warning" | "danger"; +export type BadgeSize = "sm" | "md" | "lg"; +export type BadgeColor = "teal" | "sky" | "orchid" | "violet" | "rose" | "amber"; + +export interface BadgeProps extends HTMLAttributes { + tone?: BadgeTone; + size?: BadgeSize; + icon?: ReactNode; + /** A small status dot in the tone colour. Ignored when an icon is set. */ + dot?: boolean; + /** Categorical colour from the shared tone family, for labels such as method tags. Overrides tone. */ + color?: BadgeColor; + /** Draws a hairline border in the tone colour. */ + outline?: boolean; + /** Fully rounded ends instead of the default soft corners. */ + pill?: boolean; +} + +const exitFast: Transition = { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] }; +const textIn: TargetAndTransition = { opacity: 0, y: "0.3em", filter: `blur(${motionTokens.blur.soft}px)` }; +const textOut: TargetAndTransition = { opacity: 0, y: "-0.3em", filter: `blur(${motionTokens.blur.subtle}px)`, transition: exitFast }; +const iconIn: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` }; +const shown: TargetAndTransition = { opacity: 1, y: "0em", scale: 1, filter: "blur(0px)" }; +const fadeOnly: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } }; + +/** Outgoing copies are hidden from assistive tech while they fade, so only the current text is read. */ +function Swap(props: HTMLMotionProps<"span">) { + const present = useIsPresent(); + return ; +} + +/** A new icon component crossfades in; re-rendering the same icon stays still. */ +function iconKey(icon: ReactNode) { + if (!isValidElement(icon)) return "icon"; + const type = icon.type as string | { displayName?: string; name?: string }; + return typeof type === "string" ? type : type.displayName ?? type.name ?? "icon"; +} + +export function Badge({ tone = "neutral", size = "md", icon, dot = false, color, outline = false, pill = false, className, children, ...props }: BadgeProps) { + const reduce = useReducedMotion(); + const text = typeof children === "string" || typeof children === "number" ? String(children) : null; + const glyphKey = icon ? iconKey(icon) : ""; + const body = useRef(null); + const content = useRef(null); + // Width stays auto at rest. Only a new label or icon springs it from the old size to the new one; passive reflows (a font swap, a hidden parent) follow instantly. + const width = useMotionValue("auto"); + const changedAt = useRef(0); + useLayoutEffect(() => { changedAt.current = performance.now(); }, [text, glyphKey]); + useEffect(() => { + const node = content.current; + if (!node || typeof ResizeObserver === "undefined") return; + let last: number | undefined; + let controls: AnimationPlaybackControls | undefined; + const settle = () => { width.jump("auto"); if (body.current) body.current.style.width = "auto"; }; + const observer = new ResizeObserver(([entry]) => { + if (!entry) return; + const next = entry.borderBoxSize?.[0]?.inlineSize ?? node.offsetWidth; + const current = width.get(); + const from = typeof current === "number" ? current : last; + last = next; + controls?.stop(); + if (reduce || from === undefined || from === next || performance.now() - changedAt.current > 120) return settle(); + // Pin the old width before this frame paints, then spring to the new one. + if (body.current) body.current.style.width = `${from}px`; + controls = animate(width, [from, next], { ...motionTokens.spring.morph, onComplete: settle }); + }); + observer.observe(node); + return () => { observer.disconnect(); controls?.stop(); }; + }, [width, reduce]); + const enter: Transition = reduce ? { duration: motionTokens.duration.instant } : { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }; + const mark = icon ? styles.withIcon : dot ? styles.withDot : undefined; + const classes = [styles.badge, styles[tone], color ? styles[color] : undefined, styles[size], mark, outline ? styles.outline : undefined, pill ? styles.pill : undefined, className].filter(Boolean).join(" "); + // The pill follows its content: text and icon swap in place while the width springs to the new size. + return + + + {!icon && dot ? + + ; +} + +export default Badge; diff --git a/packages/uiarc/src/button/button.module.css b/packages/uiarc/src/button/button.module.css new file mode 100644 index 00000000..9bdba573 --- /dev/null +++ b/packages/uiarc/src/button/button.module.css @@ -0,0 +1,39 @@ +/* Press scale is driven by Motion (whileTap) alone, so transform never gets a CSS transition here. */ +.button { position: relative; display: inline-flex; min-height: var(--control-height-md); align-items: center; justify-content: center; gap: var(--space-2); border: 1px solid transparent; border-radius: var(--radius-control); padding: 0 var(--space-4); font: inherit; font-size: var(--text-sm); font-weight: 500; line-height: var(--leading-body); white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), opacity var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard); } +.button:disabled { cursor: not-allowed; opacity: .52; } +.button[aria-busy="true"] { cursor: progress; } +/* Anchors of floating layers never scale: Radix opens on pointerdown and would measure a shrunken trigger. */ +.button:is([aria-haspopup]:not([aria-haspopup="false"]), [data-state], [role="combobox"]) { transform: none !important; } +/* The slot's width follows the incoming label on a spring. The label stays centered and may overflow evenly while the slot catches up; + the outgoing label pops out of flow against the slot itself, so it keeps its place instead of following the new content box. */ +.labelSlot { position: relative; display: inline-flex; min-width: 0; align-items: center; justify-content: center; transition: opacity var(--duration-fast) var(--ease-standard); } +.labelSlot[data-morphing] { clip-path: inset(-50% calc(var(--space-3) * -1)); } +.labelContent { display: inline-flex; flex: none; align-items: center; } +.labelPhase { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); white-space: nowrap; } +.labelPhase svg { flex: none; } +.primary { color: var(--background); background: var(--foreground); border-color: var(--foreground); } +.secondary { color: var(--foreground); background: var(--surface); border-color: var(--border); } +.ghost { color: var(--text-secondary); background: transparent; border-color: transparent; } +.danger { color: var(--danger); background: var(--surface); border-color: var(--border); } +/* A disabled outlined button keeps its shape and fades only its label, so it still reads as a button that is off, not as plain text. */ +.secondary:disabled, .danger:disabled { opacity: 1; color: var(--text-muted); background: var(--surface-muted); border-color: var(--border); } +.danger:disabled { color: color-mix(in oklab, var(--danger) 55%, var(--surface-muted)); } +.ghost:disabled { opacity: 1; color: var(--text-muted); } +@media (hover: hover) and (pointer: fine) { + .primary:hover:not(:disabled) { opacity: .91; box-shadow: var(--shadow-resting); } + .secondary:hover:not(:disabled) { background: var(--surface-muted); box-shadow: var(--shadow-resting); } + .ghost:hover:not(:disabled) { color: var(--foreground); background: var(--surface-muted); } + .danger:hover:not(:disabled) { border-color: var(--danger); background: var(--surface-muted); } +} +/* Color feedback on press, so touch and menu triggers (which never scale) still answer the finger. */ +.primary:active:not(:disabled) { opacity: .84; } +.secondary:active:not(:disabled), .ghost:active:not(:disabled) { color: var(--foreground); background: var(--surface-muted); } +.danger:active:not(:disabled) { border-color: var(--danger); background: var(--surface-muted); } +.sm { min-height: var(--control-height-sm); padding-inline: var(--space-3); font-size: var(--text-sm); } +.md { min-height: var(--control-height-md); } +.lg { min-height: var(--control-height-lg); padding-inline: var(--space-5); font-size: var(--text-sm); } +.loader { position: absolute; left: 50%; top: 50%; display: grid; width: var(--space-4); height: var(--space-4); margin: calc(var(--space-4) / -2); } +.spinner { border: 1.5px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: spin .7s linear infinite; } +.loadingLabel { opacity: 0; } +@keyframes spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .button { transition: none; } .labelSlot { transition: opacity var(--duration-instant) linear; } .spinner { animation-duration: .01ms; animation-iteration-count: 1; } } diff --git a/packages/uiarc/src/button/button.tsx b/packages/uiarc/src/button/button.tsx new file mode 100644 index 00000000..10435ed4 --- /dev/null +++ b/packages/uiarc/src/button/button.tsx @@ -0,0 +1,132 @@ +"use client"; + +import { forwardRef, isValidElement, useCallback, useEffect, useLayoutEffect, useRef } from "react"; +import type { ButtonHTMLAttributes, ReactNode, Ref, RefObject } from "react"; +import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, useReducedMotion } from "motion/react"; +import type { TargetAndTransition, Variants } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./button.module.css"; + +export type ButtonVariant = "primary" | "secondary" | "ghost" | "danger"; +export type ButtonSize = "sm" | "md" | "lg"; + +export interface ButtonProps extends Omit, "onDrag" | "onDragEnd" | "onDragStart" | "onAnimationStart"> { + variant?: ButtonVariant; + size?: ButtonSize; + loading?: boolean; +} + +/** Icon buttons press a little deeper, wide buttons a little less, so every size reads as the same push. */ +const pressVariants: Variants = { + pressed: (button: RefObject) => { + const width = button.current?.offsetWidth ?? 0; + return { scale: width > 220 ? .985 : width && width <= 48 ? .96 : .97, transition: { duration: motionTokens.duration.instant, ease: [...motionTokens.ease.standard] } }; + }, +}; + +const rest: TargetAndTransition = { opacity: 1, y: 0, scale: 1 }; +/** One clean crossfade: the new label rises 2px as it fades in, the outgoing one fades out faster. No blur. */ +const textIn: TargetAndTransition = { opacity: 0, y: 2 }; +const textOut: TargetAndTransition = { opacity: 0, transition: { duration: .1, ease: [...motionTokens.ease.standard] } }; +const iconIn: TargetAndTransition = { opacity: 0, scale: .85 }; +const iconOut: TargetAndTransition = { opacity: 0, transition: { duration: .1, ease: [...motionTokens.ease.standard] } }; +const fadeIn: TargetAndTransition = { ...rest, opacity: 0 }; +const fadeOut: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } }; +/** Scale rides the spring; opacity tweens. */ +const iconEnter = { ...motionTokens.spring.snappy, opacity: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.enter] } } as const; + +/** A key for the label content: text plus element names, so a new label or icon crossfades while prop-only updates stay in place. */ +function labelKey(node: ReactNode): string { + if (node == null || typeof node === "boolean") return ""; + if (typeof node === "string" || typeof node === "number" || typeof node === "bigint") return String(node); + if (Array.isArray(node)) return node.map(labelKey).join(""); + if (!isValidElement(node)) return ""; + const type = node.type as string | { displayName?: string; name?: string }; + return `<${typeof type === "string" ? type : type?.displayName ?? type?.name ?? ""}>${labelKey((node.props as { children?: ReactNode }).children)}`; +} + +/** Springs the slot to the natural width of the incoming label when it changes, so a new label never snaps the button's size. + * The outgoing label is popped out of flow at once, so it never holds the old width. Other resizes (a late web font, a parent reflow) jump straight to the new width, so nothing wobbles on first paint. */ +function useMorphWidth(content: RefObject, key: string, reduced: boolean) { + const width = useMotionValue("auto"); + const lastKey = useRef(key), armedUntil = useRef(0); + useLayoutEffect(() => { + if (lastKey.current === key) return; + lastKey.current = key; + armedUntil.current = performance.now() + 700; + }, [key]); + useEffect(() => { + const node = content.current, slot = node?.parentElement; + if (!node || !slot || typeof ResizeObserver === "undefined") return; + let measured = false; + const observer = new ResizeObserver(([entry]) => { + if (!entry) return; + const next = entry.contentRect.width; + if (!next || !measured || reduced || performance.now() > armedUntil.current) { measured = next > 0; width.jump(next || "auto"); delete slot.dataset.morphing; return; } + slot.dataset.morphing = ""; + animate(width, next, { ...motionTokens.spring.morph, onComplete: () => { delete slot.dataset.morphing; } }); + }); + observer.observe(node); + return () => observer.disconnect(); + }, [content, reduced, width]); + return width; +} + +function LabelPhase({ children, icon, reduced, ref }: { children: ReactNode; icon: boolean; reduced: boolean; ref?: Ref }) { + const present = useIsPresent(); + return {children}; +} + +export const Button = forwardRef(function Button( + { className, variant = "primary", size = "md", loading = false, disabled, children, onClick, ...props }, + ref, +) { + const reduceMotion = useReducedMotion() ?? false; + const buttonRef = useRef(null); + const contentRef = useRef(null); + const key = labelKey(children); + const width = useMorphWidth(contentRef, key, reduceMotion); + const setRefs = useCallback((node: HTMLButtonElement | null) => { + buttonRef.current = node; + if (typeof ref === "function") ref(node); else if (ref) ref.current = node; + }, [ref]); + // A trigger that anchors a menu, popover, or dialog keeps its rect still while pressed, so the layer never measures a scaled anchor. + // Radix triggers (asChild) pass aria-haspopup or data-state through; the stylesheet repeats the guard. + const popup = props["aria-haspopup"]; + const anchorsLayer = (popup !== undefined && popup !== false && popup !== "false") || props.role === "combobox" || (props as Record)["data-state"] !== undefined; + const inert = disabled || loading || props["aria-disabled"] === true || props["aria-disabled"] === "true"; + const classes = [styles.button, styles[variant], styles[size], className].filter(Boolean).join(" "); + + return ( + event.preventDefault() : onClick} + > + + {loading ? : null} + + + + + ]*>/g, ""))} reduced={reduceMotion}>{children} + + + + + ); +}); + +Button.displayName = "Button"; + +export default Button; diff --git a/packages/uiarc/src/card/card.module.css b/packages/uiarc/src/card/card.module.css new file mode 100644 index 00000000..2b7e6dcc --- /dev/null +++ b/packages/uiarc/src/card/card.module.css @@ -0,0 +1,51 @@ +/* Isolation keeps the rounded clip on the media while the card lifts on its own layer (Safari drops it otherwise). + Motion drives the lift and the quick look morph, so transform never gets a CSS transition here. */ +.card { position: relative; min-width: 0; overflow: hidden; isolation: isolate; border: 1px solid var(--border); border-radius: var(--radius-panel); background: var(--surface); color: var(--foreground); transition: border-color var(--duration-fast) var(--ease-standard), box-shadow var(--duration-standard) var(--ease-standard); } +/* A pointed-at card floats a little, so the shadow arrives with the lift. Touch and pen never lift. */ +.card[data-hover] { border-color: var(--border-strong); box-shadow: var(--shadow-raised); } +.card:has(.trigger:focus-visible) { border-color: var(--border-strong); } +.media { position: relative; overflow: hidden; background: var(--surface-muted); } +.zoom { display: grid; min-height: 112px; place-items: center; } +.content { padding: var(--space-5); } +/* Fit-content width keeps the title's box the shape of its text, so it scales evenly when it grows into the quick look. */ +.title { width: fit-content; max-width: 100%; margin: 0; font-size: var(--text-lg); font-weight: 500; letter-spacing: var(--tracking-body); line-height: 1.3; text-wrap: balance; } +.trigger { padding: 0; border: 0; background: none; color: inherit; font: inherit; letter-spacing: inherit; text-align: inherit; cursor: pointer; -webkit-tap-highlight-color: transparent; } +/* The title's hit area stretches over the whole card, so pointing anywhere opens the quick look while the action stays on top. */ +.trigger::after { content: ""; position: absolute; inset: 0; } +.trigger:focus-visible { outline: none; } +.description { max-width: 34ch; margin: var(--space-2) 0 0; color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-body); text-wrap: pretty; } +.footer { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); margin-top: var(--space-5); } +.byline { display: flex; flex: 1 1 auto; align-items: center; gap: var(--space-3); min-width: 0; } +.avatar { display: grid; flex: none; width: var(--space-8); height: var(--space-8); overflow: hidden; border-radius: var(--radius-pill); background: var(--surface-muted); } +.avatar > * { width: 100%; height: 100%; object-fit: cover; } +/* A shrinkable column, so a narrow footer truncates the byline instead of sliding it under the action. */ +.bylineText { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; font-size: var(--text-xs); line-height: var(--leading-body); } +.meta { overflow: hidden; color: var(--foreground); font-weight: 500; text-overflow: ellipsis; white-space: nowrap; } +.status { position: relative; overflow: clip visible; color: var(--text-muted); white-space: nowrap; font-variant-numeric: tabular-nums; } +/* The line clips sideways only, so a status too long for its column ends in an ellipsis while its words still rise in unclipped. */ +.roll { position: relative; display: block; } +.line { display: block; overflow: clip visible; text-overflow: ellipsis; } +.word { display: inline-block; white-space: pre; } +.srOnly { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +.action { position: relative; z-index: 1; display: flex; flex: none; flex-wrap: wrap; gap: var(--space-3); } + +.overlay { position: fixed; inset: 0; z-index: 50; background: oklch(10% 0 0 / .46); -webkit-backdrop-filter: blur(7px); backdrop-filter: blur(7px); } +/* Centered with auto margins, so transform stays free for the morph. */ +.panel { position: fixed; inset: 0; z-index: 51; width: min(calc(100vw - var(--space-8)), 30rem); height: fit-content; max-height: calc(100dvh - var(--space-8)); margin: auto; overflow: hidden auto; overscroll-behavior: contain; border: 1px solid var(--border); border-radius: var(--radius-surface); background: var(--surface-raised); color: var(--foreground); box-shadow: var(--shadow-floating); transition: background-color var(--duration-standard) var(--ease-standard), box-shadow var(--duration-standard) var(--ease-standard); } +.panel:focus { outline: none; } +/* Closing: the panel takes the card's box and look, so it lands exactly where the card sits and hands back without a seam. */ +.panel[data-returning] { inset: auto; top: var(--landing-top); left: var(--landing-left); width: var(--landing-width); height: var(--landing-height); max-height: none; margin: 0; overflow: hidden; border-color: var(--border); background: var(--surface); box-shadow: none; pointer-events: none; } +.panel[data-returning] .content { padding: var(--space-5); } +.panel[data-returning] .title { font-size: var(--text-lg); } +.panel .content { padding: var(--space-6); } +.panel .title { font-size: var(--text-xl); } +.panel .description { max-width: var(--card-measure, 34ch); } +/* The slot carries the entrance, so the button's own press answers instantly. */ +.closeSlot { position: absolute; top: var(--space-4); right: var(--space-4); z-index: 2; display: grid; } +.close { display: grid; width: var(--space-8); height: var(--space-8); place-items: center; padding: 0; border: 1px solid color-mix(in oklab, var(--border) 70%, transparent); border-radius: var(--radius-pill); background: color-mix(in oklab, var(--surface-raised) 74%, transparent); -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px); color: var(--foreground); cursor: pointer; -webkit-tap-highlight-color: transparent; transition: background-color var(--duration-fast) var(--ease-standard); } +@media (hover: hover) and (pointer: fine) { .close:hover { background: var(--surface-raised); } } +.details { margin-top: var(--space-6); padding-top: var(--space-5); border-top: 1px solid var(--border); color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-body); } + +@media (prefers-reduced-motion: reduce) { + .card, .close { transition-duration: var(--duration-instant); } +} diff --git a/packages/uiarc/src/card/card.tsx b/packages/uiarc/src/card/card.tsx new file mode 100644 index 00000000..4295ee4d --- /dev/null +++ b/packages/uiarc/src/card/card.tsx @@ -0,0 +1,198 @@ +"use client"; + +import * as Dialog from "@radix-ui/react-dialog"; +import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react"; +import type { CSSProperties, HTMLAttributes, ReactNode } from "react"; +import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react"; +import type { HTMLMotionProps, MotionProps, Transition, Variants } from "motion/react"; +import { X } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./card.module.css"; + +export interface CardProps extends HTMLAttributes { + title: string; + description?: string; + media?: ReactNode; + action?: ReactNode; + /** A small leading visual for the footer, such as the owner's avatar. */ + avatar?: ReactNode; + /** Who the card belongs to, such as the owner's name. */ + meta?: ReactNode; + /** A short status under the meta, such as "Updated 2 hours ago". Changed words rise in and are announced politely. */ + status?: string; + /** Content for a quick look. When set, the whole card opens and grows into a larger view; Escape or the close control morphs it back. */ + details?: ReactNode; + open?: boolean; + defaultOpen?: boolean; + onOpenChange?: (open: boolean) => void; +} + +type Side = "card" | "panel"; +type Geometry = { card?: number; panel?: number; measure?: number }; +type Landing = { top: number; left: number; width: number; height: number }; + +const { blur, duration, ease, spring, stagger } = motionTokens; +/** One critically damped spring carries the surface both ways, so it never overshoots and can reverse mid-flight. Closing is a touch quicker. */ +const grow: Transition = { ...spring.smooth, visualDuration: .3 }; +const settle: Transition = { ...spring.smooth, visualDuration: .26 }; +const RETURN_MS = 300; +const fade: Transition = { duration: duration.instant }; +/** The photo drifts in slowly while the card is pointed at, and eases back a little faster. */ +const ZOOM = 1.04; +const zoomIn: Transition = { duration: duration.considered * 2, ease: [...ease.standard] }; +const zoomOut: Transition = { duration: duration.considered, ease: [...ease.standard] }; +/** Quick look extras arrive once the surface has mostly grown, so they never ride the stretch. */ +const reveal: Transition = { delay: duration.instant, duration: duration.standard, ease: [...ease.enter] }; +const closeIn: Transition = { delay: duration.instant, duration: duration.fast, ease: [...ease.enter] }; + +/** A new status replaces the whole line: the old one lifts away quickly while the new words rise in one after another. */ +const lineMotion: Variants = { + enter: {}, + center: {}, + exit: { opacity: 0, y: "-.3em", filter: `blur(${blur.subtle}px)`, transition: { duration: duration.fast, ease: [...ease.standard] } }, +}; +const wordMotion: Variants = { + enter: { opacity: 0, y: ".3em", filter: `blur(${blur.soft}px)` }, + center: (order: number) => ({ opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: duration.standard, ease: [...ease.enter], delay: order * stagger.word } }), +}; + +function Status({ text, reduced }: { text: string; reduced: boolean }) { + return + {text} + + ; +} + +/** Motion only scale-corrects pixel radii, so token radii are read back in pixels for the morph. */ +function px(node: Element, value: string) { + const amount = parseFloat(value); + if (!Number.isFinite(amount)) return undefined; + return value.trim().endsWith("rem") ? amount * parseFloat(getComputedStyle(node.ownerDocument.documentElement).fontSize) : amount; +} + +export function Card({ title, description, media, action, avatar, meta, status, details, open: openProp, defaultOpen = false, onOpenChange, children, className, style, ...props }: CardProps) { + const reduced = useReducedMotion() ?? false; + const group = useId(); + const cardRef = useRef(null); + const descriptionRef = useRef(null); + const [uncontrolled, setUncontrolled] = useState(defaultOpen); + const [hovered, setHovered] = useState(false); + const [geometry, setGeometry] = useState({}); + /** Where the quick look lands when it closes: the card's box on screen. The panel travels there above the page, then hands back to the card. */ + const [landing, setLanding] = useState(null); + const open = details ? openProp ?? uncontrolled : false; + const morph = Boolean(details) && !reduced; + const returning = !open && landing !== null; + const hasDescription = Boolean(description); + const setOpen = useCallback((next: boolean) => { if (openProp === undefined) setUncontrolled(next); onOpenChange?.(next); }, [openProp, onOpenChange]); + + // The quick look keeps the card's line length, so the description never rewraps while it travels. + useEffect(() => { + const node = cardRef.current, text = descriptionRef.current; + if (!morph || !node || typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(() => { + const computed = getComputedStyle(node); + const radius = px(node, computed.borderTopLeftRadius), surface = px(node, computed.getPropertyValue("--radius-surface")), measure = text?.offsetWidth || undefined; + setGeometry(current => current.card !== undefined && current.measure === measure ? current : { card: current.card ?? radius, panel: current.panel ?? surface, measure }); + }); + observer.observe(node); + if (text) observer.observe(text); + return () => observer.disconnect(); + }, [morph, hasDescription]); + + // Closing keeps the quick look mounted and sends it back to the card's box, so the surface never drops behind the page or a clipped preview. + const wasOpen = useRef(open); + useLayoutEffect(() => { + const closed = wasOpen.current && !open; + wasOpen.current = open; + const node = cardRef.current; + if (open) setLanding(null); // eslint-disable-line react-hooks/set-state-in-effect -- reopening mid-return cancels the landing + else if (closed && morph && node) { + const box = node.getBoundingClientRect(); + setLanding({ top: box.top, left: box.left, width: box.width, height: box.height }); + } + }, [open, morph]); + // Once the surface has visually landed, the card takes over. Any last sub-pixel of travel carries on in the card itself, so the handoff has no seam. + useEffect(() => { + if (!returning) return; + const timer = window.setTimeout(() => setLanding(null), RETURN_MS); + return () => window.clearTimeout(timer); + }, [returning]); + + /** The same pieces live in the card and in the quick look; a shared id lets each one travel between them. + Crossfade is off: the arriving piece takes over at full opacity and the other hides, so one solid surface moves instead of two translucent copies. */ + const shared = (id: string, side: Side, layout: true | "position" = true): MotionProps => morph ? { layoutId: id, layout, layoutCrossfade: false, layoutDependency: side === "card" ? open : returning ? "return" : "panel", transition: { layout: side === "card" ? settle : grow } } : {}; + + const footer = (side: Side) => avatar || meta || status || action ?
+ {avatar || meta || status ? + {avatar ? {avatar} : null} + {meta ? {meta} : null}{status ? : null} + : null} + {action ? {action} : null} +
: null; + + const card = )} + ref={cardRef} + className={[styles.card, className].filter(Boolean).join(" ")} + style={{ ...style, borderRadius: geometry.card ?? style?.borderRadius }} + data-hover={hovered || undefined} + whileHover={reduced ? undefined : { y: -2 }} + onHoverStart={() => setHovered(true)} + onHoverEnd={() => setHovered(false)} + {...shared("card", "card")} + transition={{ default: spring.snappy, layout: settle }} + > + {media ? {media} : null} +
+ {details ? : title} + {description ? {description} : null} + {children} + {footer("card")} +
+
; + + if (!details) return card; + + // The quick look grows out of the card: the surface, photo, and copy travel on one spring while the details settle in beneath them. + return + + {card} + + {(open || returning) && + {open && } + + + {media ? {media} : null} + +
+ {title} + {description ? {description} : null} + {children} + {footer("panel")} + {details} +
+
+
+
} +
+
+
; +} diff --git a/packages/uiarc/src/checkbox/checkbox.module.css b/packages/uiarc/src/checkbox/checkbox.module.css new file mode 100644 index 00000000..c11957be --- /dev/null +++ b/packages/uiarc/src/checkbox/checkbox.module.css @@ -0,0 +1,15 @@ +.field { display: inline-flex; align-items: flex-start; gap: 0; min-width: 0; } +.box { position: relative; flex: 0 0 auto; display: grid; place-items: center; width: var(--control-height-md); height: var(--control-height-md); border: 0; border-radius: var(--radius-control); padding: 0; background: transparent; color: var(--control-glyph); cursor: pointer; -webkit-tap-highlight-color: transparent; } +/* The square is the only part that reacts to a press, so the hit area and label never move. */ +.visual { position: relative; display: block; width: 18px; height: 18px; border: 1px solid var(--border-strong); border-radius: 5px; background: var(--surface); transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-spring) var(--ease-spring); } +.fill { position: absolute; inset: -1px; border-radius: inherit; background: var(--control-on); } +.mark { position: absolute; inset: -1px; width: 18px; height: 18px; overflow: visible; } +.box[data-state="checked"] .visual, .box[data-state="indeterminate"] .visual { border-color: var(--control-on); } +@media (hover: hover) and (pointer: fine) { .box[data-state="unchecked"]:hover:not(:disabled) .visual { border-color: var(--text-muted); } } +.box:active:not(:disabled) .visual { transform: scale(.95); transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard); } +.box:disabled { opacity: .5; cursor: not-allowed; } +/* The label's first line centers on the square: (44px box - 19.6px line) / 2. */ +.copy { display: grid; gap: 2px; min-width: 0; margin-left: 1px; padding-top: calc((var(--control-height-md) - var(--text-sm) * 1.4) / 2); } +.copy label { color: var(--foreground); font-size: var(--text-sm); font-weight: 500; line-height: var(--leading-body); cursor: pointer; } +.copy span { color: var(--text-muted); font-size: var(--text-xs); line-height: var(--leading-body); } +@media (prefers-reduced-motion: reduce) { .visual, .box:active:not(:disabled) .visual { transition: none; transform: none; } } diff --git a/packages/uiarc/src/checkbox/checkbox.tsx b/packages/uiarc/src/checkbox/checkbox.tsx new file mode 100644 index 00000000..2309c0bf --- /dev/null +++ b/packages/uiarc/src/checkbox/checkbox.tsx @@ -0,0 +1,44 @@ +"use client"; + +import { forwardRef, useId, useState } from "react"; +import type { ComponentPropsWithoutRef, ElementRef } from "react"; +import * as CheckboxPrimitive from "@radix-ui/react-checkbox"; +import { motion, useReducedMotion } from "motion/react"; +import type { Transition } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./checkbox.module.css"; + +export interface CheckboxProps extends ComponentPropsWithoutRef { + label?: string; + description?: string; +} + +/** Both marks share three points, so the check morphs into the dash and back instead of swapping. */ +const checkPath = "M4.25 9.25 L7.25 12.25 L13.75 5.75"; +const dashPath = "M4.75 9 L9 9 L13.25 9"; + +export const Checkbox = forwardRef, CheckboxProps>(function Checkbox( + { label, description, id, className, checked, defaultChecked, onCheckedChange, ...props }, ref, +) { + const generatedId = useId(); + const controlId = id ?? generatedId; + const reduced = useReducedMotion(); + const [internal, setInternal] = useState(defaultChecked ?? false); + const state = checked ?? internal; + const on = state !== false; + const change = (next: CheckboxPrimitive.CheckedState) => { if (checked === undefined) setInternal(next); onCheckedChange?.(next); }; + const fade: Transition = { duration: on ? motionTokens.duration.instant : motionTokens.duration.fast, ease: [...motionTokens.ease.standard] }; + return
+ + + + {label || description ?
{label ? : null}{description ? {description} : null}
: null} +
; +}); + +Checkbox.displayName = "Checkbox"; diff --git a/packages/uiarc/src/dialog/dialog.module.css b/packages/uiarc/src/dialog/dialog.module.css new file mode 100644 index 00000000..c6a8baf4 --- /dev/null +++ b/packages/uiarc/src/dialog/dialog.module.css @@ -0,0 +1,36 @@ +.overlay { position: fixed; inset: 0; z-index: 50; background: oklch(10% 0 0 / .46); -webkit-backdrop-filter: blur(7px); backdrop-filter: blur(7px); } +/* Centered with auto margins (like a native modal dialog) so transform stays free for the entrance spring. */ +.content { position: fixed; z-index: 51; inset: 0; width: min(calc(100vw - var(--space-8)), 440px); height: fit-content; max-height: calc(100vh - var(--space-8)); max-height: calc(100dvh - var(--space-8)); margin: auto; overflow: auto; border: 1px solid var(--border); border-radius: var(--radius-surface); background: var(--surface-raised); color: var(--foreground); box-shadow: var(--shadow-floating); } +/* Motion animates both layers. Keyframes only run when DialogContent sits under a bare Radix root. */ +.keyframes.overlay[data-state="open"] { animation: overlay-in var(--duration-standard) var(--ease-enter) both; } +.keyframes.overlay[data-state="closed"] { animation: overlay-out var(--duration-fast) var(--ease-standard) both; } +.keyframes.content[data-state="open"] { animation: content-fade-in var(--duration-fast) var(--ease-enter) both, content-rise-in var(--duration-spring) var(--ease-spring) both; } +.keyframes.content[data-state="closed"] { animation: content-out var(--duration-fast) var(--ease-standard) both; } +.content:focus { outline: none; } +/* While the layers leave, clicks pass through, so the trigger can reopen the dialog mid-exit. Radix sets pointer-events inline on the overlay. */ +.overlay[data-state="closed"], .content[data-state="closed"] { pointer-events: none !important; } +.header { display: flex; justify-content: space-between; align-items: flex-start; gap: var(--space-5); padding: var(--space-6); border-bottom: 1px solid var(--border); } +.title { margin: 0; font-family: var(--font-body); font-size: var(--text-lg); font-weight: 500; letter-spacing: var(--tracking-body); line-height: var(--leading-body); } +.description { margin: var(--space-2) 0 0; color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-body); } +.title, .description { position: relative; overflow-wrap: anywhere; } +.swap { display: block; } +/* Line height sits on the text itself, so a page-level heading reset cannot shrink the title and pull the close button off its line. */ +.title .swap { line-height: var(--leading-body); } +/* A compact icon button: quick press, spring release. The negative margin centres it on the title's first line. */ +.close { flex: 0 0 auto; margin-block: calc((var(--text-lg) * var(--leading-body) - var(--space-8)) / 2); display: grid; place-items: center; width: var(--space-8); height: var(--space-8); border: 1px solid var(--border); border-radius: var(--radius-control); background: color-mix(in oklab, var(--surface-muted) 50%, transparent); color: var(--text-secondary); cursor: pointer; transition: background-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), transform var(--duration-spring) var(--ease-spring); } +@media (hover: hover) and (pointer: fine) { .close:hover { background: var(--surface-muted); color: var(--foreground); } } +.close:active { transform: scale(.96); transition: background-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard); } +.body { padding: var(--space-6); font-size: var(--text-sm); line-height: var(--leading-body); } +@keyframes overlay-in { from { opacity: 0; } } +@keyframes overlay-out { to { opacity: 0; } } +@keyframes content-fade-in { from { opacity: 0; } } +@keyframes content-rise-in { from { transform: translateY(8px) scale(.96); } } +@keyframes content-out { to { opacity: 0; transform: translateY(4px) scale(.98); } } +@keyframes content-fade-out { to { opacity: 0; } } +@media (prefers-reduced-motion: reduce) { + .keyframes.overlay[data-state="open"], .keyframes.content[data-state="open"] { animation: overlay-in var(--duration-instant) var(--ease-standard) both; } + .keyframes.overlay[data-state="closed"] { animation: overlay-out var(--duration-instant) var(--ease-standard) both; } + .keyframes.content[data-state="closed"] { animation: content-fade-out var(--duration-instant) var(--ease-standard) both; } + .close, .close:active { transition: none; } + .close:active { transform: none; } +} diff --git a/packages/uiarc/src/dialog/dialog.tsx b/packages/uiarc/src/dialog/dialog.tsx new file mode 100644 index 00000000..193eb806 --- /dev/null +++ b/packages/uiarc/src/dialog/dialog.tsx @@ -0,0 +1,72 @@ +"use client"; + +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { createContext, useCallback, useContext, useLayoutEffect, useRef, useState } from "react"; +import type { ComponentPropsWithoutRef, ReactNode } from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; +import type { Transition } from "motion/react"; +import { X } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./dialog.module.css"; + +/** Mirrors the open state so the content can stay mounted while it animates out, and retarget mid-flight if it is reopened or closed early. */ +const OpenContext = createContext(null); + +export function Dialog({ open: openProp, defaultOpen = false, onOpenChange, ...props }: ComponentPropsWithoutRef) { + const [uncontrolled, setUncontrolled] = useState(defaultOpen); + const open = openProp ?? uncontrolled; + const setOpen = useCallback((next: boolean) => { if (openProp === undefined) setUncontrolled(next); onOpenChange?.(next); }, [openProp, onOpenChange]); + return ; +} + +export const DialogTrigger = DialogPrimitive.Trigger; +export const DialogClose = DialogPrimitive.Close; + +export interface DialogContentProps extends ComponentPropsWithoutRef { + title: string; + description?: string; + children: ReactNode; +} + +const fade: Transition = { duration: motionTokens.duration.instant }; +const leave: Transition = { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] }; + +/** When the title or description changes while open, the new copy rises in and the old copy leaves upward. */ +function SwapText({ text }: { text: string }) { + const reduced = useReducedMotion(); + return + {text} + ; +} + +export function DialogContent({ title, description, children, className, onPointerDownOutside, ...props }: DialogContentProps) { + const open = useContext(OpenContext); + const reduced = useReducedMotion(); + // When the open state last changed. Radix waits for the click before treating a press as outside, and a press on the trigger + // while the dialog leaves reopens it first, so that press must not close it again. + const change = useRef({ open, at: 0 }); + useLayoutEffect(() => { change.current = { open, at: performance.now() }; }, [open]); + const pressOutside: DialogContentProps["onPointerDownOutside"] = event => { + onPointerDownOutside?.(event); + if (open !== null && (!change.current.open || event.detail.originalEvent.timeStamp < change.current.at)) event.preventDefault(); + }; + const classes = [styles.content, className].filter(Boolean).join(" "); + const inner = <> +
{description ? : null}
+
{children}
+ ; + // Under a bare Radix root the open state is unknown here, so CSS keyframes keyed off data-state animate the layers instead. + if (open === null) return + + {inner} + ; + // The overlay fades while the dialog rises 8px and scales up on a spring. Closing is shorter and quieter, and starts from wherever the entrance is. + return + {open && + + + {inner} + + } + ; +} diff --git a/packages/uiarc/src/drawer/drawer.module.css b/packages/uiarc/src/drawer/drawer.module.css new file mode 100644 index 00000000..edbce641 --- /dev/null +++ b/packages/uiarc/src/drawer/drawer.module.css @@ -0,0 +1,97 @@ +.overlay { + position: fixed; + inset: 0; + z-index: 50; + background: oklch(10% 0 0 / .38); + -webkit-backdrop-filter: blur(4px); backdrop-filter: blur(4px); +} + +.content { + --drawer-size: min(30rem, calc(100vw - var(--space-4))); + /* Critically damped, like a sheet spring: it never overshoots past the edge it is anchored to. */ + --ease-drawer: cubic-bezier(.32,.72,0,1); + --drawer-from: translateX(100%); + position: fixed; + z-index: 51; + display: flex; + flex-direction: column; + width: var(--drawer-size); + max-width: 100vw; + max-height: 100dvh; + overflow: hidden; + border: 1px solid var(--border); + background: var(--surface-raised); + color: var(--foreground); + box-shadow: var(--shadow-floating); +} +/* While a layer leaves it lets clicks through, so pressing the trigger again during the close reopens the drawer from wherever it is. */ +/* Radix writes pointer-events inline on the overlay, so the closing state has to win over it. */ +.overlay[data-state="closed"], .content[data-state="closed"] { pointer-events: none !important; } + +.content[data-side="right"] { inset: 0 0 0 auto; border-width: 1px 0 1px 1px; border-radius: 22px 0 0 22px; } +.content[data-side="left"] { inset: 0 auto 0 0; border-width: 1px 1px 1px 0; border-radius: 0 22px 22px 0; } +.content[data-side="top"] { inset: 0 0 auto; width: 100%; max-width: none; max-height: min(32rem, 100dvh); border-width: 0 0 1px; border-radius: 0 0 22px 22px; } +.content[data-side="bottom"] { inset: auto 0 0; width: 100%; max-width: none; max-height: min(32rem, 100dvh); border-width: 1px 0 0; border-radius: 22px 22px 0 0; } +.content[data-side="bottom"]::before { position: absolute; top: 9px; left: 50%; width: 2.25rem; height: 4px; border-radius: var(--radius-pill); background: var(--border-strong); content: ""; opacity: .75; transform: translateX(-50%); } + +/* Motion springs the panel from its edge. Keyframes only run when DrawerContent sits under a bare Radix root. */ +.content[data-side="left"] { --drawer-from: translateX(-100%); } +.content[data-side="top"] { --drawer-from: translateY(-100%); } +.content[data-side="bottom"] { --drawer-from: translateY(100%); } +.keyframes.overlay[data-state="open"] { animation: overlay-in var(--duration-standard) var(--ease-enter) both; } +.keyframes.overlay[data-state="closed"] { animation: overlay-out var(--duration-fast) var(--ease-standard) both; } +.keyframes.content[data-state="open"] { animation: drawer-in var(--duration-considered) var(--ease-drawer) both; } +.keyframes.content[data-state="closed"] { animation: drawer-out var(--duration-standard) var(--ease-standard) both; } +.content:focus { outline: none; } +/* Inside a container the layers anchor to that element instead of the viewport. */ +.overlay[data-contained], .content[data-contained] { position: absolute; } +.overlay[data-contained] { z-index: 1; background: oklch(10% 0 0 / .16); backdrop-filter: none; } +.content[data-contained] { --drawer-size: min(22rem, calc(100% - var(--space-8))); z-index: 2; max-height: 100%; box-shadow: none; } +.content[data-contained][data-side="top"], .content[data-contained][data-side="bottom"] { max-height: min(32rem, calc(100% - var(--space-8))); } +/* The container already draws the outer edges, so only the inner edge keeps a border. */ +.content[data-contained][data-side] { border-width: 0; } +.content[data-contained][data-side="right"] { border-left-width: 1px; } +.content[data-contained][data-side="left"] { border-right-width: 1px; } +.content[data-contained][data-side="top"] { border-bottom-width: 1px; } +.content[data-contained][data-side="bottom"] { border-top-width: 1px; } + +.header { display: flex; flex: 0 0 auto; align-items: flex-start; justify-content: space-between; gap: var(--space-5); padding: var(--space-6); border-bottom: 1px solid var(--border); } +/* The header doubles as the drag handle, so touch drags move the panel instead of the page. */ +.handle { touch-action: none; user-select: none; } +.content[data-side="bottom"] .handle, .content[data-side="top"] .handle { cursor: grab; } +.title, .description { position: relative; } +/* The copy sets its own line height so a page-level heading rule cannot squeeze the title. */ +.swap { display: block; line-height: var(--leading-body); } +.title { margin: 0; font-family: var(--font-body); font-size: var(--text-lg); font-weight: 500; letter-spacing: var(--tracking-body); line-height: var(--leading-body); } +.description { max-width: 32rem; margin: var(--space-2) 0 0; color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-body); } +/* Centered on the first line of the title rather than its top edge. */ +.close { display: grid; flex: 0 0 auto; width: var(--space-8); height: var(--space-8); margin-top: calc((var(--text-lg) * var(--leading-body) - var(--space-8)) / 2); place-items: center; border: 1px solid var(--border); border-radius: var(--radius-control); background: color-mix(in oklab, var(--surface-muted) 65%, transparent); color: var(--text-secondary); cursor: pointer; transition: background-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), transform var(--duration-spring) var(--ease-spring); } +@media (hover: hover) and (pointer: fine) { .close:hover { background: var(--surface-muted); color: var(--foreground); } } +.close:active { transform: scale(.96); transition: background-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard); } +.body { min-height: 0; overflow: auto; padding: var(--space-6); font-size: var(--text-sm); line-height: var(--leading-body); overscroll-behavior: contain; scrollbar-width: thin; } + +@media (max-width: 40rem) { + .content { --drawer-size: calc(100vw - var(--space-3)); } + .content[data-side="right"] { border-radius: 18px 0 0 18px; } + .content[data-side="left"] { border-radius: 0 18px 18px 0; } + .content[data-side="top"] { border-radius: 0 0 18px 18px; } + .content[data-side="bottom"] { border-radius: 18px 18px 0 0; } + .header, .body { padding: var(--space-5); } +} + +@keyframes overlay-in { from { opacity: 0; } } +@keyframes overlay-out { to { opacity: 0; } } +@keyframes drawer-in { from { transform: var(--drawer-from); } } +/* The late fade lets the floating shadow leave with the panel instead of popping away at unmount. */ +@keyframes drawer-out { 65% { opacity: 1; } to { opacity: 0; transform: var(--drawer-from); } } +@keyframes drawer-fade-in { from { opacity: 0; } } +@keyframes drawer-fade-out { to { opacity: 0; } } + +@media (prefers-reduced-motion: reduce) { + .keyframes.overlay[data-state="open"] { animation: overlay-in var(--duration-instant) linear both; } + .keyframes.overlay[data-state="closed"] { animation: overlay-out 100ms linear both; } + .keyframes.content[data-state="open"] { animation: drawer-fade-in var(--duration-instant) linear both; } + .keyframes.content[data-state="closed"] { animation: drawer-fade-out 100ms linear both; } + .close, .close:active { transition: none; } + .close:active { transform: none; } +} diff --git a/packages/uiarc/src/drawer/drawer.tsx b/packages/uiarc/src/drawer/drawer.tsx new file mode 100644 index 00000000..210b401c --- /dev/null +++ b/packages/uiarc/src/drawer/drawer.tsx @@ -0,0 +1,200 @@ +"use client"; + +import * as DialogPrimitive from "@radix-ui/react-dialog"; +import { createContext, useCallback, useContext, useMemo, useRef, useState } from "react"; +import type { ComponentPropsWithoutRef, ReactNode, RefObject } from "react"; +import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion } from "motion/react"; +import type { PanInfo, Transition } from "motion/react"; +import { X } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./drawer.module.css"; + +/** + * The last item a drawer showed. Pass the selected item (or null when nothing is open) and render the drawer's content + * from the result, so the content stays on screen while the panel slides out instead of vanishing the moment it closes. + */ +export function useDrawerItem(item: T | null | undefined): T | null | undefined { + const [last, setLast] = useState(item); + if (item != null && item !== last) setLast(item); + return item ?? last; +} + +/** Mirrors the open state so the panel can stay mounted while it slides out, retarget mid-flight, and close itself after a drag. */ +const DrawerContext = createContext<{ open: boolean; flung: boolean; setOpen: (open: boolean) => void; fling: () => void; openedAt: RefObject } | null>(null); + +export function Drawer({ open: openProp, defaultOpen = false, onOpenChange, ...props }: ComponentPropsWithoutRef) { + const [uncontrolled, setUncontrolled] = useState(defaultOpen); + // A drag that dismisses the panel hands its velocity to the exit spring; every other close uses the shorter tween. + const [flung, setFlung] = useState(false); + // When the drawer last opened, so a click that reopens it mid-close is not also read as a click outside the leaving panel. + const openedAt = useRef(0); + const open = openProp ?? uncontrolled; + const setOpen = useCallback((next: boolean) => { + setFlung(false); + if (next) openedAt.current = performance.now(); + if (openProp === undefined) setUncontrolled(next); + onOpenChange?.(next); + }, [openProp, onOpenChange]); + const fling = useCallback(() => { setOpen(false); setFlung(true); }, [setOpen]); + const value = useMemo(() => ({ open, flung, setOpen, fling, openedAt }), [open, flung, setOpen, fling]); + return ; +} + +export const DrawerTrigger = DialogPrimitive.Trigger; +export const DrawerClose = DialogPrimitive.Close; + +export interface DrawerContentProps + extends ComponentPropsWithoutRef { + title: string; + description?: string; + children: ReactNode; + side?: "left" | "right" | "top" | "bottom"; + /** Renders the drawer inside this element instead of the page body, anchored to its edges. The element needs position: relative and overflow: hidden. */ + container?: HTMLElement | null; +} + +const fade: Transition = { duration: motionTokens.duration.instant }; +/* A click or Escape returns the panel quickly; a flick keeps its velocity in a spring of the same length. The shadow fades over the last stretch so it leaves with the panel instead of popping away at unmount. */ +const shadowOut: Transition = { duration: motionTokens.duration.standard, times: [0, .65, 1], ease: "linear" }; +const leave: Transition = { default: { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.standard] }, opacity: shadowOut }; +const flingOut: Transition = { default: { ...motionTokens.spring.smooth, visualDuration: motionTokens.duration.standard }, opacity: shadowOut }; + +/** When the title or description changes while open, the new copy rises in and the old copy leaves upward. */ +function SwapText({ text }: { text: string }) { + const reduced = useReducedMotion(); + return ( + + + {text} + + + ); +} + +export function DrawerContent({ + title, + description, + children, + side = "right", + container, + className, + onInteractOutside, + ...props +}: DrawerContentProps) { + const drawer = useContext(DrawerContext); + const reduced = useReducedMotion(); + const panelRef = useRef(null); + const offset = useMotionValue(0); + const pan = useRef(null); + const axis = side === "left" || side === "right" ? "x" : "y"; + const sign = side === "right" || side === "bottom" ? 1 : -1; + const offscreen = { [axis]: `${sign * 100}%` }; + const classes = [styles.content, className].filter(Boolean).join(" "); + const draggable = drawer !== null && !reduced; + + const panelSize = () => (axis === "x" ? panelRef.current?.offsetWidth : panelRef.current?.offsetHeight) ?? 480; + + // The header is the grab handle. It follows the pointer toward the edge and rubber-bands the other way. + function panStart(event: PointerEvent) { + const target = event.target instanceof Element ? event.target : null; + if (!draggable || target?.closest("button, a, input, select, textarea, [role='button']")) return; + // The entrance animates in percent of the panel, so a grab mid-flight converts it to pixels. + const value = offset.get(); + pan.current = typeof value === "number" ? value : parseFloat(value) / 100 * panelSize(); + offset.stop(); + } + function panMove(_: PointerEvent, info: PanInfo) { + if (pan.current === null) return; + const toward = (pan.current + info.offset[axis]) * sign; + offset.set(sign * (toward >= 0 ? toward : -Math.sqrt(-toward))); + } + // Past a third of the panel, or on a quick flick toward the edge, the drawer closes and keeps its velocity; otherwise it springs back. + function panEnd(_: PointerEvent, info: PanInfo) { + if (pan.current === null) return; + pan.current = null; + const toward = Number(offset.get()) * sign; + if (toward > panelSize() / 3 || (toward > 0 && info.velocity[axis] * sign > 500)) drawer?.fling(); + else animate(offset, 0, motionTokens.spring.snappy); + } + + const inner = <> + +
+ + {description ? ( + + + + ) : null} +
+ + +
+
{children}
+ ; + + // Under a bare Radix root the open state is unknown here, so CSS keyframes keyed off data-state animate the layers instead. + if (drawer === null) { + return ( + + + {inner} + + ); + } + + // The panel springs fully opaque from its own edge and returns to it faster than it arrived, from wherever it is. + return ( + + {drawer.open && ( + + + + + { + onInteractOutside?.(event); + if (event.detail.originalEvent.timeStamp < drawer.openedAt.current) event.preventDefault(); + }} + > + reduced ? { opacity: 0, transition: fade } : { ...offscreen, opacity: [1, 1, 0], transition: flung ? flingOut : leave } }} + initial={reduced ? { opacity: 0 } : { ...offscreen, opacity: 1 }} + animate={reduced ? { opacity: 1 } : { [axis]: 0, opacity: 1 }} + exit="exit" + transition={reduced ? fade : motionTokens.spring.smooth} + > + {inner} + + + + )} + + ); +} + +export default Drawer; diff --git a/packages/uiarc/src/empty-state/empty-state.module.css b/packages/uiarc/src/empty-state/empty-state.module.css new file mode 100644 index 00000000..127e9677 --- /dev/null +++ b/packages/uiarc/src/empty-state/empty-state.module.css @@ -0,0 +1,13 @@ +.root { display: flex; width: 100%; flex-direction: column; align-items: center; padding: clamp(var(--space-8), 8vw, var(--space-12)) var(--space-5); text-align: center; } +.icon { position: relative; display: grid; width: var(--space-12); height: var(--space-12); place-items: center; border: 1px solid var(--border); border-radius: var(--radius-panel); background: var(--surface-muted); color: var(--text-secondary); animation: empty-state-icon var(--duration-considered) var(--ease-enter) both; } +.glyph { display: grid; place-items: center; } +.frame { width: 100%; max-width: 100%; } +.copy { display: flow-root; } +.root h3 { position: relative; margin: var(--space-5) 0 0; color: var(--foreground); font-size: var(--text-base); font-weight: 500; line-height: var(--leading-body); } +.root p { position: relative; max-width: 18rem; margin: var(--space-2) auto 0; color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-body); } +/* Centered copy wraps into even lines, so a new description never leaves a single word hanging. */ +.line { display: block; text-wrap: balance; } +.action { display: flex; flex-wrap: wrap; justify-content: center; gap: var(--space-3); margin-top: var(--space-5); } +/* The icon settles in once when the state first appears; later changes crossfade in place. */ +@keyframes empty-state-icon { from { opacity: 0; transform: scale(.92); } to { opacity: 1; transform: scale(1); } } +@media (prefers-reduced-motion: reduce) { .icon { animation: none; } } diff --git a/packages/uiarc/src/empty-state/empty-state.tsx b/packages/uiarc/src/empty-state/empty-state.tsx new file mode 100644 index 00000000..2c2d28c8 --- /dev/null +++ b/packages/uiarc/src/empty-state/empty-state.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { isValidElement, useEffect, useLayoutEffect, useRef, type ReactNode } from "react"; +import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, useReducedMotion, type AnimationPlaybackControls, type HTMLMotionProps, type MotionProps, type TargetAndTransition, type Transition } from "motion/react"; +import { Folder } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./empty-state.module.css"; + +export interface EmptyStateProps { + title: string; + description: string; + action?: ReactNode; + icon?: ReactNode; + className?: string; + /** Optional accessible label for the state region. */ + label?: string; +} + +const exitFast: Transition = { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] }; +const textIn: TargetAndTransition = { opacity: 0, y: "0.3em", filter: `blur(${motionTokens.blur.soft}px)` }; +const textOut: TargetAndTransition = { opacity: 0, y: "-0.3em", filter: `blur(${motionTokens.blur.subtle}px)`, transition: exitFast }; +const iconIn: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` }; +const shown: TargetAndTransition = { opacity: 1, y: "0em", scale: 1, filter: "blur(0px)" }; +const fadeOut: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } }; + +/** Outgoing copies are hidden from assistive tech while they fade. */ +function Swap(props: HTMLMotionProps<"span">) { + const present = useIsPresent(); + return ; +} + +/** A new icon component crossfades in; re-rendering the same icon stays still. */ +function iconKey(icon: ReactNode) { + if (!isValidElement(icon)) return "icon"; + const type = icon.type as string | { displayName?: string; name?: string }; + return typeof type === "string" ? type : type.displayName ?? type.name ?? "icon"; +} + +/** Follows its content height. After `morphKey` changes, the height springs from the old size to the new one and then returns to auto, so passive reflows (a resize, a font swap) follow instantly. It clips only while moving, so focus rings stay visible at rest. */ +function HeightFrame({ reduce, morphKey, children }: { reduce: boolean | null; morphKey: string; children: ReactNode }) { + const frame = useRef(null); + const content = useRef(null); + const height = useMotionValue("auto"); + const changedAt = useRef(0); + useLayoutEffect(() => { changedAt.current = performance.now(); }, [morphKey]); + useEffect(() => { + const node = content.current; + if (!node || typeof ResizeObserver === "undefined") return; + let last: number | undefined; + let controls: AnimationPlaybackControls | undefined; + const settle = () => { height.jump("auto"); if (frame.current) Object.assign(frame.current.style, { overflow: "", height: "auto" }); }; + const observer = new ResizeObserver(([entry]) => { + if (!entry) return; + const next = entry.borderBoxSize?.[0]?.blockSize ?? node.offsetHeight; + const current = height.get(); + const from = typeof current === "number" ? current : last; + last = next; + controls?.stop(); + if (reduce || from === undefined || from === next || performance.now() - changedAt.current > 120) return settle(); + // Pin the old height before this frame paints, then spring to the new one. + if (frame.current) Object.assign(frame.current.style, { overflow: "hidden", height: `${from}px` }); + controls = animate(height, [from, next], { ...motionTokens.spring.smooth, onComplete: settle }); + }); + observer.observe(node); + return () => { observer.disconnect(); controls?.stop(); }; + }, [height, reduce]); + return +
{children}
+
; +} + +export function EmptyState({ title, description, action, icon, className, label }: EmptyStateProps) { + const reduce = useReducedMotion(); + const glyph = icon ?? ; + const enter: Transition = reduce ? { duration: motionTokens.duration.instant } : { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }; + const swap: MotionProps = { initial: reduce ? { opacity: 0 } : textIn, animate: shown, exit: reduce ? fadeOut : textOut, transition: enter }; + // The result of an action morphs in place: the icon crossfades and the copy rises in while the old copy leaves. + return
+ + +

{title}

+

{description}

+
+ {action &&
{action}
} +
; +} + +export default EmptyState; diff --git a/packages/uiarc/src/foundation.css b/packages/uiarc/src/foundation.css new file mode 100644 index 00000000..b49c1e73 --- /dev/null +++ b/packages/uiarc/src/foundation.css @@ -0,0 +1,211 @@ +:root { + color-scheme: light; + --neutral-0: oklch(100% 0 0); + --neutral-1: oklch(99% 0 0); + --neutral-2: oklch(97.8% 0 0); + --neutral-3: oklch(95.8% 0 0); + --neutral-4: oklch(91.5% 0 0); + --neutral-5: oklch(84% 0 0); + --neutral-6: oklch(72% 0 0); + --neutral-7: oklch(59% 0 0); + --neutral-8: oklch(46% 0 0); + --neutral-9: oklch(34% 0 0); + --neutral-10: oklch(23% 0 0); + --neutral-11: oklch(15% 0 0); + --background: var(--neutral-0); + --surface: var(--neutral-0); + --surface-raised: var(--neutral-0); + --surface-muted: var(--neutral-2); + --foreground: var(--neutral-11); + --text-secondary: var(--neutral-8); + --text-muted: var(--neutral-7); + --border: oklch(93.5% 0 0); + --border-subtle: oklch(96.5% 0 0); + --border-strong: oklch(82% 0 0); + --accent: oklch(33% 0 0); + --accent-strong: oklch(24% 0 0); + --accent-subtle: oklch(33% 0 0 / .1); + --accent-foreground: var(--background); + /* Selection controls (switch, checkbox, radio, slider). --control-on fills a chosen control; --control-glyph is the check or dot drawn on it; + thumbs stay white in both states so they always read against the track. Tuned per accent below so white thumbs hold on every hue. */ + --control-on: oklch(23% 0 0); + --control-glyph: oklch(100% 0 0); + --control-track: oklch(89.5% 0 0); + --control-track-hover: oklch(86% 0 0); + --control-thumb: oklch(100% 0 0); + --control-thumb-on: oklch(100% 0 0); + --control-thumb-shadow: 0 0 0 .5px oklch(0% 0 0 / .07), 0 1px 2px oklch(0% 0 0 / .14), 0 2px 6px oklch(0% 0 0 / .06); + --control-on-subtle: color-mix(in oklab, var(--control-on) 10%, transparent); + /* Slider fills. Same as --control-on except neutral dark, where a mid grey keeps the white thumb distinct. */ + --control-fill: var(--control-on); + /* Pointer focus draws no ring (product decision). --focus-ring is the halo a few fields drew for any input method, so it stays transparent. + Keyboard focus uses the outline at the end of this file; tune it with --focus-outline, --focus-outline-width and --focus-outline-offset. */ + --focus-ring: transparent; + /* Categorical palette: one cool pastel family for tags, method labels, chart series and status. Light values are deepened so text + reads at AA on a soft tint of itself; dark values are the bright pastels. Tint them with color-mix(in oklab, …), never oklch. */ + --tone-teal: oklch(50% .095 182); + --tone-sky: oklch(51% .11 240); + --tone-orchid: oklch(52% .17 322); + --tone-violet: oklch(51% .16 290); + --tone-rose: oklch(53% .18 10); + --tone-amber: oklch(55% .12 68); + --tone-green: oklch(50% .12 162); + /* Status roles sit in the same family: success leans teal green, danger rose, warning a soft amber, info sky. */ + --success: var(--tone-green); + --warning: var(--tone-amber); + --danger: var(--tone-rose); + --info: var(--tone-sky); + --shadow-resting: 0 1px 2px oklch(0% 0 0 / .035); + --shadow-raised: 0 6px 18px oklch(0% 0 0 / .065), 0 1px 3px oklch(0% 0 0 / .035); + --shadow-floating: 0 20px 48px oklch(0% 0 0 / .105), 0 3px 10px oklch(0% 0 0 / .045); + /* Brand gradient: soft lavender to warm peach. Light enough for dark text (--arc-gradient-foreground, >12:1). */ + --arc-gradient-from: oklch(90% .045 300); + --arc-gradient-to: oklch(92% .045 65); + --arc-gradient: linear-gradient(100deg, var(--arc-gradient-from), var(--arc-gradient-to)); + --arc-gradient-foreground: oklch(22% .01 300); + /* Faint wash for backgrounds and tinted panels. */ + --arc-gradient-soft: linear-gradient(135deg, oklch(97.5% .016 300), oklch(98% .016 65)); + /* Hairline borders and rules. */ + --arc-gradient-line: linear-gradient(100deg, oklch(83% .06 300), oklch(86% .06 65)); + /* Text-safe stops for gradient text and small marks (>4.5:1 on the surface). */ + --arc-gradient-ink: linear-gradient(100deg, oklch(47% .1 300), oklch(50% .09 55)); + --space-1: .25rem; --space-2: .5rem; --space-3: .75rem; --space-4: 1rem; + --space-5: 1.25rem; --space-6: 1.5rem; --space-8: 2rem; --space-10: 2.5rem; + --space-12: 3rem; --space-16: 4rem; --space-20: 5rem; --space-24: 6rem; + --radius-control: 1.125rem; --radius-panel: 1.625rem; --radius-surface: 2.125rem; --radius-pill: 9999px; + --control-height-sm: 2.25rem; --control-height-md: 2.75rem; --control-height-lg: 3.125rem; + --font-display: var(--font-geist, "Geist Variable"), sans-serif; + --font-body: var(--font-inter, "Inter Variable"), sans-serif; + --text-xs: .75rem; --text-sm: .875rem; --text-base: 1rem; --text-lg: 1.125rem; + --text-xl: 1.375rem; --text-2xl: 1.75rem; --text-3xl: 2.25rem; + --text-4xl: 3.25rem; --text-5xl: 4.5rem; + --tracking-display: -.03em; --tracking-body: -.01em; + --leading-display: 1.1; --leading-body: 1.4; + --ease-enter: cubic-bezier(.16,1,.3,1); + --ease-standard: cubic-bezier(.22,1,.36,1); + --ease-exit: cubic-bezier(.7,0,.84,0); + --ease-in-out: cubic-bezier(.65,0,.35,1); + /* Critically damped spring: fast start, smooth settle, never overshoots (no jitter). Pair with --duration-spring for transform transitions. */ + --ease-spring: linear(0, 0.0213, 0.0739, 0.1443, 0.2235, 0.305, 0.3849, 0.4606, 0.5305, 0.594, 0.6508, 0.7011, 0.7452, 0.7836, 0.8168, 0.8454, 0.8699, 0.8907, 0.9084, 0.9234, 0.9361, 0.9467, 0.9557, 0.9632, 0.9694, 0.9747, 0.979, 0.9826, 0.9857, 0.9882, 0.9902, 0.992, 0.9934, 0.9946, 0.9955, 0.9963, 1); + --duration-instant: 120ms; --duration-fast: 160ms; --duration-standard: 240ms; --duration-considered: 480ms; --duration-spring: 580ms; +} + +:root[data-theme="dark"] { + color-scheme: dark; + --background: oklch(19% 0 0); + --surface: oklch(21.5% 0 0); + --surface-raised: oklch(24% 0 0); + /* Keep muted surfaces and hover states distinct from the base surface in dark mode. */ + --surface-muted: oklch(26% 0 0); + --foreground: oklch(96% 0 0); + --text-secondary: oklch(77% 0 0); + --text-muted: oklch(64% 0 0); + --border: oklch(29% 0 0); + --border-subtle: oklch(25% 0 0); + --border-strong: oklch(40% 0 0); + --focus-ring: transparent; + --accent: oklch(80% 0 0); + --accent-strong: oklch(91% 0 0); + --accent-subtle: oklch(80% 0 0 / .13); + /* Neutral dark inverts: a near-white track carries a dark thumb, so on and off never read alike. */ + --control-on: oklch(93% 0 0); + --control-glyph: oklch(19% 0 0); + --control-track: oklch(33% 0 0); + --control-track-hover: oklch(37% 0 0); + --control-thumb: oklch(97% 0 0); + --control-thumb-on: oklch(19% 0 0); + --control-fill: oklch(62% 0 0); + --control-thumb-shadow: 0 0 0 .5px oklch(0% 0 0 / .3), 0 1px 2px oklch(0% 0 0 / .35), 0 2px 6px oklch(0% 0 0 / .2); + --tone-teal: oklch(79% .13 182); + --tone-sky: oklch(79% .095 236); + --tone-orchid: oklch(76% .15 322); + --tone-violet: oklch(74% .125 290); + --tone-rose: oklch(71% .155 8); + --tone-amber: oklch(83% .12 78); + --tone-green: oklch(79% .14 162); + --success: var(--tone-green); + --warning: var(--tone-amber); + --danger: var(--tone-rose); + --info: var(--tone-sky); + --shadow-resting: 0 1px 2px oklch(0% 0 0 / .18); + --shadow-raised: 0 8px 22px oklch(0% 0 0 / .22); + --shadow-floating: 0 22px 55px oklch(0% 0 0 / .34); + --arc-gradient-from: oklch(38% .05 300); + --arc-gradient-to: oklch(40% .045 60); + --arc-gradient-foreground: oklch(96% .005 300); + --arc-gradient-soft: linear-gradient(135deg, oklch(23.5% .016 300), oklch(24% .014 65)); + --arc-gradient-line: linear-gradient(100deg, oklch(48% .06 300), oklch(52% .055 65)); + --arc-gradient-ink: linear-gradient(100deg, oklch(82% .07 300), oklch(86% .065 70)); +} + +:root[data-accent="neutral"] { --accent: oklch(33% 0 0); --accent-strong: oklch(24% 0 0); --accent-subtle: oklch(33% 0 0 / .1); } +:root[data-accent="violet"] { --accent: #7747ff; --accent-strong: #5528ce; --accent-subtle: rgb(119 71 255 / .13); } +:root[data-accent="blue"] { --accent: #0562ef; --accent-strong: #074db7; --accent-subtle: rgb(5 98 239 / .12); } +:root[data-accent="green"] { --accent: #0db879; --accent-strong: #087c54; --accent-subtle: rgb(13 184 121 / .13); --accent-foreground: #102016; } +:root[data-accent="amber"] { --accent: #f3ad20; --accent-strong: #9c6300; --accent-subtle: rgb(243 173 32 / .16); --accent-foreground: #20190d; } +:root[data-accent="orange"] { --accent: #f48120; --accent-strong: #aa4700; --accent-subtle: rgb(244 129 32 / .13); --accent-foreground: #17130f; } +:root[data-accent="coral"] { --accent: #f15f55; --accent-strong: #b92c27; --accent-subtle: rgb(241 95 85 / .14); --accent-foreground: #21110f; } +:root[data-accent="rose"] { --accent: #ed4e9d; --accent-strong: #ae2570; --accent-subtle: rgb(237 78 157 / .14); --accent-foreground: #250f1b; } +:root[data-theme="dark"][data-accent="neutral"] { --accent: oklch(80% 0 0); --accent-strong: oklch(91% 0 0); --accent-subtle: oklch(80% 0 0 / .13); } +:root[data-theme="dark"][data-accent="violet"] { --accent: #a78bff; --accent-strong: #c7b7ff; --accent-subtle: rgb(119 71 255 / .22); } +:root[data-theme="dark"][data-accent="blue"] { --accent: #6ba3ff; --accent-strong: #a4c7ff; --accent-subtle: rgb(5 98 239 / .22); } +:root[data-theme="dark"][data-accent="green"] { --accent: #53dca6; --accent-strong: #93efd0; --accent-subtle: rgb(13 184 121 / .2); } +:root[data-theme="dark"][data-accent="amber"] { --accent: #ffcb62; --accent-strong: #ffe0a1; --accent-subtle: rgb(243 173 32 / .2); } +:root[data-theme="dark"][data-accent="orange"] { --accent: #ffad5e; --accent-strong: #ffd0a0; --accent-subtle: rgb(244 129 32 / .2); --accent-foreground: #17130f; } +:root[data-theme="dark"][data-accent="coral"] { --accent: #ff9386; --accent-strong: #ffc1ba; --accent-subtle: rgb(241 95 85 / .2); } +:root[data-theme="dark"][data-accent="rose"] { --accent: #ff8bc5; --accent-strong: #ffc0df; --accent-subtle: rgb(237 78 157 / .2); } + +/* Selection control fills per accent. Light: the accent, deepened slightly where a white thumb needs it. Dark: a mid tone instead of the pastel + text accent, so white thumbs and checks keep contrast without a neon track. Amber keeps a dark glyph because white on yellow washes out. */ +:root[data-accent="neutral"] { --control-on: oklch(23% 0 0); --control-thumb-on: oklch(100% 0 0); --control-glyph: oklch(100% 0 0); } +:root[data-accent="violet"] { --control-on: #7747ff; --control-thumb-on: #fff; --control-glyph: #fff; } +:root[data-accent="blue"] { --control-on: #0562ef; --control-thumb-on: #fff; --control-glyph: #fff; } +:root[data-accent="green"] { --control-on: #10a870; --control-thumb-on: #fff; --control-glyph: #fff; } +:root[data-accent="amber"] { --control-on: #eda11a; --control-thumb-on: #fff; --control-glyph: #2a1c03; } +:root[data-accent="orange"] { --control-on: #f07818; --control-thumb-on: #fff; --control-glyph: #fff; } +:root[data-accent="coral"] { --control-on: #ec564b; --control-thumb-on: #fff; --control-glyph: #fff; } +:root[data-accent="rose"] { --control-on: #e64494; --control-thumb-on: #fff; --control-glyph: #fff; } +:root[data-theme="dark"][data-accent="neutral"] { --control-on: oklch(93% 0 0); --control-thumb-on: oklch(19% 0 0); --control-glyph: oklch(19% 0 0); } +:root[data-theme="dark"][data-accent="violet"] { --control-on: #8a66ff; --control-thumb-on: #fff; --control-glyph: #fff; --control-fill: #8a66ff; } +:root[data-theme="dark"][data-accent="blue"] { --control-on: #3b82f6; --control-thumb-on: #fff; --control-glyph: #fff; --control-fill: #3b82f6; } +:root[data-theme="dark"][data-accent="green"] { --control-on: #1fae78; --control-thumb-on: #fff; --control-glyph: #fff; --control-fill: #1fae78; } +:root[data-theme="dark"][data-accent="amber"] { --control-on: #e8a52a; --control-thumb-on: #fff; --control-glyph: #241803; --control-fill: #e8a52a; } +:root[data-theme="dark"][data-accent="orange"] { --control-on: #ef873a; --control-thumb-on: #fff; --control-glyph: #fff; --control-fill: #ef873a; } +:root[data-theme="dark"][data-accent="coral"] { --control-on: #ec6a60; --control-thumb-on: #fff; --control-glyph: #fff; --control-fill: #ec6a60; } +:root[data-theme="dark"][data-accent="rose"] { --control-on: #e457a0; --control-thumb-on: #fff; --control-glyph: #fff; --control-fill: #e457a0; } + +/* Chart series palette, shared by every chart. Series 1 is the accent itself; series 2 to 4 rotate its hue at lightness steps + around it, so they stay distinct for every accent. A neutral accent falls back to a blue. Validated with the dataviz script + across all eight accents in both themes: every pair (not only neighbours) clears CVD ΔE 9 and normal vision ΔE 17. Browsers + without relative color get the neutral set. Override --series-1 to --series-4 on any element to rebrand a chart. */ +:root { --series-1: #1f7dcf; --series-2: #7128a5; --series-3: #e58f00; --series-4: #009e84; } +:root[data-theme="dark"] { --series-1: #55adff; --series-2: #9c37be; --series-3: #e66e00; --series-4: #00a861; } +@supports (color: oklch(from red clamp(.4, l * sign(max(c - .02, 0)) + .5, .8) c h)) { + :root { + --series-1: oklch(from var(--accent) calc(l * sign(max(c - .02, 0)) + .58 * (1 - sign(max(c - .02, 0)))) calc(c * sign(max(c - .02, 0)) + .15 * (1 - sign(max(c - .02, 0)))) calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))))); + --series-2: oklch(from var(--accent) clamp(.45, l * sign(max(c - .02, 0)) + .58 * (1 - sign(max(c - .02, 0))) - 0.25, .76) .19 calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))) + 57)); + --series-3: oklch(from var(--accent) clamp(.45, l * sign(max(c - .02, 0)) + .58 * (1 - sign(max(c - .02, 0))) + 0.14, .76) .18 calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))) + 184)); + --series-4: oklch(from var(--accent) clamp(.45, l * sign(max(c - .02, 0)) + .58 * (1 - sign(max(c - .02, 0))), .76) .21 calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))) + 292)); + } + :root[data-theme="dark"] { + --series-1: oklch(from var(--accent) calc(l * sign(max(c - .02, 0)) + .73 * (1 - sign(max(c - .02, 0)))) calc(c * sign(max(c - .02, 0)) + .15 * (1 - sign(max(c - .02, 0)))) calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))))); + --series-2: oklch(from var(--accent) clamp(.485, l * sign(max(c - .02, 0)) + .73 * (1 - sign(max(c - .02, 0))) - 0.19, .665) .21 calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))) + 66)); + --series-3: oklch(from var(--accent) clamp(.485, l * sign(max(c - .02, 0)) + .73 * (1 - sign(max(c - .02, 0))) + 0.02, .665) .21 calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))) + 175)); + --series-4: oklch(from var(--accent) clamp(.485, l * sign(max(c - .02, 0)) + .73 * (1 - sign(max(c - .02, 0))) - 0.1, .665) .18 calc(h * sign(max(c - .02, 0)) + 250 * (1 - sign(max(c - .02, 0))) + 270)); + } +} + +/* Focus. Pointer focus never draws a ring (product decision). Keyboard focus (:focus-visible) draws a subtle accent outline, so keyboard users + can always see where they are (WCAG 2.4.7). Left out of the outline: text fields, which match :focus-visible on a mouse click too and show + focus with their border and caret; menu items and listbox options, whose highlight fill marks the keyboard position; and tabindex="-1" + targets (dialog panels, regions) that only receive focus from script. + Tune it on :root or any element, no !important needed: + --focus-outline color (default: the accent, softened); set transparent to hide it + --focus-outline-width default 2px + --focus-outline-offset default 2px; components inside clipped containers set a negative offset */ +:focus:not(:focus-visible), +:is(input:not([type="button"], [type="checkbox"], [type="color"], [type="file"], [type="image"], [type="radio"], [type="range"], [type="reset"], [type="submit"]), textarea, [contenteditable]:not([contenteditable="false"]), [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="option"], [tabindex="-1"]):focus { outline: none !important; } +:focus-visible:not(input:not([type="button"], [type="checkbox"], [type="color"], [type="file"], [type="image"], [type="radio"], [type="range"], [type="reset"], [type="submit"]), textarea, [contenteditable]:not([contenteditable="false"]), [role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"], [role="option"], [tabindex="-1"]) { + outline: var(--focus-outline-width, 2px) solid var(--focus-outline, color-mix(in oklab, var(--accent-strong) 72%, transparent)) !important; + outline-offset: var(--focus-outline-offset, 2px) !important; +} diff --git a/packages/uiarc/src/input/input.module.css b/packages/uiarc/src/input/input.module.css new file mode 100644 index 00000000..c836b587 --- /dev/null +++ b/packages/uiarc/src/input/input.module.css @@ -0,0 +1,22 @@ +/* No row gap: grid tracks clamp a negative margin at zero, so a closed message row would still pay the gap. Each row carries its own space instead. */ +.field { display: grid; min-width: 0; } +.label { margin-bottom: var(--space-2); color: var(--foreground); font-size: var(--text-sm); font-weight: 500; line-height: var(--leading-body); } +/* Focus answers with the border colour alone (no rings or halos); the field itself never changes size. */ +.input { width: 100%; min-height: var(--control-height-md); padding: 0 var(--space-3); border: 1px solid var(--border-strong); border-radius: var(--radius-control); background: var(--surface); color: var(--foreground); font: inherit; font-size: var(--text-sm); line-height: var(--leading-body); letter-spacing: var(--tracking-body); outline: none; transition: border-color var(--duration-fast) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard); } +.input::placeholder { color: var(--text-muted); } +@media (hover: hover) and (pointer: fine) { .input:hover:not(:disabled, [aria-invalid="true"]) { border-color: var(--foreground); } } +.input:focus-visible { border-color: var(--foreground); } +.input[aria-invalid="true"] { border-color: var(--danger); } +.input:disabled { cursor: not-allowed; opacity: .5; background: var(--surface-muted); } +/* The row's space is padding inside the clipped slot, so the height animates from a true zero. */ +.messageSlot { display: block; overflow: hidden; } +.description, .error { display: block; padding-top: var(--space-2); font-size: var(--text-xs); line-height: var(--leading-body); } +.description { color: var(--text-muted); } .error { color: var(--danger); } +/* Words are measured against this box when they pop out to leave, so it must be the positioned parent. */ +.words { position: relative; display: block; } +.word { display: inline-block; white-space: pre; } +/* One column per character of a count. Tabular digits keep columns equal, so only a gained or lost digit changes the width. */ +.column { position: relative; display: inline-flex; justify-content: center; font-variant-numeric: tabular-nums; } +.column > span { display: inline-block; } +.srOnly { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +@media (prefers-reduced-motion: reduce) { .input { transition-duration: .01ms; } } diff --git a/packages/uiarc/src/input/input.tsx b/packages/uiarc/src/input/input.tsx new file mode 100644 index 00000000..850fa3d8 --- /dev/null +++ b/packages/uiarc/src/input/input.tsx @@ -0,0 +1,85 @@ +"use client"; + +import { forwardRef, useEffect, useId, useRef, useState } from "react"; +import type { InputHTMLAttributes } from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./input.module.css"; + +export interface InputProps extends InputHTMLAttributes { + label: string; + description?: string; + error?: string; +} + +/* Digits roll up when a number grows and down when it shrinks; `custom` hands the latest direction to digits already leaving. */ +const digit = { + enter: (direction: number) => ({ opacity: 0, y: `${direction * 0.6}em`, filter: `blur(${motionTokens.blur.subtle}px)` }), + center: { opacity: 1, y: 0, filter: "blur(0px)" }, + exit: (direction: number) => ({ opacity: 0, y: `${direction * -0.6}em`, filter: `blur(${motionTokens.blur.subtle}px)` }), +}; +const isNumber = (word: string) => /^\d[\d.,/:]*%?$/.test(word); + +/** A count in the copy, such as "12 characters", rolls only the digits that changed; a gained or lost digit opens or closes its width. */ +function RollingNumber({ word }: { word: string }) { + const reduced = useReducedMotion(); + const [shown, setShown] = useState({ word, direction: 1 }); + if (shown.word !== word) setShown({ word, direction: parseFloat(word.replace(/,/g, "")) < parseFloat(shown.word.replace(/,/g, "")) ? -1 : 1 }); + const characters = word.split(""); + const transition = reduced ? { duration: 0 } : { y: motionTokens.spring.snappy, width: motionTokens.spring.morph, opacity: { duration: motionTokens.duration.fast }, filter: { duration: motionTokens.duration.fast } }; + return {characters.map((character, index) => + {character} + )}; +} + +/** Changed words rise in and unblur while unchanged words hold still, and numbers roll. Assistive tech reads the plain copy. */ +function MotionText({ text }: { text: string }) { + const reduced = useReducedMotion(); + const words = text.split(" "); + return <>{text}; +} + +/** Helper and error copy: the row opens its height on a spring, then the words settle in. */ +function FieldMessage({ id, text, className, alert }: { id?: string; text?: string; className?: string; alert?: boolean }) { + return {text ? : null}; +} + +/** The row tracks the measured copy, so a longer message that wraps opens its next line instead of snapping. */ +function MessageRow({ id, text, className, alert }: { id?: string; text: string; className?: string; alert?: boolean }) { + const reduced = useReducedMotion(); + const copyRef = useRef(null); + const [height, setHeight] = useState("auto"); + useEffect(() => { + const node = copyRef.current; + if (!node || typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(([entry]) => { if (entry) setHeight(entry.borderBoxSize?.[0]?.blockSize ?? node.offsetHeight); }); + observer.observe(node); + return () => observer.disconnect(); + }, []); + // Reduced motion mounts the row at full height: a zero-duration open would still paint one collapsed frame. The presence starts + // with initial={false}, so rows present at hydration render the same on server and client either way. + return + + ; +} + +export const Input = forwardRef(function Input( + { label, description, error, id, className, ...props }, ref, +) { + const generatedId = useId(); + const controlId = id ?? generatedId; + const hintId = description ? `${controlId}-description` : undefined; + const errorId = error ? `${controlId}-error` : undefined; + const describedBy = [props["aria-describedby"], hintId, errorId].filter(Boolean).join(" ") || undefined; + return
+ + + + +
; +}); + +Input.displayName = "Input"; diff --git a/packages/uiarc/src/lib/arc-provider.tsx b/packages/uiarc/src/lib/arc-provider.tsx new file mode 100644 index 00000000..6ef9a78c --- /dev/null +++ b/packages/uiarc/src/lib/arc-provider.tsx @@ -0,0 +1,94 @@ +"use client"; + +/** + * Lets an app swap the link and image elements Arc components render (kuratlielia/arc-library#13). + * + * Without a provider, Arc renders a plain `` and ``, so components work in any React app (Vite, Remix, Astro, + * plain React). Wrap the app once to use your framework's or your own components instead: + * + * import Link from "next/link"; + * import Image from "next/image"; + * import { ArcProvider } from "@/components/arc/lib/arc-provider"; + * + * {children} + * + * Any component that accepts these props works, such as a locale-aware Link from next-intl or a React Router Link + * wrapped to map `href` to `to`. + */ +import { createContext, createElement, useContext, useMemo, type AnchorHTMLAttributes, type ComponentType, type ImgHTMLAttributes, type ReactNode, type Ref } from "react"; + +/** The props Arc passes to a link: an href plus ordinary anchor attributes. */ +export interface ArcLinkProps extends AnchorHTMLAttributes { + href: string; + ref?: Ref; +} + +/** + * The props Arc passes to an image. A subset of next/image's props, so next/image can be passed as is: either `fill` + * (cover the positioned parent) or `width` and `height`, plus `sizes` and `priority` as hints. + */ +export interface ArcImageProps extends Omit, "src" | "alt" | "width" | "height" | "loading" | "srcSet"> { + src: string; + alt: string; + width?: number; + height?: number; + /** Fills the nearest positioned parent, like next/image's `fill`. */ + fill?: boolean; + /** Loads the image eagerly with high priority, like next/image's `priority`. */ + priority?: boolean; + loading?: "eager" | "lazy"; + ref?: Ref; +} + +export type ArcLinkComponent = ComponentType; +export type ArcImageComponent = ComponentType; + +/** The default link: a plain anchor. */ +export function ArcAnchor(props: ArcLinkProps) { + return ; +} + +const fillStyle = { position: "absolute", inset: 0, width: "100%", height: "100%" } as const; + +/** The default image: a plain, lazily decoded `` that understands `fill` and `priority`. */ +export function ArcImg({ alt, fill, priority, loading, style, ...props }: ArcImageProps) { + // eslint-disable-next-line @next/next/no-img-element -- the framework-free default; pass next/image through ArcProvider instead. + return {alt}; +} + +interface ArcComponents { + link: ArcLinkComponent; + image: ArcImageComponent; +} + +const ArcContext = createContext({ link: ArcAnchor, image: ArcImg }); + +export interface ArcProviderProps { + /** The link component Arc renders for navigation, such as next/link or your own wrapped Link. Defaults to ``. */ + link?: ArcLinkComponent; + /** The image component Arc renders for photos, such as next/image. Defaults to ``. */ + image?: ArcImageComponent; + children: ReactNode; +} + +/** Sets the link and image components for every Arc component inside it. Nested providers inherit what they do not set. */ +export function ArcProvider({ link, image, children }: ArcProviderProps) { + const parent = useContext(ArcContext); + const value = useMemo(() => ({ link: link ?? parent.link, image: image ?? parent.image }), [link, image, parent]); + return {children}; +} + +/** The link component from the nearest ArcProvider, or a plain anchor. */ +export const useArcLink = () => useContext(ArcContext).link; +/** The image component from the nearest ArcProvider, or a plain img. */ +export const useArcImage = () => useContext(ArcContext).image; + +/** What Arc components render for a link: the provider's link component, or a plain anchor. */ +export function ArcLink(props: ArcLinkProps) { + return createElement(useArcLink(), props); +} + +/** What Arc components render for an image: the provider's image component, or a plain img. */ +export function ArcImage(props: ArcImageProps) { + return createElement(useArcImage(), props); +} diff --git a/packages/uiarc/src/lib/motion-tokens.ts b/packages/uiarc/src/lib/motion-tokens.ts new file mode 100644 index 00000000..00767649 --- /dev/null +++ b/packages/uiarc/src/lib/motion-tokens.ts @@ -0,0 +1,2 @@ +/** Shared alias used by the gallery. The registry source lives in registry/motion-tokens.ts. */ +export { motionTokens } from "../motion-tokens"; diff --git a/packages/uiarc/src/motion-tokens.ts b/packages/uiarc/src/motion-tokens.ts new file mode 100644 index 00000000..8dfa91ea --- /dev/null +++ b/packages/uiarc/src/motion-tokens.ts @@ -0,0 +1,25 @@ +/** Motion presets are shared by the gallery and future registry consumers. */ +export const motionTokens = { + duration: { instant: 0.12, fast: 0.16, exit: 0.18, standard: 0.24, considered: 0.48 }, + ease: { + enter: [0.16, 1, 0.3, 1], + exit: [0.7, 0, 0.84, 0], + standard: [0.22, 1, 0.36, 1], + /** For elements that move while already on screen. */ + inOut: [0.65, 0, 0.35, 1], + }, + spring: { + responsive: { type: "spring", stiffness: 520, damping: 44 }, + gentle: { type: "spring", stiffness: 340, damping: 34 }, + /** Presses, toggles, thumbs, and small indicators. Settles fast and never overshoots, so nothing jitters. */ + snappy: { type: "spring", visualDuration: 0.26, bounce: 0 }, + /** Panels, height changes, and layout shifts. Critically damped, never overshoots. */ + smooth: { type: "spring", visualDuration: 0.4, bounce: 0 }, + /** Shape morphs, shared layout highlights, and width changes that follow new content. No bounce: sizes and positions settle without overshoot. */ + morph: { type: "spring", visualDuration: 0.42, bounce: 0 }, + }, + /** Stagger steps in seconds. Keep total stagger under roughly 0.4s. */ + stagger: { char: 0.016, word: 0.04, line: 0.08, item: 0.035 }, + /** Blur radii in px for text and content crossfades. Keep blur small and brief. */ + blur: { subtle: 2, soft: 4, text: 8 }, +} as const; diff --git a/packages/uiarc/src/popover/popover.module.css b/packages/uiarc/src/popover/popover.module.css new file mode 100644 index 00000000..c54227e7 --- /dev/null +++ b/packages/uiarc/src/popover/popover.module.css @@ -0,0 +1,32 @@ +/* Press feedback on the anchor stays in color. Radix measures the trigger when the panel opens, so a scaled trigger would move the panel. */ +.anchor:active:not(:disabled) { transform: none; } +.content { + --popover-x: 0px; + --popover-y: -5px; + z-index: 80; + min-width: 12rem; + max-width: min(22rem, calc(100vw - 20px)); + padding: 1rem; + border: 1px solid var(--border); + border-radius: var(--radius-panel); + background: var(--surface-raised); + color: var(--foreground); + box-shadow: var(--shadow-floating); + transform-origin: var(--radix-popover-content-transform-origin); + transition: opacity var(--duration-fast) var(--ease-enter), transform var(--duration-spring) var(--ease-spring); +} +/* The panel starts a few pixels toward its trigger and settles on a spring; it leaves faster than it arrives. + Transitions instead of keyframes, so a close that interrupts the open, or a reopen during the close, reverses from where the panel is. */ +.content[data-side="top"] { --popover-y: 5px; } +.content[data-side="left"] { --popover-x: 5px; --popover-y: 0px; } +.content[data-side="right"] { --popover-x: -5px; --popover-y: 0px; } +@starting-style { + .content[data-state="open"] { opacity: 0; transform: translate(var(--popover-x), var(--popover-y)) scale(.97); } +} +/* Radix unmounts when the exit animation ends, so a no-op keyframe times the exit while the transition does the visual work. */ +.content[data-state="closed"] { opacity: 0; transform: translate(calc(var(--popover-x) * .5), calc(var(--popover-y) * .5)) scale(.98); transition: opacity var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard); animation: popover-exit var(--duration-fast) linear both; pointer-events: none; } +.content:focus { outline: none; } +@keyframes popover-exit { to { --popover-exit: 1; } } +@media (prefers-reduced-motion: reduce) { + .content, .content[data-state="closed"] { transform: none; transition: opacity var(--duration-instant) var(--ease-standard); } +} diff --git a/packages/uiarc/src/popover/popover.tsx b/packages/uiarc/src/popover/popover.tsx new file mode 100644 index 00000000..a381153e --- /dev/null +++ b/packages/uiarc/src/popover/popover.tsx @@ -0,0 +1,37 @@ +"use client"; + +import * as PopoverPrimitive from "@radix-ui/react-popover"; +import { forwardRef } from "react"; +import type { ComponentPropsWithoutRef } from "react"; +import styles from "./popover.module.css"; + +export const Popover = PopoverPrimitive.Root; +export const PopoverClose = PopoverPrimitive.Close; + +/** The trigger anchors the panel, so it opts out of press-scale: a scaled rect measured on open would shift the panel as the trigger springs back. */ +export const PopoverTrigger = forwardRef< + HTMLButtonElement, + ComponentPropsWithoutRef +>(function PopoverTrigger({ className, ...props }, ref) { + return ; +}); + +PopoverTrigger.displayName = "PopoverTrigger"; + +export const PopoverContent = forwardRef< + HTMLDivElement, + ComponentPropsWithoutRef +>(function PopoverContent({ className, align = "start", sideOffset = 6, collisionPadding = 10, ...props }, ref) { + return + + ; +}); + +PopoverContent.displayName = "PopoverContent"; diff --git a/packages/uiarc/src/progress/progress.module.css b/packages/uiarc/src/progress/progress.module.css new file mode 100644 index 00000000..99829dc2 --- /dev/null +++ b/packages/uiarc/src/progress/progress.module.css @@ -0,0 +1 @@ +.progress { width: 100%; color: var(--text-secondary); font-size: var(--text-sm); } .meta { display: flex; justify-content: space-between; gap: 12px; margin-bottom: 8px; line-height: var(--leading-body); } .label { position: relative; min-width: 0; } .line { display: block; } .value { display: inline-flex; flex: none; align-items: center; gap: 4px; color: var(--text-muted); font-variant-numeric: tabular-nums; } .count { display: inline-grid; justify-items: end; } /* A hidden "100%" row reserves the widest count, so the check never shifts as the number gains a digit. */ .count::before { content: "100%"; height: 0; overflow: hidden; visibility: hidden; } .done { display: grid; place-items: center; color: var(--success); } .track { height: 7px; overflow: hidden; border: 1px solid var(--border); border-radius: 99px; background: var(--surface-muted); } .fill { display: block; width: 100%; height: 100%; border-radius: inherit; background: var(--accent); transition: background-color var(--duration-standard) var(--ease-standard); } .progress[data-complete] .fill { background: var(--success); transition-delay: 200ms; } @media (prefers-reduced-motion: reduce) { .fill, .progress[data-complete] .fill { transition: none; } } diff --git a/packages/uiarc/src/progress/progress.tsx b/packages/uiarc/src/progress/progress.tsx new file mode 100644 index 00000000..2b4b32c1 --- /dev/null +++ b/packages/uiarc/src/progress/progress.tsx @@ -0,0 +1,60 @@ +"use client"; + +import { useEffect } from "react"; +import { AnimatePresence, animate, motion, useIsPresent, useMotionValue, useReducedMotion, useTransform, type HTMLMotionProps, type TargetAndTransition, type Transition } from "motion/react"; +import { Check } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./progress.module.css"; + +export interface ProgressProps extends Omit, "children"> { + value?: number; + max?: number; + label?: string; + showValue?: boolean; +} + +const exitFast: Transition = { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] }; +const textIn: TargetAndTransition = { opacity: 0, y: "0.3em", filter: `blur(${motionTokens.blur.soft}px)` }; +const textOut: TargetAndTransition = { opacity: 0, y: "-0.3em", filter: `blur(${motionTokens.blur.subtle}px)`, transition: exitFast }; +const iconIn: TargetAndTransition = { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` }; +const shown: TargetAndTransition = { opacity: 1, y: "0em", scale: 1, filter: "blur(0px)" }; +const fadeOut: TargetAndTransition = { opacity: 0, transition: { duration: motionTokens.duration.instant } }; + +/** Outgoing copies are hidden from assistive tech while they fade. */ +function Swap(props: HTMLMotionProps<"span">) { + const present = useIsPresent(); + return ; +} + +export function Progress({ value = 0, max = 100, label, showValue = false, className, ...props }: ProgressProps) { + const reduce = useReducedMotion(); + const safeMax = max > 0 ? max : 100; + const safeValue = Math.min(Math.max(value, 0), safeMax); + const percentage = Math.round((safeValue / safeMax) * 100); + const complete = percentage >= 100; + // One spring drives both the fill and the counted label, so the number always matches the bar. + const progress = useMotionValue(percentage); + // The fill slides in from the left instead of scaling, so its rounded end keeps its shape at every value. + const x = useTransform(progress, latest => `${Math.min(Math.max(latest, 0), 100) - 100}%`); + const counted = useTransform(progress, latest => `${Math.round(Math.min(Math.max(latest, 0), 100))}%`); + useEffect(() => { + if (reduce) { progress.jump(percentage); return; } + const controls = animate(progress, percentage, motionTokens.spring.smooth); + return () => controls.stop(); + }, [percentage, progress, reduce]); + const enter: Transition = reduce ? { duration: motionTokens.duration.instant } : { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }; + const classes = [styles.progress, className].filter(Boolean).join(" "); + return
+ {(label || showValue) ?
+ {label ? {label} : } + {showValue ? + {/* Completion lands as the fill arrives: a check settles in beside the final count. */} + {complete && } + {counted} + : null} +
: null} +
+
; +} + +export default Progress; diff --git a/packages/uiarc/src/scroll-area/scroll-area.module.css b/packages/uiarc/src/scroll-area/scroll-area.module.css new file mode 100644 index 00000000..1231015e --- /dev/null +++ b/packages/uiarc/src/scroll-area/scroll-area.module.css @@ -0,0 +1,79 @@ +.root { position: relative; display: flex; min-width: 0; min-height: 0; flex-direction: column; overflow: hidden; } + +/* Native scrolling with the platform scrollbars hidden; the overlay bars below replace them. */ +.viewport { + --fade-top: 0px; --fade-bottom: 0px; --fade-left: 0px; --fade-right: 0px; + min-width: 0; + min-height: 0; + flex: 1 1 auto; + overscroll-behavior-x: contain; + scrollbar-width: none; + -webkit-overflow-scrolling: touch; +} +.viewport::-webkit-scrollbar { display: none; } +.root[data-orientation="vertical"] > .viewport { overflow-x: hidden; overflow-y: auto; } +.root[data-orientation="horizontal"] > .viewport { overflow-x: auto; overflow-y: hidden; } +.root[data-orientation="both"] > .viewport { overflow: auto; } + +/* Each fade is exactly as long as the content hidden past that edge, up to the fade size, so it grows in with the first pixels of scroll. */ +.viewport[data-fade="vertical"] { + -webkit-mask-image: linear-gradient(to bottom, transparent, #000 var(--fade-top), #000 calc(100% - var(--fade-bottom)), transparent); + mask-image: linear-gradient(to bottom, transparent, #000 var(--fade-top), #000 calc(100% - var(--fade-bottom)), transparent); +} +.viewport[data-fade="horizontal"] { + -webkit-mask-image: linear-gradient(to right, transparent, #000 var(--fade-left), #000 calc(100% - var(--fade-right)), transparent); + mask-image: linear-gradient(to right, transparent, #000 var(--fade-left), #000 calc(100% - var(--fade-right)), transparent); +} +.viewport[data-fade="both"] { + -webkit-mask-image: linear-gradient(to bottom, transparent, #000 var(--fade-top), #000 calc(100% - var(--fade-bottom)), transparent), linear-gradient(to right, transparent, #000 var(--fade-left), #000 calc(100% - var(--fade-right)), transparent); + -webkit-mask-composite: source-in; + mask-image: linear-gradient(to bottom, transparent, #000 var(--fade-top), #000 calc(100% - var(--fade-bottom)), transparent), linear-gradient(to right, transparent, #000 var(--fade-left), #000 calc(100% - var(--fade-right)), transparent); + mask-composite: intersect; +} + +/* Overlay scrollbars: a generous hit area around a thin pill that thickens under the pointer. */ +.track { + position: absolute; + z-index: 1; + opacity: 0; + pointer-events: none; + touch-action: none; + transition: opacity var(--duration-considered) var(--ease-standard); +} +.track[data-axis="y"] { top: 3px; right: 1px; bottom: 3px; width: 11px; } +.track[data-axis="x"] { right: 3px; bottom: 1px; left: 3px; height: 11px; } +.root[data-orientation="both"] > .track[data-axis="y"] { bottom: 13px; } +.root[data-orientation="both"] > .track[data-axis="x"] { right: 13px; } +.track[data-hidden] { display: none; } + +.thumb { position: absolute; top: 0; left: 0; will-change: transform; } +.track[data-axis="y"] .thumb { width: 100%; } +.track[data-axis="x"] .thumb { height: 100%; } +.thumb::after { + content: ""; + position: absolute; + border-radius: var(--radius-pill); + background: color-mix(in oklab, var(--foreground) 30%, transparent); + transition: width var(--duration-fast) var(--ease-standard), height var(--duration-fast) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard); +} +.track[data-axis="y"] .thumb::after { top: 0; right: 3px; bottom: 0; width: 5px; } +.track[data-axis="x"] .thumb::after { right: 0; bottom: 3px; left: 0; height: 5px; } + +/* Visible while scrolling, while the pointer is over the area, and always when asked. Appearing is quick; leaving lingers. */ +.root[data-scrolling] > .track, +.root[data-dragging] > .track, +.root[data-scrollbars="always"] > .track { opacity: 1; pointer-events: auto; transition-duration: var(--duration-fast); } + +@media (hover: hover) and (pointer: fine) { + .root:hover > .track { opacity: 1; pointer-events: auto; transition-duration: var(--duration-fast); } + .track:hover .thumb::after, + .root[data-dragging] .thumb::after { background: color-mix(in oklab, var(--foreground) 46%, transparent); } + .track[data-axis="y"]:hover .thumb::after, + .root[data-dragging="y"] .track[data-axis="y"] .thumb::after { width: 7px; right: 2px; } + .track[data-axis="x"]:hover .thumb::after, + .root[data-dragging="x"] .track[data-axis="x"] .thumb::after { height: 7px; bottom: 2px; } +} + +@media (prefers-reduced-motion: reduce) { + .track, .thumb::after { transition: none; } +} diff --git a/packages/uiarc/src/scroll-area/scroll-area.tsx b/packages/uiarc/src/scroll-area/scroll-area.tsx new file mode 100644 index 00000000..579a961b --- /dev/null +++ b/packages/uiarc/src/scroll-area/scroll-area.tsx @@ -0,0 +1,197 @@ +"use client"; + +import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef } from "react"; +import type { CSSProperties, HTMLAttributes, PointerEvent as ReactPointerEvent, ReactNode, Ref, UIEvent } from "react"; +import styles from "./scroll-area.module.css"; + +type Axis = "y" | "x"; + +/** Which edges still have content beyond them. */ +export interface ScrollAreaEdges { top: boolean; bottom: boolean; left: boolean; right: boolean } + +/** + * A native scroll container with thin overlay scrollbars that appear while scrolling or on hover and fade away at rest. + * Each edge fades out only when there is more content beyond it, in proportion to how much. Scrolling stays native, so + * keyboard, touch momentum, and scroll snap all behave as the platform expects. + */ +export interface ScrollAreaProps extends Omit, "onScroll"> { + children?: ReactNode; + /** Axes that scroll. Defaults to vertical. */ + orientation?: "vertical" | "horizontal" | "both"; + /** Length of the edge fade in px. 0 turns the fades off. */ + fade?: number; + /** "auto" shows scrollbars while scrolling or hovering; "always" keeps them visible when content overflows. */ + scrollbars?: "auto" | "always"; + /** How long scrollbars linger after scrolling stops, in ms. */ + hideDelay?: number; + /** Maximum height of the viewport, for vertical areas that should grow with their content. */ + maxHeight?: CSSProperties["maxHeight"]; + /** Passed to the viewport's `scroll-snap-type`, for example "x mandatory". Children set their own `scroll-snap-align`. */ + snap?: CSSProperties["scrollSnapType"]; + /** Accessible name. The viewport becomes a labelled, focusable region that arrow and page keys scroll. */ + label?: string; + /** Turns vertical wheel movement into horizontal scrolling for horizontal areas. Defaults to true. */ + wheelToHorizontal?: boolean; + viewportClassName?: string; + viewportStyle?: CSSProperties; + viewportRef?: Ref; + onScroll?: (event: UIEvent) => void; + /** Called when content starts or stops extending past an edge. */ + onEdgeChange?: (edges: ScrollAreaEdges) => void; +} + +const MIN_THUMB = 28; + +export const ScrollArea = forwardRef(function ScrollArea({ + children, orientation = "vertical", fade = 28, scrollbars = "auto", hideDelay = 900, maxHeight, snap, label, + wheelToHorizontal = true, viewportClassName, viewportStyle, viewportRef, onScroll, onEdgeChange, className, ...rest +}, forwardedRef) { + const rootRef = useRef(null); + const viewport = useRef(null); + const tracks = useRef>({ x: null, y: null }); + const thumbs = useRef>({ x: null, y: null }); + const hideTimer = useRef(undefined); + const lastEdges = useRef(""); + const onEdgeRef = useRef(onEdgeChange); + useImperativeHandle(forwardedRef, () => rootRef.current as HTMLDivElement); + useImperativeHandle(viewportRef, () => viewport.current as HTMLDivElement); + useEffect(() => { onEdgeRef.current = onEdgeChange; }, [onEdgeChange]); + + const vertical = orientation !== "horizontal", horizontal = orientation !== "vertical"; + + /* Everything visual is written straight to the DOM on each scroll frame, so scrolling never re-renders React. */ + const sync = useCallback(() => { + const node = viewport.current, root = rootRef.current; + if (!node || !root) return; + const { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = node; + const maxY = Math.max(0, scrollHeight - clientHeight), maxX = Math.max(0, scrollWidth - clientWidth); + // RTL layouts report negative scrollLeft; distance from the start edge is its magnitude. + const left = Math.abs(scrollLeft); + const edges: ScrollAreaEdges = { top: vertical && scrollTop > .5, bottom: vertical && maxY - scrollTop > .5, left: horizontal && left > .5, right: horizontal && maxX - left > .5 }; + + if (fade > 0) { + node.style.setProperty("--fade-top", `${vertical ? Math.min(fade, scrollTop) : 0}px`); + node.style.setProperty("--fade-bottom", `${vertical ? Math.min(fade, maxY - scrollTop) : 0}px`); + node.style.setProperty("--fade-left", `${horizontal ? Math.min(fade, left) : 0}px`); + node.style.setProperty("--fade-right", `${horizontal ? Math.min(fade, maxX - left) : 0}px`); + } + + const place = (axis: Axis, scroll: number, max: number, client: number, total: number) => { + const track = tracks.current[axis], thumb = thumbs.current[axis]; + if (!track || !thumb) return; + const overflowing = max > .5; + track.toggleAttribute("data-hidden", !overflowing); + if (!overflowing) return; + const length = axis === "y" ? track.clientHeight : track.clientWidth; + const size = Math.max(MIN_THUMB, length * client / total); + const offset = (length - size) * (scroll / max); + thumb.style[axis === "y" ? "height" : "width"] = `${size}px`; + thumb.style.transform = axis === "y" ? `translate3d(0, ${offset}px, 0)` : `translate3d(${offset}px, 0, 0)`; + }; + if (vertical) place("y", scrollTop, maxY, clientHeight, scrollHeight); + if (horizontal) place("x", left, maxX, clientWidth, scrollWidth); + root.toggleAttribute("data-overflow", maxY > .5 || maxX > .5); + + const key = `${edges.top}${edges.bottom}${edges.left}${edges.right}`; + if (key !== lastEdges.current) { lastEdges.current = key; onEdgeRef.current?.(edges); } + }, [fade, horizontal, vertical]); + + useLayoutEffect(() => { + const node = viewport.current; + if (!node) return; + sync(); + if (typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(() => sync()); + observer.observe(node); + Array.from(node.children).forEach(child => observer.observe(child)); + const mutations = new MutationObserver(() => { observer.disconnect(); observer.observe(node); Array.from(node.children).forEach(child => observer.observe(child)); sync(); }); + mutations.observe(node, { childList: true }); + return () => { observer.disconnect(); mutations.disconnect(); }; + }, [sync]); + + useEffect(() => () => window.clearTimeout(hideTimer.current), []); + + const wake = () => { + const root = rootRef.current; + if (!root) return; + root.setAttribute("data-scrolling", ""); + window.clearTimeout(hideTimer.current); + hideTimer.current = window.setTimeout(() => root.removeAttribute("data-scrolling"), hideDelay); + }; + + const handleScroll = (event: UIEvent) => { + sync(); + wake(); + onScroll?.(event); + }; + + // A mouse wheel over a horizontal strip moves it sideways, but only while there is room, so the page still scrolls at the ends. + useEffect(() => { + const node = viewport.current; + if (!node || orientation !== "horizontal" || !wheelToHorizontal) return; + const wheel = (event: WheelEvent) => { + if (event.ctrlKey || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return; + const max = node.scrollWidth - node.clientWidth, at = Math.abs(node.scrollLeft); + if (max <= 0 || (event.deltaY < 0 && at <= 0) || (event.deltaY > 0 && at >= max - .5)) return; + event.preventDefault(); + node.scrollLeft += event.deltaY * (getComputedStyle(node).direction === "rtl" ? -1 : 1); + }; + node.addEventListener("wheel", wheel, { passive: false }); + return () => node.removeEventListener("wheel", wheel); + }, [orientation, wheelToHorizontal]); + + /* Dragging a thumb maps pointer travel to scroll distance; pressing the track pages toward the pointer. */ + const drag = useRef<{ axis: Axis; start: number; scroll: number; ratio: number } | null>(null); + const onThumbDown = (event: ReactPointerEvent, axis: Axis) => { + const node = viewport.current, track = tracks.current[axis], thumb = thumbs.current[axis]; + if (!node || !track || !thumb || event.button !== 0) return; + event.preventDefault(); + event.stopPropagation(); + event.currentTarget.setPointerCapture(event.pointerId); + const length = axis === "y" ? track.clientHeight : track.clientWidth, size = axis === "y" ? thumb.offsetHeight : thumb.offsetWidth; + const max = axis === "y" ? node.scrollHeight - node.clientHeight : node.scrollWidth - node.clientWidth; + drag.current = { axis, start: axis === "y" ? event.clientY : event.clientX, scroll: axis === "y" ? node.scrollTop : node.scrollLeft, ratio: max / Math.max(1, length - size) }; + rootRef.current?.setAttribute("data-dragging", axis); + node.style.scrollSnapType = "none"; + }; + const onThumbMove = (event: ReactPointerEvent) => { + const state = drag.current, node = viewport.current; + if (!state || !node) return; + const delta = ((state.axis === "y" ? event.clientY : event.clientX) - state.start) * state.ratio; + if (state.axis === "y") node.scrollTop = state.scroll + delta; else node.scrollLeft = state.scroll + delta; + }; + const onThumbUp = (event: ReactPointerEvent) => { + if (!drag.current) return; + drag.current = null; + if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); + rootRef.current?.removeAttribute("data-dragging"); + if (viewport.current) viewport.current.style.scrollSnapType = ""; + wake(); + }; + const onTrackDown = (event: ReactPointerEvent, axis: Axis) => { + const node = viewport.current, thumb = thumbs.current[axis]; + if (!node || !thumb || event.button !== 0 || event.target !== event.currentTarget) return; + const rect = thumb.getBoundingClientRect(); + const before = axis === "y" ? event.clientY < rect.top : event.clientX < rect.left; + const page = (axis === "y" ? node.clientHeight : node.clientWidth) * .9 * (before ? -1 : 1); + const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches; + node.scrollBy({ [axis === "y" ? "top" : "left"]: page, behavior: reduce ? "auto" : "smooth" }); + }; + + const bar = (axis: Axis) =>
{ tracks.current[axis] = node; }} className={styles.track} data-axis={axis} data-hidden="" aria-hidden="true" + onPointerDown={event => onTrackDown(event, axis)}> +
{ thumbs.current[axis] = node; }} className={styles.thumb} + onPointerDown={event => onThumbDown(event, axis)} onPointerMove={onThumbMove} onPointerUp={onThumbUp} onPointerCancel={onThumbUp} /> +
; + + return
+
0 ? orientation : undefined} + style={{ maxHeight, scrollSnapType: snap, ...viewportStyle }} tabIndex={0} role={label ? "region" : undefined} aria-label={label} onScroll={handleScroll}> + {children} +
+ {vertical && bar("y")} + {horizontal && bar("x")} +
; +}); + +export default ScrollArea; diff --git a/packages/uiarc/src/segmented-control/segmented-control.module.css b/packages/uiarc/src/segmented-control/segmented-control.module.css new file mode 100644 index 00000000..58f10e31 --- /dev/null +++ b/packages/uiarc/src/segmented-control/segmented-control.module.css @@ -0,0 +1,15 @@ +/* The frame can shrink below its content inside flex and grid parents; the track then scrolls inside it. */ +.root { display: inline-flex; min-width: 0; max-width: 100%; flex-shrink: 1; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface-muted); } +/* The track owns the stacking context so the gliding highlight passes under every label, not over earlier ones. */ +.track { --fade-start: 0px; --fade-end: 0px; isolation: isolate; display: flex; min-width: 0; gap: 2px; overflow-x: auto; overscroll-behavior-x: contain; padding: 3px; border-radius: inherit; scrollbar-width: none; -webkit-mask-image: linear-gradient(to right, transparent, #000 var(--fade-start), #000 calc(100% - var(--fade-end)), transparent); mask-image: linear-gradient(to right, transparent, #000 var(--fade-start), #000 calc(100% - var(--fade-end)), transparent); } +.track::-webkit-scrollbar { display: none; } +.track[data-fade-start] { --fade-start: 20px; } +.track[data-fade-end] { --fade-end: 20px; } +/* Items never scale or change weight; only the highlight travels and the label color follows it. */ +.button { position: relative; flex: 0 0 auto; min-height: var(--control-height-sm); border: 0; border-radius: calc(var(--radius-control) - 4px); padding: 0 12px; background: transparent; color: var(--text-muted); font: inherit; font-size: var(--text-sm); font-weight: 500; white-space: nowrap; cursor: pointer; -webkit-tap-highlight-color: transparent; transition: color var(--duration-fast) var(--ease-standard); } +@media (hover: hover) and (pointer: fine) { .button:hover { color: var(--foreground); } } +.button:active, .button[aria-pressed="true"] { color: var(--foreground); } +.selection { position: absolute; z-index: -1; inset: 0; border: 1px solid var(--border); border-radius: inherit; background: var(--surface); box-shadow: var(--shadow-resting); } +.label { position: relative; z-index: 1; display: inline-flex; align-items: center; gap: 6px; } +@media (max-width: 380px) { .button { padding: 0 10px; } } +@media (prefers-reduced-motion: reduce) { .button { transition: none; } } diff --git a/packages/uiarc/src/segmented-control/segmented-control.tsx b/packages/uiarc/src/segmented-control/segmented-control.tsx new file mode 100644 index 00000000..c0bd6b36 --- /dev/null +++ b/packages/uiarc/src/segmented-control/segmented-control.tsx @@ -0,0 +1,73 @@ +"use client"; + +import { useEffect, useId, useLayoutEffect, useRef, type KeyboardEvent, type ReactNode } from "react"; +import { LayoutGroup, motion, useReducedMotion } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./segmented-control.module.css"; + +export interface Segment { value: string; label: string; /** Optional content after the label, such as a badge. */ accessory?: ReactNode; } +export interface SegmentedControlProps { + options: Segment[]; + value: string; + onValueChange: (value: string) => void; + label?: string; + /** Called when the pointer or focus reaches an option, before it is chosen. Use it to start loading what that option shows. */ + onOptionIntent?: (value: string) => void; + className?: string; +} + +export default function SegmentedControl({ options, value, onValueChange, label, onOptionIntent, className }: SegmentedControlProps) { + const id = useId(); + const reduced = useReducedMotion(); + const track = useRef(null); + + // When the options are wider than the container, the track scrolls inside itself. Edges fade only on the side with more to see. + useLayoutEffect(() => { + const node = track.current; + if (!node) return; + const edges = () => { + const rest = node.scrollWidth - node.clientWidth - node.scrollLeft; + node.toggleAttribute("data-fade-start", node.scrollLeft > 1); + node.toggleAttribute("data-fade-end", rest > 1); + }; + edges(); + node.addEventListener("scroll", edges, { passive: true }); + const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(edges); + observer?.observe(node); + return () => { node.removeEventListener("scroll", edges); observer?.disconnect(); }; + }, [options.length]); + + // The selected option is always scrolled fully into view, with a little room so it clears the fade. + const first = useRef(true); + useEffect(() => { + const node = track.current; + const button = node?.querySelector('[aria-pressed="true"]'); + if (!node || !button || node.scrollWidth <= node.clientWidth) { first.current = false; return; } + const room = 20, start = button.offsetLeft - room, end = button.offsetLeft + button.offsetWidth + room - node.clientWidth; + const left = node.scrollLeft > start ? start : node.scrollLeft < end ? end : node.scrollLeft; + if (left !== node.scrollLeft) node.scrollTo({ left: Math.max(0, left), behavior: first.current || reduced ? "auto" : "smooth" }); + first.current = false; + }, [value, reduced]); + + // Arrow keys, Home and End move the selection like a tab list; only the selected option is a tab stop. + const selectedIndex = Math.max(0, options.findIndex(option => option.value === value)); + const onKeyDown = (event: KeyboardEvent) => { + const last = options.length - 1; + const target = event.key === "ArrowRight" || event.key === "ArrowDown" ? (selectedIndex === last ? 0 : selectedIndex + 1) + : event.key === "ArrowLeft" || event.key === "ArrowUp" ? (selectedIndex === 0 ? last : selectedIndex - 1) + : event.key === "Home" ? 0 : event.key === "End" ? last : -1; + if (target < 0 || !options[target]) return; + event.preventDefault(); + onValueChange(options[target].value); + track.current?.querySelector(`[data-value="${CSS.escape(options[target].value)}"]`)?.focus({ preventScroll: true }); + }; + + return
+ + {options.map((option, index) => )} + +
; +} diff --git a/packages/uiarc/src/select/select.module.css b/packages/uiarc/src/select/select.module.css new file mode 100644 index 00000000..6da66f56 --- /dev/null +++ b/packages/uiarc/src/select/select.module.css @@ -0,0 +1,34 @@ +.field { display: grid; gap: var(--space-2); min-width: 0; } +.field label { font-size: var(--text-sm); font-weight: 500; } +/* The trigger anchors the floating menu. Radix opens on pointerdown and measures this box, so it never scales: press feedback is color only. */ +.trigger { position: relative; box-sizing: border-box; display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); width: 100%; min-height: var(--control-height-md); border: 1px solid var(--border); border-radius: var(--radius-control); padding: 0 var(--space-3); background: var(--surface); color: var(--foreground); font: inherit; font-size: var(--text-sm); text-align: left; cursor: pointer; transition: border-color var(--duration-fast) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard); } +@media (hover: hover) and (pointer: fine) { .trigger:hover:not([data-disabled]) { border-color: var(--border-strong); background: var(--surface-muted); } } +.trigger:active:not([data-disabled]), .trigger[data-state="open"] { border-color: var(--border-strong); background: var(--surface-muted); } +.trigger:focus-visible { border-color: var(--border-strong); } +.trigger[data-disabled] { opacity: .5; cursor: not-allowed; } +.valueText { display: grid; flex: 1; min-width: 0; grid-template-columns: minmax(0, 1fr); } +.valueText > span { grid-area: 1 / 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.valueText > [data-placeholder] { color: var(--text-muted); } +.srOnly { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } +.chevron { display: inline-flex; flex: 0 0 auto; color: var(--text-muted); transition: transform var(--duration-spring) var(--ease-spring), color var(--duration-fast) var(--ease-standard); } +.trigger[data-state="open"] .chevron { transform: rotate(180deg); } +.hint { color: var(--text-muted); font-size: var(--text-xs); } +/* Radix holds the animation until the menu is positioned, so it always grows from the trigger edge. */ +.content { --menu-x: 0px; --menu-y: -6px; box-sizing: border-box; z-index: 1000; width: var(--radix-select-trigger-width); min-width: var(--radix-select-trigger-width); max-width: min(24rem, calc(100vw - 20px)); max-height: min(320px, var(--radix-select-content-available-height)); overflow: hidden; border: 1px solid var(--border); border-radius: calc(var(--radius-control) + 2px); padding: 6px; background: var(--surface-raised); color: var(--foreground); box-shadow: var(--shadow-floating); transform-origin: var(--radix-select-content-transform-origin); animation: select-in var(--duration-standard) var(--ease-enter) both; } +.content[data-side="top"] { --menu-y: 6px; } +.content[data-side="left"] { --menu-x: 6px; --menu-y: 0px; } +.content[data-side="right"] { --menu-x: -6px; --menu-y: 0px; } +.content[data-state="closed"] { animation: select-out var(--duration-instant) var(--ease-standard) both; } +.viewport { padding: 2px 0; } +.item { position: relative; display: flex; align-items: center; min-height: 36px; border-radius: calc(var(--radius-control) - 4px); padding: 0 34px 0 11px; color: var(--foreground); font-size: var(--text-sm); cursor: default; outline: none; user-select: none; transition: background-color var(--duration-instant) var(--ease-standard), color var(--duration-instant) var(--ease-standard); } +.item[data-highlighted] { background: var(--surface-muted); } +.item[data-disabled] { opacity: .45; } +.indicator { position: absolute; right: 10px; display: inline-flex; align-items: center; color: var(--foreground); animation: indicator-in var(--duration-standard) var(--ease-enter) 40ms both; } +.scrollButton { display: grid; height: 28px; place-items: center; color: var(--text-muted); } +@keyframes select-in { from { opacity: 0; transform: translate(var(--menu-x), var(--menu-y)) scale(.97); } } +@keyframes select-out { to { opacity: 0; transform: translate(calc(var(--menu-x) / 2), calc(var(--menu-y) / 2)) scale(.98); } } +@keyframes indicator-in { from { opacity: 0; transform: scale(.6); filter: blur(2px); } } +@media (prefers-reduced-transparency: reduce) { .content { background: var(--surface-raised); backdrop-filter: none; -webkit-backdrop-filter: none; } } +@media (prefers-reduced-motion: reduce) { .trigger, .chevron, .item { transition: none; } .content { animation: select-fade var(--duration-instant) var(--ease-standard) both; } .content[data-state="closed"] { animation: select-fade-out var(--duration-instant) var(--ease-standard) both; } .indicator { animation: none; } } +@keyframes select-fade { from { opacity: 0; } } +@keyframes select-fade-out { to { opacity: 0; } } diff --git a/packages/uiarc/src/select/select.tsx b/packages/uiarc/src/select/select.tsx new file mode 100644 index 00000000..168a5ec6 --- /dev/null +++ b/packages/uiarc/src/select/select.tsx @@ -0,0 +1,91 @@ +"use client"; + +import { forwardRef, useId, useState } from "react"; +import type { ComponentPropsWithoutRef } from "react"; +import * as SelectPrimitive from "@radix-ui/react-select"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; +import type { Variants } from "motion/react"; +import { Check, ChevronDown, ChevronUp } from "lucide-react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./select.module.css"; + +export interface SelectProps extends Omit, "children"> { + label: string; + description?: string; + placeholder?: string; + id?: string; + className?: string; + options: { value: string; label: string; disabled?: boolean }[]; +} + +/** The shown value rolls in the direction of the list: a later option rises from below, an earlier one drops from above. */ +const valueRoll: Variants = { + enter: (direction: number) => ({ opacity: 0, y: `${direction * 0.35}em`, filter: `blur(${motionTokens.blur.soft}px)` }), + center: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] } }, + exit: (direction: number) => ({ opacity: 0, y: `${direction * -0.3}em`, filter: `blur(${motionTokens.blur.subtle}px)`, transition: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.standard] } }), +}; +/** Reduced motion keeps a short crossfade; the resting state matches valueRoll so server and client markup agree. */ +const valueFade: Variants = { enter: { opacity: 0 }, center: { opacity: 1, y: 0, filter: "blur(0px)", transition: { duration: motionTokens.duration.instant } }, exit: { opacity: 0, transition: { duration: motionTokens.duration.instant } } }; + +export const Select = forwardRef(function Select( + { label, description, placeholder = "Select an option", options, id, className, disabled, onValueChange, ...rootProps }, + ref, +) { + const generatedId = useId(); + const controlId = id ?? generatedId; + const hintId = description ? `${controlId}-description` : undefined; + const reduceMotion = useReducedMotion(); + const [uncontrolledValue, setUncontrolledValue] = useState(rootProps.defaultValue ?? ""); + const currentValue = rootProps.value ?? uncontrolledValue; + const index = options.findIndex((option) => option.value === currentValue); + const shown = currentValue ? options[index]?.label ?? "" : placeholder; + const [previousIndex, setPreviousIndex] = useState(index); + const [direction, setDirection] = useState(1); + if (previousIndex !== index) { setPreviousIndex(index); setDirection(index > previousIndex ? 1 : -1); } + + return ( +
+ + { setUncontrolledValue(next); onValueChange?.(next); }}> + + {/* Radix keeps the real value for assistive tech; the visible copy below animates between values. */} + + + + + + + + + + + {options.map((option) => ( + + {option.label} + + + + ))} + + + + + + + {description && {description}} +
+ ); +}); diff --git a/packages/uiarc/src/skeleton/skeleton.module.css b/packages/uiarc/src/skeleton/skeleton.module.css new file mode 100644 index 00000000..92e81238 --- /dev/null +++ b/packages/uiarc/src/skeleton/skeleton.module.css @@ -0,0 +1,11 @@ +.root { display: flex; width: 100%; min-width: 0; align-items: flex-start; gap: var(--space-4); } +/* A calm, finite pulse: each block dims a beat after the one above it, then rests after about 20 seconds. */ +.avatar, .line { display: block; flex: 0 0 auto; border-radius: var(--radius-control); background: color-mix(in oklab, var(--border-strong) 38%, var(--surface)); animation: skeleton-pulse 1.8s var(--ease-in-out) calc(var(--index, 0) * 90ms) 11 both; } +.avatar { width: var(--control-height-md); height: var(--control-height-md); border-radius: var(--radius-pill); } +.lines { display: grid; flex: 1; gap: var(--space-3); padding-top: var(--space-1); } +.line { width: 100%; height: var(--space-3); } +.line:first-child { width: 48%; height: var(--space-4); } +.line:last-child { width: 72%; } +.frame { position: relative; display: flow-root; } +@keyframes skeleton-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .52; } } +@media (prefers-reduced-motion: reduce) { .avatar, .line { animation: none; } } diff --git a/packages/uiarc/src/skeleton/skeleton.tsx b/packages/uiarc/src/skeleton/skeleton.tsx new file mode 100644 index 00000000..2073c522 --- /dev/null +++ b/packages/uiarc/src/skeleton/skeleton.tsx @@ -0,0 +1,70 @@ +"use client"; + +import { useEffect, useLayoutEffect, useRef, type CSSProperties, type ReactNode } from "react"; +import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, type AnimationPlaybackControls } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./skeleton.module.css"; + +export interface SkeletonProps { + label?: string; + lines?: number; + avatar?: boolean; + className?: string; + /** Content to reveal once loading finishes. With children, the placeholder crossfades into them. */ + children?: ReactNode; + /** Keeps the placeholder visible while true. Only used together with children. */ + loading?: boolean; +} + +/** Follows its content height. After `morphKey` changes, the height springs from the old size to the new one and then returns to auto, so passive reflows (a resize, a font swap) follow instantly. It clips only while moving, so focus rings stay visible at rest. */ +function HeightFrame({ className, busy, reduce, children }: { className?: string; busy: boolean; reduce: boolean | null; children: ReactNode }) { + const frame = useRef(null); + const content = useRef(null); + const height = useMotionValue("auto"); + const changedAt = useRef(0); + useLayoutEffect(() => { changedAt.current = performance.now(); }, [busy]); + useEffect(() => { + const node = content.current; + if (!node || typeof ResizeObserver === "undefined") return; + let last: number | undefined; + let controls: AnimationPlaybackControls | undefined; + const settle = () => { height.jump("auto"); if (frame.current) Object.assign(frame.current.style, { overflow: "", height: "auto" }); }; + const observer = new ResizeObserver(([entry]) => { + if (!entry) return; + const next = entry.borderBoxSize?.[0]?.blockSize ?? node.offsetHeight; + const current = height.get(); + const from = typeof current === "number" ? current : last; + last = next; + controls?.stop(); + if (reduce || from === undefined || from === next || performance.now() - changedAt.current > 120) return settle(); + // Pin the old height before this frame paints, then spring to the new one. + if (frame.current) Object.assign(frame.current.style, { overflow: "hidden", height: `${from}px` }); + controls = animate(height, [from, next], { ...motionTokens.spring.smooth, onComplete: settle }); + }); + observer.observe(node); + return () => { observer.disconnect(); controls?.stop(); }; + }, [height, reduce]); + return +
{children}
+
; +} + +export function Skeleton({ label = "Loading content", lines = 3, avatar = false, className, children, loading = true }: SkeletonProps) { + const reduce = useReducedMotion(); + const count = Math.min(Math.max(Math.floor(lines), 1), 6); + // Each block pulses a beat after the one above it, so the wait reads as one calm wave. + const placeholder = (extra?: string) =>
+ {avatar &&
; + if (children === undefined) return placeholder(className); + return + + {loading + ? {placeholder()} + : {children}} + + ; +} + +export default Skeleton; diff --git a/packages/uiarc/src/switch/switch.module.css b/packages/uiarc/src/switch/switch.module.css new file mode 100644 index 00000000..f98ca33a --- /dev/null +++ b/packages/uiarc/src/switch/switch.module.css @@ -0,0 +1,12 @@ +.switch { display: inline-flex; min-height: var(--control-height-md); align-items: center; gap: var(--space-3); padding: 0; border: 0; color: var(--foreground); background: transparent; font: inherit; font-size: var(--text-sm); cursor: pointer; -webkit-tap-highlight-color: transparent; } +.switch:disabled { cursor: not-allowed; opacity: .5; } +/* Fixed box: the thumb moves inside it with transforms, so nothing around the switch shifts. The track crossfades between the two fills. */ +.track { position: relative; box-sizing: border-box; display: flex; flex: 0 0 auto; width: 42px; height: 24px; align-items: center; padding: 3px; border-radius: var(--radius-pill); background: var(--control-track); isolation: isolate; transition: background-color var(--duration-fast) var(--ease-standard); } +.track::before { content: ""; position: absolute; inset: 0; z-index: -1; border-radius: inherit; background: var(--control-on); opacity: 0; transition: opacity var(--duration-standard) var(--ease-standard); } +.switch[data-state="checked"] .track::before { opacity: 1; } +.thumb { flex: 0 0 auto; width: 18px; height: 18px; border-radius: var(--radius-pill); background: var(--control-thumb); box-shadow: var(--control-thumb-shadow); will-change: transform; transition: background-color var(--duration-standard) var(--ease-standard); } +.switch[data-state="checked"] .thumb { background: var(--control-thumb-on); } +@media (hover: hover) and (pointer: fine) { .switch[data-state="unchecked"]:hover:not(:disabled) .track { background: var(--control-track-hover); } } +.switch:focus-visible { outline: none; } +.label { line-height: var(--leading-body); } +@media (prefers-reduced-motion: reduce) { .track, .track::before, .thumb { transition: none; } } diff --git a/packages/uiarc/src/switch/switch.tsx b/packages/uiarc/src/switch/switch.tsx new file mode 100644 index 00000000..a2816e0b --- /dev/null +++ b/packages/uiarc/src/switch/switch.tsx @@ -0,0 +1,74 @@ +"use client"; + +import { forwardRef, useEffect, useRef, useState } from "react"; +import type { ComponentPropsWithoutRef, ElementRef } from "react"; +import * as SwitchPrimitive from "@radix-ui/react-switch"; +import { animate, motion, useMotionValue, useReducedMotion } from "motion/react"; +import type { Transition } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./switch.module.css"; + +export interface SwitchProps extends ComponentPropsWithoutRef { + label?: string; +} + +/** Track inner width (42 - 6 padding) minus the 18px thumb; keep in sync with switch.module.css. */ +const size = 18; +const travel = 18; +/** How far the thumb widens toward the other side while pressed. */ +const stretch = 5; +/** Critically damped: the thumb lands on its end without overshooting the state it reports. */ +const glide: Transition = { type: "spring", visualDuration: 0.3, bounce: 0 }; + +export const Switch = forwardRef, SwitchProps>(function Switch( + { label, className, checked, defaultChecked, onCheckedChange, onPointerDown, onPointerUp, onPointerLeave, onPointerCancel, onKeyDown, onKeyUp, onBlur, ...props }, + ref, +) { + const reduceMotion = useReducedMotion(); + const [internal, setInternal] = useState(defaultChecked ?? false); + const [pressed, setPressed] = useState(false); + const on = checked ?? internal; + // A brief stretch along the travel, so the thumb reads as moving mass rather than a sliding dot. + const scaleX = useMotionValue(1); + const shown = useRef(on); + // A pointer or Space press already stretched the thumb, so its release should not add a second stretch on top. + const releasedAt = useRef(-Infinity); + useEffect(() => { + if (shown.current === on) return; + shown.current = on; + const fromPress = performance.now() - releasedAt.current < 250; + if (reduceMotion || fromPress) return; + const controls = animate(scaleX, [1, 1.16, 1], { duration: 0.34, times: [0, 0.4, 1], ease: ["easeOut", "easeInOut"] }); + return () => controls.stop(); + }, [on, reduceMotion, scaleX]); + const extra = pressed && !reduceMotion && !props.disabled ? stretch : 0; + const classes = [styles.switch, className].filter(Boolean).join(" "); + + return ( + { if (checked === undefined) setInternal(next); onCheckedChange?.(next); }} + onPointerDown={event => { onPointerDown?.(event); if (event.button === 0) setPressed(true); }} + onPointerUp={event => { onPointerUp?.(event); if (pressed && !props.disabled) releasedAt.current = performance.now(); setPressed(false); }} + onPointerLeave={event => { onPointerLeave?.(event); setPressed(false); }} + onPointerCancel={event => { onPointerCancel?.(event); setPressed(false); }} + onKeyDown={event => { onKeyDown?.(event); if (event.key === " ") setPressed(true); }} + onKeyUp={event => { onKeyUp?.(event); if (pressed && !props.disabled) releasedAt.current = performance.now(); setPressed(false); }} + onBlur={event => { onBlur?.(event); setPressed(false); }} + className={classes} + aria-label={props["aria-label"] ?? label} + > + + {/* The thumb stretches like a held finger and keeps its far edge anchored, then travels on a spring. */} + + + {label ? {label} : null} + + ); +}); + +Switch.displayName = "Switch"; + +export default Switch; diff --git a/packages/uiarc/src/tabs/tabs.module.css b/packages/uiarc/src/tabs/tabs.module.css new file mode 100644 index 00000000..df72aeb1 --- /dev/null +++ b/packages/uiarc/src/tabs/tabs.module.css @@ -0,0 +1,27 @@ +/* Positioned so an outgoing panel pops out exactly where it was while the next one takes its place. */ +.root { position: relative; } +.listShell { position: relative; display: inline-flex; max-width: 100%; min-width: 0; align-items: center; isolation: isolate; border: 1px solid var(--border); border-radius: var(--radius-control); background: var(--surface-muted); } +.viewport { min-width: 0; overflow-x: auto; border-radius: inherit; scrollbar-width: none; } +.viewport::-webkit-scrollbar { display: none; } +.listShell[data-left="true"] .viewport { mask-image: linear-gradient(to right, transparent, black 35px, black); } +.listShell[data-right="true"] .viewport { mask-image: linear-gradient(to right, black, black calc(100% - 35px), transparent); } +.listShell[data-left="true"][data-right="true"] .viewport { mask-image: linear-gradient(to right, transparent, black 35px, black calc(100% - 35px), transparent); } +/* The list owns the stacking context so the gliding highlight passes under every label, not over earlier ones. */ +.list { isolation: isolate; display: inline-flex; width: max-content; align-items: center; gap: var(--space-1); padding: var(--space-1); } +.scrollButton { position: absolute; z-index: 2; top: 0; bottom: 0; display: grid; width: 33px; place-items: center; border: 0; background: var(--surface-muted); color: var(--foreground); } +.scrollLeft { left: 0; border-radius: var(--radius-control) 0 0 var(--radius-control); } +.scrollRight { right: 0; border-radius: 0 var(--radius-control) var(--radius-control) 0; } +.scrollButton:disabled { opacity: 0; pointer-events: none; } +.scrollButton:focus-visible { --focus-outline-offset: -3px; } +.trigger { position: relative; -webkit-tap-highlight-color: transparent; display: inline-grid; min-width: 5.5rem; place-items: center; flex: 0 0 auto; min-height: var(--control-height-sm); border: 0; border-radius: calc(var(--radius-control) - 3px); padding: 0 var(--space-3); background: transparent; color: var(--text-muted); font: inherit; font-size: var(--text-sm); font-weight: 500; white-space: nowrap; cursor: pointer; transition: color var(--duration-fast) var(--ease-standard); } +@media (hover: hover) and (pointer: fine) { .trigger:hover { color: var(--foreground); } } +.trigger:active { color: var(--foreground); }.trigger[data-state="active"] { color: var(--accent-strong); } +.selection { position: absolute; z-index: -1; inset: 0; border: 1px solid var(--border); border-radius: inherit; background: var(--surface); box-shadow: var(--shadow-resting); will-change: transform; } +.triggerLabel { position: relative; z-index: 1; } +.trigger:disabled { cursor: not-allowed; opacity: .5; } +.content { margin-top: var(--space-4); color: var(--text-secondary); font-size: var(--text-sm); line-height: var(--leading-body); } +/* The outgoing panel is lifted out of flow by the presence animation; drop its margin so it stays in place and ignore stray clicks. */ +.content[data-motion-pop-id] { margin-top: 0; } +.content[data-state="inactive"] { pointer-events: none; } +.content:focus-visible { --focus-outline-offset: 3px; border-radius: var(--radius-control); } +@media (prefers-reduced-motion: reduce) { .trigger { transition: none; } } diff --git a/packages/uiarc/src/tabs/tabs.tsx b/packages/uiarc/src/tabs/tabs.tsx new file mode 100644 index 00000000..d68510d8 --- /dev/null +++ b/packages/uiarc/src/tabs/tabs.tsx @@ -0,0 +1,139 @@ +"use client"; + +import * as TabsPrimitive from "@radix-ui/react-tabs"; +import { createContext, useCallback, useContext, useId, useLayoutEffect, useRef, useState } from "react"; +import type { ComponentPropsWithoutRef, RefObject } from "react"; +import { ChevronLeft as NavArrowLeft, ChevronRight as NavArrowRight } from "lucide-react"; +import { AnimatePresence, LayoutGroup, animate, motion, useReducedMotion } from "motion/react"; +import type { AnimationPlaybackControls, Variants } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./tabs.module.css"; + +type RootProps = ComponentPropsWithoutRef; +/** `direction` is +1 when the new tab sits after the old one; `panelHeightRef` holds the visible panel height so the next panel can morph from it; `leavingRectRef` pins the outgoing panel where it was on screen. */ +const TabsContext = createContext<{ active: string; layoutId: string; direction: number; panelHeightRef: RefObject; leavingRectRef: RefObject }>({ active: "", layoutId: "tabs", direction: 1, panelHeightRef: { current: null }, leavingRectRef: { current: null } }); + +export function Tabs({ value, defaultValue, onValueChange, className, ...props }: RootProps) { + const [internal, setInternal] = useState(defaultValue ?? ""); + const [direction, setDirection] = useState(1); + const active = value ?? internal; + const layoutId = useId(); + const root = useRef(null); + const panelHeightRef = useRef(null); + const leavingRectRef = useRef(null); + function handleChange(next: string) { + const frame = root.current; + leavingRectRef.current = frame?.querySelector(':scope > [role="tabpanel"][data-state="active"]')?.getBoundingClientRect() ?? null; + const order = frame ? Array.from(frame.querySelectorAll('[role="tab"][data-value]')).filter(tab => tab.closest(`.${styles.root}`) === frame).map(tab => tab.dataset.value) : []; + const from = order.indexOf(active), to = order.indexOf(next); + if (from >= 0 && to >= 0 && from !== to) setDirection(to > from ? 1 : -1); + if (value === undefined) setInternal(next); onValueChange?.(next); + } + return ; +} + +export function TabsList({ className, ...props }: ComponentPropsWithoutRef) { + const { active } = useContext(TabsContext); + const reduced = useReducedMotion(); + const shell = useRef(null); + const viewport = useRef(null); + const list = useRef(null); + const [edges, setEdges] = useState({ overflow: false, left: false, right: false }); + const update = useCallback(() => { + const frame = shell.current; + const scroll = viewport.current; + if (!frame || !scroll) return; + const max = Math.max(0, scroll.scrollWidth - scroll.clientWidth); + const next = { overflow: scroll.scrollWidth > frame.clientWidth + 1, left: scroll.scrollLeft > 1, right: scroll.scrollLeft < max - 1 }; + setEdges(previous => previous.overflow === next.overflow && previous.left === next.left && previous.right === next.right ? previous : next); + }, []); + const reveal = useCallback((tab: HTMLElement | null) => { + const scroll = viewport.current; + if (!scroll || !tab) return; + const frame = scroll.getBoundingClientRect(); + const item = tab.getBoundingClientRect(); + const max = Math.max(0, scroll.scrollWidth - scroll.clientWidth); + const left = frame.left + (scroll.scrollLeft > 1 ? 34 : 0); + const right = frame.right - (scroll.scrollLeft < max - 1 ? 34 : 0); + const delta = item.left < left ? item.left - left : item.right > right ? item.right - right : 0; + if (delta) scroll.scrollBy({ left: delta, behavior: reduced ? "instant" : "smooth" }); + }, [reduced]); + useLayoutEffect(() => { + const frame = shell.current; + const scroll = viewport.current; + const content = list.current; + if (!frame || !scroll || !content) return; + const observer = new ResizeObserver(update); + observer.observe(frame); + observer.observe(scroll); + observer.observe(content); + scroll.addEventListener("scroll", update, { passive: true }); + update(); + return () => { observer.disconnect(); scroll.removeEventListener("scroll", update); }; + }, [update]); + useLayoutEffect(() => { reveal(list.current?.querySelector('[role="tab"][data-state="active"]') ?? null); }, [active, reveal]); + const scrollTabs = (direction: number) => viewport.current?.scrollBy({ left: direction * (viewport.current?.clientWidth ?? 0) * .75, behavior: reduced ? "instant" : "smooth" }); + return
+ {edges.overflow && } + { if (event.target instanceof HTMLElement && event.target.getAttribute("role") === "tab") reveal(event.target); }}> + + + {edges.overflow && } +
; +} + +export function TabsTrigger({ className, children, value, ...props }: ComponentPropsWithoutRef) { + const { active } = useContext(TabsContext); + const reduced = useReducedMotion(); + // The LayoutGroup in Tabs scopes the highlight to this instance, so it glides between triggers but never flies in from another tab set. + return + {active === value && ; +} + +const panelMotion: Variants = { + enter: (direction: number) => ({ opacity: 0, x: direction * 8 }), + center: { opacity: 1, x: 0, transition: { opacity: { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] }, x: motionTokens.spring.smooth } }, + exit: (direction: number) => ({ opacity: 0, x: direction * -6, transition: { duration: motionTokens.duration.instant, ease: [...motionTokens.ease.standard] } }), +}; +/** Reduced motion: a short crossfade in place. Keys match panelMotion so server and client render identical styles. */ +const panelFade: Variants = { + enter: { opacity: 0, x: 0 }, + center: { opacity: 1, x: 0, transition: { duration: motionTokens.duration.instant } }, + exit: { opacity: 0, x: 0, transition: { duration: .1 } }, +}; + +export function TabsContent({ className, value, forceMount, children, ...props }: ComponentPropsWithoutRef) { + const { active, direction, panelHeightRef, leavingRectRef } = useContext(TabsContext); + const reduced = useReducedMotion(); + const panel = useRef(null); + const selected = active === value; + const classes = [styles.content, className].filter(Boolean).join(" "); + // The incoming panel starts at the outgoing panel's height and settles at its own, so content below glides instead of jumping. + useLayoutEffect(() => { + const node = panel.current; + if (!node || forceMount) return; + // Outgoing: the tab root may have changed size around it, so pin the panel to where it was while it fades. + if (!selected) { const before = leavingRectRef.current; const now = node.getBoundingClientRect(); if (before) node.style.translate = `${before.left - now.left}px ${before.top - now.top}px`; node.inert = true; return; } + node.style.translate = ""; node.inert = false; + const from = panelHeightRef.current; + const to = node.offsetHeight; + let controls: AnimationPlaybackControls | undefined; + const release = () => { node.style.height = ""; node.style.overflow = ""; }; + if (from !== null && Math.abs(from - to) > 1 && !reduced) { + if (to > from) node.style.overflow = "clip"; + controls = animate(node, { height: [from, to] }, { ...motionTokens.spring.smooth, onComplete: release }); + } + panelHeightRef.current = controls && from !== null ? from : to; + const observer = new ResizeObserver(() => { panelHeightRef.current = node.offsetHeight; }); + observer.observe(node); + return () => { observer.disconnect(); controls?.stop(); release(); }; + }, [selected, reduced, forceMount, panelHeightRef, leavingRectRef]); + if (forceMount) return {children}; + return + {selected && + {children} + } + ; +} diff --git a/packages/uiarc/src/textarea/textarea.module.css b/packages/uiarc/src/textarea/textarea.module.css new file mode 100644 index 00000000..8568ff15 --- /dev/null +++ b/packages/uiarc/src/textarea/textarea.module.css @@ -0,0 +1,22 @@ +/* No row gap: grid tracks clamp a negative margin at zero, so a closed message row would still pay the gap. Each row carries its own space instead. */ +.field { display: grid; min-width: 0; } +.field label { margin-bottom: var(--space-2); font-size: var(--text-sm); font-weight: 500; } +/* Same focus language as Input: the ring contracts onto the border while it fades in, and the box never changes size. */ +.control { width: 100%; min-height: 110px; resize: vertical; border: 1px solid var(--border-strong); border-radius: var(--radius-control); padding: var(--space-3); background: var(--surface); color: var(--foreground); font: inherit; font-size: var(--text-sm); line-height: var(--leading-body); outline: none; box-shadow: 0 0 0 6px transparent; transition: border-color var(--duration-fast) var(--ease-standard), box-shadow var(--duration-standard) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard); } +.control::placeholder { color: var(--text-muted); } +@media (hover: hover) and (pointer: fine) { .control:hover:not(:disabled, [aria-invalid="true"]) { border-color: var(--foreground); } } +.control:focus-visible { border-color: var(--foreground); box-shadow: 0 0 0 3px var(--focus-ring); outline: 2px solid transparent; outline-offset: 2px; } +.control[aria-invalid="true"] { border-color: var(--danger); } +.control:disabled { cursor: not-allowed; background: var(--surface-muted); opacity: .6; } +/* The row's space is padding inside the clipped slot, so the height animates from a true zero. */ +.messageSlot { display: block; overflow: hidden; } +.hint, .error { display: block; padding-top: var(--space-2); font-size: var(--text-xs); line-height: var(--leading-body); } +.hint { color: var(--text-muted); } .error { color: var(--danger); } +/* Words are measured against this box when they pop out to leave, so it must be the positioned parent. */ +.words { position: relative; display: block; } +.word { display: inline-block; white-space: pre; } +/* One column per character of a count. Tabular digits keep columns equal, so only a gained or lost digit changes the width. */ +.column { position: relative; display: inline-flex; justify-content: center; font-variant-numeric: tabular-nums; } +.column > span { display: inline-block; } +.srOnly { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +@media (prefers-reduced-motion: reduce) { .control { transition: none; } } diff --git a/packages/uiarc/src/textarea/textarea.tsx b/packages/uiarc/src/textarea/textarea.tsx new file mode 100644 index 00000000..7043bbb7 --- /dev/null +++ b/packages/uiarc/src/textarea/textarea.tsx @@ -0,0 +1,64 @@ +"use client"; +import { forwardRef, useEffect, useId, useRef, useState } from "react"; +import type { TextareaHTMLAttributes } from "react"; +import { AnimatePresence, motion, useReducedMotion } from "motion/react"; +import { motionTokens } from "../lib/motion-tokens"; +import styles from "./textarea.module.css"; +export interface TextareaProps extends TextareaHTMLAttributes { label: string; description?: string; error?: string } +/* Digits roll up when a number grows and down when it shrinks; `custom` hands the latest direction to digits already leaving. */ +const digit = { + enter: (direction: number) => ({ opacity: 0, y: `${direction * 0.6}em`, filter: `blur(${motionTokens.blur.subtle}px)` }), + center: { opacity: 1, y: 0, filter: "blur(0px)" }, + exit: (direction: number) => ({ opacity: 0, y: `${direction * -0.6}em`, filter: `blur(${motionTokens.blur.subtle}px)` }), +}; +const isNumber = (word: string) => /^\d[\d.,/:]*%?$/.test(word); + +/** A count in the copy, such as "12 characters", rolls only the digits that changed; a gained or lost digit opens or closes its width. */ +function RollingNumber({ word }: { word: string }) { + const reduced = useReducedMotion(); + const [shown, setShown] = useState({ word, direction: 1 }); + if (shown.word !== word) setShown({ word, direction: parseFloat(word.replace(/,/g, "")) < parseFloat(shown.word.replace(/,/g, "")) ? -1 : 1 }); + const characters = word.split(""); + const transition = reduced ? { duration: 0 } : { y: motionTokens.spring.snappy, width: motionTokens.spring.morph, opacity: { duration: motionTokens.duration.fast }, filter: { duration: motionTokens.duration.fast } }; + return {characters.map((character, index) => + {character} + )}; +} + +/** Changed words rise in and unblur while unchanged words hold still, and numbers roll. Assistive tech reads the plain copy. */ +function MotionText({ text }: { text: string }) { + const reduced = useReducedMotion(); + const words = text.split(" "); + return <>{text}; +} + +/** Helper and error copy: the row opens its height on a spring, then the words settle in. */ +function FieldMessage({ id, text, className, alert }: { id?: string; text?: string; className?: string; alert?: boolean }) { + return {text ? : null}; +} + +/** The row tracks the measured copy, so a longer message that wraps opens its next line instead of snapping. */ +function MessageRow({ id, text, className, alert }: { id?: string; text: string; className?: string; alert?: boolean }) { + const reduced = useReducedMotion(); + const copyRef = useRef(null); + const [height, setHeight] = useState("auto"); + useEffect(() => { + const node = copyRef.current; + if (!node || typeof ResizeObserver === "undefined") return; + const observer = new ResizeObserver(([entry]) => { if (entry) setHeight(entry.borderBoxSize?.[0]?.blockSize ?? node.offsetHeight); }); + observer.observe(node); + return () => observer.disconnect(); + }, []); + return + + ; +} + +export const Textarea = forwardRef(function Textarea({ label, description, error, id, className, ...props }, ref) { + const generatedId = useId(); const controlId = id ?? generatedId; + const hintId = description ? `${controlId}-description` : undefined; const errorId = error ? `${controlId}-error` : undefined; + return