LCOV - code coverage report
Current view: top level - src/core/graph/widgets - dynamicWidgets.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 92.1 % 340 313
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { range, remove } from 'es-toolkit'
       2              : import { shallowReactive } from 'vue'
       3              : 
       4              : import { assert } from '@/base/assert'
       5              : import { useChainCallback } from '@/composables/functional/useChainCallback'
       6              : import type { ISlotType } from '@comfyorg/graph-model/interfaces'
       7              : import type { INodeInputSlot } from '@comfyorg/graph-model/slots'
       8              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
       9              : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
      10              : import type { LLink } from '@/lib/litegraph/src/LLink'
      11              : import { commonType } from '@/lib/litegraph/src/utils/type'
      12              : import {
      13              :   getWidgetIds,
      14              :   resolveNodeRootGraphId
      15              : } from '@/lib/litegraph/src/utils/widget'
      16              : import { transformInputSpecV1ToV2 } from '@comfyorg/object-info-parser/migration'
      17              : import type { ComboInputSpec, InputSpec } from '@comfyorg/object-info-parser'
      18              : import type { InputSpec as InputSpecV2 } from '@comfyorg/object-info-parser/schemas/nodeDefSchemaV2'
      19              : import {
      20              :   zAutogrowOptions,
      21              :   zDynamicComboInputSpec,
      22              :   zMatchTypeOptions
      23              : } from '@comfyorg/object-info-parser'
      24              : import { useLitegraphServiceAccess } from '@/core/graph/litegraphServiceAccess'
      25              : import { useApp } from '@/scripts/appInstance'
      26              : import type { ComfyApp } from '@/types/comfy'
      27              : import {
      28              :   captureInputLayout,
      29              :   replaceNodeInputs
      30              : } from '@/lib/litegraph/src/node/slotLinks'
      31              : import type { InputLayoutSnapshot } from '@/lib/litegraph/src/node/slotLinks'
      32              : import { useLinkStore } from '@/stores/linkStore'
      33              : import { graphScopeOf } from '@comfyorg/graph-model/graphScopeId'
      34              : import { useWidgetValueStore } from '@/stores/widgetValueStore'
      35              : import type { WidgetValue } from '@/types/simplifiedWidget'
      36              : import { widgetId } from '@comfyorg/graph-model/widgetId'
      37              : import { dynamicGroupWidget } from './dynamicGroupWidget'
      38              : import { realignInputLinkSlots } from '@/lib/litegraph/src/linkDeduplication'
      39              : import type { ISerialisedNode } from '@comfyorg/graph-model/serialisation'
      40              : 
      41              : type MatchTypeNode = LGraphNode &
      42              :   Pick<Required<LGraphNode>, 'onConnectionsChange'> & {
      43              :     comfyDynamic: { matchType: Record<string, Record<string, string>> }
      44              :   }
      45              : type AutogrowNode = LGraphNode &
      46              :   Pick<Required<LGraphNode>, 'onConnectionsChange' | 'widgets'> & {
      47              :     comfyDynamic: {
      48              :       autogrow: Record<
      49              :         string,
      50              :         {
      51              :           min: number
      52              :           max: number
      53              :           inputSpecs: InputSpecV2[]
      54              :           prefix?: string
      55              :           names?: string[]
      56              :         }
      57              :       >
      58              :     }
      59              :   }
      60              : 
      61          506 : function commitMutatedInputs(
      62              :   node: LGraphNode,
      63              :   previous: InputLayoutSnapshot,
      64              :   assignments: ReadonlyMap<INodeInputSlot, LLink>
      65              : ) {
      66          506 :   const finalInputs = [...node.inputs]
      67          506 :   node.inputs.splice(0, node.inputs.length, ...previous.inputs)
      68          506 :   return replaceNodeInputs(node, previous, finalInputs, assignments)
      69              : }
      70              : 
      71          132 : function syncNodeWidgetOrder(node: LGraphNode) {
      72          132 :   const graphId = resolveNodeRootGraphId(node)
      73          132 :   if (!graphId || !node.widgets) return
      74           64 :   useWidgetValueStore().setNodeWidgetOrder(
      75              :     graphId,
      76              :     node.id,
      77              :     getWidgetIds(node.widgets)
      78              :   )
      79              : }
      80              : 
      81            0 : function ensureWidgetForInput(node: LGraphNode, input: INodeInputSlot) {
      82            0 :   node.widgets ??= []
      83            0 :   const { widget } = input
      84            0 :   if (widget && node.widgets.some((w) => w.name === widget.name)) return
      85            0 :   node.widgets.push({
      86              :     draw(ctx, _n, _w, y) {
      87            0 :       ctx.save()
      88            0 :       ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR
      89            0 :       ctx.fillText(input.label ?? input.name, 20, y + 15)
      90            0 :       ctx.restore()
      91              :     },
      92              :     name: input.name,
      93              :     options: {},
      94              :     serialize: false,
      95              :     type: 'shim',
      96              :     y: 0
      97              :   })
      98            0 :   input.alwaysVisible = true
      99            0 :   input.widget = { name: input.name }
     100              : }
     101              : 
     102           71 : function dynamicComboWidget(
     103              :   node: LGraphNode,
     104              :   inputName: string,
     105              :   untypedInputData: InputSpec,
     106              :   appArg: ComfyApp,
     107              :   widgetName?: string
     108              : ) {
     109           71 :   const { addNodeInput } = useLitegraphServiceAccess()
     110           71 :   const { deleteWidget } = useWidgetValueStore()
     111           71 :   const parseResult = zDynamicComboInputSpec.safeParse(untypedInputData)
     112           71 :   if (!parseResult.success) throw new Error('invalid DynamicCombo spec')
     113           71 :   const inputData = parseResult.data
     114           71 :   const options = Object.fromEntries(
     115              :     inputData[1].options.map(({ key, inputs }) => [key, inputs])
     116              :   )
     117           71 :   const subSpec: ComboInputSpec = [Object.keys(options), {}]
     118           71 :   const result = useApp().widgets.COMBO(
     119              :     node,
     120              :     inputName,
     121              :     subSpec,
     122              :     appArg,
     123              :     widgetName
     124              :   )
     125           71 :   assert(
     126              :     result && 'widget' in result && result.widget,
     127              :     'COMBO widget constructor returned no widget'
     128              :   )
     129           71 :   const { widget, minWidth, minHeight } = result
     130           71 :   const removedWidgetValues = new Map<
     131              :     string | undefined,
     132              :     Map<string, { type: string; value: WidgetValue }>
     133              :   >()
     134           71 :   let activeOption = widget.value as string | undefined
     135          974 :   function isInGroup(e: { name: string }): boolean {
     136          974 :     return e.name.startsWith(inputName + '.')
     137              :   }
     138          132 :   function restoreRemovedValues(
     139              :     value: string | undefined,
     140              :     widgetNames: string[]
     141              :   ) {
     142          132 :     const widgets = node.widgets
     143          132 :     if (!widgets) return
     144          132 :     const graphId = resolveNodeRootGraphId(node)
     145          132 :     const removedValues = removedWidgetValues.get(value)
     146          132 :     const names = new Set(widgetNames)
     147          144 :     for (const name of removedValues?.keys() ?? []) names.add(name)
     148          132 :     for (const name of names) {
     149          185 :       const addedWidget = widgets.find((widget) => widget.name === name)
     150          185 :       if (!addedWidget) continue
     151          185 :       const removed = removedValues?.get(name)
     152          185 :       const positionalIndex = widgets
     153              :         .filter((widget) => widget.serialize !== false)
     154              :         .indexOf(addedWidget)
     155              :       const restored =
     156              :         graphId && positionalIndex >= 0
     157              :           ? useWidgetValueStore().getRestoredWidgetValue(
     158              :               graphId,
     159              :               node.id,
     160              :               addedWidget,
     161              :               positionalIndex
     162              :             )
     163              :           : undefined
     164          185 :       if (!restored && removed?.type === addedWidget.type) {
     165            9 :         addedWidget.value = removed.value
     166              :       }
     167              :     }
     168              :   }
     169           71 :   const updateWidgets = (value?: string) => {
     170          132 :     if (!node.widgets) throw new Error('Not Reachable')
     171          132 :     const newSpec = value ? options[value] : undefined
     172          132 :     const removedOption = activeOption
     173          132 :     activeOption = value
     174              : 
     175          132 :     const previous = captureInputLayout(node)
     176          132 :     const inputLinks = new Map(previous.links)
     177          132 :     const removedInputs = remove(node.inputs, isInGroup)
     178          132 :     for (const widget of remove(node.widgets, isInGroup)) {
     179           94 :       const optionValues = removedWidgetValues.get(removedOption) ?? new Map()
     180           94 :       optionValues.set(widget.name, {
     181              :         type: widget.type,
     182              :         value: widget.value
     183              :       })
     184           94 :       removedWidgetValues.set(removedOption, optionValues)
     185           94 :       widget.onRemove?.()
     186           94 :       if (widget.widgetId) deleteWidget(widget.widgetId)
     187              :     }
     188              : 
     189          132 :     if (!newSpec) {
     190              :       const result = commitMutatedInputs(node, previous, inputLinks)
     191            0 :       if (!result.ok) return
     192            0 :       syncNodeWidgetOrder(node)
     193            0 :       return
     194              :     }
     195              : 
     196          132 :     const insertionPoint = node.widgets.findIndex((w) => w === widget) + 1
     197          132 :     const startingLength = node.widgets.length
     198          132 :     const startingInputLength = node.inputs.length
     199              : 
     200          132 :     if (insertionPoint === 0)
     201            0 :       throw new Error("Dynamic widget doesn't exist on node")
     202              :     const inputTypes: (Record<string, InputSpec> | undefined)[] = [
     203              :       newSpec.required,
     204              :       newSpec.optional
     205              :     ]
     206          132 :     inputTypes.forEach((inputType, idx) => {
     207          264 :       for (const key in inputType ?? {}) {
     208          240 :         const name = `${widget.name}.${key}`
     209          240 :         const specToAdd = transformInputSpecV1ToV2(inputType![key], {
     210              :           name,
     211              :           isOptional: idx !== 0
     212              :         })
     213          240 :         specToAdd.display_name = key
     214          240 :         addNodeInput(node, specToAdd)
     215              :       }
     216              :     })
     217              : 
     218          132 :     const inputInsertionPoint =
     219              :       node.inputs.findIndex((i) => i.name === widget.name) + 1
     220          132 :     const addedWidgets = node.widgets.splice(startingLength)
     221          132 :     const addedWidgetNames = addedWidgets.map(({ name }) => name)
     222          132 :     node.widgets.splice(insertionPoint, 0, ...addedWidgets)
     223          132 :     syncNodeWidgetOrder(node)
     224          132 :     if (inputInsertionPoint === 0) {
     225           71 :       if (
     226              :         addedWidgets.length === 0 &&
     227              :         node.inputs.length !== startingInputLength
     228              :       )
     229              :         //input is inputOnly, but lacks an insertion point
     230            0 :         throw new Error('Failed to find input socket for ' + widget.name)
     231              :       const result = commitMutatedInputs(node, previous, inputLinks)
     232           71 :       if (!result.ok) return
     233           71 :       restoreRemovedValues(value, addedWidgetNames)
     234           71 :       return
     235              :     }
     236           61 :     const addedInputs = node.inputs
     237              :       .splice(startingInputLength)
     238              :       .map((addedInput) => {
     239          114 :         const existingInput = node.inputs.findIndex(
     240              :           (existingInput) => addedInput.name === existingInput.name
     241              :         )
     242          114 :         return existingInput === -1
     243              :           ? addedInput
     244              :           : node.inputs.splice(existingInput, 1)[0]
     245              :       })
     246              :     //assume existing inputs are in correct order
     247           61 :     node.inputs.splice(inputInsertionPoint, 0, ...addedInputs)
     248              : 
     249          120 :     for (const input of removedInputs) {
     250          142 :       const replacement = node.inputs.find((item) => item.name === input.name)
     251          142 :       const link = inputLinks.get(input)
     252          142 :       if (replacement && link) inputLinks.set(replacement, link)
     253              :     }
     254           61 :     const result = commitMutatedInputs(node, previous, inputLinks)
     255          124 :     if (!result.ok) return
     256              :     //A callback can grow the group it lands on, shifting every input after
     257              :     //it, so the slot captured before the batch is stale for later entries.
     258          113 :     for (const { input, link } of result.replacements) {
     259           21 :       const slot = node.inputs.indexOf(input)
     260           21 :       if (slot === -1) continue
     261           21 :       node.onConnectionsChange?.(LiteGraph.INPUT, slot, true, link, input)
     262              :     }
     263           61 :     restoreRemovedValues(value, addedWidgetNames)
     264              : 
     265          123 :     if (!node.graph) return
     266           60 :     node._setConcreteSlots()
     267           60 :     node.arrange()
     268           60 :     node.graph.setDirtyCanvas(true, true)
     269              :   }
     270              :   //Refit height on the callback channel: interaction fires it after the value
     271              :   //setter, while configure (load, clone, paste) only fires the setter and must
     272              :   //keep the serialised height.
     273           71 :   widget.callback = useChainCallback(widget.callback, () => {
     274           11 :     node.size = [node.size[0], node.computeSize([...node.size])[1]]
     275           11 :     node.graph?.setDirtyCanvas(true, true)
     276              :   })
     277              :   //A little hacky, but onConfigure won't work.
     278              :   //It fires too late and is overly disruptive
     279           71 :   let widgetValue = widget.value
     280           71 :   const getState = () => {
     281         1527 :     const graphId = resolveNodeRootGraphId(node)
     282         1527 :     if (!graphId) return undefined
     283         1458 :     return useWidgetValueStore().getWidget(
     284              :       widgetId(graphId, node.id, widget.name)
     285              :     )
     286              :   }
     287           71 :   Object.defineProperty(widget, 'value', {
     288              :     get() {
     289         1395 :       return getState()?.value ?? widgetValue
     290              :     },
     291              :     set(value) {
     292          132 :       const state = getState()
     293          132 :       if (state) state.value = value
     294          132 :       widgetValue = value
     295          132 :       updateWidgets(value)
     296              :     }
     297              :   })
     298           71 :   widget.value = widgetValue
     299           71 :   return { widget, minWidth, minHeight }
     300              : }
     301              : 
     302         2356 : export const dynamicWidgets = {
     303              :   COMFY_DYNAMICCOMBO_V3: dynamicComboWidget,
     304              :   COMFY_DYNAMICGROUP_V3: dynamicGroupWidget
     305              : }
     306         2356 : const dynamicInputs: Record<
     307              :   string,
     308              :   (node: LGraphNode, inputSpec: InputSpecV2) => void
     309              : > = {
     310              :   COMFY_AUTOGROW_V3: applyAutogrow,
     311              :   COMFY_MATCHTYPE_V3: applyMatchType
     312              : }
     313              : 
     314        29806 : export function applyDynamicInputs(
     315              :   node: LGraphNode,
     316              :   inputSpec: InputSpecV2
     317              : ): boolean {
     318        29806 :   if (!(inputSpec.type in dynamicInputs)) return false
     319              :   //TODO: move parsing/validation of inputSpec here?
     320          202 :   dynamicInputs[inputSpec.type](node, inputSpec)
     321          202 :   return true
     322              : }
     323              : 
     324           32 : function changeOutputType(
     325              :   node: LGraphNode,
     326              :   slot: number,
     327              :   combinedType: ISlotType
     328              : ) {
     329           32 :   const output = node.outputs[slot]
     330           32 :   if (output.type === combinedType) return
     331           11 :   output.type = combinedType
     332              : 
     333              :   //check and potentially remove links
     334           25 :   if (!node.graph) return
     335           11 :   const topologies = useLinkStore().getOutputSlotLinks(
     336              :     graphScopeOf(node.graph),
     337              :     node.id,
     338              :     slot
     339              :   )
     340           24 :   for (const topology of topologies) {
     341           12 :     const link = node.graph.getLink(topology.id)
     342           12 :     if (!link) continue
     343           12 :     const { input, inputNode, subgraphOutput } = link.resolve(node.graph)
     344           12 :     const inputType = (input ?? subgraphOutput)?.type
     345           12 :     if (!inputType) continue
     346           12 :     const keep = LiteGraph.isValidConnection(combinedType, inputType)
     347           12 :     if (!keep && subgraphOutput) subgraphOutput.disconnect()
     348           12 :     else if (!keep && inputNode) inputNode.disconnectInput(link.target_slot)
     349           12 :     if (input && inputNode?.onConnectionsChange)
     350           10 :       inputNode.onConnectionsChange(
     351              :         LiteGraph.INPUT,
     352              :         link.target_slot,
     353              :         keep,
     354              :         link,
     355              :         input
     356              :       )
     357              :   }
     358              : }
     359              : 
     360           44 : function withComfyMatchType(node: LGraphNode): asserts node is MatchTypeNode {
     361           44 :   if (node.comfyDynamic?.matchType) return
     362           26 :   node.comfyDynamic ??= {}
     363           26 :   node.comfyDynamic.matchType = {}
     364              : 
     365           44 :   const outputGroups = node.constructor.nodeData?.output_matchtypes
     366           44 :   node.onConnectionsChange = useChainCallback(
     367              :     node.onConnectionsChange,
     368              :     function (
     369              :       this: MatchTypeNode,
     370              :       contype: ISlotType,
     371              :       slot: number,
     372              :       iscon: boolean,
     373              :       linf: LLink | null | undefined
     374              :     ) {
     375          195 :       const input = this.inputs.at(slot)
     376          195 :       const { graph } = this
     377          195 :       if (contype !== LiteGraph.INPUT || !graph || !input) return
     378          195 :       if (useApp().configuringGraph) return
     379          195 :       const [matchKey, matchGroup] = Object.entries(
     380              :         this.comfyDynamic.matchType
     381              :       ).find(([, group]) => input.name in group) ?? ['', undefined]
     382          195 :       if (!matchGroup) return
     383          195 :       if (iscon && linf) {
     384           20 :         const { output, subgraphInput } = linf.resolve(graph)
     385           20 :         const connectingType = (output ?? subgraphInput)?.type
     386           20 :         if (connectingType) linf.type = connectingType
     387              :       }
     388              :       //NOTE: inputs contains input
     389           32 :       const groupInputs: INodeInputSlot[] = node.inputs.filter(
     390              :         (inp) => inp.name in matchGroup
     391              :       )
     392           32 :       const connectedTypes = groupInputs.map((inp) => {
     393           60 :         const link = this.getInputLink(this.inputs.indexOf(inp))
     394           60 :         if (!link) return '*'
     395           37 :         const { output, subgraphInput } = link.resolve(graph)
     396           60 :         return (output ?? subgraphInput)?.type ?? '*'
     397              :       })
     398              :       //An input slot can accept a connection that is
     399              :       // - Compatible with original type
     400              :       // - Compatible with all other input types
     401              :       //An output slot can output
     402              :       // - Only what every input can output
     403           32 :       groupInputs.forEach((input, idx) => {
     404           60 :         const otherConnected = [
     405              :           ...connectedTypes.slice(0, idx),
     406              :           ...connectedTypes.slice(idx + 1)
     407              :         ]
     408           60 :         const combinedType = commonType(
     409              :           ...otherConnected,
     410              :           matchGroup[input.name]
     411              :         )
     412           60 :         if (!combinedType) throw new Error('invalid connection')
     413           60 :         input.type = combinedType
     414              :       })
     415           32 :       const outputType = commonType(...connectedTypes)
     416          195 :       if (!outputType) throw new Error('invalid connection')
     417           32 :       this.outputs.forEach((_output, idx) => {
     418           32 :         if (!(outputGroups?.[idx] == matchKey)) return
     419           32 :         changeOutputType(this, idx, outputType)
     420              :       })
     421           32 :       graph.setDirtyCanvas(true, true)
     422              :     }
     423              :   )
     424              : }
     425              : 
     426           44 : function applyMatchType(node: LGraphNode, inputSpec: InputSpecV2) {
     427           44 :   const { addNodeInput } = useLitegraphServiceAccess()
     428           44 :   const name = inputSpec.name
     429           44 :   const parseResult = zMatchTypeOptions.safeParse(inputSpec)
     430           44 :   if (!parseResult.success) {
     431            0 :     console.warn(
     432              :       `Unparseable COMFY_MATCHTYPE_V3 spec for input "${name}"; falling back to a wildcard socket.`,
     433              :       parseResult.error.issues
     434              :     )
     435            0 :     addNodeInput(node, { ...inputSpec, type: '*' })
     436            0 :     return
     437              :   }
     438              :   const matchTypeSpec = parseResult.data
     439              : 
     440           44 :   const { allowed_types, template_id } = matchTypeSpec.template
     441              :   const typedSpec = { ...inputSpec, type: allowed_types }
     442           44 :   addNodeInput(node, typedSpec)
     443           44 :   withComfyMatchType(node)
     444           44 :   node.comfyDynamic.matchType[template_id] ??= {}
     445           44 :   node.comfyDynamic.matchType[template_id][name] = allowed_types
     446              : 
     447              :   //TODO: instead apply on output add?
     448              :   //ensure outputs get updated
     449           44 :   const index = node.inputs.length - 1
     450           44 :   requestAnimationFrame(() => {
     451           44 :     const input = node.inputs.at(index)
     452           44 :     if (!input || !node.graph) return
     453           28 :     node.inputs[index] = shallowReactive(input)
     454           28 :     const existingLink = node.getInputLink(index)
     455           44 :     node.onConnectionsChange(
     456              :       LiteGraph.INPUT,
     457              :       index,
     458              :       !!existingLink,
     459              :       existingLink ?? undefined,
     460              :       input
     461              :     )
     462              :   })
     463              : }
     464              : 
     465        25688 : function autogrowOrdinalToName(
     466              :   ordinal: number,
     467              :   key: string,
     468              :   groupName: string,
     469              :   node: AutogrowNode
     470              : ) {
     471        25688 :   const {
     472              :     names,
     473              :     prefix = '',
     474              :     inputSpecs
     475              :   } = node.comfyDynamic.autogrow[groupName]
     476        25688 :   const baseName = names
     477              :     ? names[ordinal]
     478              :     : (inputSpecs.length == 1 ? prefix : key) + ordinal
     479        25688 :   return { name: `${groupName}.${baseName}`, display_name: baseName }
     480              : }
     481              : 
     482          374 : function addAutogrowGroup(
     483              :   ordinal: number,
     484              :   groupName: string,
     485              :   node: AutogrowNode
     486              : ) {
     487          374 :   const { addNodeInput } = useLitegraphServiceAccess()
     488          374 :   const { max, min, inputSpecs } = node.comfyDynamic.autogrow[groupName]
     489          374 :   if (ordinal >= max) return
     490              : 
     491          374 :   const previous = captureInputLayout(node)
     492          374 :   const inputLinks = new Map(previous.links)
     493          374 :   const namedSpecs = inputSpecs.map((input) => ({
     494              :     ...input,
     495              :     isOptional: ordinal >= min || input.isOptional,
     496              :     ...autogrowOrdinalToName(ordinal, input.name, groupName, node)
     497              :   }))
     498              : 
     499          374 :   const existingIndex = node.inputs.findIndex(
     500              :     (inp) => inp.name === namedSpecs[0].name
     501              :   )
     502          374 :   const newInputs = namedSpecs.map((namedSpec) => {
     503          374 :     addNodeInput(node, namedSpec)
     504          374 :     const input = node.inputs.splice(node.inputs.length - 1, 1)[0]
     505          374 :     if (inputSpecs.length !== 1) ensureWidgetForInput(node, input)
     506          374 :     return input
     507              :   })
     508              : 
     509          374 :   for (const newInput of newInputs) {
     510          374 :     for (const existingInput of remove(
     511              :       node.inputs,
     512              :       (inp) => inp.name === newInput.name
     513              :     )) {
     514          151 :       const link = inputLinks.get(existingInput)
     515          151 :       if (link && !inputLinks.has(newInput)) inputLinks.set(newInput, link)
     516          151 :       if (existingInput.label) newInput.label = existingInput.label
     517              :     }
     518              :   }
     519              : 
     520          374 :   const targetName = autogrowOrdinalToName(
     521              :     ordinal - 1,
     522              :     inputSpecs.at(-1)!.name,
     523              :     groupName,
     524              :     node
     525              :   ).name
     526          374 :   const lastIndex = node.inputs.findLastIndex((inp) =>
     527              :     inp.name.startsWith(targetName)
     528              :   )
     529          374 :   const insertionIndex =
     530              :     lastIndex !== -1
     531              :       ? lastIndex + 1
     532              :       : existingIndex !== -1
     533              :         ? existingIndex
     534              :         : node.inputs.length
     535          374 :   node.inputs.splice(insertionIndex, 0, ...newInputs)
     536              :   const result = commitMutatedInputs(node, previous, inputLinks)
     537          374 :   if (!result.ok) return
     538          374 :   node.graph?.setDirtyCanvas(true, true)
     539              : }
     540              : 
     541         2356 : const ORDINAL_REGEX = /\d+$/
     542              : 
     543          453 : function resolveAutogrowOrdinal(
     544              :   inputName: string,
     545              :   groupName: string,
     546              :   node: AutogrowNode
     547              : ): number | undefined {
     548          453 :   const name = inputName.slice(groupName.length + 1)
     549          453 :   const { names } = node.comfyDynamic.autogrow[groupName]
     550          453 :   if (names) {
     551          166 :     const index = names.indexOf(name)
     552          166 :     return index === -1 ? undefined : index
     553              :   }
     554          287 :   const match = name.match(ORDINAL_REGEX)
     555          453 :   return match ? parseInt(match[0]) : undefined
     556              : }
     557          163 : function hasAutogrowGroups(node: LGraphNode): node is AutogrowNode {
     558          163 :   return !!node.comfyDynamic?.autogrow
     559              : }
     560              : 
     561              : /**
     562              :  * The live autogrow group `name` belongs to, from the node's own
     563              :  * `comfyDynamic.autogrow` registration -- real provenance from
     564              :  * `applyAutogrow`/`addAutogrowGroup`, rather than inferred from the name's
     565              :  * shape. Confirms membership with `resolveAutogrowOrdinal`, the same check
     566              :  * growth and shrink use, so a name that merely starts with a group's prefix
     567              :  * without resolving to one of its members doesn't false-match. Undefined
     568              :  * when the node has no autogrow groups, or `name` isn't a member of any of
     569              :  * them.
     570              :  */
     571          161 : export function liveAutogrowGroupOf(
     572              :   node: LGraphNode,
     573              :   name: string
     574              : ): string | undefined {
     575          161 :   if (!hasAutogrowGroups(node)) return undefined
     576           37 :   for (const groupName of Object.keys(node.comfyDynamic.autogrow)) {
     577           37 :     if (!name.startsWith(`${groupName}.`)) continue
     578           31 :     if (resolveAutogrowOrdinal(name, groupName, node) !== undefined) {
     579           31 :       return groupName
     580              :     }
     581              :   }
     582              :   return undefined
     583              : }
     584              : 
     585              : /**
     586              :  * Grows the autogrow group `name` belongs to until the node holds an input by
     587              :  * that name, and returns its live index. Undefined when `name` belongs to no
     588              :  * autogrow group of this node, or the group's `max` stops short of it.
     589              :  */
     590          126 : export function growAutogrowInput(
     591              :   node: LGraphNode,
     592              :   name: string
     593              : ): number | undefined {
     594          126 :   const groupName = liveAutogrowGroupOf(node, name)
     595          126 :   if (groupName === undefined || !hasAutogrowGroups(node)) return undefined
     596            2 :   reconcileAutogrowGroup(groupName, node, {
     597              :     atLeast: resolveAutogrowOrdinal(name, groupName, node)
     598              :   })
     599            2 :   const index = node.inputs.findIndex((input) => input.name === name)
     600          126 :   return index === -1 ? undefined : index
     601              : }
     602              : 
     603          135 : function reconcileAutogrowGroup(
     604              :   groupName: string,
     605              :   node: AutogrowNode,
     606              :   { atLeast = -1, compactFrom = Infinity } = {}
     607              : ) {
     608          135 :   if (!Object.hasOwn(node.comfyDynamic.autogrow, groupName)) return
     609          135 :   const { min, max, inputSpecs } = node.comfyDynamic.autogrow[groupName]
     610          135 :   const start = Math.min(compactFrom, max)
     611          135 :   const nameAt = (ordinal: number, column: number) =>
     612              :     autogrowOrdinalToName(ordinal, inputSpecs[column].name, groupName, node)
     613              :       .name
     614          135 :   const inputAt = (ordinal: number, column: number) =>
     615              :     node.inputs.find((input) => input.name === nameAt(ordinal, column))
     616              : 
     617          135 :   const before = captureInputLayout(node)
     618          135 :   const linkAt = (ordinal: number, column: number) => {
     619         3116 :     const input = inputAt(ordinal, column)
     620         3116 :     return input && before.links.get(input)
     621              :   }
     622          135 :   const packed = inputSpecs.map((_, column) =>
     623              :     range(start, max).flatMap((ordinal) => linkAt(ordinal, column) ?? [])
     624              :   )
     625          135 :   const highestLinked = Math.max(
     626              :     -1,
     627              :     ...range(0, start).filter((ordinal) =>
     628              :       inputSpecs.some((_, column) => linkAt(ordinal, column))
     629              :     ),
     630              :     ...packed.flatMap((links) =>
     631              :       links.length ? [start + links.length - 1] : []
     632              :     )
     633              :   )
     634          135 :   const last = Math.min(max - 1, Math.max(min, highestLinked + 1, atLeast))
     635              : 
     636          135 :   for (const ordinal of range(0, last + 1))
     637          240 :     if (!inputAt(ordinal, 0)) addAutogrowGroup(ordinal, groupName, node)
     638              : 
     639          135 :   const layout = captureInputLayout(node)
     640          135 :   const assignments = new Map(layout.links)
     641          135 :   const moved: { input: INodeInputSlot; link: LLink }[] = []
     642          135 :   for (const [column, links] of packed.entries()) {
     643          135 :     for (const ordinal of range(start, last + 1)) {
     644           17 :       const input = inputAt(ordinal, column)
     645           17 :       if (input) assignments.delete(input)
     646              :     }
     647          135 :     for (const [offset, link] of links.entries()) {
     648            6 :       const input = inputAt(start + offset, column)
     649            6 :       if (!input) continue
     650            6 :       assignments.set(input, link)
     651            6 :       if (layout.links.get(input) !== link) moved.push({ input, link })
     652              :     }
     653              :   }
     654          135 :   const removed = layout.inputs.filter((input) => {
     655         1241 :     if (!input.name.startsWith(`${groupName}.`)) return false
     656          247 :     const ordinal = resolveAutogrowOrdinal(input.name, groupName, node)
     657         1241 :     return ordinal !== undefined && ordinal > last && compactFrom !== Infinity
     658              :   })
     659          135 :   if (!moved.length && !removed.length) return
     660              : 
     661              :   const result = replaceNodeInputs(
     662              :     node,
     663              :     layout,
     664              :     layout.inputs.filter((input) => !removed.includes(input)),
     665              :     assignments
     666              :   )
     667           25 :   if (!result.ok) return
     668          135 :   node.graph?.setDirtyCanvas(true, true)
     669              : 
     670          135 :   for (const { input, link } of moved) {
     671            0 :     const slot = node.inputs.indexOf(input)
     672            0 :     if (slot !== -1)
     673            0 :       node.onConnectionsChange(LiteGraph.INPUT, slot, true, link, input)
     674              :   }
     675           10 :   for (const input of removed) {
     676            4 :     const widgetName = input.widget?.name
     677            4 :     if (!widgetName) continue
     678            0 :     for (const widget of remove(node.widgets, (w) => w.name === widgetName)) {
     679            0 :       widget.onRemove?.()
     680            0 :       if (widget.widgetId) useWidgetValueStore().deleteWidget(widget.widgetId)
     681              :     }
     682            0 :     syncNodeWidgetOrder(node)
     683              :   }
     684            3 :   node.size = [node.size[0], node.computeSize([...node.size])[1]]
     685              : }
     686              : 
     687          122 : function restoreAutogrowGroup(
     688              :   groupName: string,
     689              :   node: AutogrowNode,
     690              :   info: ISerialisedNode
     691              : ) {
     692          122 :   const { min, max } = node.comfyDynamic.autogrow[groupName]
     693          122 :   const requiredOrdinals = (info.inputs ?? []).flatMap((input) => {
     694         1083 :     if (!input.name.startsWith(`${groupName}.`)) return []
     695          163 :     const ordinal = resolveAutogrowOrdinal(input.name, groupName, node)
     696         1083 :     if (ordinal === undefined) return []
     697         1083 :     return [input.link == null ? ordinal : ordinal + 1]
     698              :   })
     699          122 :   const last = Math.min(Math.max(min, ...requiredOrdinals), max - 1)
     700          122 :   for (let ordinal = 0; ordinal <= last; ordinal++)
     701          174 :     addAutogrowGroup(ordinal, groupName, node)
     702              : }
     703              : 
     704           33 : function trimAutogrowGroups(node: AutogrowNode) {
     705           33 :   for (const [groupName, { max }] of Object.entries(node.comfyDynamic.autogrow))
     706          104 :     reconcileAutogrowGroup(groupName, node, { compactFrom: max })
     707              : }
     708              : 
     709          158 : function withComfyAutogrow(node: LGraphNode): asserts node is AutogrowNode {
     710          158 :   if (node.comfyDynamic?.autogrow) return
     711           44 :   node.comfyDynamic ??= {}
     712           44 :   node.comfyDynamic.autogrow = {}
     713              : 
     714           44 :   node.onConfigure = useChainCallback(
     715              :     node.onConfigure,
     716              :     function (this: AutogrowNode, info: ISerialisedNode) {
     717           39 :       for (const groupName of Object.keys(this.comfyDynamic.autogrow))
     718          122 :         restoreAutogrowGroup(groupName, this, info)
     719           39 :       if (this.graph) realignInputLinkSlots(this.graph, [[this.id, info]])
     720            0 :       else trimAutogrowGroups(this)
     721              :     }
     722              :   )
     723              : 
     724           44 :   node.onGraphConfigured = useChainCallback(
     725              :     node.onGraphConfigured,
     726              :     function (this: AutogrowNode) {
     727           33 :       trimAutogrowGroups(this)
     728              :     }
     729              :   )
     730              : 
     731           44 :   node.onConnectionsChange = useChainCallback(
     732              :     node.onConnectionsChange,
     733              :     function (this: AutogrowNode, contype: ISlotType, slot: number, iscon) {
     734          390 :       const input = this.inputs.at(slot)
     735          390 :       if (contype !== LiteGraph.INPUT || !input || useApp().configuringGraph)
     736          355 :         return
     737           35 :       const groupName = liveAutogrowGroupOf(this, input.name)
     738          140 :       if (groupName === undefined) return
     739           66 :       if (iscon) return reconcileAutogrowGroup(groupName, this)
     740           10 :       const { min } = this.comfyDynamic.autogrow[groupName]
     741           10 :       const ordinal = resolveAutogrowOrdinal(input.name, groupName, this)
     742          390 :       if (ordinal === undefined || ordinal + 1 < min) return
     743           10 :       requestAnimationFrame(() =>
     744              :         reconcileAutogrowGroup(groupName, this, { compactFrom: ordinal })
     745              :       )
     746              :     }
     747              :   )
     748              : }
     749          158 : function applyAutogrow(node: LGraphNode, inputSpecV2: InputSpecV2) {
     750          158 :   withComfyAutogrow(node)
     751              : 
     752          158 :   const parseResult = zAutogrowOptions.safeParse(inputSpecV2)
     753          158 :   if (!parseResult.success) throw new Error('invalid Autogrow spec')
     754              :   const inputSpec = parseResult.data
     755          158 :   const { input, min = 1, names, prefix, max = 100 } = inputSpec.template
     756              : 
     757              :   const inputTypes: (Record<string, InputSpec> | undefined)[] = [
     758              :     input.required,
     759              :     input.optional
     760              :   ]
     761          158 :   const inputsV2 = inputTypes.flatMap((inputType, index) =>
     762              :     Object.entries(inputType ?? {}).map(([name, v]) =>
     763              :       transformInputSpecV1ToV2(v, { name, isOptional: index === 1 })
     764              :     )
     765              :   )
     766          158 :   node.comfyDynamic.autogrow[inputSpecV2.name] = {
     767              :     names,
     768              :     min,
     769              :     max: names?.length ?? max,
     770              :     prefix,
     771              :     inputSpecs: inputsV2
     772              :   }
     773          158 :   for (let i = 0; i === 0 || i < min + 1; i++)
     774          188 :     addAutogrowGroup(i, inputSpecV2.name, node)
     775              : }
        

Generated by: LCOV version 2.0-1