HEL-892: pin bounded VHS combine and video load reference contracts

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 04:11:19 +08:00
co-authored by multica-agent
parent 846d6fcbfe
commit ab4e47e662
88 changed files with 74883 additions and 28 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,392 @@
import _ from 'es-toolkit/compat'
import { type Component, toRaw } from 'vue'
import { useChainCallback } from '@/composables/functional/useChainCallback'
// LegacyWidget is imported from its own module, not the barrel: the barrel
// exports it after SubgraphNode, so a litegraph-internal importer of this file
// would hit its TDZ. LGraphNode/LiteGraph must stay barrel-sourced — a direct
// LGraphNode import re-triggers the LGraph<->Subgraph cycle.
import { LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph'
import type {
IBaseWidget,
IWidgetOptions
} from '@/lib/litegraph/src/types/widgets'
import { LegacyWidget } from '@/lib/litegraph/src/widgets/LegacyWidget'
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
import { useDomWidgetStore } from '@/stores/domWidgetStore'
import { generateUUID } from '@/utils/formatUtil'
export interface BaseDOMWidget<
V extends object | string = object | string
> extends IBaseWidget<V, string, DOMWidgetOptions<V>> {
// ICustomWidget properties
type: string
options: DOMWidgetOptions<V>
value: V
callback?: (value: V) => void
// BaseDOMWidget properties
/** The unique ID of the widget. */
readonly id: string
/** The node that the widget belongs to. */
readonly node: LGraphNode
/** Whether the widget is visible. */
isVisible(): boolean
/** The margin of the widget. */
margin: number
}
/**
* A DOM widget that wraps a custom HTML element as a litegraph widget.
*/
export interface DOMWidget<
T extends HTMLElement,
V extends object | string
> extends BaseDOMWidget<V> {
element: T
/**
* @deprecated Legacy property used by some extensions for customtext
* (textarea) widgets. Use {@link element} instead as it provides the same
* functionality and works for all DOMWidget types.
*/
inputEl?: T
}
/**
* Additional props that can be passed to component widgets.
* These are in addition to the standard props that are always provided:
* - modelValue: The widget's value (handled by v-model)
* - widget: Reference to the widget instance
* - onUpdate:modelValue: The update handler for v-model
*/
type ComponentWidgetCustomProps = Record<string, unknown>
/**
* Standard props that are handled separately by DomWidget.vue and should be
* omitted when defining custom props for component widgets
*/
export type ComponentWidgetStandardProps =
| 'modelValue'
| 'widget'
| 'onUpdate:modelValue'
/**
* A DOM widget that wraps a Vue component as a litegraph widget.
*/
export interface ComponentWidget<
V extends object | string,
P extends ComponentWidgetCustomProps = ComponentWidgetCustomProps
> extends BaseDOMWidget<V> {
readonly component: Component
readonly inputSpec: InputSpec
readonly props?: P
}
export interface DOMWidgetOptions<
V extends object | string
> extends IWidgetOptions {
/**
* Whether to render a placeholder rectangle when zoomed out.
*/
hideOnZoom?: boolean
selectOn?: string[]
onHide?: (widget: BaseDOMWidget<V>) => void
getValue?: () => V
setValue?: (value: V) => void
getMinHeight?: () => number
getMaxHeight?: () => number
getHeight?: () => string | number
onDraw?: (widget: BaseDOMWidget<V>) => void
margin?: number
/**
* @deprecated Use `afterResize` instead. This callback is a legacy API
* that fires before resize happens, but it is no longer supported. Now it
* fires after resize happens.
* The resize logic has been upstreamed to litegraph in
* https://github.com/Comfy-Org/ComfyUI_frontend/pull/2557
*/
beforeResize?: (this: BaseDOMWidget<V>, node: LGraphNode) => void
afterResize?: (this: BaseDOMWidget<V>, node: LGraphNode) => void
}
export const isDOMWidget = <T extends HTMLElement, V extends object | string>(
widget: IBaseWidget
): widget is DOMWidget<T, V> => 'element' in widget && !!widget.element
export const isComponentWidget = <V extends object | string>(
widget: IBaseWidget
): widget is ComponentWidget<V> => 'component' in widget && !!widget.component
abstract class BaseDOMWidgetImpl<V extends object | string>
extends LegacyWidget<IBaseWidget<V, string, DOMWidgetOptions<V>>>
implements BaseDOMWidget<V>
{
static readonly DEFAULT_MARGIN = 10
declare readonly name: string
declare readonly options: DOMWidgetOptions<V>
declare callback?: (value: V) => void
readonly id: string
constructor(obj: {
node: LGraphNode
name: string
type: string
options: DOMWidgetOptions<V>
}) {
const { node, name, type, options } = obj
super({ y: 0, name, type, options }, node)
this.id = generateUUID()
}
override get value(): V {
return this.options.getValue?.() ?? ('' as V)
}
override set value(v: V) {
this.options.setValue?.(v)
this.callback?.(this.value)
}
get margin(): number {
return this.options.margin ?? BaseDOMWidgetImpl.DEFAULT_MARGIN
}
isVisible(): boolean {
return (
!this.hidden && !this.computedDisabled && this.node.isWidgetVisible(this)
)
}
override draw(
ctx: CanvasRenderingContext2D,
_node: LGraphNode,
widget_width: number,
y: number,
widget_height: number,
lowQuality?: boolean
): void {
const isVisible = this.isVisible()
if (this.options.hideOnZoom && lowQuality && isVisible) {
// Draw a placeholder rectangle
const originalFillStyle = ctx.fillStyle
ctx.beginPath()
ctx.fillStyle = LiteGraph.WIDGET_BGCOLOR
ctx.rect(
this.margin,
y + this.margin,
widget_width - this.margin * 2,
(this.computedHeight ?? widget_height) - 2 * this.margin
)
ctx.fill()
ctx.fillStyle = originalFillStyle
} else {
if (!isVisible) {
this.options.onDraw?.(this)
return
}
}
this.options.onDraw?.(this)
}
override onRemove(): void {
useDomWidgetStore().unregisterWidget(this.id)
}
override createCopyForNode(node: LGraphNode): this {
// @ts-expect-error
const cloned: this = new (this.constructor as typeof this)({
node: node,
name: this.name,
type: this.type,
options: this.options
})
cloned.value = this.value
// Preserve the Y position from the original widget to maintain proper positioning
// when widgets are promoted through subgraph nesting
cloned.y = this.y
return cloned
}
}
export class DOMWidgetImpl<T extends HTMLElement, V extends object | string>
extends BaseDOMWidgetImpl<V>
implements DOMWidget<T, V>
{
override readonly element: T
constructor(obj: {
node: LGraphNode
name: string
type: string
element: T
options: DOMWidgetOptions<V>
}) {
super(obj)
this.element = obj.element
}
override createCopyForNode(node: LGraphNode): this {
// @ts-expect-error
const cloned: this = new (this.constructor as typeof this)({
node: node,
name: this.name,
type: this.type,
element: this.element, // Include the element!
options: this.options
})
cloned.value = this.value
// Preserve the Y position from the original widget to maintain proper positioning
// when widgets are promoted through subgraph nesting
cloned.y = this.y
return cloned
}
/** Extract DOM widget size info */
override computeLayoutSize(node: LGraphNode) {
if (this.type === 'hidden') {
return {
minHeight: 0,
maxHeight: 0,
minWidth: 0
}
}
const styles = getComputedStyle(this.element)
let minHeight =
this.options.getMinHeight?.() ??
parseInt(styles.getPropertyValue('--comfy-widget-min-height'))
let maxHeight =
this.options.getMaxHeight?.() ??
parseInt(styles.getPropertyValue('--comfy-widget-max-height'))
let prefHeight: string | number =
this.options.getHeight?.() ??
styles.getPropertyValue('--comfy-widget-height')
if (typeof prefHeight === 'string' && prefHeight.endsWith?.('%')) {
prefHeight =
node.size[1] *
(parseFloat(prefHeight.substring(0, prefHeight.length - 1)) / 100)
} else {
prefHeight =
typeof prefHeight === 'number' ? prefHeight : parseInt(prefHeight)
if (isNaN(minHeight)) {
minHeight = prefHeight
}
}
return {
minHeight: isNaN(minHeight) ? 50 : minHeight,
maxHeight: isNaN(maxHeight) ? undefined : maxHeight,
minWidth: 0
}
}
}
export class ComponentWidgetImpl<
V extends object | string,
P extends ComponentWidgetCustomProps = ComponentWidgetCustomProps
>
extends BaseDOMWidgetImpl<V>
implements ComponentWidget<V, P>
{
readonly component: Component
readonly inputSpec: InputSpec
readonly props?: P
constructor(obj: {
node: LGraphNode
name: string
component: Component
inputSpec: InputSpec
props?: P
options: DOMWidgetOptions<V>
type?: string
}) {
super({
type: 'custom',
...obj
})
this.component = obj.component
this.inputSpec = obj.inputSpec
this.props = obj.props
}
override computeLayoutSize() {
const minHeight = this.options.getMinHeight?.() ?? 50
const maxHeight = this.options.getMaxHeight?.()
return {
minHeight,
maxHeight,
minWidth: 0
}
}
override serializeValue(): V {
return toRaw(this.value)
}
}
export const addWidget = <W extends BaseDOMWidget<object | string>>(
node: LGraphNode,
widget: W
) => {
node.addCustomWidget(widget)
if (node.graph) {
useDomWidgetStore().registerWidget(widget)
}
node.onAdded = useChainCallback(node.onAdded, () => {
useDomWidgetStore().registerWidget(widget)
})
node.onRemoved = useChainCallback(node.onRemoved, () => {
widget.onRemove?.()
})
node.onResize = useChainCallback(node.onResize, () => {
widget.options.beforeResize?.call(widget, node)
widget.options.afterResize?.call(widget, node)
})
}
LGraphNode.prototype.addDOMWidget = function <
T extends HTMLElement,
V extends object | string
>(
this: LGraphNode,
name: string,
type: string,
element: T,
options: DOMWidgetOptions<V> = {}
): DOMWidget<T, V> {
const widget = new DOMWidgetImpl({
node: this,
name,
type,
element,
options: { hideOnZoom: true, ...options }
})
// Note: Before `LGraphNode.configure` is called, `this.id` is always `-1`.
addWidget(this, widget as unknown as BaseDOMWidget<object | string>)
// Workaround for https://github.com/Comfy-Org/ComfyUI_frontend/issues/2493
// Some custom nodes are explicitly expecting getter and setter of `value`
// property to be on instance instead of prototype.
Object.defineProperty(widget, 'value', {
get(this: DOMWidgetImpl<T, V>): V {
return this.options.getValue?.() ?? ('' as V)
},
set(this: DOMWidgetImpl<T, V>, v: V) {
this.options.setValue?.(v)
this.callback?.(this.value)
}
})
return widget
}
@@ -0,0 +1,110 @@
import { applyTextReplacements as _applyTextReplacements } from '@/utils/searchAndReplace'
import { api } from './api'
import type { ComfyApp } from './app'
import { $el } from './ui'
export function clone<T>(obj: T): T {
try {
if (typeof structuredClone !== 'undefined') {
return structuredClone(obj)
}
} catch (error) {
// structuredClone is stricter than using JSON.parse/stringify so fallback to that
}
return JSON.parse(JSON.stringify(obj))
}
/**
* @deprecated Use `applyTextReplacements` from `@/utils/searchAndReplace` instead
* There are external callers to this function, so we need to keep it for now
*/
export function applyTextReplacements(app: ComfyApp, value: string): string {
return _applyTextReplacements(app.rootGraph, value)
}
export async function addStylesheet(
urlOrFile: string,
relativeTo?: string
): Promise<void> {
return new Promise((res, rej) => {
let url
if (urlOrFile.endsWith('.js')) {
url = urlOrFile.substr(0, urlOrFile.length - 2) + 'css'
} else {
url = new URL(
urlOrFile,
relativeTo ?? `${window.location.protocol}//${window.location.host}`
).toString()
}
$el('link', {
parent: document.head,
rel: 'stylesheet',
type: 'text/css',
href: url,
onload: res,
onerror: rej
})
})
}
export { downloadBlob } from '@/base/common/downloadUtil'
export function uploadFile(accept: string) {
return new Promise<File>((resolve, reject) => {
const input = document.createElement('input')
input.type = 'file'
input.accept = accept
input.onchange = (e) => {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return reject(new Error('No file selected'))
resolve(file)
}
input.click()
})
}
export function prop<T>(
target: object,
name: string,
defaultValue: T,
onChanged?: (
currentValue: T,
previousValue: T,
target: object,
name: string
) => void
): T {
// @ts-expect-error fixme ts strict error
let currentValue
Object.defineProperty(target, name, {
get() {
// @ts-expect-error fixme ts strict error
return currentValue
},
set(newValue) {
// @ts-expect-error fixme ts strict error
const prevValue = currentValue
currentValue = newValue
onChanged?.(currentValue, prevValue, target, name)
}
})
return defaultValue
}
export function getStorageValue(id: string) {
const clientId = api.clientId ?? api.initialClientId
return (
(clientId && sessionStorage.getItem(`${id}:${clientId}`)) ??
localStorage.getItem(id)
)
}
export function setStorageValue(id: string, value: string) {
const clientId = api.clientId ?? api.initialClientId
if (clientId) {
sessionStorage.setItem(`${id}:${clientId}`, value)
}
localStorage.setItem(id, value)
}
@@ -0,0 +1,248 @@
import { t } from '@/i18n'
import { type LGraphNode, isComboWidget } from '@/lib/litegraph/src/litegraph'
import type {
IBaseWidget,
IComboWidget,
IStringWidget
} from '@/lib/litegraph/src/types/widgets'
import { nextValueForLinkedTarget } from './valueControl'
import { useSettingStore } from '@/platform/settings/settingStore'
import { dynamicWidgets } from '@/core/graph/widgets/dynamicWidgets'
import { useBooleanWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget'
import { useBoundingBoxWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBoundingBoxWidget'
import { useCurveWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useCurveWidget'
import { useChartWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useChartWidget'
import { useColorWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useColorWidget'
import { useComboWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useComboWidget'
import { useFloatWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useFloatWidget'
import { useGalleriaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useGalleriaWidget'
import { useBoundingBoxesWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBoundingBoxesWidget'
import { useColorsWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useColorsWidget'
import { useImageCompareWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageCompareWidget'
import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget'
import { useIntWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useIntWidget'
import { useMarkdownWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useMarkdownWidget'
import { usePainterWidget } from '@/renderer/extensions/vueNodes/widgets/composables/usePainterWidget'
import { useRangeWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRangeWidget'
import { useStringWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useStringWidget'
import { useTextareaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useTextareaWidget'
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'
import type { InputSpec } from '@/schemas/nodeDefSchema'
import type { ComfyApp } from './app'
import { IS_CONTROL_WIDGET } from './controlWidgetMarker'
import './domWidget'
import './errorNodeWidgets'
export { IS_CONTROL_WIDGET }
export type ComfyWidgetConstructorV2 = (
node: LGraphNode,
inputSpec: InputSpecV2
) => IBaseWidget
export type ComfyWidgetConstructor = (
node: LGraphNode,
inputName: string,
inputData: InputSpec,
app: ComfyApp,
widgetName?: string
) => { widget: IBaseWidget; minWidth?: number; minHeight?: number }
/**
* Transforms a V2 widget constructor to a V1 widget constructor.
* @param widgetConstructorV2 The V2 widget constructor to transform.
* @returns The transformed V1 widget constructor.
*/
const transformWidgetConstructorV2ToV1 = (
widgetConstructorV2: ComfyWidgetConstructorV2
): ComfyWidgetConstructor => {
return (node, inputName, inputData) => {
const inputSpec = transformInputSpecV1ToV2(inputData, {
name: inputName
})
const widget = widgetConstructorV2(node, inputSpec)
return {
widget,
minWidth: widget.options.minNodeSize?.[0],
minHeight: widget.options.minNodeSize?.[1]
}
}
}
function controlValueRunBefore() {
return useSettingStore().get('Comfy.WidgetControlMode') === 'before'
}
export function updateControlWidgetLabel(widget: IBaseWidget) {
if (controlValueRunBefore()) {
widget.label = t('g.control_before_generate')
} else {
widget.label = t('g.control_after_generate')
}
}
const HAS_EXECUTED = Symbol()
export function addValueControlWidget(
node: LGraphNode,
targetWidget: IBaseWidget,
defaultValue?: string,
_values?: unknown,
widgetName?: string,
inputData?: InputSpec
): IComboWidget {
let name = inputData?.[1]?.control_after_generate
if (typeof name !== 'string') {
name = widgetName
}
const widgets = addValueControlWidgets(
node,
targetWidget,
defaultValue ?? 'randomize',
{
addFilterList: false,
controlAfterGenerateName: name
},
inputData
)
return widgets[0]
}
export function addValueControlWidgets(
node: LGraphNode,
targetWidget: IBaseWidget,
defaultValue?: string,
options?: Record<string, any>,
inputData?: InputSpec
): [IComboWidget, ...IStringWidget[]] {
if (!defaultValue) defaultValue = 'randomize'
if (!options) options = {}
const getName = (defaultName: string, optionName: string) => {
let name = defaultName
if (options[optionName]) {
name = options[optionName]
} else if (typeof inputData?.[1]?.[defaultName] === 'string') {
name = inputData?.[1]?.[defaultName]
} else if (inputData?.[1]?.control_prefix) {
name = inputData?.[1]?.control_prefix + ' ' + name
}
return name
}
const valueControl = node.addWidget(
'combo',
getName('control_after_generate', 'controlAfterGenerateName'),
defaultValue,
function () {},
{
values: ['fixed', 'increment', 'decrement', 'randomize'],
serialize: false, // Don't include this in prompt.
canvasOnly: true
}
) as IComboWidget
valueControl.tooltip =
'Allows the linked widget to be changed automatically, for example randomizing the noise seed.'
valueControl[IS_CONTROL_WIDGET] = true
updateControlWidgetLabel(valueControl)
Object.defineProperty(valueControl, 'disabled', {
get: () => targetWidget.computedDisabled
})
const widgets: [IComboWidget, ...IStringWidget[]] = [valueControl]
const isCombo = isComboWidget(targetWidget)
let comboFilter: IStringWidget
if (isCombo && valueControl.options.values) {
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
valueControl.options.values.push('increment-wrap')
}
if (isCombo && options.addFilterList !== false) {
comboFilter = node.addWidget(
'string',
getName('control_filter_list', 'controlFilterListName'),
'',
function () {},
{
serialize: false // Don't include this in prompt.
}
) as IStringWidget
updateControlWidgetLabel(comboFilter)
comboFilter.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'."
Object.defineProperty(comboFilter, 'disabled', {
get: () => targetWidget.computedDisabled
})
widgets.push(comboFilter)
}
function applyWidgetControl(isPartialExecution: boolean | undefined) {
if (
node.inputs?.some(
(input) =>
input.widget?.name === targetWidget.name && input.link != null
)
)
return
const next = nextValueForLinkedTarget({
target: targetWidget,
linkedWidgets: targetWidget.linkedWidgets,
nodeId: node.id,
isPartialExecution
})
if (next === undefined) return
targetWidget.value = next
targetWidget.callback?.(next)
}
valueControl.beforeQueued = ({ isPartialExecution } = {}) => {
if (controlValueRunBefore()) {
// Don't run on first execution
if (valueControl[HAS_EXECUTED]) {
applyWidgetControl(isPartialExecution)
}
}
valueControl[HAS_EXECUTED] = true
}
valueControl.afterQueued = ({ isPartialExecution } = {}) => {
if (!controlValueRunBefore()) {
applyWidgetControl(isPartialExecution)
}
}
return widgets
}
export const ComfyWidgets = {
INT: transformWidgetConstructorV2ToV1(useIntWidget()),
FLOAT: transformWidgetConstructorV2ToV1(useFloatWidget()),
BOOLEAN: transformWidgetConstructorV2ToV1(useBooleanWidget()),
STRING: transformWidgetConstructorV2ToV1(useStringWidget()),
MARKDOWN: transformWidgetConstructorV2ToV1(useMarkdownWidget()),
COMBO: transformWidgetConstructorV2ToV1(useComboWidget()),
IMAGEUPLOAD: useImageUploadWidget(),
COLOR: transformWidgetConstructorV2ToV1(useColorWidget()),
IMAGECOMPARE: transformWidgetConstructorV2ToV1(useImageCompareWidget()),
BOUNDING_BOX: transformWidgetConstructorV2ToV1(useBoundingBoxWidget()),
CHART: transformWidgetConstructorV2ToV1(useChartWidget()),
GALLERIA: transformWidgetConstructorV2ToV1(useGalleriaWidget()),
PAINTER: transformWidgetConstructorV2ToV1(usePainterWidget()),
TEXTAREA: transformWidgetConstructorV2ToV1(useTextareaWidget()),
CURVE: transformWidgetConstructorV2ToV1(useCurveWidget()),
RANGE: transformWidgetConstructorV2ToV1(useRangeWidget()),
BOUNDING_BOXES: transformWidgetConstructorV2ToV1(useBoundingBoxesWidget()),
COLORS: transformWidgetConstructorV2ToV1(useColorsWidget()),
...dynamicWidgets
} as const
export function isValidWidgetType(
key: unknown
): key is keyof typeof ComfyWidgets {
return ComfyWidgets[key as keyof typeof ComfyWidgets] !== undefined
}