LCOV - code coverage report
Current view: top level - src/renderer/core/canvas/litegraph - litegraphLinkAdapter.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 72.7 % 99 72
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { LLink, Reroute } from '@comfyorg/graph-model/entityRegistry'
       2              : /**
       3              :  * Litegraph Link Adapter
       4              :  *
       5              :  * Bridges the gap between litegraph's data model and the pure canvas renderer.
       6              :  * Converts litegraph-specific types (LLink, LGraphNode, slots) into generic
       7              :  * rendering data that can be consumed by the PathRenderer.
       8              :  * Maintains backward compatibility with existing litegraph integration.
       9              :  */
      10              : 
      11              : import type { CanvasColour } from '@comfyorg/graph-model/interfaces'
      12              : import type {
      13              :   PointTuple as Point,
      14              :   Point2D as PointObj,
      15              :   Bounds
      16              : } from '@comfyorg/shared-frontend-utils/geometry'
      17              : import { litegraph } from '@/lib/litegraph/src/litegraphInstance'
      18              : import {
      19              :   LinkDirection,
      20              :   LinkMarkerShape,
      21              :   LinkRenderType
      22              : } from '@comfyorg/graph-model/globalEnums'
      23              : import { CanvasPathRenderer } from '@/renderer/core/canvas/pathRenderer'
      24              : import type {
      25              :   ArrowShape,
      26              :   Direction,
      27              :   LinkRenderData,
      28              :   RenderContext as PathRenderContext,
      29              :   RenderMode
      30              : } from '@/renderer/core/canvas/pathRenderer'
      31              : import { setLinkPolyline } from '@/renderer/core/canvas/linkPolylines'
      32              : import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
      33              : 
      34              : export interface LinkRenderContext {
      35              :   // Canvas settings
      36              :   renderMode: LinkRenderType
      37              :   connectionWidth: number
      38              :   renderBorder: boolean
      39              :   lowQuality: boolean
      40              :   highQualityRender: boolean
      41              :   scale: number
      42              :   linkMarkerShape: LinkMarkerShape
      43              :   renderConnectionArrows: boolean
      44              : 
      45              :   // State
      46              :   highlightedLinks: Set<string | number>
      47              : 
      48              :   // Colors
      49              :   defaultLinkColor: CanvasColour
      50              :   linkTypeColors: Record<string, CanvasColour>
      51              : 
      52              :   // Pattern for disabled links (optional)
      53              :   disabledPattern?: CanvasPattern | null
      54              : }
      55              : 
      56         2356 : export class LitegraphLinkAdapter {
      57              :   private readonly pathRenderer = new CanvasPathRenderer()
      58              :   private readonly pathContexts = new WeakMap<
      59              :     LinkRenderContext,
      60              :     PathRenderContext
      61              :   >()
      62              : 
      63         2571 :   constructor(public readonly enableLayoutStoreWrites = true) {}
      64              : 
      65              :   private pathRenderContextFor(
      66              :     context: LinkRenderContext,
      67              :     skipBorder: boolean
      68              :   ): PathRenderContext {
      69       117266 :     const cached = this.pathContexts.get(context)
      70       117266 :     const pathContext = cached ?? this.convertToPathRenderContext(context)
      71       117266 :     if (!cached) this.pathContexts.set(context, pathContext)
      72              : 
      73       117266 :     pathContext.style.borderWidth =
      74              :       !skipBorder && context.renderBorder ? 4 : undefined
      75       117266 :     pathContext.animation = { time: litegraph().getTime() * 0.001 }
      76       117266 :     return pathContext
      77              :   }
      78              : 
      79              :   /**
      80              :    * Convert LinkDirection enum to Direction string
      81              :    */
      82              :   private convertDirection(dir: LinkDirection): Direction {
      83       234532 :     switch (dir) {
      84              :       case LinkDirection.LEFT:
      85       114666 :         return 'left'
      86              :       case LinkDirection.RIGHT:
      87       117050 :         return 'right'
      88              :       case LinkDirection.UP:
      89            0 :         return 'up'
      90              :       case LinkDirection.DOWN:
      91            0 :         return 'down'
      92              :       case LinkDirection.CENTER:
      93              :       case LinkDirection.NONE:
      94         2816 :         return 'none'
      95              :       default:
      96            0 :         return 'right'
      97              :     }
      98              :   }
      99              : 
     100              :   /**
     101              :    * Convert LinkRenderContext to PathRenderContext
     102              :    */
     103              :   private convertToPathRenderContext(
     104              :     context: LinkRenderContext
     105              :   ): PathRenderContext {
     106              :     // Match original arrow rendering conditions:
     107              :     // Arrows only render when scale >= 0.6 AND highquality_render AND render_connection_arrows
     108        18762 :     const shouldShowArrows =
     109              :       context.scale >= 0.6 &&
     110              :       context.highQualityRender &&
     111              :       context.renderConnectionArrows
     112              : 
     113              :     // Only show center marker when not set to None
     114        18762 :     const shouldShowCenterMarker =
     115              :       context.linkMarkerShape !== LinkMarkerShape.None
     116              : 
     117        18762 :     return {
     118              :       style: {
     119              :         mode: this.convertRenderMode(context.renderMode),
     120              :         connectionWidth: context.connectionWidth,
     121              :         borderWidth: context.renderBorder ? 4 : undefined,
     122              :         arrowShape: this.convertArrowShape(context.linkMarkerShape),
     123              :         showArrows: shouldShowArrows,
     124              :         lowQuality: context.lowQuality,
     125              :         // Center marker settings (matches original litegraph behavior)
     126              :         showCenterMarker: shouldShowCenterMarker,
     127              :         centerMarkerShape:
     128              :           context.linkMarkerShape === LinkMarkerShape.Arrow
     129              :             ? 'arrow'
     130              :             : 'circle',
     131              :         highQuality: context.highQualityRender
     132              :       },
     133              :       colors: {
     134              :         default: String(context.defaultLinkColor),
     135              :         byType: this.convertColorMap(context.linkTypeColors),
     136              :         highlighted: '#FFF'
     137              :       },
     138              :       patterns: {
     139              :         disabled: context.disabledPattern
     140              :       },
     141              :       animation: {
     142              :         time: litegraph().getTime() * 0.001
     143              :       },
     144              :       scale: context.scale,
     145              :       highlightedIds: new Set(Array.from(context.highlightedLinks).map(String))
     146              :     }
     147              :   }
     148              : 
     149              :   /**
     150              :    * Convert LinkRenderType to RenderMode
     151              :    */
     152              :   private convertRenderMode(mode: LinkRenderType): RenderMode {
     153        18762 :     switch (mode) {
     154              :       case LinkRenderType.LINEAR_LINK:
     155            0 :         return 'linear'
     156              :       case LinkRenderType.STRAIGHT_LINK:
     157            0 :         return 'straight'
     158              :       case LinkRenderType.SPLINE_LINK:
     159              :       default:
     160        18762 :         return 'spline'
     161              :     }
     162              :   }
     163              : 
     164              :   /**
     165              :    * Convert LinkMarkerShape to ArrowShape
     166              :    */
     167              :   private convertArrowShape(shape: LinkMarkerShape): ArrowShape {
     168        18762 :     switch (shape) {
     169              :       case LinkMarkerShape.Circle:
     170        16267 :         return 'circle'
     171              :       case LinkMarkerShape.Arrow:
     172              :       default:
     173         2495 :         return 'triangle'
     174              :     }
     175              :   }
     176              : 
     177              :   /**
     178              :    * Convert color map to ensure all values are strings
     179              :    */
     180              :   private convertColorMap(
     181              :     colors: Record<string, CanvasColour>
     182              :   ): Record<string, string> {
     183        18762 :     const result: Record<string, string> = {}
     184        18762 :     for (const [key, value] of Object.entries(colors)) {
     185      2286927 :       result[key] = String(value)
     186              :     }
     187        18762 :     return result
     188              :   }
     189              : 
     190              :   /**
     191              :    * Apply spline offset to a point, mimicking original #addSplineOffset behavior
     192              :    * Critically: does nothing for CENTER/NONE directions (no case for them)
     193              :    */
     194              :   private applySplineOffset(
     195              :     point: PointObj,
     196              :     direction: LinkDirection,
     197              :     distance: number
     198              :   ): void {
     199       234100 :     switch (direction) {
     200              :       case LinkDirection.LEFT:
     201       114666 :         point.x -= distance
     202       114666 :         break
     203              :       case LinkDirection.RIGHT:
     204       117050 :         point.x += distance
     205       117050 :         break
     206              :       case LinkDirection.UP:
     207            0 :         point.y -= distance
     208            0 :         break
     209              :       case LinkDirection.DOWN:
     210            0 :         point.y += distance
     211              :         break
     212              :       // CENTER and NONE: no offset applied (original behavior)
     213              :     }
     214              :   }
     215              : 
     216              :   /**
     217              :    * Direct rendering method compatible with LGraphCanvas
     218              :    * Converts data and delegates to pure renderer
     219              :    */
     220              :   renderLinkDirect(
     221              :     ctx: CanvasRenderingContext2D,
     222              :     a: Readonly<Point>,
     223              :     b: Readonly<Point>,
     224              :     link: LLink | null,
     225              :     skip_border: boolean,
     226              :     flow: number | boolean | null,
     227              :     color: CanvasColour | null,
     228              :     start_dir: LinkDirection,
     229              :     end_dir: LinkDirection,
     230              :     context: LinkRenderContext,
     231              :     extras: {
     232              :       reroute?: Reroute
     233              :       startControl?: Readonly<Point>
     234              :       endControl?: Readonly<Point>
     235              :       num_sublines?: number
     236              :       disabled?: boolean
     237              :     } = {}
     238              :   ): void {
     239       117266 :     const startDir = start_dir || LinkDirection.RIGHT
     240       117266 :     const endDir = end_dir || LinkDirection.LEFT
     241              : 
     242       117266 :     const flowBool = flow === true || (typeof flow === 'number' && flow > 0)
     243              : 
     244       117266 :     const linkData: LinkRenderData = {
     245              :       id: link ? String(link.id) : 'temp',
     246              :       startPoint: { x: a[0], y: a[1] },
     247              :       endPoint: { x: b[0], y: b[1] },
     248              :       startDirection: this.convertDirection(startDir),
     249              :       endDirection: this.convertDirection(endDir),
     250              :       color: color !== null ? String(color) : undefined,
     251              :       type: link?.type !== undefined ? String(link.type) : undefined,
     252              :       flow: flowBool,
     253              :       disabled: extras.disabled || false
     254              :     }
     255              : 
     256       117266 :     if (context.renderMode === LinkRenderType.SPLINE_LINK) {
     257       117266 :       const hasStartCtrl = !!extras.startControl
     258       117266 :       const hasEndCtrl = !!extras.endControl
     259              : 
     260       117266 :       const dist = Math.sqrt(
     261              :         (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])
     262              :       )
     263       117266 :       const factor = 0.25
     264              : 
     265       117266 :       const cps: PointObj[] = []
     266              : 
     267       117266 :       if (hasStartCtrl && hasEndCtrl) {
     268            1 :         cps.push(
     269              :           {
     270              :             x: a[0] + (extras.startControl![0] || 0),
     271              :             y: a[1] + (extras.startControl![1] || 0)
     272              :           },
     273              :           {
     274              :             x: b[0] + (extras.endControl![0] || 0),
     275              :             y: b[1] + (extras.endControl![1] || 0)
     276              :           }
     277              :         )
     278            1 :         linkData.controlPoints = cps
     279       117265 :       } else if (hasStartCtrl && !hasEndCtrl) {
     280          177 :         const start = {
     281              :           x: a[0] + (extras.startControl![0] || 0),
     282              :           y: a[1] + (extras.startControl![1] || 0)
     283              :         }
     284          177 :         const end = { x: b[0], y: b[1] }
     285          177 :         this.applySplineOffset(end, endDir, dist * factor)
     286          177 :         cps.push(start, end)
     287          177 :         linkData.controlPoints = cps
     288       117088 :       } else if (!hasStartCtrl && hasEndCtrl) {
     289          253 :         const start = { x: a[0], y: a[1] }
     290          253 :         this.applySplineOffset(start, startDir, dist * factor)
     291          253 :         const end = {
     292              :           x: b[0] + (extras.endControl![0] || 0),
     293              :           y: b[1] + (extras.endControl![1] || 0)
     294              :         }
     295          253 :         cps.push(start, end)
     296          253 :         linkData.controlPoints = cps
     297              :       } else {
     298       116835 :         const start = { x: a[0], y: a[1] }
     299       116835 :         const end = { x: b[0], y: b[1] }
     300       116835 :         this.applySplineOffset(start, startDir, dist * factor)
     301       116835 :         this.applySplineOffset(end, endDir, dist * factor)
     302       116835 :         cps.push(start, end)
     303       116835 :         linkData.controlPoints = cps
     304              :       }
     305              :     }
     306              : 
     307       117266 :     const pathContext = this.pathRenderContextFor(context, skip_border)
     308              : 
     309       117266 :     const path = this.pathRenderer.drawLink(ctx, linkData, pathContext)
     310              : 
     311       117266 :     const linkSegment = extras.reroute ?? link
     312       117266 :     if (linkSegment) {
     313       114771 :       linkSegment.path = path
     314       114771 :       setLinkPolyline(linkSegment, () =>
     315              :         this.pathRenderer.polylineOf(linkData, pathContext.style.mode)
     316              :       )
     317              : 
     318       114771 :       if (linkData.centerPos) {
     319       114771 :         linkSegment._pos[0] = linkData.centerPos.x
     320       114771 :         linkSegment._pos[1] = linkData.centerPos.y
     321              : 
     322       114771 :         if (linkData.centerAngle !== undefined) {
     323            0 :           linkSegment._centreAngle = linkData.centerAngle
     324              :         }
     325              :       }
     326              : 
     327       114771 :       if (this.enableLayoutStoreWrites && link && link.id !== -1) {
     328            0 :         const bounds = this.calculateLinkBounds(
     329              :           [linkData.startPoint.x, linkData.startPoint.y] as Readonly<Point>,
     330              :           [linkData.endPoint.x, linkData.endPoint.y] as Readonly<Point>,
     331              :           linkData
     332              :         )
     333            0 :         const centerPos = linkData.centerPos || {
     334              :           x: (linkData.startPoint.x + linkData.endPoint.x) / 2,
     335              :           y: (linkData.startPoint.y + linkData.endPoint.y) / 2
     336              :         }
     337              : 
     338            0 :         if (!extras.reroute) {
     339            0 :           layoutStore.updateLinkLayout(link.id, {
     340              :             id: link.id,
     341              :             path: path,
     342              :             bounds: bounds,
     343              :             centerPos: centerPos,
     344              :             sourceNodeId: link.origin_id,
     345              :             targetNodeId: link.target_id,
     346              :             sourceSlot: link.origin_slot,
     347              :             targetSlot: link.target_slot
     348              :           })
     349              :         }
     350              : 
     351            0 :         const rerouteId = extras.reroute ? extras.reroute.id : null
     352            0 :         layoutStore.updateLinkSegmentLayout(link.id, rerouteId, {
     353              :           path: path,
     354              :           bounds: bounds,
     355              :           centerPos: centerPos
     356              :         })
     357              :       }
     358              :     }
     359              :   }
     360              : 
     361              :   renderDraggingLink(
     362              :     ctx: CanvasRenderingContext2D,
     363              :     from: Readonly<Point>,
     364              :     to: Readonly<Point>,
     365              :     colour: CanvasColour,
     366              :     startDir: LinkDirection,
     367              :     endDir: LinkDirection,
     368              :     context: LinkRenderContext
     369              :   ): void {
     370         2495 :     this.renderLinkDirect(
     371              :       ctx,
     372              :       from,
     373              :       to,
     374              :       null,
     375              :       false,
     376              :       null,
     377              :       colour,
     378              :       startDir,
     379              :       endDir,
     380              :       {
     381              :         ...context,
     382              :         linkMarkerShape: LinkMarkerShape.None
     383              :       },
     384              :       {
     385              :         disabled: false
     386              :       }
     387              :     )
     388              :   }
     389              : 
     390              :   /**
     391              :    * Calculate bounding box for a link
     392              :    * Includes padding for line width and control points
     393              :    */
     394              :   private calculateLinkBounds(
     395              :     startPos: Readonly<Point>,
     396              :     endPos: Readonly<Point>,
     397              :     linkData: LinkRenderData
     398              :   ): Bounds {
     399            0 :     let minX = Math.min(startPos[0], endPos[0])
     400            0 :     let maxX = Math.max(startPos[0], endPos[0])
     401            0 :     let minY = Math.min(startPos[1], endPos[1])
     402            0 :     let maxY = Math.max(startPos[1], endPos[1])
     403              : 
     404              :     // Include control points if they exist (for spline links)
     405            0 :     if (linkData.controlPoints) {
     406            0 :       for (const cp of linkData.controlPoints) {
     407            0 :         minX = Math.min(minX, cp.x)
     408            0 :         maxX = Math.max(maxX, cp.x)
     409            0 :         minY = Math.min(minY, cp.y)
     410            0 :         maxY = Math.max(maxY, cp.y)
     411              :       }
     412              :     }
     413              : 
     414              :     // Add padding for line width and hit tolerance
     415            0 :     const padding = 20
     416              : 
     417            0 :     return {
     418              :       x: minX - padding,
     419              :       y: minY - padding,
     420              :       width: maxX - minX + 2 * padding,
     421              :       height: maxY - minY + 2 * padding
     422              :     }
     423              :   }
     424              : }
        

Generated by: LCOV version 2.0-1