Refactor component configuration and diagram management
- Removed the component configuration from `componentConfig.ts` to streamline the codebase. - Introduced a new `diagram.json` file to define the initial structure for diagrams. - Created a `diagramManager.ts` to handle diagram data, including loading, saving, and validating diagram structures. - Updated `ProjectView.vue` to integrate the new diagram management system, including handling component selection and property updates. - Enhanced the component property management to support dynamic attributes and improved error handling. - Added functions for managing connections between components within the diagram.
This commit is contained in:
@@ -1,24 +1,19 @@
|
||||
<template>
|
||||
<div class="h-screen flex flex-col overflow-hidden">
|
||||
<div class="flex flex-1 overflow-hidden relative">
|
||||
<!-- 左侧图形化区域 -->
|
||||
<div class="relative bg-base-200 overflow-hidden" :style="{ width: leftPanelWidth + '%' }"> <DiagramCanvas
|
||||
ref="diagramCanvas" :components="components"
|
||||
:componentModules="componentModules" @component-selected="handleComponentSelected"
|
||||
<!-- 左侧图形化区域 -->
|
||||
<div class="relative bg-base-200 overflow-hidden" :style="{ width: leftPanelWidth + '%' }"> <DiagramCanvas
|
||||
ref="diagramCanvas"
|
||||
:componentModules="componentModules"
|
||||
@component-selected="handleComponentSelected"
|
||||
@component-moved="handleComponentMoved"
|
||||
@update-component-prop="updateComponentProp"
|
||||
@component-delete="handleComponentDelete"
|
||||
@wire-created="handleWireCreated"
|
||||
@wire-deleted="handleWireDeleted"
|
||||
@diagram-updated="handleDiagramUpdated"
|
||||
@open-components="openComponentsMenu"
|
||||
@load-component-module="handleLoadComponentModule"
|
||||
/>
|
||||
<!-- 添加元器件按钮 -->
|
||||
<button class="btn btn-circle btn-primary absolute top-8 right-8 shadow-lg z-10" @click="openComponentsMenu">
|
||||
<!-- SVG icon -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="12" y1="5" x2="12" y2="19"></line>
|
||||
<line x1="5" y1="12" x2="19" y2="12"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 拖拽分割线 -->
|
||||
@@ -31,11 +26,11 @@
|
||||
<div class="bg-base-100 flex flex-col p-4 overflow-auto" :style="{ width: (100 - leftPanelWidth) + '%' }">
|
||||
<h3 class="text-lg font-bold mb-4">属性编辑器</h3>
|
||||
<div v-if="!selectedComponentData" class="text-gray-400">选择元器件以编辑属性</div>
|
||||
<div v-else>
|
||||
<div v-else>
|
||||
<div class="mb-4 pb-4 border-b border-base-300">
|
||||
<h4 class="font-semibold text-lg mb-1">{{ selectedComponentData.name }}</h4>
|
||||
<p class="text-xs text-gray-500">ID: {{ selectedComponentData.id }}</p>
|
||||
<p class="text-xs text-gray-500">类型: {{ selectedComponentData.type }}</p>
|
||||
<h4 class="font-semibold text-lg mb-1">{{ selectedComponentData?.type }}</h4>
|
||||
<p class="text-xs text-gray-500">ID: {{ selectedComponentData?.id }}</p>
|
||||
<p class="text-xs text-gray-500">类型: {{ selectedComponentData?.type }}</p>
|
||||
</div>
|
||||
|
||||
<!-- 动态属性表单 -->
|
||||
@@ -50,30 +45,32 @@
|
||||
type="text"
|
||||
:placeholder="prop.label || prop.name"
|
||||
class="input input-bordered input-sm w-full"
|
||||
:value="selectedComponentData.props?.[prop.name]"
|
||||
@input="updateComponentProp(selectedComponentData.id, prop.name, ($event.target as HTMLInputElement).value)"
|
||||
:value="selectedComponentData?.attrs?.[prop.name]"
|
||||
@input="updateComponentProp(selectedComponentData!.id, prop.name, ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<input
|
||||
v-else-if="prop.type === 'number'"
|
||||
type="number"
|
||||
:placeholder="prop.label || prop.name"
|
||||
class="input input-bordered input-sm w-full"
|
||||
:value="selectedComponentData.props?.[prop.name]"
|
||||
@input="updateComponentProp(selectedComponentData.id, prop.name, parseFloat(($event.target as HTMLInputElement).value) || prop.default)"
|
||||
/> <!-- 可以为 boolean 添加 checkbox,为 color 添加 color picker 等 -->
|
||||
:value="selectedComponentData?.attrs?.[prop.name]"
|
||||
@input="updateComponentProp(selectedComponentData!.id, prop.name, parseFloat(($event.target as HTMLInputElement).value) || prop.default)"
|
||||
/>
|
||||
<!-- 可以为 boolean 添加 checkbox,为 color 添加 color picker 等 -->
|
||||
<div v-else-if="prop.type === 'boolean'" class="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="checkbox checkbox-sm mr-2"
|
||||
:checked="selectedComponentData.props?.[prop.name]"
|
||||
@change="updateComponentProp(selectedComponentData.id, prop.name, ($event.target as HTMLInputElement).checked)"
|
||||
:checked="selectedComponentData?.attrs?.[prop.name]"
|
||||
@change="updateComponentProp(selectedComponentData!.id, prop.name, ($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span>{{ prop.label || prop.name }}</span>
|
||||
</div> <!-- 下拉选择框 -->
|
||||
</div>
|
||||
<!-- 下拉选择框 -->
|
||||
<select
|
||||
v-else-if="prop.type === 'select' && prop.options"
|
||||
class="select select-bordered select-sm w-full"
|
||||
:value="selectedComponentData.props?.[prop.name]"
|
||||
:value="selectedComponentData?.attrs?.[prop.name]"
|
||||
@change="(event) => {
|
||||
const selectElement = event.target as HTMLSelectElement;
|
||||
const value = selectElement.value;
|
||||
@@ -96,7 +93,8 @@
|
||||
此组件没有可配置的属性。
|
||||
</div>
|
||||
</div>
|
||||
</div> </div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 元器件选择组件 -->
|
||||
<ComponentSelector
|
||||
@@ -114,29 +112,29 @@
|
||||
import { ref, reactive, computed, onMounted, onUnmounted, defineAsyncComponent, shallowRef } from 'vue'; // 引入 defineAsyncComponent 和 shallowRef
|
||||
import DiagramCanvas from '@/components/DiagramCanvas.vue';
|
||||
import ComponentSelector from '@/components/ComponentSelector.vue';
|
||||
import { getComponentConfig } from '@/components/equipments/componentConfig';
|
||||
import type { ComponentConfig } from '@/components/equipments/componentConfig';
|
||||
import type { DiagramData, DiagramPart, ConnectionArray } from '@/components/diagramManager';
|
||||
import { validateDiagramData } from '@/components/diagramManager';
|
||||
|
||||
// --- 元器件管理 ---
|
||||
const showComponentsMenu = ref(false);
|
||||
interface ComponentItem {
|
||||
id: string;
|
||||
type: string; // 现在是组件的文件名或标识符,例如 'MechanicalButton'
|
||||
name: string;
|
||||
x: number;
|
||||
y: number;
|
||||
props?: Record<string, any>; // 添加 props 字段来存储组件实例的属性
|
||||
}
|
||||
const components = ref<ComponentItem[]>([]);
|
||||
const selectedComponentId = ref<string | null>(null); // 重命名为 selectedComponentId
|
||||
const selectedComponentData = computed(() => { // 改为计算属性
|
||||
return components.value.find(c => c.id === selectedComponentId.value) || null;
|
||||
const diagramData = ref<DiagramData>({
|
||||
version: 1,
|
||||
author: 'admin',
|
||||
editor: 'me',
|
||||
parts: [],
|
||||
connections: []
|
||||
});
|
||||
|
||||
const selectedComponentId = ref<string | null>(null);
|
||||
const selectedComponentData = computed(() => {
|
||||
return diagramData.value.parts.find(p => p.id === selectedComponentId.value) || null;
|
||||
});
|
||||
const diagramCanvas = ref(null);
|
||||
|
||||
// 存储动态导入的组件模块
|
||||
interface ComponentModule {
|
||||
default: any;
|
||||
getDefaultProps?: () => Record<string, any>;
|
||||
config?: {
|
||||
props?: Array<{
|
||||
name: string;
|
||||
@@ -173,6 +171,12 @@ async function loadComponentModule(type: string) {
|
||||
return componentModules.value[type];
|
||||
}
|
||||
|
||||
// 处理组件模块加载请求
|
||||
async function handleLoadComponentModule(type: string) {
|
||||
console.log('Handling load component module request for:', type);
|
||||
await loadComponentModule(type);
|
||||
}
|
||||
|
||||
// --- 分割面板 ---
|
||||
const leftPanelWidth = ref(60);
|
||||
const isResizing = ref(false);
|
||||
@@ -259,54 +263,140 @@ async function handleAddComponent(componentData: { type: string; name: string; p
|
||||
const offsetX = Math.floor(Math.random() * 100) - 50;
|
||||
const offsetY = Math.floor(Math.random() * 100) - 50;
|
||||
|
||||
const newComponent: ComponentItem = {
|
||||
// 将原有的 ComponentItem 转换为 DiagramPart
|
||||
const newComponent: DiagramPart = {
|
||||
id: `component-${Date.now()}`,
|
||||
type: componentData.type,
|
||||
name: componentData.name,
|
||||
x: Math.round(posX + offsetX),
|
||||
y: Math.round(posY + offsetY),
|
||||
props: componentData.props, // 使用从 ComponentSelector 传递的默认属性
|
||||
attrs: componentData.props, // 使用从 ComponentSelector 传递的默认属性
|
||||
rotate: 0,
|
||||
group: '',
|
||||
positionlock: false,
|
||||
hide: false,
|
||||
isOn: false
|
||||
};
|
||||
|
||||
components.value.push(newComponent);
|
||||
console.log('Adding new component:', newComponent);
|
||||
// 通过 diagramCanvas 添加组件
|
||||
if (canvasInstance && canvasInstance.getDiagramData && canvasInstance.setDiagramData) {
|
||||
const currentData = canvasInstance.getDiagramData();
|
||||
currentData.parts.push(newComponent);
|
||||
canvasInstance.setDiagramData(currentData);
|
||||
}
|
||||
}
|
||||
|
||||
// 处理组件选中事件
|
||||
async function handleComponentSelected(componentData: ComponentItem | null) {
|
||||
async function handleComponentSelected(componentData: DiagramPart | null) {
|
||||
selectedComponentId.value = componentData ? componentData.id : null;
|
||||
selectedComponentConfig.value = null; // 重置配置
|
||||
|
||||
if (componentData) {
|
||||
// 从配置文件中获取组件配置
|
||||
const config = getComponentConfig(componentData.type);
|
||||
if (config) {
|
||||
selectedComponentConfig.value = config;
|
||||
console.log(`Config for ${componentData.type}:`, config);
|
||||
} else {
|
||||
console.warn(`No config found for component type ${componentData.type}`);
|
||||
}
|
||||
// 先加载组件模块
|
||||
const moduleRef = await loadComponentModule(componentData.type);
|
||||
|
||||
// 同时加载组件模块以备用
|
||||
await loadComponentModule(componentData.type);
|
||||
if (moduleRef) {
|
||||
try {
|
||||
// 尝试使用组件导出的getDefaultProps方法获取配置
|
||||
if (typeof moduleRef.getDefaultProps === 'function') {
|
||||
// 从getDefaultProps方法构建配置
|
||||
const defaultProps = moduleRef.getDefaultProps();
|
||||
const propConfigs = [];
|
||||
|
||||
for (const [propName, propValue] of Object.entries(defaultProps)) {
|
||||
// 跳过pins属性,它是一个特殊的数组属性
|
||||
if (propName === 'pins') continue;
|
||||
|
||||
// 根据属性类型创建配置
|
||||
let propType = typeof propValue;
|
||||
let propConfig: any = {
|
||||
name: propName,
|
||||
label: propName.charAt(0).toUpperCase() + propName.slice(1), // 首字母大写作为标签
|
||||
default: propValue
|
||||
};
|
||||
|
||||
// 根据值类型设置表单控件类型
|
||||
if (propType === 'string') {
|
||||
propConfig.type = 'string';
|
||||
} else if (propType === 'number') {
|
||||
propConfig.type = 'number';
|
||||
propConfig.min = 0;
|
||||
propConfig.max = 100;
|
||||
propConfig.step = 0.1;
|
||||
} else if (propType === 'boolean') {
|
||||
propConfig.type = 'boolean';
|
||||
} else if (propType === 'object' && propValue !== null && propValue.hasOwnProperty('options')) {
|
||||
// 如果是含有options的对象,认为它是select类型
|
||||
propConfig.type = 'select';
|
||||
propConfig.options = propValue.options;
|
||||
}
|
||||
|
||||
propConfigs.push(propConfig);
|
||||
}
|
||||
|
||||
selectedComponentConfig.value = { props: propConfigs };
|
||||
console.log(`Built config for ${componentData.type} from getDefaultProps:`, selectedComponentConfig.value);
|
||||
} else {
|
||||
console.warn(`Component ${componentData.type} does not export getDefaultProps method.`);
|
||||
// 创建一个空配置,只显示组件提供的属性
|
||||
const attrs = componentData.attrs || {};
|
||||
const propConfigs = [];
|
||||
|
||||
for (const [propName, propValue] of Object.entries(attrs)) {
|
||||
// 跳过pins属性
|
||||
if (propName === 'pins') continue;
|
||||
// 根据属性值类型创建配置
|
||||
let propType = typeof propValue;
|
||||
let propConfig: any = {
|
||||
name: propName,
|
||||
label: propName.charAt(0).toUpperCase() + propName.slice(1), // 首字母大写作为标签
|
||||
default: propValue || '',
|
||||
type: propType
|
||||
};
|
||||
|
||||
propConfigs.push(propConfig);
|
||||
}
|
||||
|
||||
selectedComponentConfig.value = { props: propConfigs };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error building config for ${componentData.type}:`, error);
|
||||
selectedComponentConfig.value = { props: [] };
|
||||
}
|
||||
} else {
|
||||
console.warn(`Module for component ${componentData.type} not found.`);
|
||||
selectedComponentConfig.value = { props: [] };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理图表数据更新事件
|
||||
function handleDiagramUpdated(data: DiagramData) {
|
||||
diagramData.value = data;
|
||||
console.log('Diagram data updated:', data);
|
||||
}
|
||||
|
||||
// 处理组件移动事件
|
||||
function handleComponentMoved(moveData: { id: string; x: number; y: number }) {
|
||||
const component = components.value.find(c => c.id === moveData.id);
|
||||
if (component) {
|
||||
component.x = moveData.x;
|
||||
component.y = moveData.y;
|
||||
const part = diagramData.value.parts.find(p => p.id === moveData.id);
|
||||
if (part) {
|
||||
part.x = moveData.x;
|
||||
part.y = moveData.y;
|
||||
}
|
||||
}
|
||||
|
||||
// 处理组件删除事件
|
||||
function handleComponentDelete(componentId: string) {
|
||||
// 查找要删除的组件索引
|
||||
const index = components.value.findIndex(c => c.id === componentId);
|
||||
const index = diagramData.value.parts.findIndex(p => p.id === componentId);
|
||||
if (index !== -1) {
|
||||
// 从数组中移除该组件
|
||||
components.value.splice(index, 1);
|
||||
diagramData.value.parts.splice(index, 1);
|
||||
|
||||
// 同时删除与该组件相关的所有连接
|
||||
diagramData.value.connections = diagramData.value.connections.filter(
|
||||
connection => !connection[0].startsWith(`${componentId}:`) && !connection[1].startsWith(`${componentId}:`)
|
||||
);
|
||||
|
||||
// 如果删除的是当前选中的组件,清除选中状态
|
||||
if (selectedComponentId.value === componentId) {
|
||||
selectedComponentId.value = null;
|
||||
@@ -315,29 +405,29 @@ function handleComponentDelete(componentId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
// 更新组件属性的方法,处理字符串类型的初始值特殊格式
|
||||
function updateComponentProp(componentId: string | { id: string; propName: string; value: any }, propName?: string, value?: any) {
|
||||
// 处理来自 DiagramCanvas 的事件
|
||||
if (typeof componentId === 'object') {
|
||||
const { id, propName: name, value: val } = componentId;
|
||||
componentId = id;
|
||||
propName = name;
|
||||
value = val;
|
||||
// 更新组件属性的方法
|
||||
function updateComponentProp(componentId: string, propName: string, value: any) {
|
||||
const canvasInstance = diagramCanvas.value as any;
|
||||
if (!canvasInstance || !canvasInstance.getDiagramData || !canvasInstance.setDiagramData) {
|
||||
console.error('Canvas instance not available for property update');
|
||||
return;
|
||||
}
|
||||
const component = components.value.find(c => c.id === componentId);
|
||||
if (component && propName !== undefined) {
|
||||
if (!component.props) {
|
||||
component.props = {};
|
||||
|
||||
// 检查值是否为对象,如果是对象并有value属性,则使用该属性值
|
||||
if (value !== null && typeof value === 'object' && 'value' in value) {
|
||||
value = value.value;
|
||||
}
|
||||
const currentData = canvasInstance.getDiagramData();
|
||||
const part = currentData.parts.find((p: DiagramPart) => p.id === componentId);
|
||||
|
||||
if (part) {
|
||||
if (!part.attrs) {
|
||||
part.attrs = {};
|
||||
}
|
||||
|
||||
// 检查值是否为对象,如果是对象并有value属性,则使用该属性值
|
||||
if (value !== null && typeof value === 'object' && 'value' in value) {
|
||||
value = value.value;
|
||||
}
|
||||
|
||||
// 直接更新属性值
|
||||
component.props[propName] = value;
|
||||
part.attrs[propName] = value;
|
||||
|
||||
canvasInstance.setDiagramData(currentData);
|
||||
console.log(`Updated ${componentId} prop ${propName} to:`, value, typeof value);
|
||||
}
|
||||
}
|
||||
@@ -345,19 +435,69 @@ function updateComponentProp(componentId: string | { id: string; propName: strin
|
||||
// 处理连线创建事件
|
||||
function handleWireCreated(wireData: any) {
|
||||
console.log('Wire created:', wireData);
|
||||
// 连线已在DiagramCanvas.vue中完成约束处理
|
||||
}
|
||||
|
||||
// 处理连线删除事件
|
||||
function handleWireDeleted(wireId: string) {
|
||||
console.log('Wire deleted:', wireId);
|
||||
// 可以在这里添加连线删除的相关逻辑
|
||||
}
|
||||
|
||||
// 导出当前diagram数据
|
||||
function exportDiagram() {
|
||||
// 直接使用DiagramCanvas组件提供的导出功能
|
||||
const canvasInstance = diagramCanvas.value as any;
|
||||
if (canvasInstance && canvasInstance.exportDiagram) {
|
||||
canvasInstance.exportDiagram();
|
||||
}
|
||||
}
|
||||
|
||||
// --- 消息提示 ---
|
||||
const showNotification = ref(false);
|
||||
const notificationMessage = ref('');
|
||||
const notificationType = ref<'success' | 'error' | 'info'>('info');
|
||||
|
||||
function showToast(message: string, type: 'success' | 'error' | 'info' = 'info', duration = 3000) { const canvasInstance = diagramCanvas.value as any;
|
||||
if (canvasInstance && canvasInstance.showToast) {
|
||||
canvasInstance.showToast(message, type, duration);
|
||||
} else {
|
||||
// 后备方案:使用原来的通知系统
|
||||
notificationMessage.value = message;
|
||||
notificationType.value = type;
|
||||
showNotification.value = true;
|
||||
|
||||
// 设置自动消失
|
||||
setTimeout(() => {
|
||||
showNotification.value = false;
|
||||
}, duration);
|
||||
}
|
||||
}
|
||||
// 显示通知
|
||||
|
||||
// --- 生命周期钩子 ---
|
||||
onMounted(() => {
|
||||
onMounted(async () => {
|
||||
// 初始化画布设置
|
||||
console.log('ProjectView mounted, diagram canvas ref:', diagramCanvas.value);
|
||||
|
||||
// 获取初始图表数据
|
||||
const canvasInstance = diagramCanvas.value as any;
|
||||
if (canvasInstance && canvasInstance.getDiagramData) {
|
||||
diagramData.value = canvasInstance.getDiagramData();
|
||||
|
||||
// 预加载所有使用的组件模块,以确保它们在渲染时可用
|
||||
const componentTypes = new Set<string>();
|
||||
diagramData.value.parts.forEach(part => {
|
||||
componentTypes.add(part.type);
|
||||
});
|
||||
|
||||
console.log('Preloading component modules:', Array.from(componentTypes));
|
||||
|
||||
// 并行加载所有组件模块
|
||||
await Promise.all(
|
||||
Array.from(componentTypes).map(type => loadComponentModule(type))
|
||||
);
|
||||
|
||||
console.log('All component modules loaded');
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
|
||||
Reference in New Issue
Block a user