LCOV - code coverage report
Current view: top level - src/core/graph/widgets - dynamicGroupWidget.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 89.3 % 224 200
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { t } from '@/i18n'
       2              : import { SUBGRAPH_INPUT_ID } from '@/lib/litegraph/src/constants'
       3              : import type { LGraph, Subgraph } from '@/lib/litegraph/src/LGraph'
       4              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
       5              : import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode'
       6              : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
       7              : import { VueOnlyWidget } from '@/lib/litegraph/src/widgets/VueOnlyWidget'
       8              : import {
       9              :   captureInputLayout,
      10              :   inputLink,
      11              :   replaceNodeInputs
      12              : } from '@/lib/litegraph/src/node/slotLinks'
      13              : import {
      14              :   getWidgetIds,
      15              :   resolveNodeRootGraphId
      16              : } from '@/lib/litegraph/src/utils/widget'
      17              : import { transformInputSpecV1ToV2 } from '@comfyorg/object-info-parser/migration'
      18              : import type { InputSpec } from '@comfyorg/object-info-parser'
      19              : import { zDynamicGroupInputSpec } from '@comfyorg/object-info-parser'
      20              : import { useLitegraphServiceAccess } from '@/core/graph/litegraphServiceAccess'
      21              : import { useNodeDefStore } from '@/stores/nodeDefStore'
      22              : import { useWidgetValueStore } from '@/stores/widgetValueStore'
      23              : import { deriveWidgetSurfaces } from '@/types/widgetVisibility'
      24              : import { mapUniqueNodes } from '@/utils/graphTraversalUtil'
      25              : import { isSubgraph } from '@/utils/typeGuardUtil'
      26              : 
      27              : import {
      28              :   dynamicGroupRowAllocationBound,
      29              :   isRemoteDynamicGroupRowWrite,
      30              :   markDynamicGroupController,
      31              :   reportDynamicGroupRowRefusal
      32              : } from './dynamicGroupDiagnostics'
      33              : 
      34           40 : export function dynamicGroupWidget(
      35              :   node: LGraphNode,
      36              :   inputName: string,
      37              :   inputData: InputSpec
      38              : ) {
      39           40 :   const {
      40              :     min,
      41              :     max,
      42              :     template,
      43              :     group_name = inputName
      44              :   } = zDynamicGroupInputSpec.parse(inputData)[1]
      45           40 :   const fields = { ...template.required, ...template.optional }
      46           40 :   const store = useWidgetValueStore()
      47           40 :   const { addNodeInput } = useLitegraphServiceAccess()
      48           40 :   const controller: IBaseWidget = node.addCustomWidget({
      49              :     name: inputName,
      50              :     type: 'number',
      51              :     value: min,
      52              :     y: 0,
      53              :     hidden: true,
      54              :     options: { min, max, socketless: true, serialize: false }
      55              :   })
      56           40 :   markDynamicGroupController(controller, Object.keys(fields).length)
      57           40 :   node.addCustomWidget(
      58              :     new DynamicGroupNoticeWidget(
      59              :       {
      60              :         name: `${inputName}.$notice`,
      61              :         label: group_name,
      62              :         type: 'dynamic_group_notice',
      63              :         value: undefined,
      64              :         y: 0,
      65              :         serialize: false,
      66              :         options: {
      67              :           socketless: true,
      68              :           serialize: false,
      69              :           surfaces: { canvas: 'shown', vueNode: 'never', panel: 'never' }
      70              :         }
      71              :       },
      72              :       node
      73              :     )
      74              :   )
      75           40 :   const initialCount = controller.value
      76           40 :   let rowCount = 0
      77           40 :   const add: IBaseWidget = node.addCustomWidget({
      78              :     name: `${inputName}.$add`,
      79              :     label: t('dynamicGroup.add', { group: group_name }),
      80              :     type: 'button',
      81              :     value: undefined,
      82              :     y: 0,
      83              :     serialize: false,
      84              :     options: {
      85              :       socketless: true,
      86              :       serialize: false,
      87              :       iconClass: 'icon-[lucide--plus]',
      88              :       surfaces: { canvas: 'never', vueNode: 'shown', panel: 'shown' }
      89              :     },
      90              :     callback: () =>
      91              :       changeRows(() => {
      92           20 :         if (
      93              :           rows().length < max &&
      94              :           rows().length < dynamicGroupRowAllocationBound(controller)
      95              :         )
      96           20 :           controller.value = rows().length + 1
      97              :       })
      98              :   })
      99              : 
     100          578 :   function rows() {
     101          578 :     return (node.widgets ?? []).filter(
     102              :       (widget) =>
     103              :         widget.type === 'dynamic_group_row' &&
     104              :         widget.name.startsWith(`${inputName}.`)
     105              :     )
     106              :   }
     107              : 
     108          106 :   function publish() {
     109          106 :     const headers = rows()
     110          106 :     rowCount = headers.length
     111          106 :     headers.forEach((header, index) => {
     112          125 :       header.label = t('dynamicGroup.row', {
     113              :         group: group_name,
     114              :         index: index + 1
     115              :       })
     116          125 :       header.options.disabled = headers.length <= min
     117              :     })
     118          106 :     add.options.disabled =
     119              :       min > dynamicGroupRowAllocationBound(controller) ||
     120              :       headers.length >= max ||
     121              :       headers.length >= dynamicGroupRowAllocationBound(controller)
     122          106 :     if (controller.widgetId) store.setValue(controller.widgetId, headers.length)
     123          106 :     const graphId = resolveNodeRootGraphId(node)
     124          106 :     if (graphId && node.widgets)
     125           65 :       store.setNodeWidgetOrder(graphId, node.id, getWidgetIds(node.widgets))
     126              :   }
     127              : 
     128           26 :   function changeRows(change: () => void) {
     129           26 :     const graph = node.graph
     130           26 :     graph?.beforeChange()
     131           26 :     graph?.canvasAction((canvas) => canvas.emitBeforeChange())
     132           26 :     try {
     133           26 :       change()
     134           26 :       node.setSize([node.size[0], node.computeSize([...node.size])[1]])
     135              :     } finally {
     136           26 :       graph?.afterChange()
     137           26 :       graph?.canvasAction((canvas) => canvas.emitAfterChange())
     138           26 :       node.setDirtyCanvas(true, true)
     139              :     }
     140              :   }
     141              : 
     142            6 :   function removeRow(index: number, hosts = createPromotionHostLookup()) {
     143            6 :     if (!node.widgets) return false
     144            6 :     const prefix = `${inputName}.${index}`
     145            6 :     const removed = node.widgets.filter(
     146              :       (widget) => widget.name === prefix || widget.name.startsWith(`${prefix}.`)
     147              :     )
     148            6 :     if (!removed.length) return false
     149            6 :     if (!removeRowInputs(prefix, hosts)) return false
     150            6 :     for (const widget of removed.reverse()) {
     151           24 :       if (node.widgets.includes(widget)) node.removeWidget(widget)
     152              :     }
     153            6 :     for (const header of rows()) {
     154           12 :       const oldPrefix = header.name
     155           12 :       const row = Number(oldPrefix.slice(inputName.length + 1))
     156           12 :       if (row <= index) continue
     157              :       const newPrefix = `${inputName}.${row - 1}`
     158            6 :       renameRow(oldPrefix, newPrefix, hosts)
     159              :     }
     160            6 :     return true
     161              :   }
     162              : 
     163            6 :   function removeRowInputs(prefix: string, hosts: PromotionHostLookup) {
     164            6 :     const previous = captureInputLayout(node)
     165            6 :     const inputs = previous.inputs.filter(
     166              :       (input) => !input.name.startsWith(`${prefix}.`)
     167              :     )
     168            6 :     const graph = node.graph
     169            6 :     const promotedInputs = new Set(
     170              :       previous.inputs.flatMap((input) => {
     171           66 :         const link = previous.links.get(input)
     172           66 :         return isSubgraph(graph) &&
     173              :           !inputs.includes(input) &&
     174              :           link?.origin_id === SUBGRAPH_INPUT_ID
     175              :           ? [graph.inputs[link.origin_slot]]
     176              :           : []
     177              :       })
     178              :     )
     179              :     const result = replaceNodeInputs(
     180              :       node,
     181              :       previous,
     182              :       inputs,
     183              :       previous.links,
     184              :       true
     185              :     )
     186            6 :     if (!result.ok) return false
     187            6 :     for (const link of node.graph?.floatingLinks.values() ?? []) {
     188            0 :       if (link.target_id !== node.id) continue
     189            0 :       const slot = inputs.indexOf(previous.inputs[link.target_slot])
     190            0 :       if (slot === -1) node.graph?.removeFloatingLink(link)
     191            0 :       else link.target_slot = slot
     192              :     }
     193            6 :     previous.inputs.forEach((input, slot) => {
     194           66 :       if (!inputs.includes(input)) node.onInputRemoved?.(slot, input)
     195              :     })
     196            6 :     if (isSubgraph(graph))
     197            2 :       for (const input of promotedInputs)
     198            3 :         disconnectOrphanedPromotion(graph, graph.inputs.indexOf(input), hosts)
     199            6 :     return true
     200              :   }
     201              : 
     202          582 :   function fieldLabel(
     203              :     index: number,
     204              :     field: string,
     205              :     row = t('dynamicGroup.row', { group: group_name, index: index + 1 })
     206              :   ) {
     207          582 :     return `${row} ${fields[field][1]?.display_name ?? field}`
     208              :   }
     209              : 
     210            6 :   function renameRowLabels(
     211              :     oldIndex: number,
     212              :     newIndex: number,
     213              :     hosts: PromotionHostLookup,
     214              :     rowLabel?: string
     215              :   ) {
     216            6 :     for (const field of Object.keys(fields)) {
     217           18 :       const name = `${inputName}.${newIndex}.${field}`
     218           18 :       const slot = node.findInputSlot(name)
     219           18 :       const input = slot === -1 ? undefined : node.inputs[slot]
     220           18 :       const previous =
     221              :         input?.localized_name ?? fieldLabel(oldIndex, field, rowLabel)
     222           18 :       const next = fieldLabel(newIndex, field)
     223           18 :       const widget = node.widgets?.find((widget) => widget.name === name)
     224           18 :       if (widget?.label === previous) widget.label = next
     225           18 :       if (!input) continue
     226           18 :       if (input.label === previous) input.label = next
     227           18 :       input.localized_name = next
     228           18 :       renamePromotedInputLabel(node, slot, previous, next, hosts)
     229              :     }
     230              :   }
     231              : 
     232            6 :   function renameRowWidgets(oldPrefix: string, newPrefix: string) {
     233            6 :     for (const widget of node.widgets ?? []) {
     234           74 :       if (widget.name !== oldPrefix && !widget.name.startsWith(`${oldPrefix}.`))
     235           50 :         continue
     236           24 :       const name = newPrefix + widget.name.slice(oldPrefix.length)
     237           24 :       widget.name = name
     238           74 :       if (
     239              :         widget.name === name &&
     240              :         widget.serialize !== false &&
     241              :         widget.type !== 'button' &&
     242              :         widget.widgetId
     243              :       )
     244           18 :         store.announceValue(widget.widgetId)
     245              :     }
     246              :   }
     247              : 
     248            6 :   function renameRow(
     249              :     oldPrefix: string,
     250              :     newPrefix: string,
     251              :     hosts: PromotionHostLookup
     252              :   ) {
     253            6 :     const rowLabel = rows().find((row) => row.name === oldPrefix)?.label
     254            6 :     renameRowWidgets(oldPrefix, newPrefix)
     255            6 :     for (const input of node.inputs) {
     256           45 :       if (!input.name.startsWith(`${oldPrefix}.`)) continue
     257           18 :       input.name = newPrefix + input.name.slice(oldPrefix.length)
     258           18 :       if (input.widget) input.widget.name = input.name
     259              :     }
     260            6 :     renameRowLabels(
     261              :       Number(oldPrefix.slice(inputName.length + 1)),
     262              :       Number(newPrefix.slice(inputName.length + 1)),
     263              :       hosts,
     264              :       rowLabel
     265              :     )
     266              :   }
     267              : 
     268           94 :   function addRow(index: number, hosts: PromotionHostLookup) {
     269           94 :     const previousSize: [number, number] = [...node.size]
     270           94 :     const start = node.widgets?.length ?? 0
     271           94 :     const previous = captureInputLayout(node)
     272           94 :     const header: IBaseWidget = node.addCustomWidget({
     273              :       name: `${inputName}.${index}`,
     274              :       type: 'dynamic_group_row',
     275              :       value: undefined,
     276              :       y: 0,
     277              :       serialize: false,
     278              :       options: {
     279              :         socketless: true,
     280              :         serialize: false,
     281              :         surfaces: { canvas: 'never', vueNode: 'shown', panel: 'shown' }
     282              :       },
     283              :       callback: () => {
     284            6 :         if (rows().length <= min) return
     285            6 :         changeRows(() => {
     286            6 :           const requested = rows().length - 1
     287            6 :           if (!removeRow(Number(header.name.slice(inputName.length + 1))))
     288            0 :             reportDynamicGroupRowRefusal(
     289              :               node,
     290              :               'remove_row',
     291              :               requested,
     292              :               rows().length
     293              :             )
     294            6 :           publish()
     295              :         })
     296              :       }
     297              :     })
     298           94 :     addRowFields(index, hosts)
     299           94 :     const addedInputs = node.inputs.splice(previous.inputs.length)
     300           94 :     const inputs = [
     301              :       ...previous.inputs,
     302              :       ...addedInputs.filter(
     303              :         (added) => !previous.inputs.some((input) => input.name === added.name)
     304              :       )
     305              :     ]
     306              :     const result = replaceNodeInputs(node, previous, inputs, previous.links)
     307           94 :     if (!result.ok) {
     308            0 :       for (const widget of (node.widgets?.slice(start) ?? []).reverse())
     309            0 :         node.removeWidget(widget)
     310            0 :       node.setSize(previousSize)
     311            0 :       return false
     312              :     }
     313           94 :     for (const addedInput of addedInputs) {
     314          282 :       const existing = previous.inputs.find(
     315              :         (input) => input.name === addedInput.name
     316              :       )
     317          282 :       if (existing) existing.widget = addedInput.widget
     318              :     }
     319           94 :     const widgets = node.widgets
     320           94 :     if (!widgets) return false
     321           94 :     const added = widgets.splice(start)
     322           94 :     widgets.splice(widgets.indexOf(add), 0, ...added)
     323           94 :     return true
     324              :   }
     325              : 
     326          282 :   function updateInputLabel(
     327              :     name: string,
     328              :     label: string,
     329              :     hosts: PromotionHostLookup
     330              :   ) {
     331          282 :     const slot = node.findInputSlot(name)
     332          282 :     if (slot === -1) return
     333          282 :     const input = node.inputs[slot]
     334          282 :     const previous = input.localized_name
     335          282 :     if (!input.label || input.label === previous) input.label = label
     336          282 :     input.localized_name = label
     337          282 :     if (previous) renamePromotedInputLabel(node, slot, previous, label, hosts)
     338          282 :     return input
     339              :   }
     340              : 
     341           94 :   function addRowFields(index: number, hosts: PromotionHostLookup) {
     342           94 :     for (const [fields, isOptional] of [
     343              :       [template.required, false],
     344              :       [template.optional, true]
     345              :     ] as const) {
     346          188 :       for (const [field, spec] of Object.entries(fields ?? {})) {
     347          282 :         const name = `${inputName}.${index}.${field}`
     348          282 :         const refreshed = useNodeDefStore().getInputSpecForWidget(node, name)
     349          282 :         const fieldStart = node.widgets?.length ?? 0
     350          282 :         addNodeInput(node, {
     351              :           ...(refreshed ??
     352              :             transformInputSpecV1ToV2(spec, { name, isOptional })),
     353              :           display_name: fieldLabel(index, field)
     354              :         })
     355          282 :         const input = updateInputLabel(name, fieldLabel(index, field), hosts)
     356          282 :         let auxiliaryIndex = 0
     357          282 :         node.widgets?.slice(fieldStart).forEach((widget) => {
     358          282 :           const options = widget.options
     359          282 :           options.surfaces = {
     360              :             ...deriveWidgetSurfaces(widget),
     361              :             canvas: 'never'
     362              :           }
     363          282 :           widget.options = options
     364          282 :           if (widget.name === name) {
     365          282 :             if (input?.label) widget.label = input.label
     366          282 :             return
     367              :           }
     368            0 :           widget.label ??= widget.name
     369            0 :           widget.name = `${name}.${auxiliaryIndex++}`
     370              :         })
     371              :       }
     372              :     }
     373              :   }
     374              : 
     375          100 :   function announceAddedValues(existing: Set<IBaseWidget>) {
     376          100 :     for (const widget of node.widgets ?? []) {
     377          912 :       if (
     378              :         !existing.has(widget) &&
     379              :         widget.serialize !== false &&
     380              :         widget.type !== 'button' &&
     381              :         widget.widgetId
     382              :       )
     383          276 :         store.announceValue(widget.widgetId)
     384              :     }
     385              :   }
     386              : 
     387          100 :   function assertWithinAllocationBound(requested: number): void {
     388          100 :     if (requested <= dynamicGroupRowAllocationBound(controller)) return
     389            0 :     if (!isRemoteDynamicGroupRowWrite(node))
     390            0 :       reportDynamicGroupRowRefusal(node, 'add_row', requested, rowCount)
     391            0 :     throw new RangeError(
     392              :       `Row count exceeds the allocation bound for DynamicGroup '${inputName}'`
     393              :     )
     394              :   }
     395              : 
     396          100 :   function resizeRows(count: number) {
     397          100 :     const hosts = createPromotionHostLookup()
     398          100 :     for (let index = rows().length - 1; index >= count; index--) {
     399            0 :       if (!removeRow(index, hosts)) break
     400              :     }
     401          100 :     const existing = new Set(node.widgets)
     402          100 :     while (rows().length < count) {
     403           94 :       if (!addRow(rows().length, hosts)) break
     404              :     }
     405          100 :     publish()
     406          100 :     announceAddedValues(existing)
     407          100 :     if (rowCount !== count)
     408            0 :       reportDynamicGroupRowRefusal(
     409              :         node,
     410              :         rowCount > count ? 'remove_row' : 'add_row',
     411              :         count,
     412              :         rowCount
     413              :       )
     414              :   }
     415              : 
     416           40 :   Object.defineProperty(controller, 'value', {
     417              :     get: () => rowCount,
     418              :     set(value: unknown) {
     419          100 :       if (typeof value !== 'number' || !Number.isFinite(value)) return
     420              :       const requested = Math.max(0, Math.trunc(value))
     421          100 :       const count = Math.max(min, requested)
     422          100 :       assertWithinAllocationBound(count)
     423          100 :       resizeRows(count)
     424              :     }
     425              :   })
     426           40 :   controller.value = initialCount
     427           40 :   return { widget: controller }
     428              : }
     429              : 
     430              : type PromotionHostLookup = (subgraph: Subgraph) => SubgraphNode[]
     431              : 
     432          106 : function createPromotionHostLookup(): PromotionHostLookup {
     433          106 :   let hosts: Map<Subgraph, SubgraphNode[]> | undefined
     434          106 :   return (subgraph) => {
     435           42 :     if (!hosts) {
     436           14 :       hosts = new Map()
     437           14 :       for (const host of mapUniqueNodes(subgraph.rootGraph, (node) =>
     438              :         node.isSubgraphNode() ? node : undefined
     439              :       )) {
     440            2 :         const instances = hosts.get(host.subgraph) ?? []
     441            2 :         instances.push(host)
     442            2 :         hosts.set(host.subgraph, instances)
     443              :       }
     444              :     }
     445           42 :     return hosts.get(subgraph) ?? []
     446              :   }
     447              : }
     448              : 
     449          303 : function renamePromotedInputLabel(
     450              :   node: LGraphNode,
     451              :   slot: number,
     452              :   previous: string,
     453              :   next: string,
     454              :   hosts: PromotionHostLookup
     455              : ) {
     456          303 :   const graph = node.graph
     457          303 :   if (!isSubgraph(graph)) return
     458          165 :   const link = inputLink(graph, node.id, slot)
     459          303 :   if (link?.origin_id !== SUBGRAPH_INPUT_ID) return
     460           39 :   const promoted = graph.inputs[link.origin_slot]
     461          123 :   if (promoted.label !== previous) return
     462           39 :   graph.renameInput(promoted, next)
     463           99 :   for (const host of hosts(graph))
     464            3 :     renamePromotedInputLabel(host, link.origin_slot, previous, next, hosts)
     465              : }
     466              : 
     467            3 : function disconnectOrphanedPromotion(
     468              :   graph: LGraph | Subgraph | null,
     469              :   slot: number,
     470              :   hosts: PromotionHostLookup
     471              : ) {
     472            3 :   if (!isSubgraph(graph) || graph.inputs[slot]?.linkIds.length !== 0) return
     473            3 :   const input = graph.inputs[slot]
     474            3 :   for (const host of hosts(graph)) {
     475            3 :     removeFloatingHostLinks(host, slot)
     476            3 :     const link = host.graph && inputLink(host.graph, host.id, slot)
     477            3 :     if (!link) continue
     478            0 :     host.disconnectInput(slot)
     479            0 :     if (link.origin_id === SUBGRAPH_INPUT_ID)
     480            0 :       disconnectOrphanedPromotion(host.graph, link.origin_slot, hosts)
     481              :   }
     482            3 :   graph.removeInput(input)
     483            3 :   if (!graph.inputs.includes(input)) removeFloatingLinksFrom(graph, slot)
     484              : }
     485              : 
     486            3 : function removeFloatingLinksFrom(graph: Subgraph, slot: number) {
     487            3 :   for (const link of graph.floatingLinks.values()) {
     488            0 :     if (link.origin_id !== SUBGRAPH_INPUT_ID) continue
     489            0 :     if (link.origin_slot === slot) graph.removeFloatingLink(link)
     490            0 :     else if (link.origin_slot > slot) link.origin_slot--
     491              :   }
     492              : }
     493              : 
     494            3 : function removeFloatingHostLinks(host: SubgraphNode, slot: number) {
     495            3 :   for (const link of host.graph?.floatingLinks.values() ?? [])
     496            0 :     if (link.target_id === host.id && link.target_slot === slot)
     497            0 :       host.graph?.removeFloatingLink(link)
     498              : }
     499              : 
     500         2356 : class DynamicGroupNoticeWidget extends VueOnlyWidget<IBaseWidget> {
     501              :   protected get vueOnlyLabel(): string {
     502           16 :     return this.label ?? this.name
     503              :   }
     504              : }
        

Generated by: LCOV version 2.0-1