LCOV - code coverage report
Current view: top level - src/utils - litegraphUtil.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 83.0 % 135 112
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { every, filter, head, isEmpty, isEqual, map } from 'es-toolkit/compat'
       2              : 
       3              : import type { ColorOption, LGraph } from '@/lib/litegraph/src/litegraph'
       4              : import type { ExecutedWsMessage } from '@comfyorg/api-client/executionTypes'
       5              : import {
       6              :   LGraphCanvas,
       7              :   LGraphGroup,
       8              :   LGraphNode,
       9              :   LiteGraph,
      10              :   isColorable
      11              : } from '@/lib/litegraph/src/litegraph'
      12              : import type {
      13              :   ExportedSubgraph,
      14              :   ISerialisableNodeInput,
      15              :   ISerialisedGraph
      16              : } from '@comfyorg/graph-model/serialisation'
      17              : import type {
      18              :   IBaseWidget,
      19              :   IComboWidget,
      20              :   WidgetCallbackOptions
      21              : } from '@comfyorg/graph-model/widgets'
      22              : import type { InputSpec } from '@comfyorg/object-info-parser/schemas/nodeDefSchemaV2'
      23              : import { inputSpecTree } from '@/core/graph/nodeDef/inputSpecInterpreter'
      24              : import { useApp } from '@/scripts/appInstance'
      25              : import { parseNodeLocatorId } from '@comfyorg/graph-model/nodeIdentification'
      26              : import type { SerializedNodeId } from '@comfyorg/graph-model/nodeId'
      27              : import { UNASSIGNED_NODE_ID, parseNodeId } from '@comfyorg/graph-model/nodeId'
      28              : import type { WidgetId } from '@comfyorg/graph-model/widgetId'
      29              : import {
      30              :   ensureUniqueWidgetNames,
      31              :   widgetId
      32              : } from '@comfyorg/graph-model/widgetId'
      33              : 
      34              : type ImageNode = LGraphNode & { imgs: HTMLImageElement[] | undefined }
      35              : type VideoNode = LGraphNode & {
      36              :   videoContainer: HTMLElement | undefined
      37              :   imgs: HTMLVideoElement[] | undefined
      38              : }
      39              : 
      40         6229 : export function isImageNode(node: LGraphNode | undefined): node is ImageNode {
      41         6229 :   if (!node) return false
      42         6229 :   return (
      43              :     node.previewMediaType === 'image' ||
      44              :     (node.previewMediaType !== 'video' && !!node.imgs?.length)
      45              :   )
      46              : }
      47              : 
      48          778 : export function isVideoNode(node: LGraphNode | undefined): node is VideoNode {
      49          778 :   if (!node) return false
      50          778 :   return node.previewMediaType === 'video' || !!node.videoContainer
      51              : }
      52              : 
      53              : /**
      54              :  * Check if output data indicates animated content (animated webp/png or video).
      55              :  */
      56         1076 : export function isAnimatedOutput(
      57              :   output: Pick<ExecutedWsMessage['output'], 'animated'> | undefined
      58              : ): boolean {
      59         1076 :   return !!output?.animated?.find(Boolean)
      60              : }
      61              : 
      62              : /**
      63              :  * Check if output data indicates video content (animated but not webp/png).
      64              :  */
      65          361 : export function isVideoOutput(
      66              :   output: ExecutedWsMessage['output'] | undefined
      67              : ): boolean {
      68          361 :   if (!isAnimatedOutput(output)) return false
      69              : 
      70          361 :   const isAnimatedWebp = output?.images?.some((img) =>
      71              :     img.filename?.endsWith('.webp')
      72              :   )
      73          361 :   const isAnimatedPng = output?.images?.some((img) =>
      74              :     img.filename?.endsWith('.png')
      75              :   )
      76          361 :   return !isAnimatedWebp && !isAnimatedPng
      77              : }
      78              : 
      79           24 : export function isAudioNode(node: LGraphNode | undefined): boolean {
      80           24 :   return !!node && node.previewMediaType === 'audio'
      81              : }
      82              : 
      83         3226 : export function resolveComboValues(widget: IComboWidget): (string | number)[] {
      84         3226 :   const values = widget.options.values
      85         3226 :   if (typeof values === 'function') return values(widget)
      86         3226 :   if (Array.isArray(values)) return values
      87            4 :   return Object.keys(values)
      88              : }
      89              : 
      90           48 : export function addToComboValues(
      91              :   widget: Pick<IComboWidget, 'options'>,
      92              :   value: string
      93              : ) {
      94           48 :   const values = widget.options.values
      95           48 :   if (Array.isArray(values) && !values.includes(value)) {
      96           34 :     values.push(value)
      97              :   }
      98              : }
      99              : 
     100              : /**
     101              :  * True while the canvas is a picking surface rather than an editable one: its
     102              :  * own `selectOnly` flag is set, or the interaction mode the application
     103              :  * injected reads select-only (ADR-CANVAS-INTERACTION-0035).
     104              :  *
     105              :  * The canvas pointer and key dispatch and the command store read the mode
     106              :  * themselves. The document-level paste, drop and history listeners guard with
     107              :  * this helper, so a new document-level edit path has to opt in.
     108              :  */
     109         2356 : export const isSelectOnly = (canvas: LGraphCanvas | undefined): boolean =>
     110              :   canvas?.selectOnly === true
     111              : 
     112         2356 : export const isLGraphNode = (item: unknown): item is LGraphNode => {
     113         7928 :   return item instanceof LGraphNode
     114              : }
     115              : 
     116         2356 : export const isLGraphGroup = (item: unknown): item is LGraphGroup => {
     117         3328 :   return item instanceof LGraphGroup
     118              : }
     119              : 
     120              : /**
     121              :  * Get the color option of all canvas items if they are all the same.
     122              :  * @param items - The items to get the color option of.
     123              :  * @returns The color option of the item.
     124              :  */
     125         2356 : export const getItemsColorOption = (items: unknown[]): ColorOption | null => {
     126          193 :   const validItems = filter(items, isColorable)
     127          193 :   if (isEmpty(validItems)) return null
     128              : 
     129          179 :   const colorOptions = map(validItems, (item) => item.getColorOption())
     130              : 
     131          193 :   return every(colorOptions, (option) => isEqual(option, head(colorOptions)))
     132              :     ? head(colorOptions)!
     133              :     : null
     134              : }
     135              : 
     136          150 : export function executeWidgetsCallback(
     137              :   nodes: LGraphNode[],
     138              :   callbackName: 'onRemove' | 'beforeQueued' | 'afterQueued',
     139              :   options?: WidgetCallbackOptions
     140              : ) {
     141          150 :   for (const node of nodes) {
     142          599 :     for (const widget of node.widgets ?? []) {
     143         1455 :       widget[callbackName]?.(options)
     144              :     }
     145              :   }
     146              : }
     147              : 
     148              : /**
     149              :  * Since frontend version 1.16, forceInput input is no longer treated
     150              :  * as widget. So we need to remove the dummy widget value serialized
     151              :  * from workflows prior to v1.16.
     152              :  * Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3326
     153              :  *
     154              :  * @param nodeDef the node definition
     155              :  * @param widgets the widgets on the node instance (from node definition)
     156              :  * @param widgetsValues the widgets values to populate the node during configuration
     157              :  * @returns the widgets values without the dummy widget values
     158              :  */
     159        23346 : export function migrateWidgetsValues<TWidgetValue>(
     160              :   inputDefs: Record<string, InputSpec>,
     161              :   widgets: IBaseWidget[],
     162              :   widgetsValues: TWidgetValue[]
     163              : ): TWidgetValue[] {
     164        23346 :   if (
     165              :     Object.values(inputDefs).some((input) =>
     166              :       inputSpecTree(input).some((spec) => spec.type === 'COMFY_DYNAMICGROUP_V3')
     167              :     )
     168              :   )
     169           38 :     return widgetsValues
     170              : 
     171        23308 :   const widgetNames = new Set(widgets.map((w) => w.name))
     172        23308 :   const originalWidgetsInputs = Object.values(inputDefs).filter(
     173              :     (input) => widgetNames.has(input.name) || input.forceInput
     174              :   )
     175        23308 :   const skippedWidgetNames = new Set(
     176              :     map(
     177              :       filter(widgets, (widget) => widget.serialize === false),
     178              :       (widget) => widget.name
     179              :     )
     180              :   )
     181              : 
     182        23308 :   const widgetIndexHasForceInput = originalWidgetsInputs.flatMap((input) => {
     183        43034 :     if (skippedWidgetNames.has(input.name)) return []
     184        43034 :     return input.control_after_generate
     185              :       ? [!!input.forceInput, false]
     186              :       : [!!input.forceInput]
     187              :   })
     188              : 
     189        23308 :   const serializableWidgetCount = filter(
     190              :     widgets,
     191              :     (widget) => widget.serialize !== false
     192              :   ).length
     193        23346 :   if (
     194              :     !widgetIndexHasForceInput.includes(true) &&
     195              :     widgetsValues.length === serializableWidgetCount
     196              :   ) {
     197        20587 :     return widgetsValues
     198              :   }
     199              : 
     200         2721 :   const compactedWidgetValues = filter(
     201              :     widgetsValues,
     202              :     (_, index) => widgets[index]?.serialize !== false
     203              :   )
     204        23346 :   const alignedWidgetValues =
     205              :     compactedWidgetValues.length === widgetIndexHasForceInput.length
     206              :       ? compactedWidgetValues
     207              :       : widgetsValues.length === widgetIndexHasForceInput.length
     208              :         ? widgetsValues
     209              :         : undefined
     210              : 
     211        23346 :   if (!alignedWidgetValues) return widgetsValues
     212              : 
     213          159 :   return filter(
     214              :     alignedWidgetValues,
     215              :     (_, index) => !widgetIndexHasForceInput[index]
     216              :   )
     217              : }
     218              : 
     219              : /**
     220              :  * Compress widget input slots by removing all unconnected widget input slots.
     221              :  * This should match the serialization format of legacy widget conversion.
     222              :  *
     223              :  * @param graph - The graph to compress widget input slots for.
     224              :  * @throws If an infinite loop is detected.
     225              :  */
     226          275 : export function compressWidgetInputSlots(graph: ISerialisedGraph) {
     227          275 :   for (const node of graph.nodes) {
     228         1141 :     node.inputs = node.inputs?.filter(matchesLegacyApi)
     229              : 
     230         1141 :     for (const [inputIndex, input] of node.inputs?.entries() ?? []) {
     231         1504 :       if (input.link) {
     232         1176 :         const link = graph.links.find((link) => link[0] === input.link)
     233         1176 :         if (link) {
     234         1176 :           link[4] = inputIndex
     235              :         }
     236              :       }
     237              :     }
     238              :   }
     239              : 
     240          275 :   compressSubgraphWidgetInputSlots(graph.definitions?.subgraphs)
     241              : }
     242              : 
     243         3814 : function matchesLegacyApi(input: ISerialisableNodeInput) {
     244         3814 :   return !(input.widget && input.link === null && !input.label)
     245              : }
     246              : 
     247              : /**
     248              :  * Duplication to handle the legacy link arrays in the root workflow.
     249              :  * @see compressWidgetInputSlots
     250              :  * @param subgraph The subgraph to compress widget input slots for.
     251              :  */
     252          312 : function compressSubgraphWidgetInputSlots(
     253              :   subgraphs: ExportedSubgraph[] | undefined,
     254              :   visited = new WeakSet<ExportedSubgraph>()
     255              : ) {
     256          312 :   if (!subgraphs) return
     257              : 
     258           42 :   for (const subgraph of subgraphs) {
     259           37 :     if (visited.has(subgraph)) throw new Error('Infinite loop detected')
     260           37 :     visited.add(subgraph)
     261              : 
     262           37 :     if (subgraph.nodes) {
     263           37 :       for (const node of subgraph.nodes) {
     264           54 :         node.inputs = node.inputs?.filter(matchesLegacyApi)
     265              : 
     266           54 :         if (!subgraph.links) continue
     267              : 
     268           54 :         for (const [inputIndex, input] of node.inputs?.entries() ?? []) {
     269          216 :           if (input.link) {
     270           91 :             const link = subgraph.links.find((link) => link.id === input.link)
     271           91 :             if (link) link.target_slot = inputIndex
     272              :           }
     273              :         }
     274              :       }
     275              :     }
     276              : 
     277           37 :     compressSubgraphWidgetInputSlots(subgraph.definitions?.subgraphs, visited)
     278              :   }
     279              : }
     280              : 
     281         7637 : export function getLinkTypeColor(typeName: string): string {
     282         7637 :   return LGraphCanvas.link_type_colors[typeName] ?? LiteGraph.LINK_COLOR
     283              : }
     284              : 
     285         8790 : export function resolveNode(
     286              :   nodeId: SerializedNodeId,
     287              :   graph: LGraph | null | undefined = useApp().rootGraph
     288              : ): LGraphNode | undefined {
     289         8790 :   const parsedNodeId = parseNodeId(nodeId)
     290         8790 :   if (!graph || !parsedNodeId) return undefined
     291         8790 :   const found = graph.getNodeById(parsedNodeId)
     292         8790 :   if (found) return found
     293          222 :   for (const sg of graph.subgraphs.values()) {
     294          186 :     const node = sg.getNodeById(parsedNodeId)
     295          186 :     if (node) return node
     296              :   }
     297              :   return undefined
     298              : }
     299            0 : export function resolveNodeWidget(
     300              :   nodeId: SerializedNodeId,
     301              :   widgetName?: string,
     302              :   graph: LGraph = useApp().rootGraph
     303              : ): [LGraphNode, IBaseWidget] | [LGraphNode] | [] {
     304            0 :   if (widgetName && typeof nodeId === 'string') {
     305            0 :     const locator = parseNodeLocatorId(nodeId)
     306            0 :     if (locator?.subgraphUuid) {
     307            0 :       const host = graph.getNodeById(locator.localNodeId)
     308            0 :       if (host?.isSubgraphNode()) {
     309            0 :         const widget = host.widgets.find((w) => w.name === widgetName)
     310            0 :         return widget ? [host, widget] : []
     311              :       }
     312              :     }
     313              :   }
     314              : 
     315            0 :   const parsedNodeId = parseNodeId(nodeId)
     316            0 :   if (!parsedNodeId) return []
     317              : 
     318            0 :   const node = graph.getNodeById(parsedNodeId)
     319            0 :   if (!widgetName) return node ? [node] : []
     320            0 :   if (node) {
     321            0 :     const widget = node.widgets?.find((w) => w.name === widgetName)
     322            0 :     return widget ? [node, widget] : []
     323              :   }
     324              : 
     325            0 :   return []
     326              : }
     327              : 
     328         6813 : export function getWidgetIdForNode(
     329              :   node: LGraphNode,
     330              :   widget: Pick<IBaseWidget, 'name' | 'widgetId'>
     331              : ): WidgetId | undefined {
     332         6813 :   if (widget.widgetId) return widget.widgetId
     333         6813 :   const graphId = node.graph?.rootGraph.id
     334         6813 :   const nodeId = parseNodeId(node.id)
     335         6813 :   if (!graphId || !nodeId || nodeId === UNASSIGNED_NODE_ID) return undefined
     336            0 :   const liveEntry = [...mapLiveWidgetsById(node)].find(
     337              :     ([, candidate]) => candidate === widget
     338              :   )
     339            0 :   if (liveEntry) return liveEntry[0]
     340            0 :   return widgetId(graphId, nodeId, widget.name)
     341              : }
     342              : 
     343              : /**
     344              :  * Maps a node's live widgets to their {@link WidgetId}. Building the map once
     345              :  * lets callers resolve widgets by id in O(1) instead of rescanning.
     346              :  */
     347        18963 : export function mapLiveWidgetsById(
     348              :   node: LGraphNode
     349              : ): Map<WidgetId, IBaseWidget> {
     350        18963 :   const byId = new Map<WidgetId, IBaseWidget>()
     351        18963 :   const widgets = node.widgets ?? []
     352        18963 :   const distinctWidgets = [...new Set(widgets)]
     353        18963 :   const namesAreUnique = ensureUniqueWidgetNames(distinctWidgets)
     354        18963 :   const graphId = node.graph?.rootGraph.id
     355        18963 :   const nodeId = parseNodeId(node.id)
     356        18963 :   const usedNames = new Set<string>()
     357        18963 :   const reservedNames = new Set(distinctWidgets.map(({ name }) => name))
     358        18963 :   for (const widget of distinctWidgets) {
     359        47489 :     let name = widget.name
     360        47489 :     if (!namesAreUnique && usedNames.has(name)) {
     361            0 :       let suffix = 1
     362            0 :       while (
     363              :         usedNames.has(`${name}#${suffix}`) ||
     364              :         reservedNames.has(`${name}#${suffix}`)
     365              :       ) {
     366            0 :         suffix++
     367              :       }
     368            0 :       name = `${name}#${suffix}`
     369              :     }
     370        47489 :     usedNames.add(name)
     371        47489 :     const id =
     372              :       widget.widgetId ??
     373              :       (graphId && nodeId && nodeId !== UNASSIGNED_NODE_ID
     374              :         ? widgetId(graphId, nodeId, name)
     375              :         : undefined)
     376        47489 :     if (id) byId.set(id, widget)
     377              :   }
     378        18963 :   return byId
     379              : }
     380              : 
     381          124 : export function isLoad3dNode(node: LGraphNode) {
     382          124 :   return (
     383              :     node.type && (node.type === 'Load3D' || node.type === 'Load3DAnimation')
     384              :   )
     385              : }
        

Generated by: LCOV version 2.0-1