refactor: merge

This commit is contained in:
SikongJueluo 2025-07-09 17:08:12 +08:00
commit 2a766c3f6b
No known key found for this signature in database
20 changed files with 1002 additions and 988 deletions

56
components.d.ts vendored Normal file
View File

@ -0,0 +1,56 @@
/* eslint-disable */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
// biome-ignore lint: disable
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
BaseBoard: typeof import('./src/components/equipments/BaseBoard.vue')['default']
Canvas: typeof import('./src/components/Canvas.vue')['default']
CollapsibleSection: typeof import('./src/components/CollapsibleSection.vue')['default']
ComponentSelector: typeof import('./src/components/LabCanvas/ComponentSelector.vue')['default']
DDR: typeof import('./src/components/equipments/DDR.vue')['default']
DDS: typeof import('./src/components/equipments/DDS.vue')['default']
DDSPropertyEditor: typeof import('./src/components/equipments/DDSPropertyEditor.vue')['default']
DiagramCanvas: typeof import('./src/components/LabCanvas/DiagramCanvas.vue')['default']
Dialog: typeof import('./src/components/Dialog.vue')['default']
ETH: typeof import('./src/components/equipments/ETH.vue')['default']
HDMI: typeof import('./src/components/equipments/HDMI.vue')['default']
LabCanvas: typeof import('./src/components/LabCanvasNew/LabCanvas.vue')['default']
LabCanvasNew: typeof import('./src/components/LabCanvas/LabCanvasNew.vue')['default']
LabComponentsDrawer: typeof import('./src/components/LabCanvasNew/LabComponentsDrawer.vue')['default']
LabComponentsDrawerNew: typeof import('./src/components/LabCanvas/LabComponentsDrawerNew.vue')['default']
LoginCard: typeof import('./src/components/LoginCard.vue')['default']
MarkdownRenderer: typeof import('./src/components/MarkdownRenderer.vue')['default']
MechanicalButton: typeof import('./src/components/equipments/MechanicalButton.vue')['default']
MotherBoard: typeof import('./src/components/equipments/MotherBoard.vue')['default']
MotherBoardCaps: typeof import('./src/components/equipments/MotherBoardCaps.vue')['default']
Navbar: typeof import('./src/components/Navbar.vue')['default']
PG2L100H_FBG676: typeof import('./src/components/equipments/PG2L100H_FBG676.vue')['default']
Pin: typeof import('./src/components/equipments/Pin.vue')['default']
PopButton: typeof import('./src/components/PopButton.vue')['default']
PropertyEditor: typeof import('./src/components/PropertyEditor.vue')['default']
PropertyPanel: typeof import('./src/components/PropertyPanel.vue')['default']
RekaSplitterGroup: typeof import('reka-ui')['SplitterGroup']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
SD: typeof import('./src/components/equipments/SD.vue')['default']
SevenSegmentDisplay: typeof import('./src/components/equipments/SevenSegmentDisplay.vue')['default']
SFP: typeof import('./src/components/equipments/SFP.vue')['default']
Sidebar: typeof import('./src/components/Sidebar.vue')['default']
SMA: typeof import('./src/components/equipments/SMA.vue')['default']
SMT_LED: typeof import('./src/components/equipments/SMT_LED.vue')['default']
SplitterGroup: typeof import('reka-ui')['SplitterGroup']
SplitterPanel: typeof import('reka-ui')['SplitterPanel']
SplitterResizeHandle: typeof import('reka-ui')['SplitterResizeHandle']
Switch: typeof import('./src/components/equipments/Switch.vue')['default']
ThemeControlButton: typeof import('./src/components/ThemeControlButton.vue')['default']
ThemeControlToggle: typeof import('./src/components/ThemeControlToggle.vue')['default']
TutorialCarousel: typeof import('./src/components/TutorialCarousel.vue')['default']
UploadCard: typeof import('./src/components/UploadCard.vue')['default']
Wire: typeof import('./src/components/equipments/Wire.vue')['default']
}
}

10
src/assets/base.css Normal file
View File

@ -0,0 +1,10 @@
@import "tailwindcss";
@plugin "daisyui" {
themes: winter --default, night --prefersdark;
}
@custom-variant dark (&:where([data-theme=night], [data-theme=night] *));
@custom-variant light (&:where([data-theme=winter], [data-theme=winter] *));

View File

@ -1,11 +1,4 @@
@import "tailwindcss"; @import "base.css";
@plugin "daisyui" {
themes: winter --default, night --prefersdark;
}
@custom-variant dark (&:where([data-theme=night], [data-theme=night] *));
@custom-variant light (&:where([data-theme=winter], [data-theme=winter] *));
/* 禁止所有图像和SVG选择 */ /* 禁止所有图像和SVG选择 */
img, svg { img, svg {

View File

@ -181,8 +181,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, shallowRef, onMounted } from "vue"; import { ref, computed, shallowRef, onMounted } from "vue";
import motherboardSvg from "../components/equipments/svg/motherboard.svg"; import motherboardSvg from "@/components/equipments/svg/motherboard.svg";
import buttonSvg from "../components//equipments/svg/button.svg"; import buttonSvg from "@/components//equipments/svg/button.svg";
// Props // Props
interface Props { interface Props {
@ -258,7 +258,7 @@ async function loadComponentModule(type: string) {
if (!componentModules.value[type]) { if (!componentModules.value[type]) {
try { try {
// src/components/equipments/ type // src/components/equipments/ type
const module = await import(`../components/equipments/${type}.vue`); const module = await import(`@/components/equipments/${type}.vue`);
// //
componentModules.value = { componentModules.value = {

View File

@ -83,14 +83,15 @@
} }
"> ">
<!-- 动态渲染组件 --> <!-- 动态渲染组件 -->
<component :is="getComponentDefinition(component.type)" v-if="props.componentModules[component.type]" <component :is="componentManager.getComponentDefinition(component.type)"
v-bind="prepareComponentProps(component.attrs || {}, component.id)" @update:bindKey=" v-if="componentManager.componentModules.value[component.type] && componentManager.getComponentDefinition(component.type)"
v-bind="componentManager.prepareComponentProps(component.attrs || {}, component.id)" @update:bindKey="
(value: string) => (value: string) =>
updateComponentProp(component.id, 'bindKey', value) updateComponentProp(component.id, 'bindKey', value)
" @pin-click=" " @pin-click="
(pinInfo: any) => (pinInfo: any) =>
handlePinClick(component.id, pinInfo, pinInfo.originalEvent) handlePinClick(component.id, pinInfo, pinInfo.originalEvent)
" :ref="(el: any) => setComponentRef(component.id, el)" /> " :ref="(el: any) => componentManager.setComponentRef(component.id, el)" />
<!-- Fallback if component module not loaded yet --> <!-- Fallback if component module not loaded yet -->
<div v-else <div v-else
@ -98,6 +99,7 @@
<div class="flex flex-col items-center"> <div class="flex flex-col items-center">
<div class="loading loading-spinner loading-xs mb-1"></div> <div class="loading loading-spinner loading-xs mb-1"></div>
<span>Loading {{ component.type }}...</span> <span>Loading {{ component.type }}...</span>
<small class="mt-1 text-xs">{{ componentManager.componentModules.value[component.type] ? 'Module loaded but invalid' : 'Module not found' }}</small>
</div> </div>
</div> </div>
</div> </div>
@ -136,7 +138,8 @@ import {
watch, watch,
provide, provide,
} from "vue"; } from "vue";
import WireComponent from "./equipments/Wire.vue"; import { useEventListener } from "@vueuse/core";
import WireComponent from "@/components/equipments/Wire.vue";
// diagram // diagram
import { import {
@ -149,16 +152,17 @@ import {
parseConnectionPin, parseConnectionPin,
connectionArrayToWireItem, connectionArrayToWireItem,
validateDiagramData, validateDiagramData,
} from "./diagramManager"; } from "./composable/diagramManager";
import type { import type {
DiagramData, DiagramData,
DiagramPart, DiagramPart,
ConnectionArray, ConnectionArray,
WireItem, WireItem,
} from "./diagramManager"; } from "./composable/diagramManager";
import { CanvasCurrentSelectedComponentID } from "./InjectKeys"; import { CanvasCurrentSelectedComponentID } from "../InjectKeys";
import { useComponentManager } from "./composable/componentManager";
// //
function handleContextMenu(e: MouseEvent) { function handleContextMenu(e: MouseEvent) {
@ -168,22 +172,23 @@ function handleContextMenu(e: MouseEvent) {
// //
const emit = defineEmits([ const emit = defineEmits([
"diagram-updated", "diagram-updated",
"component-selected",
"component-moved",
"component-delete",
"toggle-doc-panel", "toggle-doc-panel",
"wire-created", "wire-created",
"wire-deleted", "wire-deleted",
"load-component-module",
"open-components", "open-components",
]); ]);
// //
const props = defineProps<{ const props = defineProps<{
componentModules: Record<string, any>;
showDocPanel?: boolean; // 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 canvasContainer = ref<HTMLElement | null>(null);
const canvas = ref<HTMLElement | null>(null); const canvas = ref<HTMLElement | null>(null);
@ -209,8 +214,8 @@ const diagramData = ref<DiagramData>({
connections: [], connections: [],
}); });
// // 便
const componentRefs = ref<Record<string, any>>({}); const componentRefs = computed(() => componentManager?.componentRefs.value || {});
// diagramData index // diagramData index
const diagramParts = computed<DiagramPart[]>(() => { const diagramParts = computed<DiagramPart[]>(() => {
@ -254,7 +259,7 @@ const wireItems = computed<WireItem[]>(() => {
startPos.y = startComp.y; startPos.y = startComp.y;
// //
const startCompRef = componentRefs.value?.[startCompId]; const startCompRef = componentManager?.getComponentRef(startCompId);
if (startCompRef && typeof startCompRef.getPinPosition === "function") { if (startCompRef && typeof startCompRef.getPinPosition === "function") {
try { try {
const pinPos = startCompRef.getPinPosition(startPinId); const pinPos = startCompRef.getPinPosition(startPinId);
@ -280,7 +285,7 @@ const wireItems = computed<WireItem[]>(() => {
endPos.y = endComp.y; endPos.y = endComp.y;
// //
const endCompRef = componentRefs.value?.[endCompId]; const endCompRef = componentManager?.getComponentRef(endCompId);
if (endCompRef && typeof endCompRef.getPinPosition === "function") { if (endCompRef && typeof endCompRef.getPinPosition === "function") {
try { try {
const pinPos = endCompRef.getPinPosition(endPinId); const pinPos = endCompRef.getPinPosition(endPinId);
@ -325,6 +330,37 @@ const toastTimers: number[] = [];
// //
const fileInput = ref<HTMLInputElement | null>(null); const fileInput = ref<HTMLInputElement | null>(null);
// VueUse
const isDragEventActive = ref(false);
const isComponentDragEventActive = ref(false);
const isWireCreationEventActive = ref(false);
// 使VueUse
//
useEventListener(document, 'mousemove', (e: MouseEvent) => {
if (isDragEventActive.value) {
onDrag(e);
}
if (isComponentDragEventActive.value) {
onComponentDrag(e);
}
if (isWireCreationEventActive.value) {
onCreatingWireMouseMove(e);
}
});
useEventListener(document, 'mouseup', () => {
if (isDragEventActive.value) {
stopDrag();
}
if (isComponentDragEventActive.value) {
stopComponentDrag();
}
});
//
useEventListener(window, 'keydown', handleKeyDown);
// --- --- // --- ---
const MIN_SCALE = 0.2; const MIN_SCALE = 0.2;
const MAX_SCALE = 10.0; const MAX_SCALE = 10.0;
@ -362,73 +398,16 @@ function onZoom(e: WheelEvent) {
scale.value = newScale; scale.value = newScale;
} }
// --- ---
const getComponentDefinition = (type: string) => {
const module = props.componentModules[type];
if (!module) return null;
//
if (module.default) {
return module.default;
} else if (module.__esModule && module.default) {
// Vue __esModule
return module.default;
} else {
console.warn(
`Module for ${type} found but default export is missing`,
module,
);
return null;
}
};
function prepareComponentProps(
attrs: Record<string, any>,
componentId?: string,
): Record<string, any> {
const result: Record<string, any> = { ...attrs };
if (componentId) {
result.componentId = componentId;
}
// console.log(` ID: ${componentId}`, result);
return result;
}
//
function setComponentRef(componentId: string, el: any) {
if (componentRefs.value) {
if (el) {
componentRefs.value[componentId] = el;
} else {
delete componentRefs.value[componentId];
}
}
}
//
function resetComponentRefs() {
componentRefs.value = {};
}
//
async function loadComponentModule(type: string) {
if (!props.componentModules[type]) {
try {
//
emit("load-component-module", type);
} catch (error) {
console.error(`Failed to request component module ${type}:`, error);
}
}
}
// --- --- // --- ---
function handleCanvasMouseDown(e: MouseEvent) { function handleCanvasMouseDown(e: MouseEvent) {
// //
if (e.target === canvasContainer.value || e.target === canvas.value) { if (e.target === canvasContainer.value || e.target === canvas.value) {
if (selectedComponentId.value !== null) { if (selectedComponentId.value !== null) {
selectedComponentId.value = null; selectedComponentId.value = null;
emit("component-selected", null); // componentManager
if (componentManager) {
componentManager.selectComponent(null);
}
} }
} }
@ -450,8 +429,7 @@ function startDrag(e: MouseEvent) {
dragStart.x = e.clientX - position.x; dragStart.x = e.clientX - position.x;
dragStart.y = e.clientY - position.y; dragStart.y = e.clientY - position.y;
document.addEventListener("mousemove", onDrag); isDragEventActive.value = true;
document.addEventListener("mouseup", stopDrag);
e.preventDefault(); e.preventDefault();
} }
@ -466,8 +444,7 @@ function startMiddleDrag(e: MouseEvent) {
dragStart.x = e.clientX - position.x; dragStart.x = e.clientX - position.x;
dragStart.y = e.clientY - position.y; dragStart.y = e.clientY - position.y;
document.addEventListener("mousemove", onDrag); isDragEventActive.value = true;
document.addEventListener("mouseup", stopDrag);
e.preventDefault(); e.preventDefault();
} }
@ -483,9 +460,7 @@ function onDrag(e: MouseEvent) {
function stopDrag() { function stopDrag() {
isDragging.value = false; isDragging.value = false;
isMiddleDragging.value = false; isMiddleDragging.value = false;
isDragEventActive.value = false;
document.removeEventListener("mousemove", onDrag);
document.removeEventListener("mouseup", stopDrag);
} }
// --- --- // --- ---
@ -505,7 +480,10 @@ function startComponentDrag(e: MouseEvent, component: DiagramPart) {
// //
if (selectedComponentId.value !== component.id) { if (selectedComponentId.value !== component.id) {
selectedComponentId.value = component.id; selectedComponentId.value = component.id;
emit("component-selected", component); // componentManager
if (componentManager) {
componentManager.selectComponent(component);
}
} }
// //
@ -537,9 +515,8 @@ function startComponentDrag(e: MouseEvent, component: DiagramPart) {
componentDragOffset.x = mouseX_canvas - component.x; componentDragOffset.x = mouseX_canvas - component.x;
componentDragOffset.y = mouseY_canvas - component.y; componentDragOffset.y = mouseY_canvas - component.y;
// //
document.addEventListener("mousemove", onComponentDrag); isComponentDragEventActive.value = true;
document.addEventListener("mouseup", stopComponentDrag);
} }
// //
@ -568,14 +545,6 @@ function onComponentDrag(e: MouseEvent) {
); );
if (!draggedComponent) return; if (!draggedComponent) return;
//
// diagramData.value = updatePartPosition(
// diagramData.value,
// draggingComponentId.value,
// Math.round(newX),
// Math.round(newY),
// );
// //
if (draggedComponent.group) { if (draggedComponent.group) {
const deltaX = Math.round(newX) - draggedComponent.x; const deltaX = Math.round(newX) - draggedComponent.x;
@ -600,12 +569,14 @@ function onComponentDrag(e: MouseEvent) {
} }
} }
// // componentManager
emit("component-moved", { if (componentManager) {
componentManager.moveComponent({
id: draggingComponentId.value, id: draggingComponentId.value,
x: Math.round(newX), x: Math.round(newX),
y: Math.round(newY), y: Math.round(newY),
}); });
}
// //
emit("diagram-updated", diagramData.value); emit("diagram-updated", diagramData.value);
@ -624,8 +595,7 @@ function stopComponentDrag() {
draggingComponentId.value = null; draggingComponentId.value = null;
} }
document.removeEventListener("mousemove", onComponentDrag); isComponentDragEventActive.value = false;
document.removeEventListener("mouseup", stopComponentDrag);
} }
// //
@ -634,6 +604,11 @@ function updateComponentProp(
propName: string, propName: string,
value: any, value: any,
) { ) {
// componentManager
if (componentManager) {
componentManager.updateComponentProp(componentId, propName, value);
} else {
//
diagramData.value = updatePartAttribute( diagramData.value = updatePartAttribute(
diagramData.value, diagramData.value,
componentId, componentId,
@ -642,6 +617,7 @@ function updateComponentProp(
); );
emit("diagram-updated", diagramData.value); emit("diagram-updated", diagramData.value);
saveDiagramData(diagramData.value); saveDiagramData(diagramData.value);
}
} }
// --- 线 --- // --- 线 ---
@ -671,8 +647,6 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
console.log("鼠标位置:", mousePosition); console.log("鼠标位置:", mousePosition);
if (!isCreatingWire.value) { if (!isCreatingWire.value) {
// 线
const containerRect = canvasContainer.value.getBoundingClientRect();
// //
let pinPosition = pinInfo.position; let pinPosition = pinInfo.position;
console.log("Pin信息:", pinInfo); console.log("Pin信息:", pinInfo);
@ -681,7 +655,7 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
console.log("引脚ID:", pinId); console.log("引脚ID:", pinId);
// //
const component = componentRefs.value[componentId]; const component = componentManager?.getComponentRef(componentId);
console.log("组件引用:", component); console.log("组件引用:", component);
// //
@ -742,7 +716,7 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
pinId, pinId,
pinInfo.constraint, pinInfo.constraint,
); );
document.addEventListener("mousemove", onCreatingWireMouseMove); isWireCreationEventActive.value = true;
} else { } else {
// 线 // 线
if ( if (
@ -757,7 +731,7 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
// //
let endPosition = { x: 0, y: 0 }; let endPosition = { x: 0, y: 0 };
const componentPart = diagramParts.value.find((p) => p.id === componentId); const componentPart = diagramParts.value.find((p) => p.id === componentId);
const endComponent = componentRefs.value[componentId]; const endComponent = componentManager?.getComponentRef(componentId);
console.log("终点组件部件:", componentPart); console.log("终点组件部件:", componentPart);
console.log("终点组件引用:", endComponent); console.log("终点组件引用:", endComponent);
@ -819,7 +793,7 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
// 线 // 线
resetWireCreation(); resetWireCreation();
document.removeEventListener("mousemove", onCreatingWireMouseMove); isWireCreationEventActive.value = false;
} }
} }
@ -852,7 +826,7 @@ function resetWireCreation() {
// 线 // 线
function cancelWireCreation() { function cancelWireCreation() {
resetWireCreation(); resetWireCreation();
document.removeEventListener("mousemove", onCreatingWireMouseMove); isWireCreationEventActive.value = false;
} }
// 线 // 线
@ -871,7 +845,10 @@ function deleteWire(wireIndex: number) {
// //
function deleteComponent(componentId: string) { function deleteComponent(componentId: string) {
diagramData.value = deletePart(diagramData.value, componentId); diagramData.value = deletePart(diagramData.value, componentId);
emit("component-delete", componentId); // componentManager
if (componentManager) {
componentManager.deleteComponent(componentId);
}
emit("diagram-updated", diagramData.value); emit("diagram-updated", diagramData.value);
saveDiagramData(diagramData.value); saveDiagramData(diagramData.value);
@ -1021,8 +998,23 @@ function showToast(
// --- --- // --- ---
onMounted(async () => { onMounted(async () => {
// // componentManager
resetComponentRefs(); 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 { try {
@ -1039,12 +1031,10 @@ onMounted(async () => {
Array.from(componentTypes), Array.from(componentTypes),
); );
// // componentManager
componentTypes.forEach((type) => { if (componentManager) {
if (!props.componentModules[type]) { await componentManager.preloadComponentModules(Array.from(componentTypes));
emit("load-component-module", type);
} }
});
} catch (error) { } catch (error) {
console.error("加载图表数据失败:", error); console.error("加载图表数据失败:", error);
} }
@ -1054,9 +1044,6 @@ onMounted(async () => {
position.x = canvasContainer.value.clientWidth / 2 - 5000; // position.x = canvasContainer.value.clientWidth / 2 - 5000; //
position.y = canvasContainer.value.clientHeight / 2 - 5000; // position.y = canvasContainer.value.clientHeight / 2 - 5000; //
} }
//
window.addEventListener("keydown", handleKeyDown);
}); });
// //
@ -1075,32 +1062,15 @@ function handleKeyDown(e: KeyboardEvent) {
} }
onUnmounted(() => { onUnmounted(() => {
//
document.removeEventListener("mousemove", onComponentDrag);
document.removeEventListener("mouseup", stopComponentDrag);
document.removeEventListener("mousemove", onDrag);
document.removeEventListener("mouseup", stopDrag);
document.removeEventListener("mousemove", onCreatingWireMouseMove);
//
window.removeEventListener("keydown", handleKeyDown);
// toast // toast
toastTimers.forEach((timerId) => clearTimeout(timerId)); toastTimers.forEach((timerId) => clearTimeout(timerId));
//
isDragEventActive.value = false;
isComponentDragEventActive.value = false;
isWireCreationEventActive.value = false;
}); });
// --- API ---
//
function getDiagramData() {
return diagramData.value;
}
//
function setDiagramData(data: DiagramData) {
diagramData.value = data;
emit("diagram-updated", data);
}
// //
function updateDiagramDataDirectly(data: DiagramData) { function updateDiagramDataDirectly(data: DiagramData) {
// //
@ -1115,7 +1085,7 @@ function updateDiagramDataDirectly(data: DiagramData) {
emit("diagram-updated", data); emit("diagram-updated", data);
} }
// // - 访
defineExpose({ defineExpose({
// //
getDiagramData: () => diagramData.value, getDiagramData: () => diagramData.value,
@ -1154,23 +1124,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 }), getCanvasPosition: () => ({ x: position.x, y: position.y }),
getScale: () => scale.value, getScale: () => scale.value,
@ -1187,15 +1140,6 @@ watch(
}, },
{ deep: true }, { deep: true },
); );
//
watch(
() => props.componentModules,
() => {
// Vue setComponentRef
},
{ deep: true },
);
</script> </script>
<style scoped> <style scoped>

View File

@ -0,0 +1,646 @@
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>;
};
__esModule?: boolean; // 添加 __esModule 属性
}
// 定义组件管理器的状态和方法
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<any>(null);
const componentRefs = ref<Record<string, any>>({});
// 计算当前选中的组件数据
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;
}
/**
* DOM引用
*/
function setComponentRef(componentId: string, el: any) {
if (el) {
componentRefs.value[componentId] = el;
} else {
delete componentRefs.value[componentId];
}
}
/**
* DOM引用
*/
function getComponentRef(componentId: string) {
return componentRefs.value[componentId];
}
/**
*
*/
function getDiagramData() {
const canvasInstance = diagramCanvas.value;
if (canvasInstance && canvasInstance.getDiagramData) {
return canvasInstance.getDiagramData();
}
return { parts: [], connections: [], version: 1, author: "admin", editor: "me" };
}
/**
*
*/
function updateDiagramData(data: any) {
const canvasInstance = diagramCanvas.value;
if (canvasInstance && canvasInstance.updateDiagramDataDirectly) {
canvasInstance.updateDiagramDataDirectly(data);
}
}
/**
*
*/
function getCanvasInfo() {
const canvasInstance = diagramCanvas.value;
if (!canvasInstance) return { position: { x: 0, y: 0 }, scale: 1 };
const position = canvasInstance.getCanvasPosition ? canvasInstance.getCanvasPosition() : { x: 0, y: 0 };
const scale = canvasInstance.getScale ? canvasInstance.getScale() : 1;
return { position, scale };
}
/**
*
*/
function showToast(message: string, type: "success" | "error" | "info" = "info") {
const canvasInstance = diagramCanvas.value;
if (canvasInstance && canvasInstance.showToast) {
canvasInstance.showToast(message, type);
}
}
/**
*
*/
function getComponentDefinition(type: string) {
const module = componentModules.value[type];
if (!module) {
console.warn(`No module found for component type: ${type}`);
// 尝试异步加载组件模块
loadComponentModule(type);
return null;
}
// 确保我们返回一个有效的组件定义
if (module.default) {
return module.default;
} else if (module.__esModule && module.default) {
// 有时 Vue 的动态导入会将默认导出包装在 __esModule 属性下
return module.default;
} else {
console.warn(
`Module for ${type} found but default export is missing`,
module,
);
return null;
}
}
/**
*
*/
function prepareComponentProps(
attrs: Record<string, any>,
componentId?: string,
): Record<string, any> {
const result: Record<string, any> = { ...attrs };
if (componentId) {
result.componentId = componentId;
}
return result;
}
/**
*
*/
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,
componentRefs,
// 方法
loadComponentModule,
preloadComponentModules,
addComponent,
addTemplate,
deleteComponent,
selectComponent,
updateComponentProp,
updateComponentDirectProp,
moveComponent,
setCanvasRef,
setComponentRef,
getComponentRef,
getDiagramData,
updateDiagramData,
getCanvasInfo,
showToast,
getComponentDefinition,
prepareComponentProps,
initialize,
};
}
);
export { useProvideComponentManager, useComponentManager };

View File

@ -83,4 +83,3 @@ export function setMousePosition(x: number, y: number) {
mousePosition.y = y; mousePosition.y = y;
} }
// 其它Wire相关操作可继续扩展...

View File

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

View File

@ -128,7 +128,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref } from "vue"; import { ref } from "vue";
import CollapsibleSection from "./CollapsibleSection.vue"; import CollapsibleSection from "./CollapsibleSection.vue";
import { type DiagramPart } from "@/components/diagramManager"; import { type DiagramPart } from "@/components/LabCanvas/composable/diagramManager";
import { import {
type PropertyConfig, type PropertyConfig,
getPropValue, getPropValue,

View File

@ -68,7 +68,7 @@
<script setup lang="ts"> <script setup lang="ts">
// //
import { type DiagramPart } from "@/components/diagramManager"; // import { type DiagramPart } from "@/components/LabCanvas/composable/diagramManager"; //
import { type PropertyConfig } from "@/components/equipments/componentConfig"; // import { type PropertyConfig } from "@/components/equipments/componentConfig"; //
import CollapsibleSection from "./CollapsibleSection.vue"; // import CollapsibleSection from "./CollapsibleSection.vue"; //
import PropertyEditor from "./PropertyEditor.vue"; // import PropertyEditor from "./PropertyEditor.vue"; //

View File

@ -1,5 +1,5 @@
// componentConfig.ts 提供通用的组件配置功能 // componentConfig.ts 提供通用的组件配置功能
import type { DiagramPart } from '../diagramManager'; import type { DiagramPart } from '../LabCanvas/composable/diagramManager';
// 属性配置接口 // 属性配置接口
export interface PropertyConfig { export interface PropertyConfig {

View File

@ -2,13 +2,10 @@ import './assets/main.css'
import { createApp } from 'vue' import { createApp } from 'vue'
import { createPinia } from 'pinia' import { createPinia } from 'pinia'
import VueKonva from "vue-konva"
import App from '@/App.vue' import App from '@/App.vue'
import router from './router' import router from './router'
// import { Client } from './APIClient'
const app = createApp(App).use(router).use(createPinia()).mount('#app') const app = createApp(App).use(router).use(createPinia()).use(VueKonva).mount('#app')
// 初始化约束通信
// initConstraintCommunication();

View File

@ -1,7 +1,7 @@
import { ref, reactive, watchPostEffect } from 'vue' import { ref, reactive, watchPostEffect } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { isString, toNumber } from 'lodash'; import { isString, toNumber } from 'lodash';
import { Common } from '@/Common'; import { Common } from '@/utils/Common';
import z from "zod" import z from "zod"
import { isNumber } from 'mathjs'; import { isNumber } from 'mathjs';
import { JtagClient, MatrixKeyClient, PowerClient } from "@/APIClient"; import { JtagClient, MatrixKeyClient, PowerClient } from "@/APIClient";

View File

@ -1,4 +1,4 @@
import { type FileParameter } from "./APIClient"; import { type FileParameter } from "@/APIClient";
import { isNull, isUndefined } from "lodash"; import { isNull, isUndefined } from "lodash";
export namespace Common { export namespace Common {

30
src/utils/VueKonvaType.ts Normal file
View File

@ -0,0 +1,30 @@
import Konva from "konva";
import type { VueElement } from "vue";
interface VNode extends VueElement {
getNode(): Konva.Node
}
interface VLayer extends VueElement {
getNode(): Konva.Layer
}
interface VGroup extends VueElement {
getNode(): Konva.Group
}
interface VStage extends VueElement {
getNode(): Konva.Stage
}
interface VTransformer extends VueElement {
getNode(): Konva.Transformer
}
export type {
VNode,
VLayer,
VGroup,
VStage,
VTransformer,
}

View File

@ -115,7 +115,7 @@ import { isNull, isUndefined } from "lodash";
import { ref } from "vue"; import { ref } from "vue";
import { RemoteUpdateClient } from "@/APIClient"; import { RemoteUpdateClient } from "@/APIClient";
import { useDialogStore } from "@/stores/dialog"; import { useDialogStore } from "@/stores/dialog";
import { Common } from "@/Common"; import { Common } from "@/utils/Common";
const dialog = useDialogStore(); const dialog = useDialogStore();

View File

@ -1,31 +1,37 @@
<template> <template>
<div class="h-screen flex flex-col overflow-hidden"> <div class="h-screen flex flex-col overflow-hidden">
<div class="flex flex-1 overflow-hidden relative"> <div class="flex flex-1 overflow-hidden relative">
<SplitterGroup id="splitter-group" direction="horizontal" class="w-full h-full">
<!-- 左侧图形化区域 --> <!-- 左侧图形化区域 -->
<div class="relative bg-base-200 overflow-hidden h-full" :style="{ width: leftPanelWidth + '%' }"> <SplitterPanel
<DiagramCanvas ref="diagramCanvas" :componentModules="componentModules" :showDocPanel="showDocPanel" id="splitter-group-panel-canvas"
@component-selected="handleComponentSelected" @component-moved="handleComponentMoved" :default-size="60"
@component-delete="handleComponentDelete" @wire-created="handleWireCreated" @wire-deleted="handleWireDeleted" :min-size="30"
class="relative bg-base-200 overflow-hidden h-full"
>
<DiagramCanvas ref="diagramCanvas" :showDocPanel="showDocPanel"
@diagram-updated="handleDiagramUpdated" @open-components="openComponentsMenu" @diagram-updated="handleDiagramUpdated" @open-components="openComponentsMenu"
@load-component-module="handleLoadComponentModule" @toggle-doc-panel="toggleDocPanel" /> @toggle-doc-panel="toggleDocPanel" />
</div> </SplitterPanel>
<!-- 拖拽分割线 --> <!-- 拖拽分割线 -->
<div <SplitterResizeHandle id="splitter-group-resize-handle" class="w-2 bg-base-100 hover:bg-primary hover:opacity-70 transition-colors" />
class="resizer bg-base-100 hover:bg-primary hover:opacity-70 active:bg-primary active:opacity-90 transition-colors"
@mousedown="startResize"></div>
<!-- 右侧编辑区域 --> <!-- 右侧编辑区域 -->
<div class="bg-base-200 h-full overflow-hidden flex flex-col" :style="{ width: 100 - leftPanelWidth + '%' }"> <SplitterPanel
id="splitter-group-panel-properties"
:min-size="20"
class="bg-base-200 h-full overflow-hidden flex flex-col"
>
<div class="overflow-y-auto flex-1"> <div class="overflow-y-auto flex-1">
<!-- 使用条件渲染显示不同的面板 --> <!-- 使用条件渲染显示不同的面板 -->
<PropertyPanel v-show="!showDocPanel" :componentData="selectedComponentData" <PropertyPanel v-show="!showDocPanel" :componentData="componentManager.selectedComponentData.value"
:componentConfig="selectedComponentConfig" @updateProp="updateComponentProp" :componentConfig="componentManager.selectedComponentConfig.value" @updateProp="updateComponentProp"
@updateDirectProp="updateComponentDirectProp" /> @updateDirectProp="updateComponentDirectProp" />
<div v-show="showDocPanel" class="doc-panel overflow-y-auto h-full"> <div v-show="showDocPanel" class="doc-panel overflow-y-auto h-full">
<MarkdownRenderer :content="documentContent" /> <MarkdownRenderer :content="documentContent" />
</div> </div>
</div> </div>
</div> </SplitterPanel>
</SplitterGroup>
</div> </div>
<!-- 元器件选择组件 --> <!-- 元器件选择组件 -->
<ComponentSelector :open="showComponentsMenu" @update:open="showComponentsMenu = $event" <ComponentSelector :open="showComponentsMenu" @update:open="showComponentsMenu = $event"
@ -34,29 +40,26 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
// wokwi-elements import { ref, onMounted, watch } from "vue";
// import "@wokwi/elements"; // wokwi import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from "reka-ui";
import { ref, computed, onMounted, onUnmounted, shallowRef } from "vue"; // defineAsyncComponent shallowRef import DiagramCanvas from "@/components/LabCanvas/DiagramCanvas.vue";
import DiagramCanvas from "@/components/DiagramCanvas.vue"; import ComponentSelector from "@/components/LabCanvas/ComponentSelector.vue";
import ComponentSelector from "@/components/ComponentSelector.vue";
import PropertyPanel from "@/components/PropertyPanel.vue"; import PropertyPanel from "@/components/PropertyPanel.vue";
import MarkdownRenderer from "@/components/MarkdownRenderer.vue"; import MarkdownRenderer from "@/components/MarkdownRenderer.vue";
import type { DiagramData, DiagramPart } from "@/components/diagramManager"; import { useProvideComponentManager } from "@/components/LabCanvas";
import { import type { DiagramData, DiagramPart } from "@/components/LabCanvas";
type PropertyConfig,
generatePropertyConfigs,
generatePropsFromDefault,
generatePropsFromAttrs,
} from "@/components/equipments/componentConfig"; //
// --- ---
const showDocPanel = ref(false);
const documentContent = ref("");
// //
import { useRoute } from "vue-router"; import { useRoute } from "vue-router";
const route = useRoute(); const route = useRoute();
//
const componentManager = useProvideComponentManager();
// --- ---
const showDocPanel = ref(false);
const documentContent = ref("");
// //
async function toggleDocPanel() { async function toggleDocPanel() {
showDocPanel.value = !showDocPanel.value; showDocPanel.value = !showDocPanel.value;
@ -99,610 +102,11 @@ async function loadDocumentContent() {
} }
} }
// // --- UI ---
onMounted(async () => {
if (route.query.tutorial) {
showDocPanel.value = true;
await loadDocumentContent();
}
});
// --- ---
const showComponentsMenu = ref(false); 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); 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);
}
// --- ---
const leftPanelWidth = ref(60);
const isResizing = ref(false);
//
function startResize(e: MouseEvent) {
isResizing.value = true;
document.addEventListener("mousemove", onResize);
document.addEventListener("mouseup", stopResize);
e.preventDefault(); //
}
function onResize(e: MouseEvent) {
if (!isResizing.value) return;
//
const container = document.querySelector(
".flex-1.overflow-hidden",
) as HTMLElement;
if (!container) return;
const containerWidth = container.clientWidth;
const mouseX = e.clientX;
//
let newWidth = (mouseX / containerWidth) * 100;
//
newWidth = Math.max(20, Math.min(newWidth, 80));
//
leftPanelWidth.value = newWidth;
}
function stopResize() {
isResizing.value = false;
document.removeEventListener("mousemove", onResize);
document.removeEventListener("mouseup", stopResize);
}
// --- ---
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;
}
//
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,
);
}
}
// - 使updateComponentProp
// 线
function handleWireCreated(wireData: any) {
console.log("Wire created:", wireData);
}
// 线
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 showNotification = ref(false);
const notificationMessage = ref(""); const notificationMessage = ref("");
const notificationType = ref<"success" | "error" | "info">("info"); const notificationType = ref<"success" | "error" | "info">("info");
@ -727,41 +131,68 @@ function showToast(
}, duration); }, 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 () => { onMounted(async () => {
// //
console.log("ProjectView mounted, diagram canvas ref:", diagramCanvas.value); if (route.query.tutorial) {
showDocPanel.value = true;
// await loadDocumentContent();
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(() => { //
document.removeEventListener("mousemove", onResize); componentManager.setCanvasRef(diagramCanvas.value);
document.removeEventListener("mouseup", stopResize); await componentManager.initialize();
}); });
</script> </script>
@ -769,26 +200,6 @@ onUnmounted(() => {
/* 样式保持不变 */ /* 样式保持不变 */
@import "../assets/main.css"; @import "../assets/main.css";
/* 分割线样式 */
.resizer {
width: 6px;
height: 100%;
cursor: col-resize;
transition: background-color 0.3s;
z-index: 10;
}
.resizer:hover,
.resizer:active {
width: 6px;
}
/* 调整大小时应用全局样式 */
:global(body.resizing) {
cursor: col-resize;
user-select: none;
}
.animate-slideRight { .animate-slideRight {
animation: slideRight 0.3s ease-out forwards; animation: slideRight 0.3s ease-out forwards;
} }

View File

@ -1,99 +1,5 @@
<template> <template>
<div class="flex w-screen h-screen justify-center">
<div class="flex flex-col w-3/5 h-screen shadow-2xl p-10">
<div class="flex justify-center">
<h1 class="font-bold text-3xl">Jtag 下载</h1>
</div>
<div class="divider"></div>
<div class="w-full">
<div class="collapse bg-primary">
<input type="checkbox" />
<div class="collapse-title font-semibold text-lg text-white">
自定义开发板参数
</div>
<div class="collapse-content bg-primary-content text-sm">
<div class="form-control w-full my-3">
<label class="label">
<span class="label-text text-gray-700">开发板IP地址</span>
</label>
<label class="input w-full">
<img class="h-[1em] opacity-50" src="@/assets/pwd.svg" alt="User img" />
<input type="text" class="grow" placeholder="IP地址" v-model="boardAddress" />
</label>
</div>
<div class="form-control w-full my-3">
<label class="label">
<span class="label-text text-gray-700">开发板端口号</span>
</label>
<label class="input w-full">
<img class="h-[1em] opacity-50" src="@/assets/pwd.svg" alt="User img" />
<input type="text" class="grow" placeholder="端口号" v-model="boardPort" />
</label>
</div>
</div>
</div>
</div>
<div class="divider"></div>
<UploadCard :upload-event="uploadBitstream" :download-event="downloadBitstream">
</UploadCard>
</div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { JtagClient, type FileParameter } from "@/APIClient";
import UploadCard from "@/components/UploadCard.vue";
import { useDialogStore } from "@/stores/dialog";
import { Common } from "@/Common";
import { toNumber, isUndefined } from "lodash";
import { ref } from "vue";
const jtagController = new JtagClient();
const dialog = useDialogStore();
// Models with default values
const boardAddress = ref("127.0.0.1"); // IP
const boardPort = ref("1234"); //
async function uploadBitstream(bitstream: File): Promise<boolean> {
if (isUndefined(boardAddress.value) || isUndefined(boardPort.value)) {
dialog.error("开发板地址或端口空缺");
return false;
}
try {
const resp = await jtagController.uploadBitstream(
boardAddress.value,
Common.toFileParameterOrNull(bitstream),
);
return resp;
} catch (e) {
dialog.error("上传错误");
console.error(e);
return false;
}
}
async function downloadBitstream(): Promise<boolean> {
if (isUndefined(boardAddress.value) || isUndefined(boardPort.value)) {
dialog.error("开发板地址或端口空缺");
return false;
}
try {
const resp = await jtagController.downloadBitstream(
boardAddress.value,
toNumber(boardPort.value),
);
return resp;
} catch (e) {
dialog.error("上传错误");
console.error(e);
return false;
}
}
</script> </script>
<style scoped lang="postcss">
@import "../assets/main.css";
</style>

View File

@ -6,6 +6,8 @@ import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools' import vueDevTools from 'vite-plugin-vue-devtools'
import tailwindcss from '@tailwindcss/postcss' import tailwindcss from '@tailwindcss/postcss'
import autoprefixer from 'autoprefixer' import autoprefixer from 'autoprefixer'
import Components from 'unplugin-vue-components/vite'
import RekaResolver from 'reka-ui/resolver'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
@ -20,6 +22,18 @@ export default defineConfig({
}), }),
vueJsx(), vueJsx(),
vueDevTools(), vueDevTools(),
Components(
{
dts: true,
resolvers: [
RekaResolver()
// RekaResolver({
// prefix: '' // use the prefix option to add Prefix to the imported components
// })
],
}
)
], ],
resolve: { resolve: {
alias: { alias: {