feat: Refactor code structure for improved readability and maintainability

This commit is contained in:
alivender
2025-05-09 19:28:43 +08:00
parent d4b34bd6d4
commit 6a786c1519
17 changed files with 2913 additions and 583 deletions

View File

@@ -2,7 +2,8 @@
<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
<div class="relative bg-base-200 overflow-hidden h-full" :style="{ width: leftPanelWidth + '%' }">
<DiagramCanvas
ref="diagramCanvas"
:componentModules="componentModules"
@component-selected="handleComponentSelected"
@@ -21,86 +22,24 @@
class="resizer cursor-col-resize bg-base-300 hover:bg-primary hover:opacity-70 active:bg-primary active:opacity-90 transition-colors"
@mousedown="startResize"
></div>
<!-- 右侧编辑区域 -->
<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 class="mb-4 pb-4 border-b border-base-300">
<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>
<!-- 动态属性表单 -->
<div v-if="selectedComponentConfig && selectedComponentConfig.props" class="space-y-4">
<div v-for="prop in selectedComponentConfig.props" :key="prop.name" class="form-control">
<label class="label">
<span class="label-text">{{ prop.label || prop.name }}</span>
</label>
<!-- 根据 prop 类型选择输入控件 -->
<input
v-if="prop.type === 'string'"
type="text"
:placeholder="prop.label || prop.name"
class="input input-bordered input-sm w-full"
: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?.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?.attrs?.[prop.name]"
@change="updateComponentProp(selectedComponentData!.id, prop.name, ($event.target as HTMLInputElement).checked)"
/>
<span>{{ prop.label || prop.name }}</span>
</div>
<!-- 下拉选择框 -->
<select
v-else-if="prop.type === 'select' && prop.options"
class="select select-bordered select-sm w-full"
:value="selectedComponentData?.attrs?.[prop.name]"
@change="(event) => {
const selectElement = event.target as HTMLSelectElement;
const value = selectElement.value;
console.log('选择的值:', value, '类型:', typeof value);
if (selectedComponentData) {updateComponentProp(selectedComponentData.id, prop.name, value);}
}"
>
<option v-for="option in prop.options" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
<p v-else class="text-xs text-warning">不支持的属性类型: {{ prop.type }}</p>
</div>
</div>
<div v-else-if="selectedComponentData && !selectedComponentConfig" class="text-gray-500 text-sm">
正在加载组件配置...
</div>
<div v-else-if="selectedComponentData && selectedComponentConfig && (!selectedComponentConfig.props || selectedComponentConfig.props.length === 0)" class="text-gray-500 text-sm">
此组件没有可配置的属性
</div>
<div class="bg-base-100 h-full overflow-hidden flex flex-col" :style="{ width: (100 - leftPanelWidth) + '%' }">
<div class="overflow-y-auto p-4 flex-1">
<PropertyPanel
:componentData="selectedComponentData"
:componentConfig="selectedComponentConfig"
@updateProp="updateComponentProp"
@updateDirectProp="updateComponentDirectProp"
/>
</div>
</div>
</div>
<!-- 元器件选择组件 -->
</div>
</div> <!-- 元器件选择组件 -->
<ComponentSelector
:open="showComponentsMenu"
@update:open="showComponentsMenu = $event"
@add-component="handleAddComponent"
@add-template="handleAddTemplate"
@close="showComponentsMenu = false"
/>
</div>
@@ -112,8 +51,16 @@
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 PropertyPanel from '@/components/PropertyPanel.vue';
import type { DiagramData, DiagramPart, ConnectionArray } from '@/components/diagramManager';
import { validateDiagramData } from '@/components/diagramManager';
import {
type PropertyConfig,
generatePropertyConfigs,
generatePropsFromDefault,
generatePropsFromAttrs,
getPropValue
} from '@/components/equipments/componentConfig'; // 引入组件配置工具
// --- 元器件管理 ---
const showComponentsMenu = ref(false);
@@ -136,18 +83,12 @@ interface ComponentModule {
default: any;
getDefaultProps?: () => Record<string, any>;
config?: {
props?: Array<{
name: string;
type: string;
label?: string;
default: any;
options?: Array<{ value: any; label: string }>; // 添加 options 字段用于 select 类型
}>;
props?: Array<PropertyConfig>;
};
}
const componentModules = shallowRef<Record<string, ComponentModule>>({});
const selectedComponentConfig = shallowRef<ComponentModule['config'] | null>(null); // 存储选中组件的配置
const selectedComponentConfig = shallowRef<{ props: PropertyConfig[] } | null>(null); // 存储选中组件的配置
// 动态加载组件定义
async function loadComponentModule(type: string) {
@@ -228,56 +169,53 @@ async function handleAddComponent(componentData: { type: string; name: string; p
// 获取画布容器和位置信息
const canvasInstance = diagramCanvas.value as any;
// 默认位置(当无法获取画布信息时使用)
let posX = 100;
let posY = 100;
// 获取当前画布的位置信息
let position = { x: 100, y: 100 };
let scale = 1;
try {
if (canvasInstance) {
if (canvasInstance && canvasInstance.getCanvasPosition && canvasInstance.getScale) {
position = canvasInstance.getCanvasPosition();
scale = canvasInstance.getScale();
// 获取画布容器
const canvasContainer = canvasInstance.$el as HTMLElement;
if (canvasContainer) {
// 获取当前画布的位置和缩放信息
const canvasPosition = canvasInstance.getCanvasPosition ?
canvasInstance.getCanvasPosition() :
{ x: 0, y: 0 };
const scale = canvasInstance.getScale ?
canvasInstance.getScale() :
1;
// 计算可视区域中心点在画布坐标系中的位置
const viewportWidth = canvasContainer.clientWidth;
const viewportHeight = canvasContainer.clientHeight;
// 计算画布中心点的坐标
posX = (viewportWidth / 2 - canvasPosition.x) / scale;
posY = (viewportHeight / 2 - canvasPosition.y) / scale;
position.x = (viewportWidth / 2 - position.x) / scale;
position.y = (viewportHeight / 2 - position.y) / scale;
}
}
} catch (error) {
console.error('Error getting canvas position:', error);
// 使用默认位置
console.error('获取画布位置时出错:', error);
}
// 添加一些随机偏移,避免元器件重叠
const offsetX = Math.floor(Math.random() * 100) - 50;
const offsetY = Math.floor(Math.random() * 100) - 50;
// 将原有的 ComponentItem 转换为 DiagramPart
// 创建新组件使用diagramManager接口定义
const newComponent: DiagramPart = {
id: `component-${Date.now()}`,
type: componentData.type,
x: Math.round(posX + offsetX),
y: Math.round(posY + offsetY),
attrs: componentData.props, // 使用从 ComponentSelector 传递的默认属性
x: Math.round(position.x + offsetX),
y: Math.round(position.y + offsetY),
attrs: componentData.props,
rotate: 0,
group: '',
positionlock: false,
hide: false,
isOn: false
hidepins: true,
isOn: true,
index: 0
};
console.log('Adding new component:', newComponent);
// 通过 diagramCanvas 添加组件
console.log('添加组件:', newComponent);
// 通过画布实例添加组件
if (canvasInstance && canvasInstance.getDiagramData && canvasInstance.setDiagramData) {
const currentData = canvasInstance.getDiagramData();
currentData.parts.push(newComponent);
@@ -285,6 +223,133 @@ async function handleAddComponent(componentData: { type: string; name: string; p
}
}
// 处理模板添加事件
async function handleAddTemplate(templateData: { id: string; name: string; template: any }) {
console.log('添加模板:', templateData);
console.log('=== 模板组件数量:', templateData.template?.parts?.length || 0);
// 获取画布实例
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance || !canvasInstance.getDiagramData || !canvasInstance.setDiagramData) {
console.error('没有可用的画布实例添加模板');
return;
}
// 获取当前图表数据
const currentData = canvasInstance.getDiagramData();
console.log('=== 当前图表组件数量:', currentData.parts.length);
// 生成唯一ID前缀以确保添加的组件ID不重复
const idPrefix = `template-${Date.now()}-`;
// 处理模板组件并添加到图表
if (templateData.template && templateData.template.parts) {
// 获取当前视口中心位置
let viewportCenter = { x: 300, y: 200 }; // 默认值
try {
if (canvasInstance && canvasInstance.getCanvasPosition && canvasInstance.getScale) {
const position = canvasInstance.getCanvasPosition();
const scale = canvasInstance.getScale();
// 获取画布容器
const canvasContainer = canvasInstance.$el as HTMLElement;
if (canvasContainer) {
// 计算可视区域中心点在画布坐标系中的位置
const viewportWidth = canvasContainer.clientWidth;
const viewportHeight = canvasContainer.clientHeight;
// 计算视口中心点的坐标 (与handleAddComponent函数中的方法相同)
viewportCenter.x = (viewportWidth / 2 - position.x) / scale;
viewportCenter.y = (viewportHeight / 2 - position.y) / scale;
console.log(`=== 计算的视口中心: x=${viewportCenter.x}, y=${viewportCenter.y}, scale=${scale}`);
}
}
} catch (error) {
console.error('获取视口中心位置时出错:', error);
}
console.log('=== 使用视口中心添加模板组件:', viewportCenter);
// 找到模板中的主要组件(假设是第一个组件)
const mainPart = templateData.template.parts[0];
// 创建带有新位置的组件
const newParts = templateData.template.parts.map((part: any) => {
// 创建组件副本并分配新ID
const newPart = JSON.parse(JSON.stringify(part));
newPart.id = `${idPrefix}${part.id}`;
// 计算相对于主要组件的偏移量,保持模板内部组件的相对位置关系
if (typeof newPart.x === 'number' && typeof newPart.y === 'number') {
const oldX = newPart.x;
const oldY = newPart.y;
// 计算相对位置(相对于主要组件)
const relativeX = part.x - mainPart.x;
const relativeY = part.y - mainPart.y;
// 应用到视口中心位置
newPart.x = viewportCenter.x + relativeX;
newPart.y = viewportCenter.y + relativeY;
console.log(`=== 组件[${newPart.id}]位置调整: (${oldX},${oldY}) -> (${newPart.x},${newPart.y})`);
}
return newPart;
});
// 向图表添加新组件
currentData.parts.push(...newParts);
// 处理连接关系
if (templateData.template.connections) {
// 创建一个映射表用于转换旧组件ID到新组件ID
const idMap: Record<string, string> = {};
templateData.template.parts.forEach((part: any) => {
idMap[part.id] = `${idPrefix}${part.id}`;
});
// 添加连接更新组件ID引用
const newConnections = templateData.template.connections.map((conn: any) => {
// 处理连接数据 (格式为 [from, to, type, path])
if (Array.isArray(conn)) {
const [from, to, type, path] = conn;
// 从连接字符串中提取组件ID和引脚ID
const fromParts = from.split(':');
const toParts = to.split(':');
if (fromParts.length === 2 && toParts.length === 2) {
const fromComponentId = fromParts[0];
const fromPinId = fromParts[1];
const toComponentId = toParts[0];
const toPinId = toParts[1];
// 创建新的连接字符串使用新的组件ID
const newFrom = `${idMap[fromComponentId] || fromComponentId}:${fromPinId}`;
const newTo = `${idMap[toComponentId] || toComponentId}:${toPinId}`;
return [newFrom, newTo, type, path];
}
}
return conn; // 如果格式不匹配,保持原样
});
// 添加到当前连接列表
currentData.connections.push(...newConnections);
}
// 更新图表数据
canvasInstance.setDiagramData(currentData);
console.log('=== 更新图表数据完成,新组件数量:', currentData.parts.length);
// 显示成功消息
showToast(`已添加 ${templateData.name} 模板`, 'success');
} else {
console.error('模板格式错误缺少parts数组');
showToast('模板格式错误', 'error');
}
}
// 处理组件选中事件
async function handleComponentSelected(componentData: DiagramPart | null) {
selectedComponentId.value = componentData ? componentData.id : null;
@@ -296,42 +361,19 @@ async function handleComponentSelected(componentData: DiagramPart | null) {
if (moduleRef) {
try {
// 尝试使用组件导出的getDefaultProps方法获取配置
// 使用组件配置工具创建配置
const propConfigs: PropertyConfig[] = [];
// 1. 自动获取组件属性信息 - 利用DiagramPart接口结构
const directPropConfigs = generatePropertyConfigs(componentData);
propConfigs.push(...directPropConfigs);
// 2. 尝试使用组件导出的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);
}
const defaultPropConfigs = generatePropsFromDefault(defaultProps);
propConfigs.push(...defaultPropConfigs);
selectedComponentConfig.value = { props: propConfigs };
console.log(`Built config for ${componentData.type} from getDefaultProps:`, selectedComponentConfig.value);
@@ -339,22 +381,8 @@ async function handleComponentSelected(componentData: DiagramPart | null) {
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);
}
const attrPropConfigs = generatePropsFromAttrs(attrs);
propConfigs.push(...attrPropConfigs);
selectedComponentConfig.value = { props: propConfigs };
}
@@ -386,22 +414,45 @@ function handleComponentMoved(moveData: { id: string; x: number; y: number }) {
// 处理组件删除事件
function handleComponentDelete(componentId: string) {
// 查找要删除的组件索引
const index = diagramData.value.parts.findIndex(p => p.id === componentId);
if (index !== -1) {
// 从数组中移除该组件
diagramData.value.parts.splice(index, 1);
// 同时删除与该组件相关的所有连接
diagramData.value.connections = diagramData.value.connections.filter(
connection => !connection[0].startsWith(`${componentId}:`) && !connection[1].startsWith(`${componentId}:`)
// 查找要删除的组件
const component = diagramData.value.parts.find(p => p.id === componentId);
if (!component) return;
// 收集需要删除的组件ID列表包括当前组件和同组组件
const componentsToDelete: string[] = [componentId];
// 如果组件属于一个组,则找出所有同组的组件
if (component.group && component.group !== '') {
const groupMembers = diagramData.value.parts.filter(
p => p.group === component.group && p.id !== componentId
);
// 如果删除的是当前选中的组件,清除选中状态
if (selectedComponentId.value === componentId) {
selectedComponentId.value = null;
selectedComponentConfig.value = null;
// 将同组组件ID添加到删除列表
componentsToDelete.push(...groupMembers.map(p => p.id));
console.log(`删除组件 ${componentId} 及其组 ${component.group} 中的 ${groupMembers.length} 个组件`);
}
// 删除所有标记的组件
diagramData.value.parts = diagramData.value.parts.filter(
p => !componentsToDelete.includes(p.id)
);
// 同时删除与这些组件相关的所有连接
diagramData.value.connections = diagramData.value.connections.filter(
connection => {
for (const id of componentsToDelete) {
if (connection[0].startsWith(`${id}:`) || connection[1].startsWith(`${id}:`)) {
return false;
}
}
return true;
}
);
// 如果删除的是当前选中的组件,清除选中状态
if (selectedComponentId.value && componentsToDelete.includes(selectedComponentId.value)) {
selectedComponentId.value = null;
selectedComponentConfig.value = null;
}
}
@@ -409,7 +460,7 @@ function handleComponentDelete(componentId: string) {
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');
console.error('没有可用的画布实例进行属性更新');
return;
}
@@ -417,21 +468,49 @@ function updateComponentProp(componentId: string, propName: string, value: any)
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 = {};
// 检查是否为基本属性
if (propName in part) {
(part as any)[propName] = value;
} else {
// 否则当作attrs中的属性处理
if (!part.attrs) {
part.attrs = {};
}
part.attrs[propName] = value;
}
part.attrs[propName] = value;
canvasInstance.setDiagramData(currentData);
console.log(`Updated ${componentId} prop ${propName} to:`, value, typeof value);
console.log(`更新组件${componentId}的属性${propName}:`, value, typeof value);
}
}
// 更新组件的直接属性
function updateComponentDirectProp(componentId: string, propName: string, value: any) {
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance || !canvasInstance.getDiagramData || !canvasInstance.setDiagramData) {
console.error('没有可用的画布实例进行属性更新');
return;
}
const currentData = canvasInstance.getDiagramData();
const part = currentData.parts.find((p: DiagramPart) => p.id === componentId);
if (part) {
// @ts-ignore: 动态属性赋值
part[propName] = value;
canvasInstance.setDiagramData(currentData);
console.log(`更新组件${componentId}的直接属性${propName}为:`, value, typeof value);
}
}
// 专门用于更新组件的显示层级 - 这个方法可以删除直接使用updateComponentProp即可
// 处理连线创建事件
function handleWireCreated(wireData: any) {
console.log('Wire created:', wireData);
@@ -473,6 +552,9 @@ function showToast(message: string, type: 'success' | 'error' | 'info' = 'info',
}
// 显示通知
// --- 组件属性处理辅助函数 ---
// 直接使用 componentConfig.ts 中导入的 getPropValue 函数
// --- 生命周期钩子 ---
onMounted(async () => {
// 初始化画布设置
@@ -514,7 +596,7 @@ onUnmounted(() => {
.resizer {
width: 6px;
height: 100%;
background-color: var(--b3);
background-color: hsl(var(--b3));
cursor: col-resize;
transition: background-color 0.3s;
z-index: 10;
@@ -544,4 +626,12 @@ onUnmounted(() => {
transform: translateX(0);
}
}
/* 确保滚动行为仅在需要时出现 */
html, body {
overflow: hidden;
height: 100%;
margin: 0;
padding: 0;
}
</style>