fix: 完善连接 workflow 节点时的合法性校验

This commit is contained in:
Aqr-K
2025-03-05 04:24:54 +08:00
parent fc36496aee
commit f6e3807a3d

View File

@@ -1,6 +1,6 @@
<script lang="ts" setup>
import { ref } from 'vue'
import { VueFlow, useVueFlow } from '@vue-flow/core'
import { VueFlow, useVueFlow, type Connection, type GraphNode } from '@vue-flow/core'
import { MiniMap } from '@vue-flow/minimap'
import useDragAndDrop from '@core/utils/workflow'
import { Workflow } from '@/api/types'
@@ -14,7 +14,46 @@ const { onConnect, addEdges, nodes, edges } = useVueFlow()
const { onDragOver, onDrop, onDragLeave, isDragOver } = useDragAndDrop()
onConnect(addEdges)
// 连接事件
onConnect((connection: Connection) => {
// 双重校验
if (!isValidConnection(connection)) {
$toast.warning('非法连接:不能连接自身或同类型端口!')
return
}
addEdges(connection)
})
// 获取指定节点端口的类型(输入/输出)
const getPortType = (node: GraphNode, handleId: string) => {
// 检查是否是输入端口(对应 handleBounds.target
const isInput = node.handleBounds?.target?.some(h => h.id === handleId)
if (isInput) return 'input'
// 检查是否是输出端口(对应 handleBounds.source
const isOutput = node.handleBounds?.source?.some(h => h.id === handleId)
return isOutput ? 'output' : null
}
// 校验连接是否合法
const isValidConnection = (connection: Connection) => {
// 获取连接的源节点和目标节点
const sourceNode = nodes.value.find(n => n.id === connection.source)
const targetNode = nodes.value.find(n => n.id === connection.target)
if (!sourceNode || !targetNode) return false
// 获取端口类型
const sourcePortType = getPortType(sourceNode, connection.sourceHandle!)
const targetPortType = getPortType(targetNode, connection.targetHandle!)
/* 同时满足三个条件,才允许连接:
* 1. 源端口是输出类型output
* 2. 目标端口是输入类型input
* 3. 不是同一节点的连接
*/
return sourcePortType === 'output' && targetPortType === 'input' && connection.source !== connection.target
}
// 自定义节点类型
const nodeTypes: Record<string, any> = ref({})
@@ -170,6 +209,7 @@ onMounted(() => {
:nodes="nodes"
:edges="edges"
:nodeTypes="nodeTypes"
:is-valid-connection="isValidConnection"
:default-edge-options="{ type: 'animation', animated: true }"
:edge-updater-radius="10"
@dragover="onDragOver"