From ed21a2424bf68ad83c7d52abe8c1cae0e3aa24f2 Mon Sep 17 00:00:00 2001 From: Amp Date: Wed, 26 Aug 2026 05:37:30 +0000 Subject: [PATCH 1/7] refactor: migrate widget controls to ECS Amp-Thread-ID: https://ampcode.com/threads/T-01a03c7a-8c71-740a-8f44-616bcad0a22f --- docs/specs/widget-control-ecs.md | 137 ++++++++++++++ src/components/graph/GraphCanvas.vue | 14 -- .../rightSidePanel/parameters/WidgetItem.vue | 4 +- .../widgets/control/controlProjection.test.ts | 34 ++++ .../widgets/control/controlProjection.ts | 114 ++++++++++++ .../widgets/control}/valueControl.test.ts | 32 +--- .../graph/widgets/control}/valueControl.ts | 87 ++++----- .../widgets/control/widgetControl.test.ts | 76 ++++++++ .../graph/widgets/control/widgetControl.ts | 71 ++++++++ .../widgetControlSystem.promoted.test.ts} | 34 ++-- .../control/widgetControlSystem.test.ts | 71 ++++++++ .../widgets/control/widgetControlSystem.ts | 75 ++++++++ src/extensions/core/widgetInputs.ts | 39 ++-- src/lib/litegraph/src/LGraphNode.ts | 42 ++++- .../litegraph/src/subgraph/SubgraphNode.ts | 43 ++++- .../subgraph/SubgraphWidgetPromotion.test.ts | 29 +-- src/lib/litegraph/src/types/widgets.ts | 3 + src/lib/litegraph/src/widgetControlLabel.ts | 13 ++ src/lib/litegraph/src/widgets/BaseWidget.ts | 6 +- .../composables/processedWidgetRenderModel.ts | 6 +- .../widgets/components/WidgetWithControl.vue | 11 +- .../composables/useComboWidget.test.ts | 17 +- .../widgets/composables/useComboWidget.ts | 25 +-- .../composables/useFloatWidget.test.ts | 2 +- .../widgets/composables/useFloatWidget.ts | 11 +- .../widgets/composables/useIntWidget.test.ts | 2 +- .../widgets/composables/useIntWidget.ts | 11 +- src/scripts/app.ts | 12 +- src/scripts/controlWidgetMarker.ts | 1 - src/scripts/promotedWidgetControl.ts | 113 ------------ src/scripts/widgets.ts | 168 +++--------------- src/stores/widgetValueStore.ts | 83 ++++++++- src/types/simplifiedWidget.ts | 19 +- src/types/widgetState.ts | 12 ++ 34 files changed, 881 insertions(+), 536 deletions(-) create mode 100644 docs/specs/widget-control-ecs.md create mode 100644 src/core/graph/widgets/control/controlProjection.test.ts create mode 100644 src/core/graph/widgets/control/controlProjection.ts rename src/{scripts => core/graph/widgets/control}/valueControl.test.ts (80%) rename src/{scripts => core/graph/widgets/control}/valueControl.ts (65%) create mode 100644 src/core/graph/widgets/control/widgetControl.test.ts create mode 100644 src/core/graph/widgets/control/widgetControl.ts rename src/{scripts/promotedWidgetControl.test.ts => core/graph/widgets/control/widgetControlSystem.promoted.test.ts} (76%) create mode 100644 src/core/graph/widgets/control/widgetControlSystem.test.ts create mode 100644 src/core/graph/widgets/control/widgetControlSystem.ts create mode 100644 src/lib/litegraph/src/widgetControlLabel.ts delete mode 100644 src/scripts/controlWidgetMarker.ts delete mode 100644 src/scripts/promotedWidgetControl.ts diff --git a/docs/specs/widget-control-ecs.md b/docs/specs/widget-control-ecs.md new file mode 100644 index 00000000000..1cbd4ea84d8 --- /dev/null +++ b/docs/specs/widget-control-ecs.md @@ -0,0 +1,137 @@ +# Widget Control ECS + +## Objective + +Replace `control_after_generate` widgets with plain control state attached to +the widget they control and one graph-level system that advances controlled +values during queueing. + +The workflow format and user-visible controls remain compatible. The runtime +model changes from linked widgets with callbacks to a Component and System. + +## Model + +Each controlled target has one `WidgetControlState` keyed by the target's +canonical `WidgetId`: + +```ts +interface WidgetControlState { + mode: 'fixed' | 'increment' | 'increment-wrap' | 'decrement' | 'randomize' + filter?: string + hasExecuted: boolean +} +``` + +- `filter` exists only for combo controls that expose a filter field. +- `hasExecuted` implements the existing first-run skip in "before" mode. +- The component contains no widget, node, graph, callback, or DOM references. +- The target value and options remain in `widgetValueStore`. +- Popover, focus, and hover state remain local to the view. + +The component is registered when the target receives its `WidgetId`, released +with the target, renamed with the target, and cleared with the root graph. +Re-registration preserves the current component state. Replacing the target +with a different widget type removes stale control state. + +## System + +`runWidgetControl(rootGraph, phase, options)` runs once in each existing queue +phase. + +1. Skip partial executions. +2. Skip the phase not selected by `Comfy.WidgetControlMode`. +3. Query controls scoped to the root graph. +4. Derive link-fed target IDs from the live graph and skip them. +5. In "before" mode, mark the component executed and skip its first run. +6. Compute the next value with the existing pure value-control rules. +7. Write through `widgetValueStore`. + +There is no general ECS scheduler. The existing queue lifecycle is the system's +explicit scheduling boundary. + +## Presentation + +The control is not present in `node.widgets` and is not identified through +`linkedWidgets`. + +- Classic canvas rendering projects transient mode and filter rows beside the + target. Projection objects may be cached for stable layout but hold no source + of truth. +- Vue rendering reads and updates `WidgetControlState` directly by target + `WidgetId`. +- Control labels continue to reflect the before/after user setting. + +## Persistence + +Existing workflows retain their positional layout: + +- Number: `[targetValue, controlMode]` +- Combo: `[targetValue, controlMode, filter]` + +Serialization appends component values after each controlled target. +Configuration consumes valid control slots after registering the target. A +missing or invalid control slot must not consume the next target widget's +value. Control values remain absent from API prompt serialization. + +Named widget values continue to describe target widgets only; control +component values remain a compatibility concern of positional +`widgets_values`. + +## Promotion and graph scope + +A promoted target is controlled at the graph level where its authoritative +value lives. Promotion copies the source control configuration to a component +keyed by the host target's `WidgetId`; host and interior components are +independent after promotion. + +The system queries the root graph once and handles regular, nested, and +promoted targets uniformly. It must not traverse into an interior widget at +execution time to mutate a promoted value. + +## Compatibility constraints + +- Preserve fixed, increment, decrement, randomize, combo wrap, and combo + filtering behavior. +- Preserve before-mode first-run behavior and after-mode timing. +- Preserve partial-execution and link-fed suppression. +- Preserve positional workflow round trips, including older files with omitted + control slots. +- Preserve target widget callbacks required by custom widgets when a system + changes a value. +- Do not add state or behavior to `LGraphNode`, `LGraphCanvas`, `LGraph`, or + `Subgraph` beyond narrow projection and lifecycle integration. + +## Removal + +Once all presentation and persistence paths use the component, remove: + +- Real `control_after_generate` and filter widgets from `node.widgets`. +- `IS_CONTROL_WIDGET` and control-widget duck typing. +- Per-control `beforeQueued` and `afterQueued` closures. +- Runtime control identity through `linkedWidgets`. +- The separate promoted-widget control execution path and its `WeakSet`. + +## Acceptance criteria + +1. A regular number or combo control behaves identically before and after + workflow save/load. +2. Classic and Vue node renderers edit the same component state. +3. Link-fed and partial-execution targets do not advance. +4. Before mode skips the first execution and advances subsequent executions. +5. Promoted and nested promoted targets advance their authoritative host value + exactly once. +6. Deleting, replacing, renaming, or clearing a target cannot leave an active + orphan control. +7. Existing workflow fixtures round-trip without changing positional value + meaning. +8. No control form widget participates in prompt serialization or + `node.widgets` iteration. + +## Implementation order + +1. Component state and lifecycle in the widget value store. +2. Pure value transition and graph-level queue system. +3. Registration, classic projection, and positional persistence. +4. Vue component bridge. +5. Promotion copy and removal of the legacy promoted execution path. +6. Delete obsolete widget markers, callbacks, and compatibility code. diff --git a/src/components/graph/GraphCanvas.vue b/src/components/graph/GraphCanvas.vue index ece7bde5a46..f2bdd8a285e 100644 --- a/src/components/graph/GraphCanvas.vue +++ b/src/components/graph/GraphCanvas.vue @@ -186,7 +186,6 @@ import { requestSlotLayoutSyncForAllNodes } from '@/renderer/extensions/vueNodes import { UnauthorizedError } from '@/scripts/api' import { app as comfyApp } from '@/scripts/app' import { ChangeTracker } from '@/scripts/changeTracker' -import { IS_CONTROL_WIDGET, updateControlWidgetLabel } from '@/scripts/widgets' import { useColorPaletteService } from '@/services/colorPaletteService' import { useNewUserService } from '@/services/useNewUserService' import { shouldIgnoreCopyPaste } from '@/workbench/eventHelpers' @@ -201,7 +200,6 @@ import { useColorPaletteStore } from '@/stores/workspace/colorPaletteStore' import { useSearchBoxStore } from '@/stores/workspace/searchBoxStore' import { useAppMode } from '@/composables/useAppMode' import { useWorkspaceStore } from '@/stores/workspaceStore' -import { forEachNode } from '@/utils/graphTraversalUtil' import SelectionRectangle from './SelectionRectangle.vue' import { useUrlActionLoaders } from '@/composables/useUrlActionLoaders' @@ -373,18 +371,6 @@ watch( () => settingStore.get('Comfy.WidgetControlMode'), () => { if (!canvasStore.canvas) return - - forEachNode(comfyApp.rootGraph, (n) => { - if (!n.widgets) return - for (const w of n.widgets) { - if (!w[IS_CONTROL_WIDGET]) continue - updateControlWidgetLabel(w) - if (!w.linkedWidgets) continue - for (const l of w.linkedWidgets) { - updateControlWidgetLabel(l) - } - } - }) canvasStore.canvas.setDirty(true) } ) diff --git a/src/components/rightSidePanel/parameters/WidgetItem.vue b/src/components/rightSidePanel/parameters/WidgetItem.vue index f2dce67e2a4..186ef2c8274 100644 --- a/src/components/rightSidePanel/parameters/WidgetItem.vue +++ b/src/components/rightSidePanel/parameters/WidgetItem.vue @@ -3,6 +3,7 @@ import { computed, customRef, ref } from 'vue' import { useI18n } from 'vue-i18n' import EditableText from '@/components/common/EditableText.vue' +import { getWidgetControlView } from '@/core/graph/widgets/control/widgetControl' import type { LGraphNode } from '@/lib/litegraph/src/litegraph' import type { SubgraphNode } from '@/lib/litegraph/src/subgraph/SubgraphNode' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' @@ -20,7 +21,6 @@ import { useWidgetValueStore } from '@/stores/widgetValueStore' import { useFavoritedWidgetsStore } from '@/stores/workspace/favoritedWidgetsStore' -import { getControlWidget } from '@/types/simplifiedWidget' import type { SimplifiedWidget, WidgetValue as SimplifiedWidgetValue @@ -101,7 +101,7 @@ const simplifiedWidget = computed((): SimplifiedWidget => { label: widgetState?.label ?? widget.label, options: { ...baseOptions, disabled }, spec: nodeDefStore.getInputSpecForWidget(node, widgetName), - controlWidget: getControlWidget(widget) + controlWidget: getWidgetControlView(widget) } }) diff --git a/src/core/graph/widgets/control/controlProjection.test.ts b/src/core/graph/widgets/control/controlProjection.test.ts new file mode 100644 index 00000000000..e09bf5b968b --- /dev/null +++ b/src/core/graph/widgets/control/controlProjection.test.ts @@ -0,0 +1,34 @@ +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' + +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import { useWidgetValueStore } from '@/stores/widgetValueStore' + +describe('classic control projection', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + }) + + it('renders and edits component state without entering node.widgets', () => { + const graph = new LGraph() + const node = new LGraphNode('SeedNode') + const seed = node.addWidget('number', 'seed', 1, () => {}, {}) + seed.controlConfig = { mode: 'increment', hasFilter: false } + graph.add(node) + + const rendered = node.getLayoutWidgets() + expect(node.widgets?.map(({ name }) => name)).toEqual(['seed']) + expect(rendered.map(({ name }) => name)).toEqual([ + 'seed', + 'control_after_generate' + ]) + + rendered[1].callback?.('randomize') + expect( + seed.widgetId + ? useWidgetValueStore().getWidgetControl(seed.widgetId)?.mode + : undefined + ).toBe('randomize') + }) +}) diff --git a/src/core/graph/widgets/control/controlProjection.ts b/src/core/graph/widgets/control/controlProjection.ts new file mode 100644 index 00000000000..974225416a4 --- /dev/null +++ b/src/core/graph/widgets/control/controlProjection.ts @@ -0,0 +1,114 @@ +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { widgetControlLabel } from '@/lib/litegraph/src/widgetControlLabel' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { WidgetId } from '@/types/widgetId' + +import { + COMBO_CONTROL_MODES, + isValueControlMode, + NUMBER_CONTROL_MODES +} from './valueControl' + +const projectionCache = new WeakMap>() + +function getCache(target: IBaseWidget): Map { + const cached = projectionCache.get(target) + if (cached) return cached + const cache = new Map() + projectionCache.set(target, cache) + return cache +} + +function createModeProjection( + targetId: WidgetId, + target: IBaseWidget +): IBaseWidget { + const store = useWidgetValueStore() + return { + type: 'combo', + name: 'control_after_generate', + options: { + values: + target.type === 'combo' + ? [...COMBO_CONTROL_MODES] + : [...NUMBER_CONTROL_MODES], + serialize: false + }, + serialize: false, + tooltip: + 'Allows the linked widget to be changed automatically, for example randomizing the noise seed.', + y: 0, + get computedDisabled() { + return target.computedDisabled + }, + get label() { + return widgetControlLabel() + }, + get value() { + return store.getWidgetControl(targetId)?.mode ?? 'fixed' + }, + set value(value) { + if (isValueControlMode(value)) { + store.updateWidgetControl(targetId, { mode: value }) + } + }, + callback(value) { + if (isValueControlMode(value)) { + store.updateWidgetControl(targetId, { mode: value }) + } + } + } +} + +function createFilterProjection( + targetId: WidgetId, + target: IBaseWidget +): IBaseWidget { + const store = useWidgetValueStore() + return { + type: 'string', + name: 'control_filter_list', + options: { serialize: false }, + serialize: false, + tooltip: + "Allows for filtering the list of values when changing the value via the control generate mode. Allows for RegEx matches in the format /abc/ to only filter to values containing 'abc'.", + y: 0, + get computedDisabled() { + return target.computedDisabled + }, + get value() { + return store.getWidgetControl(targetId)?.filter ?? '' + }, + set value(value) { + store.updateWidgetControl(targetId, { filter: String(value) }) + }, + callback(value) { + store.updateWidgetControl(targetId, { filter: String(value) }) + } + } +} + +export function getControlProjections(target: IBaseWidget): IBaseWidget[] { + const targetId = target.widgetId + if (!targetId) return [] + + const control = useWidgetValueStore().getWidgetControl(targetId) + if (!control) return [] + + const cache = getCache(target) + const modeKey = `${targetId}:mode` + let mode = cache.get(modeKey) + if (!mode) { + mode = createModeProjection(targetId, target) + cache.set(modeKey, mode) + } + if (control.filter === undefined) return [mode] + + const filterKey = `${targetId}:filter` + let filter = cache.get(filterKey) + if (!filter) { + filter = createFilterProjection(targetId, target) + cache.set(filterKey, filter) + } + return [mode, filter] +} diff --git a/src/scripts/valueControl.test.ts b/src/core/graph/widgets/control/valueControl.test.ts similarity index 80% rename from src/scripts/valueControl.test.ts rename to src/core/graph/widgets/control/valueControl.test.ts index 7c0f25b34e9..f4e3098c2ff 100644 --- a/src/scripts/valueControl.test.ts +++ b/src/core/graph/widgets/control/valueControl.test.ts @@ -2,11 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' -import { IS_CONTROL_WIDGET } from './controlWidgetMarker' -import { - computeNextControlledValue, - isValueControlWidget -} from './valueControl' +import { computeNextControlledValue } from './valueControl' const makeNumberWidget = ( value: number, @@ -27,32 +23,6 @@ const makeComboWidget = (value: string, values: string[]): IBaseWidget => options: { values } }) as unknown as IBaseWidget -describe('isValueControlWidget', () => { - it('returns true for a marked widget with both lifecycle hooks', () => { - const widget = { - [IS_CONTROL_WIDGET]: true, - beforeQueued: () => {}, - afterQueued: () => {} - } as unknown as IBaseWidget - expect(isValueControlWidget(widget)).toBe(true) - }) - - it('returns false when the marker symbol is missing', () => { - const widget = { - beforeQueued: () => {}, - afterQueued: () => {} - } as unknown as IBaseWidget - expect(isValueControlWidget(widget)).toBe(false) - }) - - it('returns false when lifecycle hooks are missing', () => { - const widget = { - [IS_CONTROL_WIDGET]: true - } as unknown as IBaseWidget - expect(isValueControlWidget(widget)).toBe(false) - }) -}) - describe('computeNextControlledValue (number)', () => { it('returns undefined for fixed mode', () => { expect( diff --git a/src/scripts/valueControl.ts b/src/core/graph/widgets/control/valueControl.ts similarity index 65% rename from src/scripts/valueControl.ts rename to src/core/graph/widgets/control/valueControl.ts index b3e29fc07bf..1898742945a 100644 --- a/src/scripts/valueControl.ts +++ b/src/core/graph/widgets/control/valueControl.ts @@ -1,52 +1,42 @@ -import { isComboWidget } from '@/lib/litegraph/src/litegraph' import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' -import { IS_CONTROL_WIDGET } from './controlWidgetMarker' - -type ValueControlMode = +export type ValueControlMode = | 'fixed' | 'increment' | 'increment-wrap' | 'decrement' | 'randomize' -export function nextValueForLinkedTarget(params: { - target: IBaseWidget - linkedWidgets: IBaseWidget[] | undefined - nodeId: unknown - isPartialExecution: boolean | undefined -}): IBaseWidget['value'] | undefined { - if (params.isPartialExecution) return undefined - const linked = params.linkedWidgets - if (!linked) return undefined - - const controlWidget = linked.find(isValueControlWidget) - if (!controlWidget) return undefined - - const comboFilter = linked.find( - (w) => w !== controlWidget && w.type === 'string' - ) - const filterValue = - typeof comboFilter?.value === 'string' ? comboFilter.value : undefined - - const mode = controlWidget.value as ValueControlMode - return computeNextControlledValue(params.target, mode, { - comboFilter: filterValue, - nodeId: params.nodeId - }) +export const COMBO_CONTROL_MODES: readonly ValueControlMode[] = [ + 'fixed', + 'increment', + 'increment-wrap', + 'decrement', + 'randomize' +] + +export const NUMBER_CONTROL_MODES: readonly ValueControlMode[] = [ + 'fixed', + 'increment', + 'decrement', + 'randomize' +] + +const VALUE_CONTROL_MODES: ReadonlySet = new Set(COMBO_CONTROL_MODES) + +export function isValueControlMode(value: unknown): value is ValueControlMode { + return typeof value === 'string' && VALUE_CONTROL_MODES.has(value) +} + +interface ValueControlTarget { + type: IBaseWidget['type'] + value?: unknown + options: IBaseWidget['options'] } const SAFE_INTEGER_MAX = 1125899906842624 const SAFE_INTEGER_MIN = -1125899906842624 -export function isValueControlWidget(widget: IBaseWidget): boolean { - return ( - (widget as Record)[IS_CONTROL_WIDGET] === true && - typeof widget.beforeQueued === 'function' && - typeof widget.afterQueued === 'function' - ) -} - function buildComboFilter( filter: string | undefined, nodeId?: unknown @@ -71,21 +61,19 @@ function buildComboFilter( } export function computeNextControlledValue( - target: IBaseWidget, + target: ValueControlTarget, mode: ValueControlMode, options: { comboFilter?: string; nodeId?: unknown } = {} ): IBaseWidget['value'] | undefined { if (mode === 'fixed') return undefined - - if (isComboWidget(target)) { + if (target.type === 'combo') { return computeNextComboValue(target, mode, options) } - return computeNextNumberValue(target, mode) } function computeNextComboValue( - target: IBaseWidget, + target: ValueControlTarget, mode: ValueControlMode, { comboFilter, nodeId }: { comboFilter?: string; nodeId?: unknown } ): IBaseWidget['value'] | undefined { @@ -108,16 +96,14 @@ function computeNextComboValue( return undefined } - let currentIndex = values.indexOf(target.value as string) + let currentIndex = values.indexOf(String(target.value)) const length = values.length - switch (mode) { case 'increment': currentIndex += 1 break case 'increment-wrap': - currentIndex += 1 - if (currentIndex >= length) currentIndex = 0 + currentIndex = (currentIndex + 1) % length break case 'decrement': currentIndex -= 1 @@ -125,14 +111,15 @@ function computeNextComboValue( case 'randomize': currentIndex = Math.floor(Math.random() * length) break + case 'fixed': + return undefined } - currentIndex = Math.max(0, Math.min(length - 1, currentIndex)) - return values[currentIndex] + return values[Math.max(0, Math.min(length - 1, currentIndex))] } function computeNextNumberValue( - target: IBaseWidget, + target: ValueControlTarget, mode: ValueControlMode ): number | undefined { if (typeof target.value !== 'number') return undefined @@ -141,8 +128,8 @@ function computeNextNumberValue( const max = Math.min(SAFE_INTEGER_MAX, rawMax) const min = Math.max(SAFE_INTEGER_MIN, rawMin) const range = (max - min) / step2 - let next = target.value + switch (mode) { case 'increment': case 'increment-wrap': @@ -154,6 +141,8 @@ function computeNextNumberValue( case 'randomize': next = Math.floor(Math.random() * range) * step2 + min break + case 'fixed': + return undefined } return Math.min(Math.max(next, min), max) diff --git a/src/core/graph/widgets/control/widgetControl.test.ts b/src/core/graph/widgets/control/widgetControl.test.ts new file mode 100644 index 00000000000..2fd1b6ada41 --- /dev/null +++ b/src/core/graph/widgets/control/widgetControl.test.ts @@ -0,0 +1,76 @@ +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it } from 'vitest' + +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' +import { useWidgetValueStore } from '@/stores/widgetValueStore' + +function createControlledNode(): { graph: LGraph; node: LGraphNode } { + const graph = new LGraph() + const node = new LGraphNode('TestNode') + node.serialize_widgets = true + const seed = node.addWidget('number', 'seed', 0, () => {}, {}) + seed.controlConfig = { mode: 'randomize', hasFilter: false } + node.addWidget('text', 'prompt', '', () => {}, {}) + graph.add(node) + return { graph, node } +} + +describe('widget control persistence', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + }) + + it('round-trips the component through the legacy positional layout', () => { + const { node } = createControlledNode() + + node.configure({ + ...node.serialize(), + widgets_values: [12345, 'increment', 'a prompt'] + }) + + const target = node.widgets?.[0] + expect(target?.value).toBe(12345) + expect(node.widgets?.[1].value).toBe('a prompt') + expect( + target?.widgetId + ? useWidgetValueStore().getWidgetControl(target.widgetId)?.mode + : undefined + ).toBe('increment') + expect(node.serialize().widgets_values).toEqual([ + 12345, + 'increment', + 'a prompt' + ]) + }) + + it('does not consume the next widget when the control slot is absent', () => { + const { node } = createControlledNode() + + node.configure({ + ...node.serialize(), + widgets_values: [12345, 'a prompt'] + }) + + expect(node.widgets?.map(({ value }) => value)).toEqual([12345, 'a prompt']) + }) + + it('moves and removes the component with its target widget', () => { + const { node } = createControlledNode() + const store = useWidgetValueStore() + const target = node.widgets?.[0] + const oldId = target?.widgetId + if (!target || !oldId) throw new Error('Target widget was not registered') + + target.name = 'renamed_seed' + const newId = target.widgetId + + expect(store.getWidgetControl(oldId)).toBeUndefined() + expect(newId ? store.getWidgetControl(newId)?.mode : undefined).toBe( + 'randomize' + ) + + node.removeWidget(target) + expect(newId ? store.getWidgetControl(newId) : undefined).toBeUndefined() + }) +}) diff --git a/src/core/graph/widgets/control/widgetControl.ts b/src/core/graph/widgets/control/widgetControl.ts new file mode 100644 index 00000000000..7506624ea0a --- /dev/null +++ b/src/core/graph/widgets/control/widgetControl.ts @@ -0,0 +1,71 @@ +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import { normalizeControlOption } from '@/types/simplifiedWidget' +import type { SafeControlWidget } from '@/types/simplifiedWidget' +import type { WidgetId } from '@/types/widgetId' + +import { isValueControlMode } from './valueControl' + +export function registerWidgetControlFromConfig(widget: IBaseWidget): void { + const config = widget.controlConfig + const targetId = widget.widgetId + if (!config || !targetId) return + + useWidgetValueStore().registerWidgetControl(targetId, { + mode: config.mode, + filter: config.hasFilter ? '' : undefined + }) +} + +export function getWidgetControlView( + widget: Pick +): SafeControlWidget | undefined { + const targetId = widget.widgetId + if (!targetId) return undefined + const store = useWidgetValueStore() + const control = store.getWidgetControl(targetId) + if (!control) return undefined + return { + value: normalizeControlOption(control.mode), + update: (value) => { + store.updateWidgetControl(targetId, { + mode: normalizeControlOption(value) + }) + } + } +} + +export function appendControlValues( + targetId: WidgetId | undefined, + values: unknown[] +): void { + if (!targetId) return + const control = useWidgetValueStore().getWidgetControl(targetId) + if (!control) return + values.push(control.mode) + if (control.filter !== undefined) values.push(control.filter) +} + +export function applyControlValues( + targetId: WidgetId | undefined, + values: readonly unknown[], + index: number +): number { + if (!targetId) return index + const store = useWidgetValueStore() + const control = store.getWidgetControl(targetId) + if (!control) return index + + let next = index + const mode = values[next] + if (!isValueControlMode(mode)) return next + + store.updateWidgetControl(targetId, { mode }) + next++ + const filter = values[next] + if (control.filter !== undefined && typeof filter === 'string') { + store.updateWidgetControl(targetId, { filter }) + next++ + } + return next +} diff --git a/src/scripts/promotedWidgetControl.test.ts b/src/core/graph/widgets/control/widgetControlSystem.promoted.test.ts similarity index 76% rename from src/scripts/promotedWidgetControl.test.ts rename to src/core/graph/widgets/control/widgetControlSystem.promoted.test.ts index 9194ccfd16b..b353b9d136e 100644 --- a/src/scripts/promotedWidgetControl.test.ts +++ b/src/core/graph/widgets/control/widgetControlSystem.promoted.test.ts @@ -9,8 +9,7 @@ import { } from '@/lib/litegraph/src/subgraph/__fixtures__/subgraphHelpers' import { useWidgetValueStore } from '@/stores/widgetValueStore' -import { IS_CONTROL_WIDGET } from './controlWidgetMarker' -import { applyPromotedWidgetControl } from './promotedWidgetControl' +import { runWidgetControl } from './widgetControlSystem' class SeedNode extends LGraphNode { constructor(controlMode: string) { @@ -23,17 +22,10 @@ class SeedNode extends LGraphNode { max: 1_000_000, step2: 1 }) - const control = this.addWidget( - 'combo', - 'control_after_generate', - controlMode, - () => {}, - { values: ['fixed', 'increment', 'decrement', 'randomize'] } - ) - control[IS_CONTROL_WIDGET] = true - control.beforeQueued = () => {} - control.afterQueued = () => {} - seed.linkedWidgets = [control] + seed.controlConfig = { + mode: controlMode === 'increment' ? 'increment' : 'fixed', + hasFilter: false + } } } @@ -54,12 +46,12 @@ function createPromotedSeedHost(controlMode: string): SubgraphNode { return host } -describe('applyPromotedWidgetControl', () => { +describe('runWidgetControl with promoted targets', () => { it('increments the host-owned value of a promoted seed after queueing', () => { const host = createPromotedSeedHost('increment') expect(promotedSeedValue(host)).toBe(1) - applyPromotedWidgetControl(host, 'afterQueued') + runWidgetControl(host.rootGraph, 'after') expect(promotedSeedValue(host)).toBe(2) }) @@ -67,7 +59,7 @@ describe('applyPromotedWidgetControl', () => { it('leaves the value unchanged when the control mode is fixed', () => { const host = createPromotedSeedHost('fixed') - applyPromotedWidgetControl(host, 'afterQueued') + runWidgetControl(host.rootGraph, 'after') expect(promotedSeedValue(host)).toBe(1) }) @@ -77,10 +69,18 @@ describe('applyPromotedWidgetControl', () => { const seedInput = host.inputs.find((input) => input.name === 'seed')! const source = new LGraphNode('Source') source.addOutput('out', 'INT') + if (host.graph?.getNodeById(host.id) !== host) host.graph?.add(host) host.graph!.add(source) source.connect(0, host, host.inputs.indexOf(seedInput)) + expect(host.isInputConnected(host.inputs.indexOf(seedInput))).toBe(true) + expect(seedInput.widgetId).toBeDefined() + expect( + useWidgetValueStore() + .getWidgetControls(host.rootGraph.id) + .map(([id]) => id) + ).toContain(seedInput.widgetId) - applyPromotedWidgetControl(host, 'afterQueued') + runWidgetControl(host.rootGraph, 'after') expect(promotedSeedValue(host)).toBe(1) }) diff --git a/src/core/graph/widgets/control/widgetControlSystem.test.ts b/src/core/graph/widgets/control/widgetControlSystem.test.ts new file mode 100644 index 00000000000..b71e005097e --- /dev/null +++ b/src/core/graph/widgets/control/widgetControlSystem.test.ts @@ -0,0 +1,71 @@ +import { createTestingPinia } from '@pinia/testing' +import { setActivePinia } from 'pinia' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' + +import { runWidgetControl } from './widgetControlSystem' + +const controlPhase = vi.hoisted(() => ({ value: 'after' })) + +vi.mock('@/platform/settings/settingStore', () => ({ + useSettingStore: () => ({ + get: () => controlPhase.value + }) +})) + +function createControlledSeed(callback = vi.fn()) { + const graph = new LGraph() + const node = new LGraphNode('SeedNode') + const seed = node.addWidget('number', 'seed', 1, callback, { + min: 0, + max: 100, + step2: 1 + }) + seed.controlConfig = { mode: 'increment', hasFilter: false } + graph.add(node) + return { callback, graph, node, seed } +} + +describe('runWidgetControl', () => { + beforeEach(() => { + setActivePinia(createTestingPinia({ stubActions: false })) + controlPhase.value = 'after' + }) + + it('advances the target and invokes its compatibility callback', () => { + const { callback, graph, seed } = createControlledSeed() + + runWidgetControl(graph, 'after') + + expect(seed.value).toBe(2) + expect(callback).toHaveBeenCalledWith(2) + }) + + it('skips partial and link-fed targets', () => { + const { graph, node, seed } = createControlledSeed() + node.addInput('seed', 'number', { widget: { name: 'seed' } }) + const source = new LGraphNode('Source') + source.addOutput('value', 'number') + graph.add(source) + source.connect(0, node, 0) + + runWidgetControl(graph, 'after') + expect(seed.value).toBe(1) + + node.disconnectInput(0) + runWidgetControl(graph, 'after', { isPartialExecution: true }) + expect(seed.value).toBe(1) + }) + + it('skips the first execution in before mode', () => { + controlPhase.value = 'before' + const { graph, seed } = createControlledSeed() + + runWidgetControl(graph, 'before') + expect(seed.value).toBe(1) + + runWidgetControl(graph, 'before') + expect(seed.value).toBe(2) + }) +}) diff --git a/src/core/graph/widgets/control/widgetControlSystem.ts b/src/core/graph/widgets/control/widgetControlSystem.ts new file mode 100644 index 00000000000..d957aa6aba6 --- /dev/null +++ b/src/core/graph/widgets/control/widgetControlSystem.ts @@ -0,0 +1,75 @@ +import type { LGraph } from '@/lib/litegraph/src/litegraph' +import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets' +import { useSettingStore } from '@/platform/settings/settingStore' +import { useWidgetValueStore } from '@/stores/widgetValueStore' +import type { WidgetId } from '@/types/widgetId' +import { parseWidgetId, widgetId } from '@/types/widgetId' +import { forEachNode } from '@/utils/graphTraversalUtil' +import { mapLiveWidgetsById } from '@/utils/litegraphUtil' + +import { computeNextControlledValue } from './valueControl' + +type WidgetControlPhase = 'before' | 'after' + +function collectGraphTargets(graph: LGraph): { + linkFed: Set + live: Map +} { + const graphId = graph.rootGraph.id + const linkFed = new Set() + const live = new Map() + + forEachNode(graph, (node) => { + for (const [id, widget] of mapLiveWidgetsById(node)) live.set(id, widget) + for (const [index, input] of (node.inputs ?? []).entries()) { + if (input.widgetId) { + const widget = node.getWidgetFromSlot(input) + if (widget) live.set(input.widgetId, widget) + } + if (!node.isInputConnected(index)) continue + if (input.widgetId) linkFed.add(input.widgetId) + else if (input.widget?.name) { + linkFed.add(widgetId(graphId, node.id, input.widget.name)) + } + } + }) + + return { linkFed, live } +} + +export function runWidgetControl( + graph: LGraph, + phase: WidgetControlPhase, + { isPartialExecution }: { isPartialExecution?: boolean } = {} +): void { + if (isPartialExecution) return + + const runBefore = + useSettingStore().get('Comfy.WidgetControlMode') === 'before' + if (phase === 'before' && !runBefore) return + if (phase === 'after' && runBefore) return + + const store = useWidgetValueStore() + const { linkFed, live } = collectGraphTargets(graph) + for (const [targetId, control] of store.getWidgetControls( + graph.rootGraph.id + )) { + const target = store.getWidget(targetId) + if (!target || linkFed.has(targetId)) continue + + if (phase === 'before') { + const firstRun = !control.hasExecuted + store.updateWidgetControl(targetId, { hasExecuted: true }) + if (firstRun) continue + } + + const next = computeNextControlledValue(target, control.mode, { + comboFilter: control.filter, + nodeId: parseWidgetId(targetId).nodeId + }) + if (next === undefined) continue + + store.setValue(targetId, next) + live.get(targetId)?.callback?.(next) + } +} diff --git a/src/extensions/core/widgetInputs.ts b/src/extensions/core/widgetInputs.ts index 41bae08495d..1e721dce015 100644 --- a/src/extensions/core/widgetInputs.ts +++ b/src/extensions/core/widgetInputs.ts @@ -1,6 +1,7 @@ import { intersection } from 'es-toolkit/compat' import { useChainCallback } from '@/composables/functional/useChainCallback' +import { applyControlValues } from '@/core/graph/widgets/control/widgetControl' import { LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph' import type { INodeInputSlot, @@ -291,35 +292,19 @@ export class PrimitiveNode extends LGraphNode { if (!control_value) { control_value = 'fixed' } - addValueControlWidgets( - this, - widget, - control_value as string, - undefined, - inputData - ) - if (this.widgets?.[1]) widget.linkedWidgets = [this.widgets[1]] - const filter = useWidgetValueStore().getPositionalRestoredWidgetValue( graphId, this.id, 2 ) - if (filter && this.widgets && this.widgets.length === 3) { - this.widgets[2].value = filter - } + addValueControlWidgets(widget, String(control_value)) + applyControlValues(widget.widgetId, [control_value, filter], 0) } // Restore any saved control values const controlValues = this.controlValues - if ( - this.widgets && - this.lastType === this.widgets[0]?.type && - controlValues?.length === this.widgets.length - 1 - ) { - for (let i = 0; i < controlValues.length; i++) { - this.widgets[i + 1].value = controlValues[i] - } + if (this.lastType === this.widgets?.[0]?.type && controlValues?.length) { + applyControlValues(widget.widgetId, controlValues, 0) } this._finalizeWidget(widget, oldWidth, oldHeight, recreating) @@ -433,12 +418,16 @@ export class PrimitiveNode extends LGraphNode { } } - // Temporarily store the current values in case the node is being recreated - this.controlValues = [] this.lastType = this.widgets[0]?.type - for (let i = 1; i < this.widgets.length; i++) { - this.controlValues.push(this.widgets[i].value) - } + const targetId = this.widgets[0]?.widgetId + const control = targetId + ? useWidgetValueStore().getWidgetControl(targetId) + : undefined + this.controlValues = control + ? control.filter === undefined + ? [control.mode] + : [control.mode, control.filter] + : [] setTimeout(() => { delete this.lastType delete this.controlValues diff --git a/src/lib/litegraph/src/LGraphNode.ts b/src/lib/litegraph/src/LGraphNode.ts index d99654124ed..4b31d4a8266 100644 --- a/src/lib/litegraph/src/LGraphNode.ts +++ b/src/lib/litegraph/src/LGraphNode.ts @@ -4,6 +4,11 @@ import { createNodeShellState, setTrackedNodeState } from '@/core/graph/nodeShell/nodeShellState' +import { getControlProjections } from '@/core/graph/widgets/control/controlProjection' +import { + appendControlValues, + applyControlValues +} from '@/core/graph/widgets/control/widgetControl' import { calculateInputSlotPosFromSlot, getSlotPosition @@ -163,6 +168,12 @@ interface IMouseOverData { overWidget?: IBaseWidget } +function renderWidgets(node: LGraphNode): IBaseWidget[] { + const widgets = node.widgets ?? [] + if (LiteGraph.vueNodesMode) return [...widgets] + return widgets.flatMap((widget) => [widget, ...getControlProjections(widget)]) +} + function serialiseWidgetValues(widgets: IBaseWidget[]) { const positional: TWidgetValue[] = [] const named: Record = {} @@ -174,6 +185,7 @@ function serialiseWidgetValues(widgets: IBaseWidget[]) { ? JSON.parse(JSON.stringify(value)) : (value ?? null) positional.push(serialisedValue) + appendControlValues(widget.widgetId, positional) named[widget.name] = serialisedValue } return { widgets_values: positional, widgets_values_named: named } @@ -1171,9 +1183,14 @@ export class LGraphNode graphId, this.id, widget.name, - positionalIndex++ + positionalIndex ) if (restored) widget.value = restored.value + positionalIndex = applyControlValues( + widget.widgetId, + positionalValues, + positionalIndex + 1 + ) } } @@ -1994,7 +2011,8 @@ export class LGraphNode const ctorSize = this.constructor.size if (ctorSize) return [ctorSize[0], ctorSize[1]] - const { inputs, outputs, widgets } = this + const { inputs, outputs } = this + const widgets = renderWidgets(this) let rows = Math.max( inputs ? inputs.filter((input) => !isWidgetInputSlot(input)).length : 1, outputs ? outputs.length : 1 @@ -2259,9 +2277,14 @@ export class LGraphNode if (widget.serialize === false) return widget - const positionalIndex = - this.widgets.filter((candidate) => candidate.serialize !== false).length - - 1 + const precedingValues: unknown[] = [] + for (const candidate of this.widgets) { + if (candidate === widget) break + if (candidate.serialize === false) continue + precedingValues.push(null) + appendControlValues(candidate.widgetId, precedingValues) + } + const positionalIndex = precedingValues.length const restored = useWidgetValueStore().getRestoredWidgetValue( this.graph?.rootGraph.id ?? zeroUuid, this.id, @@ -2507,8 +2530,9 @@ export class LGraphNode canvasY: number, includeDisabled = false ): IBaseWidget | undefined { - const { widgets, pos, size } = this - if (!widgets?.length) return + const { pos, size } = this + const widgets = renderWidgets(this) + if (!widgets.length) return const x = canvasX - pos[0] const y = canvasY - pos[1] @@ -4111,7 +4135,7 @@ export class LGraphNode * Filters out hidden widgets only (not collapsed/advanced). */ getLayoutWidgets(): IBaseWidget[] { - return this.widgets?.filter((w) => !w.hidden) ?? [] + return renderWidgets(this).filter((w) => !w.hidden) } /** @@ -4138,7 +4162,7 @@ export class LGraphNode if (!this.widgets) return const nodeWidth = this.renderingSize[0] - const { widgets } = this + const widgets = renderWidgets(this) const H = LiteGraph.NODE_WIDGET_HEIGHT const showText = !lowQuality ctx.save() diff --git a/src/lib/litegraph/src/subgraph/SubgraphNode.ts b/src/lib/litegraph/src/subgraph/SubgraphNode.ts index 73d0018762d..f563b67e2ee 100644 --- a/src/lib/litegraph/src/subgraph/SubgraphNode.ts +++ b/src/lib/litegraph/src/subgraph/SubgraphNode.ts @@ -1,4 +1,8 @@ import cloneDeep from 'es-toolkit/compat/cloneDeep' +import { + appendControlValues, + applyControlValues +} from '@/core/graph/widgets/control/widgetControl' import type { BaseLGraph, LGraph, SubgraphId } from '@/lib/litegraph/src/LGraph' import type { LGraphButton } from '@/lib/litegraph/src/LGraphButton' import type { LGraphCanvas } from '@/lib/litegraph/src/LGraphCanvas' @@ -458,12 +462,15 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { ) super.configure(info) - if (!info.widgets_values_named || !LiteGraph.namedValuesRestore) - this._applyPromotedWidgetValues(info.widgets_values) + this._applyPromotedWidgetValues( + info.widgets_values, + !info.widgets_values_named || !LiteGraph.namedValuesRestore + ) } private _applyPromotedWidgetValues( - widgetValues: ExportedSubgraphInstance['widgets_values'] + widgetValues: ExportedSubgraphInstance['widgets_values'], + restoreTargetValues = true ): void { const quarantineValuesByInputName = this._readQuarantineHostValuesByName() @@ -473,10 +480,14 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { const value = quarantineValuesByInputName.has(input.name) ? quarantineValuesByInputName.get(input.name) : widgetValues?.[valueIndex] - if (value !== undefined) { + if (restoreTargetValues && value !== undefined) { useWidgetValueStore().setValue(input.widgetId, value) } - valueIndex += 1 + valueIndex = applyControlValues( + input.widgetId, + widgetValues ?? [], + valueIndex + 1 + ) } } @@ -671,6 +682,15 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { } input.widgetId = id + const sourceControl = interiorWidget.widgetId + ? store.getWidgetControl(interiorWidget.widgetId) + : undefined + if (sourceControl) { + store.registerWidgetControl(id, { + mode: sourceControl.mode, + filter: sourceControl.filter + }) + } input._widget = this.createPromotedHostWidget(input, id, interiorWidget) ?? this._projectPromotedWidget(input) @@ -702,6 +722,9 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { private _clearPromotedWidget(input: INodeInputSlot): void { input._widget?.onRemove?.() input._widget = undefined + if (input.widgetId) { + useWidgetValueStore().deleteWidgetControl(input.widgetId) + } } override onAdded(_graph: LGraph): void { @@ -950,11 +973,13 @@ export class SubgraphNode extends LGraphNode implements BaseLGraph { serialized.properties = serializedProperties - const widgetValues = this.inputs.flatMap((input) => { - if (!input.widgetId) return [] + const widgetValues: TWidgetValue[] = [] + for (const input of this.inputs) { + if (!input.widgetId) continue const value = useWidgetValueStore().getWidget(input.widgetId)?.value - return [isWidgetValue(value) ? value : undefined] - }) + widgetValues.push(isWidgetValue(value) ? value : undefined) + appendControlValues(input.widgetId, widgetValues) + } if (widgetValues.some((value) => value !== undefined)) { serialized.widgets_values = widgetValues diff --git a/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts b/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts index 5a8637dc89a..09f649997d5 100644 --- a/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts +++ b/src/lib/litegraph/src/subgraph/SubgraphWidgetPromotion.test.ts @@ -21,7 +21,6 @@ import { } from '@/core/graph/subgraph/migration/proxyWidgetMigration' import { reorderSubgraphInputsByName } from '@/core/graph/subgraph/promotionUtils' import type { SerializedProxyWidgetTuple } from '@/core/schemas/promotionSchema' -import { IS_CONTROL_WIDGET } from '@/scripts/controlWidgetMarker' import { getPreviewExposureHostLocator, usePreviewExposureStore @@ -917,20 +916,6 @@ describe('SubgraphWidgetPromotion', () => { if (r.kind === 'byName') reorderSubgraphInputsByName(host, r.order) } - function makeControlWidget( - value: 'increment' | 'fixed', - marker: boolean - ) { - const base = { - name: 'control_after_generate', - value, - serialize: false, - beforeQueued: () => {}, - afterQueued: () => {} - } - return marker ? { ...base, [IS_CONTROL_WIDGET]: true } : base - } - type ReorderCase = { name: string sources: SourceSpec[] @@ -1033,8 +1018,6 @@ describe('SubgraphWidgetPromotion', () => { type ControlCase = { name: string editVia: 'viewKey' | 'vue' - controlMode: 'increment' | 'fixed' - controlMarker: boolean seedHostValue: number mutateSourceSeedAfterReorder?: number expect: { @@ -1045,19 +1028,15 @@ describe('SubgraphWidgetPromotion', () => { const controlCases: ControlCase[] = [ { - name: 'ViewKey + increment: source seed mutation after reorder is ignored in prompt', + name: 'ViewKey: source seed mutation after reorder is ignored in prompt', editVia: 'viewKey', - controlMode: 'increment', - controlMarker: false, seedHostValue: 123456, mutateSourceSeedAfterReorder: 789, expect: { promptSeed: 123456 } }, { - name: 'Vue + fixed: host-wins — does not push Vue value into source seed', + name: 'Vue: host-wins — does not push Vue value into source seed', editVia: 'vue', - controlMode: 'fixed', - controlMarker: false, seedHostValue: 123456, expect: { sourceSeed: 0 } } @@ -1081,10 +1060,6 @@ describe('SubgraphWidgetPromotion', () => { writePromotedWidgetValue(host, 0, 'positive prompt') writePromotedWidgetValue(host, 1, 'negative prompt') writePromotedWidgetValue(host, 2, c.seedHostValue) - seed.widget.linkedWidgets = [ - makeControlWidget(c.controlMode, c.controlMarker) as never - ] - reorderSubgraphInputsByName(host, ['text_1', 'seed', 'text']) if (c.mutateSourceSeedAfterReorder !== undefined) { diff --git a/src/lib/litegraph/src/types/widgets.ts b/src/lib/litegraph/src/types/widgets.ts index e2998ba3df5..e76f4e9827c 100644 --- a/src/lib/litegraph/src/types/widgets.ts +++ b/src/lib/litegraph/src/types/widgets.ts @@ -5,6 +5,7 @@ import type { BoundingBox } from '@/types/boundingBoxes' import type { NodeId } from '@/types/nodeId' import type { WidgetValue } from '@/types/simplifiedWidget' import type { WidgetId } from '@/types/widgetId' +import type { WidgetControlConfig } from '@/types/widgetState' import type { CanvasColour, @@ -456,6 +457,8 @@ export interface IBaseWidget< linkedWidgets?: IBaseWidget[] + controlConfig?: WidgetControlConfig + readonly widgetId?: WidgetId name: string diff --git a/src/lib/litegraph/src/widgetControlLabel.ts b/src/lib/litegraph/src/widgetControlLabel.ts new file mode 100644 index 00000000000..c7bf4ecf3cd --- /dev/null +++ b/src/lib/litegraph/src/widgetControlLabel.ts @@ -0,0 +1,13 @@ +import { t } from '@/i18n' + +let labelProvider = () => t('g.control_after_generate') + +export function registerWidgetControlLabelProvider( + provider: () => string +): void { + labelProvider = provider +} + +export function widgetControlLabel(): string { + return labelProvider() +} diff --git a/src/lib/litegraph/src/widgets/BaseWidget.ts b/src/lib/litegraph/src/widgets/BaseWidget.ts index bf20b4f0cfb..a999fee06d9 100644 --- a/src/lib/litegraph/src/widgets/BaseWidget.ts +++ b/src/lib/litegraph/src/widgets/BaseWidget.ts @@ -1,4 +1,5 @@ import { t } from '@/i18n' +import { registerWidgetControlFromConfig } from '@/core/graph/widgets/control/widgetControl' import { drawTextInArea } from '@/lib/litegraph/src/draw' import { cachedMeasureText } from '@/lib/litegraph/src/utils/textMeasureCache' import { Rectangle } from '@/lib/litegraph/src/infrastructure/Rectangle' @@ -192,7 +193,10 @@ export abstract class BaseWidget }, deriveWidgetRenderState(this) ) - if (registered) this._state = registered + if (registered) { + this._state = registered + registerWidgetControlFromConfig(this) + } } constructor(widget: TWidget & { node: LGraphNode }) diff --git a/src/renderer/extensions/vueNodes/composables/processedWidgetRenderModel.ts b/src/renderer/extensions/vueNodes/composables/processedWidgetRenderModel.ts index c193168439d..b3063411b03 100644 --- a/src/renderer/extensions/vueNodes/composables/processedWidgetRenderModel.ts +++ b/src/renderer/extensions/vueNodes/composables/processedWidgetRenderModel.ts @@ -1,6 +1,7 @@ import type { TooltipOptions } from 'primevue' import { showNodeOptions } from '@/composables/graph/useMoreOptionsMenu' +import { getWidgetControlView } from '@/core/graph/widgets/control/widgetControl' import { resolvePromotedWidgetSource } from '@/core/graph/subgraph/resolvePromotedWidgetSource' import type { INodeInputSlot } from '@/lib/litegraph/src/interfaces' import type { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph' @@ -36,7 +37,6 @@ import { import type { NodeExecutionId, NodeLocatorId } from '@/types/nodeIdentification' import type { NodeId } from '@/types/nodeId' import type { NodeState } from '@/types/nodeState' -import { getControlWidget } from '@/types/simplifiedWidget' import type { LinkedUpstreamInfo, SafeControlWidget, @@ -291,9 +291,9 @@ function resolveLiveWidgetContext( } : undefined const controlWidget = - getControlWidget(liveWidget) ?? + getWidgetControlView(liveWidget) ?? (promotedSource?.sourceWidget - ? getControlWidget(promotedSource.sourceWidget) + ? getWidgetControlView(promotedSource.sourceWidget) : undefined) return { diff --git a/src/renderer/extensions/vueNodes/widgets/components/WidgetWithControl.vue b/src/renderer/extensions/vueNodes/widgets/components/WidgetWithControl.vue index 13e35d916da..2403bcc01c6 100644 --- a/src/renderer/extensions/vueNodes/widgets/components/WidgetWithControl.vue +++ b/src/renderer/extensions/vueNodes/widgets/components/WidgetWithControl.vue @@ -1,5 +1,5 @@