Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(ui-lab): add design system workbench (MUL-7425) (#8388)
Jiayuan Zhang0cb64a77aa12
diff --git a/.github/ci-paths.json b/.github/ci-paths.jsonindex a67b6a9e29..03368772da 100644--- a/.github/ci-paths.json+++ b/.github/ci-paths.json@@ -3,6 +3,7 @@".github/actions/frontend-quality/**","apps/web/**","apps/desktop/**",+ "apps/ui-lab/**","packages/**","package.json",".npmrc",diff --git a/AGENTS.md b/AGENTS.mdindex d3fc6e58aa..c87d399ee1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -101,6 +101,8 @@ Workspace-scoped queries filter by `workspace_id`; membership gates access and `## Web/Desktop UI Rules+- For Button and Dialog usage, read `packages/ui/docs/button.md` and `packages/ui/docs/dialog.md`. These component contracts also power UI Lab documentation.+- Prefer existing shadcn/Base UI primitives. Add components with `pnpm ui:add <component>`.- For `pnpm ui:add @reui/<name>`, decline overwrite prompts. Keep `REUI_LICENSE_KEY` in the environment, never in repo files. Adapt vendored primitives into `packages/ui/components/ui/` and compositions into `packages/views/`.- Use shared semantic tokens in `packages/ui/styles/`. Typography uses the role-named `--text-*` scale in `packages/ui/styles/tokens.css`, not Tailwind's default size ramp.diff --git a/apps/ui-lab/README.md b/apps/ui-lab/README.mdnew file mode 100644index 0000000000..a1df3cd71b--- /dev/null+++ b/apps/ui-lab/README.md@@ -0,0 +1,219 @@+# Multica UI Lab++An internal, independently running design workbench for Multica Web and Desktop.++```sh+pnpm install+pnpm dev:ui-lab+```++Vite starts at http://127.0.0.1:4310 (or the next available port). No backend,+workspace, login, or environment file is required. This does not start Electron+or the public web application.++The interface defaults to English. Use EN / 中文 in the header to switch the+workbench and all previews together. The browser remembers your language; switching+languages preserves design overrides, saved schemes, and local sample edits.++## Catalog structure++The overview links to six modules: Foundations, Components, Patterns, Product,+Layouts, and Changes. Each module has an index and a collapsible navigation group.+Pages marked **To build** are placeholders; their content and editing controls are+not implemented yet. Button, Dialog and the component gallery live under+Components. Foundations → Colors edits semantic colors, and Motion previews shared Dialog motion; production issue list/detail previews live under Layouts. Changes+contains the working token review, saved designs, and CSS export pages. Impact+analysis and source application remain planned.++Pages have hash URLs (for example `#/components/button`) that support direct links,+reload, and browser back/forward. Drafts and edit history stay in the workbench+while navigating. Only live preview pages display the property inspector.++To add content, update the page entry in `src/catalog.ts`, provide the renderer,+and add English/Chinese copy in `src/locales/`. The registry supplies navigation,+module indexes, availability counts, and route validation. Preview scenes still+use the validated iframe protocol in `src/protocol.ts`.++## Workflow++1. Choose Button, Dialog, Motion, the component gallery, or an issue list/detail fixture.+2. Adjust a semantic color in the light or dark theme. Typography, radius and+ issue row height apply to both themes. Changes are isolated to the preview.+3. Switch to the original or compare both versions side by side. On small+ workbench windows the comparison scrolls horizontally instead of shrinking+ the previews to unreadable sizes.+4. Undo/redo edits, reset to the source defaults, or save a named scheme.+5. Export or copy CSS and merge the declarations into the matching `@theme`,+ `:root`, and `.dark` blocks in `packages/ui/styles/tokens.css`. The Lab never+ writes to source files. The CSS is a patch to merge, not a replacement file.++The current draft and up to 20 named schemes are stored in this browser's+localStorage, scoped to the dev server origin. Saved schemes contain absolute+overrides; reopening them against newer code applies them over the new defaults.+Defaults are read directly from the shared CSS, never from a second theme file.+This first version does not sync schemes or import files. Export CSS before+clearing browser data or changing ports. All sample edits stay inside the frame.++## Preview fidelity++- The gallery imports production primitives directly from `@multica/ui`. Its+ cards only arrange specimens; they do not override control styles. CSS resets+ remain in the base layer so they cannot override Tailwind component utilities.+- Business previews mount the production `IssuesPage`, `IssueDetail`, and+ `AppSidebar` from `@multica/views`. They include the real ListRow, toolbars,+ property pickers, rich-text editor, comment cards and responsive sidebar.+ There are no recreated list/detail/sidebar templates or page-specific CSS.+- `product-preview.tsx` supplies the platform providers used by these views:+ navigation, workspace identity, React Query, auth/chat stores, i18n, tooltips,+ sidebar and a disconnected realtime context. Preview assets load lazily; a+ ready handshake applies the latest design after the frame finishes mounting.+- `product-fixtures.ts` replaces only API results with typed, deterministic data.+ Each frame owns its fixture client. Issue edits and comments stay in memory;+ refreshing restores them. Unsupported operations reject explicitly and never+ fall through to the network. Navigation is limited to issue list/detail.+ This is a visual workbench, not a full backend simulator. Other groupings,+ advanced filter combinations, uploads and agent execution are not supported.+- `--issue-row-height` is used by the production `ListRow`. Its default remains+ 36px. First-paint spacers use the same token before scroll restoration;+ virtualization starts from the rendered seed row height and measures subsequent+ changes. Table and board density are independent. Other design changes still+ export to the shared token file.+- The frame's sidebar follows product breakpoints. Use the real sidebar toggle+ when the preview width triggers automatic collapse. Theme, portals and fonts+ are isolated from the workbench controls and the original comparison frame.++## Verify++```sh+pnpm --filter @multica/ui-lab typecheck+pnpm --filter @multica/ui-lab lint+pnpm --filter @multica/ui-lab test+pnpm --filter @multica/ui-lab build+```++The pure tests cover source token parsing, CSS export scope, restored defaults,+undo/redo, persistence, the validated iframe message protocol, fixture isolation+and rejection of unsupported network operations. Browser smoke+checks should include theme/typography changes, original comparison, Dialog+portals, local scheme reload and CSS download.++## Button workbench++The Button page is the first dedicated component page. It mounts the shared+`Button` with all eight variants and eight sizes. The playground supports text,+leading/trailing icons, icon-only content, disabled, loading and invalid states.+Hover, focus and pressed feedback come from real pointer/keyboard interaction;+the gallery does not synthesize these pseudo states. Popover and Dialog examples+exercise the real portal components. Example submissions stay local.++The size selector controls the playground and variant matrix in both frames.+Twelve `--button-*` variables in `packages/ui/styles/tokens.css` cover height,+horizontal padding and icon/text gap for `xs`, `sm`, `default` and `lg`. Icon-only+buttons share the height ladder. The initial values preserve the production+geometry, including inline icon padding offsets. Explicit class overrides at+call sites retain precedence (for example `h-7`, `size-6` and `px-2`).++Button variables are shared between light/dark themes and export to `:root`;+typography still exports to `@theme`, and colors to `:root` / `.dark`. Existing+save, undo, redo, original comparison and CSS export apply to these variables.+Reset Button parameters clears only the button overrides. Exported CSS must be+merged into the shared source file; the workbench does not write source files.++## Color editor++Color roles appear as labeled swatch rows; click one to open the color picker.+The sRGB picker supports+pointer/touch dragging and keyboard adjustment, HEX input, quick colors, copy,+and original/current comparison. OKLCH controls remain under Precision adjustment.+A color-plane or hue drag previews live and commits one undo step on release.++Color.js converts edited HEX values to OKLCH for persistence/export. Opening the+picker does not quantize the source color. Out-of-sRGB colors retain their exact+OKLCH value; only the HEX/plane preview uses a gamut-mapped approximation. HEX+input accepts 3 or 6 digits; opacity has a separate numeric/scrub control. Color+and OKLCH edits preserve existing alpha, including transparent dark-mode borders. The chroma validation+range is 0–0.4 to include saturated sRGB colors such as pure blue.++## Property inspector++The right panel follows the compact property grouping and swatch-triggered popup+pattern described in [Figma's property panel guide](https://help.figma.com/hc/en-us/articles/360039832014-Design-prototype-and-explore-layer-properties-in-the-right-sidebar).+Design shows component dimensions separately from global appearance, colors and+typography. The Changes tab lists original/current values with per-token reset.++Numeric fields commit on Enter or blur, clamp to the supported bounds, and reject+non-numeric text. Arrow keys adjust by the field's step; Shift uses 10× and Alt+uses 0.1×. Drag the field prefix to scrub with live preview and one undo step on+release. Escape cancels a scrub or discards typed input. Color rows open the+existing color editor toward the canvas; Escape closes it and returns focus.+++## Dialog and Motion++`#/components/dialog` and `#/foundations/motion` mount the real shared Dialog.+Choose a form or long-content composition. The frame toolbar opens, closes and+replays the dialog, including after its exit animation completes. Playback speed+is 1×, 0.5× or 0.25× and is local to each comparison frame; it is never saved or+exported as a product setting.++The inspector edits `--dialog-enter-duration`, `--dialog-exit-duration`,+`--dialog-enter-easing` and `--dialog-exit-easing`. Popup and backdrop consume+these variables. Existing 100ms/ease defaults are preserved, with shared easing+presets sourced from `@multica/ui/lib/motion`. Saved schemes, undo/redo and CSS+export include these tokens. They affect shared Dialog consumers only, not+Popover, Tooltip, AlertDialog or JavaScript animation constants.++Reduced motion disables popup/backdrop animation, including during slow playback.+Verify Escape, focus restoration, required field validation, long-content scroll,+rapid open/close, replay, and both themes. Frame commands accept only a known+same-origin parent and a validated action. Timeline scrubbing, recording and+frame-state export are not implemented.++## Component rules++Button and Dialog have a collapsed Usage & code section backed directly by+`packages/ui/docs/{button,dialog}{,.zh}.md`, with Markdown downloads. These files+are also readable by agents and document supported APIs, usage, correct/incorrect+examples, affected tokens and how to apply exported changes. Keep the rules next+to the production components up to date when their contracts change.+++## Colors++`#/foundations/colors` exposes 43 existing semantic colors in seven groups:+surfaces, content, actions, feedback, borders/focus, charts and sidebar. Search+by localized label or token name, then select a swatch to edit it in the right+inspector. Original comparison, both themes, live preview, saved schemes,+undo/redo and CSS export use the same draft as all other component pages.++Background, card and popover aliases point to their existing source tokens;+selecting an alias edits its target rather than replacing the relationship.+HEX is a gamut-mapped RGB display; the separate opacity control preserves+transparency, while OKLCH retains the source color. Percentage and decimal+alpha are equivalent when restoring defaults. Specialty tokens such as scrollbar+and find highlights are not part of this initial catalog.++The **Usage & contrast** tab maps the current main action, active filter, line+Tabs, Input, focus and error roles to editable tokens. It mounts production+Button, Tabs and Input; hover/press/focus come from real browser interactions,+with local disabled/error toggles. Click a mapping token to edit it. The controls+keep their current production styles instead of simulating states with Lab CSS.++The light brand defaults to `#0070E3`. Dark mode retains its brighter source+brand because the same token also paints body-text links on dark surfaces.++Contrast is measured from computed styles after transitions, recalculated on+interaction, token edits and theme changes. The checker composites nested alpha+backgrounds and foregrounds in sRGB and compares unrounded WCAG ratios. Text is+checked at 4.5:1; focused borders at 3:1 against both adjacent surfaces, respecting+background clipping. Disabled controls are exempt. Unsupported backgrounds or+group opacity show “Not measured”, not a pass. This covers these sample color+pairs only: placeholders, tab indicators, focus-ring geometry and complete WCAG+compliance still need separate review. Current source colors may fail; the+checker reports failures without silently changing production tokens.++Use each sidebar’s header icon to collapse it; restore icons appear on the+corresponding side of the canvas heading. Desktop+panel preferences persist across routes and reloads, separately from design+drafts. On narrow screens the left toggle opens the navigation drawer; the+right panel closes from its own header and reopens from the canvas heading.diff --git a/apps/ui-lab/docs/ui-lab.png b/apps/ui-lab/docs/ui-lab.pngnew file mode 100644index 0000000000..e9aa559b3aBinary files /dev/null and b/apps/ui-lab/docs/ui-lab.png differdiff --git a/apps/ui-lab/eslint.config.mjs b/apps/ui-lab/eslint.config.mjsnew file mode 100644index 0000000000..2d0e006f09--- /dev/null+++ b/apps/ui-lab/eslint.config.mjs@@ -0,0 +1,2 @@+import reactConfig from "@multica/eslint-config/react";+export default [...reactConfig, { ignores: ["dist/"] }];diff --git a/apps/ui-lab/index.html b/apps/ui-lab/index.htmlnew file mode 100644index 0000000000..3dbdb60493--- /dev/null+++ b/apps/ui-lab/index.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="theme-color" content="#f6f6f7" />+ <title>Multica UI Lab</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/apps/ui-lab/package.json b/apps/ui-lab/package.jsonnew file mode 100644index 0000000000..52eeae4561--- /dev/null+++ b/apps/ui-lab/package.json@@ -0,0 +1,45 @@+{+ "name": "@multica/ui-lab",+ "version": "0.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "dev": "vite --host 127.0.0.1 --port 4310",+ "build": "vite build",+ "preview": "vite preview --host 127.0.0.1 --port 4310",+ "typecheck": "tsc --noEmit",+ "lint": "eslint .",+ "test": "vitest run"+ },+ "dependencies": {+ "@fontsource-variable/inter": "^5.2.5",+ "@multica/core": "workspace:*",+ "@multica/ui": "workspace:*",+ "@multica/views": "workspace:*",+ "@tanstack/react-query": "catalog:",+ "colorjs.io": "^0.7.1",+ "i18next": "catalog:",+ "lucide-react": "catalog:",+ "react": "catalog:",+ "react-colorful": "^5.8.1",+ "react-dom": "catalog:",+ "react-i18next": "catalog:",+ "shadcn": "^4.1.0",+ "sonner": "^2.0.7",+ "tw-animate-css": "^1.4.0"+ },+ "devDependencies": {+ "@multica/eslint-config": "workspace:*",+ "@multica/tsconfig": "workspace:*",+ "@tailwindcss/vite": "catalog:",+ "@types/node": "catalog:",+ "@types/react": "catalog:",+ "@types/react-dom": "catalog:",+ "@vitejs/plugin-react": "catalog:",+ "eslint": "^9.0.0",+ "tailwindcss": "catalog:",+ "typescript": "catalog:",+ "vite": "^8.0.1",+ "vitest": "catalog:"+ }+}diff --git a/apps/ui-lab/src/app.tsx b/apps/ui-lab/src/app.tsxnew file mode 100644index 0000000000..7fad7f9040--- /dev/null+++ b/apps/ui-lab/src/app.tsx@@ -0,0 +1,811 @@+import { useSyncExternalStore } from "react";+import { resolveCatalogRoute, pageHref } from "./catalog";+import { CatalogNavigation } from "./catalog-navigation";+import { CatalogContent } from "./catalog-content";+import { LabI18nProvider } from "./lab-i18n";+import { loadLocale, LOCALE_STORAGE_KEY, type LabLocale } from "./locale";+import { useTranslation } from "react-i18next";+import { useCallback, useEffect, useReducer, useRef, useState } from "react";+import {+ ArrowDownToLine,+ Check,+ ChevronRight,+ Code2,+ Columns2,+ Copy,+ Moon,+ PanelLeft,+ PanelLeftClose,+ PanelLeftOpen,+ PanelRightClose,+ PanelRightOpen,+ Redo2,+ Save,+ Sun,+ Trash2,+ Undo2,+ X,+} from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { MulticaIcon } from "@multica/ui/components/common/multica-icon";+import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ type ButtonScale,+ isColorToken,+ type ColorToken,+ changeCount,+ editHistory,+ emptyDraft,+ exportCss,+ tokenValue,+ numericTokenValue,+ updateToken,+ type Draft,+ type Theme,+} from "./tokens";+import { Inspector } from "./inspector";+import {+ playbackSpeeds,+ isColorSelection,+ dialogActions,+ type DialogCommand,+ type PreviewSettings,+ type Scene,+} from "./protocol";+import {+ encodeSession,+ loadSession,+ STORAGE_KEY,+ type SavedDesign,+} from "./storage";++function PreviewFrame({+ draft,+ theme,+ scene,+ buttonScale,+ original = false,+ selectedColor,+ onColorSelect,+}: {+ draft: Draft;+ theme: Theme;+ scene: Scene;+ buttonScale: ButtonScale;+ original?: boolean;+ selectedColor: ColorToken;+ onColorSelect: (token: string) => void;+}) {+ const { t, i18n } = useTranslation("uiLab");+ const locale: LabLocale = i18n.language === "zh-Hans" ? "zh" : "en";+ const ref = useRef<HTMLIFrameElement>(null);+ const [playbackSpeed, setPlaybackSpeed] = useState(1);+ const send = useCallback(() => {+ ref.current?.contentWindow?.postMessage(+ {+ type: "multica-ui-lab:preview",+ draft,+ theme,+ scene,+ buttonScale,+ locale,+ playbackSpeed,+ selectedColor,+ } satisfies PreviewSettings,+ location.origin,+ );+ }, [draft, theme, scene, buttonScale, locale, playbackSpeed, selectedColor]);+ useEffect(() => {+ const onReady = (event: MessageEvent<{ type?: string }>) => {+ if (+ event.origin === location.origin &&+ event.source === ref.current?.contentWindow &&+ scene === "colors" &&+ isColorSelection(event.data)+ )+ onColorSelect(event.data.token);+ if (+ event.origin === location.origin &&+ event.source === ref.current?.contentWindow &&+ event.data?.type === "multica-ui-lab:ready"+ )+ send();+ };+ window.addEventListener("message", onReady);+ send();+ return () => window.removeEventListener("message", onReady);+ }, [send, scene, onColorSelect]);+ return (+ <section className="preview-frame">+ <div className="frame-toolbar">+ <span className={`frame-dot ${original ? "" : "is-live"}`} />+ <span>+ {original+ ? t(($) => $.lab.preview.source)+ : t(($) => $.lab.preview.preview)}+ </span>+ <span className="ml-auto">+ {theme === "light"+ ? t(($) => $.lab.theme.light)+ : t(($) => $.lab.theme.dark)}+ </span>+ </div>+ {(scene === "dialog" || scene === "motion") && (+ <div className="motion-toolbar">+ {dialogActions.map((action) => (+ <Button+ key={action}+ variant="ghost"+ size="sm"+ onClick={() =>+ ref.current?.contentWindow?.postMessage(+ {+ type: "multica-ui-lab:dialog",+ action,+ } satisfies DialogCommand,+ location.origin,+ )+ }+ >+ {t(($) => $.motion.actions[action])}+ </Button>+ ))}+ <label>+ <span>{t(($) => $.motion.controls.speed)}</span>+ <select+ value={playbackSpeed}+ onChange={(event) => setPlaybackSpeed(Number(event.target.value))}+ >+ {playbackSpeeds.map((speed) => (+ <option key={speed} value={speed}>+ {speed}×+ </option>+ ))}+ </select>+ </label>+ </div>+ )}+ <iframe+ ref={ref}+ src="?preview"+ title={+ original+ ? t(($) => $.lab.preview.originalFrame)+ : t(($) => $.lab.preview.editedFrame)+ }+ onLoad={send}+ />+ </section>+ );+}+const originalDraft = emptyDraft();+const subscribeRoute = (notify: () => void) => {+ window.addEventListener("hashchange", notify);+ return () => window.removeEventListener("hashchange", notify);+};+const routeSnapshot = () => window.location.hash;++export function App() {+ const [locale, setLocale] = useState(loadLocale);+ return (+ <LabI18nProvider locale={locale}>+ <Workbench locale={locale} onLocaleChange={setLocale} />+ </LabI18nProvider>+ );+}++function Workbench({+ locale,+ onLocaleChange,+}: {+ locale: LabLocale;+ onLocaleChange: (locale: LabLocale) => void;+}) {+ const { t } = useTranslation("uiLab");+ const [session] = useState(loadSession);+ const [history, dispatch] = useReducer(editHistory, {+ past: [],+ present: session.draft,+ future: [],+ });+ const draft = history.present;+ const [theme, setTheme] = useState<Theme>("light");+ const hash = useSyncExternalStore(subscribeRoute, routeSnapshot);+ const route = resolveCatalogRoute(hash);+ const scene =+ route.kind === "page" && route.page.content.kind === "preview"+ ? route.page.content.scene+ : null;+ const [buttonScale, setButtonScale] = useState<ButtonScale>("default");+ const [compare, setCompare] = useState(false);+ const [original, setOriginal] = useState(false);+ const [numberPreview, setNumberPreview] = useState<{+ key: string;+ value: number;+ } | null>(null);+ const [colorPreview, setColorPreview] = useState<string | null>(null);+ const [color, setColor] = useState<ColorToken>("--brand");+ const selectColor = useCallback((key: string) => {+ if (!isColorToken(key)) return;+ setColorPreview(null);+ setNumberPreview(null);+ setColor(key);+ }, []);+ const [designs, setDesigns] = useState<SavedDesign[]>(session.designs);+ const [saveOpen, setSaveOpen] = useState(false);+ const [exportOpen, setExportOpen] = useState(false);+ const [name, setName] = useState("");+ const [notice, setNotice] = useState<{+ key: "saved" | "copied" | "copyFailed" | "exported" | "loaded";+ name?: string;+ } | null>(null);+ const [storageError, setStorageError] = useState(false);+ const [navOpen, setNavOpen] = useState(false);+ const [panels, setPanels] = useState(() => {+ try {+ const saved = JSON.parse(+ localStorage.getItem("multica-ui-lab:panels") ?? "null",+ );+ return {+ leftCollapsed: saved?.leftCollapsed === true,+ rightCollapsed: saved?.rightCollapsed === true,+ };+ } catch {+ return { leftCollapsed: false, rightCollapsed: false };+ }+ });+ useEffect(() => {+ try {+ localStorage.setItem("multica-ui-lab:panels", JSON.stringify(panels));+ } catch {+ /* Panel toggles remain usable when storage is unavailable. */+ }+ }, [panels]);+ const count = changeCount(draft);+ const title =+ route.kind === "overview"+ ? t(($) => $.system.navigation.title)+ : route.kind === "notFound"+ ? t(($) => $.system.empty.notFound)+ : route.kind === "module"+ ? t(($) => $.system.modules[route.module.id])+ : t(($) => $.system.pages[route.page.id]);+ useEffect(() => {+ setColorPreview(null);+ setNumberPreview(null);+ setOriginal(false);+ setCompare(false);+ setNavOpen(false);+ }, [hash]);+ const currentColor = colorPreview ?? tokenValue(draft, theme, color);+ const previewDraft = colorPreview+ ? updateToken(draft, theme, color, colorPreview)+ : numberPreview+ ? updateToken(+ draft,+ "shared",+ numberPreview.key,+ numericTokenValue(numberPreview.key, numberPreview.value),+ )+ : draft;+ const css = exportCss(draft);+ useEffect(() => {+ try {+ localStorage.setItem(STORAGE_KEY, encodeSession({ draft, designs }));+ localStorage.setItem(LOCALE_STORAGE_KEY, locale);+ setStorageError(false);+ } catch {+ setStorageError(true);+ }+ }, [draft, designs, locale]);+ useEffect(() => {+ if (!notice) return;+ const timer = window.setTimeout(() => setNotice(null), 4000);+ return () => window.clearTimeout(timer);+ }, [notice]);+ const edit = (next: Draft) => {+ setColorPreview(null);+ setNumberPreview(null);+ dispatch({ type: "edit", draft: next });+ setOriginal(false);+ };+ const saveDesign = () => {+ if (!name.trim()) return;+ setDesigns(+ [+ {+ id: crypto.randomUUID(),+ name: name.trim(),+ draft,+ savedAt: new Date().toISOString(),+ },+ ...designs,+ ].slice(0, 20),+ );+ setName("");+ setSaveOpen(false);+ setNotice({ key: "saved" });+ };+ const copyCss = async () => {+ try {+ await navigator.clipboard.writeText(css);+ setNotice({ key: "copied" });+ } catch {+ setNotice({ key: "copyFailed" });+ }+ };+ const downloadCss = () => {+ const url = URL.createObjectURL(+ new Blob([css], { type: "text/css;charset=utf-8" }),+ );+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = "multica-ui-tokens.css";+ anchor.click();+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);+ setNotice({ key: "exported" });+ };+ const leftPanelToggleRef = useRef<HTMLButtonElement>(null);+ const rightPanelToggleRef = useRef<HTMLButtonElement>(null);+ const leftPanelToggle = (+ <Button+ ref={leftPanelToggleRef}+ className="desktop-nav-toggle"+ size="icon-sm"+ variant="ghost"+ aria-label={t(+ ($) =>+ $.lab.panels[panels.leftCollapsed ? "expandLeft" : "collapseLeft"],+ )}+ title={t(+ ($) =>+ $.lab.panels[panels.leftCollapsed ? "expandLeft" : "collapseLeft"],+ )}+ aria-expanded={!panels.leftCollapsed}+ aria-controls="lab-navigation"+ onClick={() => {+ setPanels((current) => ({+ ...current,+ leftCollapsed: !current.leftCollapsed,+ }));+ requestAnimationFrame(() => leftPanelToggleRef.current?.focus());+ }}+ >+ {panels.leftCollapsed ? <PanelLeftOpen /> : <PanelLeftClose />}+ </Button>+ );+ const rightPanelToggle = (+ <Button+ ref={rightPanelToggleRef}+ size="icon-sm"+ variant="ghost"+ aria-label={t(+ ($) =>+ $.lab.panels[panels.rightCollapsed ? "expandRight" : "collapseRight"],+ )}+ title={t(+ ($) =>+ $.lab.panels[panels.rightCollapsed ? "expandRight" : "collapseRight"],+ )}+ aria-expanded={!panels.rightCollapsed}+ aria-controls="lab-inspector-panel"+ onClick={() => {+ setColorPreview(null);+ setNumberPreview(null);+ setPanels((current) => ({+ ...current,+ rightCollapsed: !current.rightCollapsed,+ }));+ requestAnimationFrame(() => rightPanelToggleRef.current?.focus());+ }}+ >+ {panels.rightCollapsed ? <PanelRightOpen /> : <PanelRightClose />}+ </Button>+ );+ return (+ <div+ className={`lab-shell ${scene ? "" : "catalog-shell"} ${panels.leftCollapsed ? "nav-collapsed" : ""} ${panels.rightCollapsed ? "inspector-collapsed" : ""}`}+ >+ <header className="lab-header">+ <Button+ className="mobile-nav-toggle"+ size="icon"+ variant="ghost"+ aria-label={t(($) => $.lab.nav.toggle)}+ aria-expanded={navOpen}+ aria-controls="lab-navigation"+ onClick={() => setNavOpen(!navOpen)}+ >+ <PanelLeft />+ </Button>+ <a className="lab-brand" href="#/overview" aria-label="Multica UI Lab">+ <span className="logo-mark">+ <MulticaIcon className="size-4" noSpin />+ </span>+ <strong>multica</strong>+ <span className="brand-divider" />+ <span>UI Lab</span>+ </a>+ <span className="internal-label">{t(($) => $.lab.nav.internal)}</span>+ <div className="header-actions">+ <div+ className="language-toggle"+ role="group"+ aria-label={t(($) => $.lab.language.label)}+ >+ {(["en", "zh"] as const).map((value) => (+ <Button+ key={value}+ size="sm"+ variant={locale === value ? "secondary" : "ghost"}+ aria-pressed={locale === value}+ lang={value === "zh" ? "zh-Hans" : "en"}+ onClick={() => onLocaleChange(value)}+ >+ {value === "en" ? "EN" : "中文"}+ </Button>+ ))}+ </div>+ <Button+ variant="ghost"+ size="icon"+ aria-label={t(($) => $.lab.actions.undo)}+ title={t(($) => $.lab.actions.undo)}+ disabled={!history.past.length}+ onClick={() => dispatch({ type: "undo" })}+ >+ <Undo2 />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ aria-label={t(($) => $.lab.actions.redo)}+ title={t(($) => $.lab.actions.redo)}+ disabled={!history.future.length}+ onClick={() => dispatch({ type: "redo" })}+ >+ <Redo2 />+ </Button>+ <span className="header-separator" />+ <Button+ variant="outline"+ aria-label={t(($) => $.lab.actions.save)}+ onClick={() => setSaveOpen(true)}+ >+ <Save />+ <span>{t(($) => $.lab.actions.save)}</span>+ </Button>+ <Button+ aria-label={t(($) => $.lab.actions.export)}+ onClick={() => setExportOpen(true)}+ >+ <Code2 />+ <span>{t(($) => $.lab.actions.export)}</span>+ </Button>+ </div>+ </header>+ <aside+ id="lab-navigation"+ className={`lab-nav ${navOpen ? "nav-open" : ""}`}+ >+ <div className="lab-nav-header">+ <span>{t(($) => $.system.navigation.title)}</span>+ {!panels.leftCollapsed && leftPanelToggle}+ </div>+ <CatalogNavigation route={route} onNavigate={() => setNavOpen(false)} />+ </aside>+ <main className="lab-main">+ <div className="workspace-heading">+ <div className="workspace-heading-left">+ {panels.leftCollapsed && leftPanelToggle}+ <div>+ {route.kind !== "overview" && (+ <div className="workspace-breadcrumb">+ <a href="#/overview">+ {t(($) => $.system.navigation.overview)}+ </a>+ {route.kind === "page" && (+ <>+ <ChevronRight />+ <a href={pageHref(route.module.id)}>+ {t(($) => $.system.modules[route.module.id])}+ </a>+ </>+ )}+ </div>+ )}+ <h1>{title}</h1>+ </div>+ </div>+ {scene && (+ <div className="workspace-heading-actions">+ <div+ className="theme-toggle"+ aria-label={t(($) => $.lab.theme.label)}+ >+ <Button+ variant={theme === "light" ? "secondary" : "ghost"}+ size="icon"+ aria-label={t(($) => $.lab.theme.lightLabel)}+ aria-pressed={theme === "light"}+ onClick={() => {+ setColorPreview(null);+ setTheme("light");+ }}+ >+ <Sun />+ </Button>+ <Button+ variant={theme === "dark" ? "secondary" : "ghost"}+ size="icon"+ aria-label={t(($) => $.lab.theme.darkLabel)}+ aria-pressed={theme === "dark"}+ onClick={() => {+ setColorPreview(null);+ setTheme("dark");+ }}+ >+ <Moon />+ </Button>+ </div>+ {panels.rightCollapsed && rightPanelToggle}+ </div>+ )}+ </div>+ {scene ? (+ <>+ <div className="canvas-toolbar">+ <span className="canvas-caption">+ <span className="status-dot" />+ {count+ ? t(($) => $.lab.preview.changeCount, { count })+ : t(($) => $.lab.preview.unchanged)}+ </span>+ <div className="ml-auto flex gap-1">+ <Button+ variant={original ? "secondary" : "ghost"}+ size="sm"+ aria-pressed={original}+ disabled={compare}+ onClick={() => setOriginal(!original)}+ >+ {original+ ? t(($) => $.lab.preview.back)+ : t(($) => $.lab.preview.original)}+ </Button>+ <Button+ variant={compare ? "secondary" : "ghost"}+ size="sm"+ aria-pressed={compare}+ onClick={() => {+ setCompare(!compare);+ setOriginal(false);+ }}+ >+ <Columns2 />+ {t(($) => $.lab.preview.compare)}+ </Button>+ </div>+ </div>+ <div className={`preview-canvas ${compare ? "compare" : ""}`}>+ {compare && (+ <PreviewFrame+ draft={originalDraft}+ theme={theme}+ scene={scene}+ buttonScale={buttonScale}+ selectedColor={color}+ onColorSelect={selectColor}+ original+ />+ )}+ <PreviewFrame+ draft={original ? originalDraft : previewDraft}+ theme={theme}+ scene={scene}+ buttonScale={buttonScale}+ selectedColor={color}+ onColorSelect={selectColor}+ original={original}+ />+ </div>+ </>+ ) : (+ <CatalogContent+ route={route}+ draft={draft}+ onEdit={edit}+ onSave={() => setSaveOpen(true)}+ onExport={() => setExportOpen(true)}+ savedDesigns={+ <>+ <div className="nav-heading saved-heading">+ {t(($) => $.lab.nav.saved)}+ <span>{String(designs.length).padStart(2, "0")}</span>+ </div>+ <div className="saved-designs">+ {designs.length ? (+ designs.map((design) => (+ <div className="saved-design" key={design.id}>+ <button+ title={design.name}+ onClick={() => {+ edit(design.draft);+ setNotice({ key: "loaded", name: design.name });+ }}+ >+ <span+ className="design-swatch"+ style={{+ background: tokenValue(+ design.draft,+ "light",+ "--brand",+ ),+ }}+ />+ <span>{design.name}</span>+ </button>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.lab.actions.deleteDesign, {+ name: design.name,+ })}+ onClick={() =>+ setDesigns(+ designs.filter((item) => item.id !== design.id),+ )+ }+ >+ <Trash2 />+ </Button>+ </div>+ ))+ ) : (+ <p className="nav-empty">{t(($) => $.lab.nav.empty)}</p>+ )}+ </div>+ </>+ }+ exportContent={+ <>+ <p className="catalog-export-note">+ {t(($) => $.lab.export.description)}+ </p>+ <pre className="export-code" tabIndex={0}>+ <code>{css}</code>+ </pre>+ <div className="flex justify-end gap-2">+ <Button variant="outline" onClick={copyCss}>+ <Copy />+ {t(($) => $.lab.export.copy)}+ </Button>+ <Button onClick={downloadCss}>+ <ArrowDownToLine />+ {t(($) => $.lab.export.download)}+ </Button>+ </div>+ </>+ }+ />+ )}+ </main>+ {scene && (+ <div+ id="lab-inspector-panel"+ className="lab-inspector-slot"+ hidden={panels.rightCollapsed}+ >+ {!panels.rightCollapsed && (+ <Inspector+ panelAction={rightPanelToggle}+ scene={scene}+ theme={theme}+ draft={draft}+ previewDraft={previewDraft}+ buttonScale={buttonScale}+ color={color}+ currentColor={currentColor}+ onScaleChange={setButtonScale}+ onEdit={edit}+ onNumberPreview={(key, value) => {+ setColorPreview(null);+ setNumberPreview({ key, value });+ }}+ onNumberCancel={() => setNumberPreview(null)}+ onColorSelect={selectColor}+ onColorPreview={setColorPreview}+ onColorCancel={() => setColorPreview(null)}+ onExport={() => setExportOpen(true)}+ />+ )}+ </div>+ )}+ {storageError && (+ <div className="storage-warning" role="alert">+ {t(($) => $.lab.notice.storageFailed)}+ </div>+ )}+ {notice && (+ <div className="lab-notice" role="status">+ <Check className="size-4" />+ <span>+ {t(($) => $.lab.notice[notice.key], { name: notice.name })}+ </span>+ <button+ aria-label={t(($) => $.lab.notice.dismiss)}+ onClick={() => setNotice(null)}+ >+ <X className="size-3" />+ </button>+ </div>+ )}+ <Dialog open={saveOpen} onOpenChange={setSaveOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t(($) => $.lab.save.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.lab.save.description)}+ </DialogDescription>+ </DialogHeader>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ saveDesign();+ }}+ >+ <label htmlFor="design-name" className="mb-2 block text-label">+ {t(($) => $.lab.save.name)}+ </label>+ <Input+ id="design-name"+ maxLength={60}+ value={name}+ placeholder={t(($) => $.lab.save.placeholder)}+ onChange={(event) => setName(event.target.value)}+ autoFocus+ />+ <Button+ type="submit"+ className="mt-4 w-full"+ disabled={!name.trim()}+ >+ {t(($) => $.lab.actions.save)}+ </Button>+ </form>+ </DialogContent>+ </Dialog>+ <Dialog open={exportOpen} onOpenChange={setExportOpen}>+ <DialogContent className="sm:max-w-2xl">+ <DialogHeader>+ <DialogTitle>{t(($) => $.lab.export.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.lab.export.description)}+ </DialogDescription>+ </DialogHeader>+ <pre className="export-code" tabIndex={0}>+ <code>{css}</code>+ </pre>+ <div className="flex justify-end gap-2">+ <Button variant="outline" onClick={copyCss}>+ <Copy />+ {t(($) => $.lab.export.copy)}+ </Button>+ <Button onClick={downloadCss}>+ <ArrowDownToLine />+ {t(($) => $.lab.export.download)}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/apps/ui-lab/src/button-scene.tsx b/apps/ui-lab/src/button-scene.tsxnew file mode 100644index 0000000000..5909271d96--- /dev/null+++ b/apps/ui-lab/src/button-scene.tsx@@ -0,0 +1,457 @@+import { ComponentRules } from "./component-rules";+import { useTranslation } from "react-i18next";+import { useEffect, useRef, useState, type ComponentProps } from "react";+import {+ ArrowRight,+ Check,+ ChevronDown,+ Loader2,+ Plus,+ Send,+} from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@multica/ui/components/ui/dialog";+import {+ buttonScales,+ sizeValue,+ tokenValue,+ type ButtonScale,+ type Draft,+} from "./tokens";++type Variant = NonNullable<ComponentProps<typeof Button>["variant"]>;+type Size = NonNullable<ComponentProps<typeof Button>["size"]>;+const iconSizes = {+ xs: "icon-xs",+ sm: "icon-sm",+ default: "icon",+ lg: "icon-lg",+} as const satisfies Record<ButtonScale, Size>;++export function ButtonScene({+ scale,+ draft,+}: {+ scale: ButtonScale;+ draft: Draft;+}) {+ const { t } = useTranslation("uiLab");+ const variants = {+ default: { label: t(($) => $.button.variants.primary) },+ outline: { label: t(($) => $.button.variants.secondary) },+ secondary: { label: t(($) => $.button.variants.soft) },+ ghost: { label: t(($) => $.button.variants.ghost) },+ brand: { label: t(($) => $.button.variants.brand) },+ brandSubtle: {+ label: t(($) => $.button.variants.brandSoft),+ },+ destructive: {+ label: t(($) => $.button.variants.destructive),+ },+ link: { label: t(($) => $.button.variants.link) },+ } satisfies Record<Variant, { label: string }>;+ const entries = Object.entries(variants) as [+ Variant,+ (typeof variants)[Variant],+ ][];+ const [variant, setVariant] = useState<Variant>("default");+ const [label, setLabel] = useState<string | null>(null);+ const [state, setState] = useState("normal");+ const [icon, setIcon] = useState("start");+ const [clicks, setClicks] = useState(0);+ const [sending, setSending] = useState(false);+ const [sent, setSent] = useState(false);+ const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ useEffect(() => () => clearTimeout(timer.current), []);+ const loading = state === "loading";+ const buttonLabel = label?.trim() || t(($) => $.button.actions.create);+ const size = (key: string) =>+ `${sizeValue(tokenValue(draft, "shared", key))}px`;+ return (+ <div className="button-scene">+ <header className="button-intro">+ <h1>{t(($) => $.button.page.title)}</h1>+ <div className="button-meta">+ <span>{t(($) => $.button.page.variantCount)}</span>+ <span>{t(($) => $.button.page.sizeCount)}</span>+ </div>+ </header>+ <nav+ className="button-section-nav"+ aria-label={t(($) => $.button.page.contents)}+ >+ <a href="#button-playground">{t(($) => $.button.page.playground)}</a>+ <a href="#button-variants">{t(($) => $.button.page.variants)}</a>+ <a href="#button-sizes">{t(($) => $.inspector.sections.size)}</a>+ <a href="#button-context">{t(($) => $.button.page.context)}</a>+ </nav>++ <section+ className="button-section"+ id="button-playground"+ aria-labelledby="playground-title"+ >+ <div className="button-section-heading">+ <div>+ <h2 id="playground-title">{t(($) => $.button.page.try)}</h2>+ </div>+ <code>{scale}</code>+ </div>+ <div className="button-playground-controls">+ <label>+ {t(($) => $.button.controls.label)}+ <Input+ aria-label={t(($) => $.button.controls.label)}+ value={label ?? t(($) => $.button.actions.create)}+ maxLength={100}+ onChange={(event) => setLabel(event.target.value)}+ />+ </label>+ <label>+ {t(($) => $.inspector.sections.appearance)}+ <select+ aria-label={t(($) => $.inspector.sections.appearance)}+ value={variant}+ onChange={(event) => setVariant(event.target.value as Variant)}+ >+ {entries.map(([key, value]) => (+ <option key={key} value={key}>+ {value.label}+ </option>+ ))}+ </select>+ </label>+ <label>+ {t(($) => $.button.controls.content)}+ <select+ aria-label={t(($) => $.button.controls.content)}+ value={icon}+ onChange={(event) => setIcon(event.target.value)}+ >+ <option value="start">+ {t(($) => $.button.controls.leading)}+ </option>+ <option value="end">+ {t(($) => $.button.controls.trailing)}+ </option>+ <option value="none">+ {t(($) => $.button.controls.textOnly)}+ </option>+ <option value="only">+ {t(($) => $.button.controls.iconOnly)}+ </option>+ </select>+ </label>+ <label>+ {t(($) => $.button.controls.state)}+ <select+ aria-label={t(($) => $.button.controls.state)}+ value={state}+ onChange={(event) => setState(event.target.value)}+ >+ <option value="normal">+ {t(($) => $.button.states.default)}+ </option>+ <option value="disabled">+ {t(($) => $.button.states.disabled)}+ </option>+ <option value="loading">+ {t(($) => $.button.states.loading)}+ </option>+ <option value="invalid">+ {t(($) => $.button.states.invalid)}+ </option>+ </select>+ </label>+ </div>+ <div className="button-stage">+ <Button+ data-testid="button-playground"+ variant={variant}+ size={icon === "only" ? iconSizes[scale] : scale}+ disabled={state === "disabled" || loading}+ aria-busy={loading || undefined}+ aria-invalid={state === "invalid" || undefined}+ aria-label={icon === "only" ? buttonLabel : undefined}+ onClick={() => setClicks((value) => value + 1)}+ >+ {loading ? (+ <Loader2 className="animate-spin" />+ ) : icon === "start" || icon === "only" ? (+ <Plus data-icon={icon === "start" ? "inline-start" : undefined} />+ ) : null}+ {icon !== "only" && buttonLabel}+ {!loading && icon === "end" && (+ <ArrowRight data-icon="inline-end" />+ )}+ </Button>+ <p role="status">+ {clicks ? t(($) => $.button.states.clicked, { count: clicks }) : ""}+ </p>+ </div>+ <div className="button-stage-footer">+ <span>+ {t(($) => $.button.geometry.height)}{" "}+ {size(`--button-height-${scale}`)}+ </span>+ <span>+ {t(($) => $.button.geometry.padding)}{" "}+ {size(`--button-padding-${scale}`)}+ </span>+ <span>+ {t(($) => $.tokens.labels.gap)} {size(`--button-gap-${scale}`)}+ </span>+ </div>+ </section>++ <section+ className="button-section"+ id="button-variants"+ aria-labelledby="variants-title"+ >+ <div className="button-section-heading">+ <div>+ <h2 id="variants-title">{t(($) => $.button.page.variants)}</h2>+ </div>+ <code>{scale}</code>+ </div>+ <div className="button-table-scroll">+ <table className="button-matrix">+ <thead>+ <tr>+ <th scope="col">{t(($) => $.inspector.sections.appearance)}</th>+ <th scope="col">{t(($) => $.button.states.interactive)}</th>+ <th scope="col">{t(($) => $.button.states.disabled)}</th>+ <th scope="col">{t(($) => $.button.states.loading)}</th>+ </tr>+ </thead>+ <tbody>+ {entries.map(([key, value]) => (+ <tr key={key} data-variant={key}>+ <th scope="row">+ <code>{key}</code>+ </th>+ <td>+ <Button+ variant={key}+ size={scale}+ onClick={() => setClicks((n) => n + 1)}+ >+ {value.label}+ </Button>+ </td>+ <td>+ <Button variant={key} size={scale} disabled>+ {value.label}+ </Button>+ </td>+ <td>+ <Button+ variant={key}+ size={scale}+ disabled+ aria-busy="true"+ >+ <Loader2 className="animate-spin" />+ {t(($) => $.button.states.processing)}+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </section>++ <section+ className="button-section"+ id="button-sizes"+ aria-labelledby="sizes-title"+ >+ <div className="button-section-heading">+ <div>+ <h2 id="sizes-title">{t(($) => $.button.page.sizes)}</h2>+ </div>+ </div>+ <div className="button-table-scroll">+ <table className="button-matrix button-size-matrix">+ <thead>+ <tr>+ <th scope="col">{t(($) => $.inspector.sections.size)}</th>+ <th scope="col">{t(($) => $.button.controls.text)}</th>+ <th scope="col">{t(($) => $.button.controls.leading)}</th>+ <th scope="col">{t(($) => $.button.controls.trailing)}</th>+ <th scope="col">{t(($) => $.button.controls.icon)}</th>+ </tr>+ </thead>+ <tbody>+ {buttonScales.map((item) => (+ <tr key={item} data-size={item} data-selected={item === scale}>+ <th scope="row">+ <code>{item}</code>+ <span>{size(`--button-height-${item}`)}</span>+ </th>+ <td>+ <Button size={item} variant={variant}>+ {t(($) => $.button.actions.create)}+ </Button>+ </td>+ <td>+ <Button size={item} variant={variant}>+ <Plus data-icon="inline-start" />+ {t(($) => $.button.actions.create)}+ </Button>+ </td>+ <td>+ <Button size={item} variant={variant}>+ {t(($) => $.button.actions.continue)}+ <ArrowRight data-icon="inline-end" />+ </Button>+ </td>+ <td>+ <Button+ size={iconSizes[item]}+ variant={variant}+ aria-label={t(($) => $.button.actions.addSize, {+ size: iconSizes[item],+ })}+ >+ <Plus />+ </Button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </section>++ <section+ className="button-section"+ id="button-context"+ aria-labelledby="context-title"+ >+ <div className="button-section-heading">+ <div>+ <h2 id="context-title">{t(($) => $.button.page.context)}</h2>+ </div>+ </div>+ <div className="button-context-grid">+ <div className="button-context-card">+ <h3>{t(($) => $.button.context.submit)}</h3>+ <div className="button-example-actions">+ <Button+ size={scale}+ disabled={sending}+ aria-busy={sending || undefined}+ onClick={() => {+ setSending(true);+ setSent(false);+ timer.current = setTimeout(() => {+ setSending(false);+ setSent(true);+ }, 1200);+ }}+ >+ {sending ? (+ <Loader2 className="animate-spin" />+ ) : sent ? (+ <Check />+ ) : (+ <Send />+ )}+ {sending+ ? t(($) => $.button.states.submitting)+ : sent+ ? t(($) => $.button.states.submitted)+ : t(($) => $.button.actions.submit)}+ </Button>+ <span+ className="text-caption text-muted-foreground"+ role="status"+ >+ {sent ? t(($) => $.button.states.complete) : ""}+ </span>+ </div>+ </div>+ <div className="button-context-card">+ <h3>{t(($) => $.button.context.triggers)}</h3>+ <div className="button-example-actions">+ <Popover>+ <PopoverTrigger+ render={<Button variant="outline" size={scale} />}+ >+ {t(($) => $.button.actions.more)}+ <ChevronDown data-icon="inline-end" />+ </PopoverTrigger>+ <PopoverContent>+ <p className="text-body">+ {t(($) => $.button.context.popover)}+ </p>+ </PopoverContent>+ </Popover>+ <Dialog>+ <DialogTrigger+ render={<Button variant="secondary" size={scale} />}+ >+ {t(($) => $.button.actions.dialog)}+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t(($) => $.button.actions.save)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.button.context.saveDescription)}+ </DialogDescription>+ </DialogHeader>+ <Button size={scale} onClick={() => setClicks((n) => n + 1)}>+ {t(($) => $.button.actions.saveExample)}+ </Button>+ </DialogContent>+ </Dialog>+ </div>+ </div>+ <div className="button-context-card">+ <h3>{t(($) => $.button.context.length)}</h3>+ <div className="button-example-actions">+ <Button variant="outline" size={scale}>+ {t(($) => $.button.actions.save)}+ </Button>+ <Button size={scale}>+ {t(($) => $.button.actions.saveNext)}+ </Button>+ </div>+ </div>+ <div className="button-context-card">+ <h3>{t(($) => $.button.context.compact)}</h3>+ <div className="button-example-actions">+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.button.actions.compactAdd)}+ >+ <Plus className="size-3" />+ </Button>+ <Button variant="outline" size="sm">+ {t(($) => $.button.actions.quick)}+ </Button>+ </div>+ </div>+ </div>+ </section>+ <ComponentRules component="button" />+ </div>+ );+}diff --git a/apps/ui-lab/src/catalog-content.tsx b/apps/ui-lab/src/catalog-content.tsxnew file mode 100644index 0000000000..28b6bc5264--- /dev/null+++ b/apps/ui-lab/src/catalog-content.tsx@@ -0,0 +1,165 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { ArrowRight, CircleDashed, RotateCcw } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import {+ catalog,+ availableCount,+ pageHref,+ type CatalogRoute,+} from "./catalog";+import { moduleIcons } from "./catalog-navigation";+import { TokenChanges } from "./token-changes";+import { changeCount, emptyDraft, type Draft } from "./tokens";++export function CatalogContent({+ route,+ draft,+ onEdit,+ onSave,+ onExport,+ savedDesigns,+ exportContent,+}: {+ route: CatalogRoute;+ draft: Draft;+ onEdit: (draft: Draft) => void;+ onSave: () => void;+ onExport: () => void;+ savedDesigns: ReactNode;+ exportContent: ReactNode;+}) {+ const { t } = useTranslation("uiLab");+ const status = (available: boolean) => (+ <span className={`catalog-status ${available ? "available" : ""}`}>+ <span className="catalog-dot" />+ {t(($) => $.system.status[available ? "available" : "planned"])}+ </span>+ );+ return (+ <div+ className="catalog-content"+ key={+ route.kind === "page"+ ? `${route.module.id}/${route.page.id}`+ : route.kind === "module"+ ? route.module.id+ : route.kind+ }+ >+ {route.kind === "overview" && (+ <div className="catalog-module-grid">+ {catalog.map((module, index) => {+ const Icon = moduleIcons[module.id];+ return (+ <a+ className="catalog-module-card"+ href={pageHref(module.id)}+ key={module.id}+ >+ <div className="catalog-card-top">+ <Icon />+ <span>{String(index + 1).padStart(2, "0")}</span>+ </div>+ <h2>{t(($) => $.system.modules[module.id])}</h2>+ <p>{t(($) => $.system.descriptions[module.id])}</p>+ <div className="catalog-card-footer">+ <span>+ {t(($) => $.system.status.progress, {+ ready: availableCount(module),+ total: module.pages.length,+ })}+ </span>+ <ArrowRight />+ </div>+ </a>+ );+ })}+ </div>+ )}+ {route.kind === "module" && (+ <>+ <div className="catalog-module-summary">+ <p>{t(($) => $.system.descriptions[route.module.id])}</p>+ <span>+ {t(($) => $.system.status.progress, {+ ready: availableCount(route.module),+ total: route.module.pages.length,+ })}+ </span>+ </div>+ <div className="catalog-page-grid">+ {route.module.pages.map((page) => (+ <a+ className="catalog-page-card"+ href={pageHref(route.module.id, page.id)}+ key={page.id}+ >+ <h2>{t(($) => $.system.pages[page.id])}</h2>+ {status(page.content.kind !== "planned")}+ <ArrowRight />+ </a>+ ))}+ </div>+ </>+ )}+ {route.kind === "page" && route.page.content.kind === "planned" && (+ <div className="catalog-placeholder">+ <CircleDashed className="catalog-placeholder-icon" />+ {status(false)}+ <p>{t(($) => $.system.empty.message)}</p>+ <a href={pageHref(route.module.id)}>+ {t(($) => $.system.empty.back, {+ module: t(($) => $.system.modules[route.module.id]),+ })}+ <ArrowRight />+ </a>+ </div>+ )}+ {route.kind === "notFound" && (+ <div className="catalog-placeholder">+ <CircleDashed className="catalog-placeholder-icon" />+ <a href="#/overview">+ {t(($) => $.system.navigation.overview)}+ <ArrowRight />+ </a>+ </div>+ )}+ {route.kind === "page" && route.page.content.kind === "changes" && (+ <div className="catalog-changes">+ {route.page.content.view === "review" && (+ <>+ <div className="catalog-changes-actions">+ <a href={pageHref("components", "button")}>+ {t(($) => $.system.changes.return)}+ <ArrowRight />+ </a>+ <Button+ variant="ghost"+ disabled={!changeCount(draft)}+ onClick={() => onEdit(emptyDraft())}+ >+ <RotateCcw />+ {t(($) => $.system.changes.reset)}+ </Button>+ <Button variant="outline" onClick={onExport}>+ {t(($) => $.lab.actions.export)}+ </Button>+ </div>+ <TokenChanges draft={draft} onEdit={onEdit} />+ </>+ )}+ {route.page.content.view === "saved" && (+ <>+ <div className="catalog-changes-actions">+ <Button onClick={onSave}>{t(($) => $.lab.actions.save)}</Button>+ </div>+ {savedDesigns}+ </>+ )}+ {route.page.content.view === "export" && exportContent}+ </div>+ )}+ </div>+ );+}diff --git a/apps/ui-lab/src/catalog-navigation.tsx b/apps/ui-lab/src/catalog-navigation.tsxnew file mode 100644index 0000000000..e157ba7e92--- /dev/null+++ b/apps/ui-lab/src/catalog-navigation.tsx@@ -0,0 +1,138 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Blocks,+ BookOpen,+ Box,+ ChevronDown,+ Component,+ History,+ LayoutDashboard,+ Palette,+} from "lucide-react";+import {+ catalog,+ availableCount,+ pageHref,+ type ModuleId,+ type CatalogRoute,+} from "./catalog";++export const moduleIcons = {+ foundations: Palette,+ components: Component,+ patterns: Blocks,+ product: Box,+ layouts: LayoutDashboard,+ changes: History,+};++export function CatalogNavigation({+ route,+ onNavigate,+}: {+ route: CatalogRoute;+ onNavigate: () => void;+}) {+ const { t } = useTranslation("uiLab");+ const [expanded, setExpanded] = useState<Partial<Record<ModuleId, boolean>>>({+ components: true,+ });+ const currentModule = "module" in route ? route.module.id : undefined;+ const currentPage = route.kind === "page" ? route.page.id : undefined;+ useEffect(() => {+ if (currentModule)+ setExpanded((previous) => ({ ...previous, [currentModule]: true }));+ }, [currentModule, currentPage]);+ return (+ <nav+ className="catalog-navigation"+ aria-label={t(($) => $.system.navigation.title)}+ >+ <a+ className="catalog-home"+ href="#/overview"+ aria-current={route.kind === "overview" ? "page" : undefined}+ onClick={onNavigate}+ >+ <BookOpen />+ <span>{t(($) => $.system.navigation.overview)}</span>+ </a>+ {catalog.map((module) => {+ const Icon = moduleIcons[module.id];+ const open = expanded[module.id] ?? currentModule === module.id;+ return (+ <section className="catalog-nav-group" key={module.id}>+ <div className="catalog-nav-heading">+ <a+ href={pageHref(module.id)}+ aria-current={+ route.kind === "module" && currentModule === module.id+ ? "page"+ : undefined+ }+ onClick={onNavigate}+ >+ <Icon />+ <span>{t(($) => $.system.modules[module.id])}</span>+ </a>+ <button+ type="button"+ aria-label={t(($) => $.system.navigation.expand, {+ module: t(($) => $.system.modules[module.id]),+ })}+ aria-expanded={open}+ aria-controls={`nav-${module.id}`}+ onClick={() =>+ setExpanded((previous) => ({+ ...previous,+ [module.id]: !open,+ }))+ }+ >+ <span>+ {availableCount(module)}/{module.pages.length}+ </span>+ <ChevronDown className={open ? "" : "is-collapsed"} />+ </button>+ </div>+ <div+ className="catalog-nav-items"+ id={`nav-${module.id}`}+ hidden={!open}+ >+ {module.pages.map((page) => (+ <a+ key={page.id}+ href={pageHref(module.id, page.id)}+ aria-current={+ route.kind === "page" &&+ currentModule === module.id &&+ route.page.id === page.id+ ? "page"+ : undefined+ }+ onClick={onNavigate}+ >+ <span>{t(($) => $.system.pages[page.id])}</span>+ <span+ className={`catalog-dot ${page.content.kind === "planned" ? "" : "available"}`}+ role="img"+ aria-label={t(+ ($) =>+ $.system.status[+ page.content.kind === "planned"+ ? "planned"+ : "available"+ ],+ )}+ />+ </a>+ ))}+ </div>+ </section>+ );+ })}+ </nav>+ );+}diff --git a/apps/ui-lab/src/catalog.test.ts b/apps/ui-lab/src/catalog.test.tsnew file mode 100644index 0000000000..c4423555da--- /dev/null+++ b/apps/ui-lab/src/catalog.test.ts@@ -0,0 +1,52 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { catalog, pageHref, resolveCatalogRoute } from "./catalog";+import { scenes } from "./protocol";++describe("design system catalog routes", () => {+ it("opens the overview for the root and rejects unknown or incomplete paths", () => {+ for (const hash of ["", "#", "#/", "#/overview"]) {+ expect(resolveCatalogRoute(hash)).toEqual({ kind: "overview" });+ }+ for (const hash of [+ "#/missing",+ "#/foundations/button",+ "#/components/button/extra",+ "#components",+ "#/components/",+ ]) {+ expect(resolveCatalogRoute(hash)).toEqual({ kind: "notFound" });+ }+ });+ it("gives each module and page a unique, reloadable location", () => {+ const paths = new Set<string>();+ for (const module of catalog) {+ expect(resolveCatalogRoute(pageHref(module.id))).toEqual({+ kind: "module",+ module,+ });+ for (const page of module.pages) {+ const path = pageHref(module.id, page.id);+ expect(paths.has(path)).toBe(false);+ paths.add(path);+ expect(resolveCatalogRoute(path)).toEqual({+ kind: "page",+ module,+ page,+ });+ }+ }+ });+ it("keeps every production preview reachable and marks unimplemented source operations as planned", () => {+ const previews = catalog+ .flatMap((module) => module.pages)+ .flatMap((page) =>+ page.content.kind === "preview" ? [page.content.scene] : [],+ );+ expect(previews.sort()).toEqual(scenes.map((scene) => scene.id).sort());+ for (const page of ["impact", "source"] as const) {+ const route = resolveCatalogRoute(pageHref("changes", page));+ expect(route.kind === "page" && route.page.content.kind).toBe("planned");+ }+ });+});diff --git a/apps/ui-lab/src/catalog.ts b/apps/ui-lab/src/catalog.tsnew file mode 100644index 0000000000..2072346db9--- /dev/null+++ b/apps/ui-lab/src/catalog.ts@@ -0,0 +1,103 @@+import type en from "./locales/en.json";+import type { Scene } from "./protocol";++export type ModuleId = keyof typeof en.system.modules;+export type PageId = keyof typeof en.system.pages;+export type CatalogPage = {+ id: PageId;+ content:+ | { kind: "planned" }+ | { kind: "preview"; scene: Scene }+ | { kind: "changes"; view: "review" | "saved" | "export" };+};+export type CatalogModule = { id: ModuleId; pages: readonly CatalogPage[] };+const planned = (...ids: PageId[]): CatalogPage[] =>+ ids.map((id) => ({ id, content: { kind: "planned" } }));++// One registry drives navigation, module indexes, availability and routing.+export const catalog: readonly CatalogModule[] = [+ {+ id: "foundations",+ pages: [+ { id: "colors", content: { kind: "preview", scene: "colors" } },+ ...planned("typography", "spacing", "radius", "shadows", "icons"),+ { id: "motion", content: { kind: "preview", scene: "motion" } },+ ],+ },+ {+ id: "components",+ pages: [+ { id: "gallery", content: { kind: "preview", scene: "components" } },+ { id: "button", content: { kind: "preview", scene: "button" } },+ { id: "dialog", content: { kind: "preview", scene: "dialog" } },+ ...planned(+ "input",+ "select",+ "checkbox",+ "switch",+ "badge",+ "tabs",+ "tooltip",+ "popover",+ ),+ ],+ },+ {+ id: "patterns",+ pages: planned(+ "forms",+ "filters",+ "properties",+ "confirmation",+ "feedback",+ ),+ },+ {+ id: "product",+ pages: planned(+ "issueRow",+ "statusPicker",+ "assigneePicker",+ "comments",+ "agentRun",+ ),+ },+ {+ id: "layouts",+ pages: [+ ...planned("sidebar"),+ { id: "list", content: { kind: "preview", scene: "list" } },+ { id: "detail", content: { kind: "preview", scene: "detail" } },+ ...planned("settings", "split"),+ ],+ },+ {+ id: "changes",+ pages: [+ { id: "review", content: { kind: "changes", view: "review" } },+ { id: "saved", content: { kind: "changes", view: "saved" } },+ { id: "export", content: { kind: "changes", view: "export" } },+ ...planned("impact", "source"),+ ],+ },+];+export const pageHref = (module: ModuleId, page?: PageId) =>+ `#/${module}${page ? `/${page}` : ""}`;+export const availableCount = (module: CatalogModule) =>+ module.pages.filter((page) => page.content.kind !== "planned").length;+export type CatalogRoute =+ | { kind: "overview" }+ | { kind: "module"; module: CatalogModule }+ | { kind: "page"; module: CatalogModule; page: CatalogPage }+ | { kind: "notFound" };++export function resolveCatalogRoute(hash: string): CatalogRoute {+ if (!hash || hash === "#" || hash === "#/" || hash === "#/overview")+ return { kind: "overview" };+ const match = /^#\/([^/]+)(?:\/([^/]+))?$/.exec(hash);+ const module = catalog.find((item) => item.id === match?.[1]);+ if (!module) return { kind: "notFound" };+ if (!match?.[2]) return { kind: "module", module };+ const page = module.pages.find((item) => item.id === match[2]);+ return page ? { kind: "page", module, page } : { kind: "notFound" };+}diff --git a/apps/ui-lab/src/color-editor.tsx b/apps/ui-lab/src/color-editor.tsxnew file mode 100644index 0000000000..62040f10bc--- /dev/null+++ b/apps/ui-lab/src/color-editor.tsx@@ -0,0 +1,342 @@+import { useTranslation } from "react-i18next";+import { useEffect, useId, useRef, useState } from "react";+import { HexColorPicker } from "react-colorful";+import { Check, ChevronDown, Copy, RotateCcw, Search } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { colorToHex, hexToOklch, isSrgb } from "./color";+import { NumberField } from "./number-field";+import { colorTokens, parseColor, colorAlpha, withColorAlpha } from "./tokens";++const presets = [+ "#FFFFFF",+ "#18181B",+ "#71717A",+ "#2563EB",+ "#7C3AED",+ "#DB2777",+ "#DC2626",+ "#D97706",+ "#16A34A",+];++export function ColorEditor({+ showRoleSelector = true,+ token,+ value,+ original,+ modified,+ values,+ onTokenChange,+ onPreview,+ onCommit,+ onCancel,+}: {+ showRoleSelector?: boolean;+ token: string;+ value: string;+ original: string;+ modified: boolean;+ values: Record<string, string>;+ onTokenChange: (token: string) => void;+ onPreview: (color: string) => void;+ onCommit: (color: string) => void;+ onCancel: () => void;+}) {+ const { t } = useTranslation("uiLab");+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const [hexInput, setHexInput] = useState(colorToHex(value));+ const [error, setError] = useState(false);+ const [copyState, setCopyState] = useState<"copied" | "copyFailed" | null>(+ null,+ );+ const errorId = useId();+ const hexDirty = useRef(false);+ const hex = colorToHex(value);+ const channels = parseColor(value);+ const alpha = colorAlpha(value);+ const label = t(+ ($) => $.tokens.labels[colorTokens.find(([key]) => key === token)![1]],+ );+ useEffect(() => {+ hexDirty.current = false;+ setHexInput(hex);+ setError(false);+ }, [hex]);+ useEffect(() => {+ if (!copyState) return;+ const timeout = setTimeout(() => setCopyState(null), 2000);+ return () => clearTimeout(timeout);+ }, [copyState]);+ const commitHex = () => {+ if (!hexDirty.current) return;+ const next = hexToOklch(hexInput);+ if (!next) {+ setError(true);+ return;+ }+ hexDirty.current = false;+ setError(false);+ setHexInput(colorToHex(next));+ // Focusing/blurring an approximate HEX display must not rewrite a wide-gamut token.+ if (colorToHex(next) !== hex) onCommit(withColorAlpha(next, alpha));+ };+ return (+ <div className="color-editor">+ {showRoleSelector && (+ <Popover+ open={open}+ onOpenChange={(next) => {+ setOpen(next);+ if (!next) setQuery("");+ }}+ >+ <PopoverTrigger+ render={+ <Button+ variant="outline"+ className="color-role-trigger"+ aria-label={t(($) => $.color.roles.current, { label })}+ />+ }+ >+ <span className="color-role-swatch" style={{ background: value }} />+ <span className="color-role-label">+ <strong>{label}</strong>+ <code>{token}</code>+ </span>+ <ChevronDown className="size-3.5 shrink-0" />+ </PopoverTrigger>+ <PopoverContent className="color-role-popover" align="end">+ <div className="color-role-search">+ <Search className="size-3.5" />+ <Input+ aria-label={t(($) => $.color.roles.searchLabel)}+ placeholder={t(($) => $.color.roles.searchPlaceholder)}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ </div>+ <div+ className="color-role-list"+ aria-label={t(($) => $.color.roles.title)}+ >+ {colorTokens+ .filter(([key, name]) =>+ `${key} ${t(($) => $.tokens.labels[name])}`+ .toLowerCase()+ .includes(query.toLowerCase()),+ )+ .map(([key, name]) => (+ <Button+ key={key}+ variant="ghost"+ className="color-role-option"+ aria-pressed={token === key}+ onClick={() => {+ onTokenChange(key);+ setOpen(false);+ setQuery("");+ }}+ >+ <span+ className="color-role-swatch"+ style={{ background: values[key] }}+ />+ <span className="color-role-label">+ <strong>{t(($) => $.tokens.labels[name])}</strong>+ <code>{key}</code>+ </span>+ {key === token && <Check className="size-3.5" />}+ </Button>+ ))}+ {!colorTokens.some(([key, name]) =>+ `${key} ${t(($) => $.tokens.labels[name])}`+ .toLowerCase()+ .includes(query.toLowerCase()),+ ) && (+ <p className="color-role-empty">+ {t(($) => $.color.roles.empty)}+ </p>+ )}+ </div>+ </PopoverContent>+ </Popover>+ )}+ <div className="color-picker-panel">+ <HexColorPicker+ color={hex}+ onChange={(next) =>+ onPreview(withColorAlpha(hexToOklch(next)!, alpha))+ }+ onChangeEnd={(next) =>+ onCommit(withColorAlpha(hexToOklch(next)!, alpha))+ }+ aria-label={t(($) => $.color.controls.picker)}+ />+ </div>+ <div className="color-hex-row">+ <label className="color-hex-field">+ <span>HEX</span>+ <Input+ aria-label={t(($) => $.color.controls.hex)}+ value={hexInput}+ maxLength={7}+ spellCheck={false}+ aria-invalid={!!error}+ aria-describedby={error ? errorId : undefined}+ onChange={(event) => {+ hexDirty.current = true;+ setHexInput(event.target.value);+ setError(false);+ }}+ onBlur={commitHex}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ commitHex();+ }+ if (event.key === "Escape") {+ hexDirty.current = false;+ setHexInput(hex);+ setError(false);+ }+ }}+ />+ </label>+ <Button+ variant="outline"+ size="icon"+ aria-label={t(($) => $.color.controls.copy)}+ title={t(($) => $.color.controls.copy)}+ onClick={async () => {+ try {+ await navigator.clipboard.writeText(hex);+ setCopyState("copied");+ } catch {+ setCopyState("copyFailed");+ }+ }}+ >+ {copyState === "copied" ? <Check /> : <Copy />}+ </Button>+ </div>+ {error && (+ <p className="color-field-error" role="alert" id={errorId}>+ {t(($) => $.color.feedback.invalid)}+ </p>+ )}+ {copyState && (+ <p className="color-feedback" role="status">+ {t(($) => $.color.feedback[copyState])}+ </p>+ )}+ {!isSrgb(value) && (+ <p className="color-feedback">{t(($) => $.color.feedback.gamut)}</p>+ )}+ <div className="color-opacity">+ <NumberField+ label={t(($) => $.color.controls.opacity)}+ symbol="A"+ token={token}+ min={0}+ max={100}+ step={1}+ unit="%"+ value={Number((alpha * 100).toFixed(3))}+ modified={alpha !== colorAlpha(original)}+ onPreview={(next) => onPreview(withColorAlpha(value, next / 100))}+ onCommit={(next) => onCommit(withColorAlpha(value, next / 100))}+ onCancel={onCancel}+ onReset={() => onCommit(withColorAlpha(value, colorAlpha(original)))}+ />+ </div>+ <div className="color-comparison">+ <button+ type="button"+ onClick={() => onCommit(original)}+ title={t(($) => $.color.controls.restoreTitle)}+ aria-label={t(($) => $.color.controls.restore)}+ disabled={!modified}+ >+ <span style={{ background: original }} />+ <small>{t(($) => $.color.controls.original)}</small>+ </button>+ <div>+ <span style={{ background: value }} />+ <small>{t(($) => $.color.controls.current)}</small>+ </div>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.color.controls.reset)}+ title={t(($) => $.color.controls.reset)}+ disabled={!modified}+ onClick={() => onCommit(original)}+ >+ <RotateCcw />+ </Button>+ </div>+ <div className="color-presets-heading">+ {t(($) => $.color.controls.presets)}+ <span>sRGB</span>+ </div>+ <div className="color-presets">+ {presets.map((preset) => (+ <button+ type="button"+ key={preset}+ aria-label={t(($) => $.color.controls.use, { color: preset })}+ title={preset}+ aria-pressed={hex === preset}+ style={{ background: preset }}+ onClick={() => onCommit(withColorAlpha(hexToOklch(preset)!, alpha))}+ />+ ))}+ </div>+ <details className="color-advanced">+ <summary>+ {t(($) => $.color.controls.advanced)}+ <span>OKLCH</span>+ <ChevronDown className="size-3" />+ </summary>+ <div className="color-channels">+ {(+ [+ [t(($) => $.color.channels.lightness), 0, 1, 0.005],+ [t(($) => $.color.channels.chroma), 1, 0.4, 0.005],+ [t(($) => $.color.channels.hue), 2, 360, 1],+ ] as const+ ).map(([name, index, max, step]) => (+ <label key={name}>+ <span>+ {name}+ <output>{channels[index]}</output>+ </span>+ <input+ type="range"+ aria-label={`OKLCH ${name}`}+ min={0}+ max={max}+ step={step}+ value={channels[index]}+ onChange={(event) => {+ const next = [...channels];+ next[index] = Number(event.target.value);+ onCommit(withColorAlpha(`oklch(${next.join(" ")})`, alpha));+ }}+ />+ </label>+ ))}+ </div>+ <code className="color-raw-value">{value}</code>+ </details>+ </div>+ );+}diff --git a/apps/ui-lab/src/color-usage.tsx b/apps/ui-lab/src/color-usage.tsxnew file mode 100644index 0000000000..3a23ef7c65--- /dev/null+++ b/apps/ui-lab/src/color-usage.tsx@@ -0,0 +1,373 @@+import { useEffect, useRef, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import {+ Tabs,+ TabsList,+ TabsTrigger,+ TabsContent,+} from "@multica/ui/components/ui/tabs";+import { contrastPasses, contrastRatio, resolveBackground } from "./contrast";+import type { ColorToken, Draft, Theme } from "./tokens";++const mappings = [+ { id: "action", tokens: ["--primary", "--primary-foreground"] },+ { id: "brand", tokens: ["--brand", "--brand-foreground"] },+ { id: "tabs", tokens: ["--foreground", "--muted-foreground"] },+ { id: "input", tokens: ["--foreground", "--input"] },+ { id: "focus", tokens: ["--ring"] },+ { id: "error", tokens: ["--destructive"] },+] as const satisfies ReadonlyArray<{+ id: string;+ tokens: readonly ColorToken[];+}>;++type Reading = {+ label: string;+ state:+ | "default"+ | "hover"+ | "pressed"+ | "focus"+ | "selected"+ | "invalid"+ | "disabled";+ ratio?: number;+ focusRatio?: number;+};++// Read actual rendered styles so production hover/pressed rules stay authoritative.+function readControl(element: HTMLElement): Reading {+ const disabled = element.matches(":disabled, [aria-disabled=true]");+ const focus = element.matches(":focus-visible");+ const state = disabled+ ? "disabled"+ : element.matches(":active")+ ? "pressed"+ : focus+ ? "focus"+ : element.matches(":hover")+ ? "hover"+ : element.matches("[aria-invalid=true]")+ ? "invalid"+ : element.matches("[aria-selected=true], [aria-pressed=true]")+ ? "selected"+ : "default";+ const reading: Reading = { label: element.dataset.colorProbe!, state };+ if (+ disabled ||+ (element instanceof HTMLInputElement && !element.value) ||+ element+ .getAnimations()+ .some((animation) => animation.playState === "running")+ )+ return reading;+ try {+ const layers: string[] = [];+ let current: HTMLElement | null = element;+ while (current) {+ const style = getComputedStyle(current);+ // Group opacity and images need a more complete paint model; never report a false pass.+ if (Number(style.opacity) !== 1 || style.backgroundImage !== "none")+ return reading;+ layers.unshift(style.backgroundColor);+ current = current.parentElement;+ }+ const opaque = layers.findIndex((layer) => {+ try {+ contrastRatio("black", [layer]);+ return true;+ } catch {+ return false;+ }+ });+ if (opaque < 0) return reading;+ const backgrounds = layers.slice(opaque);+ const style = getComputedStyle(element);+ reading.ratio = contrastRatio(style.color, backgrounds);+ // Check the painted border pixel against both neighbors, respecting background-clip.+ // Ring size and shadow geometry remain a separate visual review.+ if (focus) {+ const outside = backgrounds.slice(0, -1);+ if (outside.length) {+ const underBorder =+ style.backgroundClip === "border-box" ? backgrounds : outside;+ const resolved = resolveBackground([+ ...underBorder,+ style.borderTopColor,+ ]).toString();+ reading.focusRatio = Math.min(+ contrastRatio(resolved, backgrounds),+ contrastRatio(resolved, outside),+ );+ }+ }+ } catch {+ /* Unsupported paint is shown as unmeasured. */+ }+ return reading;+}++function MeasuredSample({+ title,+ children,+ revision,+}: {+ title: string;+ children: ReactNode;+ revision: string;+}) {+ const { t } = useTranslation("uiLab");+ const root = useRef<HTMLDivElement>(null);+ const [readings, setReadings] = useState<Reading[]>([]);+ useEffect(() => {+ const node = root.current!;+ let frame = 0;+ let timer = 0;+ const read = () => {+ const next = Array.from(+ node.querySelectorAll<HTMLElement>("[data-color-probe]"),+ ).map(readControl);+ setReadings((previous) =>+ JSON.stringify(previous) === JSON.stringify(next) ? previous : next,+ );+ };+ const schedule = () => {+ cancelAnimationFrame(frame);+ clearTimeout(timer);+ frame = requestAnimationFrame(read);+ timer = window.setTimeout(read, 250);+ };+ const events = [+ "pointerover",+ "pointerout",+ "pointerdown",+ "pointerup",+ "pointercancel",+ "focusin",+ "focusout",+ "keydown",+ "keyup",+ "input",+ "transitionend",+ ];+ events.forEach((event) => node.addEventListener(event, schedule));+ // Releasing outside the card must also clear a pressed reading.+ window.addEventListener("pointerup", schedule);+ const observer = new MutationObserver(schedule);+ observer.observe(node, {+ subtree: true,+ attributes: true,+ attributeFilter: [+ "disabled",+ "aria-disabled",+ "aria-invalid",+ "aria-selected",+ "aria-pressed",+ "data-active",+ "class",+ ],+ });+ schedule();+ return () => {+ observer.disconnect();+ cancelAnimationFrame(frame);+ clearTimeout(timer);+ events.forEach((event) => node.removeEventListener(event, schedule));+ window.removeEventListener("pointerup", schedule);+ };+ }, [revision]);+ const result = (ratio: number | undefined, minimum: number) =>+ ratio === undefined+ ? t(($) => $.colorUsage.unmeasured)+ : `${ratio.toFixed(2)}:1 · ${t(($) => $.colorUsage[contrastPasses(ratio, minimum) ? "pass" : "fail"])}`;+ return (+ <section className="color-usage-card">+ <h3>{title}</h3>+ <div ref={root} className="color-usage-sample bg-surface text-foreground">+ {children}+ </div>+ <div className="color-usage-readings">+ {readings.map((reading) => (+ <div key={reading.label} className="color-usage-reading">+ <div>+ <strong>{reading.label}</strong>+ <span>{t(($) => $.colorUsage.states[reading.state])}</span>+ </div>+ <output+ data-result={+ reading.ratio === undefined+ ? "unknown"+ : contrastPasses(reading.ratio, 4.5)+ ? "pass"+ : "fail"+ }+ >+ {reading.state === "disabled"+ ? t(($) => $.colorUsage.exempt)+ : `${t(($) => $.colorUsage.text)} ${result(reading.ratio, 4.5)}`}+ </output>+ {reading.focusRatio !== undefined && (+ <output+ data-result={+ contrastPasses(reading.focusRatio, 3) ? "pass" : "fail"+ }+ >+ {t(($) => $.colorUsage.focusBorder)}{" "}+ {result(reading.focusRatio, 3)}+ </output>+ )}+ </div>+ ))}+ </div>+ </section>+ );+}++export function ColorUsage({+ draft,+ theme,+ select,+}: {+ draft: Draft;+ theme: Theme;+ select: (token: ColorToken) => void;+}) {+ const { t, i18n } = useTranslation("uiLab");+ const [disabled, setDisabled] = useState(false);+ const [invalid, setInvalid] = useState(false);+ const [active, setActive] = useState(true);+ const revision = JSON.stringify([+ draft,+ theme,+ i18n.language,+ disabled,+ invalid,+ active,+ ]);+ return (+ <div className="color-usage">+ <section className="palette-group">+ <h2>{t(($) => $.colorUsage.mapping)}</h2>+ <div className="color-usage-mappings">+ {mappings.map(({ id, tokens }) => (+ <div key={id}>+ <span>{t(($) => $.colorUsage.roles[id])}</span>+ <div>+ {tokens.map((token) => (+ <button+ key={token}+ type="button"+ onClick={() => select(token)}+ >+ <code>{token}</code>+ </button>+ ))}+ </div>+ </div>+ ))}+ </div>+ </section>+ <div className="color-usage-toolbar">+ <h2>{t(($) => $.colorUsage.preview)}</h2>+ <label>+ <input+ type="checkbox"+ checked={disabled}+ onChange={(event) => setDisabled(event.target.checked)}+ />+ {t(($) => $.colorUsage.states.disabled)}+ </label>+ </div>+ <p className="color-usage-hint">{t(($) => $.colorUsage.hint)}</p>+ <div className="color-usage-grid">+ <MeasuredSample title="Button" revision={revision}>+ <Button+ data-color-probe={t(($) => $.colorUsage.mainAction)}+ disabled={disabled}+ >+ {t(($) => $.palette.sample.create)}+ </Button>+ <Button+ data-color-probe={t(($) => $.colorUsage.activeFilter)}+ variant={active ? "brand" : "outline"}+ aria-pressed={active}+ onClick={() => setActive(!active)}+ disabled={disabled}+ >+ {t(($) => $.colorUsage.activeFilter)}+ </Button>+ </MeasuredSample>+ <MeasuredSample title="Tabs" revision={revision}>+ <Tabs defaultValue="overview">+ <TabsList+ variant="line"+ aria-label={t(($) => $.colorUsage.preview)}+ >+ <TabsTrigger+ value="overview"+ disabled={disabled}+ data-color-probe={t(($) => $.colorUsage.overview)}+ >+ {t(($) => $.colorUsage.overview)}+ </TabsTrigger>+ <TabsTrigger+ value="activity"+ disabled={disabled}+ data-color-probe={t(($) => $.colorUsage.activity)}+ >+ {t(($) => $.colorUsage.activity)}+ </TabsTrigger>+ </TabsList>+ <TabsContent value="overview">+ {t(($) => $.colorUsage.overviewContent)}+ </TabsContent>+ <TabsContent value="activity">+ {t(($) => $.colorUsage.activityContent)}+ </TabsContent>+ </Tabs>+ </MeasuredSample>+ <MeasuredSample title="Input" revision={revision}>+ <label className="color-usage-input">+ <span>{t(($) => $.colorUsage.taskName)}</span>+ <Input+ data-color-probe={t(($) => $.colorUsage.taskName)}+ defaultValue="Multica"+ aria-invalid={invalid || undefined}+ disabled={disabled}+ />+ </label>+ <label className="color-usage-toggle">+ <input+ type="checkbox"+ checked={invalid}+ onChange={(event) => setInvalid(event.target.checked)}+ />+ {t(($) => $.colorUsage.states.invalid)}+ </label>+ </MeasuredSample>+ </div>+ <details className="color-usage-notes">+ <summary>{t(($) => $.colorUsage.rules)}</summary>+ <p>{t(($) => $.colorUsage.scope)}</p>+ <p>{t(($) => $.colorUsage.policy)}</p>+ <a+ href="https://www.w3.org/WAI/WCAG22/Understanding/contrast-minimum.html"+ target="_blank"+ rel="noreferrer"+ >+ WCAG 1.4.3+ </a>+ {" · "}+ <a+ href="https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html"+ target="_blank"+ rel="noreferrer"+ >+ WCAG 1.4.11+ </a>+ </details>+ </div>+ );+}diff --git a/apps/ui-lab/src/color.test.ts b/apps/ui-lab/src/color.test.tsnew file mode 100644index 0000000000..2282ff6343--- /dev/null+++ b/apps/ui-lab/src/color.test.ts@@ -0,0 +1,97 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { colorToHex, hexToOklch, isSrgb } from "./color";+import {+ baseline,+ colorAlpha,+ withColorAlpha,+ emptyDraft,+ exportCss,+ isDraft,+ updateToken,+} from "./tokens";+import { decodeSession, encodeSession } from "./storage";++describe("color editing boundary", () => {+ it.each(["#FFFFFF", "#000000", "#FF0000", "#0000FF", "#00FF00", "#2563EB"])(+ "round trips %s through persisted OKLCH",+ (hex) => {+ const value = hexToOklch(hex)!;+ expect(colorToHex(value)).toBe(hex);+ const draft = updateToken(emptyDraft(), "light", "--brand", value);+ expect(isDraft(draft)).toBe(true);+ expect(+ decodeSession(encodeSession({ draft, designs: [] })).draft,+ ).toEqual(draft);+ expect(exportCss(draft)).toContain(value);+ },+ );+ it("accepts short HEX while rejecting alpha, CSS and malformed values", () => {+ expect(colorToHex(hexToOklch("abc")!)).toBe("#AABBCC");+ for (const value of [+ "#12345",+ "#12345678",+ "red",+ "#GGFFFF",+ "",+ "#000; color: red",+ ])+ expect(hexToOklch(value)).toBeNull();+ });+ it("displays a gamut-mapped approximation without mutating source tokens", () => {+ const source = "oklch(0.7 0.4 150)";+ expect(isSrgb(source)).toBe(false);+ expect(colorToHex(source)).toMatch(/^#[A-F0-9]{6}$/);+ expect(colorToHex(baseline.light["--brand"]!)).toMatch(/^#[A-F0-9]{6}$/);+ });+});++describe("transparent semantic colors", () => {+ it("preserves opacity when changing hue and round trips it through storage", () => {+ const value = withColorAlpha(+ hexToOklch("#123456")!,+ colorAlpha("oklch(1 0 0 / 6%)"),+ );+ expect(colorAlpha(value)).toBe(0.06);+ expect(colorToHex(value)).toBe("#123456");+ const draft = updateToken(emptyDraft(), "dark", "--border", value);+ expect(isDraft(draft)).toBe(true);+ expect(decodeSession(encodeSession({ draft, designs: [] })).draft).toEqual(+ draft,+ );+ expect(exportCss(draft)).toContain(" / 0.06)");+ });+ it("restores equivalent percentage and decimal alpha without leaving a change", () => {+ const original = baseline.dark["--border"]!;+ expect(withColorAlpha(original, colorAlpha(original))).toBe(original);+ const draft = updateToken(+ emptyDraft(),+ "dark",+ "--border",+ "oklch(1 0 0 / 0.2)",+ );+ expect(+ updateToken(draft, "dark", "--border", "oklch(1 0 0 / 0.06)"),+ ).toEqual(emptyDraft());+ for (const value of [+ "oklch(1 0 0 / 0)",+ "oklch(1 0 0 / 1)",+ "oklch(1 0 0 / 100%)",+ ]) {+ expect(isDraft({ ...emptyDraft(), dark: { "--border": value } })).toBe(+ true,+ );+ }+ for (const value of [+ "oklch(1 0 0 / 101%)",+ "oklch(1 0 0 / 1.1)",+ "oklch(1 0 0 / .)",+ "oklch(1 0 0 / -1)",+ "oklch(1 0 0 / 5%); color: red",+ ]) {+ expect(isDraft({ ...emptyDraft(), dark: { "--border": value } })).toBe(+ false,+ );+ }+ });+});diff --git a/apps/ui-lab/src/color.ts b/apps/ui-lab/src/color.tsnew file mode 100644index 0000000000..32eb297270--- /dev/null+++ b/apps/ui-lab/src/color.ts@@ -0,0 +1,27 @@+import Color from "colorjs.io";++export function colorToHex(value: string): string {+ const rgb = new Color(value).to("srgb").toGamut();+ return `#${rgb.coords+ .map((channel) =>+ Math.round(Math.max(0, Math.min(1, channel ?? 0)) * 255)+ .toString(16)+ .padStart(2, "0"),+ )+ .join("")+ .toUpperCase()}`;+}+export function isSrgb(value: string): boolean {+ return new Color(value).inGamut("srgb");+}+export function hexToOklch(value: string): string | null {+ const hex = value.trim().replace(/^#?/, "#");+ if (!/^#(?:[\da-f]{3}|[\da-f]{6})$/i.test(hex)) return null;+ const [l, c, h] = new Color(hex).to("oklch").coords;+ const coords = [+ Math.max(0, Math.min(1, l ?? 0)),+ Math.max(0, c ?? 0),+ Number.isFinite(h) ? ((h! % 360) + 360) % 360 : 0,+ ];+ return `oklch(${coords.map((n) => Number(n.toFixed(6))).join(" ")})`;+}diff --git a/apps/ui-lab/src/colors-scene.test.ts b/apps/ui-lab/src/colors-scene.test.tsnew file mode 100644index 0000000000..249592e356--- /dev/null+++ b/apps/ui-lab/src/colors-scene.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import {+ baseline,+ colorGroups,+ colorTokens,+ colorAliases,+ emptyDraft,+ isDraft,+ updateToken,+ exportCss,+ previewCss,+} from "./tokens";+import { colorToHex } from "./color";+import { isColorSelection } from "./protocol";++describe("semantic color catalog", () => {+ it("includes each role once, with editable values from both source themes", () => {+ expect(new Set(colorTokens.map(([key]) => key)).size).toBe(+ colorTokens.length,+ );+ expect(new Set(colorGroups.map((group) => group.id)).size).toBe(+ colorGroups.length,+ );+ for (const [key] of colorTokens) {+ for (const theme of ["light", "dark"] as const) {+ const value = baseline[theme][key]!;+ expect(value, `${theme}: ${key}`).toMatch(/^oklch\(/);+ expect(+ isDraft({ ...emptyDraft(), [theme]: { [key]: value } }),+ `${theme}: ${key}`,+ ).toBe(true);+ expect(colorToHex(value)).toMatch(/^#[0-9A-F]{6}$/);+ }+ }+ });+ it("keeps aliases linked to source roles instead of allowing independent overrides", () => {+ for (const [alias, target] of colorAliases) {+ expect(baseline.light[alias]).toBe(`var(${target})`);+ expect(baseline.dark[alias]).toBe(`var(${target})`);+ expect(colorTokens.some(([key]) => key === target)).toBe(true);+ expect(+ isDraft({ ...emptyDraft(), light: { [alias]: "oklch(0.5 0.1 255)" } }),+ ).toBe(false);+ }+ });+ it("exports newly available feedback colors only to their edited theme", () => {+ const draft = updateToken(+ emptyDraft(),+ "dark",+ "--success",+ "oklch(0.7 0.1 150)",+ );+ expect(isDraft(draft)).toBe(true);+ expect(exportCss(draft)).toContain(+ ".dark {\n --success: oklch(0.7 0.1 150);\n}",+ );+ expect(previewCss(draft)).not.toContain(":root");+ });+ it("accepts only known color selections from the frame", () => {+ expect(+ isColorSelection({+ type: "multica-ui-lab:color-select",+ token: "--brand",+ }),+ ).toBe(true);+ for (const token of [+ "--radius",+ "--background",+ "--not-a-color",+ "red; display: none",+ undefined,+ ]) {+ expect(+ isColorSelection({ type: "multica-ui-lab:color-select", token }),+ ).toBe(false);+ }+ expect(isColorSelection({ type: "other", token: "--brand" })).toBe(false);+ expect(isColorSelection(null)).toBe(false);+ });+});diff --git a/apps/ui-lab/src/colors-scene.tsx b/apps/ui-lab/src/colors-scene.tsxnew file mode 100644index 0000000000..1f8411f3b7--- /dev/null+++ b/apps/ui-lab/src/colors-scene.tsx@@ -0,0 +1,172 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Tabs,+ TabsList,+ TabsTrigger,+ TabsContent,+} from "@multica/ui/components/ui/tabs";+import { ColorUsage } from "./color-usage";+import { Input } from "@multica/ui/components/ui/input";+import { colorToHex } from "./color";+import {+ colorGroups,+ colorAlpha,+ colorAliases,+ tokenValue,+ type ColorToken,+ type Draft,+ type Theme,+} from "./tokens";+import type { ColorSelection } from "./protocol";++export function ColorsScene({+ draft,+ theme,+ selected,+}: {+ draft: Draft;+ theme: Theme;+ selected: ColorToken;+}) {+ const { t } = useTranslation("uiLab");+ const [query, setQuery] = useState("");+ const [section, setSection] = useState("palette");+ const groups = colorGroups+ .map((group) => ({+ id: group.id,+ tokens: group.tokens.filter(([key, label]) =>+ `${key} ${t(($) => $.tokens.labels[label])}`+ .toLowerCase()+ .includes(query.trim().toLowerCase()),+ ),+ }))+ .filter((group) => group.tokens.length > 0);+ const select = (token: ColorToken) =>+ window.parent.postMessage(+ { type: "multica-ui-lab:color-select", token } satisfies ColorSelection,+ location.origin,+ );+ return (+ <div className="colors-scene">+ <header className="palette-header">+ <div>+ <h1>{t(($) => $.palette.page.title)}</h1>+ <span>+ {t(($) => $.palette.page.count, {+ count: groups.reduce(+ (count, group) => count + group.tokens.length,+ 0,+ ),+ })}+ </span>+ </div>+ {section === "palette" && (+ <Input+ type="search"+ aria-label={t(($) => $.palette.page.search)}+ placeholder={t(($) => $.palette.page.placeholder)}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ )}+ </header>+ <Tabs+ value={section}+ onValueChange={(value) => setSection(String(value))}+ >+ <TabsList aria-label={t(($) => $.colorUsage.sections)}>+ <TabsTrigger value="palette">+ {t(($) => $.colorUsage.palette)}+ </TabsTrigger>+ <TabsTrigger value="usage">+ {t(($) => $.colorUsage.title)}+ </TabsTrigger>+ </TabsList>+ <TabsContent value="usage">+ <ColorUsage draft={draft} theme={theme} select={select} />+ </TabsContent>+ <TabsContent value="palette">+ {groups.map((group) => (+ <section+ className="palette-group"+ key={group.id}+ aria-labelledby={`palette-${group.id}`}+ >+ <h2 id={`palette-${group.id}`}>+ {t(($) => $.palette.groups[group.id])}+ </h2>+ <div className="palette-grid">+ {group.tokens.map(([key, label]) => {+ const value = tokenValue(draft, theme, key);+ const name = t(($) => $.tokens.labels[label]);+ return (+ <button+ type="button"+ className="palette-token"+ key={key}+ aria-label={t(($) => $.palette.page.edit, {+ label: name,+ })}+ aria-pressed={selected === key}+ onClick={() => select(key)}+ >+ <span+ className="palette-swatch"+ style={{ backgroundColor: value }}+ />+ <span className="palette-token-heading">+ <strong>{name}</strong>+ {draft[theme][key] && (+ <span+ className="property-modified"+ title={t(($) => $.inspector.changes.modified)}+ aria-label={t(($) => $.inspector.changes.modified)}+ />+ )}+ </span>+ <code>{key}</code>+ <span className="palette-hex">+ {colorToHex(value)}+ {colorAlpha(value) < 1 &&+ ` · ${Number((colorAlpha(value) * 100).toFixed(1))}%`}+ </span>+ </button>+ );+ })}+ </div>+ </section>+ ))}+ {!groups.length && (+ <p className="palette-empty" role="status">+ {t(($) => $.palette.page.empty)}+ </p>+ )}+ {!query.trim() && (+ <>+ <section+ className="palette-group"+ aria-labelledby="palette-aliases"+ >+ <h2 id="palette-aliases">{t(($) => $.palette.page.aliases)}</h2>+ <div className="palette-aliases">+ {colorAliases.map(([alias, target]) => (+ <button+ key={alias}+ type="button"+ onClick={() => select(target)}+ >+ <code>{alias}</code>+ <span aria-hidden="true">→</span>+ <code>{target}</code>+ </button>+ ))}+ </div>+ </section>+ </>+ )}+ </TabsContent>+ </Tabs>+ </div>+ );+}diff --git a/apps/ui-lab/src/component-rules.tsx b/apps/ui-lab/src/component-rules.tsxnew file mode 100644index 0000000000..a3febe0963--- /dev/null+++ b/apps/ui-lab/src/component-rules.tsx@@ -0,0 +1,46 @@+import { useTranslation } from "react-i18next";+import { Markdown } from "@multica/ui/markdown";+import { Button } from "@multica/ui/components/ui/button";+import buttonEn from "@multica/ui/docs/button.md?raw";+import buttonZh from "@multica/ui/docs/button.zh.md?raw";+import dialogEn from "@multica/ui/docs/dialog.md?raw";+import dialogZh from "@multica/ui/docs/dialog.zh.md?raw";++const rules = {+ button: { en: buttonEn, zh: buttonZh },+ dialog: { en: dialogEn, zh: dialogZh },+};++export function ComponentRules({+ component,+}: {+ component: keyof typeof rules;+}) {+ const { t, i18n } = useTranslation("uiLab");+ const locale = i18n.language === "zh-Hans" ? "zh" : "en";+ const content = rules[component][locale];+ return (+ <details className="component-rules">+ <summary>{t(($) => $.rules.content.title)}</summary>+ <div className="rules-source">+ <code>+ packages/ui/docs/{component}+ {locale === "zh" ? ".zh" : ""}.md+ </code>+ <Button+ variant="outline"+ size="sm"+ render={+ <a+ href={`data:text/markdown;charset=utf-8,${encodeURIComponent(content)}`}+ download={`${component}.${locale}.md`}+ />+ }+ >+ {t(($) => $.rules.content.download)}+ </Button>+ </div>+ <Markdown mode="full">{content}</Markdown>+ </details>+ );+}diff --git a/apps/ui-lab/src/contrast.test.ts b/apps/ui-lab/src/contrast.test.tsnew file mode 100644index 0000000000..598aa5eb6b--- /dev/null+++ b/apps/ui-lab/src/contrast.test.ts@@ -0,0 +1,35 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { contrastPasses, contrastRatio } from "./contrast";++describe("rendered color contrast", () => {+ it("uses WCAG relative luminance", () => {+ expect(contrastRatio("black", ["white"])).toBeCloseTo(21, 5);+ expect(contrastRatio("white", ["white"])).toBeCloseTo(1, 5);+ expect(contrastRatio("#777", ["white"])).toBeCloseTo(4.478, 3);+ });+ it("composites translucent surfaces and foregrounds in paint order", () => {+ expect(contrastRatio("rgb(0 0 0 / 50%)", ["white"])).toBeCloseTo(+ contrastRatio("rgb(127.5 127.5 127.5)", ["white"]),+ 8,+ );+ expect(+ contrastRatio("white", [+ "black",+ "rgb(255 255 255 / 10%)",+ "rgb(255 255 255 / 50%)",+ ]),+ ).toBeCloseTo(contrastRatio("white", ["rgb(140.25 140.25 140.25)"]), 8);+ expect(contrastRatio("transparent", ["white"])).toBeCloseTo(1, 8);+ });+ it("does not round a failing ratio into a pass", () => {+ expect(contrastPasses(4.4999, 4.5)).toBe(false);+ expect(contrastPasses(4.5, 4.5)).toBe(true);+ expect(contrastPasses(2.9999, 3)).toBe(false);+ });+ it("requires a known canvas and rejects unsupported colors", () => {+ expect(() => contrastRatio("black", [])).toThrow();+ expect(() => contrastRatio("black", ["transparent"])).toThrow();+ expect(() => contrastRatio("var(--unknown)", ["white"])).toThrow();+ });+});diff --git a/apps/ui-lab/src/contrast.ts b/apps/ui-lab/src/contrast.tsnew file mode 100644index 0000000000..3b91cd55ad--- /dev/null+++ b/apps/ui-lab/src/contrast.ts@@ -0,0 +1,43 @@+import Color from "colorjs.io";++type Rgb = [number, number, number];++function rgb(value: string) {+ const color = new Color(value).to("srgb").toGamut();+ return {+ channels: color.coords.map((n) => n ?? 0) as Rgb,+ alpha: color.alpha,+ };+}++function composite(value: string, background: Rgb): Rgb {+ const { channels, alpha } = rgb(value);+ return channels.map(+ (channel, i) => channel * alpha + background[i]! * (1 - alpha),+ ) as Rgb;+}++/** Backgrounds run from the opaque outer canvas to the innermost surface. */+export function resolveBackground(backgrounds: string[]): Color {+ if (!backgrounds.length || rgb(backgrounds[0]!).alpha < 1) {+ throw new Error("Contrast requires an opaque canvas");+ }+ const background = backgrounds.reduce<Rgb>(+ (result, layer) => composite(layer, result),+ [0, 0, 0],+ );+ return new Color("srgb", background);+}++export function contrastRatio(+ foreground: string,+ backgrounds: string[],+): number {+ const background = resolveBackground(backgrounds);+ const text = composite(foreground, background.coords as Rgb);+ return Color.contrastWCAG21(new Color("srgb", text), background);+}++export function contrastPasses(ratio: number, minimum: number): boolean {+ return ratio >= minimum;+}diff --git a/apps/ui-lab/src/dialog-scene.tsx b/apps/ui-lab/src/dialog-scene.tsxnew file mode 100644index 0000000000..62e24de546--- /dev/null+++ b/apps/ui-lab/src/dialog-scene.tsx@@ -0,0 +1,175 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@multica/ui/components/ui/dialog";+import { ComponentRules } from "./component-rules";+import { isDialogCommand } from "./protocol";+import { motionTokens, easingTokens, tokenValue, type Draft } from "./tokens";++export function DialogScene({+ motion,+ draft,+ speed,+}: {+ motion: boolean;+ draft: Draft;+ speed: number;+}) {+ const { t } = useTranslation("uiLab");+ const [open, setOpen] = useState(false);+ const [example, setExample] = useState("form");+ const [title, setTitle] = useState<string | null>(null);+ const [saved, setSaved] = useState(false);+ const [reduced, setReduced] = useState(false);+ const replay = useRef(false);+ const openRef = useRef(open);+ openRef.current = open;+ useEffect(() => {+ const query = matchMedia("(prefers-reduced-motion: reduce)");+ const sync = () => setReduced(query.matches);+ sync();+ query.addEventListener("change", sync);+ return () => query.removeEventListener("change", sync);+ }, []);+ useEffect(() => {+ const receive = (event: MessageEvent<unknown>) => {+ if (+ event.origin !== location.origin ||+ event.source !== window.parent ||+ !isDialogCommand(event.data)+ )+ return;+ if (event.data.action !== "close") setSaved(false);+ replay.current = event.data.action === "replay" && openRef.current;+ setOpen(+ event.data.action === "open" ||+ (event.data.action === "replay" && !openRef.current),+ );+ };+ window.addEventListener("message", receive);+ return () => window.removeEventListener("message", receive);+ }, []);+ const selectors =+ ':root [data-slot="dialog-content"], :root [data-slot="dialog-overlay"]';+ return (+ <div className="button-scene dialog-scene">+ <style>{`${selectors} { --tw-animation-duration: calc(var(--dialog-enter-duration) / ${speed}); } :root [data-slot="dialog-content"][data-closed], :root [data-slot="dialog-overlay"][data-closed] { --tw-animation-duration: calc(var(--dialog-exit-duration) / ${speed}); }`}</style>+ <header className="button-intro">+ <h1>{t(($) => $.system.pages[motion ? "motion" : "dialog"])}</h1>+ {motion && <code>Dialog</code>}+ </header>+ {reduced && (+ <p className="motion-reduced" role="status">+ {t(($) => $.motion.controls.reduced)}+ </p>+ )}+ <section className="button-section">+ <div className="button-playground-controls dialog-options">+ <label>+ {t(($) => $.dialog.controls.example)}+ <select+ value={example}+ onChange={(event) => {+ setExample(event.target.value);+ setSaved(false);+ }}+ >+ <option value="form">{t(($) => $.dialog.controls.form)}</option>+ <option value="long">{t(($) => $.dialog.controls.long)}</option>+ </select>+ </label>+ </div>+ <div className="button-stage">+ <Dialog+ open={open}+ onOpenChange={(value) => {+ if (value) setSaved(false);+ replay.current = false;+ setOpen(value);+ }}+ onOpenChangeComplete={(value) => {+ if (!value && replay.current) {+ replay.current = false;+ setOpen(true);+ }+ }}+ >+ <DialogTrigger render={<Button />}>+ {t(($) => $.dialog.actions.open)}+ </DialogTrigger>+ <DialogContent showCloseButton={false}>+ <DialogHeader>+ <DialogTitle>{t(($) => $.dialog.content.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.dialog.content.description)}+ </DialogDescription>+ </DialogHeader>+ <form+ className="dialog-example-form"+ onSubmit={(event) => {+ event.preventDefault();+ setSaved(true);+ replay.current = false;+ setOpen(false);+ }}+ >+ <label>+ {t(($) => $.dialog.content.label)}+ <Input+ required+ value={title ?? t(($) => $.dialog.content.defaultTitle)}+ onChange={(event) => setTitle(event.target.value)}+ />+ </label>+ {example === "long" && (+ <div className="dialog-long-content">+ {Array.from({ length: 12 }, (_, index) => (+ <p key={index}>+ {t(($) => $.dialog.content.item, { number: index + 1 })}+ </p>+ ))}+ </div>+ )}+ <DialogFooter>+ <DialogClose+ render={<Button type="button" variant="outline" />}+ >+ {t(($) => $.dialog.actions.cancel)}+ </DialogClose>+ <Button type="submit">+ {t(($) => $.dialog.actions.save)}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ <p role="status">+ {t(+ ($) =>+ $.dialog.states[saved ? "saved" : open ? "open" : "closed"],+ )}+ </p>+ </div>+ <div className="motion-token-list">+ {[...motionTokens, ...easingTokens].map((token) => (+ <div key={token.key}>+ <span>{t(($) => $.tokens.labels[token.label])}</span>+ <code>{tokenValue(draft, "shared", token.key)}</code>+ </div>+ ))}+ </div>+ </section>+ <ComponentRules component="dialog" />+ </div>+ );+}diff --git a/apps/ui-lab/src/inspector.tsx b/apps/ui-lab/src/inspector.tsxnew file mode 100644index 0000000000..08e824f4c0--- /dev/null+++ b/apps/ui-lab/src/inspector.tsx@@ -0,0 +1,529 @@+import { TokenChanges } from "./token-changes";+import { useTranslation } from "react-i18next";+import { useEffect, useState, type ReactNode } from "react";+import {+ ArrowDownToLine,+ ChevronDown,+ Component,+ RotateCcw,+ X,+} from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "@multica/ui/components/ui/tabs";+import {+ baseline,+ motionTokens,+ easingTokens,+ motionEasings,+ numericTokenValue,+ buttonScales,+ buttonTokens,+ changeCount,+ colorTokens,+ colorAlpha,+ sizeTokens,+ sizeValue,+ tokenValue,+ updateToken,+ type ButtonScale,+ type Draft,+ type Scope,+ type Theme,+} from "./tokens";+import { type Scene } from "./protocol";+import { NumberField } from "./number-field";+import { ColorEditor } from "./color-editor";+import { colorToHex } from "./color";++function PropertySection({+ title,+ scope,+ children,+ actions,+}: {+ title: string;+ scope?: string;+ children: ReactNode;+ actions?: ReactNode;+}) {+ return (+ <section className="property-section">+ <header>+ <h3>{title}</h3>+ {scope && <span className="property-scope">{scope}</span>}+ {actions}+ </header>+ {children}+ </section>+ );+}++export function Inspector({+ panelAction,+ scene,+ theme,+ draft,+ previewDraft,+ buttonScale,+ color,+ currentColor,+ onScaleChange,+ onEdit,+ onNumberPreview,+ onNumberCancel,+ onColorSelect,+ onColorPreview,+ onColorCancel,+ onExport,+}: {+ panelAction?: ReactNode;+ scene: Scene;+ theme: Theme;+ draft: Draft;+ previewDraft: Draft;+ buttonScale: ButtonScale;+ color: string;+ currentColor: string;+ onScaleChange: (scale: ButtonScale) => void;+ onEdit: (draft: Draft) => void;+ onNumberPreview: (key: string, value: number) => void;+ onNumberCancel: () => void;+ onColorSelect: (token: string) => void;+ onColorPreview: (value: string) => void;+ onColorCancel: () => void;+ onExport: () => void;+}) {+ const { t } = useTranslation("uiLab");+ const [tab, setTab] = useState("design");+ const [openColor, setOpenColor] = useState<string | null>(null);+ useEffect(() => {+ if (scene === "colors") setTab("design");+ }, [color, scene]);+ const count = changeCount(draft);+ const reset = (scope: Scope, key: string) =>+ onEdit(updateToken(draft, scope, key, baseline[scope][key]!));+ const symbols: Record<string, string> = {+ radius: "⌜",+ type: "T",+ density: "H",+ };+ const number = (token: (typeof sizeTokens)[number]) => (+ <NumberField+ key={token.key}+ label={t(($) => $.tokens.labels[token.label])}+ min={token.min}+ max={token.max}+ step={token.step}+ unit={token.unit}+ token={token.key}+ symbol={+ token.key.includes("height")+ ? "H"+ : token.key.includes("padding")+ ? "↔"+ : token.key.includes("gap")+ ? "⋮"+ : (symbols[token.group] ?? "#")+ }+ value={sizeValue(tokenValue(previewDraft, "shared", token.key))}+ modified={!!draft.shared[token.key]}+ onPreview={(value) => onNumberPreview(token.key, value)}+ onCommit={(value) =>+ onEdit(+ updateToken(+ draft,+ "shared",+ token.key,+ numericTokenValue(token.key, value),+ ),+ )+ }+ onCancel={onNumberCancel}+ onReset={() => reset("shared", token.key)}+ />+ );+ const prominent =+ scene === "button"+ ? ["--primary", "--primary-foreground", "--brand", "--destructive"]+ : scene === "dialog" || scene === "motion"+ ? [+ "--surface-raised",+ "--foreground",+ "--muted-foreground",+ "--primary",+ ]+ : ["--page-canvas", "--surface", "--foreground", "--brand"];+ const colorRow = ([key, labelKey]: (typeof colorTokens)[number]) => {+ const label = t(($) => $.tokens.labels[labelKey]);+ const value = color === key ? currentColor : tokenValue(draft, theme, key);+ return (+ <Popover+ key={key}+ open={openColor === key}+ onOpenChange={(open) => {+ setOpenColor(open ? key : null);+ if (open) onColorSelect(key);+ else onColorCancel();+ }}+ >+ <PopoverTrigger+ render={+ <button+ type="button"+ className="property-color-row"+ aria-label={t(($) => $.inspector.actions.edit, { label })}+ />+ }+ >+ <span className="property-color-label" title={key}>+ {label}+ </span>+ <span className="property-color-value">+ <span+ className="property-color-chip"+ style={{ background: value }}+ />+ <code>+ {colorToHex(value).slice(1)}+ {colorAlpha(value) < 1 &&+ ` · ${Math.round(colorAlpha(value) * 100)}%`}+ </code>+ {draft[theme][key] && (+ <span+ className="property-modified"+ aria-hidden="true"+ title={t(($) => $.inspector.changes.modified)}+ />+ )}+ </span>+ </PopoverTrigger>+ <PopoverContent+ side="left"+ align="start"+ sideOffset={12}+ className="property-color-popup"+ aria-label={t(($) => $.color.controls.editor, { label })}+ >+ <div className="property-popup-heading">+ <strong>{label}</strong>+ <span>+ {theme === "light"+ ? t(($) => $.lab.theme.light)+ : t(($) => $.lab.theme.dark)}+ </span>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.color.controls.close)}+ onClick={() => {+ setOpenColor(null);+ onColorCancel();+ }}+ >+ <X />+ </Button>+ </div>+ <ColorEditor+ key={`${theme}:${key}`}+ showRoleSelector={false}+ token={key}+ value={value}+ original={baseline[theme][key]!}+ modified={!!draft[theme][key]}+ values={Object.fromEntries(+ colorTokens.map(([token]) => [+ token,+ tokenValue(draft, theme, token),+ ]),+ )}+ onTokenChange={onColorSelect}+ onPreview={onColorPreview}+ onCancel={onColorCancel}+ onCommit={(next) => onEdit(updateToken(draft, theme, key, next))}+ />+ </PopoverContent>+ </Popover>+ );+ };+ return (+ <aside+ className="lab-inspector property-inspector"+ aria-label={t(($) => $.inspector.panel.label)}+ >+ <Tabs+ value={tab}+ onValueChange={(value) => {+ setTab(value);+ onNumberCancel();+ onColorCancel();+ }}+ className="property-tabs"+ >+ <div className="property-tabs-header">+ <TabsList+ variant="line"+ aria-label={t(($) => $.inspector.panel.tabs)}+ >+ <TabsTrigger value="design">+ {t(($) => $.inspector.panel.design)}+ </TabsTrigger>+ <TabsTrigger value="changes">+ {t(($) => $.inspector.panel.changes)}+ {count > 0 && <span className="property-count">{count}</span>}+ </TabsTrigger>+ </TabsList>+ <div className="property-header-actions">+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.inspector.changes.reset)}+ title={t(($) => $.inspector.changes.resetTitle)}+ disabled={!count}+ onClick={() => onEdit({ light: {}, dark: {}, shared: {} })}+ >+ <RotateCcw />+ </Button>+ {panelAction}+ </div>+ </div>+ <TabsContent value="design" className="property-tab-panel">+ {scene === "colors" ? (+ <section+ className="palette-editor-section"+ aria-label={t(($) => $.palette.page.selected)}+ >+ <div className="palette-editor-theme">+ {t(($) => $.lab.theme[theme])}+ </div>+ <ColorEditor+ key={`${theme}:${color}`}+ token={color}+ value={currentColor}+ original={baseline[theme][color]!}+ modified={!!draft[theme][color]}+ values={Object.fromEntries(+ colorTokens.map(([token]) => [+ token,+ tokenValue(draft, theme, token),+ ]),+ )}+ onTokenChange={onColorSelect}+ onPreview={onColorPreview}+ onCancel={onColorCancel}+ onCommit={(value) =>+ onEdit(updateToken(draft, theme, color, value))+ }+ />+ </section>+ ) : (+ <>+ <div className="property-object">+ <div>+ <Component className="size-4" />+ <strong>+ {scene === "button"+ ? "Button"+ : scene === "dialog" || scene === "motion"+ ? "Dialog"+ : t(($) => $.inspector.panel.system)}+ </strong>+ </div>+ </div>+ {scene === "button" && (+ <PropertySection+ title={t(($) => $.inspector.sections.size)}+ scope={t(($) => $.inspector.scope.component)}+ actions={+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.inspector.changes.resetButton)}+ title={t(($) => $.inspector.changes.resetButtonTitle)}+ disabled={+ !buttonTokens.some((token) => draft.shared[token.key])+ }+ onClick={() =>+ onEdit({+ ...draft,+ shared: Object.fromEntries(+ Object.entries(draft.shared).filter(+ ([key]) => !key.startsWith("--button-"),+ ),+ ),+ })+ }+ >+ <RotateCcw />+ </Button>+ }+ >+ <div+ className="property-segments"+ role="group"+ aria-label={t(($) => $.inspector.sections.adjustSize)}+ >+ {buttonScales.map((scale) => (+ <button+ key={scale}+ type="button"+ aria-label={t(($) => $.inspector.actions.size, {+ size: scale,+ })}+ aria-pressed={buttonScale === scale}+ onClick={() => onScaleChange(scale)}+ >+ {scale === "default"+ ? "M"+ : scale === "sm"+ ? "S"+ : scale.toUpperCase()}+ </button>+ ))}+ </div>+ <div className="property-grid">+ {buttonTokens+ .filter((token) => token.scale === buttonScale)+ .map(number)}+ </div>+ </PropertySection>+ )}+ {(scene === "dialog" || scene === "motion") && (+ <PropertySection+ title={t(($) => $.motion.controls.title)}+ scope="Dialog"+ >+ <div className="property-grid">+ {motionTokens.map(number)}+ </div>+ {easingTokens.map((token) => (+ <div className="motion-easing" key={token.key}>+ <span>{t(($) => $.tokens.labels[token.label])}</span>+ <select+ aria-label={t(($) => $.tokens.labels[token.label])}+ value={tokenValue(draft, "shared", token.key)}+ onChange={(event) =>+ onEdit(+ updateToken(+ draft,+ "shared",+ token.key,+ event.target.value,+ ),+ )+ }+ >+ {motionEasings.map((easing) => (+ <option key={easing.value} value={easing.value}>+ {t(($) => $.motion.easing[easing.label])}+ </option>+ ))}+ </select>+ <Button+ variant="ghost"+ size="icon-xs"+ disabled={!draft.shared[token.key]}+ aria-label={t(($) => $.inspector.actions.restore, {+ key: token.key,+ scope: t(($) => $.inspector.scope.shared),+ })}+ onClick={() => reset("shared", token.key)}+ >+ <RotateCcw />+ </Button>+ </div>+ ))}+ </PropertySection>+ )}+ <PropertySection+ title={t(($) => $.inspector.sections.appearance)}+ scope={t(($) => $.inspector.scope.global)}+ >+ <div className="property-grid">+ {sizeTokens+ .filter((token) => token.group === "radius")+ .map(number)}+ <div className="property-radius-preview" aria-hidden="true">+ <span+ style={{+ borderRadius: sizeValue(+ tokenValue(previewDraft, "shared", "--radius"),+ ),+ }}+ />+ </div>+ </div>+ </PropertySection>+ <PropertySection+ title={t(($) => $.inspector.sections.colors)}+ scope={t(($) => $.inspector.scope.theme, {+ theme: t(($) => $.lab.theme[theme]),+ })}+ >+ <div className="property-colors">+ {colorTokens+ .filter(([key]) => prominent.includes(key))+ .map(colorRow)}+ </div>+ <details className="property-more-colors">+ <summary>+ {t(($) => $.inspector.sections.moreColors)}+ <ChevronDown className="size-3" />+ </summary>+ <div className="property-colors">+ {colorTokens+ .filter(([key]) => !prominent.includes(key))+ .map(colorRow)}+ </div>+ </details>+ </PropertySection>+ <PropertySection+ title={t(($) => $.inspector.sections.type)}+ scope={t(($) => $.inspector.scope.global)}+ >+ <div className="property-grid">+ {sizeTokens+ .filter((token) => token.group === "type")+ .map(number)}+ </div>+ </PropertySection>+ {(scene === "list" ||+ scene === "detail" ||+ scene === "components") && (+ <PropertySection+ title={t(($) => $.inspector.sections.density)}+ scope={t(($) => $.inspector.scope.global)}+ >+ <div className="property-grid">+ {sizeTokens+ .filter((token) => token.group === "density")+ .map(number)}+ </div>+ </PropertySection>+ )}+ </>+ )}+ </TabsContent>+ <TabsContent value="changes" className="property-tab-panel">+ <TokenChanges draft={draft} onEdit={onEdit} />+ </TabsContent>+ </Tabs>+ <div className="property-export">+ <Button variant="outline" onClick={onExport}>+ <ArrowDownToLine />+ {t(($) => $.inspector.changes.export)}+ <span>{count || ""}</span>+ </Button>+ </div>+ </aside>+ );+}diff --git a/apps/ui-lab/src/lab-i18n.tsx b/apps/ui-lab/src/lab-i18n.tsxnew file mode 100644index 0000000000..02788b2ba5--- /dev/null+++ b/apps/ui-lab/src/lab-i18n.tsx@@ -0,0 +1,35 @@+import { useEffect, type ReactNode } from "react";+import { I18nProvider } from "@multica/core/i18n/react";+import enUi from "@multica/views/locales/en/ui.json";+import zhUi from "@multica/views/locales/zh-Hans/ui.json";+import en from "./locales/en.json";+import zh from "./locales/zh.json";+import { productLocale, type LabLocale } from "./locale";++declare global {+ interface I18nResources {+ uiLab: typeof en;+ }+}++const resources = {+ en: { uiLab: en, ui: enUi },+ "zh-Hans": { uiLab: zh, ui: zhUi },+};++export function LabI18nProvider({+ locale,+ children,+}: {+ locale: LabLocale;+ children: ReactNode;+}) {+ useEffect(() => {+ document.documentElement.lang = productLocale(locale);+ }, [locale]);+ return (+ <I18nProvider locale={productLocale(locale)} resources={resources}>+ {children}+ </I18nProvider>+ );+}diff --git a/apps/ui-lab/src/locale.test.ts b/apps/ui-lab/src/locale.test.tsnew file mode 100644index 0000000000..a71aee80eb--- /dev/null+++ b/apps/ui-lab/src/locale.test.ts@@ -0,0 +1,97 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import i18next from "i18next";+import {+ isLabLocale,+ loadLocale,+ LOCALE_STORAGE_KEY,+ productLocale,+} from "./locale";+import { isPreviewSettings } from "./protocol";+import { emptyDraft } from "./tokens";+import en from "./locales/en.json";+import zh from "./locales/zh.json";++afterEach(() => vi.unstubAllGlobals());++describe("UI Lab language preference", () => {+ it("defaults to English regardless of browser language and accepts only en or zh", () => {+ vi.stubGlobal("navigator", { language: "zh-CN" });+ for (const saved of [null, "", "ja", "zh-Hans", "garbage"]) {+ vi.stubGlobal("localStorage", {+ getItem: vi.fn().mockReturnValue(saved),+ });+ expect(loadLocale()).toBe("en");+ }+ for (const saved of ["en", "zh"]) {+ const getItem = vi.fn().mockReturnValue(saved);+ vi.stubGlobal("localStorage", { getItem });+ expect(loadLocale()).toBe(saved);+ expect(getItem).toHaveBeenCalledWith(LOCALE_STORAGE_KEY);+ }+ vi.stubGlobal("localStorage", {+ getItem: () => {+ throw new Error("Storage blocked");+ },+ });+ expect(loadLocale()).toBe("en");+ });++ it("validates iframe locales and maps zh to the production locale", () => {+ const message = {+ type: "multica-ui-lab:preview",+ selectedColor: "--brand",+ playbackSpeed: 1,+ scene: "button",+ theme: "light",+ buttonScale: "default",+ draft: emptyDraft(),+ };+ for (const locale of [+ undefined,+ null,+ "",+ "fr",+ "zh-Hans",+ {},+ "en",+ "zh",+ ]) {+ expect(isPreviewSettings({ ...message, locale })).toBe(+ isLabLocale(locale),+ );+ }+ expect(productLocale("en")).toBe("en");+ expect(productLocale("zh")).toBe("zh-Hans");+ });++ it("provides both catalogs with matching keys and working counts and interpolation", () => {+ const keys = (value: object, prefix = ""): string[] =>+ Object.entries(value).flatMap(([key, item]) =>+ item && typeof item === "object"+ ? keys(item, `${prefix}${key}.`)+ : [`${prefix}${key}`],+ );+ expect(keys(zh).sort()).toEqual(keys(en).sort());+ const i18n = i18next.createInstance();+ void i18n.init({+ lng: "en",+ initAsync: false,+ resources: { en: { uiLab: en }, zh: { uiLab: zh } },+ });+ const english = i18n.getFixedT("en", "uiLab");+ const chinese = i18n.getFixedT("zh", "uiLab");+ expect(english(($) => $.lab.preview.changeCount, { count: 1 })).toBe(+ "1 change",+ );+ expect(english(($) => $.lab.preview.changeCount, { count: 2 })).toBe(+ "2 changes",+ );+ expect(chinese(($) => $.lab.preview.changeCount, { count: 2 })).toBe(+ "2 项修改",+ );+ expect(+ english(($) => $.lab.notice.loaded, { name: "Custom <design>" }),+ ).toContain("Custom");+ });+});diff --git a/apps/ui-lab/src/locale.ts b/apps/ui-lab/src/locale.tsnew file mode 100644index 0000000000..1391155c17--- /dev/null+++ b/apps/ui-lab/src/locale.ts@@ -0,0 +1,15 @@+export type LabLocale = "en" | "zh";+export const LOCALE_STORAGE_KEY = "multica-ui-lab:locale";+export function isLabLocale(value: unknown): value is LabLocale {+ return value === "en" || value === "zh";+}+export function loadLocale(): LabLocale {+ try {+ const saved = localStorage.getItem(LOCALE_STORAGE_KEY);+ return isLabLocale(saved) ? saved : "en";+ } catch {+ return "en";+ }+}+export const productLocale = (locale: LabLocale) =>+ locale === "zh" ? "zh-Hans" : "en";diff --git a/apps/ui-lab/src/locales/en.json b/apps/ui-lab/src/locales/en.jsonnew file mode 100644index 0000000000..c4d6a5a66c--- /dev/null+++ b/apps/ui-lab/src/locales/en.json@@ -0,0 +1,553 @@+{+ "lab": {+ "preview": {+ "source": "Source",+ "preview": "Preview",+ "originalFrame": "Original preview",+ "editedFrame": "Edited preview",+ "unchanged": "No changes",+ "back": "Back to edits",+ "original": "View original",+ "compare": "Compare",+ "unavailable": "This preview includes the issue list and detail pages.",+ "changeCount_other": "{{count}} changes",+ "changeCount_one": "{{count}} change"+ },+ "theme": {+ "light": "Light",+ "dark": "Dark",+ "label": "Preview theme",+ "lightLabel": "Light theme",+ "darkLabel": "Dark theme"+ },+ "notice": {+ "saved": "Design saved",+ "copied": "CSS copied",+ "copyFailed": "Select the code to copy it, or download CSS.",+ "exported": "CSS exported",+ "storageFailed": "Cannot save drafts. Export CSS to keep your changes.",+ "dismiss": "Dismiss notification",+ "loaded": "Loaded: {{name}}"+ },+ "nav": {+ "toggle": "Toggle navigation",+ "internal": "Workbench",+ "scenes": "Components & scenes",+ "previewScenes": "Preview scenes",+ "saved": "Saved designs",+ "empty": "No saved designs",+ "workbench": "Workbench"+ },+ "actions": {+ "undo": "Undo",+ "redo": "Redo",+ "save": "Save design",+ "export": "Export changes",+ "deleteDesign": "Delete design {{name}}"+ },+ "save": {+ "title": "Save design",+ "description": "Saved in this browser. Up to 20 designs.",+ "name": "Design name",+ "placeholder": "e.g. Compact issue list"+ },+ "export": {+ "title": "Export changes",+ "description": "Merge into the matching blocks in packages/ui/styles/tokens.css. Export does not update source files.",+ "copy": "Copy CSS",+ "download": "Download CSS"+ },+ "scenes": {+ "components": "Components",+ "button": "Button",+ "list": "Issue list",+ "detail": "Issue detail",+ "dialog": "Dialog",+ "motion": "Motion",+ "colors": "Colors"+ },+ "language": {+ "label": "Language"+ },+ "panels": {+ "expandLeft": "Expand left sidebar",+ "collapseLeft": "Collapse left sidebar",+ "expandRight": "Expand right sidebar",+ "collapseRight": "Collapse right sidebar"+ }+ },+ "button": {+ "variants": {+ "primary": "Primary",+ "secondary": "Secondary",+ "soft": "Soft fill",+ "ghost": "Ghost",+ "brand": "Brand",+ "brandSoft": "Soft brand",+ "destructive": "Destructive",+ "link": "Link"+ },+ "actions": {+ "create": "Create issue",+ "continue": "Continue",+ "submit": "Submit issue",+ "more": "More actions",+ "dialog": "Open dialog",+ "save": "Save changes",+ "saveExample": "Save example",+ "saveNext": "Save and create another issue",+ "compactAdd": "Add in compact layout",+ "quick": "Quick action",+ "addSize": "Add issue {{size}}"+ },+ "page": {+ "title": "Button",+ "variantCount": "8 variants",+ "sizeCount": "8 sizes",+ "contents": "Button sections",+ "playground": "Playground",+ "variants": "Variants & states",+ "context": "In context",+ "try": "Try a button",+ "sizes": "Sizes & icons"+ },+ "controls": {+ "label": "Label",+ "content": "Content",+ "leading": "Leading icon",+ "trailing": "Trailing icon",+ "textOnly": "Text only",+ "iconOnly": "Icon only",+ "state": "State",+ "icon": "Icon",+ "text": "Text"+ },+ "states": {+ "default": "Default",+ "disabled": "Disabled",+ "loading": "Loading",+ "invalid": "Invalid",+ "interactive": "Default / interactive",+ "processing": "Processing",+ "submitting": "Submitting...",+ "submitted": "Submitted",+ "complete": "Example submitted",+ "clicked_other": "Example triggered {{count}} times",+ "clicked_one": "Example triggered {{count}} time"+ },+ "geometry": {+ "height": "Height",+ "padding": "Padding"+ },+ "context": {+ "submit": "Submit & feedback",+ "triggers": "Overlay triggers",+ "popover": "Popover content",+ "saveDescription": "Save your changes.",+ "length": "Label length",+ "compact": "Compact layouts"+ }+ },+ "inspector": {+ "sections": {+ "size": "Size",+ "appearance": "Appearance",+ "type": "Typography",+ "adjustSize": "Adjust size",+ "colors": "Colors",+ "moreColors": "More colors",+ "density": "List density"+ },+ "changes": {+ "modified": "Modified",+ "reset": "Reset all changes",+ "resetTitle": "Reset all changes (can be undone)",+ "resetButton": "Reset button properties",+ "resetButtonTitle": "Reset all button sizes",+ "unchanged": "No changes",+ "empty": "All properties match the source",+ "export": "Export CSS",+ "restore": "Restore original value"+ },+ "panel": {+ "label": "Design properties",+ "tabs": "Property panel",+ "design": "Design",+ "changes": "Changes",+ "system": "Design system"+ },+ "scope": {+ "component": "Component",+ "global": "Global",+ "shared": "Shared",+ "theme": "Global · {{theme}}"+ },+ "actions": {+ "edit": "Edit {{label}}",+ "size": "Size {{size}}",+ "restore": "Restore {{key}} ({{scope}})",+ "scrub": "Drag to adjust {{label}}",+ "scrubHint": "{{token}}\nDrag to adjust. Shift for larger steps. Click to enter a value.",+ "reset": "Reset {{label}}",+ "invalid": "Enter a number between {{min}} and {{max}}."+ }+ },+ "tokens": {+ "labels": {+ "gap": "Icon gap",+ "brand": "Brand",+ "primary": "Primary fill",+ "primaryText": "Primary text",+ "secondary": "Secondary fill",+ "secondaryText": "Secondary text",+ "destructive": "Destructive",+ "ring": "Focus ring",+ "shell": "App shell",+ "page": "Page background",+ "surface": "Surface",+ "raised": "Overlay background",+ "hover": "Hover background",+ "selected": "Selected background",+ "foreground": "Text",+ "muted": "Muted text",+ "height": "Button height",+ "padding": "Horizontal padding",+ "rowHeight": "Issue row height",+ "radius": "Corner radius",+ "caption": "Caption",+ "label": "Label",+ "body": "Body",+ "lineHeight": "Body line height",+ "title": "Heading",+ "enterDuration": "Enter duration",+ "exitDuration": "Exit duration",+ "enterEasing": "Enter easing",+ "exitEasing": "Exit easing",+ "faint": "Subtle icons",+ "surfaceText": "Surface text",+ "selectedText": "Selected text",+ "cardText": "Card text",+ "popoverText": "Popover text",+ "brandText": "Brand text",+ "accent": "Accent fill",+ "accentText": "Accent text",+ "mutedFill": "Muted fill",+ "success": "Success",+ "warning": "Warning",+ "info": "Information",+ "border": "Border",+ "surfaceBorder": "Surface border",+ "inputBorder": "Input border",+ "sidebar": "Sidebar background",+ "sidebarText": "Sidebar text",+ "sidebarPrimary": "Sidebar primary",+ "sidebarPrimaryText": "Sidebar primary text",+ "sidebarAccent": "Sidebar hover",+ "sidebarAccentText": "Sidebar hover text",+ "sidebarBorder": "Sidebar border",+ "sidebarRing": "Sidebar focus ring",+ "chart1": "Chart 1",+ "chart2": "Chart 2",+ "chart3": "Chart 3",+ "chart4": "Chart 4",+ "chart5": "Chart 5"+ }+ },+ "color": {+ "feedback": {+ "invalid": "Enter a 3- or 6-digit HEX value.",+ "copied": "Color copied",+ "copyFailed": "Select the value to copy it manually.",+ "gamut": "Outside sRGB. HEX is approximate."+ },+ "roles": {+ "searchLabel": "Search color roles",+ "searchPlaceholder": "Search colors or variables...",+ "title": "Color roles",+ "empty": "No matching colors.",+ "current": "Color role: {{label}}"+ },+ "controls": {+ "picker": "Color picker",+ "hex": "HEX color",+ "copy": "Copy HEX color",+ "restoreTitle": "Restore the original color",+ "restore": "Restore original color",+ "original": "Original",+ "current": "Current",+ "reset": "Reset color",+ "presets": "Presets",+ "advanced": "Advanced",+ "close": "Close color editor",+ "use": "Use color {{color}}",+ "editor": "{{label}} color editor",+ "opacity": "Opacity"+ },+ "channels": {+ "lightness": "Lightness",+ "chroma": "Chroma",+ "hue": "Hue"+ }+ },+ "gallery": {+ "surfaces": {+ "shell": "Shell",+ "page": "Page",+ "surface": "Surface",+ "raised": "Overlay",+ "hover": "Hover",+ "selected": "Selected"+ },+ "dialog": {+ "open": "Open dialog",+ "title": "New issue",+ "description": "Enter an issue title.",+ "label": "Dialog issue title",+ "placeholder": "Enter issue title..."+ },+ "sections": {+ "title": "Components",+ "surfaces": "Surfaces",+ "forms": "Forms",+ "status": "Status & badges",+ "typography": "Typography",+ "elevation": "Elevation & radius",+ "feedback": "Loading & empty states"+ },+ "actions": {+ "new": "New",+ "outline": "Outline",+ "delete": "Delete",+ "disabled": "Disabled"+ },+ "form": {+ "title": "Example issue title",+ "placeholder": "Name your issue...",+ "notify": "Notify assignee",+ "autopilot": "Autopilot",+ "disabled": "Disabled input",+ "readonly": "Read only",+ "attention": "Needs attention"+ },+ "type": {+ "heading": "Small details. Better experiences.",+ "body": "Build with intention. Bring agents and teams together.",+ "label": "Issue properties · Assignee · Project",+ "caption": "Secondary text should be easy to read · 2 minutes ago",+ "cardTitle": "Improve the product experience",+ "cardDescription": "Inner and outer corner radii",+ "empty": "You're all caught up"+ }+ },+ "fixtures": {+ "issues": {+ "titles": [+ "Unify visual hierarchy across issue lists and details",+ "Improve keyboard navigation in the command menu",+ "Improve feedback and status display for agent runs",+ "Check mixed-language text and truncation of very long issue titles in narrow windows",+ "Establish consistent corner radii for menus and dialogs",+ "Refine selection and hover states in dark mode",+ "Keep empty states clear and lightweight"+ ],+ "description": "## Goal\n\nHelp the team find the most important information. Clear headings, comfortable body text, and quiet secondary details.\n\n## Acceptance criteria\n\n- [x] Share semantic colors and corner radii\n- [ ] Handle mixed-language text and long titles naturally\n- [ ] Keep selection visible on hover\n\nBuild with intention. Bring agents and teams together."+ },+ "comments": {+ "first": "Check list density, then compare typography in the detail page."+ }+ },+ "system": {+ "modules": {+ "foundations": "Foundations",+ "components": "Components",+ "patterns": "Patterns",+ "product": "Product",+ "layouts": "Layouts",+ "changes": "Changes"+ },+ "descriptions": {+ "foundations": "Colors, type, spacing and visual rules.",+ "components": "Primitives, variants and interaction states.",+ "patterns": "Reusable flows built from components.",+ "product": "Issue, team and agent interfaces.",+ "layouts": "Page structure and responsive behavior.",+ "changes": "Review, save and export design edits."+ },+ "pages": {+ "colors": "Colors",+ "typography": "Typography",+ "spacing": "Spacing",+ "radius": "Radius",+ "shadows": "Shadows",+ "motion": "Motion",+ "icons": "Icons",+ "gallery": "Component gallery",+ "button": "Button",+ "input": "Input",+ "select": "Select",+ "checkbox": "Checkbox",+ "switch": "Switch",+ "badge": "Badge",+ "tabs": "Tabs",+ "tooltip": "Tooltip",+ "dialog": "Dialog",+ "popover": "Popover",+ "forms": "Forms",+ "filters": "Search & filters",+ "properties": "Property editing",+ "confirmation": "Confirmation",+ "feedback": "Loading, empty & error",+ "issueRow": "Issue row",+ "statusPicker": "Status picker",+ "assigneePicker": "Assignee picker",+ "comments": "Comments",+ "agentRun": "Agent run",+ "sidebar": "Sidebar",+ "list": "Issue list",+ "detail": "Issue detail",+ "settings": "Settings",+ "split": "Split view",+ "review": "Change review",+ "saved": "Saved designs",+ "export": "CSS export",+ "impact": "Impact scope",+ "source": "Apply to source"+ },+ "navigation": {+ "overview": "Overview",+ "title": "Design system",+ "expand": "Toggle {{module}}"+ },+ "status": {+ "available": "Available",+ "planned": "To build",+ "progress": "{{ready}} / {{total}} available"+ },+ "empty": {+ "message": "This page is ready for its first examples.",+ "back": "Back to {{module}}",+ "notFound": "Page not found"+ },+ "changes": {+ "reset": "Reset all",+ "return": "Open Button"+ }+ },+ "motion": {+ "actions": {+ "open": "Open",+ "close": "Close",+ "replay": "Replay"+ },+ "controls": {+ "title": "Motion",+ "speed": "Preview speed",+ "reduced": "Reduced motion is enabled. Animations are disabled."+ },+ "easing": {+ "standard": "Standard",+ "linear": "Linear",+ "easeOut": "Ease out",+ "easeIn": "Ease in"+ }+ },+ "rules": {+ "content": {+ "title": "Usage & code",+ "download": "Download Markdown"+ }+ },+ "dialog": {+ "controls": {+ "example": "Example",+ "form": "Form",+ "long": "Long content"+ },+ "actions": {+ "open": "Open dialog",+ "cancel": "Cancel",+ "save": "Save"+ },+ "content": {+ "title": "Edit issue",+ "description": "Update the issue title.",+ "label": "Title",+ "defaultTitle": "Review interface",+ "item": "Check {{number}}: verify layout, content and actions remain accessible on a narrow screen."+ },+ "states": {+ "open": "Open",+ "closed": "Closed",+ "saved": "Example saved"+ }+ },+ "palette": {+ "page": {+ "title": "Colors",+ "search": "Search colors",+ "placeholder": "Search by name or token…",+ "empty": "No matching colors",+ "count": "{{count}} tokens",+ "edit": "Edit {{label}}",+ "aliases": "Aliases",+ "selected": "Selected color",+ "sample": "In use"+ },+ "groups": {+ "surfaces": "Surfaces",+ "content": "Content",+ "actions": "Actions",+ "feedback": "Feedback",+ "borders": "Borders & focus",+ "charts": "Charts",+ "sidebar": "Sidebar"+ },+ "sample": {+ "title": "Review interface",+ "description": "Update the task before assigning it.",+ "create": "Create issue",+ "cancel": "Cancel"+ }+ },+ "colorUsage": {+ "sections": "Color sections",+ "palette": "Palette",+ "title": "Usage & contrast",+ "mapping": "Token mapping",+ "preview": "Live states",+ "hint": "Hover, hold to press, or use Tab to focus. Select a token above to edit it.",+ "roles": {+ "action": "Main action",+ "brand": "Active filter / toggle",+ "tabs": "Tabs · label / indicator",+ "input": "Input · text / border",+ "focus": "Keyboard focus",+ "error": "Invalid input"+ },+ "states": {+ "default": "Default",+ "hover": "Hover",+ "pressed": "Pressed",+ "focus": "Focus",+ "selected": "Selected",+ "invalid": "Invalid",+ "disabled": "Disabled"+ },+ "unmeasured": "Not measured",+ "pass": "Pass",+ "fail": "Fail",+ "exempt": "Exempt · disabled",+ "text": "Text",+ "focusBorder": "Focus border",+ "mainAction": "Main action",+ "activeFilter": "Assigned to me",+ "overview": "Overview",+ "activity": "Activity",+ "overviewContent": "Task details",+ "activityContent": "Recent updates",+ "taskName": "Task name",+ "rules": "Rules & measurement",+ "scope": "Text target: 4.5:1. Focus border target: 3:1 against both adjacent surfaces. Uses rendered sRGB colors, composited transparency and settled transitions. Disabled controls are exempt. Images and group opacity are not measured. Placeholder text, tab indicators and focus-ring geometry require separate review; this is not a full accessibility audit.",+ "policy": "Keep main actions neutral; brand identifies active controls. Tabs use foreground and muted text. Input errors use destructive, and focus uses ring. Check both themes before exporting. Token edits affect every consumer of that token."+ }+}diff --git a/apps/ui-lab/src/locales/zh.json b/apps/ui-lab/src/locales/zh.jsonnew file mode 100644index 0000000000..1ac45f494a--- /dev/null+++ b/apps/ui-lab/src/locales/zh.json@@ -0,0 +1,553 @@+{+ "lab": {+ "preview": {+ "source": "当前代码",+ "preview": "预览",+ "originalFrame": "原版界面",+ "editedFrame": "调整后的界面",+ "unchanged": "与当前代码一致",+ "back": "返回修改版",+ "original": "查看原版",+ "compare": "并排对比",+ "unavailable": "当前预览提供任务列表和详情,其他页面尚未配置样例数据。",+ "changeCount_other": "{{count}} 项修改",+ "changeCount_one": "{{count}} 项修改"+ },+ "theme": {+ "light": "浅色",+ "dark": "深色",+ "label": "预览主题",+ "lightLabel": "浅色主题",+ "darkLabel": "深色主题"+ },+ "notice": {+ "saved": "方案已保存到此浏览器",+ "copied": "CSS 已复制",+ "copyFailed": "无法访问剪贴板,请选择代码手动复制,或下载 CSS",+ "exported": "CSS 已导出",+ "storageFailed": "浏览器无法保存草稿,请导出 CSS 以保留修改。",+ "dismiss": "关闭提示",+ "loaded": "已载入:{{name}}"+ },+ "nav": {+ "toggle": "切换场景导航",+ "internal": "内部工作台",+ "scenes": "组件与场景",+ "previewScenes": "预览场景",+ "saved": "已存方案",+ "empty": "暂无方案",+ "workbench": "工作台"+ },+ "actions": {+ "undo": "撤销",+ "redo": "重做",+ "save": "保存方案",+ "export": "导出修改",+ "deleteDesign": "删除方案 {{name}}"+ },+ "save": {+ "title": "保存设计方案",+ "description": "保存在当前浏览器,最多 20 份。",+ "name": "方案名称",+ "placeholder": "例如:更紧凑的任务视图"+ },+ "export": {+ "title": "导出设计修改",+ "description": "合并到 packages/ui/styles/tokens.css 的对应代码块。导出不会写回源码。",+ "copy": "复制 CSS",+ "download": "下载 CSS"+ },+ "scenes": {+ "components": "组件总览",+ "button": "Button 按钮",+ "list": "任务列表",+ "detail": "任务详情",+ "dialog": "弹窗",+ "motion": "动效",+ "colors": "颜色"+ },+ "language": {+ "label": "语言"+ },+ "panels": {+ "expandLeft": "展开左侧栏",+ "collapseLeft": "折叠左侧栏",+ "expandRight": "展开右侧栏",+ "collapseRight": "折叠右侧栏"+ }+ },+ "button": {+ "variants": {+ "primary": "主要操作",+ "secondary": "次要操作",+ "soft": "柔和填充",+ "ghost": "轻量操作",+ "brand": "品牌强调",+ "brandSoft": "品牌浅色",+ "destructive": "危险操作",+ "link": "链接样式"+ },+ "actions": {+ "create": "创建任务",+ "continue": "继续",+ "submit": "提交任务",+ "more": "更多操作",+ "dialog": "打开对话框",+ "save": "保存修改",+ "saveExample": "保存示例",+ "saveNext": "保存并继续创建下一项任务",+ "compactAdd": "紧凑添加",+ "quick": "快捷操作",+ "addSize": "添加任务 {{size}}"+ },+ "page": {+ "title": "按钮",+ "variantCount": "8 种外观",+ "sizeCount": "8 种尺寸",+ "contents": "按钮页面目录",+ "playground": "试用",+ "variants": "外观与状态",+ "context": "使用场景",+ "try": "试用按钮",+ "sizes": "尺寸与图标"+ },+ "controls": {+ "label": "按钮文字",+ "content": "内容",+ "leading": "前置图标",+ "trailing": "后置图标",+ "textOnly": "仅文字",+ "iconOnly": "仅图标",+ "state": "状态",+ "icon": "图标",+ "text": "文字"+ },+ "states": {+ "default": "默认",+ "disabled": "禁用",+ "loading": "加载中",+ "invalid": "无效输入",+ "interactive": "默认 / 可交互",+ "processing": "处理中",+ "submitting": "提交中...",+ "submitted": "已提交",+ "complete": "示例提交完成",+ "clicked_other": "已触发 {{count}} 次示例操作",+ "clicked_one": "已触发 {{count}} 次示例操作"+ },+ "geometry": {+ "height": "高度",+ "padding": "内边距"+ },+ "context": {+ "submit": "提交与反馈",+ "triggers": "弹层触发器",+ "popover": "弹层内容",+ "saveDescription": "保存当前修改。",+ "length": "文字长度",+ "compact": "紧凑空间"+ }+ },+ "inspector": {+ "sections": {+ "size": "尺寸",+ "appearance": "外观",+ "type": "文字",+ "adjustSize": "调整尺寸",+ "colors": "颜色",+ "moreColors": "更多颜色",+ "density": "列表密度"+ },+ "changes": {+ "modified": "已修改",+ "reset": "重置全部修改",+ "resetTitle": "重置全部修改(可撤销)",+ "resetButton": "重置按钮参数",+ "resetButtonTitle": "重置全部按钮尺寸",+ "unchanged": "与原版一致",+ "empty": "所有参数均使用当前代码的值",+ "export": "导出 CSS",+ "restore": "恢复原版值"+ },+ "panel": {+ "label": "设计参数",+ "tabs": "属性面板",+ "design": "设计",+ "changes": "修改",+ "system": "设计系统"+ },+ "scope": {+ "component": "组件",+ "global": "全局",+ "shared": "共享",+ "theme": "全局 · {{theme}}"+ },+ "actions": {+ "edit": "编辑{{label}}",+ "size": "尺寸 {{size}}",+ "restore": "恢复 {{key}} {{scope}}",+ "scrub": "拖动调整{{label}}",+ "scrubHint": "{{token}}\n左右拖动调整,Shift 加速;点击输入数值。",+ "reset": "重置{{label}}",+ "invalid": "请输入 {{min}}–{{max}} 之间的数值。"+ }+ },+ "tokens": {+ "labels": {+ "gap": "图文间距",+ "brand": "品牌色",+ "primary": "主要操作背景",+ "primaryText": "主要操作文字",+ "secondary": "次要操作背景",+ "secondaryText": "次要操作文字",+ "destructive": "危险操作颜色",+ "ring": "聚焦轮廓",+ "shell": "外层框架",+ "page": "页面背景",+ "surface": "内容表面",+ "raised": "浮层背景",+ "hover": "悬停背景",+ "selected": "选中背景",+ "foreground": "正文颜色",+ "muted": "次要文字",+ "height": "按钮高度",+ "padding": "水平内边距",+ "rowHeight": "任务行高",+ "radius": "基础圆角",+ "caption": "辅助文字",+ "label": "信息标签",+ "body": "正文",+ "lineHeight": "正文行高",+ "title": "标题",+ "enterDuration": "进入时长",+ "exitDuration": "退出时长",+ "enterEasing": "进入曲线",+ "exitEasing": "退出曲线",+ "faint": "弱化图标",+ "surfaceText": "容器文字",+ "selectedText": "选中文字",+ "cardText": "卡片文字",+ "popoverText": "浮层文字",+ "brandText": "品牌色上的文字",+ "accent": "强调背景",+ "accentText": "强调文字",+ "mutedFill": "弱化背景",+ "success": "成功",+ "warning": "警告",+ "info": "信息",+ "border": "边框",+ "surfaceBorder": "容器边框",+ "inputBorder": "输入框边框",+ "sidebar": "侧栏背景",+ "sidebarText": "侧栏文字",+ "sidebarPrimary": "侧栏主要操作",+ "sidebarPrimaryText": "侧栏主要操作文字",+ "sidebarAccent": "侧栏悬停",+ "sidebarAccentText": "侧栏悬停文字",+ "sidebarBorder": "侧栏边框",+ "sidebarRing": "侧栏焦点环",+ "chart1": "图表 1",+ "chart2": "图表 2",+ "chart3": "图表 3",+ "chart4": "图表 4",+ "chart5": "图表 5"+ }+ },+ "color": {+ "feedback": {+ "invalid": "请输入 3 位或 6 位 HEX 色值。",+ "copied": "已复制色值",+ "copyFailed": "无法复制,请选择色值后手动复制。",+ "gamut": "超出 sRGB,HEX 为近似值。"+ },+ "roles": {+ "searchLabel": "搜索颜色角色",+ "searchPlaceholder": "搜索颜色或变量...",+ "title": "颜色角色",+ "empty": "没有找到匹配的颜色。",+ "current": "颜色角色:{{label}}"+ },+ "controls": {+ "picker": "颜色色板",+ "hex": "HEX 色值",+ "copy": "复制 HEX 色值",+ "restoreTitle": "恢复此颜色的原版值",+ "restore": "恢复原版颜色",+ "original": "原版",+ "current": "当前",+ "reset": "重置此颜色",+ "presets": "快捷色",+ "advanced": "精确调整",+ "close": "关闭颜色编辑器",+ "use": "使用颜色 {{color}}",+ "editor": "{{label}}颜色编辑器",+ "opacity": "不透明度"+ },+ "channels": {+ "lightness": "明度",+ "chroma": "色度",+ "hue": "色相"+ }+ },+ "gallery": {+ "surfaces": {+ "shell": "框架",+ "page": "页面",+ "surface": "表面",+ "raised": "浮层",+ "hover": "悬停",+ "selected": "选中"+ },+ "dialog": {+ "open": "打开弹窗",+ "title": "新建任务",+ "description": "填写任务标题。",+ "label": "弹窗任务标题",+ "placeholder": "输入任务标题..."+ },+ "sections": {+ "title": "基础组件",+ "surfaces": "表面与层次",+ "forms": "输入与选择",+ "status": "状态与标签",+ "typography": "文字层级",+ "elevation": "浮层与圆角",+ "feedback": "加载与空状态"+ },+ "actions": {+ "new": "新建",+ "outline": "边框按钮",+ "delete": "删除",+ "disabled": "不可用"+ },+ "form": {+ "title": "组件任务标题",+ "placeholder": "为任务起一个名字...",+ "notify": "通知负责人",+ "autopilot": "自动化",+ "disabled": "禁用输入框",+ "readonly": "只读状态",+ "attention": "需关注"+ },+ "type": {+ "heading": "小细节,构成好体验",+ "body": "Build with intention. 让智能体和团队一起工作。",+ "label": "任务属性 · 负责人 · 项目",+ "caption": "次要信息也应该清楚可读 · 2 分钟前",+ "cardTitle": "产品体验优化",+ "cardDescription": "内外层圆角的关系",+ "empty": "所有通知都已处理"+ }+ },+ "fixtures": {+ "issues": {+ "titles": [+ "统一任务列表与详情页的视觉层次",+ "优化命令菜单的键盘导航",+ "优化智能体运行中的反馈与状态展示",+ "检查中英文混排,以及很长的任务标题在窄窗口中的截断表现",+ "为菜单和弹窗建立一致的圆角规则",+ "完善深色模式下的选中与悬停状态",+ "让空状态保持清晰、轻量"+ ],+ "description": "## 目标\n\n让团队更容易找到当前最重要的信息。标题清晰、正文舒适,次要信息保持安静。\n\n## 验收标准\n\n- [x] 共享同一套语义颜色与圆角\n- [ ] 中英文混排与长标题表现自然\n- [ ] 选中状态在悬停时依然清晰\n\nBuild with intention. 让智能体和团队一起工作。"+ },+ "comments": {+ "first": "先检查列表的密度,再比较详情页中的文字层级。"+ }+ },+ "system": {+ "modules": {+ "foundations": "设计基础",+ "components": "基础组件",+ "patterns": "组合模式",+ "product": "业务组件",+ "layouts": "页面布局",+ "changes": "修改管理"+ },+ "descriptions": {+ "foundations": "颜色、字体、间距与视觉规则。",+ "components": "基础控件、变体与交互状态。",+ "patterns": "由组件组成的常用操作流程。",+ "product": "任务、团队与智能体界面。",+ "layouts": "页面结构与响应式布局。",+ "changes": "查看、保存与导出设计修改。"+ },+ "pages": {+ "colors": "颜色",+ "typography": "字体",+ "spacing": "间距",+ "radius": "圆角",+ "shadows": "阴影",+ "motion": "动效",+ "icons": "图标",+ "gallery": "组件总览",+ "button": "按钮",+ "input": "输入框",+ "select": "选择器",+ "checkbox": "复选框",+ "switch": "开关",+ "badge": "标签",+ "tabs": "选项卡",+ "tooltip": "提示框",+ "dialog": "对话框",+ "popover": "弹出层",+ "forms": "表单",+ "filters": "搜索与筛选",+ "properties": "属性编辑",+ "confirmation": "操作确认",+ "feedback": "加载、空状态与错误",+ "issueRow": "任务行",+ "statusPicker": "状态选择器",+ "assigneePicker": "负责人选择器",+ "comments": "评论",+ "agentRun": "智能体运行",+ "sidebar": "侧边栏",+ "list": "任务列表",+ "detail": "任务详情",+ "settings": "设置页",+ "split": "分栏布局",+ "review": "修改记录",+ "saved": "保存方案",+ "export": "CSS 导出",+ "impact": "影响范围",+ "source": "应用到源码"+ },+ "navigation": {+ "overview": "总览",+ "title": "设计系统",+ "expand": "展开或收起{{module}}"+ },+ "status": {+ "available": "已接入",+ "planned": "待补充",+ "progress": "{{ready}} / {{total}} 已接入"+ },+ "empty": {+ "message": "后续在这里补充示例与规范。",+ "back": "返回{{module}}",+ "notFound": "页面不存在"+ },+ "changes": {+ "reset": "重置全部",+ "return": "打开按钮工作台"+ }+ },+ "motion": {+ "actions": {+ "open": "打开",+ "close": "关闭",+ "replay": "重播"+ },+ "controls": {+ "title": "动效",+ "speed": "预览速度",+ "reduced": "系统已启用减少动态效果,动画已关闭。"+ },+ "easing": {+ "standard": "标准",+ "linear": "线性",+ "easeOut": "缓出",+ "easeIn": "缓入"+ }+ },+ "rules": {+ "content": {+ "title": "使用规则与代码",+ "download": "下载 Markdown"+ }+ },+ "dialog": {+ "controls": {+ "example": "示例",+ "form": "表单",+ "long": "长内容"+ },+ "actions": {+ "open": "打开弹窗",+ "cancel": "取消",+ "save": "保存"+ },+ "content": {+ "title": "编辑任务",+ "description": "更新任务标题。",+ "label": "标题",+ "defaultTitle": "检查界面",+ "item": "检查项 {{number}}:确认布局、内容和操作在窄屏下仍可访问。"+ },+ "states": {+ "open": "已打开",+ "closed": "已关闭",+ "saved": "已保存示例"+ }+ },+ "palette": {+ "page": {+ "title": "颜色",+ "search": "搜索颜色",+ "placeholder": "搜索名称或 token...",+ "empty": "没有匹配的颜色",+ "count": "{{count}} 个 token",+ "edit": "编辑{{label}}",+ "aliases": "别名",+ "selected": "当前颜色",+ "sample": "实际效果"+ },+ "groups": {+ "surfaces": "背景与容器",+ "content": "文字与图标",+ "actions": "操作",+ "feedback": "反馈",+ "borders": "边框与焦点",+ "charts": "图表",+ "sidebar": "侧栏"+ },+ "sample": {+ "title": "检查界面",+ "description": "分配前更新任务内容。",+ "create": "新建任务",+ "cancel": "取消"+ }+ },+ "colorUsage": {+ "sections": "颜色分区",+ "palette": "色板",+ "title": "用途与对比度",+ "mapping": "用途映射",+ "preview": "交互状态",+ "hint": "悬停、按住鼠标或用 Tab 聚焦。点击上方 token 可编辑。",+ "roles": {+ "action": "主要操作",+ "brand": "激活的筛选 / 开关",+ "tabs": "标签页 · 文字 / 指示线",+ "input": "输入框 · 文字 / 边框",+ "focus": "键盘焦点",+ "error": "输入错误"+ },+ "states": {+ "default": "默认",+ "hover": "悬停",+ "pressed": "按下",+ "focus": "聚焦",+ "selected": "选中",+ "invalid": "错误",+ "disabled": "禁用"+ },+ "unmeasured": "未测量",+ "pass": "通过",+ "fail": "未通过",+ "exempt": "豁免 · 已禁用",+ "text": "文字",+ "focusBorder": "焦点边框",+ "mainAction": "主要操作",+ "activeFilter": "分配给我",+ "overview": "概览",+ "activity": "动态",+ "overviewContent": "任务详情",+ "activityContent": "最近更新",+ "taskName": "任务名称",+ "rules": "规则与测量说明",+ "scope": "文字目标为 4.5:1;焦点边框与内外相邻背景的目标均为 3:1。基于过渡结束后的实际 sRGB 颜色计算,并合成透明度。禁用控件豁免,背景图片和整体透明度不测量。占位文字、标签页指示线和焦点环几何形态需单独检查;此处不代表完整的无障碍审查。",+ "policy": "主要操作保持中性色,品牌色标识激活的控件。标签页使用正文色和次要文字色;输入错误使用 destructive,焦点使用 ring。导出前检查明暗主题。修改 token 会影响所有使用它的组件。"+ }+}diff --git a/apps/ui-lab/src/main.tsx b/apps/ui-lab/src/main.tsxnew file mode 100644index 0000000000..1de75a983c--- /dev/null+++ b/apps/ui-lab/src/main.tsx@@ -0,0 +1,20 @@+import { lazy, StrictMode, Suspense } from "react";+import { createRoot } from "react-dom/client";+import "@fontsource-variable/inter";+import "./styles.css";+import { App } from "./app";+const Preview = lazy(() =>+ import("./preview").then((module) => ({ default: module.Preview })),+);++createRoot(document.getElementById("root")!).render(+ <StrictMode>+ {window.location.search === "?preview" ? (+ <Suspense fallback={null}>+ <Preview />+ </Suspense>+ ) : (+ <App />+ )}+ </StrictMode>,+);diff --git a/apps/ui-lab/src/number-field.tsx b/apps/ui-lab/src/number-field.tsxnew file mode 100644index 0000000000..ffc0cdcdef--- /dev/null+++ b/apps/ui-lab/src/number-field.tsx@@ -0,0 +1,217 @@+import { useTranslation } from "react-i18next";+import { useEffect, useId, useRef, useState } from "react";+import { RotateCcw } from "lucide-react";++export function NumberField({+ label,+ symbol,+ value,+ min,+ max,+ step,+ unit,+ modified,+ token,+ onPreview,+ onCommit,+ onCancel,+ onReset,+}: {+ label: string;+ symbol: string;+ value: number;+ min: number;+ max: number;+ step: number;+ unit: string;+ modified: boolean;+ token: string;+ onPreview: (value: number) => void;+ onCommit: (value: number) => void;+ onCancel: () => void;+ onReset: () => void;+}) {+ const { t } = useTranslation("uiLab");+ const id = useId();+ const input = useRef<HTMLInputElement>(null);+ const dirty = useRef(false);+ const drag = useRef<{+ x: number;+ value: number;+ last: number;+ moved: boolean;+ } | null>(null);+ const [text, setText] = useState(String(value));+ const [invalid, setInvalid] = useState(false);+ const clamp = (n: number) =>+ Number(Math.max(min, Math.min(max, n)).toFixed(3));+ useEffect(() => {+ dirty.current = false;+ setText(String(value));+ setInvalid(false);+ }, [value]);+ const commit = () => {+ if (!dirty.current) return;+ const n = Number(text.trim());+ if (!text.trim() || !Number.isFinite(n)) {+ setInvalid(true);+ return;+ }+ dirty.current = false;+ const next = clamp(n);+ setText(String(next));+ setInvalid(false);+ onCommit(next);+ };+ const cancelDrag = () => {+ if (drag.current) {+ drag.current = null;+ onCancel();+ }+ };+ return (+ <div className="property-number">+ <label htmlFor={id}>+ {label}+ {modified && (+ <span+ className="property-modified"+ aria-hidden="true"+ title={t(($) => $.inspector.changes.modified)}+ />+ )}+ </label>+ <div className="property-number-control" data-invalid={invalid}>+ <button+ type="button"+ className="property-scrub"+ aria-label={t(($) => $.inspector.actions.scrub, { label })}+ title={t(($) => $.inspector.actions.scrubHint, { token })}+ onPointerDown={(event) => {+ if (event.button !== 0) return;+ event.preventDefault();+ event.currentTarget.focus();+ event.currentTarget.setPointerCapture(event.pointerId);+ drag.current = {+ x: event.clientX,+ value,+ last: value,+ moved: false,+ };+ }}+ onPointerMove={(event) => {+ const current = drag.current;+ if (!current) return;+ const delta = event.clientX - current.x;+ if (Math.abs(delta) < 3 && !current.moved) return;+ current.moved = true;+ current.last = clamp(+ current.value ++ Math.round(delta / 2) *+ step *+ (event.shiftKey ? 10 : event.altKey ? 0.1 : 1),+ );+ onPreview(current.last);+ }}+ onPointerUp={(event) => {+ const current = drag.current;+ if (!current) return;+ drag.current = null;+ event.currentTarget.releasePointerCapture(event.pointerId);+ if (current.moved) onCommit(current.last);+ else {+ input.current?.focus();+ input.current?.select();+ }+ }}+ onPointerCancel={cancelDrag}+ onLostPointerCapture={cancelDrag}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ event.preventDefault();+ cancelDrag();+ }+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ input.current?.focus();+ input.current?.select();+ }+ }}+ >+ {symbol}+ </button>+ <input+ ref={input}+ id={id}+ role="spinbutton"+ aria-label={label}+ aria-valuetext={`${value}${unit}`}+ inputMode="decimal"+ aria-valuemin={min}+ aria-valuemax={max}+ aria-valuenow={value}+ aria-invalid={invalid}+ aria-describedby={invalid ? `${id}-error` : undefined}+ value={text}+ onFocus={(event) => event.target.select()}+ onChange={(event) => {+ dirty.current = true;+ setText(event.target.value);+ setInvalid(false);+ }}+ onBlur={commit}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ commit();+ event.currentTarget.select();+ }+ if (event.key === "Escape") {+ event.preventDefault();+ dirty.current = false;+ setText(String(value));+ setInvalid(false);+ onCancel();+ }+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {+ event.preventDefault();+ const next = clamp(+ value ++ (event.key === "ArrowUp" ? 1 : -1) *+ step *+ (event.shiftKey ? 10 : event.altKey ? 0.1 : 1),+ );+ dirty.current = false;+ setText(String(next));+ onCommit(next);+ }+ if (event.key === "Home" || event.key === "End") {+ event.preventDefault();+ const next = event.key === "Home" ? min : max;+ dirty.current = false;+ setText(String(next));+ onCommit(next);+ }+ }}+ />+ <span className="property-unit">{unit}</span>+ {modified && (+ <button+ type="button"+ className="property-reset"+ aria-label={t(($) => $.inspector.actions.reset, { label })}+ title={t(($) => $.inspector.changes.restore)}+ onClick={onReset}+ >+ <RotateCcw className="size-3" />+ </button>+ )}+ </div>+ {invalid && (+ <span className="property-error" id={`${id}-error`}>+ {t(($) => $.inspector.actions.invalid, { min, max })}+ </span>+ )}+ </div>+ );+}diff --git a/apps/ui-lab/src/preview.tsx b/apps/ui-lab/src/preview.tsxnew file mode 100644index 0000000000..6fa6438c41--- /dev/null+++ b/apps/ui-lab/src/preview.tsx@@ -0,0 +1,310 @@+import { LabI18nProvider } from "./lab-i18n";+import { useTranslation } from "react-i18next";+import { useEffect, useState, type ReactNode } from "react";+import { ArrowUpRight, Check, Inbox, Plus } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Badge } from "@multica/ui/components/ui/badge";+import { Input } from "@multica/ui/components/ui/input";+import { Checkbox } from "@multica/ui/components/ui/checkbox";+import { Switch } from "@multica/ui/components/ui/switch";+import { Avatar, AvatarFallback } from "@multica/ui/components/ui/avatar";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@multica/ui/components/ui/dialog";+import { StatusIcon } from "@multica/views/issues/visuals";+import { ColorsScene } from "./colors-scene";+import { DialogScene } from "./dialog-scene";+import { ButtonScene } from "./button-scene";+import { ProductPreview } from "./product-preview";+import { emptyDraft, previewCss } from "./tokens";+import { isPreviewSettings, type PreviewSettings } from "./protocol";++function Specimen({+ title,+ caption,+ children,+ wide = false,+}: {+ title: string;+ caption: string;+ children: ReactNode;+ wide?: boolean;+}) {+ return (+ <section className={`specimen ${wide ? "specimen-wide" : ""}`}>+ <header>+ <h2>{title}</h2>+ <span>{caption}</span>+ </header>+ <div className="specimen-body">{children}</div>+ </section>+ );+}+function Person({ name = "JZ" }: { name?: string }) {+ return (+ <Avatar size="sm">+ <AvatarFallback>{name}</AvatarFallback>+ </Avatar>+ );+}+function SurfaceSwatches() {+ const { t } = useTranslation("uiLab");+ const surfaces = [+ ["--app-shell", t(($) => $.gallery.surfaces.shell)],+ ["--page-canvas", t(($) => $.gallery.surfaces.page)],+ ["--surface", t(($) => $.gallery.surfaces.surface)],+ ["--surface-raised", t(($) => $.gallery.surfaces.raised)],+ ["--surface-hover", t(($) => $.gallery.surfaces.hover)],+ ["--surface-selected", t(($) => $.gallery.surfaces.selected)],+ ];+ return (+ <div className="surface-swatches">+ {surfaces.map(([key, name]) => (+ <div key={key}>+ <div style={{ background: `var(${key})` }}>Aa</div>+ <span>{name}</span>+ </div>+ ))}+ </div>+ );+}+function ExampleDialog() {+ const { t } = useTranslation("uiLab");+ return (+ <Dialog>+ <DialogTrigger render={<Button variant="outline" />}>+ {t(($) => $.gallery.dialog.open)}+ <ArrowUpRight />+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t(($) => $.gallery.dialog.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.gallery.dialog.description)}+ </DialogDescription>+ </DialogHeader>+ <Input+ aria-label={t(($) => $.gallery.dialog.label)}+ placeholder={t(($) => $.gallery.dialog.placeholder)}+ />+ </DialogContent>+ </Dialog>+ );+}+function ComponentsScene() {+ const { t } = useTranslation("uiLab");+ return (+ <div className="component-scene">+ <div className="scene-intro">+ <h1>{t(($) => $.gallery.sections.title)}</h1>+ </div>+ <div className="specimen-grid">+ <Specimen+ title={t(($) => $.gallery.sections.surfaces)}+ caption="SURFACES"+ wide+ >+ <SurfaceSwatches />+ </Specimen>+ <Specimen title={t(($) => $.button.page.title)} caption="BUTTON">+ <div className="flex flex-wrap gap-3">+ <Button>{t(($) => $.button.actions.create)}</Button>+ <Button variant="brand">+ <Plus />+ {t(($) => $.gallery.actions.new)}+ </Button>+ <Button variant="secondary">+ {t(($) => $.button.variants.secondary)}+ </Button>+ <Button variant="outline">+ {t(($) => $.gallery.actions.outline)}+ </Button>+ <Button variant="ghost">{t(($) => $.button.variants.ghost)}</Button>+ <Button variant="destructive">+ {t(($) => $.gallery.actions.delete)}+ </Button>+ <Button disabled>{t(($) => $.gallery.actions.disabled)}</Button>+ </div>+ </Specimen>+ <Specimen title={t(($) => $.gallery.sections.forms)} caption="FORM">+ <div className="grid gap-4">+ <Input+ aria-label={t(($) => $.gallery.form.title)}+ placeholder={t(($) => $.gallery.form.placeholder)}+ />+ <div className="flex items-center justify-between gap-4">+ <label className="flex items-center gap-2 text-body">+ <Checkbox defaultChecked />+ {t(($) => $.gallery.form.notify)}+ </label>+ <label className="flex items-center gap-2 text-body">+ {t(($) => $.gallery.form.autopilot)}+ <Switch defaultChecked />+ </label>+ </div>+ <Input+ aria-label={t(($) => $.gallery.form.disabled)}+ disabled+ placeholder={t(($) => $.gallery.form.readonly)}+ />+ </div>+ </Specimen>+ <Specimen title={t(($) => $.gallery.sections.status)} caption="STATUS">+ <div className="flex flex-wrap gap-x-5 gap-y-4">+ {[+ "backlog",+ "todo",+ "in_progress",+ "in_review",+ "done",+ "blocked",+ ].map((status) => (+ <span+ key={status}+ className="flex items-center gap-2 text-caption"+ >+ <StatusIcon status={status} />+ {status}+ </span>+ ))}+ </div>+ <div className="mt-5 flex flex-wrap gap-2">+ <Badge>Design</Badge>+ <Badge variant="secondary">Frontend</Badge>+ <Badge variant="outline">v0.4.0</Badge>+ <Badge variant="destructive">+ {t(($) => $.gallery.form.attention)}+ </Badge>+ </div>+ </Specimen>+ <Specimen+ title={t(($) => $.gallery.sections.typography)}+ caption="TYPOGRAPHY"+ >+ <div className="grid gap-2">+ <h3 className="text-title-lg font-semibold">+ {t(($) => $.gallery.type.heading)}+ </h3>+ <p className="text-body">{t(($) => $.gallery.type.body)}</p>+ <p className="text-label">{t(($) => $.gallery.type.label)}</p>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.gallery.type.caption)}+ </p>+ </div>+ </Specimen>+ <Specimen+ title={t(($) => $.gallery.sections.elevation)}+ caption="ELEVATION"+ >+ <div className="rounded-xl border border-surface-border bg-surface p-4 shadow-[var(--surface-shadow)]">+ <div className="mb-4 flex items-center gap-3">+ <Person />+ <div>+ <p className="text-body font-medium">+ {t(($) => $.gallery.type.cardTitle)}+ </p>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.gallery.type.cardDescription)}+ </p>+ </div>+ </div>+ <ExampleDialog />+ </div>+ </Specimen>+ <Specimen+ title={t(($) => $.gallery.sections.feedback)}+ caption="FEEDBACK"+ >+ <div className="flex items-center gap-3">+ <Skeleton className="size-8 rounded-full" />+ <div className="flex-1 space-y-2">+ <Skeleton className="h-3 w-3/5" />+ <Skeleton className="h-3 w-2/5" />+ </div>+ </div>+ <div className="mt-5 flex items-center gap-3 text-muted-foreground">+ <Inbox className="size-5" />+ <span className="text-body">{t(($) => $.gallery.type.empty)}</span>+ <Check className="ml-auto size-4 text-success" />+ </div>+ </Specimen>+ </div>+ </div>+ );+}+export function Preview() {+ const [settings, setSettings] = useState<PreviewSettings>({+ type: "multica-ui-lab:preview",+ draft: emptyDraft(),+ theme: "light",+ scene: "components",+ buttonScale: "default",+ locale: "en",+ playbackSpeed: 1,+ selectedColor: "--brand",+ });+ useEffect(() => {+ const receive = (event: MessageEvent<unknown>) => {+ if (+ event.origin === location.origin &&+ event.source === window.parent &&+ isPreviewSettings(event.data)+ )+ setSettings(event.data);+ };+ window.addEventListener("message", receive);+ window.parent.postMessage(+ { type: "multica-ui-lab:ready" },+ location.origin,+ );+ return () => window.removeEventListener("message", receive);+ }, []);+ useEffect(() => {+ document.documentElement.classList.toggle(+ "dark",+ settings.theme === "dark",+ );+ }, [settings.theme]);+ useEffect(() => {+ window.scrollTo(0, 0);+ }, [settings.scene]);+ return (+ <LabI18nProvider locale={settings.locale}>+ <div className="preview-root">+ <style>{previewCss(settings.draft)}</style>+ {settings.scene === "colors" ? (+ <ColorsScene+ draft={settings.draft}+ theme={settings.theme}+ selected={settings.selectedColor}+ />+ ) : settings.scene === "components" ? (+ <ComponentsScene />+ ) : settings.scene === "button" ? (+ <ButtonScene scale={settings.buttonScale} draft={settings.draft} />+ ) : settings.scene === "dialog" || settings.scene === "motion" ? (+ <DialogScene+ key={settings.scene}+ motion={settings.scene === "motion"}+ draft={settings.draft}+ speed={settings.playbackSpeed}+ />+ ) : settings.scene === "list" ? (+ <ProductPreview key="list" scene="list" locale={settings.locale} />+ ) : (+ <ProductPreview+ key="detail"+ scene="detail"+ locale={settings.locale}+ />+ )}+ </div>+ </LabI18nProvider>+ );+}diff --git a/apps/ui-lab/src/product-fixtures.test.ts b/apps/ui-lab/src/product-fixtures.test.tsnew file mode 100644index 0000000000..10bca23b48--- /dev/null+++ b/apps/ui-lab/src/product-fixtures.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { createFixtureApi, issues } from "./product-fixtures";+import type { LabLocale } from "./locale";+import type { IssueTableQuerySpec } from "@multica/core/types";++const query: IssueTableQuerySpec = {+ scope: { kind: "workspace" },+ filters: {},+ sort: { field: "position", direction: "asc" },+};+afterEach(() => vi.restoreAllMocks());+describe("the UI Lab data boundary", () => {+ it("isolates edits between preview instances", async () => {+ const modified = createFixtureApi();+ const original = createFixtureApi();+ await modified.updateIssue(issues[0]!.id, { title: "Edited locally" });+ expect((await modified.getIssue(issues[0]!.id)).title).toBe(+ "Edited locally",+ );+ expect((await original.getIssue(issues[0]!.id)).title).toBe(+ issues[0]!.title,+ );+ });+ it("serves the status branches requested by the production list", async () => {+ const api = createFixtureApi();+ const response = await api.listIssueTableRows({+ query,+ group: { kind: "status" },+ group_key: "status:todo",+ hierarchy: { enabled: false },+ parent_id: null,+ });+ expect(response.rows.length).toBeGreaterThan(0);+ expect(response.rows.every((row) => row.issue.status === "todo")).toBe(+ true,+ );+ expect(response.branch_total).toBe(response.rows.length);+ });+ it("keeps comments local and available through the real timeline query", async () => {+ const api = createFixtureApi();+ const other = createFixtureApi();+ const comment = await api.createComment(issues[0]!.id, "Local comment");+ expect(+ (await api.listTimeline(issues[0]!.id)).some(+ (row) => row.id === comment.id,+ ),+ ).toBe(true);+ expect(+ (await other.listTimeline(issues[0]!.id)).some(+ (row) => row.id === comment.id,+ ),+ ).toBe(false);+ });+ it("translates sample content without replacing local edits or comments", async () => {+ let locale: LabLocale = "en";+ const api = createFixtureApi(() => locale);+ const first = issues[0]!.id;+ const second = issues[1]!.id;+ await api.updateIssue(first, { title: "Custom title", status: "done" });+ const comment = await api.createComment(first, "My comment");+ locale = "zh";+ expect((await api.getIssue(first)).title).toBe("Custom title");+ expect((await api.getIssue(first)).status).toBe("done");+ expect((await api.getIssue(second)).title).toBe("优化命令菜单的键盘导航");+ expect((await api.getIssue(first)).description).toContain("## 目标");+ expect(+ (await api.listComments(first)).find((row) => row.id === comment.id)+ ?.content,+ ).toBe("My comment");+ const response = await api.listIssueTableRows({+ query: { ...query, search: "键盘导航" },+ group_key: null,+ group: { kind: "status" },+ hierarchy: { enabled: false },+ parent_id: null,+ });+ expect(response.rows.map((row) => row.issue.id)).toEqual([second]);+ locale = "en";+ expect((await api.getIssue(second)).title).toBe(issues[1]!.title);+ expect((await api.getIssue(first)).title).toBe("Custom title");+ });+ it("rejects unconfigured operations instead of reaching the network", async () => {+ const network = vi.spyOn(globalThis, "fetch");+ vi.spyOn(console, "warn").mockImplementation(() => {});+ await expect(createFixtureApi().listSkills()).rejects.toThrow("UI Lab");+ expect(network).not.toHaveBeenCalled();+ });+});diff --git a/apps/ui-lab/src/product-fixtures.ts b/apps/ui-lab/src/product-fixtures.tsnew file mode 100644index 0000000000..666b9ed050--- /dev/null+++ b/apps/ui-lab/src/product-fixtures.ts@@ -0,0 +1,356 @@+import en from "./locales/en.json";+import zh from "./locales/zh.json";+import { productLocale, type LabLocale } from "./locale";+import type {+ Issue,+ User,+ Workspace,+ MemberWithUser,+ StorageAdapter,+ IssueTableQuerySpec,+ Comment,+} from "@multica/core/types";+import { STATUS_ORDER } from "@multica/core/issues/config";+import { ApiClient } from "@multica/core/api";++const time = "2026-09-14T06:00:00Z";+export const workspace: Workspace = {+ id: "10000000-0000-4000-8000-000000000001",+ slug: "ui-lab",+ name: "Multica",+ description: "UI Lab fixture workspace",+ context: null,+ settings: {},+ repos: [],+ issue_prefix: "MUL",+ avatar_url: null,+ created_at: time,+ updated_at: time,+};+export const user: User = {+ id: "10000000-0000-4000-8000-000000000002",+ name: "Jiayuan",+ email: "[email protected]",+ avatar_url: null,+ onboarded_at: time,+ onboarding_questionnaire: {},+ starter_content_state: "imported",+ language: "en",+ profile_description: "",+ timezone: "Asia/Shanghai",+ created_at: time,+ updated_at: time,+};+export const members: MemberWithUser[] = [+ {+ id: "10000000-0000-4000-8000-000000000003",+ workspace_id: workspace.id,+ user_id: user.id,+ role: "owner",+ created_at: time,+ name: user.name,+ email: user.email,+ avatar_url: null,+ },+];+const titles = en.fixtures.issues.titles;+export const issues: Issue[] = titles.map((title, index) => ({+ id: `20000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,+ workspace_id: workspace.id,+ number: 241 + index,+ identifier: `MUL-${241 + index}`,+ title,+ description: en.fixtures.issues.description,+ status: index < 3 ? "in_progress" : index < 6 ? "todo" : "done",+ priority: index % 2 ? "medium" : "high",+ assignee_type: "member",+ assignee_id: user.id,+ creator_type: "member",+ creator_id: user.id,+ parent_issue_id: null,+ project_id: null,+ position: index * 1000,+ stage: null,+ start_date: null,+ due_date: null,+ metadata: {},+ properties: {},+ labels: [],+ created_at: time,+ updated_at: time,+ revision: 1,+}));+export const memoryStorage = (): StorageAdapter => {+ const values = new Map<string, string>();+ return {+ getItem: (key) => values.get(key) ?? null,+ setItem: (key, value) => {+ values.set(key, value);+ },+ removeItem: (key) => {+ values.delete(key);+ },+ keys: () => [...values.keys()],+ };+};++// Only data is substituted. Views, hooks, stores and mutations are the production modules.+// There is deliberately no fallback to ApiClient's network implementation.+export function createFixtureApi(getLocale: () => LabLocale = () => "en") {+ const messages = () => (getLocale() === "zh" ? zh.fixtures : en.fixtures);+ // Translate untouched fixtures at the data boundary; preserve user edits.+ const localizeIssue = (issue: Issue): Issue => {+ const index = issues.findIndex((original) => original.id === issue.id);+ const original = issues[index];+ return {+ ...issue,+ title:+ original && issue.title === original.title+ ? messages().issues.titles[index]!+ : issue.title,+ description:+ original && issue.description === original.description+ ? messages().issues.description+ : issue.description,+ };+ };+ const localizeComment = (comment: Comment): Comment => ({+ ...comment,+ content:+ comment.id === "30000000-0000-4000-8000-000000000001"+ ? messages().comments.first+ : comment.content,+ });+ let rows = structuredClone(issues);+ const comments: Comment[] = [+ {+ id: "30000000-0000-4000-8000-000000000001",+ issue_id: issues[0]!.id,+ author_type: "member",+ author_id: user.id,+ content: en.fixtures.comments.first,+ type: "comment",+ parent_id: null,+ reactions: [],+ attachments: [],+ created_at: time,+ updated_at: time,+ revision: 1,+ resolved_at: null,+ resolved_by_type: null,+ resolved_by_id: null,+ },+ ];+ const queryRows = (query: IssueTableQuerySpec) =>+ rows.filter((issue) => {+ const filters = query.filters;+ return (+ (!filters.statuses?.length ||+ filters.statuses.includes(issue.status)) &&+ (!filters.priorities?.length ||+ filters.priorities.includes(issue.priority)) &&+ (!query.search ||+ `${issue.identifier} ${localizeIssue(issue).title}`+ .toLowerCase()+ .includes(query.search.toLowerCase())) &&+ (!filters.working_issue_ids ||+ filters.working_issue_ids.includes(issue.id)) &&+ (!("assignee_types" in query.scope) ||+ !query.scope.assignee_types?.length ||+ query.scope.assignee_types.includes(issue.assignee_type!))+ );+ });+ const handlers: Partial<ApiClient> = {+ getBaseUrl: () => "/ui-lab-fixtures",+ getMe: async () => ({ ...user, language: productLocale(getLocale()) }),+ listWorkspaces: async () => [workspace],+ getWorkspace: async () => workspace,+ listMembers: async () => members,+ listSquads: async () => [],+ listAgents: async () => [],+ listRuntimes: async () => [],+ listProjects: async () => ({ projects: [], total: 0 }),+ listIssues: async (params) => {+ const filtered = rows.filter(+ (issue) =>+ (!params?.statuses?.length ||+ params.statuses.includes(issue.status)) &&+ (!params?.ids || params.ids.includes(issue.id)) &&+ (!params?.priorities?.length ||+ params.priorities.includes(issue.priority)),+ );+ return {+ issues: filtered+ .slice(+ params?.offset ?? 0,+ (params?.offset ?? 0) + (params?.limit ?? 100),+ )+ .map(localizeIssue),+ total: filtered.length,+ };+ },+ listIssueTableRows: async (request) => {+ const matched = queryRows(request.query);+ const group = request.group_key?.replace(/^status(?:_category)?:/, "");+ const branch = request.parent_id+ ? []+ : matched.filter((issue) => !group || issue.status === group);+ return {+ query_fingerprint: JSON.stringify(request.query),+ group_key: request.group_key,+ parent_id: request.parent_id,+ total: matched.length,+ branch_total: branch.length,+ rows: branch.map((issue) => ({+ issue: localizeIssue(issue),+ direct_child_count: 0,+ })),+ next_cursor: null,+ };+ },+ listIssueTableGroups: async (request) => ({+ query_fingerprint: JSON.stringify(request.query),+ total: queryRows(request.query).length,+ groups: STATUS_ORDER.map((status) => ({+ key: `status:${status}`,+ value: { kind: "status", status },+ count: queryRows(request.query).filter(+ (issue) => issue.status === status,+ ).length,+ })),+ next_cursor: null,+ }),+ listIssueTableFacets: async (request) => {+ const matched = queryRows(request.query);+ return {+ query_fingerprint: JSON.stringify(request.query),+ total: matched.length,+ facets: request.facets.map((facet) => ({+ ...facet,+ values:+ facet.kind === "status"+ ? STATUS_ORDER.map((key) => ({+ key,+ count: matched.filter((issue) => issue.status === key).length,+ }))+ : [],+ })),+ };+ },+ getIssue: async (id) => {+ const issue = rows.find((row) => row.id === id || row.identifier === id);+ if (!issue) throw new Error(`Unknown fixture issue: ${id}`);+ return structuredClone(localizeIssue(issue));+ },+ updateIssue: async (id, updates) => {+ const current = rows.find((row) => row.id === id);+ if (!current) throw new Error("Unknown fixture issue");+ const next = {+ ...current,+ ...updates,+ revision: (current.revision ?? 0) + 1,+ };+ rows = rows.map((row) => (row.id === id ? next : row));+ return structuredClone(localizeIssue(next));+ },+ listChildIssues: async () => ({ issues: [] }),+ listChildrenByParents: async () => ({ issues: [] }),+ getChildIssueProgress: async () => ({ progress: [] }),+ listComments: async (id) =>+ comments+ .filter((comment) => comment.issue_id === id)+ .map(localizeComment),+ listTimeline: async (id) =>+ comments+ .filter((comment) => comment.issue_id === id)+ .map((comment) => ({+ ...localizeComment(comment),+ type: "comment",+ actor_type: comment.author_type,+ actor_id: comment.author_id,+ actor_name: user.name,+ })),+ previewCommentTriggers: async () => ({ agents: [] }),+ createComment: async (issueId, content, _type, parentId) => {+ const comment: Comment = {+ id: crypto.randomUUID(),+ issue_id: issueId,+ author_type: "member",+ author_id: user.id,+ content,+ type: "comment",+ parent_id: parentId ?? null,+ reactions: [],+ attachments: [],+ created_at: time,+ updated_at: time,+ revision: 1,+ resolved_at: null,+ resolved_by_type: null,+ resolved_by_id: null,+ };+ comments.push(comment);+ return comment;+ },+ listTasksByIssue: async () => [],+ getActiveTasksForIssue: async () => ({ tasks: [] }),+ getAgentTaskSnapshot: async () => [],+ getWorkspaceWorkingAgents: async () => [],+ listGitHubInstallations: async () => ({+ installations: [],+ configured: false,+ }),+ listIssuePullRequests: async () => ({ pull_requests: [] }),+ listAttachments: async () => [],+ listIssueSubscribers: async () => [],+ getAssigneeFrequency: async () => [],+ listLabelsForIssue: async () => ({ labels: [] }),+ listLabels: async () => ({ labels: [], total: 0 }),+ listProperties: async () => ({ properties: [], total: 0 }),+ listQuickActions: async () => ({ quick_actions: [] }),+ listIssueStatuses: async () => ({+ statuses: STATUS_ORDER.map((key, index) => ({+ id: key,+ workspace_id: workspace.id,+ key,+ name: key,+ description: "",+ category: key,+ color: "#777777",+ is_system: true,+ position: index,+ archived_at: null,+ created_at: time,+ updated_at: time,+ })),+ categories: STATUS_ORDER,+ total: STATUS_ORDER.length,+ }),+ listPins: async () => [],+ listMyInvitations: async () => [],+ getInboxUnreadSummary: async () => [],+ getUnreadInboxCount: async () => ({ count: 0 }),+ listChatSessions: async () => [],+ listIssueViews: async () => [],+ getIssueViewPreference: async (params) => ({+ ...params,+ prefs: { hidden: [], order: [] },+ updated_at: time,+ }),+ listPluginInstallations: async () => ({ plugins: [] }),+ getWorkspaceSubscriptionSummary: async () => null,+ getIssueLimitUsage: async () => null,+ };+ return new Proxy(new ApiClient("/ui-lab-fixtures"), {+ get(_target, property: string) {+ const handler = handlers[property as keyof ApiClient];+ if (handler !== undefined) return handler;+ if (property === "then") return undefined;+ return () => {+ const message = `UI Lab has no fixture for this operation: ${property}`;+ console.warn(message);+ return Promise.reject(new Error(message));+ };+ },+ });+}diff --git a/apps/ui-lab/src/product-preview.tsx b/apps/ui-lab/src/product-preview.tsxnew file mode 100644index 0000000000..803cc6dba8--- /dev/null+++ b/apps/ui-lab/src/product-preview.tsx@@ -0,0 +1,123 @@+import { productLocale, type LabLocale } from "./locale";+import { useTranslation } from "react-i18next";+import { useEffect, useMemo, useState } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createAuthStore, registerAuthStore } from "@multica/core/auth";+import { createChatStore, registerChatStore } from "@multica/core/chat";+import { setApiInstance } from "@multica/core/api";+import { WSProvider } from "@multica/core/realtime";+import { I18nProvider } from "@multica/core/i18n/react";+import { WorkspaceSlugProvider } from "@multica/core/paths";+import { workspaceKeys } from "@multica/core/workspace/queries";+import { setCurrentWorkspace } from "@multica/core/platform";+import { getIssueSurfaceViewStore } from "@multica/core/issues/stores/surface-view-store";+import { AppSidebar } from "@multica/views/layout";+import { IssueDetail, IssuesPage } from "@multica/views/issues/components";+import {+ NavigationProvider,+ type NavigationAdapter,+} from "@multica/views/navigation";+import { RESOURCES } from "@multica/views/locales";+import {+ SidebarInset,+ SidebarProvider,+} from "@multica/ui/components/ui/sidebar";+import { TooltipProvider } from "@multica/ui/components/ui/tooltip";+import { Toaster, toast } from "sonner";+import {+ createFixtureApi,+ issues,+ memoryStorage,+ user,+ workspace,+} from "./product-fixtures";++let fixtureLocale: LabLocale = "en";+const api = createFixtureApi(() => fixtureLocale);+setApiInstance(api);+const storage = memoryStorage();+const auth = createAuthStore({ api, storage });+auth.setState({ user, isLoading: false, status: "authenticated" });+registerAuthStore(auth);+registerChatStore(createChatStore({ storage }));+setCurrentWorkspace(workspace.slug, workspace.id);+getIssueSurfaceViewStore("workspace:all").setState({ viewMode: "list" });+const resources = { en: RESOURCES.en, "zh-Hans": RESOURCES["zh-Hans"] };++export function ProductPreview({+ scene,+ locale,+}: {+ scene: "list" | "detail";+ locale: LabLocale;+}) {+ const { t } = useTranslation("uiLab");+ const [client] = useState(() => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ staleTime: Infinity,+ refetchOnWindowFocus: false,+ },+ mutations: { retry: false },+ },+ });+ queryClient.setQueryData(workspaceKeys.list(), [workspace]);+ return queryClient;+ });+ useEffect(() => {+ fixtureLocale = locale;+ auth.setState({ user: { ...user, language: productLocale(locale) } });+ // Discard in-flight results from the previous language before refetching.+ void client.cancelQueries().then(() => client.invalidateQueries());+ }, [client, locale]);+ const [path, setPath] = useState(+ scene === "detail" ? `/ui-lab/issues/${issues[0]!.id}` : "/ui-lab/issues",+ );+ const navigation = useMemo<NavigationAdapter>(() => {+ const navigate = (next: string) => {+ if (/^\/ui-lab\/issues(?:\/[^/]+)?$/.test(next)) setPath(next);+ else toast.info(t(($) => $.lab.preview.unavailable));+ };+ return {+ pathname: path,+ searchParams: new URLSearchParams(),+ hash: "",+ push: navigate,+ replace: navigate,+ back: () => setPath("/ui-lab/issues"),+ getShareableUrl: (value) => `${location.origin}${value}`,+ };+ }, [path, t]);+ const issueId = path.split("/")[3];+ return (+ <QueryClientProvider client={client}>+ <WSProvider+ wsUrl="ws://127.0.0.1/ui-lab-disabled"+ authStore={auth}+ storage={storage}+ >+ <I18nProvider locale={productLocale(locale)} resources={resources}>+ <WorkspaceSlugProvider slug={workspace.slug}>+ <NavigationProvider value={navigation}>+ <TooltipProvider>+ <SidebarProvider className="h-svh bg-app-shell">+ <AppSidebar />+ <SidebarInset className="relative overflow-hidden">+ {issueId ? (+ <IssueDetail issueId={issueId} />+ ) : (+ <IssuesPage />+ )}+ </SidebarInset>+ </SidebarProvider>+ <Toaster />+ </TooltipProvider>+ </NavigationProvider>+ </WorkspaceSlugProvider>+ </I18nProvider>+ </WSProvider>+ </QueryClientProvider>+ );+}diff --git a/apps/ui-lab/src/protocol.test.ts b/apps/ui-lab/src/protocol.test.tsnew file mode 100644index 0000000000..8f4c365231--- /dev/null+++ b/apps/ui-lab/src/protocol.test.ts@@ -0,0 +1,38 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { emptyDraft, numericTokenValue } from "./tokens";+import { isDialogCommand, isPreviewSettings } from "./protocol";++describe("motion preview boundary", () => {+ it("accepts only supported playback speeds and commands", () => {+ const message = {+ type: "multica-ui-lab:preview",+ selectedColor: "--brand",+ draft: emptyDraft(),+ theme: "light",+ scene: "motion",+ buttonScale: "default",+ locale: "en",+ };+ for (const playbackSpeed of [1, 0.5, 0.25])+ expect(isPreviewSettings({ ...message, playbackSpeed })).toBe(true);+ for (const playbackSpeed of [0, -1, 2, Infinity, "1", null, undefined])+ expect(isPreviewSettings({ ...message, playbackSpeed })).toBe(false);+ for (const action of ["open", "close", "replay"])+ expect(isDialogCommand({ type: "multica-ui-lab:dialog", action })).toBe(+ true,+ );+ for (const value of [+ null,+ {},+ { type: "multica-ui-lab:dialog", action: "execute" },+ { type: "other", action: "open" },+ ])+ expect(isDialogCommand(value)).toBe(false);+ });+ it("formats scrubbed numeric values with their declared units", () => {+ expect(numericTokenValue("--dialog-enter-duration", 320)).toBe("320ms");+ expect(numericTokenValue("--button-height-default", 32)).toBe("32px");+ expect(() => numericTokenValue("--unknown", 32)).toThrow();+ });+});diff --git a/apps/ui-lab/src/protocol.ts b/apps/ui-lab/src/protocol.tsnew file mode 100644index 0000000000..efc44050a8--- /dev/null+++ b/apps/ui-lab/src/protocol.ts@@ -0,0 +1,83 @@+import { isLabLocale, type LabLocale } from "./locale";+import {+ isDraft,+ isColorToken,+ type ColorToken,+ buttonScales,+ type ButtonScale,+ type Draft,+ type Theme,+} from "./tokens";+export const scenes = [+ { id: "colors", label: "colors" },+ { id: "dialog", label: "dialog" },+ { id: "motion", label: "motion" },+ {+ id: "components",+ label: "components",+ },+ {+ id: "button",+ label: "button",+ },+ {+ id: "list",+ label: "list",+ },+ {+ id: "detail",+ label: "detail",+ },+] as const;+export type Scene = (typeof scenes)[number]["id"];+export type PreviewSettings = {+ type: "multica-ui-lab:preview";+ draft: Draft;+ theme: Theme;+ scene: Scene;+ buttonScale: ButtonScale;+ locale: LabLocale;+ playbackSpeed: number;+ selectedColor: ColorToken;+};+export function isPreviewSettings(value: unknown): value is PreviewSettings {+ if (!value || typeof value !== "object") return false;+ const data = value as Record<string, unknown>;+ return (+ data.type === "multica-ui-lab:preview" &&+ (data.theme === "light" || data.theme === "dark") &&+ scenes.some((scene) => scene.id === data.scene) &&+ buttonScales.some((scale) => scale === data.buttonScale) &&+ isLabLocale(data.locale) &&+ isColorToken(data.selectedColor) &&+ playbackSpeeds.some((speed) => speed === data.playbackSpeed) &&+ isDraft(data.draft)+ );+}++export const playbackSpeeds = [1, 0.5, 0.25] as const;+export const dialogActions = ["open", "close", "replay"] as const;+export type DialogCommand = {+ type: "multica-ui-lab:dialog";+ action: (typeof dialogActions)[number];+};+export function isDialogCommand(value: unknown): value is DialogCommand {+ if (!value || typeof value !== "object") return false;+ const data = value as Record<string, unknown>;+ return (+ data.type === "multica-ui-lab:dialog" &&+ dialogActions.some((action) => action === data.action)+ );+}++export type ColorSelection = {+ type: "multica-ui-lab:color-select";+ token: ColorToken;+};+export function isColorSelection(value: unknown): value is ColorSelection {+ if (!value || typeof value !== "object") return false;+ const data = value as Record<string, unknown>;+ return (+ data.type === "multica-ui-lab:color-select" && isColorToken(data.token)+ );+}diff --git a/apps/ui-lab/src/storage.ts b/apps/ui-lab/src/storage.tsnew file mode 100644index 0000000000..f1b91a7de9--- /dev/null+++ b/apps/ui-lab/src/storage.ts@@ -0,0 +1,50 @@+import { emptyDraft, isDraft, sourceRevision, type Draft } from "./tokens";++export const STORAGE_KEY = "multica-ui-lab:v1";+export type SavedDesign = {+ id: string;+ name: string;+ draft: Draft;+ savedAt: string;+};+export type LabSession = { draft: Draft; designs: SavedDesign[] };+const freshSession = (): LabSession => ({ draft: emptyDraft(), designs: [] });+export function decodeSession(raw: string | null): LabSession {+ if (!raw) return freshSession();+ try {+ const data = JSON.parse(raw);+ if (+ data.version !== 1 ||+ !isDraft(data.draft) ||+ !Array.isArray(data.designs)+ )+ return freshSession();+ const designs = data.designs+ .filter((item: unknown): item is SavedDesign => {+ if (!item || typeof item !== "object") return false;+ const value = item as Record<string, unknown>;+ return (+ typeof value.id === "string" &&+ typeof value.name === "string" &&+ value.name.length > 0 &&+ value.name.length <= 60 &&+ typeof value.savedAt === "string" &&+ isDraft(value.draft)+ );+ })+ .slice(0, 20);+ return { draft: data.draft, designs };+ } catch {+ return freshSession();+ }+}+export function encodeSession(session: LabSession): string {+ return JSON.stringify({ version: 1, sourceRevision, ...session });+}+export function loadSession(): LabSession {+ try {+ return decodeSession(localStorage.getItem(STORAGE_KEY));+ } catch {+ return freshSession();+ }+}diff --git a/apps/ui-lab/src/styles.css b/apps/ui-lab/src/styles.cssnew file mode 100644index 0000000000..7fa94f6209--- /dev/null+++ b/apps/ui-lab/src/styles.css@@ -0,0 +1,2264 @@+@import "tailwindcss";+@import "tw-animate-css";+@import "shadcn/tailwind.css";+@import "@multica/ui/styles/tokens.css";+@import "@multica/ui/styles/base.css";+@source "../../../packages/ui";+@source "../../../packages/views";+@source "../../../packages/core";+@custom-variant dark (&:is(.dark *));++:root {+ --font-sans:+ "Inter Variable", Inter, -apple-system, BlinkMacSystemFont, "PingFang SC",+ "Microsoft YaHei", sans-serif;+ --font-mono: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-family: var(--font-sans);+ font-synthesis: none;+ color: var(--foreground);+ background: var(--background);+}+@layer base {+ * {+ box-sizing: border-box;+ border-color: var(--border);+ }+}+body {+ margin: 0;+}++.lab-shell button:not(:disabled),+.lab-shell select {+ cursor: pointer;+}+.lab-shell button:focus-visible,+.lab-shell a:focus-visible,+.lab-shell select:focus-visible,+.lab-shell input:focus-visible,+.lab-shell pre:focus-visible {+ outline: 2px solid var(--brand);+ outline-offset: 3px;+}+.lab-shell {+ display: grid;+ grid-template-rows: 64px minmax(0, 1fr);+ height: 100dvh;+ min-height: 540px;+ font-size: var(--text-body);+}+.lab-header {+ grid-column: 1 / -1;+ display: flex;+ align-items: center;+ gap: 20px;+ padding: 0 22px;+ border-bottom: 1px solid var(--border);+ background: var(--surface);+}+.lab-brand {+ display: flex;+ align-items: center;+ gap: 10px;+ text-decoration: none;+ color: var(--foreground);+ white-space: nowrap;+}+.lab-brand strong {+ font-size: var(--text-title);+ letter-spacing: -0.6px;+}+.lab-brand > span:last-child {+ font-size: var(--text-label);+ color: var(--muted-foreground);+}+.logo-mark {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 27px;+ height: 27px;+ background: var(--primary);+ color: var(--primary-foreground);+ border-radius: var(--radius-md);+}+.logo-mark svg {+ width: 17px;+ height: 17px;+}+.brand-divider {+ height: 18px;+ width: 1px;+ background: var(--border);+ margin: 0 2px;+}+.internal-label {+ border: 1px solid var(--border);+ border-radius: var(--radius-md);+ padding: 3px 6px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}+.header-actions {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-left: auto;+}+.language-toggle {+ display: flex;+ align-items: center;+ gap: 2px;+ flex-shrink: 0;+}+.header-separator {+ width: 1px;+ height: 18px;+ background: var(--border);+ margin: 0 5px;+}+.mobile-nav-toggle {+ display: none;+}+.lab-nav {+ display: flex;+ flex-direction: column;+ padding: 27px 12px 18px;+ background: var(--surface);+ border-right: 1px solid var(--border);+ min-height: 0;+ overflow: auto;+}+.nav-heading {+ display: flex;+ justify-content: space-between;+ padding: 0 11px;+ margin-bottom: 12px;+ font-size: var(--text-micro);+ color: var(--muted-foreground);+}+.nav-heading > span {+ font-family: var(--font-mono);+ color: var(--faint-foreground);+}+.lab-nav nav {+ display: grid;+ gap: 4px;+}+.lab-nav nav button {+ display: flex;+ align-items: center;+ width: 100%;+ gap: 10px;+ padding: 10px;+ border-radius: var(--radius-md);+ color: var(--muted-foreground);+ font-size: var(--text-label);+}+.lab-nav nav button svg {+ width: 15px;+ height: 15px;+}+.lab-nav nav button:hover {+ background: var(--surface-hover);+}+.lab-nav nav button[aria-current] {+ background: var(--surface-selected);+ color: var(--foreground);+ font-weight: 600;+}+.saved-heading {+ margin-top: 36px;+}+.nav-empty {+ padding: 0 11px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+ line-height: 1.8;+}+.saved-design {+ display: flex;+ align-items: center;+ gap: 3px;+}+.saved-design > button:first-child {+ min-width: 0;+ display: flex;+ align-items: center;+ flex: 1;+ gap: 8px;+ padding: 9px;+ font-size: var(--text-caption);+}+.saved-design > button:first-child > span:last-child {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.saved-design:hover {+ background: var(--surface-hover);+ border-radius: var(--radius-md);+}+.design-swatch {+ width: 12px;+ height: 12px;+ border: 1px solid var(--border);+ border-radius: 50%;+ flex-shrink: 0;+}+.status-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--success);+ display: inline-block;+ flex-shrink: 0;+}+.lab-main {+ display: flex;+ flex-direction: column;+ min-width: 0;+ min-height: 0;+ background: var(--app-shell);+}+.workspace-heading {+ padding: 25px 28px 22px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+}+.workspace-breadcrumb {+ display: flex;+ align-items: center;+ gap: 7px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ margin-bottom: 13px;+}+.workspace-breadcrumb svg {+ width: 11px;+ height: 11px;+}+.workspace-heading h1 {+ font-size: var(--text-title-lg);+ font-weight: 600;+ letter-spacing: -0.5px;+}+.workspace-heading p {+ color: var(--muted-foreground);+ font-size: var(--text-caption);+ margin-top: 7px;+}+.theme-toggle {+ display: flex;+ gap: 3px;+ background: var(--surface);+ border: 1px solid var(--border);+ padding: 3px;+ border-radius: var(--radius-lg);+}+.canvas-toolbar {+ padding: 0 28px 10px;+ display: flex;+ gap: 8px;+ align-items: center;+}+.canvas-caption {+ display: flex;+ align-items: center;+ gap: 7px;+ font-size: var(--text-caption);+ color: var(--muted-foreground);+}+.preview-canvas {+ flex: 1;+ min-height: 0;+ overflow: auto;+ padding: 0 28px 20px;+ display: flex;+ gap: 16px;+}+.preview-frame {+ display: flex;+ flex-direction: column;+ min-width: 0;+ flex: 1;+ overflow: hidden;+ background: var(--surface);+ border: 1px solid var(--surface-border);+ border-radius: var(--radius-xl);+ box-shadow: var(--surface-shadow);+}+.frame-toolbar {+ display: flex;+ align-items: center;+ gap: 7px;+ background: var(--surface);+ border-bottom: 1px solid var(--border);+ padding: 10px 14px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}+.frame-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--faint-foreground);+}+.frame-dot.is-live {+ background: var(--brand);+}+.preview-frame iframe {+ width: 100%;+ height: 100%;+ flex: 1;+ min-height: 0;+ border: 0;+ background: var(--page-canvas);+}+.compare .preview-frame {+ min-width: 460px;+}+.lab-inspector {+ display: flex;+ flex-direction: column;+ min-height: 0;+ background: var(--surface);+ border-left: 1px solid var(--border);+}+.color-selection {+ height: 5px;+ width: 5px;+ border-radius: 50%;+ background: var(--surface);+ box-shadow: 0 0 0 1px var(--foreground);+}+.token-name {+ font-family: var(--font-mono);+ font-size: var(--text-micro);+ color: var(--muted-foreground);+ margin-top: 7px;+ margin-bottom: 21px;+}+.inspector-note {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ line-height: 1.7;+ margin-top: 12px;+}+.lab-notice,+.storage-warning {+ position: fixed;+ bottom: 22px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 10px;+ max-width: 90vw;+ background: var(--primary);+ color: var(--primary-foreground);+ padding: 12px 18px;+ border-radius: var(--radius-lg);+ z-index: 100;+ box-shadow: var(--floating-shadow);+ font-size: var(--text-caption);+}+.storage-warning {+ bottom: 76px;+ background: var(--surface);+ color: var(--destructive);+}+.export-code {+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ max-height: 55dvh;+ overflow: auto;+ padding: 18px;+ border-radius: var(--radius-md);+ background: var(--muted);+ font-size: var(--text-caption);+ line-height: 1.8;+}++/* Preview rules live in the separate document, including portal content. */+.preview-root {+ min-height: 100dvh;+ background: var(--page-canvas);+ color: var(--foreground);+ font-size: var(--text-body);+}+.component-scene {+ padding: 36px;+ max-width: 1120px;+ margin: auto;+}+.eyebrow {+ font-size: var(--text-micro);+ color: var(--muted-foreground);+ letter-spacing: 1.7px;+ font-family: var(--font-mono);+}+.scene-intro h1 {+ margin-top: 13px;+ font-size: var(--text-title-lg);+ font-weight: 600;+ letter-spacing: -0.5px;+}+.scene-intro p {+ margin-top: 10px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+ line-height: 1.7;+}+.specimen-grid {+ margin-top: 32px;+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 20px;+}+.specimen {+ min-width: 0;+ border: 1px solid var(--surface-border);+ border-radius: var(--radius-xl);+ background: var(--surface);+ overflow: hidden;+}+.specimen-wide {+ grid-column: 1 / -1;+}+.specimen > header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 16px 20px 0;+}+.specimen h2 {+ font-size: var(--text-label);+ font-weight: 500;+}+.specimen header > span {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ font-family: var(--font-mono);+ letter-spacing: 0.6px;+}+.specimen-body {+ padding: 23px 20px;+}+.surface-swatches {+ display: grid;+ grid-template-columns: repeat(6, minmax(0, 1fr));+ gap: 8px;+}+.surface-swatches > div {+ text-align: center;+ min-width: 0;+}+.surface-swatches > div > div {+ border: 1px solid var(--surface-border);+ height: 48px;+ border-radius: var(--radius-md);+ display: grid;+ place-items: center;+ font-size: var(--text-body);+}+.surface-swatches span {+ display: block;+ margin-top: 9px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}+@media (max-width: 1200px) {+ .workspace-heading {+ padding: 22px 20px;+ }+ .canvas-toolbar {+ padding-left: 20px;+ padding-right: 20px;+ }+ .preview-canvas {+ padding: 0 20px 20px;+ }+ .internal-label {+ display: none;+ }+}+@media (max-width: 1000px) {+ .lab-nav {+ display: none;+ }+ .mobile-nav-toggle {+ display: inline-flex;+ }+ .lab-nav.nav-open {+ display: flex;+ position: fixed;+ top: 64px;+ bottom: 0;+ left: 0;+ width: 210px;+ z-index: 20;+ box-shadow: var(--floating-shadow);+ }+}+@media (max-width: 760px) {+ .header-actions button > span {+ display: none;+ }+ .specimen-grid {+ grid-template-columns: 1fr;+ }+ .component-scene {+ padding: 24px;+ }+}+@media (max-width: 600px) {+ .lab-shell {+ display: flex;+ flex-direction: column;+ height: auto;+ min-height: 100dvh;+ }+ .lab-header {+ min-height: 64px;+ padding: 0 12px;+ gap: 5px;+ position: sticky;+ top: 0;+ z-index: 10;+ }+ .header-actions {+ gap: 2px;+ }+ .lab-brand strong,+ .lab-brand .brand-divider,+ .lab-brand > span:last-child {+ display: none;+ }+ .header-separator {+ display: none;+ }+ .lab-main {+ min-height: 740px;+ height: 85dvh;+ flex: none;+ }+ .lab-inspector {+ border-top: 1px solid var(--border);+ border-left: 0;+ }+ .workspace-heading p {+ max-width: 220px;+ }+ .canvas-caption {+ font-size: var(--text-micro);+ }+ .lab-brand {+ gap: 6px;+ }+ .lab-brand strong {+ font-size: var(--text-title-sm);+ }+}+@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ transition-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ }+}++/* Layout only: specimens retain the production Button's own styles. */+.button-scene {+ max-width: 1120px;+ margin: auto;+ padding: 32px;+}+.button-intro h1 {+ margin-top: 12px;+ font-size: var(--text-display-sm);+ font-weight: 600;+ letter-spacing: -0.8px;+}+.button-intro h1 > span {+ margin-left: 8px;+ color: var(--muted-foreground);+ font-size: var(--text-title);+ font-weight: 400;+ letter-spacing: 0;+}+.button-intro p,+.button-section-heading p {+ margin-top: 8px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+ line-height: 1.7;+}+.button-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-top: 18px;+}+.button-meta > span {+ border: 1px solid var(--surface-border);+ border-radius: var(--radius-md);+ padding: 3px 8px;+ font-size: var(--text-micro);+ color: var(--muted-foreground);+ background: var(--surface);+}+.button-section-nav {+ display: flex;+ flex-wrap: wrap;+ gap: 20px;+ padding: 18px 0;+ margin-top: 20px;+ border-bottom: 1px solid var(--border);+ font-size: var(--text-caption);+}+.button-section-nav a {+ color: var(--muted-foreground);+ text-underline-offset: 5px;+}+.button-section-nav a:hover {+ color: var(--foreground);+ text-decoration: underline;+}+.button-section {+ margin-top: 32px;+ scroll-margin-top: 20px;+}+.button-section-heading {+ display: flex;+ align-items: start;+ justify-content: space-between;+ gap: 12px;+ margin-bottom: 18px;+}+.button-section-heading h2 {+ font-size: var(--text-title-sm);+ font-weight: 600;+}+.button-section-heading > code {+ font-size: var(--text-caption);+ color: var(--muted-foreground);+ border: 1px solid var(--border);+ padding: 3px 7px;+ border-radius: var(--radius-sm);+}+.button-playground-controls {+ display: grid;+ grid-template-columns: minmax(140px, 1.5fr) repeat(3, minmax(100px, 1fr));+ gap: 12px;+ margin-bottom: 14px;+}+.button-playground-controls label {+ display: flex;+ flex-direction: column;+ gap: 7px;+ min-width: 0;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.button-playground-controls select {+ border: 1px solid var(--input);+ border-radius: var(--radius-lg);+ background: var(--surface);+ color: var(--foreground);+ font-size: var(--text-body);+ height: 32px;+ padding: 0 8px;+}+.button-stage {+ min-height: 190px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 22px;+ background: var(--surface);+ border: 1px solid var(--surface-border);+ border-radius: var(--radius-xl) var(--radius-xl) 0 0;+ padding: 28px;+ overflow-x: auto;+}+.button-stage > p {+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.button-stage-footer {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: 20px;+ padding: 10px 14px;+ border: 1px solid var(--surface-border);+ border-top: 0;+ border-radius: 0 0 var(--radius-xl) var(--radius-xl);+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ font-variant-numeric: tabular-nums;+}+.button-table-scroll {+ overflow-x: auto;+ border: 1px solid var(--surface-border);+ border-radius: var(--radius-xl);+ background: var(--surface);+}+.button-matrix {+ width: 100%;+ min-width: 590px;+ border-collapse: collapse;+ text-align: left;+}+.button-matrix th,+.button-matrix td {+ padding: 16px;+ border-bottom: 1px solid var(--border);+}+.button-matrix thead {+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.button-matrix th {+ font-weight: 500;+}+.button-matrix tbody th {+ width: 28%;+}+.button-matrix tbody th > code {+ display: block;+ font-size: var(--text-caption);+}+.button-matrix tbody th > span {+ display: block;+ max-width: 190px;+ margin-top: 5px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ font-weight: 400;+ line-height: 1.6;+}+.button-matrix tr:last-child td,+.button-matrix tr:last-child th {+ border-bottom: 0;+}+.button-size-matrix tbody th {+ width: auto;+}+.button-size-matrix tr[data-selected="true"] {+ background: var(--surface-selected);+}+.button-context-grid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 14px;+}+.button-context-card {+ min-width: 0;+ padding: 20px;+ border: 1px solid var(--surface-border);+ border-radius: var(--radius-xl);+ background: var(--surface);+}+.button-context-card h3 {+ font-size: var(--text-label);+ font-weight: 500;+}+.button-context-card > p {+ margin-top: 8px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+ line-height: 1.7;+}+.button-example-actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 12px;+ margin-top: 22px;+ overflow-x: auto;+}+.button-source dl {+ border-top: 1px solid var(--border);+ font-size: var(--text-caption);+}+.button-source dl > div {+ display: grid;+ grid-template-columns: 90px minmax(0, 1fr);+ gap: 16px;+ padding: 14px 0;+ border-bottom: 1px solid var(--border);+ line-height: 1.8;+}+.button-source dt {+ font-weight: 500;+}+.button-source dd {+ color: var(--muted-foreground);+ overflow-wrap: anywhere;+}+.button-source code {+ font-size: var(--text-micro);+}+@media (max-width: 760px) {+ .button-scene {+ padding: 24px 20px;+ }+ .button-playground-controls {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+ .button-context-grid {+ grid-template-columns: 1fr;+ }+ .button-stage-footer {+ gap: 10px;+ }+}++.color-editor {+ min-width: 0;+}+.color-role-trigger {+ width: 100%;+ height: auto;+ padding: 10px;+ gap: 9px;+ justify-content: flex-start;+ text-align: left;+}+.color-role-swatch {+ display: block;+ width: 25px;+ height: 25px;+ flex-shrink: 0;+ border-radius: 6px;+ box-shadow: inset 0 0 0 1px rgb(0 0 0 / 10%);+}+.color-role-label {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 3px;+}+.color-role-label strong {+ font-size: var(--text-caption);+ font-weight: 500;+}+.color-role-label code {+ font-size: var(--text-micro);+ font-weight: 400;+ color: var(--muted-foreground);+ overflow: hidden;+ text-overflow: ellipsis;+}+.color-role-popover[data-slot="popover-content"] {+ width: 292px;+ padding: 6px;+ gap: 6px;+}+.color-role-search {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 4px 6px;+ color: var(--muted-foreground);+}+.color-role-search input {+ min-width: 0;+}+.color-role-list {+ max-height: 330px;+ overflow-y: auto;+}+.color-role-option {+ width: 100%;+ height: auto;+ padding: 8px;+ justify-content: flex-start;+ text-align: left;+ gap: 9px;+}+.color-role-option[aria-pressed="true"] {+ background: var(--surface-selected);+}+.color-role-empty {+ padding: 15px 8px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.color-picker-panel {+ margin-top: 16px;+}+.color-picker-panel .react-colorful {+ width: 100%;+ height: 185px;+ gap: 15px;+}+.color-picker-panel .react-colorful__saturation {+ border: 0;+ border-radius: 8px;+ box-shadow: inset 0 0 0 1px rgb(0 0 0 / 8%);+}+.color-picker-panel .react-colorful__hue {+ flex: 0 0 12px;+ border-radius: 10px;+}+.color-picker-panel .react-colorful__pointer {+ width: 16px;+ height: 16px;+ border-width: 2px;+ box-shadow: 0 1px 4px rgb(0 0 0 / 35%);+}+.color-picker-panel+ .react-colorful__interactive:focus+ .react-colorful__pointer {+ outline: 2px solid var(--foreground);+ outline-offset: 2px;+ transform: translate(-50%, -50%);+}+.color-hex-row {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 18px;+}+.color-hex-field {+ display: flex;+ align-items: center;+ min-width: 0;+ flex: 1;+ border: 1px solid var(--input);+ border-radius: var(--radius-lg);+}+.color-hex-field > span {+ font-size: var(--text-micro);+ color: var(--muted-foreground);+ padding-left: 10px;+}+.color-hex-field input {+ border: none;+ box-shadow: none;+ font-family: var(--font-mono);+ font-size: var(--text-caption);+ padding-left: 10px;+}+.color-field-error {+ color: var(--destructive);+ font-size: var(--text-micro);+ margin-top: 7px;+}+.color-feedback {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ margin-top: 7px;+ line-height: 1.6;+}+.color-comparison {+ display: flex;+ align-items: center;+ margin-top: 14px;+ gap: 0;+}+.color-comparison > button:first-child,+.color-comparison > div {+ display: flex;+ align-items: center;+ gap: 7px;+ flex: 1;+ min-width: 0;+}+.color-comparison > button:first-child > span,+.color-comparison > div > span {+ display: block;+ width: 24px;+ height: 24px;+ border-radius: 5px;+ box-shadow: inset 0 0 0 1px rgb(0 0 0 / 12%);+}+.color-comparison small {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}+.color-presets-heading {+ display: flex;+ justify-content: space-between;+ margin: 18px 0 9px;+ font-size: var(--text-micro);+ color: var(--muted-foreground);+}+.color-presets-heading > span {+ font-family: var(--font-mono);+ font-size: var(--text-micro);+}+.color-presets {+ display: flex;+ justify-content: space-between;+ gap: 6px;+}+.color-presets button {+ width: 20px;+ height: 20px;+ border-radius: 5px;+ box-shadow: inset 0 0 0 1px rgb(0 0 0 / 10%);+}+.color-presets button[aria-pressed="true"] {+ outline: 2px solid var(--foreground);+ outline-offset: 2px;+}+.color-advanced {+ margin-top: 18px;+ border-top: 1px solid var(--border);+ padding-top: 14px;+}+.color-advanced summary {+ display: flex;+ align-items: center;+ gap: 8px;+ list-style: none;+ cursor: pointer;+ font-size: var(--text-caption);+}+.color-advanced summary::-webkit-details-marker {+ display: none;+}+.color-advanced summary > span {+ font-size: var(--text-micro);+ color: var(--muted-foreground);+ margin-left: auto;+ font-family: var(--font-mono);+}+.color-advanced[open] summary > svg {+ transform: rotate(180deg);+}+.color-channels label {+ display: block;+ margin-top: 15px;+}+.color-channels label > span {+ display: flex;+ justify-content: space-between;+ font-size: var(--text-caption);+ margin-bottom: 7px;+}+.color-channels output {+ color: var(--muted-foreground);+ font-family: var(--font-mono);+ font-size: var(--text-micro);+}+.color-channels input {+ width: 100%;+ accent-color: var(--brand);+}+.color-raw-value {+ display: block;+ overflow-wrap: anywhere;+ margin-top: 12px;+ padding: 8px;+ background: var(--muted);+ border-radius: var(--radius-sm);+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ line-height: 1.8;+}++/* Compact property inspector; preview components keep their own CSS. */+.property-inspector {+ font-size: var(--text-caption);+}+.property-tabs {+ display: flex;+ flex: 1;+ min-height: 0;+ flex-direction: column;+ gap: 0;+}+.property-tabs-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ min-height: 46px;+ padding: 0 16px;+ border-bottom: 1px solid var(--border);+}+.property-tabs-header [data-slot="tabs-list"] {+ height: 46px;+ gap: 16px;+}+.property-tabs-header [data-slot="tabs-trigger"] {+ font-size: var(--text-caption);+ padding: 0;+}+.property-count {+ background: var(--muted);+ padding: 1px 5px;+ border-radius: 4px;+ font-size: var(--text-micro);+}+.property-tab-panel {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ margin: 0;+}+.property-object {+ display: flex;+ flex-direction: column;+ gap: 7px;+ padding: 16px;+ border-bottom: 1px solid var(--border);+}+.property-object > div {+ display: flex;+ align-items: center;+ gap: 8px;+}+.property-object svg {+ color: var(--brand);+}+.property-object strong {+ font-size: var(--text-label);+ font-weight: 600;+}+.property-object > span {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ padding-left: 24px;+}+.property-section {+ padding: 14px 16px 16px;+ border-bottom: 1px solid var(--border);+}+.property-section > header {+ display: flex;+ align-items: center;+ min-height: 22px;+ gap: 8px;+ margin-bottom: 12px;+}+.property-section h3 {+ font-size: var(--text-caption);+ font-weight: 600;+}+.property-scope {+ font-size: var(--text-micro);+ color: var(--muted-foreground);+ margin-left: auto;+}+.property-segments {+ display: flex;+ background: var(--muted);+ border-radius: 6px;+ padding: 3px;+ margin-bottom: 14px;+ gap: 3px;+}+.property-segments > button {+ flex: 1;+ height: 25px;+ border-radius: 4px;+ font-size: var(--text-micro);+ color: var(--muted-foreground);+}+.property-segments > button[aria-pressed="true"] {+ background: var(--surface);+ color: var(--foreground);+ box-shadow: 0 1px 3px rgb(0 0 0 / 10%);+}+.property-grid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px 8px;+}+.property-number {+ min-width: 0;+}+.property-number > label {+ display: flex;+ align-items: center;+ gap: 5px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ margin-bottom: 6px;+}+.property-modified {+ display: inline-block;+ width: 4px;+ height: 4px;+ border-radius: 50%;+ background: var(--brand);+ flex-shrink: 0;+}+.property-number-control {+ display: flex;+ align-items: center;+ height: 30px;+ border: 1px solid transparent;+ background: var(--muted);+ border-radius: 5px;+ overflow: hidden;+}+.property-number-control:hover {+ border-color: var(--border);+}+.property-number-control:focus-within {+ border-color: var(--brand);+ box-shadow: 0 0 0 1px var(--brand);+ background: var(--surface);+}+.property-number-control[data-invalid="true"] {+ border-color: var(--destructive);+}+.property-scrub {+ display: grid;+ place-items: center;+ align-self: stretch;+ width: 27px;+ flex-shrink: 0;+ font-size: var(--text-caption);+ color: var(--muted-foreground);+ touch-action: none;+ user-select: none;+}+.lab-shell .property-scrub {+ cursor: ew-resize;+}+.property-number-control > input {+ min-width: 0;+ flex: 1;+ width: 100%;+ background: transparent;+ border: 0;+ color: var(--foreground);+ font-size: var(--text-caption);+ font-variant-numeric: tabular-nums;+ height: 100%;+ padding: 0;+}+.lab-shell .property-number-control > input:focus-visible {+ outline: none;+}+.property-unit {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ padding: 0 6px 0 2px;+}+.property-reset {+ display: grid;+ place-items: center;+ width: 20px;+ height: 100%;+ flex-shrink: 0;+ color: var(--muted-foreground);+}+.property-reset:hover {+ color: var(--foreground);+}+.property-error {+ display: block;+ font-size: var(--text-micro);+ color: var(--destructive);+ margin-top: 5px;+}+.property-radius-preview {+ display: grid;+ place-items: center;+ padding-top: 15px;+}+.property-radius-preview > span {+ width: 29px;+ height: 24px;+ border: 1px solid var(--muted-foreground);+ opacity: 0.6;+}+.property-colors {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.property-color-row {+ width: 100%;+ text-align: left;+ display: flex;+ align-items: center;+ gap: 8px;+}+.property-color-label {+ flex: 1;+ min-width: 0;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}+.property-color-value {+ display: flex;+ align-items: center;+ gap: 7px;+ background: var(--muted);+ padding: 5px 7px;+ border: 1px solid transparent;+ border-radius: 5px;+ width: 128px;+ height: 30px;+}+.property-color-value:hover {+ border-color: var(--border);+}+.property-color-row[aria-expanded="true"] .property-color-value {+ border-color: var(--brand);+}+.property-color-chip {+ width: 18px;+ height: 18px;+ flex-shrink: 0;+ border-radius: 3px;+ box-shadow: inset 0 0 0 1px rgb(0 0 0 / 12%);+}+.property-color-value code {+ font-family: var(--font-mono);+ font-size: var(--text-micro);+ flex: 1;+ text-align: left;+}+.property-more-colors {+ margin-top: 12px;+}+.property-more-colors summary {+ list-style: none;+ display: flex;+ align-items: center;+ justify-content: space-between;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ cursor: pointer;+}+.property-more-colors summary::-webkit-details-marker {+ display: none;+}+.property-more-colors[open] summary {+ margin-bottom: 12px;+}+.property-more-colors[open] summary svg {+ transform: rotate(180deg);+}+.property-color-popup[data-slot="popover-content"] {+ width: 280px;+ max-width: calc(100vw - 24px);+ max-height: calc(100dvh - 24px);+ overflow-y: auto;+ padding: 16px;+ gap: 0;+ border-radius: 10px;+ box-shadow:+ 0 12px 48px rgb(0 0 0 / 16%),+ 0 0 0 1px var(--border);+}+.property-popup-heading {+ display: flex;+ align-items: center;+ gap: 8px;+}+.property-popup-heading strong {+ font-weight: 600;+ font-size: var(--text-caption);+}+.property-popup-heading > span {+ margin-left: auto;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}+.property-color-popup .color-hex-field input:focus-visible {+ outline: none;+}+.property-color-popup .color-hex-field:focus-within {+ box-shadow: 0 0 0 1px var(--brand);+}+.property-help {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ line-height: 1.7;+ padding: 14px 16px;+}+.property-export {+ border-top: 1px solid var(--border);+ padding: 12px 16px;+}+.property-export > button {+ width: 100%;+ font-size: var(--text-caption);+}+.property-export > button > span {+ margin-left: auto;+ color: var(--muted-foreground);+}+.property-changes-intro {+ padding: 20px 16px;+ border-bottom: 1px solid var(--border);+}+.property-changes-intro strong {+ font-size: var(--text-label);+ font-weight: 600;+}+.property-changes-intro p {+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ margin-top: 7px;+}+.property-change {+ padding: 14px 16px;+ border-bottom: 1px solid var(--border);+}+.property-change header {+ display: flex;+ align-items: center;+ gap: 7px;+}+.property-change strong {+ font-size: var(--text-caption);+ font-weight: 500;+}+.property-change header > span {+ margin-left: auto;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}+.property-change > code {+ display: block;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+ margin-top: 7px;+ overflow-wrap: anywhere;+}+.property-change-values {+ display: flex;+ flex-direction: column;+ gap: 5px;+ font-family: var(--font-mono);+ font-size: var(--text-micro);+ margin-top: 12px;+ overflow-wrap: anywhere;+}+.property-change-values del {+ color: var(--muted-foreground);+}+.property-change-values > span {+ color: var(--foreground);+}+.property-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 14px;+ padding: 35px 16px;+ color: var(--muted-foreground);+ font-size: var(--text-micro);+}++/* Catalog pages share the workbench shell; only live previews show an inspector. */+.lab-nav .catalog-navigation {+ gap: 18px;+}+.catalog-navigation a {+ display: flex;+ align-items: center;+ gap: 9px;+ min-width: 0;+ color: var(--muted-foreground);+ text-decoration: none;+ border-radius: var(--radius-md);+}+.catalog-navigation a:hover {+ background: var(--surface-hover);+}+.catalog-navigation a[aria-current] {+ color: var(--foreground);+ background: var(--surface-selected);+ font-weight: 600;+}+.catalog-navigation a > span:first-of-type {+ flex: 1;+ min-width: 0;+}+.catalog-navigation svg {+ width: 15px;+ height: 15px;+ flex-shrink: 0;+}+.catalog-home {+ padding: 9px 10px;+}+.catalog-nav-heading {+ display: flex;+ align-items: center;+ gap: 3px;+}+.catalog-nav-heading > a {+ flex: 1;+ padding: 8px 6px 8px 10px;+ font-size: var(--text-label);+}+.lab-nav .catalog-nav-heading > button {+ width: auto;+ gap: 5px;+ padding: 6px 4px;+ flex-shrink: 0;+ font-size: var(--text-micro);+ font-family: var(--font-mono);+}+.lab-nav .catalog-nav-heading > button svg {+ width: 12px;+ height: 12px;+}+.catalog-nav-heading .is-collapsed {+ transform: rotate(-90deg);+}+.catalog-nav-items {+ display: grid;+ gap: 2px;+ margin-top: 4px;+}+.catalog-nav-items[hidden] {+ display: none;+}+.catalog-nav-items a {+ padding: 7px 10px 7px 34px;+ font-size: var(--text-caption);+}+.catalog-dot {+ display: inline-block;+ width: 5px;+ height: 5px;+ border: 1px solid var(--faint-foreground);+ border-radius: 50%;+ flex-shrink: 0;+}+.catalog-dot.available,+.catalog-status.available .catalog-dot {+ background: var(--success);+ border-color: var(--success);+}+.catalog-content {+ flex: 1;+ min-height: 0;+ overflow: auto;+ padding: 0 28px 32px;+}+.catalog-module-grid {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 16px;+ max-width: 1400px;+}+.catalog-module-card {+ display: flex;+ flex-direction: column;+ gap: 12px;+ min-width: 0;+ padding: 24px;+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius-xl);+ text-decoration: none;+ color: var(--foreground);+}+.catalog-module-card:hover,+.catalog-page-card:hover {+ border-color: var(--brand);+ background: var(--surface-hover);+}+.catalog-card-top,+.catalog-card-footer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ color: var(--muted-foreground);+}+.catalog-card-top {+ margin-bottom: 16px;+}+.catalog-card-top svg {+ width: 24px;+ height: 24px;+ color: var(--foreground);+ stroke-width: 1.5;+}+.catalog-card-top span {+ font: var(--text-caption) var(--font-mono);+}+.catalog-module-card h2 {+ font-size: var(--text-title);+ font-weight: 600;+}+.catalog-module-card p {+ font-size: var(--text-body);+ line-height: 1.6;+ color: var(--muted-foreground);+ flex: 1;+}+.catalog-card-footer {+ margin-top: 24px;+ font-size: var(--text-caption);+}+.catalog-card-footer svg,+.catalog-page-card > svg {+ width: 15px;+ height: 15px;+ flex-shrink: 0;+}+.catalog-module-summary {+ display: flex;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 12px;+ margin-bottom: 24px;+ font-size: var(--text-body);+ color: var(--muted-foreground);+}+.catalog-module-summary > span {+ font-size: var(--text-caption);+}+.catalog-page-grid {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px;+}+.catalog-page-card {+ display: flex;+ align-items: center;+ gap: 16px;+ padding: 22px;+ border: 1px solid var(--border);+ border-radius: var(--radius-lg);+ background: var(--surface);+ color: var(--foreground);+ text-decoration: none;+}+.catalog-page-card h2 {+ font-size: var(--text-body);+ font-weight: 500;+ flex: 1;+}+.catalog-status {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ font-size: var(--text-caption);+ color: var(--muted-foreground);+ white-space: nowrap;+}+.catalog-placeholder {+ min-height: 320px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 16px;+ border: 1px dashed var(--border);+ border-radius: var(--radius-xl);+ color: var(--muted-foreground);+ background: var(--surface);+ padding: 28px;+ text-align: center;+}+.catalog-placeholder-icon {+ width: 36px;+ height: 36px;+ stroke-width: 1;+ color: var(--faint-foreground);+}+.catalog-placeholder p {+ font-size: var(--text-caption);+}+.catalog-placeholder a,+.catalog-changes-actions > a {+ display: inline-flex;+ align-items: center;+ gap: 7px;+ font-size: var(--text-caption);+ color: var(--foreground);+}+.catalog-placeholder a svg,+.catalog-changes-actions > a svg {+ width: 13px;+ height: 13px;+}+.catalog-changes {+ max-width: 960px;+ padding: 24px;+ border: 1px solid var(--border);+ border-radius: var(--radius-xl);+ background: var(--surface);+}+.catalog-changes-actions {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-wrap: wrap;+ gap: 8px;+ margin-bottom: 16px;+}+.catalog-changes-actions > a {+ margin-right: auto;+}+.catalog-changes .saved-heading {+ margin-top: 20px;+}+.catalog-export-note {+ margin-bottom: 16px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.catalog-changes .export-code {+ margin-bottom: 20px;+}+@media (max-width: 1200px) {+ .catalog-module-grid {+ grid-template-columns: repeat(2, minmax(0, 1fr));+ }+}+@media (max-width: 1000px) {+ .lab-nav.nav-open {+ width: 240px;+ }+}+@media (max-width: 600px) {+ .catalog-module-grid,+ .catalog-page-grid {+ grid-template-columns: minmax(0, 1fr);+ }+ .catalog-shell .lab-main {+ height: auto;+ min-height: calc(100dvh - 64px);+ }+ .catalog-content {+ padding: 0 20px 24px;+ overflow: visible;+ }+ .catalog-changes {+ padding: 16px;+ }+ .catalog-page-card {+ gap: 10px;+ padding: 18px;+ }+ .workspace-breadcrumb {+ flex-wrap: wrap;+ }+}++.motion-toolbar {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 4px;+ padding: 6px 12px;+ border-bottom: 1px solid var(--border);+ background: var(--surface);+}+.motion-toolbar label {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-left: auto;+ font-size: var(--text-caption);+ color: var(--muted-foreground);+}+.motion-toolbar select,+.motion-easing select {+ min-width: 0;+ height: 28px;+ padding: 0 6px;+ border: 1px solid var(--input);+ border-radius: var(--radius-md);+ background: var(--surface);+ color: var(--foreground);+}+.motion-easing {+ display: grid;+ grid-template-columns: 1fr minmax(70px, 1fr) 24px;+ align-items: center;+ gap: 6px;+ margin-top: 12px;+ font-size: var(--text-caption);+}+.dialog-options {+ grid-template-columns: minmax(140px, 220px);+}+.dialog-example-form {+ display: grid;+ gap: 16px;+ min-width: 0;+}+.dialog-example-form > label {+ display: grid;+ gap: 8px;+}+.dialog-long-content {+ display: grid;+ gap: 20px;+ color: var(--muted-foreground);+}+.motion-token-list {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 12px 24px;+ padding: 20px 0;+ font-size: var(--text-caption);+}+.motion-token-list > div {+ display: grid;+ gap: 6px;+ min-width: 0;+}+.motion-token-list span {+ color: var(--muted-foreground);+}+.motion-token-list code {+ overflow-wrap: anywhere;+}+.motion-reduced {+ font-size: var(--text-caption);+ color: var(--muted-foreground);+ margin-bottom: 16px;+}+.component-rules {+ margin-top: 28px;+ border-top: 1px solid var(--border);+ padding-top: 16px;+}+.component-rules summary {+ cursor: pointer;+ font-size: var(--text-body);+ font-weight: 600;+}+.rules-source {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 12px;+ justify-content: space-between;+ margin: 20px 0;+}+.rules-source code {+ font-size: var(--text-caption);+ color: var(--muted-foreground);+ overflow-wrap: anywhere;+}+.component-rules > div {+ min-width: 0;+}+.component-rules pre {+ max-width: 100%;+ overflow-x: auto;+}++.colors-scene {+ max-width: 1160px;+ margin: 0 auto;+ padding: 36px;+}+.palette-header {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 20px;+ justify-content: space-between;+ margin-bottom: 36px;+}+.palette-header > div {+ display: flex;+ align-items: baseline;+ gap: 12px;+}+.palette-header h1 {+ font-size: var(--text-title-lg);+ font-weight: 600;+}+.palette-header span {+ font-size: var(--text-caption);+ color: var(--muted-foreground);+}+.palette-header input {+ width: 260px;+ max-width: 100%;+}+.palette-group {+ margin-bottom: 32px;+}+.palette-group h2 {+ margin-bottom: 14px;+ font-size: var(--text-body);+ font-weight: 600;+}+.palette-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));+ gap: 12px;+}+.palette-token {+ display: flex;+ flex-direction: column;+ min-width: 0;+ text-align: left;+ padding: 7px 7px 12px;+ gap: 5px;+ border-radius: 10px;+ border: 1px solid var(--surface-border);+ background: var(--surface);+ color: var(--foreground);+ cursor: pointer;+}+.palette-token:hover {+ border-color: var(--muted-foreground);+}+.palette-token[aria-pressed="true"] {+ outline: 2px solid var(--brand);+ outline-offset: 2px;+}+.palette-token:focus-visible {+ outline: 2px solid var(--ring);+ outline-offset: 3px;+}+.palette-token[aria-pressed="true"] strong {+ font-weight: 700;+}+.palette-swatch {+ width: 100%;+ height: 76px;+ border-radius: 5px;+ border: 1px solid var(--surface-border);+ margin-bottom: 5px;+}+.palette-token-heading {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 0 3px;+ font-size: var(--text-caption);+}+.palette-token-heading strong {+ font-weight: 500;+}+.palette-token > code {+ overflow-wrap: anywhere;+ padding: 0 3px;+ font-size: var(--text-micro);+ color: var(--muted-foreground);+}+.palette-hex {+ padding: 0 3px;+ font-size: var(--text-caption);+ font-variant-numeric: tabular-nums;+}+.palette-aliases {+ display: grid;+ gap: 8px;+}+.palette-aliases button {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+ width: fit-content;+ padding: 6px 8px;+ border-radius: var(--radius-md);+ text-align: left;+ font-size: var(--text-caption);+ cursor: pointer;+}+.palette-aliases button:hover {+ background: var(--surface-hover);+}+.palette-aliases button:focus-visible {+ outline: 2px solid var(--ring);+}+.palette-aliases code:last-child {+ color: var(--muted-foreground);+}+.palette-sample {+ padding: 20px;+ display: grid;+ gap: 12px;+}+.palette-editor-section {+ padding: 16px;+}+.palette-editor-theme {+ margin-bottom: 12px;+ font-size: var(--text-caption);+ color: var(--muted-foreground);+}+.palette-editor-section .color-role-label {+ min-width: 0;+}+.palette-editor-section .color-role-label code {+ overflow-wrap: anywhere;+}+.palette-empty {+ padding: 30px 0;+ color: var(--muted-foreground);+ font-size: var(--text-body);+}+@media (max-width: 600px) {+ .colors-scene {+ padding: 20px 16px;+ }+ .palette-grid {+ grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));+ }+ .palette-header {+ margin-bottom: 24px;+ }+}++.color-usage {+ padding-top: 20px;+}+.color-usage-mappings {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));+ gap: 16px 24px;+}+.color-usage-mappings > div {+ display: grid;+ gap: 8px;+ font-size: var(--text-caption);+}+.color-usage-mappings > div > div {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}+.color-usage-mappings button {+ padding: 4px 8px;+ border-radius: 5px;+ background: var(--surface-hover);+ cursor: pointer;+ font-size: var(--text-micro);+ overflow-wrap: anywhere;+}+.color-usage-mappings button:hover {+ background: var(--surface-selected);+}+.color-usage-mappings button:focus-visible {+ outline: 2px solid var(--ring);+ outline-offset: 2px;+}+.color-usage-toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+}+.color-usage-toolbar h2 {+ font-size: var(--text-body);+ font-weight: 600;+}+.color-usage-toolbar label,+.color-usage-toggle {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: var(--text-caption);+}+.color-usage-hint {+ margin: 8px 0 16px;+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.color-usage-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(min(100%, 250px), 1fr));+ gap: 16px;+}+.color-usage-card {+ min-width: 0;+ border: 1px solid var(--surface-border);+ border-radius: 10px;+ overflow: hidden;+}+.color-usage-card h3 {+ padding: 16px 16px 0;+ font-weight: 600;+ font-size: var(--text-body);+}+.color-usage-sample {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 12px;+ padding: 20px 16px;+ min-height: 135px;+}+.color-usage-sample [data-slot="tabs"] {+ gap: 18px;+}+.color-usage-input {+ display: grid;+ gap: 8px;+ width: 100%;+ font-size: var(--text-caption);+}+.color-usage-readings {+ padding: 0 16px 16px;+ display: grid;+ gap: 14px;+}+.color-usage-reading {+ display: grid;+ gap: 4px;+ font-size: var(--text-caption);+ font-variant-numeric: tabular-nums;+}+.color-usage-reading > div {+ display: flex;+ flex-wrap: wrap;+ justify-content: space-between;+ gap: 8px;+}+.color-usage-reading strong {+ font-weight: 500;+}+.color-usage-reading span {+ color: var(--muted-foreground);+}+.color-usage-reading [data-result="fail"] {+ font-weight: 600;+ text-decoration: underline;+ text-decoration-style: dotted;+ text-underline-offset: 4px;+}+.color-usage-notes {+ margin-top: 24px;+ font-size: var(--text-caption);+ color: var(--muted-foreground);+}+.color-usage-notes summary {+ cursor: pointer;+ width: fit-content;+}+.color-usage-notes p {+ margin: 12px 0;+ max-width: 75ch;+}+.color-usage-notes a {+ text-decoration: underline;+}+.colors-scene > [data-slot="tabs"] > [data-slot="tabs-content"] {+ padding-top: 16px;+}++/* Keep panel widths independent so either side can release canvas space. */+.lab-shell,+.lab-shell.catalog-shell {+ --nav-size: 228px;+ --inspector-size: 292px;+ --nav-width: var(--nav-size);+ --inspector-width: var(--inspector-size);+ grid-template-columns: var(--nav-width) minmax(0, 1fr) var(--inspector-width);+}+.lab-shell.nav-collapsed {+ --nav-width: 0px;+}+.lab-shell.inspector-collapsed,+.lab-shell.catalog-shell {+ --inspector-width: 0px;+}+.lab-main {+ grid-column: 2;+}+.lab-inspector-slot {+ grid-column: 3;+ display: flex;+ min-width: 0;+ min-height: 0;+}+.lab-inspector-slot[hidden] {+ display: none;+}+.lab-inspector-slot > .lab-inspector {+ flex: 1;+ min-width: 0;+}+@media (min-width: 1001px) {+ .lab-shell.nav-collapsed > .lab-nav {+ display: none;+ }+}+@media (max-width: 1200px) {+ .lab-shell,+ .lab-shell.catalog-shell {+ --nav-size: 208px;+ --inspector-size: 264px;+ }+}+@media (max-width: 1000px) {+ .lab-shell,+ .lab-shell.catalog-shell {+ --nav-width: 0px;+ --inspector-size: 260px;+ }+ .desktop-nav-toggle {+ display: none;+ }+}+@media (max-width: 600px) {+ .lab-header > .mobile-nav-toggle,+ .header-actions > button {+ width: 28px;+ padding-inline: 0;+ flex-shrink: 0;+ }+ .language-toggle > button {+ padding-inline: 6px;+ }+}++/* Panel actions sit with the panel they control; restore actions stay on the same side. */+.lab-nav {+ padding-top: 0;+}+.lab-nav-header {+ position: sticky;+ top: 0;+ z-index: 1;+ display: flex;+ align-items: center;+ justify-content: space-between;+ min-height: 46px;+ flex-shrink: 0;+ padding-left: 10px;+ background: var(--surface);+ color: var(--muted-foreground);+ font-size: var(--text-caption);+}+.lab-nav .catalog-navigation {+ padding-top: 16px;+}+.workspace-heading-left,+.workspace-heading-actions,+.property-header-actions {+ display: flex;+ align-items: center;+ gap: 8px;+}+.workspace-heading-left {+ min-width: 0;+}+.workspace-heading-actions,+.property-header-actions {+ flex-shrink: 0;+}+.property-header-actions {+ gap: 4px;+}diff --git a/apps/ui-lab/src/token-changes.tsx b/apps/ui-lab/src/token-changes.tsxnew file mode 100644index 0000000000..2898a39665--- /dev/null+++ b/apps/ui-lab/src/token-changes.tsx@@ -0,0 +1,87 @@+import { useTranslation } from "react-i18next";+import { Check, RotateCcw } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import {+ baseline,+ changeCount,+ colorTokens,+ sizeTokens,+ easingTokens,+ updateToken,+ type Draft,+ type Scope,+} from "./tokens";++export function TokenChanges({+ draft,+ onEdit,+}: {+ draft: Draft;+ onEdit: (draft: Draft) => void;+}) {+ const { t } = useTranslation("uiLab");+ const count = changeCount(draft);+ const reset = (scope: Scope, key: string) =>+ onEdit(updateToken(draft, scope, key, baseline[scope][key]!));+ const changes = (+ Object.entries(draft) as [Scope, Record<string, string>][]+ ).flatMap(([scope, values]) =>+ Object.entries(values).map(([key, value]) => ({ scope, key, value })),+ );+ return (+ <>+ <div className="property-changes-intro">+ <strong>+ {count+ ? t(($) => $.lab.preview.changeCount, { count })+ : t(($) => $.inspector.changes.unchanged)}+ </strong>+ </div>+ {changes.map(({ scope, key, value }) => {+ const label =+ sizeTokens.find((token) => token.key === key)?.label ??+ easingTokens.find((token) => token.key === key)?.label ??+ colorTokens.find(([token]) => token === key)?.[1];+ return (+ <div className="property-change" key={`${scope}:${key}`}>+ <header>+ <strong>{label ? t(($) => $.tokens.labels[label]) : key}</strong>+ <span>+ {scope === "shared"+ ? t(($) => $.inspector.scope.shared)+ : scope === "light"+ ? t(($) => $.lab.theme.light)+ : t(($) => $.lab.theme.dark)}+ </span>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t(($) => $.inspector.actions.restore, {+ key,+ scope:+ scope === "shared"+ ? t(($) => $.inspector.scope.shared)+ : t(($) => $.lab.theme[scope]),+ })}+ onClick={() => reset(scope, key)}+ >+ <RotateCcw />+ </Button>+ </header>+ <code>{key}</code>+ <div className="property-change-values">+ <del>{baseline[scope][key]}</del>+ <span>{value}</span>+ </div>+ </div>+ );+ })}+ {!count && (+ <div className="property-empty">+ <Check className="size-6" />+ <span>{t(($) => $.inspector.changes.empty)}</span>+ </div>+ )}+ </>+ );+}diff --git a/apps/ui-lab/src/tokens.test.ts b/apps/ui-lab/src/tokens.test.tsnew file mode 100644index 0000000000..cefc3a1423--- /dev/null+++ b/apps/ui-lab/src/tokens.test.ts@@ -0,0 +1,318 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import {+ baseline,+ changeCount,+ editHistory,+ emptyDraft,+ exportCss,+ isDraft,+ parseColor,+ previewCss,+ readSourceTokens,+ sizeValue,+ updateToken,+} from "./tokens";+import { decodeSession, encodeSession } from "./storage";+import { isPreviewSettings } from "./protocol";++describe("the shared design-token contract", () => {+ it("reads current defaults and retains semantic aliases", () => {+ expect(baseline.light["--background"]).toBe("var(--page-canvas)");+ expect(sizeValue(baseline.shared["--radius"]!)).toBeGreaterThanOrEqual(0);+ expect(sizeValue(baseline.shared["--issue-row-height"]!)).toBeGreaterThan(+ 0,+ );+ expect(parseColor(baseline.dark["--brand"]!)).toHaveLength(3);+ expect(changeCount(emptyDraft())).toBe(0);+ expect(previewCss(emptyDraft())).toBe("");+ });+ it("parses source blocks without mistaking comment examples for declarations", () => {+ const parsed = readSourceTokens(`+ /* :root { --radius: 999px; } */+ @theme { --text-body: 14px; }+ :root { --radius: 0.625rem; --issue-row-height: 36px; --background: var(--page-canvas); }+ .dark { --page-canvas: oklch(0.2 0 0); }+ `);+ expect(sizeValue(parsed.shared["--radius"]!)).toBe(10);+ expect(parsed.dark["--background"]).toBe("var(--page-canvas)");+ });+ it("keeps light, dark and shared changes separate in exported source", () => {+ let draft = updateToken(+ emptyDraft(),+ "light",+ "--brand",+ "oklch(0.5 0.12 150)",+ );+ draft = updateToken(draft, "dark", "--brand", "oklch(0.7 0.12 150)");+ draft = updateToken(draft, "shared", "--text-body", "16px");+ draft = updateToken(draft, "shared", "--issue-row-height", "40px");+ const css = exportCss(draft);+ expect(css).toContain("@theme {\n --text-body: 16px;\n}");+ expect(css).toContain(+ ":root {\n --brand: oklch(0.5 0.12 150);\n --issue-row-height: 40px;\n}",+ );+ expect(css).toContain(".dark {\n --brand: oklch(0.7 0.12 150);\n}");+ expect(css).not.toContain("--background:");+ expect(previewCss(draft)).not.toContain("@theme");+ expect(previewCss(draft)).toContain("--text-body: 16px");+ });+ it("removes a restored value even if px and rem differ", () => {+ const draft = updateToken(emptyDraft(), "shared", "--radius", "12px");+ expect(+ changeCount(+ updateToken(+ draft,+ "shared",+ "--radius",+ `${sizeValue(baseline.shared["--radius"]!)}px`,+ ),+ ),+ ).toBe(0);+ });+ it("rejects arbitrary CSS and malformed persisted values", () => {+ expect(+ isDraft({+ ...emptyDraft(),+ light: { "--brand": "red; } body { display: none" },+ }),+ ).toBe(false);+ expect(isDraft({ ...emptyDraft(), shared: { "--radius": "100px" } })).toBe(+ false,+ );+ expect(isDraft({ ...emptyDraft(), shared: { "--unknown": "12px" } })).toBe(+ false,+ );+ expect(+ isDraft({ ...emptyDraft(), dark: { "--brand": "oklch(. 0 200)" } }),+ ).toBe(false);+ expect(isDraft({ ...emptyDraft(), shared: [] })).toBe(false);+ expect(+ isDraft(updateToken(emptyDraft(), "shared", "--text-body", "16px")),+ ).toBe(true);+ });+});+describe("design editing and persistence", () => {+ it("undoes, redoes and discards the redo branch after a new edit", () => {+ const initial = { past: [], present: emptyDraft(), future: [] };+ const draft = updateToken(initial.present, "shared", "--radius", "12px");+ const edited = editHistory(initial, { type: "edit", draft });+ const undone = editHistory(edited, { type: "undo" });+ expect(undone.present).toEqual(initial.present);+ expect(editHistory(undone, { type: "redo" }).present).toEqual(draft);+ const branched = editHistory(undone, {+ type: "edit",+ draft: updateToken(emptyDraft(), "shared", "--radius", "14px"),+ });+ expect(branched.future).toEqual([]);+ });+ it("round trips saved schemes and ignores corrupted storage", () => {+ const draft = updateToken(+ emptyDraft(),+ "dark",+ "--brand",+ "oklch(0.7 0.1 200)",+ );+ const session = {+ draft,+ designs: [+ { id: "a", name: "Design A", draft, savedAt: "2026-09-14T00:00:00Z" },+ ],+ };+ expect(decodeSession(encodeSession(session))).toEqual(session);+ expect(decodeSession("{not json")).toEqual({+ draft: emptyDraft(),+ designs: [],+ });+ expect(+ decodeSession('{"version":1,"draft":null,"designs":[]}').designs,+ ).toEqual([]);+ });+ it("keeps saved overrides when the source revision changes", () => {+ const draft = updateToken(emptyDraft(), "shared", "--radius", "12px");+ const data = JSON.parse(encodeSession({ draft, designs: [] }));+ data.sourceRevision = "older-source";+ expect(decodeSession(JSON.stringify(data)).draft).toEqual(draft);+ });+ it("validates frame settings before applying CSS", () => {+ const message = {+ type: "multica-ui-lab:preview",+ selectedColor: "--brand",+ playbackSpeed: 1,+ locale: "en",+ theme: "dark",+ scene: "list",+ buttonScale: "default",+ draft: emptyDraft(),+ };+ expect(isPreviewSettings(message)).toBe(true);+ expect(isPreviewSettings({ ...message, scene: "untrusted" })).toBe(false);+ expect(isPreviewSettings({ ...message, draft: null })).toBe(false);+ });+});++describe("Button geometry export", () => {+ it("exports button dimensions to :root, with typography in @theme", () => {+ let draft = updateToken(+ emptyDraft(),+ "shared",+ "--button-height-default",+ "40px",+ );+ draft = updateToken(draft, "shared", "--button-padding-sm", "12px");+ draft = updateToken(draft, "shared", "--text-body", "16px");+ expect(isDraft(draft)).toBe(true);+ const css = exportCss(draft);+ expect(css).toContain(+ ":root {\n --button-height-default: 40px;\n --button-padding-sm: 12px;\n}",+ );+ expect(css).toContain("@theme {\n --text-body: 16px;\n}");+ expect(decodeSession(encodeSession({ draft, designs: [] })).draft).toEqual(+ draft,+ );+ expect(previewCss(draft)).toContain("--button-height-default: 40px");+ });+ it("restores a button dimension to its source value and validates bounds", () => {+ const original = baseline.shared["--button-height-default"]!;+ const draft = updateToken(+ emptyDraft(),+ "shared",+ "--button-height-default",+ "40px",+ );+ expect(+ updateToken(+ draft,+ "shared",+ "--button-height-default",+ `${sizeValue(original)}px`,+ ),+ ).toEqual(emptyDraft());+ expect(+ isDraft({ ...draft, shared: { "--button-height-default": "200px" } }),+ ).toBe(false);+ expect(isDraft({ ...draft, shared: { "--button-gap-lg": "-2px" } })).toBe(+ false,+ );+ expect(+ isDraft({ ...emptyDraft(), dark: { "--button-height-default": "40px" } }),+ ).toBe(false);+ });+ it("accepts only supported button preview sizes", () => {+ const message = {+ type: "multica-ui-lab:preview",+ selectedColor: "--brand",+ playbackSpeed: 1,+ locale: "en",+ theme: "light",+ scene: "button",+ buttonScale: "sm",+ draft: emptyDraft(),+ };+ expect(isPreviewSettings(message)).toBe(true);+ expect(isPreviewSettings({ ...message, buttonScale: "huge" })).toBe(false);+ });+});++describe("preview theme isolation", () => {+ it("limits light overrides to the light root while keeping geometry shared", () => {+ const draft = {+ light: { "--primary": "oklch(0.5 0.2 260)" },+ dark: {},+ shared: { "--button-height-default": "40px" },+ };+ const css = previewCss(draft);+ expect(css).toContain(":root {\n --button-height-default: 40px;\n}");+ expect(css).toContain(+ ":root:not(.dark) {\n --primary: oklch(0.5 0.2 260);\n}",+ );+ expect(css).not.toContain(".dark {");+ });+});++describe("Dialog motion token contract", () => {+ it("preserves default timing and round trips edited motion through history, persistence and export", () => {+ expect(baseline.shared["--dialog-enter-duration"]).toBe("100ms");+ expect(baseline.shared["--dialog-exit-duration"]).toBe("100ms");+ expect(baseline.shared["--dialog-enter-easing"]).toBe("ease");+ let draft = updateToken(+ emptyDraft(),+ "shared",+ "--dialog-enter-duration",+ "320ms",+ );+ draft = updateToken(draft, "shared", "--dialog-exit-duration", "0ms");+ draft = updateToken(+ draft,+ "shared",+ "--dialog-enter-easing",+ "cubic-bezier(0.23, 1, 0.32, 1)",+ );+ expect(isDraft(draft)).toBe(true);+ expect(decodeSession(encodeSession({ draft, designs: [] })).draft).toEqual(+ draft,+ );+ const css = exportCss(draft);+ expect(css).toContain("--dialog-enter-duration: 320ms;");+ expect(css).toContain("--dialog-exit-duration: 0ms;");+ expect(css).toContain(+ "--dialog-enter-easing: cubic-bezier(0.23, 1, 0.32, 1);",+ );+ expect(css).not.toContain("@theme");+ const history = editHistory(+ { past: [], present: emptyDraft(), future: [] },+ { type: "edit", draft },+ );+ expect(editHistory(history, { type: "undo" }).present).toEqual(+ emptyDraft(),+ );+ expect(+ editHistory(editHistory(history, { type: "undo" }), { type: "redo" })+ .present,+ ).toEqual(draft);+ expect(+ updateToken(draft, "shared", "--dialog-enter-duration", "100ms").shared,+ ).not.toHaveProperty("--dialog-enter-duration");+ });+ it("rejects incorrect units, unbounded timings and arbitrary easing CSS", () => {+ for (const value of [+ "100px",+ "1s",+ "-1ms",+ "1001ms",+ "NaNms",+ "100ms; color: red",+ "var(--other)",+ ]) {+ expect(+ isDraft({+ ...emptyDraft(),+ shared: { "--dialog-enter-duration": value },+ }),+ value,+ ).toBe(false);+ }+ for (const value of [+ "cubic-bezier(2, 0, 1, 1)",+ "ease; display: none",+ "var(--unknown)",+ ]) {+ expect(+ isDraft({+ ...emptyDraft(),+ shared: { "--dialog-enter-easing": value },+ }),+ value,+ ).toBe(false);+ }+ expect(isDraft({ ...emptyDraft(), shared: { "--radius": "10ms" } })).toBe(+ false,+ );+ expect(+ isDraft({+ ...emptyDraft(),+ dark: { "--dialog-enter-duration": "200ms" },+ }),+ ).toBe(false);+ });+});diff --git a/apps/ui-lab/src/tokens.ts b/apps/ui-lab/src/tokens.tsnew file mode 100644index 0000000000..02dd9613f9--- /dev/null+++ b/apps/ui-lab/src/tokens.ts@@ -0,0 +1,453 @@+import { UI_EASE_OUT_CSS, UI_EASE_IN } from "@multica/ui/lib/motion";+import source from "@multica/ui/styles/tokens.css?raw";++export type Theme = "light" | "dark";+export type Scope = Theme | "shared";+export type TokenValues = Record<string, string>;+export type Draft = Record<Scope, TokenValues>;+export const emptyDraft = (): Draft => ({ light: {}, dark: {}, shared: {} });++export const colorGroups = [+ {+ id: "surfaces",+ tokens: [+ ["--app-shell", "shell"],+ ["--page-canvas", "page"],+ ["--surface", "surface"],+ ["--surface-raised", "raised"],+ ["--surface-hover", "hover"],+ ["--surface-selected", "selected"],+ ],+ },+ {+ id: "content",+ tokens: [+ ["--foreground", "foreground"],+ ["--muted-foreground", "muted"],+ ["--faint-foreground", "faint"],+ ["--surface-foreground", "surfaceText"],+ ["--surface-selected-foreground", "selectedText"],+ ["--card-foreground", "cardText"],+ ["--popover-foreground", "popoverText"],+ ],+ },+ {+ id: "actions",+ tokens: [+ ["--brand", "brand"],+ ["--brand-foreground", "brandText"],+ ["--primary", "primary"],+ ["--primary-foreground", "primaryText"],+ ["--secondary", "secondary"],+ ["--secondary-foreground", "secondaryText"],+ ["--accent", "accent"],+ ["--accent-foreground", "accentText"],+ ["--muted", "mutedFill"],+ ],+ },+ {+ id: "feedback",+ tokens: [+ ["--destructive", "destructive"],+ ["--success", "success"],+ ["--warning", "warning"],+ ["--info", "info"],+ ],+ },+ {+ id: "borders",+ tokens: [+ ["--border", "border"],+ ["--surface-border", "surfaceBorder"],+ ["--input", "inputBorder"],+ ["--ring", "ring"],+ ],+ },+ {+ id: "charts",+ tokens: [+ ["--chart-1", "chart1"],+ ["--chart-2", "chart2"],+ ["--chart-3", "chart3"],+ ["--chart-4", "chart4"],+ ["--chart-5", "chart5"],+ ],+ },+ {+ id: "sidebar",+ tokens: [+ ["--sidebar", "sidebar"],+ ["--sidebar-foreground", "sidebarText"],+ ["--sidebar-primary", "sidebarPrimary"],+ ["--sidebar-primary-foreground", "sidebarPrimaryText"],+ ["--sidebar-accent", "sidebarAccent"],+ ["--sidebar-accent-foreground", "sidebarAccentText"],+ ["--sidebar-border", "sidebarBorder"],+ ["--sidebar-ring", "sidebarRing"],+ ],+ },+] as const;+export const colorTokens = colorGroups.flatMap((group) => [...group.tokens]);+export type ColorToken = (typeof colorTokens)[number][0];+export const isColorToken = (value: unknown): value is ColorToken =>+ colorTokens.some(([key]) => key === value);+export const colorAliases = [+ ["--background", "--page-canvas"],+ ["--card", "--surface"],+ ["--popover", "--surface-raised"],+] as const;+export const buttonScales = ["xs", "sm", "default", "lg"] as const;+export type ButtonScale = (typeof buttonScales)[number];+export const buttonTokens = buttonScales.flatMap(+ (scale) =>+ [+ {+ key: `--button-height-${scale}`,+ label: "height",+ min: 20,+ max: 48,+ step: 1,+ unit: "px",+ group: "button",+ scale,+ },+ {+ key: `--button-padding-${scale}`,+ label: "padding",+ min: 4,+ max: 24,+ step: 1,+ unit: "px",+ group: "button",+ scale,+ },+ {+ key: `--button-gap-${scale}`,+ label: "gap",+ min: 0,+ max: 16,+ step: 1,+ unit: "px",+ group: "button",+ scale,+ },+ ] as const,+);+export const motionTokens = [+ {+ key: "--dialog-enter-duration",+ label: "enterDuration",+ min: 0,+ max: 1000,+ step: 10,+ unit: "ms",+ group: "motion",+ },+ {+ key: "--dialog-exit-duration",+ label: "exitDuration",+ min: 0,+ max: 1000,+ step: 10,+ unit: "ms",+ group: "motion",+ },+] as const;+export const easingTokens = [+ { key: "--dialog-enter-easing", label: "enterEasing" },+ { key: "--dialog-exit-easing", label: "exitEasing" },+] as const;+export const motionEasings = [+ { label: "standard", value: "ease" },+ { label: "linear", value: "linear" },+ { label: "easeOut", value: UI_EASE_OUT_CSS },+ { label: "easeIn", value: `cubic-bezier(${UI_EASE_IN.join(", ")})` },+] as const;+export const sizeTokens = [+ ...motionTokens,+ ...buttonTokens,+ {+ key: "--issue-row-height",+ label: "rowHeight",+ min: 32,+ max: 48,+ step: 2,+ unit: "px",+ group: "density",+ },+ {+ key: "--radius",+ label: "radius",+ min: 0,+ max: 16,+ step: 1,+ unit: "px",+ group: "radius",+ },+ {+ key: "--text-caption",+ label: "caption",+ min: 10,+ max: 16,+ step: 1,+ unit: "px",+ group: "type",+ },+ {+ key: "--text-label",+ label: "label",+ min: 11,+ max: 17,+ step: 1,+ unit: "px",+ group: "type",+ },+ {+ key: "--text-body",+ label: "body",+ min: 12,+ max: 18,+ step: 1,+ unit: "px",+ group: "type",+ },+ {+ key: "--text-body--line-height",+ label: "lineHeight",+ min: 18,+ max: 30,+ step: 1,+ unit: "px",+ group: "type",+ },+ {+ key: "--text-title-lg",+ label: "title",+ min: 18,+ max: 28,+ step: 1,+ unit: "px",+ group: "type",+ },+] as const;++// Read the authoritative file at build time. Defaults never become a second theme.+export function readSourceTokens(css: string): Draft {+ const clean = css.replace(/\/\*[\s\S]*?\*\//g, "");+ const block = (selector: RegExp): TokenValues => {+ const body = clean.match(selector)?.[1];+ if (!body) throw new Error("Cannot locate the shared design tokens.");+ return Object.fromEntries(+ [...body.matchAll(/(--[\w-]+)\s*:\s*([^;]+);/g)].map((m) => [+ m[1]!,+ m[2]!.trim(),+ ]),+ );+ };+ const light = block(/:root\s*\{([^}]+)\}/);+ const dark = block(/\.dark\s*\{([^}]+)\}/);+ const typography = block(/@theme\s*\{([^}]+)\}/);+ return {+ light,+ dark: { ...light, ...dark },+ shared: {+ ...typography,+ ...Object.fromEntries(+ Object.entries(light).filter(+ ([key]) => key.startsWith("--button-") || key.startsWith("--dialog-"),+ ),+ ),+ "--radius": light["--radius"]!,+ "--issue-row-height": light["--issue-row-height"]!,+ },+ };+}+export const baseline = readSourceTokens(source);+export const sourceRevision = [...source]+ .reduce(+ (hash, char) => Math.imul(hash ^ char.charCodeAt(0), 16777619),+ 2166136261,+ )+ .toString(16);++export function tokenValue(draft: Draft, scope: Scope, key: string): string {+ const value = draft[scope][key] ?? baseline[scope][key];+ if (value === undefined) throw new Error(`Unknown token: ${key}`);+ return value;+}+export function sizeValue(value: string): number {+ return parseFloat(value) * (value.endsWith("rem") ? 16 : 1);+}+export function numericTokenValue(key: string, value: number): string {+ const token = sizeTokens.find((item) => item.key === key);+ if (!token) throw new Error(`Unknown numeric token: ${key}`);+ return `${value}${token.unit}`;+}+const colorPattern =+ /^oklch\(([\d.]+) ([\d.]+) ([\d.]+)(?: \/ ([\d.]+)(%)?)?\)$/;+export function parseColor(value: string): [number, number, number] {+ const match = colorPattern.exec(value);+ if (!match) throw new Error(`Unsupported color: ${value}`);+ return [Number(match[1]), Number(match[2]), Number(match[3])];+}+export function colorAlpha(value: string): number {+ const match = colorPattern.exec(value);+ if (!match) throw new Error(`Unsupported color: ${value}`);+ return match[4] === undefined ? 1 : Number(match[4]) / (match[5] ? 100 : 1);+}+export function withColorAlpha(value: string, alpha: number): string {+ if (alpha === colorAlpha(value)) return value;+ return `oklch(${parseColor(value).join(" ")}${alpha === 1 ? "" : ` / ${Number(alpha.toFixed(6))}`})`;+}+function equalColors(value: string, original: string): boolean {+ try {+ return (+ colorAlpha(value) === colorAlpha(original) &&+ parseColor(value).every(+ (channel, index) => channel === parseColor(original)[index],+ )+ );+ } catch {+ return false;+ }+}+export function updateToken(+ draft: Draft,+ scope: Scope,+ key: string,+ value: string,+): Draft {+ const values = { ...draft[scope] };+ const original = baseline[scope][key];+ const equal =+ value === original ||+ (scope === "shared" && sizeValue(value) === sizeValue(original ?? "")) ||+ (scope !== "shared" && !!original && equalColors(value, original));+ if (equal) delete values[key];+ else values[key] = value;+ return { ...draft, [scope]: values };+}+export function changeCount(draft: Draft): number {+ return Object.values(draft).reduce(+ (sum, values) => sum + Object.keys(values).length,+ 0,+ );+}+function block(selector: string, values: TokenValues): string {+ const entries = Object.entries(values).sort(([a], [b]) => a.localeCompare(b));+ return entries.length+ ? `${selector} {\n${entries.map(([key, value]) => ` ${key}: ${value};`).join("\n")}\n}`+ : "";+}+export function previewCss(draft: Draft): string {+ return [+ block(":root", draft.shared),+ block(":root:not(.dark)", draft.light),+ block(".dark", draft.dark),+ ]+ .filter(Boolean)+ .join("\n\n");+}+export function exportCss(draft: Draft): string {+ if (!changeCount(draft))+ return "/* No changes to the current Multica tokens. */\n";+ const typography = Object.fromEntries(+ Object.entries(draft.shared).filter(([key]) => key.startsWith("--text-")),+ );+ const geometry = Object.fromEntries(+ Object.entries(draft.shared).filter(([key]) => !key.startsWith("--text-")),+ );+ return (+ [+ "/* Multica UI Lab — merge these declarations into the matching blocks in\n packages/ui/styles/tokens.css. Review both themes before applying.\n Existing aliases and radius multipliers remain unchanged. */",+ block("@theme", typography),+ block(":root", {+ ...geometry,+ ...draft.light,+ }),+ block(".dark", draft.dark),+ ]+ .filter(Boolean)+ .join("\n\n") + "\n"+ );+}++export function isDraft(value: unknown): value is Draft {+ if (!value || typeof value !== "object") return false;+ const candidate = value as Record<string, unknown>;+ if (Object.keys(candidate).sort().join() !== "dark,light,shared")+ return false;+ return (["light", "dark", "shared"] as const).every((scope) => {+ const values = candidate[scope];+ if (!values || typeof values !== "object" || Array.isArray(values))+ return false;+ return Object.entries(values).every(([key, v]) => {+ if (typeof v !== "string") return false;+ if (scope === "shared") {+ const definition = sizeTokens.find((token) => token.key === key);+ if (easingTokens.some((token) => token.key === key))+ return motionEasings.some((easing) => easing.value === v);+ if (+ !definition ||+ !/^\d+(\.\d+)?(px|ms)$/.test(v) ||+ !v.endsWith(definition.unit)+ )+ return false;+ const numeric = sizeValue(v);+ return numeric >= definition.min && numeric <= definition.max;+ }+ if (!colorTokens.some(([token]) => token === key)) return false;+ try {+ const [l, c, h] = parseColor(v);+ const alpha = colorAlpha(v);+ return (+ l >= 0 &&+ l <= 1 &&+ c >= 0 &&+ c <= 0.4 &&+ h >= 0 &&+ h <= 360 &&+ alpha >= 0 &&+ alpha <= 1+ );+ } catch {+ return false;+ }+ });+ });+}++export type History = { past: Draft[]; present: Draft; future: Draft[] };+export type EditAction =+ | { type: "edit"; draft: Draft }+ | { type: "undo" }+ | { type: "redo" };+export function editHistory(state: History, action: EditAction): History {+ if (action.type === "edit") {+ if (JSON.stringify(state.present) === JSON.stringify(action.draft))+ return state;+ return {+ past: [...state.past.slice(-99), state.present],+ present: action.draft,+ future: [],+ };+ }+ if (action.type === "undo") {+ const previous = state.past.at(-1);+ return previous+ ? {+ past: state.past.slice(0, -1),+ present: previous,+ future: [state.present, ...state.future],+ }+ : state;+ }+ const next = state.future[0];+ return next+ ? {+ past: [...state.past, state.present],+ present: next,+ future: state.future.slice(1),+ }+ : state;+}diff --git a/apps/ui-lab/tsconfig.json b/apps/ui-lab/tsconfig.jsonnew file mode 100644index 0000000000..e4bc591d14--- /dev/null+++ b/apps/ui-lab/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "@multica/tsconfig/base.json",+ "compilerOptions": {+ "lib": ["ESNext", "DOM", "DOM.Iterable"],+ "jsx": "react-jsx",+ "noEmit": true,+ "types": ["vite/client"]+ },+ "include": ["src", "vite.config.ts"]+}diff --git a/apps/ui-lab/vite.config.ts b/apps/ui-lab/vite.config.tsnew file mode 100644index 0000000000..4ecc12653a--- /dev/null+++ b/apps/ui-lab/vite.config.ts@@ -0,0 +1,12 @@+import { defineConfig } from "vitest/config";+import react from "@vitejs/plugin-react";+import tailwindcss from "@tailwindcss/vite";++export default defineConfig({+ plugins: [react(), tailwindcss()],+ test: {+ environment: "node",+ css: { include: [/tokens\.css/] },+ include: ["src/**/*.test.ts"],+ },+});diff --git a/package.json b/package.jsonindex 217bf8a9de..1d5515966d 100644--- a/package.json+++ b/package.json@@ -28,7 +28,8 @@"check:ui-radii": "node scripts/check-ui-radius-tokens.mjs","clean": "turbo clean && rm -rf node_modules","ui:add": "cd packages/ui && npx shadcn@latest add",- "generate:reserved-slugs": "node scripts/generate-reserved-slugs.mjs"+ "generate:reserved-slugs": "node scripts/generate-reserved-slugs.mjs",+ "dev:ui-lab": "pnpm --filter @multica/ui-lab dev"},"engines": {"node": ">=22"diff --git a/packages/ui/components/ui/button.tsx b/packages/ui/components/ui/button.tsxindex 8cbaeaf9b4..62251611e2 100644--- a/packages/ui/components/ui/button.tsx+++ b/packages/ui/components/ui/button.tsx@@ -44,16 +44,16 @@ const buttonVariants = cva(},size: {default:- "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- xs: "h-6 gap-1 rounded-md px-2 text-caption in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",- sm: "h-7 gap-1 rounded-md px-2.5 text-label in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3",- icon: "size-8",+ "h-[var(--button-height-default)] gap-[var(--button-gap-default)] px-[var(--button-padding-default)] has-data-[icon=inline-end]:pr-[max(0px,calc(var(--button-padding-default)-0.125rem))] has-data-[icon=inline-start]:pl-[max(0px,calc(var(--button-padding-default)-0.125rem))]",+ xs: "h-[var(--button-height-xs)] gap-[var(--button-gap-xs)] rounded-md px-[var(--button-padding-xs)] text-caption in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-[max(0px,calc(var(--button-padding-xs)-0.125rem))] has-data-[icon=inline-start]:pl-[max(0px,calc(var(--button-padding-xs)-0.125rem))] [&_svg:not([class*='size-'])]:size-3",+ sm: "h-[var(--button-height-sm)] gap-[var(--button-gap-sm)] rounded-md px-[var(--button-padding-sm)] text-label in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-[max(0px,calc(var(--button-padding-sm)-0.25rem))] has-data-[icon=inline-start]:pl-[max(0px,calc(var(--button-padding-sm)-0.25rem))] [&_svg:not([class*='size-'])]:size-3.5",+ lg: "h-[var(--button-height-lg)] gap-[var(--button-gap-lg)] px-[var(--button-padding-lg)] has-data-[icon=inline-end]:pr-[calc(var(--button-padding-lg)+0.125rem)] has-data-[icon=inline-start]:pl-[calc(var(--button-padding-lg)+0.125rem)]",+ icon: "size-[var(--button-height-default)]","icon-xs":- "size-6 rounded-md in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",+ "size-[var(--button-height-xs)] rounded-md in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3","icon-sm":- "size-7 rounded-md in-data-[slot=button-group]:rounded-lg",- "icon-lg": "size-9",+ "size-[var(--button-height-sm)] rounded-md in-data-[slot=button-group]:rounded-lg",+ "icon-lg": "size-[var(--button-height-lg)]",},},defaultVariants: {diff --git a/packages/ui/components/ui/dialog.tsx b/packages/ui/components/ui/dialog.tsxindex 6fc70da891..a07a3af7f0 100644--- a/packages/ui/components/ui/dialog.tsx+++ b/packages/ui/components/ui/dialog.tsx@@ -31,7 +31,7 @@ function DialogOverlay({<DialogPrimitive.Backdropdata-slot="dialog-overlay"className={cn(- "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",+ "fixed inset-0 isolate z-50 bg-black/10 data-open:duration-[var(--dialog-enter-duration)] data-closed:duration-[var(--dialog-exit-duration)] data-open:ease-[var(--dialog-enter-easing)] data-closed:ease-[var(--dialog-exit-easing)] motion-reduce:animate-none! supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",className)}{...props}@@ -61,7 +61,7 @@ function DialogContent({// fits is unaffected. `overflow-auto` shares tailwind-merge's// conflict group with `overflow-hidden`, so a dialog that manages// its own scrolling still opts out by passing that.- "fixed top-1/2 left-1/2 z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 overflow-auto rounded-xl bg-surface-raised p-4 text-body text-popover-foreground shadow-[var(--floating-shadow)] ring-1 ring-surface-border duration-100 outline-none sm:max-w-sm 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",+ "fixed top-1/2 left-1/2 z-50 grid max-h-[calc(100dvh-2rem)] w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 overflow-auto rounded-xl bg-surface-raised p-4 text-body text-popover-foreground shadow-[var(--floating-shadow)] ring-1 ring-surface-border data-open:duration-[var(--dialog-enter-duration)] data-closed:duration-[var(--dialog-exit-duration)] data-open:ease-[var(--dialog-enter-easing)] data-closed:ease-[var(--dialog-exit-easing)] motion-reduce:animate-none! outline-none sm:max-w-sm 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)}{...props}diff --git a/packages/ui/docs/button.md b/packages/ui/docs/button.mdnew file mode 100644index 0000000000..777c4215df--- /dev/null+++ b/packages/ui/docs/button.md@@ -0,0 +1,47 @@+# Button++Import from `@multica/ui/components/ui/button`.++## Usage++Use Button for actions. Use a navigation link for destinations. Keep one dominant action per dialog or form.++| Variant | Use |+| --- | --- |+| `default` | Main action, such as Save or Create |+| `outline` | Secondary action, such as Cancel |+| `secondary` | Neutral action with a soft fill |+| `ghost` | Low emphasis toolbar action |+| `brand` | Active control, such as an enabled filter |+| `brandSubtle` | Activity without a strongly selected state |+| `destructive` | Delete or another destructive action |+| `link` | An action styled like a link; use an actual link for navigation |++## Sizes and states++Text sizes: `xs`, `sm`, `default`, `lg`. Icon sizes: `icon-xs`, `icon-sm`, `icon`, `icon-lg`.++Use `disabled` when an action is unavailable. For pending actions, compose a spinner with `disabled` and `aria-busy`; Button has no `loading` prop. Icon-only buttons need an accessible name. Keep visible keyboard focus.++## Correct++```tsx+<Button type="submit" variant="default">Save</Button>+<Button type="button" variant="outline" onClick={onCancel}>Cancel</Button>+<Button variant="ghost" size="icon-xs" aria-label="Add item"><Plus /></Button>+```++## Avoid++```tsx+<Button variant="primary" loading>Save</Button>+<Button className="h-6 bg-blue-500 px-2">Save</Button>+```++`primary` and `loading` are not supported props. Choose a supported size and semantic variant before overriding geometry or colors.++## Tokens and application++`--button-height-*`, `--button-padding-*` and `--button-gap-*` control each size. Theme colors come from semantic tokens. Geometry changes affect every Button using that size; local class overrides can take precedence.++UI Lab exports a CSS patch for `packages/ui/styles/tokens.css`. Review the original and edited previews in both themes, merge declarations into the matching blocks, then review the source diff. Saving a browser design does not apply it to product code.diff --git a/packages/ui/docs/button.zh.md b/packages/ui/docs/button.zh.mdnew file mode 100644index 0000000000..f05793e5a4--- /dev/null+++ b/packages/ui/docs/button.zh.md@@ -0,0 +1,47 @@+# 按钮++从 `@multica/ui/components/ui/button` 导入。++## 使用规则++Button 用于执行操作,页面跳转使用链接。每个弹窗或表单保留一个突出显示的主要操作。++| Variant | 用途 |+| --- | --- |+| `default` | 保存、新建等主要操作 |+| `outline` | 取消等次要操作 |+| `secondary` | 柔和底色的普通操作 |+| `ghost` | 工具栏中弱化显示的操作 |+| `brand` | 已启用的筛选器等选中状态 |+| `brandSubtle` | 有活动但不需要突出选中的状态 |+| `destructive` | 删除等破坏性操作 |+| `link` | 链接样式的操作;页面跳转仍使用真实链接 |++## 尺寸与状态++文字尺寸:`xs`、`sm`、`default`、`lg`。图标尺寸:`icon-xs`、`icon-sm`、`icon`、`icon-lg`。++操作不可用时使用 `disabled`。提交中组合加载图标、`disabled` 和 `aria-busy`;Button 没有 `loading` 属性。纯图标按钮必须有无障碍名称。保留键盘焦点样式。++## 正确示例++```tsx+<Button type="submit" variant="default">保存</Button>+<Button type="button" variant="outline" onClick={onCancel}>取消</Button>+<Button variant="ghost" size="icon-xs" aria-label="添加条目"><Plus /></Button>+```++## 避免++```tsx+<Button variant="primary" loading>保存</Button>+<Button className="h-6 bg-blue-500 px-2">保存</Button>+```++不支持 `primary` 和 `loading`。优先使用现有尺寸和语义样式,再考虑覆盖大小或颜色。++## 参数与应用++`--button-height-*`、`--button-padding-*`、`--button-gap-*` 分别控制各尺寸。颜色使用语义 token。尺寸修改影响所有使用该尺寸的按钮;局部样式覆盖可能优先。++UI Lab 导出 `packages/ui/styles/tokens.css` 的 CSS 补丁。对比浅色、深色下的原始与修改效果,合并到对应区块,再检查代码差异。在浏览器中保存方案不会修改产品代码。diff --git a/packages/ui/docs/dialog.md b/packages/ui/docs/dialog.mdnew file mode 100644index 0000000000..6e91bfe24d--- /dev/null+++ b/packages/ui/docs/dialog.md@@ -0,0 +1,57 @@+# Dialog++Import from `@multica/ui/components/ui/dialog`.++## Usage++Use Dialog for a focused task that needs a modal surface. Use Popover for contextual options and AlertDialog for a consequential confirmation.++Compose `Dialog`, `DialogTrigger`, `DialogContent`, `DialogHeader`, `DialogTitle`, `DialogDescription`, `DialogFooter` and `DialogClose`. Dialog has no `variant` prop; form and long-content examples are compositions of the same component.++## Behavior++Provide a title and a concise description. Let the primitive manage focus trapping, Escape, outside dismissal and focus restoration. Use `DialogTrigger` so focus can return to the opener. Label form fields. Keep the footer reachable with long content and narrow viewports.++Only close a submitting dialog after the operation succeeds. Preserve its input and show an error on failure. The UI Lab save interaction is a local demonstration; it makes no API request.++## Correct++```tsx+<Dialog>+ <DialogTrigger render={<Button />}>Edit title</DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Edit title</DialogTitle>+ <DialogDescription>Update the task title.</DialogDescription>+ </DialogHeader>+ <label>Title<Input defaultValue="Review interface" /></label>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>+ <Button onClick={saveThenClose}>Save</Button>+ </DialogFooter>+ </DialogContent>+</Dialog>+```++## Avoid++```tsx+<div role="dialog" className="fixed inset-0">+ <Input placeholder="Title" />+ <Button onClick={() => { save(); close(); }}>Save</Button>+</div>+```++A role alone does not supply an accessible name, focus management or dismissal behavior. Do not close before an asynchronous save succeeds.++## Motion++Popup and backdrop consume `--dialog-enter-duration`, `--dialog-exit-duration`, `--dialog-enter-easing` and `--dialog-exit-easing` from `packages/ui/styles/tokens.css`. The defaults preserve the existing 100ms/ease animation. The popup also fades and scales between 95% and 100%.++Changes affect shared Dialog instances on web and desktop, including compositions that use DialogContent, unless callers override the animation. They do not change Popover, Tooltip, AlertDialog or JavaScript motion constants.++Respect `prefers-reduced-motion`: popup and backdrop animations are disabled. UI Lab playback speed is preview-only and never exported. Open, close and replay the real component; also interrupt it with rapid open/close actions.++## Application++Compare both themes and keyboard behavior. Save a scheme for later or export CSS and merge into the matching `:root` block in `packages/ui/styles/tokens.css`. Exporting does not write to product code.diff --git a/packages/ui/docs/dialog.zh.md b/packages/ui/docs/dialog.zh.mdnew file mode 100644index 0000000000..2cdadedc3f--- /dev/null+++ b/packages/ui/docs/dialog.zh.md@@ -0,0 +1,57 @@+# 弹窗++从 `@multica/ui/components/ui/dialog` 导入。++## 使用规则++Dialog 用于需要模态界面的独立操作。上下文选项使用 Popover;重要操作确认使用 AlertDialog。++组合使用 `Dialog`、`DialogTrigger`、`DialogContent`、`DialogHeader`、`DialogTitle`、`DialogDescription`、`DialogFooter` 和 `DialogClose`。Dialog 没有 `variant` 属性;表单和长内容只是同一组件的不同组合。++## 行为++提供标题和简短说明。由组件处理焦点限制、Escape、点击外部关闭和焦点恢复。使用 `DialogTrigger`,让焦点能返回打开按钮。表单字段需要标签。长内容和窄屏下,底部操作必须可访问。++提交成功后再关闭;失败时保留输入并显示错误。UI Lab 中的保存是本地演示,不发送 API 请求。++## 正确示例++```tsx+<Dialog>+ <DialogTrigger render={<Button />}>编辑标题</DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>编辑标题</DialogTitle>+ <DialogDescription>更新任务标题。</DialogDescription>+ </DialogHeader>+ <label>标题<Input defaultValue="检查界面" /></label>+ <DialogFooter>+ <DialogClose render={<Button variant="outline" />}>取消</DialogClose>+ <Button onClick={saveThenClose}>保存</Button>+ </DialogFooter>+ </DialogContent>+</Dialog>+```++## 避免++```tsx+<div role="dialog" className="fixed inset-0">+ <Input placeholder="标题" />+ <Button onClick={() => { save(); close(); }}>保存</Button>+</div>+```++仅设置 role 不会提供无障碍名称、焦点管理和关闭行为。异步保存成功前不要关闭弹窗。++## 动效++弹窗和遮罩读取 `packages/ui/styles/tokens.css` 中的 `--dialog-enter-duration`、`--dialog-exit-duration`、`--dialog-enter-easing` 和 `--dialog-exit-easing`。默认保持现有的 100ms/ease 动画,弹窗同时淡入淡出并在 95% 和 100% 之间缩放。++参数影响网页端和桌面端的共享 Dialog,以及使用 DialogContent 的组合;调用方自行覆盖动画时除外。不影响 Popover、Tooltip、AlertDialog 和 JavaScript 动效常量。++遵循系统减少动态效果设置,禁用弹窗和遮罩动画。UI Lab 的播放速度仅用于预览,不参与导出。打开、关闭和重播真实组件,也要快速交替打开与关闭,检查中断效果。++## 应用修改++检查两种主题和键盘操作。保存方案,或导出 CSS 并合并到 `packages/ui/styles/tokens.css` 的 `:root` 区块。导出不会直接修改产品代码。diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 788a404eea..d56e2d4837 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -24,7 +24,11 @@"./lib/motion": "./lib/motion.ts","./i18n-types": "./types/i18next.ts","./styles/tokens.css": "./styles/tokens.css",- "./styles/base.css": "./styles/base.css"+ "./styles/base.css": "./styles/base.css",+ "./docs/button.md": "./docs/button.md",+ "./docs/button.zh.md": "./docs/button.zh.md",+ "./docs/dialog.md": "./docs/dialog.md",+ "./docs/dialog.zh.md": "./docs/dialog.zh.md"},"dependencies": {"@base-ui/react": "^1.3.0",diff --git a/packages/ui/styles/tokens.css b/packages/ui/styles/tokens.cssindex dfe94e37df..3565863da5 100644--- a/packages/ui/styles/tokens.css+++ b/packages/ui/styles/tokens.css@@ -122,7 +122,27 @@}:root {+ /* Dialog motion, shared by popup and backdrop. */+ --dialog-enter-duration: 100ms;+ --dialog-exit-duration: 100ms;+ --dialog-enter-easing: ease;+ --dialog-exit-easing: ease;+color-scheme: light;+ /* Button geometry. Text and icon-only buttons share the height ladder.+ Keep the defaults aligned with the existing compact product controls. */+ --button-height-xs: 1.5rem;+ --button-height-sm: 1.75rem;+ --button-height-default: 2rem;+ --button-height-lg: 2.25rem;+ --button-padding-xs: 0.5rem;+ --button-padding-sm: 0.625rem;+ --button-padding-default: 0.625rem;+ --button-padding-lg: 0.625rem;+ --button-gap-xs: 0.25rem;+ --button-gap-sm: 0.25rem;+ --button-gap-default: 0.375rem;+ --button-gap-lg: 0.375rem;/* Surface system: the app shell is the quiet outer frame; the page canvasis where lists, boards, and conversations live; surfaces are reservedfor bounded content groups; raised surfaces are ephemeral overlays. */@@ -201,6 +221,7 @@--chart-4: oklch(0.85 0.06 255);--chart-5: oklch(0.92 0.03 255);--radius: 0.5rem;+ --issue-row-height: 36px;--sidebar: oklch(0.964435 0.001327 286.375);--sidebar-foreground: oklch(0.141 0.005 285.823);--sidebar-primary: oklch(0.21 0.006 285.885);@@ -209,7 +230,7 @@--sidebar-accent-foreground: oklch(0.21 0.006 285.885);--sidebar-border: oklch(0.92 0.004 286.32);--sidebar-ring: oklch(0.705 0.015 286.067);- --brand: oklch(0.55 0.16 255);+ --brand: oklch(0.56079497 0.19449888 256.41258418);--brand-foreground: oklch(0.985 0 0);--success: oklch(0.55 0.16 145);--warning: oklch(0.75 0.16 85);@@ -279,6 +300,7 @@--sidebar-accent-foreground: oklch(0.985 0 0);--sidebar-border: oklch(1 0 0 / 10%);--sidebar-ring: oklch(0.552 0.016 285.938);+ /* Brand also paints body-text links; keep it readable on dark surfaces. */--brand: oklch(0.65 0.16 255);--brand-foreground: oklch(0.985 0 0);--success: oklch(0.65 0.15 145);diff --git a/packages/views/common/virtuoso-seed.test.tsx b/packages/views/common/virtuoso-seed.test.tsxnew file mode 100644index 0000000000..3180e118a4--- /dev/null+++ b/packages/views/common/virtuoso-seed.test.tsx@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { render } from "@testing-library/react";+import { VirtuosoSeed } from "./virtuoso-seed";++describe("VirtuosoSeed scroll-height reservation", () => {+ const data = Array.from({ length: 100 }, (_, index) => index);+ const props = {+ data,+ computeItemKey: (index: number) => index,+ itemContent: (_index: number, value: number) => <div data-row>{value}</div>,+ };++ it.each([+ [36, "2520px"],+ ["var(--issue-row-height)", "calc(70 * var(--issue-row-height))"],+ ])("reserves unmounted rows using %s", (height, expected) => {+ const { container } = render(<VirtuosoSeed {...props} estimatedItemHeight={height} />);+ expect(container.querySelectorAll("[data-row]")).toHaveLength(30);+ expect(container.querySelector<HTMLElement>("[aria-hidden]")?.style.height).toBe(expected);+ });++ it("does not reserve space beyond the data for a short list", () => {+ const { container } = render(<VirtuosoSeed {...props} data={[1, 2]} estimatedItemHeight="var(--issue-row-height)" />);+ expect(container.querySelectorAll("[data-row]")).toHaveLength(2);+ expect(container.querySelector("[aria-hidden]")).toBeNull();+ });+});diff --git a/packages/views/common/virtuoso-seed.tsx b/packages/views/common/virtuoso-seed.tsxindex 16486f3a4d..77af1c837b 100644--- a/packages/views/common/virtuoso-seed.tsx+++ b/packages/views/common/virtuoso-seed.tsx@@ -36,8 +36,9 @@ export const VIRTUOSO_SEED_COUNT = 30;* thumb) approximates the full list from the first frame. Without it, the* seed frame's scroll height is only the seeded rows, and the handoff to* Virtuoso — which spaces out the full count — visibly re-draws the- * scrollbar. Pass the same estimate as the Virtuoso's `defaultItemHeight` so- * both phases agree until real measurements land.+ * scrollbar. Pass the same estimate (or its resolved pixel height for a CSS+ * length) as Virtuoso's `defaultItemHeight` so both phases agree until real+ * measurements land.*/export function VirtuosoSeed<T>({data,@@ -50,9 +51,9 @@ export function VirtuosoSeed<T>({itemContent: (index: number, item: T) => ReactNode;computeItemKey: (index: number, item: T) => Key;count?: number;- /** Estimated row height (px, including any per-row gap) used to reserve- * scroll height for the rows beyond `count`. */- estimatedItemHeight?: number;+ /** Estimated row height (pixels or a CSS length, including any per-row gap)+ * used to reserve scroll height for the rows beyond `count`. */+ estimatedItemHeight?: number | string;}) {const seeded = data.slice(0, count);const remaining = data.length - seeded.length;@@ -64,7 +65,15 @@ export function VirtuosoSeed<T>({</Fragment>))}{estimatedItemHeight !== undefined && remaining > 0 && (- <div aria-hidden style={{ height: remaining * estimatedItemHeight }} />+ <div+ aria-hidden+ style={{+ height:+ typeof estimatedItemHeight === "number"+ ? remaining * estimatedItemHeight+ : `calc(${remaining} * ${estimatedItemHeight})`,+ }}+ />)}</>);diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsxindex 7f3115709f..36df290844 100644--- a/packages/views/issues/components/list-row.tsx+++ b/packages/views/issues/components/list-row.tsx@@ -80,9 +80,10 @@ function ListRowContent({<IssueActionsContextMenu issue={issue}><divref={containerRef}+ data-slot="issue-list-row"style={containerStyle}{...containerProps}- className={`group/row flex h-9 items-center gap-2 px-4 text-body transition-colors ${+ className={`group/row flex h-[var(--issue-row-height)] items-center gap-2 px-4 text-body transition-colors ${selected? "bg-surface-selected hover:not-data-[popup-open]:bg-surface-selected data-[popup-open]:bg-surface-selected": "hover:not-data-[popup-open]:bg-surface-hover data-[popup-open]:bg-surface-hover"diff --git a/packages/views/issues/components/list-view.test.tsx b/packages/views/issues/components/list-view.test.tsxindex eda8e73cb4..72a1a210ed 100644--- a/packages/views/issues/components/list-view.test.tsx+++ b/packages/views/issues/components/list-view.test.tsx@@ -7,7 +7,7 @@ import { issueStatusKeys } from "@multica/core/issue-statuses/queries";import type { Issue, IssueStatus, IssueStatusEntry } from "@multica/core/types";import { ListView } from "./list-view";import { IssueContextMenuProvider } from "../actions";-import { ScrollRestorationProvider } from "../../platform";+import { ScrollRestorationProvider, type ScrollRestorationAdapter } from "../../platform";import type { IssueStatusPagination } from "../surface/use-issue-status-branches";import enCommon from "../../locales/en/common.json";import enIssues from "../../locales/en/issues.json";@@ -156,8 +156,8 @@ vi.mock("@dnd-kit/utilities", () => ({// jsdom has no layout, so the real Virtuoso measures a 0-height viewport and// renders nothing. Render rows inline so the panel's contents are assertable.vi.mock("react-virtuoso", () => ({- Virtuoso: ({ data, itemContent }: any) => (- <div data-testid="virtuoso-mock">+ Virtuoso: ({ data, itemContent, defaultItemHeight }: any) => (+ <div data-testid="virtuoso-mock" data-estimated-height={defaultItemHeight}>{(data ?? []).map((item: any, i: number) => (<div key={i}>{itemContent(i, item)}</div>))}@@ -211,6 +211,7 @@ function renderListView(hiddenStatuses: IssueStatus[] = [],onMoveIssue = vi.fn(),statuses: IssueStatusEntry[] = [],+ scrollAdapter: ScrollRestorationAdapter = { get: () => undefined },) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false, gcTime: 0 } },@@ -220,7 +221,7 @@ function renderListView(<QueryClientProvider client={queryClient}><I18nProvider resources={TEST_RESOURCES} locale="en"><IssueContextMenuProvider>- <ScrollRestorationProvider adapter={{ get: () => undefined }}>+ <ScrollRestorationProvider adapter={scrollAdapter}><ListViewissues={issues}visibleStatuses={visibleStatuses}@@ -255,6 +256,34 @@ describe("ListView status header collapse", () => {expect(screen.queryByTestId("priority-icon")).not.toBeInTheDocument();});+ it.each([32, 36, 48])("reserves token-sized rows before restoring scroll and hands %ipx rows to Virtuoso", (height) => {+ // jsdom has no layout engine or Tailwind compiler. Supply the resolved+ // row height, but inspect the real seed DOM at the restoration boundary.+ const styles = document.createElement("style");+ styles.textContent = `[class~="group/row"] { height: ${height}px; }`;+ document.head.append(styles);+ const issues = Array.from({ length: 100 }, (_, index) => ({+ ...ISSUES[0]!, id: `issue-${index}`, identifier: `MUL-${index}`, position: index,+ }));+ let seedRows = 0;+ let spacerHeight: string | undefined;+ const get = vi.fn(() => {+ const scroller = document.querySelector('[data-tab-scroll-root="list"]')!;+ seedRows = scroller.querySelectorAll('[class~="group/row"]').length;+ spacerHeight = scroller.querySelector<HTMLElement>('div[aria-hidden="true"][style*="height"]')?.style.height;+ return { top: 2400, height: 600 };+ });+ try {+ renderListView(issues, ["todo"], [], vi.fn(), [], { get });+ expect(get).toHaveBeenCalledWith("list");+ expect(seedRows).toBe(30);+ expect(spacerHeight).toBe("calc(70 * var(--issue-row-height))");+ expect(screen.getByTestId("virtuoso-mock")).toHaveAttribute("data-estimated-height", String(height));+ } finally {+ styles.remove();+ }+ });+it("shows hidden statuses with a recovery action", async () => {const user = userEvent.setup();renderListView(ISSUES, ["todo"], ["cancelled"]);diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsxindex da747ff7b3..21cfa2dfca 100644--- a/packages/views/issues/components/list-view.tsx+++ b/packages/views/issues/components/list-view.tsx@@ -52,12 +52,9 @@ import { useRestoredScrollRef } from "../../platform";import { HiddenColumnsPanel, HiddenColumnRow } from "./hidden-columns-panel";import { toast } from "sonner";-// List rows are a fixed 36px (h-9). Sharing the estimate between the seed's-// trailing spacer and Virtuoso's defaultItemHeight keeps the shared-// scroller's height truthful from the first frame — which both stops the-// scrollbar from re-drawing across the seed → Virtuoso handoff and lets the-// restored scrollTop assignment stick at ref-attach (MUL-4741).-const LIST_ROW_ESTIMATED_HEIGHT = 36;+// The seed must use the same CSS height as ListRow before scroll restoration+// runs at ref-attach. Virtuoso receives the seed's resolved pixel height below.+const LIST_ROW_HEIGHT = "var(--issue-row-height)";const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();const EMPTY_IDS: string[] = [];@@ -358,12 +355,19 @@ function ListViewImpl({// the current sticky-header + cross-section scroll behavior; only the rows// inside each expanded panel virtualize.const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);+ const [rowHeight, setRowHeight] = useState<number>();// Pull-based scroll restoration (MUL-4741): assign the saved offset when// the shared scroller attaches — the per-status seeds plus their estimate// spacers give it a truthful height on the first commit.const restoreScrollRef = useRestoredScrollRef("list");const attachScroller = useCallback((el: HTMLDivElement | null) => {+ const row = el?.querySelector<HTMLElement>('[data-slot="issue-list-row"]');+ // Read the rendered height, not parseFloat of the custom property: the+ // source token may be a rem/calc length. With no seed rows, let Virtuoso+ // measure its first item when a group is expanded or data arrives.+ const height = row ? Number.parseFloat(getComputedStyle(row).height) : 0;+ setRowHeight(height > 0 ? height : undefined);setScrollEl(el);restoreScrollRef(el);},@@ -404,6 +408,7 @@ function ListViewImpl({isExpanded={isExpanded}sortLabel={sortLabel}scrollParent={scrollEl}+ rowHeight={rowHeight}/>);})}@@ -471,6 +476,7 @@ function StatusAccordionItem({isExpanded,sortLabel,scrollParent,+ rowHeight,}: {status: IssueStatus;issueIds: string[];@@ -484,6 +490,7 @@ function StatusAccordionItem({isExpanded: boolean;sortLabel: string | null;scrollParent: HTMLElement | null;+ rowHeight: number | undefined;}) {const { t } = useT("issues");const selection = useIssueSurfaceSelection();@@ -572,7 +579,7 @@ function StatusAccordionItem({data={issues}computeItemKey={computeItemKey}initialItemCount={Math.min(issues.length, VIRTUOSO_SEED_COUNT)}- defaultItemHeight={LIST_ROW_ESTIMATED_HEIGHT}+ defaultItemHeight={rowHeight}increaseViewportBy={{ top: 400, bottom: 400 }}components={listComponents}itemContent={itemContent}@@ -582,7 +589,7 @@ function StatusAccordionItem({data={issues}itemContent={itemContent}computeItemKey={computeItemKey}- estimatedItemHeight={LIST_ROW_ESTIMATED_HEIGHT}+ estimatedItemHeight={LIST_ROW_HEIGHT}/>)) : null;diff --git a/packages/views/issues/components/visuals.ts b/packages/views/issues/components/visuals.tsnew file mode 100644index 0000000000..435df62d02--- /dev/null+++ b/packages/views/issues/components/visuals.ts@@ -0,0 +1,3 @@+// Small, presentational exports for consumers that do not mount issue pages.+export { StatusIcon } from "./status-icon";+export { PriorityIcon } from "./priority-icon";diff --git a/packages/views/package.json b/packages/views/package.jsonindex 198e99d6de..3ddf5a530b 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -54,7 +54,8 @@"./i18n": "./i18n/index.ts","./attachments": "./attachments/index.ts","./locales": "./locales/index.ts",- "./locales/*": "./locales/*"+ "./locales/*": "./locales/*",+ "./issues/visuals": "./issues/components/visuals.ts"},"dependencies": {"@base-ui/react": "^1.3.0",diff --git a/packages/views/settings/components/issue-statuses-tab.test.tsx b/packages/views/settings/components/issue-statuses-tab.test.tsxindex c01b68483b..29c5796bd3 100644--- a/packages/views/settings/components/issue-statuses-tab.test.tsx+++ b/packages/views/settings/components/issue-statuses-tab.test.tsx@@ -109,11 +109,11 @@ describe("IssueStatusesTab", () => {render(<IssueStatusesTab />);const add = screen.getByLabelText(`${en.issue_statuses.add}: ${en.issue_statuses.category_labels.started}`);expect(add.parentElement).toHaveClass("px-4");- expect(add).toHaveClass("size-7", "shrink-0", "[@media(pointer:coarse)]:size-11");+ expect(add).toHaveClass("size-[var(--button-height-sm)]", "shrink-0", "[@media(pointer:coarse)]:size-11");for (const name of ["in_review", "QA"]) {const action = screen.getByLabelText(en.issue_statuses.actions.open.replace("{{name}}", name));expect(action.closest(".group\\/row")).toHaveClass("pr-4");- expect(action).toHaveClass("size-7", "shrink-0", "[@media(pointer:coarse)]:size-11");+ expect(action).toHaveClass("size-[var(--button-height-sm)]", "shrink-0", "[@media(pointer:coarse)]:size-11");}});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5f7c188bbb..77bf231db1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -12,6 +12,9 @@ catalogs:'@tailwindcss/postcss':specifier: ^4version: 4.2.2+ '@tailwindcss/vite':+ specifier: ^4+ version: 4.2.2'@tanstack/react-query':specifier: ^5.96.2version: 5.96.2@@ -535,6 +538,91 @@ importers:specifier: 'catalog:'version: 4.1.0(@opentelemetry/[email protected])(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))+ apps/ui-lab:+ dependencies:+ '@fontsource-variable/inter':+ specifier: ^5.2.5+ version: 5.2.8+ '@multica/core':+ specifier: workspace:*+ version: link:../../packages/core+ '@multica/ui':+ specifier: workspace:*+ version: link:../../packages/ui+ '@multica/views':+ specifier: workspace:*+ version: link:../../packages/views+ '@tanstack/react-query':+ specifier: 'catalog:'+ version: 5.96.2([email protected])+ colorjs.io:+ specifier: ^0.7.1+ version: 0.7.1+ i18next:+ specifier: 'catalog:'+ version: 26.0.8([email protected])+ lucide-react:+ specifier: 'catalog:'+ version: 1.0.1([email protected])+ react:+ specifier: 'catalog:'+ version: 19.2.3+ react-colorful:+ specifier: ^5.8.1+ react-dom:+ specifier: 'catalog:'+ version: 19.2.3([email protected])+ react-i18next:+ specifier: 'catalog:'+ version: 17.0.6([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ shadcn:+ specifier: ^4.1.0+ version: 4.1.0(@types/[email protected])([email protected])+ sonner:+ specifier: ^2.0.7+ tw-animate-css:+ specifier: ^1.4.0+ version: 1.4.0+ devDependencies:+ '@multica/eslint-config':+ specifier: workspace:*+ version: link:../../packages/eslint-config+ '@multica/tsconfig':+ specifier: workspace:*+ version: link:../../packages/tsconfig+ '@tailwindcss/vite':+ specifier: 'catalog:'+ version: 4.2.2([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))+ '@types/node':+ specifier: 'catalog:'+ version: 25.5.0+ '@types/react':+ specifier: ^19.2.0+ version: 19.2.14+ '@types/react-dom':+ specifier: ^19.2.0+ version: 19.2.3(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: 'catalog:'+ version: 6.0.1([email protected])([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))+ eslint:+ specifier: ^9.0.0+ version: 9.39.4([email protected])+ tailwindcss:+ specifier: 'catalog:'+ version: 4.2.2+ typescript:+ specifier: 'catalog:'+ version: 5.9.3+ vite:+ specifier: ^8.0.1+ version: 8.0.1(@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: 'catalog:'+ version: 4.1.0(@opentelemetry/[email protected])(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))+apps/web:dependencies:'@multica/core':@@ -1070,6 +1158,15 @@ importers:version: 4.1.0(@opentelemetry/[email protected])(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected]))([email protected](@emnapi/[email protected])(@emnapi/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))packages:+ resolution: {integrity: sha512-oz68bhsnFWnpDf1ZR8daiQbYpXUnM2h2J6hl9Zg2rTpM/DU6vCqe1E+CpqmqLnJucMZetHZeifSAfJ+geN9lcA==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'++ resolution: {integrity: sha512-LY7OHnJZxHwT5UlzNa9bbhHHDbzB6yE5+3MIPwJEQKRvSCt/T4G7epsj+9j2BExUIIfXFIJGsIXUKdfrK9Q5tA==}+resolution: {integrity: sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==}@@ -11124,6 +11221,13 @@ packages:resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}snapshots:+ dependencies:+ react: 19.2.3+ react-dom: 19.2.3([email protected])++ [email protected]: {}+diff --git a/scripts/ci-scope.test.mjs b/scripts/ci-scope.test.mjsindex a44336242f..d207924b5f 100644--- a/scripts/ci-scope.test.mjs+++ b/scripts/ci-scope.test.mjs@@ -19,6 +19,7 @@ for (const [name, files, selected] of [["readme only", ["README.md"], []],["docs only", ["apps/docs/content/docs/guide.mdx"], ["quality"]],["web changelog", ["apps/web/features/landing/i18n/en.ts"], ["frontend", "quality"]],+ ["UI Lab", ["apps/ui-lab/src/app.tsx"], ["frontend", "quality"]],["mobile UI", ["apps/mobile/app/index.tsx"], ["quality"]],["migration only", ["server/migrations/999_example.up.sql"], ["backend", "sqlc"]],["agent process code", ["server/pkg/agent/cursor_background.go"], ["backend", "runtime"]],