feat(core): implement connection radius

Signed-off-by: braks <78412429+bcakmakoglu@users.noreply.github.com>
This commit is contained in:
braks
2023-02-01 22:57:05 +01:00
committed by Braks
parent 7abd0bfdf3
commit e74a20d923
9 changed files with 344 additions and 321 deletions
+11 -1
View File
@@ -29,7 +29,7 @@ declare global {
const autoResetRef: typeof import('@vueuse/core')['autoResetRef']
const boxToRect: typeof import('./utils/graph')['boxToRect']
const calcNextPosition: typeof import('./utils/drag')['calcNextPosition']
const checkElementBelowIsValid: typeof import('./composables/useHandle')['checkElementBelowIsValid']
const checkElementBelowIsValid: typeof import('./composables/useHandleDepr')['checkElementBelowIsValid']
const clamp: typeof import('./utils/graph')['clamp']
const clampPosition: typeof import('./utils/graph')['clampPosition']
const computed: typeof import('vue')['computed']
@@ -66,6 +66,7 @@ declare global {
const getBezierEdgeCenter: typeof import('./components/Edges/utils/general')['getBezierEdgeCenter']
const getBezierPath: typeof import('./components/Edges/utils/bezier')['getBezierPath']
const getBoundsofRects: typeof import('./utils/graph')['getBoundsofRects']
const getClosestHandle: typeof import('./utils/handle')['getClosestHandle']
const getConnectedEdges: typeof import('./utils/graph')['getConnectedEdges']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
@@ -74,10 +75,14 @@ declare global {
const getEdgeId: typeof import('./utils/graph')['getEdgeId']
const getEdgePositions: typeof import('./utils/edge')['getEdgePositions']
const getEventHandlerParams: typeof import('./utils/drag')['getEventHandlerParams']
const getEventPosition: typeof import('./utils/handle')['getEventPosition']
const getExtent: typeof import('./utils/drag')['getExtent']
const getHandle: typeof import('./utils/edge')['getHandle']
const getHandleBounds: typeof import('./utils/node')['getHandleBounds']
const getHandleLookup: typeof import('./utils/handle')['getHandleLookup']
const getHandlePosition: typeof import('./utils/edge')['getHandlePosition']
const getHandleType: typeof import('./utils/handle')['getHandleType']
const getHandles: typeof import('./utils/handle')['getHandles']
const getHostForElement: typeof import('./utils/graph')['getHostForElement']
const getIncomers: typeof import('./utils/graph')['getIncomers']
const getMarkerId: typeof import('./utils/graph')['getMarkerId']
@@ -106,6 +111,7 @@ declare global {
const isGraphEdge: typeof import('./utils/graph')['isGraphEdge']
const isGraphNode: typeof import('./utils/graph')['isGraphNode']
const isInputDOMNode: typeof import('./composables/useKeyPress')['isInputDOMNode']
const isMouseEvent: typeof import('./utils/handle')['isMouseEvent']
const isNode: typeof import('./utils/graph')['isNode']
const isParentSelected: typeof import('./utils/graph')['isParentSelected']
const isProxy: typeof import('vue')['isProxy']
@@ -113,6 +119,7 @@ declare global {
const isReadonly: typeof import('vue')['isReadonly']
const isRect: typeof import('./utils/graph')['isRect']
const isRef: typeof import('vue')['isRef']
const isValidHandle: typeof import('./utils/handle')['isValidHandle']
const makeDestructurable: typeof import('@vueuse/core')['makeDestructurable']
const markRaw: typeof import('vue')['markRaw']
const nextTick: typeof import('vue')['nextTick']
@@ -153,6 +160,8 @@ declare global {
const refDefault: typeof import('@vueuse/core')['refDefault']
const refThrottled: typeof import('@vueuse/core')['refThrottled']
const refWithControl: typeof import('@vueuse/core')['refWithControl']
const rendererPointToPoint: typeof import('./utils/graph')['rendererPointToPoint']
const resetRecentHandle: typeof import('./utils/handle')['resetRecentHandle']
const resolveComponent: typeof import('vue')['resolveComponent']
const resolveDirective: typeof import('vue')['resolveDirective']
const resolveRef: typeof import('@vueuse/core')['resolveRef']
@@ -249,6 +258,7 @@ declare global {
const useGetPointerPosition: typeof import('./composables/useGetPointerPosition')['useGetPointerPosition']
const useGetters: typeof import('./store/getters')['useGetters']
const useHandle: typeof import('./composables/useHandle')['default']
const useHandleDepr: typeof import('./composables/useHandleDepr')['default']
const useHooks: typeof import('./store/hooks')['useHooks']
const useIdle: typeof import('@vueuse/core')['useIdle']
const useImage: typeof import('@vueuse/core')['useImage']
@@ -43,7 +43,7 @@ const EdgeWrapper = defineComponent({
const type = ref<HandleType>('source')
const elementEdgeUpdaterType = ref<HandleType>('source')
const edgeUpdaterType = ref<HandleType>('source')
const mouseEvent = ref<MouseEvent>()
@@ -70,12 +70,12 @@ const EdgeWrapper = defineComponent({
updating = false
}
const { onMouseDown } = useHandle({
const { handlePointerDown } = useHandle({
nodeId,
handleId,
type,
isValidConnection: undefined,
elementEdgeUpdaterType,
edgeUpdaterType,
onEdgeUpdate,
onEdgeUpdateEnd,
})
@@ -84,12 +84,12 @@ const EdgeWrapper = defineComponent({
nodeId.value = isSourceHandle ? edge.target : edge.source
handleId.value = (isSourceHandle ? edge.targetHandle : edge.sourceHandle) ?? ''
type.value = isSourceHandle ? 'target' : 'source'
elementEdgeUpdaterType.value = type.value
edgeUpdaterType.value = type.value
mouseEvent.value = event
hooks.emit.updateStart({ event, edge })
onMouseDown(event)
handlePointerDown(event)
}
const onEdgeClick = (event: MouseEvent) => {
@@ -15,7 +15,7 @@ const handle = ref<HTMLDivElement>()
const handleId = $computed(() => id ?? `${nodeId}__handle-${position}`)
const { onMouseDown, onTouchStart, onClick } = useHandle({
const { handlePointerDown, handleClick } = useHandle({
nodeId,
handleId,
isValidConnection,
@@ -80,6 +80,7 @@ export default {
<template>
<div
ref="handle"
:data-id="`${nodeId}-${handleId}-${type}`"
:data-handleid="handleId"
:data-nodeid="nodeId"
:data-handlepos="position"
@@ -98,9 +99,9 @@ export default {
connectionStartHandle.type === type,
},
]"
@mousedown="onMouseDown"
@touchstart="onTouchStart"
@click="onClick"
@mousedown="handlePointerDown"
@touchstart="handlePointerDown"
@click="handleClick"
>
<slot :id="id" />
</div>
+144 -311
View File
@@ -1,368 +1,202 @@
import type { MaybeRef } from '@vueuse/core'
import { isFunction } from '@vueuse/core'
import type { Actions, Connection, GraphEdge, HandleType, ValidConnectionFunc, XYPosition } from '~/types'
import { ConnectionMode } from '~/types'
interface Result {
elementBelow: Element | null
isValid: boolean
connection: Connection
isHoveringHandle: boolean
}
import type { Connection, ConnectionHandle, HandleType, ValidConnectionFunc } from '~/types'
interface UseHandleProps {
handleId: MaybeRef<string | null>
nodeId: MaybeRef<string>
type: MaybeRef<HandleType>
isValidConnection?: ValidConnectionFunc
elementEdgeUpdaterType?: MaybeRef<HandleType>
edgeUpdaterType?: MaybeRef<HandleType>
onEdgeUpdate?: (connection: Connection) => void
onEdgeUpdateEnd?: () => void
onEdgeUpdateEnd?: (event: MouseEvent | TouchEvent) => void
}
// checks if element below mouse is a handle and returns connection in form of an object { source: 123, target: 312 }
export const checkElementBelowIsValid = (
event: MouseEvent | TouchEvent,
connectionMode: ConnectionMode,
isTarget: boolean,
nodeId: string,
handleId: string | null,
isValidConnection: ValidConnectionFunc | undefined,
doc: Document,
edges: GraphEdge[],
findNode: Actions['findNode'],
) => {
const clientX = (event as TouchEvent).touches ? (event as TouchEvent).touches[0].clientX : (event as MouseEvent).clientX
const clientY = (event as TouchEvent).touches ? (event as TouchEvent).touches[0].clientY : (event as MouseEvent).clientY
const elementBelow = doc.elementFromPoint(clientX, clientY)
const elementBelowIsTarget = elementBelow?.classList.contains('target') || false
const elementBelowIsSource = elementBelow?.classList.contains('source') || false
const result: Result = {
elementBelow,
isValid: false,
connection: { source: '', target: '', sourceHandle: null, targetHandle: null },
isHoveringHandle: false,
}
if (elementBelow && (elementBelowIsTarget || elementBelowIsSource)) {
result.isHoveringHandle = true
// in strict mode we don't allow target to target or source to source connections
const isValid =
connectionMode === ConnectionMode.Strict ? (isTarget && elementBelowIsSource) || (!isTarget && elementBelowIsTarget) : true
if (isValid) {
const elementBelowNodeId = elementBelow.getAttribute('data-nodeid') ?? ''
const elementBelowHandleId = elementBelow.getAttribute('data-handleid') ?? ''
const sourceId = isTarget ? elementBelowNodeId : nodeId
const sourceHandleId = isTarget ? elementBelowHandleId : handleId
const targetId = isTarget ? nodeId : elementBelowNodeId
const targetHandleId = isTarget ? handleId : elementBelowHandleId
const connection: Connection = {
source: sourceId,
sourceHandle: sourceHandleId,
target: targetId,
targetHandle: targetHandleId,
}
result.connection = connection
result.isValid =
(isFunction(isValidConnection)
? isValidConnection(connection, { edges, sourceNode: findNode(sourceId)!, targetNode: findNode(targetId)! })
: elementBelowNodeId !== nodeId || elementBelowHandleId !== handleId) ||
!result.connection.target ||
!result.connection.source
}
}
return result
}
const resetRecentHandle = (hoveredHandle: Element): void => {
hoveredHandle?.classList.remove('vue-flow__handle-valid')
hoveredHandle?.classList.remove('vue-flow__handle-connecting')
}
/**
* This composable can be used to create custom Handle components
*
* It provides an `onClick` and `onMouseDown` handler that you can bind to your custom handle, so it will behave like the default handle.
*
*/
export default function useHandle({
handleId,
nodeId,
isValidConnection,
handleId: _handleId,
nodeId: _nodeId,
type,
elementEdgeUpdaterType,
onEdgeUpdateEnd,
isValidConnection,
edgeUpdaterType: _edgeUpdaterType,
onEdgeUpdate,
onEdgeUpdateEnd,
}: UseHandleProps) {
const isTarget = $computed(() => unref(type) === 'target')
const nodeId = $computed(() => unref(_nodeId))
const handleId = $computed(() => unref(_handleId))
const edgeUpdaterType = $computed(() => unref(_edgeUpdaterType))
const {
edges,
connectOnClick,
nodesConnectable,
connectionClickStartHandle,
vueFlowRef,
connectionMode,
emits,
connectionRadius,
connectOnClick,
connectionClickStartHandle,
nodesConnectable,
defaultEdgeOptions,
findNode,
getNodes,
startConnection,
updateConnection,
endConnection,
findNode,
vueFlowRef,
} = $(useVueFlow())
emits,
viewport,
} = useVueFlow()
const isTarget = $computed(() => unref(type) === 'target')
function handlePointerDown(event: MouseEvent | TouchEvent) {
const isMouseTriggered = isMouseEvent(event)
let recentHoveredHandle: Element
if ((isMouseTriggered && event.button === 0) || !isMouseTriggered) {
// when vue-flow is used inside a shadow root we can't use document
const doc = getHostForElement(event.target as HTMLElement)
const onMouseDown = (event: MouseEvent) => {
if (event.button !== 0) return
const validConnectFunc = isValidConnection || (() => true)
const doc = getHostForElement(event.target as HTMLElement)
if (!doc) return
let prevClosestHandle: ConnectionHandle | null
let validConnectFunc = isValidConnection
const { x, y } = getEventPosition(event)
const clickedHandle = doc?.elementFromPoint(x, y)
const handleType = getHandleType(unref(edgeUpdaterType), clickedHandle)
const containerBounds = vueFlowRef.value?.getBoundingClientRect()
const node = findNode(unref(nodeId))
if (!containerBounds || !handleType) {
return
}
if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return
let prevActiveHandle: Element
let connectionPosition = getEventPosition(event, containerBounds)
if (!isValidConnection) {
if (node) validConnectFunc = !isTarget ? node.isValidTargetPos : node.isValidSourcePos
}
const elementBelow = doc.elementFromPoint(event.clientX, event.clientY)
const elementBelowIsTarget = elementBelow?.classList.contains('target')
const elementBelowIsSource = elementBelow?.classList.contains('source')
if (!vueFlowRef || (!elementBelowIsTarget && !elementBelowIsSource && !elementEdgeUpdaterType)) return
const handleType = elementEdgeUpdaterType ?? (elementBelowIsTarget ? 'target' : 'source')
const containerBounds = vueFlowRef.getBoundingClientRect()
startConnection(
{
nodeId: unref(nodeId),
handleId: unref(handleId),
type: unref(handleType),
},
{
x: event.clientX - containerBounds.left,
y: event.clientY - containerBounds.top,
},
event,
)
function onMouseMove(event: MouseEvent) {
updateConnection({
x: event.clientX - containerBounds.left,
y: event.clientY - containerBounds.top,
const handleLookup = getHandleLookup({
nodes: getNodes.value,
nodeId,
handleId,
handleType,
})
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(
startConnection(
{
nodeId: unref(nodeId),
handleId: unref(handleId),
type: unref(handleType),
},
{
x: x - containerBounds.left,
y: y - containerBounds.top,
},
event,
connectionMode,
unref(isTarget),
unref(nodeId),
unref(handleId),
validConnectFunc,
doc,
edges,
findNode,
)
if (!isHoveringHandle) return resetRecentHandle(recentHoveredHandle)
emits.connectStart({ event, nodeId, handleId, handleType })
const isOwnHandle = connection.source === connection.target
function onPointerMove(event: MouseEvent | TouchEvent) {
connectionPosition = getEventPosition(event, containerBounds)
if (!isOwnHandle && elementBelow) {
recentHoveredHandle = elementBelow
elementBelow.classList.add('vue-flow__handle-connecting')
elementBelow.classList.toggle('vue-flow__handle-valid', isValid)
}
}
prevClosestHandle = getClosestHandle(
pointToRendererPoint(connectionPosition, viewport.value, false, [1, 1]),
connectionRadius.value,
handleLookup,
)
function onMouseUp(event: MouseEvent) {
const { connection, isValid } = checkElementBelowIsValid(
event,
connectionMode,
unref(isTarget),
unref(nodeId),
unref(handleId),
validConnectFunc,
doc,
edges,
findNode,
)
updateConnection(
prevClosestHandle
? rendererPointToPoint(
{
x: prevClosestHandle.x,
y: prevClosestHandle.y,
},
viewport.value,
)
: connectionPosition,
)
const isOwnHandle = connection.source === connection.target
if (!prevClosestHandle) {
return resetRecentHandle(prevActiveHandle)
}
if (isValid && !isOwnHandle) {
if (!onEdgeUpdate) emits.connect(connection)
else onEdgeUpdate(connection)
const { connection, handleDomNode, isValid } = isValidHandle(
prevClosestHandle,
connectionMode.value,
nodeId,
handleId,
isTarget ? 'target' : 'source',
validConnectFunc,
doc,
)
if (connection.source !== connection.target && handleDomNode) {
resetRecentHandle(prevActiveHandle)
prevActiveHandle = handleDomNode
handleDomNode.classList.add('vue-flow__handle-connecting')
handleDomNode.classList.toggle('vue-flow__handle-valid', isValid)
}
}
if (elementEdgeUpdaterType) onEdgeUpdateEnd?.()
function onPointerUp(event: MouseEvent | TouchEvent) {
if (prevClosestHandle) {
const { connection, isValid } = isValidHandle(
prevClosestHandle,
connectionMode.value,
nodeId,
handleId,
isTarget ? 'target' : 'source',
validConnectFunc,
doc,
)
resetRecentHandle(recentHoveredHandle)
if (isValid) {
if (!onEdgeUpdate) emits.connect({ ...defaultEdgeOptions, ...connection })
else onEdgeUpdate(connection)
}
}
endConnection(event)
emits.connectEnd(event)
doc.removeEventListener('mousemove', onMouseMove as EventListenerOrEventListenerObject)
doc.removeEventListener('mouseup', onMouseUp as EventListenerOrEventListenerObject)
if (edgeUpdaterType) onEdgeUpdateEnd?.(event)
resetRecentHandle(prevActiveHandle)
endConnection(event)
doc.removeEventListener('mousemove', onPointerMove as EventListener)
doc.removeEventListener('mouseup', onPointerUp as EventListener)
doc.removeEventListener('touchmove', onPointerMove as EventListener)
doc.removeEventListener('touchend', onPointerUp as EventListener)
}
doc.addEventListener('mousemove', onPointerMove as EventListener)
doc.addEventListener('mouseup', onPointerUp as EventListener)
doc.addEventListener('touchmove', onPointerMove as EventListener)
doc.addEventListener('touchend', onPointerUp as EventListener)
}
doc.addEventListener('mousemove', onMouseMove as EventListenerOrEventListenerObject)
doc.addEventListener('mouseup', onMouseUp as EventListenerOrEventListenerObject)
}
const lastTouchPos = ref<XYPosition>({ x: 0, y: 0 })
const handleClick = (event: MouseEvent) => {
if (!connectOnClick.value) return
const onTouchStart = (event: TouchEvent) => {
const clientX = event.touches[0].clientX
const clientY = event.touches[0].clientY
const doc = getHostForElement(event.target as HTMLElement)
if (!doc) return
let validConnectFunc = isValidConnection
const node = findNode(unref(nodeId))
if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return
if (!isValidConnection) {
if (node) validConnectFunc = !isTarget ? node.isValidTargetPos : node.isValidSourcePos
}
const elementBelow = doc.elementFromPoint(clientX, clientY)
const elementBelowIsTarget = elementBelow?.classList.contains('target')
const elementBelowIsSource = elementBelow?.classList.contains('source')
if (!vueFlowRef || (!elementBelowIsTarget && !elementBelowIsSource && !elementEdgeUpdaterType)) return
const handleType = elementEdgeUpdaterType ?? (elementBelowIsTarget ? 'target' : 'source')
const containerBounds = vueFlowRef.getBoundingClientRect()
startConnection(
{
nodeId: unref(nodeId),
handleId: unref(handleId),
type: unref(handleType),
},
{
x: clientX - containerBounds.left,
y: clientY - containerBounds.top,
},
event,
)
function onTouchMove(event: TouchEvent) {
updateConnection({
x: event.touches[0].clientX - containerBounds.left,
y: event.touches[0].clientY - containerBounds.top,
})
lastTouchPos.value = {
x: event.touches[0].clientX,
y: event.touches[0].clientY,
}
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(
event,
connectionMode,
unref(isTarget),
unref(nodeId),
unref(handleId),
validConnectFunc,
doc,
edges,
findNode,
)
if (!isHoveringHandle) return resetRecentHandle(recentHoveredHandle)
const isOwnHandle = connection.source === connection.target
if (!isOwnHandle && elementBelow) {
recentHoveredHandle = elementBelow
elementBelow.classList.add('vue-flow__handle-connecting')
elementBelow.classList.toggle('vue-flow__handle-valid', isValid)
}
}
function onTouchEnd(event: TouchEvent) {
const { connection, isValid } = checkElementBelowIsValid(
{ clientX: lastTouchPos.value.x, clientY: lastTouchPos.value.y } as unknown as MouseEvent,
connectionMode,
unref(isTarget),
unref(nodeId),
unref(handleId),
validConnectFunc,
doc,
edges,
findNode,
)
const isOwnHandle = connection.source === connection.target
if (isValid && !isOwnHandle) {
if (!onEdgeUpdate) emits.connect(connection)
else onEdgeUpdate(connection)
}
if (elementEdgeUpdaterType) onEdgeUpdateEnd?.()
resetRecentHandle(recentHoveredHandle)
endConnection(event)
lastTouchPos.value = { x: 0, y: 0 }
doc.removeEventListener('touchmove', onTouchMove as EventListenerOrEventListenerObject)
doc.removeEventListener('touchend', onTouchEnd as EventListenerOrEventListenerObject)
}
doc.addEventListener('touchmove', onTouchMove as EventListenerOrEventListenerObject)
doc.addEventListener('touchend', onTouchEnd as EventListenerOrEventListenerObject)
}
const onClick = (event: MouseEvent) => {
if (!connectOnClick) return
if (!connectionClickStartHandle) {
if (!connectionClickStartHandle.value) {
startConnection({ nodeId: unref(nodeId), type: unref(type), handleId: unref(handleId) }, undefined, event, true)
} else {
let validConnectFunc: ValidConnectionFunc = isValidConnection ?? (() => true)
const validConnectFunc: ValidConnectionFunc = isValidConnection ?? (() => true)
const node = findNode(unref(nodeId))
if (node && (typeof node.connectable === 'undefined' ? nodesConnectable : node.connectable) === false) return
if (!isValidConnection) {
if (node) validConnectFunc = (!isTarget ? node.isValidTargetPos : node.isValidSourcePos) ?? (() => true)
}
const doc = getHostForElement(event.target as HTMLElement)
const { connection, isValid } = checkElementBelowIsValid(
event as MouseEvent,
connectionMode,
connectionClickStartHandle.type === 'target',
connectionClickStartHandle.nodeId,
connectionClickStartHandle.handleId || null,
const { connection, isValid } = isValidHandle(
{
nodeId,
id: handleId,
type: unref(type),
},
connectionMode.value,
connectionClickStartHandle.value.nodeId,
connectionClickStartHandle.value.handleId || null,
connectionClickStartHandle.value.type,
validConnectFunc,
doc,
edges,
findNode,
)
const isOwnHandle = connection.source === connection.target
@@ -374,8 +208,7 @@ export default function useHandle({
}
return {
onMouseDown,
onTouchStart,
onClick,
handlePointerDown,
handleClick,
}
}
+1
View File
@@ -86,6 +86,7 @@ const defaultState = (): State => ({
connectionStartHandle: null,
connectionClickStartHandle: null,
connectionPosition: { x: NaN, y: NaN },
connectionRadius: 20,
connectOnClick: true,
snapGrid: [15, 15],
+8
View File
@@ -10,6 +10,14 @@ export interface HandleElement extends XYPosition, Dimensions {
position: Position
}
export interface ConnectionHandle {
id: string | null
type: HandleType
nodeId: string
x: number
y: number
}
export interface StartHandle {
nodeId: string
type: HandleType
+1
View File
@@ -80,6 +80,7 @@ export interface State extends Omit<FlowOptions, 'id' | 'modelValue'> {
connectionStartHandle: StartHandle | null
connectionClickStartHandle: StartHandle | null
connectionPosition: XYPosition
connectionRadius: number
connectOnClick: boolean
edgeUpdaterRadius: number
+6
View File
@@ -215,6 +215,12 @@ export const updateEdge = (oldEdge: Edge, newConnection: Connection, elements: E
return elements.filter((e) => e.id !== oldEdge.id)
}
export const rendererPointToPoint = ({ x, y }: XYPosition, { x: tx, y: ty, zoom: tScale }: ViewportTransform): XYPosition => {
return {
x: x * tScale + tx,
y: y * tScale + ty,
}
}
export const pointToRendererPoint = (
{ x, y }: XYPosition,
{ x: tx, y: ty, zoom: tScale }: ViewportTransform,
+163
View File
@@ -0,0 +1,163 @@
import { ConnectionMode } from '~/types'
import type { Connection, GraphNode, HandleType, NodeHandleBounds, ValidConnectionFunc, XYPosition } from '~/types'
export interface ConnectionHandle {
id: string | null
type: HandleType
nodeId: string
x: number
y: number
}
// this functions collects all handles and adds an absolute position
// so that we can later find the closest handle to the mouse position
export function getHandles(
node: GraphNode,
handleBounds: NodeHandleBounds,
type: HandleType,
currentHandle: string,
): ConnectionHandle[] {
return (handleBounds[type] || []).reduce<ConnectionHandle[]>((res, h) => {
if (`${node.id}-${h.id}-${type}` !== currentHandle) {
res.push({
id: h.id || null,
type,
nodeId: node.id,
x: (node.computedPosition?.x ?? 0) + h.x + h.width / 2,
y: (node.computedPosition?.y ?? 0) + h.y + h.height / 2,
})
}
return res
}, [])
}
export function getClosestHandle(
pos: XYPosition,
connectionRadius: number,
handles: ConnectionHandle[],
): ConnectionHandle | null {
let closestHandle: ConnectionHandle | null = null
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) {
minDistance = distance
closestHandle = handle
}
})
return closestHandle
}
interface Result {
handleDomNode: Element | null
isValid: boolean
connection: Connection
}
// checks if and returns connection in fom of an object { source: 123, target: 312 }
export function isValidHandle(
handle: Pick<ConnectionHandle, 'nodeId' | 'id' | 'type'>,
connectionMode: ConnectionMode,
fromNodeId: string,
fromHandleId: string | null,
fromType: string,
isValidConnection: ValidConnectionFunc,
doc: Document | ShadowRoot,
) {
const { edges, findNode } = useVueFlow()
const isTarget = fromType === 'target'
const handleDomNode = doc.querySelector(`.vue-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]`)
const result: Result = {
handleDomNode,
isValid: false,
connection: { source: '', target: '', sourceHandle: null, targetHandle: null },
}
if (handleDomNode) {
const handleIsTarget = handle.type === 'target'
const handleIsSource = handle.type === 'source'
const handleNodeId = handleDomNode.getAttribute('data-nodeid')
const handleId = handleDomNode.getAttribute('data-handleid')
const connection: Connection = {
source: isTarget ? handle.nodeId : fromNodeId,
sourceHandle: isTarget ? handle.id : fromHandleId,
target: isTarget ? fromNodeId : handle.nodeId,
targetHandle: isTarget ? fromHandleId : handle.id,
}
result.connection = connection
// in strict mode we don't allow target to target or source to source connections
const isValid =
connectionMode === ConnectionMode.Strict
? (isTarget && handleIsSource) || (!isTarget && handleIsTarget)
: handleNodeId !== fromNodeId || handleId !== fromHandleId
if (isValid) {
result.isValid = isValidConnection(connection, {
edges: edges.value,
sourceNode: findNode(connection.source)!,
targetNode: findNode(connection.target)!,
})
}
}
return result
}
interface GetHandleLookupParams {
nodes: GraphNode[]
nodeId: string
handleId: string | null
handleType: string
}
export function getHandleLookup({ nodes, nodeId, handleId, handleType }: GetHandleLookupParams) {
return nodes.reduce<ConnectionHandle[]>((res, node) => {
const { handleBounds } = node
let sourceHandles: ConnectionHandle[] = []
let targetHandles: ConnectionHandle[] = []
if (handleBounds) {
sourceHandles = getHandles(node, handleBounds, 'source', `${nodeId}-${handleId}-${handleType}`)
targetHandles = getHandles(node, handleBounds, 'target', `${nodeId}-${handleId}-${handleType}`)
}
res.push(...sourceHandles, ...targetHandles)
return res
}, [])
}
export function getHandleType(edgeUpdaterType: HandleType | undefined, handleDomNode: Element | null): HandleType | null {
if (edgeUpdaterType) {
return edgeUpdaterType
} else if (handleDomNode?.classList.contains('target')) {
return 'target'
} else if (handleDomNode?.classList.contains('source')) {
return 'source'
}
return null
}
export function resetRecentHandle(handleDomNode: Element): void {
handleDomNode?.classList.remove('vue-flow__handle-valid')
handleDomNode?.classList.remove('vue-flow__handle-connecting')
}
export const isMouseEvent = (event: MouseEvent | TouchEvent): event is MouseEvent => 'clientX' in event
export const getEventPosition = (event: MouseEvent | TouchEvent, bounds?: DOMRect) => {
const isMouseTriggered = isMouseEvent(event)
const evtX = isMouseTriggered ? event.clientX : event.touches?.[0].clientX
const evtY = isMouseTriggered ? event.clientY : event.touches?.[0].clientY
return {
x: evtX - (bounds?.left ?? 0),
y: evtY - (bounds?.top ?? 0),
}
}