LCOV - code coverage report
Current view: top level - src/renderer/extensions/minimap/composables - useMinimap.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 72.1 % 122 88
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import {
       2              :   useDocumentVisibility,
       3              :   useIntervalFn,
       4              :   usePreferredReducedMotion,
       5              :   useRafFn
       6              : } from '@vueuse/core'
       7              : import { computed, nextTick, ref, shallowRef, watch } from 'vue'
       8              : import type { ShallowRef } from 'vue'
       9              : 
      10              : import type { LGraph } from '@/lib/litegraph/src/litegraph'
      11              : import { useSettingStore } from '@/platform/settings/settingStore'
      12              : import {
      13              :   getMinimapDecorations,
      14              :   minimapDecorationRevision
      15              : } from '@/platform/canvas/minimapDecorationRegistry'
      16              : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
      17              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      18              : import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
      19              : 
      20              : import { MINIMAP_DECORATION_POP_MS } from '@/renderer/extensions/minimap/minimapCanvasRenderer'
      21              : import type {
      22              :   MinimapCanvas,
      23              :   MinimapSettingsKey
      24              : } from '@/renderer/extensions/minimap/types'
      25              : import { useMinimapGraph } from './useMinimapGraph'
      26              : import { useMinimapInteraction } from './useMinimapInteraction'
      27              : import { useMinimapRenderer } from './useMinimapRenderer'
      28              : import { useMinimapSettings } from './useMinimapSettings'
      29              : import { useMinimapViewport } from './useMinimapViewport'
      30              : 
      31              : /** How often to compare digests for state that emits no event; see the poll. */
      32         2355 : const CHANGE_DETECTION_INTERVAL_MS = 100
      33              : 
      34         2102 : export function useMinimap({
      35              :   canvasRefMaybe,
      36              :   containerRefMaybe
      37              : }: {
      38              :   canvasRefMaybe?: Readonly<ShallowRef<HTMLCanvasElement | null>>
      39              :   containerRefMaybe?: Readonly<ShallowRef<HTMLDivElement | null>>
      40              : } = {}) {
      41         2102 :   const canvasStore = useCanvasStore()
      42         2102 :   const workflowStore = useWorkflowStore()
      43         2102 :   const settingStore = useSettingStore()
      44              : 
      45         2102 :   const minimapRef = ref<HTMLElement | null>(null)
      46         2102 :   const canvasRef = canvasRefMaybe ?? shallowRef(null)
      47         2102 :   const containerRef = containerRefMaybe ?? shallowRef(null)
      48              : 
      49         2102 :   const visible = ref(true)
      50         2102 :   const initialized = ref(false)
      51         2102 :   const motionPreference = usePreferredReducedMotion()
      52              : 
      53         2102 :   const width = 250
      54         2102 :   const height = 200
      55              : 
      56         2102 :   const canvas = computed(() => canvasStore.canvas as MinimapCanvas | null)
      57         2102 :   const graph = computed(() => {
      58              :     // If we're in a subgraph, use that; otherwise use the canvas graph
      59              :     const activeSubgraph = workflowStore.activeSubgraph
      60         2272 :     return (activeSubgraph || canvas.value?.graph) as LGraph | null
      61              :   })
      62         2102 :   const decorations = computed(() => {
      63         8562 :     const revision = minimapDecorationRevision.value
      64              :     void revision
      65         8562 :     if (!graph.value) return []
      66         8562 :     const rows = getMinimapDecorations(graphScopeOf(graph.value))
      67              :     const reducedMotion =
      68              :       settingStore.get('Comfy.Appearance.DisableAnimations') ||
      69              :       motionPreference.value === 'reduce'
      70         8562 :     return reducedMotion
      71              :       ? rows.map((row) => ({
      72              :           ...row,
      73              :           enter: undefined,
      74              :           enteredAt: undefined
      75              :         }))
      76              :       : rows
      77              :   })
      78              : 
      79              :   // Settings
      80         2102 :   const settings = useMinimapSettings()
      81         2102 :   const {
      82              :     nodeColors,
      83              :     showLinks,
      84              :     showGroups,
      85              :     renderBypass,
      86              :     renderError,
      87              :     containerStyles,
      88              :     panelStyles
      89              :   } = settings
      90              : 
      91         2102 :   const updateOption = async (key: MinimapSettingsKey, value: boolean) => {
      92            0 :     await settingStore.set(key, value)
      93            0 :     renderer.forceFullRedraw()
      94            0 :     renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
      95              :   }
      96              : 
      97              :   // Viewport management
      98         2102 :   const viewport = useMinimapViewport(canvas, graph, width, height)
      99              : 
     100              :   // Interaction handling
     101         2102 :   const interaction = useMinimapInteraction(
     102              :     containerRef,
     103              :     viewport.bounds,
     104              :     viewport.scale,
     105              :     width,
     106              :     height,
     107              :     viewport.centerViewOn,
     108              :     canvas
     109              :   )
     110              : 
     111              :   // Two of the three useMinimap() call sites have no canvas. updateBounds()
     112              :   // runs before renderMinimap discovers there is nothing to draw, and it costs
     113              :   // a full layout-map rebuild, so every path that redraws checks this first.
     114         2102 :   const canDraw = computed(() => visible.value && !!canvasRef.value)
     115              : 
     116              :   // Graph events are hints to compare the digests, not commands to repaint:
     117              :   // graphChanged fires for plenty the minimap does not draw (zIndex from every
     118              :   // widget pointerdown, widget values, title edits), and the digest is the one
     119              :   // place that knows whether the picture moved.
     120         2102 :   const checkAndRepaint = () => {
     121        27506 :     if (!canDraw.value) return
     122        27492 :     if (graphManager.checkForChanges()) {
     123         8066 :       renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
     124              :     }
     125              :   }
     126              : 
     127         2102 :   const graphManager = useMinimapGraph(graph, () => checkAndRepaint())
     128              : 
     129              :   // Rendering
     130         2102 :   const renderer = useMinimapRenderer(
     131              :     canvasRef,
     132              :     graph,
     133              :     viewport.bounds,
     134              :     viewport.scale,
     135              :     graphManager.updateFlags,
     136              :     settings,
     137              :     width,
     138              :     height,
     139              :     decorations
     140              :   )
     141              : 
     142         2102 :   const decorationFrames = useRafFn(
     143              :     () => {
     144            0 :       const now = performance.now()
     145            0 :       if (
     146              :         !canDraw.value ||
     147              :         decorations.value.every(
     148              :           ({ enteredAt }) =>
     149              :             enteredAt === undefined ||
     150              :             now - enteredAt >= MINIMAP_DECORATION_POP_MS
     151              :         )
     152              :       ) {
     153            0 :         decorationFrames.pause()
     154            0 :         return
     155              :       }
     156            0 :       renderer.forceFullRedraw()
     157            0 :       renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
     158              :     },
     159              :     { immediate: false }
     160              :   )
     161              : 
     162         2102 :   const shouldAnimateDecorations = computed(
     163              :     () =>
     164              :       initialized.value &&
     165              :       canDraw.value &&
     166              :       decorations.value.some(
     167              :         ({ enteredAt }) =>
     168              :           enteredAt !== undefined &&
     169              :           performance.now() - enteredAt < MINIMAP_DECORATION_POP_MS
     170              :       )
     171              :   )
     172              : 
     173         2102 :   watch(
     174              :     shouldAnimateDecorations,
     175              :     (active) => {
     176         2102 :       if (!initialized.value || !canDraw.value) {
     177         2102 :         decorationFrames.pause()
     178         2102 :         return
     179              :       }
     180            0 :       renderer.forceFullRedraw()
     181            0 :       renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
     182            0 :       if (active) decorationFrames.resume()
     183            0 :       else decorationFrames.pause()
     184              :     },
     185              :     { immediate: true }
     186              :   )
     187              : 
     188              :   // Most edits reach the digest comparison through useMinimapGraph's event
     189              :   // hooks. This loop is the backstop for state that emits no event at all:
     190              :   // snapPoint mutating `_pos` elements in place, extensions assigning
     191              :   // `node.pos[0]` directly (only `size` is Proxy-wrapped against that),
     192              :   // `has_errors`, group drags, and execution-state transitions, which arrive
     193              :   // in executionStore rather than as graph events. Repaints happen only when
     194              :   // the digests move, so idle ticks cost one O(n) comparison and nothing else.
     195         2102 :   const { pause: pauseChangeDetection, resume: resumeChangeDetection } =
     196              :     useIntervalFn(checkAndRepaint, CHANGE_DETECTION_INTERVAL_MS, {
     197              :       immediate: false
     198              :     })
     199              : 
     200              :   // Polling is derived state, not something init() decides once. init() runs
     201              :   // synchronously from the immediate canvas watcher - before the template ref
     202              :   // has mounted - so any start decision taken there sees canvasRef as null and
     203              :   // the poll never starts. Deriving from the refs means the loop starts the
     204              :   // moment the canvas mounts and stops the moment any condition lapses.
     205              :   //
     206              :   // Document visibility is part of the condition because rAF was suspended
     207              :   // entirely on a hidden tab while setInterval is only clamped, and a tab that
     208              :   // is hidden at mount (middle-click, session restore) never fires a
     209              :   // visibilitychange to a transition-only watcher.
     210         2102 :   const documentVisibility = useDocumentVisibility()
     211         2102 :   const shouldPoll = computed(
     212              :     () =>
     213              :       initialized.value &&
     214              :       canDraw.value &&
     215              :       documentVisibility.value !== 'hidden'
     216              :   )
     217              : 
     218         2102 :   watch(
     219              :     shouldPoll,
     220              :     (active) => {
     221         4070 :       if (active) resumeChangeDetection()
     222         2103 :       else pauseChangeDetection()
     223              :     },
     224              :     { immediate: true }
     225              :   )
     226              : 
     227         2102 :   const init = async () => {
     228         2102 :     if (initialized.value) return
     229              : 
     230         2102 :     visible.value = settingStore.get('Comfy.Minimap.Visible')
     231              : 
     232         2102 :     if (canvas.value && graph.value) {
     233         2102 :       graphManager.init()
     234              : 
     235         2102 :       if (containerRef.value) {
     236            0 :         interaction.updateContainerRect()
     237              :       }
     238         2102 :       viewport.updateCanvasDimensions()
     239              : 
     240         2102 :       window.addEventListener('resize', interaction.updateContainerRect)
     241         2102 :       window.addEventListener('scroll', interaction.updateContainerRect)
     242         2102 :       window.addEventListener('resize', viewport.updateCanvasDimensions)
     243              : 
     244         2102 :       renderer.forceFullRedraw()
     245         2102 :       renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
     246         2102 :       viewport.updateViewport()
     247              : 
     248         2102 :       if (visible.value) viewport.startViewportSync()
     249         2102 :       initialized.value = true
     250              :     }
     251              :   }
     252              : 
     253         2102 :   const destroy = () => {
     254           68 :     pauseChangeDetection()
     255           68 :     decorationFrames.pause()
     256           68 :     viewport.stopViewportSync()
     257           68 :     graphManager.destroy()
     258              : 
     259           68 :     window.removeEventListener('resize', interaction.updateContainerRect)
     260           68 :     window.removeEventListener('scroll', interaction.updateContainerRect)
     261           68 :     window.removeEventListener('resize', viewport.updateCanvasDimensions)
     262              : 
     263           68 :     initialized.value = false
     264              :   }
     265              : 
     266         2102 :   watch(
     267              :     canvas,
     268              :     async (newCanvas, oldCanvas) => {
     269         2102 :       if (oldCanvas) {
     270            0 :         graphManager.cleanupEventListeners()
     271            0 :         pauseChangeDetection()
     272            0 :         viewport.stopViewportSync()
     273            0 :         graphManager.destroy()
     274            0 :         window.removeEventListener('resize', interaction.updateContainerRect)
     275            0 :         window.removeEventListener('scroll', interaction.updateContainerRect)
     276            0 :         window.removeEventListener('resize', viewport.updateCanvasDimensions)
     277              :       }
     278         2102 :       if (newCanvas && !initialized.value) {
     279         2102 :         await init()
     280              :       }
     281              :     },
     282              :     { immediate: true, flush: 'post' }
     283              :   )
     284              : 
     285              :   // Watch for graph changes (e.g., when navigating to/from subgraphs)
     286         2102 :   watch(graph, (newGraph, oldGraph) => {
     287          170 :     if (newGraph && newGraph !== oldGraph) {
     288          170 :       graphManager.cleanupEventListeners(oldGraph || undefined)
     289          170 :       graphManager.setupEventListeners()
     290          170 :       if (!canDraw.value) return
     291          166 :       renderer.forceFullRedraw()
     292          166 :       renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
     293              :     }
     294              :   })
     295              : 
     296         2102 :   watch(visible, async (isVisible) => {
     297            0 :     if (isVisible) {
     298            0 :       if (containerRef.value) {
     299            0 :         interaction.updateContainerRect()
     300              :       }
     301            0 :       viewport.updateCanvasDimensions()
     302              : 
     303            0 :       renderer.forceFullRedraw()
     304              : 
     305            0 :       await nextTick()
     306            0 :       await nextTick()
     307              : 
     308            0 :       renderer.updateMinimap(viewport.updateBounds, viewport.updateViewport)
     309            0 :       viewport.updateViewport()
     310            0 :       viewport.startViewportSync()
     311              :     } else {
     312            0 :       viewport.stopViewportSync()
     313              :     }
     314              :   })
     315              : 
     316         2102 :   const toggle = async () => {
     317            0 :     visible.value = !visible.value
     318            0 :     await settingStore.set('Comfy.Minimap.Visible', visible.value)
     319              :   }
     320              : 
     321         2102 :   const setMinimapRef = (ref: HTMLElement | null) => {
     322         1966 :     minimapRef.value = ref
     323              :   }
     324              : 
     325              :   // Dynamic viewport styles based on actual viewport transform
     326         2102 :   const viewportStyles = computed(() => {
     327         9906 :     const transform = viewport.viewportTransform.value
     328         9906 :     return {
     329              :       transform: `translate(${transform.x}px, ${transform.y}px)`,
     330              :       width: `${transform.width}px`,
     331              :       height: `${transform.height}px`,
     332              :       border: '2px solid var(--foreground)',
     333              :       backgroundColor: 'color-mix(in srgb, var(--foreground) 20%, transparent)',
     334              :       willChange: 'transform',
     335              :       backfaceVisibility: 'hidden' as const,
     336              :       perspective: '1000px',
     337              :       pointerEvents: 'none' as const
     338              :     }
     339              :   })
     340              : 
     341         2102 :   return {
     342              :     visible: computed(() => visible.value),
     343              :     initialized: computed(() => initialized.value),
     344              :     decorationCount: computed(() => decorations.value.length),
     345              : 
     346              :     containerStyles,
     347              :     viewportStyles,
     348              :     panelStyles,
     349              :     width,
     350              :     height,
     351              : 
     352              :     nodeColors,
     353              :     showLinks,
     354              :     showGroups,
     355              :     renderBypass,
     356              :     renderError,
     357              : 
     358              :     init,
     359              :     destroy,
     360              :     toggle,
     361              :     renderMinimap: renderer.renderMinimap,
     362              :     handlePointerDown: interaction.handlePointerDown,
     363              :     handlePointerMove: interaction.handlePointerMove,
     364              :     handlePointerUp: interaction.handlePointerUp,
     365              :     handlePointerCancel: interaction.handlePointerCancel,
     366              :     handleWheel: interaction.handleWheel,
     367              :     setMinimapRef,
     368              :     updateOption
     369              :   }
     370              : }
        

Generated by: LCOV version 2.0-1