LCOV - code coverage report
Current view: top level - src/renderer/extensions/vueNodes/composables - useSlotLinkInteraction.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 83.1 % 384 319
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { tryOnScopeDispose, useEventListener } from '@vueuse/core'
       2              : import type { Fn } from '@vueuse/core'
       3              : 
       4              : import { useSharedCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion'
       5              : import { AutoPanController } from '@/renderer/core/canvas/useAutoPan'
       6              : import type { LGraph } from '@/lib/litegraph/src/LGraph'
       7              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
       8              : import { LLink, slotFloatingLinks } from '@/lib/litegraph/src/LLink'
       9              : import { CanvasPointer } from '@/lib/litegraph/src/CanvasPointer'
      10              : import {
      11              :   hasModifierKey,
      12              :   selectSlotLinks
      13              : } from '@/lib/litegraph/src/canvas/linkSelection'
      14              : import type { Reroute } from '@/lib/litegraph/src/Reroute'
      15              : import type { RenderLink } from '@/lib/litegraph/src/canvas/RenderLink'
      16              : import type {
      17              :   INodeInputSlot,
      18              :   INodeOutputSlot
      19              : } from '@comfyorg/graph-model/slots'
      20              : import { LinkDirection } from '@comfyorg/graph-model/globalEnums'
      21              : import {
      22              :   clearCanvasPointerHistory,
      23              :   toCanvasPointerEvent
      24              : } from '@/renderer/core/canvas/interaction/canvasPointerEvent'
      25              : import { createLinkConnectorAdapter } from '@/renderer/core/canvas/links/linkConnectorAdapter'
      26              : import type { LinkConnectorAdapter } from '@/renderer/core/canvas/links/linkConnectorAdapter'
      27              : import { getGraphSlotLayout } from '@/renderer/core/canvas/litegraph/slotCalculations'
      28              : import {
      29              :   resolveNodeSurfaceSlotCandidate,
      30              :   resolveSlotTargetCandidate
      31              : } from '@/renderer/core/canvas/links/linkDropOrchestrator'
      32              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      33              : import { isLinkRevealed } from '@/lib/litegraph/src/canvas/linkRevealState'
      34              : import { useSlotLinkDragUIState } from '@/renderer/core/canvas/links/slotLinkDragUIState'
      35              : import type { SlotDropCandidate } from '@/renderer/core/canvas/links/slotLinkDragUIState'
      36              : import { getSlotKey } from '@/renderer/core/layout/slots/slotIdentifier'
      37              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      38              : import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
      39              : import type { Point2D as Point } from '@comfyorg/shared-frontend-utils/geometry'
      40              : import { toPoint } from '@/renderer/core/layout/utils/geometry'
      41              : import { createSlotLinkDragContext } from '@/renderer/extensions/vueNodes/composables/slotLinkDragContext'
      42              : import { useSlotLinkReveal } from '@/renderer/extensions/vueNodes/composables/useSlotLinkReveal'
      43              : import { augmentToCanvasPointerEvent } from '@/renderer/extensions/vueNodes/utils/eventUtils'
      44              : import { app } from '@/scripts/app'
      45              : import { inputLink } from '@/lib/litegraph/src/node/slotLinks'
      46              : import { useLinkPresentationStore } from '@/stores/linkPresentationStore'
      47              : import { useLinkStore } from '@/stores/linkStore'
      48              : import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
      49              : import { UNASSIGNED_NODE_ID, toNodeId } from '@comfyorg/graph-model/nodeId'
      50              : import type { NodeId } from '@comfyorg/graph-model/nodeId'
      51              : import { createRafBatch } from '@/utils/rafBatch'
      52              : 
      53              : interface SlotInteractionOptions {
      54              :   nodeId?: NodeId
      55              :   index: number
      56              :   type: 'input' | 'output'
      57              : }
      58              : 
      59              : interface SlotInteractionHandlers {
      60              :   onClick: (event: PointerEvent) => void
      61              :   onDoubleClick: (event: PointerEvent) => void
      62              :   onPointerDown: (event: PointerEvent) => void
      63              : }
      64              : 
      65              : interface SlotPress {
      66              :   readonly client: Point
      67              :   readonly node: LGraphNode | undefined
      68              :   readonly withModifier: boolean
      69              : }
      70              : 
      71              : interface PointerSession {
      72              :   begin: (pointerId: number) => void
      73              :   register: (...stops: Array<Fn | null | undefined>) => void
      74              :   matches: (event: PointerEvent) => boolean
      75              :   isActive: () => boolean
      76              :   clear: () => void
      77              : }
      78              : 
      79        35695 : function createPointerSession(): PointerSession {
      80        35695 :   let pointerId: number | null = null
      81        35695 :   let stops: Fn[] = []
      82              : 
      83        35695 :   const begin = (id: number) => {
      84           65 :     pointerId = id
      85              :   }
      86              : 
      87        35695 :   const register = (...newStops: Array<Fn | null | undefined>) => {
      88           65 :     for (const stop of newStops) {
      89          195 :       if (typeof stop === 'function') {
      90          195 :         stops.push(stop)
      91              :       }
      92              :     }
      93              :   }
      94              : 
      95        35695 :   const matches = (event: PointerEvent) =>
      96              :     pointerId !== null && event.pointerId === pointerId
      97              : 
      98        35695 :   const isActive = () => pointerId !== null
      99              : 
     100        35695 :   const clear = () => {
     101           65 :     for (const stop of stops) {
     102          195 :       stop()
     103              :     }
     104           65 :     stops = []
     105           65 :     pointerId = null
     106              :   }
     107              : 
     108        35695 :   return { begin, register, matches, isActive, clear }
     109              : }
     110              : 
     111              : /**
     112              :  * Resolves the actual DOM element under the pointer position.
     113              :  *
     114              :  * On touch/mobile devices, pointer events have "implicit pointer capture" -
     115              :  * event.target stays as the element where the touch started, not the element
     116              :  * currently under the pointer. This helper uses document.elementFromPoint()
     117              :  * to get the actual element under the pointer, falling back to the provided
     118              :  * fallback target if elementFromPoint returns null.
     119              :  *
     120              :  * @param clientX - The client X coordinate of the pointer
     121              :  * @param clientY - The client Y coordinate of the pointer
     122              :  * @param fallback - Fallback target to use if elementFromPoint returns null
     123              :  * @returns The resolved target element
     124              :  */
     125          496 : export function resolvePointerTarget(
     126              :   clientX: number,
     127              :   clientY: number,
     128              :   fallback: EventTarget | null
     129              : ): EventTarget | null {
     130          496 :   return document.elementFromPoint(clientX, clientY) ?? fallback
     131              : }
     132              : 
     133            0 : export function isRerouteVisibleForLinkDrag(
     134              :   graph: Pick<LGraph, 'getLink' | 'id' | 'rootGraph'>,
     135              :   reroute: Pick<Reroute, 'linkIds' | 'floatingLinkIds'>
     136              : ): boolean {
     137            0 :   if (reroute.linkIds.size === 0 || reroute.floatingLinkIds.size > 0)
     138            0 :     return true
     139              : 
     140            0 :   const scope = graphScopeOf(graph)
     141            0 :   for (const linkId of reroute.linkIds) {
     142              :     const link = graph.getLink(linkId)
     143              :     const hidden =
     144              :       link && useLinkPresentationStore().getPresentation(scope, linkId)?.hidden
     145            0 :     if (!hidden || isLinkRevealed(scope.rootGraphId, linkId)) {
     146            0 :       return true
     147              :     }
     148              :   }
     149            0 :   return false
     150              : }
     151              : 
     152        35695 : export function useSlotLinkInteraction({
     153              :   nodeId,
     154              :   index,
     155              :   type
     156              : }: SlotInteractionOptions): SlotInteractionHandlers {
     157        35695 :   const {
     158              :     state,
     159              :     beginDrag,
     160              :     endDrag,
     161              :     updatePointerPosition,
     162              :     setCandidate,
     163              :     setCompatibleForKey,
     164              :     clearCompatible
     165              :   } = useSlotLinkDragUIState()
     166        35695 :   const canvasStore = useCanvasStore()
     167        35695 :   const conversion = useSharedCanvasPositionConversion()
     168        35695 :   const pointerSession = createPointerSession()
     169        35695 :   let activeAdapter: LinkConnectorAdapter | null = null
     170        35695 :   let autoPan: AutoPanController | null = null
     171        35695 :   let press: SlotPress | null = null
     172        35695 :   let hasDragged = false
     173              : 
     174        35695 :   const latchDragPastClickDrift = (event: PointerEvent) => {
     175          499 :     if (hasDragged || !press) return
     176           68 :     hasDragged =
     177              :       Math.hypot(
     178              :         event.clientX - press.client.x,
     179              :         event.clientY - press.client.y
     180              :       ) > CanvasPointer.maxClickDrift
     181              :   }
     182              : 
     183        35695 :   const isSlotClick = (event: PointerEvent) => {
     184           65 :     latchDragPastClickDrift(event)
     185           65 :     return press !== null && !hasDragged && !press.withModifier
     186              :   }
     187              : 
     188        35695 :   const selectClickedSlotLinks = (node: LGraphNode | undefined) => {
     189            2 :     const { graph } = app.canvas
     190            2 :     if (!graph || !node) return
     191            2 :     const layout = getGraphSlotLayout(graph, node.id, index, type === 'input')
     192            2 :     if (!layout) return
     193            2 :     selectSlotLinks(app.canvas, node, type, index, layout.position)
     194              :   }
     195              : 
     196              :   // Per-drag drag-state context (non-reactive caches + RAF batching)
     197        35695 :   const dragContext = createSlotLinkDragContext()
     198        35695 :   const dragReveal = useSlotLinkReveal({ nodeId, index, type, kind: 'drag' })
     199              : 
     200        35695 :   const resolveRenderLinkSource = (link: RenderLink): Point | null => {
     201          504 :     if (link.fromReroute) {
     202           22 :       const graphId = app.canvas.graph?.rootGraph.id
     203           22 :       const rerouteLayout = graphId
     204              :         ? layoutStore.getRerouteLayout(graphId, link.fromReroute.id)
     205              :         : null
     206           22 :       if (rerouteLayout) return rerouteLayout.position
     207            0 :       const [x, y] = link.fromReroute.pos
     208            0 :       return toPoint(x, y)
     209              :     }
     210              : 
     211          482 :     const nodeId = link.node.id
     212          482 :     const isInputFrom = link.toType === 'output'
     213          482 :     const graph = app.canvas.graph
     214          504 :     const layout = graph
     215              :       ? getGraphSlotLayout(graph, nodeId, link.fromSlotIndex, isInputFrom)
     216              :       : null
     217          504 :     if (layout) return layout.position
     218              : 
     219           14 :     const pos = link.fromPos
     220           14 :     return toPoint(pos[0], pos[1])
     221              :   }
     222              : 
     223        35695 :   const syncRenderLinkOrigins = () => {
     224          498 :     if (!activeAdapter) return
     225          498 :     for (const link of activeAdapter.renderLinks) {
     226          504 :       const origin = resolveRenderLinkSource(link)
     227          504 :       if (!origin) continue
     228          504 :       const x = origin.x
     229          504 :       const y = origin.y
     230          504 :       if (link.fromPos[0] !== x || link.fromPos[1] !== y) {
     231            0 :         link.fromPos[0] = x
     232            0 :         link.fromPos[1] = y
     233              :       }
     234              :     }
     235              :   }
     236              : 
     237            0 :   function hasCanConnectToReroute(
     238              :     link: RenderLink
     239              :   ): link is RenderLink & { canConnectToReroute: (r: Reroute) => boolean } {
     240            0 :     return 'canConnectToReroute' in link
     241              :   }
     242              : 
     243              :   type ToInputLink = RenderLink & { toType: 'input' }
     244              :   type ToOutputLink = RenderLink & { toType: 'output' }
     245        35695 :   const isToInputLink = (link: RenderLink): link is ToInputLink =>
     246              :     link.toType === 'input'
     247        35695 :   const isToOutputLink = (link: RenderLink): link is ToOutputLink =>
     248              :     link.toType === 'output'
     249              : 
     250           39 :   function connectLinksToInput(
     251              :     links: ReadonlyArray<RenderLink>,
     252              :     node: LGraphNode,
     253              :     inputSlot: INodeInputSlot
     254              :   ): boolean {
     255           39 :     const validCandidates = links
     256              :       .filter(isToInputLink)
     257              :       .filter((link) => link.canConnectToInput(node, inputSlot))
     258              : 
     259           39 :     for (const link of validCandidates) {
     260           39 :       link.connectToInput(node, inputSlot, activeAdapter?.linkConnector.events)
     261              :     }
     262              : 
     263           39 :     return validCandidates.length > 0
     264              :   }
     265              : 
     266            2 :   function connectLinksToOutput(
     267              :     links: ReadonlyArray<RenderLink>,
     268              :     node: LGraphNode,
     269              :     outputSlot: INodeOutputSlot
     270              :   ): boolean {
     271            2 :     const validCandidates = links
     272              :       .filter(isToOutputLink)
     273              :       .filter((link) => link.canConnectToOutput(node, outputSlot))
     274              : 
     275            2 :     for (const link of validCandidates) {
     276            2 :       link.connectToOutput(
     277              :         node,
     278              :         outputSlot,
     279              :         activeAdapter?.linkConnector.events
     280              :       )
     281              :     }
     282              : 
     283            2 :     return validCandidates.length > 0
     284              :   }
     285              : 
     286        35695 :   const resolveLinkOrigin = (
     287              :     link: LLink | undefined
     288              :   ): { position: Point; direction: LinkDirection } | null => {
     289            9 :     if (!link) return null
     290            9 :     if (link.origin_id === UNASSIGNED_NODE_ID) return null
     291              : 
     292            9 :     const graph = app.canvas.graph
     293            9 :     const layout = graph
     294              :       ? getGraphSlotLayout(graph, link.origin_id, link.origin_slot, false)
     295              :       : null
     296            9 :     if (!layout) return null
     297              : 
     298            6 :     return { position: { ...layout.position }, direction: LinkDirection.NONE }
     299              :   }
     300              : 
     301        35695 :   const resolveExistingInputLinkAnchor = (
     302              :     graph: LGraph,
     303              :     nodeId: NodeId,
     304              :     slotIndex: number,
     305              :     inputSlot: INodeInputSlot | undefined
     306              :   ): { position: Point; direction: LinkDirection } | null => {
     307           15 :     if (!inputSlot) return null
     308              : 
     309           15 :     const directLink = inputLink(graph, nodeId, slotIndex)
     310           15 :     if (directLink) {
     311              :       const reroutes = LLink.getReroutes(graph, directLink)
     312           10 :       const lastReroute = reroutes.at(-1)
     313           10 :       if (lastReroute) {
     314            1 :         const rerouteLayout = layoutStore.getRerouteLayout(
     315              :           graph.rootGraph.id,
     316              :           lastReroute.id
     317              :         )
     318            1 :         if (rerouteLayout) {
     319            1 :           return {
     320              :             position: { ...rerouteLayout.position },
     321              :             direction: LinkDirection.NONE
     322              :           }
     323              :         }
     324              : 
     325            0 :         const pos = lastReroute.pos
     326            0 :         return {
     327              :           position: toPoint(pos[0], pos[1]),
     328              :           direction: LinkDirection.NONE
     329              :         }
     330              :       }
     331              : 
     332            9 :       const directAnchor = resolveLinkOrigin(directLink)
     333            9 :       if (directAnchor) return directAnchor
     334              :     }
     335              : 
     336            8 :     const floatingLink = slotFloatingLinks(
     337              :       graph,
     338              :       'input',
     339              :       nodeId,
     340              :       slotIndex
     341              :     ).at(0)
     342            8 :     if (!floatingLink) return null
     343              : 
     344            0 :     if (floatingLink.parentId != null) {
     345            0 :       const rerouteLayout = layoutStore.getRerouteLayout(
     346              :         graph.rootGraph.id,
     347              :         floatingLink.parentId
     348              :       )
     349            0 :       if (rerouteLayout) {
     350            0 :         return {
     351              :           position: { ...rerouteLayout.position },
     352              :           direction: LinkDirection.NONE
     353              :         }
     354              :       }
     355              : 
     356            0 :       const reroute = graph.getReroute(floatingLink.parentId)
     357            0 :       if (reroute) {
     358            0 :         return {
     359              :           position: toPoint(reroute.pos[0], reroute.pos[1]),
     360              :           direction: LinkDirection.NONE
     361              :         }
     362              :       }
     363              :     }
     364              : 
     365            0 :     return null
     366              :   }
     367              : 
     368        35695 :   const cleanupInteraction = () => {
     369           65 :     autoPan?.stop()
     370           65 :     autoPan = null
     371           65 :     if (state.pointerId != null) {
     372           65 :       clearCanvasPointerHistory(state.pointerId)
     373              :     }
     374           65 :     activeAdapter?.reset()
     375           65 :     pointerSession.clear()
     376           65 :     press = null
     377           65 :     hasDragged = false
     378           65 :     endDrag()
     379           65 :     activeAdapter = null
     380           65 :     raf.cancel()
     381           65 :     dragContext.dispose()
     382           65 :     dragReveal.unrevealLinks()
     383           65 :     clearCompatible()
     384              :   }
     385              : 
     386        35695 :   const updatePointerState = (event: PointerEvent) => {
     387           65 :     const clientX = event.clientX
     388           65 :     const clientY = event.clientY
     389           65 :     const [canvasX, canvasY] = conversion.clientPosToCanvasPos([
     390              :       clientX,
     391              :       clientY
     392              :     ])
     393              : 
     394           65 :     updatePointerPosition(clientX, clientY, canvasX, canvasY)
     395              :   }
     396              : 
     397        35695 :   const processPointerMoveFrame = () => {
     398          433 :     const data = dragContext.pendingPointerMove
     399          433 :     if (!data) return
     400          433 :     dragContext.pendingPointerMove = null
     401              : 
     402          433 :     const [canvasX, canvasY] = conversion.clientPosToCanvasPos([
     403              :       data.clientX,
     404              :       data.clientY
     405              :     ])
     406          433 :     updatePointerPosition(data.clientX, data.clientY, canvasX, canvasY)
     407              : 
     408          433 :     syncRenderLinkOrigins()
     409              : 
     410          433 :     let hoveredSlotKey: string | null = null
     411          433 :     let hoveredNodeId: NodeId | null = null
     412          433 :     const target = resolvePointerTarget(data.clientX, data.clientY, data.target)
     413          433 :     if (target === dragContext.lastPointerEventTarget) {
     414          284 :       hoveredSlotKey = dragContext.lastPointerTargetSlotKey
     415          284 :       hoveredNodeId = dragContext.lastPointerTargetNodeId
     416          149 :     } else if (target instanceof HTMLElement) {
     417          148 :       const elWithSlot = target
     418              :         .closest('.lg-slot, .lg-node-widget')
     419              :         ?.querySelector<HTMLElement>('[data-slot-key]')
     420          148 :       const elWithNode = target.closest<HTMLElement>('[data-node-id]')
     421          148 :       hoveredSlotKey = elWithSlot?.dataset['slotKey'] ?? null
     422          148 :       hoveredNodeId = elWithNode?.dataset['nodeId']
     423              :         ? toNodeId(elWithNode.dataset['nodeId'])
     424              :         : null
     425          148 :       dragContext.lastPointerEventTarget = target
     426          148 :       dragContext.lastPointerTargetSlotKey = hoveredSlotKey
     427          148 :       dragContext.lastPointerTargetNodeId = hoveredNodeId
     428              :     }
     429              : 
     430          433 :     const hoverChanged =
     431              :       hoveredSlotKey !== dragContext.lastHoverSlotKey ||
     432              :       hoveredNodeId !== dragContext.lastHoverNodeId
     433              : 
     434          433 :     let candidate: SlotDropCandidate | null = state.candidate
     435              : 
     436          433 :     if (hoverChanged) {
     437              :       const adapter = activeAdapter
     438              :       const graph = app.canvas.graph ?? null
     439          104 :       const context = { adapter, graph, session: dragContext }
     440          104 :       const slotCandidate = resolveSlotTargetCandidate(target, context)
     441          104 :       const nodeCandidate = resolveNodeSurfaceSlotCandidate(target, context)
     442          104 :       candidate = slotCandidate?.compatible ? slotCandidate : nodeCandidate
     443          104 :       dragContext.lastHoverSlotKey = hoveredSlotKey
     444          104 :       dragContext.lastHoverNodeId = hoveredNodeId
     445              : 
     446          104 :       if (slotCandidate) {
     447           70 :         const key = getSlotKey(
     448              :           slotCandidate.layout.nodeId,
     449              :           slotCandidate.layout.index,
     450              :           slotCandidate.layout.type === 'input'
     451              :         )
     452           70 :         setCompatibleForKey(key, slotCandidate.compatible)
     453              :       }
     454          104 :       if (nodeCandidate && !slotCandidate?.compatible) {
     455           23 :         const key = getSlotKey(
     456              :           nodeCandidate.layout.nodeId,
     457              :           nodeCandidate.layout.index,
     458              :           nodeCandidate.layout.type === 'input'
     459              :         )
     460           23 :         setCompatibleForKey(key, nodeCandidate.compatible)
     461              :       }
     462              :     }
     463              : 
     464          433 :     const newCandidate = candidate?.compatible ? candidate : null
     465          433 :     const newCandidateKey = newCandidate
     466              :       ? getSlotKey(
     467              :           newCandidate.layout.nodeId,
     468              :           newCandidate.layout.index,
     469              :           newCandidate.layout.type === 'input'
     470              :         )
     471              :       : null
     472              : 
     473          433 :     const candidateChanged = newCandidateKey !== dragContext.lastCandidateKey
     474          433 :     if (candidateChanged) {
     475           68 :       setCandidate(newCandidate)
     476           68 :       dragContext.lastCandidateKey = newCandidateKey
     477              :     }
     478              : 
     479          433 :     let snapPosChanged = false
     480          433 :     if (activeAdapter) {
     481          433 :       const snapX = newCandidate
     482              :         ? newCandidate.layout.position.x
     483              :         : state.pointer.canvas.x
     484          433 :       const snapY = newCandidate
     485              :         ? newCandidate.layout.position.y
     486              :         : state.pointer.canvas.y
     487          433 :       const currentSnap = activeAdapter.linkConnector.state.snapLinksPos
     488          433 :       snapPosChanged =
     489              :         !currentSnap || currentSnap[0] !== snapX || currentSnap[1] !== snapY
     490          433 :       if (snapPosChanged) {
     491          349 :         activeAdapter.linkConnector.state.snapLinksPos = [snapX, snapY]
     492              :       }
     493              :     }
     494              : 
     495              :     const shouldRedraw = candidateChanged || snapPosChanged
     496          433 :     if (shouldRedraw) app.canvas.setDirty(true, true)
     497              :   }
     498        35695 :   const raf = createRafBatch(processPointerMoveFrame)
     499              : 
     500        35695 :   const canvas = app.canvas
     501        35695 :   const node = nodeId ? canvas.graph?.getNodeById(nodeId) : null
     502        35695 :   const handlePointerMove = (event: PointerEvent) => {
     503          434 :     if (!pointerSession.matches(event)) return
     504          434 :     latchDragPastClickDrift(event)
     505          434 :     if (canvasStore.isReadOnly) {
     506            1 :       autoPan?.stop()
     507            1 :       return
     508              :     }
     509              : 
     510          433 :     event.stopPropagation()
     511              : 
     512          433 :     app.canvas.last_mouse = [event.clientX, event.clientY]
     513          434 :     autoPan?.updatePointer(event.clientX, event.clientY)
     514          434 :     if (hasDragged) autoPan?.start()
     515              : 
     516          434 :     if (canvas.subgraph && node) {
     517           15 :       augmentToCanvasPointerEvent(event, node, canvas)
     518           15 :       canvas.subgraph.inputNode.onPointerMove(event)
     519           15 :       canvas.subgraph.outputNode.onPointerMove(event)
     520              :     }
     521              : 
     522          433 :     dragContext.pendingPointerMove = {
     523              :       clientX: event.clientX,
     524              :       clientY: event.clientY,
     525              :       target: event.target
     526              :     }
     527          433 :     raf.schedule()
     528              :   }
     529              : 
     530              :   // Attempt to finalize by connecting to a DOM slot candidate
     531        35695 :   const tryConnectToCandidate = (
     532              :     candidate: SlotDropCandidate | null
     533              :   ): boolean => {
     534          107 :     if (!candidate?.compatible) return false
     535           41 :     const graph = app.canvas.graph
     536           41 :     const adapter = activeAdapter
     537          107 :     if (!graph || !adapter) return false
     538              : 
     539           41 :     const nodeId: NodeId = candidate.layout.nodeId
     540           41 :     const targetNode = graph.getNodeById(nodeId)
     541           59 :     if (!targetNode) return false
     542              : 
     543           41 :     if (candidate.layout.type === 'input') {
     544           39 :       const inputSlot = targetNode.inputs.at(candidate.layout.index)
     545           39 :       return (
     546              :         !!inputSlot &&
     547              :         connectLinksToInput(adapter.renderLinks, targetNode, inputSlot)
     548              :       )
     549              :     }
     550              : 
     551            2 :     const outputSlot = targetNode.outputs.at(candidate.layout.index)
     552          107 :     return (
     553              :       !!outputSlot &&
     554              :       connectLinksToOutput(adapter.renderLinks, targetNode, outputSlot)
     555              :     )
     556              :   }
     557              : 
     558              :   // Attempt to finalize by dropping on a reroute under the pointer
     559        35695 :   const tryConnectViaRerouteAtPointer = (): boolean => {
     560           22 :     const graph = app.canvas.graph
     561           22 :     const adapter = activeAdapter
     562           22 :     if (!graph || !adapter) return false
     563              : 
     564           22 :     const rerouteLayout = layoutStore.queryRerouteAtPoint(graph.rootGraph.id, {
     565              :       x: state.pointer.canvas.x,
     566              :       y: state.pointer.canvas.y
     567              :     })
     568           22 :     if (!rerouteLayout) return false
     569              : 
     570            0 :     const reroute = graph.getReroute(rerouteLayout.id)
     571           22 :     if (
     572              :       !reroute ||
     573              :       !isRerouteVisibleForLinkDrag(graph, reroute) ||
     574              :       !adapter.isRerouteValidDrop(reroute.id)
     575              :     ) {
     576            0 :       return false
     577              :     }
     578              : 
     579            0 :     let didConnect = false
     580              : 
     581           22 :     const results = reroute.findTargetInputs() ?? []
     582           22 :     const maybeReroutes = reroute.getReroutes()
     583           22 :     if (results.length && maybeReroutes !== null) {
     584            0 :       const originalReroutes = maybeReroutes.slice(0, -1).reverse()
     585            0 :       for (const link of adapter.renderLinks) {
     586            0 :         if (!isToInputLink(link)) continue
     587            0 :         for (const result of results) {
     588            0 :           link.connectToRerouteInput(
     589              :             reroute,
     590              :             result,
     591              :             adapter.linkConnector.events,
     592              :             originalReroutes
     593              :           )
     594            0 :           didConnect = true
     595              :         }
     596              :       }
     597              :     }
     598              : 
     599            0 :     const sourceOutput = reroute.findSourceOutput()
     600            0 :     if (sourceOutput) {
     601            0 :       const { node, output } = sourceOutput
     602            0 :       for (const link of adapter.renderLinks) {
     603            0 :         if (!isToOutputLink(link)) continue
     604            0 :         if (hasCanConnectToReroute(link) && !link.canConnectToReroute(reroute))
     605            0 :           continue
     606            0 :         link.connectToRerouteOutput(
     607              :           reroute,
     608              :           node,
     609              :           output,
     610              :           adapter.linkConnector.events
     611              :         )
     612            0 :         didConnect = true
     613              :       }
     614              :     }
     615              : 
     616            0 :     return didConnect
     617              :   }
     618              : 
     619        35695 :   const finishInteraction = (event: PointerEvent) => {
     620           65 :     if (!pointerSession.matches(event)) return
     621           65 :     const canvasEvent = toCanvasPointerEvent(event)
     622           65 :     canvasEvent.preventDefault()
     623              : 
     624           65 :     raf.flush()
     625              : 
     626           65 :     if (isSlotClick(event)) {
     627            2 :       const pressedNode = press?.node
     628            2 :       cleanupInteraction()
     629            2 :       selectClickedSlotLinks(pressedNode)
     630            2 :       app.canvas.setDirty(true, true)
     631            2 :       useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
     632            2 :       return
     633              :     }
     634              : 
     635           63 :     if (!state.source) {
     636            0 :       cleanupInteraction()
     637            0 :       app.canvas.setDirty(true, true)
     638            0 :       return
     639              :     }
     640              : 
     641           65 :     const snappedCandidate = state.candidate?.compatible
     642              :       ? state.candidate
     643              :       : null
     644              : 
     645           65 :     const dropTarget = resolvePointerTarget(
     646              :       event.clientX,
     647              :       event.clientY,
     648              :       canvasEvent.target
     649              :     )
     650              :     const hasConnected = connectByPriority(dropTarget, snappedCandidate)
     651              : 
     652           65 :     if (!hasConnected && dropTarget === app.canvas.canvas) {
     653           17 :       activeAdapter?.dropOnCanvas(canvasEvent)
     654              :     }
     655              : 
     656           63 :     cleanupInteraction()
     657           63 :     app.canvas.setDirty(true, true)
     658           65 :     useWorkflowStore().activeWorkflow?.changeTracker.captureCanvasState()
     659              :   }
     660              : 
     661        35695 :   const handlePointerUp = (event: PointerEvent) => {
     662           65 :     event.stopPropagation()
     663           65 :     finishInteraction(event)
     664              :   }
     665              : 
     666        35695 :   const handlePointerCancel = (event: PointerEvent) => {
     667            0 :     if (!pointerSession.matches(event)) return
     668              : 
     669            0 :     raf.flush()
     670            0 :     toCanvasPointerEvent(event)
     671            0 :     cleanupInteraction()
     672            0 :     app.canvas.setDirty(true, true)
     673              :   }
     674              : 
     675           63 :   function connectByPriority(
     676              :     target: EventTarget | null,
     677              :     snappedCandidate: SlotDropCandidate | null
     678              :   ): boolean {
     679              :     const adapter = activeAdapter
     680              :     const graph = app.canvas.graph ?? null
     681           63 :     const context = { adapter, graph, session: dragContext }
     682              : 
     683           63 :     const domSlotCandidate = resolveSlotTargetCandidate(target, context)
     684           63 :     const nodeSurfaceSlotCandidate = resolveNodeSurfaceSlotCandidate(
     685              :       target,
     686              :       context
     687              :     )
     688              : 
     689           63 :     return (
     690              :       tryConnectToCandidate(snappedCandidate) ||
     691              :       tryConnectToCandidate(domSlotCandidate) ||
     692              :       tryConnectToCandidate(nodeSurfaceSlotCandidate) ||
     693              :       tryConnectViaRerouteAtPointer()
     694              :     )
     695              :   }
     696              : 
     697        35695 :   const onPointerDown = (event: PointerEvent) => {
     698           66 :     if (event.button !== 0) return
     699           66 :     if (!nodeId) return
     700           66 :     if (pointerSession.isActive()) return
     701           66 :     event.preventDefault()
     702           66 :     event.stopPropagation()
     703              : 
     704           66 :     const canvas = app.canvas
     705           66 :     const graph = canvas.graph
     706           66 :     if (!graph) return
     707              : 
     708           66 :     activeAdapter = createLinkConnectorAdapter()
     709           66 :     if (!activeAdapter) return
     710           66 :     raf.cancel()
     711           66 :     dragContext.reset()
     712              : 
     713           66 :     const layout = getGraphSlotLayout(graph, nodeId, index, type === 'input')
     714           66 :     if (!layout) return
     715              : 
     716           66 :     const localNodeId: NodeId = nodeId
     717           66 :     const isInputSlot = type === 'input'
     718           66 :     const isOutputSlot = type === 'output'
     719              : 
     720           66 :     const resolvedNode = graph.getNodeById(localNodeId)
     721           66 :     const inputSlot = isInputSlot ? resolvedNode?.inputs[index] : undefined
     722           66 :     const outputSlot = isOutputSlot ? resolvedNode?.outputs[index] : undefined
     723              : 
     724           66 :     const ctrlOrMeta = event.ctrlKey || event.metaKey
     725              : 
     726           66 :     const existingInputLink = isInputSlot
     727              :       ? inputLink(graph, localNodeId, index)
     728              :       : undefined
     729           66 :     const inputFloatingCount = isInputSlot
     730              :       ? slotFloatingLinks(graph, 'input', localNodeId, index).length
     731              :       : 0
     732           66 :     const hasExistingInputLink =
     733              :       existingInputLink !== undefined || inputFloatingCount > 0
     734              : 
     735           66 :     const hasExistingOutputLink =
     736              :       isOutputSlot &&
     737              :       (useLinkStore().isOutputSlotConnected(
     738              :         graphScopeOf(graph),
     739              :         localNodeId,
     740              :         index
     741              :       ) ||
     742              :         slotFloatingLinks(graph, 'output', localNodeId, index).length > 0)
     743              : 
     744           66 :     const shouldBreakExistingInputLink =
     745              :       isInputSlot &&
     746              :       hasExistingInputLink &&
     747              :       ctrlOrMeta &&
     748              :       event.altKey &&
     749              :       !event.shiftKey
     750              : 
     751           66 :     const shouldBatchDisconnectOutputLinks =
     752              :       isOutputSlot &&
     753              :       hasExistingOutputLink &&
     754              :       ctrlOrMeta &&
     755              :       event.altKey &&
     756              :       !event.shiftKey
     757              : 
     758           66 :     if (shouldBreakExistingInputLink && resolvedNode) {
     759            2 :       resolvedNode.disconnectInput(index, true)
     760              :     }
     761              : 
     762           66 :     if (shouldBatchDisconnectOutputLinks && resolvedNode) {
     763            1 :       resolvedNode.disconnectOutput(index)
     764            1 :       canvas.setDirty(true, true)
     765            1 :       event.preventDefault()
     766            1 :       event.stopPropagation()
     767            1 :       return
     768              :     }
     769              : 
     770           66 :     const baseDirection = isInputSlot
     771              :       ? (inputSlot?.dir ?? LinkDirection.LEFT)
     772              :       : (outputSlot?.dir ?? LinkDirection.RIGHT)
     773              : 
     774           66 :     const existingAnchor =
     775              :       isInputSlot && !shouldBreakExistingInputLink
     776              :         ? resolveExistingInputLinkAnchor(graph, localNodeId, index, inputSlot)
     777              :         : null
     778              : 
     779           66 :     const shouldMoveExistingOutput =
     780              :       isOutputSlot && event.shiftKey && hasExistingOutputLink
     781              : 
     782           66 :     const shouldMoveExistingInput =
     783              :       isInputSlot && !shouldBreakExistingInputLink && hasExistingInputLink
     784              : 
     785           66 :     const wasConnecting = activeAdapter.linkConnector.isConnecting
     786           66 :     if (isOutputSlot) {
     787           48 :       activeAdapter.beginFromOutput(localNodeId, index, {
     788              :         moveExisting: shouldMoveExistingOutput
     789              :       })
     790              :     } else {
     791           17 :       activeAdapter.beginFromInput(localNodeId, index, {
     792              :         moveExisting: shouldMoveExistingInput,
     793              :         layout
     794              :       })
     795              :     }
     796              : 
     797           66 :     if (!wasConnecting && activeAdapter.linkConnector.isConnecting) {
     798           65 :       dragReveal.revealLinks()
     799           65 :       const { linkConnector } = activeAdapter
     800           65 :       linkConnector.events.addEventListener(
     801              :         'reset',
     802              :         () =>
     803              :           queueMicrotask(() => {
     804           65 :             if (!linkConnector.isConnecting) dragReveal.unrevealLinks()
     805              :           }),
     806              :         { once: true }
     807              :       )
     808              :     }
     809              : 
     810           66 :     if (shouldMoveExistingInput && existingInputLink) {
     811           10 :       existingInputLink._dragging = true
     812              :     }
     813              : 
     814           65 :     syncRenderLinkOrigins()
     815              : 
     816           66 :     const direction = existingAnchor?.direction ?? baseDirection
     817           66 :     const startPosition = existingAnchor?.position ?? {
     818              :       x: layout.position.x,
     819              :       y: layout.position.y
     820              :     }
     821              : 
     822           66 :     beginDrag(
     823              :       {
     824              :         nodeId,
     825              :         slotIndex: index,
     826              :         type,
     827              :         direction,
     828              :         position: startPosition,
     829              :         linkId: !shouldBreakExistingInputLink
     830              :           ? existingInputLink?.id
     831              :           : undefined,
     832              :         movingExistingOutput: shouldMoveExistingOutput
     833              :       },
     834              :       event.pointerId
     835              :     )
     836              : 
     837           66 :     pointerSession.begin(event.pointerId)
     838           66 :     press = {
     839              :       client: { x: event.clientX, y: event.clientY },
     840              :       node: resolvedNode ?? undefined,
     841              :       withModifier: hasModifierKey(event)
     842              :     }
     843              : 
     844           66 :     toCanvasPointerEvent(event)
     845           66 :     updatePointerState(event)
     846              : 
     847           66 :     activeAdapter.linkConnector.state.snapLinksPos = [
     848              :       state.pointer.canvas.x,
     849              :       state.pointer.canvas.y
     850              :     ]
     851              : 
     852           66 :     pointerSession.register(
     853              :       useEventListener('pointermove', handlePointerMove, {
     854              :         capture: true
     855              :       }),
     856              :       useEventListener('pointerup', handlePointerUp, {
     857              :         capture: true
     858              :       }),
     859              :       useEventListener('pointercancel', handlePointerCancel, {
     860              :         capture: true
     861              :       })
     862              :     )
     863           66 :     const targetType: 'input' | 'output' = type === 'input' ? 'output' : 'input'
     864           66 :     clearCompatible()
     865           66 :     for (const candidateNode of graph.nodes) {
     866          232 :       const slots =
     867              :         targetType === 'input' ? candidateNode.inputs : candidateNode.outputs
     868          232 :       for (const [slotIndex] of slots.entries()) {
     869          682 :         const key = getSlotKey(
     870              :           candidateNode.id,
     871              :           slotIndex,
     872              :           targetType === 'input'
     873              :         )
     874          682 :         const compatible =
     875              :           targetType === 'input'
     876              :             ? activeAdapter.isInputValidDrop(candidateNode.id, slotIndex)
     877              :             : activeAdapter.isOutputValidDrop(candidateNode.id, slotIndex)
     878          682 :         setCompatibleForKey(key, compatible)
     879              :       }
     880              :     }
     881           65 :     autoPan = new AutoPanController({
     882              :       canvas,
     883              :       maxPanSpeed: canvas.auto_pan_speed,
     884              :       onPan: () => {
     885            0 :         const [canvasX, canvasY] = conversion.clientPosToCanvasPos([
     886              :           state.pointer.client.x,
     887              :           state.pointer.client.y
     888              :         ])
     889            0 :         updatePointerPosition(
     890              :           state.pointer.client.x,
     891              :           state.pointer.client.y,
     892              :           canvasX,
     893              :           canvasY
     894              :         )
     895            0 :         if (activeAdapter) {
     896            0 :           activeAdapter.linkConnector.state.snapLinksPos = [canvasX, canvasY]
     897              :         }
     898            0 :         canvas.setDirty(true, true)
     899              :       }
     900              :     })
     901           65 :     autoPan.updatePointer(event.clientX, event.clientY)
     902              : 
     903           65 :     canvas.setDirty(true, true)
     904              :   }
     905              : 
     906        35695 :   tryOnScopeDispose(() => {
     907        23666 :     if (pointerSession.isActive()) {
     908            0 :       cleanupInteraction()
     909              :     }
     910              :   })
     911              : 
     912            0 :   function onDoubleClick(e: PointerEvent) {
     913            0 :     if (!nodeId) return
     914            0 :     const { graph } = app.canvas
     915            0 :     if (!graph) return
     916            0 :     const node = graph.getNodeById(nodeId)
     917            0 :     if (!node) return
     918            0 :     augmentToCanvasPointerEvent(e, node, app.canvas)
     919            0 :     node.onInputDblClick?.(index, e)
     920              :   }
     921            4 :   function onClick(e: PointerEvent) {
     922            4 :     if (!nodeId) return
     923            4 :     const { graph } = app.canvas
     924            4 :     if (!graph) return
     925            4 :     const node = graph.getNodeById(nodeId)
     926            4 :     if (!node) return
     927            4 :     augmentToCanvasPointerEvent(e, node, app.canvas)
     928            4 :     node.onInputClick?.(index, e)
     929              :   }
     930              : 
     931        35695 :   return {
     932              :     onClick,
     933              :     onDoubleClick,
     934              :     onPointerDown
     935              :   }
     936              : }
        

Generated by: LCOV version 2.0-1