refactor(core): pick target handle if handles are on top of each other

Signed-off-by: braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
braks
2023-05-11 15:33:42 +02:00
committed by Braks
parent f5e0cef116
commit fb1181f209
2 changed files with 29 additions and 13 deletions
+20 -4
View File
@@ -57,18 +57,31 @@ export function getClosestHandle(
connectionRadius: number,
handles: ConnectionHandle[],
): ConnectionHandle | null {
let closestHandle: ConnectionHandle | null = null
let closestHandles: ConnectionHandle[] = []
let minDistance = Infinity
handles.forEach((handle) => {
const distance = Math.sqrt((handle.x - pos.x) ** 2 + (handle.y - pos.y) ** 2)
if (distance <= connectionRadius && distance < minDistance) {
if (distance <= connectionRadius) {
if (distance < minDistance) {
closestHandles = [handle]
} else if (distance === minDistance) {
// when multiple handles are on the same distance we collect all of them
closestHandles.push(handle)
}
minDistance = distance
closestHandle = handle
}
})
return closestHandle
if (!closestHandles.length) {
return null
}
return closestHandles.length === 1
? closestHandles[0]
: // if multiple handles are layout on top of each other we take the one with type = target because it's more likely that the user wants to connect to this one
closestHandles.find((handle) => handle.type === 'target') || closestHandles[0]
}
// checks if and returns connection in fom of an object { source: 123, target: 312 }
@@ -89,6 +102,9 @@ export function isValidHandle(
const handleDomNode = doc.querySelector(`.vue-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]`)
const { x, y } = getEventPosition(event)
const handleBelow = doc.elementFromPoint(x, y)
// we always want to prioritize the handle below the mouse cursor over the closest distance handle,
// because it could be that the center of another handle is closer to the mouse pointer than the handle below the cursor
const handleToCheck = handleBelow?.classList.contains('vue-flow__handle') ? handleBelow : handleDomNode
const result: ValidHandleResult = {