refactor: 给Canvas解耦合

This commit is contained in:
SikongJueluo 2025-07-09 15:55:49 +08:00
parent c5ce246caf
commit 91b00a977c
No known key found for this signature in database
7 changed files with 768 additions and 650 deletions

View File

@ -258,7 +258,7 @@ async function loadComponentModule(type: string) {
if (!componentModules.value[type]) {
try {
// src/components/equipments/ type
const module = await import(`../components/equipments/${type}.vue`);
const module = await import(`@/components/equipments/${type}.vue`);
//
componentModules.value = {

View File

@ -83,7 +83,8 @@
}
">
<!-- 动态渲染组件 -->
<component :is="getComponentDefinition(component.type)" v-if="props.componentModules[component.type]"
<component :is="getComponentDefinition(component.type)"
v-if="props.componentModules[component.type] && getComponentDefinition(component.type)"
v-bind="prepareComponentProps(component.attrs || {}, component.id)" @update:bindKey="
(value: string) =>
updateComponentProp(component.id, 'bindKey', value)
@ -98,6 +99,7 @@
<div class="flex flex-col items-center">
<div class="loading loading-spinner loading-xs mb-1"></div>
<span>Loading {{ component.type }}...</span>
<small class="mt-1 text-xs">{{ props.componentModules[component.type] ? 'Module loaded but invalid' : 'Module not found' }}</small>
</div>
</div>
</div>
@ -159,6 +161,7 @@ import type {
} from "./diagramManager";
import { CanvasCurrentSelectedComponentID } from "../InjectKeys";
import { useComponentManager } from "./componentManager";
//
function handleContextMenu(e: MouseEvent) {
@ -168,13 +171,9 @@ function handleContextMenu(e: MouseEvent) {
//
const emit = defineEmits([
"diagram-updated",
"component-selected",
"component-moved",
"component-delete",
"toggle-doc-panel",
"wire-created",
"wire-deleted",
"load-component-module",
"open-components",
]);
@ -184,6 +183,12 @@ const props = defineProps<{
showDocPanel?: boolean; //
}>();
// componentManager
const componentManager = useComponentManager();
if (!componentManager) {
throw new Error("DiagramCanvas must be used within a component manager provider");
}
// --- ---
const canvasContainer = ref<HTMLElement | null>(null);
const canvas = ref<HTMLElement | null>(null);
@ -365,7 +370,13 @@ function onZoom(e: WheelEvent) {
// --- ---
const getComponentDefinition = (type: string) => {
const module = props.componentModules[type];
if (!module) return null;
if (!module) {
console.warn(`No module found for component type: ${type}`);
//
loadComponentModule(type);
return null;
}
//
if (module.default) {
@ -414,8 +425,12 @@ function resetComponentRefs() {
async function loadComponentModule(type: string) {
if (!props.componentModules[type]) {
try {
//
emit("load-component-module", type);
// componentManager
if (componentManager) {
await componentManager.loadComponentModule(type);
//
console.log(`Component module ${type} loaded successfully`);
}
} catch (error) {
console.error(`Failed to request component module ${type}:`, error);
}
@ -428,7 +443,10 @@ function handleCanvasMouseDown(e: MouseEvent) {
if (e.target === canvasContainer.value || e.target === canvas.value) {
if (selectedComponentId.value !== null) {
selectedComponentId.value = null;
emit("component-selected", null);
// componentManager
if (componentManager) {
componentManager.selectComponent(null);
}
}
}
@ -505,7 +523,10 @@ function startComponentDrag(e: MouseEvent, component: DiagramPart) {
//
if (selectedComponentId.value !== component.id) {
selectedComponentId.value = component.id;
emit("component-selected", component);
// componentManager
if (componentManager) {
componentManager.selectComponent(component);
}
}
//
@ -600,12 +621,14 @@ function onComponentDrag(e: MouseEvent) {
}
}
//
emit("component-moved", {
id: draggingComponentId.value,
x: Math.round(newX),
y: Math.round(newY),
});
// componentManager
if (componentManager) {
componentManager.moveComponent({
id: draggingComponentId.value,
x: Math.round(newX),
y: Math.round(newY),
});
}
//
emit("diagram-updated", diagramData.value);
@ -634,14 +657,20 @@ function updateComponentProp(
propName: string,
value: any,
) {
diagramData.value = updatePartAttribute(
diagramData.value,
componentId,
propName,
value,
);
emit("diagram-updated", diagramData.value);
saveDiagramData(diagramData.value);
// componentManager
if (componentManager) {
componentManager.updateComponentProp(componentId, propName, value);
} else {
//
diagramData.value = updatePartAttribute(
diagramData.value,
componentId,
propName,
value,
);
emit("diagram-updated", diagramData.value);
saveDiagramData(diagramData.value);
}
}
// --- 线 ---
@ -871,7 +900,10 @@ function deleteWire(wireIndex: number) {
//
function deleteComponent(componentId: string) {
diagramData.value = deletePart(diagramData.value, componentId);
emit("component-delete", componentId);
// componentManager
if (componentManager) {
componentManager.deleteComponent(componentId);
}
emit("diagram-updated", diagramData.value);
saveDiagramData(diagramData.value);
@ -1024,6 +1056,24 @@ onMounted(async () => {
//
resetComponentRefs();
// componentManager
if (componentManager) {
// API
const canvasAPI = {
getDiagramData: () => diagramData.value,
updateDiagramDataDirectly: (data: DiagramData) => {
diagramData.value = data;
saveDiagramData(data);
emit("diagram-updated", data);
},
getCanvasPosition: () => ({ x: position.x, y: position.y }),
getScale: () => scale.value,
$el: canvasContainer.value,
showToast
};
componentManager.setCanvasRef(canvasAPI);
}
//
try {
diagramData.value = await loadDiagramData();
@ -1039,12 +1089,10 @@ onMounted(async () => {
Array.from(componentTypes),
);
//
componentTypes.forEach((type) => {
if (!props.componentModules[type]) {
emit("load-component-module", type);
}
});
// componentManager
if (componentManager) {
await componentManager.preloadComponentModules(Array.from(componentTypes));
}
} catch (error) {
console.error("加载图表数据失败:", error);
}
@ -1115,7 +1163,7 @@ function updateDiagramDataDirectly(data: DiagramData) {
emit("diagram-updated", data);
}
//
// - 访
defineExpose({
//
getDiagramData: () => diagramData.value,
@ -1154,23 +1202,6 @@ defineExpose({
});
},
//
openDiagramFileSelector,
exportDiagram,
//
getSelectedComponent: () => {
if (!selectedComponentId.value) return null;
return (
diagramParts.value.find((p) => p.id === selectedComponentId.value) || null
);
},
deleteSelectedComponent: () => {
if (selectedComponentId.value) {
deleteComponent(selectedComponentId.value);
}
},
//
getCanvasPosition: () => ({ x: position.x, y: position.y }),
getScale: () => scale.value,

View File

@ -0,0 +1,75 @@
# 组件管理器重构
这次重构将 ProjectView 中关于组件和模板的增删查改逻辑抽取到了独立的服务中,使代码更加模块化和可维护。
## 新增文件
### `/src/components/LabCanvas/componentManager.ts`
使用 VueUse 的 `createInjectionState` 创建的组件管理服务,包含以下功能:
#### 状态管理
- `componentModules`: 存储动态导入的组件模块
- `selectedComponentId`: 当前选中的组件ID
- `selectedComponentData`: 当前选中的组件数据(计算属性)
- `selectedComponentConfig`: 当前选中组件的配置信息
#### 核心方法
- `loadComponentModule(type: string)`: 动态加载组件模块
- `preloadComponentModules(types: string[])`: 预加载多个组件模块
- `addComponent(componentData)`: 添加新组件到画布
- `addTemplate(templateData)`: 添加模板到画布
- `deleteComponent(componentId)`: 删除组件及其相关连接
- `selectComponent(componentData)`: 选中组件并生成配置
- `updateComponentProp()`: 更新组件属性
- `updateComponentDirectProp()`: 更新组件直接属性
- `moveComponent()`: 移动组件位置
### `/src/components/LabCanvas/index.ts`
统一导出文件,提供清晰的模块接口:
- 导出组件管理器的 hooks
- 导出类型定义
## 重构后的 ProjectView
现在 ProjectView 仅负责:
### 页面UI状态管理
- 文档面板的显示/隐藏
- 组件选择器的显示/隐藏
- 通知消息的显示
### 文档相关功能
- 加载和显示教程文档
- 文档面板的切换动画
### 事件委托
- 将所有组件操作事件委托给组件管理器处理
- 保持简洁的事件处理逻辑
## 使用方式
在需要使用组件管理功能的地方:
```typescript
// 提供服务(通常在父组件中)
import { useProvideComponentManager } from "@/components/LabCanvas";
const componentManager = useProvideComponentManager();
// 消费服务(在子组件中)
import { useComponentManager } from "@/components/LabCanvas";
const componentManager = useComponentManager(); // 如果未提供则会报错
```
## 优势
1. **关注点分离**: ProjectView 专注于页面动画和UI状态组件管理逻辑独立
2. **可重用性**: componentManager 可以在其他页面或组件中复用
3. **可测试性**: 组件管理逻辑可以独立进行单元测试
4. **类型安全**: 完整的 TypeScript 类型支持
5. **依赖注入**: 使用 VueUse 的注入机制,避免 prop drilling
## 注意事项
- 组件管理器需要在使用前通过 `useProvideComponentManager` 提供
- 画布引用需要通过 `setCanvasRef` 设置
- 初始化需要调用 `initialize` 方法

View File

@ -0,0 +1,531 @@
import { ref, shallowRef, computed } from "vue";
import { createInjectionState } from "@vueuse/core";
import type { DiagramData, DiagramPart } from "./diagramManager";
import type { PropertyConfig } from "@/components/equipments/componentConfig";
import {
generatePropertyConfigs,
generatePropsFromDefault,
generatePropsFromAttrs,
} from "@/components/equipments/componentConfig";
// 存储动态导入的组件模块
interface ComponentModule {
default: any;
getDefaultProps?: () => Record<string, any>;
config?: {
props?: Array<PropertyConfig>;
};
}
// 定义组件管理器的状态和方法
const [useProvideComponentManager, useComponentManager] = createInjectionState(
() => {
// --- 状态管理 ---
const componentModules = ref<Record<string, ComponentModule>>({});
const selectedComponentId = ref<string | null>(null);
const selectedComponentConfig = shallowRef<{ props: PropertyConfig[] } | null>(null);
const diagramCanvas = ref(null);
// 计算当前选中的组件数据
const selectedComponentData = computed(() => {
if (!diagramCanvas.value || !selectedComponentId.value) return null;
const canvasInstance = diagramCanvas.value as any;
if (canvasInstance && canvasInstance.getDiagramData) {
const data = canvasInstance.getDiagramData();
return data.parts.find((p: DiagramPart) => p.id === selectedComponentId.value) || null;
}
return null;
});
// --- 组件模块管理 ---
/**
*
*/
async function loadComponentModule(type: string) {
console.log(`尝试加载组件模块: ${type}`);
console.log(`当前已加载的模块:`, Object.keys(componentModules.value));
if (!componentModules.value[type]) {
try {
console.log(`正在动态导入模块: @/components/equipments/${type}.vue`);
const module = await import(`@/components/equipments/${type}.vue`);
console.log(`成功导入模块 ${type}:`, module);
// 直接设置新的对象引用以触发响应性
componentModules.value = {
...componentModules.value,
[type]: module,
};
console.log(`模块 ${type} 已添加到 componentModules`);
console.log(`更新后的模块列表:`, Object.keys(componentModules.value));
} catch (error) {
console.error(`Failed to load component module ${type}:`, error);
return null;
}
} else {
console.log(`模块 ${type} 已经存在`);
}
return componentModules.value[type];
}
/**
*
*/
async function preloadComponentModules(componentTypes: string[]) {
console.log("Preloading component modules:", componentTypes);
await Promise.all(
componentTypes.map((type) => loadComponentModule(type))
);
console.log("All component modules loaded");
}
// --- 组件操作 ---
/**
*
*/
async function addComponent(componentData: {
type: string;
name: string;
props: Record<string, any>;
}) {
console.log("=== 开始添加组件 ===");
console.log("组件数据:", componentData);
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance) {
console.error("没有可用的画布实例");
return;
}
// 预加载组件模块,确保组件能正常渲染
console.log(`预加载组件模块: ${componentData.type}`);
const componentModule = await loadComponentModule(componentData.type);
if (!componentModule) {
console.error(`无法加载组件模块: ${componentData.type}`);
return;
}
console.log(`组件模块加载成功: ${componentData.type}`, componentModule);
// 获取画布位置信息
let position = { x: 100, y: 100 };
let scale = 1;
try {
if (canvasInstance.getCanvasPosition && canvasInstance.getScale) {
position = canvasInstance.getCanvasPosition();
scale = canvasInstance.getScale();
const canvasContainer = canvasInstance.$el as HTMLElement;
if (canvasContainer) {
const viewportWidth = canvasContainer.clientWidth;
const viewportHeight = canvasContainer.clientHeight;
position.x = (viewportWidth / 2 - position.x) / scale;
position.y = (viewportHeight / 2 - position.y) / scale;
}
}
} catch (error) {
console.error("获取画布位置时出错:", error);
}
// 添加随机偏移
const offsetX = Math.floor(Math.random() * 100) - 50;
const offsetY = Math.floor(Math.random() * 100) - 50;
// 获取组件能力页面
let capsPage = null;
if (
componentModule &&
componentModule.default &&
typeof componentModule.default.getCapabilities === "function"
) {
try {
capsPage = componentModule.default.getCapabilities();
console.log(`获取到${componentData.type}组件的能力页面`);
} catch (error) {
console.error(`获取${componentData.type}组件能力页面失败:`, error);
}
}
// 创建新组件
const newComponent: DiagramPart = {
id: `component-${Date.now()}`,
type: componentData.type,
x: Math.round(position.x + offsetX),
y: Math.round(position.y + offsetY),
attrs: componentData.props,
rotate: 0,
group: "",
positionlock: false,
hidepins: true,
isOn: true,
index: 0,
};
// 通过画布实例添加组件
if (canvasInstance.getDiagramData && canvasInstance.updateDiagramDataDirectly) {
const currentData = canvasInstance.getDiagramData();
currentData.parts.push(newComponent);
// 使用 updateDiagramDataDirectly 避免触发加载状态
canvasInstance.updateDiagramDataDirectly(currentData);
console.log("组件添加完成:", newComponent);
// 等待Vue的下一个tick确保组件模块已经更新
await new Promise(resolve => setTimeout(resolve, 50));
}
}
/**
*
*/
async function addTemplate(templateData: {
id: string;
name: string;
template: any;
}) {
console.log("添加模板:", templateData);
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance?.getDiagramData || !canvasInstance?.updateDiagramDataDirectly) {
console.error("没有可用的画布实例添加模板");
return;
}
const currentData = canvasInstance.getDiagramData();
console.log("=== 当前图表组件数量:", currentData.parts.length);
// 生成唯一ID前缀
const idPrefix = `template-${Date.now()}-`;
if (templateData.template?.parts) {
// 获取视口中心位置
let viewportCenter = { x: 300, y: 200 };
try {
if (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;
viewportCenter.x = (viewportWidth / 2 - position.x) / scale;
viewportCenter.y = (viewportHeight / 2 - position.y) / scale;
}
}
} catch (error) {
console.error("获取视口中心位置时出错:", error);
}
const mainPart = templateData.template.parts[0];
// 创建新组件
const newParts = await Promise.all(
templateData.template.parts.map(async (part: any) => {
const newPart = JSON.parse(JSON.stringify(part));
newPart.id = `${idPrefix}${part.id}`;
// 加载组件模块并获取能力页面
try {
const componentModule = await loadComponentModule(part.type);
if (
componentModule?.default &&
typeof componentModule.default.getCapabilities === "function"
) {
newPart.capsPage = componentModule.default.getCapabilities();
console.log(`加载模板组件${part.type}组件的能力页面成功`);
}
} catch (error) {
console.error(`加载模板组件${part.type}的能力页面失败:`, error);
}
// 计算新位置
if (typeof newPart.x === "number" && typeof newPart.y === "number") {
const relativeX = part.x - mainPart.x;
const relativeY = part.y - mainPart.y;
newPart.x = viewportCenter.x + relativeX;
newPart.y = viewportCenter.y + relativeY;
}
return newPart;
})
);
currentData.parts.push(...newParts);
// 处理连接关系
if (templateData.template.connections) {
const idMap: Record<string, string> = {};
templateData.template.parts.forEach((part: any) => {
idMap[part.id] = `${idPrefix}${part.id}`;
});
const newConnections = templateData.template.connections.map((conn: any) => {
if (Array.isArray(conn)) {
const [from, to, type, path] = conn;
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];
const newFrom = `${idMap[fromComponentId] || fromComponentId}:${fromPinId}`;
const newTo = `${idMap[toComponentId] || toComponentId}:${toPinId}`;
return [newFrom, newTo, type, path];
}
}
return conn;
});
currentData.connections.push(...newConnections);
}
canvasInstance.updateDiagramDataDirectly(currentData);
console.log("=== 更新图表数据完成,新组件数量:", currentData.parts.length);
return { success: true, message: `已添加 ${templateData.name} 模板` };
} else {
console.error("模板格式错误缺少parts数组");
return { success: false, message: "模板格式错误" };
}
}
/**
*
*/
function deleteComponent(componentId: string) {
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance?.getDiagramData || !canvasInstance?.updateDiagramDataDirectly) {
return;
}
const currentData = canvasInstance.getDiagramData();
const component = currentData.parts.find((p: DiagramPart) => p.id === componentId);
if (!component) return;
const componentsToDelete: string[] = [componentId];
// 处理组件组
if (component.group && component.group !== "") {
const groupMembers = currentData.parts.filter(
(p: DiagramPart) => p.group === component.group && p.id !== componentId
);
componentsToDelete.push(...groupMembers.map((p: DiagramPart) => p.id));
console.log(`删除组件 ${componentId} 及其组 ${component.group} 中的 ${groupMembers.length} 个组件`);
}
// 删除组件
currentData.parts = currentData.parts.filter(
(p: DiagramPart) => !componentsToDelete.includes(p.id)
);
// 删除相关连接
currentData.connections = currentData.connections.filter((connection: any) => {
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;
}
canvasInstance.updateDiagramDataDirectly(currentData);
}
/**
*
*/
async function selectComponent(componentData: DiagramPart | null) {
selectedComponentId.value = componentData ? componentData.id : null;
selectedComponentConfig.value = null;
if (componentData) {
const moduleRef = await loadComponentModule(componentData.type);
if (moduleRef) {
try {
const propConfigs: PropertyConfig[] = [];
const addedProps = new Set<string>();
// 从 getDefaultProps 方法获取默认配置
if (typeof moduleRef.getDefaultProps === "function") {
const defaultProps = moduleRef.getDefaultProps();
const defaultPropConfigs = generatePropsFromDefault(defaultProps);
defaultPropConfigs.forEach((config) => {
propConfigs.push(config);
addedProps.add(config.name);
});
}
// 添加组件直接属性
const directPropConfigs = generatePropertyConfigs(componentData);
const newDirectProps = directPropConfigs.filter(
(config) => !addedProps.has(config.name)
);
propConfigs.push(...newDirectProps);
// 添加 attrs 中的属性
if (componentData.attrs) {
const attrPropConfigs = generatePropsFromAttrs(componentData.attrs);
attrPropConfigs.forEach((attrConfig) => {
const existingIndex = propConfigs.findIndex(
(p) => p.name === attrConfig.name
);
if (existingIndex >= 0) {
propConfigs[existingIndex] = attrConfig;
} else {
propConfigs.push(attrConfig);
}
});
}
selectedComponentConfig.value = { props: propConfigs };
console.log(`Built config for ${componentData.type}:`, selectedComponentConfig.value);
} 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 updateComponentProp(componentId: string, propName: string, value: any) {
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance?.getDiagramData || !canvasInstance?.updateDiagramDataDirectly) {
console.error("没有可用的画布实例进行属性更新");
return;
}
// 检查值格式
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 (propName in part) {
(part as any)[propName] = value;
} else {
if (!part.attrs) {
part.attrs = {};
}
part.attrs[propName] = value;
}
canvasInstance.updateDiagramDataDirectly(currentData);
console.log(`更新组件${componentId}的属性${propName}为:`, value, typeof value);
}
}
/**
*
*/
function updateComponentDirectProp(componentId: string, propName: string, value: any) {
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance?.getDiagramData || !canvasInstance?.updateDiagramDataDirectly) {
console.error("没有可用的画布实例进行属性更新");
return;
}
const currentData = canvasInstance.getDiagramData();
const part = currentData.parts.find((p: DiagramPart) => p.id === componentId);
if (part) {
(part as any)[propName] = value;
canvasInstance.updateDiagramDataDirectly(currentData);
console.log(`更新组件${componentId}的直接属性${propName}为:`, value, typeof value);
}
}
/**
*
*/
function moveComponent(moveData: { id: string; x: number; y: number }) {
const canvasInstance = diagramCanvas.value as any;
if (!canvasInstance?.getDiagramData || !canvasInstance?.updateDiagramDataDirectly) {
return;
}
const currentData = canvasInstance.getDiagramData();
const part = currentData.parts.find((p: DiagramPart) => p.id === moveData.id);
if (part) {
part.x = moveData.x;
part.y = moveData.y;
canvasInstance.updateDiagramDataDirectly(currentData);
}
}
/**
*
*/
function setCanvasRef(canvasRef: any) {
diagramCanvas.value = canvasRef;
}
/**
*
*/
async function initialize() {
const canvasInstance = diagramCanvas.value as any;
if (canvasInstance?.getDiagramData) {
const diagramData = canvasInstance.getDiagramData();
// 收集所有组件类型
const componentTypes = new Set<string>();
diagramData.parts.forEach((part: DiagramPart) => {
componentTypes.add(part.type);
});
// 预加载组件模块
await preloadComponentModules(Array.from(componentTypes));
}
}
return {
// 状态
componentModules,
selectedComponentId,
selectedComponentData,
selectedComponentConfig,
// 方法
loadComponentModule,
preloadComponentModules,
addComponent,
addTemplate,
deleteComponent,
selectComponent,
updateComponentProp,
updateComponentDirectProp,
moveComponent,
setCanvasRef,
initialize,
};
}
);
export { useProvideComponentManager, useComponentManager };

View File

@ -0,0 +1,8 @@
// 导出组件管理器服务
export { useProvideComponentManager, useComponentManager } from './componentManager';
// 导出图表管理器
export type { DiagramData, DiagramPart } from './diagramManager';
// 导出连线管理器
export type { WireItem } from './wireManager';

View File

@ -410,7 +410,7 @@ async function loadComponentModule(type: string) {
if (!componentModules.value[type]) {
try {
// src/components/equipments/ type
const module = await import(`../../components/equipments/${type}.vue`);
const module = await import(`@/components/equipments/${type}.vue`);
//
componentModules.value = {

View File

@ -9,11 +9,9 @@
:min-size="30"
class="relative bg-base-200 overflow-hidden h-full"
>
<DiagramCanvas ref="diagramCanvas" :componentModules="componentModules" :showDocPanel="showDocPanel"
@component-selected="handleComponentSelected" @component-moved="handleComponentMoved"
@component-delete="handleComponentDelete" @wire-created="handleWireCreated" @wire-deeted="handleWireDeleted"
<DiagramCanvas ref="diagramCanvas" :componentModules="componentManager.componentModules.value" :showDocPanel="showDocPanel"
@diagram-updated="handleDiagramUpdated" @open-components="openComponentsMenu"
@load-component-module="handleLoadComponentModule" @toggle-doc-panel="toggleDocPanel" />
@toggle-doc-panel="toggleDocPanel" />
</SplitterPanel>
<!-- 拖拽分割线 -->
<SplitterResizeHandle id="splitter-group-resize-handle" class="w-2 bg-base-100 hover:bg-primary hover:opacity-70 transition-colors" />
@ -25,8 +23,8 @@
>
<div class="overflow-y-auto flex-1">
<!-- 使用条件渲染显示不同的面板 -->
<PropertyPanel v-show="!showDocPanel" :componentData="selectedComponentData"
:componentConfig="selectedComponentConfig" @updateProp="updateComponentProp"
<PropertyPanel v-show="!showDocPanel" :componentData="componentManager.selectedComponentData.value"
:componentConfig="componentManager.selectedComponentConfig.value" @updateProp="updateComponentProp"
@updateDirectProp="updateComponentDirectProp" />
<div v-show="showDocPanel" class="doc-panel overflow-y-auto h-full">
<MarkdownRenderer :content="documentContent" />
@ -42,30 +40,26 @@
</template>
<script setup lang="ts">
// wokwi-elements
// import "@wokwi/elements"; // wokwi
import { ref, computed, onMounted, onUnmounted, shallowRef } from "vue"; // defineAsyncComponent shallowRef
import { ref, onMounted, watch } from "vue";
import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from "reka-ui";
import DiagramCanvas from "@/components/LabCanvas/DiagramCanvas.vue";
import ComponentSelector from "@/components/LabCanvas/ComponentSelector.vue";
import PropertyPanel from "@/components/PropertyPanel.vue";
import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
import type { DiagramData, DiagramPart } from "@/components/LabCanvas/diagramManager";
import {
type PropertyConfig,
generatePropertyConfigs,
generatePropsFromDefault,
generatePropsFromAttrs,
} from "@/components/equipments/componentConfig"; //
// --- ---
const showDocPanel = ref(false);
const documentContent = ref("");
import { useProvideComponentManager } from "@/components/LabCanvas";
import type { DiagramData, DiagramPart } from "@/components/LabCanvas";
//
import { useRoute } from "vue-router";
const route = useRoute();
//
const componentManager = useProvideComponentManager();
// --- ---
const showDocPanel = ref(false);
const documentContent = ref("");
//
async function toggleDocPanel() {
showDocPanel.value = !showDocPanel.value;
@ -108,560 +102,11 @@ async function loadDocumentContent() {
}
}
//
onMounted(async () => {
if (route.query.tutorial) {
showDocPanel.value = true;
await loadDocumentContent();
}
});
// --- ---
// --- UI ---
const showComponentsMenu = ref(false);
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<PropertyConfig>;
};
}
const componentModules = shallowRef<Record<string, ComponentModule>>({});
const selectedComponentConfig = shallowRef<{ props: PropertyConfig[] } | null>(
null,
); //
//
async function loadComponentModule(type: string) {
if (!componentModules.value[type]) {
try {
// src/components/equipments/ type
const module = await import(`../components/equipments/${type}.vue`);
// 使 markRaw
componentModules.value = {
...componentModules.value,
[type]: module,
};
console.log(`Loaded module for ${type}:`, module);
} catch (error) {
console.error(`Failed to load component module ${type}:`, error);
return null;
}
}
return componentModules.value[type];
}
//
async function handleLoadComponentModule(type: string) {
console.log("Handling load component module request for:", type);
await loadComponentModule(type);
}
// --- ---
function openComponentsMenu() {
showComponentsMenu.value = true;
}
// ComponentSelector
async function handleAddComponent(componentData: {
type: string;
name: string;
props: Record<string, any>;
}) {
// 便使
const componentModule = await loadComponentModule(componentData.type);
//
const canvasInstance = diagramCanvas.value as any;
//
let position = { x: 100, y: 100 };
let scale = 1;
try {
if (
canvasInstance &&
canvasInstance.getCanvasPosition &&
canvasInstance.getScale
) {
position = canvasInstance.getCanvasPosition();
scale = canvasInstance.getScale();
//
const canvasContainer = canvasInstance.$el as HTMLElement;
if (canvasContainer) {
//
const viewportWidth = canvasContainer.clientWidth;
const viewportHeight = canvasContainer.clientHeight;
//
position.x = (viewportWidth / 2 - position.x) / scale;
position.y = (viewportHeight / 2 - position.y) / scale;
}
}
} catch (error) {
console.error("获取画布位置时出错:", error);
}
//
const offsetX = Math.floor(Math.random() * 100) - 50;
const offsetY = Math.floor(Math.random() * 100) - 50;
//
let capsPage = null;
if (
componentModule &&
componentModule.default &&
typeof componentModule.default.getCapabilities === "function"
) {
try {
capsPage = componentModule.default.getCapabilities();
console.log(`获取到${componentData.type}组件的能力页面`);
} catch (error) {
console.error(`获取${componentData.type}组件能力页面失败:`, error);
}
}
// 使diagramManager
const newComponent: DiagramPart = {
id: `component-${Date.now()}`,
type: componentData.type,
x: Math.round(position.x + offsetX),
y: Math.round(position.y + offsetY),
attrs: componentData.props,
rotate: 0,
group: "",
positionlock: false,
hidepins: true,
isOn: true,
index: 0,
};
console.log("添加新组件:", newComponent);
//
if (
canvasInstance &&
canvasInstance.getDiagramData &&
canvasInstance.updateDiagramDataDirectly
) {
const currentData = canvasInstance.getDiagramData();
currentData.parts.push(newComponent);
canvasInstance.updateDiagramDataDirectly(currentData);
}
}
//
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.updateDiagramDataDirectly
) {
console.error("没有可用的画布实例添加模板");
return;
}
//
const currentData = canvasInstance.getDiagramData();
console.log("=== 当前图表组件数量:", currentData.parts.length);
// IDID
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 = await Promise.all(
templateData.template.parts.map(async (part: any) => {
// ID
const newPart = JSON.parse(JSON.stringify(part));
newPart.id = `${idPrefix}${part.id}`;
//
try {
const componentModule = await loadComponentModule(part.type);
if (
componentModule &&
componentModule.default &&
typeof componentModule.default.getCapabilities === "function"
) {
newPart.capsPage = componentModule.default.getCapabilities();
console.log(`加载模板组件${part.type}组件的能力页面成功`);
}
} catch (error) {
console.error(`加载模板组件${part.type}的能力页面失败:`, error);
}
//
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) {
// IDID
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;
// IDID
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.updateDiagramDataDirectly(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;
selectedComponentConfig.value = null; //
if (componentData) {
//
const moduleRef = await loadComponentModule(componentData.type);
if (moduleRef) {
try {
//
const propConfigs: PropertyConfig[] = [];
//
const addedProps = new Set<string>();
// 1. getDefaultProps
if (typeof moduleRef.getDefaultProps === "function") {
const defaultProps = moduleRef.getDefaultProps();
const defaultPropConfigs = generatePropsFromDefault(defaultProps);
//
defaultPropConfigs.forEach((config) => {
propConfigs.push(config);
addedProps.add(config.name);
});
}
// 2.
const directPropConfigs = generatePropertyConfigs(componentData);
//
const newDirectProps = directPropConfigs.filter(
(config) => !addedProps.has(config.name),
);
propConfigs.push(...newDirectProps);
// 3. attrs
if (componentData.attrs) {
const attrs = componentData.attrs;
const attrPropConfigs = generatePropsFromAttrs(attrs);
//
attrPropConfigs.forEach((attrConfig) => {
const existingIndex = propConfigs.findIndex(
(p) => p.name === attrConfig.name,
);
if (existingIndex >= 0) {
//
propConfigs[existingIndex] = attrConfig;
} else {
//
propConfigs.push(attrConfig);
}
});
}
selectedComponentConfig.value = { props: propConfigs };
console.log(
`Built config for ${componentData.type}:`,
selectedComponentConfig.value,
);
} 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 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 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,
);
// 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;
}
}
//
function updateComponentProp(
componentId: string,
propName: string,
value: any,
) {
const canvasInstance = diagramCanvas.value as any;
if (
!canvasInstance ||
!canvasInstance.getDiagramData ||
!canvasInstance.updateDiagramDataDirectly
) {
console.error("没有可用的画布实例进行属性更新");
return;
}
// 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 (propName in part) {
(part as any)[propName] = value;
} else {
// attrs
if (!part.attrs) {
part.attrs = {};
}
part.attrs[propName] = value;
}
canvasInstance.updateDiagramDataDirectly(currentData);
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.updateDiagramDataDirectly
) {
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.updateDiagramDataDirectly(currentData);
console.log(
`更新组件${componentId}的直接属性${propName}为:`,
value,
typeof value,
);
}
}
// 线
function handleWireCreated(wireData: any) {
console.log("Wire created:", wireData);
}
// 线
function handleWireDeleted(wireId: string) {
console.log("Wire deleted:", wireId);
}
// --- ---
// --- ---
const showNotification = ref(false);
const notificationMessage = ref("");
const notificationType = ref<"success" | "error" | "info">("info");
@ -686,40 +131,68 @@ function showToast(
}, duration);
}
}
//
// --- ---
// 使 componentConfig.ts getPropValue
// --- ---
function openComponentsMenu() {
showComponentsMenu.value = true;
}
// ComponentSelector
async function handleAddComponent(componentData: {
type: string;
name: string;
props: Record<string, any>;
}) {
await componentManager.addComponent(componentData);
}
//
async function handleAddTemplate(templateData: {
id: string;
name: string;
template: any;
}) {
const result = await componentManager.addTemplate(templateData);
if (result) {
showToast(result.message, result.success ? "success" : "error");
}
}
//
function handleDiagramUpdated(data: DiagramData) {
console.log("Diagram data updated:", data);
}
// - componentManager
function updateComponentProp(
componentId: string,
propName: string,
value: any,
) {
componentManager.updateComponentProp(componentId, propName, value);
}
// - componentManager
function updateComponentDirectProp(
componentId: string,
propName: string,
value: any,
) {
componentManager.updateComponentDirectProp(componentId, propName, value);
}
// --- ---
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");
//
if (route.query.tutorial) {
showDocPanel.value = true;
await loadDocumentContent();
}
});
onUnmounted(() => {
//
//
componentManager.setCanvasRef(diagramCanvas.value);
await componentManager.initialize();
});
</script>