LCOV - code coverage report
Current view: top level - src/renderer/core/layout/store - layoutStore.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 78.2 % 459 359
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import log from 'loglevel'
       2              : import { computed, ref, shallowReactive } from 'vue'
       3              : import type { ComputedRef } from 'vue'
       4              : import * as Y from 'yjs'
       5              : 
       6              : import { toGroupId } from '@comfyorg/graph-model/groupId'
       7              : import { toNodeId } from '@comfyorg/graph-model/nodeId'
       8              : import type { GroupId } from '@comfyorg/graph-model/groupId'
       9              : import type { LinkId } from '@comfyorg/graph-model/linkId'
      10              : import type { RerouteId } from '@comfyorg/graph-model/rerouteId'
      11              : import { reportError } from '@comfyorg/telemetry/reportError'
      12              : import { readBrowserDpr } from '@/renderer/core/canvas/canvasViewport'
      13              : import { removeNodeTitleHeight } from '@/renderer/core/layout/utils/nodeSizeUtil'
      14              : import { toRerouteId } from '@comfyorg/graph-model/rerouteId'
      15              : import type { UUID } from '@/utils/uuid'
      16              : 
      17              : import { ACTOR_CONFIG } from '@/renderer/core/layout/constants'
      18              : import { LayoutSource } from '@/renderer/core/layout/types'
      19              : import type {
      20              :   BatchUpdateBoundsOperation,
      21              :   CreateNodeOperation,
      22              :   CreateRerouteOperation,
      23              :   DeleteNodeOperation,
      24              :   DeleteRerouteOperation,
      25              :   LayoutChange,
      26              :   LayoutOperation,
      27              :   LinkLayout,
      28              :   LinkSegmentLayout,
      29              :   MoveNodeOperation,
      30              :   MoveRerouteOperation,
      31              :   NodeId,
      32              :   ResizeNodeOperation,
      33              :   SetGroupBoundsOperation,
      34              :   SetNodeZIndexOperation
      35              : } from '@/renderer/core/layout/types'
      36              : import type {
      37              :   GroupLayout,
      38              :   NodeBoundsUpdate,
      39              :   NodeLayout,
      40              :   RerouteLayout,
      41              :   SlotOffset,
      42              :   SlotOffsetMode
      43              : } from '@comfyorg/graph-model/layout'
      44              : import type {
      45              :   Point2D as Point,
      46              :   Size2D as Size,
      47              :   RectTuple as StoredRect
      48              : } from '@comfyorg/shared-frontend-utils/geometry'
      49              : import type { SlotDirection, SlotIndex } from '@comfyorg/graph-model/slotId'
      50              : import {
      51              :   isBoundsEqual,
      52              :   isPointEqual
      53              : } from '@/renderer/core/layout/utils/geometry'
      54              : import {
      55              :   REROUTE_RADIUS,
      56              :   pointInBounds
      57              : } from '@/renderer/core/layout/utils/layoutMath'
      58              : import { makeLinkSegmentKey } from '@/renderer/core/layout/utils/layoutUtils'
      59              : import {
      60              :   layoutToYGroup,
      61              :   setYGroupRect,
      62              :   layoutToYNode,
      63              :   yGroupToLayout,
      64              :   yNodeToLayout
      65              : } from '@/renderer/core/layout/utils/mappers'
      66              : import type {
      67              :   GroupLayoutMap,
      68              :   NodeLayoutMap
      69              : } from '@/renderer/core/layout/utils/mappers'
      70              : import { SpatialIndexManager } from '@/renderer/core/spatial/SpatialIndex'
      71              : 
      72              : /** Top-level map keys touched by a batch of deep Yjs events. */
      73       110833 : function collectEventKeys(
      74              :   events: readonly Y.YEvent<Y.AbstractType<unknown>>[]
      75              : ): Set<string> {
      76       110833 :   const keys = new Set<string>()
      77       110833 :   for (const event of events) {
      78       110925 :     if (event.path.length === 0 && event instanceof Y.YMapEvent) {
      79        25445 :       event.changes.keys.forEach((_change, key) => keys.add(key))
      80        85480 :     } else if (typeof event.path[0] === 'string') {
      81        85480 :       keys.add(event.path[0])
      82              :     }
      83              :   }
      84       110833 :   return keys
      85              : }
      86              : 
      87       120782 : function createLayoutChange(operation: LayoutOperation): LayoutChange {
      88       120782 :   return {
      89              :     type: 'update',
      90              :     nodeIds: [],
      91              :     sizeChangedNodeIds: [],
      92              :     timestamp: operation.timestamp,
      93              :     source: operation.source,
      94              :     operation
      95              :   }
      96              : }
      97              : 
      98       377922 : function isNodeRect(value: unknown): value is StoredRect {
      99       377922 :   return (
     100              :     Array.isArray(value) &&
     101              :     value.length === 4 &&
     102              :     value.every((coordinate) => typeof coordinate === 'number')
     103              :   )
     104              : }
     105              : 
     106         2356 : const logger = log.getLogger('LayoutStore')
     107              : 
     108              : type ScopedLayoutKey = string & { readonly __brand: 'ScopedLayoutKey' }
     109              : 
     110              : /** Yjs surfaces its own keys as raw strings; brand them back on the way in. */
     111      1626613 : function toScopedLayoutKey(key: string): ScopedLayoutKey {
     112      1626613 :   return key as ScopedLayoutKey
     113              : }
     114              : 
     115      1506966 : function makeScopedLayoutKey(
     116              :   graphId: UUID,
     117              :   localId: number | string
     118              : ): ScopedLayoutKey {
     119      1506966 :   return toScopedLayoutKey(graphId + ':' + localId)
     120              : }
     121              : 
     122              : /** A UUID never contains `:`, so the first one always ends the graph id. */
     123       130740 : function parseLayoutKey(key: string): { graphId: UUID; localId: string } {
     124       130740 :   const separatorIndex = key.indexOf(':')
     125       130740 :   return {
     126              :     graphId: key.slice(0, separatorIndex),
     127              :     localId: key.slice(separatorIndex + 1)
     128              :   }
     129              : }
     130              : 
     131              : interface RerouteData {
     132              :   id: RerouteId
     133              :   position: Point
     134              : }
     135              : 
     136              : // Generic typed Y.Map interface
     137              : interface TypedYMap<T> {
     138              :   get<K extends keyof T>(key: K): T[K] | undefined
     139              :   get<K extends keyof T>(key: K, defaultValue: T[K]): T[K]
     140              : }
     141              : 
     142              : interface BatchUpdateBoundsOptions {
     143              :   boundsIncludeTitleHeight?: boolean
     144              :   source: LayoutSource
     145              : }
     146              : 
     147              : interface SlotOffsetSnapshot {
     148              :   mode: SlotOffsetMode
     149              :   byDirection: Record<SlotDirection, Map<SlotIndex, Point>>
     150              : }
     151              : 
     152        17980 : function isSlotOffsetSnapshotEqual(
     153              :   current: SlotOffsetSnapshot,
     154              :   next: SlotOffsetSnapshot
     155              : ): boolean {
     156        17980 :   if (current.mode !== next.mode) return false
     157              : 
     158        17980 :   for (const direction of ['input', 'output'] as const) {
     159        34207 :     const currentOffsets = current.byDirection[direction]
     160        34207 :     const nextOffsets = next.byDirection[direction]
     161        34207 :     if (currentOffsets.size !== nextOffsets.size) return false
     162        34207 :     for (const [index, point] of nextOffsets) {
     163        76108 :       const currentPoint = currentOffsets.get(index)
     164        76108 :       if (!currentPoint || !isPointEqual(currentPoint, point)) return false
     165              :     }
     166              :   }
     167        16188 :   return true
     168              : }
     169              : 
     170              : type LayoutListenerScope = 'geometry' | 'global' | 'node'
     171              : type LayoutListener =
     172              :   | ((change: LayoutChange) => void)
     173              :   | ((graphIds: ReadonlySet<UUID>) => void)
     174              : 
     175              : class LayoutStoreImpl {
     176              :   private static readonly REROUTE_DEFAULTS: RerouteData = {
     177              :     id: toRerouteId(0),
     178              :     position: { x: 0, y: 0 }
     179              :   }
     180              : 
     181              :   // Yjs document and shared data structures
     182              :   private ydoc = new Y.Doc()
     183              :   private ynodes: Y.Map<NodeLayoutMap> // Maps nodeId -> NodeLayoutMap containing NodeLayout data
     184              :   private yreroutes: Y.Map<Y.Map<unknown>> // Maps rerouteId -> Y.Map containing reroute data
     185              :   private ygroups: Y.Map<GroupLayoutMap> // Maps groupId -> GroupLayoutMap containing GroupLayout data
     186              : 
     187              :   // Vue reactivity layer
     188              :   private version = ref(0)
     189              :   private _nodeGeometryVersion = 0
     190              :   private _contentSizeVersion = 0
     191              :   private _slotOffsetVersion = ref(0)
     192              :   private currentActor = `${ACTOR_CONFIG.USER_PREFIX}${Math.random()
     193              :     .toString(36)
     194              :     .substring(2, 2 + ACTOR_CONFIG.ID_LENGTH)}`
     195              : 
     196              :   // Change listeners
     197              :   private changeListeners = new Set<(change: LayoutChange) => void>()
     198              :   private nodeChangeListeners = new Map<
     199              :     ScopedLayoutKey,
     200              :     Set<(change: LayoutChange) => void>
     201              :   >()
     202              :   private pendingGlobalChanges: LayoutChange[] = []
     203              :   private isGlobalDispatchQueued = false
     204              : 
     205              :   private nodeRevisions = shallowReactive(new Map<ScopedLayoutKey, number>())
     206              :   private pendingGeometryGraphIds = new Set<UUID>()
     207              :   private geometryListeners = new Set<(graphIds: ReadonlySet<UUID>) => void>()
     208              :   private pendingGeometryChanges: ReadonlySet<UUID>[] = []
     209              :   private isGeometryDispatchQueued = false
     210              :   private readonly reportedListenerFailures: Record<
     211              :     LayoutListenerScope,
     212              :     WeakSet<LayoutListener>
     213              :   > = {
     214              :     geometry: new WeakSet(),
     215              :     global: new WeakSet(),
     216              :     node: new WeakSet()
     217              :   }
     218              : 
     219              :   // New data structures for hit testing
     220              :   private linkLayouts = new Map<LinkId, LinkLayout>()
     221              :   private linkSegmentLayouts = new Map<string, LinkSegmentLayout>() // Internal string key: ${linkId}:${rerouteId ?? 'final'}
     222              :   private slotOffsets = new Map<ScopedLayoutKey, SlotOffsetSnapshot>()
     223              :   private contentSizes = new Map<ScopedLayoutKey, Size>()
     224              :   private suppressedContentSizes = new Map<ScopedLayoutKey, Size>()
     225              :   private rerouteLayouts = new Map<ScopedLayoutKey, RerouteLayout>()
     226              : 
     227              :   // Spatial index managers
     228              :   private linkSegmentSpatialIndex: SpatialIndexManager<string> // For link segments (single index for all link geometry)
     229              :   private rerouteSpatialIndex: SpatialIndexManager<ScopedLayoutKey> // For reroutes
     230              : 
     231              :   private highestZIndex = 0
     232              : 
     233              :   // Vue dragging state for selection toolbox (public ref for direct mutation)
     234              :   public isDraggingVueNodes = ref(false)
     235              :   // Vue resizing state to prevent drag from activating during resize
     236              :   public isResizingVueNodes = ref(false)
     237              : 
     238              :   /**
     239              :    * Number of tracked nodes, without materialising their layouts.
     240              :    * Callers that only need a count or emptiness check should prefer this over
     241              :    * `getAllNodes()`, which rebuilds the full layout map on every access.
     242              :    */
     243              :   get nodeCount(): number {
     244            0 :     return this.ynodes.size
     245              :   }
     246              : 
     247              :   /**
     248              :    * Counter bumped when the Yjs-backed node, link and reroute maps change, for
     249              :    * use as a cache key.
     250              :    *
     251              :    * Scope is exactly those maps. Link and reroute *geometry* live in plain
     252              :    * Maps that are mutated without bumping this.
     253              :    * Anything deriving node geometry from this should also read that geometry
     254              :    * from this store, so key and data stay consistent.
     255              :    *
     256              :    * Local per-peer counter, not a CRDT document version: two peers holding
     257              :    * identical layouts will hold different values, so it is not meaningful to
     258              :    * compare across peers.
     259              :    */
     260              :   get layoutVersion(): number {
     261       137847 :     return this.version.value
     262              :   }
     263              : 
     264              :   /**
     265              :    * Counter bumped only when node geometry changes: a node is added or
     266              :    * removed, or an existing node's position, size or bounds is written.
     267              :    *
     268              :    * `layoutVersion` counts operations, so it also moves for changes nothing
     269              :    * renders from geometry - `setNodeZIndex` alone fires on every widget
     270              :    * pointerdown. Consumers that rebuild geometry-derived state should key on
     271              :    * this instead, or they repaint for edits that cannot move a pixel.
     272              :    *
     273              :    * Backed by `observeDeep`, so it covers writes that never touch a top-level
     274              :    * key - a move mutates fields inside a node's own map - and therefore also
     275              :    * covers remote changes arriving through `applyUpdate`, which run no local
     276              :    * operation handler.
     277              :    */
     278              :   get nodeGeometryVersion(): number {
     279      6350954 :     return this._nodeGeometryVersion
     280              :   }
     281              : 
     282              :   /** Non-reactive revision for measured Vue content dimensions. */
     283              :   get contentSizeVersion(): number {
     284      6797331 :     return this._contentSizeVersion
     285              :   }
     286              : 
     287              :   /**
     288              :    * Reactive counter bumped when measured slot offsets are dropped in bulk.
     289              :    * A Vue node that stays mounted through a graph reload has nothing else to
     290              :    * tell it that its measurements are gone, so it re-measures on this.
     291              :    */
     292              :   get slotOffsetVersion(): number {
     293        16278 :     return this._slotOffsetVersion.value
     294              :   }
     295              : 
     296              :   constructor() {
     297              :     // Initialize Yjs data structures
     298         2356 :     this.ynodes = this.ydoc.getMap('nodes')
     299         2356 :     this.yreroutes = this.ydoc.getMap('reroutes')
     300         2356 :     this.ygroups = this.ydoc.getMap('groups')
     301              : 
     302              :     // Initialize spatial index managers
     303         2356 :     this.linkSegmentSpatialIndex = new SpatialIndexManager<string>() // Single index for all link geometry
     304         2356 :     this.rerouteSpatialIndex = new SpatialIndexManager<ScopedLayoutKey>()
     305              : 
     306              :     // Deep observers so nested field writes (ynode.set('rect', ...)) fire
     307              :     // for both local operations and externally-applied updates.
     308         2356 :     this.ynodes.observeDeep((events) => {
     309       110488 :       if (
     310              :         events.some(
     311              :           (event) =>
     312              :             (event.target === this.ynodes && event.changes.keys.size > 0) ||
     313              :             event.changes.keys.has('rect')
     314              :         )
     315              :       ) {
     316       108929 :         this._nodeGeometryVersion++
     317              :       }
     318              : 
     319       110488 :       for (const key of collectEventKeys(events)) {
     320       119585 :         const nodeKey = toScopedLayoutKey(key)
     321       119585 :         const ynode = this.ynodes.get(nodeKey)
     322       119585 :         const zIndex = ynode?.get('zIndex')
     323       119585 :         if (typeof zIndex === 'number') {
     324       108606 :           this.highestZIndex = Math.max(this.highestZIndex, zIndex)
     325              :         }
     326       119585 :         if (ynode) this.triggerNodeLayout(nodeKey)
     327        10979 :         else this.nodeRevisions.delete(nodeKey)
     328       119585 :         this.pendingGeometryGraphIds.add(parseLayoutKey(key).graphId)
     329              :       }
     330              :     })
     331              : 
     332         2356 :     this.ygroups.observeDeep((events) => {
     333          284 :       for (const key of collectEventKeys(events)) {
     334          314 :         this.pendingGeometryGraphIds.add(parseLayoutKey(key).graphId)
     335              :       }
     336              :     })
     337              : 
     338         2356 :     this.yreroutes.observeDeep((events) => {
     339           61 :       for (const key of collectEventKeys(events)) {
     340           62 :         this.projectReroute(toScopedLayoutKey(key))
     341           62 :         this.pendingGeometryGraphIds.add(parseLayoutKey(key).graphId)
     342              :       }
     343              :     })
     344              : 
     345         2356 :     this.ydoc.on('afterTransaction', () => {
     346       122523 :       if (this.pendingGeometryGraphIds.size === 0) return
     347       110800 :       this.version.value++
     348       110800 :       const graphIds: ReadonlySet<UUID> = new Set(this.pendingGeometryGraphIds)
     349       110800 :       this.pendingGeometryGraphIds.clear()
     350       110800 :       this.queueGeometryChange(graphIds)
     351              :     })
     352              :   }
     353              : 
     354              :   private getRerouteField<K extends keyof RerouteData>(
     355              :     yreroute: Y.Map<unknown>,
     356              :     field: K,
     357              :     defaultValue: RerouteData[K] = LayoutStoreImpl.REROUTE_DEFAULTS[field]
     358              :   ): RerouteData[K] {
     359              :     const typedReroute = yreroute as TypedYMap<RerouteData>
     360              :     const value = typedReroute.get(field)
     361           46 :     return value ?? defaultValue
     362              :   }
     363              : 
     364              :   getNodeLayout(rootGraphId: UUID, nodeId: NodeId): NodeLayout | null {
     365       178194 :     const ynode = this.ynodes.get(makeScopedLayoutKey(rootGraphId, nodeId))
     366       178194 :     return ynode ? yNodeToLayout(ynode) : null
     367              :   }
     368              : 
     369              :   private triggerNodeLayout(nodeKey: ScopedLayoutKey): void {
     370       108606 :     this.nodeRevisions.set(nodeKey, (this.nodeRevisions.get(nodeKey) ?? 0) + 1)
     371              :   }
     372              : 
     373              :   getNodeLayoutRef(
     374              :     rootGraphId: UUID,
     375              :     nodeId: NodeId
     376              :   ): ComputedRef<NodeLayout | null> {
     377        31270 :     const nodeKey = makeScopedLayoutKey(rootGraphId, nodeId)
     378        31270 :     return computed(() => {
     379        90611 :       void this.nodeRevisions.get(nodeKey)
     380        90611 :       return this.getNodeLayout(rootGraphId, nodeId)
     381              :     })
     382              :   }
     383              : 
     384              :   /**
     385              :    * Get all groups as a reactive map
     386              :    */
     387              :   getAllGroups(
     388              :     rootGraphId: UUID
     389              :   ): ComputedRef<ReadonlyMap<GroupId, GroupLayout>> {
     390            0 :     return computed(() => {
     391            0 :       void this.version.value
     392              : 
     393            0 :       const result = new Map<GroupId, GroupLayout>()
     394            0 :       for (const [key, ygroup] of this.ygroups) {
     395            0 :         const parsed = parseLayoutKey(key)
     396            0 :         if (parsed.graphId !== rootGraphId) continue
     397            0 :         const groupId = toGroupId(Number(parsed.localId))
     398            0 :         result.set(groupId, yGroupToLayout(ygroup, groupId))
     399              :       }
     400            0 :       return result
     401              :     })
     402              :   }
     403              : 
     404              :   getGroupLayout(rootGraphId: UUID, groupId: GroupId): GroupLayout | null {
     405        16200 :     const ygroup = this.ygroups.get(makeScopedLayoutKey(rootGraphId, groupId))
     406        16200 :     return ygroup ? yGroupToLayout(ygroup, groupId) : null
     407              :   }
     408              : 
     409              :   get geometryVersion(): number {
     410            0 :     return this.version.value
     411              :   }
     412              : 
     413              :   readNodeRect(rootGraphId: UUID, nodeId: NodeId, out: Float64Array): boolean {
     414       340664 :     const rect = this.ynodes
     415              :       .get(makeScopedLayoutKey(rootGraphId, nodeId))
     416              :       ?.get('rect')
     417       340664 :     if (!isNodeRect(rect)) return false
     418              : 
     419       340664 :     out[0] = rect[0]
     420       340664 :     out[1] = rect[1]
     421       340664 :     out[2] = rect[2]
     422       340664 :     out[3] = rect[3]
     423       340664 :     return true
     424              :   }
     425              : 
     426              :   contentSizeOf(rootGraphId: UUID, nodeId: NodeId): Size | undefined {
     427       194657 :     return this.contentSizes.get(makeScopedLayoutKey(rootGraphId, nodeId))
     428              :   }
     429              : 
     430              :   reportContentSize(rootGraphId: UUID, nodeId: NodeId, size: Size): void {
     431         9220 :     const key = makeScopedLayoutKey(rootGraphId, nodeId)
     432         9220 :     const suppressed = this.suppressedContentSizes.get(key)
     433         9220 :     if (suppressed) {
     434           53 :       if (suppressed.width === size.width && suppressed.height === size.height)
     435            0 :         return
     436           53 :       this.suppressedContentSizes.delete(key)
     437              :     }
     438         9220 :     const previous = this.contentSizes.get(key)
     439         9220 :     if (previous?.width === size.width && previous.height === size.height)
     440            0 :       return
     441         9220 :     this.contentSizes.set(key, size)
     442         9220 :     this._contentSizeVersion++
     443              :   }
     444              : 
     445              :   clearContentSize(rootGraphId: UUID, nodeId: NodeId): void {
     446        36660 :     const key = makeScopedLayoutKey(rootGraphId, nodeId)
     447        36660 :     const previous = this.contentSizes.get(key)
     448        36660 :     if (!previous) return
     449           54 :     this.suppressedContentSizes.set(key, previous)
     450           54 :     this.contentSizes.delete(key)
     451           54 :     this._contentSizeVersion++
     452              :   }
     453              : 
     454              :   /**
     455              :    * Get current version for change detection
     456              :    */
     457              :   getVersion(): ComputedRef<number> {
     458            0 :     return computed(() => this.version.value)
     459              :   }
     460              : 
     461              :   /**
     462              :    * Update link layout data (for geometry/debug, no separate spatial index)
     463              :    */
     464              :   updateLinkLayout(linkId: LinkId, layout: LinkLayout): void {
     465            0 :     const existing = this.linkLayouts.get(linkId)
     466              : 
     467            0 :     if (
     468              :       existing &&
     469              :       isBoundsEqual(existing.bounds, layout.bounds) &&
     470              :       isPointEqual(existing.centerPos, layout.centerPos)
     471              :     ) {
     472            0 :       existing.path = layout.path
     473            0 :       return
     474              :     }
     475              : 
     476            0 :     this.linkLayouts.set(linkId, { ...layout, id: linkId })
     477              :   }
     478              : 
     479              :   /**
     480              :    * Delete link layout data
     481              :    */
     482              :   deleteLinkLayout(linkId: LinkId): void {
     483              :     const deleted = this.linkLayouts.delete(linkId)
     484          912 :     if (deleted) {
     485            0 :       this.cleanupLinkSegments(linkId)
     486              :     }
     487              :   }
     488              :   /**
     489              :    * Update reroute layout data
     490              :    */
     491              :   updateRerouteLayout(
     492              :     rootGraphId: UUID,
     493              :     rerouteId: RerouteId,
     494              :     layout: RerouteLayout
     495              :   ): void {
     496           46 :     const rerouteKey = makeScopedLayoutKey(rootGraphId, rerouteId)
     497           46 :     const existing = this.rerouteLayouts.get(rerouteKey)
     498              : 
     499           46 :     if (!existing) {
     500           41 :       logger.debug('Adding reroute layout:', {
     501              :         rerouteId,
     502              :         position: layout.position,
     503              :         bounds: layout.bounds
     504              :       })
     505              :     }
     506              : 
     507           46 :     if (existing) {
     508              :       // Update spatial index
     509            5 :       this.rerouteSpatialIndex.update(rerouteKey, layout.bounds)
     510              :     } else {
     511              :       // Insert into spatial index
     512           41 :       this.rerouteSpatialIndex.insert(rerouteKey, layout.bounds)
     513              :     }
     514              : 
     515           46 :     this.rerouteLayouts.set(rerouteKey, layout)
     516              :   }
     517              : 
     518              :   /**
     519              :    * Get link layout data
     520              :    */
     521              :   getLinkLayout(linkId: LinkId): LinkLayout | null {
     522            0 :     return this.linkLayouts.get(linkId) || null
     523              :   }
     524              : 
     525              :   updateNodeSlotOffsets(
     526              :     graphId: UUID,
     527              :     nodeId: NodeId,
     528              :     offsets: readonly SlotOffset[],
     529              :     mode: SlotOffsetMode
     530              :   ): void {
     531        26172 :     const key = makeScopedLayoutKey(graphId, nodeId)
     532        26172 :     const byDirection: Record<SlotDirection, Map<SlotIndex, Point>> = {
     533              :       input: new Map(),
     534              :       output: new Map()
     535              :     }
     536        26172 :     for (const offset of offsets) {
     537       116113 :       byDirection[offset.type].set(offset.index, offset.position)
     538              :     }
     539        26172 :     const next = { mode, byDirection }
     540        26172 :     const current = this.slotOffsets.get(key)
     541        26172 :     if (current && isSlotOffsetSnapshotEqual(current, next)) return
     542              : 
     543         9984 :     this.slotOffsets.set(key, next)
     544        26172 :     if (current?.mode === mode || offsets.length > 0) {
     545         9960 :       this.queueGeometryChange(new Set([graphId]))
     546              :     }
     547              :   }
     548              : 
     549              :   getSlotOffset(
     550              :     graphId: UUID,
     551              :     nodeId: NodeId,
     552              :     index: SlotIndex,
     553              :     type: SlotDirection,
     554              :     mode: SlotOffsetMode
     555              :   ): Point | null {
     556       314088 :     const offsets = this.slotOffsets.get(makeScopedLayoutKey(graphId, nodeId))
     557       314088 :     return offsets?.mode === mode
     558              :       ? (offsets.byDirection[type].get(index) ?? null)
     559              :       : null
     560              :   }
     561              :   /**
     562              :    * Get reroute layout data
     563              :    */
     564              :   getRerouteLayout(
     565              :     rootGraphId: UUID,
     566              :     rerouteId: RerouteId
     567              :   ): RerouteLayout | null {
     568        11136 :     return (
     569              :       this.rerouteLayouts.get(makeScopedLayoutKey(rootGraphId, rerouteId)) ??
     570              :       null
     571              :     )
     572              :   }
     573              : 
     574              :   /**
     575              :    * Update link segment layout data
     576              :    */
     577              :   updateLinkSegmentLayout(
     578              :     linkId: LinkId,
     579              :     rerouteId: RerouteId | null,
     580              :     layout: Omit<LinkSegmentLayout, 'linkId' | 'rerouteId'>
     581              :   ): void {
     582            0 :     const key = makeLinkSegmentKey(linkId, rerouteId)
     583            0 :     const existing = this.linkSegmentLayouts.get(key)
     584              : 
     585            0 :     if (
     586              :       existing &&
     587              :       isBoundsEqual(existing.bounds, layout.bounds) &&
     588              :       isPointEqual(existing.centerPos, layout.centerPos)
     589              :     ) {
     590            0 :       existing.path = layout.path
     591            0 :       return
     592              :     }
     593              : 
     594            0 :     const fullLayout: LinkSegmentLayout = {
     595              :       ...layout,
     596              :       linkId,
     597              :       rerouteId
     598              :     }
     599              : 
     600            0 :     if (!existing) {
     601            0 :       logger.debug('Adding link segment:', {
     602              :         linkId,
     603              :         rerouteId,
     604              :         bounds: layout.bounds,
     605              :         hasPath: !!layout.path
     606              :       })
     607              :     }
     608              : 
     609            0 :     if (existing) {
     610            0 :       this.linkSegmentSpatialIndex.update(key, layout.bounds)
     611              :     } else {
     612            0 :       this.linkSegmentSpatialIndex.insert(key, layout.bounds)
     613              :     }
     614              : 
     615            0 :     this.linkSegmentLayouts.set(key, fullLayout)
     616              :   }
     617              : 
     618              :   /**
     619              :    * Delete link segment layout data
     620              :    */
     621              :   deleteLinkSegmentLayout(linkId: LinkId, rerouteId: RerouteId | null): void {
     622            0 :     const key = makeLinkSegmentKey(linkId, rerouteId)
     623              :     const deleted = this.linkSegmentLayouts.delete(key)
     624            0 :     if (deleted) {
     625            0 :       this.linkSegmentSpatialIndex.remove(key)
     626              :     }
     627              :   }
     628              :   /**
     629              :    * Query link segment at point (returns structured data)
     630              :    *
     631              :    * @param dpr Device pixel ratio used to map the CSS-space point into the
     632              :    *   canvas's device-pixel-scaled stroke space. Pass the active
     633              :    *   `LGraphCanvas.dpr` so this hit-test agrees with `processMouseDown`'s
     634              :    *   `isPointInStroke` fallback. Defaults to the normalized browser DPR
     635              :    *   for legacy callers without a canvas reference.
     636              :    */
     637              :   queryLinkSegmentAtPoint(
     638              :     point: Point,
     639              :     ctx?: CanvasRenderingContext2D,
     640              :     dpr = readBrowserDpr()
     641              :   ): { linkId: LinkId; rerouteId: RerouteId | null } | null {
     642              :     // Determine tolerance from current canvas state (if available)
     643              :     // - Use the caller-provided ctx.lineWidth (LGraphCanvas sets this to connections_width + padding)
     644              :     // - Fall back to a sensible default when ctx is not provided
     645          370 :     const hitWidth = ctx?.lineWidth ?? 10
     646          370 :     const halfSize = Math.max(10, hitWidth) // keep a minimum window for spatial index
     647              : 
     648              :     // Use spatial index to get candidate segments
     649          370 :     const searchArea = {
     650              :       x: point.x - halfSize,
     651              :       y: point.y - halfSize,
     652              :       width: halfSize * 2,
     653              :       height: halfSize * 2
     654              :     }
     655          370 :     const candidateKeys = this.linkSegmentSpatialIndex.query(searchArea)
     656              : 
     657          370 :     if (candidateKeys.length > 0) {
     658            0 :       logger.debug('Checking link segments at point:', {
     659              :         point,
     660              :         candidateCount: candidateKeys.length,
     661              :         tolerance: hitWidth
     662              :       })
     663              :     }
     664              : 
     665              :     // Precise hit test only on candidates
     666          370 :     for (const key of candidateKeys) {
     667            0 :       const segmentLayout = this.linkSegmentLayouts.get(key)
     668            0 :       if (!segmentLayout) continue
     669              : 
     670            0 :       if (ctx) {
     671            0 :         const hit = ctx.isPointInStroke(
     672              :           segmentLayout.path,
     673              :           point.x * dpr,
     674              :           point.y * dpr
     675              :         )
     676              : 
     677              :         if (hit) {
     678            0 :           logger.debug('Link segment hit:', {
     679              :             linkId: segmentLayout.linkId,
     680              :             rerouteId: segmentLayout.rerouteId,
     681              :             point
     682              :           })
     683            0 :           return {
     684              :             linkId: segmentLayout.linkId,
     685              :             rerouteId: segmentLayout.rerouteId
     686              :           }
     687              :         }
     688            0 :       } else if (pointInBounds(point, segmentLayout.bounds)) {
     689              :         // Fallback to bounding box test
     690            0 :         return {
     691              :           linkId: segmentLayout.linkId,
     692              :           rerouteId: segmentLayout.rerouteId
     693              :         }
     694              :       }
     695              :     }
     696              : 
     697          370 :     return null
     698              :   }
     699              : 
     700              :   /**
     701              :    * Query link at point (derived from segment query)
     702              :    */
     703              :   queryLinkAtPoint(
     704              :     point: Point,
     705              :     ctx?: CanvasRenderingContext2D,
     706              :     dpr?: number
     707              :   ): LinkId | null {
     708              :     // Invoke segment query and return just the linkId
     709            0 :     const segment = this.queryLinkSegmentAtPoint(point, ctx, dpr)
     710            0 :     return segment ? segment.linkId : null
     711              :   }
     712              : 
     713              :   /**
     714              :    * Query reroute at point
     715              :    */
     716              :   queryRerouteAtPoint(rootGraphId: UUID, point: Point): RerouteLayout | null {
     717              :     // Use spatial index to get candidate reroutes
     718          481 :     const maxRadius = 20 // Maximum expected reroute radius
     719          481 :     const searchArea = {
     720              :       x: point.x - maxRadius,
     721              :       y: point.y - maxRadius,
     722              :       width: maxRadius * 2,
     723              :       height: maxRadius * 2
     724              :     }
     725          481 :     const candidateRerouteKeys = this.rerouteSpatialIndex.query(searchArea)
     726              : 
     727          481 :     if (candidateRerouteKeys.length > 0) {
     728            2 :       logger.debug('Checking reroutes at point:', {
     729              :         point,
     730              :         candidateCount: candidateRerouteKeys.length
     731              :       })
     732              :     }
     733              : 
     734              :     // Check precise distance for candidates
     735          481 :     for (const rerouteKey of candidateRerouteKeys) {
     736              :       const parsed = parseLayoutKey(rerouteKey)
     737            2 :       if (parsed.graphId !== rootGraphId) continue
     738            2 :       const rerouteLayout = this.rerouteLayouts.get(rerouteKey)
     739            2 :       if (rerouteLayout) {
     740            2 :         const dx = point.x - rerouteLayout.position.x
     741            2 :         const dy = point.y - rerouteLayout.position.y
     742            2 :         const distance = Math.sqrt(dx * dx + dy * dy)
     743              : 
     744            2 :         if (distance <= rerouteLayout.radius) {
     745            0 :           logger.debug('Reroute hit:', {
     746              :             rerouteId: rerouteLayout.id,
     747              :             position: rerouteLayout.position,
     748              :             distance
     749              :           })
     750            0 :           return rerouteLayout
     751              :         }
     752              :       }
     753              :     }
     754          481 :     return null
     755              :   }
     756              : 
     757              :   /**
     758              :    * Apply a layout operation using Yjs transactions
     759              :    */
     760              :   applyOperation(operation: LayoutOperation): void {
     761       120746 :     const stamped = this.stampActor(operation)
     762       120746 :     const change = createLayoutChange(stamped)
     763       120746 :     const result: { applied?: boolean } = {}
     764       120746 :     this.ydoc.transact(() => {
     765       120746 :       result.applied = this.applyOperationInTransaction(stamped, change)
     766              :     }, this.currentActor)
     767       120746 :     if (!result.applied) return
     768              : 
     769       110780 :     this.finalizeOperation(change)
     770              :   }
     771              : 
     772              :   /** Applies several operations in one Yjs transaction. */
     773              :   applyOperations(operations: readonly LayoutOperation[]): void {
     774         1554 :     if (operations.length === 0) return
     775              : 
     776           20 :     const appliedChanges: LayoutChange[] = []
     777           20 :     this.ydoc.transact(() => {
     778           20 :       for (const operation of operations) {
     779           36 :         const stamped = this.stampActor(operation)
     780           36 :         const change = createLayoutChange(stamped)
     781           36 :         if (this.applyOperationInTransaction(stamped, change)) {
     782           36 :           appliedChanges.push(change)
     783              :         }
     784              :       }
     785              :     }, this.currentActor)
     786              : 
     787           94 :     for (const change of appliedChanges) this.finalizeOperation(change)
     788              :   }
     789              : 
     790              :   /** Stamps this session's actor on operations that carry none. */
     791              :   private stampActor(operation: LayoutOperation): LayoutOperation {
     792       120782 :     return operation.actor === undefined
     793              :       ? { ...operation, actor: this.currentActor }
     794              :       : operation
     795              :   }
     796              : 
     797              :   /**
     798              :    * Runs `fn` with every actor-less operation stamped as `actor` instead of
     799              :    * this session's actor. The per-mutation command source remote appliers and
     800              :    * provenance-aware listeners key on: stamping happens synchronously at
     801              :    * apply time, so deferred change delivery still carries the scoped actor on
     802              :    * `change.operation.actor`.
     803              :    */
     804              :   withActor<T>(actor: string, fn: () => T): T {
     805            0 :     const previous = this.currentActor
     806            0 :     this.currentActor = actor
     807            0 :     try {
     808            0 :       return fn()
     809              :     } finally {
     810            0 :       this.currentActor = previous
     811              :     }
     812              :   }
     813              : 
     814              :   /**
     815              :    * Apply operation within a transaction.
     816              :    * @returns Whether the operation changed store state.
     817              :    */
     818              :   private applyOperationInTransaction(
     819              :     operation: LayoutOperation,
     820              :     change: LayoutChange
     821              :   ): boolean {
     822       120782 :     switch (operation.type) {
     823              :       case 'moveNode':
     824        46553 :         return this.handleMoveNode(operation, change)
     825              :       case 'resizeNode':
     826        36785 :         return this.handleResizeNode(operation, change)
     827              :       case 'setNodeZIndex':
     828         1559 :         return this.handleSetNodeZIndex(operation, change)
     829              :       case 'createNode':
     830        23236 :         return this.handleCreateNode(operation, change)
     831              :       case 'deleteNode':
     832          248 :         return this.handleDeleteNode(operation, change)
     833              :       case 'batchUpdateBounds':
     834          381 :         return this.handleBatchUpdateBounds(operation, change)
     835              :       case 'createReroute':
     836           41 :         return this.handleCreateReroute(operation, change)
     837              :       case 'deleteReroute':
     838            0 :         return this.handleDeleteReroute(operation, change)
     839              :       case 'moveReroute':
     840            5 :         return this.handleMoveReroute(operation, change)
     841              :       case 'createGroup': {
     842          154 :         const groupKey = makeScopedLayoutKey(
     843              :           operation.graphId,
     844              :           operation.groupId
     845              :         )
     846          154 :         if (this.ygroups.has(groupKey)) return false
     847          154 :         this.ygroups.set(groupKey, layoutToYGroup(operation.layout))
     848          154 :         change.type = 'create'
     849          154 :         return true
     850              :       }
     851              :       case 'setGroupBounds':
     852          105 :         return this.handleSetGroupBounds(operation)
     853              :       case 'deleteGroup': {
     854            6 :         const groupKey = makeScopedLayoutKey(
     855              :           operation.graphId,
     856              :           operation.groupId
     857              :         )
     858            6 :         if (!this.ygroups.has(groupKey)) return false
     859            6 :         this.ygroups.delete(groupKey)
     860            6 :         change.type = 'delete'
     861            6 :         return true
     862              :       }
     863              :       case 'clearGraph':
     864        11709 :         return this.handleClearGraph(operation.graphId, change)
     865              :     }
     866              :   }
     867              : 
     868              :   private handleClearGraph(graphId: UUID, change: LayoutChange): boolean {
     869        11709 :     const prefix = graphId + ':'
     870        11709 :     let deleted = false
     871              : 
     872        11709 :     for (const key of Array.from(this.ynodes.keys())) {
     873        10731 :       if (!key.startsWith(prefix)) continue
     874        10731 :       this.ynodes.delete(key)
     875        10731 :       change.nodeIds.push(toNodeId(parseLayoutKey(key).localId))
     876        10731 :       deleted = true
     877              :     }
     878        11709 :     for (const key of this.contentSizes.keys()) {
     879         4784 :       if (!key.startsWith(prefix)) continue
     880         4784 :       this.contentSizes.delete(key)
     881         4784 :       this._contentSizeVersion++
     882              :     }
     883        11709 :     for (const key of this.suppressedContentSizes.keys()) {
     884            0 :       if (key.startsWith(prefix)) this.suppressedContentSizes.delete(key)
     885              :     }
     886        11709 :     let slotOffsetsDropped = false
     887        11709 :     for (const key of this.slotOffsets.keys()) {
     888         4855 :       if (!key.startsWith(prefix)) continue
     889         4855 :       this.slotOffsets.delete(key)
     890         4855 :       slotOffsetsDropped = true
     891              :     }
     892        11709 :     if (slotOffsetsDropped) this._slotOffsetVersion.value++
     893        11709 :     for (const key of Array.from(this.ygroups.keys())) {
     894           49 :       if (!key.startsWith(prefix)) continue
     895           49 :       this.ygroups.delete(key)
     896           49 :       deleted = true
     897              :     }
     898        11709 :     for (const key of Array.from(this.yreroutes.keys())) {
     899           16 :       if (!key.startsWith(prefix)) continue
     900           16 :       this.yreroutes.delete(key)
     901           16 :       deleted = true
     902              :     }
     903              : 
     904        11709 :     change.type = 'delete'
     905        11709 :     return deleted
     906              :   }
     907              : 
     908              :   /**
     909              :    * Finalize operation after transaction. Version bumps and node-ref
     910              :    * triggers happen in the Yjs observers, which fire for local and
     911              :    * external updates alike.
     912              :    */
     913              :   private finalizeOperation(change: LayoutChange): void {
     914       110816 :     this.queueChange(change)
     915              :   }
     916              : 
     917              :   /**
     918              :    * Subscribe to layout changes
     919              :    */
     920              :   onChange(callback: (change: LayoutChange) => void): () => void {
     921         2355 :     this.changeListeners.add(callback)
     922         2355 :     return () => this.changeListeners.delete(callback)
     923              :   }
     924              : 
     925              :   /**
     926              :    * Subscribe to per-transaction geometry notifications. Fires once per Yjs
     927              :    * transaction with the set of graph ids whose node, group, or reroute
     928              :    * geometry changed — including changes that touch no node (group- or
     929              :    * reroute-only edits).
     930              :    */
     931              :   onGeometryChange(
     932              :     callback: (graphIds: ReadonlySet<UUID>) => void
     933              :   ): () => void {
     934         2355 :     this.geometryListeners.add(callback)
     935         2355 :     return () => this.geometryListeners.delete(callback)
     936              :   }
     937              : 
     938              :   onNodeChange(
     939              :     rootGraphId: UUID,
     940              :     nodeId: NodeId,
     941              :     callback: (change: LayoutChange) => void
     942              :   ): () => void {
     943            0 :     const nodeKey = makeScopedLayoutKey(rootGraphId, nodeId)
     944            0 :     const listenersForNode = this.nodeChangeListeners.get(nodeKey) ?? new Set()
     945            0 :     listenersForNode.add(callback)
     946            0 :     this.nodeChangeListeners.set(nodeKey, listenersForNode)
     947              : 
     948            0 :     return () => {
     949            0 :       const existingListeners = this.nodeChangeListeners.get(nodeKey)
     950            0 :       if (!existingListeners) return
     951              : 
     952            0 :       existingListeners.delete(callback)
     953            0 :       if (existingListeners.size === 0) {
     954            0 :         this.nodeChangeListeners.delete(nodeKey)
     955              :       }
     956              :     }
     957              :   }
     958              : 
     959              :   /**
     960              :    * Claims a stacking order above every node the store has seen. Stacking is
     961              :    * the store's own sequence, independent of a node's position in
     962              :    * {@link LGraph._nodes}.
     963              :    */
     964              :   allocateZIndex(): number {
     965        24795 :     return ++this.highestZIndex
     966              :   }
     967              : 
     968              :   /** Drops entity layout owned by a root graph and its subgraph definitions. */
     969              :   clearGraph(rootGraphId: UUID): void {
     970        11709 :     this.applyOperation({
     971              :       type: 'clearGraph',
     972              :       graphId: rootGraphId,
     973              :       timestamp: Date.now(),
     974              :       source: LayoutSource.Canvas
     975              :     })
     976              :   }
     977              : 
     978              :   /**
     979              :    * Test-only escape hatch: drops everything, including entity entries that
     980              :    * production drops through `detachGraphLayouts`. Calling it with a
     981              :    * graph attached desyncs the store from every entity in it.
     982              :    */
     983              :   resetForTests(): void {
     984            0 :     this.highestZIndex = 0
     985            0 :     this.ydoc.transact(() => {
     986            0 :       this.ynodes.clear()
     987            0 :       this.ygroups.clear()
     988            0 :       this.yreroutes.clear()
     989            0 :       this.rerouteLayouts.clear()
     990            0 :       this.rerouteSpatialIndex.clear()
     991            0 :       this.slotOffsets.clear()
     992              :     }, 'initialization')
     993            0 :     this.clearViewGeometry()
     994              :   }
     995              : 
     996              :   /**
     997              :    * Drops view-local link geometry and the listeners and queues bound to the
     998              :    * graph being left. Entity geometry leaves through `detachGraphLayouts`.
     999              :    */
    1000              :   clearViewGeometry(): void {
    1001         1757 :     this.ydoc.transact(() => {
    1002         1757 :       this.nodeChangeListeners.clear()
    1003         1757 :       this.linkSegmentSpatialIndex.clear()
    1004         1757 :       this.linkLayouts.clear()
    1005         1757 :       this.linkSegmentLayouts.clear()
    1006         1757 :       if (this.contentSizes.size > 0) {
    1007          157 :         this.contentSizes.clear()
    1008          157 :         this._contentSizeVersion++
    1009              :       }
    1010         1757 :       this.suppressedContentSizes.clear()
    1011         1757 :       if (this.slotOffsets.size > 0) {
    1012          164 :         this.slotOffsets.clear()
    1013          164 :         this._slotOffsetVersion.value++
    1014              :       }
    1015              :       // Reroute layouts outlive active-graph switches.
    1016         1757 :       this.pendingGlobalChanges = []
    1017         1757 :       this.isGlobalDispatchQueued = false
    1018         1757 :       this.pendingGeometryChanges = []
    1019         1757 :       this.isGeometryDispatchQueued = false
    1020              :     }, 'initialization')
    1021              :   }
    1022              : 
    1023              :   // Operation handlers
    1024              :   private handleMoveNode(
    1025              :     operation: MoveNodeOperation,
    1026              :     change: LayoutChange
    1027              :   ): boolean {
    1028        46553 :     const { nodeId } = operation
    1029        46553 :     const ynode = this.ynodes.get(
    1030              :       makeScopedLayoutKey(operation.graphId, nodeId)
    1031              :     )
    1032        46553 :     if (!ynode) return false
    1033              : 
    1034        46553 :     const size = yNodeToLayout(ynode).size
    1035              : 
    1036        46553 :     ynode.set('rect', [
    1037              :       operation.position.x,
    1038              :       operation.position.y,
    1039              :       size.width,
    1040              :       size.height
    1041              :     ])
    1042              : 
    1043        46553 :     change.nodeIds.push(nodeId)
    1044        46553 :     return true
    1045              :   }
    1046              : 
    1047              :   private handleResizeNode(
    1048              :     operation: ResizeNodeOperation,
    1049              :     change: LayoutChange
    1050              :   ): boolean {
    1051        36785 :     const { nodeId } = operation
    1052        36785 :     const ynode = this.ynodes.get(
    1053              :       makeScopedLayoutKey(operation.graphId, nodeId)
    1054              :     )
    1055        36785 :     if (!ynode) return false
    1056              : 
    1057        36785 :     const rect = ynode.get('rect')
    1058        36785 :     if (!isNodeRect(rect)) return false
    1059        36785 :     if (rect[2] !== operation.size.width || rect[3] !== operation.size.height) {
    1060        36776 :       change.sizeChangedNodeIds.push(nodeId)
    1061              :     }
    1062              : 
    1063        36785 :     ynode.set('rect', [
    1064              :       rect[0],
    1065              :       rect[1],
    1066              :       operation.size.width,
    1067              :       operation.size.height
    1068              :     ])
    1069              : 
    1070        36785 :     change.nodeIds.push(nodeId)
    1071        36785 :     return true
    1072              :   }
    1073              : 
    1074              :   private handleSetGroupBounds(operation: SetGroupBoundsOperation): boolean {
    1075          105 :     const ygroup = this.ygroups.get(
    1076              :       makeScopedLayoutKey(operation.graphId, operation.groupId)
    1077              :     )
    1078          105 :     if (!ygroup) return false
    1079              : 
    1080          105 :     setYGroupRect(ygroup, operation.position, operation.size)
    1081          105 :     return true
    1082              :   }
    1083              : 
    1084              :   private handleSetNodeZIndex(
    1085              :     operation: SetNodeZIndexOperation,
    1086              :     change: LayoutChange
    1087              :   ): boolean {
    1088         1559 :     const { nodeId } = operation
    1089         1559 :     const ynode = this.ynodes.get(
    1090              :       makeScopedLayoutKey(operation.graphId, nodeId)
    1091              :     )
    1092         1559 :     if (!ynode) return false
    1093              : 
    1094         1559 :     ynode.set('zIndex', operation.zIndex)
    1095         1559 :     this.highestZIndex = Math.max(this.highestZIndex, operation.zIndex)
    1096         1559 :     change.nodeIds.push(nodeId)
    1097         1559 :     return true
    1098              :   }
    1099              : 
    1100              :   private handleCreateNode(
    1101              :     operation: CreateNodeOperation,
    1102              :     change: LayoutChange
    1103              :   ): boolean {
    1104        23236 :     const { nodeId } = operation
    1105        23236 :     const nodeKey = makeScopedLayoutKey(operation.graphId, nodeId)
    1106        23236 :     if (this.ynodes.has(nodeKey)) return false
    1107              : 
    1108        23236 :     this.ynodes.set(nodeKey, layoutToYNode(operation.layout))
    1109        23236 :     this.highestZIndex = Math.max(this.highestZIndex, operation.layout.zIndex)
    1110              : 
    1111        23236 :     change.type = 'create'
    1112        23236 :     change.nodeIds.push(nodeId)
    1113        23236 :     return true
    1114              :   }
    1115              : 
    1116              :   private handleDeleteNode(
    1117              :     operation: DeleteNodeOperation,
    1118              :     change: LayoutChange
    1119              :   ): boolean {
    1120          248 :     const { nodeId } = operation
    1121          248 :     const nodeKey = makeScopedLayoutKey(operation.graphId, nodeId)
    1122          248 :     if (!this.ynodes.has(nodeKey)) return false
    1123              : 
    1124          248 :     this.ynodes.delete(nodeKey)
    1125          248 :     if (this.contentSizes.delete(nodeKey)) this._contentSizeVersion++
    1126          248 :     this.suppressedContentSizes.delete(nodeKey)
    1127          248 :     this.slotOffsets.delete(nodeKey)
    1128              :     // Link geometry is cleaned up per-link by LLink.disconnect as the node's
    1129              :     // connections are severed, so nothing to do here.
    1130              : 
    1131          248 :     change.type = 'delete'
    1132          248 :     change.nodeIds.push(nodeId)
    1133          248 :     return true
    1134              :   }
    1135              : 
    1136              :   private handleBatchUpdateBounds(
    1137              :     operation: BatchUpdateBoundsOperation,
    1138              :     change: LayoutChange
    1139              :   ): boolean {
    1140          381 :     for (const nodeId of operation.nodeIds) {
    1141          473 :       const bounds = operation.bounds[nodeId]
    1142          473 :       const ynode = this.ynodes.get(
    1143              :         makeScopedLayoutKey(operation.graphId, nodeId)
    1144              :       )
    1145          473 :       if (!ynode) continue
    1146              : 
    1147          473 :       const rect = ynode.get('rect')
    1148          473 :       if (
    1149              :         isNodeRect(rect) &&
    1150              :         (rect[2] !== bounds.width || rect[3] !== bounds.height)
    1151              :       ) {
    1152           19 :         change.sizeChangedNodeIds.push(nodeId)
    1153              :       }
    1154          473 :       ynode.set('rect', [bounds.x, bounds.y, bounds.width, bounds.height])
    1155              : 
    1156          473 :       change.nodeIds.push(nodeId)
    1157              :     }
    1158              : 
    1159          381 :     if (change.nodeIds.length) {
    1160          381 :       change.type = 'update'
    1161              :     }
    1162          381 :     return change.nodeIds.length > 0
    1163              :   }
    1164              : 
    1165              :   private handleCreateReroute(
    1166              :     operation: CreateRerouteOperation,
    1167              :     change: LayoutChange
    1168              :   ): boolean {
    1169           41 :     const rerouteKey = makeScopedLayoutKey(
    1170              :       operation.graphId,
    1171              :       operation.rerouteId
    1172              :     )
    1173           41 :     if (this.yreroutes.has(rerouteKey)) return false
    1174              : 
    1175           41 :     const rerouteData = new Y.Map<unknown>()
    1176           41 :     rerouteData.set('id', operation.rerouteId)
    1177           41 :     rerouteData.set('position', operation.position)
    1178              : 
    1179           41 :     this.yreroutes.set(rerouteKey, rerouteData)
    1180           41 :     change.type = 'create'
    1181           41 :     return true
    1182              :   }
    1183              : 
    1184              :   private handleDeleteReroute(
    1185              :     operation: DeleteRerouteOperation,
    1186              :     change: LayoutChange
    1187              :   ): boolean {
    1188            0 :     const rerouteKey = makeScopedLayoutKey(
    1189              :       operation.graphId,
    1190              :       operation.rerouteId
    1191              :     )
    1192            0 :     if (!this.yreroutes.has(rerouteKey)) return false
    1193              : 
    1194            0 :     this.yreroutes.delete(rerouteKey)
    1195            0 :     this.rerouteLayouts.delete(rerouteKey)
    1196            0 :     this.rerouteSpatialIndex.remove(rerouteKey)
    1197            0 :     change.type = 'delete'
    1198            0 :     return true
    1199              :   }
    1200              : 
    1201              :   private handleMoveReroute(
    1202              :     operation: MoveRerouteOperation,
    1203              :     change: LayoutChange
    1204              :   ): boolean {
    1205            5 :     const rerouteKey = makeScopedLayoutKey(
    1206              :       operation.graphId,
    1207              :       operation.rerouteId
    1208              :     )
    1209            5 :     const yreroute = this.yreroutes.get(rerouteKey)
    1210            5 :     if (!yreroute) return false
    1211              : 
    1212            5 :     yreroute.set('position', operation.position)
    1213            5 :     change.type = 'update'
    1214            5 :     return true
    1215              :   }
    1216              : 
    1217              :   /**
    1218              :    * Clean up all segment layouts for a link
    1219              :    */
    1220              :   private cleanupLinkSegments(linkId: LinkId): void {
    1221            0 :     const linkPrefix = `${linkId}:`
    1222            0 :     const keysToDelete: string[] = []
    1223            0 :     for (const [key] of this.linkSegmentLayouts) {
    1224            0 :       if (key.startsWith(linkPrefix)) {
    1225            0 :         keysToDelete.push(key)
    1226              :       }
    1227              :     }
    1228              : 
    1229            0 :     for (const key of keysToDelete) {
    1230            0 :       this.linkSegmentLayouts.delete(key)
    1231            0 :       this.linkSegmentSpatialIndex.remove(key)
    1232              :     }
    1233              :   }
    1234              : 
    1235              :   /**
    1236              :    * Projects a reroute's spatial-index entry from the current map state,
    1237              :    * rather than trusting an event's action, so replayed or externally
    1238              :    * applied updates converge to the same projection.
    1239              :    */
    1240              :   private projectReroute(key: ScopedLayoutKey): void {
    1241           62 :     const rerouteData = this.yreroutes.get(key)
    1242           62 :     if (!rerouteData) {
    1243           16 :       this.rerouteLayouts.delete(key)
    1244           16 :       this.rerouteSpatialIndex.remove(key)
    1245           16 :       return
    1246              :     }
    1247              : 
    1248           46 :     const parsed = parseLayoutKey(key)
    1249           46 :     const rerouteId = toRerouteId(Number(parsed.localId))
    1250           46 :     const position = this.getRerouteField(rerouteData, 'position')
    1251           46 :     this.updateRerouteLayout(
    1252              :       parsed.graphId,
    1253              :       rerouteId,
    1254              :       this.createRerouteLayout(rerouteId, position)
    1255              :     )
    1256              :   }
    1257              : 
    1258              :   /**
    1259              :    * Create reroute layout from position
    1260              :    */
    1261              :   private createRerouteLayout(
    1262              :     rerouteId: RerouteId,
    1263              :     position: Point
    1264              :   ): RerouteLayout {
    1265           46 :     return {
    1266              :       id: rerouteId,
    1267              :       position,
    1268              :       radius: REROUTE_RADIUS,
    1269              :       bounds: {
    1270              :         x: position.x - REROUTE_RADIUS,
    1271              :         y: position.y - REROUTE_RADIUS,
    1272              :         width: REROUTE_RADIUS * 2,
    1273              :         height: REROUTE_RADIUS * 2
    1274              :       }
    1275              :     }
    1276              :   }
    1277              : 
    1278              :   // Helper methods
    1279              : 
    1280              :   private queueChange(change: LayoutChange): void {
    1281       110816 :     const { graphId } = change.operation
    1282       110816 :     const hasNodeListener = change.nodeIds.some((nodeId) =>
    1283              :       this.nodeChangeListeners.has(makeScopedLayoutKey(graphId, nodeId))
    1284              :     )
    1285       110816 :     if (this.changeListeners.size === 0 && !hasNodeListener) return
    1286              : 
    1287       110816 :     this.pendingGlobalChanges.push(change)
    1288       110816 :     if (this.isGlobalDispatchQueued) return
    1289              : 
    1290         8126 :     this.isGlobalDispatchQueued = true
    1291         8126 :     queueMicrotask(() => {
    1292         8126 :       this.flushQueuedGlobalChanges()
    1293              :     })
    1294              :   }
    1295              : 
    1296              :   flushPendingChanges(): void {
    1297       126784 :     this.flushQueuedGlobalChanges()
    1298       126784 :     this.flushQueuedGeometryChanges()
    1299              :   }
    1300              : 
    1301              :   private flushQueuedGlobalChanges(): void {
    1302       134910 :     this.isGlobalDispatchQueued = false
    1303       134910 :     if (this.pendingGlobalChanges.length === 0) return
    1304              : 
    1305         8122 :     const queuedChanges = this.pendingGlobalChanges
    1306         8122 :     this.pendingGlobalChanges = []
    1307              : 
    1308         8122 :     queuedChanges.forEach((queuedChange) => {
    1309       110694 :       this.notifyNodeChange(queuedChange)
    1310       110694 :       this.notifyChange(queuedChange)
    1311              :     })
    1312              :   }
    1313              : 
    1314              :   private queueGeometryChange(graphIds: ReadonlySet<UUID>): void {
    1315       120760 :     if (this.geometryListeners.size === 0) return
    1316       120760 :     this.pendingGeometryChanges.push(graphIds)
    1317       120760 :     if (this.isGeometryDispatchQueued) return
    1318              : 
    1319         9942 :     this.isGeometryDispatchQueued = true
    1320         9942 :     queueMicrotask(() => {
    1321         9942 :       this.flushQueuedGeometryChanges()
    1322              :     })
    1323              :   }
    1324              : 
    1325              :   private flushQueuedGeometryChanges(): void {
    1326       136726 :     this.isGeometryDispatchQueued = false
    1327       136726 :     const changes = this.pendingGeometryChanges
    1328       136726 :     this.pendingGeometryChanges = []
    1329       136726 :     for (const change of changes) {
    1330       120638 :       for (const listener of this.geometryListeners) {
    1331       120638 :         try {
    1332       120638 :           listener(change)
    1333              :         } catch (error) {
    1334            0 :           this.reportListenerFailure(error, 'geometry', listener)
    1335              :         }
    1336              :       }
    1337              :     }
    1338              :   }
    1339              : 
    1340              :   private reportListenerFailure(
    1341              :     error: unknown,
    1342              :     scope: LayoutListenerScope,
    1343              :     listener: LayoutListener
    1344              :   ): void {
    1345            0 :     const reportedFailures = this.reportedListenerFailures[scope]
    1346            0 :     if (reportedFailures.has(listener)) return
    1347            0 :     reportedFailures.add(listener)
    1348              : 
    1349            0 :     reportError(error, {
    1350              :       surface: 'platform',
    1351              :       errorType: 'canvas_layout_listener_failed',
    1352              :       tags: {
    1353              :         failure_kind: 'caught_unexpected',
    1354              :         feature_area: 'canvas',
    1355              :         operation: 'sync',
    1356              :         outcome: 'failed',
    1357              :         listener_scope: scope
    1358              :       },
    1359              :       level: 'error'
    1360              :     })
    1361              :   }
    1362              : 
    1363              :   private notifyChange(change: LayoutChange): void {
    1364       110694 :     this.changeListeners.forEach((listener) => {
    1365       110694 :       try {
    1366       110694 :         listener(change)
    1367              :       } catch (error) {
    1368            0 :         this.reportListenerFailure(error, 'global', listener)
    1369              :       }
    1370              :     })
    1371              :   }
    1372              : 
    1373              :   private notifyNodeChange(change: LayoutChange): void {
    1374       110694 :     const { graphId } = change.operation
    1375       110694 :     for (const nodeId of new Set(change.nodeIds)) {
    1376       119436 :       const listeners = this.nodeChangeListeners.get(
    1377              :         makeScopedLayoutKey(graphId, nodeId)
    1378              :       )
    1379       119436 :       if (!listeners) continue
    1380              : 
    1381            0 :       listeners.forEach((listener) => {
    1382            0 :         try {
    1383            0 :           listener(change)
    1384              :         } catch (error) {
    1385            0 :           this.reportListenerFailure(error, 'node', listener)
    1386              :         }
    1387              :       })
    1388              :     }
    1389              :   }
    1390              : 
    1391              :   /**
    1392              :    * Batch update node bounds using Yjs transaction for atomicity.
    1393              :    */
    1394              :   batchUpdateNodeBounds(
    1395              :     rootGraphId: UUID,
    1396              :     updates: NodeBoundsUpdate[],
    1397              :     options: BatchUpdateBoundsOptions
    1398              :   ): void {
    1399          382 :     if (updates.length === 0) return
    1400              : 
    1401          381 :     const { source, boundsIncludeTitleHeight = false } = options
    1402          381 :     const nodeIds: NodeId[] = []
    1403          381 :     const boundsRecord: BatchUpdateBoundsOperation['bounds'] = {}
    1404              : 
    1405          381 :     for (const { nodeId, bounds } of updates) {
    1406          473 :       if (!this.ynodes.has(makeScopedLayoutKey(rootGraphId, nodeId))) continue
    1407              : 
    1408          473 :       boundsRecord[nodeId] = boundsIncludeTitleHeight
    1409              :         ? { ...bounds, height: removeNodeTitleHeight(bounds.height) }
    1410              :         : bounds
    1411          473 :       nodeIds.push(nodeId)
    1412              :     }
    1413              : 
    1414          381 :     if (!nodeIds.length) return
    1415              : 
    1416          381 :     this.applyOperation({
    1417              :       type: 'batchUpdateBounds',
    1418              :       graphId: rootGraphId,
    1419              :       nodeIds,
    1420              :       bounds: boundsRecord,
    1421              :       timestamp: Date.now(),
    1422              :       source,
    1423              :       actor: this.currentActor
    1424              :     })
    1425              :   }
    1426              : }
    1427              : 
    1428              : // Create singleton instance
    1429         2356 : export const layoutStore = new LayoutStoreImpl()
        

Generated by: LCOV version 2.0-1