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

            Line data    Source code
       1              : /**
       2              :  * Generic Vue Element Tracking System
       3              :  *
       4              :  * Automatically tracks DOM size and position changes for Vue-rendered elements
       5              :  * and syncs them to the layout store. Uses a single shared ResizeObserver for
       6              :  * performance, with elements identified by configurable data attributes.
       7              :  *
       8              :  * Supports different element types (nodes, slots, widgets, etc.) with
       9              :  * customizable data attributes and update handlers.
      10              :  */
      11              : import type { EffectScope, Ref } from 'vue'
      12              : import {
      13              :   effectScope,
      14              :   getCurrentInstance,
      15              :   onMounted,
      16              :   onUnmounted,
      17              :   watch
      18              : } from 'vue'
      19              : 
      20              : import { useDocumentVisibility } from '@vueuse/core'
      21              : 
      22              : import { useSharedCanvasPositionConversion } from '@/composables/element/useCanvasPositionConversion'
      23              : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
      24              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      25              : import { layoutStore } from '@/renderer/core/layout/store/layoutStore'
      26              : import { syncSlotOffsets } from '@/renderer/core/layout/slots/syncSlotOffsets'
      27              : import type {
      28              :   Bounds,
      29              :   Size2D as Size
      30              : } from '@comfyorg/shared-frontend-utils/geometry'
      31              : import type { NodeId } from '@/renderer/core/layout/types'
      32              : import { toNodeId } from '@comfyorg/graph-model/nodeId'
      33              : import { isSizeEqual } from '@/renderer/core/layout/utils/geometry'
      34              : import { removeNodeTitleHeight } from '@/renderer/core/layout/utils/nodeSizeUtil'
      35              : import type { UUID } from '@/utils/uuid'
      36              : 
      37              : /**
      38              :  * Generic update item for element bounds tracking
      39              :  */
      40              : interface ElementBoundsUpdate {
      41              :   id: NodeId
      42              :   /** Updated bounds */
      43              :   bounds: Bounds
      44              : }
      45              : 
      46              : interface CachedNodeMeasurement {
      47              :   rootGraphId: UUID
      48              :   nodeId: NodeId
      49              :   size: Size
      50              : }
      51              : 
      52              : /**
      53              :  * Configuration for different types of tracked elements
      54              :  */
      55              : interface ElementTrackingConfig {
      56              :   /** Data attribute name (e.g., 'nodeId') */
      57              :   dataAttribute: string
      58              :   syncSlots?: boolean
      59              :   /** Handler for processing bounds updates. Omit for signal-only entries. */
      60              :   updateHandler?: (updates: ElementBoundsUpdate[]) => void
      61              : }
      62              : 
      63              : /**
      64              :  * Registry of tracking configurations by element type
      65              :  */
      66         2355 : const trackingConfigs = new Map<string, ElementTrackingConfig>([
      67              :   [
      68              :     'node',
      69              :     {
      70              :       dataAttribute: 'nodeId',
      71              :       updateHandler: (updates) => {
      72         3018 :         const { rootGraphId } = useCanvasStore()
      73         3018 :         if (!rootGraphId) return
      74              : 
      75         3018 :         for (const { id, bounds } of updates) {
      76         9220 :           layoutStore.reportContentSize(rootGraphId, id, {
      77              :             width: bounds.width,
      78              :             height: removeNodeTitleHeight(bounds.height)
      79              :           })
      80              :         }
      81              :       }
      82              :     }
      83              :   ],
      84              :   ['widgets-grid', { dataAttribute: 'widgetsGridNodeId', syncSlots: true }]
      85              : ])
      86              : 
      87         2355 : const deferredElements = new Set<HTMLElement>()
      88         2355 : const elementsNeedingFreshMeasurement = new WeakSet<HTMLElement>()
      89         2355 : const cachedNodeMeasurements = new WeakMap<HTMLElement, CachedNodeMeasurement>()
      90         2355 : const trackedElements = new Set<HTMLElement>()
      91              : 
      92              : interface ResizeTracking {
      93              :   scope: EffectScope
      94              :   observer: ResizeObserver
      95              :   visibility: Ref<DocumentVisibilityState>
      96              : }
      97              : 
      98         2355 : let resizeTracking: ResizeTracking | undefined
      99              : 
     100        14909 : function markElementForFreshMeasurement(element: HTMLElement) {
     101        14909 :   elementsNeedingFreshMeasurement.add(element)
     102        14909 :   cachedNodeMeasurements.delete(element)
     103              : }
     104              : 
     105         3292 : function measureEntries(
     106              :   entries: ResizeObserverEntry[],
     107              :   { observer, visibility }: ResizeTracking
     108              : ) {
     109         3292 :   const { linearMode, rootGraphId } = useCanvasStore()
     110         3292 :   if (linearMode) return
     111              : 
     112         3245 :   if (visibility.value === 'hidden') {
     113            0 :     for (const entry of entries) {
     114            0 :       if (entry.target instanceof HTMLElement) {
     115            0 :         deferredElements.add(entry.target)
     116            0 :         observer.unobserve(entry.target)
     117              :       }
     118              :     }
     119            0 :     return
     120              :   }
     121              : 
     122         3161 :   const conv = useSharedCanvasPositionConversion()
     123         3161 :   const updatesByType = new Map<string, ElementBoundsUpdate[]>()
     124         3161 :   const slotSyncElements = new Map<NodeId, HTMLElement>()
     125         3226 :   for (const entry of entries) {
     126        17353 :     if (!(entry.target instanceof HTMLElement)) continue
     127        17353 :     const element = entry.target
     128              : 
     129        17353 :     let elementType: string | undefined
     130        17353 :     let elementId: string | undefined
     131              : 
     132        17353 :     for (const [type, config] of trackingConfigs) {
     133        25415 :       const id = element.dataset[config.dataAttribute]
     134        25415 :       if (id) {
     135        17353 :         elementType = type
     136        17353 :         elementId = id
     137        17353 :         break
     138              :       }
     139              :     }
     140              : 
     141        17353 :     if (!elementType || !elementId) continue
     142        17353 :     const config = trackingConfigs.get(elementType)
     143        17353 :     const nodeId = toNodeId(elementId)
     144        17353 :     if (config?.syncSlots) {
     145         8062 :       slotSyncElements.set(nodeId, element)
     146         8062 :       continue
     147              :     }
     148              : 
     149        17353 :     const borderBox = Array.isArray(entry.borderBoxSize)
     150              :       ? entry.borderBoxSize[0]
     151              :       : {
     152              :           inlineSize: entry.contentRect.width,
     153              :           blockSize: entry.contentRect.height
     154              :         }
     155        17353 :     const width = Math.max(0, borderBox.inlineSize)
     156        17353 :     const height = Math.max(0, borderBox.blockSize)
     157              : 
     158        17353 :     const nodeLayout =
     159              :       nodeId && rootGraphId
     160              :         ? layoutStore.getNodeLayout(rootGraphId, nodeId)
     161              :         : null
     162              :     const normalizedHeight = removeNodeTitleHeight(height)
     163        17353 :     const measuredSize = { width, height: normalizedHeight }
     164        17353 :     const previousMeasurement = cachedNodeMeasurements.get(element)
     165        17353 :     const reportedContentSize =
     166              :       nodeId && rootGraphId
     167              :         ? layoutStore.contentSizeOf(rootGraphId, nodeId)
     168              :         : undefined
     169        17353 :     const hasFreshMeasurementPending =
     170              :       elementsNeedingFreshMeasurement.has(element)
     171        17353 :     const hasMatchingCachedNodeMeasurement =
     172              :       previousMeasurement != null &&
     173              :       previousMeasurement.rootGraphId === rootGraphId &&
     174              :       previousMeasurement.nodeId === nodeId &&
     175              :       isSizeEqual(previousMeasurement.size, measuredSize) &&
     176              :       reportedContentSize != null &&
     177              :       isSizeEqual(reportedContentSize, measuredSize)
     178              : 
     179        17353 :     if (!hasFreshMeasurementPending && hasMatchingCachedNodeMeasurement) {
     180           71 :       continue
     181              :     }
     182         9220 :     if (rootGraphId) {
     183         9220 :       slotSyncElements.set(nodeId, element)
     184              :     }
     185              : 
     186        17353 :     const existingPos = nodeLayout?.position
     187        17353 :     let posX: number
     188        17353 :     let posY: number
     189        17353 :     if (existingPos) {
     190         9220 :       posX = existingPos.x
     191         9220 :       posY = existingPos.y
     192              :     } else {
     193            0 :       const rect = element.getBoundingClientRect()
     194            0 :       const [cx, cy] = conv.clientPosToCanvasPos([rect.left, rect.top])
     195            0 :       posX = cx
     196            0 :       posY = cy + LiteGraph.NODE_TITLE_HEIGHT
     197              :     }
     198         9220 :     const bounds: Bounds = {
     199              :       x: posX,
     200              :       y: posY,
     201              :       width,
     202              :       height
     203              :     }
     204         9220 :     elementsNeedingFreshMeasurement.delete(element)
     205        17353 :     if (nodeId && rootGraphId) {
     206         9220 :       cachedNodeMeasurements.set(element, {
     207              :         rootGraphId,
     208              :         nodeId,
     209              :         size: measuredSize
     210              :       })
     211         9220 :       element.dataset.measured = ''
     212              :     }
     213              : 
     214         9220 :     let updates = updatesByType.get(elementType)
     215        17341 :     if (!updates) {
     216         3018 :       updates = []
     217         3018 :       updatesByType.set(elementType, updates)
     218              :     }
     219         9220 :     updates.push({ id: nodeId, bounds })
     220              :   }
     221              : 
     222         3182 :   for (const [type, updates] of updatesByType) {
     223         3018 :     const config = trackingConfigs.get(type)
     224         3018 :     if (config?.updateHandler && updates.length) config.updateHandler(updates)
     225              :   }
     226         3161 :   if (rootGraphId) {
     227         3161 :     for (const [nodeId, element] of slotSyncElements) {
     228         9443 :       syncSlotOffsets(element, rootGraphId, nodeId)
     229              :     }
     230              :   }
     231              : }
     232              : 
     233         1743 : function createResizeTracking(scope: EffectScope): ResizeTracking {
     234         1743 :   const tracking: ResizeTracking = {
     235              :     scope,
     236              :     visibility: useDocumentVisibility(),
     237              :     observer: new ResizeObserver((entries) => measureEntries(entries, tracking))
     238              :   }
     239         1743 :   watch(tracking.visibility, (state) => {
     240           44 :     if (state !== 'visible' || deferredElements.size === 0) return
     241              : 
     242            0 :     for (const element of deferredElements) {
     243            0 :       if (element.isConnected) {
     244            0 :         tracking.observer.observe(element)
     245              :       }
     246              :     }
     247            0 :     deferredElements.clear()
     248              :   })
     249         1743 :   return tracking
     250              : }
     251              : 
     252         1743 : function startResizeTracking() {
     253         1743 :   const scope = effectScope(true)
     254         1743 :   return scope.run(() => createResizeTracking(scope))
     255              : }
     256              : 
     257          923 : function stopResizeTracking() {
     258          923 :   resizeTracking?.scope.stop()
     259          923 :   resizeTracking?.observer.disconnect()
     260          923 :   resizeTracking = undefined
     261          923 :   trackedElements.clear()
     262          923 :   deferredElements.clear()
     263              : }
     264              : 
     265        14909 : function trackElement(element: HTMLElement) {
     266        14909 :   trackedElements.add(element)
     267        14909 :   resizeTracking ??= startResizeTracking()
     268        14909 :   resizeTracking?.observer.observe(element)
     269              : }
     270              : 
     271         9760 : function untrackElement(element: HTMLElement) {
     272         9760 :   if (!trackedElements.delete(element)) return
     273         9760 :   resizeTracking?.observer.unobserve(element)
     274         9760 :   if (trackedElements.size === 0) stopResizeTracking()
     275              : }
     276              : 
     277              : import.meta.hot?.dispose(stopResizeTracking)
     278              : 
     279              : /**
     280              :  * Tracks DOM element size/position changes for a Vue component and syncs to layout store
     281              :  *
     282              :  * Sets up automatic ResizeObserver tracking when the component mounts and cleans up
     283              :  * when unmounted. The tracked element is identified by a data attribute set on the
     284              :  * component's root DOM element.
     285              :  *
     286              :  * @param appIdentifier - Application-level identifier for this tracked element (not a DOM ID)
     287              :  *                       Example: node ID like 'node-123', widget ID like 'widget-456'
     288              :  * @param trackingType - Type of element being tracked, determines which tracking config to use
     289              :  *                      Example: 'node' for Vue nodes, 'widget' for UI widgets
     290              :  *
     291              :  * @example
     292              :  * ```ts
     293              :  * // Track a Vue node component with ID 'my-node-123'
     294              :  * useVueElementTracking('my-node-123', 'node')
     295              :  *
     296              :  * // Would set data-node-id="my-node-123" on the component's root element
     297              :  * // and sync size changes to layoutStore.batchUpdateNodeBounds()
     298              :  * ```
     299              :  */
     300        14925 : export function useVueElementTracking(
     301              :   appIdentifier: string,
     302              :   trackingType: string
     303              : ) {
     304        14925 :   onMounted(() => {
     305        14925 :     const element = getCurrentInstance()?.proxy?.$el
     306        14925 :     if (!(element instanceof HTMLElement) || !appIdentifier) return
     307              : 
     308        14909 :     const config = trackingConfigs.get(trackingType)
     309        14914 :     if (!config) return
     310              : 
     311        14909 :     element.dataset[config.dataAttribute] = appIdentifier
     312        14909 :     markElementForFreshMeasurement(element)
     313        14909 :     trackElement(element)
     314              :   })
     315              : 
     316        14925 :   onUnmounted(() => {
     317         9760 :     const element = getCurrentInstance()?.proxy?.$el
     318         9760 :     if (!(element instanceof HTMLElement)) return
     319              : 
     320         9760 :     const config = trackingConfigs.get(trackingType)
     321         9760 :     if (!config) return
     322              : 
     323         9760 :     delete element.dataset[config.dataAttribute]
     324         9760 :     cachedNodeMeasurements.delete(element)
     325         9760 :     elementsNeedingFreshMeasurement.delete(element)
     326         9760 :     deferredElements.delete(element)
     327         9760 :     untrackElement(element)
     328              :   })
     329              : }
        

Generated by: LCOV version 2.0-1