feat: Pin移动连线也跟着移动

This commit is contained in:
alivender 2025-04-27 14:08:05 +08:00
parent b3a5342d6b
commit 10db7c67bf
6 changed files with 348 additions and 467 deletions

View File

@ -9,7 +9,7 @@
:style="{ transform: `translate(${position.x}px, ${position.y}px) scale(${scale})` }"> <!-- 渲染连线 -->
<svg class="wires-layer" width="4000" height="4000">
<!-- 已完成的连线 -->
<Wire
<WireComponent
v-for="wire in wires"
:key="wire.id"
:id="wire.id"
@ -19,16 +19,17 @@
:end-y="wire.endY"
:stroke-color="wire.color || '#4a5568'"
:stroke-width="2"
:is-active="wire.isActive"
:is-active="wireSelectedId === wire.id"
:start-component-id="wire.startComponentId"
:start-pin-label="wire.startPinLabel"
:end-component-id="wire.endComponentId"
:end-pin-label="wire.endPinLabel"
:constraint="wire.constraint"
@click="handleWireClick(wire)"
/>
<!-- 正在创建的连线 -->
<Wire
<WireComponent
v-if="isCreatingWire"
id="temp-wire"
:start-x="creatingWireStart.x"
@ -58,7 +59,7 @@
@mouseleave="hoveredComponent = null"><!-- 动态渲染组件 --> <component
:is="getComponentDefinition(component.type)"
v-if="props.componentModules[component.type]"
v-bind="prepareComponentProps(component.props || {})"
v-bind="prepareComponentProps(component.props || {}, component.id)"
@update:bindKey="(value: string) => updateComponentProp(component.id, 'bindKey', value)"
@pin-click="(pinInfo: any) => handlePinClick(component.id, pinInfo, pinInfo.originalEvent)"
:ref="(el: any) => { if (el) componentRefs[component.id] = el; }"
@ -80,7 +81,7 @@
<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import Wire from '@/components/Wire.vue';
import WireComponent from '@/components/equipments/Wire.vue';
//
interface ComponentItem {
@ -112,6 +113,7 @@ const selectedComponentId = ref<string | null>(null);
const hoveredComponent = ref<string | null>(null);
const draggingComponentId = ref<string | null>(null);
const componentDragOffset = reactive({ x: 0, y: 0 });
const wireSelectedId = ref<string | null>(null);
//
const componentRefs = ref<Record<string, any>>({});
@ -170,20 +172,27 @@ const getComponentDefinition = (type: string) => {
};
//
function prepareComponentProps(props: Record<string, any>): Record<string, any> {
const result: Record<string, any> = {};
for (const key in props) {
let value = props[key];
function prepareComponentProps(props: Record<string, any>, componentId?: string): Record<string, any> {
const result: Record<string, any> = { ...props };
// ID
if (componentId) {
result.componentId = componentId;
}
//
for (const key in result) {
let value = result[key];
// null/undefined string
if (
(key === 'style' || key === 'direction' || key === 'type') &&
value != null &&
typeof value !== 'string'
) {
value = String(value);
result[key] = String(value);
}
result[key] = value;
}
return result;
}
@ -363,6 +372,17 @@ function getComponentRef(componentId: string) {
return componentRefs.value[component.id] || null;
}
// Wire
function getWireRef(wireId: string) {
// SVGWire
const wire = document.querySelector(`[data-wire-id="${wireId}"]`);
if (wire && '__vueParentInstance' in wire) {
// @ts-ignore - 访Vue
return wire.__vueParentInstance?.component?.exposed;
}
return null;
}
//
defineExpose({
getComponentRef,
@ -384,6 +404,9 @@ interface WireItem {
color?: string;
isActive?: boolean;
constraint?: string;
strokeWidth?: number;
routingMode?: 'auto' | 'orthogonal' | 'direct';
showLabel?: boolean;
}
const wires = ref<WireItem[]>([]);
@ -449,39 +472,62 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
//
document.addEventListener('mousemove', onCreatingWireMouseMove);
} else {
// 线
} else { // 线
if (componentId === creatingWireStartInfo.componentId && pinInfo.label === creatingWireStartInfo.pinLabel) {
// Pin线
cancelWireCreation();
return;
}
//
const startConstraint = creatingWireStartInfo.constraint;
const endConstraint = pinInfo.constraint;
if (startConstraint && endConstraint && startConstraint !== endConstraint) {
// Pin
promptForConstraintSelection(
componentId,
pinInfo,
startConstraint,
endConstraint
);
} else {
//
//
const startConstraint = creatingWireStartInfo.constraint || '';
const endConstraint = pinInfo.constraint || '';
let finalConstraint = '';
if (startConstraint) {
//
if (startConstraint && endConstraint && startConstraint === endConstraint) {
finalConstraint = startConstraint;
} else {
// 使
let replacedConstraint: string | null = null;
let newConstraint: string | null = null;
if (startConstraint && endConstraint) {
const isStartSystemConstraint = startConstraint.startsWith('$');
const isEndSystemConstraint = endConstraint.startsWith('$');
if (!isStartSystemConstraint && isEndSystemConstraint) {
finalConstraint = startConstraint;
replacedConstraint = endConstraint;
newConstraint = startConstraint;
} else if (isStartSystemConstraint && !isEndSystemConstraint) {
finalConstraint = endConstraint;
replacedConstraint = startConstraint;
newConstraint = endConstraint;
} else if (isStartSystemConstraint && isEndSystemConstraint) {
finalConstraint = Math.random() < 0.5 ? startConstraint : endConstraint;
replacedConstraint = (finalConstraint === startConstraint) ? endConstraint : startConstraint;
newConstraint = finalConstraint;
} else {
const userChoice = confirm(`针脚约束冲突:${startConstraint}${endConstraint}。点击"确定"保留${startConstraint},点击"取消"保留${endConstraint}`);
finalConstraint = userChoice ? startConstraint : endConstraint;
replacedConstraint = userChoice ? endConstraint : startConstraint;
newConstraint = finalConstraint;
}
} else if (startConstraint) {
finalConstraint = startConstraint;
} else if (endConstraint) {
finalConstraint = endConstraint;
} else {
// Pin
finalConstraint = generateRandomConstraint();
}
// Pin
if (replacedConstraint && newConstraint && replacedConstraint !== newConstraint) {
props.components.forEach(comp => {
if (comp.props && comp.props.constraint === replacedConstraint) {
emit('update-component-prop', { id: comp.id, propName: 'constraint', value: newConstraint });
}
});
}
}
// 线
completeWireCreation(
componentId,
@ -495,7 +541,6 @@ function handlePinClick(componentId: string, pinInfo: any, event: MouseEvent) {
updatePinConstraint(componentId, pinInfo.label, finalConstraint);
}
}
}
//
function generateRandomConstraint() {
@ -503,36 +548,6 @@ function generateRandomConstraint() {
return `$auto_constraint_${randomId}`;
}
//
function promptForConstraintSelection(
endComponentId: string,
endPinInfo: any,
startConstraint: string,
endConstraint: string
) {
// 使ModalUI
// 使confirm
const useStartConstraint = confirm(
`连接两个不同约束的Pin:\n` +
`- 起点约束: ${startConstraint}\n` +
`- 终点约束: ${endConstraint}\n\n` +
`点击"确定"使用起点约束,点击"取消"使用终点约束。`
);
const finalConstraint = useStartConstraint ? startConstraint : endConstraint;
// 线
completeWireCreation(
endComponentId,
endPinInfo.label,
finalConstraint,
endPinInfo
);
// Pin
updatePinConstraint(creatingWireStartInfo.componentId, creatingWireStartInfo.pinLabel, finalConstraint);
updatePinConstraint(endComponentId, endPinInfo.label, finalConstraint);
}
// Pin
function updatePinConstraint(componentId: string, pinLabel: string, constraint: string) {
// ID
@ -575,26 +590,15 @@ function completeWireCreation(endComponentId: string, endPinLabel: string, const
endX = (pinPosition.x - containerRect.left - position.x) / scale.value;
endY = (pinPosition.y - containerRect.top - position.y) / scale.value;
console.log(`通过 getPinPosition 获取终点针脚 ${endPinLabel} 的画布坐标: (${endX}, ${endY})`);
} else {
console.warn(`getPinPosition 返回 null将使用备选方法`);
} else { console.warn(`getPinPosition 返回 null将使用备选方法`);
}
} else if (endPinInfo && endPinInfo.position) {
// getPinPosition 使
const pinPagePosition = endPinInfo.position;
endX = (pinPagePosition.x - containerRect.left - position.x) / scale.value;
endY = (pinPagePosition.y - containerRect.top - position.y) / scale.value;
console.log(`通过 pinInfo.position 获取终点针脚位置: (${endX}, ${endY})`);
} else {
console.warn(`无法获取针脚 ${endPinLabel} 的精确位置,使用鼠标位置代替`);
}
//
const distanceSquared = Math.pow(endX - creatingWireStart.x, 2) + Math.pow(endY - creatingWireStart.y, 2);
if (distanceSquared < 1) { // 1
console.warn(`起点和终点太接近 (${distanceSquared}像素²),调整终点位置`);
//
endX += 10 + Math.random() * 5;
endY += 10 + Math.random() * 5;
}
// 线
const newWire: WireItem = {
id: `wire-${Date.now()}`,
@ -607,18 +611,12 @@ function completeWireCreation(endComponentId: string, endPinLabel: string, const
endComponentId: endComponentId,
endPinLabel: endPinLabel,
color: '#4a5568',
constraint: constraint
constraint: constraint,
routingMode: 'orthogonal',
strokeWidth: 2,
showLabel: false
};
console.log(`新连线创建完成:`, newWire);
//
if (Math.abs(newWire.startX - newWire.endX) < 1 && Math.abs(newWire.startY - newWire.endY) < 1) {
console.warn(`连线的起点和终点重合,调整终点位置`);
newWire.endX += 20;
newWire.endY += 20;
}
wires.value.push(newWire);
// 线
@ -642,28 +640,7 @@ function onCreatingWireMouseMove(e: MouseEvent) {
// 线
function handleWireClick(wire: WireItem) {
// 线
const deleteWire = confirm('是否删除此连线?');
if (deleteWire) {
// 线
const index = wires.value.findIndex(w => w.id === wire.id);
if (index !== -1) {
const deletedWire = wires.value.splice(index, 1)[0];
// 线
emit('wire-deleted', deletedWire.id);
}
}
}
// 线
function updateAllWires() {
if (!canvasContainer.value) return;
// 线
wires.value.forEach(wire => {
updateWireWithPinPositions(wire);
});
wireSelectedId.value = wire.id;
}
// 线
@ -671,32 +648,15 @@ function updateWireWithPinPositions(wire: WireItem) {
if (!canvasContainer.value) return;
const containerRect = canvasContainer.value.getBoundingClientRect();
console.log(`更新连线 ${wire.id},当前位置: 起点(${wire.startX}, ${wire.startY}), 终点(${wire.endX}, ${wire.endY})`);
//
const originalStartX = wire.startX;
const originalStartY = wire.startY;
const originalEndX = wire.endX;
const originalEndY = wire.endY;
//
if (wire.startComponentId && wire.startPinLabel) {
const startComponentRef = componentRefs.value[wire.startComponentId];
if (startComponentRef && startComponentRef.getPinPosition) {
const pinPosition = startComponentRef.getPinPosition(wire.startPinLabel);
if (pinPosition) {
const newStartX = (pinPosition.x - containerRect.left - position.x) / scale.value;
const newStartY = (pinPosition.y - containerRect.top - position.y) / scale.value;
console.log(`更新连线起点 ${wire.startComponentId}/${wire.startPinLabel}: (${wire.startX}, ${wire.startY}) => (${newStartX}, ${newStartY})`);
wire.startX = newStartX;
wire.startY = newStartY;
} else {
console.warn(`无法获取针脚 ${wire.startComponentId}/${wire.startPinLabel} 的位置`);
wire.startX = (pinPosition.x - containerRect.left - position.x) / scale.value;
wire.startY = (pinPosition.y - containerRect.top - position.y) / scale.value;
}
} else {
console.warn(`组件 ${wire.startComponentId} 没有实现 getPinPosition 方法`);
}
}
@ -706,31 +666,10 @@ function updateWireWithPinPositions(wire: WireItem) {
if (endComponentRef && endComponentRef.getPinPosition) {
const pinPosition = endComponentRef.getPinPosition(wire.endPinLabel);
if (pinPosition) {
const newEndX = (pinPosition.x - containerRect.left - position.x) / scale.value;
const newEndY = (pinPosition.y - containerRect.top - position.y) / scale.value;
console.log(`更新连线终点 ${wire.endComponentId}/${wire.endPinLabel}: (${wire.endX}, ${wire.endY}) => (${newEndX}, ${newEndY})`);
wire.endX = newEndX;
wire.endY = newEndY;
} else {
console.warn(`无法获取针脚 ${wire.endComponentId}/${wire.endPinLabel} 的位置`);
}
} else {
console.warn(`组件 ${wire.endComponentId} 没有实现 getPinPosition 方法`);
wire.endX = (pinPosition.x - containerRect.left - position.x) / scale.value;
wire.endY = (pinPosition.y - containerRect.top - position.y) / scale.value;
}
}
//
const positionChanged =
originalStartX !== wire.startX ||
originalStartY !== wire.startY ||
originalEndX !== wire.endX ||
originalEndY !== wire.endY;
if (positionChanged) {
//
ensureUniquePinPositions(wire);
}
}
@ -738,14 +677,9 @@ function updateWireWithPinPositions(wire: WireItem) {
function updateWiresForComponent(componentId: string) {
if (!canvasContainer.value || !componentId) return;
console.log(`更新组件 ${componentId} 相关的连线位置`);
//
const component = props.components.find(c => c.id === componentId);
if (!component) {
console.warn(`找不到组件 ${componentId}`);
return;
}
if (!component) return;
// 线
const relatedWires = wires.value.filter(wire =>
@ -753,49 +687,14 @@ function updateWiresForComponent(componentId: string) {
wire.endComponentId === componentId
);
console.log(`找到 ${relatedWires.length} 条相关连线`);
if (relatedWires.length === 0) {
// 线线
console.log('没有找到直接关联的连线,检查所有连线');
// 线
wires.value.forEach((wire, index) => {
console.log(`连线 ${index}: startComponentId=${wire.startComponentId}, endComponentId=${wire.endComponentId}`);
});
return;
}
if (relatedWires.length === 0) return;
// 线
relatedWires.forEach(wire => {
console.log(`更新连线 ${wire.id} (${wire.startComponentId}/${wire.startPinLabel} -> ${wire.endComponentId}/${wire.endPinLabel})`);
updateWireWithPinPositions(wire);
});
}
//
function ensureUniquePinPositions(wire: WireItem) {
if (Math.abs(wire.startX - wire.endX) < 5 && Math.abs(wire.startY - wire.endY) < 5) {
console.warn('检测到连线起点和终点非常接近,添加随机偏移');
// ID
const idSum = (wire.startComponentId?.charCodeAt(0) || 0) +
(wire.endComponentId?.charCodeAt(0) || 0) +
(wire.startPinLabel?.charCodeAt(0) || 0) +
(wire.endPinLabel?.charCodeAt(0) || 0);
// 使ID
const offsetX = 20 * Math.cos(idSum * 0.1);
const offsetY = 20 * Math.sin(idSum * 0.1);
wire.endX += offsetX;
wire.endY += offsetY;
console.log(`应用偏移 (${offsetX.toFixed(2)}, ${offsetY.toFixed(2)}) 到连线终点`);
}
}
// --- ---
onMounted(() => {
//
@ -809,18 +708,6 @@ onMounted(() => {
//
window.addEventListener('keydown', handleKeyDown);
// 线
const wireUpdateInterval = setInterval(() => {
if (wires.value.length > 0) {
updateAllWires();
}
}, 1000); // 线
//
onUnmounted(() => {
clearInterval(wireUpdateInterval);
});
});
//
@ -838,6 +725,16 @@ function handleKeyDown(e: KeyboardEvent) {
// 线
cancelWireCreation();
}
// 线
if (wireSelectedId.value && (e.key === 'Delete' || e.key === 'Backspace')) {
const idx = wires.value.findIndex(w => w.id === wireSelectedId.value);
if (idx !== -1) {
const deletedWire = wires.value.splice(idx, 1)[0];
emit('wire-deleted', deletedWire.id);
wireSelectedId.value = null;
}
}
}
onUnmounted(() => {
@ -891,7 +788,7 @@ onUnmounted(() => {
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
pointer-events: auto; /* 修复:允许线被点击 */
z-index: 50;
}
@ -961,4 +858,9 @@ onUnmounted(() => {
.component-wrapper :deep(input) {
pointer-events: auto !important;
}
.wire-active {
stroke: #ff9800 !important;
filter: drop-shadow(0 0 4px #ff9800cc);
}
</style>

View File

@ -1,141 +0,0 @@
<template>
<path
:d="pathData"
fill="none"
:stroke="strokeColor"
:stroke-width="strokeWidth"
stroke-linecap="round"
stroke-linejoin="round"
:class="{ 'wire-active': isActive }"
@click="handleClick"
/>
</template>
<script setup lang="ts">
import { computed, defineEmits } from 'vue';
interface Props {
id: string;
startX: number;
startY: number;
endX: number;
endY: number;
strokeColor?: string;
strokeWidth?: number;
isActive?: boolean;
routingMode?: 'auto' | 'orthogonal' | 'direct';
//
startComponentId?: string;
startPinLabel?: string;
endComponentId?: string;
endPinLabel?: string;
}
const props = withDefaults(defineProps<Props>(), {
strokeColor: '#4a5568',
strokeWidth: 2,
isActive: false,
routingMode: 'orthogonal'
});
const emit = defineEmits(['click']);
function handleClick(event: MouseEvent) {
emit('click', { id: props.id, event });
}
const pathData = computed(() => {
//
const dx = Math.abs(props.endX - props.startX);
const dy = Math.abs(props.endY - props.startY);
//
if (dx < 0.5 && dy < 0.5) {
console.warn('连线的起点和终点几乎重合,强制绘制可见路径');
//
const r = 5; // 5
return `M ${props.startX} ${props.startY}
m -${r}, 0
a ${r},${r} 0 1,0 ${r*2},0
a ${r},${r} 0 1,0 -${r*2},0`;
}
if (props.routingMode === 'direct') {
return `M ${props.startX} ${props.startY} L ${props.endX} ${props.endY}`;
} else if (props.routingMode === 'orthogonal') {
// 线
return calculateOrthogonalPath(props.startX, props.startY, props.endX, props.endY);
} else {
// 线
if (dx < 10 || dy < 10) {
// 使线
return `M ${props.startX} ${props.startY} L ${props.endX} ${props.endY}`;
} else {
// 使线
return calculateOrthogonalPath(props.startX, props.startY, props.endX, props.endY);
}
}
});
function calculateOrthogonalPath(startX: number, startY: number, endX: number, endY: number) {
//
const dx = endX - startX;
const dy = endY - startY;
//
if (Math.abs(dx) < 1 && Math.abs(dy) < 1) {
console.warn('连线的起点和终点几乎重合,调整路径显示');
//
const offset = 5; // 5
return `M ${startX} ${startY}
L ${startX + offset} ${startY}
L ${startX + offset} ${startY + offset}
L ${startX} ${startY + offset}
L ${startX} ${startY}`;
}
// 线线
if (dx === 0 || dy === 0) {
return `M ${startX} ${startY} L ${endX} ${endY}`;
}
// 45线
const absDx = Math.abs(dx);
const absDy = Math.abs(dy);
if (absDx === absDy) {
// 45线
return `M ${startX} ${startY} L ${endX} ${endY}`;
}
// - 使L
//
if (absDx > absDy) {
const middleX = startX + dx * 0.5;
return `M ${startX} ${startY}
L ${middleX} ${startY}
L ${middleX} ${endY}
L ${endX} ${endY}`;
} else {
//
const middleY = startY + dy * 0.5;
return `M ${startX} ${startY}
L ${startX} ${middleY}
L ${endX} ${middleY}
L ${endX} ${endY}`;
}
}
</script>
<style scoped>
.wire-active {
stroke-dasharray: 5;
animation: dash 0.5s linear infinite;
}
@keyframes dash {
to {
stroke-dashoffset: 10;
}
}
</style>

View File

@ -5,71 +5,63 @@
:height="height"
:viewBox="'0 0 ' + viewBoxWidth + ' ' + viewBoxHeight"
class="pin-component"
:data-pin-id="props.label"
>
<g :transform="`translate(${viewBoxWidth/2}, ${viewBoxHeight/2})`"> <g v-if="props.appearance === 'None'">
<g transform="translate(-12.5, -12.5)" class="interactive"> <circle
:data-component-id="componentId"
:data-pin-label="props.label"
> <g :transform="`translate(${viewBoxWidth/2}, ${viewBoxHeight/2})`">
<g v-if="props.appearance === 'None'">
<g transform="translate(-12.5, -12.5)">
<circle
style="fill:#909090"
cx="12.5"
cy="12.5"
r="3.75"
@mouseenter="showPinTooltip"
@mouseleave="hidePinTooltip"
class="interactive"
@click.stop="handlePinClick"
:data-pin-id="`${props.label}-${props.constraint}`" />
:data-pin-element="`${props.componentId}-${props.label}`" />
</g>
</g>
<g v-else-if="props.appearance === 'Dip'">
<!-- 使用inkscape创建的SVG替代原有Dip样式 -->
<g transform="translate(-12.5, -12.5)" class="interactive">
<g transform="translate(-12.5, -12.5)">
<rect
:style="`fill:${props.type === 'analog' ? '#2a6099' : '#000000'};fill-opacity:0.772973`"
width="25"
height="25"
x="0"
y="0"
rx="2.5" /> <circle
rx="2.5" />
<circle
style="fill:#ecececc5;fill-opacity:0.772973"
cx="12.5"
cy="12.5"
r="3.75"
@mouseenter="showPinTooltip"
@mouseleave="hidePinTooltip"
class="interactive"
@click.stop="handlePinClick"
:data-pin-id="`${props.label}-${props.constraint}`" />
:data-pin-element="`${props.componentId}-${props.label}`" />
<text
style="font-size:6.85px;text-align:start;fill:#ffffff;fill-opacity:0.772973"
x="7.3"
y="7"
xml:space="preserve">{{ props.label }}</text>
</g>
</g> <g v-else-if="props.appearance === 'SMT'">
</g>
<g v-else-if="props.appearance === 'SMT'">
<rect x="-20" y="-10" width="40" height="20" fill="#aaa" rx="2" ry="2" />
<rect x="-18" y="-8" width="36" height="16" :fill="getColorByType" rx="1" ry="1" />
<rect x="-16" y="-6" width="26" height="12" :fill="getColorByType" rx="1" ry="1" />
<text text-anchor="middle" dominant-baseline="middle" font-size="8" fill="white" x="-3">{{ props.label }}</text>
<!-- SMT样式的针脚 --> <circle
<circle
fill="#ecececc5"
cx="10"
cy="0"
r="3.75"
class="interactive"
@mouseenter="showPinTooltip"
@mouseleave="hidePinTooltip"
@click.stop="handlePinClick"
:data-pin-id="`${props.label}-${props.constraint}`" />
</g> </g>
:data-pin-element="`${props.componentId}-${props.label}`"
/>
</g>
</g>
</svg>
<!-- 提示框 - 在SVG外部 -->
<div v-if="showTooltip" class="pin-tooltip" :style="{
position: 'absolute',
top: tooltipPosition.top + 'px',
left: tooltipPosition.left + 'px',
transform: 'translate(-50%, -100%)',
marginTop: '-5px'
}">
{{ tooltipText }}
</div>
</template>
<script setup lang="ts">
@ -82,6 +74,7 @@ interface Props {
direction?: 'input' | 'output' | 'inout';
type?: 'digital' | 'analog';
appearance?: 'None' | 'Dip' | 'SMT';
componentId?: string; // ID
}
const props = withDefaults(defineProps<Props>(), {
@ -90,7 +83,8 @@ const props = withDefaults(defineProps<Props>(), {
constraint: '',
direction: 'input',
type: 'digital',
appearance: 'Dip'
appearance: 'Dip',
componentId: 'pin-default' // ID
});
const emit = defineEmits([
@ -100,58 +94,6 @@ const emit = defineEmits([
//
const analogValue = ref(0);
const showTooltip = ref(false);
const tooltipText = ref('');
const tooltipPosition = reactive({
top: 0,
left: 0
});
//
function showPinTooltip(event: MouseEvent) {
showTooltip.value = true;
const target = event.target as SVGElement;
const rect = target.getBoundingClientRect();
//
tooltipPosition.top = rect.top;
tooltipPosition.left = rect.left + rect.width / 2;
//
tooltipText.value = generateTooltipText();
}
//
function hidePinTooltip() {
showTooltip.value = false;
}
//
function generateTooltipText() {
const parts = [];
parts.push(`标签: ${props.label}`);
if (props.constraint) {
parts.push(`约束: ${props.constraint}`);
} else {
parts.push('约束: 未定义');
}
parts.push(`方向: ${getDirectionText()}`);
parts.push(`类型: ${props.type === 'digital' ? '数字' : '模拟'}`);
return parts.join(' | ');
}
//
function getDirectionText() {
switch (props.direction) {
case 'input': return '输入';
case 'output': return '输出';
case 'inout': return '双向';
default: return '未知';
}
}
//
function handlePinClick(event: MouseEvent) {
@ -222,10 +164,10 @@ defineExpose({
// Pin
if (pinLabel !== props.label) return null;
// 使DOM
// document.querySelector
const pinElement = document.querySelector(`[data-pin-id="${props.label}-${props.constraint}"]`) as SVGElement;
// 使ID
const selector = `[data-pin-element="${props.componentId}-${props.label}"]`;
const pinElement = document.querySelector(selector) as SVGElement;
if (pinElement) {
//
const rect = pinElement.getBoundingClientRect();
@ -235,13 +177,11 @@ defineExpose({
};
}
// 使
// SVG
const svgElement = document.querySelector(`.pin-component[data-pin-id="${props.label}"]`) as SVGElement;
if (!svgElement) {
console.error(`找不到针脚 ${props.label} 的SVG元素`);
return null;
}
// 使SVG
const svgSelector = `svg.pin-component[data-component-id="${props.componentId}"][data-pin-label="${props.label}"]`;
const svgElement = document.querySelector(svgSelector) as SVGElement;
if (!svgElement) return null;
const svgRect = svgElement.getBoundingClientRect();
@ -249,12 +189,6 @@ defineExpose({
let pinX = svgRect.left + svgRect.width / 2;
let pinY = svgRect.top + svgRect.height / 2;
//
// 使
const randomOffset = 0.1;
pinX += Math.random() * randomOffset;
pinY += Math.random() * randomOffset;
return { x: pinX, y: pinY };
}
});
@ -273,15 +207,4 @@ defineExpose({
.interactive:hover {
filter: brightness(1.2);
}
.pin-tooltip {
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
z-index: 1000;
pointer-events: none;
white-space: nowrap;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
</style>

View File

@ -0,0 +1,149 @@
<template>
<g :data-wire-id="props.id">
<path
:d="pathData"
fill="none"
:stroke="computedStroke"
:stroke-width="strokeWidth"
stroke-linecap="round"
stroke-linejoin="round"
:class="{ 'wire-active': props.isActive }"
@click="handleClick"
/>
<!-- 可选添加连线标签或状态指示器 -->
<text
v-if="showLabel"
:x="labelPosition.x"
:y="labelPosition.y"
class="wire-label"
>{{ props.constraint || '' }}</text>
</g>
</template>
<script setup lang="ts">
import { computed, defineEmits, reactive } from 'vue';
interface Props {
id: string;
startX: number;
startY: number;
endX: number;
endY: number;
strokeColor?: string;
strokeWidth?: number;
isActive?: boolean;
routingMode?: 'auto' | 'orthogonal' | 'direct';
//
startComponentId?: string;
startPinLabel?: string;
endComponentId?: string;
endPinLabel?: string;
//
constraint?: string;
//
showLabel?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
strokeColor: '#4a5568',
strokeWidth: 2,
isActive: false,
routingMode: 'orthogonal',
showLabel: false,
constraint: ''
});
const computedStroke = computed(() => props.isActive ? '#ff9800' : props.strokeColor);
const emit = defineEmits(['click', 'update:active', 'update:position']);
function handleClick(event: MouseEvent) {
emit('click', { id: props.id, event });
}
// - 线
const labelPosition = computed(() => {
return {
x: (props.startX + props.endX) / 2,
y: (props.startY + props.endY) / 2 - 5
};
});
const pathData = computed(() => {
return calculateOrthogonalPath(props.startX, props.startY, props.endX, props.endY);
});
function calculateOrthogonalPath(startX: number, startY: number, endX: number, endY: number) {
//
const dx = endX - startX;
const dy = endY - startY;
// 线线
if (dx === 0 || dy === 0) {
return `M ${startX} ${startY} L ${endX} ${endY}`;
}
const absDx = Math.abs(dx);
const absDy = Math.abs(dy);
if (absDx > absDy) {
//
const middleX = startX + dx * 0.5;
return `M ${startX} ${startY} L ${middleX} ${startY} L ${middleX} ${endY} L ${endX} ${endY}`;
} else {
//
const middleY = startY + dy * 0.5;
return `M ${startX} ${startY} L ${startX} ${middleY} L ${endX} ${middleY} L ${endX} ${endY}`;
}
}
// 线
defineExpose({ id: props.id,
getInfo: () => ({
id: props.id,
startComponentId: props.startComponentId,
startPinLabel: props.startPinLabel,
endComponentId: props.endComponentId,
endPinLabel: props.endPinLabel,
constraint: props.constraint
}),
// 线
updatePosition: (newStartX: number, newStartY: number, newEndX: number, newEndY: number) => {
// props
emit('update:position', {
id: props.id,
startX: newStartX,
startY: newStartY,
endX: newEndX,
endY: newEndY
});
},
// 线
getPinPosition: () => null, // Wire
// 线
getRoutingMode: () => props.routingMode,
// 线
setActive: (active: boolean) => {
emit('update:active', active);
}
});
</script>
<style scoped>
.wire-active {
stroke-dasharray: 5;
animation: dash 0.5s linear infinite;
}
@keyframes dash {
to {
stroke-dashoffset: 10;
}
}
.wire-label {
font-size: 10px;
fill: #666;
text-anchor: middle;
pointer-events: none;
user-select: none;
}
</style>

View File

@ -318,7 +318,55 @@ const componentConfigs: Record<string, ComponentConfig> = {
description: '相同约束字符串的组件将被视为有电气连接'
}
]
},
// 线缆配置
Wire: {
props: [
{
name: 'routingMode',
type: 'select',
label: '路由方式',
default: 'orthogonal',
options: [
{ value: 'orthogonal', label: '直角' },
{ value: 'direct', label: '直线' },
{ value: 'auto', label: '自动' }
],
description: '线路连接方式'
},
{
name: 'strokeColor',
type: 'string',
label: '线条颜色',
default: '#4a5568',
description: '线条颜色使用CSS颜色值'
},
{
name: 'strokeWidth',
type: 'number',
label: '线条宽度',
default: 2,
min: 1,
max: 10,
step: 0.5,
description: '线条宽度'
},
{
name: 'constraint',
type: 'string',
label: '约束名称',
default: '',
description: '线路约束名称,用于标识连接关系'
},
{
name: 'showLabel',
type: 'boolean',
label: '显示标签',
default: false,
description: '是否显示连线上的约束标签'
}
]
},
};
// 获取组件配置的函数

View File

@ -344,7 +344,7 @@ function updateComponentProp(componentId: string | { id: string; propName: strin
// 线
function handleWireCreated(wireData: any) {
console.log('Wire created:', wireData);
// 线
// 线DiagramCanvas.vue
}
// 线