This commit is contained in:
wfz
2026-01-20 21:53:09 +08:00
parent 4a90340ab3
commit bfa4e3107f
23 changed files with 2154 additions and 592 deletions

166
README.md Normal file
View File

@@ -0,0 +1,166 @@
# Fauto Design - Vue页面可视化设计器
<p align="center">
<img src="https://img.shields.io/badge/Vue-3.5-4FC08D?logo=vue.js" alt="Vue 3">
<img src="https://img.shields.io/badge/TypeScript-5.x-3178C6?logo=typescript" alt="TypeScript">
<img src="https://img.shields.io/badge/Vite-7.3-646CFF?logo=vite" alt="Vite">
<img src="https://img.shields.io/badge/Element%20Plus-Latest-409EFF" alt="Element Plus">
<img src="https://img.shields.io/badge/Node.js-22.x-339933?logo=node.js" alt="Node.js">
</p>
<p align="center">
<strong>🤖 本项目完全由 Qoder AI 开发,所有代码均为 AI 生成</strong>
</p>
---
## 📖 项目简介
**Fauto Design** 是一个基于 Vue3 的**可视化页面设计器**,通过拖拽操作直接编辑真实的 Vue 源文件。与传统低代码平台不同,本项目直接操作 `.vue` 文件,生成的代码即是最终代码。
### ✨ 核心特性
- 🎯 **直接编辑源码** - 拖拽操作实时修改 Vue 文件,所见即所得
- 🖱️ **智能拖拽交互** - 两阶段拖拽:先选源元素层级,再选目标位置
- ⌨️ **键盘层级选择** - ↑↓ 键切换嵌套元素层级,精准定位
- 🔄 **跨类型拖放** - 支持 el-row/el-col 之间的灵活布局调整
- 📝 **保持代码格式** - AST 解析 + 智能缩进,保持源码整洁
---
## 🏗️ 技术架构
```
┌─────────────────────────────────────────────────┐
│ 前端 (Vue3 + Vite) │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────┐ │
│ │ PageManager │ │DesignCenter│ │DropZone │ │
│ └─────────────┘ └─────────────┘ └─────────┘ │
│ ↓ ↓ ↓ │
│ ┌──────────────────────────────────────────┐ │
│ │ dragStore (Pinia) │ │
│ │ 两阶段拖拽 | 层级选择 | 跨类型判断 │ │
│ └──────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
│ HTTP
┌─────────────────────────────────────────────────┐
│ 后端 (Node.js + Express) │
│ ┌──────────────────────────────────────────┐ │
│ │ templateService.js │ │
│ │ @vue/compiler-sfc | AST解析 | 元素移动 │ │
│ └──────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
Vue 源文件 (*.vue)
```
---
## 🚀 快速开始
### 环境要求
- Node.js >= 18.x
- npm >= 9.x
### 安装依赖
```bash
# 前端
cd draggable-panels
npm install
# 后端
cd vue-template-service
npm install
```
### 启动服务
```bash
# 终端1 - 启动前端 (端口 5173)
cd draggable-panels
npm run dev
# 终端2 - 启动后端 (端口 3001)
cd vue-template-service
node src/index.js
```
### 访问
打开浏览器访问:**http://localhost:5173/draggable**
---
## 📁 项目结构
```
fauto-design/
├── 项目上下文.md # AI 协作上下文文档
├── 项目设计文档.md # 详细技术设计文档
├── README.md # 本文件
├── draggable-panels/ # 前端项目
│ └── src/
│ ├── fauto/ # 设计器核心
│ │ ├── components/ # UI组件
│ │ ├── materials/ # 物料组件
│ │ ├── plugins/ # 核心插件 (dragStore等)
│ │ └── stores/ # 状态管理
│ └── views/ # 示例页面
└── vue-template-service/ # 后端服务
└── src/
└── services/
└── templateService.js # Vue模板解析修改
```
---
## 🎮 使用方法
1. **选择页面** - 在左侧面板选择要编辑的 Vue 页面
2. **开始拖拽** - 点击页面中的 el-row 或 el-col 元素
3. **选择源层级** - 按 ↑↓ 键切换要移动的层级
4. **移动到目标** - 拖动到目标元素上
5. **选择目标层级** - 按 ↑↓ 键切换目标层级
6. **确认位置** - 松开鼠标,选择放置方向(上/下/左/右/内部)
7. **自动保存** - 源文件自动更新,页面热刷新
---
## 🤖 关于 AI 开发
本项目是一个 **AI 驱动开发**的实验性项目:
- **开发工具**Qoder AIAI 编程助手)
- **代码生成**100% 由 AI 生成
- **人工参与**:需求描述、测试反馈、方向指导
这证明了 AI 辅助开发在复杂前端项目中的可行性,包括:
- 状态管理设计
- 拖拽交互实现
- AST 解析与修改
- 多阶段工作流
---
## 📄 相关文档
- [项目上下文.md](./项目上下文.md) - AI 协作快速恢复上下文
- [项目设计文档.md](./项目设计文档.md) - 详细技术设计
---
## 📜 License
MIT License
---
<p align="center">
<strong>🚀 Powered by Qoder AI</strong>
</p>

View File

@@ -1,5 +0,0 @@
# Vue 3 + TypeScript + Vite
This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about the recommended Project Setup and IDE Support in the [Vue Docs TypeScript Guide](https://vuejs.org/guide/typescript/overview.html#project-setup).

View File

@@ -40,112 +40,20 @@
"id": "right",
"tabs": [
{
"id": "vrh9bl2",
"title": "数据表格",
"id": "09w17vo",
"title": "数据",
"content": "新窗口内容",
"materialId": "DataTable",
"materialState": {
"data": [
{
"property": "项目名称",
"value": "1111"
"materialId": "DataTable"
},
{
"property": "框架",
"value": "9999"
},
{
"property": "语言",
"value": "TypeScript"
},
{
"property": "构建工具",
"value": "Vite"
},
{
"property": "状态管理",
"value": "Pinia"
},
{
"property": "版本",
"value": "1.0.0"
},
{
"property": "作者",
"value": "Developer"
},
{
"property": "许可证",
"value": "MIT"
}
]
}
},
{
"id": "mxfx11j",
"title": "树形展示器",
"id": "vihlzl5",
"title": "结构",
"content": "新窗口内容",
"materialId": "TreeViewer",
"materialState": {
"treeData": [
{
"id": "1",
"label": "项目根目录",
"expanded": true,
"children": [
{
"id": "1-1",
"label": "src",
"expanded": true,
"children": [
{
"id": "1-1-2",
"label": "stores"
},
{
"id": "1-1-4",
"label": "App.vue"
},
{
"id": "1-1-5",
"label": "main.ts"
},
{
"id": "1-1-1",
"label": "components"
}
]
},
{
"id": "1-1-3",
"label": "types"
},
{
"id": "1-2",
"label": "public",
"children": [
{
"id": "1-3",
"label": "package.json"
},
{
"id": "1-2-1",
"label": "favicon.ico"
}
]
},
{
"id": "1-4",
"label": "vite.config.ts"
}
]
}
]
}
"materialId": "TreeViewer"
}
],
"activeTabId": "mxfx11j"
"activeTabId": "09w17vo"
}
},
"lastUpdated": "2026-01-20T11:33:21.385Z"
"lastUpdated": "2026-01-20T13:52:38.363Z"
}

View File

@@ -1,9 +1,42 @@
{
"id": "GridTable",
"name": "表格",
"icon": "📊",
"description": "用于展示数据的表格组件",
"props": {
"rows": 3,
"columns": 3,
"headers": ["列1", "列2", "列3"]
"template": "template.html",
"defaultSpan": 24,
"metadata": {
"span": {
"label": "宽度",
"type": "number",
"min": 1,
"max": 24,
"target": "el-col",
"attr": ":span"
},
"size": {
"label": "尺寸",
"type": "select",
"options": ["", "medium", "small", "mini"],
"target": "el-table",
"attr": "size"
},
"stripe": {
"label": "斑马纹",
"type": "boolean",
"target": "el-table",
"attr": "stripe"
},
"border": {
"label": "边框",
"type": "boolean",
"target": "el-table",
"attr": "border"
},
"columns": {
"label": "列配置",
"type": "columns",
"target": "el-table-column"
}
}
}

View File

@@ -1,63 +0,0 @@
<script setup lang="ts">
import { computed } from 'vue'
const props = defineProps<{
rows?: number
columns?: number
headers?: string[]
}>()
const tableRows = computed(() => props.rows || 3)
const tableCols = computed(() => props.columns || 3)
const tableHeaders = computed(() => props.headers || [])
</script>
<template>
<div class="design-grid-table">
<table>
<thead>
<tr>
<th v-for="(header, i) in tableHeaders" :key="i">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in tableRows" :key="row">
<td v-for="col in tableCols" :key="col">
单元格 {{ row }}-{{ col }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.design-grid-table {
padding: 8px;
background: #2d2d2d;
border-radius: 4px;
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
th, td {
padding: 6px 8px;
border: 1px solid #3c3c3c;
text-align: left;
color: #cccccc;
}
th {
background: #1e1e1e;
font-weight: 500;
}
td {
background: #252526;
}
</style>

View File

@@ -0,0 +1,9 @@
<el-col :span="24">
<div class="design-component design-grid-table" data-component="表格">
<el-table :data="tableData" border style="width: 100%">
<el-table-column prop="col1" label="列1" />
<el-table-column prop="col2" label="列2" />
<el-table-column prop="col3" label="列3" />
</el-table>
</div>
</el-col>

View File

@@ -1,7 +1,49 @@
{
"id": "RadioSelect",
"name": "单选器",
"icon": "⭕",
"description": "用于选择单个选项的表单组件",
"props": {
"options": ["选项1", "选项2", "选项3"]
"template": "template.html",
"defaultSpan": 12,
"metadata": {
"span": {
"label": "宽度",
"type": "number",
"min": 1,
"max": 24,
"target": "el-col",
"attr": ":span"
},
"label": {
"label": "标签",
"type": "text",
"target": "el-form-item",
"attr": "label"
},
"size": {
"label": "尺寸",
"type": "select",
"options": ["", "medium", "small", "mini"],
"target": "el-radio-group",
"attr": "size"
},
"disabled": {
"label": "禁用",
"type": "boolean",
"target": "el-radio-group",
"attr": "disabled"
},
"fill": {
"label": "填充色",
"type": "color",
"target": "el-radio-group",
"attr": "fill"
},
"textColor": {
"label": "文字颜色",
"type": "color",
"target": "el-radio-group",
"attr": "text-color"
}
}
}

View File

@@ -1,75 +0,0 @@
<script setup lang="ts">
import { ref } from 'vue'
const props = defineProps<{
options?: string[]
}>()
const selected = ref<string | null>(null)
</script>
<template>
<div class="design-radio-select">
<div
v-for="option in (options || [])"
:key="option"
class="radio-item"
@click="selected = option"
>
<span class="radio-circle" :class="{ active: selected === option }">
<span class="radio-dot" v-if="selected === option"></span>
</span>
<span class="radio-label">{{ option }}</span>
</div>
</div>
</template>
<style scoped>
.design-radio-select {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
background: #2d2d2d;
border-radius: 4px;
}
.radio-item {
display: flex;
align-items: center;
gap: 8px;
padding: 4px;
cursor: pointer;
border-radius: 4px;
}
.radio-item:hover {
background: #3c3c3c;
}
.radio-circle {
width: 16px;
height: 16px;
border: 2px solid #555;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.radio-circle.active {
border-color: #007acc;
}
.radio-dot {
width: 8px;
height: 8px;
background: #007acc;
border-radius: 50%;
}
.radio-label {
color: #cccccc;
font-size: 13px;
}
</style>

View File

@@ -0,0 +1,11 @@
<el-col :span="12">
<div class="design-component design-radio-select" data-component="单选器">
<el-form-item label="单选选择">
<el-radio-group v-model="radioValue">
<el-radio label="选项1" value="1" />
<el-radio label="选项2" value="2" />
<el-radio label="选项3" value="3" />
</el-radio-group>
</el-form-item>
</div>
</el-col>

View File

@@ -1,9 +1,51 @@
{
"name": "文本输入框",
"id": "TextInput",
"name": "输入框",
"icon": "✏️",
"description": "用于输入文本的表单组件",
"props": {
"label": "标签名称",
"width": 200,
"maxLength": 100
"template": "template.html",
"defaultSpan": 12,
"metadata": {
"span": {
"label": "宽度",
"type": "number",
"min": 1,
"max": 24,
"target": "el-col",
"attr": ":span"
},
"label": {
"label": "标签",
"type": "text",
"target": "el-form-item",
"attr": "label"
},
"type": {
"label": "类型",
"type": "select",
"options": ["", "text", "textarea"],
"target": "el-input",
"attr": "type"
},
"placeholder": {
"label": "占位文本",
"type": "text",
"target": "el-input",
"attr": "placeholder"
},
"minlength": {
"label": "最小长度",
"type": "number",
"min": 0,
"target": "el-input",
"attr": "minlength"
},
"maxlength": {
"label": "最大长度",
"type": "number",
"min": 0,
"target": "el-input",
"attr": "maxlength"
}
}
}

View File

@@ -1,49 +0,0 @@
<script setup lang="ts">
defineProps<{
label?: string
width?: number
maxLength?: number
}>()
</script>
<template>
<div class="design-text-input" :style="{ width: width + 'px' }">
<label class="input-label">{{ label }}</label>
<input
type="text"
class="input-field"
:maxlength="maxLength"
placeholder="请输入..."
/>
</div>
</template>
<style scoped>
.design-text-input {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px;
background: #2d2d2d;
border-radius: 4px;
}
.input-label {
color: #cccccc;
font-size: 12px;
}
.input-field {
padding: 6px 8px;
background: #1e1e1e;
border: 1px solid #3c3c3c;
border-radius: 4px;
color: #d4d4d4;
font-size: 13px;
outline: none;
}
.input-field:focus {
border-color: #007acc;
}
</style>

View File

@@ -0,0 +1,7 @@
<el-col :span="12">
<div class="design-component design-text-input" data-component="输入框">
<el-form-item label="文本输入">
<el-input v-model="inputValue" placeholder="请输入内容"></el-input>
</el-form-item>
</div>
</el-col>

View File

@@ -1,17 +1,4 @@
{
"name": "数据表格",
"description": "展示属性和值的简单表格组件",
"props": {
"columns": ["属性", "值"],
"data": [
{ "property": "项目名称", "value": "draggable-panels" },
{ "property": "框架", "value": "Vue 3" },
{ "property": "语言", "value": "TypeScript" },
{ "property": "构建工具", "value": "Vite" },
{ "property": "状态管理", "value": "Pinia" },
{ "property": "版本", "value": "1.0.0" },
{ "property": "作者", "value": "Developer" },
{ "property": "许可证", "value": "MIT" }
]
}
"name": "数据",
"description": "展示和编辑设计组件的属性"
}

View File

@@ -1,125 +1,224 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ref, watch } from 'vue'
import { useDesignStore } from '../../stores/designStore'
import { useVueFileStore } from '../../stores/vueFileStore'
import config from './index.json'
const TEMPLATE_SERVICE_URL = 'http://localhost:3001'
const designStore = useDesignStore()
const vueFileStore = useVueFileStore()
// 编辑状态
const editingCell = ref<{ key: string } | null>(null)
const editValue = ref('')
// 本地编辑值
const localValues = ref<Record<string, any>>({})
// 获取选中组件的属性列表
const propertyList = computed(() => {
const comp = designStore.selectedComponent
if (!comp) return []
// 更新中状态
const updating = ref(false)
return Object.entries(comp.props).map(([key, value]) => ({
key,
value: formatValue(value),
rawValue: value
}))
// 初始化本地值
watch(() => designStore.selectedComponent, (comp) => {
if (comp) {
localValues.value = { ...comp.props }
// 提取 span 值
if (comp.props.span !== undefined) {
localValues.value.span = comp.props.span
}
} else {
localValues.value = {}
}
}, { immediate: true, deep: true })
// 更新属性
const updateProp = async (key: string, value: any) => {
if (!designStore.selectedComponent || !vueFileStore.selectedFilePath) return
updating.value = true
try {
const updates: Record<string, any> = {}
// 根据元数据 schema 构建更新
const schema = designStore.selectedMetadataSchema
if (schema && schema[key]) {
const field = schema[key]
if (key === 'span') {
updates.span = value
} else {
updates[`${field.target}:${field.attr}`] = value
}
}
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/update-props`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
elementPath: designStore.selectedComponent.path,
updates
})
})
// 格式化显示值
const formatValue = (value: any): string => {
if (Array.isArray(value)) {
return value.join(', ')
}
return String(value)
}
const result = await response.json()
// 开始编辑
const startEdit = (key: string, value: any) => {
editingCell.value = { key }
editValue.value = formatValue(value)
if (result.success) {
console.log('[元数据] 更新成功:', key, value)
// 触发页面刷新
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
} else {
console.error('[元数据] 更新失败:', result.error)
}
// 完成编辑
const finishEdit = () => {
if (editingCell.value && designStore.selectedId) {
const { key } = editingCell.value
// 尝试解析值
let newValue: any = editValue.value
// 如果原始值是数组,尝试解析为数组
const comp = designStore.selectedComponent
if (comp && Array.isArray(comp.props[key])) {
newValue = editValue.value.split(',').map(s => s.trim())
} else if (!isNaN(Number(editValue.value)) && editValue.value !== '') {
newValue = Number(editValue.value)
}
designStore.updateComponentProps(designStore.selectedId, key, newValue)
editingCell.value = null
} catch (error) {
console.error('[元数据] 请求失败:', error)
} finally {
updating.value = false
}
}
// 取消编辑
const cancelEdit = () => {
editingCell.value = null
// 输入变化处理
const handleInputChange = (key: string, event: Event) => {
const target = event.target as HTMLInputElement
let value: any = target.value
const schema = designStore.selectedMetadataSchema
if (schema && schema[key]) {
if (schema[key].type === 'number') {
value = parseInt(value) || 0
} else if (schema[key].type === 'boolean') {
value = target.checked
}
}
// 检查是否正在编辑
const isEditing = (key: string) => {
return editingCell.value?.key === key
localValues.value[key] = value
updateProp(key, value)
}
// 选择变化处理
const handleSelectChange = (key: string, event: Event) => {
const target = event.target as HTMLSelectElement
localValues.value[key] = target.value
updateProp(key, target.value)
}
// 布尔值变化处理
const handleBooleanChange = (key: string, event: Event) => {
const target = event.target as HTMLInputElement
localValues.value[key] = target.checked
updateProp(key, target.checked)
}
// 色彩变化处理
const handleColorChange = (key: string, event: Event) => {
const target = event.target as HTMLInputElement
localValues.value[`${designStore.selectedMetadataSchema?.[key]?.target}:${designStore.selectedMetadataSchema?.[key]?.attr}`] = target.value
updateProp(key, target.value)
}
</script>
<template>
<div class="data-table">
<div class="table-header">
<div class="metadata-editor">
<div class="editor-header">
<span class="title">{{ config.name }}</span>
<span class="hint" v-if="designStore.selectedComponent">
{{ designStore.selectedComponent.name }}
{{ designStore.selectedComponent.componentName }}
</span>
<span class="hint" v-else>请选择组件</span>
</div>
<div class="table-body">
<table class="table" v-if="propertyList.length > 0">
<thead>
<tr>
<th>属性</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="prop in propertyList" :key="prop.key">
<td class="prop-key">{{ prop.key }}</td>
<td @dblclick="startEdit(prop.key, prop.rawValue)">
<input
v-if="isEditing(prop.key)"
v-model="editValue"
class="edit-input"
@blur="finishEdit"
@keyup.enter="finishEdit"
@keyup.escape="cancelEdit"
autofocus
/>
<span v-else class="cell-value">{{ prop.value }}</span>
</td>
</tr>
</tbody>
</table>
<div class="editor-body">
<!-- 有选中组件且有元数据 -->
<div v-if="designStore.selectedComponent && designStore.selectedMetadataSchema" class="props-list">
<div
v-for="(field, key) in designStore.selectedMetadataSchema"
:key="key"
class="prop-item"
>
<label class="prop-label">{{ field.label }}</label>
<!-- 数字输入 -->
<input
v-if="field.type === 'number'"
type="number"
class="prop-input"
:min="field.min"
:max="field.max"
:value="localValues[key] ?? localValues.span"
@change="handleInputChange(key as string, $event)"
:disabled="updating"
/>
<!-- 文本输入 -->
<input
v-else-if="field.type === 'text'"
type="text"
class="prop-input"
:value="localValues[`${field.target}:${field.attr}`] || ''"
@change="handleInputChange(key as string, $event)"
:disabled="updating"
/>
<!-- 单选下拉 -->
<select
v-else-if="field.type === 'select'"
class="prop-select"
:value="localValues[`${field.target}:${field.attr}`] || ''"
@change="handleSelectChange(key as string, $event)"
:disabled="updating"
>
<option v-for="opt in field.options" :key="opt" :value="opt">
{{ opt || '默认' }}
</option>
</select>
<!-- 布尔开关 -->
<label v-else-if="field.type === 'boolean'" class="prop-checkbox">
<input
type="checkbox"
:checked="localValues[`${field.target}:${field.attr}`] === 'true' || localValues[`${field.target}:${field.attr}`] === true"
@change="handleBooleanChange(key as string, $event)"
:disabled="updating"
/>
<span class="checkbox-text">{{ localValues[`${field.target}:${field.attr}`] ? '是' : '否' }}</span>
</label>
<!-- 颜色选择器 -->
<div v-else-if="field.type === 'color'" class="color-picker-wrapper">
<input
type="color"
class="prop-color"
:value="localValues[`${field.target}:${field.attr}`] || '#409EFF'"
@input="handleColorChange(key as string, $event)"
:disabled="updating"
/>
<span class="color-value">{{ localValues[`${field.target}:${field.attr}`] || '#409EFF' }}</span>
</div>
<!-- 列配置暂不支持 -->
<span v-else-if="field.type === 'columns'" class="prop-hint">
(暂不支持编辑)
</span>
</div>
</div>
<!-- 空状态 -->
<div v-else class="empty-tip">
<div class="empty-icon">📋</div>
<div>暂无属性</div>
<div class="empty-hint">先在树形或设计中心选择一个组件</div>
<div>暂无元数据</div>
<div class="empty-hint">点击设计中心或结构树中的组件</div>
</div>
</div>
</div>
</template>
<style scoped>
.data-table {
.metadata-editor {
display: flex;
flex-direction: column;
height: 100%;
background: #1e1e1e;
}
.table-header {
.editor-header {
padding: 8px 12px;
background: #2d2d2d;
border-bottom: 1px solid #3c3c3c;
@@ -135,74 +234,94 @@ const isEditing = (key: string) => {
}
.hint {
color: #007acc;
color: #4fc3f7;
font-size: 11px;
}
.table-body {
.editor-body {
flex: 1;
padding: 12px;
overflow: auto;
}
.table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
.props-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.table th,
.table td {
padding: 10px 12px;
text-align: left;
border-bottom: 1px solid #3c3c3c;
.prop-item {
display: flex;
align-items: center;
gap: 12px;
}
.table th {
background: #2d2d2d;
color: #cccccc;
font-weight: 500;
}
.table td {
color: #d4d4d4;
cursor: pointer;
position: relative;
}
.table td.prop-key {
.prop-label {
min-width: 80px;
color: #9cdcfe;
font-family: monospace;
cursor: default;
font-size: 12px;
}
.table td:hover {
background: #2a2d2e;
}
.table tbody tr:hover {
background: #2a2d2e;
}
.cell-value {
display: block;
min-height: 20px;
}
.edit-input {
width: 100%;
padding: 4px 8px;
.prop-input,
.prop-select {
flex: 1;
padding: 6px 10px;
background: #3c3c3c;
border: 1px solid #007acc;
border-radius: 3px;
color: #ffffff;
font-size: 13px;
border: 1px solid #555;
border-radius: 4px;
color: #fff;
font-size: 12px;
outline: none;
}
.edit-input:focus {
.prop-input:focus,
.prop-select:focus {
border-color: #007acc;
box-shadow: 0 0 0 2px rgba(0, 122, 204, 0.3);
}
.prop-input:disabled,
.prop-select:disabled {
opacity: 0.6;
}
.prop-checkbox {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.checkbox-text {
color: #ccc;
font-size: 12px;
}
.prop-color {
width: 40px;
height: 30px;
padding: 2px;
background: #3c3c3c;
border: 1px solid #555;
border-radius: 4px;
cursor: pointer;
}
.color-picker-wrapper {
display: flex;
align-items: center;
gap: 10px;
}
.color-value {
color: #ccc;
font-size: 12px;
font-family: monospace;
}
.prop-hint {
color: #666;
font-size: 11px;
font-style: italic;
}
.empty-tip {

View File

@@ -3,6 +3,7 @@ import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'
import { useInteractionStore, useDragStore, generateElementPath } from '../../plugins'
import type { ElementType, InteractionTarget } from '../../plugins'
import { useVueFileStore } from '../../stores/vueFileStore'
import { useDesignStore } from '../../stores/designStore'
import DropZone from './DropZone.vue'
import DragPreview from './DragPreview.vue'
@@ -13,8 +14,12 @@ const props = defineProps<{
const interactionStore = useInteractionStore()
const dragStore = useDragStore()
const vueFileStore = useVueFileStore()
const designStore = useDesignStore()
const containerRef = ref<HTMLElement | null>(null)
// 右键菜单状态
const contextMenu = ref<{ x: number, y: number, path: string, type: ElementType } | null>(null)
// 存储所有绑定的事件清理函数
const cleanupFunctions: (() => void)[] = []
@@ -92,6 +97,21 @@ const bindElementEvents = (element: HTMLElement, type: ElementType, path: string
el.classList.remove('fauto-selected')
})
element.classList.add('fauto-selected')
// 检查是否是叶子节点(设计组件)
if (type === 'ec') {
const componentDiv = element.querySelector('[data-component]')
if (componentDiv && vueFileStore.selectedFilePath) {
const componentName = componentDiv.getAttribute('data-component')
if (componentName) {
designStore.selectComponent(path, componentName, vueFileStore.selectedFilePath)
// 触发自定义事件,通知结构树同步选中
window.dispatchEvent(new CustomEvent('design-component-selected', {
detail: { path, componentName }
}))
}
}
}
}
// 鼠标按下(画布内元素拖拽)
@@ -105,11 +125,19 @@ const bindElementEvents = (element: HTMLElement, type: ElementType, path: string
dragStore.startDragFromCanvas(path, type, element)
}
// 右键菜单
const handleContextMenu = (e: MouseEvent) => {
e.preventDefault()
e.stopPropagation()
contextMenu.value = { x: e.clientX, y: e.clientY, path, type }
}
// 绑定事件
element.addEventListener('mouseenter', handleMouseEnter)
element.addEventListener('mouseleave', handleMouseLeave)
element.addEventListener('click', handleClick)
element.addEventListener('mousedown', handleMouseDown)
element.addEventListener('contextmenu', handleContextMenu)
console.log(`[注入] ${type} 路径: ${path}`)
@@ -119,11 +147,60 @@ const bindElementEvents = (element: HTMLElement, type: ElementType, path: string
element.removeEventListener('mouseleave', handleMouseLeave)
element.removeEventListener('click', handleClick)
element.removeEventListener('mousedown', handleMouseDown)
element.removeEventListener('contextmenu', handleContextMenu)
element.classList.remove('fauto-interactive', 'fauto-hover', 'fauto-selected')
element.removeAttribute('data-fauto-bindend')
}
}
// 关闭右键菜单
const closeContextMenu = () => {
contextMenu.value = null
}
// 删除元素
const deleteElement = async () => {
if (!contextMenu.value || !vueFileStore.selectedFilePath) return
const { path } = contextMenu.value
if (!confirm('确定要删除该元素吗?')) {
closeContextMenu()
return
}
try {
const response = await fetch('http://localhost:3001/api/delete-element', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
elementPath: path
})
})
const result = await response.json()
if (result.success) {
console.log('[设计中心] 删除成功:', path)
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
// 如果删除的是选中的组件,清除选中
if (designStore.selectedComponent?.path === path) {
designStore.clearSelection()
}
} else {
alert('删除失败: ' + result.error)
}
} catch (error) {
console.error('[设计中心] 删除失败:', error)
}
closeContextMenu()
}
/**
* 扫描并注入事件到所有el-row和el-col元素
*/
@@ -275,6 +352,8 @@ onMounted(() => {
document.addEventListener('mousemove', handleGlobalMouseMove)
// 添加全局鼠标松开事件
document.addEventListener('mouseup', handleGlobalMouseUp)
// 点击其他地方关闭右键菜单
document.addEventListener('click', closeContextMenu)
})
// 组件卸载时清理事件
@@ -291,6 +370,7 @@ onUnmounted(() => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('mousemove', handleGlobalMouseMove)
document.removeEventListener('mouseup', handleGlobalMouseUp)
document.removeEventListener('click', closeContextMenu)
})
// 监听组件变化,重新注入事件
@@ -324,6 +404,18 @@ watch(() => interactionStore.hoverTarget, (target) => {
<!-- 拖拽预览跟随鼠标 -->
<DragPreview />
<!-- 右键菜单 -->
<div
v-if="contextMenu"
class="context-menu"
:style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
>
<div class="menu-item delete" @click="deleteElement">
<span class="menu-icon">🗑</span>
<span>删除</span>
</div>
</div>
<!-- 拖拽时的层级选择提示 -->
<div v-if="dragStore.isDragging && dragStore.hierarchyNodes.length > 1" class="hierarchy-hint">
<div class="hint-title"> 用上下键切换层级</div>
@@ -444,4 +536,39 @@ watch(() => interactionStore.hoverTarget, (target) => {
.hint-path {
font-family: monospace;
}
/* 右键菜单 */
.context-menu {
position: fixed;
background: #2d2d2d;
border: 1px solid #3c3c3c;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
z-index: 2000;
min-width: 120px;
padding: 4px 0;
}
.menu-item {
padding: 8px 16px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: #ccc;
font-size: 13px;
transition: background 0.15s;
}
.menu-item:hover {
background: #094771;
}
.menu-item.delete:hover {
background: #c23a3a;
}
.menu-icon {
font-size: 14px;
}
</style>

View File

@@ -30,10 +30,6 @@ onUnmounted(() => {
}
})
const handleAddComponent = (componentId: string) => {
designStore.addComponent(componentId)
}
// 鼠标悬停设计组件
const handleMouseEnter = (componentId: string, componentName: string) => {
const target: InteractionTarget = {
@@ -60,15 +56,13 @@ const handleClick = (componentId: string, componentName: string) => {
componentId: componentName
}
interactionStore.onClick(target)
// 添加组件
designStore.addComponent(componentId)
}
// 鼠标按下 - 开始检测拖拽
// 鼠标按下 - 开始拖拽
const handleMouseDown = (e: MouseEvent, componentId: string, componentName: string) => {
e.preventDefault()
// 立即开始拖拽(不需要长按)
// 立即开始拖拽
draggingId.value = componentId
dragStore.startDragFromComponentList(componentId, componentName)
}
@@ -100,7 +94,7 @@ const handleGlobalMouseUp = () => {
@mouseleave="handleMouseLeave"
@mousedown="handleMouseDown($event, meta.id, meta.name)"
>
<div class="component-icon">📦</div>
<div class="component-icon">{{ meta.icon }}</div>
<div class="component-info">
<div class="component-name">{{ meta.name }}</div>
<div class="component-desc">{{ meta.description }}</div>

View File

@@ -1,36 +1,4 @@
{
"name": "树形展示器",
"description": "用于展示树形结构数据的组件",
"props": {
"treeData": [
{
"id": "1",
"label": "项目根目录",
"expanded": true,
"children": [
{
"id": "1-1",
"label": "src",
"expanded": true,
"children": [
{ "id": "1-1-1", "label": "components" },
{ "id": "1-1-2", "label": "stores" },
{ "id": "1-1-3", "label": "types" },
{ "id": "1-1-4", "label": "App.vue" },
{ "id": "1-1-5", "label": "main.ts" }
]
},
{
"id": "1-2",
"label": "public",
"children": [
{ "id": "1-2-1", "label": "favicon.ico" }
]
},
{ "id": "1-3", "label": "package.json" },
{ "id": "1-4", "label": "vite.config.ts" }
]
}
]
}
"name": "结构",
"description": "展示当前页面的el-row/el-col布局结构"
}

View File

@@ -1,75 +1,392 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import draggable from 'vuedraggable'
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useVueFileStore } from '../../stores/vueFileStore'
import { useDesignStore } from '../../stores/designStore'
import config from './index.json'
const TEMPLATE_SERVICE_URL = 'http://localhost:3001'
const vueFileStore = useVueFileStore()
const designStore = useDesignStore()
// 创建可响应的本地副本用于拖拽
const localComponents = ref([...designStore.components])
// 元素树节点类型
interface ElementNode {
type: 'row' | 'col'
path: string
label: string
componentName?: string | null
children?: ElementNode[]
}
// 监听 designStore 组件变化,同步到本地副本
watch(
() => designStore.components,
(newVal) => {
localComponents.value = [...newVal]
},
{ deep: true, immediate: true }
// 元素树数据
const elementTree = ref<ElementNode[]>([])
const loading = ref(false)
// 拖拽状态
const draggingNode = ref<ElementNode | null>(null)
const dropTarget = ref<{ node: ElementNode, position: 'before' | 'after' | 'inside' } | null>(null)
// 右键菜单状态
const contextMenu = ref<{ x: number, y: number, node: ElementNode } | null>(null)
// 选中的节点
const selectedPath = ref<string | null>(null)
// 获取页面元素结构
const fetchElementTree = async () => {
if (!vueFileStore.selectedFilePath) {
elementTree.value = []
return
}
loading.value = true
try {
const response = await fetch(
`${TEMPLATE_SERVICE_URL}/api/element-tree?pagePath=${encodeURIComponent(vueFileStore.selectedFilePath)}`
)
const result = await response.json()
// 拖拽结束处理 - 同步顺序到 designStore
const onDragEnd = () => {
// 重新排序 designStore 中的组件
designStore.reorderComponents([...localComponents.value])
if (result.success) {
elementTree.value = result.tree || []
} else {
elementTree.value = []
}
} catch (error) {
elementTree.value = []
} finally {
loading.value = false
}
}
// 获取节点显示文本
const getNodeText = (node: ElementNode): string => {
if (node.type === 'row') return node.path
if (node.componentName) return `${node.path}-${node.componentName}`
return node.path
}
// 判断是否为叶子节点
const isLeafNode = (node: ElementNode): boolean => {
return node.type === 'col' && !!node.componentName && (!node.children || node.children.length === 0)
}
// 计算允许的放置位置
const getAllowedPosition = (source: ElementNode, target: ElementNode): 'before' | 'after' | 'inside' | null => {
if (source.path === target.path) return null
if (target.path.startsWith(source.path)) return null
if (source.type === 'col' && target.type === 'col') return 'after'
if (source.type === 'row' && target.type === 'row') return 'after'
if (source.type === 'col' && target.type === 'row') return 'inside'
if (source.type === 'row' && target.type === 'col' && !isLeafNode(target)) return 'inside'
return null
}
// 点击节点 - 选中组件
const handleNodeClick = (nodeId: string) => {
designStore.selectComponent(nodeId)
const handleNodeClick = (node: ElementNode) => {
selectedPath.value = node.path
// 如果是叶子节点,选中组件显示元数据
if (isLeafNode(node) && node.componentName && vueFileStore.selectedFilePath) {
designStore.selectComponent(node.path, node.componentName, vueFileStore.selectedFilePath)
}
// 获取组件类型图标
const getComponentIcon = (componentId: string) => {
const icons: Record<string, string> = {
TextInput: '✏️',
RadioSelect: '◉',
GridTable: '☰'
// 高亮设计中心对应元素
highlightDesignCenterElement(node.path)
}
return icons[componentId] || '⭕'
// 高亮设计中心的对应元素
const highlightDesignCenterElement = (path: string) => {
// 移除其他选中
document.querySelectorAll('.fauto-selected').forEach(el => {
el.classList.remove('fauto-selected')
})
// 找到对应元素并选中
const element = document.querySelector(`[data-path="${path}"]`)
if (element) {
element.classList.add('fauto-selected')
// 滚动到可见区域
element.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
}
// 监听设计中心的选中事件,同步选中结构树
const handleDesignComponentSelected = (e: CustomEvent) => {
const { path } = e.detail
if (path) {
selectedPath.value = path
}
}
// 右键菜单
const handleContextMenu = (e: MouseEvent, node: ElementNode) => {
e.preventDefault()
e.stopPropagation()
contextMenu.value = { x: e.clientX, y: e.clientY, node }
}
// 关闭右键菜单
const closeContextMenu = () => {
contextMenu.value = null
}
// 删除节点
const deleteNode = async (node: ElementNode) => {
if (!vueFileStore.selectedFilePath) return
if (!confirm(`确定要删除 ${getNodeText(node)} 吗?`)) return
try {
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/delete-element`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
elementPath: node.path
})
})
const result = await response.json()
if (result.success) {
console.log('[结构] 删除成功:', node.path)
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
// 如果删除的是选中的组件,清除选中
if (designStore.selectedComponent?.path === node.path) {
designStore.clearSelection()
}
} else {
alert('删除失败: ' + result.error)
}
} catch (error) {
console.error('[结构] 删除失败:', error)
}
closeContextMenu()
}
// 键盘事件处理
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Delete' && selectedPath.value) {
const node = findNodeByPath(elementTree.value, selectedPath.value)
if (node) {
deleteNode(node)
}
}
if (e.key === 'Escape') {
closeContextMenu()
}
}
// 查找节点
const findNodeByPath = (nodes: ElementNode[], path: string): ElementNode | null => {
for (const node of nodes) {
if (node.path === path) return node
if (node.children) {
const found = findNodeByPath(node.children, path)
if (found) return found
}
}
return null
}
// 拖拽事件
const handleDragStart = (e: DragEvent, node: ElementNode) => {
draggingNode.value = node
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', node.path)
}
}
const handleDragOver = (e: DragEvent, node: ElementNode) => {
if (!draggingNode.value) return
const position = getAllowedPosition(draggingNode.value, node)
if (position) {
e.preventDefault()
dropTarget.value = { node, position }
} else {
dropTarget.value = null
}
}
const handleDragLeave = () => {
dropTarget.value = null
}
const handleDrop = async (e: DragEvent, node: ElementNode) => {
e.preventDefault()
if (!draggingNode.value || !vueFileStore.selectedFilePath) {
resetDragState()
return
}
const position = getAllowedPosition(draggingNode.value, node)
if (!position) {
resetDragState()
return
}
let direction: string
if (position === 'inside') {
direction = 'inside'
} else if (position === 'after') {
direction = node.type === 'row' ? 'bottom' : 'right'
} else {
direction = node.type === 'row' ? 'top' : 'left'
}
try {
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/move-element`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
pagePath: vueFileStore.selectedFilePath,
source: {
type: 'canvas-element',
path: draggingNode.value.path,
elementType: draggingNode.value.type === 'row' ? 'er' : 'ec'
},
targetPath: node.path,
targetType: node.type === 'row' ? 'er' : 'ec',
direction
})
})
const result = await response.json()
if (result.success) {
window.dispatchEvent(new CustomEvent('vue-template-updated', {
detail: { pagePath: vueFileStore.selectedFilePath }
}))
}
} catch (error) {
console.error('[结构] 移动失败:', error)
}
resetDragState()
}
const handleDragEnd = () => {
resetDragState()
}
const resetDragState = () => {
draggingNode.value = null
dropTarget.value = null
}
// 递归渲染树
const flattenTree = (nodes: ElementNode[], depth = 0): Array<{ node: ElementNode, depth: number }> => {
const result: Array<{ node: ElementNode, depth: number }> = []
for (const node of nodes) {
result.push({ node, depth })
if (node.children && node.children.length > 0) {
result.push(...flattenTree(node.children, depth + 1))
}
}
return result
}
// 获取节点样式类
const getNodeClass = (node: ElementNode) => {
const classes: string[] = []
if (node.type === 'row') classes.push('is-row')
if (node.type === 'col') classes.push('is-col')
if (draggingNode.value?.path === node.path) classes.push('is-dragging')
if (selectedPath.value === node.path) classes.push('is-selected')
if (dropTarget.value?.node.path === node.path) {
classes.push('is-drop-target')
classes.push(`drop-${dropTarget.value.position}`)
}
return classes
}
// 监听
watch(() => vueFileStore.selectedFilePath, () => {
fetchElementTree()
}, { immediate: true })
onMounted(() => {
window.addEventListener('vue-template-updated', () => {
setTimeout(fetchElementTree, 300)
})
// 监听设计中心的选中事件
window.addEventListener('design-component-selected', handleDesignComponentSelected as EventListener)
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('click', closeContextMenu)
// 阻止组件内的浏览器默认右键菜单
document.addEventListener('contextmenu', handleGlobalContextMenu)
})
// 全局右键菜单处理,阻止浏览器默认菜单
const handleGlobalContextMenu = (e: MouseEvent) => {
// 检查是否在树节点上点击
const target = e.target as HTMLElement
if (target.closest('.tree-node')) {
e.preventDefault()
}
}
onUnmounted(() => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('click', closeContextMenu)
document.removeEventListener('contextmenu', handleGlobalContextMenu)
window.removeEventListener('design-component-selected', handleDesignComponentSelected as EventListener)
})
</script>
<template>
<div class="tree-viewer">
<div class="viewer-header">
<span class="title">{{ config.name }}</span>
<span class="hint">设计组件列表</span>
</div>
<div class="viewer-body">
<div class="tree-container">
<draggable
:list="localComponents"
item-key="id"
:animation="150"
ghost-class="node-ghost"
@end="onDragEnd"
>
<template #item="{ element: node }">
<div
class="tree-node"
:class="{ selected: designStore.selectedId === node.id }"
@click="handleNodeClick(node.id)"
>
<span class="node-icon">{{ getComponentIcon(node.componentId) }}</span>
<span class="node-label">{{ node.name }}</span>
</div>
</template>
</draggable>
<div v-if="loading" class="loading-tip">加载中...</div>
<div v-if="localComponents.length === 0" class="empty-tip">
暂无设计组件
<div v-else-if="elementTree.length === 0" class="empty-tip">
{{ vueFileStore.selectedFilePath ? '暂无布局元素' : '请先选择页面' }}
</div>
<div v-else class="tree-container">
<div
v-for="item in flattenTree(elementTree)"
:key="item.node.path"
class="tree-node"
:class="getNodeClass(item.node)"
:style="{ paddingLeft: (item.depth * 16 + 8) + 'px' }"
draggable="true"
@click="handleNodeClick(item.node)"
@contextmenu="handleContextMenu($event, item.node)"
@dragstart="handleDragStart($event, item.node)"
@dragover="handleDragOver($event, item.node)"
@dragleave="handleDragLeave"
@drop="handleDrop($event, item.node)"
@dragend="handleDragEnd"
>
<span class="node-text">{{ getNodeText(item.node) }}</span>
<span v-if="dropTarget?.node.path === item.node.path" class="drop-hint">
{{ dropTarget.position === 'inside' ? '放入' : '后面' }}
</span>
<span class="delete-icon" @click.stop="deleteNode(item.node)" title="删除">🗑</span>
</div>
</div>
</div>
<!-- 右键菜单 -->
<div
v-if="contextMenu"
class="context-menu"
:style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
>
<div class="menu-item" @click="deleteNode(contextMenu.node)">
<span class="menu-icon">🗑</span>
<span>删除</span>
</div>
</div>
</div>
@@ -81,15 +398,13 @@ const getComponentIcon = (componentId: string) => {
flex-direction: column;
height: 100%;
background: #1e1e1e;
position: relative;
}
.viewer-header {
padding: 8px 12px;
background: #2d2d2d;
border-bottom: 1px solid #3c3c3c;
display: flex;
align-items: center;
justify-content: space-between;
}
.title {
@@ -98,11 +413,6 @@ const getComponentIcon = (componentId: string) => {
font-weight: 500;
}
.hint {
color: #666666;
font-size: 11px;
}
.viewer-body {
flex: 1;
padding: 8px;
@@ -110,43 +420,87 @@ const getComponentIcon = (componentId: string) => {
}
.tree-container {
font-size: 13px;
font-size: 12px;
font-family: 'Consolas', 'Monaco', monospace;
}
.tree-node {
padding: 4px 8px;
cursor: grab;
border-radius: 3px;
color: #888;
user-select: none;
margin-bottom: 1px;
transition: all 0.15s;
display: flex;
align-items: center;
padding: 8px 12px;
cursor: grab;
border-radius: 4px;
color: #cccccc;
user-select: none;
margin-bottom: 2px;
transition: all 0.15s;
}
.tree-node:active {
cursor: grabbing;
gap: 8px;
}
.tree-node:hover {
background: #2a2d2e;
}
.tree-node.selected {
.tree-node:hover .delete-icon {
opacity: 1;
}
.tree-node:active {
cursor: grabbing;
}
.tree-node.is-row {
color: #4fc3f7;
}
.tree-node.is-col {
color: #c586c0;
}
.tree-node.is-dragging {
opacity: 0.5;
}
.tree-node.is-selected {
background: #094771;
}
.node-icon {
width: 20px;
margin-right: 8px;
text-align: center;
.tree-node.is-drop-target {
background: #094771;
}
.node-label {
.tree-node.drop-inside {
border: 1px dashed #4fc3f7;
}
.tree-node.drop-after {
border-bottom: 2px solid #4fc3f7;
}
.node-text {
flex: 1;
}
.drop-hint {
font-size: 10px;
color: #4fc3f7;
background: rgba(79, 195, 247, 0.2);
padding: 1px 4px;
border-radius: 2px;
}
.delete-icon {
opacity: 0;
cursor: pointer;
font-size: 12px;
transition: opacity 0.15s;
}
.delete-icon:hover {
transform: scale(1.1);
}
.loading-tip,
.empty-tip {
color: #666666;
text-align: center;
@@ -154,10 +508,32 @@ const getComponentIcon = (componentId: string) => {
font-size: 12px;
}
/* 拖拽样式 */
.node-ghost {
opacity: 0.4;
background: #094771;
/* 右键菜单 */
.context-menu {
position: fixed;
background: #2d2d2d;
border: 1px solid #3c3c3c;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
z-index: 1000;
min-width: 120px;
}
.menu-item {
padding: 8px 12px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
color: #ccc;
font-size: 12px;
}
.menu-item:hover {
background: #094771;
}
.menu-icon {
font-size: 14px;
}
</style>

View File

@@ -100,9 +100,12 @@ export const useDragStore = defineStore('drag', () => {
/**
* 开始拖拽(从设计组件列表)
* 设计组件拖动直接进入目标选择阶段
*/
const startDragFromComponentList = (componentId: string, componentName: string) => {
isDragging.value = true
dragPhase.value = 'target' // 设计组件直接进入目标选择阶段
confirmedSource.value = null
dragSource.value = {
type: 'design-component',
componentId,
@@ -369,8 +372,14 @@ export const useDragStore = defineStore('drag', () => {
console.log('[DragStore] 确认拖放:', record)
// 如果提供了页面路径发送API请求到后端
if (pagePath && record.source.type === 'canvas-element') {
if (pagePath) {
if (record.source.type === 'canvas-element') {
// 画布内元素移动
await sendMoveRequest(pagePath, record)
} else if (record.source.type === 'design-component') {
// 设计组件插入
await sendInsertRequest(pagePath, record)
}
}
return record
@@ -414,6 +423,43 @@ export const useDragStore = defineStore('drag', () => {
}
}
/**
* 发送设计组件插入请求到后端服务
*/
const sendInsertRequest = async (pagePath: string, record: DropRecord) => {
try {
console.log('[DragStore] 发送插入请求:', { pagePath, record })
const response = await fetch(`${TEMPLATE_SERVICE_URL}/api/insert-component`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pagePath,
componentId: record.source.componentId,
targetPath: record.targetPath,
direction: record.direction
})
})
const result = await response.json()
if (result.success) {
console.log('[DragStore] 插入成功:', result.message)
// 触发页面刷新事件
window.dispatchEvent(new CustomEvent('vue-template-updated', { detail: { pagePath } }))
} else {
console.error('[DragStore] 插入失败:', result.error)
}
return result
} catch (error) {
console.error('[DragStore] API请求失败:', error)
return { success: false, error: (error as Error).message }
}
}
/**
* 取消拖拽
*/

View File

@@ -1,11 +1,35 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ref, computed } from 'vue'
const TEMPLATE_SERVICE_URL = 'http://localhost:3001'
// 元数据字段定义
export interface MetadataField {
label: string
type: 'text' | 'number' | 'select' | 'boolean' | 'color' | 'columns'
min?: number
max?: number
options?: string[]
target: string
attr: string
}
// 设计组件定义
export interface DesignComponentMeta {
id: string
name: string
icon: string
description: string
template: string
defaultSpan: number
metadata?: Record<string, MetadataField>
}
// 选中的组件信息
export interface SelectedComponent {
path: string
componentId: string
componentName: string
props: Record<string, any>
}
@@ -13,28 +37,39 @@ export const useDesignStore = defineStore('design', () => {
// 设计组件元数据缓存
const componentMetas = ref<DesignComponentMeta[]>([])
// 当前选中的组件
const selectedComponent = ref<SelectedComponent | null>(null)
// 自动扫描所有设计组件的 .json 配置文件
const designComponentMetaModules = import.meta.glob('../designComponents/*/index.json', { eager: true })
// 加载设计组件元数据(从本地文件自动扫描)
// 自动扫描所有设计组件的模板文件
const designComponentTemplateModules = import.meta.glob('../designComponents/*/template.html', { eager: true, query: '?raw', import: 'default' })
// 加载设计组件元数据
const loadComponentMetas = async () => {
try {
const metas: DesignComponentMeta[] = []
for (const path in designComponentMetaModules) {
// 从路径中提取组件 ID例如 '../designComponents/TextInput/index.json' => 'TextInput'
const match = path.match(/\/designComponents\/(.+)\/index\.json$/)
if (!match) continue
const id = match[1]
const componentId = match[1]
const mod = designComponentMetaModules[path] as any
const config = mod.default || mod
const templatePath = `../designComponents/${componentId}/template.html`
const templateContent = designComponentTemplateModules[templatePath] as string || ''
metas.push({
id,
id: config.id || componentId,
name: config.name,
icon: config.icon || '📦',
description: config.description,
props: config.props || {}
template: templateContent,
defaultSpan: config.defaultSpan || 12,
metadata: config.metadata
})
}
@@ -50,9 +85,67 @@ export const useDesignStore = defineStore('design', () => {
return componentMetas.value.find(m => m.id === componentId)
}
// 根据名称获取组件元数据
const getComponentMetaByName = (name: string) => {
return componentMetas.value.find(m => m.name === name)
}
// 获取组件模板
const getComponentTemplate = (componentId: string): string | null => {
const meta = getComponentMeta(componentId)
return meta?.template || null
}
// 选中组件
const selectComponent = async (path: string, componentName: string, pagePath: string) => {
try {
// 获取组件属性
const response = await fetch(
`${TEMPLATE_SERVICE_URL}/api/component-props?pagePath=${encodeURIComponent(pagePath)}&elementPath=${encodeURIComponent(path)}`
)
const result = await response.json()
if (result.success) {
selectedComponent.value = {
path,
componentId: result.componentId || componentName,
componentName,
props: result.props || {}
}
console.log('[设计Store] 选中组件:', selectedComponent.value)
}
} catch (error) {
console.error('[设计Store] 获取组件属性失败:', error)
}
}
// 清除选中
const clearSelection = () => {
selectedComponent.value = null
}
// 获取当前选中组件的元数据schema
const selectedMetadataSchema = computed(() => {
if (!selectedComponent.value) return null
const meta = getComponentMetaByName(selectedComponent.value.componentName)
return meta?.metadata || null
})
// 初始化
const init = async () => {
await loadComponentMetas()
}
return {
componentMetas,
selectedComponent,
selectedMetadataSchema,
init,
loadComponentMetas,
getComponentMeta
getComponentMeta,
getComponentMetaByName,
getComponentTemplate,
selectComponent,
clearSelection
}
})

View File

@@ -1,25 +1,71 @@
<template>
<el-row class="page-container" :gutter="20">
<el-col :span="12">
<div class="design-component">左侧内容区域</div>
<div class="design-component design-text-input">
<el-form-item label="文本输入">
<el-input v-model="inputValue" placeholder="请输入内容"></el-input>
</el-form-item>
</div>
</el-col>
<el-col :span="12">
<el-row :gutter="10">
<el-col :span="24">
<div class="design-component">右侧标题</div>
</el-col>
</el-row>
<el-row :gutter="10">
<el-col :span="12">
<div class="design-component">右侧列2</div>
</el-col>
</el-row>
<el-row :gutter="10">
<el-col :span="12">
<div class="design-component design-radio-select">
<el-form-item label="单选选择">
<el-radio-group v-model="radioValue">
<el-radio label="选项1" value="1" />
<el-radio label="选项2" value="2" />
<el-radio label="选项3" value="3" />
</el-radio-group>
</el-form-item>
</div>
</el-col>
<el-col :span="12">
<div class="design-component">右侧列1</div>
<div class="design-component">左侧内容区域</div>
</el-col>
</el-row>
</el-col>
<el-col :span="12">
<div class="design-component design-radio-select" data-component="单选器">
<el-form-item label="单选选择">
<el-radio-group text-color="#da0707" fill="#703e67" >
<el-radio label="选项1" value="1" />
<el-radio label="选项2" value="2" />
<el-radio label="选项3" value="3" />
</el-radio-group>
</el-form-item>
</div>
</el-col>
<el-col :span="16">
<div class="design-component design-grid-table" data-component="表格">
<el-table border="false" stripe="false" size="mini" :data="tableData" style="width: 100%">
<el-table-column prop="col1" label="列1" />
<el-table-column prop="col2" label="列2" />
<el-table-column prop="col3" label="列3" />
</el-table>
</div>
</el-col>
<el-col :span="12">
<div class="design-component design-text-input" data-component="输入框">
<el-form-item label="文本输入">
<el-input v-model="inputValue" placeholder="请输入内容111"></el-input>
</el-form-item>
</div>
</el-col>
</el-row>
</template>

View File

@@ -6,9 +6,12 @@
import express from 'express'
import cors from 'cors'
import { moveElement } from './services/templateService.js'
import { moveElement, insertElement, parseElementTree, parseComponentProps, updateComponentProps, deleteElement } from './services/templateService.js'
import { readFile, writeFile } from 'fs/promises'
import path from 'path'
import { fileURLToPath } from 'url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const app = express()
const PORT = 3001
@@ -20,6 +23,9 @@ app.use(express.json())
// Vue源码目录相对于服务根目录
const VUE_SOURCE_DIR = path.resolve('../draggable-panels/src/views')
// 设计组件模板目录
const DESIGN_COMPONENTS_DIR = path.resolve('../draggable-panels/src/fauto/designComponents')
/**
* API: 执行元素移动操作
*
@@ -127,8 +133,276 @@ app.get('/api/health', (req, res) => {
})
})
/**
* API: 插入设计组件
*
* POST /api/insert-component
* Body: {
* pagePath: string, // Vue文件路径
* componentId: string, // 设计组件ID
* targetPath: string, // 目标元素路径
* direction: string // 插入方向
* }
*/
app.post('/api/insert-component', async (req, res) => {
try {
const { pagePath, componentId, targetPath, direction } = req.body
console.log('[API] 收到插入请求:', {
pagePath,
componentId,
targetPath,
direction
})
// 验证参数
if (!pagePath || !componentId || !targetPath || !direction) {
return res.status(400).json({
success: false,
error: '缺少必要参数'
})
}
// 构建完整文件路径
let normalizedPath = pagePath
const viewsIndex = normalizedPath.indexOf('views/')
if (viewsIndex !== -1) {
normalizedPath = normalizedPath.substring(viewsIndex + 6)
}
const filePath = path.join(VUE_SOURCE_DIR, normalizedPath)
// 读取设计组件模板
const templatePath = path.join(DESIGN_COMPONENTS_DIR, componentId, 'template.html')
let componentTemplate
try {
componentTemplate = await readFile(templatePath, 'utf-8')
} catch (err) {
return res.status(404).json({
success: false,
error: `设计组件模板不存在: ${componentId}`
})
}
console.log('[API] 设计组件模板:', componentTemplate.substring(0, 100) + '...')
// 读取Vue文件
let vueContent
try {
vueContent = await readFile(filePath, 'utf-8')
} catch (err) {
return res.status(404).json({
success: false,
error: `文件不存在: ${pagePath}`
})
}
// 执行插入操作
const result = insertElement(vueContent, {
templateContent: componentTemplate.trim(),
targetPath,
direction
})
if (!result.success) {
return res.status(400).json({
success: false,
error: result.error
})
}
// 写回文件
await writeFile(filePath, result.content, 'utf-8')
console.log('[API] 插入成功')
res.json({
success: true,
message: `已将 ${componentId} 插入到 ${targetPath}${direction}方向`
})
} catch (error) {
console.error('[API] 错误:', error)
res.status(500).json({
success: false,
error: error.message
})
}
})
/**
* API: 获取页面元素结构树
*
* GET /api/element-tree?pagePath=xxx
*/
app.get('/api/element-tree', async (req, res) => {
try {
const { pagePath } = req.query
if (!pagePath) {
return res.status(400).json({
success: false,
error: '缺少pagePath参数'
})
}
// 构建完整文件路径
let normalizedPath = pagePath
const viewsIndex = normalizedPath.indexOf('views/')
if (viewsIndex !== -1) {
normalizedPath = normalizedPath.substring(viewsIndex + 6)
}
const filePath = path.join(VUE_SOURCE_DIR, normalizedPath)
console.log('[API] 获取结构树:', filePath)
// 读取Vue文件
let vueContent
try {
vueContent = await readFile(filePath, 'utf-8')
} catch (err) {
return res.status(404).json({
success: false,
error: `文件不存在: ${pagePath}`
})
}
// 解析结构树
const result = parseElementTree(vueContent)
if (!result.success) {
return res.status(400).json({
success: false,
error: result.error
})
}
res.json({
success: true,
tree: result.tree
})
} catch (error) {
console.error('[API] 错误:', error)
res.status(500).json({
success: false,
error: error.message
})
}
})
// 启动服务
app.listen(PORT, () => {
console.log(`🚀 Vue模板服务启动: http://localhost:${PORT}`)
console.log(`📁 源码目录: ${VUE_SOURCE_DIR}`)
})
/**
* API: 获取组件属性
* GET /api/component-props?pagePath=xxx&elementPath=xxx
*/
app.get('/api/component-props', async (req, res) => {
try {
const { pagePath, elementPath } = req.query
if (!pagePath || !elementPath) {
return res.status(400).json({
success: false,
error: '缺少参数'
})
}
let normalizedPath = pagePath
const viewsIndex = normalizedPath.indexOf('views/')
if (viewsIndex !== -1) {
normalizedPath = normalizedPath.substring(viewsIndex + 6)
}
const filePath = path.join(VUE_SOURCE_DIR, normalizedPath)
const vueContent = await readFile(filePath, 'utf-8')
const result = parseComponentProps(vueContent, elementPath)
if (!result.success) {
return res.status(400).json(result)
}
res.json(result)
} catch (error) {
res.status(500).json({ success: false, error: error.message })
}
})
/**
* API: 更新组件属性
* POST /api/update-props
*/
app.post('/api/update-props', async (req, res) => {
try {
const { pagePath, elementPath, updates } = req.body
if (!pagePath || !elementPath || !updates) {
return res.status(400).json({
success: false,
error: '缺少参数'
})
}
let normalizedPath = pagePath
const viewsIndex = normalizedPath.indexOf('views/')
if (viewsIndex !== -1) {
normalizedPath = normalizedPath.substring(viewsIndex + 6)
}
const filePath = path.join(VUE_SOURCE_DIR, normalizedPath)
const vueContent = await readFile(filePath, 'utf-8')
const result = updateComponentProps(vueContent, elementPath, updates)
if (!result.success) {
return res.status(400).json(result)
}
await writeFile(filePath, result.content, 'utf-8')
res.json({ success: true, message: '属性更新成功' })
} catch (error) {
res.status(500).json({ success: false, error: error.message })
}
})
/**
* API: 删除元素
* POST /api/delete-element
*/
app.post('/api/delete-element', async (req, res) => {
try {
const { pagePath, elementPath } = req.body
if (!pagePath || !elementPath) {
return res.status(400).json({
success: false,
error: '缺少参数'
})
}
let normalizedPath = pagePath
const viewsIndex = normalizedPath.indexOf('views/')
if (viewsIndex !== -1) {
normalizedPath = normalizedPath.substring(viewsIndex + 6)
}
const filePath = path.join(VUE_SOURCE_DIR, normalizedPath)
const vueContent = await readFile(filePath, 'utf-8')
const result = deleteElement(vueContent, elementPath)
if (!result.success) {
return res.status(400).json(result)
}
await writeFile(filePath, result.content, 'utf-8')
console.log(`[API] 删除成功: ${elementPath}`)
res.json({ success: true, message: '元素删除成功' })
} catch (error) {
res.status(500).json({ success: false, error: error.message })
}
})

View File

@@ -375,3 +375,509 @@ export function getTemplateAST(vueContent) {
whitespace: 'preserve'
})
}
/**
* 插入新元素到指定位置
*
* @param {string} vueContent - 完整的Vue文件内容
* @param {Object} options - 插入选项
* @param {string} options.templateContent - 要插入的模板内容
* @param {string} options.targetPath - 目标元素路径,如 "r1c2"
* @param {string} options.direction - 插入方向: 'top' | 'bottom' | 'left' | 'right' | 'inside'
* @returns {Object} - { success: boolean, content?: string, error?: string }
*/
/**
* 解析Vue文件的el-row/el-col结构树
* @param {string} vueContent - Vue文件内容
* @returns {Object} - { success: boolean, tree?: Array, error?: string }
*/
export function parseElementTree(vueContent) {
try {
// 1. 解析Vue SFC文件
const sfcResult = parseSFC(vueContent)
if (sfcResult.errors.length > 0) {
return {
success: false,
error: `Vue文件解析错误: ${sfcResult.errors[0].message}`
}
}
const templateBlock = sfcResult.descriptor.template
if (!templateBlock) {
return {
success: false,
error: '未找到template块'
}
}
// 2. 解析template获取AST
const templateAST = parseTemplate(templateBlock.content, {
comments: true,
whitespace: 'preserve'
})
// 3. 递归构建el-row/el-col树
const buildTree = (children, pathPrefix = '') => {
const result = []
let rowIndex = 0
let colIndex = 0
for (const child of children) {
if (child.type !== 1) continue // 跳过非元素节点
if (child.tag === 'el-row') {
rowIndex++
const path = pathPrefix + 'r' + rowIndex
const node = {
type: 'row',
path,
label: 'el-row',
children: buildTree(child.children || [], path)
}
result.push(node)
} else if (child.tag === 'el-col') {
colIndex++
const path = pathPrefix + 'c' + colIndex
// 检查el-col内部的子组件
const componentName = getInnerComponentName(child.children || [])
const spanAttr = child.props?.find(p => p.name === 'span' || (p.name === 'bind' && p.arg?.content === 'span'))
let span = 24
if (spanAttr) {
if (spanAttr.name === 'span' && spanAttr.value) {
span = parseInt(spanAttr.value.content) || 24
} else if (spanAttr.exp) {
span = parseInt(spanAttr.exp.content) || 24
}
}
const node = {
type: 'col',
path,
label: `el-col :span="${span}"`,
componentName,
children: buildTree(child.children || [], path)
}
result.push(node)
}
}
return result
}
// 获取el-col内部的组件名称优先读data-component属性
const getInnerComponentName = (children) => {
for (const child of children) {
if (child.type !== 1) continue
if (child.tag === 'el-row' || child.tag === 'el-col') continue
// 优先检查 data-component 属性
if (child.props) {
const dataComponentAttr = child.props.find(p => p.name === 'data-component')
if (dataComponentAttr?.value?.content) {
return dataComponentAttr.value.content
}
}
// 其他元素返回"其他"
return '其他'
}
return null
}
const tree = buildTree(templateAST.children)
return { success: true, tree }
} catch (error) {
console.error('[parseElementTree] 错误:', error)
return { success: false, error: error.message }
}
}
export function insertElement(vueContent, options) {
const { templateContent: insertContent, targetPath, direction } = options
try {
// 1. 解析Vue SFC文件
const sfcResult = parseSFC(vueContent)
if (sfcResult.errors.length > 0) {
return {
success: false,
error: `Vue文件解析错误: ${sfcResult.errors[0].message}`
}
}
const templateBlock = sfcResult.descriptor.template
if (!templateBlock) {
return {
success: false,
error: '未找到template块'
}
}
const templateContent = templateBlock.content
// 找到 <template> 内容在原文件中的实际位置
const templateTagStart = vueContent.indexOf('<template')
const templateTagEnd = vueContent.indexOf('>', templateTagStart) + 1
const templateCloseStart = vueContent.indexOf('</template>', templateTagEnd)
const contentStart = templateTagEnd
const contentEnd = templateCloseStart
// 2. 解析template获取AST
const templateAST = parseTemplate(templateContent, {
comments: true,
whitespace: 'preserve'
})
// 3. 查找目标元素
const targetNode = findElementByPath(templateAST, targetPath)
if (!targetNode) {
return { success: false, error: `未找到目标元素: ${targetPath}` }
}
// 4. 获取目标元素的位置和缩进
const targetStart = targetNode.loc.start.offset
const targetEnd = targetNode.loc.end.offset
const targetLineStart = templateContent.lastIndexOf('\n', targetStart - 1) + 1
const targetIndent = templateContent.substring(targetLineStart, targetStart)
console.log(`[insertElement] 目标: ${targetPath} [${targetStart}-${targetEnd}]`)
console.log(`[insertElement] 方向: ${direction}`)
let newTemplateContent
// 5. 根据方向插入
if (direction === 'inside') {
// 放入目标元素内部
const targetText = templateContent.substring(targetStart, targetEnd)
const closeTagPattern = `</${targetNode.tag}>`
const closeTagIndex = targetText.lastIndexOf(closeTagPattern)
if (closeTagIndex === -1) {
return { success: false, error: `未找到目标元素的结束标签` }
}
const insertPosition = targetStart + closeTagIndex
const childIndent = targetIndent + ' '
const adjustedContent = adjustIndentation(insertContent, childIndent)
const insertText = adjustedContent + '\n' + targetIndent
newTemplateContent = templateContent.substring(0, insertPosition) +
insertText +
templateContent.substring(insertPosition)
} else {
// 放在目标元素前面或后面
const insertAfterTarget = (direction === 'bottom' || direction === 'right')
const insertPosition = insertAfterTarget ? targetEnd : targetStart
const adjustedContent = adjustIndentation(insertContent, targetIndent)
const insertText = insertAfterTarget
? '\n' + adjustedContent
: adjustedContent + '\n'
newTemplateContent = templateContent.substring(0, insertPosition) +
insertText +
templateContent.substring(insertPosition)
}
// 6. 重建Vue文件
const newVueContent = vueContent.substring(0, contentStart) +
newTemplateContent +
vueContent.substring(contentEnd)
console.log('[insertElement] 插入成功')
return { success: true, content: newVueContent }
} catch (error) {
console.error('[insertElement] 错误:', error)
return { success: false, error: error.message }
}
}
/**
* 解析组件属性值
* @param {string} vueContent - Vue文件内容
* @param {string} elementPath - 元素路径
* @returns {Object} - { success: boolean, props?: Object, componentId?: string, error?: string }
*/
export function parseComponentProps(vueContent, elementPath) {
try {
const sfcResult = parseSFC(vueContent)
if (sfcResult.errors.length > 0) {
return { success: false, error: `Vue文件解析错误` }
}
const templateBlock = sfcResult.descriptor.template
if (!templateBlock) {
return { success: false, error: '未找到template块' }
}
const templateAST = parseTemplate(templateBlock.content, {
comments: true,
whitespace: 'preserve'
})
const targetNode = findElementByPath(templateAST, elementPath)
if (!targetNode) {
return { success: false, error: `未找到元素: ${elementPath}` }
}
// 提取属性
const props = {}
// 提取span属性从el-col
if (targetNode.tag === 'el-col') {
const spanProp = targetNode.props?.find(p =>
p.name === 'span' || (p.name === 'bind' && p.arg?.content === 'span')
)
if (spanProp) {
if (spanProp.name === 'span' && spanProp.value) {
props.span = parseInt(spanProp.value.content) || 24
} else if (spanProp.exp) {
props.span = parseInt(spanProp.exp.content) || 24
}
} else {
props.span = 24
}
}
// 查找内部组件并提取属性
let componentId = null
const extractChildProps = (children) => {
for (const child of children || []) {
if (child.type !== 1) continue
if (child.tag === 'el-row' || child.tag === 'el-col') continue
// 检查 data-component 属性
const dataCompAttr = child.props?.find(p => p.name === 'data-component')
if (dataCompAttr?.value?.content) {
componentId = dataCompAttr.value.content
}
// 提取子元素属性
extractElementProps(child, props)
// 递归提取孩子节点
if (child.children) {
extractChildProps(child.children)
}
}
}
// 提取元素属性
const extractElementProps = (node, result) => {
if (!node.props) return
for (const prop of node.props) {
if (prop.type === 6) { // 普通属性
const key = `${node.tag}:${prop.name}`
result[key] = prop.value?.content || ''
} else if (prop.type === 7 && prop.name === 'bind') { // v-bind 属性
const key = `${node.tag}::${prop.arg?.content}`
result[key] = prop.exp?.content || ''
}
}
}
extractChildProps(targetNode.children)
console.log('[parseComponentProps] 解析属性:', { elementPath, componentId, props })
return { success: true, props, componentId }
} catch (error) {
console.error('[parseComponentProps] 错误:', error)
return { success: false, error: error.message }
}
}
/**
* 更新组件属性值
* @param {string} vueContent - Vue文件内容
* @param {string} elementPath - 元素路径
* @param {Object} updates - 要更新的属性 { key: value }
* @returns {Object} - { success: boolean, content?: string, error?: string }
*/
export function updateComponentProps(vueContent, elementPath, updates) {
try {
const sfcResult = parseSFC(vueContent)
if (sfcResult.errors.length > 0) {
return { success: false, error: `Vue文件解析错误` }
}
const templateBlock = sfcResult.descriptor.template
if (!templateBlock) {
return { success: false, error: '未找到template块' }
}
const templateContent = templateBlock.content
const templateTagStart = vueContent.indexOf('<template')
const templateTagEnd = vueContent.indexOf('>', templateTagStart) + 1
const templateCloseStart = vueContent.indexOf('</template>', templateTagEnd)
const templateAST = parseTemplate(templateContent, {
comments: true,
whitespace: 'preserve'
})
const targetNode = findElementByPath(templateAST, elementPath)
if (!targetNode) {
return { success: false, error: `未找到元素: ${elementPath}` }
}
let newTemplateContent = templateContent
// 处理span更新el-col的:span属性
if (updates.span !== undefined && targetNode.tag === 'el-col') {
const nodeText = templateContent.substring(targetNode.loc.start.offset, targetNode.loc.end.offset)
const spanMatch = nodeText.match(/:span="(\d+)"/)
if (spanMatch) {
const newNodeText = nodeText.replace(/:span="\d+"/, `:span="${updates.span}"`)
newTemplateContent = newTemplateContent.substring(0, targetNode.loc.start.offset) +
newNodeText +
newTemplateContent.substring(targetNode.loc.end.offset)
}
delete updates.span
}
// 处理其他属性更新
for (const [key, value] of Object.entries(updates)) {
const [tagName, attrName] = key.split(':')
if (!tagName || !attrName) continue
// 查找目标元素
const findTargetElement = (node) => {
if (node.type === 1 && node.tag === tagName) return node
if (node.children) {
for (const child of node.children) {
const found = findTargetElement(child)
if (found) return found
}
}
return null
}
const targetEl = findTargetElement(targetNode)
if (!targetEl) continue
const elStart = targetEl.loc.start.offset
const elEnd = targetEl.loc.end.offset
let elText = newTemplateContent.substring(elStart, elEnd)
// 更新属性
const isBinding = attrName.startsWith(':')
const realAttrName = isBinding ? attrName.substring(1) : attrName
const attrRegex = new RegExp(`(${isBinding ? ':' : ''}${realAttrName})="[^"]*"`)
if (value === '' || value === null || value === undefined) {
// 删除属性
elText = elText.replace(attrRegex, '')
elText = elText.replace(/\s+>/g, '>').replace(/\s{2,}/g, ' ')
} else if (attrRegex.test(elText)) {
// 更新属性
elText = elText.replace(attrRegex, `${isBinding ? ':' : ''}${realAttrName}="${value}"`)
} else {
// 添加属性
const tagEndMatch = elText.match(/<[\w-]+/)
if (tagEndMatch) {
const insertPos = tagEndMatch[0].length
elText = elText.substring(0, insertPos) +
` ${isBinding ? ':' : ''}${realAttrName}="${value}"` +
elText.substring(insertPos)
}
}
newTemplateContent = newTemplateContent.substring(0, elStart) +
elText +
newTemplateContent.substring(elEnd)
}
const newVueContent = vueContent.substring(0, templateTagEnd) +
newTemplateContent +
vueContent.substring(templateCloseStart)
console.log('[updateComponentProps] 更新成功')
return { success: true, content: newVueContent }
} catch (error) {
console.error('[updateComponentProps] 错误:', error)
return { success: false, error: error.message }
}
}
/**
* 删除元素
* @param {string} vueContent - Vue文件内容
* @param {string} elementPath - 元素路径
* @returns {Object} - { success: boolean, content?: string, error?: string }
*/
export function deleteElement(vueContent, elementPath) {
try {
const sfcResult = parseSFC(vueContent)
if (sfcResult.errors.length > 0) {
return { success: false, error: `Vue文件解析错误` }
}
const templateBlock = sfcResult.descriptor.template
if (!templateBlock) {
return { success: false, error: '未找到template块' }
}
const templateContent = templateBlock.content
const templateTagStart = vueContent.indexOf('<template')
const templateTagEnd = vueContent.indexOf('>', templateTagStart) + 1
const templateCloseStart = vueContent.indexOf('</template>', templateTagEnd)
const templateAST = parseTemplate(templateContent, {
comments: true,
whitespace: 'preserve'
})
const targetNode = findElementByPath(templateAST, elementPath)
if (!targetNode) {
return { success: false, error: `未找到元素: ${elementPath}` }
}
// 计算删除范围
let deleteStart = targetNode.loc.start.offset
let deleteEnd = targetNode.loc.end.offset
// 向前查找这一行的开始
const lineStart = templateContent.lastIndexOf('\n', deleteStart - 1) + 1
const beforeElement = templateContent.substring(lineStart, deleteStart)
// 如果元素前面只有空白,则从行开始删除
if (/^\s*$/.test(beforeElement)) {
deleteStart = lineStart
}
// 向后查找是否有换行
if (templateContent[deleteEnd] === '\n') {
deleteEnd = deleteEnd + 1
}
const newTemplateContent = templateContent.substring(0, deleteStart) +
templateContent.substring(deleteEnd)
const newVueContent = vueContent.substring(0, templateTagEnd) +
newTemplateContent +
vueContent.substring(templateCloseStart)
console.log(`[deleteElement] 删除成功: ${elementPath}`)
return { success: true, content: newVueContent }
} catch (error) {
console.error('[deleteElement] 错误:', error)
return { success: false, error: error.message }
}
}