源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
@@ -0,0 +1,146 @@
|
||||
# AGENTS.md
|
||||
|
||||
## Scope
|
||||
|
||||
This file applies to `packages/ui/system/*`.
|
||||
|
||||
`packages/ui/system` is the source package for `@tutti-os/ui-system`, the
|
||||
shared Tutti UI component library. It owns shared CSS tokens, theme styles,
|
||||
icon exports, presentation primitives, reusable host-agnostic business display
|
||||
components, component metadata, storyboard inventory, and the bundled
|
||||
`tutti-ui-system` agent skill.
|
||||
|
||||
Before changing components, icons, metadata, styles, storyboard examples, or
|
||||
the bundled skill, read `ui-system.md`.
|
||||
|
||||
UI-system design compliance is a release gate for this package, not a follow-up
|
||||
task. If a promoted component does not yet follow the shared token model,
|
||||
surface language, primitive vocabulary, and storyboard evidence standard, do
|
||||
not report it as complete.
|
||||
|
||||
## Public API
|
||||
|
||||
Stable public imports are:
|
||||
|
||||
- `@tutti-os/ui-system`
|
||||
- `@tutti-os/ui-system/components`
|
||||
- `@tutti-os/ui-system/metadata`
|
||||
- `@tutti-os/ui-system/icons`
|
||||
- `@tutti-os/ui-system/styles.css`
|
||||
- `@tutti-os/ui-system/utils`
|
||||
|
||||
Rules:
|
||||
|
||||
- prefer adding exports to an existing public barrel before introducing a new
|
||||
public subpath
|
||||
- do not expose `src/*` layout as public API
|
||||
- do not encourage per-file deep imports such as
|
||||
`@tutti-os/ui-system/components/button`
|
||||
- if package exports change intentionally, update both the package exports and
|
||||
the UI-boundary check script
|
||||
|
||||
## Component Library Rules
|
||||
|
||||
- keep `base` components low-level, generic, and
|
||||
frontend-foundation-focused
|
||||
- allow `business` components only when they are reusable business display
|
||||
components that remain host-agnostic and side-effect-free
|
||||
- business components may expose domain display props such as workspace, file,
|
||||
task, agent, status, permission, and callbacks, but must not own daemon,
|
||||
Electron, router, store, query, filesystem, persistence, or workflow calls
|
||||
- before promoting a business component, scan source usage, build a
|
||||
code-evidence state matrix, and define the public props boundary from that
|
||||
evidence; after that, promote it directly into `packages/ui/system` and add
|
||||
storyboard coverage for the accepted states
|
||||
- business components should compose `base` primitives instead of recreating
|
||||
buttons, fields, dialogs, cards, icons, or overlays
|
||||
- promoted components and their storyboard examples must use UI-system semantic
|
||||
tokens and approved shared CSS variables; do not leave raw `hex`,
|
||||
`rgb(...)`, `rgba(...)`, ad hoc gradients, or app-local palette values in the
|
||||
final UI-system implementation unless they already come from approved shared
|
||||
tokens
|
||||
- storyboard coverage must show the component's real promoted surface and
|
||||
states; do not rely on surrounding docs chrome or wrapper panels to mask
|
||||
component-level visual drift
|
||||
- UI storyboard foundation content is JSON-driven. When changing documented
|
||||
token, color, typography, spacing, radius, motion, or overview display data,
|
||||
edit `apps/ui-storyboard/src/foundation/*.json` directly instead of
|
||||
hardcoding those values in `apps/ui-storyboard/src/App.tsx`
|
||||
- migrated consumers must end on the same UI-system visual implementation for
|
||||
the promoted surface; temporary bridges are allowed only for wiring, not as a
|
||||
separate long-lived token or styling system
|
||||
- treat this package as the shared shadcn and Radix host package
|
||||
- when a primitive exists in the shadcn registry, acquire it through shadcn CLI
|
||||
targeted at this package instead of handwriting the component body
|
||||
- keep `components.json` and package aliases usable enough that CLI download
|
||||
remains the default path for shared primitives
|
||||
- after CLI acquisition, limit edits to narrow package-specific adaptation such
|
||||
as icon routing, import aliases, stable exports, and boundary-check fixes
|
||||
- keep CSS variables as the source of truth for token values
|
||||
- prefer semantic token naming over raw palette leakage in public APIs
|
||||
- keep helper exports minimal and tied to primitive support, not general
|
||||
convenience reuse
|
||||
- build primitives for a calm workbench shell, not for marketing-card theatrics
|
||||
- every public component, icon, utility, or style entry must have metadata with
|
||||
a stable readable `id` and `layer`
|
||||
- use the single `tutti-ui-system` skill for component reuse, extraction,
|
||||
base/business classification, metadata, and storyboard work
|
||||
|
||||
## React Component Splitting Rules
|
||||
|
||||
- default to one component per directory; keep the component file, tests,
|
||||
stories, local styles, and tightly coupled implementation-detail helpers
|
||||
colocated inside that directory
|
||||
- default to one React component per file; allow multiple small stateless
|
||||
helpers in one file only when they are tightly coupled implementation detail
|
||||
of the exported component
|
||||
- split presentational components away from host wiring; components promoted
|
||||
into ui-system must receive data, labels, status, and callbacks through props
|
||||
rather than owning side effects or app workflow
|
||||
- if a component does not need internal state or refs, prefer a plain function
|
||||
component; introduce heavier component structure only when state, refs, or
|
||||
lifecycle-like coordination is actually required
|
||||
- when behavior is reusable but host-owned, extract it into caller-owned hooks,
|
||||
adapters, or controller code instead of embedding that logic in the ui-system
|
||||
component body
|
||||
- do not use mixin-style reuse or implicit component coupling; prefer explicit
|
||||
composition through child components, slots, helper modules, or narrow
|
||||
wrappers
|
||||
- keep component APIs semantic and stable; do not repurpose DOM prop names such
|
||||
as `style` or `className` to carry business meaning when a clearer prop like
|
||||
`variant`, `tone`, `status`, or `layout` is intended
|
||||
- use spread props sparingly on public components; pass explicit props whenever
|
||||
possible so the boundary stays readable and host-agnostic
|
||||
- list and collection components must render with stable identity from caller
|
||||
data; do not rely on array index keys in promoted UI-system surfaces
|
||||
- when a component grows multiple visual regions or branches, first try to
|
||||
split subparts into local render helpers or child components before adding
|
||||
more mode booleans to one large component
|
||||
- avoid boolean-prop sprawl for mutually exclusive modes; prefer a finite
|
||||
variant, discriminated union, explicit slot, or separate subcomponent when
|
||||
states represent distinct rendering modes
|
||||
- keep user-visible copy caller-owned by default; if text changes by host,
|
||||
locale, or workflow, expose it through props, labels, or children instead of
|
||||
hardcoding it inside the shared component
|
||||
- use the filename as the component name and keep exported component names in
|
||||
PascalCase so file boundaries stay obvious during promotion, review, and
|
||||
migration
|
||||
|
||||
## Validation
|
||||
|
||||
- Run `pnpm typecheck`
|
||||
- Run `pnpm check:ui-boundaries`
|
||||
- If component metadata changed, run `node tools/scripts/check-ui-metadata.mjs`
|
||||
- If storyboard inventory changed, run
|
||||
`pnpm --filter @tutti-os/ui-storyboard typecheck`
|
||||
- If a change affects desktop integration, also run
|
||||
`pnpm --filter @tutti-os/desktop build`
|
||||
- In the handoff, explicitly state whether tokens, primitives, storyboard
|
||||
surface, and migrated consumer all comply with the UI-system standard; if any
|
||||
of those are still divergent, the work is not complete
|
||||
|
||||
## Related Docs
|
||||
|
||||
- `ui-system.md`
|
||||
- `docs/conventions/desktop-visual-language.md`
|
||||
- `docs/conventions/local-git-hooks.md`
|
||||
@@ -0,0 +1,114 @@
|
||||
@tutti-os/ui-system
|
||||
|
||||
The Sortable compound component in
|
||||
src/components/sortable/sortable.tsx is adapted from Dice UI
|
||||
(https://github.com/sadmann7/diceui), used under the MIT License. The source was
|
||||
installed from the Dice UI shadcn registry with
|
||||
`pnpm dlx shadcn@latest add @diceui/sortable` and then adapted to Tutti's UI
|
||||
System accessibility, input-sensor, and reduced-motion contracts. The upstream
|
||||
source revision reviewed for this integration is
|
||||
d9763d82530416dfa4c81c462387b55d06bae4ec.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Sadman Sakib
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
The compose-refs utility in src/lib/compose-refs.ts is adapted from Radix UI
|
||||
Primitives (https://github.com/radix-ui/primitives), revision
|
||||
3956076860c350d6c2461c9ce2a1ad707dc097ad, used under the MIT License.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 WorkOS
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
The MessageSquareTextIcon, QuoteIcon, and GripVerticalIcon paths in
|
||||
src/icons/system-icons.tsx are source-derived from Lucide
|
||||
(https://github.com/lucide-icons/lucide), revision
|
||||
658573b0171e693bc965c167592cc0b92d002a3e, used under the ISC License.
|
||||
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
|
||||
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
|
||||
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
|
||||
USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
----------------------------------------------------------------------
|
||||
|
||||
The Native Button interaction and variant structure in
|
||||
src/native/button.tsx was adapted from the React Native Reusables NativeWind
|
||||
Button registry item (https://reactnativereusables.com/r/nativewind/button.json),
|
||||
reviewed on 2026-07-25, and then rewritten to use Tutti Native semantic tokens
|
||||
and public component contracts. React Native Reusables is used under the MIT
|
||||
License.
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) Founded Labs
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,97 @@
|
||||
# @tutti-os/ui-system
|
||||
|
||||
Shared Tutti UI tokens, styles, icons, and low-level React primitives.
|
||||
|
||||
This package is published to npm as `@tutti-os/ui-system`.
|
||||
|
||||
Import the stylesheet once from the renderer or application shell:
|
||||
|
||||
```ts
|
||||
import "@tutti-os/ui-system/styles.css";
|
||||
```
|
||||
|
||||
Application code should prefer the root package export and the documented stable
|
||||
subpaths over deep imports from internal files.
|
||||
|
||||
## External Development
|
||||
|
||||
External consumers should install the package normally:
|
||||
|
||||
```bash
|
||||
pnpm add @tutti-os/ui-system
|
||||
```
|
||||
|
||||
For local source sync from a Tutti checkout, start the UI system dev server:
|
||||
|
||||
```bash
|
||||
pnpm --filter @tutti-os/ui-system dev:server
|
||||
```
|
||||
|
||||
Then add the Vite plugin in the external app:
|
||||
|
||||
```ts
|
||||
import { tuttiUISystemDev } from "@tutti-os/ui-system/dev-vite";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tuttiUISystemDev()]
|
||||
});
|
||||
```
|
||||
|
||||
When the dev server is reachable, the plugin mirrors the allowed UI-system
|
||||
source and skill-support files into `.tutti-ui-system-dev/` and aliases the
|
||||
stable package entrypoints to that cache. When the dev server is unavailable,
|
||||
resolution falls back to the installed package in `node_modules`.
|
||||
|
||||
Add the generated cache to the external app's `.gitignore`:
|
||||
|
||||
```text
|
||||
.tutti-ui-system-dev/
|
||||
```
|
||||
|
||||
If the external app uses Tailwind CSS, include both the installed package output
|
||||
and the generated dev cache in the app's Tailwind source scan:
|
||||
|
||||
```css
|
||||
@source "../node_modules/@tutti-os/ui-system/dist";
|
||||
@source "../.tutti-ui-system-dev";
|
||||
```
|
||||
|
||||
## Agent Usage
|
||||
|
||||
Coding agents should read component metadata before creating or promoting UI:
|
||||
|
||||
```ts
|
||||
import { uiSystemMetadata } from "@tutti-os/ui-system/metadata";
|
||||
```
|
||||
|
||||
When promoting business UI into this package, use the bundled
|
||||
`agent/tutti-ui-system/SKILL.md` skill when it is available. In the source
|
||||
checkout, also read `AGENTS.md`, `ui-system.md`, and
|
||||
`docs/conventions/desktop-visual-language.md`. The durable rules are:
|
||||
|
||||
1. prefer existing metadata entries before creating a component
|
||||
2. classify the component as `base` or `business`
|
||||
3. keep business components host-agnostic and side-effect-free
|
||||
4. before promoting a business component, scan source usage and define the
|
||||
public props boundary from code evidence
|
||||
5. compose business components from base primitives
|
||||
6. add metadata, stable exports, and storyboard examples for public UI
|
||||
7. run metadata and boundary validation before shipping
|
||||
|
||||
External repositories can install the bundled skill into their local Codex
|
||||
skill directory with one command:
|
||||
|
||||
```bash
|
||||
pnpm exec tutti-ui-system-install-skill
|
||||
```
|
||||
|
||||
This copies the package skill into:
|
||||
|
||||
```text
|
||||
.codex/skills/tutti-ui-system/SKILL.md
|
||||
```
|
||||
|
||||
When `.tutti-ui-system-dev/` is present, the installer prefers the synced
|
||||
source checkout so the installed skill and bundled UI-system rules stay aligned
|
||||
with the current local UI-system source. The installer does not overwrite a
|
||||
locally modified skill unless `--force` is provided.
|
||||
Executable
+241
@@ -0,0 +1,241 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
access,
|
||||
cp,
|
||||
mkdir,
|
||||
readdir,
|
||||
readFile,
|
||||
rm,
|
||||
stat
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
const skillName = "tutti-ui-system";
|
||||
const devCacheDirectoryName = ".tutti-ui-system-dev";
|
||||
const companionFiles = ["AGENTS.md", "ui-system.md"];
|
||||
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
|
||||
if (options.help) {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const targetRoot = resolve(options.cwd, ".codex", "skills");
|
||||
const targetDirectory = join(targetRoot, skillName);
|
||||
const sourceRoot = await resolveSourceRoot(options.cwd);
|
||||
const sourceDirectory = join(sourceRoot, "agent", skillName);
|
||||
|
||||
await assertReadableDirectory(sourceDirectory);
|
||||
await Promise.all(
|
||||
companionFiles.map((fileName) =>
|
||||
assertReadableFile(join(sourceRoot, fileName))
|
||||
)
|
||||
);
|
||||
await mkdir(targetRoot, { recursive: true });
|
||||
|
||||
if (await pathExists(targetDirectory)) {
|
||||
const targetStats = await stat(targetDirectory);
|
||||
|
||||
if (!targetStats.isDirectory()) {
|
||||
throw new Error(`Target exists and is not a directory: ${targetDirectory}`);
|
||||
}
|
||||
|
||||
if (!options.force) {
|
||||
if (await directoriesMatch(sourceRoot, sourceDirectory, targetDirectory)) {
|
||||
console.log(
|
||||
`tutti-ui-system skill already configured at ${targetDirectory}`
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Target skill already exists with local changes: ${targetDirectory}\n` +
|
||||
"Run with --force to replace it."
|
||||
);
|
||||
}
|
||||
|
||||
await rm(targetDirectory, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
await cp(sourceDirectory, targetDirectory, {
|
||||
errorOnExist: false,
|
||||
force: true,
|
||||
recursive: true
|
||||
});
|
||||
await Promise.all(
|
||||
companionFiles.map((fileName) =>
|
||||
cp(join(sourceRoot, fileName), join(targetDirectory, fileName), {
|
||||
errorOnExist: false,
|
||||
force: true,
|
||||
recursive: false
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
console.log(`Installed tutti-ui-system skill to ${targetDirectory}`);
|
||||
console.log(
|
||||
"Agents can now load it from .codex/skills/tutti-ui-system/SKILL.md"
|
||||
);
|
||||
|
||||
function parseArgs(args) {
|
||||
const parsed = {
|
||||
cwd: process.cwd(),
|
||||
force: false,
|
||||
help: false
|
||||
};
|
||||
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index];
|
||||
|
||||
if (arg === "--force") {
|
||||
parsed.force = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
parsed.help = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--cwd") {
|
||||
const cwd = args[index + 1];
|
||||
if (!cwd) {
|
||||
throw new Error("--cwd requires a directory path");
|
||||
}
|
||||
parsed.cwd = resolve(cwd);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown option: ${arg}`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage: tutti-ui-system-install-skill [options]
|
||||
|
||||
Copies the bundled Tutti UI System skill into the current repository.
|
||||
|
||||
Options:
|
||||
--cwd <path> Repository root to configure. Defaults to the current directory.
|
||||
--force Replace an existing .codex/skills/tutti-ui-system directory.
|
||||
-h, --help Show this help message.`);
|
||||
}
|
||||
|
||||
async function assertReadableDirectory(path) {
|
||||
await access(path, constants.R_OK);
|
||||
const pathStats = await stat(path);
|
||||
|
||||
if (!pathStats.isDirectory()) {
|
||||
throw new Error(`Expected directory: ${path}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function assertReadableFile(path) {
|
||||
await access(path, constants.R_OK);
|
||||
const pathStats = await stat(path);
|
||||
|
||||
if (!pathStats.isFile()) {
|
||||
throw new Error(`Expected file: ${path}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function pathExists(path) {
|
||||
try {
|
||||
await access(path, constants.F_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveSourceRoot(cwd) {
|
||||
const devCacheRoot = resolve(cwd, devCacheDirectoryName);
|
||||
const devCacheSkillDirectory = join(devCacheRoot, "agent", skillName);
|
||||
|
||||
if (
|
||||
(await pathExists(devCacheSkillDirectory)) &&
|
||||
(await pathExists(join(devCacheRoot, "AGENTS.md"))) &&
|
||||
(await pathExists(join(devCacheRoot, "ui-system.md")))
|
||||
) {
|
||||
return devCacheRoot;
|
||||
}
|
||||
|
||||
return packageRoot;
|
||||
}
|
||||
|
||||
async function directoriesMatch(sourceRoot, sourceDirectory, rightDirectory) {
|
||||
const sourceEntries = await listBundleFiles(sourceRoot, sourceDirectory);
|
||||
const leftEntries = sourceEntries.map((entry) => entry.targetRelativePath);
|
||||
const rightEntries = await listFiles(rightDirectory, rightDirectory);
|
||||
|
||||
if (leftEntries.length !== rightEntries.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let index = 0; index < leftEntries.length; index += 1) {
|
||||
if (leftEntries[index] !== rightEntries[index]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const leftFile = sourceEntries[index].sourceAbsolutePath;
|
||||
const rightFile = join(rightDirectory, rightEntries[index]);
|
||||
|
||||
const [leftContent, rightContent] = await Promise.all([
|
||||
readFile(leftFile),
|
||||
readFile(rightFile)
|
||||
]);
|
||||
|
||||
if (!leftContent.equals(rightContent)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async function listBundleFiles(sourceRoot, sourceDirectory) {
|
||||
const skillFiles = await listFiles(sourceDirectory, sourceDirectory);
|
||||
const companionEntries = companionFiles.map((fileName) => ({
|
||||
sourceAbsolutePath: join(sourceRoot, fileName),
|
||||
targetRelativePath: fileName
|
||||
}));
|
||||
|
||||
return skillFiles
|
||||
.map((relativePath) => ({
|
||||
sourceAbsolutePath: join(sourceDirectory, relativePath),
|
||||
targetRelativePath: relativePath
|
||||
}))
|
||||
.concat(companionEntries)
|
||||
.sort((left, right) =>
|
||||
left.targetRelativePath.localeCompare(right.targetRelativePath)
|
||||
);
|
||||
}
|
||||
|
||||
async function listFiles(rootDirectory, directory) {
|
||||
const entries = await readdir(directory, { withFileTypes: true });
|
||||
const files = await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const absolutePath = join(directory, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
return listFiles(rootDirectory, absolutePath);
|
||||
}
|
||||
|
||||
if (!entry.isFile()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return relative(rootDirectory, absolutePath);
|
||||
})
|
||||
);
|
||||
|
||||
return files.flat().sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
---
|
||||
name: tutti-ui-system
|
||||
description: Use when working with @tutti-os/ui-system components, replacing local UI with shared components, querying component ids or metadata, promoting UI into shared base or business components, or maintaining UI-system storyboard inventory.
|
||||
---
|
||||
|
||||
# Tutti UI System
|
||||
|
||||
Use this skill as the single entrypoint for `@tutti-os/ui-system` component
|
||||
reuse, extraction, promotion, metadata, and storyboard work.
|
||||
|
||||
## Non-Negotiable Standard
|
||||
|
||||
Any UI promoted into `@tutti-os/ui-system` must fully follow the UI-system
|
||||
design standard before it can be reported as complete.
|
||||
|
||||
Treat these as hard requirements, not cleanup suggestions:
|
||||
|
||||
- use UI-system semantic tokens and existing shared CSS variables; do not leave
|
||||
raw `hex`, `rgb(...)`, `rgba(...)`, ad hoc gradients, or app-local palette
|
||||
values in promoted components or their storyboard examples unless the source
|
||||
of truth already exposes them as approved tokens
|
||||
- compose existing UI-system `base` primitives such as `Card`, `Button`,
|
||||
`Tooltip`, `Dialog`, and related vocabulary before creating custom panel,
|
||||
button, field, or overlay treatments
|
||||
- use icon components from `@tutti-os/ui-system/icons` for promoted
|
||||
components and storyboard examples. Do not inline SVG/data URI assets, import
|
||||
app-local icon files, or pull third-party icon packages directly from promoted
|
||||
UI. If the source UI depends on an icon that is not in the UI system, promote
|
||||
the source-derived icon into `packages/ui/system/src/icons` with metadata
|
||||
first, then consume the UI-system icon export.
|
||||
- make storyboard examples render the real component surface and states; do not
|
||||
rely on surrounding docs chrome to hide component-level visual drift or to
|
||||
fake the final panel/surface language
|
||||
- when a consumer is migrated, its final rendered result must also follow the
|
||||
same UI-system visual standard; a temporary bridge may help wiring, but it is
|
||||
not acceptable as the final visual implementation if it keeps a second token
|
||||
system or divergent component styling
|
||||
|
||||
If these conditions are not met, report the promotion as incomplete or blocked,
|
||||
not complete.
|
||||
|
||||
## Source Of Truth
|
||||
|
||||
Read these before editing:
|
||||
|
||||
1. nearest `AGENTS.md` for the target code
|
||||
2. local `AGENTS.md` bundled with this skill
|
||||
3. local `ui-system.md` bundled with this skill
|
||||
4. component metadata from the first available source:
|
||||
- `GET http://127.0.0.1:4100/components`
|
||||
- `packages/ui/system/src/metadata/components.json`
|
||||
- `@tutti-os/ui-system/metadata` from the installed package
|
||||
|
||||
Use stable public imports only:
|
||||
|
||||
- `@tutti-os/ui-system`
|
||||
- `@tutti-os/ui-system/components`
|
||||
- `@tutti-os/ui-system/icons`
|
||||
- `@tutti-os/ui-system/metadata`
|
||||
- `@tutti-os/ui-system/styles.css`
|
||||
- `@tutti-os/ui-system/utils`
|
||||
|
||||
Never deep import `@tutti-os/ui-system/src/*` or per-file component paths.
|
||||
|
||||
## Route The Task
|
||||
|
||||
Read only the reference file that matches the task.
|
||||
|
||||
- Using or querying existing components:
|
||||
`references/use-existing-component.md`
|
||||
- Extracting a low-level base primitive:
|
||||
`references/extract-base-component.md`
|
||||
- Promoting reusable business UI into a shared component:
|
||||
`references/promote-business-component.md`
|
||||
- Maintaining ids, metadata, exports, or storyboard inventory:
|
||||
`references/maintain-inventory.md`
|
||||
|
||||
## Global Boundaries
|
||||
|
||||
Keep these outside `@tutti-os/ui-system` components:
|
||||
|
||||
- daemon, Electron, filesystem, router, or host adapter calls
|
||||
- data fetching, cache mutation, persistence, polling, and global store
|
||||
ownership
|
||||
- workflow orchestration such as onboarding, workspace registration, install or
|
||||
uninstall flows, confirmation dialogs, queueing, or navigation
|
||||
- i18n key lookup and business-specific copy derivation unless supplied by
|
||||
props, children, or labels
|
||||
|
||||
For any promoted public component, add stable exports, metadata, and storyboard
|
||||
coverage that match the chosen reference workflow.
|
||||
|
||||
For promoted base components, preview coverage is not satisfied by metadata
|
||||
alone. DOM components need a real renderable example in `apps/ui-storyboard`.
|
||||
React Native components need a real renderable example in the Mobile
|
||||
development gallery because the DOM storyboard cannot render their final
|
||||
surface. In both cases, the example must use the stable public entrypoint and
|
||||
show the component's public states.
|
||||
|
||||
For business component promotion, use a copy-first workflow: move the existing
|
||||
business component structure as intact as possible, preserve the real DOM,
|
||||
visual hierarchy, state branches, and interaction layout, then progressively
|
||||
remove host dependencies and standardize the public API. Do not begin by
|
||||
inventing a cleaner abstraction or new visual treatment. The state matrix,
|
||||
props boundary, and candidate source UI define what to copy, what to keep
|
||||
caller-owned, and what to standardize after parity exists.
|
||||
|
||||
Treat business component promotion as an iterative migration-review loop, not a
|
||||
single extraction pass:
|
||||
|
||||
1. migrate the source UI copy-first
|
||||
2. recreate source-backed states in storyboard
|
||||
3. run independent review against the original source and screenshot
|
||||
4. migrate again to close review findings
|
||||
5. repeat review until source/design parity is acceptable
|
||||
|
||||
Only after that loop should the API be generalized further. Do not report the
|
||||
component as complete after the first migration if review still shows material
|
||||
DOM, visual, token, state, icon, or storyboard coverage drift.
|
||||
|
||||
The promoted UI must follow the original design exactly unless the user
|
||||
explicitly approves a visual change. Do not add new decoration, controls,
|
||||
icons, layout chrome, copy, motion, states, spacing, or visual hierarchy that
|
||||
does not exist in the source UI or provided screenshot. If UI-system token or
|
||||
primitive replacement is needed, it must preserve the observed design and
|
||||
interaction path rather than becoming a redesign.
|
||||
|
||||
Copy-first also applies to dependent presentational subcomponents and
|
||||
third-party-library wrappers used by the candidate UI. Do not copy only the top
|
||||
level JSX and recreate nested behavior from memory. Trace the dependency tree:
|
||||
pure display helpers should move with the component; reusable wrappers around
|
||||
Radix, floating UI, resizable panels, virtualization, or similar libraries
|
||||
should be promoted or reused as `base` primitives first; host-coupled children
|
||||
must be split into caller-owned data, labels, callbacks, or slots before the
|
||||
business component is considered promoted.
|
||||
|
||||
## Design Foundation Verification
|
||||
|
||||
Every promoted component must comply with
|
||||
`ui-system.md`, especially the shared tokens,
|
||||
theme variables, spacing, radius, typography, surface language, interactive
|
||||
states, and existing `base` primitive vocabulary.
|
||||
|
||||
Explicitly check and report all of these before completion:
|
||||
|
||||
- color and surface styling come from UI-system semantic tokens rather than raw
|
||||
palette values
|
||||
- panels, rows, controls, and overlays compose existing base primitives where
|
||||
applicable instead of recreating them locally
|
||||
- storyboard shows the component's real promoted surface rather than only a
|
||||
documentation wrapper
|
||||
- migrated consumers no longer depend on a separate visual token system for the
|
||||
promoted surface
|
||||
|
||||
Run the Tutti promotion review gate before reporting completion. The gate is
|
||||
adapted from frontend design review practice but constrained to Tutti's dense
|
||||
workbench product language:
|
||||
|
||||
- Frictionless: the migrated consumer preserves the original task path, keeps a
|
||||
clear action hierarchy, and does not bury primary or recovery actions.
|
||||
- Quality craft: visual parity evidence is captured for selected states, shared
|
||||
tokens and primitives are used, light/dark and interactive states work, and no
|
||||
unapproved raw palette, spacing, radius, typography, or motion drift remains.
|
||||
- Trustworthy: empty, loading, disabled, error-like, permission-limited, and
|
||||
AI-generated-content states keep clear labels, actionable recovery, and
|
||||
host-owned policy or provenance outside the shared component.
|
||||
|
||||
After promoting a base or business component, start an independent subagent to
|
||||
review design-foundation compliance before reporting completion. Provide the
|
||||
subagent with the promoted files, source usage, selected states, storyboard and
|
||||
metadata entries, and the UI-system guidelines. If subagents are unavailable,
|
||||
state that design-foundation verification is blocked and do not claim full
|
||||
compliance.
|
||||
|
||||
Report the gate result with:
|
||||
|
||||
- context: source usage, promoted component id/layer, user task, selected states
|
||||
- status: pass, needs work, or blocked
|
||||
- pillar assessment: Frictionless, Quality craft, Trustworthy
|
||||
- issues grouped as blocking, major, and minor
|
||||
- validation commands and exact results
|
||||
- remaining risks, uncovered states, or approved visual deltas
|
||||
|
||||
## API Composition Review
|
||||
|
||||
When converting source states into public props, review the API shape before
|
||||
writing the promoted component:
|
||||
|
||||
- avoid boolean prop proliferation for rendering modes; mode axes such as
|
||||
`isFoo`, `showBar`, or `withBaz` must come from code evidence and usually
|
||||
become a finite variant, discriminated union, explicit component variant,
|
||||
slot, or composed child
|
||||
- keep standard UI booleans such as `disabled`, `loading`, `selected`, `open`,
|
||||
`required`, and `invalid` only when they represent real component state and
|
||||
cannot create impossible combinations
|
||||
- prefer `children` or named slots for caller-owned visual regions; use render
|
||||
props only when the shared component must pass data back to the caller
|
||||
- use compound components and context only for genuinely complex reusable
|
||||
structures where consumers need to compose subparts without prop drilling
|
||||
- if shared state is needed, define a narrow context value as `state`,
|
||||
`actions`, and `meta`; providers may inject state but must not own daemon,
|
||||
Electron, router, store, query, persistence, or workflow side effects
|
||||
- for new React components in this React 19 codebase, prefer the React 19 API
|
||||
shape such as `ref` as a prop; do not churn shadcn or Radix-acquired code only
|
||||
to normalize style when behavior and public API are already sound
|
||||
|
||||
Report the API composition decision with the state matrix: which differences
|
||||
became props, variants, slots, children, explicit variants, provider state, or
|
||||
stayed host-owned.
|
||||
|
||||
## Validation Commands
|
||||
|
||||
Run the smallest relevant checks from the selected reference. Common checks are:
|
||||
|
||||
```bash
|
||||
node tools/scripts/check-ui-metadata.mjs
|
||||
pnpm check:ui-boundaries
|
||||
pnpm --filter @tutti-os/ui-storyboard typecheck
|
||||
```
|
||||
|
||||
If runtime component code changed, also run the relevant package typecheck or
|
||||
consumer build.
|
||||
|
||||
When a base component is promoted, verify both of these conditions before
|
||||
reporting completion:
|
||||
|
||||
- the component metadata opts into storyboard visibility when appropriate
|
||||
- `apps/ui-storyboard` contains a concrete rendered example for the promoted
|
||||
component states, not just inventory wiring
|
||||
@@ -0,0 +1,89 @@
|
||||
# Extract Base Component
|
||||
|
||||
Use this reference when the target is a low-level visual primitive.
|
||||
|
||||
## Base Criteria
|
||||
|
||||
Proceed only if the public API has no domain noun and props describe generic UI
|
||||
concerns:
|
||||
|
||||
- presentation and variants
|
||||
- interaction and accessibility
|
||||
- refs, slots, class names, and children
|
||||
- controlled or uncontrolled primitive state
|
||||
|
||||
If the component represents a workspace, file, task, agent, run, project,
|
||||
account, or other business concept, use `promote-business-component.md`
|
||||
instead.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Check metadata and existing exports first.
|
||||
2. Read the bundled `ui-system.md` before implementation and
|
||||
treat it as a hard gate for the extraction. The component must follow the
|
||||
shared token, theme variable, spacing, radius, typography, surface,
|
||||
interactive-state, accessibility, and reduced-motion rules from
|
||||
`@tutti-os/ui-system`; do not preserve or introduce caller-local styling
|
||||
when it conflicts with those guidelines.
|
||||
3. If the primitive exists in the shadcn registry, acquire it through shadcn CLI
|
||||
targeted at `packages/ui/system`.
|
||||
4. Decide the primitive API before editing:
|
||||
- use finite variants or discriminated unions for mutually exclusive visual
|
||||
modes
|
||||
- keep standard UI booleans such as `disabled`, `loading`, `selected`,
|
||||
`open`, `required`, and `invalid` only when they represent real states
|
||||
- prefer `children`, slots, refs, and class names for composition instead
|
||||
of broad render props
|
||||
- use compound components or context only when consumers need to assemble
|
||||
reusable subparts that share primitive state
|
||||
- follow the React 19 baseline for new hand-authored components, but do not
|
||||
rewrite shadcn or Radix internals only for API-style churn
|
||||
5. Adapt only package aliases, icon routing, tokens, stable exports, metadata,
|
||||
storyboard examples, and boundary-check issues.
|
||||
6. Keep helper exports minimal and directly tied to primitive support.
|
||||
7. Add metadata with `layer: "base"`.
|
||||
8. Add preview coverage for the public states and variants exposed by the
|
||||
primitive.
|
||||
- This is mandatory for base-component promotion.
|
||||
- Do not treat metadata as sufficient by itself.
|
||||
- DOM primitives need an example in `apps/ui-storyboard`; React Native
|
||||
primitives need an example in the Mobile development gallery. Do not
|
||||
pretend that a DOM wrapper is evidence for a Native surface.
|
||||
9. Replace duplicated local UI only after the shared primitive exists.
|
||||
10. Run the promotion review gate from
|
||||
`ui-system.md`: verify Frictionless task
|
||||
preservation, Quality Craft visual/token/state parity, and Trustworthy
|
||||
status/error/accessibility behavior for the migrated consumer.
|
||||
11. Start an independent design-foundation review subagent after promotion. The
|
||||
review must check the promoted files against
|
||||
`ui-system.md`, existing tokens, primitives,
|
||||
API shape, storyboard coverage, and metadata. Resolve any reported design
|
||||
drift before completion.
|
||||
|
||||
## Validation
|
||||
|
||||
Run the relevant checks:
|
||||
|
||||
```bash
|
||||
node tools/scripts/check-ui-metadata.mjs
|
||||
pnpm check:ui-boundaries
|
||||
pnpm --filter @tutti-os/ui-storyboard typecheck
|
||||
pnpm --filter @tutti-os/ui-system typecheck
|
||||
```
|
||||
|
||||
If a consumer was migrated, also run that consumer's typecheck or build.
|
||||
|
||||
Before reporting completion, confirm preview delivery at two levels:
|
||||
|
||||
- inventory: the component is discoverable from the appropriate DOM storyboard
|
||||
or Native development gallery
|
||||
- rendering: the component has a concrete example that renders its public
|
||||
states or variants on its target renderer
|
||||
|
||||
Do not report full design-foundation compliance unless the subagent review ran
|
||||
and found no unresolved drift. If subagents are unavailable, report the
|
||||
verification as blocked.
|
||||
|
||||
Report the promotion review result with the component id, selected states,
|
||||
Frictionless / Quality Craft / Trustworthy pillar status, blocking/major/minor
|
||||
issues, validation commands, and remaining risks or approved visual deltas.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Maintain Inventory
|
||||
|
||||
Use this reference when changing component ids, metadata, exports, or storyboard
|
||||
inventory without promoting a new component.
|
||||
|
||||
## Metadata Rules
|
||||
|
||||
Every public UI-system entry must have metadata with:
|
||||
|
||||
- stable readable `id`
|
||||
- globally unique kebab-case id
|
||||
- `layer` as `base` or `business`
|
||||
- `source` under `packages/ui/system/src`
|
||||
- stable public `from` entrypoint
|
||||
|
||||
Do not expose `src/*` layout as public API and do not encourage per-file deep
|
||||
imports.
|
||||
|
||||
## Storyboard Rules
|
||||
|
||||
Keep storyboard grouped by:
|
||||
|
||||
- `Foundation`
|
||||
- `Base Components`
|
||||
- `Business Components`
|
||||
|
||||
Visible component stories should support copying the component id.
|
||||
|
||||
When a base component is newly promoted into `@tutti-os/ui-system`, updating
|
||||
inventory alone is not enough. The same change must also add or refresh a real
|
||||
renderable example in `apps/ui-storyboard` so the promoted component is
|
||||
immediately reviewable from the shared storyboard.
|
||||
|
||||
When changing metadata or storyboard inventory, keep ids stable unless the
|
||||
rename is intentional and callers or docs are updated together.
|
||||
|
||||
## Validation
|
||||
|
||||
Run the relevant checks:
|
||||
|
||||
```bash
|
||||
node tools/scripts/check-ui-metadata.mjs
|
||||
pnpm check:ui-boundaries
|
||||
pnpm --filter @tutti-os/ui-storyboard typecheck
|
||||
```
|
||||
@@ -0,0 +1,316 @@
|
||||
# Promote Business Component
|
||||
|
||||
Use this reference when business-side UI should become a reusable
|
||||
host-agnostic display component.
|
||||
|
||||
## Business Criteria
|
||||
|
||||
Proceed only if the component can render from props with no host side effects.
|
||||
Business components may expose domain display props such as workspace, file,
|
||||
task, agent, run, project, account, status, permission, labels, and callbacks.
|
||||
|
||||
Do not promote UI that owns daemon, Electron, router, store, query, persistence,
|
||||
polling, filesystem access, or workflow orchestration.
|
||||
|
||||
## Agent-Owned Analysis
|
||||
|
||||
The agent must automatically analyze the candidate from code evidence. Do not
|
||||
ask the user to provide the state matrix or props boundary unless the code has
|
||||
conflicting evidence or an unclear business meaning.
|
||||
|
||||
Scan:
|
||||
|
||||
- source component and nearby helpers
|
||||
- dependent presentational subcomponents imported by the source component
|
||||
- third-party-library wrappers used by the candidate UI, such as Radix,
|
||||
floating UI, resizable panels, drag/drop, virtualization, or editor shells
|
||||
- call sites and conditional rendering branches
|
||||
- props, types, tests, mocks, fixtures, and sample data
|
||||
- relevant i18n keys and resolved labels
|
||||
- existing UI-system metadata and components
|
||||
|
||||
Build a state matrix from that evidence. For each candidate state, record:
|
||||
|
||||
- state name
|
||||
- source file or branch proving the state
|
||||
- props or data needed to render it
|
||||
- variation axes and whether each axis is visual, structural, behavioral, or
|
||||
host-owned
|
||||
- host-owned behavior that must stay outside the shared component
|
||||
- whether the state belongs in the shared component contract
|
||||
|
||||
## Agent-Owned Boundary Decision
|
||||
|
||||
The agent decides the proposed component boundary before implementation:
|
||||
|
||||
- component `id` and `layer: "business"`
|
||||
- source usage being replaced
|
||||
- intended reuse surfaces
|
||||
- public props and callbacks
|
||||
- API shape decision: variants, discriminated unions, slots, children, explicit
|
||||
component variants, compound subcomponents, provider state, and host-owned
|
||||
caller logic
|
||||
- host-owned state and side effects that remain outside
|
||||
- states that will appear in storyboard
|
||||
- stable export path and metadata entry
|
||||
|
||||
If the candidate is not reusable or cannot stay host-agnostic, do not promote
|
||||
it. Prefer using existing components or keeping the UI local.
|
||||
|
||||
## API Composition Gate
|
||||
|
||||
Before writing the promoted component, convert the state matrix into a public
|
||||
API deliberately:
|
||||
|
||||
1. List every visual, structural, and behavioral variation found in source
|
||||
evidence.
|
||||
2. Keep only standard state booleans such as `disabled`, `loading`, `selected`,
|
||||
`open`, `required`, or `invalid` when they represent real states and do not
|
||||
create impossible combinations.
|
||||
3. Replace mode booleans such as `isFoo`, `showBar`, and `withBaz` with a
|
||||
finite variant, discriminated union, explicit component variant, slot, or
|
||||
composed child.
|
||||
4. Prefer `children` or named slots for caller-owned visual regions. Use render
|
||||
props only when the shared component needs to pass data back to the caller.
|
||||
5. Use compound components and context only when consumers need to assemble
|
||||
subparts while sharing state. A simple row, card, badge, toolbar, or display
|
||||
panel should stay as a direct props-driven component.
|
||||
6. If shared state is necessary, define a narrow injectable context contract as
|
||||
`state`, `actions`, and `meta`. Providers may adapt caller state, but daemon,
|
||||
Electron, router, store, query, persistence, filesystem, i18n lookup, and
|
||||
workflow orchestration remain outside `@tutti-os/ui-system`.
|
||||
7. For new React components, use the repository's React 19 baseline, including
|
||||
`ref` as a prop when needed. Do not rewrite shadcn or Radix-acquired
|
||||
internals solely to normalize API style.
|
||||
|
||||
Stop promotion if the only way to represent the source states is a broad bag of
|
||||
unrelated boolean props or leaked host state. Narrow the boundary, create
|
||||
explicit variants, or keep the UI local.
|
||||
|
||||
## Implementation Blueprint
|
||||
|
||||
Use a copy-first promotion workflow. The first implementation should be a
|
||||
props-driven copy of the source business UI, not a new abstraction designed from
|
||||
memory. Preserve the source DOM hierarchy, visual structure, spacing, state
|
||||
branches, slots, and interaction affordances until parity is visible in
|
||||
storyboard. Only after parity exists should the API be tightened and generalized.
|
||||
|
||||
Run promotion as a loop: migrate, review, migrate, review. The first migration
|
||||
must make source-backed parity visible; review then measures drift against the
|
||||
original code and screenshot; the next migration closes those findings without
|
||||
redesigning. Continue until no material DOM, visual, token, state, icon, or
|
||||
storyboard coverage drift remains. Do not treat the first extracted abstraction
|
||||
as done if review still reports medium or high difference.
|
||||
|
||||
The promoted UI must follow the original design. Do not introduce new visual
|
||||
ideas while promoting: no extra decoration, layout chrome, icons, controls,
|
||||
copy, motion, spacing, state branches, or hierarchy that cannot be traced to the
|
||||
source UI or the user's screenshot. Token replacement and primitive composition
|
||||
are allowed only when they preserve the observed design and interaction path.
|
||||
|
||||
Icons are part of that source-derived visual contract and must still enter the
|
||||
shared package through the UI-system icon layer. When the source UI uses an
|
||||
icon, first reuse an existing `@tutti-os/ui-system/icons` export. If no
|
||||
matching icon exists, promote the source-derived SVG or mark into
|
||||
`packages/ui/system/src/icons`, add metadata, and consume that exported icon
|
||||
from the business component or storyboard. Do not leave inline SVG/data URI
|
||||
icons, app-local asset imports, or direct third-party icon imports in promoted
|
||||
components or storyboard examples.
|
||||
|
||||
Copy and classify dependent subcomponents during the same migration. If a
|
||||
nested helper is pure display, move it with the business component and convert
|
||||
host data to props. If it wraps a third-party UI behavior that is reusable
|
||||
outside the business domain, promote or reuse it as a `base` primitive first and
|
||||
compose it from the business component. If it owns host state, i18n lookup,
|
||||
daemon calls, router/filesystem access, persistence, or workflow orchestration,
|
||||
leave that behavior in the caller and replace the nested region with data,
|
||||
labels, callbacks, or slots. Do not rewrite a new nested component from memory
|
||||
while the original source behavior still exists to copy.
|
||||
|
||||
Implement the promoted component directly from three inputs:
|
||||
|
||||
- the code-evidence state matrix
|
||||
- the proposed public props and callback boundary
|
||||
- the existing candidate source UI or visual surface being extracted
|
||||
|
||||
The promoted component should start as a props-driven version of the candidate
|
||||
source with host-owned behavior removed. Preserve the real visual structure,
|
||||
component composition, class names, spacing, icons, and state-specific branches
|
||||
unless they depend on host-owned behavior. Replace host-owned behavior with
|
||||
public props, callbacks, caller-owned slots, or explicit variants. Add
|
||||
storyboard examples for every accepted public state in the same change so the
|
||||
review can inspect the finished implementation instead of a preflight draft.
|
||||
Do not add states, controls, copy, icons, animation, or visual wrappers that the
|
||||
source component did not have unless the user explicitly asks for that design
|
||||
change.
|
||||
|
||||
Generalize in this order:
|
||||
|
||||
1. Copy the existing component structure and nearby presentational helpers.
|
||||
2. Trace dependent subcomponents and third-party wrappers; move pure display
|
||||
helpers with the component, promote reusable third-party wrappers to `base`
|
||||
primitives, and mark host-coupled children as caller-owned slots or data.
|
||||
3. Replace host imports, data derivation, i18n lookup, store reads, side effects,
|
||||
and daemon/router/filesystem calls with props, labels, callbacks, or slots.
|
||||
4. Recreate the original visual states in storyboard before simplifying the API.
|
||||
5. Run independent review against the source UI and close material drift before
|
||||
simplifying the API.
|
||||
6. Standardize the API names and types around data, labels, actions, variants,
|
||||
and slots while preserving visual and behavioral parity.
|
||||
7. Replace app-local styling with UI-system tokens and base primitives only when
|
||||
the replacement does not change the observed UI or interaction path.
|
||||
8. Reject or remove any invented UI added during promotion unless it is backed
|
||||
by source evidence or an explicit user-approved visual change.
|
||||
|
||||
Do not skip directly to a polished abstraction. If the first promoted version
|
||||
cannot be compared against the source screenshot or source state, the promotion
|
||||
is incomplete.
|
||||
|
||||
If the draft still needs app state, navigation, fetching, persistence, i18n key
|
||||
lookup, or host adapters to render, stop and revise the component boundary
|
||||
instead of promoting it.
|
||||
|
||||
## Promotion Chain Demo
|
||||
|
||||
Example request:
|
||||
|
||||
```text
|
||||
Promote the managed agent settings table into @tutti-os/ui-system.
|
||||
```
|
||||
|
||||
Expected chain:
|
||||
|
||||
1. **Analyze source evidence**
|
||||
- Read the source table, settings panel call sites, tests, mocks, and i18n
|
||||
labels.
|
||||
- Check existing metadata for reusable table, badge, button, dialog, and
|
||||
icon primitives.
|
||||
2. **Build the state matrix**
|
||||
|
||||
```text
|
||||
normal
|
||||
- Evidence: settings table renders installed agents with status and actions.
|
||||
- Props/data: rows, status labels, action labels, icon slots, callbacks.
|
||||
- Host-owned: install/uninstall orchestration, queue state derivation, i18n.
|
||||
- Contract: yes.
|
||||
|
||||
empty
|
||||
- Evidence: settings surface renders no configured agents.
|
||||
- Props/data: empty title/body.
|
||||
- Host-owned: deciding whether inventory is empty.
|
||||
- Contract: yes.
|
||||
|
||||
disabled
|
||||
- Evidence: actions disabled while an operation is pending.
|
||||
- Props/data: disabled rows or disabled actions.
|
||||
- Host-owned: permission and pending-operation calculation.
|
||||
- Contract: yes.
|
||||
|
||||
error-like
|
||||
- Evidence: row can show install failure or unavailable status.
|
||||
- Props/data: tone, status label, supporting text.
|
||||
- Host-owned: failure classification and retry behavior.
|
||||
- Contract: yes.
|
||||
```
|
||||
|
||||
3. **Decide the boundary before implementation**
|
||||
- `id`: a stable kebab-case business component id, for example
|
||||
`example-business-component`
|
||||
- `layer`: `business`
|
||||
- Export: a matching PascalCase component name, for example
|
||||
`ExampleBusinessComponent`
|
||||
- Public props: rows, labels, icon render slots, action callbacks, disabled
|
||||
flags, status/tone fields, empty-state copy.
|
||||
- API shape: row status as finite tone values, callbacks as host-provided
|
||||
actions, empty state copy as labels, and no install/uninstall mode
|
||||
booleans. If the table later needs caller-owned row adornments, prefer a
|
||||
named slot or composed child over a broad render prop.
|
||||
- Host-owned behavior: i18n lookup, daemon calls, install queue,
|
||||
confirmation dialogs, persistence, routing, and state derivation.
|
||||
4. **Implement the promoted component with copy-first parity**
|
||||
- Copy the current candidate source into the final
|
||||
`packages/ui/system/src/components/<component-dir>/index.tsx` component.
|
||||
- Copy dependent presentational helpers and classify any third-party
|
||||
wrappers before changing behavior. Reuse or promote base primitives for
|
||||
reusable library wrappers instead of rebuilding them in the business file.
|
||||
- Route icons through `@tutti-os/ui-system/icons`: reuse existing exports or
|
||||
promote source-derived icons into the package icon layer with metadata
|
||||
before using them in the component or storyboard.
|
||||
- Keep the real table layout, status cells, action affordances, icon
|
||||
placement, empty state, nested display helpers, and disabled/error branches.
|
||||
- Replace host behavior with props, labels, callbacks, and caller-owned
|
||||
slots: i18n lookup, queue state, confirmation dialog decisions, daemon
|
||||
calls, and install orchestration stay outside the component.
|
||||
- Only after storyboard parity is visible, simplify the copied API toward
|
||||
durable `items`, `labels`, `actions`, explicit variants, and slots.
|
||||
- Make only package integration edits: final exported prop types, imports,
|
||||
class cleanup, and package-local helpers.
|
||||
- Export it from stable barrels.
|
||||
- Add metadata with `layer: "business"` and storyboard coverage for the
|
||||
accepted states.
|
||||
- Replace the original app UI with `@tutti-os/ui-system` imports while
|
||||
leaving host-owned behavior in the caller.
|
||||
5. **Validate and report**
|
||||
- Review the finished implementation through the storyboard states and the
|
||||
migrated consumer surface.
|
||||
- Start an independent design-foundation review subagent. Give it the
|
||||
promoted files, original source usage, selected state matrix, storyboard
|
||||
entry, metadata entry, and `ui-system.md`.
|
||||
- Include the API shape review in the handoff: accepted booleans, variants,
|
||||
slots or children, explicit variants, provider state if any, and
|
||||
host-owned behavior kept in the caller.
|
||||
- Resolve any subagent-reported design drift before reporting completion.
|
||||
- Run the promotion review gate: Frictionless task path and action hierarchy,
|
||||
Quality Craft visual parity and token/state coverage, and Trustworthy
|
||||
labels, recovery, policy, and provenance behavior.
|
||||
- Run metadata, boundary, storyboard, and relevant package checks.
|
||||
- Report the state matrix summary, final boundary, promotion review result,
|
||||
subagent design-foundation result, validation results, and uncovered
|
||||
risks.
|
||||
|
||||
## Implementation
|
||||
|
||||
1. Copy the existing business component structure into `packages/ui/system`
|
||||
before abstracting it.
|
||||
2. Keep all host-owned behavior in the caller by replacing it with props,
|
||||
labels, callbacks, or caller-owned slots.
|
||||
3. Preserve the source visual and interaction shape until storyboard parity is
|
||||
visible.
|
||||
4. Standardize the API incrementally. Do not add new mode booleans or
|
||||
host-owned state while moving the candidate UI into the shared package.
|
||||
5. Add stable exports and metadata with `layer: "business"`.
|
||||
6. Add storyboard examples for normal, empty, disabled, loading, and error-like
|
||||
states when those states exist in the public contract.
|
||||
7. Migrate callers by replacing only the visual surface.
|
||||
8. Run the promotion review gate from
|
||||
`ui-system.md` against the promoted component
|
||||
and migrated consumer.
|
||||
9. Start the design-foundation review subagent and resolve any reported drift.
|
||||
|
||||
## Validation
|
||||
|
||||
Run the relevant checks:
|
||||
|
||||
```bash
|
||||
node tools/scripts/check-ui-metadata.mjs
|
||||
pnpm check:ui-boundaries
|
||||
pnpm --filter @tutti-os/ui-storyboard typecheck
|
||||
pnpm --filter @tutti-os/ui-system typecheck
|
||||
```
|
||||
|
||||
If a consumer was migrated, also run that consumer's typecheck or build.
|
||||
|
||||
Report:
|
||||
|
||||
- state matrix summary
|
||||
- component boundary decision
|
||||
- API composition decision and any rejected boolean or state combinations
|
||||
- promotion review result with Frictionless / Quality Craft / Trustworthy
|
||||
pillar status and blocking/major/minor issues
|
||||
- design-foundation subagent result
|
||||
- validation commands and results
|
||||
- remaining risks or uncovered states
|
||||
|
||||
Do not report full design-foundation compliance unless the subagent review ran
|
||||
and found no unresolved drift. If subagents are unavailable, report the
|
||||
verification as blocked.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Use Existing Component
|
||||
|
||||
Use this reference when replacing local UI with `@tutti-os/ui-system` or when
|
||||
answering what shared components exist.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Read component metadata first by `id`, `name`, `export`, `layer`, and
|
||||
`useCases`.
|
||||
2. Prefer an existing component before creating, extracting, or promoting a new
|
||||
one.
|
||||
3. Read the selected component source and props type before using it.
|
||||
4. Import through stable public entrypoints only.
|
||||
5. Replace only the visual surface.
|
||||
|
||||
## Caller-Owned Work
|
||||
|
||||
Keep these in the caller:
|
||||
|
||||
- host state and derived business state
|
||||
- data loading, cache mutation, and persistence
|
||||
- routing, daemon calls, Electron calls, and filesystem access
|
||||
- i18n key lookup and user-visible product copy selection
|
||||
- confirmation dialogs, queueing, install or uninstall flows, and navigation
|
||||
|
||||
The UI-system component should receive resolved props, labels, callbacks,
|
||||
status values, icons, and children.
|
||||
|
||||
## Validation
|
||||
|
||||
Run the smallest relevant checks:
|
||||
|
||||
```bash
|
||||
pnpm check:ui-boundaries
|
||||
```
|
||||
|
||||
If the consumer code changed, also run the relevant consumer typecheck or build.
|
||||
@@ -0,0 +1,658 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { constants } from "node:fs";
|
||||
import { access, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { tmpdir } from "node:os";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
|
||||
const sourcePackageRoot = resolve(scriptDirectory, "..", "..", "..");
|
||||
const cwdRequire = createRequire(join(process.cwd(), "package.json"));
|
||||
const packageRoot = await resolvePackageRoot(sourcePackageRoot);
|
||||
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
|
||||
if (options.help) {
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (!options.componentId) {
|
||||
throw new Error("--component-id is required");
|
||||
}
|
||||
|
||||
if (!options.componentName) {
|
||||
throw new Error("--component-name is required");
|
||||
}
|
||||
|
||||
if (!options.stateMatrixPath) {
|
||||
throw new Error("--state-matrix is required");
|
||||
}
|
||||
|
||||
const componentId = normalizeComponentId(options.componentId);
|
||||
const componentName = normalizeComponentName(options.componentName);
|
||||
const serverUrl = options.serverUrl || "http://127.0.0.1:4100";
|
||||
const outputDirectory = resolve(
|
||||
options.outDir || join(tmpdir(), `tutti-ui-system-preview-${componentId}`)
|
||||
);
|
||||
const stateMatrix = normalizeStateMatrix(
|
||||
JSON.parse(await readFile(resolve(options.stateMatrixPath), "utf8"))
|
||||
);
|
||||
|
||||
await assertReadableDirectory(packageRoot);
|
||||
|
||||
if (await pathExists(outputDirectory)) {
|
||||
if (!options.force) {
|
||||
throw new Error(
|
||||
`Preview directory already exists: ${outputDirectory}\n` +
|
||||
"Run with --force to replace it."
|
||||
);
|
||||
}
|
||||
|
||||
await rm(outputDirectory, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
await mkdir(join(outputDirectory, "src"), { recursive: true });
|
||||
|
||||
const files = new Map([
|
||||
["package.json", packageJson(componentId)],
|
||||
["index.html", indexHtml(componentName)],
|
||||
["vite.config.ts", viteConfig(serverUrl)],
|
||||
["tsconfig.json", tsconfigJson()],
|
||||
["src/main.tsx", mainTsx()],
|
||||
["src/Preview.tsx", previewTsx(componentName)],
|
||||
["src/stateMatrix.ts", stateMatrixTs(stateMatrix)],
|
||||
["src/style.css", styleCss()]
|
||||
]);
|
||||
|
||||
await Promise.all(
|
||||
Array.from(files, ([relativePath, content]) =>
|
||||
writeFile(join(outputDirectory, relativePath), content)
|
||||
)
|
||||
);
|
||||
|
||||
console.log(`Created preview scaffold at ${outputDirectory}`);
|
||||
console.log("");
|
||||
console.log("Run:");
|
||||
console.log(` cd ${outputDirectory}`);
|
||||
console.log(" pnpm install");
|
||||
console.log(" pnpm dev -- --host 127.0.0.1");
|
||||
console.log("");
|
||||
console.log("Before reviewing, make sure the UI-system dev server is running:");
|
||||
console.log(" pnpm --filter @tutti-os/ui-system dev:server");
|
||||
console.log(` curl ${serverUrl}/health`);
|
||||
|
||||
function parseArgs(args) {
|
||||
const parsed = {
|
||||
componentId: "",
|
||||
componentName: "",
|
||||
force: false,
|
||||
help: false,
|
||||
outDir: "",
|
||||
serverUrl: "",
|
||||
stateMatrixPath: ""
|
||||
};
|
||||
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index];
|
||||
|
||||
if (arg === "--help" || arg === "-h") {
|
||||
parsed.help = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--force") {
|
||||
parsed.force = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--component-id") {
|
||||
parsed.componentId = requireValue(args, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--component-name") {
|
||||
parsed.componentName = requireValue(args, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--state-matrix") {
|
||||
parsed.stateMatrixPath = requireValue(args, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--out-dir") {
|
||||
parsed.outDir = requireValue(args, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg === "--server-url") {
|
||||
parsed.serverUrl = requireValue(args, index, arg);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown option: ${arg}`);
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function requireValue(args, index, optionName) {
|
||||
const value = args[index + 1];
|
||||
|
||||
if (!value) {
|
||||
throw new Error(`${optionName} requires a value`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`Usage: create-business-preview.mjs --component-id <id> --component-name <Name> --state-matrix <path> [options]
|
||||
|
||||
Generates a temporary Vite React preview scaffold for a proposed
|
||||
@tutti-os/ui-system business component promotion.
|
||||
|
||||
Options:
|
||||
--component-id <id> Stable kebab-case component id.
|
||||
--component-name <Name> Proposed React export name.
|
||||
--state-matrix <path> JSON file with an array of states or { "states": [] }.
|
||||
--out-dir <path> Output directory. Defaults to $TMPDIR/tutti-ui-system-preview-<id>.
|
||||
--server-url <url> UI-system dev server URL. Defaults to http://127.0.0.1:4100.
|
||||
--force Replace an existing output directory.
|
||||
-h, --help Show this help message.
|
||||
|
||||
State matrix item fields:
|
||||
name, evidence, propsData, hostOwnedBehavior, includedInContract,
|
||||
description, boundaryNotes`);
|
||||
}
|
||||
|
||||
function normalizeComponentId(value) {
|
||||
const normalized = value
|
||||
.trim()
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1-$2")
|
||||
.replace(/[^a-zA-Z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.toLowerCase();
|
||||
|
||||
if (!normalized) {
|
||||
throw new Error(
|
||||
"Component id must contain at least one alphanumeric character"
|
||||
);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeComponentName(value) {
|
||||
const normalized = value.trim();
|
||||
|
||||
if (!/^[A-Z][A-Za-z0-9]*$/.test(normalized)) {
|
||||
throw new Error(
|
||||
"--component-name must be a PascalCase React component name"
|
||||
);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeStateMatrix(value) {
|
||||
const states = Array.isArray(value) ? value : value?.states;
|
||||
|
||||
if (!Array.isArray(states) || states.length === 0) {
|
||||
throw new Error(
|
||||
'State matrix must be a non-empty array or { "states": [] }'
|
||||
);
|
||||
}
|
||||
|
||||
return states.map((state, index) => {
|
||||
if (state === null || typeof state !== "object" || Array.isArray(state)) {
|
||||
throw new Error(`State matrix item ${index + 1} must be an object`);
|
||||
}
|
||||
|
||||
const name = stringField(state, "name", `state-${index + 1}`);
|
||||
|
||||
return {
|
||||
name,
|
||||
evidence: stringListField(state, "evidence"),
|
||||
propsData: stringListField(state, "propsData"),
|
||||
hostOwnedBehavior: stringListField(state, "hostOwnedBehavior"),
|
||||
includedInContract: Boolean(state.includedInContract),
|
||||
description: stringField(state, "description", ""),
|
||||
boundaryNotes: stringListField(state, "boundaryNotes")
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function stringField(object, field, fallback) {
|
||||
const value = object[field];
|
||||
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function stringListField(object, field) {
|
||||
const value = object[field];
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => String(item));
|
||||
}
|
||||
|
||||
if (typeof value === "string" && value.length > 0) {
|
||||
return [value];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
async function assertReadableDirectory(path) {
|
||||
await access(path, constants.R_OK);
|
||||
const pathStats = await stat(path);
|
||||
|
||||
if (!pathStats.isDirectory()) {
|
||||
throw new Error(`Expected directory: ${path}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function resolvePackageRoot(sourceCandidate) {
|
||||
if (await isUISystemPackageRoot(sourceCandidate)) {
|
||||
return sourceCandidate;
|
||||
}
|
||||
|
||||
let entrypoint;
|
||||
|
||||
try {
|
||||
entrypoint = cwdRequire.resolve("@tutti-os/ui-system");
|
||||
} catch {
|
||||
throw new Error(
|
||||
"Unable to resolve @tutti-os/ui-system. Run this from a Tutti checkout " +
|
||||
"or a project with @tutti-os/ui-system installed."
|
||||
);
|
||||
}
|
||||
|
||||
const resolvedRoot = await findPackageRoot(dirname(entrypoint));
|
||||
|
||||
if (resolvedRoot === null) {
|
||||
throw new Error(
|
||||
`Unable to find @tutti-os/ui-system package root from ${entrypoint}`
|
||||
);
|
||||
}
|
||||
|
||||
return resolvedRoot;
|
||||
}
|
||||
|
||||
async function isUISystemPackageRoot(candidate) {
|
||||
try {
|
||||
const packageJson = JSON.parse(
|
||||
await readFile(join(candidate, "package.json"), "utf8")
|
||||
);
|
||||
|
||||
return packageJson.name === "@tutti-os/ui-system";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function findPackageRoot(startDirectory) {
|
||||
let current = startDirectory;
|
||||
|
||||
while (true) {
|
||||
if (await isUISystemPackageRoot(current)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
const parent = dirname(current);
|
||||
|
||||
if (parent === current) {
|
||||
return null;
|
||||
}
|
||||
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
|
||||
async function pathExists(path) {
|
||||
try {
|
||||
await access(path, constants.F_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function packageJson(componentId) {
|
||||
return `${JSON.stringify(
|
||||
{
|
||||
name: `tutti-ui-system-preview-${componentId}`,
|
||||
private: true,
|
||||
type: "module",
|
||||
scripts: {
|
||||
dev: "vite",
|
||||
typecheck: "tsc --noEmit"
|
||||
},
|
||||
dependencies: {
|
||||
"@tutti-os/ui-system": `file:${packageRoot}`,
|
||||
"@vitejs/plugin-react": "^5.1.1",
|
||||
vite: "^6.4.2",
|
||||
typescript: "^5.8.3",
|
||||
react: "^19.1.0",
|
||||
"react-dom": "^19.1.0"
|
||||
},
|
||||
devDependencies: {
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5"
|
||||
}
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}\n`;
|
||||
}
|
||||
|
||||
function indexHtml(componentName) {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>${componentName} Promotion Preview</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
function viteConfig(serverUrl) {
|
||||
return `import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vite";
|
||||
import { tuttiUISystemDev } from "@tutti-os/ui-system/dev-vite";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
tuttiUISystemDev({ serverUrl: ${JSON.stringify(serverUrl)} }),
|
||||
react()
|
||||
],
|
||||
server: {
|
||||
host: "127.0.0.1"
|
||||
}
|
||||
});
|
||||
`;
|
||||
}
|
||||
|
||||
function tsconfigJson() {
|
||||
return `${JSON.stringify(
|
||||
{
|
||||
compilerOptions: {
|
||||
target: "ES2022",
|
||||
useDefineForClassFields: true,
|
||||
lib: ["DOM", "DOM.Iterable", "ES2022"],
|
||||
allowJs: false,
|
||||
skipLibCheck: true,
|
||||
esModuleInterop: true,
|
||||
allowSyntheticDefaultImports: true,
|
||||
strict: true,
|
||||
forceConsistentCasingInFileNames: true,
|
||||
module: "ESNext",
|
||||
moduleResolution: "Bundler",
|
||||
resolveJsonModule: true,
|
||||
isolatedModules: true,
|
||||
noEmit: true,
|
||||
jsx: "react-jsx"
|
||||
},
|
||||
include: ["src", "vite.config.ts"]
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}\n`;
|
||||
}
|
||||
|
||||
function mainTsx() {
|
||||
return `import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
import { Preview } from "./Preview";
|
||||
import "./style.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<Preview />
|
||||
</StrictMode>
|
||||
);
|
||||
`;
|
||||
}
|
||||
|
||||
function previewTsx(componentName) {
|
||||
return `import "@tutti-os/ui-system/styles.css";
|
||||
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle
|
||||
} from "@tutti-os/ui-system/components";
|
||||
|
||||
import { stateMatrix, type PreviewState } from "./stateMatrix";
|
||||
|
||||
type ${componentName}DraftProps = {
|
||||
state: PreviewState;
|
||||
onPrimaryAction?: (stateName: string) => void;
|
||||
};
|
||||
|
||||
function ${componentName}Draft({
|
||||
state,
|
||||
onPrimaryAction = () => undefined
|
||||
}: ${componentName}DraftProps) {
|
||||
return (
|
||||
<Card className="preview-draft">
|
||||
<CardHeader>
|
||||
<div className="preview-draft-header">
|
||||
<div>
|
||||
<CardTitle>{state.name}</CardTitle>
|
||||
<CardDescription>
|
||||
{state.description || "Draft visual surface for review."}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Badge variant={state.includedInContract ? "default" : "secondary"}>
|
||||
{state.includedInContract ? "in contract" : "excluded"}
|
||||
</Badge>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="preview-draft-body">
|
||||
<dl>
|
||||
<BoundaryRow label="Evidence" values={state.evidence} />
|
||||
<BoundaryRow label="Props/Data" values={state.propsData} />
|
||||
<BoundaryRow
|
||||
label="Host owned"
|
||||
values={state.hostOwnedBehavior}
|
||||
/>
|
||||
<BoundaryRow label="Boundary notes" values={state.boundaryNotes} />
|
||||
</dl>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => onPrimaryAction(state.name)}
|
||||
>
|
||||
Draft callback
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function BoundaryRow({
|
||||
label,
|
||||
values
|
||||
}: {
|
||||
label: string;
|
||||
values: string[];
|
||||
}) {
|
||||
return (
|
||||
<div className="boundary-row">
|
||||
<dt>{label}</dt>
|
||||
<dd>{values.length > 0 ? values.join("; ") : "None recorded"}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Preview() {
|
||||
return (
|
||||
<main className="preview-shell">
|
||||
<header className="preview-header">
|
||||
<p className="preview-kicker">Tutti UI-system business promotion</p>
|
||||
<h1>${componentName} Preview</h1>
|
||||
<p>
|
||||
Review the state coverage, visual behavior, props boundary, and
|
||||
host-owned behavior before promoting this component into
|
||||
<code>@tutti-os/ui-system</code>.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<section className="preview-grid">
|
||||
{stateMatrix.map((state) => (
|
||||
<${componentName}Draft
|
||||
key={state.name}
|
||||
state={state}
|
||||
onPrimaryAction={(stateName) => {
|
||||
console.log("Draft callback fired for", stateName);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
function stateMatrixTs(stateMatrix) {
|
||||
return `export type PreviewState = {
|
||||
name: string;
|
||||
evidence: string[];
|
||||
propsData: string[];
|
||||
hostOwnedBehavior: string[];
|
||||
includedInContract: boolean;
|
||||
description: string;
|
||||
boundaryNotes: string[];
|
||||
};
|
||||
|
||||
export const stateMatrix = ${JSON.stringify(stateMatrix, null, 2)} satisfies PreviewState[];
|
||||
`;
|
||||
}
|
||||
|
||||
function styleCss() {
|
||||
return `@source "../.tutti-ui-system-dev";
|
||||
@source "../node_modules/@tutti-os/ui-system/dist";
|
||||
|
||||
:root {
|
||||
color: hsl(var(--foreground));
|
||||
background: hsl(var(--background));
|
||||
font-family:
|
||||
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-width: 320px;
|
||||
}
|
||||
|
||||
code {
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: 4px;
|
||||
background: hsl(var(--muted));
|
||||
padding: 0.1rem 0.3rem;
|
||||
}
|
||||
|
||||
.preview-shell {
|
||||
margin: 0 auto;
|
||||
max-width: 1180px;
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
.preview-header {
|
||||
max-width: 760px;
|
||||
padding-bottom: 24px;
|
||||
}
|
||||
|
||||
.preview-header h1 {
|
||||
margin: 0;
|
||||
font-size: 32px;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.preview-header p {
|
||||
color: hsl(var(--muted-foreground));
|
||||
}
|
||||
|
||||
.preview-kicker {
|
||||
margin: 0 0 8px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.preview-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.preview-draft {
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.preview-draft-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.preview-draft-body {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.boundary-row {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
padding: 10px 0;
|
||||
border-top: 1px solid hsl(var(--border));
|
||||
}
|
||||
|
||||
.boundary-row:first-child {
|
||||
border-top: 0;
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.boundary-row dt {
|
||||
color: hsl(var(--muted-foreground));
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.boundary-row dd {
|
||||
margin: 0;
|
||||
color: hsl(var(--foreground));
|
||||
font-size: 13px;
|
||||
}
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "radix-nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/styles/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"aliases": {
|
||||
"components": "#components",
|
||||
"icons": "#icons",
|
||||
"utils": "#lib/utils",
|
||||
"ui": "#components",
|
||||
"lib": "#lib"
|
||||
},
|
||||
"registries": {
|
||||
"@diceui": "https://diceui.com/r/{style}/{name}.json"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
{
|
||||
"name": "@tutti-os/ui-system",
|
||||
"version": "0.1.0",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"types": "./src/index.ts",
|
||||
"sideEffects": [
|
||||
"./src/styles/*.css",
|
||||
"./dist/styles/*.css",
|
||||
"./dist/styles.css"
|
||||
],
|
||||
"bin": {
|
||||
"tutti-ui-system-install-skill": "./agent/install-skill.mjs"
|
||||
},
|
||||
"imports": {
|
||||
"#components/*": "./src/components/*/index.tsx",
|
||||
"#icons/*": "./src/icons/*.tsx",
|
||||
"#lib/*": "./src/lib/*.ts"
|
||||
},
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./components": "./src/components/index.ts",
|
||||
"./date-format": "./src/lib/date-format.ts",
|
||||
"./dev-vite": "./src/dev-vite.ts",
|
||||
"./icons": "./src/icons/index.ts",
|
||||
"./metadata": "./src/metadata/index.ts",
|
||||
"./native": "./src/native/index.ts",
|
||||
"./native.css": {
|
||||
"types": "./src/styles/native.css.d.ts",
|
||||
"default": "./src/styles/native.css"
|
||||
},
|
||||
"./styles.css": "./src/styles/index.css",
|
||||
"./utils": "./src/lib/utils.ts"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"agent",
|
||||
"AGENTS.md",
|
||||
"NOTICE",
|
||||
"ui-system.md",
|
||||
"README.md"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tutti-os/tutti.git",
|
||||
"directory": "packages/ui/system"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsup --config tsup.config.ts && node ../../../tools/scripts/copy-package-assets.mjs src/styles dist/styles src/metadata/components.json dist/metadata/components.json src/metadata/components.schema.json dist/metadata/components.schema.json",
|
||||
"dev:server": "tsx src/dev-server/server.ts",
|
||||
"test": "vitest run",
|
||||
"typecheck": "node ../../../tools/scripts/run-tsgo-typecheck.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/modifiers": "^9.0.0",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/lexend": "^5.2.11",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"radix-ui": "^1.4.2",
|
||||
"react-resizable-panels": "^4.11.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.3.0",
|
||||
"tw-animate-css": "^1.3.1",
|
||||
"vaul": "^1.1.2",
|
||||
"ws": "^8.20.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@tutti-os/config-tsconfig": "workspace:*",
|
||||
"@types/react": "^19.1.6",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@types/ws": "^8.18.1",
|
||||
"react-native": "0.86.0",
|
||||
"jsdom": "^27.2.0",
|
||||
"tsx": "^4.22.3",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^6.4.2",
|
||||
"vitest": "^4.0.13"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-native": ">=0.86 <0.87"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"react-native": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"tutti": {
|
||||
"tailwindSourceRoot": "src"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./components": {
|
||||
"types": "./dist/components/index.d.ts",
|
||||
"import": "./dist/components/index.js"
|
||||
},
|
||||
"./date-format": {
|
||||
"types": "./dist/date-format.d.ts",
|
||||
"import": "./dist/date-format.js"
|
||||
},
|
||||
"./dev-vite": {
|
||||
"types": "./dist/dev-vite.d.ts",
|
||||
"import": "./dist/dev-vite.js"
|
||||
},
|
||||
"./icons": {
|
||||
"types": "./dist/icons/index.d.ts",
|
||||
"import": "./dist/icons/index.js"
|
||||
},
|
||||
"./metadata": {
|
||||
"types": "./dist/metadata/index.d.ts",
|
||||
"import": "./dist/metadata/index.js"
|
||||
},
|
||||
"./native": {
|
||||
"types": "./dist/native.d.ts",
|
||||
"import": "./dist/native.js"
|
||||
},
|
||||
"./native.css": {
|
||||
"types": "./dist/styles/native.css.d.ts",
|
||||
"default": "./dist/styles/native.css"
|
||||
},
|
||||
"./styles.css": "./dist/styles/index.css",
|
||||
"./utils": {
|
||||
"types": "./dist/utils.d.ts",
|
||||
"import": "./dist/utils.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"components": [
|
||||
"./dist/components/index.d.ts"
|
||||
],
|
||||
"date-format": [
|
||||
"./dist/date-format.d.ts"
|
||||
],
|
||||
"icons": [
|
||||
"./dist/icons/index.d.ts"
|
||||
],
|
||||
"metadata": [
|
||||
"./dist/metadata/index.d.ts"
|
||||
],
|
||||
"native": [
|
||||
"./dist/native.d.ts"
|
||||
],
|
||||
"utils": [
|
||||
"./dist/utils.d.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
# Avatar Delivery Contract
|
||||
|
||||
## Scope
|
||||
|
||||
This file applies to the shared `Avatar` primitive in this directory. `Avatar`
|
||||
is consumed by Tutti and TSH through the stable
|
||||
`@tutti-os/ui-system/components` entrypoint.
|
||||
|
||||
## Usage
|
||||
|
||||
Callers provide a stable accessible `label` and a directly consumable image
|
||||
URL:
|
||||
|
||||
```tsx
|
||||
<Avatar label={user.displayName} size={40} src={user.avatarUrl} />
|
||||
```
|
||||
|
||||
By default, `Avatar` requests `src` unchanged and uses
|
||||
`referrerPolicy="no-referrer"`. Callers may override the referrer policy through
|
||||
`imageProps` when the source contract requires it. Pass `transform` when the
|
||||
caller knows that the URL supports image-delivery query parameters:
|
||||
|
||||
```tsx
|
||||
<Avatar
|
||||
label={user.displayName}
|
||||
size={40}
|
||||
src={user.avatarUrl}
|
||||
transform={user.avatarClientTransform}
|
||||
/>
|
||||
```
|
||||
|
||||
When `transform` is true, `Avatar`:
|
||||
|
||||
- measures the rendered avatar box
|
||||
- requests twice its width and height
|
||||
- rounds each requested dimension up to
|
||||
`32, 48, 64, 96, 128, 192, 256, 384, or 512`
|
||||
- sets `format=webp` and `fit=inside`
|
||||
- appends the delivery parameters without rewriting, reordering, or removing
|
||||
the source query string
|
||||
|
||||
When `transform` is false or omitted, no delivery parameters are added.
|
||||
`data:`, `blob:`, `file:`, relative, and other non-HTTP(S) sources are left
|
||||
unchanged even when `transform` is true.
|
||||
|
||||
## URL Contract
|
||||
|
||||
- `src` must already be directly consumable by the browser.
|
||||
- Production avatar URLs must point to the CloudFront image-delivery domain.
|
||||
- The URL must identify the original image and allow the browser to append the
|
||||
`width`, `height`, `format`, and `fit` query parameters.
|
||||
- Callers must pass `transform` only when their resource descriptor or delivery
|
||||
metadata declares client-side transformation support.
|
||||
- Callers must never pass a bucket, object key, storage credential, or
|
||||
business-specific resource locator to this component.
|
||||
- Do not persist the generated transformed URL. Persist only the resource
|
||||
identity or original delivery URL owned by the service contract.
|
||||
- Treat `width`, `height`, `format`, and `fit` as reserved delivery parameters.
|
||||
Change them only together with the Image Handler Lambda validation and the
|
||||
CloudFront cache-query allowlist.
|
||||
|
||||
If transformed delivery fails, `Avatar` retries the unmodified `src` once.
|
||||
Pass the independently consumable original URL as `fallbackSrc` when the
|
||||
delivery service supplies one:
|
||||
|
||||
```tsx
|
||||
<Avatar
|
||||
fallbackSrc={user.avatarFallbackUrl}
|
||||
label={user.displayName}
|
||||
src={user.avatarUrl}
|
||||
/>
|
||||
```
|
||||
|
||||
When the unmodified capability also fails, `Avatar` tries `fallbackSrc`, then
|
||||
uses the requested initial or empty fallback.
|
||||
|
||||
## Component Boundary
|
||||
|
||||
Keep identity lookup, API calls, authorization, signing, storage selection, and
|
||||
resource lifecycle management in the host or service. This primitive owns only
|
||||
render sizing, URL derivation, image loading, and visual fallback.
|
||||
|
||||
Do not add:
|
||||
|
||||
- calls to tsh-server, account, daemon, Electron, router, or application stores
|
||||
- bucket or object-key parsing
|
||||
- user-specific cache or persistence
|
||||
- business copy or identity-resolution rules
|
||||
|
||||
## Required Tests
|
||||
|
||||
When changing this component, cover:
|
||||
|
||||
- 2x sizing and bucket selection
|
||||
- WebP and `fit=inside` query parameters
|
||||
- preservation of unrelated query parameters
|
||||
- rendered-size updates through `ResizeObserver`
|
||||
- default original mode and non-HTTP(S) sources
|
||||
- transformed-image failure, original retry, and final fallback
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm --filter @tutti-os/ui-system test -- avatar
|
||||
pnpm --filter @tutti-os/ui-system typecheck
|
||||
pnpm check:ui-boundaries
|
||||
```
|
||||
@@ -0,0 +1,457 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Avatar } from "./avatar";
|
||||
|
||||
class MockImage extends EventTarget {
|
||||
complete = false;
|
||||
naturalWidth = 0;
|
||||
private source = "";
|
||||
|
||||
get src(): string {
|
||||
return this.source;
|
||||
}
|
||||
|
||||
set src(value: string) {
|
||||
if (value !== this.source) {
|
||||
this.complete = false;
|
||||
this.naturalWidth = 0;
|
||||
this.source = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let preloadedImages: MockImage[] = [];
|
||||
let resizeObservers: MockResizeObserver[] = [];
|
||||
|
||||
class MockResizeObserver {
|
||||
constructor(private callback: ResizeObserverCallback) {
|
||||
resizeObservers.push(this);
|
||||
}
|
||||
|
||||
disconnect(): void {}
|
||||
|
||||
observe(): void {}
|
||||
|
||||
resize(width: number, height: number): void {
|
||||
this.callback(
|
||||
[
|
||||
{
|
||||
contentRect: { height, width }
|
||||
} as ResizeObserverEntry
|
||||
],
|
||||
this as unknown as ResizeObserver
|
||||
);
|
||||
}
|
||||
|
||||
unobserve(): void {}
|
||||
}
|
||||
|
||||
function expectDeliveryUrl(
|
||||
source: string,
|
||||
expected: {
|
||||
format?: string;
|
||||
height: string;
|
||||
width: string;
|
||||
}
|
||||
): void {
|
||||
const url = new URL(source);
|
||||
expect(url.searchParams.get("width")).toBe(expected.width);
|
||||
expect(url.searchParams.get("height")).toBe(expected.height);
|
||||
expect(url.searchParams.get("format")).toBe(expected.format ?? "webp");
|
||||
expect(url.searchParams.get("fit")).toBe("inside");
|
||||
}
|
||||
|
||||
function finishPreload(status: "error" | "loaded"): void {
|
||||
const image = preloadedImages.at(-1);
|
||||
if (!image) {
|
||||
throw new Error("Expected Radix Avatar to create an image preloader");
|
||||
}
|
||||
|
||||
if (status === "loaded") {
|
||||
image.complete = true;
|
||||
image.naturalWidth = 40;
|
||||
}
|
||||
|
||||
act(() => {
|
||||
image.dispatchEvent(new Event(status === "loaded" ? "load" : "error"));
|
||||
});
|
||||
}
|
||||
|
||||
describe("Avatar", () => {
|
||||
beforeEach(() => {
|
||||
preloadedImages = [];
|
||||
resizeObservers = [];
|
||||
vi.stubGlobal(
|
||||
"Image",
|
||||
class extends MockImage {
|
||||
constructor() {
|
||||
super();
|
||||
preloadedImages.push(this);
|
||||
}
|
||||
}
|
||||
);
|
||||
vi.stubGlobal("ResizeObserver", MockResizeObserver);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("renders a decorative image and forwards root and image props", () => {
|
||||
const onLoad = vi.fn();
|
||||
|
||||
render(
|
||||
<Avatar
|
||||
aria-label="Jun Sun"
|
||||
data-testid="avatar"
|
||||
imageClassName="object-contain"
|
||||
imageProps={{ "data-testid": "avatar-image", onLoad }}
|
||||
label="Jun Sun"
|
||||
src="https://example.test/avatar.png"
|
||||
surfaceClassName="bg-muted"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"loading"
|
||||
);
|
||||
expect(screen.queryByTestId("avatar-image")).not.toBeInTheDocument();
|
||||
|
||||
finishPreload("loaded");
|
||||
const image = screen.getByTestId("avatar-image");
|
||||
fireEvent.load(image);
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"image"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"aria-label",
|
||||
"Jun Sun"
|
||||
);
|
||||
expect(image).toHaveAttribute("alt", "");
|
||||
expect(image).toHaveClass("object-contain");
|
||||
expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
|
||||
expect(onLoad).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("allows callers to override the default referrer policy", () => {
|
||||
render(
|
||||
<Avatar
|
||||
imageProps={{
|
||||
"data-testid": "avatar-image",
|
||||
referrerPolicy: "origin"
|
||||
}}
|
||||
label="Jun Sun"
|
||||
src="https://example.test/avatar.png"
|
||||
/>
|
||||
);
|
||||
|
||||
finishPreload("loaded");
|
||||
|
||||
expect(screen.getByTestId("avatar-image")).toHaveAttribute(
|
||||
"referrerpolicy",
|
||||
"origin"
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the requested initial when an image fails", () => {
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
fallbackColor="rgb(10, 20, 30)"
|
||||
imageProps={{ "data-testid": "avatar-image" }}
|
||||
initial="j"
|
||||
label="Jun Sun"
|
||||
size="sm"
|
||||
src="https://example.test/avatar.png"
|
||||
/>
|
||||
);
|
||||
|
||||
finishPreload("error");
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"initial"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("J");
|
||||
expect(
|
||||
screen.getByTestId("avatar").querySelector('[data-slot="avatar-surface"]')
|
||||
).toHaveStyle({ backgroundColor: "rgb(10, 20, 30)" });
|
||||
});
|
||||
|
||||
it("does not show the initial while an image is loading", () => {
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
label="Jun Sun"
|
||||
src="https://example.test/avatar.png"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"loading"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).not.toHaveTextContent("J");
|
||||
expect(
|
||||
screen.getByTestId("avatar").querySelector('[data-slot="avatar-surface"]')
|
||||
).toHaveClass("bg-transparent");
|
||||
|
||||
finishPreload("error");
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("J");
|
||||
});
|
||||
|
||||
it("falls back when the rendered image fails after preloading", () => {
|
||||
const onError = vi.fn();
|
||||
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
imageProps={{ "data-testid": "avatar-image", onError }}
|
||||
label="Jun Sun"
|
||||
src="https://example.test/avatar.png"
|
||||
/>
|
||||
);
|
||||
|
||||
finishPreload("loaded");
|
||||
fireEvent.error(screen.getByTestId("avatar-image"));
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"initial"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("J");
|
||||
expect(screen.queryByTestId("avatar-image")).not.toBeInTheDocument();
|
||||
expect(onError).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("uses an independent fallback after transformed and original delivery fail", () => {
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
fallbackSrc="https://original.example.test/avatar.png"
|
||||
label="Jun Sun"
|
||||
src="https://images.example.test/capability?Policy=signed"
|
||||
transform
|
||||
/>
|
||||
);
|
||||
|
||||
expectDeliveryUrl(preloadedImages.at(-1)?.src ?? "", {
|
||||
height: "64",
|
||||
width: "64"
|
||||
});
|
||||
finishPreload("error");
|
||||
expect(preloadedImages.at(-1)?.src).toBe(
|
||||
"https://images.example.test/capability?Policy=signed"
|
||||
);
|
||||
finishPreload("error");
|
||||
expect(preloadedImages.at(-1)?.src).toBe(
|
||||
"https://original.example.test/avatar.png"
|
||||
);
|
||||
finishPreload("loaded");
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"image"
|
||||
);
|
||||
});
|
||||
|
||||
it("does not request the fallback image when no source was provided", () => {
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
fallbackSrc="https://fallback.example.test/avatar.png"
|
||||
initial="J"
|
||||
label="Jun Sun"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(preloadedImages.map((image) => image.src)).not.toContain(
|
||||
"https://fallback.example.test/avatar.png"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"initial"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("J");
|
||||
});
|
||||
|
||||
it("supports an intentionally empty fallback and numeric sizing", () => {
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
fallback="empty"
|
||||
fallbackColor="red"
|
||||
label="Private profile"
|
||||
size={18}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"empty"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveStyle({
|
||||
height: "18px",
|
||||
width: "18px"
|
||||
});
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("");
|
||||
});
|
||||
|
||||
it("renders a loading surface without an image or initial", () => {
|
||||
render(
|
||||
<Avatar
|
||||
data-testid="avatar"
|
||||
label="Jun Sun"
|
||||
loading
|
||||
src="https://example.test/avatar.png"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("avatar")).toHaveAttribute(
|
||||
"data-avatar-state",
|
||||
"loading"
|
||||
);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("");
|
||||
expect(screen.queryByRole("img")).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByTestId("avatar").querySelector('[data-slot="avatar-surface"]')
|
||||
).toHaveClass("animate-pulse", "motion-reduce:animate-none");
|
||||
});
|
||||
|
||||
it("retries a failed URL after the source changes away and back", () => {
|
||||
const { rerender } = render(
|
||||
<Avatar
|
||||
imageProps={{ "data-testid": "avatar-image" }}
|
||||
label="Jun Sun"
|
||||
src="https://example.test/a.png"
|
||||
/>
|
||||
);
|
||||
|
||||
finishPreload("error");
|
||||
rerender(
|
||||
<Avatar
|
||||
imageProps={{ "data-testid": "avatar-image" }}
|
||||
label="Jun Sun"
|
||||
src="https://example.test/b.png"
|
||||
/>
|
||||
);
|
||||
finishPreload("loaded");
|
||||
rerender(
|
||||
<Avatar
|
||||
imageProps={{ "data-testid": "avatar-image" }}
|
||||
label="Jun Sun"
|
||||
src="https://example.test/a.png"
|
||||
/>
|
||||
);
|
||||
finishPreload("loaded");
|
||||
|
||||
expect(screen.getByTestId("avatar-image")).toHaveAttribute(
|
||||
"src",
|
||||
"https://example.test/a.png"
|
||||
);
|
||||
});
|
||||
|
||||
it("requests a bucketed 2x WebP image and preserves the original query string", () => {
|
||||
const original =
|
||||
"https://cdn.example.test/avatar.png?Policy=a%2Bb&Signature=c%20d";
|
||||
|
||||
render(<Avatar label="Jun Sun" size="lg" src={original} transform />);
|
||||
|
||||
const source = preloadedImages.at(-1)?.src;
|
||||
expect(source).toBeDefined();
|
||||
expectDeliveryUrl(source ?? "", { height: "96", width: "96" });
|
||||
expect(source?.startsWith(`${original}&`)).toBe(true);
|
||||
});
|
||||
|
||||
it("updates transform dimensions from the rendered avatar box", () => {
|
||||
render(
|
||||
<Avatar
|
||||
label="Jun Sun"
|
||||
src="https://cdn.example.test/avatar.png"
|
||||
transform
|
||||
/>
|
||||
);
|
||||
|
||||
act(() => {
|
||||
resizeObservers.at(-1)?.resize(88, 40);
|
||||
});
|
||||
|
||||
expectDeliveryUrl(preloadedImages.at(-1)?.src ?? "", {
|
||||
height: "96",
|
||||
width: "192"
|
||||
});
|
||||
});
|
||||
|
||||
it("requests the original source by default", () => {
|
||||
render(
|
||||
<Avatar
|
||||
label="Jun Sun"
|
||||
src="https://cdn.example.test/avatar.png?token=preserved"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(preloadedImages.at(-1)?.src).toBe(
|
||||
"https://cdn.example.test/avatar.png?token=preserved"
|
||||
);
|
||||
});
|
||||
|
||||
it("does not transform non-HTTP image sources", () => {
|
||||
render(
|
||||
<Avatar
|
||||
label="Jun Sun"
|
||||
src="data:image/png;base64,cHJldmlldw=="
|
||||
transform
|
||||
/>
|
||||
);
|
||||
|
||||
expect(preloadedImages.at(-1)?.src).toBe(
|
||||
"data:image/png;base64,cHJldmlldw=="
|
||||
);
|
||||
});
|
||||
|
||||
it("retries the original URL when image delivery fails", () => {
|
||||
render(
|
||||
<Avatar
|
||||
imageProps={{ "data-testid": "avatar-image" }}
|
||||
label="Jun Sun"
|
||||
src="https://cdn.example.test/avatar.png?token=preserved"
|
||||
transform
|
||||
/>
|
||||
);
|
||||
|
||||
finishPreload("error");
|
||||
expect(preloadedImages.at(-1)?.src).toBe(
|
||||
"https://cdn.example.test/avatar.png?token=preserved"
|
||||
);
|
||||
finishPreload("loaded");
|
||||
|
||||
expect(screen.getByTestId("avatar-image")).toHaveAttribute(
|
||||
"src",
|
||||
"https://cdn.example.test/avatar.png?token=preserved"
|
||||
);
|
||||
});
|
||||
|
||||
it("renders overlays outside the clipped image surface", () => {
|
||||
render(
|
||||
<Avatar data-testid="avatar" label="Alice">
|
||||
<span data-testid="badge">online</span>
|
||||
</Avatar>
|
||||
);
|
||||
|
||||
expect(screen.getByTestId("avatar")).toContainElement(
|
||||
screen.getByTestId("badge")
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the first Unicode character and a question mark for blank labels", () => {
|
||||
const { rerender } = render(<Avatar data-testid="avatar" label="阿丽塔" />);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("阿");
|
||||
|
||||
rerender(<Avatar data-testid="avatar" label="" />);
|
||||
expect(screen.getByTestId("avatar")).toHaveTextContent("?");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,322 @@
|
||||
import { Avatar as AvatarPrimitive } from "radix-ui";
|
||||
import {
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type ComponentPropsWithoutRef,
|
||||
type ReactNode
|
||||
} from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
type AvatarFallback = "initial" | "empty";
|
||||
type AvatarSize = "xs" | "sm" | "md" | "lg" | number;
|
||||
type AvatarImageStatus = Parameters<
|
||||
NonNullable<
|
||||
ComponentPropsWithoutRef<
|
||||
typeof AvatarPrimitive.Image
|
||||
>["onLoadingStatusChange"]
|
||||
>
|
||||
>[0];
|
||||
type DataAttributes = {
|
||||
[key: `data-${string}`]: boolean | number | string | undefined;
|
||||
};
|
||||
|
||||
interface AvatarProps extends Omit<
|
||||
ComponentProps<typeof AvatarPrimitive.Root>,
|
||||
"asChild" | "children"
|
||||
> {
|
||||
children?: ReactNode;
|
||||
fallback?: AvatarFallback;
|
||||
fallbackColor?: string;
|
||||
fallbackSrc?: string | null;
|
||||
imageClassName?: string;
|
||||
imageProps?: Omit<
|
||||
ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>,
|
||||
"alt" | "className" | "src"
|
||||
> &
|
||||
DataAttributes;
|
||||
initial?: string;
|
||||
label: string;
|
||||
loading?: boolean;
|
||||
size?: AvatarSize;
|
||||
src?: string | null;
|
||||
surfaceClassName?: string;
|
||||
transform?: boolean;
|
||||
}
|
||||
|
||||
const sizeClassNames: Record<Exclude<AvatarSize, number>, string> = {
|
||||
xs: "size-4",
|
||||
sm: "size-6",
|
||||
md: "size-8",
|
||||
lg: "size-10"
|
||||
};
|
||||
|
||||
const sizePixels: Record<Exclude<AvatarSize, number>, number> = {
|
||||
xs: 16,
|
||||
sm: 24,
|
||||
md: 32,
|
||||
lg: 40
|
||||
};
|
||||
|
||||
const avatarDeliveryBuckets = [32, 48, 64, 96, 128, 192, 256, 384, 512];
|
||||
|
||||
function avatarInitial(label: string, initial?: string): string {
|
||||
const value = initial?.trim() || label.trim();
|
||||
return Array.from(value)[0]?.toLocaleUpperCase() || "?";
|
||||
}
|
||||
|
||||
function avatarSizePixels(size: AvatarSize): number {
|
||||
return typeof size === "number" && Number.isFinite(size) && size > 0
|
||||
? size
|
||||
: typeof size === "number"
|
||||
? sizePixels.md
|
||||
: sizePixels[size];
|
||||
}
|
||||
|
||||
function avatarDeliveryDimension(value: number): number {
|
||||
const desiredSize = Math.ceil(value * 2);
|
||||
return (
|
||||
avatarDeliveryBuckets.find((bucket) => bucket >= desiredSize) ??
|
||||
avatarDeliveryBuckets.at(-1) ??
|
||||
desiredSize
|
||||
);
|
||||
}
|
||||
|
||||
function avatarTransformUrl(
|
||||
src: string,
|
||||
dimensions: { height: number; width: number }
|
||||
): string {
|
||||
let url: URL;
|
||||
|
||||
try {
|
||||
url = new URL(src);
|
||||
} catch {
|
||||
return src;
|
||||
}
|
||||
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return src;
|
||||
}
|
||||
|
||||
const fragmentIndex = src.indexOf("#");
|
||||
const sourceWithoutFragment =
|
||||
fragmentIndex >= 0 ? src.slice(0, fragmentIndex) : src;
|
||||
const fragment = fragmentIndex >= 0 ? src.slice(fragmentIndex) : "";
|
||||
const separator = sourceWithoutFragment.includes("?")
|
||||
? sourceWithoutFragment.endsWith("?") || sourceWithoutFragment.endsWith("&")
|
||||
? ""
|
||||
: "&"
|
||||
: "?";
|
||||
const transformQuery = new URLSearchParams({
|
||||
width: String(avatarDeliveryDimension(dimensions.width)),
|
||||
height: String(avatarDeliveryDimension(dimensions.height)),
|
||||
format: "webp",
|
||||
fit: "inside"
|
||||
});
|
||||
return `${sourceWithoutFragment}${separator}${transformQuery}${fragment}`;
|
||||
}
|
||||
|
||||
function Avatar({
|
||||
children,
|
||||
className,
|
||||
fallback = "initial",
|
||||
fallbackColor,
|
||||
fallbackSrc,
|
||||
imageClassName,
|
||||
imageProps,
|
||||
initial,
|
||||
label,
|
||||
loading = false,
|
||||
size = "md",
|
||||
src,
|
||||
style,
|
||||
surfaceClassName,
|
||||
transform = false,
|
||||
...rootProps
|
||||
}: AvatarProps): React.JSX.Element {
|
||||
const normalizedSrc = src?.trim() ?? "";
|
||||
const normalizedFallbackSrc = fallbackSrc?.trim() ?? "";
|
||||
const initialSize = avatarSizePixels(size);
|
||||
const surfaceRef = useRef<HTMLSpanElement>(null);
|
||||
const [renderedDimensions, setRenderedDimensions] = useState<{
|
||||
height: number;
|
||||
width: number;
|
||||
} | null>(null);
|
||||
const [failedTransformUrl, setFailedTransformUrl] = useState("");
|
||||
const [failedOriginalUrl, setFailedOriginalUrl] = useState("");
|
||||
const transformedImageSrc = transform
|
||||
? avatarTransformUrl(
|
||||
normalizedSrc,
|
||||
renderedDimensions ?? { height: initialSize, width: initialSize }
|
||||
)
|
||||
: normalizedSrc;
|
||||
const shouldRetryOriginal =
|
||||
transformedImageSrc !== normalizedSrc &&
|
||||
failedTransformUrl === transformedImageSrc;
|
||||
const originalCandidateSrc = shouldRetryOriginal
|
||||
? normalizedSrc
|
||||
: transformedImageSrc;
|
||||
const shouldUseFallback =
|
||||
normalizedSrc.length > 0 &&
|
||||
originalCandidateSrc === normalizedSrc &&
|
||||
failedOriginalUrl === normalizedSrc;
|
||||
const effectiveImageSrc = loading
|
||||
? ""
|
||||
: shouldUseFallback
|
||||
? normalizedFallbackSrc
|
||||
: originalCandidateSrc;
|
||||
const [imageState, setImageState] = useState<{
|
||||
src: string;
|
||||
status: AvatarImageStatus;
|
||||
}>({ src: "", status: "idle" });
|
||||
const imageStatus =
|
||||
imageState.src === effectiveImageSrc
|
||||
? imageState.status
|
||||
: effectiveImageSrc
|
||||
? "loading"
|
||||
: "error";
|
||||
const showImage = imageStatus === "loaded" && effectiveImageSrc.length > 0;
|
||||
const imagePending =
|
||||
effectiveImageSrc.length > 0 &&
|
||||
(imageStatus === "loading" || imageStatus === "idle");
|
||||
const imageSrcForPrimitive =
|
||||
imageStatus === "error" ? undefined : effectiveImageSrc || undefined;
|
||||
const avatarState = loading
|
||||
? "loading"
|
||||
: effectiveImageSrc.length === 0
|
||||
? fallback
|
||||
: imageStatus === "loading" || imageStatus === "idle"
|
||||
? "loading"
|
||||
: showImage
|
||||
? "image"
|
||||
: fallback;
|
||||
const numericSizeStyle =
|
||||
typeof size === "number"
|
||||
? { height: `${size}px`, width: `${size}px`, ...style }
|
||||
: style;
|
||||
|
||||
useEffect(() => {
|
||||
setFailedTransformUrl("");
|
||||
setFailedOriginalUrl("");
|
||||
}, [normalizedFallbackSrc, normalizedSrc, transform]);
|
||||
|
||||
useEffect(() => {
|
||||
const surface = surfaceRef.current;
|
||||
if (!surface) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updateDimensions = (width: number, height: number): void => {
|
||||
if (width <= 0 || height <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRenderedDimensions((current) =>
|
||||
current?.width === width && current.height === height
|
||||
? current
|
||||
: { height, width }
|
||||
);
|
||||
};
|
||||
const rect = surface.getBoundingClientRect();
|
||||
updateDimensions(rect.width, rect.height);
|
||||
|
||||
if (typeof ResizeObserver === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
if (entry) {
|
||||
updateDimensions(entry.contentRect.width, entry.contentRect.height);
|
||||
}
|
||||
});
|
||||
observer.observe(surface);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const markImageError = (): void => {
|
||||
if (
|
||||
transformedImageSrc !== normalizedSrc &&
|
||||
effectiveImageSrc === transformedImageSrc &&
|
||||
shouldRetryOriginal === false
|
||||
) {
|
||||
setFailedTransformUrl(transformedImageSrc);
|
||||
} else if (effectiveImageSrc === normalizedSrc) {
|
||||
setFailedOriginalUrl(normalizedSrc);
|
||||
}
|
||||
setImageState({ src: effectiveImageSrc, status: "error" });
|
||||
};
|
||||
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
{...rootProps}
|
||||
className={cn(
|
||||
"relative inline-grid shrink-0 place-items-center rounded-full align-middle",
|
||||
typeof size === "number" ? undefined : sizeClassNames[size],
|
||||
className
|
||||
)}
|
||||
data-avatar-state={avatarState}
|
||||
data-slot="avatar"
|
||||
style={numericSizeStyle}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"grid size-full place-items-center overflow-hidden rounded-[inherit]",
|
||||
loading
|
||||
? "animate-pulse bg-[var(--transparency-block)] motion-reduce:animate-none"
|
||||
: fallback === "empty" || imagePending
|
||||
? "bg-transparent"
|
||||
: "bg-[var(--text-primary)] font-semibold leading-none text-[var(--text-inverted)]",
|
||||
surfaceClassName
|
||||
)}
|
||||
data-slot="avatar-surface"
|
||||
ref={surfaceRef}
|
||||
style={
|
||||
fallback === "initial" &&
|
||||
fallbackColor &&
|
||||
!showImage &&
|
||||
!loading &&
|
||||
!imagePending
|
||||
? { backgroundColor: fallbackColor }
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<AvatarPrimitive.Image
|
||||
{...imageProps}
|
||||
alt=""
|
||||
className={cn(
|
||||
"block size-full max-w-none object-cover",
|
||||
imageClassName
|
||||
)}
|
||||
referrerPolicy={imageProps?.referrerPolicy ?? "no-referrer"}
|
||||
src={imageSrcForPrimitive}
|
||||
onError={(event) => {
|
||||
markImageError();
|
||||
imageProps?.onError?.(event);
|
||||
}}
|
||||
onLoadingStatusChange={(status) => {
|
||||
if (status === "error") {
|
||||
markImageError();
|
||||
} else {
|
||||
setImageState({ src: effectiveImageSrc, status });
|
||||
}
|
||||
imageProps?.onLoadingStatusChange?.(status);
|
||||
}}
|
||||
/>
|
||||
<AvatarPrimitive.Fallback>
|
||||
{loading || fallback === "empty" || imagePending
|
||||
? null
|
||||
: avatarInitial(label, initial)}
|
||||
</AvatarPrimitive.Fallback>
|
||||
</span>
|
||||
{children}
|
||||
</AvatarPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Avatar };
|
||||
export type { AvatarProps };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./avatar";
|
||||
@@ -0,0 +1,67 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Slot } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"group/badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-[4px] border border-transparent whitespace-nowrap transition-[background-color,border-color,color,box-shadow] focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/35 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-[var(--transparency-block)] text-[var(--text-secondary)] [a]:hover:bg-[var(--transparency-hover)]",
|
||||
accent:
|
||||
"bg-[var(--accent-bg)] text-[var(--accent)] [a]:hover:bg-[var(--accent-bg)]",
|
||||
success:
|
||||
"bg-[color-mix(in_srgb,var(--state-success)_10%,transparent)] text-[var(--state-success)] [a]:hover:bg-[color-mix(in_srgb,var(--state-success)_14%,transparent)]",
|
||||
warning:
|
||||
"bg-[color-mix(in_srgb,var(--state-warning)_12%,transparent)] text-[var(--state-warning)] [a]:hover:bg-[color-mix(in_srgb,var(--state-warning)_16%,transparent)]",
|
||||
pending:
|
||||
"bg-[color-mix(in_srgb,var(--rich-text-mention-issue)_12%,transparent)] text-[var(--rich-text-mention-issue)] [a]:hover:bg-[color-mix(in_srgb,var(--rich-text-mention-issue)_16%,transparent)]",
|
||||
muted:
|
||||
"bg-[color-mix(in_srgb,var(--transparency-block)_72%,transparent)] text-[var(--text-tertiary)] [a]:hover:bg-[var(--transparency-hover)]",
|
||||
secondary:
|
||||
"bg-[var(--transparency-block)] text-[var(--text-secondary)] [a]:hover:bg-[var(--transparency-hover)]",
|
||||
destructive:
|
||||
"bg-[var(--on-danger)] text-[var(--state-danger)] focus-visible:ring-[color-mix(in_srgb,var(--state-danger)_20%,transparent)] [a]:hover:bg-[var(--on-danger-hover)]",
|
||||
outline:
|
||||
"border-border bg-card/90 text-foreground [a]:hover:bg-muted [a]:hover:text-foreground",
|
||||
ghost:
|
||||
"hover:bg-accent/80 hover:text-accent-foreground dark:hover:bg-muted/50",
|
||||
link: "text-primary underline-offset-4 hover:underline"
|
||||
},
|
||||
size: {
|
||||
default: "h-5 px-1 py-0.5 text-[0.72rem] font-normal [&>svg]:size-3!",
|
||||
sm: "h-4 gap-0.5 px-1 py-0 text-[10px] font-medium leading-none [&>svg]:size-2.5!"
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(badgeVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./badge";
|
||||
@@ -0,0 +1,68 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Slot } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const bareIconButtonVariants = cva(
|
||||
"inline-flex shrink-0 cursor-pointer items-center justify-center border border-transparent bg-transparent p-0 text-[var(--text-tertiary)] transition-[color,opacity,box-shadow] duration-150 outline-none select-none hover:border-transparent hover:bg-transparent hover:text-[var(--text-primary)] active:bg-transparent active:text-[var(--text-primary)] aria-expanded:bg-transparent aria-expanded:text-[var(--text-primary)] focus-visible:border-transparent focus-visible:bg-transparent focus-visible:text-[var(--text-primary)] focus-visible:ring-2 focus-visible:ring-[var(--border-focus)] disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-transparent disabled:text-[var(--text-disabled)] disabled:opacity-100 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
md: "size-6 rounded-[4px] [&_svg:not([class*='size-'])]:size-4",
|
||||
sm: "size-5 rounded-[3px] [&_svg:not([class*='size-'])]:size-3.5"
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
size: "md"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
type BareIconButtonSize = NonNullable<
|
||||
VariantProps<typeof bareIconButtonVariants>["size"]
|
||||
>;
|
||||
|
||||
type BareIconButtonProps = Omit<
|
||||
React.ComponentProps<"button">,
|
||||
"aria-label" | "children"
|
||||
> & {
|
||||
"aria-label": string;
|
||||
asChild?: boolean;
|
||||
children: React.ReactNode;
|
||||
size?: BareIconButtonSize;
|
||||
};
|
||||
|
||||
const BareIconButton = React.forwardRef<HTMLButtonElement, BareIconButtonProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
size = "md",
|
||||
asChild = false,
|
||||
type = "button",
|
||||
title,
|
||||
"aria-label": ariaLabel,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const Comp = asChild ? Slot.Root : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-slot="bare-icon-button"
|
||||
data-size={size}
|
||||
type={type}
|
||||
aria-label={ariaLabel}
|
||||
title={title ?? ariaLabel}
|
||||
className={cn(bareIconButtonVariants({ size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
BareIconButton.displayName = "BareIconButton";
|
||||
|
||||
export { BareIconButton };
|
||||
export type { BareIconButtonProps };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./bare-icon-button";
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { Slot } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"group/button inline-flex shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent text-[13px] font-normal whitespace-nowrap transition-[background-color,border-color,color,box-shadow,transform] outline-none select-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/35 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-2 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-[var(--text-primary)] text-[var(--text-inverted)] shadow-none hover:bg-[var(--text-primary-hover)]",
|
||||
outline:
|
||||
"border-border bg-card text-foreground hover:bg-muted/80 hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-transparency-block text-[var(--text-primary)] hover:bg-transparency-hover aria-expanded:bg-transparency-hover aria-expanded:text-[var(--text-primary)]",
|
||||
ghost:
|
||||
"bg-transparent text-[var(--text-primary)] hover:bg-transparency-hover aria-expanded:bg-transparency-hover aria-expanded:text-[var(--text-primary)]",
|
||||
chrome:
|
||||
"border border-transparent bg-transparent text-[var(--text-tertiary)] shadow-none hover:border-transparent hover:bg-[var(--transparency-hover)] hover:text-[var(--text-primary)] active:bg-[var(--transparency-active)] active:text-[var(--text-primary)] aria-expanded:border-transparent aria-expanded:bg-[var(--transparency-block)] aria-expanded:text-[var(--text-primary)] disabled:pointer-events-auto disabled:cursor-not-allowed disabled:opacity-45",
|
||||
destructive:
|
||||
"bg-[var(--state-danger)] text-[var(--white-stationary)] hover:bg-[var(--state-danger-hover)] focus-visible:border-[var(--state-danger)] focus-visible:ring-[color-mix(in_srgb,var(--state-danger)_25%,transparent)]",
|
||||
"destructive-secondary":
|
||||
"bg-[var(--on-danger)] text-[var(--state-danger)] hover:bg-[var(--on-danger-hover)] focus-visible:border-[var(--state-danger)] focus-visible:ring-[color-mix(in_srgb,var(--state-danger)_25%,transparent)]",
|
||||
link: "text-primary underline-offset-4 hover:underline"
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 gap-[6px] px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&_svg[data-icon=inline-start]:not([class*='size-'])]:size-3.5 [&_[data-icon=inline-start]_svg:not([class*='size-'])]:size-3.5",
|
||||
dialog:
|
||||
"h-8 gap-[6px] rounded-md px-3 text-[13px] font-normal leading-5 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 [&_svg[data-icon=inline-start]:not([class*='size-'])]:size-3.5 [&_[data-icon=inline-start]_svg:not([class*='size-'])]:size-3.5",
|
||||
xs: "h-6 gap-1 rounded-sm px-2 text-[11px] in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3 [&_svg[data-icon=inline-start]:not([class*='size-'])]:size-2.5 [&_[data-icon=inline-start]_svg:not([class*='size-'])]:size-2.5",
|
||||
sm: "h-7 gap-1 rounded-sm px-2.5 text-[13px] in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 [&_svg[data-icon=inline-start]:not([class*='size-'])]:size-3 [&_[data-icon=inline-start]_svg:not([class*='size-'])]:size-3",
|
||||
lg: "h-9 gap-2 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 [&_svg[data-icon=inline-start]:not([class*='size-'])]:size-3.5 [&_[data-icon=inline-start]_svg:not([class*='size-'])]:size-3.5",
|
||||
icon: "size-8",
|
||||
"icon-xs":
|
||||
"size-6 rounded-sm in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3 [&_svg[data-icon=inline-start]:not([class*='size-'])]:size-2.5 [&_[data-icon=inline-start]_svg:not([class*='size-'])]:size-2.5",
|
||||
"icon-sm": "size-7 rounded-sm in-data-[slot=button-group]:rounded-md",
|
||||
"icon-lg": "size-9"
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default"
|
||||
},
|
||||
compoundVariants: [
|
||||
{
|
||||
variant: "chrome",
|
||||
size: "icon-sm",
|
||||
class: "rounded-[4px]"
|
||||
}
|
||||
]
|
||||
}
|
||||
);
|
||||
|
||||
type ButtonProps = React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean;
|
||||
};
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const Comp = asChild ? Slot.Root : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
ref={ref}
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
Button.displayName = "Button";
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./button";
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Card({
|
||||
className,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/card flex flex-col gap-4 overflow-hidden rounded-lg border border-border/70 bg-card py-4 text-[13px] text-card-foreground shadow-none has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-lg *:[img:last-child]:rounded-b-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-lg px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:border-border/70 [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn(
|
||||
"text-[15px] leading-snug font-medium group-data-[size=sm]/card:text-[13px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn(
|
||||
"text-[13px] leading-[1.3] text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn(
|
||||
"flex items-center rounded-b-lg border-t border-border/70 bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./card";
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as React from "react";
|
||||
import { Checkbox as CheckboxPrimitive } from "radix-ui";
|
||||
|
||||
import { CheckIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer inline-flex size-4 shrink-0 items-center justify-center rounded-[4px] border border-[var(--border-1)] bg-[var(--transparency-block)] text-[var(--text-inverted)] transition-[background-color,border-color,color,box-shadow] outline-none focus-visible:border-[var(--border-focus)] focus-visible:ring-2 focus-visible:ring-[color-mix(in_srgb,var(--border-focus)_30%,transparent)] disabled:cursor-not-allowed disabled:border-[var(--border-1)] disabled:bg-[var(--transparency-block)] disabled:text-[var(--text-inverted)] disabled:opacity-100 data-disabled:border-[var(--border-1)] aria-invalid:border-[var(--state-danger)] aria-invalid:ring-2 aria-invalid:ring-[color-mix(in_srgb,var(--state-danger)_20%,transparent)] data-[state=checked]:border-[var(--text-primary)] data-[state=checked]:bg-[var(--text-primary)] data-[state=indeterminate]:border-[var(--text-primary)] data-[state=indeterminate]:bg-[var(--text-primary)] data-[state=unchecked]:hover:border-[color-mix(in_srgb,var(--text-primary)_40%,transparent)] disabled:data-[state=checked]:border-[var(--border-1)] disabled:data-[state=checked]:bg-[var(--text-disabled)] disabled:data-[state=indeterminate]:border-[var(--border-1)] disabled:data-[state=indeterminate]:bg-[var(--text-disabled)] data-disabled:data-[state=checked]:border-[var(--border-1)] data-disabled:data-[state=indeterminate]:border-[var(--border-1)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="grid place-content-center text-current transition-none data-[state=checked]:[&>span]:hidden data-[state=indeterminate]:[&>svg]:hidden [&>svg]:size-3"
|
||||
>
|
||||
<CheckIcon size={14} />
|
||||
<span className="h-0.5 w-2.5 rounded-full bg-current" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Checkbox };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./checkbox";
|
||||
@@ -0,0 +1,182 @@
|
||||
import type * as React from "react";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Combobox } from "./combobox";
|
||||
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
}
|
||||
);
|
||||
|
||||
const options = [
|
||||
{ label: "gpt-5.5", value: "gpt-5.5" },
|
||||
{
|
||||
description: "Claude Sonnet",
|
||||
keywords: ["Sonnet"],
|
||||
label: "claude-sonnet-4-6",
|
||||
value: "claude-sonnet-4-6"
|
||||
},
|
||||
{ label: "deepseek-chat", value: "deepseek-chat" }
|
||||
];
|
||||
|
||||
function renderCombobox(
|
||||
props: Partial<React.ComponentProps<typeof Combobox>> = {}
|
||||
) {
|
||||
const onValueChange = vi.fn();
|
||||
render(
|
||||
<Combobox
|
||||
aria-label="Model"
|
||||
options={options}
|
||||
searchPlaceholder="Search models"
|
||||
value=""
|
||||
onValueChange={onValueChange}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
return { onValueChange };
|
||||
}
|
||||
|
||||
function openCombobox() {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Model" }));
|
||||
return screen.getByPlaceholderText("Search models");
|
||||
}
|
||||
|
||||
function activeRowText(): string | null {
|
||||
const active = screen
|
||||
.getAllByRole("option")
|
||||
.find((row) => row.dataset.active === "true");
|
||||
return active?.textContent ?? null;
|
||||
}
|
||||
|
||||
describe("Combobox", () => {
|
||||
it("shows the placeholder until a value is selected", () => {
|
||||
renderCombobox({ placeholder: "Pick a model" });
|
||||
|
||||
expect(screen.getByRole("button", { name: "Model" })).toHaveTextContent(
|
||||
"Pick a model"
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the combobox role on the search input only", () => {
|
||||
renderCombobox();
|
||||
|
||||
// Closed: the trigger is a plain popover button, not a second combobox.
|
||||
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
|
||||
|
||||
const search = openCombobox();
|
||||
const comboboxes = screen.getAllByRole("combobox");
|
||||
expect(comboboxes).toHaveLength(1);
|
||||
expect(comboboxes[0]).toBe(search);
|
||||
expect(search).toHaveAttribute("aria-expanded", "true");
|
||||
});
|
||||
|
||||
it("commits a clicked option and closes the surface", () => {
|
||||
const { onValueChange } = renderCombobox();
|
||||
openCombobox();
|
||||
|
||||
fireEvent.click(screen.getByRole("option", { name: "gpt-5.5" }));
|
||||
|
||||
expect(onValueChange).toHaveBeenCalledWith("gpt-5.5");
|
||||
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("wraps arrow-key navigation around both ends and commits with Enter", () => {
|
||||
const { onValueChange } = renderCombobox();
|
||||
const search = openCombobox();
|
||||
|
||||
expect(activeRowText()).toContain("gpt-5.5");
|
||||
|
||||
fireEvent.keyDown(search, { key: "ArrowUp" });
|
||||
expect(activeRowText()).toContain("deepseek-chat");
|
||||
|
||||
fireEvent.keyDown(search, { key: "ArrowDown" });
|
||||
expect(activeRowText()).toContain("gpt-5.5");
|
||||
|
||||
fireEvent.keyDown(search, { key: "ArrowDown" });
|
||||
fireEvent.keyDown(search, { key: "ArrowDown" });
|
||||
expect(activeRowText()).toContain("deepseek-chat");
|
||||
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
expect(onValueChange).toHaveBeenCalledWith("deepseek-chat");
|
||||
expect(screen.queryByRole("listbox")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("jumps to the first and last rows with Home and End", () => {
|
||||
renderCombobox();
|
||||
const search = openCombobox();
|
||||
|
||||
fireEvent.keyDown(search, { key: "End" });
|
||||
expect(activeRowText()).toContain("deepseek-chat");
|
||||
|
||||
fireEvent.keyDown(search, { key: "Home" });
|
||||
expect(activeRowText()).toContain("gpt-5.5");
|
||||
});
|
||||
|
||||
it("filters rows by option keywords", () => {
|
||||
renderCombobox();
|
||||
const search = openCombobox();
|
||||
|
||||
fireEvent.change(search, { target: { value: "sonnet" } });
|
||||
|
||||
const rows = screen.getAllByRole("option");
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toHaveTextContent("claude-sonnet-4-6");
|
||||
});
|
||||
|
||||
it("offers the typed query as a custom value and commits it", () => {
|
||||
const { onValueChange } = renderCombobox({
|
||||
allowCustomValue: true,
|
||||
customValueLabel: (query) => `Use "${query}"`,
|
||||
emptyMessage: "No matches"
|
||||
});
|
||||
const search = openCombobox();
|
||||
|
||||
fireEvent.change(search, { target: { value: "my-private-model" } });
|
||||
|
||||
const rows = screen.getAllByRole("option");
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toHaveTextContent('Use "my-private-model"');
|
||||
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
expect(onValueChange).toHaveBeenCalledWith("my-private-model");
|
||||
});
|
||||
|
||||
it("excludes a custom row when the query matches an existing option id", () => {
|
||||
renderCombobox({ allowCustomValue: true });
|
||||
const search = openCombobox();
|
||||
|
||||
fireEvent.change(search, { target: { value: "gpt-5.5" } });
|
||||
|
||||
const rows = screen.getAllByRole("option");
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toHaveTextContent("gpt-5.5");
|
||||
});
|
||||
|
||||
it("never commits a disabled row", () => {
|
||||
const { onValueChange } = renderCombobox({
|
||||
options: [{ disabled: true, label: "gpt-5.5", value: "gpt-5.5" }]
|
||||
});
|
||||
const search = openCombobox();
|
||||
|
||||
fireEvent.keyDown(search, { key: "Enter" });
|
||||
fireEvent.click(screen.getByRole("option", { name: "gpt-5.5" }));
|
||||
|
||||
expect(onValueChange).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("listbox")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the empty message when nothing matches and custom values are off", () => {
|
||||
renderCombobox({ emptyMessage: "No matching models." });
|
||||
const search = openCombobox();
|
||||
|
||||
fireEvent.change(search, { target: { value: "unknown-model" } });
|
||||
|
||||
expect(screen.queryAllByRole("option")).toHaveLength(0);
|
||||
expect(screen.getByText("No matching models.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,251 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { CheckIcon, ChevronDownIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
import { Input } from "../input";
|
||||
import { menuItemIndicatorClassName } from "../menu-surface";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../popover";
|
||||
|
||||
interface ComboboxOption {
|
||||
description?: string;
|
||||
disabled?: boolean;
|
||||
/** Extra strings the search filter matches beyond value and label. */
|
||||
keywords?: readonly string[];
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface ComboboxProps {
|
||||
align?: "center" | "end" | "start";
|
||||
/**
|
||||
* Offer the typed query as a selectable value when it matches no option.
|
||||
* The caller localizes the row through customValueLabel.
|
||||
*/
|
||||
allowCustomValue?: boolean;
|
||||
"aria-label"?: string;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
contentStyle?: React.CSSProperties;
|
||||
customValueLabel?: (query: string) => React.ReactNode;
|
||||
disabled?: boolean;
|
||||
emptyMessage?: React.ReactNode;
|
||||
onValueChange: (value: string) => void;
|
||||
options: readonly ComboboxOption[];
|
||||
placeholder?: string;
|
||||
searchPlaceholder?: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const comboboxItemClassName =
|
||||
"relative flex w-full cursor-pointer scroll-my-1 flex-col items-start gap-0.5 rounded-sm px-2 py-1 pr-8 text-left text-[13px] text-[var(--text-primary)] outline-hidden transition-colors duration-200 select-none data-[active=true]:bg-[var(--transparency-hover)] data-disabled:pointer-events-none data-disabled:text-[var(--text-disabled)]";
|
||||
|
||||
function comboboxOptionMatches(option: ComboboxOption, query: string): boolean {
|
||||
if (!query) {
|
||||
return true;
|
||||
}
|
||||
return [option.label, option.value, ...(option.keywords ?? [])].some(
|
||||
(candidate) => candidate.toLocaleLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searchable single-value picker composed from Popover and Input. Unlike
|
||||
* Select, the open surface is query-driven with a fixed-height option list,
|
||||
* and it can accept a typed value that is not in the option catalog.
|
||||
*/
|
||||
function Combobox({
|
||||
align = "start",
|
||||
allowCustomValue = false,
|
||||
"aria-label": ariaLabel,
|
||||
className,
|
||||
contentClassName,
|
||||
contentStyle,
|
||||
customValueLabel,
|
||||
disabled = false,
|
||||
emptyMessage,
|
||||
onValueChange,
|
||||
options,
|
||||
placeholder,
|
||||
searchPlaceholder,
|
||||
value
|
||||
}: ComboboxProps) {
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [activeIndex, setActiveIndex] = React.useState(0);
|
||||
const listboxID = React.useId();
|
||||
|
||||
const normalizedQuery = query.trim().toLocaleLowerCase();
|
||||
const visibleOptions = options.filter((option) =>
|
||||
comboboxOptionMatches(option, normalizedQuery)
|
||||
);
|
||||
const customValue =
|
||||
allowCustomValue &&
|
||||
query.trim() &&
|
||||
!options.some((option) => option.value === query.trim())
|
||||
? query.trim()
|
||||
: null;
|
||||
const rows: ComboboxOption[] = customValue
|
||||
? [...visibleOptions, { label: customValue, value: customValue }]
|
||||
: visibleOptions;
|
||||
const clampedActiveIndex = Math.min(
|
||||
activeIndex,
|
||||
Math.max(rows.length - 1, 0)
|
||||
);
|
||||
const selectedOption = options.find((option) => option.value === value);
|
||||
const triggerLabel = selectedOption?.label ?? value;
|
||||
|
||||
const commit = (row: ComboboxOption) => {
|
||||
if (row.disabled) {
|
||||
return;
|
||||
}
|
||||
onValueChange(row.value);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const onOpenChange = (nextOpen: boolean) => {
|
||||
setOpen(nextOpen);
|
||||
setQuery("");
|
||||
setActiveIndex(0);
|
||||
};
|
||||
|
||||
const onSearchKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
if (rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
const delta = event.key === "ArrowDown" ? 1 : -1;
|
||||
setActiveIndex((rows.length + clampedActiveIndex + delta) % rows.length);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Home" || event.key === "End") {
|
||||
event.preventDefault();
|
||||
setActiveIndex(event.key === "Home" ? 0 : Math.max(rows.length - 1, 0));
|
||||
return;
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
const row = rows[clampedActiveIndex];
|
||||
if (row) {
|
||||
commit(row);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={onOpenChange}>
|
||||
<PopoverTrigger asChild>
|
||||
<button
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
"flex h-8 w-full min-w-0 cursor-pointer items-center justify-between gap-1.5 rounded-lg border border-transparent bg-[var(--transparency-block)] py-2 pr-2 pl-2.5 text-[13px] text-[var(--text-primary)] transition-colors outline-none select-none hover:bg-[var(--transparency-hover)] focus:bg-[var(--transparency-hover)] focus-visible:bg-[var(--transparency-hover)] disabled:cursor-not-allowed disabled:bg-[var(--transparency-block)] disabled:text-[var(--text-disabled)]",
|
||||
"[&[data-state=open]>svg]:rotate-180 [&>svg]:transition-transform [&>svg]:duration-200",
|
||||
className
|
||||
)}
|
||||
data-slot="combobox-trigger"
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"min-w-0 flex-1 truncate text-left",
|
||||
!triggerLabel && "text-[var(--text-placeholder)]"
|
||||
)}
|
||||
>
|
||||
{triggerLabel || placeholder}
|
||||
</span>
|
||||
<ChevronDownIcon className="pointer-events-none size-4 shrink-0 text-current" />
|
||||
</button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align={align}
|
||||
className={cn(
|
||||
"w-[var(--radix-popover-trigger-width)] min-w-44 gap-0 p-1",
|
||||
contentClassName
|
||||
)}
|
||||
data-slot="combobox-content"
|
||||
style={contentStyle}
|
||||
onOpenAutoFocus={(event) => {
|
||||
// Focus lands on the search input instead of the surface.
|
||||
event.preventDefault();
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
aria-activedescendant={
|
||||
rows[clampedActiveIndex]
|
||||
? `${listboxID}-${clampedActiveIndex}`
|
||||
: undefined
|
||||
}
|
||||
aria-autocomplete="list"
|
||||
aria-controls={listboxID}
|
||||
aria-expanded
|
||||
autoFocus
|
||||
className="shrink-0"
|
||||
data-slot="combobox-search"
|
||||
placeholder={searchPlaceholder}
|
||||
// The search input is the ARIA combobox: it owns the listbox,
|
||||
// autocomplete, and active-descendant wiring. The closed trigger
|
||||
// stays a plain popover button so the role is never duplicated.
|
||||
role="combobox"
|
||||
value={query}
|
||||
onChange={(event) => {
|
||||
setQuery(event.currentTarget.value);
|
||||
setActiveIndex(0);
|
||||
}}
|
||||
onKeyDown={onSearchKeyDown}
|
||||
/>
|
||||
<div
|
||||
className="mt-1 flex max-h-56 flex-col gap-0.5 overflow-y-auto overscroll-contain"
|
||||
data-slot="combobox-listbox"
|
||||
id={listboxID}
|
||||
role="listbox"
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<span className="px-2 py-1.5 text-[12px] text-[var(--text-tertiary)]">
|
||||
{emptyMessage}
|
||||
</span>
|
||||
) : (
|
||||
rows.map((row, index) => {
|
||||
const isCustomRow =
|
||||
customValue !== null && index === rows.length - 1;
|
||||
return (
|
||||
<button
|
||||
key={`${row.value}:${isCustomRow ? "custom" : "option"}`}
|
||||
aria-selected={row.value === value}
|
||||
className={comboboxItemClassName}
|
||||
data-active={index === clampedActiveIndex}
|
||||
data-disabled={row.disabled ? "" : undefined}
|
||||
data-slot="combobox-item"
|
||||
id={`${listboxID}-${index}`}
|
||||
role="option"
|
||||
tabIndex={-1}
|
||||
type="button"
|
||||
onClick={() => commit(row)}
|
||||
onPointerMove={() => setActiveIndex(index)}
|
||||
>
|
||||
<span className="w-full truncate pr-2">
|
||||
{isCustomRow
|
||||
? (customValueLabel?.(row.value) ?? row.label)
|
||||
: row.label}
|
||||
</span>
|
||||
{row.description ? (
|
||||
<span className="w-full truncate pr-2 text-[11px] text-[var(--text-tertiary)]">
|
||||
{row.description}
|
||||
</span>
|
||||
) : null}
|
||||
{row.value === value ? (
|
||||
<span className={menuItemIndicatorClassName}>
|
||||
<CheckIcon className="pointer-events-none" />
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
export { Combobox, type ComboboxOption };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./combobox";
|
||||
@@ -0,0 +1,133 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { Button } from "#components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from "#components/dialog";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
type ConfirmationDialogTone = "default" | "destructive";
|
||||
|
||||
function confirmToneClassName(tone: ConfirmationDialogTone) {
|
||||
if (tone === "destructive") {
|
||||
return "shadow-none";
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function ConfirmationDialog({
|
||||
cancelLabel,
|
||||
children,
|
||||
className,
|
||||
confirmBusy = false,
|
||||
confirmDisabled = false,
|
||||
confirmLabel,
|
||||
description,
|
||||
disableCloseWhileBusy = true,
|
||||
footer,
|
||||
hideConfirmButton = false,
|
||||
onCancel,
|
||||
onConfirm,
|
||||
onOpenChange,
|
||||
open,
|
||||
overlayClassName,
|
||||
portaled = true,
|
||||
tone = "default",
|
||||
title
|
||||
}: {
|
||||
cancelLabel: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
confirmBusy?: boolean;
|
||||
confirmDisabled?: boolean;
|
||||
confirmLabel: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
disableCloseWhileBusy?: boolean;
|
||||
footer?: React.ReactNode;
|
||||
hideConfirmButton?: boolean;
|
||||
onCancel?: () => void;
|
||||
onConfirm?: () => void;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
open: boolean;
|
||||
overlayClassName?: string;
|
||||
portaled?: boolean;
|
||||
tone?: ConfirmationDialogTone;
|
||||
title: React.ReactNode;
|
||||
}) {
|
||||
const isCloseDisabled = disableCloseWhileBusy && confirmBusy;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className={cn(
|
||||
"max-w-[calc(100%-2rem)] text-left sm:max-w-[360px]",
|
||||
className
|
||||
)}
|
||||
overlayClassName={cn(overlayClassName)}
|
||||
portaled={portaled}
|
||||
showCloseButton={false}
|
||||
onEscapeKeyDown={(event) => {
|
||||
if (isCloseDisabled) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
onInteractOutside={(event) => {
|
||||
if (isCloseDisabled) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
{description ? (
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
{children ? (
|
||||
<div className="text-[13px] leading-[1.3] text-text-secondary">
|
||||
{children}
|
||||
</div>
|
||||
) : null}
|
||||
{footer ?? (
|
||||
<DialogFooter>
|
||||
<Button
|
||||
disabled={confirmBusy}
|
||||
size="dialog"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
onCancel?.();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{cancelLabel}
|
||||
</Button>
|
||||
{hideConfirmButton ? null : (
|
||||
<Button
|
||||
disabled={confirmBusy || confirmDisabled}
|
||||
size="dialog"
|
||||
type="button"
|
||||
variant={tone === "default" ? "default" : "destructive"}
|
||||
className={cn("shadow-none", confirmToneClassName(tone))}
|
||||
onClick={() => {
|
||||
onConfirm?.();
|
||||
}}
|
||||
>
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export { ConfirmationDialog };
|
||||
export type { ConfirmationDialogTone };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./confirmation-dialog";
|
||||
@@ -0,0 +1,149 @@
|
||||
import * as React from "react";
|
||||
import { ContextMenu as ContextMenuPrimitive } from "radix-ui";
|
||||
|
||||
import { ArrowRightIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
import { MenuSurface, menuItemClassName } from "../menu-surface";
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />;
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
asChild
|
||||
data-slot="context-menu-content"
|
||||
{...props}
|
||||
>
|
||||
<MenuSurface
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"z-50 min-w-32 overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-popover)", ...style }}
|
||||
>
|
||||
{children}
|
||||
</MenuSurface>
|
||||
</ContextMenuPrimitive.Content>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-inset={inset}
|
||||
data-slot="context-menu-item"
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"group/context-menu-item",
|
||||
menuItemClassName,
|
||||
"data-inset:pl-7",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("mx-2 my-0.5 h-px bg-[var(--border-1)]", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
className={cn(
|
||||
menuItemClassName,
|
||||
"data-open:bg-[var(--transparency-block)] data-open:text-[var(--text-primary)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ArrowRightIcon className="ml-auto text-[var(--text-tertiary)]" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.SubContent
|
||||
asChild
|
||||
data-slot="context-menu-sub-content"
|
||||
{...props}
|
||||
>
|
||||
<MenuSurface
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn("z-50 min-w-[96px] overflow-hidden", className)}
|
||||
style={{ zIndex: "var(--z-popover)", ...style }}
|
||||
>
|
||||
{children}
|
||||
</MenuSurface>
|
||||
</ContextMenuPrimitive.SubContent>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuTrigger
|
||||
};
|
||||
@@ -0,0 +1,467 @@
|
||||
import * as React from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
export interface DatePickerLabels {
|
||||
placeholder: string;
|
||||
previousMonth: string;
|
||||
nextMonth: string;
|
||||
clear: string;
|
||||
today: string;
|
||||
weekdayLabels: readonly [
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string
|
||||
];
|
||||
}
|
||||
|
||||
export interface DatePickerProps extends Omit<
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
"onChange" | "value" | "type"
|
||||
> {
|
||||
value?: string;
|
||||
onValueChange?: (value: string) => void;
|
||||
labels?: Partial<DatePickerLabels>;
|
||||
formatDisplayValue?: (date: Date) => string;
|
||||
formatMonthLabel?: (date: Date) => string;
|
||||
}
|
||||
|
||||
const defaultLabels: DatePickerLabels = {
|
||||
placeholder: "Year / Month / Day",
|
||||
previousMonth: "Previous month",
|
||||
nextMonth: "Next month",
|
||||
clear: "Clear",
|
||||
today: "Today",
|
||||
weekdayLabels: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
|
||||
};
|
||||
|
||||
const DATE_PICKER_POPOVER_WIDTH_PX = 264;
|
||||
const DATE_PICKER_POPOVER_HEIGHT_PX = 336;
|
||||
const DATE_PICKER_POPOVER_GAP_PX = 6;
|
||||
const DATE_PICKER_VIEWPORT_MARGIN_PX = 8;
|
||||
|
||||
function parseDateValue(value: string | undefined): Date | null {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [year, month, day] = value.split("-").map(Number);
|
||||
if (!year || !month || !day) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Date(year, month - 1, day);
|
||||
}
|
||||
|
||||
function formatDateValue(date: Date): string {
|
||||
const year = date.getFullYear();
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, "0");
|
||||
const day = `${date.getDate()}`.padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function defaultDisplayValueFormatter(date: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit"
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function defaultMonthLabelFormatter(date: Date): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
year: "numeric",
|
||||
month: "long"
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function isSameDate(left: Date | null, right: Date | null): boolean {
|
||||
return Boolean(
|
||||
left &&
|
||||
right &&
|
||||
left.getFullYear() === right.getFullYear() &&
|
||||
left.getMonth() === right.getMonth() &&
|
||||
left.getDate() === right.getDate()
|
||||
);
|
||||
}
|
||||
|
||||
function buildMonthGrid(monthDate: Date): Date[] {
|
||||
const firstOfMonth = new Date(
|
||||
monthDate.getFullYear(),
|
||||
monthDate.getMonth(),
|
||||
1
|
||||
);
|
||||
const gridStart = new Date(firstOfMonth);
|
||||
gridStart.setDate(firstOfMonth.getDate() - firstOfMonth.getDay());
|
||||
|
||||
return Array.from({ length: 42 }, (_, index) => {
|
||||
const date = new Date(gridStart);
|
||||
date.setDate(gridStart.getDate() + index);
|
||||
return date;
|
||||
});
|
||||
}
|
||||
|
||||
function resolvePopoverPosition(rect: DOMRect): {
|
||||
top: number;
|
||||
left: number;
|
||||
width: number;
|
||||
} {
|
||||
const width = Math.max(rect.width, DATE_PICKER_POPOVER_WIDTH_PX);
|
||||
const maxLeft = window.innerWidth - width - DATE_PICKER_VIEWPORT_MARGIN_PX;
|
||||
const left = Math.max(
|
||||
DATE_PICKER_VIEWPORT_MARGIN_PX,
|
||||
Math.min(rect.left, Math.max(DATE_PICKER_VIEWPORT_MARGIN_PX, maxLeft))
|
||||
);
|
||||
const belowTop = rect.bottom + DATE_PICKER_POPOVER_GAP_PX;
|
||||
const aboveTop =
|
||||
rect.top - DATE_PICKER_POPOVER_GAP_PX - DATE_PICKER_POPOVER_HEIGHT_PX;
|
||||
const canOpenBelow =
|
||||
belowTop + DATE_PICKER_POPOVER_HEIGHT_PX <=
|
||||
window.innerHeight - DATE_PICKER_VIEWPORT_MARGIN_PX;
|
||||
const top = canOpenBelow
|
||||
? belowTop
|
||||
: Math.max(DATE_PICKER_VIEWPORT_MARGIN_PX, aboveTop);
|
||||
|
||||
return { top, left, width };
|
||||
}
|
||||
|
||||
function subscribeScrollableAncestors(
|
||||
trigger: HTMLElement,
|
||||
onScrollLike: () => void
|
||||
): () => void {
|
||||
const cleanups: Array<() => void> = [];
|
||||
let element: HTMLElement | null = trigger.parentElement;
|
||||
|
||||
while (element && element !== document.documentElement) {
|
||||
const { overflowX, overflowY } = window.getComputedStyle(element);
|
||||
if (
|
||||
overflowY === "auto" ||
|
||||
overflowY === "scroll" ||
|
||||
overflowY === "overlay" ||
|
||||
overflowX === "auto" ||
|
||||
overflowX === "scroll" ||
|
||||
overflowX === "overlay"
|
||||
) {
|
||||
element.addEventListener("scroll", onScrollLike, { passive: true });
|
||||
const current = element;
|
||||
cleanups.push(() => current.removeEventListener("scroll", onScrollLike));
|
||||
}
|
||||
element = element.parentElement;
|
||||
}
|
||||
|
||||
return () => cleanups.forEach((dispose) => dispose());
|
||||
}
|
||||
|
||||
const DatePicker = React.forwardRef<HTMLButtonElement, DatePickerProps>(
|
||||
(
|
||||
{
|
||||
className,
|
||||
value,
|
||||
onValueChange,
|
||||
onClick,
|
||||
disabled,
|
||||
labels,
|
||||
formatDisplayValue = defaultDisplayValueFormatter,
|
||||
formatMonthLabel = defaultMonthLabelFormatter,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const resolvedLabels: DatePickerLabels = {
|
||||
...defaultLabels,
|
||||
...labels,
|
||||
weekdayLabels: labels?.weekdayLabels ?? defaultLabels.weekdayLabels
|
||||
};
|
||||
const triggerRef = React.useRef<HTMLButtonElement | null>(null);
|
||||
const popoverRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const selectedDate = React.useMemo(() => parseDateValue(value), [value]);
|
||||
const [isOpen, setIsOpen] = React.useState(false);
|
||||
const [visibleMonth, setVisibleMonth] = React.useState(
|
||||
() => selectedDate ?? new Date()
|
||||
);
|
||||
const [popoverPosition, setPopoverPosition] = React.useState<{
|
||||
top: number;
|
||||
left: number;
|
||||
width: number;
|
||||
} | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (selectedDate) {
|
||||
setVisibleMonth(selectedDate);
|
||||
}
|
||||
}, [selectedDate]);
|
||||
|
||||
const openPopover = React.useCallback(() => {
|
||||
const trigger = triggerRef.current;
|
||||
if (!trigger) {
|
||||
return;
|
||||
}
|
||||
setPopoverPosition(
|
||||
resolvePopoverPosition(trigger.getBoundingClientRect())
|
||||
);
|
||||
setIsOpen(true);
|
||||
}, []);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
if (!isOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sync = () => {
|
||||
const element = triggerRef.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
setPopoverPosition(
|
||||
resolvePopoverPosition(element.getBoundingClientRect())
|
||||
);
|
||||
};
|
||||
|
||||
sync();
|
||||
const rafId = window.requestAnimationFrame(sync);
|
||||
return () => window.cancelAnimationFrame(rafId);
|
||||
}, [isOpen]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isOpen) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ac = new AbortController();
|
||||
const { signal } = ac;
|
||||
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
const target = event.target as Node | null;
|
||||
if (
|
||||
target &&
|
||||
(triggerRef.current?.contains(target) ||
|
||||
popoverRef.current?.contains(target))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setIsOpen(false);
|
||||
triggerRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const updatePosition = () => {
|
||||
const element = triggerRef.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
setPopoverPosition(
|
||||
resolvePopoverPosition(element.getBoundingClientRect())
|
||||
);
|
||||
};
|
||||
|
||||
document.addEventListener("pointerdown", handlePointerDown, { signal });
|
||||
document.addEventListener("keydown", handleKeyDown, { signal });
|
||||
window.addEventListener("resize", updatePosition, { signal });
|
||||
document.addEventListener(
|
||||
"wheel",
|
||||
() => window.requestAnimationFrame(updatePosition),
|
||||
{
|
||||
capture: true,
|
||||
passive: true,
|
||||
signal
|
||||
}
|
||||
);
|
||||
|
||||
const unsubAncestors = triggerRef.current
|
||||
? subscribeScrollableAncestors(triggerRef.current, updatePosition)
|
||||
: () => {};
|
||||
|
||||
return () => {
|
||||
ac.abort();
|
||||
unsubAncestors();
|
||||
};
|
||||
}, [isOpen]);
|
||||
|
||||
const today = React.useMemo(() => new Date(), []);
|
||||
const monthGrid = React.useMemo(
|
||||
() => buildMonthGrid(visibleMonth),
|
||||
[visibleMonth]
|
||||
);
|
||||
|
||||
const displayValue = selectedDate
|
||||
? formatDisplayValue(selectedDate)
|
||||
: resolvedLabels.placeholder;
|
||||
|
||||
const selectDate = (date: Date) => {
|
||||
onValueChange?.(formatDateValue(date));
|
||||
setIsOpen(false);
|
||||
triggerRef.current?.focus();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={(node) => {
|
||||
triggerRef.current = node;
|
||||
if (typeof ref === "function") {
|
||||
ref(node);
|
||||
} else if (ref) {
|
||||
ref.current = node;
|
||||
}
|
||||
}}
|
||||
data-slot="date-picker"
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
className={cn(
|
||||
"inline-flex h-8 min-h-8 w-full items-center justify-start rounded-md border border-transparent bg-[var(--workbench-field-bg)] px-3 text-left text-[13px] text-foreground transition-[background-color,border-color,box-shadow,color] outline-none hover:bg-muted/60 focus-visible:border-border focus-visible:ring-2 focus-visible:ring-ring/30 disabled:cursor-not-allowed disabled:bg-muted disabled:text-muted-foreground disabled:opacity-100",
|
||||
!selectedDate && "text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
if (isOpen) {
|
||||
setIsOpen(false);
|
||||
} else {
|
||||
openPopover();
|
||||
}
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<span className="min-w-0 truncate">{displayValue}</span>
|
||||
</button>
|
||||
|
||||
{isOpen && popoverPosition
|
||||
? createPortal(
|
||||
<div
|
||||
ref={popoverRef}
|
||||
data-slot="date-picker-content"
|
||||
className="fixed z-50 flex min-w-[264px] max-w-[min(100vw-16px,320px)] flex-col overflow-hidden rounded-xl border border-border/70 bg-popover p-3 text-popover-foreground shadow-soft"
|
||||
style={{
|
||||
top: popoverPosition.top,
|
||||
left: popoverPosition.left,
|
||||
width: popoverPosition.width,
|
||||
zIndex: "var(--z-popover)"
|
||||
}}
|
||||
>
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<div className="text-[13px] font-semibold text-foreground">
|
||||
{formatMonthLabel(visibleMonth)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
aria-label={resolvedLabels.previousMonth}
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setVisibleMonth(
|
||||
(current) =>
|
||||
new Date(
|
||||
current.getFullYear(),
|
||||
current.getMonth() - 1,
|
||||
1
|
||||
)
|
||||
)
|
||||
}
|
||||
>
|
||||
<ArrowLeftIcon size={16} />
|
||||
</button>
|
||||
<button
|
||||
aria-label={resolvedLabels.nextMonth}
|
||||
className="inline-flex h-7 w-7 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setVisibleMonth(
|
||||
(current) =>
|
||||
new Date(
|
||||
current.getFullYear(),
|
||||
current.getMonth() + 1,
|
||||
1
|
||||
)
|
||||
)
|
||||
}
|
||||
>
|
||||
<ArrowRightIcon size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-7 gap-1 text-center text-[11px] font-semibold text-muted-foreground">
|
||||
{resolvedLabels.weekdayLabels.map((day) => (
|
||||
<div key={day} className="py-1">
|
||||
{day}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
className="mt-1 grid grid-cols-7 justify-items-center gap-1"
|
||||
role="grid"
|
||||
>
|
||||
{monthGrid.map((date) => {
|
||||
const isSelected = isSameDate(date, selectedDate);
|
||||
const isToday = isSameDate(date, today);
|
||||
const inCurrentMonth =
|
||||
date.getMonth() === visibleMonth.getMonth();
|
||||
|
||||
return (
|
||||
<button
|
||||
key={formatDateValue(date)}
|
||||
aria-pressed={isSelected}
|
||||
className={cn(
|
||||
"inline-flex h-8 w-8 items-center justify-center rounded-sm text-[13px] transition-[background-color,color,box-shadow] hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",
|
||||
inCurrentMonth
|
||||
? "text-foreground"
|
||||
: "text-muted-foreground",
|
||||
isToday &&
|
||||
"bg-primary/10 text-primary shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-primary)_20%,transparent)]",
|
||||
isSelected &&
|
||||
"bg-primary text-primary-foreground hover:bg-primary"
|
||||
)}
|
||||
role="gridcell"
|
||||
type="button"
|
||||
onClick={() => selectDate(date)}
|
||||
>
|
||||
{date.getDate()}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between gap-2 border-t border-border/70 pt-3">
|
||||
<button
|
||||
className="inline-flex min-h-8 items-center justify-center rounded-sm px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onValueChange?.("");
|
||||
setIsOpen(false);
|
||||
triggerRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
{resolvedLabels.clear}
|
||||
</button>
|
||||
<button
|
||||
className="inline-flex min-h-8 items-center justify-center rounded-sm bg-primary px-3 text-[13px] font-medium text-primary-foreground transition-opacity hover:opacity-90"
|
||||
type="button"
|
||||
onClick={() => selectDate(today)}
|
||||
>
|
||||
{resolvedLabels.today}
|
||||
</button>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
: null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
DatePicker.displayName = "DatePicker";
|
||||
|
||||
export { DatePicker };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./date-picker";
|
||||
@@ -0,0 +1,240 @@
|
||||
import * as React from "react";
|
||||
import { Dialog as DialogPrimitive } from "radix-ui";
|
||||
|
||||
import { Button } from "#components/button";
|
||||
import { CloseIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const dialogCloseDurationMs = 150;
|
||||
|
||||
const DialogMotionContext = React.createContext<{ open: boolean }>({
|
||||
open: false
|
||||
});
|
||||
|
||||
function Dialog({
|
||||
defaultOpen,
|
||||
onOpenChange,
|
||||
open,
|
||||
...props
|
||||
}: Omit<React.ComponentProps<typeof DialogPrimitive.Root>, "onOpenChange"> & {
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const [uncontrolledOpen, setUncontrolledOpen] = React.useState(
|
||||
defaultOpen ?? false
|
||||
);
|
||||
const currentOpen = open ?? uncontrolledOpen;
|
||||
|
||||
const handleOpenChange = React.useCallback(
|
||||
(nextOpen: boolean) => {
|
||||
if (open === undefined) {
|
||||
setUncontrolledOpen(nextOpen);
|
||||
}
|
||||
onOpenChange?.(nextOpen);
|
||||
},
|
||||
[onOpenChange, open]
|
||||
);
|
||||
|
||||
return (
|
||||
<DialogMotionContext.Provider value={{ open: currentOpen }}>
|
||||
<DialogPrimitive.Root
|
||||
data-slot="dialog"
|
||||
open={currentOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
{...props}
|
||||
/>
|
||||
</DialogMotionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate bg-[var(--backdrop)] duration-150 supports-backdrop-filter:backdrop-blur-sm data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-dialog-overlay)", ...style }}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
overlayClassName,
|
||||
portaled = true,
|
||||
showCloseButton = true,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
overlayClassName?: string;
|
||||
portaled?: boolean;
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
const { open } = React.useContext(DialogMotionContext);
|
||||
const [mounted, setMounted] = React.useState(open);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setMounted(true);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const timeout = window.setTimeout(() => {
|
||||
setMounted(false);
|
||||
}, dialogCloseDurationMs);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timeout);
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
if (!mounted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<DialogOverlay className={overlayClassName} forceMount />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
forceMount
|
||||
className={cn(
|
||||
portaled ? "fixed" : "absolute",
|
||||
"nodrag pointer-events-none top-1/2 left-1/2 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 origin-center gap-3 rounded-[16px] border border-border-1 bg-[var(--background-panel)] p-[18px] text-[13px] text-foreground shadow-panel outline-none ease-[cubic-bezier(0.22,1,0.36,1)] will-change-[transform,opacity] [-webkit-app-region:no-drag] sm:max-w-[360px] data-[state=closed]:!pointer-events-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-[0.96] data-[state=closed]:duration-[150ms] data-[state=open]:pointer-events-auto data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-[0.96] data-[state=open]:duration-[250ms] motion-reduce:animate-none",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-dialog)", ...style }}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close data-slot="dialog-close" asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-3 right-3"
|
||||
size="icon-sm"
|
||||
>
|
||||
<CloseIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</>
|
||||
);
|
||||
|
||||
if (!portaled) {
|
||||
return content;
|
||||
}
|
||||
|
||||
return <DialogPortal forceMount>{content}</DialogPortal>;
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 pr-8", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 pt-1 sm:flex-row sm:justify-end sm:gap-2.5",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="ghost" size="dialog">
|
||||
Close
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn(
|
||||
"text-[15px] leading-[1.35] font-semibold tracking-normal text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-[13px] font-[400] leading-[1.3] text-text-secondary *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./dialog";
|
||||
@@ -0,0 +1,147 @@
|
||||
import * as React from "react";
|
||||
import { Drawer as DrawerPrimitive } from "vaul";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Drawer({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />;
|
||||
}
|
||||
|
||||
function DrawerTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DrawerPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DrawerClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />;
|
||||
}
|
||||
|
||||
function DrawerOverlay({
|
||||
className,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||
return (
|
||||
<DrawerPrimitive.Overlay
|
||||
data-slot="drawer-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate bg-[var(--backdrop)] duration-150 supports-backdrop-filter:backdrop-blur-sm data-closed:animate-out data-closed:fade-out-0 data-open:animate-in data-open:fade-in-0",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-dialog-overlay)", ...style }}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerContent({
|
||||
className,
|
||||
children,
|
||||
portalContainer,
|
||||
showOverlay = true,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Content> & {
|
||||
portalContainer?: React.ComponentProps<
|
||||
typeof DrawerPrimitive.Portal
|
||||
>["container"];
|
||||
showOverlay?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DrawerPortal data-slot="drawer-portal" container={portalContainer}>
|
||||
{showOverlay ? <DrawerOverlay /> : null}
|
||||
<DrawerPrimitive.Content
|
||||
data-slot="drawer-content"
|
||||
className={cn(
|
||||
"group/drawer-content fixed flex h-auto flex-col border-[var(--border-1)] bg-background-fronted text-[13px] text-foreground shadow-panel outline-none",
|
||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-xl data-[vaul-drawer-direction=bottom]:border-t",
|
||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:rounded-r-xl data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:rounded-l-xl data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-xl data-[vaul-drawer-direction=top]:border-b",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-dialog)", ...style }}
|
||||
{...props}
|
||||
>
|
||||
<div className="mx-auto mt-4 hidden h-1 w-[100px] shrink-0 rounded-full bg-muted group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-header"
|
||||
className={cn(
|
||||
"flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-0.5 md:text-left",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||
return (
|
||||
<DrawerPrimitive.Title
|
||||
data-slot="drawer-title"
|
||||
className={cn(
|
||||
"text-[15px] font-medium leading-[1.35] text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DrawerDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||
return (
|
||||
<DrawerPrimitive.Description
|
||||
data-slot="drawer-description"
|
||||
className={cn("text-[13px] text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerFooter,
|
||||
DrawerHeader,
|
||||
DrawerOverlay,
|
||||
DrawerPortal,
|
||||
DrawerTitle,
|
||||
DrawerTrigger
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./drawer";
|
||||
@@ -0,0 +1,316 @@
|
||||
import * as React from "react";
|
||||
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
|
||||
|
||||
import { ArrowRightIcon, CheckIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
import {
|
||||
MenuSurface,
|
||||
menuItemClassName,
|
||||
menuItemIndicatorClassName,
|
||||
menuItemWithIndicatorClassName
|
||||
} from "../menu-surface";
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
children,
|
||||
align = "start",
|
||||
sideOffset = 4,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
asChild
|
||||
data-slot="dropdown-menu-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
{...props}
|
||||
>
|
||||
<MenuSurface
|
||||
data-slot="dropdown-menu-content"
|
||||
className={cn(
|
||||
"z-50 max-h-(--radix-dropdown-menu-content-available-height) w-(--radix-dropdown-menu-trigger-width) min-w-32 origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-popover)", ...style }}
|
||||
>
|
||||
{children}
|
||||
</MenuSurface>
|
||||
</DropdownMenuPrimitive.Content>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group
|
||||
data-slot="dropdown-menu-group"
|
||||
className={cn("flex flex-col gap-0.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-inset={inset}
|
||||
data-slot="dropdown-menu-item"
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"group/dropdown-menu-item",
|
||||
menuItemClassName,
|
||||
"data-inset:pl-7 data-[variant=destructive]:text-[var(--state-danger)] data-[variant=destructive]:focus:bg-[var(--on-danger-hover)] data-[variant=destructive]:focus:text-[var(--state-danger)] data-[variant=destructive]:hover:bg-[var(--on-danger-hover)] data-[variant=destructive]:hover:text-[var(--state-danger)] data-[variant=destructive]:*:[svg]:text-[var(--state-danger)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
checked={checked}
|
||||
data-inset={inset}
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
menuItemWithIndicatorClassName,
|
||||
"data-inset:pl-7 data-[state=checked]:[&_[data-slot=dropdown-menu-checkbox-item-indeterminate]]:hidden data-[state=indeterminate]:[&_[data-slot=dropdown-menu-checkbox-item-check]]:hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
className={menuItemIndicatorClassName}
|
||||
data-slot="dropdown-menu-checkbox-item-indicator"
|
||||
>
|
||||
<DropdownMenuPrimitive.ItemIndicator className="grid place-content-center text-[var(--tutti-purple)]">
|
||||
<CheckIcon data-slot="dropdown-menu-checkbox-item-check" />
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="h-0.5 w-2.5 rounded-full bg-current"
|
||||
data-slot="dropdown-menu-checkbox-item-indeterminate"
|
||||
/>
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
className={cn("flex flex-col gap-0.5", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-inset={inset}
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
menuItemWithIndicatorClassName,
|
||||
"data-inset:pl-7",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
className={menuItemIndicatorClassName}
|
||||
data-slot="dropdown-menu-radio-item-indicator"
|
||||
>
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="text-[var(--tutti-purple)]" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-inset={inset}
|
||||
data-slot="dropdown-menu-label"
|
||||
className={cn(
|
||||
"px-1.5 py-1 text-[11px] font-medium text-[var(--text-secondary)] data-inset:pl-7",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("mx-2 my-0.5 h-px bg-[var(--border-1)]", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-[11px] tracking-widest text-[var(--text-secondary)] group-focus/dropdown-menu-item:text-[var(--text-primary)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-inset={inset}
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
className={cn(
|
||||
menuItemClassName,
|
||||
"data-inset:pl-7 data-open:bg-[var(--transparency-block)] data-open:text-[var(--text-primary)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ArrowRightIcon className="ml-auto text-[var(--text-tertiary)]" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
asChild
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
{...props}
|
||||
>
|
||||
<MenuSurface
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"z-50 min-w-[96px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-popover)", ...style }}
|
||||
>
|
||||
{children}
|
||||
</MenuSurface>
|
||||
</DropdownMenuPrimitive.SubContent>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./dropdown-menu";
|
||||
@@ -0,0 +1,136 @@
|
||||
import {
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type ImgHTMLAttributes,
|
||||
type ReactNode
|
||||
} from "react";
|
||||
|
||||
const DEFAULT_RETRY_COUNT = 1;
|
||||
const DEFAULT_RETRY_DELAY_MS = 150;
|
||||
const MAX_RETRY_COUNT = 3;
|
||||
|
||||
interface ImageDeliveryState {
|
||||
attempt: number;
|
||||
phase: "ready" | "retrying" | "failed";
|
||||
src: string;
|
||||
}
|
||||
|
||||
export interface ImageWithFallbackProps extends Omit<
|
||||
ImgHTMLAttributes<HTMLImageElement>,
|
||||
"src"
|
||||
> {
|
||||
/** Content shown while retrying and after the retry budget is exhausted. */
|
||||
fallback?: ReactNode;
|
||||
/** Number of additional requests allowed after the first load failure. */
|
||||
retryCount?: number;
|
||||
/** Delay between bounded image requests. */
|
||||
retryDelayMs?: number;
|
||||
src?: string | null;
|
||||
}
|
||||
|
||||
function normalizeRetryCount(value: number): number {
|
||||
if (!Number.isFinite(value)) {
|
||||
return DEFAULT_RETRY_COUNT;
|
||||
}
|
||||
return Math.min(MAX_RETRY_COUNT, Math.max(0, Math.floor(value)));
|
||||
}
|
||||
|
||||
function normalizeRetryDelay(value: number): number {
|
||||
if (!Number.isFinite(value)) {
|
||||
return DEFAULT_RETRY_DELAY_MS;
|
||||
}
|
||||
return Math.max(0, Math.floor(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorative remote image with a bounded same-URL retry and caller-owned
|
||||
* fallback. Retrying remounts the image without mutating the URL, so signed
|
||||
* URLs remain valid and content-addressed URLs keep their cache identity.
|
||||
*/
|
||||
export function ImageWithFallback({
|
||||
fallback = null,
|
||||
onError,
|
||||
retryCount = DEFAULT_RETRY_COUNT,
|
||||
retryDelayMs = DEFAULT_RETRY_DELAY_MS,
|
||||
src,
|
||||
...imageProps
|
||||
}: ImageWithFallbackProps): React.JSX.Element | null {
|
||||
const normalizedSrc = src?.trim() ?? "";
|
||||
const maxRetries = normalizeRetryCount(retryCount);
|
||||
const delayMs = normalizeRetryDelay(retryDelayMs);
|
||||
const retryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [deliveryState, setDeliveryState] = useState<ImageDeliveryState>({
|
||||
attempt: 0,
|
||||
phase: "ready",
|
||||
src: normalizedSrc
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (deliveryState.src !== normalizedSrc) {
|
||||
setDeliveryState({ attempt: 0, phase: "ready", src: normalizedSrc });
|
||||
}
|
||||
if (retryTimerRef.current !== null) {
|
||||
clearTimeout(retryTimerRef.current);
|
||||
retryTimerRef.current = null;
|
||||
}
|
||||
}, [deliveryState.src, normalizedSrc]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (retryTimerRef.current !== null) {
|
||||
clearTimeout(retryTimerRef.current);
|
||||
}
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const currentState =
|
||||
deliveryState.src === normalizedSrc
|
||||
? deliveryState
|
||||
: { attempt: 0, phase: "ready" as const, src: normalizedSrc };
|
||||
|
||||
if (
|
||||
normalizedSrc.length === 0 ||
|
||||
currentState.phase === "failed" ||
|
||||
currentState.phase === "retrying"
|
||||
) {
|
||||
return <>{fallback}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
{...imageProps}
|
||||
key={`${normalizedSrc}:${currentState.attempt}`}
|
||||
src={normalizedSrc}
|
||||
onError={(event) => {
|
||||
onError?.(event);
|
||||
if (currentState.attempt >= maxRetries) {
|
||||
setDeliveryState((previous) =>
|
||||
previous.src === normalizedSrc
|
||||
? { ...previous, phase: "failed" }
|
||||
: previous
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const nextAttempt = currentState.attempt + 1;
|
||||
setDeliveryState((previous) =>
|
||||
previous.src === normalizedSrc
|
||||
? { attempt: nextAttempt, phase: "retrying", src: normalizedSrc }
|
||||
: previous
|
||||
);
|
||||
retryTimerRef.current = setTimeout(() => {
|
||||
retryTimerRef.current = null;
|
||||
setDeliveryState((previous) =>
|
||||
previous.src === normalizedSrc &&
|
||||
previous.attempt === nextAttempt &&
|
||||
previous.phase === "retrying"
|
||||
? { ...previous, phase: "ready" }
|
||||
: previous
|
||||
);
|
||||
}, delayMs);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export {
|
||||
ImageWithFallback,
|
||||
type ImageWithFallbackProps
|
||||
} from "./image-with-fallback";
|
||||
@@ -0,0 +1,37 @@
|
||||
export * from "./avatar";
|
||||
export * from "./badge";
|
||||
export * from "./bare-icon-button";
|
||||
export * from "./button";
|
||||
export * from "./card";
|
||||
export * from "./checkbox";
|
||||
export * from "./combobox";
|
||||
export * from "./confirmation-dialog";
|
||||
export * from "./context-menu/context-menu";
|
||||
export * from "./date-picker";
|
||||
export * from "./dialog";
|
||||
export * from "./drawer";
|
||||
export * from "./dropdown-menu";
|
||||
export * from "./input";
|
||||
export * from "./image-with-fallback";
|
||||
export * from "./mention-pill";
|
||||
export * from "./menu-surface";
|
||||
export * from "./popover";
|
||||
export * from "./radio-indicator";
|
||||
export * from "./resizable";
|
||||
export * from "./scroll-area";
|
||||
export * from "./select";
|
||||
export * from "./separator";
|
||||
export * from "./section-tabs";
|
||||
export * from "./segment-bar";
|
||||
export * from "./shortcut-badge";
|
||||
export * from "./slider";
|
||||
export * from "./sonner";
|
||||
export * from "./spinner";
|
||||
export * from "./sortable";
|
||||
export * from "./status-dot";
|
||||
export * from "./switch";
|
||||
export * from "./textarea";
|
||||
export * from "./toast";
|
||||
export * from "./tooltip";
|
||||
export * from "./underline-tabs";
|
||||
export * from "./viewport-menu-surface";
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./input";
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
type InputVariant = "lg" | "md" | "sm" | "otp";
|
||||
|
||||
type InputProps = Omit<React.ComponentProps<"input">, "size"> & {
|
||||
variant?: InputVariant;
|
||||
size?: "default" | "sm";
|
||||
};
|
||||
|
||||
const inputVariantClassNames: Record<InputVariant | "default", string> = {
|
||||
default: "h-8 rounded-md px-3 py-0 text-[13px] leading-[1.3]",
|
||||
lg: "h-12 rounded-[8px] px-4 py-3 text-[15px] leading-[1.3]",
|
||||
md: "h-8 rounded-md px-3 py-0 text-[13px] leading-[1.3]",
|
||||
sm: "h-8 rounded-md px-3 py-0 text-[13px] leading-[1.3]",
|
||||
otp: "h-12 w-12 rounded-[4px] px-0 text-center text-xl font-medium sm:h-14 sm:w-14 sm:text-2xl"
|
||||
};
|
||||
|
||||
function Input({
|
||||
className,
|
||||
size = "default",
|
||||
type,
|
||||
variant,
|
||||
...props
|
||||
}: InputProps) {
|
||||
const resolvedVariant = variant ?? (size === "sm" ? "sm" : "default");
|
||||
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
data-size={size}
|
||||
data-variant={resolvedVariant}
|
||||
className={cn(
|
||||
"w-full min-w-0 appearance-none border-0 bg-[var(--transparency-block)] font-normal text-[var(--text-primary)] shadow-none transition-colors duration-200 outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-[13px] file:font-medium file:text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)] hover:bg-[var(--transparency-hover)] focus:bg-[var(--transparency-hover)] focus-visible:border-0 focus-visible:bg-[var(--transparency-hover)] focus-visible:ring-0 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-[var(--transparency-block)] disabled:text-[var(--text-disabled)] disabled:opacity-100 aria-invalid:border-0 aria-invalid:bg-[var(--transparency-block)] aria-invalid:hover:bg-[var(--transparency-hover)] aria-invalid:focus:bg-[var(--transparency-hover)] aria-invalid:focus-visible:bg-[var(--transparency-hover)] aria-invalid:ring-0 aria-invalid:shadow-none",
|
||||
inputVariantClassNames[resolvedVariant],
|
||||
!variant && size === "sm" && "h-7 rounded-[4px] px-2 text-[11px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./mention-pill";
|
||||
export * from "./truncating-pill-label";
|
||||
@@ -0,0 +1,175 @@
|
||||
import * as React from "react";
|
||||
|
||||
import {
|
||||
AgentSessionsIcon,
|
||||
AppWindowIcon,
|
||||
CloseIcon,
|
||||
FileIcon,
|
||||
FolderFilledIcon,
|
||||
IssueIcon
|
||||
} from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
import { TruncatingPillLabel } from "./truncating-pill-label";
|
||||
|
||||
type MentionPillKind = "app" | "issue" | "session" | "file";
|
||||
type MentionPillFileKind = "file" | "folder";
|
||||
type MentionPillDataAttributes = {
|
||||
[key: `data-${string}`]: string | number | boolean | undefined;
|
||||
};
|
||||
|
||||
const mentionPillTokenByKind: Record<MentionPillKind, string> = {
|
||||
app: "var(--rich-text-folder)",
|
||||
issue: "var(--rich-text-mention-issue)",
|
||||
session: "var(--rich-text-mention-session)",
|
||||
file: "var(--folder)"
|
||||
};
|
||||
|
||||
const mentionPillDataKindByKind: Record<MentionPillKind, string> = {
|
||||
app: "app",
|
||||
issue: "task",
|
||||
session: "session",
|
||||
file: "file"
|
||||
};
|
||||
|
||||
export interface MentionPillProps extends Omit<
|
||||
React.ComponentProps<"span">,
|
||||
"children"
|
||||
> {
|
||||
fileKind?: MentionPillFileKind;
|
||||
iconUrl?: string | null;
|
||||
iconContainerProps?: React.ComponentProps<"span"> & MentionPillDataAttributes;
|
||||
fallbackIconProps?: React.SVGProps<SVGSVGElement> & MentionPillDataAttributes;
|
||||
kind: MentionPillKind;
|
||||
label: React.ReactNode;
|
||||
removable?: boolean;
|
||||
removeButtonProps?: React.ComponentProps<"button">;
|
||||
summary?: React.ReactNode;
|
||||
tooltipEnabled?: boolean;
|
||||
withTooltipProvider?: boolean;
|
||||
}
|
||||
|
||||
function MentionPill({
|
||||
className,
|
||||
fileKind = "file",
|
||||
iconUrl,
|
||||
iconContainerProps,
|
||||
fallbackIconProps,
|
||||
kind,
|
||||
label,
|
||||
removable = kind === "file",
|
||||
removeButtonProps,
|
||||
style,
|
||||
summary,
|
||||
tooltipEnabled = true,
|
||||
withTooltipProvider = true,
|
||||
...props
|
||||
}: MentionPillProps): React.JSX.Element {
|
||||
const isFile = kind === "file";
|
||||
const Icon = isFile
|
||||
? fileKind === "folder"
|
||||
? FolderFilledIcon
|
||||
: FileIcon
|
||||
: kind === "app"
|
||||
? AppWindowIcon
|
||||
: kind === "issue"
|
||||
? IssueIcon
|
||||
: AgentSessionsIcon;
|
||||
const color =
|
||||
isFile && fileKind === "folder"
|
||||
? "var(--folder)"
|
||||
: mentionPillTokenByKind[kind];
|
||||
const dataKind = mentionPillDataKindByKind[kind];
|
||||
const normalizedIconUrl = iconUrl?.trim() ?? "";
|
||||
const [failedIconUrl, setFailedIconUrl] = React.useState<string | null>(null);
|
||||
const iconSizeClassName = "size-4";
|
||||
// session mentions align their icon shell with the @agent (agent-target)
|
||||
// mention, which uses a 16px (size-4) shell; other non-file kinds keep 18px.
|
||||
const iconShellClassName =
|
||||
isFile || kind === "session" ? "size-4" : "size-[18px]";
|
||||
|
||||
// 超出最大展示宽度时,标签截断为省略号;溢出时 hover 弹设计系统 Tooltip 看完整文本。
|
||||
const tooltipText = [label, summary]
|
||||
.filter(
|
||||
(part): part is string => typeof part === "string" && part.trim() !== ""
|
||||
)
|
||||
.join(" ");
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"group relative top-[3px] inline-flex max-w-[min(100%,var(--agent-mention-max-width,16rem))] cursor-default items-center overflow-hidden rounded-[4px] border border-transparent bg-transparent py-0.5 align-baseline text-[13px] font-medium leading-5 no-underline transition-colors hover:border-transparent hover:bg-[color-mix(in_srgb,currentColor_12%,transparent)]",
|
||||
isFile ? "gap-1.5 px-1.5" : "gap-1 px-1",
|
||||
className
|
||||
)}
|
||||
data-agent-file-mention="true"
|
||||
data-agent-mention-kind={dataKind}
|
||||
data-slot="mention-pill"
|
||||
style={{
|
||||
color,
|
||||
...style
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
{...iconContainerProps}
|
||||
aria-hidden={removable ? undefined : true}
|
||||
className={cn(
|
||||
"relative grid shrink-0 place-items-center",
|
||||
iconShellClassName,
|
||||
iconContainerProps?.className
|
||||
)}
|
||||
>
|
||||
{normalizedIconUrl && failedIconUrl !== normalizedIconUrl ? (
|
||||
<img
|
||||
src={normalizedIconUrl}
|
||||
alt=""
|
||||
className={cn(
|
||||
"col-start-1 row-start-1 size-full rounded-[3px] object-cover transition-opacity",
|
||||
removable && "group-hover:opacity-0 group-focus-within:opacity-0"
|
||||
)}
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
draggable={false}
|
||||
onError={() => {
|
||||
setFailedIconUrl(normalizedIconUrl);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Icon
|
||||
{...fallbackIconProps}
|
||||
className={cn(
|
||||
"col-start-1 row-start-1 text-current transition-opacity",
|
||||
removable && "group-hover:opacity-0 group-focus-within:opacity-0",
|
||||
iconSizeClassName,
|
||||
fallbackIconProps?.className
|
||||
)}
|
||||
data-mention-pill-fallback-icon="true"
|
||||
/>
|
||||
)}
|
||||
{removable ? (
|
||||
<button
|
||||
aria-label={removeButtonProps?.["aria-label"]}
|
||||
type="button"
|
||||
{...removeButtonProps}
|
||||
className={cn(
|
||||
"absolute top-1/2 left-1/2 inline-flex size-5 -translate-x-1/2 -translate-y-1/2 items-center justify-center text-[var(--text-secondary)] opacity-0 transition-opacity group-hover:opacity-100 hover:text-[var(--text-primary)] focus-visible:opacity-100",
|
||||
removeButtonProps?.className
|
||||
)}
|
||||
>
|
||||
<CloseIcon className="size-3.5" />
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
<TruncatingPillLabel
|
||||
tooltip={tooltipEnabled ? tooltipText : ""}
|
||||
withTooltipProvider={withTooltipProvider}
|
||||
>
|
||||
<span>{label}</span>
|
||||
{summary ? <span className="text-current"> {summary}</span> : null}
|
||||
</TruncatingPillLabel>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export { MentionPill };
|
||||
export type { MentionPillFileKind, MentionPillKind };
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger
|
||||
} from "../tooltip/tooltip";
|
||||
|
||||
/**
|
||||
* 监测元素或指定后代是否因 overflow 被截断(scrollWidth > clientWidth)。
|
||||
* 返回要挂到「截断元素」上的 ref,以及是否正在溢出。随容器尺寸变化实时更新。
|
||||
*/
|
||||
export function useTextOverflow<T extends HTMLElement = HTMLElement>(
|
||||
watch: unknown,
|
||||
descendantSelector?: string
|
||||
): { ref: React.RefObject<T | null>; overflowing: boolean } {
|
||||
const ref = React.useRef<T>(null);
|
||||
const [overflowing, setOverflowing] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
const element = ref.current;
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
const overflowCandidates = (): HTMLElement[] => [
|
||||
element,
|
||||
...(descendantSelector
|
||||
? element.querySelectorAll<HTMLElement>(descendantSelector)
|
||||
: [])
|
||||
];
|
||||
const measure = (): void => {
|
||||
setOverflowing(
|
||||
overflowCandidates().some(
|
||||
(candidate) => candidate.scrollWidth - candidate.clientWidth > 1
|
||||
)
|
||||
);
|
||||
};
|
||||
measure();
|
||||
if (typeof ResizeObserver === "undefined") {
|
||||
return;
|
||||
}
|
||||
const observer = new ResizeObserver(measure);
|
||||
for (const candidate of overflowCandidates()) observer.observe(candidate);
|
||||
return () => observer.disconnect();
|
||||
}, [descendantSelector, watch]);
|
||||
|
||||
return { ref, overflowing };
|
||||
}
|
||||
|
||||
export interface TruncatingPillLabelProps {
|
||||
/** 完整文本;仅在标签被省略号截断时,通过 Tooltip 展示。 */
|
||||
tooltip: string;
|
||||
className?: string;
|
||||
children: React.ReactNode;
|
||||
withTooltipProvider?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* mention chip 的标签:省略号截断 + 「超出才显示」的设计系统 Tooltip。
|
||||
* 仅当实际溢出(scrollWidth > clientWidth)时,hover 才弹出完整文本,避免短标签也弹无意义 tooltip。
|
||||
* 依赖上层已挂载的 TooltipProvider(app 根已提供)。Trigger 始终包裹标签以保持 DOM 稳定,
|
||||
* 仅切换 TooltipContent 的渲染,从而 ResizeObserver 不会因重挂载而丢失。
|
||||
*/
|
||||
export function TruncatingPillLabel({
|
||||
tooltip,
|
||||
className,
|
||||
children,
|
||||
withTooltipProvider = true
|
||||
}: TruncatingPillLabelProps): React.JSX.Element {
|
||||
const { ref: labelRef, overflowing } =
|
||||
useTextOverflow<HTMLSpanElement>(tooltip);
|
||||
|
||||
const label = (
|
||||
<span
|
||||
ref={labelRef}
|
||||
className={cn(
|
||||
"min-w-0 overflow-hidden text-ellipsis whitespace-nowrap",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
|
||||
if (!tooltip) {
|
||||
return label;
|
||||
}
|
||||
|
||||
const tooltipElement = (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{label}</TooltipTrigger>
|
||||
{overflowing ? (
|
||||
<TooltipContent className="max-w-[min(420px,calc(100vw-32px))] whitespace-normal text-left [overflow-wrap:anywhere]">
|
||||
{tooltip}
|
||||
</TooltipContent>
|
||||
) : null}
|
||||
</Tooltip>
|
||||
);
|
||||
return withTooltipProvider ? (
|
||||
<TooltipProvider delayDuration={200}>{tooltipElement}</TooltipProvider>
|
||||
) : (
|
||||
tooltipElement
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./menu-surface";
|
||||
@@ -0,0 +1,51 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const menuSurfaceClassName =
|
||||
"t-dropdown flex flex-col gap-0.5 rounded-[8px] border border-[var(--border-1)] bg-[var(--background-fronted)] p-1 text-[13px] text-[var(--text-primary)] shadow-panel outline-none";
|
||||
const menuItemClassName =
|
||||
"relative flex cursor-pointer items-center gap-1.5 rounded-sm px-2 py-1 text-[13px] text-[var(--text-primary)] outline-hidden transition-colors duration-200 select-none hover:bg-[var(--transparency-hover)] hover:text-[var(--text-primary)] focus:bg-[var(--transparency-hover)] focus:text-[var(--text-primary)] data-[highlighted]:bg-[var(--transparency-hover)] data-[highlighted]:text-[var(--text-primary)] data-disabled:pointer-events-none data-disabled:text-[var(--text-disabled)] [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:min-w-0 *:[span]:last:flex-1 *:[span]:last:items-center *:[span]:last:gap-2";
|
||||
const menuItemWithIndicatorClassName = `${menuItemClassName} pr-8`;
|
||||
const menuItemIndicatorClassName =
|
||||
"pointer-events-none absolute right-2 flex size-4 items-center justify-center text-[var(--tutti-purple)]";
|
||||
|
||||
type MenuSurfaceProps = React.HTMLAttributes<HTMLDivElement> & {
|
||||
"data-state"?: "open" | "closed";
|
||||
asChild?: boolean;
|
||||
state?: "open" | "closed";
|
||||
};
|
||||
|
||||
const MenuSurface = React.forwardRef<HTMLDivElement, MenuSurfaceProps>(
|
||||
(
|
||||
{
|
||||
asChild = false,
|
||||
className,
|
||||
"data-state": dataState,
|
||||
state = "open",
|
||||
...props
|
||||
},
|
||||
ref
|
||||
) => {
|
||||
const Comp = asChild ? Slot.Root : "div";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
{...props}
|
||||
ref={ref}
|
||||
className={cn(menuSurfaceClassName, className)}
|
||||
data-state={dataState ?? state}
|
||||
/>
|
||||
);
|
||||
}
|
||||
);
|
||||
MenuSurface.displayName = "MenuSurface";
|
||||
|
||||
export {
|
||||
MenuSurface,
|
||||
menuItemClassName,
|
||||
menuItemIndicatorClassName,
|
||||
menuItemWithIndicatorClassName,
|
||||
menuSurfaceClassName
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./popover";
|
||||
@@ -0,0 +1,66 @@
|
||||
import * as React from "react";
|
||||
import { Popover as PopoverPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Portal>) {
|
||||
return <PopoverPrimitive.Portal data-slot="popover-portal" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Close>) {
|
||||
return <PopoverPrimitive.Close data-slot="popover-close" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPortal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"t-dropdown z-50 flex w-72 origin-(--radix-popover-content-transform-origin) flex-col gap-2.5 rounded-lg border border-[var(--border-1)] bg-[var(--background-fronted)] p-3 text-[13px] text-popover-foreground shadow-soft outline-hidden",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-popover)" }}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
||||
}
|
||||
|
||||
export {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverClose,
|
||||
PopoverContent,
|
||||
PopoverPortal,
|
||||
PopoverTrigger
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./radio-indicator";
|
||||
@@ -0,0 +1,40 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
type RadioIndicatorProps = React.ComponentProps<"span"> & {
|
||||
checked?: boolean;
|
||||
disabled?: boolean;
|
||||
};
|
||||
|
||||
function RadioIndicator({
|
||||
checked = false,
|
||||
disabled = false,
|
||||
className,
|
||||
...props
|
||||
}: RadioIndicatorProps) {
|
||||
return (
|
||||
<span
|
||||
{...props}
|
||||
aria-hidden={props["aria-hidden"] ?? true}
|
||||
data-checked={checked || undefined}
|
||||
data-disabled={disabled || undefined}
|
||||
data-slot="radio-indicator"
|
||||
data-state={checked ? "checked" : "unchecked"}
|
||||
className={cn(
|
||||
"inline-flex size-4 shrink-0 items-center justify-center rounded-full border-2 border-[var(--border-1)] bg-transparent transition-[border-color,background-color,box-shadow] data-[state=checked]:border-[var(--tutti-purple)] data-[state=unchecked]:hover:border-[color-mix(in_srgb,var(--text-primary)_40%,transparent)] data-disabled:cursor-not-allowed data-disabled:opacity-60",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{checked ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="size-2 rounded-full bg-[var(--tutti-purple)]"
|
||||
/>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export { RadioIndicator };
|
||||
export type { RadioIndicatorProps };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./resizable";
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as ResizablePrimitive from "react-resizable-panels";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Group>) {
|
||||
return (
|
||||
<ResizablePrimitive.Group
|
||||
data-orientation={orientation}
|
||||
data-slot="resizable-panel-group"
|
||||
className={cn(
|
||||
"flex h-full w-full data-[orientation=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
orientation={orientation}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ResizablePanel(
|
||||
props: React.ComponentProps<typeof ResizablePrimitive.Panel>
|
||||
) {
|
||||
return <ResizablePrimitive.Panel data-slot="resizable-panel" {...props} />;
|
||||
}
|
||||
|
||||
function ResizableHandle({
|
||||
className,
|
||||
withHandle,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ResizablePrimitive.Separator> & {
|
||||
withHandle?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<ResizablePrimitive.Separator
|
||||
data-slot="resizable-handle"
|
||||
className={cn(
|
||||
"group relative flex items-center justify-center bg-transparent outline-none after:absolute after:bg-border/70 after:transition-colors hover:after:bg-border focus-visible:after:bg-ring aria-[orientation=horizontal]:h-px aria-[orientation=horizontal]:w-full aria-[orientation=horizontal]:cursor-row-resize aria-[orientation=horizontal]:after:inset-x-0 aria-[orientation=horizontal]:after:top-1/2 aria-[orientation=horizontal]:after:h-px aria-[orientation=horizontal]:after:-translate-y-1/2 aria-[orientation=vertical]:h-full aria-[orientation=vertical]:w-px aria-[orientation=vertical]:cursor-col-resize aria-[orientation=vertical]:after:inset-y-0 aria-[orientation=vertical]:after:left-1/2 aria-[orientation=vertical]:after:w-px aria-[orientation=vertical]:after:-translate-x-1/2",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{withHandle ? (
|
||||
<div className="z-10 flex items-center justify-center rounded-full bg-border/85 opacity-0 transition-[background-color,opacity] group-hover:bg-border group-hover:opacity-100 group-focus-visible:bg-border group-focus-visible:opacity-100 group-aria-[orientation=horizontal]:h-[3px] group-aria-[orientation=horizontal]:w-10 group-aria-[orientation=vertical]:h-10 group-aria-[orientation=vertical]:w-[3px]" />
|
||||
) : null}
|
||||
</ResizablePrimitive.Separator>
|
||||
);
|
||||
}
|
||||
|
||||
export { ResizableHandle, ResizablePanel, ResizablePanelGroup };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./scroll-area";
|
||||
@@ -0,0 +1,742 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const MIN_THUMB_SIZE_PX = 24;
|
||||
|
||||
type ScrollAreaType = "auto" | "always" | "scroll" | "hover";
|
||||
type ScrollAreaOrientation = "vertical" | "horizontal";
|
||||
|
||||
type ScrollAreaProps = React.HTMLAttributes<HTMLDivElement> & {
|
||||
scrollbarMode?: "custom" | "native";
|
||||
scrollHideDelay?: number;
|
||||
type?: ScrollAreaType;
|
||||
viewportClassName?: string;
|
||||
/** Receives the element that directly wraps children inside the viewport. */
|
||||
viewportContentRef?: React.Ref<HTMLDivElement>;
|
||||
viewportContentStyle?: React.CSSProperties;
|
||||
viewportProps?: Omit<
|
||||
React.ComponentPropsWithoutRef<"div">,
|
||||
"children" | "className" | "ref"
|
||||
>;
|
||||
viewportRef?: React.Ref<HTMLDivElement>;
|
||||
viewportTestId?: string;
|
||||
};
|
||||
|
||||
type ScrollBarProps = React.HTMLAttributes<HTMLDivElement> & {
|
||||
forceMount?: true;
|
||||
orientation?: ScrollAreaOrientation;
|
||||
};
|
||||
|
||||
type ScrollAreaImplementationProps = Omit<
|
||||
ScrollAreaProps,
|
||||
"scrollbarMode" | "scrollHideDelay"
|
||||
> & {
|
||||
scrollbarMode: NonNullable<ScrollAreaProps["scrollbarMode"]>;
|
||||
};
|
||||
|
||||
type ScrollbarDragState = {
|
||||
maxScrollOffset: number;
|
||||
maxThumbOffset: number;
|
||||
startClientOffset: number;
|
||||
startScrollOffset: number;
|
||||
};
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
onBlur,
|
||||
onFocus,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
scrollbarMode = "custom",
|
||||
scrollHideDelay: _scrollHideDelay,
|
||||
type,
|
||||
viewportClassName,
|
||||
viewportContentRef,
|
||||
viewportContentStyle,
|
||||
viewportProps,
|
||||
viewportRef,
|
||||
viewportTestId,
|
||||
...props
|
||||
}: ScrollAreaProps) {
|
||||
const implementationProps = {
|
||||
className,
|
||||
onBlur,
|
||||
onFocus,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
scrollbarMode,
|
||||
type,
|
||||
viewportClassName,
|
||||
viewportContentRef,
|
||||
viewportContentStyle,
|
||||
viewportProps,
|
||||
viewportRef,
|
||||
viewportTestId,
|
||||
...props
|
||||
} satisfies ScrollAreaImplementationProps;
|
||||
|
||||
if (scrollbarMode === "native") {
|
||||
return (
|
||||
<NativeScrollArea {...implementationProps}>{children}</NativeScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CustomScrollArea {...implementationProps}>{children}</CustomScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
function NativeScrollArea({
|
||||
className,
|
||||
children,
|
||||
onBlur,
|
||||
onFocus,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
scrollbarMode,
|
||||
type,
|
||||
viewportClassName,
|
||||
viewportContentRef,
|
||||
viewportContentStyle,
|
||||
viewportProps,
|
||||
viewportRef,
|
||||
viewportTestId,
|
||||
...props
|
||||
}: ScrollAreaImplementationProps) {
|
||||
const alwaysVisible =
|
||||
type === "always" ||
|
||||
type === "scroll" ||
|
||||
hasAlwaysVisibleScrollbarSelector(className);
|
||||
|
||||
return (
|
||||
<ScrollAreaFrame
|
||||
{...props}
|
||||
className={className}
|
||||
data-scrollbar-mode={scrollbarMode}
|
||||
onBlur={onBlur}
|
||||
onFocus={onFocus}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
alwaysVisible={false}
|
||||
contentRef={viewportContentRef}
|
||||
viewportClassName={cn(
|
||||
nativeScrollbarClassName(alwaysVisible),
|
||||
viewportClassName
|
||||
)}
|
||||
viewportContentStyle={viewportContentStyle}
|
||||
viewportProps={viewportProps}
|
||||
viewportRef={viewportRef}
|
||||
viewportTestId={viewportTestId}
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaFrame>
|
||||
);
|
||||
}
|
||||
|
||||
function CustomScrollArea({
|
||||
className,
|
||||
children,
|
||||
onBlur,
|
||||
onFocus,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
scrollbarMode,
|
||||
type,
|
||||
viewportClassName,
|
||||
viewportContentRef,
|
||||
viewportContentStyle,
|
||||
viewportProps,
|
||||
viewportRef,
|
||||
viewportTestId,
|
||||
...props
|
||||
}: ScrollAreaImplementationProps) {
|
||||
const localViewportRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const contentRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const [active, setActive] = React.useState(false);
|
||||
|
||||
const alwaysVisible =
|
||||
type === "always" ||
|
||||
type === "scroll" ||
|
||||
hasAlwaysVisibleScrollbarSelector(className);
|
||||
|
||||
return (
|
||||
<ScrollAreaFrame
|
||||
{...props}
|
||||
className={className}
|
||||
contentRef={setRefs(contentRef, viewportContentRef)}
|
||||
data-scrollbar-mode={scrollbarMode}
|
||||
onBlur={(event) => {
|
||||
onBlur?.(event);
|
||||
if (!event.currentTarget.contains(event.relatedTarget)) {
|
||||
setActive(false);
|
||||
}
|
||||
}}
|
||||
onFocus={(event) => {
|
||||
onFocus?.(event);
|
||||
setActive(true);
|
||||
}}
|
||||
onMouseEnter={(event) => {
|
||||
onMouseEnter?.(event);
|
||||
setActive(true);
|
||||
}}
|
||||
onMouseLeave={(event) => {
|
||||
onMouseLeave?.(event);
|
||||
setActive(false);
|
||||
}}
|
||||
alwaysVisible={alwaysVisible}
|
||||
viewportClassName={cn(
|
||||
"[scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
|
||||
viewportClassName
|
||||
)}
|
||||
viewportContentStyle={viewportContentStyle}
|
||||
viewportProps={viewportProps}
|
||||
viewportRef={setRefs(localViewportRef, viewportRef)}
|
||||
viewportTestId={viewportTestId}
|
||||
>
|
||||
{children}
|
||||
<ScrollAreaScrollbar
|
||||
active={active || alwaysVisible}
|
||||
contentRef={contentRef}
|
||||
orientation="vertical"
|
||||
viewportRef={localViewportRef}
|
||||
/>
|
||||
</ScrollAreaFrame>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollAreaFrame({
|
||||
alwaysVisible,
|
||||
children,
|
||||
className,
|
||||
contentRef,
|
||||
viewportClassName,
|
||||
viewportContentStyle,
|
||||
viewportProps,
|
||||
viewportRef,
|
||||
viewportTestId,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement> & {
|
||||
alwaysVisible: boolean;
|
||||
contentRef?: React.Ref<HTMLDivElement>;
|
||||
viewportClassName?: string;
|
||||
viewportContentStyle?: React.CSSProperties;
|
||||
viewportProps?: ScrollAreaProps["viewportProps"];
|
||||
viewportRef?: React.Ref<HTMLDivElement>;
|
||||
viewportTestId?: string;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="scroll-area"
|
||||
className={cn(
|
||||
"group/scroll-area relative",
|
||||
alwaysVisible
|
||||
? "[&_[data-slot=scroll-area-scrollbar]]:opacity-100"
|
||||
: null,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
{...viewportProps}
|
||||
data-slot="scroll-area-viewport"
|
||||
data-testid={viewportTestId}
|
||||
ref={viewportRef}
|
||||
className={cn(
|
||||
"size-full overflow-auto rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1",
|
||||
viewportClassName
|
||||
)}
|
||||
>
|
||||
<div
|
||||
ref={contentRef}
|
||||
data-slot="scroll-area-content"
|
||||
style={{
|
||||
minWidth: "100%",
|
||||
display: "block",
|
||||
...viewportContentStyle
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollAreaScrollbar({
|
||||
active,
|
||||
contentRef,
|
||||
orientation,
|
||||
viewportRef
|
||||
}: {
|
||||
active: boolean;
|
||||
contentRef: React.RefObject<HTMLElement | null>;
|
||||
orientation: ScrollAreaOrientation;
|
||||
viewportRef: React.RefObject<HTMLElement | null>;
|
||||
}) {
|
||||
const trackRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const thumbRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const dragStateRef = React.useRef<ScrollbarDragState | null>(null);
|
||||
const frameRef = React.useRef<number | null>(null);
|
||||
const scrollableRef = React.useRef(false);
|
||||
const [dragging, setDragging] = React.useState(false);
|
||||
const [scrollable, setScrollable] = React.useState(false);
|
||||
const [trackActive, setTrackActive] = React.useState(false);
|
||||
|
||||
const syncScrollbarState = React.useCallback(() => {
|
||||
const viewport = viewportRef.current;
|
||||
const track = trackRef.current;
|
||||
const thumb = thumbRef.current;
|
||||
if (!viewport || !track || !thumb) {
|
||||
updateScrollable(false, scrollableRef, setScrollable);
|
||||
return;
|
||||
}
|
||||
|
||||
const viewportSize =
|
||||
orientation === "vertical" ? viewport.clientHeight : viewport.clientWidth;
|
||||
const scrollSize =
|
||||
orientation === "vertical" ? viewport.scrollHeight : viewport.scrollWidth;
|
||||
const scrollOffset =
|
||||
orientation === "vertical" ? viewport.scrollTop : viewport.scrollLeft;
|
||||
const trackSize =
|
||||
orientation === "vertical" ? track.clientHeight : track.clientWidth;
|
||||
const maxScrollOffset = Math.max(0, scrollSize - viewportSize);
|
||||
if (viewportSize <= 0 || trackSize <= 0 || maxScrollOffset <= 0) {
|
||||
updateScrollable(false, scrollableRef, setScrollable);
|
||||
return;
|
||||
}
|
||||
|
||||
const thumbSize = Math.min(
|
||||
trackSize,
|
||||
Math.max(
|
||||
MIN_THUMB_SIZE_PX,
|
||||
Math.round((viewportSize / scrollSize) * trackSize)
|
||||
)
|
||||
);
|
||||
const maxThumbOffset = Math.max(0, trackSize - thumbSize);
|
||||
const thumbOffset = Math.round(
|
||||
(scrollOffset / maxScrollOffset) * maxThumbOffset
|
||||
);
|
||||
|
||||
if (orientation === "vertical") {
|
||||
thumb.style.height = `${thumbSize}px`;
|
||||
thumb.style.width = "";
|
||||
thumb.style.transform = `translateY(${thumbOffset}px)`;
|
||||
} else {
|
||||
thumb.style.width = `${thumbSize}px`;
|
||||
thumb.style.height = "";
|
||||
thumb.style.transform = `translateX(${thumbOffset}px)`;
|
||||
}
|
||||
|
||||
updateScrollable(true, scrollableRef, setScrollable);
|
||||
}, [orientation, viewportRef]);
|
||||
|
||||
const scheduleSync = React.useCallback(() => {
|
||||
if (frameRef.current !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
frameRef.current = requestAnimationFrameSafely(() => {
|
||||
frameRef.current = null;
|
||||
syncScrollbarState();
|
||||
});
|
||||
}, [syncScrollbarState]);
|
||||
|
||||
const scrollViewportToThumbOffset = React.useCallback(
|
||||
(thumbOffset: number) => {
|
||||
const viewport = viewportRef.current;
|
||||
const track = trackRef.current;
|
||||
const thumb = thumbRef.current;
|
||||
if (!viewport || !track || !thumb) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewportSize =
|
||||
orientation === "vertical"
|
||||
? viewport.clientHeight
|
||||
: viewport.clientWidth;
|
||||
const scrollSize =
|
||||
orientation === "vertical"
|
||||
? viewport.scrollHeight
|
||||
: viewport.scrollWidth;
|
||||
const trackSize =
|
||||
orientation === "vertical" ? track.clientHeight : track.clientWidth;
|
||||
const thumbSize =
|
||||
orientation === "vertical" ? thumb.offsetHeight : thumb.offsetWidth;
|
||||
const maxScrollOffset = Math.max(0, scrollSize - viewportSize);
|
||||
const maxThumbOffset = Math.max(0, trackSize - thumbSize);
|
||||
if (maxScrollOffset <= 0 || maxThumbOffset <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextScrollOffset =
|
||||
(clamp(thumbOffset, 0, maxThumbOffset) / maxThumbOffset) *
|
||||
maxScrollOffset;
|
||||
if (orientation === "vertical") {
|
||||
viewport.scrollTop = nextScrollOffset;
|
||||
} else {
|
||||
viewport.scrollLeft = nextScrollOffset;
|
||||
}
|
||||
syncScrollbarState();
|
||||
},
|
||||
[orientation, syncScrollbarState, viewportRef]
|
||||
);
|
||||
|
||||
const handleTrackPointerDown = React.useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0 || !scrollableRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const track = trackRef.current;
|
||||
const thumb = thumbRef.current;
|
||||
if (!track || !thumb || event.target === thumb) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const trackRect = track.getBoundingClientRect();
|
||||
const clientOffset =
|
||||
orientation === "vertical" ? event.clientY : event.clientX;
|
||||
const trackStart =
|
||||
orientation === "vertical" ? trackRect.top : trackRect.left;
|
||||
const thumbSize =
|
||||
orientation === "vertical" ? thumb.offsetHeight : thumb.offsetWidth;
|
||||
scrollViewportToThumbOffset(clientOffset - trackStart - thumbSize / 2);
|
||||
},
|
||||
[orientation, scrollViewportToThumbOffset]
|
||||
);
|
||||
|
||||
const handleThumbPointerDown = React.useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0 || !scrollableRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewport = viewportRef.current;
|
||||
const track = trackRef.current;
|
||||
const thumb = thumbRef.current;
|
||||
if (!viewport || !track || !thumb) {
|
||||
return;
|
||||
}
|
||||
|
||||
const viewportSize =
|
||||
orientation === "vertical"
|
||||
? viewport.clientHeight
|
||||
: viewport.clientWidth;
|
||||
const scrollSize =
|
||||
orientation === "vertical"
|
||||
? viewport.scrollHeight
|
||||
: viewport.scrollWidth;
|
||||
const trackSize =
|
||||
orientation === "vertical" ? track.clientHeight : track.clientWidth;
|
||||
const thumbSize =
|
||||
orientation === "vertical" ? thumb.offsetHeight : thumb.offsetWidth;
|
||||
const maxScrollOffset = Math.max(0, scrollSize - viewportSize);
|
||||
const maxThumbOffset = Math.max(0, trackSize - thumbSize);
|
||||
if (maxScrollOffset <= 0 || maxThumbOffset <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
dragStateRef.current = {
|
||||
maxScrollOffset,
|
||||
maxThumbOffset,
|
||||
startClientOffset:
|
||||
orientation === "vertical" ? event.clientY : event.clientX,
|
||||
startScrollOffset:
|
||||
orientation === "vertical" ? viewport.scrollTop : viewport.scrollLeft
|
||||
};
|
||||
setDragging(true);
|
||||
},
|
||||
[orientation, viewportRef]
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!dragging) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handlePointerMove = (event: PointerEvent): void => {
|
||||
const dragState = dragStateRef.current;
|
||||
const viewport = viewportRef.current;
|
||||
if (!dragState || !viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
const clientOffset =
|
||||
orientation === "vertical" ? event.clientY : event.clientX;
|
||||
const nextThumbOffset =
|
||||
(dragState.startScrollOffset / dragState.maxScrollOffset) *
|
||||
dragState.maxThumbOffset +
|
||||
(clientOffset - dragState.startClientOffset);
|
||||
const nextScrollOffset =
|
||||
(clamp(nextThumbOffset, 0, dragState.maxThumbOffset) /
|
||||
dragState.maxThumbOffset) *
|
||||
dragState.maxScrollOffset;
|
||||
|
||||
if (orientation === "vertical") {
|
||||
viewport.scrollTop = nextScrollOffset;
|
||||
} else {
|
||||
viewport.scrollLeft = nextScrollOffset;
|
||||
}
|
||||
syncScrollbarState();
|
||||
};
|
||||
|
||||
const handlePointerUp = (): void => {
|
||||
dragStateRef.current = null;
|
||||
setDragging(false);
|
||||
};
|
||||
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
return () => {
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
};
|
||||
}, [dragging, orientation, syncScrollbarState, viewportRef]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) {
|
||||
updateScrollable(false, scrollableRef, setScrollable);
|
||||
return;
|
||||
}
|
||||
|
||||
syncScrollbarState();
|
||||
viewport.addEventListener("scroll", scheduleSync, { passive: true });
|
||||
|
||||
const resizeObserver =
|
||||
typeof ResizeObserver !== "undefined"
|
||||
? new ResizeObserver(scheduleSync)
|
||||
: null;
|
||||
resizeObserver?.observe(viewport);
|
||||
if (contentRef.current) {
|
||||
resizeObserver?.observe(contentRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (frameRef.current !== null) {
|
||||
cancelAnimationFrameSafely(frameRef.current);
|
||||
frameRef.current = null;
|
||||
}
|
||||
viewport.removeEventListener("scroll", scheduleSync);
|
||||
resizeObserver?.disconnect();
|
||||
};
|
||||
}, [contentRef, scheduleSync, syncScrollbarState, viewportRef]);
|
||||
|
||||
React.useEffect(() => {
|
||||
scheduleSync();
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={trackRef}
|
||||
data-dragging={dragging ? "true" : "false"}
|
||||
data-orientation={orientation}
|
||||
data-scrollable={scrollable ? "true" : "false"}
|
||||
data-slot="scroll-area-scrollbar"
|
||||
aria-hidden="true"
|
||||
className={scrollbarClassName(orientation)}
|
||||
style={scrollbarStyle({
|
||||
active: active || dragging,
|
||||
orientation,
|
||||
scrollable
|
||||
})}
|
||||
onPointerEnter={() => setTrackActive(true)}
|
||||
onPointerLeave={() => setTrackActive(false)}
|
||||
onPointerDown={handleTrackPointerDown}
|
||||
>
|
||||
<div
|
||||
ref={thumbRef}
|
||||
data-slot="scroll-area-thumb"
|
||||
className={thumbClassName(orientation)}
|
||||
style={thumbStyle({ active: trackActive || dragging, orientation })}
|
||||
onPointerDown={handleThumbPointerDown}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
forceMount: _forceMount,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: ScrollBarProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="scroll-area-scrollbar"
|
||||
data-orientation={orientation}
|
||||
className={cn(scrollbarClassName(orientation), className)}
|
||||
style={scrollbarStyle({ active: false, orientation, scrollable: true })}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
data-slot="scroll-area-thumb"
|
||||
className={thumbClassName(orientation)}
|
||||
style={thumbStyle({ active: false, orientation })}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function scrollbarClassName(orientation: ScrollAreaOrientation): string {
|
||||
return cn(
|
||||
orientation === "horizontal"
|
||||
? "data-[orientation=horizontal]:h-2"
|
||||
: "data-[orientation=vertical]:w-2"
|
||||
);
|
||||
}
|
||||
|
||||
function thumbClassName(orientation: ScrollAreaOrientation): string {
|
||||
return cn(
|
||||
"rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-[2px] bottom-[2px]"
|
||||
: "right-[2px] left-[2px]"
|
||||
);
|
||||
}
|
||||
|
||||
function nativeScrollbarClassName(alwaysVisible: boolean): string {
|
||||
return cn(
|
||||
"[scrollbar-width:thin] [scrollbar-color:transparent_transparent]",
|
||||
"[&::-webkit-scrollbar]:block [&::-webkit-scrollbar]:h-2 [&::-webkit-scrollbar]:w-2",
|
||||
"[&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-track]:bg-transparent",
|
||||
"[&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:border-2 [&::-webkit-scrollbar-thumb]:border-solid [&::-webkit-scrollbar-thumb]:border-transparent [&::-webkit-scrollbar-thumb]:bg-clip-content",
|
||||
alwaysVisible
|
||||
? "[scrollbar-color:var(--transparency-block)_transparent] [&::-webkit-scrollbar-thumb]:bg-[var(--transparency-block)] hover:[&::-webkit-scrollbar-thumb]:bg-[var(--transparency-hover)]"
|
||||
: "hover:[scrollbar-color:var(--transparency-block)_transparent] focus-within:[scrollbar-color:var(--transparency-block)_transparent] hover:[&::-webkit-scrollbar-thumb]:bg-[var(--transparency-block)] focus-within:[&::-webkit-scrollbar-thumb]:bg-[var(--transparency-block)]"
|
||||
);
|
||||
}
|
||||
|
||||
function scrollbarStyle({
|
||||
active,
|
||||
orientation,
|
||||
scrollable
|
||||
}: {
|
||||
active: boolean;
|
||||
orientation: ScrollAreaOrientation;
|
||||
scrollable: boolean;
|
||||
}): React.CSSProperties {
|
||||
return {
|
||||
position: "absolute",
|
||||
zIndex: 10,
|
||||
display: "flex",
|
||||
touchAction: "none",
|
||||
padding: 2,
|
||||
opacity: active && scrollable ? 1 : 0,
|
||||
pointerEvents: scrollable ? "auto" : "none",
|
||||
userSelect: "none",
|
||||
transition: "opacity 150ms ease-in-out",
|
||||
cursor: "pointer",
|
||||
...(orientation === "horizontal"
|
||||
? {
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
height: 8,
|
||||
flexDirection: "column"
|
||||
}
|
||||
: {
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
width: 8
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function thumbStyle({
|
||||
active,
|
||||
orientation
|
||||
}: {
|
||||
active: boolean;
|
||||
orientation: ScrollAreaOrientation;
|
||||
}): React.CSSProperties {
|
||||
return {
|
||||
position: "absolute",
|
||||
minHeight: orientation === "vertical" ? MIN_THUMB_SIZE_PX : undefined,
|
||||
minWidth: orientation === "horizontal" ? MIN_THUMB_SIZE_PX : undefined,
|
||||
borderRadius: 999,
|
||||
background: active
|
||||
? "var(--transparency-hover)"
|
||||
: "var(--transparency-block)",
|
||||
cursor: active ? "grabbing" : "grab",
|
||||
transition: "background-color 150ms ease-in-out",
|
||||
...(orientation === "horizontal"
|
||||
? {
|
||||
top: 2,
|
||||
bottom: 2
|
||||
}
|
||||
: {
|
||||
right: 2,
|
||||
left: 2
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function hasAlwaysVisibleScrollbarSelector(
|
||||
className: ScrollAreaProps["className"]
|
||||
): boolean {
|
||||
return (
|
||||
typeof className === "string" &&
|
||||
className.includes("scroll-area-scrollbar") &&
|
||||
className.includes("opacity-100")
|
||||
);
|
||||
}
|
||||
|
||||
function setRefs<T>(
|
||||
localRef: React.MutableRefObject<T | null>,
|
||||
forwardedRef: React.Ref<T> | undefined
|
||||
): (node: T | null) => void {
|
||||
return (node) => {
|
||||
localRef.current = node;
|
||||
if (typeof forwardedRef === "function") {
|
||||
forwardedRef(node);
|
||||
} else if (forwardedRef) {
|
||||
forwardedRef.current = node;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function updateScrollable(
|
||||
nextScrollable: boolean,
|
||||
scrollableRef: React.MutableRefObject<boolean>,
|
||||
setScrollable: React.Dispatch<React.SetStateAction<boolean>>
|
||||
): void {
|
||||
if (scrollableRef.current === nextScrollable) {
|
||||
return;
|
||||
}
|
||||
|
||||
scrollableRef.current = nextScrollable;
|
||||
setScrollable(nextScrollable);
|
||||
}
|
||||
|
||||
function requestAnimationFrameSafely(callback: FrameRequestCallback): number {
|
||||
if (typeof window.requestAnimationFrame === "function") {
|
||||
return window.requestAnimationFrame(callback);
|
||||
}
|
||||
|
||||
return window.setTimeout(() => callback(performance.now()), 16);
|
||||
}
|
||||
|
||||
function cancelAnimationFrameSafely(frameId: number): void {
|
||||
if (typeof window.cancelAnimationFrame === "function") {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
return;
|
||||
}
|
||||
|
||||
window.clearTimeout(frameId);
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./section-tabs";
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { JSX, ReactNode } from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
export interface SectionTabItem<TValue extends string> {
|
||||
value: TValue;
|
||||
label: ReactNode;
|
||||
count?: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
interface SectionTabsProps<TValue extends string> {
|
||||
tabs: ReadonlyArray<SectionTabItem<TValue>>;
|
||||
value: TValue;
|
||||
onValueChange: (value: TValue) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function SectionTabs<TValue extends string>({
|
||||
tabs,
|
||||
value,
|
||||
onValueChange,
|
||||
ariaLabel,
|
||||
className,
|
||||
testId
|
||||
}: SectionTabsProps<TValue>): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
aria-label={ariaLabel}
|
||||
className={cn("flex min-w-0 items-center gap-5", className)}
|
||||
data-slot="section-tabs"
|
||||
data-testid={testId}
|
||||
role="tablist"
|
||||
>
|
||||
{tabs.map((tab) => {
|
||||
const isActive = value === tab.value;
|
||||
return (
|
||||
<button
|
||||
key={tab.value}
|
||||
aria-selected={isActive}
|
||||
className={cn(
|
||||
"relative inline-flex h-5 shrink-0 items-center gap-1.5 whitespace-nowrap border-0 bg-transparent p-0 text-[15px] font-semibold leading-5 tracking-[0] text-[var(--text-secondary)] transition-colors duration-150 hover:text-[var(--text-primary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--border-focus)]",
|
||||
isActive && "text-[var(--text-primary)]"
|
||||
)}
|
||||
data-active={isActive ? "true" : "false"}
|
||||
data-slot="section-tabs-tab"
|
||||
data-testid={tab.testId}
|
||||
role="tab"
|
||||
type="button"
|
||||
onClick={() => onValueChange(tab.value)}
|
||||
>
|
||||
<span className="min-w-0 truncate">{tab.label}</span>
|
||||
{tab.count !== undefined ? (
|
||||
<span className="text-[15px] font-semibold leading-5 text-[inherit]">
|
||||
{tab.count}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { SectionTabs };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./segment-bar";
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { JSX, ReactNode } from "react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
export interface SegmentBarItem<TValue extends string> {
|
||||
value: TValue;
|
||||
label: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
interface SegmentBarProps<TValue extends string> {
|
||||
segments: ReadonlyArray<SegmentBarItem<TValue>>;
|
||||
value: TValue;
|
||||
onValueChange: (value: TValue) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Segmented control with a sliding active pill. Generic over the segment
|
||||
* value type so callers stay type-safe for any number of segments.
|
||||
*/
|
||||
function SegmentBar<TValue extends string>({
|
||||
segments,
|
||||
value,
|
||||
onValueChange,
|
||||
ariaLabel,
|
||||
className,
|
||||
testId
|
||||
}: SegmentBarProps<TValue>): JSX.Element {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRefs = useRef<Partial<Record<TValue, HTMLButtonElement>>>({});
|
||||
const [indicator, setIndicator] = useState({
|
||||
left: 0,
|
||||
width: 0,
|
||||
ready: false
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const button = buttonRefs.current[value];
|
||||
if (!button) {
|
||||
setIndicator((current) =>
|
||||
current.ready ? current : { ...current, ready: false }
|
||||
);
|
||||
return;
|
||||
}
|
||||
const next = {
|
||||
left: button.offsetLeft,
|
||||
width: button.offsetWidth,
|
||||
ready: true
|
||||
};
|
||||
setIndicator((current) =>
|
||||
current.left === next.left &&
|
||||
current.width === next.width &&
|
||||
current.ready === next.ready
|
||||
? current
|
||||
: next
|
||||
);
|
||||
}, [segments, value]);
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container || typeof ResizeObserver === "undefined") {
|
||||
return;
|
||||
}
|
||||
const sync = (): void => {
|
||||
const button = buttonRefs.current[value];
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
setIndicator((current) =>
|
||||
current.left === button.offsetLeft &&
|
||||
current.width === button.offsetWidth
|
||||
? current
|
||||
: {
|
||||
left: button.offsetLeft,
|
||||
width: button.offsetWidth,
|
||||
ready: true
|
||||
}
|
||||
);
|
||||
};
|
||||
const observer = new ResizeObserver(sync);
|
||||
observer.observe(container);
|
||||
for (const key of Object.keys(buttonRefs.current) as TValue[]) {
|
||||
const node = buttonRefs.current[key];
|
||||
if (node) {
|
||||
observer.observe(node);
|
||||
}
|
||||
}
|
||||
return () => observer.disconnect();
|
||||
}, [segments, value]);
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
"relative inline-flex h-8 shrink-0 items-center gap-0.5 rounded-md bg-[var(--transparency-block)] p-0.5",
|
||||
className
|
||||
)}
|
||||
data-slot="segment-bar"
|
||||
data-testid={testId}
|
||||
ref={containerRef}
|
||||
role="tablist"
|
||||
>
|
||||
{indicator.ready ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute top-0.5 bottom-0.5 rounded-[5px] bg-[var(--background-board-card)] transition-[left,width] duration-150 ease-out"
|
||||
data-slot="segment-bar-indicator"
|
||||
style={{ left: indicator.left, width: indicator.width }}
|
||||
/>
|
||||
) : null}
|
||||
{segments.map((segment) => {
|
||||
const isActive = value === segment.value;
|
||||
return (
|
||||
<button
|
||||
aria-selected={isActive}
|
||||
className={cn(
|
||||
"relative z-[1] inline-flex h-7 shrink-0 items-center justify-center whitespace-nowrap rounded-[5px] px-2.5 text-[12px] font-semibold leading-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/25",
|
||||
isActive
|
||||
? "text-[var(--text-primary)]"
|
||||
: "text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
|
||||
)}
|
||||
data-active={isActive ? "true" : "false"}
|
||||
data-slot="segment-bar-segment"
|
||||
data-testid={segment.testId}
|
||||
key={segment.value}
|
||||
ref={(node) => {
|
||||
if (node) {
|
||||
buttonRefs.current[segment.value] = node;
|
||||
}
|
||||
}}
|
||||
role="tab"
|
||||
type="button"
|
||||
onClick={() => onValueChange(segment.value)}
|
||||
>
|
||||
{segment.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { SegmentBar };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./select";
|
||||
@@ -0,0 +1,309 @@
|
||||
import * as React from "react";
|
||||
import { Select as SelectPrimitive } from "radix-ui";
|
||||
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
import { buttonVariants } from "../button";
|
||||
import {
|
||||
MenuSurface,
|
||||
menuItemIndicatorClassName,
|
||||
menuItemWithIndicatorClassName
|
||||
} from "../menu-surface";
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return (
|
||||
<SelectPrimitive.Group
|
||||
data-slot="select-group"
|
||||
className={cn("flex flex-col gap-0.5 scroll-my-1 p-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
variant = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default" | "dialog";
|
||||
variant?: "button" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
variant === "button"
|
||||
? buttonVariants({ variant: "default", size })
|
||||
: "flex w-fit cursor-pointer items-center justify-between gap-1.5 rounded-lg border border-transparent bg-[var(--transparency-block)] py-2 pr-2 pl-2.5 text-[13px] text-[var(--text-primary)] whitespace-nowrap transition-colors outline-none select-none hover:bg-[var(--transparency-hover)] focus:bg-[var(--transparency-hover)] focus-visible:border-transparent focus-visible:bg-[var(--transparency-hover)] focus-visible:ring-0 disabled:cursor-not-allowed disabled:bg-[var(--transparency-block)] disabled:text-[var(--text-disabled)] disabled:opacity-100 aria-invalid:border-[var(--state-danger)] aria-invalid:bg-[var(--transparency-block)] aria-invalid:hover:bg-[var(--transparency-hover)] aria-invalid:focus:bg-[var(--transparency-hover)] aria-invalid:focus-visible:bg-[var(--transparency-hover)] aria-invalid:ring-0 aria-invalid:shadow-none data-placeholder:text-[var(--text-placeholder)] data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"[&[data-state=open]>svg]:rotate-180 [&>svg]:transition-transform [&>svg]:duration-200",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon
|
||||
className={cn("pointer-events-none size-4", "text-current")}
|
||||
/>
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
align = "center",
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
asChild
|
||||
data-slot="select-content"
|
||||
data-align-trigger={position === "item-aligned"}
|
||||
position={position}
|
||||
align={align}
|
||||
{...props}
|
||||
>
|
||||
<MenuSurface
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-36 origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-popover)", ...style }}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
data-position={position}
|
||||
className={cn(
|
||||
"flex flex-col gap-0.5 data-[position=popper]:w-full data-[position=popper]:[min-width:var(--tutti-select-content-min-width,var(--radix-select-trigger-width))]"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</MenuSurface>
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn(
|
||||
"px-1.5 py-1 text-[11px] font-normal text-[var(--text-secondary)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSplitLayout({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="select-split-layout"
|
||||
className={cn(
|
||||
"grid h-full min-h-0 grid-cols-[minmax(0,1fr)_1px_minmax(104px,132px)] gap-1 overflow-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSplitColumn({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="select-split-column"
|
||||
className={cn("flex h-full min-h-0 min-w-0 flex-col", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSplitColumnLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="select-split-column-label"
|
||||
className={cn(
|
||||
"shrink-0 px-2 pt-1 pb-2 text-[11px] font-normal leading-[18px] text-[var(--text-secondary)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSplitColumnItems({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="select-split-column-items"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto overscroll-contain",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSplitDivider({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
data-slot="select-split-divider"
|
||||
className={cn(
|
||||
"self-stretch bg-[var(--border-2,var(--border-1))]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
forceSelectedIndicator = false,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item> & {
|
||||
forceSelectedIndicator?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn("w-full", menuItemWithIndicatorClassName, className)}
|
||||
{...props}
|
||||
>
|
||||
<span className={menuItemIndicatorClassName}>
|
||||
{forceSelectedIndicator ? (
|
||||
<CheckIcon
|
||||
className="pointer-events-none text-[var(--tutti-purple)]"
|
||||
data-slot="select-item-forced-indicator"
|
||||
/>
|
||||
) : (
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="pointer-events-none text-[var(--tutti-purple)]" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
)}
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn(
|
||||
"pointer-events-none mx-2 my-0.5 h-px bg-[var(--border-1)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"z-10 flex cursor-pointer items-center justify-center bg-[var(--background-fronted)] py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"z-10 flex cursor-pointer items-center justify-center bg-[var(--background-fronted)] py-1 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectSplitColumn,
|
||||
SelectSplitColumnItems,
|
||||
SelectSplitColumnLabel,
|
||||
SelectSplitDivider,
|
||||
SelectSplitLayout,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./separator";
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as React from "react";
|
||||
import { Separator as SeparatorPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./shortcut-badge";
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function ShortcutBadge({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="shortcut-badge"
|
||||
className={cn(
|
||||
"inline-flex h-5 min-w-0 max-w-full shrink-0 items-center justify-center overflow-hidden rounded-[4px] bg-[color-mix(in_srgb,var(--transparency-block)_72%,transparent)] px-1.5 py-1 font-[inherit] text-[11px] leading-none font-semibold whitespace-nowrap text-[var(--text-tertiary)] not-italic [font-variant:normal] [text-overflow:ellipsis]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { ShortcutBadge };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./slider";
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as React from "react";
|
||||
import { Slider as SliderPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
type SliderProps = React.ComponentProps<typeof SliderPrimitive.Root> & {
|
||||
/** Caller-owned accessible names for each thumb in a multi-value slider. */
|
||||
thumbAriaLabels?: readonly string[];
|
||||
};
|
||||
|
||||
function Slider({
|
||||
"aria-label": ariaLabel,
|
||||
"aria-labelledby": ariaLabelledBy,
|
||||
className,
|
||||
defaultValue,
|
||||
value,
|
||||
min = 0,
|
||||
max = 100,
|
||||
thumbAriaLabels,
|
||||
...props
|
||||
}: SliderProps) {
|
||||
const values = React.useMemo(
|
||||
() =>
|
||||
Array.isArray(value)
|
||||
? value
|
||||
: Array.isArray(defaultValue)
|
||||
? defaultValue
|
||||
: [min],
|
||||
[defaultValue, min, value]
|
||||
);
|
||||
|
||||
return (
|
||||
<SliderPrimitive.Root
|
||||
data-slot="slider"
|
||||
defaultValue={defaultValue}
|
||||
value={value}
|
||||
min={min}
|
||||
max={max}
|
||||
className={cn(
|
||||
"relative flex w-full touch-none items-center select-none outline-none data-disabled:cursor-not-allowed data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-40 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track
|
||||
data-slot="slider-track"
|
||||
className="relative grow overflow-hidden rounded-full bg-[var(--transparency-block)] data-[orientation=horizontal]:h-1 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1"
|
||||
>
|
||||
<SliderPrimitive.Range
|
||||
data-slot="slider-range"
|
||||
className="absolute bg-[var(--tutti-purple)] select-none data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
|
||||
/>
|
||||
</SliderPrimitive.Track>
|
||||
{Array.from({ length: values.length }, (_, index) => (
|
||||
<SliderPrimitive.Thumb
|
||||
aria-disabled={props.disabled || undefined}
|
||||
aria-label={
|
||||
thumbAriaLabels?.[index] ??
|
||||
(values.length === 1 ? ariaLabel : undefined)
|
||||
}
|
||||
aria-labelledby={values.length === 1 ? ariaLabelledBy : undefined}
|
||||
data-slot="slider-thumb"
|
||||
key={index}
|
||||
className="relative block size-3 shrink-0 rounded-full border border-[var(--tutti-purple)] bg-[var(--background-fronted)] shadow-none transition-[box-shadow] outline-none select-none after:absolute after:-inset-2 hover:ring-3 hover:ring-[color-mix(in_srgb,var(--tutti-purple)_20%,transparent)] focus-visible:ring-3 focus-visible:ring-[color-mix(in_srgb,var(--border-focus)_30%,transparent)] data-disabled:pointer-events-none data-disabled:hover:ring-0"
|
||||
/>
|
||||
))}
|
||||
</SliderPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Slider, type SliderProps };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./sonner";
|
||||
@@ -0,0 +1,66 @@
|
||||
import type * as React from "react";
|
||||
import {
|
||||
Toaster as SonnerToaster,
|
||||
toast,
|
||||
type ExternalToast,
|
||||
type ToasterProps
|
||||
} from "sonner";
|
||||
|
||||
import {
|
||||
FailedFilledIcon,
|
||||
LoadingIcon,
|
||||
SuccessFilledIcon,
|
||||
WarningFilledIcon,
|
||||
WarningLinedIcon
|
||||
} from "#icons/system-icons";
|
||||
|
||||
function Toaster({ toastOptions, style, ...props }: ToasterProps) {
|
||||
return (
|
||||
<SonnerToaster
|
||||
closeButton
|
||||
expand={false}
|
||||
gap={8}
|
||||
position="top-right"
|
||||
visibleToasts={4}
|
||||
icons={{
|
||||
error: <FailedFilledIcon className="size-4" />,
|
||||
info: <WarningLinedIcon className="size-4" />,
|
||||
loading: <LoadingIcon className="size-4 animate-spin" />,
|
||||
success: <SuccessFilledIcon className="size-4" />,
|
||||
warning: <WarningFilledIcon className="size-4" />
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--background-fronted)",
|
||||
"--normal-border": "var(--line-2)",
|
||||
"--normal-text": "var(--text-primary)",
|
||||
"--border-radius": "8px",
|
||||
zIndex: "var(--z-toast)",
|
||||
...style
|
||||
} as React.CSSProperties
|
||||
}
|
||||
toastOptions={{
|
||||
...toastOptions,
|
||||
classNames: {
|
||||
toast:
|
||||
"group pointer-events-auto min-h-14 rounded-[8px] border border-[var(--line-2)] bg-[var(--background-fronted)] p-3 text-[var(--text-primary)] shadow-[0_14px_40px_var(--shadow-elevated)]",
|
||||
title: "text-[13px] font-medium leading-5 text-[var(--text-primary)]",
|
||||
description:
|
||||
"mt-0.5 text-[11px] leading-[1.3] text-[var(--text-secondary)]",
|
||||
actionButton:
|
||||
"h-7 rounded-[6px] bg-[var(--text-primary)] px-2.5 text-[11px] font-normal text-[var(--text-inverted)] transition-colors hover:bg-[var(--text-primary-hover)]",
|
||||
cancelButton:
|
||||
"h-7 rounded-[6px] bg-[var(--transparency-block)] px-2.5 text-[11px] font-normal text-[var(--text-primary)] transition-colors hover:bg-[var(--transparency-hover)]",
|
||||
closeButton:
|
||||
"border-[var(--line-2)] bg-[var(--background-fronted)] text-[var(--text-secondary)] hover:bg-[var(--transparency-hover)] hover:text-[var(--text-primary)]",
|
||||
icon: "text-[var(--accent)]",
|
||||
...toastOptions?.classNames
|
||||
}
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Toaster, toast };
|
||||
export type { ExternalToast, ToasterProps };
|
||||
@@ -0,0 +1,8 @@
|
||||
export {
|
||||
Sortable,
|
||||
SortableContent,
|
||||
SortableItem,
|
||||
SortableItemHandle,
|
||||
SortableOverlay,
|
||||
type SortableProps
|
||||
} from "./sortable";
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { DndContextProps, DragEndEvent } from "@dnd-kit/core";
|
||||
import { act, render } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const dndContext = vi.hoisted(() => ({
|
||||
props: null as DndContextProps | null
|
||||
}));
|
||||
|
||||
vi.mock("@dnd-kit/core", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@dnd-kit/core")>();
|
||||
return {
|
||||
...actual,
|
||||
DndContext: (props: DndContextProps) => {
|
||||
dndContext.props = props;
|
||||
return props.children as ReactNode;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
import { Sortable } from "./sortable";
|
||||
|
||||
const accessibility = {
|
||||
announcements: {
|
||||
onDragStart: () => undefined,
|
||||
onDragMove: () => undefined,
|
||||
onDragOver: () => undefined,
|
||||
onDragEnd: () => undefined,
|
||||
onDragCancel: () => undefined
|
||||
},
|
||||
screenReaderInstructions: { draggable: "Use the keyboard to move an item" }
|
||||
};
|
||||
|
||||
describe("Sortable behavior", () => {
|
||||
it("commits a keyboard move when the sensor prevented the activator event", () => {
|
||||
const onMove = vi.fn();
|
||||
render(
|
||||
<Sortable
|
||||
accessibility={accessibility}
|
||||
onMove={onMove}
|
||||
value={["first", "second"]}
|
||||
>
|
||||
<div />
|
||||
</Sortable>
|
||||
);
|
||||
const activatorEvent = new KeyboardEvent("keydown", { cancelable: true });
|
||||
activatorEvent.preventDefault();
|
||||
|
||||
act(() => {
|
||||
dndContext.props?.onDragEnd?.({
|
||||
active: { id: "second" },
|
||||
over: { id: "first" },
|
||||
activatorEvent
|
||||
} as unknown as DragEndEvent);
|
||||
});
|
||||
|
||||
expect(activatorEvent.defaultPrevented).toBe(true);
|
||||
expect(onMove).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ activeIndex: 1, overIndex: 0 })
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores a stale drag whose active item disappeared from controlled value", () => {
|
||||
const onMove = vi.fn();
|
||||
render(
|
||||
<Sortable
|
||||
accessibility={accessibility}
|
||||
onMove={onMove}
|
||||
value={["first", "second"]}
|
||||
>
|
||||
<div />
|
||||
</Sortable>
|
||||
);
|
||||
|
||||
act(() => {
|
||||
dndContext.props?.onDragEnd?.({
|
||||
active: { id: "removed" },
|
||||
over: { id: "first" },
|
||||
activatorEvent: new MouseEvent("mouseup")
|
||||
} as unknown as DragEndEvent);
|
||||
});
|
||||
|
||||
expect(onMove).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
Sortable,
|
||||
SortableContent,
|
||||
SortableItem,
|
||||
SortableItemHandle
|
||||
} from "./sortable";
|
||||
|
||||
const accessibility = {
|
||||
announcements: {
|
||||
onDragStart: () => "Started sorting",
|
||||
onDragOver: () => "Changed position",
|
||||
onDragEnd: () => "Finished sorting",
|
||||
onDragCancel: () => "Canceled sorting"
|
||||
},
|
||||
screenReaderInstructions: {
|
||||
draggable: "Use Space and arrow keys to reorder"
|
||||
}
|
||||
};
|
||||
|
||||
function SortableHarness(): React.JSX.Element {
|
||||
const [items, setItems] = useState(["first", "second", "third"]);
|
||||
return (
|
||||
<Sortable
|
||||
accessibility={accessibility}
|
||||
value={items}
|
||||
onValueChange={setItems}
|
||||
>
|
||||
<SortableContent>
|
||||
{items.map((item, index) => (
|
||||
<SortableItem key={item} data-sortable-index={index} value={item}>
|
||||
<SortableItemHandle aria-label={`Reorder ${item}`} />
|
||||
<span>{item}</span>
|
||||
</SortableItem>
|
||||
))}
|
||||
</SortableContent>
|
||||
</Sortable>
|
||||
);
|
||||
}
|
||||
|
||||
describe("Sortable keyboard sensor", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("moves an item with Space, ArrowUp, Space through the real DndContext", async () => {
|
||||
const rectFor = (element: Element): DOMRect => {
|
||||
const item = element.closest<HTMLElement>("[data-sortable-index]");
|
||||
const index = Number(item?.dataset.sortableIndex ?? 0);
|
||||
const top = index * 40;
|
||||
return {
|
||||
bottom: top + 32,
|
||||
height: 32,
|
||||
left: 0,
|
||||
right: 160,
|
||||
top,
|
||||
width: 160,
|
||||
x: 0,
|
||||
y: top,
|
||||
toJSON: () => ({})
|
||||
};
|
||||
};
|
||||
vi.spyOn(Element.prototype, "getBoundingClientRect").mockImplementation(
|
||||
function (this: Element) {
|
||||
return rectFor(this);
|
||||
}
|
||||
);
|
||||
vi.spyOn(Element.prototype, "getClientRects").mockImplementation(
|
||||
function (this: Element) {
|
||||
return [rectFor(this)] as unknown as DOMRectList;
|
||||
}
|
||||
);
|
||||
render(<SortableHarness />);
|
||||
|
||||
const handle = screen.getByRole("button", { name: "Reorder second" });
|
||||
handle.focus();
|
||||
fireEvent.keyDown(handle, { code: "Space", key: " " });
|
||||
await waitFor(() => expect(handle).toHaveAttribute("aria-pressed", "true"));
|
||||
fireEvent.keyDown(handle, { code: "ArrowUp", key: "ArrowUp" });
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Changed position")
|
||||
);
|
||||
fireEvent.keyDown(handle, { code: "Space", key: " " });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getAllByRole("button").map((button) => button.ariaLabel)
|
||||
).toEqual(["Reorder second", "Reorder first", "Reorder third"])
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,558 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
closestCenter,
|
||||
closestCorners,
|
||||
DndContext,
|
||||
type DndContextProps,
|
||||
type DragEndEvent,
|
||||
type DraggableAttributes,
|
||||
type DraggableSyntheticListeners,
|
||||
DragOverlay,
|
||||
type DragStartEvent,
|
||||
type DropAnimation,
|
||||
defaultDropAnimationSideEffects,
|
||||
KeyboardSensor,
|
||||
MouseSensor,
|
||||
TouchSensor,
|
||||
type UniqueIdentifier,
|
||||
useSensor,
|
||||
useSensors
|
||||
} from "@dnd-kit/core";
|
||||
import {
|
||||
restrictToHorizontalAxis,
|
||||
restrictToParentElement,
|
||||
restrictToVerticalAxis
|
||||
} from "@dnd-kit/modifiers";
|
||||
import {
|
||||
arrayMove,
|
||||
horizontalListSortingStrategy,
|
||||
SortableContext,
|
||||
type SortableContextProps,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import { Slot as SlotPrimitive } from "radix-ui";
|
||||
import * as React from "react";
|
||||
import * as ReactDOM from "react-dom";
|
||||
import { useComposedRefs } from "#lib/compose-refs";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const orientationConfig = {
|
||||
vertical: {
|
||||
modifiers: [restrictToVerticalAxis, restrictToParentElement],
|
||||
strategy: verticalListSortingStrategy,
|
||||
collisionDetection: closestCenter
|
||||
},
|
||||
horizontal: {
|
||||
modifiers: [restrictToHorizontalAxis, restrictToParentElement],
|
||||
strategy: horizontalListSortingStrategy,
|
||||
collisionDetection: closestCenter
|
||||
},
|
||||
mixed: {
|
||||
modifiers: [restrictToParentElement],
|
||||
strategy: undefined,
|
||||
collisionDetection: closestCorners
|
||||
}
|
||||
};
|
||||
|
||||
const ROOT_NAME = "Sortable";
|
||||
const CONTENT_NAME = "SortableContent";
|
||||
const ITEM_NAME = "SortableItem";
|
||||
const ITEM_HANDLE_NAME = "SortableItemHandle";
|
||||
const OVERLAY_NAME = "SortableOverlay";
|
||||
|
||||
interface SortableRootContextValue<T> {
|
||||
id: string;
|
||||
items: UniqueIdentifier[];
|
||||
modifiers: DndContextProps["modifiers"];
|
||||
strategy: SortableContextProps["strategy"];
|
||||
activeId: UniqueIdentifier | null;
|
||||
setActiveId: (id: UniqueIdentifier | null) => void;
|
||||
getItemValue: (item: T) => UniqueIdentifier;
|
||||
flatCursor: boolean;
|
||||
}
|
||||
|
||||
const SortableRootContext =
|
||||
React.createContext<SortableRootContextValue<unknown> | null>(null);
|
||||
|
||||
function useSortableContext(consumerName: string) {
|
||||
const context = React.useContext(SortableRootContext);
|
||||
if (!context) {
|
||||
throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface GetItemValue<T> {
|
||||
/**
|
||||
* Callback that returns a unique identifier for each sortable item. Required for array of objects.
|
||||
* @example getItemValue={(item) => item.id}
|
||||
*/
|
||||
getItemValue: (item: T) => UniqueIdentifier;
|
||||
}
|
||||
|
||||
type SortableProps<T> = DndContextProps &
|
||||
(T extends object ? GetItemValue<T> : Partial<GetItemValue<T>>) & {
|
||||
value: T[];
|
||||
onValueChange?: (items: T[]) => void;
|
||||
onMove?: (
|
||||
event: DragEndEvent & { activeIndex: number; overIndex: number }
|
||||
) => void;
|
||||
strategy?: SortableContextProps["strategy"];
|
||||
orientation?: "vertical" | "horizontal" | "mixed";
|
||||
flatCursor?: boolean;
|
||||
accessibility: NonNullable<DndContextProps["accessibility"]> &
|
||||
Required<
|
||||
Pick<
|
||||
NonNullable<DndContextProps["accessibility"]>,
|
||||
"announcements" | "screenReaderInstructions"
|
||||
>
|
||||
>;
|
||||
};
|
||||
|
||||
function Sortable<T>(props: SortableProps<T>) {
|
||||
const {
|
||||
value,
|
||||
onValueChange,
|
||||
collisionDetection,
|
||||
modifiers,
|
||||
strategy,
|
||||
onMove,
|
||||
orientation = "vertical",
|
||||
flatCursor = false,
|
||||
getItemValue: getItemValueProp,
|
||||
accessibility,
|
||||
...sortableProps
|
||||
} = props;
|
||||
|
||||
const id = React.useId();
|
||||
const [activeId, setActiveId] = React.useState<UniqueIdentifier | null>(null);
|
||||
|
||||
const sensors = useSensors(
|
||||
useSensor(MouseSensor, {
|
||||
activationConstraint: { distance: 6 }
|
||||
}),
|
||||
useSensor(TouchSensor, {
|
||||
activationConstraint: { delay: 180, tolerance: 5 }
|
||||
}),
|
||||
useSensor(KeyboardSensor, {
|
||||
coordinateGetter: sortableKeyboardCoordinates
|
||||
})
|
||||
);
|
||||
const config = React.useMemo(
|
||||
() => orientationConfig[orientation],
|
||||
[orientation]
|
||||
);
|
||||
|
||||
const getItemValue = React.useCallback(
|
||||
(item: T): UniqueIdentifier => {
|
||||
if (typeof item === "object" && !getItemValueProp) {
|
||||
throw new Error(
|
||||
"`getItemValue` is required when using array of objects"
|
||||
);
|
||||
}
|
||||
return getItemValueProp
|
||||
? getItemValueProp(item)
|
||||
: (item as UniqueIdentifier);
|
||||
},
|
||||
[getItemValueProp]
|
||||
);
|
||||
|
||||
const items = React.useMemo(() => {
|
||||
return value.map((item) => getItemValue(item));
|
||||
}, [value, getItemValue]);
|
||||
|
||||
const onDragStart = React.useCallback(
|
||||
(event: DragStartEvent) => {
|
||||
sortableProps.onDragStart?.(event);
|
||||
setActiveId(event.active.id);
|
||||
},
|
||||
[sortableProps.onDragStart]
|
||||
);
|
||||
|
||||
const onDragEnd = React.useCallback(
|
||||
(event: DragEndEvent) => {
|
||||
sortableProps.onDragEnd?.(event);
|
||||
|
||||
const { active, over } = event;
|
||||
if (over && active.id !== over?.id) {
|
||||
const activeIndex = value.findIndex(
|
||||
(item) => getItemValue(item) === active.id
|
||||
);
|
||||
const overIndex = value.findIndex(
|
||||
(item) => getItemValue(item) === over.id
|
||||
);
|
||||
|
||||
if (activeIndex < 0 || overIndex < 0) {
|
||||
setActiveId(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (onMove) {
|
||||
onMove({ ...event, activeIndex, overIndex });
|
||||
} else {
|
||||
onValueChange?.(arrayMove(value, activeIndex, overIndex));
|
||||
}
|
||||
}
|
||||
setActiveId(null);
|
||||
},
|
||||
[value, onValueChange, onMove, getItemValue, sortableProps.onDragEnd]
|
||||
);
|
||||
|
||||
const onDragCancel = React.useCallback(
|
||||
(event: DragEndEvent) => {
|
||||
sortableProps.onDragCancel?.(event);
|
||||
setActiveId(null);
|
||||
},
|
||||
[sortableProps.onDragCancel]
|
||||
);
|
||||
|
||||
const contextValue = React.useMemo(
|
||||
() => ({
|
||||
id,
|
||||
items,
|
||||
modifiers: modifiers ?? config.modifiers,
|
||||
strategy: strategy ?? config.strategy,
|
||||
activeId,
|
||||
setActiveId,
|
||||
getItemValue,
|
||||
flatCursor
|
||||
}),
|
||||
[
|
||||
id,
|
||||
items,
|
||||
modifiers,
|
||||
strategy,
|
||||
config.modifiers,
|
||||
config.strategy,
|
||||
activeId,
|
||||
getItemValue,
|
||||
flatCursor
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<SortableRootContext.Provider
|
||||
value={contextValue as SortableRootContextValue<unknown>}
|
||||
>
|
||||
<DndContext
|
||||
collisionDetection={collisionDetection ?? config.collisionDetection}
|
||||
modifiers={modifiers ?? config.modifiers}
|
||||
sensors={sensors}
|
||||
{...sortableProps}
|
||||
id={id}
|
||||
onDragStart={onDragStart}
|
||||
onDragEnd={onDragEnd}
|
||||
onDragCancel={onDragCancel}
|
||||
accessibility={accessibility}
|
||||
/>
|
||||
</SortableRootContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const SortableContentContext = React.createContext<boolean>(false);
|
||||
|
||||
interface SortableContentProps extends React.ComponentProps<"div"> {
|
||||
strategy?: SortableContextProps["strategy"];
|
||||
children: React.ReactNode;
|
||||
asChild?: boolean;
|
||||
withoutSlot?: boolean;
|
||||
}
|
||||
|
||||
function SortableContent(props: SortableContentProps) {
|
||||
const {
|
||||
strategy: strategyProp,
|
||||
asChild,
|
||||
withoutSlot,
|
||||
children,
|
||||
ref,
|
||||
...contentProps
|
||||
} = props;
|
||||
|
||||
const context = useSortableContext(CONTENT_NAME);
|
||||
|
||||
const ContentPrimitive = asChild ? SlotPrimitive.Slot : "div";
|
||||
|
||||
return (
|
||||
<SortableContentContext.Provider value={true}>
|
||||
<SortableContext
|
||||
items={context.items}
|
||||
strategy={strategyProp ?? context.strategy}
|
||||
>
|
||||
{withoutSlot ? (
|
||||
children
|
||||
) : (
|
||||
<ContentPrimitive
|
||||
data-slot="sortable-content"
|
||||
{...contentProps}
|
||||
ref={ref}
|
||||
>
|
||||
{children}
|
||||
</ContentPrimitive>
|
||||
)}
|
||||
</SortableContext>
|
||||
</SortableContentContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
interface SortableItemContextValue {
|
||||
id: string;
|
||||
attributes: DraggableAttributes;
|
||||
listeners: DraggableSyntheticListeners | undefined;
|
||||
setActivatorNodeRef: (node: HTMLElement | null) => void;
|
||||
isDragging?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const SortableItemContext =
|
||||
React.createContext<SortableItemContextValue | null>(null);
|
||||
|
||||
function useSortableItemContext(consumerName: string) {
|
||||
const context = React.useContext(SortableItemContext);
|
||||
if (!context) {
|
||||
throw new Error(`\`${consumerName}\` must be used within \`${ITEM_NAME}\``);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface SortableItemProps extends React.ComponentProps<"div"> {
|
||||
value: UniqueIdentifier;
|
||||
asHandle?: boolean;
|
||||
asChild?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function SortableItem(props: SortableItemProps) {
|
||||
const {
|
||||
value,
|
||||
style,
|
||||
asHandle,
|
||||
asChild,
|
||||
disabled,
|
||||
className,
|
||||
ref,
|
||||
...itemProps
|
||||
} = props;
|
||||
|
||||
const inSortableContent = React.useContext(SortableContentContext);
|
||||
const inSortableOverlay = React.useContext(SortableOverlayContext);
|
||||
|
||||
if (!inSortableContent && !inSortableOverlay) {
|
||||
throw new Error(
|
||||
`\`${ITEM_NAME}\` must be used within \`${CONTENT_NAME}\` or \`${OVERLAY_NAME}\``
|
||||
);
|
||||
}
|
||||
|
||||
if (value === "") {
|
||||
throw new Error(`\`${ITEM_NAME}\` value cannot be an empty string`);
|
||||
}
|
||||
|
||||
const context = useSortableContext(ITEM_NAME);
|
||||
const id = React.useId();
|
||||
const {
|
||||
attributes,
|
||||
listeners,
|
||||
setNodeRef,
|
||||
setActivatorNodeRef,
|
||||
transform,
|
||||
transition,
|
||||
isDragging
|
||||
} = useSortable({ id: value, disabled });
|
||||
const prefersReducedMotion = usePrefersReducedMotion();
|
||||
|
||||
const composedRef = useComposedRefs(ref, (node) => {
|
||||
if (disabled) return;
|
||||
setNodeRef(node);
|
||||
if (asHandle) setActivatorNodeRef(node);
|
||||
});
|
||||
|
||||
const composedStyle = React.useMemo<React.CSSProperties>(() => {
|
||||
return {
|
||||
transform: CSS.Translate.toString(transform),
|
||||
transition: prefersReducedMotion ? undefined : transition,
|
||||
...style
|
||||
};
|
||||
}, [prefersReducedMotion, transform, transition, style]);
|
||||
|
||||
const itemContext = React.useMemo<SortableItemContextValue>(
|
||||
() => ({
|
||||
id,
|
||||
attributes,
|
||||
listeners,
|
||||
setActivatorNodeRef,
|
||||
isDragging,
|
||||
disabled
|
||||
}),
|
||||
[id, attributes, listeners, setActivatorNodeRef, isDragging, disabled]
|
||||
);
|
||||
|
||||
const ItemPrimitive = asChild ? SlotPrimitive.Slot : "div";
|
||||
|
||||
return (
|
||||
<SortableItemContext.Provider value={itemContext}>
|
||||
<ItemPrimitive
|
||||
id={id}
|
||||
data-disabled={disabled}
|
||||
data-dragging={isDragging ? "" : undefined}
|
||||
data-slot="sortable-item"
|
||||
{...itemProps}
|
||||
{...(asHandle && !disabled ? attributes : {})}
|
||||
{...(asHandle && !disabled ? listeners : {})}
|
||||
ref={composedRef}
|
||||
style={composedStyle}
|
||||
className={cn(
|
||||
"focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1",
|
||||
{
|
||||
"touch-none select-none": asHandle,
|
||||
"cursor-default": context.flatCursor,
|
||||
"data-dragging:cursor-grabbing": !context.flatCursor,
|
||||
"cursor-grab": !isDragging && asHandle && !context.flatCursor,
|
||||
"opacity-50": isDragging,
|
||||
"pointer-events-none opacity-50": disabled
|
||||
},
|
||||
className
|
||||
)}
|
||||
/>
|
||||
</SortableItemContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
interface SortableItemHandleProps extends React.ComponentProps<"button"> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
function SortableItemHandle(props: SortableItemHandleProps) {
|
||||
const { asChild, disabled, className, ref, ...itemHandleProps } = props;
|
||||
|
||||
const context = useSortableContext(ITEM_HANDLE_NAME);
|
||||
const itemContext = useSortableItemContext(ITEM_HANDLE_NAME);
|
||||
|
||||
const isDisabled = Boolean(itemContext.disabled || disabled);
|
||||
|
||||
const composedRef = useComposedRefs(ref, (node) => {
|
||||
if (isDisabled) return;
|
||||
itemContext.setActivatorNodeRef(node);
|
||||
});
|
||||
|
||||
const HandlePrimitive = asChild ? SlotPrimitive.Slot : "button";
|
||||
|
||||
return (
|
||||
<HandlePrimitive
|
||||
type="button"
|
||||
aria-controls={itemContext.id}
|
||||
data-disabled={isDisabled}
|
||||
data-dragging={itemContext.isDragging ? "" : undefined}
|
||||
data-slot="sortable-item-handle"
|
||||
{...itemHandleProps}
|
||||
{...(isDisabled ? {} : itemContext.attributes)}
|
||||
{...(isDisabled ? {} : itemContext.listeners)}
|
||||
ref={composedRef}
|
||||
className={cn(
|
||||
"select-none disabled:pointer-events-none disabled:opacity-50",
|
||||
context.flatCursor
|
||||
? "cursor-default"
|
||||
: "cursor-grab data-dragging:cursor-grabbing",
|
||||
className
|
||||
)}
|
||||
disabled={isDisabled}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function usePrefersReducedMotion(): boolean {
|
||||
const [reduced, setReduced] = React.useState(
|
||||
() =>
|
||||
globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ??
|
||||
false
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
const query = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)");
|
||||
if (!query) return;
|
||||
const update = () => setReduced(query.matches);
|
||||
update();
|
||||
query.addEventListener("change", update);
|
||||
return () => query.removeEventListener("change", update);
|
||||
}, []);
|
||||
|
||||
return reduced;
|
||||
}
|
||||
|
||||
const SortableOverlayContext = React.createContext(false);
|
||||
|
||||
const defaultDropAnimation: DropAnimation = {
|
||||
sideEffects: defaultDropAnimationSideEffects({
|
||||
styles: {
|
||||
active: {
|
||||
opacity: "0.4"
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
interface SortableOverlayProps extends Omit<
|
||||
React.ComponentProps<typeof DragOverlay>,
|
||||
"children"
|
||||
> {
|
||||
container?: Element | DocumentFragment | null;
|
||||
children?:
|
||||
| ((params: { value: UniqueIdentifier }) => React.ReactNode)
|
||||
| React.ReactNode;
|
||||
}
|
||||
|
||||
function SortableOverlay(props: SortableOverlayProps) {
|
||||
const {
|
||||
container: containerProp,
|
||||
children,
|
||||
dropAnimation: callerDropAnimation,
|
||||
...overlayProps
|
||||
} = props;
|
||||
|
||||
const context = useSortableContext(OVERLAY_NAME);
|
||||
const prefersReducedMotion = usePrefersReducedMotion();
|
||||
|
||||
const [mounted, setMounted] = React.useState(false);
|
||||
|
||||
React.useLayoutEffect(() => setMounted(true), []);
|
||||
|
||||
const container =
|
||||
containerProp ?? (mounted ? globalThis.document?.body : null);
|
||||
|
||||
if (!container) return null;
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
<DragOverlay
|
||||
modifiers={context.modifiers}
|
||||
className={cn(!context.flatCursor && "cursor-grabbing")}
|
||||
{...overlayProps}
|
||||
dropAnimation={
|
||||
prefersReducedMotion
|
||||
? null
|
||||
: callerDropAnimation === undefined
|
||||
? defaultDropAnimation
|
||||
: callerDropAnimation
|
||||
}
|
||||
>
|
||||
<SortableOverlayContext.Provider value={true}>
|
||||
{context.activeId
|
||||
? typeof children === "function"
|
||||
? children({ value: context.activeId })
|
||||
: children
|
||||
: null}
|
||||
</SortableOverlayContext.Provider>
|
||||
</DragOverlay>,
|
||||
container
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Sortable,
|
||||
SortableContent,
|
||||
SortableItem,
|
||||
SortableItemHandle,
|
||||
SortableOverlay,
|
||||
type SortableProps
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./spinner";
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { CSSProperties, JSX } from "react";
|
||||
|
||||
import { LoadingIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
export interface SpinnerProps {
|
||||
className?: string;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
style?: CSSProperties;
|
||||
testId?: string;
|
||||
trackColor?: string;
|
||||
}
|
||||
|
||||
function Spinner({
|
||||
className,
|
||||
size = 16,
|
||||
strokeWidth = 2,
|
||||
style,
|
||||
testId,
|
||||
trackColor
|
||||
}: SpinnerProps): JSX.Element {
|
||||
return (
|
||||
<LoadingIcon
|
||||
data-slot="spinner"
|
||||
data-testid={testId}
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"inline-block shrink-0 animate-spin text-primary",
|
||||
className
|
||||
)}
|
||||
size={size}
|
||||
style={style}
|
||||
strokeWidth={strokeWidth}
|
||||
trackColor={trackColor}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Spinner };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./status-dot";
|
||||
@@ -0,0 +1,60 @@
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const statusDotVariants = cva("inline-flex shrink-0 rounded-full", {
|
||||
variants: {
|
||||
tone: {
|
||||
neutral: "bg-[var(--text-tertiary)]",
|
||||
green: "bg-[var(--state-success)]",
|
||||
blue: "bg-[var(--status-running)]",
|
||||
amber: "bg-[var(--state-warning)]",
|
||||
red: "bg-[var(--state-danger)]"
|
||||
},
|
||||
size: {
|
||||
xs: "size-1.5",
|
||||
sm: "size-2",
|
||||
md: "size-2.5"
|
||||
},
|
||||
pulse: {
|
||||
true: "animate-pulse",
|
||||
false: ""
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
tone: "neutral",
|
||||
size: "sm",
|
||||
pulse: false
|
||||
}
|
||||
});
|
||||
|
||||
type StatusDotProps = VariantProps<typeof statusDotVariants> & {
|
||||
ariaLabel?: string;
|
||||
title?: string;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
function StatusDot({
|
||||
tone = "neutral",
|
||||
size = "sm",
|
||||
pulse = false,
|
||||
ariaLabel,
|
||||
title,
|
||||
className
|
||||
}: StatusDotProps): React.JSX.Element {
|
||||
return (
|
||||
<span
|
||||
aria-hidden={ariaLabel ? undefined : true}
|
||||
aria-label={ariaLabel}
|
||||
className={cn(statusDotVariants({ tone, size, pulse }), className)}
|
||||
data-pulse={pulse ? "true" : undefined}
|
||||
data-size={size}
|
||||
data-slot="status-dot"
|
||||
data-tone={tone}
|
||||
role={ariaLabel ? "img" : undefined}
|
||||
title={title}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { StatusDot, statusDotVariants };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./switch";
|
||||
@@ -0,0 +1,45 @@
|
||||
import * as React from "react";
|
||||
import { Switch as SwitchPrimitive } from "radix-ui";
|
||||
|
||||
import { LoadingIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
disabled,
|
||||
loading = false,
|
||||
size = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
|
||||
loading?: boolean;
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
data-size={size}
|
||||
data-loading={loading ? "true" : "false"}
|
||||
aria-busy={loading || undefined}
|
||||
disabled={loading || disabled}
|
||||
className={cn(
|
||||
"peer group/switch relative inline-flex shrink-0 items-center rounded-full border border-transparent transition-[background-color,border-color,box-shadow] outline-none focus-visible:border-[var(--border-focus)] focus-visible:ring-2 focus-visible:ring-[color-mix(in_srgb,var(--border-focus)_30%,transparent)] aria-invalid:border-[var(--state-danger)] aria-invalid:ring-2 aria-invalid:ring-[color-mix(in_srgb,var(--state-danger)_20%,transparent)] data-[size=default]:h-[18px] data-[size=default]:w-[32px] data-[size=sm]:h-[14px] data-[size=sm]:w-[24px] data-[state=checked]:bg-[var(--tutti-purple)] data-[state=unchecked]:bg-[var(--text-disabled)] data-disabled:cursor-not-allowed data-disabled:opacity-100 data-[loading=true]:cursor-wait",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className="pointer-events-none inline-flex items-center justify-center rounded-full bg-[var(--white-stationary)] ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 group-data-[size=default]/switch:data-[state=checked]:translate-x-[14px] group-data-[size=sm]/switch:data-[state=checked]:translate-x-[10px] group-data-[size=default]/switch:data-[state=unchecked]:translate-x-0 group-data-[size=sm]/switch:data-[state=unchecked]:translate-x-0"
|
||||
>
|
||||
{loading ? (
|
||||
<LoadingIcon
|
||||
aria-hidden="true"
|
||||
className="size-3 animate-spin text-[var(--tutti-purple)] group-data-[size=sm]/switch:size-2.5"
|
||||
/>
|
||||
) : null}
|
||||
</SwitchPrimitive.Thumb>
|
||||
</SwitchPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Switch };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./textarea";
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"flex field-sizing-content min-h-20 w-full rounded-[6px] border border-transparent bg-[var(--transparency-block)] px-3 py-3 text-[13px] font-normal leading-[1.3] text-[var(--text-primary)] transition-[background-color,border-color,color] outline-none shadow-none placeholder:text-[var(--text-placeholder)] hover:bg-[var(--transparency-hover)] focus:bg-[var(--transparency-hover)] focus-visible:border-transparent focus-visible:bg-[var(--transparency-hover)] focus-visible:ring-0 disabled:cursor-not-allowed disabled:bg-[var(--transparency-block)] disabled:text-[var(--text-disabled)] disabled:opacity-100 aria-invalid:border-[var(--state-danger)] aria-invalid:bg-[var(--transparency-block)] aria-invalid:hover:bg-[var(--transparency-hover)] aria-invalid:focus:bg-[var(--transparency-hover)] aria-invalid:focus-visible:bg-[var(--transparency-hover)] aria-invalid:ring-0 aria-invalid:shadow-none",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./toast";
|
||||
@@ -0,0 +1,223 @@
|
||||
import * as React from "react";
|
||||
import { Toast as ToastPrimitive } from "radix-ui";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import {
|
||||
CloseIcon,
|
||||
FailedFilledIcon,
|
||||
SuccessFilledIcon
|
||||
} from "#icons/system-icons";
|
||||
import { Spinner } from "../spinner";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
const toastDefaultDurationMs = 3000;
|
||||
|
||||
function ToastProvider({
|
||||
duration = toastDefaultDurationMs,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToastPrimitive.Provider>) {
|
||||
return <ToastPrimitive.Provider duration={duration} {...props} />;
|
||||
}
|
||||
|
||||
const ToastVisualContext = React.createContext<{
|
||||
busy: boolean;
|
||||
variant: VariantProps<typeof toastVariants>["variant"];
|
||||
} | null>(null);
|
||||
|
||||
type ToastStatusIconVariant = "destructive" | "success";
|
||||
|
||||
const toastStatusIconByVariant = {
|
||||
destructive: FailedFilledIcon,
|
||||
success: SuccessFilledIcon
|
||||
} satisfies Record<
|
||||
ToastStatusIconVariant,
|
||||
React.ComponentType<{ className?: string }>
|
||||
>;
|
||||
|
||||
function hasToastStatusIcon(
|
||||
variant: VariantProps<typeof toastVariants>["variant"]
|
||||
): variant is ToastStatusIconVariant {
|
||||
return variant === "destructive" || variant === "success";
|
||||
}
|
||||
|
||||
function stripToastTrailingSentencePunctuation(value: string): string {
|
||||
let nextValue = value.replace(/\s+$/u, "");
|
||||
while (nextValue.length > 0) {
|
||||
const last = nextValue.at(-1);
|
||||
if (last === "." || last === "。" || last === ".") {
|
||||
nextValue = nextValue.slice(0, -1).replace(/\s+$/u, "");
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nextValue;
|
||||
}
|
||||
|
||||
function formatToastText(children: React.ReactNode): React.ReactNode {
|
||||
if (typeof children === "string") {
|
||||
return stripToastTrailingSentencePunctuation(children);
|
||||
}
|
||||
const flatChildren = React.Children.toArray(children);
|
||||
if (flatChildren.length === 1 && typeof flatChildren[0] === "string") {
|
||||
return stripToastTrailingSentencePunctuation(flatChildren[0]);
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
||||
const toastVariants = cva(
|
||||
"group pointer-events-auto relative flex min-h-8 min-w-0 max-w-[min(92vw,420px)] items-center justify-center rounded-[8px] px-3 py-1.5 text-center text-[13px] font-normal leading-normal shadow-none transition-all data-closed:fade-out-80 data-closed:slide-out-to-top-full data-open:slide-in-from-top-full data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border border-[var(--toast-neutral-border)] bg-[var(--toast-neutral-bg)] text-[var(--toast-neutral-fg)]",
|
||||
destructive:
|
||||
"border-0 bg-[var(--state-danger)] text-[var(--white-stationary)]",
|
||||
success:
|
||||
"border-0 bg-[var(--state-success)] text-[var(--text-inverted)]"
|
||||
}
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
function ToastRoot({
|
||||
className,
|
||||
variant,
|
||||
busy = false,
|
||||
anchor = "viewport",
|
||||
nodeInsetTopPx = 16,
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToastPrimitive.Root> &
|
||||
VariantProps<typeof toastVariants> & {
|
||||
busy?: boolean;
|
||||
anchor?: "viewport" | "node";
|
||||
nodeInsetTopPx?: number;
|
||||
}) {
|
||||
const isDestructive = variant === "destructive";
|
||||
return (
|
||||
<ToastPrimitive.Root
|
||||
aria-busy={busy}
|
||||
aria-live={isDestructive ? "assertive" : "polite"}
|
||||
data-slot="toast"
|
||||
className={cn(
|
||||
toastVariants({ variant }),
|
||||
anchor === "node" && "absolute left-1/2 -translate-x-1/2",
|
||||
className
|
||||
)}
|
||||
role={isDestructive ? "alert" : "status"}
|
||||
style={{
|
||||
...(anchor === "node" ? { top: `${nodeInsetTopPx}px` } : {}),
|
||||
...style
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<ToastVisualContext.Provider value={{ busy, variant }}>
|
||||
<span className="flex min-w-0 max-w-full flex-col items-center justify-center whitespace-normal break-words text-center">
|
||||
{children}
|
||||
</span>
|
||||
</ToastVisualContext.Provider>
|
||||
</ToastPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ToastTitle({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToastPrimitive.Title>) {
|
||||
const toastVisual = React.useContext(ToastVisualContext);
|
||||
const StatusIcon =
|
||||
toastVisual?.variant && hasToastStatusIcon(toastVisual.variant)
|
||||
? toastStatusIconByVariant[toastVisual.variant]
|
||||
: null;
|
||||
|
||||
return (
|
||||
<ToastPrimitive.Title
|
||||
data-slot="toast-title"
|
||||
className={cn(
|
||||
"inline-flex max-w-full items-center justify-center gap-[6px] text-center text-[13px] font-normal leading-normal",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{toastVisual?.busy ? (
|
||||
<Spinner
|
||||
className="shrink-0 text-current"
|
||||
size={16}
|
||||
strokeWidth={2}
|
||||
trackColor="color-mix(in srgb, currentColor 28%, transparent)"
|
||||
/>
|
||||
) : StatusIcon ? (
|
||||
<StatusIcon className="size-4 shrink-0 text-current" />
|
||||
) : null}
|
||||
<span className="min-w-0 break-words">{formatToastText(children)}</span>
|
||||
</ToastPrimitive.Title>
|
||||
);
|
||||
}
|
||||
|
||||
function ToastDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToastPrimitive.Description>) {
|
||||
return (
|
||||
<ToastPrimitive.Description
|
||||
data-slot="toast-description"
|
||||
className={cn(
|
||||
"box-border w-full px-2 text-[11px] font-normal leading-[1.3] text-current opacity-75 [overflow-wrap:anywhere]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ToastClose({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToastPrimitive.Close>) {
|
||||
return (
|
||||
<ToastPrimitive.Close
|
||||
data-slot="toast-close"
|
||||
className={cn(
|
||||
"absolute right-1.5 top-1.5 inline-flex size-5 items-center justify-center rounded-[4px] text-current opacity-65 transition-[background-color,opacity] hover:bg-[color-mix(in_srgb,currentColor_10%,transparent)] hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color-mix(in_srgb,currentColor_28%,transparent)]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CloseIcon className="size-4" />
|
||||
</ToastPrimitive.Close>
|
||||
);
|
||||
}
|
||||
|
||||
function ToastViewport({
|
||||
className,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToastPrimitive.Viewport>) {
|
||||
return (
|
||||
<ToastPrimitive.Viewport
|
||||
data-slot="toast-viewport"
|
||||
className={cn(
|
||||
"fixed left-1/2 top-3 flex max-h-screen w-auto -translate-x-1/2 flex-col items-center gap-2 p-0",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-toast)", ...style }}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
ToastProvider,
|
||||
ToastRoot,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastViewport,
|
||||
toastVariants
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./tooltip";
|
||||
@@ -0,0 +1,68 @@
|
||||
import * as React from "react";
|
||||
import { Tooltip as TooltipPrimitive } from "radix-ui";
|
||||
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Portal>) {
|
||||
return <TooltipPrimitive.Portal data-slot="tooltip-portal" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 8,
|
||||
children,
|
||||
style,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPortal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-2 rounded-md border border-[var(--border-1)] bg-[var(--background-fronted)] px-2 py-1 text-[13px] leading-[1.3] text-popover-foreground shadow-soft outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
style={{ zIndex: "var(--z-tooltip, 100700)", ...style }}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPortal>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipPortal,
|
||||
TooltipProvider,
|
||||
TooltipTrigger
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./underline-tabs";
|
||||
@@ -0,0 +1,242 @@
|
||||
import type { JSX, ReactNode } from "react";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "#icons/system-icons";
|
||||
import { cn } from "#lib/utils";
|
||||
|
||||
export interface UnderlineTabItem<TValue extends string> {
|
||||
value: TValue;
|
||||
label: ReactNode;
|
||||
count?: ReactNode;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
interface UnderlineTabsProps<TValue extends string> {
|
||||
tabs: ReadonlyArray<UnderlineTabItem<TValue>>;
|
||||
value: TValue;
|
||||
onValueChange: (value: TValue) => void;
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
testId?: string;
|
||||
viewportTestId?: string;
|
||||
scrollLeftLabel?: string;
|
||||
scrollRightLabel?: string;
|
||||
scrollLeftTestId?: string;
|
||||
scrollRightTestId?: string;
|
||||
preventMouseDownDefault?: boolean;
|
||||
}
|
||||
|
||||
function UnderlineTabs<TValue extends string>({
|
||||
tabs,
|
||||
value,
|
||||
onValueChange,
|
||||
ariaLabel,
|
||||
className,
|
||||
testId,
|
||||
viewportTestId,
|
||||
scrollLeftLabel = "Scroll left",
|
||||
scrollRightLabel = "Scroll right",
|
||||
scrollLeftTestId,
|
||||
scrollRightTestId,
|
||||
preventMouseDownDefault = false
|
||||
}: UnderlineTabsProps<TValue>): JSX.Element {
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
const rowRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRefs = useRef<Partial<Record<TValue, HTMLButtonElement>>>({});
|
||||
const [indicatorStyle, setIndicatorStyle] = useState({ left: 0, width: 0 });
|
||||
const [overflow, setOverflow] = useState({
|
||||
canScrollLeft: false,
|
||||
canScrollRight: false
|
||||
});
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const row = rowRef.current;
|
||||
const button = buttonRefs.current[value];
|
||||
if (!row || !button) {
|
||||
setIndicatorStyle((current) =>
|
||||
current.left === 0 && current.width === 0
|
||||
? current
|
||||
: { left: 0, width: 0 }
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const nextStyle = {
|
||||
left: button.offsetLeft,
|
||||
width: button.offsetWidth
|
||||
};
|
||||
|
||||
setIndicatorStyle((current) =>
|
||||
current.left === nextStyle.left && current.width === nextStyle.width
|
||||
? current
|
||||
: nextStyle
|
||||
);
|
||||
}, [tabs, value]);
|
||||
|
||||
useEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
const syncOverflow = () => {
|
||||
const maxScrollLeft = viewport.scrollWidth - viewport.clientWidth;
|
||||
setOverflow((current) => {
|
||||
const next = {
|
||||
canScrollLeft: viewport.scrollLeft > 1,
|
||||
canScrollRight: viewport.scrollLeft < maxScrollLeft - 1
|
||||
};
|
||||
|
||||
return current.canScrollLeft === next.canScrollLeft &&
|
||||
current.canScrollRight === next.canScrollRight
|
||||
? current
|
||||
: next;
|
||||
});
|
||||
};
|
||||
|
||||
syncOverflow();
|
||||
viewport.addEventListener("scroll", syncOverflow, { passive: true });
|
||||
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
if (typeof ResizeObserver !== "undefined") {
|
||||
resizeObserver = new ResizeObserver(syncOverflow);
|
||||
resizeObserver.observe(viewport);
|
||||
if (rowRef.current) {
|
||||
resizeObserver.observe(rowRef.current);
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("resize", syncOverflow);
|
||||
|
||||
return () => {
|
||||
viewport.removeEventListener("scroll", syncOverflow);
|
||||
window.removeEventListener("resize", syncOverflow);
|
||||
resizeObserver?.disconnect();
|
||||
};
|
||||
}, [tabs]);
|
||||
|
||||
const scrollTabs = (direction: "left" | "right") => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
const delta = Math.max(120, viewport.clientWidth * 0.72);
|
||||
viewport.scrollBy({
|
||||
left: direction === "left" ? -delta : delta,
|
||||
behavior: "smooth"
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
"group relative box-border h-[33px] min-w-0 border-b border-[var(--border-1)] px-4",
|
||||
className
|
||||
)}
|
||||
data-slot="underline-tabs"
|
||||
data-testid={testId}
|
||||
role="tablist"
|
||||
>
|
||||
<div
|
||||
ref={viewportRef}
|
||||
className={cn(
|
||||
"h-8 overflow-x-auto overflow-y-hidden [scrollbar-gutter:stable] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
|
||||
overflow.canScrollLeft &&
|
||||
!overflow.canScrollRight &&
|
||||
"[mask-image:linear-gradient(90deg,transparent_0,black_28px,black_100%)] [-webkit-mask-image:linear-gradient(90deg,transparent_0,black_28px,black_100%)]",
|
||||
!overflow.canScrollLeft &&
|
||||
overflow.canScrollRight &&
|
||||
"[mask-image:linear-gradient(90deg,black_0,black_calc(100%_-_28px),transparent_100%)] [-webkit-mask-image:linear-gradient(90deg,black_0,black_calc(100%_-_28px),transparent_100%)]",
|
||||
overflow.canScrollLeft &&
|
||||
overflow.canScrollRight &&
|
||||
"[mask-image:linear-gradient(90deg,transparent_0,black_28px,black_calc(100%_-_28px),transparent_100%)] [-webkit-mask-image:linear-gradient(90deg,transparent_0,black_28px,black_calc(100%_-_28px),transparent_100%)]"
|
||||
)}
|
||||
data-can-scroll-left={overflow.canScrollLeft ? "true" : "false"}
|
||||
data-can-scroll-right={overflow.canScrollRight ? "true" : "false"}
|
||||
data-slot="underline-tabs-viewport"
|
||||
data-testid={viewportTestId}
|
||||
>
|
||||
<div
|
||||
ref={rowRef}
|
||||
className="relative flex h-8 w-max min-w-full items-center gap-[14px] pb-2"
|
||||
>
|
||||
{tabs.map((tab) => {
|
||||
const isActive = value === tab.value;
|
||||
return (
|
||||
<button
|
||||
key={tab.value}
|
||||
ref={(element) => {
|
||||
if (element) {
|
||||
buttonRefs.current[tab.value] = element;
|
||||
} else {
|
||||
delete buttonRefs.current[tab.value];
|
||||
}
|
||||
}}
|
||||
aria-selected={isActive}
|
||||
className={cn(
|
||||
"relative inline-flex h-6 shrink-0 items-center gap-1.5 whitespace-nowrap border-0 bg-transparent p-0 text-[13px] font-medium leading-6 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none",
|
||||
isActive && "text-[var(--tutti-purple)]"
|
||||
)}
|
||||
data-active={isActive ? "true" : "false"}
|
||||
data-slot="underline-tabs-tab"
|
||||
data-testid={tab.testId}
|
||||
role="tab"
|
||||
type="button"
|
||||
onClick={() => onValueChange(tab.value)}
|
||||
onMouseDown={
|
||||
preventMouseDownDefault
|
||||
? (event) => event.preventDefault()
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<span>{tab.label}</span>
|
||||
{tab.count !== undefined ? (
|
||||
<span className="text-[11px] font-medium leading-6 text-[inherit]">
|
||||
{tab.count}
|
||||
</span>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute bottom-0 left-0 z-[1] h-0.5 rounded-[1px] bg-[var(--tutti-purple)] transition-[transform,width] duration-[220ms] ease-[cubic-bezier(0.4,0,0.2,1)] motion-reduce:transition-none"
|
||||
data-slot="underline-tabs-indicator"
|
||||
style={{
|
||||
transform: `translateX(${indicatorStyle.left}px)`,
|
||||
width: indicatorStyle.width
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
aria-label={scrollLeftLabel}
|
||||
className="pointer-events-none absolute left-4 top-3 z-[3] inline-flex size-6 translate-y-[-50%] scale-[0.94] items-center justify-center rounded-full border-0 bg-[var(--background-fronted)] p-0 text-[var(--text-secondary)] opacity-0 shadow-[0_4px_16px_rgba(15,23,42,0.12)] transition-[opacity,transform,background-color,color] duration-[160ms] ease-in-out hover:bg-[var(--background-fronted)] hover:text-[var(--text-primary)] focus-visible:bg-[var(--background-fronted)] focus-visible:text-[var(--text-primary)] group-hover:data-[visible=true]:pointer-events-auto group-hover:data-[visible=true]:scale-100 group-hover:data-[visible=true]:opacity-100 group-focus-within:data-[visible=true]:pointer-events-auto group-focus-within:data-[visible=true]:scale-100 group-focus-within:data-[visible=true]:opacity-100 disabled:pointer-events-none"
|
||||
data-slot="underline-tabs-scroll-left"
|
||||
data-testid={scrollLeftTestId}
|
||||
data-visible={overflow.canScrollLeft ? "true" : "false"}
|
||||
disabled={!overflow.canScrollLeft}
|
||||
type="button"
|
||||
onClick={() => scrollTabs("left")}
|
||||
>
|
||||
<ArrowLeftIcon size={16} />
|
||||
</button>
|
||||
<button
|
||||
aria-label={scrollRightLabel}
|
||||
className="pointer-events-none absolute right-4 top-3 z-[3] inline-flex size-6 translate-y-[-50%] scale-[0.94] items-center justify-center rounded-full border-0 bg-[var(--background-fronted)] p-0 text-[var(--text-secondary)] opacity-0 shadow-[0_4px_16px_rgba(15,23,42,0.12)] transition-[opacity,transform,background-color,color] duration-[160ms] ease-in-out hover:bg-[var(--background-fronted)] hover:text-[var(--text-primary)] focus-visible:bg-[var(--background-fronted)] focus-visible:text-[var(--text-primary)] group-hover:data-[visible=true]:pointer-events-auto group-hover:data-[visible=true]:scale-100 group-hover:data-[visible=true]:opacity-100 group-focus-within:data-[visible=true]:pointer-events-auto group-focus-within:data-[visible=true]:scale-100 group-focus-within:data-[visible=true]:opacity-100 disabled:pointer-events-none"
|
||||
data-slot="underline-tabs-scroll-right"
|
||||
data-testid={scrollRightTestId}
|
||||
data-visible={overflow.canScrollRight ? "true" : "false"}
|
||||
disabled={!overflow.canScrollRight}
|
||||
type="button"
|
||||
onClick={() => scrollTabs("right")}
|
||||
>
|
||||
<ArrowRightIcon size={16} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { UnderlineTabs };
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./viewport-menu-surface";
|
||||
@@ -0,0 +1,462 @@
|
||||
import * as React from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
import { MenuSurface } from "../menu-surface";
|
||||
|
||||
export interface MenuSize {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface MenuPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export type MenuPointAlignment = "start" | "end" | "auto";
|
||||
|
||||
interface AbsoluteViewportMenuPlacement {
|
||||
type: "absolute";
|
||||
left: number;
|
||||
top: number;
|
||||
boundaryPoint?: MenuPoint;
|
||||
constrainToBoundary?: boolean;
|
||||
}
|
||||
|
||||
interface PointViewportMenuPlacement {
|
||||
type: "point";
|
||||
point: MenuPoint;
|
||||
boundaryPoint?: MenuPoint;
|
||||
alignX?: MenuPointAlignment;
|
||||
alignY?: MenuPointAlignment;
|
||||
padding?: number;
|
||||
estimatedSize?: MenuSize;
|
||||
}
|
||||
|
||||
export type ViewportMenuPlacement =
|
||||
| AbsoluteViewportMenuPlacement
|
||||
| PointViewportMenuPlacement;
|
||||
|
||||
export interface ViewportMenuSurfaceProps extends Omit<
|
||||
React.HTMLAttributes<HTMLDivElement>,
|
||||
"children"
|
||||
> {
|
||||
open: boolean;
|
||||
placement: ViewportMenuPlacement;
|
||||
children: React.ReactNode;
|
||||
onDismiss?: () => void;
|
||||
dismissOnPointerDownOutside?: boolean;
|
||||
dismissOnEscape?: boolean;
|
||||
dismissOnScroll?: boolean;
|
||||
dismissIgnoreRefs?: Array<React.RefObject<HTMLElement | null>>;
|
||||
stopEventPropagation?: boolean;
|
||||
}
|
||||
|
||||
const VIEWPORT_MENU_PADDING = 12;
|
||||
const MENU_BOUNDARY_PADDING = 8;
|
||||
|
||||
interface MenuBoundaryRect {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface MenuBoundary {
|
||||
portalTarget: Element | null;
|
||||
rect: MenuBoundaryRect;
|
||||
}
|
||||
|
||||
function clampMenuCoordinate(
|
||||
origin: number,
|
||||
size: number,
|
||||
viewportExtent: number,
|
||||
padding: number
|
||||
): number {
|
||||
return Math.max(
|
||||
padding,
|
||||
Math.min(origin, Math.max(padding, viewportExtent - padding - size))
|
||||
);
|
||||
}
|
||||
|
||||
function resolveAlignedCoordinate(options: {
|
||||
origin: number;
|
||||
size: number;
|
||||
viewportExtent: number;
|
||||
padding: number;
|
||||
alignment: MenuPointAlignment;
|
||||
}): number {
|
||||
const { origin, size, viewportExtent, padding, alignment } = options;
|
||||
const startCoordinate = origin;
|
||||
const endCoordinate = origin - size;
|
||||
|
||||
if (alignment === "start") {
|
||||
return clampMenuCoordinate(startCoordinate, size, viewportExtent, padding);
|
||||
}
|
||||
|
||||
if (alignment === "end") {
|
||||
return clampMenuCoordinate(endCoordinate, size, viewportExtent, padding);
|
||||
}
|
||||
|
||||
const startFits = startCoordinate + size <= viewportExtent - padding;
|
||||
const endFits = endCoordinate >= padding;
|
||||
|
||||
if (startFits || !endFits) {
|
||||
return clampMenuCoordinate(startCoordinate, size, viewportExtent, padding);
|
||||
}
|
||||
|
||||
return clampMenuCoordinate(endCoordinate, size, viewportExtent, padding);
|
||||
}
|
||||
|
||||
function placeViewportMenuAtPoint(options: {
|
||||
point: MenuPoint;
|
||||
menuSize: MenuSize;
|
||||
viewport: { width: number; height: number };
|
||||
padding?: number;
|
||||
alignX?: MenuPointAlignment;
|
||||
alignY?: MenuPointAlignment;
|
||||
}): { left: number; top: number } {
|
||||
const padding = options.padding ?? VIEWPORT_MENU_PADDING;
|
||||
|
||||
return {
|
||||
left: resolveAlignedCoordinate({
|
||||
origin: options.point.x,
|
||||
size: options.menuSize.width,
|
||||
viewportExtent: options.viewport.width,
|
||||
padding,
|
||||
alignment: options.alignX ?? "start"
|
||||
}),
|
||||
top: resolveAlignedCoordinate({
|
||||
origin: options.point.y,
|
||||
size: options.menuSize.height,
|
||||
viewportExtent: options.viewport.height,
|
||||
padding,
|
||||
alignment: options.alignY ?? "start"
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function viewportBoundary(): MenuBoundaryRect {
|
||||
return {
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: typeof window === "undefined" ? 1280 : window.innerWidth,
|
||||
height: typeof window === "undefined" ? 720 : window.innerHeight
|
||||
};
|
||||
}
|
||||
|
||||
function rectToBoundary(rect: DOMRect): MenuBoundaryRect {
|
||||
return {
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
width: rect.width,
|
||||
height: rect.height
|
||||
};
|
||||
}
|
||||
|
||||
function resolveMenuBoundaryFromPoint(point: {
|
||||
x: number;
|
||||
y: number;
|
||||
}): MenuBoundary {
|
||||
if (typeof document === "undefined" || !document.elementsFromPoint) {
|
||||
return {
|
||||
portalTarget: null,
|
||||
rect: viewportBoundary()
|
||||
};
|
||||
}
|
||||
|
||||
const selector = '[data-slot="viewport-menu-boundary"]';
|
||||
for (const element of document.elementsFromPoint(point.x, point.y)) {
|
||||
const boundaryElement = element.closest(selector);
|
||||
if (boundaryElement) {
|
||||
return {
|
||||
portalTarget:
|
||||
boundaryElement.getAttribute("data-viewport-menu-portal-target") ===
|
||||
"body"
|
||||
? null
|
||||
: boundaryElement,
|
||||
rect: rectToBoundary(boundaryElement.getBoundingClientRect())
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
portalTarget: null,
|
||||
rect: viewportBoundary()
|
||||
};
|
||||
}
|
||||
|
||||
function clampMenuPositionToBoundary(options: {
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
boundary: MenuBoundaryRect;
|
||||
padding?: number;
|
||||
}): { left: number; top: number } {
|
||||
const padding = options.padding ?? MENU_BOUNDARY_PADDING;
|
||||
const minLeft = options.boundary.left + padding;
|
||||
const minTop = options.boundary.top + padding;
|
||||
const maxLeft = Math.max(
|
||||
minLeft,
|
||||
options.boundary.left + options.boundary.width - padding - options.width
|
||||
);
|
||||
const maxTop = Math.max(
|
||||
minTop,
|
||||
options.boundary.top + options.boundary.height - padding - options.height
|
||||
);
|
||||
|
||||
return {
|
||||
left: Math.max(minLeft, Math.min(options.left, maxLeft)),
|
||||
top: Math.max(minTop, Math.min(options.top, maxTop))
|
||||
};
|
||||
}
|
||||
|
||||
function assignRef<T>(ref: React.ForwardedRef<T>, value: T): void {
|
||||
if (typeof ref === "function") {
|
||||
ref(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ref) {
|
||||
ref.current = value;
|
||||
}
|
||||
}
|
||||
|
||||
function callHandler<E extends React.SyntheticEvent>(
|
||||
handler: ((event: E) => void) | undefined,
|
||||
event: E
|
||||
): void {
|
||||
handler?.(event);
|
||||
}
|
||||
|
||||
const ViewportMenuSurface = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
ViewportMenuSurfaceProps
|
||||
>(function ViewportMenuSurface(
|
||||
{
|
||||
open,
|
||||
placement,
|
||||
children,
|
||||
onDismiss,
|
||||
dismissOnPointerDownOutside = false,
|
||||
dismissOnEscape = false,
|
||||
dismissOnScroll = false,
|
||||
dismissIgnoreRefs = [],
|
||||
stopEventPropagation = true,
|
||||
style,
|
||||
onMouseDown,
|
||||
onClick,
|
||||
className,
|
||||
...rest
|
||||
},
|
||||
forwardedRef
|
||||
): React.JSX.Element | null {
|
||||
const surfaceRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const [measuredSize, setMeasuredSize] = React.useState<MenuSize | null>(null);
|
||||
|
||||
const setRefs = React.useCallback(
|
||||
(node: HTMLDivElement | null) => {
|
||||
surfaceRef.current = node;
|
||||
assignRef(forwardedRef, node);
|
||||
},
|
||||
[forwardedRef]
|
||||
);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
if (!open) {
|
||||
setMeasuredSize(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const element = surfaceRef.current;
|
||||
if (!element) {
|
||||
setMeasuredSize(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const updateMeasuredSize = () => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
setMeasuredSize((previous) =>
|
||||
previous &&
|
||||
Math.abs(previous.width - rect.width) < 0.5 &&
|
||||
Math.abs(previous.height - rect.height) < 0.5
|
||||
? previous
|
||||
: { width: rect.width, height: rect.height }
|
||||
);
|
||||
};
|
||||
|
||||
updateMeasuredSize();
|
||||
|
||||
if (typeof ResizeObserver === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(updateMeasuredSize);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, [open, placement]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!onDismiss ||
|
||||
(!dismissOnPointerDownOutside && !dismissOnEscape && !dismissOnScroll)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldIgnoreTarget = (target: EventTarget | null): boolean => {
|
||||
if (!(target instanceof Node)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (surfaceRef.current?.contains(target)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return dismissIgnoreRefs.some(
|
||||
(ref) => ref.current?.contains(target) ?? false
|
||||
);
|
||||
};
|
||||
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
if (!dismissOnPointerDownOutside) {
|
||||
return;
|
||||
}
|
||||
if (shouldIgnoreTarget(event.target)) {
|
||||
return;
|
||||
}
|
||||
onDismiss();
|
||||
};
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (!dismissOnEscape || event.key !== "Escape") {
|
||||
return;
|
||||
}
|
||||
onDismiss();
|
||||
};
|
||||
|
||||
const handleScroll = () => {
|
||||
if (dismissOnScroll) {
|
||||
onDismiss();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("pointerdown", handlePointerDown, true);
|
||||
window.addEventListener("keydown", handleKeyDown, true);
|
||||
window.addEventListener("scroll", handleScroll, {
|
||||
capture: true,
|
||||
passive: true
|
||||
});
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", handlePointerDown, true);
|
||||
window.removeEventListener("keydown", handleKeyDown, true);
|
||||
window.removeEventListener("scroll", handleScroll, true);
|
||||
};
|
||||
}, [
|
||||
dismissIgnoreRefs,
|
||||
dismissOnEscape,
|
||||
dismissOnPointerDownOutside,
|
||||
dismissOnScroll,
|
||||
onDismiss,
|
||||
open
|
||||
]);
|
||||
|
||||
const resolvedPlacement = React.useMemo(() => {
|
||||
if (placement.type === "absolute") {
|
||||
const boundary = resolveMenuBoundaryFromPoint(
|
||||
placement.boundaryPoint ?? {
|
||||
x: placement.left,
|
||||
y: placement.top
|
||||
}
|
||||
);
|
||||
const menuSize = measuredSize ?? { width: 0, height: 0 };
|
||||
return {
|
||||
portalTarget: boundary.portalTarget,
|
||||
position:
|
||||
placement.constrainToBoundary === false
|
||||
? {
|
||||
left: placement.left,
|
||||
top: placement.top
|
||||
}
|
||||
: clampMenuPositionToBoundary({
|
||||
left: placement.left,
|
||||
top: placement.top,
|
||||
width: menuSize.width,
|
||||
height: menuSize.height,
|
||||
boundary: boundary.rect
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
const boundary = resolveMenuBoundaryFromPoint(
|
||||
placement.boundaryPoint ?? placement.point
|
||||
);
|
||||
const menuSize = measuredSize ??
|
||||
placement.estimatedSize ?? { width: 0, height: 0 };
|
||||
const relativePoint = {
|
||||
x: placement.point.x - boundary.rect.left,
|
||||
y: placement.point.y - boundary.rect.top
|
||||
};
|
||||
const relativePosition = placeViewportMenuAtPoint({
|
||||
point: relativePoint,
|
||||
menuSize,
|
||||
viewport: { width: boundary.rect.width, height: boundary.rect.height },
|
||||
padding: placement.padding,
|
||||
alignX: placement.alignX,
|
||||
alignY: placement.alignY
|
||||
});
|
||||
|
||||
return {
|
||||
portalTarget: boundary.portalTarget,
|
||||
position: {
|
||||
left: boundary.rect.left + relativePosition.left,
|
||||
top: boundary.rect.top + relativePosition.top
|
||||
}
|
||||
};
|
||||
}, [measuredSize, placement]);
|
||||
|
||||
if (!open || typeof document === "undefined" || !document.body) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const portalTarget = resolvedPlacement.portalTarget ?? document.body;
|
||||
|
||||
return createPortal(
|
||||
<MenuSurface
|
||||
{...rest}
|
||||
ref={setRefs}
|
||||
className={className}
|
||||
data-slot="viewport-menu-surface"
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: resolvedPlacement.position.top,
|
||||
left: resolvedPlacement.position.left,
|
||||
zIndex: "var(--z-popover)",
|
||||
...style
|
||||
}}
|
||||
onClick={(event) => {
|
||||
if (stopEventPropagation) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
callHandler(onClick, event);
|
||||
}}
|
||||
onMouseDown={(event) => {
|
||||
if (stopEventPropagation) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
callHandler(onMouseDown, event);
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</MenuSurface>,
|
||||
portalTarget
|
||||
);
|
||||
});
|
||||
|
||||
export { ViewportMenuSurface };
|
||||
@@ -0,0 +1,14 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { getPackageRoot } from "./fileManifest.js";
|
||||
|
||||
export async function loadComponentsMetadata(): Promise<unknown> {
|
||||
const metadataPath = path.join(
|
||||
getPackageRoot(),
|
||||
"src/metadata/components.json"
|
||||
);
|
||||
const metadata = await readFile(metadataPath, "utf8");
|
||||
|
||||
return JSON.parse(metadata);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { lstat, readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import type { UISystemDevFile } from "./protocol.js";
|
||||
|
||||
const packageRoot = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../.."
|
||||
);
|
||||
|
||||
const rejectedSegments = new Set([
|
||||
".git",
|
||||
"coverage",
|
||||
"dist",
|
||||
"node_modules",
|
||||
"test-results"
|
||||
]);
|
||||
const allowedRootFiles = new Set([
|
||||
"AGENTS.md",
|
||||
"README.md",
|
||||
"ui-system.md",
|
||||
"package.json"
|
||||
]);
|
||||
const allowedSkillPathPrefix = "agent/tutti-ui-system/";
|
||||
|
||||
export function getPackageRoot(): string {
|
||||
return packageRoot;
|
||||
}
|
||||
|
||||
export function normalizeSyncPath(input: string): string | null {
|
||||
if (hasTraversalSegment(input)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let decoded: string;
|
||||
|
||||
try {
|
||||
decoded = decodeURIComponent(input);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (hasTraversalSegment(decoded)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const slashPath = decoded.replaceAll("\\", "/").replace(/^\/+/, "");
|
||||
const normalized = path.posix.normalize(slashPath);
|
||||
|
||||
if (normalized === "." || normalized.startsWith("../")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function hasTraversalSegment(input: string): boolean {
|
||||
return input.replaceAll("\\", "/").split("/").includes("..");
|
||||
}
|
||||
|
||||
export function isAllowedSyncPath(input: string): boolean {
|
||||
const syncPath = normalizeSyncPath(input);
|
||||
|
||||
if (syncPath === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parts = syncPath.split("/");
|
||||
|
||||
if (
|
||||
parts.some(
|
||||
(part) =>
|
||||
rejectedSegments.has(part) ||
|
||||
part.startsWith(".env") ||
|
||||
part.endsWith(".log")
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (allowedRootFiles.has(syncPath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (syncPath.startsWith(allowedSkillPathPrefix)) {
|
||||
return (
|
||||
syncPath.endsWith(".json") ||
|
||||
syncPath.endsWith(".md") ||
|
||||
syncPath.endsWith(".mjs")
|
||||
);
|
||||
}
|
||||
|
||||
if (!syncPath.startsWith("src/")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (syncPath.startsWith("src/metadata/") && syncPath.endsWith(".json")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
syncPath.endsWith(".ts") ||
|
||||
syncPath.endsWith(".tsx") ||
|
||||
syncPath.endsWith(".css")
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveAllowedFile(input: string): string | null {
|
||||
const syncPath = normalizeSyncPath(input);
|
||||
|
||||
if (syncPath === null || !isAllowedSyncPath(syncPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const absolutePath = path.resolve(packageRoot, syncPath);
|
||||
const relativePath = path.relative(packageRoot, absolutePath);
|
||||
|
||||
if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return absolutePath;
|
||||
}
|
||||
|
||||
export async function hashFile(absolutePath: string): Promise<string> {
|
||||
const fileStat = await lstat(absolutePath);
|
||||
|
||||
if (fileStat.isSymbolicLink() || !fileStat.isFile()) {
|
||||
throw new Error(`Refusing to hash non-regular file: ${absolutePath}`);
|
||||
}
|
||||
|
||||
const bytes = await readFile(absolutePath);
|
||||
const hash = createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
return `sha256:${hash}`;
|
||||
}
|
||||
|
||||
export async function getSyncFile(
|
||||
input: string
|
||||
): Promise<UISystemDevFile | null> {
|
||||
const syncPath = normalizeSyncPath(input);
|
||||
const absolutePath = resolveAllowedFile(input);
|
||||
|
||||
if (syncPath === null || absolutePath === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileStat = await lstat(absolutePath);
|
||||
|
||||
if (fileStat.isSymbolicLink() || !fileStat.isFile()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
path: syncPath,
|
||||
hash: await hashFile(absolutePath),
|
||||
size: fileStat.size
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSyncFiles(): Promise<UISystemDevFile[]> {
|
||||
const files = await Promise.all([
|
||||
...Array.from(allowedRootFiles, (syncPath) => getSyncFile(syncPath)),
|
||||
...(
|
||||
await listSyncPaths(
|
||||
path.join(packageRoot, "agent", "tutti-ui-system"),
|
||||
"agent/tutti-ui-system"
|
||||
)
|
||||
).map((syncPath) => getSyncFile(syncPath)),
|
||||
...(await listSyncPaths(path.join(packageRoot, "src"), "src")).map(
|
||||
(syncPath) => getSyncFile(syncPath)
|
||||
)
|
||||
]);
|
||||
|
||||
return files
|
||||
.filter((file): file is UISystemDevFile => file !== null)
|
||||
.sort((left, right) => left.path.localeCompare(right.path));
|
||||
}
|
||||
|
||||
async function listSyncPaths(
|
||||
absoluteDirectory: string,
|
||||
syncDirectory: string
|
||||
): Promise<string[]> {
|
||||
const entries = await readdir(absoluteDirectory, { withFileTypes: true });
|
||||
const paths = await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const syncPath = `${syncDirectory}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory() && isRejectedPath(syncPath)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
return listSyncPaths(
|
||||
path.join(absoluteDirectory, entry.name),
|
||||
syncPath
|
||||
);
|
||||
}
|
||||
|
||||
return isAllowedSyncPath(syncPath) ? [syncPath] : [];
|
||||
})
|
||||
);
|
||||
|
||||
return paths.flat();
|
||||
}
|
||||
|
||||
function isRejectedPath(syncPath: string): boolean {
|
||||
const parts = syncPath.split("/");
|
||||
|
||||
return parts.some(
|
||||
(part) =>
|
||||
rejectedSegments.has(part) ||
|
||||
part.startsWith(".env") ||
|
||||
part.endsWith(".log")
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export type UISystemDevManifest = {
|
||||
packageName: "@tutti-os/ui-system";
|
||||
version: string;
|
||||
entrypoints: Record<string, string>;
|
||||
tailwindSourceRoot: "src";
|
||||
componentsMetadata: "src/metadata/components.json";
|
||||
};
|
||||
|
||||
export type UISystemDevFile = {
|
||||
path: string;
|
||||
hash: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type UISystemDevEvent =
|
||||
| { type: "fileChanged"; path: string; hash: string }
|
||||
| { type: "fileDeleted"; path: string }
|
||||
| { type: "manifestChanged" }
|
||||
| { type: "componentsChanged" };
|
||||
@@ -0,0 +1,258 @@
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type ServerResponse
|
||||
} from "node:http";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { watch, type FSWatcher } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
|
||||
import { loadComponentsMetadata } from "./components.js";
|
||||
import {
|
||||
getPackageRoot,
|
||||
getSyncFile,
|
||||
getSyncFiles,
|
||||
hashFile,
|
||||
isAllowedSyncPath,
|
||||
normalizeSyncPath,
|
||||
resolveAllowedFile
|
||||
} from "./fileManifest.js";
|
||||
import type { UISystemDevEvent, UISystemDevManifest } from "./protocol.js";
|
||||
|
||||
const packageName = "@tutti-os/ui-system";
|
||||
const host = process.env.UI_SYSTEM_DEV_SERVER_HOST ?? "127.0.0.1";
|
||||
const port = Number(process.env.UI_SYSTEM_DEV_SERVER_PORT ?? 4100);
|
||||
|
||||
const manifest: UISystemDevManifest = {
|
||||
packageName,
|
||||
version: "0.1.0",
|
||||
entrypoints: {
|
||||
".": "src/index.ts",
|
||||
"./components": "src/components/index.ts",
|
||||
"./icons": "src/icons/index.ts",
|
||||
"./native": "src/native/index.ts",
|
||||
"./native.css": "src/styles/native.css",
|
||||
"./styles.css": "src/styles/index.css",
|
||||
"./utils": "src/lib/utils.ts"
|
||||
},
|
||||
tailwindSourceRoot: "src",
|
||||
componentsMetadata: "src/metadata/components.json"
|
||||
};
|
||||
|
||||
const server = createServer((request, response) => {
|
||||
void handleRequest(request, response);
|
||||
});
|
||||
|
||||
async function handleRequest(
|
||||
request: IncomingMessage,
|
||||
response: ServerResponse
|
||||
): Promise<void> {
|
||||
if (request.method !== "GET" || request.url === undefined) {
|
||||
sendNotFound(response);
|
||||
return;
|
||||
}
|
||||
|
||||
const rawPathname = request.url.split(/[?#]/, 1)[0] ?? "/";
|
||||
const url = new URL(request.url, `http://${host}:${port}`);
|
||||
|
||||
try {
|
||||
if (url.pathname === "/health") {
|
||||
sendJson(response, { ok: true, packageName });
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/manifest") {
|
||||
sendJson(response, manifest);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rawPathname === "/files") {
|
||||
sendJson(response, await getSyncFiles());
|
||||
return;
|
||||
}
|
||||
|
||||
if (rawPathname.startsWith("/files/")) {
|
||||
await sendFile(response, rawPathname.slice("/files/".length));
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/components") {
|
||||
sendJson(response, await loadComponentsMetadata());
|
||||
return;
|
||||
}
|
||||
|
||||
sendNotFound(response);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
sendJson(response, { error: message }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
const events = new WebSocketServer({ noServer: true });
|
||||
const watchers: FSWatcher[] = [];
|
||||
|
||||
server.on("upgrade", (request, socket, head) => {
|
||||
const url = new URL(request.url ?? "/", `http://${host}:${port}`);
|
||||
|
||||
if (url.pathname !== "/events") {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
events.handleUpgrade(request, socket, head, (websocket) => {
|
||||
events.emit("connection", websocket, request);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, host, () => {
|
||||
console.log(
|
||||
`@tutti-os/ui-system dev server listening on http://${host}:${port}`
|
||||
);
|
||||
});
|
||||
|
||||
startWatching();
|
||||
|
||||
process.on("SIGINT", stop);
|
||||
process.on("SIGTERM", stop);
|
||||
|
||||
async function sendFile(
|
||||
response: ServerResponse,
|
||||
requestPath: string
|
||||
): Promise<void> {
|
||||
const syncPath = normalizeSyncPath(requestPath);
|
||||
const absolutePath = syncPath === null ? null : resolveAllowedFile(syncPath);
|
||||
|
||||
if (syncPath === null || absolutePath === null) {
|
||||
sendNotFound(response);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const file = await getSyncFile(syncPath);
|
||||
|
||||
if (file === null) {
|
||||
sendNotFound(response);
|
||||
return;
|
||||
}
|
||||
|
||||
const bytes = await readFile(absolutePath);
|
||||
response.writeHead(200, {
|
||||
"Content-Length": bytes.byteLength,
|
||||
"Content-Type": contentTypeForPath(syncPath)
|
||||
});
|
||||
response.end(bytes);
|
||||
} catch {
|
||||
sendNotFound(response);
|
||||
}
|
||||
}
|
||||
|
||||
function sendJson(
|
||||
response: ServerResponse,
|
||||
payload: unknown,
|
||||
statusCode = 200
|
||||
): void {
|
||||
const body = JSON.stringify(payload, null, 2);
|
||||
response.writeHead(statusCode, {
|
||||
"Content-Length": Buffer.byteLength(body),
|
||||
"Content-Type": "application/json; charset=utf-8"
|
||||
});
|
||||
response.end(body);
|
||||
}
|
||||
|
||||
function sendNotFound(response: ServerResponse): void {
|
||||
sendJson(response, { error: "Not found" }, 404);
|
||||
}
|
||||
|
||||
function contentTypeForPath(syncPath: string): string {
|
||||
if (syncPath.endsWith(".json")) {
|
||||
return "application/json; charset=utf-8";
|
||||
}
|
||||
|
||||
if (syncPath.endsWith(".css")) {
|
||||
return "text/css; charset=utf-8";
|
||||
}
|
||||
|
||||
if (syncPath.endsWith(".md")) {
|
||||
return "text/markdown; charset=utf-8";
|
||||
}
|
||||
|
||||
return "text/plain; charset=utf-8";
|
||||
}
|
||||
|
||||
function startWatching(): void {
|
||||
watchPath(path.join(getPackageRoot(), "src"), true);
|
||||
watchPath(path.join(getPackageRoot(), "agent"), true);
|
||||
watchPath(getPackageRoot(), false);
|
||||
}
|
||||
|
||||
function watchPath(absolutePath: string, recursive: boolean): void {
|
||||
try {
|
||||
watchers.push(
|
||||
watch(absolutePath, { recursive }, (_eventType, filename) => {
|
||||
if (filename === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
void publishPathEvent(
|
||||
path.relative(getPackageRoot(), path.join(absolutePath, filename))
|
||||
);
|
||||
})
|
||||
);
|
||||
} catch {
|
||||
// Watching is best-effort for local development; HTTP endpoints remain usable.
|
||||
}
|
||||
}
|
||||
|
||||
async function publishPathEvent(syncPathInput: string): Promise<void> {
|
||||
const syncPath = normalizeSyncPath(syncPathInput);
|
||||
|
||||
if (syncPath === null || !isAllowedSyncPath(syncPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (syncPath === "package.json") {
|
||||
broadcast({ type: "manifestChanged" });
|
||||
}
|
||||
|
||||
if (syncPath === "src/metadata/components.json") {
|
||||
broadcast({ type: "componentsChanged" });
|
||||
}
|
||||
|
||||
const absolutePath = resolveAllowedFile(syncPath);
|
||||
|
||||
if (absolutePath === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
broadcast({
|
||||
type: "fileChanged",
|
||||
path: syncPath,
|
||||
hash: await hashFile(absolutePath)
|
||||
});
|
||||
} catch {
|
||||
broadcast({ type: "fileDeleted", path: syncPath });
|
||||
}
|
||||
}
|
||||
|
||||
function broadcast(event: UISystemDevEvent): void {
|
||||
const payload = JSON.stringify(event);
|
||||
|
||||
for (const client of events.clients) {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stop(): void {
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
events.close();
|
||||
server.close(() => {
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { tuttiUISystemDev } from "./plugins/vite.ts";
|
||||
export type { TuttiUISystemDevOptions } from "./plugins/vite.ts";
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { IconProps } from "./types";
|
||||
|
||||
export function ChangeLined({
|
||||
className,
|
||||
size = 24,
|
||||
title,
|
||||
...props
|
||||
}: IconProps) {
|
||||
const dimension = typeof size === "number" ? `${size}` : size;
|
||||
|
||||
return (
|
||||
<svg
|
||||
aria-hidden={title ? undefined : true}
|
||||
className={className}
|
||||
fill="none"
|
||||
height={dimension}
|
||||
viewBox="0 0 24 24"
|
||||
width={dimension}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
{title ? <title>{title}</title> : null}
|
||||
<path
|
||||
d="M19 14.5008C19.4044 14.5008 19.769 14.7444 19.9238 15.118C20.0785 15.4916 19.993 15.9219 19.707 16.2079L16.207 19.7079C15.8165 20.098 15.1834 20.0981 14.793 19.7079C14.4027 19.3175 14.4028 18.6843 14.793 18.2938L16.5859 16.5008H5C4.44813 16.5006 4.00027 16.0527 4 15.5008C4 14.9487 4.44796 14.5011 5 14.5008H19ZM7.79297 4.2928C8.18344 3.90236 8.8165 3.90244 9.20703 4.2928C9.59751 4.68331 9.59751 5.31634 9.20703 5.70686L7.41406 7.49984H19C19.5521 7.49999 19.9999 7.9477 20 8.49984C19.9999 9.05197 19.5521 9.4997 19 9.49985H5C4.59573 9.49967 4.23091 9.25617 4.07617 8.88266C3.92146 8.50912 4.00722 8.0788 4.29297 7.79281L7.79297 4.2928Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./layout-preset-icons";
|
||||
export * from "./tutti-mark";
|
||||
export * from "./tutti-mark-new";
|
||||
export * from "./change-lined";
|
||||
export * from "./system-icons";
|
||||
export type { IconProps } from "./types";
|
||||
Loaded 100 of 8018 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user