Commit 071ca81d by Lin

功能(d2c):使用 Nuxt.js 和 Tailwind CSS 初始化设计转代码平台

- 为 Design-to-Code 平台创建了一个新的 Nuxt.js 项目,实现了从 Figma 设计到 Vue 3 代码的生成。
- 添加了必要的配置文件,包括 `nuxt.config.ts`、`tailwind.config.ts` 和 `package.json`。
- 实现了一个基本的应用程序结构,包含初始的 `app.vue` 和 `index.vue` 页面。
- 引入了环境变量管理,附带了一个示例 `.env.example` 文件。
- 为 Figma 集成建立了 API 端点,用于获取设计数据并生成 Vue 组件。
- 包含了一个用于 AI 辅助代码生成的提示系统,并有一个专门的文件夹用于管理提示。
- 设置了一个 `.gitignore` 文件,以排除敏感信息和不必要的文件,使其不被纳入版本控制。
1 parent 4aabfcf9
# ============================================================
# 使用说明
# 复制本文件为 d2c/.env 后按需填写:
# copy .env.example .env (Windows)
# cp .env.example .env (macOS / Linux)
# Nuxt 也支持 NUXT_* 前缀(与下方同名变量二选一即可)
# ============================================================
# ============================================================
# Figma(调用 Figma REST API 时必填)
# 获取: Figma -> Settings -> Security -> Personal access tokens
# ============================================================
FIGMA_PERSONAL_ACCESS_TOKEN=
# 或使用: NUXT_FIGMA_TOKEN=
# ============================================================
# AI(可选;未配置时使用内置规则引擎生成 Vue)
# 兼容 OpenAI Chat Completions 格式的网关均可
# ============================================================
AI_API_KEY=
AI_BASE_URL=https://api.openai.com/v1
AI_MODEL=gpt-4o-mini
# 等价: OPENAI_API_KEY= / NUXT_AI_API_KEY=
# NUXT_AI_BASE_URL= / NUXT_AI_MODEL=
# DeepSeek 示例:
# AI_API_KEY=
# AI_BASE_URL=https://api.deepseek.com/v1
# AI_MODEL=deepseek-chat
# ============================================================
# 本地开发(Nuxt 默认 3000,可用 PORT 或 NUXT_PORT)
# ============================================================
PORT=3000
HOST=127.0.0.1
# Nuxt
.nuxt
.output
.data
.cache
# Node
node_modules
dist
# 环境变量(包含敏感信息,不提交)
.env
.env.*
!.env.example
# 日志
*.log
npm-debug.log*
# 系统文件
.DS_Store
Thumbs.db
# 编辑器
.vscode
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
<template>
<NuxtPage />
</template>
export default defineNuxtConfig({
devtools: { enabled: true },
modules: ['@nuxtjs/tailwindcss'],
runtimeConfig: {
// 服务端私有配置(仅在服务端可用)
// 从 .env 的 FIGMA_PERSONAL_ACCESS_TOKEN 或 NUXT_FIGMA_TOKEN 读取
figmaToken: process.env.FIGMA_PERSONAL_ACCESS_TOKEN || process.env.NUXT_FIGMA_TOKEN || '',
aiApiKey: process.env.AI_API_KEY || process.env.OPENAI_API_KEY || process.env.NUXT_AI_API_KEY || '',
aiBaseUrl: process.env.AI_BASE_URL || process.env.NUXT_AI_BASE_URL || 'https://api.openai.com/v1',
aiModel: process.env.AI_MODEL || process.env.NUXT_AI_MODEL || 'gpt-4o-mini',
},
typescript: {
strict: true,
},
nitro: {
experimental: {
wasm: false,
},
},
})
{
"name": "design-to-code-nuxt",
"version": "1.0.0",
"description": "AI 驱动的 Design To Code 平台 —— NuxtJS 版本,支持通过 Figma 设计稿链接生成 Vue 3 SFC 代码",
"private": true,
"type": "module",
"scripts": {
"dev": "nuxt dev",
"build": "nuxt build",
"preview": "nuxt preview",
"generate": "nuxt generate"
},
"dependencies": {
"nuxt": "^3.15.0",
"vue": "^3.5.13",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@nuxtjs/tailwindcss": "^6.12.2",
"typescript": "^5.7.2"
},
"engines": {
"node": ">=20.10.0"
},
"packageManager": "pnpm@10.14.0"
}
Figma 设计稿还原精度提升方案(Design-to-Code 平台)
## 一、平台现状与核心瓶颈
在现有实现中,平台已经具备「Figma → DSL →(AI/规则引擎)→ Vue 3 + Tailwind」的完整流水线,但还原精度受限于以下几点:
### 1. DSL 信息严重不完整(最核心问题)
`figmaParser.ts` 在从 Figma JSON 到 DSL 的过程中丢弃了大量关键字段:
- **视觉相关**
- `opacity` / `blendMode`:透明度、混合模式丢失
- `effects`(`DROP_SHADOW` / `INNER_SHADOW` / `LAYER_BLUR` 等):阴影、毛玻璃、模糊无法还原
- 图片类型 `fills`:背景图/图片节点缺乏清晰标记
- **布局与尺寸相关**
- `primaryAxisSizingMode` / `counterAxisSizingMode`:`HUG` / `FILL` / `FIXED` 未保留,所有尺寸退化为固定像素
- `layoutGrow`:`flex-grow` 行为缺失,子元素无法按设计拉伸
- `layoutAlign`:子元素在交叉轴上的对齐(如 `STRETCH`)丢失
- `layoutWrap` / `counterAxisSpacing`:无法生成 `flex-wrap` 和多行间距
- `clipsContent`:是否需要 `overflow: hidden` 缺失
- `minWidth` / `maxWidth` 等约束信息缺失
- **边框与描边**
- `strokeWeight` / `strokeAlign` / `strokes`:border 宽度、位置、颜色无法重建
- **文本排版**
- `lineHeightPx` / `lineHeightUnit`:行高信息未充分利用
- `fontFamily` / `italic` / `textDecoration`:字体族、斜体、下划线等缺失
- **设计系统相关**
- `variables`(Figma Variables):设计 Token 无法映射到 CSS 变量 / Tailwind Token
目前使用 `GET /v1/files/:fileKey` 拉整文件,对复杂文件既低效又噪声多,更适合改为:
- `GET /v1/nodes/:fileKey?ids=:nodeId`:只拉取目标节点及其子树 → 更精准、更轻量。
### 2. AI Prompt 工程过于简单
现有 `DEFAULT_SYSTEM_PROMPT` 主要是风格与输出格式约束,缺少:
- DSL 字段的语义说明(AI 不知道每个数值字段真正含义与用法)
- few-shot 示范(典型卡片、导航栏、表单等模式的“DSL → 代码”示例)
- 对 `layoutGrow`、`clipsContent`、`effects`、sizing mode 等关键字段的明确使用规则
- 更高的上下文容量(`max_tokens` 仅 4096,对复杂页面偏紧)
### 3. 规则引擎覆盖面窄,更多只是兜底
当前 `vueGenerator.ts` 仅支持 Auto Layout → Flex 的简单映射:
- 非 Auto Layout(绝对定位)节点缺乏支持
- 未覆盖阴影、渐变、图片填充、描边等效果
- 节点一律 `<div>/<span>`,缺少语义标签(`button/nav/header/main/section` 等)
整体来看,架构路径是对的,但输入信号(DSL + Prompt)远没有把 Figma 设计中的关键信息“喂”充分。
---
## 二、改进建议(按优先级排序)
### 1. 视觉引用 + 多模态 AI(最高 ROI)
**目标:让模型既能“看图”,又能“读数据”。**
当前 AI 仅接收 DSL JSON,对复杂视觉效果(层级关系、对比度、留白、视觉节奏)很难仅凭数字精确还原。建议:
- 从 Figma 同时获取:
- `GET /v1/nodes/:fileKey?ids=:nodeId` → 精准节点 DSL(树)
- `GET /v1/images/:fileKey?ids=:nodeId` → 节点截图 PNG(或整帧截图)
- 后端调用多模态模型(如 GPT-4o、Claude 3.5 Sonnet 等)时:
- **system**:详细生成规范 + DSL 字段说明
- **user(image)**:Figma 节点截图,让模型“看到”真实设计
- **user(text)**:DSL JSON,让模型“读懂”精确尺寸与属性
这可以显著提升:
- 层叠关系、阴影强度、圆角/留白的整体节奏
- 文本与图标的对齐细节
- 复杂卡片、Dashboard、表格类 UI 的整体布局
这是在不大改整体架构前提下,单点收益最大的提升手段。
### 2. 修复与扩充 DSL 信息提取
在 `figmaParser.ts` 中扩展 `toDSLNode`,尽量无损保留与视觉/布局强相关的字段,例如(伪代码):
// 尺寸模式(HUG / FILL / FIXED)
if (node.primaryAxisSizingMode)
dsl.primaryAxisSizingMode = node.primaryAxisSizingMode
if (node.counterAxisSizingMode)
dsl.counterAxisSizingMode = node.counterAxisSizingMode
if (node.layoutGrow !== undefined)
dsl.layoutGrow = node.layoutGrow
if (node.layoutAlign)
dsl.layoutAlign = node.layoutAlign
// 透明度与效果
if (node.opacity !== undefined && node.opacity !== 1)
dsl.opacity = node.opacity
if (node.effects?.length)
dsl.effects = node.effects
if (node.clipsContent)
dsl.clipsContent = true
// 描边
if (node.strokes?.length && node.strokeWeight) {
dsl.strokeWeight = node.strokeWeight
dsl.strokeAlign = node.strokeAlign
}
// 文本扩展
if (node.type === 'TEXT' && node.style) {
dsl.textStyle = {
...dsl.textStyle,
lineHeightPx: node.style.lineHeightPx,
lineHeightUnit: node.style.lineHeightUnit,
fontFamily: node.style.fontFamily,
italic: node.style.italic,
textDecoration: node.style.textDecoration,
}
}
// 布局换行
if (node.layoutWrap)
dsl.layoutWrap = node.layoutWrap
if (node.counterAxisSpacing)
dsl.counterAxisSpacing = node.counterAxisSpacing
This diff could not be displayed because it is too large.
# AI 提示词
此文件夹用于存放自定义 AI 系统提示词,供 Design-to-Code 生成 Vue 代码时使用。
- 在页面中编辑提示词后,点击「保存到本地」即可将提示词保存到此文件夹
- 文件格式为 `.md`,便于阅读和维护
- 可在项目中统一管理、版本控制与团队共享
你是一名前端专家,负责将 Figma 设计稿的 JSON 结构(DSL)转换为高质量、可维护的 Vue 3 单文件组件代码。请严格遵循以下规范:
**核心目标:**
根据输入的 Figma DSL 数据,精准生成语义化、响应式且样式一致的 Vue 3 模板代码。
**输出要求:**
1. **组件格式**:生成标准的 Vue 3 单文件组件(.vue),包含 `<template>`、`<script setup>` 和 `<style>` 部分。
2. **模板与标签**:
* 使用语义化的 HTML5 标签(如 `<header>`、`<nav>`、`<main>`、`<section>`)。
* 为可交互元素(如按钮、链接)添加合理的鼠标悬停(`hover:`)和焦点(`focus:`)状态样式。
* 图片元素(`<img>`)必须包含有意义的 `alt` 属性描述。
3. **样式与 Tailwind CSS**:
* 所有样式必须且仅使用 Tailwind CSS 工具类实现,不在 `<style>` 标签内编写 CSS 规则。
* `<style>` 标签仅用于添加 `scoped` 属性,即 `<style scoped>`。
* 颜色、间距、字体大小等样式值须与 Figma DSL 中的设计令牌(Design Tokens)严格对应。
4. **响应式设计**:使用 Tailwind 响应式前缀(如 `md:`、`lg:`)实现设计稿中定义的断点布局变化。
5. **代码质量**:
* 代码应整洁、格式规范,符合 Vue 3 最佳实践。
* 对于重复的结构(如列表项),使用 `v-for` 进行高效渲染。
* 为必要的元素绑定合理的动态数据或事件占位符(如 `@click`)。
**输入与输出格式:**
* **输入**:用户将提供一份 Figma 设计稿的 JSON(DSL)描述。
* **输出**:你只需直接输出完整的 Vue 单文件组件代码,无需任何额外解释或注释。
\ No newline at end of file
你是一名前端专家,负责将 Figma 设计稿的 JSON 结构(DSL)转换为高质量、可维护的 Vue 3 单文件组件代码。请严格遵循以下规范:
**一、核心目标**
根据输入的 Figma DSL 数据,精准生成语义化、响应式且样式一致的 Vue 3 模板代码。
**二、组件结构与格式**
1. 输出必须是完整的 Vue 3 单文件组件(.vue),包含 `<template>`、`<script setup>` 和 `<style>` 三个部分。
2. 在 `<script setup>` 中,无需引入 Vue 或定义组件名,除非 DSL 中有明确的交互逻辑需要声明响应式数据或方法。
3. `<style>` 标签仅用于添加 `scoped` 属性,即写作 `<style scoped>`,其内部不编写任何 CSS 规则。
**三、模板与 HTML 规范**
1. **语义化标签**:使用恰当的 HTML5 语义化标签(如 `<header>`、`<nav>`、`<main>`、`<section>`、`<article>`、`<aside>`、`<footer>`)。
2. **可交互元素**:为按钮、链接等可交互元素添加合理的 `hover:` 和 `focus:` 状态样式。
3. **图片处理**:所有 `<img>` 标签必须包含描述性的 `alt` 属性。`src` 可使用占位符或 DSL 中提供的路径。
4. **列表渲染**:对于重复出现的列表项等结构,必须使用 `v-for` 进行循环渲染,确保代码简洁高效。
5. **事件占位符**:为需要交互的元素(如按钮)绑定合理的事件占位符,例如 `@click="handleClick"`。
**四、样式与 Tailwind CSS 规范**
1. **唯一样式方案**:所有视觉样式必须且仅能通过 Tailwind CSS 工具类实现。
2. **设计令牌映射**:颜色、字体大小、字体粗细、间距(padding, margin)、圆角、阴影等样式值,必须与 Figma DSL 中提供的设计令牌(Design Tokens)严格对应。
3. **响应式实现**:使用 Tailwind CSS 的响应式前缀(如 `sm:`、`md:`、`lg:`、`xl:`)来实现 DSL 中定义的不同断点下的布局与样式变化。
**五、代码质量与输入输出**
1. **代码风格**:代码应整洁、格式规范,符合 Vue 3 组合式 API 的最佳实践。
2. **输入**:你将收到一份 Figma 设计稿的 JSON(DSL)描述。
3. **输出**:你只需直接输出完整的、可运行的 Vue 单文件组件代码,无需任何额外的解释、注释或说明文字。
\ No newline at end of file
import { parseFigmaUrl, fetchFigmaFile, buildDSL } from '../../utils/figmaParser'
/**
* POST /api/figma/dsl
* 输入:{ figmaUrl: string }
* 输出:DSLResult { meta, root }
*/
export default defineEventHandler(async (event) => {
const body = await readBody<{ figmaUrl?: string }>(event)
const { figmaUrl } = body ?? {}
if (!figmaUrl?.trim()) {
throw createError({ statusCode: 400, message: '请提供有效的 figmaUrl 参数' })
}
const config = useRuntimeConfig()
const token = config.figmaToken as string
if (!token) {
throw createError({
statusCode: 500,
message: '服务端未配置 FIGMA_PERSONAL_ACCESS_TOKEN,请在 .env 文件中设置',
})
}
try {
const { fileKey, nodeId } = parseFigmaUrl(figmaUrl)
const figmaData = await fetchFigmaFile(fileKey, token, nodeId)
const dsl = buildDSL(figmaData, fileKey, nodeId)
return dsl
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '生成 DSL 失败'
throw createError({ statusCode: 500, message })
}
})
import { parseFigmaUrl, fetchFigmaFile, buildDSL } from '../../utils/figmaParser'
import { dslToVueSFC } from '../../utils/vueGenerator'
import { generateVueWithAI, isAiConfigured, type AIConfig } from '../../utils/aiGenerator'
import type { VueGenerateResult } from '../../utils/types'
/**
* POST /api/figma/vue
* 输入:{ figmaUrl: string; componentName?: string; prompt?: string }
* 输出:VueGenerateResult { dsl, vue: { componentName, code, source } }
*
* 生成策略:
* 1. 若配置了 AI_API_KEY → 优先使用 AI 生成
* 2. AI 失败 → 自动降级到规则引擎
* 3. 未配置 AI → 直接使用规则引擎
*/
export default defineEventHandler(async (event) => {
const body = await readBody<{
figmaUrl?: string
componentName?: string
prompt?: string
}>(event)
const { figmaUrl, componentName = 'GeneratedComponent', prompt } = body ?? {}
if (!figmaUrl?.trim()) {
throw createError({ statusCode: 400, message: '请提供有效的 figmaUrl 参数' })
}
const config = useRuntimeConfig()
const token = config.figmaToken as string
if (!token) {
throw createError({
statusCode: 500,
message: '服务端未配置 FIGMA_PERSONAL_ACCESS_TOKEN,请在 .env 文件中设置',
})
}
try {
// 1. 解析 Figma URL 并拉取设计数据
const { fileKey, nodeId } = parseFigmaUrl(figmaUrl)
const figmaData = await fetchFigmaFile(fileKey, token, nodeId)
const dsl = buildDSL(figmaData, fileKey, nodeId)
// 2. 生成 Vue SFC(AI 优先,规则引擎兜底)
let vueCode: string
let source: 'ai' | 'rule' = 'rule'
const aiConfig: AIConfig = {
apiKey: (config.aiApiKey as string) || '',
baseUrl: (config.aiBaseUrl as string) || 'https://api.openai.com/v1',
model: (config.aiModel as string) || 'gpt-4o-mini',
}
if (isAiConfigured(aiConfig)) {
try {
vueCode = await generateVueWithAI(dsl.root, componentName, aiConfig, prompt)
source = 'ai'
console.log(`[D2C] AI 生成成功,模型:${aiConfig.model}`)
} catch (aiErr) {
console.warn('[D2C] AI 生成失败,自动降级到规则引擎:', aiErr)
vueCode = dslToVueSFC(dsl.root, { componentName })
}
} else {
vueCode = dslToVueSFC(dsl.root, { componentName })
console.log('[D2C] 未配置 AI,使用规则引擎生成')
}
const result: VueGenerateResult = {
dsl,
vue: {
componentName,
code: vueCode,
source,
},
}
return result
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '生成 Vue 代码失败'
throw createError({ statusCode: 500, message })
}
})
import { readdir, readFile, stat } from 'node:fs/promises'
import { join } from 'node:path'
export interface PromptItem {
filename: string
path: string
content: string
updatedAt: string
}
export default defineEventHandler(async (event) => {
const query = getQuery(event)
const includeContent = query.content !== '0' && query.content !== 'false'
const promptDir = join(process.cwd(), 'prompt')
let files: string[] = []
try {
files = await readdir(promptDir)
} catch {
return { items: [] as PromptItem[] }
}
const items: PromptItem[] = []
for (const f of files) {
if (!f.endsWith('.md') || f === 'README.md') continue
const filePath = join(promptDir, f)
try {
const st = await stat(filePath)
const content = includeContent
? await readFile(filePath, 'utf-8')
: ''
items.push({
filename: f,
path: `prompt/${f}`,
content,
updatedAt: st.mtime.toISOString(),
})
} catch {
// 跳过无法读取的文件
}
}
// 按更新时间倒序
items.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
return { items }
})
import { isAiConfigured, type AIConfig } from '../../utils/aiGenerator'
interface OptimizePromptBody {
prompt?: string
}
interface OptimizePromptResult {
prompt: string
}
export default defineEventHandler(async (event): Promise<OptimizePromptResult> => {
const body = await readBody<OptimizePromptBody>(event)
const originalPrompt = body?.prompt?.trim()
if (!originalPrompt) {
throw createError({
statusCode: 400,
message: '请提供要优化的提示词内容',
})
}
const config = useRuntimeConfig()
const aiConfig: AIConfig = {
apiKey: (config.aiApiKey as string) || '',
baseUrl: (config.aiBaseUrl as string) || 'https://api.openai.com/v1',
model: (config.aiModel as string) || 'gpt-4o-mini',
}
if (!isAiConfigured(aiConfig)) {
throw createError({
statusCode: 500,
message: '服务端未配置 AI_API_KEY/AI_BASE_URL/AI_MODEL,无法优化提示词',
})
}
const systemPrompt =
'你是一名专业的 Prompt Engineer,擅长为前端代码生成任务优化中文提示词。' +
'请在保持原始意图不变的前提下,使提示词更加清晰、结构化、可执行,适合用于指导大模型将 Figma DSL 转换为 Vue 3 + Tailwind 代码。' +
'直接输出优化后的提示词文本,不要解释,不要添加 Markdown 代码块。'
const userMessage = `请优化下面这段用于“Figma 设计稿 DSL → Vue 3 + Tailwind 组件生成”的系统提示词:
---------------- 原始提示词 ----------------
${originalPrompt}
------------------------------------------
请在保留核心意图的前提下:
1. 补全关键约束(如组件结构、语义化标签、Tailwind 使用等)
2. 使用条列式结构,逻辑更清晰
3. 使用简洁专业的中文表述。
`
const response = await fetch(`${aiConfig.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${aiConfig.apiKey}`,
},
body: JSON.stringify({
model: aiConfig.model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage },
],
temperature: 0.4,
max_tokens: 1024,
}),
})
if (!response.ok) {
const errText = await response.text()
throw createError({
statusCode: 500,
message: `提示词优化失败 (HTTP ${response.status}):${errText}`,
})
}
const data = (await response.json()) as {
choices?: Array<{ message?: { content?: string } }>
}
const optimized = data.choices?.[0]?.message?.content?.trim()
if (!optimized) {
throw createError({
statusCode: 500,
message: '提示词优化失败:AI 未返回有效内容',
})
}
return {
prompt: optimized,
}
})
import { writeFile, mkdir } from 'node:fs/promises'
import { join } from 'node:path'
interface SavePromptBody {
prompt: string
name?: string
}
/** 校验文件名,防止路径遍历 */
function sanitizeFilename(name: string): string {
return name.replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g, '-').replace(/-+/g, '-') || 'prompt'
}
export default defineEventHandler(async (event) => {
const body = await readBody<SavePromptBody>(event)
const prompt = body?.prompt?.trim()
const name = body?.name?.trim()
if (!prompt) {
throw createError({
statusCode: 400,
message: '请提供要保存的提示词内容',
})
}
const promptDir = join(process.cwd(), 'prompt')
await mkdir(promptDir, { recursive: true })
const baseName = name ? sanitizeFilename(name) : `prompt-${Date.now()}`
const filename = `${baseName}.md`
const filePath = join(promptDir, filename)
await writeFile(filePath, prompt, 'utf-8')
return {
success: true,
path: `prompt/${filename}`,
filename,
}
})
import type { FigmaNodeDSL } from './types'
export interface AIConfig {
apiKey: string
baseUrl: string
model: string
}
const DEFAULT_SYSTEM_PROMPT = `你是一个专业的 Vue 3 前端工程师,擅长将设计稿 DSL 转换为高质量、可维护的 Vue 3 单文件组件。
请严格遵循以下规则:
1. 使用 Tailwind CSS 实现所有样式,优先使用语义化工具类
2. 使用语义化 HTML 标签(button、nav、header、main、section、article、p、h1-h6 等)
3. 布局必须与 DSL 描述一致,保持相对尺寸比例
4. 颜色直接使用 style 属性(rgba 格式)或 Tailwind 任意值语法
5. 使用 <script setup lang="ts"> 语法
6. 只输出完整的 .vue 文件内容,不要使用任何 markdown 代码块包裹(不要 \`\`\`vue ... \`\`\`)
7. 不要添加多余的注释,保持代码简洁`
/**
* 检查 AI 配置是否完整
*/
export function isAiConfigured(config: AIConfig): boolean {
return !!(config.apiKey && config.baseUrl && config.model)
}
/**
* 使用 AI 模型将 DSL 转换为 Vue SFC
* 支持 OpenAI、DeepSeek 等兼容 OpenAI 格式的 API
*/
export async function generateVueWithAI(
dslRoot: FigmaNodeDSL,
componentName: string,
config: AIConfig,
customPrompt?: string,
): Promise<string> {
const systemPrompt = customPrompt?.trim() || DEFAULT_SYSTEM_PROMPT
const userMessage = `请将以下 Figma 设计稿 DSL 转换为 Vue 3 单文件组件,组件名称为 \`${componentName}\`。
DSL 数据:
\`\`\`json
${JSON.stringify(dslRoot, null, 2)}
\`\`\``
const response = await fetch(`${config.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.apiKey}`,
},
body: JSON.stringify({
model: config.model,
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userMessage },
],
temperature: 0.3,
max_tokens: 4096,
}),
})
if (!response.ok) {
const errText = await response.text()
throw new Error(`AI API 请求失败 (HTTP ${response.status}):${errText}`)
}
const data = (await response.json()) as {
choices?: Array<{ message?: { content?: string } }>
}
const content = data.choices?.[0]?.message?.content ?? ''
// 移除可能存在的 markdown 代码块包裹
return content
.replace(/^```(?:vue|html)?\s*\n?/, '')
.replace(/\n?```\s*$/, '')
.trim()
}
import type { FigmaNodeDSL, FigmaFill, DSLResult } from './types'
/**
* 从 Figma URL 中解析 fileKey 和 nodeId
* 支持格式:
* - https://www.figma.com/design/:fileKey/:name?node-id=xxx
* - https://www.figma.com/file/:fileKey/:name?node-id=xxx
*/
export function parseFigmaUrl(url: string): { fileKey: string; nodeId: string | null } {
const fileKeyMatch = url.match(/figma\.com\/(?:design|file)\/([^/?#]+)/)
if (!fileKeyMatch) {
throw new Error('无效的 Figma URL,无法提取 fileKey,请确认链接格式正确')
}
const fileKey = fileKeyMatch[1]
const nodeIdMatch = url.match(/node-id=([^&#]+)/)
let nodeId: string | null = null
if (nodeIdMatch) {
// Figma URL 中的 node-id 使用连字符,API 中使用冒号
nodeId = decodeURIComponent(nodeIdMatch[1]).replace(/-/g, ':')
}
return { fileKey, nodeId }
}
/**
* 调用 Figma REST API 拉取文件 JSON
*/
export async function fetchFigmaFile(
fileKey: string,
token: string,
nodeId?: string | null
): Promise<any> {
const baseUrl = 'https://api.figma.com/v1'
console.log('nodeId', nodeId)
const url = nodeId
? `${baseUrl}/files/${fileKey}/nodes?ids=${encodeURIComponent(nodeId)}`
: `${baseUrl}/files/${fileKey}`
console.log('url', url)
const res = await fetch(url, {
headers: { 'X-Figma-Token': token },
})
if (!res.ok) {
const errText = await res.text()
throw new Error(`Figma API 请求失败 (HTTP ${res.status}):${errText}`)
}
const data = await res.json()
// 若按节点维度拉取,仅保留目标节点子树,使下游逻辑保持兼容(仍然有 document 根节点)
if (nodeId) {
const nodeEntry = data.nodes?.[nodeId]
if (!nodeEntry || !nodeEntry.document) {
throw new Error(`Figma API 返回中未找到节点(nodeId: ${nodeId})`)
}
return {
name: data.name,
document: nodeEntry.document,
}
}
return data
}
/**
* 将 Figma 原始节点转换为精简的 DSL 节点
* 去除噪声字段,保留布局/尺寸/颜色/文本/圆角等关键属性
*/
function toDSLNode(node: any): FigmaNodeDSL {
const dsl: FigmaNodeDSL = {
id: node.id,
name: node.name,
type: node.type,
}
if (node.visible === false) dsl.visible = false
// 尺寸和位置
if (node.absoluteBoundingBox) {
dsl.width = Math.round(node.absoluteBoundingBox.width)
dsl.height = Math.round(node.absoluteBoundingBox.height)
dsl.x = Math.round(node.absoluteBoundingBox.x)
dsl.y = Math.round(node.absoluteBoundingBox.y)
}
// 文本节点
if (node.type === 'TEXT') {
dsl.text = node.characters ?? ''
if (node.style) {
dsl.textStyle = {
fontFamily: node.style.fontFamily,
fontSize: node.style.fontSize,
fontWeight: node.style.fontWeight,
lineHeightPx: node.style.lineHeightPx,
textAlignHorizontal: node.style.textAlignHorizontal,
letterSpacing: node.style.letterSpacing,
}
}
}
// 填充和描边
if (node.fills?.length) dsl.fills = node.fills as FigmaFill[]
if (node.strokes?.length) dsl.strokes = node.strokes as FigmaFill[]
// 圆角
if (node.rectangleCornerRadii) {
dsl.cornerRadius = node.rectangleCornerRadii as number[]
} else if (node.cornerRadius !== undefined) {
dsl.cornerRadius = node.cornerRadius as number
}
// Auto Layout
if (node.layoutMode && node.layoutMode !== 'NONE') {
dsl.layoutMode = node.layoutMode
dsl.primaryAxisAlignItems = node.primaryAxisAlignItems
dsl.counterAxisAlignItems = node.counterAxisAlignItems
if (node.itemSpacing) dsl.itemSpacing = node.itemSpacing
const top = node.paddingTop
const right = node.paddingRight
const bottom = node.paddingBottom
const left = node.paddingLeft
if (top || right || bottom || left) {
dsl.padding = { top, right, bottom, left }
}
}
// 递归处理子节点
if (node.children?.length) {
dsl.children = node.children.map(toDSLNode)
}
return dsl
}
/**
* 深度优先搜索指定 nodeId 的节点
* 未指定 nodeId 时取首页第一个子节点
*/
function findTargetNode(figmaData: any, nodeId: string | null): any {
const document = figmaData.document
if (!nodeId) {
const firstPage = document?.children?.[0]
return firstPage?.children?.[0] ?? firstPage ?? document
}
function dfs(node: any): any {
if (!node) return null
if (node.id === nodeId) return node
if (node.children) {
for (const child of node.children) {
const found = dfs(child)
if (found) return found
}
}
return null
}
return dfs(document)
}
/**
* 构建完整 DSL 对象(包含 meta 信息)
*/
export function buildDSL(figmaData: any, fileKey: string, nodeId: string | null): DSLResult {
const targetNode = findTargetNode(figmaData, nodeId)
if (!targetNode) {
throw new Error(`未找到目标节点(nodeId: ${nodeId ?? '自动取首个节点'}),请检查节点 ID 是否正确`)
}
return {
meta: {
figmaFileKey: fileKey,
figmaNodeId: nodeId,
name: figmaData.name ?? targetNode.name,
generatedAt: new Date().toISOString(),
},
root: toDSLNode(targetNode),
}
}
// Figma 设计稿转换后的 DSL 节点结构
export interface FigmaNodeDSL {
id: string
name: string
type: string
visible?: boolean
width?: number
height?: number
x?: number
y?: number
children?: FigmaNodeDSL[]
text?: string
textStyle?: {
fontFamily?: string
fontSize?: number
fontWeight?: number
lineHeightPx?: number
textAlignHorizontal?: string
letterSpacing?: number
}
fills?: FigmaFill[]
strokes?: FigmaFill[]
cornerRadius?: number | number[]
layoutMode?: 'HORIZONTAL' | 'VERTICAL' | 'NONE'
primaryAxisAlignItems?: 'MIN' | 'CENTER' | 'MAX' | 'SPACE_BETWEEN'
counterAxisAlignItems?: 'MIN' | 'CENTER' | 'MAX'
itemSpacing?: number
padding?: {
top?: number
right?: number
bottom?: number
left?: number
}
}
export interface FigmaFill {
type: 'SOLID' | 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'IMAGE'
visible?: boolean
opacity?: number
color?: { r: number; g: number; b: number; a?: number }
}
export interface DSLMeta {
figmaFileKey: string
figmaNodeId: string | null
name: string
generatedAt: string
}
export interface DSLResult {
meta: DSLMeta
root: FigmaNodeDSL
}
export interface VueGenerateResult {
dsl: DSLResult
vue: {
componentName: string
code: string
source: 'ai' | 'rule'
}
}
import type { FigmaNodeDSL, FigmaFill } from './types'
/**
* 将 Figma RGBA 颜色值转换为 CSS rgba() 字符串
*/
function toRgba(fills: FigmaFill[] | undefined): string | null {
if (!fills?.length) return null
const solid = fills.find(f => f.type === 'SOLID' && f.visible !== false)
if (!solid?.color) return null
const { r, g, b, a = 1 } = solid.color
return `rgba(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)},${a.toFixed(2)})`
}
/**
* 将 DSL 节点属性映射为 Tailwind CSS 类名和内联样式
*/
function buildStyles(node: FigmaNodeDSL): { cls: string; style: string } {
const cls: string[] = []
const styleMap: string[] = []
// Auto Layout → Flexbox
if (node.layoutMode === 'HORIZONTAL') {
cls.push('flex', 'flex-row')
const ca = node.counterAxisAlignItems
const pa = node.primaryAxisAlignItems
if (ca === 'CENTER') cls.push('items-center')
else if (ca === 'MAX') cls.push('items-end')
if (pa === 'CENTER') cls.push('justify-center')
else if (pa === 'MAX') cls.push('justify-end')
else if (pa === 'SPACE_BETWEEN') cls.push('justify-between')
} else if (node.layoutMode === 'VERTICAL') {
cls.push('flex', 'flex-col')
const ca = node.counterAxisAlignItems
const pa = node.primaryAxisAlignItems
if (ca === 'CENTER') cls.push('items-center')
else if (ca === 'MAX') cls.push('items-end')
if (pa === 'CENTER') cls.push('justify-center')
else if (pa === 'MAX') cls.push('justify-end')
else if (pa === 'SPACE_BETWEEN') cls.push('justify-between')
}
// 尺寸
if (node.width) cls.push(`w-[${node.width}px]`)
if (node.height) cls.push(`h-[${node.height}px]`)
// 内边距
if (node.padding) {
const { top, right, bottom, left } = node.padding
if (top) cls.push(`pt-[${top}px]`)
if (right) cls.push(`pr-[${right}px]`)
if (bottom) cls.push(`pb-[${bottom}px]`)
if (left) cls.push(`pl-[${left}px]`)
}
// 间距
if (node.itemSpacing) cls.push(`gap-[${node.itemSpacing}px]`)
// 圆角
if (node.cornerRadius) {
if (typeof node.cornerRadius === 'number' && node.cornerRadius > 0) {
cls.push(`rounded-[${node.cornerRadius}px]`)
} else if (Array.isArray(node.cornerRadius)) {
const [tl, tr, br, bl] = node.cornerRadius
styleMap.push(`border-radius: ${tl}px ${tr}px ${br}px ${bl}px`)
}
}
// 文本样式
if (node.textStyle) {
const { fontSize, fontWeight, textAlignHorizontal } = node.textStyle
if (fontSize) cls.push(`text-[${fontSize}px]`)
if (fontWeight) {
if (fontWeight >= 700) cls.push('font-bold')
else if (fontWeight >= 600) cls.push('font-semibold')
else if (fontWeight >= 500) cls.push('font-medium')
else cls.push('font-normal')
}
if (textAlignHorizontal === 'CENTER') cls.push('text-center')
else if (textAlignHorizontal === 'RIGHT') cls.push('text-right')
else if (textAlignHorizontal === 'LEFT') cls.push('text-left')
const textColor = toRgba(node.fills)
if (textColor) styleMap.push(`color: ${textColor}`)
}
// 背景色(非文本节点)
if (node.type !== 'TEXT') {
const bgColor = toRgba(node.fills)
if (bgColor) styleMap.push(`background-color: ${bgColor}`)
}
return {
cls: cls.join(' '),
style: styleMap.join('; '),
}
}
/**
* 递归将 DSL 节点渲染为 HTML 字符串
*/
function renderNode(node: FigmaNodeDSL, indent = 4): string {
const { cls, style } = buildStyles(node)
const pad = ' '.repeat(indent)
const clsAttr = cls ? ` class="${cls}"` : ''
const styleAttr = style ? ` style="${style}"` : ''
if (node.type === 'TEXT') {
return `${pad}<span${clsAttr}${styleAttr}>${node.text ?? ''}</span>`
}
if (!node.children?.length) {
return `${pad}<div${clsAttr}${styleAttr}></div>`
}
const children = node.children.map(c => renderNode(c, indent + 2)).join('\n')
return `${pad}<div${clsAttr}${styleAttr}>\n${children}\n${pad}</div>`
}
export interface VueSFCOptions {
componentName?: string
}
/**
* 将 DSL 根节点转换为完整的 Vue 3 SFC 文件内容
*/
export function dslToVueSFC(root: FigmaNodeDSL, options: VueSFCOptions = {}): string {
const { componentName = 'GeneratedComponent' } = options
const template = renderNode(root, 4)
return `<template>
<div>
${template}
</div>
</template>
<script setup lang="ts">
// ${componentName}
// Generated by Design-to-Code Platform (Rule Engine)
</script>
`
}
import type { Config } from 'tailwindcss'
export default {
content: [
'./components/**/*.{vue,js,ts}',
'./layouts/**/*.vue',
'./pages/**/*.vue',
'./app.vue',
],
theme: {
extend: {
fontFamily: {
mono: ['JetBrains Mono', 'Fira Code', 'Cascadia Code', 'Consolas', 'monospace'],
},
colors: {
gray: {
950: '#030712',
},
},
},
},
} satisfies Config
......@@ -49,7 +49,11 @@
"venus:create": "pnpm venus create",
"venus:create:interactive": "pnpm venus create",
"venus:ls": "pnpm venus ls-templates",
"command:test": "node scripts/build/commandTest.mjs"
"command:test": "node scripts/build/commandTest.mjs",
"install:d2c": "pnpm --dir d2c install --ignore-workspace",
"dev:d2c": "pnpm --dir d2c run dev",
"build:d2c": "pnpm --dir d2c run build",
"preview:d2c": "pnpm --dir d2c run preview"
},
"dependencies": {
"glsk-toolkit": "catalog:"
......
......@@ -639,6 +639,14 @@ importers:
specifier: ^6.3.5
version: 6.4.1(@types/node@24.10.4)(jiti@2.6.1)(lightningcss@1.31.1)(sass@1.97.2)(terser@5.44.1)(yaml@2.8.2)
apps/uniappX/uniapp-x-simgle/unpackage/dist/build/app-android/uni_modules/lime-sqlite:
dependencies:
sql.js:
specifier: ^1.13.0
version: 1.14.0
apps/uniappX/uniapp-x-simgle/unpackage/dist/build/app-android/uni_modules/uview-unix: {}
apps/uniappX/uniapp-x-tape:
dependencies:
'@types/echarts':
......@@ -761,6 +769,20 @@ importers:
apps/uniappX/uniapp-x-tape/uni_modules/z-paging-x: {}
apps/uniappX/uniapp-x-tape/unpackage/dist/build/app-android/uni_modules/lime-sqlite:
dependencies:
sql.js:
specifier: ^1.13.0
version: 1.14.0
apps/uniappX/uniapp-x-tape/unpackage/dist/build/app-android/uni_modules/uview-unix: {}
apps/uniappX/uniapp-x-tape/unpackage/dist/build/app-ios/uni_modules/lime-sqlite:
dependencies:
sql.js:
specifier: ^1.13.0
version: 1.14.0
apps/web/venus-agentic/venus-agentic-assisant:
dependencies:
'@element-plus/icons-vue':
......@@ -10677,7 +10699,6 @@ packages:
vue-i18n@9.14.5:
resolution: {integrity: sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==}
engines: {node: '>= 16'}
deprecated: v9 and v10 no longer supported. please migrate to v11. about maintenance status, see https://vue-i18n.intlify.dev/guide/maintenance.html
peerDependencies:
vue: ^3.5.17
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!