LCOV - code coverage report
Current view: top level - src/extensions/core - customWidgets.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 81.9 % 127 104
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import { clamp } from 'es-toolkit'
       2              : import { computed, shallowReactive } from 'vue'
       3              : 
       4              : import { useChainCallback } from '@/composables/functional/useChainCallback'
       5              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
       6              : import type { LLink } from '@/lib/litegraph/src/litegraph'
       7              : import type { IBaseWidget } from '@comfyorg/graph-model/widgets'
       8              : import { BaseWidget } from '@/lib/litegraph/src/widgets/BaseWidget'
       9              : import type { ComfyNodeDef } from '@comfyorg/object-info-parser'
      10              : import { app } from '@/scripts/app'
      11              : import { GET_CONFIG } from '@comfyorg/graph-model/widgets'
      12              : import { useWidgetValueStore } from '@/stores/widgetValueStore'
      13              : import type { WidgetValue } from '@/types/simplifiedWidget'
      14              : 
      15              : import { applyFirstWidgetValueToGraph } from './widgetValuePropagation'
      16              : import { widgetId } from '@comfyorg/graph-model/widgetId'
      17              : import type { ComfyExtension } from '@/types/comfy'
      18              : 
      19            0 : function applyToGraph(this: LGraphNode, extraLinks: LLink[] = []) {
      20            0 :   applyFirstWidgetValueToGraph(this, extraLinks)
      21              : }
      22              : 
      23              : type SerializationNode = Parameters<
      24              :   NonNullable<IBaseWidget['serializeValue']>
      25              : >[0]
      26              : 
      27            4 : function resolveChoiceValue(
      28              :   interiorNode: LGraphNode,
      29              :   comboWidget: IBaseWidget,
      30              :   resolverNode: SerializationNode = interiorNode
      31              : ) {
      32            4 :   const choiceInputIndex = interiorNode.inputs.findIndex(
      33              :     (input) => input.widget?.name === comboWidget.name
      34              :   )
      35            4 :   if (choiceInputIndex < 0 || !('resolveInput' in resolverNode)) {
      36            0 :     return comboWidget.value
      37              :   }
      38              : 
      39            4 :   const resolved = resolverNode.resolveInput(choiceInputIndex)
      40            4 :   return resolved?.widgetInfo ? resolved.widgetInfo.value : comboWidget.value
      41              : }
      42              : 
      43            2 : function onCustomComboCreated(this: LGraphNode) {
      44            2 :   this.applyToGraph = applyToGraph
      45              : 
      46            2 :   const comboWidget = this.widgets![0]
      47            2 :   const values = shallowReactive<string[]>([])
      48            2 :   comboWidget.options.values = values
      49              : 
      50            2 :   const updateCombo = () => {
      51           12 :     values.splice(
      52              :       0,
      53              :       values.length,
      54              :       ...this.widgets!.filter(
      55              :         (w) => w.name.startsWith('option') && w.value
      56              :       ).map((w) => `${w.value}`)
      57              :     )
      58           12 :     if (app.configuringGraph || !this.graph) return
      59            0 :     if (values.includes(`${comboWidget.value}`)) return
      60           12 :     comboWidget.value = values.at(0) ?? ''
      61           12 :     comboWidget.callback?.(comboWidget.value)
      62              :   }
      63            2 :   comboWidget.callback = useChainCallback(comboWidget.callback, () =>
      64              :     this.applyToGraph!()
      65              :   )
      66            2 :   this.onAdded = useChainCallback(this.onAdded, function () {
      67            2 :     updateCombo()
      68              :   })
      69              : 
      70           10 :   function addOption(node: LGraphNode) {
      71           10 :     if (!node.widgets) return
      72              :     const newCount = node.widgets.length - 1
      73              :     const widgetName = `option${newCount}`
      74           10 :     const widget = node.addWidget('string', widgetName, '', () => {})
      75           10 :     let localValue = `${widget.value ?? ''}`
      76              : 
      77           10 :     Object.defineProperty(widget, 'value', {
      78              :       get() {
      79          151 :         return (
      80              :           useWidgetValueStore().getWidget(
      81              :             widgetId(app.rootGraph.id, node.id, widgetName)
      82              :           )?.value ?? localValue
      83              :         )
      84              :       },
      85              :       set(v: string) {
      86           10 :         localValue = v
      87           10 :         const state = useWidgetValueStore().getWidget(
      88              :           widgetId(app.rootGraph.id, node.id, widgetName)
      89              :         )
      90           10 :         if (state) state.value = v
      91           10 :         updateCombo()
      92           10 :         if (!node.widgets) return
      93           10 :         const lastWidget = node.widgets.at(-1)
      94           10 :         if (lastWidget === this) {
      95           10 :           if (v) addOption(node)
      96           10 :           return
      97              :         }
      98           10 :         if (v || node.widgets.at(-2) !== this || lastWidget?.value) return
      99            0 :         node.widgets.pop()
     100            0 :         node.computeSize(node.size)
     101            0 :         this.callback(v)
     102              :       }
     103              :     })
     104              :   }
     105            2 :   const widgets = this.widgets!
     106            2 :   widgets.push({
     107              :     name: 'index',
     108              :     type: 'hidden',
     109              :     get value() {
     110           24 :       return widgets.slice(2).findIndex((w) => w.value === comboWidget.value)
     111              :     },
     112              :     set value(_) {},
     113              :     draw: () => undefined,
     114              :     hidden: true,
     115              :     options: {},
     116              :     y: 0,
     117              :     serializeValue: (resolverNode: SerializationNode) =>
     118              :       widgets
     119              :         .slice(2)
     120              :         .findIndex(
     121              :           (w) => w.value === resolveChoiceValue(this, comboWidget, resolverNode)
     122              :         )
     123              :   })
     124            2 :   addOption(this)
     125              : }
     126              : 
     127         2355 : class StubWidget<T extends WidgetValue> extends BaseWidget {
     128              :   override serialize = true
     129              :   constructor(
     130              :     node: LGraphNode,
     131              :     name: string,
     132            1 :     protected valueGetter: () => T
     133              :   ) {
     134            1 :     super({ name, node, options: { socketless: true }, type: 'hidden', y: 0 })
     135              :   }
     136              :   drawWidget() {}
     137              :   onClick() {}
     138              :   override get value(): T {
     139           45 :     return this.valueGetter()
     140              :   }
     141              :   override set value(_: T) {}
     142              : }
     143            2 : function connectedInputsFor(node: LGraphNode, prefix: string = 'autogrow.') {
     144            2 :   return computed(() =>
     145              :     node.inputs
     146              :       .filter((input) => input.name.startsWith(prefix) && input.link)
     147              :       .map((input) => input.label ?? input.localized_name ?? input.name)
     148              :   )
     149              : }
     150              : 
     151           62 : function onCustomIntCreated(this: LGraphNode) {
     152           62 :   const valueWidget = this.widgets?.[0]
     153           62 :   if (!valueWidget) return
     154              : 
     155           62 :   Object.defineProperty(valueWidget.options, 'min', {
     156              :     get: () => this.properties.min ?? -(2 ** 63),
     157              :     set: (v) => {
     158            0 :       this.properties.min = v
     159            0 :       valueWidget.callback?.(valueWidget.value)
     160              :     }
     161              :   })
     162           62 :   Object.defineProperty(valueWidget.options, 'max', {
     163              :     get: () => this.properties.max ?? 2 ** 63,
     164              :     set: (v) => {
     165            0 :       this.properties.max = v
     166            0 :       valueWidget.callback?.(valueWidget.value)
     167              :     }
     168              :   })
     169           62 :   Object.defineProperty(valueWidget.options, 'step2', {
     170              :     get: () => this.properties.step ?? 1,
     171              :     set: (v) => {
     172            0 :       this.properties.step = v
     173            0 :       valueWidget.callback?.(valueWidget.value) // for vue reactivity
     174              :     }
     175              :   })
     176              : }
     177         2355 : const DISPLAY_WIDGET_TYPES = new Set(['gradientslider', 'slider', 'knob'])
     178              : 
     179         2355 : const finiteNumber = (value: unknown) =>
     180              :   typeof value === 'number' && Number.isFinite(value) ? value : undefined
     181              : 
     182         2355 : const positiveNumber = (value: unknown) => {
     183           67 :   const n = finiteNumber(value)
     184           67 :   return n !== undefined && n > 0 ? n : undefined
     185              : }
     186              : 
     187         2355 : const fractionDigits = (value: unknown) => {
     188           75 :   const n = finiteNumber(value)
     189           75 :   return n === undefined ? undefined : clamp(Math.trunc(n), 0, 100)
     190              : }
     191              : 
     192         2355 : const lastDecimalPlace = (places: number) =>
     193              :   Number((10 ** -places).toFixed(places))
     194              : 
     195           14 : function onCustomFloatCreated(this: LGraphNode) {
     196           14 :   const valueWidget = this.widgets?.[0]
     197           14 :   if (!valueWidget) return
     198              : 
     199           14 :   const declaredPrecision = fractionDigits(valueWidget.options.precision) ?? 1
     200           14 :   const declaredStep =
     201              :     positiveNumber(valueWidget.options.step2) ??
     202              :     lastDecimalPlace(declaredPrecision)
     203           14 :   const declaredRound = valueWidget.options.round
     204           14 :   const declaresRounding = positiveNumber(declaredRound) !== undefined
     205           14 :   const nodePrecision = () => fractionDigits(this.properties.precision)
     206              : 
     207           14 :   let baseType = valueWidget.type
     208           14 :   Object.defineProperty(valueWidget, 'type', {
     209              :     get: () => {
     210          125 :       const display = this.properties.display as string | undefined
     211          125 :       if (display && DISPLAY_WIDGET_TYPES.has(display)) return display
     212          125 :       return baseType
     213              :     },
     214              :     set: (v: string) => {
     215            0 :       baseType = v
     216              :     }
     217              :   })
     218              : 
     219           14 :   Object.defineProperty(valueWidget.options, 'gradient_stops', {
     220              :     enumerable: true,
     221              :     get: () => this.properties.gradient_stops,
     222              :     set: (v) => {
     223            0 :       this.properties.gradient_stops = v
     224              :     }
     225              :   })
     226           14 :   Object.defineProperty(valueWidget.options, 'min', {
     227              :     get: () => this.properties.min ?? -Infinity,
     228              :     set: (v) => {
     229            0 :       this.properties.min = v
     230            0 :       valueWidget.callback?.(valueWidget.value)
     231              :     }
     232              :   })
     233           14 :   Object.defineProperty(valueWidget.options, 'max', {
     234              :     get: () => this.properties.max ?? Infinity,
     235              :     set: (v) => {
     236            0 :       this.properties.max = v
     237            0 :       valueWidget.callback?.(valueWidget.value)
     238              :     }
     239              :   })
     240           14 :   Object.defineProperty(valueWidget.options, 'precision', {
     241              :     get: () => nodePrecision() ?? declaredPrecision,
     242              :     set: (v) => {
     243            0 :       this.properties.precision = v
     244            0 :       valueWidget.callback?.(valueWidget.value)
     245              :     }
     246              :   })
     247           14 :   Object.defineProperty(valueWidget.options, 'step2', {
     248              :     get: () => {
     249           17 :       const configured = positiveNumber(this.properties.step)
     250           17 :       if (configured !== undefined) return configured
     251           17 :       const places = nodePrecision()
     252           17 :       return places === undefined ? declaredStep : lastDecimalPlace(places)
     253              :     },
     254              :     set: (v) => (this.properties.step = v)
     255              :   })
     256           14 :   Object.defineProperty(valueWidget.options, 'round', {
     257              :     get: () => {
     258           22 :       const configured = positiveNumber(this.properties.round)
     259           22 :       if (configured !== undefined) return configured
     260           22 :       const places = nodePrecision()
     261           22 :       return places !== undefined && declaresRounding
     262              :         ? lastDecimalPlace(places)
     263              :         : declaredRound
     264              :     },
     265              :     set: (v) => {
     266            0 :       this.properties.round = v
     267            0 :       valueWidget.callback?.(valueWidget.value)
     268              :     }
     269              :   })
     270              : }
     271              : 
     272         2355 : export const customWidgetsExtension: ComfyExtension = {
     273              :   name: 'Comfy.CustomWidgets',
     274              :   beforeRegisterNodeDef(nodeType: typeof LGraphNode, nodeData: ComfyNodeDef) {
     275      2439372 :     if (nodeData.name === 'CustomCombo')
     276         2366 :       nodeType.prototype.onNodeCreated = useChainCallback(
     277              :         nodeType.prototype.onNodeCreated,
     278              :         onCustomComboCreated
     279              :       )
     280      2437006 :     else if (nodeData.name === 'PrimitiveInt')
     281         2366 :       nodeType.prototype.onNodeCreated = useChainCallback(
     282              :         nodeType.prototype.onNodeCreated,
     283              :         onCustomIntCreated
     284              :       )
     285      2434640 :     else if (nodeData.name === 'PrimitiveFloat')
     286         2366 :       nodeType.prototype.onNodeCreated = useChainCallback(
     287              :         nodeType.prototype.onNodeCreated,
     288              :         onCustomFloatCreated
     289              :       )
     290              :   },
     291              :   getCustomWidgets() {
     292         2355 :     return {
     293              :       COMFY_BRANCH_INPUT_NAMES: function (node, inputName) {
     294            1 :         const connectedInputs = connectedInputsFor(node)
     295            1 :         const values = () => connectedInputs.value
     296            1 :         node.addCustomWidget(new StubWidget<string[]>(node, inputName, values))
     297              :       },
     298              :       COMFY_BRANCH_SELECTOR: function (node, inputName) {
     299            1 :         const connectedInputs = connectedInputsFor(node)
     300            1 :         const values = () => connectedInputs.value
     301            1 :         const startValue = connectedInputs.value[0] ?? ''
     302            1 :         node.addWidget('combo', inputName, startValue, () => {}, { values })
     303            1 :         node.onInputAdded = useChainCallback(node.onInputAdded, (input) => {
     304            3 :           if (input.widget?.name !== inputName) return
     305            1 :           input.widget[GET_CONFIG] = () => ['COMBO', { options: values }]
     306              :         })
     307              :       }
     308              :     }
     309              :   }
     310              : }
        

Generated by: LCOV version 2.0-1