refactor: 重构projectview页面结构

This commit is contained in:
2025-07-09 14:42:29 +08:00
parent c3bd61ed51
commit c5ce246caf
16 changed files with 822 additions and 882 deletions

View File

@@ -2,53 +2,25 @@
<div>
<!-- 元器件选择菜单 (Drawer) -->
<div class="drawer drawer-end z-50">
<input
id="Lab-drawer"
type="checkbox"
class="drawer-toggle"
v-model="showComponentsMenu"
/>
<div class="drawer-content">
<!-- Page content here -->
<label
for="Lab-drawer"
class="drawer-button btn btn-primary rounded-2xl"
><Plus></Plus
></label>
</div>
<input id="component-drawer" type="checkbox" class="drawer-toggle" v-model="showComponentsMenu" />
<div class="drawer-side">
<label
for="Lab-drawer"
aria-label="close sidebar"
class="drawer-overlay !bg-opacity-50"
></label>
<div
class="menu p-0 w-[460px] min-h-full bg-base-100 shadow-xl flex flex-col"
>
<label for="component-drawer" aria-label="close sidebar" class="drawer-overlay !bg-opacity-50"></label>
<div class="menu p-0 w-[460px] min-h-full bg-base-100 shadow-xl flex flex-col">
<!-- 菜单头部 -->
<div
class="p-6 border-b border-base-300 flex justify-between items-center"
>
<div class="p-6 border-b border-base-300 flex justify-between items-center">
<h3 class="text-xl font-bold text-primary flex items-center gap-2">
<Plus class="text-primary w-5 h-5"></Plus>
添加实验元器件
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="text-primary">
<circle cx="12" cy="12" r="10"></circle>
<path d="M12 8v8"></path>
<path d="M8 12h8"></path>
</svg>
添加元器件
</h3>
<label
for="Lab-drawer"
class="btn btn-ghost btn-sm btn-circle"
@click="closeMenu"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<label for="component-drawer" class="btn btn-ghost btn-sm btn-circle" @click="closeMenu">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18"></line>
<line x1="6" y1="6" x2="18" y2="18"></line>
</svg>
@@ -57,49 +29,21 @@
<!-- 导航栏 -->
<div class="tabs tabs-boxed bg-base-200 mx-6 mt-4 rounded-box">
<a
class="tab"
:class="{ 'tab-active': activeTab === 'components' }"
@click="activeTab = 'components'"
>元器件</a
>
<a
class="tab"
:class="{ 'tab-active': activeTab === 'templates' }"
@click="activeTab = 'templates'"
>模板</a
>
<a
class="tab"
:class="{ 'tab-active': activeTab === 'virtual' }"
@click="activeTab = 'virtual'"
>虚拟外设</a
>
<a class="tab" :class="{ 'tab-active': activeTab === 'components' }"
@click="activeTab = 'components'">元器件</a>
<a class="tab" :class="{ 'tab-active': activeTab === 'templates' }" @click="activeTab = 'templates'">模板</a>
<a class="tab" :class="{ 'tab-active': activeTab === 'virtual' }" @click="activeTab = 'virtual'">虚拟外设</a>
</div>
<!-- 搜索框 -->
<div class="px-6 py-4 border-b border-base-300">
<div class="join w-full">
<div class="join-item flex-1 relative">
<input
type="text"
placeholder="搜索..."
class="input input-bordered input-sm w-full pl-10"
v-model="searchQuery"
@keyup.enter="searchComponents"
/>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="absolute left-3 top-1/2 -translate-y-1/2 text-base-content opacity-60"
>
<input type="text" placeholder="搜索..." class="input input-bordered input-sm w-full pl-10"
v-model="searchQuery" @keyup.enter="searchComponents" />
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
class="absolute left-3 top-1/2 -translate-y-1/2 text-base-content opacity-60">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
</svg>
@@ -111,31 +55,17 @@
</div>
<!-- 元器件列表 (组件选项卡) -->
<div
v-if="activeTab === 'components'"
class="px-6 py-4 overflow-auto flex-1"
>
<div
v-if="filteredComponents.length > 0"
class="grid grid-cols-2 gap-4"
>
<div
v-for="(component, index) in filteredComponents"
:key="index"
<div v-if="activeTab === 'components'" class="px-6 py-4 overflow-auto flex-1">
<div v-if="filteredComponents.length > 0" class="grid grid-cols-2 gap-4">
<div v-for="(component, index) in filteredComponents" :key="index"
class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer"
@click="addComponent(component)"
>
@click="addComponent(component)">
<div class="card-body p-3 items-center text-center">
<div
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2"
>
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2">
<!-- 直接使用组件作为预览 -->
<component
v-if="componentModules[component.type]"
:is="componentModules[component.type].default"
class="component-preview"
:size="getPreviewSize(component.type)"
/>
<component v-if="componentModules[component.type]" :is="componentModules[component.type].default"
class="component-preview" :size="getPreviewSize(component.type)" />
<!-- 加载中状态 -->
<span v-else class="text-xs text-gray-400">加载中...</span>
</div>
@@ -146,58 +76,31 @@
</div>
<!-- 无搜索结果 -->
<div v-else class="py-16 text-center">
<svg
xmlns="http://www.w3.org/2000/svg"
width="48"
height="48"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class="mx-auto text-base-300 mb-3"
>
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
class="mx-auto text-base-300 mb-3">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
<p class="text-base-content opacity-70">没有找到匹配的元器件</p>
<button
class="btn btn-sm btn-ghost mt-3"
@click="searchQuery = ''"
>
<button class="btn btn-sm btn-ghost mt-3" @click="searchQuery = ''">
清除搜索
</button>
</div>
</div>
<!-- 模板列表 (模板选项卡) -->
<div
v-if="activeTab === 'templates'"
class="px-6 py-4 overflow-auto flex-1"
>
<div
v-if="filteredTemplates.length > 0"
class="grid grid-cols-2 gap-4"
>
<div
v-for="(template, index) in filteredTemplates"
:key="index"
<div v-if="activeTab === 'templates'" class="px-6 py-4 overflow-auto flex-1">
<div v-if="filteredTemplates.length > 0" class="grid grid-cols-2 gap-4">
<div v-for="(template, index) in filteredTemplates" :key="index"
class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer"
@click="addTemplate(template)"
>
@click="addTemplate(template)">
<div class="card-body p-3 items-center text-center">
<div
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2"
>
<img
:src="
template.thumbnailUrl || '/placeholder-template.png'
"
alt="Template thumbnail"
class="max-h-full max-w-full object-contain"
/>
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2">
<img :src="template.thumbnailUrl || '/placeholder-template.png'
" alt="Template thumbnail" class="max-h-full max-w-full object-contain" />
</div>
<h3 class="card-title text-sm mt-2">{{ template.name }}</h3>
<p class="text-xs opacity-70">
@@ -208,58 +111,31 @@
</div>
<!-- 无搜索结果 -->
<div v-else class="py-16 text-center">
<svg
xmlns="http://www.w3.org/2000/svg"
width="48"
height="48"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class="mx-auto text-base-300 mb-3"
>
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
class="mx-auto text-base-300 mb-3">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
<p class="text-base-content opacity-70">没有找到匹配的模板</p>
<button
class="btn btn-sm btn-ghost mt-3"
@click="searchQuery = ''"
>
<button class="btn btn-sm btn-ghost mt-3" @click="searchQuery = ''">
清除搜索
</button>
</div>
</div>
<!-- 虚拟外设列表 (虚拟外设选项卡) -->
<div
v-if="activeTab === 'virtual'"
class="px-6 py-4 overflow-auto flex-1"
>
<div
v-if="filteredVirtualDevices.length > 0"
class="grid grid-cols-2 gap-4"
>
<div
v-for="(device, index) in filteredVirtualDevices"
:key="index"
<div v-if="activeTab === 'virtual'" class="px-6 py-4 overflow-auto flex-1">
<div v-if="filteredVirtualDevices.length > 0" class="grid grid-cols-2 gap-4">
<div v-for="(device, index) in filteredVirtualDevices" :key="index"
class="card bg-base-200 hover:bg-base-300 transition-all duration-300 hover:shadow-md cursor-pointer"
@click="addComponent(device)"
>
@click="addComponent(device)">
<div class="card-body p-3 items-center text-center">
<div
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2"
>
class="bg-base-100 rounded-lg w-full h-[90px] flex items-center justify-center overflow-hidden p-2">
<!-- 直接使用组件作为预览 -->
<component
v-if="componentModules[device.type]"
:is="componentModules[device.type].default"
class="component-preview"
:size="getPreviewSize(device.type)"
/>
<component v-if="componentModules[device.type]" :is="componentModules[device.type].default"
class="component-preview" :size="getPreviewSize(device.type)" />
<!-- 加载中状态 -->
<span v-else class="text-xs text-gray-400">加载中...</span>
</div>
@@ -270,62 +146,30 @@
</div>
<!-- 无搜索结果 -->
<div v-else class="py-16 text-center">
<svg
xmlns="http://www.w3.org/2000/svg"
width="48"
height="48"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
class="mx-auto text-base-300 mb-3"
>
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"
class="mx-auto text-base-300 mb-3">
<circle cx="11" cy="11" r="8"></circle>
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
<line x1="8" y1="11" x2="14" y2="11"></line>
</svg>
<p class="text-base-content opacity-70">没有找到匹配的虚拟外设</p>
<button
class="btn btn-sm btn-ghost mt-3"
@click="searchQuery = ''"
>
<button class="btn btn-sm btn-ghost mt-3" @click="searchQuery = ''">
清除搜索
</button>
</div>
</div>
<!-- 底部操作区 -->
<div
class="p-4 border-t border-base-300 bg-base-200 flex justify-between"
>
<label
for="Lab-drawer"
class="btn btn-sm btn-ghost"
@click="closeMenu"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="mr-1"
>
<div class="p-4 border-t border-base-300 bg-base-200 flex justify-between">
<label for="component-drawer" class="btn btn-sm btn-ghost" @click="closeMenu">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1">
<path d="M19 12H5M12 19l-7-7 7-7"></path>
</svg>
返回
</label>
<label
for="Lab-drawer"
class="btn btn-sm btn-primary"
@click="closeMenu"
>
<label for="component-drawer" class="btn btn-sm btn-primary" @click="closeMenu">
完成
</label>
</div>
@@ -336,25 +180,23 @@
</template>
<script setup lang="ts">
import { Plus } from "lucide-vue-next";
import { ref, computed, shallowRef, onMounted } from "vue";
import motherboardSvg from "../../components/equipments/svg/motherboard.svg";
import buttonSvg from "../../components/equipments/svg/button.svg";
import motherboardSvg from "@/components/equipments/svg/motherboard.svg";
import buttonSvg from "@/components//equipments/svg/button.svg";
// /
const isOpen = defineModel<boolean>("open", {
default: false,
});
const showComponentsMenu = computed({
get: () => isOpen.value,
set: (value) => (isOpen.value = value),
});
// Props
interface Props {
open: boolean;
}
const props = defineProps<Props>();
//
const emit = defineEmits([
"close",
"add-component",
"add-template",
"update:open",
]);
//
@@ -402,6 +244,12 @@ const availableTemplates = ref([
},
]);
// /
const showComponentsMenu = computed({
get: () => props.open,
set: (value) => emit("update:open", value),
});
//
const componentModules = shallowRef<Record<string, any>>({});
@@ -410,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 = {
@@ -533,7 +381,7 @@ async function addTemplate(template: any) {
id: template.id,
name: template.name,
template: templateData,
capsPage: template.capsPage,
capsPage: template.capsPage
});
//

File diff suppressed because it is too large Load Diff

View File

@@ -1,536 +0,0 @@
<template>
<div class="w-full h-full relative" @contextmenu.prevent>
<v-stage
class="h-full w-full"
ref="stageRef"
:config="labCanvasStore?.stageConfig"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp"
@wheel="handleWheel"
@click="handleStageClick"
@contextmenu="handleContextMenu"
>
<v-layer ref="layerRef">
<template
ref="canvasObjectsRef"
v-for="item in objMap.values()"
:key="item.id"
>
<v-group
:config="{
x: item.x,
y: item.y,
draggable: true,
id: `group-${item.id}`,
}"
@dragstart="handleDragStart"
@dragend="handleDragEnd"
@mouseover="handleCanvasObjectMouseOver"
@mouseout="handleCanvasObjectMouseOut"
>
<!-- Hover Box -->
<v-rect
v-show="!isUndefined(item.hoverBox)"
:config="{
...item.hoverBox,
visible:
!isUndefined(item.hoverBox) &&
item.isHoverring &&
!isDragging &&
selectedIds.length == 0,
stroke: 'rgb(125,193,239)',
strokeWidth: 2.5,
dash: [10, 5],
cornerRadius: 10,
}"
>
</v-rect>
<v-shape :config="item.config">
<component
:is="item.component"
@mouseover="handleCanvasObjectMouseOver"
@mouseout="handleCanvasObjectMouseOut"
></component>
</v-shape>
</v-group>
</template>
<v-transformer
ref="transformerRef"
:config="{
borderStroke: 'rgb(125,193,239)',
borderStrokeWidth: 3,
}"
/>
<v-rect
ref="selectRectRef"
v-if="selectionRectangle.visible"
:config="{
x: Math.min(selectionRectangle.x1, selectionRectangle.x2),
y: Math.min(selectionRectangle.y1, selectionRectangle.y2),
width: Math.abs(selectionRectangle.x2 - selectionRectangle.x1),
height: Math.abs(selectionRectangle.y2 - selectionRectangle.y1),
fill: '#0069FF88',
}"
/>
</v-layer>
</v-stage>
<LabComponentsDrawer
class="absolute top-10 right-20"
v-model:open="isDrawerOpen"
:add-component="labCanvasStore.addComponent"
></LabComponentsDrawer>
</div>
</template>
<script setup lang="ts">
import LabComponentsDrawer from "./LabComponentsDrawer.vue";
import Konva from "konva";
import { isNull, isUndefined } from "lodash";
import type { VLayer, VNode, VStage, VTransformer } from "@/utils/VueKonvaType";
import { ref, reactive, watch, onMounted, useTemplateRef, computed } from "vue";
import type { Stage } from "konva/lib/Stage";
import type { LabCanvasComponentConfig } from "./LabCanvasType";
import { useLabCanvasStore } from "./composable/LabCanvasManager";
const labCanvasStore = useLabCanvasStore();
function calculateRectBounding(
width: number,
height: number,
rotation: number,
scale: number = 1,
padding?: number,
) {
// Apply scale to dimensions first
const scaledWidth = width * scale;
const scaledHeight = height * scale;
// calculate bounding box for rotated rectangle
const radians = (rotation * Math.PI) / 180;
const cos = Math.cos(radians);
const sin = Math.sin(radians);
// calculate corners of the scaled rectangle
const corners = [
{ x: 0, y: 0 },
{ x: scaledWidth, y: 0 },
{ x: scaledWidth, y: scaledHeight },
{ x: 0, y: scaledHeight },
].map((point) => ({
x: point.x * cos - point.y * sin,
y: point.x * sin + point.y * cos,
}));
// find bounding box dimensions
const minX = Math.min(...corners.map((p) => p.x));
const maxX = Math.max(...corners.map((p) => p.x));
const minY = Math.min(...corners.map((p) => p.y));
const maxY = Math.max(...corners.map((p) => p.y));
if (padding) {
const scaledPadding = padding * scale;
return {
x: minX - scaledPadding,
y: minY - scaledPadding,
width: maxX - minX + scaledPadding * 2,
height: maxY - minY + scaledPadding * 2,
};
} else {
return {
x: minX,
y: minY,
width: maxX - minX,
height: maxY - minY,
};
}
}
const objMap = computed(() => {
return new Map(labCanvasStore?.components.value.map((item) => [item.id, item]));
});
const layerRef = useTemplateRef<VLayer>("layerRef");
const canvasObjectsRef =
useTemplateRef<HTMLTemplateElement[]>("canvasObjectsRef");
const transformerRef = useTemplateRef<VTransformer>("transformerRef");
const selectRectRef = useTemplateRef<VNode>("selectRectRef");
const stageRef = useTemplateRef<VStage>("StageRef");
const isDragging = ref(false);
const dragItemId = ref<string | null>(null);
const isRightDragging = ref(false);
const lastPointerPosition = ref<{ x: number; y: number } | null>(null);
const isSelecting = ref(false);
const selectedIds = ref<string[]>([]);
const selectionRectangle = reactive({
visible: false,
x1: 0,
y1: 0,
x2: 0,
y2: 0,
});
const stageScale = ref(1);
const isDrawerOpen = ref(false);
onMounted(() => {
if (isNull(transformerRef.value)) return;
const selectedBox = transformerRef.value.getNode();
selectedBox.resizeEnabled(false);
selectedBox.rotateEnabled(false);
});
// Update transformer nodes when selection changes
watch(selectedIds, () => {
if (isNull(transformerRef.value)) return;
const nodes = selectedIds.value.map((id) => {
if (isNull(layerRef.value)) {
console.error("layer is null");
return null;
}
for (let node of layerRef.value.getNode().children) {
if (node instanceof Konva.Group && node.id() === `group-${id}`)
return node;
}
}) as Konva.Node[];
// console.log(nodes);
if (!isUndefined(nodes)) transformerRef.value.getNode().nodes(nodes);
});
function handleCacheChange(e: Event) {
const target = e.target as HTMLInputElement;
const shouldCache = isNull(target) ? false : target.checked;
if (isNull(layerRef.value)) return;
if (shouldCache) {
layerRef.value.getNode().cache();
} else {
layerRef.value.getNode().clearCache();
}
}
// Drag event handlers
function handleDragStart(e: Event) {
isDragging.value = true;
// save drag element:
const target = e.target as unknown as Konva.Node;
dragItemId.value = target.id();
}
function handleDragEnd() {
isDragging.value = false;
dragItemId.value = null;
}
// Mouse event handlers
function handleStageClick(e: { target: any; evt: MouseEvent }) {
if (isNull(e.target)) return;
const target = e.target as unknown as Konva.Shape | Konva.Group;
// if we are selecting with rect, do nothing
if (selectionRectangle.visible) {
return;
}
// if click on empty area - remove all selections
if (target === target.getStage()) {
selectedIds.value = [];
return;
}
const clickedId = target.attrs.id;
// do we pressed shift or ctrl?
const metaPressed = e.evt.shiftKey || e.evt.ctrlKey || e.evt.metaKey;
const isSelected = selectedIds.value.includes(clickedId);
if (!metaPressed && !isSelected) {
// if no key pressed and the node is not selected
// select just one
selectedIds.value = [clickedId];
} else if (metaPressed && isSelected) {
// if we pressed keys and node was selected
// we need to remove it from selection:
selectedIds.value = selectedIds.value.filter((id) => id !== clickedId);
} else if (metaPressed && !isSelected) {
// add the node into selection
selectedIds.value = [...selectedIds.value, clickedId];
}
}
function handleContextMenu(e: Event) {
// 防止默认右键菜单弹出
e.preventDefault();
}
function handleMouseDown(e: Event) {
if (isNull(e.target)) return;
const target = e.target as unknown as Konva.Container;
const stage = target.getStage();
// 获取鼠标事件信息
const mouseEvent = (e as any).evt as MouseEvent;
// 如果是右键按下,开始右键拖拽
if (mouseEvent.button === 2) {
isRightDragging.value = true;
const pos = stage?.getPointerPosition();
if (pos) {
lastPointerPosition.value = { x: pos.x, y: pos.y };
}
return;
}
// do nothing if we mousedown on any shape
if ((e.target as unknown) !== target.getStage()) {
return;
}
// start selection rectangle
isSelecting.value = true;
const pos = stage?.getPointerPosition();
if (!isNull(pos) && !isUndefined(pos) && !isNull(stage)) {
// Convert pointer position to relative coordinates considering scale and position
const relativePos = {
x: (pos.x - stage.x()) / stage.scaleX(),
y: (pos.y - stage.y()) / stage.scaleY(),
};
selectionRectangle.visible = true;
selectionRectangle.x1 = relativePos.x;
selectionRectangle.y1 = relativePos.y;
selectionRectangle.x2 = relativePos.x;
selectionRectangle.y2 = relativePos.y;
}
}
function handleMouseMove(e: Event) {
if (isNull(e.target)) return;
const target = e.target as unknown as Konva.Container;
const stage = target.getStage();
// 如果正在右键拖拽,移动画布
if (isRightDragging.value && lastPointerPosition.value && stage) {
const pos = stage.getPointerPosition();
if (pos) {
const dx = pos.x - lastPointerPosition.value.x;
const dy = pos.y - lastPointerPosition.value.y;
const currentPos = stage.position();
stage.position({
x: currentPos.x + dx,
y: currentPos.y + dy,
});
lastPointerPosition.value = { x: pos.x, y: pos.y };
}
return;
}
// do nothing if we didn't start selection
if (!isSelecting.value) {
return;
}
const pos = stage?.getPointerPosition();
if (!isNull(pos) && !isUndefined(pos) && !isNull(stage)) {
// Convert pointer position to relative coordinates considering scale and position
const relativePos = {
x: (pos.x - stage.x()) / stage.scaleX(),
y: (pos.y - stage.y()) / stage.scaleY(),
};
selectionRectangle.x2 = relativePos.x;
selectionRectangle.y2 = relativePos.y;
}
}
function handleMouseUp(e: Event) {
// 如果是右键释放,结束右键拖拽
const mouseEvent = (e as any).evt as MouseEvent;
if (mouseEvent.button === 2 && isRightDragging.value) {
isRightDragging.value = false;
lastPointerPosition.value = null;
return;
}
// do nothing if we didn't start selection
if (!isSelecting.value) {
return;
}
isSelecting.value = false;
// update visibility in timeout, so we can check it in click event
setTimeout(() => {
selectionRectangle.visible = false;
});
const selBox = {
x: Math.min(selectionRectangle.x1, selectionRectangle.x2),
y: Math.min(selectionRectangle.y1, selectionRectangle.y2),
width: Math.abs(selectionRectangle.x2 - selectionRectangle.x1),
height: Math.abs(selectionRectangle.y2 - selectionRectangle.y1),
};
// console.log(`Stage Scale: ${stageScale.value}`);
let currentSelectedIds = [];
for (let [key, shape] of objMap.value) {
const shapeConfig = objMap.value.get(shape.id);
if (isUndefined(shapeConfig)) {
return;
}
if (isUndefined(shapeConfig.hoverBox)) {
if (
shapeConfig.config.width &&
shapeConfig.config.height &&
shapeConfig.config.rotation
) {
shapeConfig.hoverBox = calculateRectBounding(
shapeConfig.config.width,
shapeConfig.config.height,
shapeConfig.config.rotation,
stageScale.value,
5,
);
} else {
console.error("Could not calculate rect bounding");
return;
}
}
if (
Konva.Util.haveIntersection(selBox, {
x: shapeConfig.hoverBox.x + shapeConfig.x,
y: shapeConfig.hoverBox.y + shapeConfig.y,
width: shapeConfig.hoverBox.width,
height: shapeConfig.hoverBox.height,
})
)
currentSelectedIds.push(shapeConfig.id);
}
selectedIds.value = currentSelectedIds;
}
function handleWheel(e: { target: any; evt: MouseEvent & { deltaY: number } }) {
e.evt.preventDefault();
const stage = e.target as Stage;
if (stage === null || stage === undefined) {
console.error("Stage is not defined");
return;
}
const oldScale = stage.scaleX();
const pointer = stage.getPointerPosition();
if (pointer === null || pointer === undefined) {
console.error("Pointer position is not defined");
return;
}
const mousePointTo = {
x: (pointer.x - stage.x()) / oldScale,
y: (pointer.y - stage.y()) / oldScale,
};
// how to scale? Zoom in? Or zoom out?
let direction = e.evt.deltaY < 0 ? 1 : -1;
// when we zoom on trackpad, e.evt.ctrlKey is true
// in that case lets revert direction
if (e.evt.ctrlKey) {
direction = -direction;
}
const scaleBy = 1.05;
const newScale = direction > 0 ? oldScale * scaleBy : oldScale / scaleBy;
stage.scale({ x: newScale, y: newScale });
stageScale.value = newScale;
const newPos = {
x: pointer.x - mousePointTo.x * newScale,
y: pointer.y - mousePointTo.y * newScale,
};
stage.position(newPos);
}
function handleCanvasObjectMouseOver(evt: Event) {
if (isNull(evt.target)) return;
const target = evt.target;
let object = null;
if (target instanceof Konva.Group) {
if (!target.hasChildren()) return;
object = target.children[0];
} else if (target instanceof Konva.Rect) {
object = target;
} else {
console.trace(`Not Konva class: ${target}`);
return;
}
// Get client rect
const objectConfig = objMap.value.get(object.id());
if (isUndefined(objectConfig)) {
return;
}
// Get clientBox for first time
if (isUndefined(objectConfig.hoverBox)) {
if (
objectConfig.config.width &&
objectConfig.config.height &&
objectConfig.config.rotation
) {
objectConfig.hoverBox = calculateRectBounding(
objectConfig.config.width,
objectConfig.config.height,
objectConfig.config.rotation,
stageScale.value, // 传入当前缩放比例
5,
);
} else console.error("Could not calculate rect bounding");
}
objectConfig.isHoverring = true;
}
function handleCanvasObjectMouseOut(evt: Event) {
if (isNull(evt.target)) return;
const target = evt.target;
let object = null;
if (target instanceof Konva.Group) {
if (!target.hasChildren()) return;
object = target.children[0];
} else if (target instanceof Konva.Rect) {
object = target;
} else {
console.trace(`Not Konva class: ${target}`);
return;
}
// Get client rect
const objectConfig = objMap.value.get(object.id());
if (isUndefined(objectConfig)) {
return;
}
objectConfig.isHoverring = false;
}
</script>
<style>
@import "../../assets/main.css";
</style>

View File

@@ -1,20 +0,0 @@
import type { VNode } from "@/utils/VueKonvaType";
import Konva from "konva";
import BaseBoard from "../equipments/BaseBoard.vue";
export type LabCanvasComponentConfig = {
id: string;
component: VNode;
x: number;
y: number;
config: Konva.ShapeConfig;
isHoverring: boolean;
hoverBox: {
x: number;
y: number;
width: number;
height: number;
};
};
export type LabCanvasComponent = typeof BaseBoard;

View File

@@ -1,123 +0,0 @@
import { computed, shallowRef } from "vue";
import { createInjectionState, useStorage } from "@vueuse/core";
import { type LabCanvasComponentConfig } from "../LabCanvasType";
import type Konva from "konva";
const [useProvideLabCanvasStore, useLabCanvasStore] = createInjectionState(
(initialStageConfig: Konva.StageConfig) => {
const components = useStorage(
"LabCanvasComponents",
[] as LabCanvasComponentConfig[],
);
// state
const stageConfig = shallowRef<Konva.StageConfig>(initialStageConfig);
// getters
const getComponentById = computed(() => (id: string) => {
return components.value.find(component => component.id === id);
});
const componentCount = computed(() => components.value.length);
// actions
function addComponent(componentData: {
id: string;
component: any;
x?: number;
y?: number;
config: Konva.ShapeConfig;
}) {
const newComponent: LabCanvasComponentConfig = {
id: componentData.id,
component: componentData.component,
x: componentData.x ?? 100,
y: componentData.y ?? 100,
config: componentData.config,
isHoverring: false,
hoverBox: {
x: 0,
y: 0,
width: componentData.config.width || 100,
height: componentData.config.height || 100,
},
};
components.value.push(newComponent);
return newComponent;
}
function removeComponent(id: string) {
const index = components.value.findIndex(component => component.id === id);
if (index !== -1) {
const removedComponent = components.value[index];
components.value.splice(index, 1);
return removedComponent;
}
return null;
}
function removeComponents(ids: string[]) {
const removedComponents: LabCanvasComponentConfig[] = [];
ids.forEach(id => {
const removed = removeComponent(id);
if (removed) {
removedComponents.push(removed);
}
});
return removedComponents;
}
function updateComponent(id: string, updates: Partial<LabCanvasComponentConfig>) {
const component = components.value.find(comp => comp.id === id);
if (component) {
Object.assign(component, updates);
return component;
}
return null;
}
function updateComponentPosition(id: string, x: number, y: number) {
return updateComponent(id, { x, y });
}
function updateComponentConfig(id: string, config: Partial<Konva.ShapeConfig>) {
const component = components.value.find(comp => comp.id === id);
if (component) {
component.config = { ...component.config, ...config };
return component;
}
return null;
}
function clearComponents() {
const clearedComponents = [...components.value];
components.value.splice(0);
return clearedComponents;
}
function setComponents(newComponents: LabCanvasComponentConfig[]) {
components.value.splice(0, components.value.length, ...newComponents);
}
return {
stageConfig,
components,
// getters
getComponentById,
componentCount,
// actions
addComponent,
removeComponent,
removeComponents,
updateComponent,
updateComponentPosition,
updateComponentConfig,
clearComponents,
setComponents,
};
});
export { useProvideLabCanvasStore, useLabCanvasStore };

View File

@@ -0,0 +1,331 @@
// 定义 diagram.json 的类型结构
export interface DiagramData {
version: number;
author: string;
editor: string;
parts: DiagramPart[];
connections: ConnectionArray[];
exportTime?: string; // 导出时的时间戳
}
// 组件部分的类型定义
export interface DiagramPart {
id: string;
type: string;
x: number;
y: number;
attrs: Record<string, any>;
rotate: number;
group: string;
positionlock: boolean;
hidepins: boolean;
isOn: boolean;
index?: number; // 显示层级,数值越大显示越靠前
}
// 连接类型定义 - 使用元组类型表示四元素数组
export type ConnectionArray = [string, string, number, string[]];
// 解析连接字符串为组件ID和引脚ID
export function parseConnectionPin(connectionPin: string): { componentId: string; pinId: string } {
const [componentId, pinId] = connectionPin.split(':');
return { componentId, pinId };
}
// 将连接数组转换为适用于渲染的格式
export function connectionArrayToWireItem(
connection: ConnectionArray,
index: number,
startPos = { x: 0, y: 0 },
endPos = { x: 0, y: 0 }
): WireItem {
const [startPinStr, endPinStr, width, path] = connection;
const { componentId: startComponentId, pinId: startPinId } = parseConnectionPin(startPinStr);
const { componentId: endComponentId, pinId: endPinId } = parseConnectionPin(endPinStr);
return {
id: `wire-${index}`,
startX: startPos.x,
startY: startPos.y,
endX: endPos.x,
endY: endPos.y,
startComponentId,
startPinId,
endComponentId,
endPinId,
strokeWidth: width,
color: '#4a5568', // 默认颜色
routingMode: 'path',
pathCommands: path,
showLabel: false
};
}
// WireItem 接口定义
export interface WireItem {
id: string;
startX: number;
startY: number;
endX: number;
endY: number;
startComponentId: string;
startPinId?: string;
endComponentId: string;
endPinId?: string;
strokeWidth: number;
color: string;
routingMode: 'orthogonal' | 'path';
constraint?: string;
pathCommands?: string[];
showLabel: boolean;
}
// 从本地存储加载图表数据
export async function loadDiagramData(): Promise<DiagramData> {
try {
// 先尝试从本地存储加载
const savedData = localStorage.getItem('diagramData');
if (savedData) {
return JSON.parse(savedData);
}
// 如果本地存储没有,从文件加载
const response = await fetch('/src/components/diagram.json');
if (!response.ok) {
throw new Error(`Failed to load diagram.json: ${response.statusText}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error loading diagram data:', error);
// 返回空的默认数据结构
return createEmptyDiagram();
}
}
// 创建空的图表数据
export function createEmptyDiagram(): DiagramData {
return {
version: 1,
author: 'user',
editor: 'user',
parts: [],
connections: []
};
}
// 保存图表数据到本地存储
export function saveDiagramData(data: DiagramData): void {
try {
localStorage.setItem('diagramData', JSON.stringify(data));
} catch (error) {
console.error('Error saving diagram data:', error);
}
}
// 添加新组件到图表数据
export function addPart(data: DiagramData, part: DiagramPart): DiagramData {
return {
...data,
parts: [...data.parts, part]
};
}
// 更新组件位置
export function updatePartPosition(
data: DiagramData,
partId: string,
x: number,
y: number
): DiagramData {
return {
...data,
parts: data.parts.map(part =>
part.id === partId
? { ...part, x, y }
: part
)
};
}
// 更新组件属性
export function updatePartAttribute(
data: DiagramData,
partId: string,
attrName: string,
value: any
): DiagramData {
return {
...data,
parts: data.parts.map(part =>
part.id === partId
? {
...part,
attrs: {
...part.attrs,
[attrName]: value
}
}
: part
)
};
}
// 删除组件及同组组件
export function deletePart(data: DiagramData, partId: string): DiagramData {
// 首先找到要删除的组件
const component = data.parts.find(part => part.id === partId);
if (!component) return data;
// 收集需要删除的组件ID列表
const componentsToDelete: string[] = [partId];
// 如果组件属于一个组,则找出所有同组的组件
if (component.group && component.group !== '') {
const groupMembers = data.parts.filter(
p => p.group === component.group && p.id !== partId
);
// 将同组组件ID添加到删除列表
componentsToDelete.push(...groupMembers.map(p => p.id));
console.log(`删除组件 ${partId} 及其组 ${component.group} 中的 ${groupMembers.length} 个组件`);
}
return {
...data,
// 删除所有标记的组件
parts: data.parts.filter(part => !componentsToDelete.includes(part.id)),
// 删除与这些组件相关的所有连接
connections: data.connections.filter(conn => {
const [startPin, endPin] = conn;
const startCompId = startPin.split(':')[0];
const endCompId = endPin.split(':')[0];
// 检查连接两端的组件是否在删除列表中
return !componentsToDelete.includes(startCompId) && !componentsToDelete.includes(endCompId);
})
};
}
// 添加连接
export function addConnection(
data: DiagramData,
startComponentId: string,
startPinId: string,
endComponentId: string,
endPinId: string,
width: number = 2,
path: string[] = []
): DiagramData {
const newConnection: ConnectionArray = [
`${startComponentId}:${startPinId}`,
`${endComponentId}:${endPinId}`,
width,
path
];
return {
...data,
connections: [...data.connections, newConnection]
};
}
// 删除连接
export function deleteConnection(
data: DiagramData,
connectionIndex: number
): DiagramData {
return {
...data,
connections: data.connections.filter((_, index) => index !== connectionIndex)
};
}
// 查找与组件关联的所有连接
export function findConnectionsByPart(
data: DiagramData,
partId: string
): { connection: ConnectionArray; index: number }[] {
return data.connections
.map((connection, index) => ({ connection, index }))
.filter(({ connection }) => {
const [startPin, endPin] = connection;
const startCompId = startPin.split(':')[0];
const endCompId = endPin.split(':')[0];
return startCompId === partId || endCompId === partId;
});
}
// 基于组的移动相关组件
export function moveGroupComponents(
data: DiagramData,
groupId: string,
deltaX: number,
deltaY: number
): DiagramData {
if (!groupId) return data;
return {
...data,
parts: data.parts.map(part =>
part.group === groupId
? { ...part, x: part.x + deltaX, y: part.y + deltaY }
: part
)
};
}
// 添加验证diagram.json文件的函数
export function validateDiagramData(data: any): { isValid: boolean; errors: string[] } {
const errors: string[] = [];
// 检查版本号
if (!data.version) {
errors.push('缺少version字段');
}
// 检查parts数组
if (!Array.isArray(data.parts)) {
errors.push('parts字段不是数组');
} else {
// 验证parts中的每个对象
data.parts.forEach((part: any, index: number) => {
if (!part.id) errors.push(`parts[${index}]缺少id`);
if (!part.type) errors.push(`parts[${index}]缺少type`);
if (typeof part.x !== 'number') errors.push(`parts[${index}]缺少有效的x坐标`);
if (typeof part.y !== 'number') errors.push(`parts[${index}]缺少有效的y坐标`);
});
}
// 检查connections数组
if (!Array.isArray(data.connections)) {
errors.push('connections字段不是数组');
} else {
// 验证connections中的每个数组
data.connections.forEach((conn: any, index: number) => {
if (!Array.isArray(conn) || conn.length < 3) {
errors.push(`connections[${index}]不是有效的连接数组`);
return;
}
const [startPin, endPin, width] = conn;
if (typeof startPin !== 'string' || !startPin.includes(':')) {
errors.push(`connections[${index}]的起始针脚格式无效`);
}
if (typeof endPin !== 'string' || !endPin.includes(':')) {
errors.push(`connections[${index}]的结束针脚格式无效`);
}
if (typeof width !== 'number') {
errors.push(`connections[${index}]的宽度不是有效的数字`);
}
});
}
return {
isValid: errors.length === 0,
errors
};
}

View File

@@ -1,5 +0,0 @@
import LabCanvas from './LabCanvas.vue';
import LabComponentsDrawer from './LabComponentsDrawer.vue';
import { useProvideLabCanvasStore, useLabCanvasStore } from './composable/LabCanvasManager';
export {LabCanvas, LabComponentsDrawer};

View File

@@ -0,0 +1,86 @@
import { ref, reactive } from 'vue';
export interface WireItem {
id: string;
startX: number;
startY: number;
endX: number;
endY: number;
startComponentId: string;
endComponentId?: string;
color?: string;
isActive?: boolean;
constraint?: string;
strokeWidth?: number;
routingMode?: 'auto' | 'orthogonal' | 'direct';
showLabel?: boolean;
}
// 全局wires状态
export const wires = ref<WireItem[]>([]);
// 添加新连线
export function addWire(wire: WireItem) {
wires.value.push(wire);
}
// 删除连线
export function deleteWire(wireId: string) {
const idx = wires.value.findIndex(w => w.id === wireId);
if (idx !== -1) wires.value.splice(idx, 1);
}
// 批量更新与某个引脚相关的所有Wire的约束
export function updateWiresConstraintByPin(componentId: string, newConstraint: string) {
wires.value.forEach(wire => {
if (
(wire.startComponentId === componentId) ||
(wire.endComponentId === componentId)
) {
wire.constraint = newConstraint;
}
});
}
// 查找与某个引脚相关的所有Wire
export function findWiresByPin(componentId: string) {
return wires.value.filter(wire =>
(wire.startComponentId === componentId) ||
(wire.endComponentId === componentId)
);
}
// 临时连线相关状态
export const isCreatingWire = ref(false);
export const creatingWireStart = reactive({ x: 0, y: 0 });
export const creatingWireStartInfo = reactive({
componentId: '',
pinLabel: '',
constraint: ''
});
export const mousePosition = reactive({ x: 0, y: 0 });
export function resetWireCreation() {
isCreatingWire.value = false;
creatingWireStart.x = 0;
creatingWireStart.y = 0;
creatingWireStartInfo.componentId = '';
creatingWireStartInfo.pinLabel = '';
creatingWireStartInfo.constraint = '';
}
export function setWireCreationStart(x: number, y: number, componentId: string, pinLabel: string, constraint: string) {
isCreatingWire.value = true;
creatingWireStart.x = x;
creatingWireStart.y = y;
creatingWireStartInfo.componentId = componentId;
creatingWireStartInfo.pinLabel = pinLabel;
creatingWireStartInfo.constraint = constraint;
}
export function setMousePosition(x: number, y: number) {
mousePosition.x = x;
mousePosition.y = y;
}
// 其它Wire相关操作可继续扩展...