From e2601b5efb0642edca4d0f155806747ff26a5882 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:28:57 +0800 Subject: [PATCH 01/10] feat(ui-plugins): add Design To Components (design-to-components) --- marketplace.json | 50 ++++++++++++++++ pnpm-lock.yaml | 153 +++++++++++++++++++++++++++++++++-------------- 2 files changed, 159 insertions(+), 44 deletions(-) diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..ba01dfbb 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,56 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "design-to-components", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/design-to-components", + "displayName": "Design To Components", + "displayName_i18n": { + "en": "Design To Components", + "zh-CN": "设计稿转组件库" + }, + "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。会提示写死的颜色和缺少的状态示例。全部在本地完成。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "developer-tools", + "keywords": [ + "react", + "components", + "design system", + "design tokens", + "tsx", + "typescript", + "storybook", + "esbuild", + "组件库", + "设计稿", + "设计变量", + "前端" + ], + "examplePrompts": [ + "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" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "按这张设计稿做一套 React 组件", + "把截图里的颜色和字号整理成设计变量", + "给按钮加一个加载状态并检查能否编译" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..2b331984 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,7 +13,7 @@ importers: version: 2.0.0 '@modelcontextprotocol/ext-apps': specifier: 2.0.0 - version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.5) '@modelcontextprotocol/sdk': specifier: 1.29.0 version: 1.29.0(zod@4.6.5) @@ -48,6 +48,52 @@ importers: ui-plugins/deckcraft: {} + ui-plugins/design-to-components: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + '@types/react': + specifier: 19.3.1 + version: 19.3.1 + esbuild-wasm: + specifier: 0.28.2 + version: 0.28.2 + react: + specifier: 19.3.1 + version: 19.3.1 + react-dom: + specifier: 19.3.1 + version: 19.3.1(react@19.3.1) + typescript: + specifier: 6.0.2 + version: 6.0.2 + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + '@types/react-dom': + specifier: 19.3.0 + version: 19.3.0(@types/react@19.3.1) + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + ui-plugins/designcraft: {} ui-plugins/excalidraw: @@ -160,7 +206,7 @@ importers: version: 2.0.0 '@modelcontextprotocol/ext-apps': specifier: 2.0.0 - version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.5) '@modelcontextprotocol/sdk': specifier: 1.29.0 version: 1.29.0(zod@4.6.5) @@ -212,7 +258,7 @@ importers: version: 2.0.0 '@modelcontextprotocol/ext-apps': specifier: 2.0.0 - version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.5) bun: specifier: 1.3.11 version: 1.3.11 @@ -1892,9 +1938,17 @@ packages: peerDependencies: '@types/react': ^19.2.0 + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + '@types/react@19.3.1': + resolution: {integrity: sha512-HNTkBIm8zmHX8LUXX2vtZ/ONzehrV1J3abl2fUIiZ5qxTYRCj/z+rDeFwOltqCLl9lRdUTKWT41OLtYuFV/Arg==} + '@types/statuses@2.0.6': resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==} @@ -2448,6 +2502,11 @@ packages: resolution: {integrity: sha512-VHErXfzR/6r/+yyzPKeBvO0lgjfC5cbDCQWjWwMZWSb6YU39TGIl51OUmCfWCq4ylMdJSB8zkz2vIuIeIxXApA==} engines: {node: '>=0.10.0'} + esbuild-wasm@0.28.2: + resolution: {integrity: sha512-GccVwhv3mmOUVQHCQm2Ox/rby8n/EqUwvZxE6Pjfikrq/lWw9g9WX/u9EykWnpot3Ko6j426DgQdea2xWKIAQA==} + engines: {node: '>=18'} + hasBin: true + esbuild@0.25.12: resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} engines: {node: '>=18'} @@ -2475,10 +2534,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2769,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -3068,10 +3120,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3156,6 +3204,11 @@ packages: peerDependencies: react: ^19.2.7 + react-dom@19.3.1: + resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==} + peerDependencies: + react: ^19.3.1 + react-remove-scroll-bar@2.3.8: resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==} engines: {node: '>=10'} @@ -3190,6 +3243,10 @@ packages: resolution: {integrity: sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==} engines: {node: '>=0.10.0'} + react@19.3.1: + resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} + engines: {node: '>=0.10.0'} + readable-stream@2.3.8: resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} @@ -3258,6 +3315,9 @@ packages: scheduler@0.27.0: resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} + scheduler@0.28.0: + resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + send@1.2.1: resolution: {integrity: sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==} engines: {node: '>= 18'} @@ -3383,18 +3443,10 @@ packages: tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3794,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -4276,6 +4328,17 @@ snapshots: react: 19.2.7 react-dom: 19.2.7(react@19.2.7) + '@modelcontextprotocol/ext-apps@2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(zod@4.6.5)': + dependencies: + '@modelcontextprotocol/client': 2.2.0 + '@modelcontextprotocol/core': 2.0.0 + '@standard-schema/spec': 1.1.0 + zod: 4.6.5 + optionalDependencies: + '@modelcontextprotocol/server': 2.0.0 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + '@modelcontextprotocol/sdk@1.29.0(zod@4.6.5)': dependencies: '@hono/node-server': 1.19.14(hono@4.12.12) @@ -4285,11 +4348,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -5125,10 +5188,18 @@ snapshots: dependencies: '@types/react': 19.2.14 + '@types/react-dom@19.3.0(@types/react@19.3.1)': + dependencies: + '@types/react': 19.3.1 + '@types/react@19.2.14': dependencies: csstype: 3.2.3 + '@types/react@19.3.1': + dependencies: + csstype: 3.2.3 + '@types/statuses@2.0.6': optional: true @@ -5737,6 +5808,8 @@ snapshots: es6-promise-pool@2.5.0: {} + esbuild-wasm@0.28.2: {} + esbuild@0.25.12: optionalDependencies: '@esbuild/aix-ppc64': 0.25.12 @@ -5809,13 +5882,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5940,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6115,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6406,8 +6471,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6495,6 +6558,11 @@ snapshots: react: 19.2.7 scheduler: 0.27.0 + react-dom@19.3.1(react@19.3.1): + dependencies: + react: 19.3.1 + scheduler: 0.28.0 + react-remove-scroll-bar@2.3.8(@types/react@19.2.14)(react@19.2.7): dependencies: react: 19.2.7 @@ -6524,6 +6592,8 @@ snapshots: react@19.2.7: {} + react@19.3.1: {} + readable-stream@2.3.8: dependencies: core-util-is: 1.0.3 @@ -6632,6 +6702,8 @@ snapshots: scheduler@0.27.0: {} + scheduler@0.28.0: {} + send@1.2.1: dependencies: debug: 4.4.3 @@ -6745,7 +6817,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6779,15 +6851,8 @@ snapshots: tinybench@2.9.0: {} - tinyexec@1.1.1: {} - tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) From c44a07b823edb6bd5abd537d32b9e89d23c11a60 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:29:31 +0800 Subject: [PATCH 02/10] feat(ui-plugins): add Design To Components (design-to-components) --- external_plugins/design-to-components/LICENSE | 21 ++++++++ .../design-to-components/README.md | 48 +++++++++++++++++++ .../design-to-components/README_CN.md | 48 +++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 external_plugins/design-to-components/LICENSE create mode 100644 external_plugins/design-to-components/README.md create mode 100644 external_plugins/design-to-components/README_CN.md 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`。 From 45c13438dd017bb1156e36c94a24dbdc269a146b Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:30:05 +0800 Subject: [PATCH 03/10] feat(ui-plugins): add Design To Components (design-to-components) --- ui-plugins/design-to-components/package.json | 38 +++++++++++++++++++ ui-plugins/design-to-components/tsconfig.json | 14 +++++++ .../design-to-components/vitest.config.ts | 2 + 3 files changed, 54 insertions(+) create mode 100644 ui-plugins/design-to-components/package.json create mode 100644 ui-plugins/design-to-components/tsconfig.json create mode 100644 ui-plugins/design-to-components/vitest.config.ts diff --git a/ui-plugins/design-to-components/package.json b/ui-plugins/design-to-components/package.json new file mode 100644 index 00000000..6d6c0de8 --- /dev/null +++ b/ui-plugins/design-to-components/package.json @@ -0,0 +1,38 @@ +{ + "name": "@penova/plugin-design-to-components", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "Design To Components" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5", + "react": "19.3.1", + "react-dom": "19.3.1", + "@types/react": "19.3.1", + "esbuild-wasm": "0.28.2", + "typescript": "6.0.2" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4", + "@types/react-dom": "19.3.0" + } +} 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/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 } }); From 8d74729bd2a0119508e8e568f3cedeeff7d34766 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:30:38 +0800 Subject: [PATCH 04/10] feat(ui-plugins): add Design To Components (design-to-components) --- .../.zcode-plugin/plugin.json | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 external_plugins/design-to-components/.zcode-plugin/plugin.json 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" + } + ] + } +} From 376c915ad2db8f2ce1d0bf59013e8c4b17363ac6 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:31:13 +0800 Subject: [PATCH 05/10] feat(ui-plugins): add Design To Components (design-to-components) --- .../design-to-components/scripts/build.mjs | 85 +++++++++ .../design-to-components/scripts/e2e.mts | 70 ++++++++ .../design-to-components/scripts/harness.mjs | 162 ++++++++++++++++++ .../design-to-components/scripts/licenses.mjs | 43 +++++ 4 files changed, 360 insertions(+) create mode 100644 ui-plugins/design-to-components/scripts/build.mjs create mode 100644 ui-plugins/design-to-components/scripts/e2e.mts create mode 100644 ui-plugins/design-to-components/scripts/harness.mjs create mode 100644 ui-plugins/design-to-components/scripts/licenses.mjs diff --git a/ui-plugins/design-to-components/scripts/build.mjs b/ui-plugins/design-to-components/scripts/build.mjs new file mode 100644 index 00000000..6d855bc4 --- /dev/null +++ b/ui-plugins/design-to-components/scripts/build.mjs @@ -0,0 +1,85 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + external: ["esbuild-wasm"], + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url); import { fileURLToPath as __fu } from "node:url"; import { dirname as __dn } from "node:path"; const __filename=__fu(import.meta.url); const __dirname=__dn(__filename);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +// 组件目录页用的 React(浏览器、生产模式)、esbuild-wasm 整包、TypeScript 标准库和 React 类型声明。 +const vendor = await build({ entryPoints: [join(root, "src/vendor-entry.ts")], outfile: join(dist, "vendor/react.js"), bundle: true, format: "iife", platform: "browser", minify: true, metafile: true, legalComments: "none", define: { "process.env.NODE_ENV": '"production"' } }); +const nm = (p) => join(root, "node_modules", p); +await cp(nm("esbuild-wasm"), join(dist, "node_modules/esbuild-wasm"), { recursive: true, dereference: true, filter: (p) => !/esbuild-wasm[\\/](esm|lib[\\/]browser)/.test(p) }); +await mkdir(join(dist, "types/ts-lib"), { recursive: true }); +for (const f of (await import("node:fs")).readdirSync(nm("typescript/lib"))) if (/^lib\..*\.d\.ts$/.test(f)) await copyFile(nm(`typescript/lib/${f}`), join(dist, "types/ts-lib", f)); +await cp(nm("@types/react"), join(dist, "types/react"), { recursive: true, dereference: true, filter: (p) => !/ts5\.0/.test(p) }); +const csstype = join(dirname(dirname((await import("node:fs")).realpathSync(nm("@types/react")))), "csstype"); +await cp(csstype, join(dist, "types/csstype"), { recursive: true, dereference: true }); + +await writeNotices([ui.metafile, server.metafile, vendor.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/design-to-components/scripts/e2e.mts b/ui-plugins/design-to-components/scripts/e2e.mts new file mode 100644 index 00000000..bdf7739c --- /dev/null +++ b/ui-plugins/design-to-components/scripts/e2e.mts @@ -0,0 +1,70 @@ +// 浏览器端到端测试:真实打包的 server(esbuild-wasm + TypeScript + React SSR)+ 官方 AppBridge 宿主 + 隔离 iframe 中的面板; +// 再用 Chrome 以 file:// 打开生成的交互式组件目录页。需要 Chrome。 +import assert from "node:assert/strict"; +import { cp, mkdir, mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "design-to-components-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "dc-e2e-")); +const samples = process.env.DC_SAMPLES ?? "/workspace/zcode-new-plugins/samples/components"; +await cp(samples, join(workspace, "设计稿"), { recursive: true }); +const A = (f: string) => readFile(join(samples, "agent", f), "utf8"); +const harness = await startHarness({ workspace }); +const step = (t: string) => process.stdout.write(`• ${t}\n`); +try { + const { outer, frame, context } = await harness.open("?locale=zh-CN", { width: 1500, height: 1000 }); + step("user creates the kit from the design"); + await frame.locator("input.name").fill("Fieldnote UI"); + await frame.locator("label", { hasText: "fieldnote-design.png" }).locator("input").check(); + await frame.locator("button", { hasText: "创建" }).click(); + await frame.locator(".design img").waitFor({ timeout: 30_000 }); + step("agent reads the tokens and component list off the design, writes a first Button"); + await harness.agent(outer, "dc_tokens", { tokens: JSON.parse(await A("tokens.json")) }); + await harness.agent(outer, "dc_plan", { components: [{ name: "Button", states: ["primary", "secondary", "disabled", "loading"] }, { name: "TextField", states: ["default", "error"] }, { name: "Badge", states: ["success", "warning", "neutral"] }, { name: "Card", states: [] }] }); + await harness.agent(outer, "dc_write", { files: { "Button.tsx": await A("Button.first-draft.tsx"), "Button.css": await A("Button.css") } }); + await frame.locator(".badge.bad", { hasText: "2 个错误" }).waitFor({ timeout: 60_000 }); + await frame.locator(".issue.error", { hasText: "onClik" }).waitFor(); + await frame.locator(".issue a", { hasText: "src/Button.tsx:5" }).first().click(); + await frame.locator("pre.code", { hasText: "onClik" }).waitFor(); + await outer.screenshot({ path: join(shots, "02-type-errors.png") }); + step("agent writes all four components; preview renders every state"); + const files: Record = {}; + for (const f of ["Button", "TextField", "Badge", "Card"]) for (const e of ["tsx", "css"]) files[`${f}.${e}`] = await A(`${f}.${e}`); + await harness.agent(outer, "dc_write", { files }); + await frame.locator(".badge.ok", { hasText: "编译通过" }).waitFor({ timeout: 60_000 }); + await frame.locator(".tab", { hasText: "组件预览" }).click(); + const pv = frame.frameLocator("iframe.pv"); + await pv.locator("button.fn-button--primary", { hasText: "Save entry" }).waitFor(); + await pv.locator(".fn-field--error small", { hasText: "Enter a valid email address" }).waitFor(); + assert.equal(await pv.locator("button.fn-button--primary").first().evaluate((b) => getComputedStyle(b).backgroundColor), "rgb(31, 111, 92)"); + assert.equal(await frame.locator(".plan .st.done").count(), 4); + await outer.screenshot({ path: join(shots, "01-design-vs-components.png") }); + step("user tweaks the primary colour token"); + await frame.locator('.tok:has(input[data-token="colors.primary"]) input.tv').fill("#0b4f8a"); + await frame.locator(".tokens button", { hasText: "保存" }).click(); + await frame.locator(".toast", { hasText: "设计变量已保存" }).waitFor({ timeout: 30_000 }); + assert.equal(await frame.frameLocator("iframe.pv").locator("button.fn-button--primary").first().evaluate((b) => getComputedStyle(b).backgroundColor), "rgb(11, 79, 138)"); + assert.match(await readFile(join(workspace, "ui-kit/fieldnote-ui/tokens.css"), "utf8"), /--color-primary: #0b4f8a;/); + step("the interactive catalog works from file://"); + const page = await context.newPage(); + const errs: string[] = []; + page.on("pageerror", (e) => errs.push(String(e))); + page.on("console", (m) => { if (m.type() === "error") errs.push(m.text()); }); + await page.setViewportSize({ width: 1200, height: 900 }); + await page.goto(pathToFileURL(join(workspace, "ui-kit/fieldnote-ui/catalog/index.html")).href); + await page.locator("#Card .fn-card h3", { hasText: "Coastal path" }).waitFor(); + await page.locator("#TextField input").first().fill("Evening swim"); + assert.equal(await page.locator("#TextField input").first().inputValue(), "Evening swim"); + await page.locator(".dc-head input[type=checkbox]").check(); + await page.locator(".dc-catalog.dc-dark").waitFor(); + await page.screenshot({ path: join(shots, "03-catalog.png"), fullPage: true }); + assert.deepEqual(errs, []); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} finally { + await harness.close(); +} diff --git a/ui-plugins/design-to-components/scripts/harness.mjs b/ui-plugins/design-to-components/scripts/harness.mjs new file mode 100644 index 00000000..a45e6e41 --- /dev/null +++ b/ui-plugins/design-to-components/scripts/harness.mjs @@ -0,0 +1,162 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: "chrome" }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/design-to-components/scripts/licenses.mjs b/ui-plugins/design-to-components/scripts/licenses.mjs new file mode 100644 index 00000000..5107fe7c --- /dev/null +++ b/ui-plugins/design-to-components/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name && pkg.version) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} From 6149979a3bbe573e07e81d8310d9061012353c81 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:31:52 +0800 Subject: [PATCH 06/10] feat(ui-plugins): add Design To Components (design-to-components) --- ui-plugins/design-to-components/src/bundle.ts | 88 +++++++ .../design-to-components/src/compile.ts | 35 +++ ui-plugins/design-to-components/src/main.ts | 14 + ui-plugins/design-to-components/src/server.ts | 246 ++++++++++++++++++ ui-plugins/design-to-components/src/tokens.ts | 48 ++++ .../design-to-components/src/vendor-entry.ts | 6 + 6 files changed, 437 insertions(+) create mode 100644 ui-plugins/design-to-components/src/bundle.ts create mode 100644 ui-plugins/design-to-components/src/compile.ts create mode 100644 ui-plugins/design-to-components/src/main.ts create mode 100644 ui-plugins/design-to-components/src/server.ts create mode 100644 ui-plugins/design-to-components/src/tokens.ts create mode 100644 ui-plugins/design-to-components/src/vendor-entry.ts diff --git a/ui-plugins/design-to-components/src/bundle.ts b/ui-plugins/design-to-components/src/bundle.ts new file mode 100644 index 00000000..31ad95de --- /dev/null +++ b/ui-plugins/design-to-components/src/bundle.ts @@ -0,0 +1,88 @@ +import { posix } from "node:path"; +import type { Plugin } from "esbuild-wasm"; +import type { CodeIssue } from "./compile.ts"; + +type Esbuild = typeof import("esbuild-wasm"); +let esb: Promise | undefined; +/** esbuild-wasm:插件包里附带 wasm 版本,不依赖用户电脑上的原生 esbuild。 */ +export const esbuild = () => (esb ??= import("esbuild-wasm").then((m) => (m as unknown as { default?: Esbuild }).default ?? m)); + +const REACT: Record = { + react: "module.exports = globalThis.__dc.React;", + "react/jsx-runtime": "module.exports = globalThis.__dc.JSX;", + "react-dom": "module.exports = globalThis.__dc.DOM;", + "react-dom/client": "module.exports = globalThis.__dc.DOMClient;", +}; + +function vfsPlugin(files: Record, mode: "ssr" | "browser"): Plugin { + const find = (p: string) => [p, `${p}.tsx`, `${p}.ts`, `${p}.jsx`, `${p}.js`, `${p}/index.tsx`, `${p}/index.ts`].find((c) => c in files); + return { + name: "kit-vfs", + setup(b) { + b.onResolve({ filter: /.*/ }, (args) => { + if (args.path in REACT) return mode === "ssr" ? { path: args.path, external: true } : { path: args.path, namespace: "react-global" }; + if (args.kind === "entry-point") return { path: args.path, namespace: "kit" }; + if (args.path.startsWith(".") || args.path.startsWith("/")) { + const base = args.path.startsWith("/") ? args.path.slice(1) : posix.join(posix.dirname(args.importer), args.path); + const hit = find(posix.normalize(base)); + if (!hit) return { errors: [{ text: `Cannot find “${args.path}” (from ${args.importer}).` }] }; + return { path: hit, namespace: "kit" }; + } + return { errors: [{ text: `Package “${args.path}” is not available — components may import only react, react-dom and files in the kit.` }] }; + }); + b.onLoad({ filter: /.*/, namespace: "react-global" }, (a) => ({ contents: REACT[a.path], loader: "js" })); + b.onLoad({ filter: /.*/, namespace: "kit" }, (a) => { + const ext = posix.extname(a.path).slice(1); + if (ext === "css") return mode === "ssr" ? { contents: "", loader: "js" } : { contents: files[a.path], loader: "css", resolveDir: "/" }; + return { contents: files[a.path], loader: (ext === "ts" ? "ts" : ext === "jsx" ? "jsx" : ext === "js" ? "js" : "tsx") as "tsx", resolveDir: "/" }; + }); + }, + }; +} +const toIssues = (msgs: { text: string; location?: { file: string; line: number; column: number } | null }[], severity: "error" | "warning"): CodeIssue[] => + msgs.map((m) => ({ file: m.location?.file ?? "", line: m.location?.line, col: m.location ? m.location.column + 1 : undefined, message: m.text, severity, source: "esbuild" })); + +async function run(files: Record, entry: string, mode: "ssr" | "browser") { + const e = await esbuild(); + try { + const r = await e.build({ + entryPoints: [entry], bundle: true, write: false, outdir: "/out", format: mode === "ssr" ? "cjs" : "iife", platform: mode === "ssr" ? "node" : "browser", + jsx: "automatic", target: "es2020", minify: mode === "browser", logLevel: "silent", plugins: [vfsPlugin(files, mode)], define: { "process.env.NODE_ENV": '"production"' }, + }); + const js = r.outputFiles.find((f) => f.path.endsWith(".js"))?.text ?? ""; + const css = r.outputFiles.find((f) => f.path.endsWith(".css"))?.text ?? ""; + return { js, css, issues: toIssues(r.warnings, "warning") }; + } catch (err) { + const f = err as { errors?: { text: string; location?: { file: string; line: number; column: number } | null }[]; message: string }; + return { js: "", css: "", issues: f.errors?.length ? toIssues(f.errors, "error") : [{ file: "", message: f.message, severity: "error" as const, source: "esbuild" as const }] }; + } +} + +export function ssrEntry(names: string[]) { + return names.map((n, i) => `import * as M${i} from "./src/${n}";`).join("\n") + `\nexport const mods = { ${names.map((n, i) => `${JSON.stringify(n)}: M${i}`).join(", ")} };\n`; +} +export function catalogEntry(names: string[], title: string) { + return `import { createRoot } from "react-dom/client"; +import { useState } from "react"; +${names.map((n, i) => `import * as M${i} from "./src/${n}";`).join("\n")} +const comps: { name: string; mod: any }[] = [${names.map((n, i) => `{ name: ${JSON.stringify(n)}, mod: M${i} }`).join(", ")}]; +function App() { + const [dark, setDark] = useState(false); + return ( +
+

${title.replace(/[<>{}"]/g, "")}

+ + {comps.map((c) => ( +
+

{c.name}

+
{(c.mod.examples ?? []).map((e: any) =>
{e.render()}
{e.name}
)}
+
+ ))} +
+ ); +} +createRoot(document.getElementById("root")!).render(); +`; +} +export const bundleSsr = (files: Record, names: string[]) => run({ ...files, "__ssr.tsx": ssrEntry(names) }, "__ssr.tsx", "ssr"); +export const bundleCatalog = (files: Record, names: string[], title: string) => run({ ...files, "__catalog.tsx": catalogEntry(names, title) }, "__catalog.tsx", "browser"); diff --git a/ui-plugins/design-to-components/src/compile.ts b/ui-plugins/design-to-components/src/compile.ts new file mode 100644 index 00000000..fb03157c --- /dev/null +++ b/ui-plugins/design-to-components/src/compile.ts @@ -0,0 +1,35 @@ +import { readFileSync, readdirSync } from "node:fs"; +import { join } from "node:path"; +import ts from "typescript"; + +export interface CodeIssue { file: string; line?: number; col?: number; message: string; severity: "error" | "warning"; source: "typescript" | "esbuild" | "render" | "check" } + +/** 用 TypeScript 在内存里做类型检查(strict + react-jsx),React 类型来自随插件附带的 @types/react。 */ +export function typecheck(files: Record, typesRoot: string): CodeIssue[] { + const vfs = new Map(); + for (const [p, s] of Object.entries(files)) vfs.set(`/kit/${p}`, s); + vfs.set("/kit/__ambient.d.ts", 'declare module "*.css";\ndeclare module "*.svg" { const src: string; export default src; }\ndeclare module "*.png" { const src: string; export default src; }\n'); + const disk = (dir: string, prefix: string) => { for (const f of readdirSync(dir)) if (f.endsWith(".d.ts") || f === "package.json") vfs.set(`${prefix}/${f}`, readFileSync(join(dir, f), "utf8")); }; + disk(join(typesRoot, "react"), "/node_modules/@types/react"); + disk(join(typesRoot, "csstype"), "/node_modules/csstype"); + const libDir = join(typesRoot, "ts-lib"); + const options: ts.CompilerOptions = { + strict: true, noEmit: true, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, + lib: ["lib.es2022.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts"], types: [], skipLibCheck: true, allowImportingTsExtensions: true, noUnusedLocals: false, isolatedModules: true, esModuleInterop: true, + }; + const read = (f: string) => vfs.get(f) ?? (f.startsWith("/lib/") ? (() => { try { return readFileSync(join(libDir, f.slice(5)), "utf8"); } catch { return undefined; } })() : undefined); + const host: ts.CompilerHost = { + getSourceFile: (f, v) => { const s = read(f); return s === undefined ? undefined : ts.createSourceFile(f, s, v, true); }, + getDefaultLibFileName: () => "/lib/lib.d.ts", getDefaultLibLocation: () => "/lib", writeFile: () => undefined, getCurrentDirectory: () => "/kit", + getCanonicalFileName: (f) => f, useCaseSensitiveFileNames: () => true, getNewLine: () => "\n", + fileExists: (f) => read(f) !== undefined, readFile: read, + directoryExists: (d) => [...vfs.keys()].some((k) => k.startsWith(d.endsWith("/") ? d : `${d}/`)) || d === "/lib", + getDirectories: () => [], + }; + const roots = [...vfs.keys()].filter((f) => f.startsWith("/kit/") && /\.tsx?$/.test(f)); + const program = ts.createProgram(roots, options, host); + return ts.getPreEmitDiagnostics(program).filter((d) => !d.file || d.file.fileName.startsWith("/kit/")).map((d) => { + const pos = d.file && d.start !== undefined ? d.file.getLineAndCharacterOfPosition(d.start) : undefined; + return { file: d.file ? d.file.fileName.slice(5) : "", line: pos ? pos.line + 1 : undefined, col: pos ? pos.character + 1 : undefined, message: ts.flattenDiagnosticMessageText(d.messageText, "\n"), severity: d.category === ts.DiagnosticCategory.Error ? "error" : "warning", source: "typescript" } as CodeIssue; + }); +} diff --git a/ui-plugins/design-to-components/src/main.ts b/ui-plugins/design-to-components/src/main.ts new file mode 100644 index 00000000..8cb535b3 --- /dev/null +++ b/ui-plugins/design-to-components/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[design-to-components] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/design-to-components/src/server.ts b/ui-plugins/design-to-components/src/server.ts new file mode 100644 index 00000000..63e3bd4e --- /dev/null +++ b/ui-plugins/design-to-components/src/server.ts @@ -0,0 +1,246 @@ +import { statSync } from "node:fs"; +import { dirname as fitDirname } from "node:path"; +import { readFile } from "node:fs/promises"; +import { join, posix } from "node:path"; +import vm from "node:vm"; +import * as React from "react"; +import * as JSXRT from "react/jsx-runtime"; +import * as ReactDOM from "react-dom"; +import { renderToStaticMarkup } from "react-dom/server"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { bundleCatalog, bundleSsr } from "./bundle.ts"; +import { type CodeIssue, typecheck } from "./compile.ts"; +import { DEFAULT_TOKENS, GROUPS, type Tokens, tokensCss, tokensTs, validateTokens } from "./tokens.ts"; + +export const NAME = "design-to-components"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +const PROJECT = ".design-to-components/project.json"; + +export interface ServerOptions { workspaceRoot: string; assetRoot: string; log?: (line: string) => void } +interface PlanItem { name: string; description?: string; states: string[] } +interface Kit { slug: string; name: string; dir: string; design: string[]; plan: PlanItem[] } +interface Project { version: 1; kits: Kit[]; current: string } +const slugify = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[^\w]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "ui-kit"; +const PASCAL = /^[A-Z][A-Za-z0-9]*$/; + +export const CATALOG_CSS = `.dc-catalog{font-family:var(--font-body,system-ui,sans-serif);color:var(--color-text,#111);background:#fff;padding:24px;min-height:100vh;box-sizing:border-box} +.dc-catalog.dc-dark{background:#1f2023;color:#eee}.dc-head{display:flex;justify-content:space-between;align-items:center}.dc-head h1{font-size:22px;margin:0} +.dc-nav{display:flex;gap:12px;flex-wrap:wrap;margin:12px 0 8px;font-size:13px}.dc-comp{margin:22px 0}.dc-comp h2{font-size:15px;margin:0 0 10px;font-family:ui-monospace,monospace} +.dc-examples{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-start}.dc-examples figure{margin:0;border:1px dashed #d0d5dd;border-radius:8px;padding:16px;min-width:180px;max-width:100%} +.dc-examples figcaption{font-size:11px;color:#667085;margin-top:10px;font-family:system-ui,sans-serif}.dc-stage{display:flex;gap:8px;flex-wrap:wrap;align-items:center} +.dc-error{color:#b42318;font:12px ui-monospace,monospace;white-space:pre-wrap}`; + +/** 从目标目录往上找:第一个已存在的路径如果是文件,返回它(相对工作区)。 */ +function fileInTheWay(ws: Workspace, rel: string): string | null { + let p = ws.resolve(rel); + while (p !== ws.root && p.startsWith(ws.root)) { + const st = statSync(p, { throwIfNoEntry: false }); + if (st) return st.isDirectory() ? null : ws.rel(p); + p = fitDirname(p); + } + return null; +} + +/** + * 组件文件都平铺在 src/。常见的嵌套写法 src/components/Button/Button.tsx、src/Button/Button.css、 + * components/Button.tsx 会被平铺成 src/Button.tsx;其它嵌套(例如 src/a/b/index.ts)仍然拒绝。 + */ +export function flatName(f: string): string | null { + const n = posix.normalize(f.replace(/^\.?\//, "")).replace(/^src\//, ""); + if (!/\.(tsx|ts|css)$/.test(n) || n.startsWith("..")) return null; + const parts = n.split("/"); + const file = parts.at(-1)!, stem = file.replace(/\.(tsx|ts|css)$/, ""); + const dirs = parts.slice(0, -1); + if (dirs[0] === "components") dirs.shift(); + if (dirs.length === 0) return file; + if (dirs.length === 1 && dirs[0] === stem && stem !== "index") return file; + return null; +} +/** 平铺后修正相对导入:../../tokens → ../tokens,./components/X/X 或 ../X/X → ./X。 */ +export function fixImports(src: string): string { + return src + .replace(/(["'])(?:\.\.\/)+tokens(["'])/g, "$1../tokens$2") + .replace(/(["'])(?:\.\/|\.\.\/)+(?:components\/)?([A-Za-z0-9_]+)\/\2(\.css)?(["'])/g, "$1./$2$3$4"); +} + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const { server, tool } = createKitServer({ name: NAME, version: VERSION, panelUri: PANEL_URI, surface: "editor", panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), log: options.log }); + const typesRoot = join(options.assetRoot, "types"); + let vendor: string | undefined; + + const load = async (): Promise => ((await ws.exists(PROJECT)) ? JSON.parse(await ws.readText(PROJECT)) : undefined); + const save = (p: Project) => ws.write(PROJECT, JSON.stringify(p, null, 1) + "\n"); + async function pick(slug?: string) { + const p = await load(); + if (!p?.kits.length) throw new KitError("no_kit", "No component kit yet; call dc_new first."); + const k = p.kits.find((x) => x.slug === (slug ?? p.current)); + if (!k) throw new KitError("unknown_kit", `No kit “${slug}”. Kits: ${p.kits.map((x) => x.slug).join(", ")}`); + if (slug && p.current !== slug) { p.current = slug; await save(p); } + return { p, k }; + } + const tokensOf = async (k: Kit): Promise => JSON.parse(await ws.readText(`${k.dir}/tokens.json`)); + async function writeTokens(k: Kit, t: Tokens) { + await ws.write(`${k.dir}/tokens.json`, JSON.stringify(t, null, 2) + "\n"); + await ws.write(`${k.dir}/tokens.css`, tokensCss(t)); + await ws.write(`${k.dir}/tokens.ts`, tokensTs(t)); + } + async function sources(k: Kit) { + const files: Record = {}; + for (const f of await ws.list({ dir: `${k.dir}/src`, exts: [".tsx", ".ts", ".css"], limit: 500 })) files[posix.relative(k.dir, f.path)] = await ws.readText(f.path); + files["tokens.ts"] = await ws.readText(`${k.dir}/tokens.ts`); + return files; + } + + type Comp = { name: string; file: string; examples: { name: string; html?: string; error?: string }[] }; + /** 类型检查 + 约定检查 + 服务端渲染每个示例 + 打包浏览器目录页。 */ + async function build(k: Kit) { + const t = await tokensOf(k); + const tokenIssues = validateTokens(t); + const files = await sources(k); + const names = Object.keys(files).filter((f) => /^src\/[A-Z][A-Za-z0-9]*\.tsx$/.test(f)).map((f) => posix.basename(f, ".tsx")).sort(); + const issues: CodeIssue[] = names.length ? typecheck(files, typesRoot) : []; + // 约定:颜色等写死的值应该用设计变量 + for (const [f, s] of Object.entries(files)) if (/\.(css|tsx)$/.test(f)) s.split("\n").forEach((line, i) => { + const m = line.replace(/var\([^)]*\)/g, "").match(/#[0-9a-fA-F]{3,8}\b|\brgba?\([^)]*\)/); + if (m && !/^\s*(\/\/|\/\*|\*)/.test(line)) issues.push({ file: f, line: i + 1, message: `Hard-coded colour ${m[0]}; use a token such as var(--color-primary).`, severity: "warning", source: "check" }); + }); + const comps: Comp[] = []; + let css = ""; + if (names.length) { + const ssr = await bundleSsr(files, names); + issues.push(...ssr.issues); + if (ssr.js) { + const require = (id: string) => { if (id === "react") return React; if (id === "react/jsx-runtime") return JSXRT; if (id === "react-dom") return ReactDOM; throw new Error(`Cannot require ${id}`); }; + const ctx = vm.createContext({ require, module: { exports: {} as Record }, renderToStaticMarkup, console: { log() {}, warn() {}, error() {} } }); + try { + vm.runInContext(`(function(module, exports){${ssr.js}\n})(module, module.exports);`, ctx, { timeout: 5000, filename: "components.js" }); + const mods = (ctx.module.exports as { mods: Record> }).mods; + for (const n of names) { + const mod = mods[n] ?? {}; + const c: Comp = { name: n, file: `src/${n}.tsx`, examples: [] }; + if (typeof mod[n] !== "function" && typeof mod[n] !== "object") issues.push({ file: c.file, message: `src/${n}.tsx must export a component named ${n} (export function ${n}(props) …).`, severity: "error", source: "check" }); + const ex = mod.examples as { name: string; render: () => unknown }[] | undefined; + if (!Array.isArray(ex) || !ex.length) issues.push({ file: c.file, message: `Add \`export const examples = [{ name: "Default", render: () => <${n} /> }, …]\` — one example per state.`, severity: "warning", source: "check" }); + else for (const [i, e] of ex.entries()) { + ctx.__e = e; + try { c.examples.push({ name: String(e.name ?? `Example ${i + 1}`), html: vm.runInContext("renderToStaticMarkup(__e.render())", ctx, { timeout: 3000 }) as string }); } + catch (err) { const msg = (err as Error).message; c.examples.push({ name: String(e.name ?? i), error: msg }); issues.push({ file: c.file, message: `Example “${e.name}” failed to render: ${msg}`, severity: "error", source: "render" }); } + } + const plan = k.plan.find((x) => x.name === n); + for (const st of plan?.states ?? []) if (!c.examples.some((e) => e.name.toLowerCase().includes(st.toLowerCase()))) issues.push({ file: c.file, message: `No example for the planned state “${st}”.`, severity: "warning", source: "check" }); + comps.push(c); + } + } catch (err) { issues.push({ file: "", message: `Loading the components failed: ${(err as Error).message}`, severity: "error", source: "render" }); } + } + const cat = await bundleCatalog(files, names, k.name); + issues.push(...cat.issues.filter((i) => !ssr.issues.some((s) => s.message === i.message))); + css = cat.css; + if (cat.js) { + vendor ??= await readFile(join(options.assetRoot, "vendor/react.js"), "utf8"); + const safe = (s: string) => s.replace(/<\/(script|style)/gi, "<\\/$1"); + await ws.write(`${k.dir}/catalog/index.html`, `\n${k.name.replace(/</g, "<")} — components\n\n
\n\n\n`); + } + await ws.write(`${k.dir}/index.ts`, `// Generated by Design To Components.\n${names.map((n) => `export { ${n} } from "./src/${n}";`).join("\n")}\nexport { tokens } from "./tokens";\n`); + } + const planned = k.plan.map((pl) => { + const c = comps.find((x) => x.name === pl.name); + const errs = issues.filter((i) => i.severity === "error" && i.file === `src/${pl.name}.tsx`).length; + return { ...pl, status: !names.includes(pl.name) ? "todo" : errs ? "error" : "done", examples: c?.examples.length ?? 0 }; + }); + const preview = `
${comps.map((c) => `

${c.name}

${c.examples.map((e) => `
${e.html ?? `
${(e.error ?? "").replace(/`}
${e.name.replace(/
`).join("")}
`).join("") || '

No components yet.

'}
`; + const order = { error: 0, warning: 1 }; + issues.sort((a, b) => order[a.severity] - order[b.severity] || a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0)); + return { tokens: t, tokenIssues, comps, issues, planned, preview, names, files: Object.keys(files).filter((f) => f.startsWith("src/")) }; + } + type Built = Awaited>; + const view = (p: Project, k: Kit, b: Built) => ({ kind: "kit", project: p, kit: k, tokens: b.tokens, tokenIssues: b.tokenIssues, plan: b.planned, components: b.comps.map((c) => ({ name: c.name, examples: c.examples.map((e) => e.name) })), issues: b.issues, preview: b.preview, files: b.files, catalog: b.names.length ? `${k.dir}/catalog/index.html` : null }); + const line = (i: CodeIssue) => `${i.severity === "error" ? "✗" : "!"} ${i.file}${i.line ? `:${i.line}` : ""} [${i.source}] ${i.message}`; + const brief = (k: Kit, b: Built) => { + const errs = b.issues.filter((i) => i.severity === "error").length; + return `${k.dir}: ${b.names.length} component(s) (${b.comps.map((c) => `${c.name} ×${c.examples.length}`).join(", ") || "none"}), ${errs} error(s), ${b.issues.length - errs} warning(s).${b.planned.length ? ` Plan: ${b.planned.map((x) => `${x.name} ${x.status}`).join(", ")}.` : ""}${b.names.length ? ` Catalog: ${k.dir}/catalog/index.html.` : ""}${[...b.tokenIssues.map((t) => `\n✗ tokens.${t.group}.${t.key}: ${t.message}`), ...b.issues.slice(0, 40).map((i) => `\n${line(i)}`)].join("")}`; + }; + const respond = async (p: Project, k: Kit) => { const b = await build(k); return { text: brief(k, b), structured: view(p, k, b) }; }; + + const tokenShape = z.object(Object.fromEntries(GROUPS.map((g) => [g, z.record(z.string(), z.string()).optional()]))).partial(); + tool("dc_new", { + description: "Start a React component kit from design images: creates ui-kit// with tokens.json (colours, fonts, font sizes, radii, spacing, shadows) → generated tokens.css (CSS variables) and tokens.ts, and links the design images for the panel. Then set the tokens from the design (dc_tokens), list the components (dc_plan) and write them (dc_write).", + input: { name: z.string().min(1), design: z.array(z.string()).optional(), tokens: tokenShape.optional(), dir: z.string().optional() }, openPanel: true, + }, async ({ name, design, tokens, dir }) => { + const p: Project = (await load()) ?? { version: 1, kits: [], current: "" }; + const slug = slugify(name); + if (p.kits.some((x) => x.slug === slug)) throw new KitError("exists", `Kit ${slug} already exists.`); + for (const d of design ?? []) if (!(await ws.exists(d))) throw new KitError("not_found", `${d} not found.`); + const k: Kit = { slug, name, dir: (dir ?? `ui-kit/${slug}`).replace(/^\/+|\/+$/g, ""), design: design ?? [], plan: [] }; + // 输出目录(或它的某一级上级)是个已存在的文件时给出可读错误,而不是 mkdir 的 EEXIST(TEST-FINDINGS #6) + { const f = fileInTheWay(ws, k.dir); if (f) throw new KitError("not_a_folder", `${f} is a file, so ${k.dir} cannot be a folder. Pass another dir.`); } + if (await ws.exists(`${k.dir}/tokens.json`)) throw new KitError("exists", `${k.dir} already has a kit.`); + const t = structuredClone(DEFAULT_TOKENS) as Tokens; + for (const g of GROUPS) if (tokens?.[g]) t[g] = { ...tokens[g] } as Record; + await writeTokens(k, t); + await ws.write(`${k.dir}/README.md`, `# ${name}\n\nReact components generated with Design To Components.\n\n- \`tokens.json\` → \`tokens.css\` (CSS variables) and \`tokens.ts\`\n- \`src/.tsx\` + \`src/.css\`; each file exports the component and \`examples\` (one per state)\n- \`index.ts\` re-exports all components\n- \`catalog/index.html\` — open in a browser to see every component and state\n\nUse in a React 18/19 project: copy \`src/\`, \`tokens.css\`, \`tokens.ts\` and \`index.ts\`, import \`tokens.css\` once, and let your bundler handle the CSS imports.\n`); + p.kits.push(k); p.current = slug; await save(p); + return respond(p, k); + }); + tool("dc_tokens", { + description: "Set design tokens taken from the design (merged per group; use remove: [\"colors.old-name\"] to delete). Regenerates tokens.css / tokens.ts and re-checks the components. Components should use var(--color-), var(--font-), var(--font-size-), var(--radius-), var(--space-), var(--shadow-).", + input: { tokens: tokenShape.optional(), remove: z.array(z.string()).optional(), kit: z.string().optional() }, + }, async ({ tokens, remove, kit }) => { + const { p, k } = await pick(kit); + const t = await tokensOf(k); + for (const g of GROUPS) if (tokens?.[g]) Object.assign(t[g], tokens[g]); + for (const r of remove ?? []) { const [g, ...rest] = r.split("."); if ((GROUPS as readonly string[]).includes(g)) delete (t as unknown as Record>)[g][rest.join(".")]; } + const bad = validateTokens(t); + if (bad.length) throw new KitError("bad_tokens", bad.map((b) => `${b.group}.${b.key}: ${b.message}`).join("\n")); + await writeTokens(k, t); + return respond(p, k); + }); + tool("dc_plan", { + description: "Set the component list from the design: name (PascalCase), what it is, and the states/variants each needs an example for (e.g. Button: primary, secondary, disabled, loading). The panel tracks which are written and compiled.", + input: { components: z.array(z.object({ name: z.string(), description: z.string().optional(), states: z.array(z.string()).default([]) })), kit: z.string().optional() }, + }, async ({ components, kit }) => { + const { p, k } = await pick(kit); + for (const c of components) if (!PASCAL.test(c.name)) throw new KitError("bad_name", `Component name “${c.name}” must be PascalCase, e.g. PriceTag.`); + k.plan = components; await save(p); + return respond(p, k); + }); + tool("dc_write", { + description: "Write component files into src/ (flat: src/Button.tsx; src/components/Button/Button.tsx is accepted and flattened) and rebuild: .tsx (export function (props) and export const examples = [{ name: \"Primary\", render: () => }, …] — one example per planned state) and optional .css (import \"./.css\"; use token CSS variables, no hard-coded colours). Only react / react-dom and files in the kit can be imported (tokens: \"../tokens\"). Returns TypeScript errors, render errors and convention warnings.", + input: { files: z.record(z.string(), z.string()).default({}), delete: z.array(z.string()).optional(), kit: z.string().optional() }, + }, async ({ files, delete: del, kit }) => { + const { p, k } = await pick(kit); + const notes: string[] = []; + const clean = (f: string) => { + const n = flatName(f); + if (!n) throw new KitError("bad_path", `“${f}”: write files directly in src/ (or src/components//.tsx, which is flattened) with .tsx, .ts or .css.`); + return `${k.dir}/src/${n}`; + }; + for (const [f, s] of Object.entries(files)) { + const n = flatName(f)!; + const flat = posix.normalize(f.replace(/^\.?\//, "")) !== `src/${n}` && posix.normalize(f) !== n; + if (flat) notes.push(`${f} → src/${n}`); + await ws.write(clean(f), flat ? fixImports(s as string) : (s as string)); + } + for (const f of del ?? []) { const path = clean(f); if (await ws.exists(path)) await (await import("node:fs/promises")).rm(ws.resolve(path)); } + const r = await respond(p, k); + if (notes.length) r.text = `Flattened nested paths (the kit keeps every component directly in src/): ${notes.join(", ")}.\n${r.text}`; + return r; + }); + tool("dc_build", { description: "Type-check (TypeScript strict), render every example, and rebuild catalog/index.html and index.ts.", input: { kit: z.string().optional() } }, async ({ kit }) => { const { p, k } = await pick(kit); return respond(p, k); }); + + tool("dc_state", { description: "Panel state.", input: { kit: z.string().optional() }, visibility: ["app"], readOnly: true }, async ({ kit }) => { + try { const { p, k } = await pick(kit); return { text: "", structured: view(p, k, await build(k)) }; } catch { return { text: "", structured: { kind: "none" } }; } + }); + tool("dc_file", { description: "A kit file.", input: { path: z.string() }, visibility: ["app"], readOnly: true }, async ({ path }) => { const { k } = await pick(); return { text: "", structured: { text: await ws.readText(`${k.dir}/${posix.normalize(path)}`) } }; }); + tool("dc_design", { description: "Design image.", input: { path: z.string() }, visibility: ["app"], readOnly: true }, async ({ path }) => { + const p = await load(); + if (!p?.kits.some((x) => x.design.includes(path))) throw new KitError("not_design", "Not a design image of a kit."); + const ext = posix.extname(path).toLowerCase(); + return { text: "", structured: { dataUrl: `data:${ext === ".png" ? "image/png" : ext === ".webp" ? "image/webp" : "image/jpeg"};base64,${(await ws.read(path)).toString("base64")}` } }; + }); + tool("workspace_images", { description: "Images.", input: {}, visibility: ["app"], readOnly: true }, async () => ({ text: "", structured: { files: (await ws.list({ exts: [".png", ".jpg", ".jpeg", ".webp"], limit: 3000 })).map((f) => f.path) } })); + return server; +} diff --git a/ui-plugins/design-to-components/src/tokens.ts b/ui-plugins/design-to-components/src/tokens.ts new file mode 100644 index 00000000..9d75e11e --- /dev/null +++ b/ui-plugins/design-to-components/src/tokens.ts @@ -0,0 +1,48 @@ +// 设计变量:tokens.json → tokens.css(CSS 变量)+ tokens.ts(带类型的常量)。 +export interface Tokens { + colors: Record; + fonts: Record; + fontSizes: Record; + radii: Record; + spacing: Record; + shadows: Record; +} +export const GROUPS = ["colors", "fonts", "fontSizes", "radii", "spacing", "shadows"] as const; +const PREFIX: Record<(typeof GROUPS)[number], string> = { colors: "color", fonts: "font", fontSizes: "font-size", radii: "radius", spacing: "space", shadows: "shadow" }; + +export const DEFAULT_TOKENS: Tokens = { + colors: { primary: "#2563eb", "primary-contrast": "#ffffff", surface: "#ffffff", "surface-muted": "#f3f4f6", text: "#111827", "text-muted": "#6b7280", border: "#e5e7eb", danger: "#dc2626", success: "#16a34a" }, + fonts: { body: "system-ui, -apple-system, 'Segoe UI', sans-serif", heading: "system-ui, -apple-system, 'Segoe UI', sans-serif", mono: "ui-monospace, Menlo, monospace" }, + fontSizes: { xs: "12px", sm: "14px", md: "16px", lg: "20px", xl: "28px" }, + radii: { sm: "4px", md: "8px", lg: "16px", full: "999px" }, + spacing: { "1": "4px", "2": "8px", "3": "12px", "4": "16px", "6": "24px", "8": "32px" }, + shadows: { sm: "0 1px 2px rgba(0,0,0,.06)", md: "0 4px 12px rgba(0,0,0,.08)" }, +}; + +export interface TokenIssue { group: string; key: string; message: string } +const isColor = (v: string) => /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(v) || /^(rgb|rgba|hsl|hsla|oklch|color-mix)\(/i.test(v) || v === "transparent"; +const isLength = (v: string) => /^-?(\d+(\.\d+)?|\.\d+)(px|rem|em|%)?$/.test(v) || v === "0"; + +export function validateTokens(t: Tokens): TokenIssue[] { + const out: TokenIssue[] = []; + for (const g of GROUPS) for (const [k, v] of Object.entries(t[g] ?? {})) { + if (!/^[a-z0-9][a-z0-9-]*$/.test(k)) out.push({ group: g, key: k, message: `Token name “${k}” must be lowercase letters, digits and dashes.` }); + if (typeof v !== "string" || !v.trim()) out.push({ group: g, key: k, message: "Empty value." }); + else if (g === "colors" && !isColor(v)) out.push({ group: g, key: k, message: `“${v}” is not a colour (#hex, rgb(), hsl(), oklch()).` }); + else if ((g === "fontSizes" || g === "radii" || g === "spacing") && !isLength(v)) out.push({ group: g, key: k, message: `“${v}” is not a length (px, rem, em, %).` }); + else if (/[;{}]/.test(v)) out.push({ group: g, key: k, message: "Value cannot contain ; { }." }); + } + return out; +} + +export const cssVar = (g: (typeof GROUPS)[number], k: string) => `--${PREFIX[g]}-${k}`; +export function tokensCss(t: Tokens): string { + const lines = ["/* Generated by Design To Components from tokens.json — edit tokens.json, not this file. */", ":root {"]; + for (const g of GROUPS) for (const [k, v] of Object.entries(t[g] ?? {})) lines.push(` ${cssVar(g, k)}: ${v};`); + lines.push("}", ""); + return lines.join("\n"); +} +export function tokensTs(t: Tokens): string { + const body = GROUPS.map((g) => ` ${g}: {\n${Object.entries(t[g] ?? {}).map(([k, v]) => ` ${JSON.stringify(k)}: { value: ${JSON.stringify(v)}, css: "var(${cssVar(g, k)})" },`).join("\n")}\n },`).join("\n"); + return `// Generated by Design To Components from tokens.json — edit tokens.json, not this file.\nexport const tokens = {\n${body}\n} as const;\nexport type Tokens = typeof tokens;\n`; +} diff --git a/ui-plugins/design-to-components/src/vendor-entry.ts b/ui-plugins/design-to-components/src/vendor-entry.ts new file mode 100644 index 00000000..5e51eca3 --- /dev/null +++ b/ui-plugins/design-to-components/src/vendor-entry.ts @@ -0,0 +1,6 @@ +// 打包时生成 dist/vendor/react.js:浏览器里的组件目录页通过 globalThis.__dc 使用 React。 +import * as React from "react"; +import * as JSX from "react/jsx-runtime"; +import * as DOM from "react-dom"; +import * as DOMClient from "react-dom/client"; +(globalThis as unknown as { __dc: unknown }).__dc = { React, JSX, DOM, DOMClient }; From 306c6dea87163e4b0e9f697766eab79906a46d0f Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:32:27 +0800 Subject: [PATCH 07/10] feat(ui-plugins): add Design To Components (design-to-components) --- .../design-to-components/test/_mkclient.ts | 18 ++++ .../test/findings-fixes.test.ts | 48 ++++++++++ .../design-to-components/test/tools.test.ts | 87 +++++++++++++++++++ .../test/workspace-links.test.ts | 43 +++++++++ 4 files changed, 196 insertions(+) create mode 100644 ui-plugins/design-to-components/test/_mkclient.ts create mode 100644 ui-plugins/design-to-components/test/findings-fixes.test.ts create mode 100644 ui-plugins/design-to-components/test/tools.test.ts create mode 100644 ui-plugins/design-to-components/test/workspace-links.test.ts diff --git a/ui-plugins/design-to-components/test/_mkclient.ts b/ui-plugins/design-to-components/test/_mkclient.ts new file mode 100644 index 00000000..ab96ba54 --- /dev/null +++ b/ui-plugins/design-to-components/test/_mkclient.ts @@ -0,0 +1,18 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { createServer } from "../src/server.ts"; + +export async function mkclient(prefix: string) { + const root = mkdtempSync(join(tmpdir(), prefix)); + const server = createServer({ workspaceRoot: root, assetRoot: join(import.meta.dirname, "../dist") } as any); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; + const text = (r: any) => (r.content ?? []).map((c: any) => c.text ?? "").join(" "); + return { root, call, text }; +} diff --git a/ui-plugins/design-to-components/test/findings-fixes.test.ts b/ui-plugins/design-to-components/test/findings-fixes.test.ts new file mode 100644 index 00000000..f7cbb98c --- /dev/null +++ b/ui-plugins/design-to-components/test/findings-fixes.test.ts @@ -0,0 +1,48 @@ +import { writeFileSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { fixImports, flatName } from "../src/server.ts"; +import { mkclient } from "./_mkclient.ts"; + +describe("DRYRUN: nested component paths are flattened", () => { + it("maps the common nested layouts to src/ and rejects the rest", () => { + expect(flatName("src/components/Button/Button.tsx")).toBe("Button.tsx"); + expect(flatName("src/Button/Button.css")).toBe("Button.css"); + expect(flatName("components/Card.tsx")).toBe("Card.tsx"); + expect(flatName("./src/Tag.tsx")).toBe("Tag.tsx"); + expect(flatName("Tag.tsx")).toBe("Tag.tsx"); + expect(flatName("src/components/Button/index.ts")).toBeNull(); + expect(flatName("src/a/b/Button.tsx")).toBeNull(); + expect(flatName("../evil.ts")).toBeNull(); + expect(flatName("src/Button.js")).toBeNull(); + }); + it("fixes relative imports after flattening", () => { + expect(fixImports('import { tokens } from "../../../tokens";\nimport "./Button.css";\nimport { Icon } from "../Icon/Icon";')) + .toBe('import { tokens } from "../tokens";\nimport "./Button.css";\nimport { Icon } from "./Icon";'); + }); + it("dc_write accepts src/components/Tag/Tag.tsx end to end", async () => { + const { root, call, text } = await mkclient("dc-nested-"); + expect((await call("dc_new", { name: "中文 Kit" })).isError).toBeFalsy(); + const tsx = 'import "./Tag.css";\nexport function Tag({ label }: { label: string }) { return {label}; }\nexport const examples = [{ name: "Default", render: () => }];\n'; + const r = await call("dc_write", { files: { "src/components/Tag/Tag.tsx": tsx, "src/components/Tag/Tag.css": ".tag { color: var(--color-text, #111); }\n" } }); + expect(r.isError, text(r)).toBeFalsy(); + expect(text(r)).toContain("src/components/Tag/Tag.tsx → src/Tag.tsx"); + const dir = (r.structuredContent?.kit?.dir as string) ?? "ui-kit/kit"; + expect(existsSync(join(root, "ui-kit")) ).toBe(true); + expect((r.structuredContent.issues ?? []).filter((i: any) => i.severity === "error")).toEqual([]); + void dir; + }); +}); + +describe("TEST-FINDINGS #6: dc_new with dir pointing at a file", () => { + it("returns not_a_folder instead of EEXIST", async () => { + const { root, call, text } = await mkclient("dc-file-"); + writeFileSync(join(root, "设计.pdf"), "x"); + for (const dir of ["设计.pdf", "设计.pdf/sub"]) { + const r = await call("dc_new", { name: `Kit ${dir.length}`, dir }); + expect(r.isError).toBe(true); + expect(text(r)).toContain("not_a_folder"); + expect(text(r)).not.toMatch(/EEXIST|ENOTDIR|internal_error/); + } + }); +}); diff --git a/ui-plugins/design-to-components/test/tools.test.ts b/ui-plugins/design-to-components/test/tools.test.ts new file mode 100644 index 00000000..343d67b3 --- /dev/null +++ b/ui-plugins/design-to-components/test/tools.test.ts @@ -0,0 +1,87 @@ +import { cp, mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { beforeAll, describe, expect, it } from "vitest"; +import { typecheck } from "../src/compile.ts"; +import { createServer } from "../src/server.ts"; +import { DEFAULT_TOKENS, tokensCss, tokensTs, validateTokens } from "../src/tokens.ts"; + +// 虚构的 “Fieldnote UI” 设计稿和 Agent 写的组件(samples/components)。 +const SAMPLES = process.env.DC_SAMPLES ?? "/workspace/zcode-new-plugins/samples/components"; +const DIST = join(import.meta.dirname, "../dist"); +let ws: string; +let call: (name: string, args: Record) => Promise; +const A = (f: string) => readFile(join(SAMPLES, "agent", f), "utf8"); +beforeAll(async () => { + ws = await mkdtemp(join(tmpdir(), "dc-")); + await cp(SAMPLES, join(ws, "design"), { recursive: true }); + const server = createServer({ workspaceRoot: ws, assetRoot: DIST }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + call = async (name, args) => (await client.callTool({ name, arguments: args }, undefined, { timeout: 120_000 })) as any; +}); + +describe("tokens", () => { + it("generates CSS variables and a typed module", () => { + expect(tokensCss(DEFAULT_TOKENS)).toContain("--color-primary: #2563eb;"); + expect(tokensCss(DEFAULT_TOKENS)).toContain("--font-size-md: 16px;"); + expect(tokensCss(DEFAULT_TOKENS)).toContain("--space-4: 16px;"); + expect(tokensTs(DEFAULT_TOKENS)).toContain('"primary": { value: "#2563eb", css: "var(--color-primary)" }'); + expect(validateTokens(DEFAULT_TOKENS)).toEqual([]); + const bad = validateTokens({ ...DEFAULT_TOKENS, colors: { Primary: "#12", ok: "red;}" }, radii: { md: "big" } }); + expect(bad.map((b) => `${b.group}.${b.key}`)).toEqual(["colors.Primary", "colors.Primary", "colors.ok", "radii.md"]); + }); + it("type-checks TSX against the bundled React types", () => { + const ok = typecheck({ "src/A.tsx": 'import { useState } from "react";\nexport function A() { const [n, set] = useState(0); return ; }\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" }); + }); +}); From 6b6889c5123a2b488fa497a543135c9d45c27ae9 Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:33:04 +0800 Subject: [PATCH 08/10] feat(ui-plugins): add Design To Components (design-to-components) --- ui-plugins/design-to-components/ui/env.d.ts | 4 + ui-plugins/design-to-components/ui/kit.css | 34 +++++ ui-plugins/design-to-components/ui/kit.ts | 133 +++++++++++++++++++ ui-plugins/design-to-components/ui/main.ts | 92 +++++++++++++ ui-plugins/design-to-components/ui/panel.css | 21 +++ 5 files changed, 284 insertions(+) create mode 100644 ui-plugins/design-to-components/ui/env.d.ts create mode 100644 ui-plugins/design-to-components/ui/kit.css create mode 100644 ui-plugins/design-to-components/ui/kit.ts create mode 100644 ui-plugins/design-to-components/ui/main.ts create mode 100644 ui-plugins/design-to-components/ui/panel.css 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; } From 0c237dd90f290ab08df358b288d87d3a0ce91f9f Mon Sep 17 00:00:00 2001 From: ppppp2005-p <360128433+ppppp2005-p@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:33:36 +0800 Subject: [PATCH 09/10] feat(ui-plugins): add Design To Components (design-to-components) --- .../skills/design-to-components/SKILL.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 external_plugins/design-to-components/skills/design-to-components/SKILL.md 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`,按钮用 `