diff --git a/external_plugins/design-to-components/.zcode-plugin/plugin.json b/external_plugins/design-to-components/.zcode-plugin/plugin.json new file mode 100644 index 00000000..e0449798 --- /dev/null +++ b/external_plugins/design-to-components/.zcode-plugin/plugin.json @@ -0,0 +1,58 @@ +{ + "name": "design-to-components", + "version": "0.1.0", + "description": "Turn a design or screenshot into a React component kit: keep design tokens (colours, fonts, font sizes, radii, spacing, shadows) and a component checklist in the panel, the agent writes TSX components with one example per state, and the plugin type-checks them with TypeScript (strict), renders every example next to the design, bundles them with esbuild-wasm into an interactive catalog page, and outputs tokens.css and tokens.ts. Flags hard-coded colours and missing states. Local only.", + "description_i18n": { + "en": "Turn a design or screenshot into a React component kit: keep design tokens (colours, fonts, font sizes, radii, spacing, shadows) and a component checklist in the panel, the agent writes TSX components with one example per state, and the plugin type-checks them with TypeScript (strict), renders every example next to the design, bundles them with esbuild-wasm into an interactive catalog page, and outputs tokens.css and tokens.ts. Flags hard-coded colours and missing states. Local only.", + "zh-CN": "把设计稿或截图做成 React 组件库:在面板里维护设计变量(颜色、字体、字号、圆角、间距、阴影)和组件清单,Agent 为每个组件写 TSX,每种状态一个示例;插件用 TypeScript(strict)做类型检查,把每个示例渲染出来与设计稿并排对照,用 esbuild-wasm 打包成可交互的组件目录页,并输出 tokens.css 和 tokens.ts。会提示写死的颜色和缺少的状态示例。全部在本地完成。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "react", + "components", + "design system", + "design tokens", + "tsx", + "typescript", + "storybook", + "esbuild", + "组件库", + "设计稿", + "设计变量", + "前端" + ], + "skills": "skills", + "mcpServers": { + "design-to-components": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "设计稿转组件库", + "en-US": "Design To Components" + }, + "icon": "component", + "server": "design-to-components", + "resourceUri": "ui://design-to-components/panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/design-to-components/LICENSE b/external_plugins/design-to-components/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/design-to-components/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/design-to-components/README.md b/external_plugins/design-to-components/README.md new file mode 100644 index 00000000..153abf72 --- /dev/null +++ b/external_plugins/design-to-components/README.md @@ -0,0 +1,48 @@ +# Design To Components + +Turn a design or screenshot into a **React component kit**. The panel keeps the design tokens and a component checklist. The agent writes the TSX components. The plugin type-checks them, renders every state next to the design, and builds an interactive catalog page. + +## Features + +- **Design tokens** (`dc_tokens`): colours, fonts, font sizes, radii, spacing and shadows in `tokens.json`. They generate `tokens.css` (`--color-primary`, `--font-size-md`, `--radius-md`, `--space-4`, …) and a typed `tokens.ts`. You can edit them in the panel with colour pickers. +- **Component checklist** (`dc_plan`): each component lists the states it needs (for example Button: primary, secondary, disabled, loading). The panel shows which are written and compile (✓ / ✗ / ○). +- **Components** (`dc_write`): `src/.tsx` (+ `src/.css`). Each file exports the component and `examples`, one per state. Files live directly in `src/`; `src/components//.tsx` is accepted and flattened. +- **Checks** on every write: + - **TypeScript strict** type-check with React 19 types. + - esbuild bundling (only `react` / `react-dom` and kit files can be imported). + - Every example is rendered (render errors are shown). + - The named export must exist, and each planned state needs an example. + - **Hard-coded colours** that should be tokens are flagged. +- **Preview**: every example rendered with the real CSS, next to the design image. +- **Catalog**: `catalog/index.html` is a self-contained interactive page (React + your components, bundled with esbuild-wasm) that works from `file://`. Plus `index.ts`, which re-exports everything. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Build React components from this design" +- "Pull the colours and type scale from the screenshot into tokens" +- "Add a loading state to the Button and check it compiles" + +To use the kit in your app (React 18/19), copy `src/`, `tokens.css`, `tokens.ts` and `index.ts`, import `tokens.css` once, and let your bundler (Vite, Next, …) handle the CSS imports. + +## Tools + +| Tool | Purpose | +|---|---| +| `dc_new` | Create a kit (tokens files, README) and link design images | +| `dc_tokens` | Set / remove tokens; regenerates tokens.css / tokens.ts | +| `dc_plan` | Component checklist with required states | +| `dc_write` | Write / delete component files and rebuild | +| `dc_build` | Type-check, render examples and rebuild the catalog | + +## Scope (v0.1) + +- React + TypeScript with plain CSS files. No Vue, no Figma import, and no Tailwind or CSS-in-JS setup. +- Components can import only React and files in the kit. Third-party UI libraries are not available in the preview. +- The panel preview is static (each state is its own example). Hover, focus and typing can be tried in `catalog/index.html`. + +## Privacy, network and files + +- Runs locally with no network access and no API keys. esbuild (WebAssembly), TypeScript and the React types are bundled with the plugin. +- Writes only `ui-kit//` and `.design-to-components/project.json`. diff --git a/external_plugins/design-to-components/README_CN.md b/external_plugins/design-to-components/README_CN.md new file mode 100644 index 00000000..7cb55710 --- /dev/null +++ b/external_plugins/design-to-components/README_CN.md @@ -0,0 +1,48 @@ +# 设计稿转组件库 + +把设计稿或截图做成 **React 组件库**。面板里维护设计变量和组件清单,Agent 编写 TSX 组件,插件负责类型检查,把每种状态渲染出来与设计稿并排对照,并生成可交互的组件目录页。 + +## 功能 + +- **设计变量**(`dc_tokens`):颜色、字体、字号、圆角、间距、阴影都存在 `tokens.json` 里。插件据此生成 `tokens.css`(`--color-primary`、`--font-size-md`、`--radius-md`、`--space-4` 等)和带类型的 `tokens.ts`。面板里可以用取色器直接修改。 +- **组件清单**(`dc_plan`):列出每个组件需要的状态(例如 Button:primary、secondary、disabled、loading)。面板显示哪些已经写好、能否编译(✓ / ✗ / ○)。 +- **组件**(`dc_write`):`src/<名称>.tsx`(可配 `src/<名称>.css`)。每个文件导出组件本身和 `examples`,每种状态一个示例。文件都直接放在 `src/`;写成 `src/components/<名称>/<名称>.tsx` 也可以,会自动平铺。 +- **每次写入都会检查**: + - **TypeScript strict** 类型检查(使用 React 19 类型)。 + - 用 esbuild 打包:只能引用 `react` / `react-dom` 和组件库里的文件。 + - 渲染每个示例,渲染出错会直接显示。 + - 必须有同名导出;清单里每种状态都要有对应示例。 + - 提示应该改用设计变量的**写死颜色**。 +- **预览**:每个示例都用真实 CSS 渲染,与设计稿并排显示。 +- **组件目录页**:`catalog/index.html` 是一个自包含的交互页面(用 esbuild-wasm 把 React 和你的组件打包在一起),通过 `file://` 直接打开也能用。另外生成 `index.ts`,统一导出所有组件。 + +## 用法 + +在 ZCode Desktop 里对 Agent 说: + +- “按这张设计稿做一套 React 组件” +- “把截图里的颜色和字号整理成设计变量” +- “给按钮加一个加载状态并检查能否编译” + +在自己的项目(React 18/19)里使用:复制 `src/`、`tokens.css`、`tokens.ts` 和 `index.ts`,在入口处引入一次 `tokens.css`,CSS 文件交给打包工具(Vite、Next 等)处理。 + +## 工具 + +| 工具 | 作用 | +|---|---| +| `dc_new` | 新建组件库(生成设计变量文件和 README),关联设计稿 | +| `dc_tokens` | 设置或删除设计变量,重新生成 tokens.css / tokens.ts | +| `dc_plan` | 组件清单及每个组件需要的状态 | +| `dc_write` | 写入或删除组件文件,并重新构建 | +| `dc_build` | 类型检查、渲染示例、重新生成组件目录页 | + +## 范围(v0.1) + +- 只支持 React + TypeScript,样式用普通 CSS 文件;不支持 Vue,不接入 Figma,也不配置 Tailwind 或 CSS-in-JS。 +- 组件只能引用 React 和组件库里的文件;第三方 UI 库在预览中不可用。 +- 面板里的预览是静态的(每种状态单独写一个示例)。悬停、聚焦、输入等交互可以在 `catalog/index.html` 里试。 + +## 隐私、网络和文件 + +- 本地运行,不联网,不需要 API 密钥。esbuild(WebAssembly 版)、TypeScript 和 React 类型声明都随插件附带。 +- 只写 `ui-kit/<名称>/` 和 `.design-to-components/project.json`。 diff --git a/external_plugins/design-to-components/skills/design-to-components/SKILL.md b/external_plugins/design-to-components/skills/design-to-components/SKILL.md new file mode 100644 index 00000000..7b113aa9 --- /dev/null +++ b/external_plugins/design-to-components/skills/design-to-components/SKILL.md @@ -0,0 +1,20 @@ +--- +name: design-to-components +description: 按设计稿/截图做 React 组件库:整理设计变量(tokens.css / tokens.ts)、列组件清单与状态、写 TSX 组件,插件做 TypeScript 检查、渲染每个状态与设计稿对照、生成可交互目录页。用户提到“设计稿转组件 / 组件库 / design system / 设计变量 / React 组件”时使用。 +--- + +# 设计稿转组件库(React + TSX) + +1. 看设计稿,整理出: + - 颜色(主色、主色上的文字色、背景、次级背景、文字、次要文字、边框,以及危险、成功、警告等状态色)。 + - 字体、字号阶梯、圆角、间距和阴影。 +2. 用 `dc_new(name, design, tokens)` 新建组件库,或用 `dc_tokens({tokens})` 补全设计变量。变量名只用小写字母、数字和短横线。 +3. 用 `dc_plan({components})` 列出组件,每个组件写出需要的状态,例如 Button:primary、secondary、disabled、loading。 +4. 用 `dc_write({files})` 写组件,可以一次写多个。文件都平铺在 `src/`(如 `src/Button.tsx`、`src/Button.css`);写成 `src/components/Button/Button.tsx` 也会被自动平铺到 `src/Button.tsx` 并修正导入: + - `Name.tsx`:`export function Name(props)`。props 要有类型,并按需扩展原生属性,例如 `ButtonHTMLAttributes`。 + - 同一个文件里写 `export const examples = [{ name: "Primary", render: () => }, …]`。每种计划中的状态都要有一个示例,示例名里要包含状态名。 + - `Name.css`:类名加前缀(例如 `fn-button`)。颜色、字号、圆角、间距一律用 `var(--color-…)`、`var(--font-size-…)`、`var(--radius-…)`、`var(--space-…)`,不要写死颜色。 + - 只能引用 `react` 和组件库里的文件(例如 `./Button`、`../tokens`)。 + - 注意无障碍:`label` 关联 `input`,出错时设置 `aria-invalid`,加载中设置 `aria-busy`,按钮用 `; }\n' }, join(DIST, "types")); + expect(ok).toEqual([]); + const bad = typecheck({ "src/A.tsx": 'export function A({ n }: { n: number }) { return
{n.toFixed()}
; }\nexport const x = ;\n' }, join(DIST, "types")); + expect(bad.map((i) => i.line)).toEqual([1, 2]); + expect(bad[0].message).toMatch(/onClik/); + }); +}); + +describe("tools", () => { + it("builds the Fieldnote kit from a bad draft to a clean catalog", async () => { + const n = await call("dc_new", { name: "Fieldnote UI", design: ["design/fieldnote-design.png"], tokens: JSON.parse(await A("tokens.json")) }); + expect(n.isError).toBeFalsy(); + expect(await readFile(join(ws, "ui-kit/fieldnote-ui/tokens.css"), "utf8")).toContain("--color-primary: #1f6f5c;"); + await call("dc_plan", { components: [{ name: "Button", states: ["primary", "secondary", "disabled", "loading"] }, { name: "TextField", states: ["default", "error"] }, { name: "Badge", states: ["success", "warning", "neutral"] }, { name: "Card", states: [] }] }); + expect((await call("dc_plan", { components: [{ name: "price-tag", states: [] }] })).content[0].text).toMatch(/PascalCase/); + const d = await call("dc_write", { files: { "Button.tsx": await A("Button.first-draft.tsx"), "Button.css": await A("Button.css") } }); + const msgs = d.structuredContent.issues.map((i: any) => `${i.severity}:${i.source}:${i.line ?? ""}`); + expect(msgs).toEqual(expect.arrayContaining(["error:typescript:5", "error:typescript:8", "warning:check:5"])); + expect(d.content[0].text).toMatch(/No example for the planned state “loading”/); + expect(d.content[0].text).toMatch(/Hard-coded colour #1f6f5c/); + const files: Record = {}; + for (const f of ["Button", "TextField", "Badge", "Card"]) for (const e of ["tsx", "css"]) files[`${f}.${e}`] = await A(`${f}.${e}`); + const w = await call("dc_write", { files }); + expect(w.structuredContent.issues).toEqual([]); + expect(w.structuredContent.plan.map((p: any) => `${p.name}:${p.status}:${p.examples}`)).toEqual(["Button:done:4", "TextField:done:2", "Badge:done:3", "Card:done:2"]); + const pv: string = w.structuredContent.preview; + expect(pv).toContain(''); + expect(pv).toMatch(/aria-busy="true"/); + expect(pv).toContain('aria-invalid="true"'); + expect(pv).toContain(".fn-badge--success{"); + const cat = await readFile(join(ws, "ui-kit/fieldnote-ui/catalog/index.html"), "utf8"); + expect(cat).toContain("globalThis.__dc"); + expect(cat).toContain("--color-primary: #1f6f5c;"); + expect(await readFile(join(ws, "ui-kit/fieldnote-ui/index.ts"), "utf8")).toContain('export { TextField } from "./src/TextField";'); + }); + it("reports render errors, bad imports and missing exports; updates tokens", async () => { + const r = await call("dc_write", { files: { "Broken.tsx": 'import x from "lodash";\nexport const y = x;\nexport const examples = [];\n' } }); + expect(r.content[0].text).toMatch(/Package “lodash” is not available/); + const t = await call("dc_write", { files: { "Broken.tsx": 'export function Broken(): JSX.Element { throw new Error("boom"); }\nexport const examples = [{ name: "Default", render: () => }];\n' } }); + expect(t.content[0].text).toMatch(/Example “Default” failed to render: boom/); + const m = await call("dc_write", { files: { "Broken.tsx": "export const examples = [];\n" } }); + expect(m.content[0].text).toMatch(/must export a component named Broken/); + expect((await call("dc_write", { files: {}, delete: ["Broken.tsx"] })).structuredContent.issues).toEqual([]); + expect((await call("dc_write", { files: { "../evil.ts": "x" } })).content[0].text).toMatch(/bad_path/); + const tk = await call("dc_tokens", { tokens: { colors: { primary: "#0b5d4b" } } }); + expect(tk.structuredContent.preview).toContain("--color-primary: #0b5d4b;"); + expect((await call("dc_tokens", { tokens: { colors: { primary: "green-ish" } } })).content[0].text).toMatch(/not a colour/); + }); +}); diff --git a/ui-plugins/design-to-components/test/workspace-links.test.ts b/ui-plugins/design-to-components/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/design-to-components/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); diff --git a/ui-plugins/design-to-components/tsconfig.json b/ui-plugins/design-to-components/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/design-to-components/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/design-to-components/ui/env.d.ts b/ui-plugins/design-to-components/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/design-to-components/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/design-to-components/ui/kit.css b/ui-plugins/design-to-components/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/design-to-components/ui/kit.css @@ -0,0 +1,34 @@ +:root { --bg:#fff; --fg:#1d1f23; --muted:#6b7280; --line:#e5e7eb; --panel:#f7f7f8; --accent:#2563eb; --warn:#b45309; --warnbg:#fef3c7; --bad:#b91c1c; --badbg:#fee2e2; --okbg:#dcfce7; --ok:#15803d; } +[data-theme="dark"] { --bg:#18191b; --fg:#e8e8ea; --muted:#9ca3af; --line:#2e3035; --panel:#222327; --accent:#60a5fa; --warn:#fbbf24; --warnbg:#3b2f10; --bad:#f87171; --badbg:#3b1717; --okbg:#12301d; --ok:#4ade80; } +* { box-sizing: border-box; } +html, body { margin:0; background:var(--bg); color:var(--fg); font:13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; } +#root { padding: 12px; } +h1 { font-size: 15px; margin: 0 0 8px; } +h2 { font-size: 13px; margin: 14px 0 6px; color: var(--muted); font-weight: 600; text-transform: none; } +button { font: inherit; border:1px solid var(--line); background:var(--panel); color:var(--fg); border-radius:6px; padding:5px 10px; cursor:pointer; } +button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +button:disabled { opacity:.5; cursor:default; } +input, select, textarea { font: inherit; color: var(--fg); background: var(--bg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; } +input[type="color"] { padding: 0; width: 32px; height: 26px; } +input[type="range"] { padding: 0; } +label { display:flex; gap:6px; align-items:center; } +.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin: 6px 0; } +.muted { color: var(--muted); } +.card { border:1px solid var(--line); border-radius:8px; padding:10px; background:var(--panel); margin: 8px 0; } +.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:8px; } +.thumb { border:1px solid var(--line); border-radius:6px; overflow:hidden; background: var(--bg); cursor:pointer; position:relative; } +.thumb img { width:100%; display:block; aspect-ratio:1; object-fit:contain; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; } +.thumb .cap { padding:4px 6px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +.thumb.selected { outline: 2px solid var(--accent); } +.badge { display:inline-block; font-size:11px; padding:1px 6px; border-radius:10px; background:var(--warnbg); color:var(--warn); } +.badge.bad { background: var(--badbg); color: var(--bad); } +.badge.ok { background: var(--okbg); color: var(--ok); } +table.data { border-collapse: collapse; width: 100%; } +table.data td, table.data th { border:1px solid var(--line); padding:3px 6px; text-align:left; vertical-align:top; } +table.data th { background: var(--panel); } +.toast { position: fixed; right: 12px; bottom: 12px; padding: 8px 12px; border-radius: 6px; background: var(--okbg); color: var(--ok); z-index: 10; max-width: 80%; } +.toast.error { background: var(--badbg); color: var(--bad); } +.empty { padding: 24px; text-align:center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; } +.busy { opacity:.6; pointer-events:none; } +.split { display:grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 10px; } +@media (max-width: 640px) { .split { grid-template-columns: 1fr; } } diff --git a/ui-plugins/design-to-components/ui/kit.ts b/ui-plugins/design-to-components/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/design-to-components/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call>(name: string, args: Record = {}, timeout = 300_000): Promise { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h( + tag: K, + props: Record = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/design-to-components/ui/main.ts b/ui-plugins/design-to-components/ui/main.ts new file mode 100644 index 00000000..a571d8a9 --- /dev/null +++ b/ui-plugins/design-to-components/ui/main.ts @@ -0,0 +1,92 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast, updateContext } from "./kit.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +type Group = "colors" | "fonts" | "fontSizes" | "radii" | "spacing" | "shadows"; +const GROUPS: Group[] = ["colors", "fontSizes", "radii", "spacing", "fonts", "shadows"]; +interface Issue { file: string; line?: number; message: string; severity: "error" | "warning"; source: string } +interface View { kind: "kit"; project: { kits: { slug: string; name: string }[] }; kit: { slug: string; name: string; dir: string; design: string[] }; tokens: Record>; tokenIssues: { group: string; key: string; message: string }[]; plan: { name: string; description?: string; states: string[]; status: string; examples: number }[]; components: { name: string; examples: string[] }[]; issues: Issue[]; preview: string; files: string[]; catalog: string | null } +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const GNAME: Record = { colors: ["颜色", "Colours"], fontSizes: ["字号", "Font sizes"], radii: ["圆角", "Radii"], spacing: ["间距", "Spacing"], fonts: ["字体", "Fonts"], shadows: ["阴影", "Shadows"] }; +const root = document.getElementById("root")!; +const state: { v?: View; images: string[]; design: Record; edit?: Record>; showDesign: boolean; tab: "preview" | "code"; file?: string; code?: string; newName: string; newDesign: Set } = { images: [], design: {}, showDesign: true, tab: "preview", newName: "", newDesign: new Set() }; + +async function busy(work: () => Promise): Promise { + root.classList.add("busy"); + try { return await work(); } catch (error) { toast(error instanceof Error ? error.message.replace(/^\[\w+\]\s*/, "") : String(error), "error"); return undefined; } finally { root.classList.remove("busy"); } +} +async function setView(v: View) { + state.v = v; state.edit = structuredClone(v.tokens); + for (const d of v.kit.design) if (!state.design[d]) { const r = await call<{ dataUrl: string }>("dc_design", { path: d }).catch(() => undefined); if (r) state.design[d] = r.dataUrl; } + if (state.file && v.files.includes(state.file)) state.code = (await call<{ text: string }>("dc_file", { path: state.file }).catch(() => ({ text: "" }))).text; + render(); + const e = v.issues.filter((i) => i.severity === "error").length; + void updateContext(`Component kit ${v.kit.dir}: ${v.components.map((c) => c.name).join(", ") || "no components"}; ${e} errors, ${v.issues.length - e} warnings.`).catch(() => undefined); +} +onToolResult((v) => { if (v?.kind === "kit") void setView(v as unknown as View); }); + +const create = async () => { + if (!state.newName.trim()) { toast(T("请填写名称", "Enter a name"), "error"); return; } + const r = await busy(() => call("dc_new", { name: state.newName.trim(), design: [...state.newDesign] })); + if (r) await setView(r); +}; +const saveTokens = async () => { + const r = await busy(() => call("dc_tokens", { tokens: state.edit })); + if (r) { await setView(r); toast(T("设计变量已保存", "Tokens saved")); } +}; +const openFile = async (f: string) => { state.file = f; state.tab = "code"; state.code = (await call<{ text: string }>("dc_file", { path: f }).catch(() => ({ text: "" }))).text; render(); }; + +function tokenEditor(v: View) { + const e = state.edit!; + return h("div", { class: "card tokens" }, h("div", { class: "row" }, h("b", {}, T("设计变量", "Tokens")), h("span", { class: "grow" }), h("button", { class: "primary", onclick: () => void saveTokens() }, T("保存", "Save"))), + ...GROUPS.filter((g) => Object.keys(e[g] ?? {}).length).map((g) => h("div", { class: "tg" }, h("div", { class: "tgn" }, GNAME[g][locale() === "zh" ? 0 : 1]), + ...Object.entries(e[g]).map(([k, val]) => h("div", { class: "tok" }, + g === "colors" ? h("input", { type: "color", value: /^#[0-9a-f]{6}$/i.test(val) ? val : "#000000", "data-token": `${g}.${k}`, oninput: (ev: Event) => { e[g][k] = (ev.target as HTMLInputElement).value; const t = (ev.target as HTMLElement).parentElement!.querySelector("input.tv") as HTMLInputElement; t.value = e[g][k]; } }) : null, + h("span", { class: "tk" }, k), + h("input", { class: "tv", value: val, oninput: (ev: Event) => { e[g][k] = (ev.target as HTMLInputElement).value; } }))))), + ...v.tokenIssues.map((t) => h("div", { class: "issue error" }, `${t.group}.${t.key}: ${t.message}`))); +} + +function render() { + applyTheme(); + const v = state.v; + if (!v) { + put(root, h("div", { class: "card" }, h("b", {}, T("新建组件库", "New component kit")), + h("div", { class: "row" }, h("label", {}, T("名称 ", "Name "), h("input", { class: "name", value: state.newName, oninput: (e: Event) => { state.newName = (e.target as HTMLInputElement).value; } }))), + h("div", {}, T("设计稿:", "Design images:")), + h("div", { class: "flist" }, ...state.images.map((f) => h("label", {}, h("input", { type: "checkbox", checked: state.newDesign.has(f), onchange: (e: Event) => { (e.target as HTMLInputElement).checked ? state.newDesign.add(f) : state.newDesign.delete(f); } }), f))), + h("div", { class: "row" }, h("button", { class: "primary", onclick: () => void create() }, T("创建", "Create")))), + h("div", { class: "empty" }, T("也可以对 Agent 说:“按这张设计稿做一套 React 组件”。", "Or ask the agent: “build React components from this design”."))); + return; + } + const errors = v.issues.filter((i) => i.severity === "error").length, warns = v.issues.length - errors; + const top = h("div", { class: "top" }, h("b", {}, v.kit.name), h("span", { class: "muted" }, v.kit.dir), h("span", { class: "grow" }), + h("span", { class: `badge ${errors ? "bad" : "ok"}` }, errors ? T(`${errors} 个错误`, `${errors} errors`) : T("编译通过", "Compiles")), warns ? h("span", { class: "badge" }, T(`${warns} 个提醒`, `${warns} warnings`)) : null, + v.kit.design.length ? h("label", { class: "chk" }, h("input", { type: "checkbox", checked: state.showDesign, onchange: (e: Event) => { state.showDesign = (e.target as HTMLInputElement).checked; render(); } }), T("对照设计稿", "Show design")) : null, + h("button", { onclick: async () => { const r = await busy(() => call("dc_build", {})); if (r) await setView(r); } }, T("重新构建", "Rebuild"))); + const plan = h("div", { class: "card" }, h("b", {}, T("组件清单", "Components")), + v.plan.length || v.components.length ? h("table", { class: "data plan" }, ...[...v.plan, ...v.components.filter((c) => !v.plan.some((p) => p.name === c.name)).map((c) => ({ name: c.name, states: [] as string[], status: "done", examples: c.examples.length, description: "" }))].map((p) => + h("tr", {}, h("td", {}, h("span", { class: `st ${p.status}` }, p.status === "done" ? "✓" : p.status === "error" ? "✗" : "○"), " ", v.files.includes(`src/${p.name}.tsx`) ? h("a", { href: "#", onclick: (e: Event) => { e.preventDefault(); void openFile(`src/${p.name}.tsx`); } }, p.name) : p.name), + h("td", { class: "muted" }, p.states.join(" · ") || "—"), h("td", { class: "num" }, T(`${p.examples} 个示例`, `${p.examples} examples`))))) : h("div", { class: "muted" }, T("还没有组件。", "No components yet."))); + const issues = v.issues.length ? h("div", { class: "card" }, h("b", {}, T("问题", "Problems")), ...v.issues.map((i) => h("div", { class: `issue ${i.severity}` }, + h("span", { class: "src" }, i.source), i.file ? h("a", { href: "#", onclick: (e: Event) => { e.preventDefault(); void openFile(i.file); } }, `${i.file}${i.line ? `:${i.line}` : ""}`) : null, " ", i.message))) : null; + const tabs = h("div", { class: "tbar" }, h("button", { class: `tab${state.tab === "preview" ? " on" : ""}`, onclick: () => { state.tab = "preview"; render(); } }, T("组件预览", "Preview")), + ...v.files.map((f) => h("button", { class: `tab${state.tab === "code" && state.file === f ? " on" : ""}`, onclick: () => void openFile(f) }, f.replace(/^src\//, "")))); + const main = state.tab === "preview" ? h("iframe", { class: "pv", sandbox: "", title: "preview", srcdoc: v.preview }) : h("pre", { class: "code" }, state.code ?? ""); + const design = state.showDesign && v.kit.design.length ? h("div", { class: "design" }, ...v.kit.design.map((d) => state.design[d] ? h("img", { src: state.design[d], alt: d }) : h("div", {}, d))) : null; + put(root, top, h("div", { class: `layout${design ? " wd" : ""}` }, design, h("div", { class: "center" }, tabs, main, + v.catalog ? h("div", { class: "small muted" }, T(`可交互的组件目录:${v.catalog}(在浏览器中打开)`, `Interactive catalog: ${v.catalog} (open in a browser)`)) : null), + h("div", { class: "side" }, plan, issues, tokenEditor(v)))); +} + +onHostContext(() => render()); +render(); +void initHost("design-to-components", "0.1.0").then(async () => { + state.images = (await call<{ files: string[] }>("workspace_images").catch(() => ({ files: [] }))).files; + const st = await call>("dc_state", {}).catch(() => undefined); + if (st?.kind === "kit") await setView(st as unknown as View); else render(); +}); diff --git a/ui-plugins/design-to-components/ui/panel.css b/ui-plugins/design-to-components/ui/panel.css new file mode 100644 index 00000000..8e141b21 --- /dev/null +++ b/ui-plugins/design-to-components/ui/panel.css @@ -0,0 +1,21 @@ +.top { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-bottom:8px; } .grow { flex:1; } +.chk { margin-left:6px; } +.layout { display:grid; grid-template-columns: minmax(0,1.6fr) minmax(300px,1fr); gap:10px; } +.layout.wd { grid-template-columns: minmax(0,1fr) minmax(0,1.4fr) minmax(300px,1fr); } +.design { max-height: 82vh; overflow:auto; border:1px solid var(--line); border-radius:6px; } .design img { width:100%; display:block; } +.center { min-width:0; display:flex; flex-direction:column; gap:6px; } +iframe.pv { width:100%; height:78vh; border:1px solid var(--line); border-radius:6px; background:#fff; } +pre.code { height:78vh; overflow:auto; margin:0; background: var(--panel); border-radius:6px; padding:10px; font-size:12px; } +.tbar { display:flex; gap:2px; flex-wrap:wrap; } .tab { border:none; border-bottom:2px solid transparent; border-radius:0; background:none; font-size:12px; padding:4px 8px; } +.tab.on { border-bottom-color: var(--accent); color: var(--accent); } +.side { min-width:0; max-height: 84vh; overflow:auto; } +.plan td { vertical-align: middle; } .st.done { color: var(--ok); } .st.error { color: var(--bad); } .st.todo { color: var(--muted); } +td.num { white-space:nowrap; color: var(--muted); font-size:12px; } +.issue { font-size:12px; margin:3px 0; } .issue .src { font-size:10px; border:1px solid var(--line); border-radius:4px; padding:0 4px; margin-right:4px; color: var(--muted); } +.issue.error a { color: var(--bad); } .issue.warning a { color: var(--warn); } +.tg { margin:6px 0; } .tgn { font-size:12px; font-weight:600; color: var(--muted); margin-bottom:3px; } +.tok { display:grid; grid-template-columns: 30px 110px minmax(0,1fr); gap:6px; align-items:center; margin:2px 0; } +.tok .tk { font-family: ui-monospace, monospace; font-size:12px; grid-column: 2; } .tok input.tv { grid-column: 3; font-size:12px; } +.tok input[type=color] { grid-column: 1; width:28px; height:22px; } +.flist { display:flex; flex-wrap:wrap; gap:4px 14px; margin:6px 0; } input.name { width:240px; } +.small { font-size:12px; } diff --git a/ui-plugins/design-to-components/vitest.config.ts b/ui-plugins/design-to-components/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/design-to-components/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } });