Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 73 additions & 146 deletions src/composables/graph/useGraphNodeManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
* Provides event-driven reactivity with performance optimizations
*/
import { reactiveComputed } from '@vueuse/core'
import { reactive, shallowReactive } from 'vue'
import { reactive, ref, shallowReactive, watch } from 'vue'
import type { Ref } from 'vue'

import { useChainCallback } from '@/composables/functional/useChainCallback'
import type {
Expand All @@ -19,7 +20,6 @@ import { isDOMWidget } from '@/scripts/domWidget'
import { useNodeDefStore } from '@/stores/nodeDefStore'
import type {
WidgetValue,
SafeControlWidget,
ControlWidgetOptions
} from '@/types/simplifiedWidget'

Expand All @@ -41,14 +41,14 @@ export interface WidgetSlotMetadata {
export interface SafeWidgetData {
name: string
type: string
value: WidgetValue
value: () => Ref<WidgetValue>
label?: string
options?: Record<string, unknown>
callback?: ((value: unknown) => void) | undefined
spec?: InputSpec
slotMetadata?: WidgetSlotMetadata
isDOMWidget?: boolean
controlWidget?: SafeControlWidget
controlWidget?: () => Ref<ControlWidgetOptions>
}

export interface VueNodeData {
Expand Down Expand Up @@ -84,8 +84,40 @@ export interface GraphNodeManager {
cleanup(): void
}

/**
* Validates that a value is a valid WidgetValue type
*/
function validateWidgetValue(value: unknown): WidgetValue {
if (value === null || value === undefined || value === void 0) {
return undefined
}
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
) {
return value
}
if (typeof value === 'object') {
// Check if it's a File array
if (
Array.isArray(value) &&
value.length > 0 &&
value.every((item): item is File => item instanceof File)
) {
return value
}
// Otherwise it's a generic object
return value
}
// If none of the above, return undefined
console.warn(`Invalid widget value type: ${typeof value}`, value)
return undefined
}

function validateControlWidgetValue(val: unknown): ControlWidgetOptions {
//TODO: Is there a way to do this without repeating?
//NOTE: global is not currently allowed
switch (val) {
case 'fixed':
return 'fixed'
Expand All @@ -96,15 +128,21 @@ function validateControlWidgetValue(val: unknown): ControlWidgetOptions {
}
return 'randomize'
}
function getControlWidget(widget: IBaseWidget): SafeControlWidget | undefined {
function getControlWidget(
widget: IBaseWidget
): (() => Ref<ControlWidgetOptions>) | undefined {
const cagWidget = widget.linkedWidgets?.find(
(w) => w.name == 'control_after_generate'
)
if (!cagWidget) return
return {
value: validateControlWidgetValue(cagWidget.value),
update: (value) => (cagWidget.value = validateControlWidgetValue(value))
}
const cagRef = ref<ControlWidgetOptions>(
validateControlWidgetValue(cagWidget.value)
)
watch(cagRef, (value) => {
cagWidget.value = value
cagWidget.callback?.(value)
})
return () => cagRef
}

export function safeWidgetMapper(
Expand All @@ -114,29 +152,37 @@ export function safeWidgetMapper(
const nodeDefStore = useNodeDefStore()
return function (widget) {
try {
// TODO: Use widget.getReactiveData() once TypeScript types are updated
let value = widget.value

// For combo widgets, if value is undefined, use the first option as default
if (
value === undefined &&
widget.value === undefined &&
widget.type === 'combo' &&
widget.options?.values &&
Array.isArray(widget.options.values) &&
widget.options.values.length > 0
) {
value = widget.options.values[0]
widget.value = widget.options.values[0]
}
if (!widget.valueRef) {
const valueRef = ref(widget.value)
watch(valueRef, (newValue) => {
widget.value = newValue
widget.callback?.(newValue)
})
widget.callback = useChainCallback(widget.callback, () => {
if (valueRef.value !== widget.value)
valueRef.value = validateWidgetValue(widget.value) ?? undefined
})
widget.valueRef = () => valueRef
}
const spec = nodeDefStore.getInputSpecForWidget(node, widget.name)
const slotInfo = slotMetadata.get(widget.name)

return {
name: widget.name,
type: widget.type,
value: value,
value: widget.valueRef,
label: widget.label,
options: widget.options ? { ...widget.options } : undefined,
callback: widget.callback,
spec,
slotMetadata: slotInfo,
isDOMWidget: isDOMWidget(widget),
Expand All @@ -146,7 +192,7 @@ export function safeWidgetMapper(
return {
name: widget.name || 'unknown',
type: widget.type || 'text',
value: undefined
value: () => ref()
}
}
}
Expand Down Expand Up @@ -222,6 +268,15 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
reactiveWidgets.splice(0, reactiveWidgets.length, ...v)
}
})
const reactiveInputs = shallowReactive<INodeInputSlot[]>(node.inputs ?? [])
Object.defineProperty(node, 'inputs', {
get() {
return reactiveInputs
},
set(v) {
reactiveInputs.splice(0, reactiveInputs.length, ...v)
}
})

const safeWidgets = reactiveComputed<SafeWidgetData[]>(() => {
node.inputs?.forEach((input, index) => {
Expand Down Expand Up @@ -256,7 +311,7 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
badges,
hasErrors: !!node.has_errors,
widgets: safeWidgets,
inputs: node.inputs ? [...node.inputs] : undefined,
inputs: reactiveInputs,
outputs: node.outputs ? [...node.outputs] : undefined,
flags: node.flags ? { ...node.flags } : undefined,
color: node.color || undefined,
Expand All @@ -269,128 +324,6 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
return nodeRefs.get(id)
}

/**
* Validates that a value is a valid WidgetValue type
*/
const validateWidgetValue = (value: unknown): WidgetValue => {
if (value === null || value === undefined || value === void 0) {
return undefined
}
if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
) {
return value
}
if (typeof value === 'object') {
// Check if it's a File array
if (
Array.isArray(value) &&
value.length > 0 &&
value.every((item): item is File => item instanceof File)
) {
return value
}
// Otherwise it's a generic object
return value
}
// If none of the above, return undefined
console.warn(`Invalid widget value type: ${typeof value}`, value)
return undefined
}

/**
* Updates Vue state when widget values change
*/
const updateVueWidgetState = (
nodeId: string,
widgetName: string,
value: unknown
): void => {
try {
const currentData = vueNodeData.get(nodeId)
if (!currentData?.widgets) return

const updatedWidgets = currentData.widgets.map((w) =>
w.name === widgetName ? { ...w, value: validateWidgetValue(value) } : w
)
// Create a completely new object to ensure Vue reactivity triggers
const updatedData = {
...currentData,
widgets: updatedWidgets
}

vueNodeData.set(nodeId, updatedData)
} catch (error) {
// Ignore widget update errors to prevent cascade failures
}
}

/**
* Creates a wrapped callback for a widget that maintains LiteGraph/Vue sync
*/
const createWrappedWidgetCallback = (
widget: { value?: unknown; name: string }, // LiteGraph widget with minimal typing
originalCallback: ((value: unknown) => void) | undefined,
nodeId: string
) => {
let updateInProgress = false

return (value: unknown) => {
if (updateInProgress) return
updateInProgress = true

try {
// 1. Update the widget value in LiteGraph (critical for LiteGraph state)
// Validate that the value is of an acceptable type
if (
value !== null &&
value !== undefined &&
typeof value !== 'string' &&
typeof value !== 'number' &&
typeof value !== 'boolean' &&
typeof value !== 'object'
) {
console.warn(`Invalid widget value type: ${typeof value}`)
updateInProgress = false
return
}

// Always update widget.value to ensure sync
widget.value = value

// 2. Call the original callback if it exists
if (originalCallback) {
originalCallback.call(widget, value)
}

// 3. Update Vue state to maintain synchronization
updateVueWidgetState(nodeId, widget.name, value)
} finally {
updateInProgress = false
}
}
}

/**
* Sets up widget callbacks for a node
*/
const setupNodeWidgetCallbacks = (node: LGraphNode) => {
if (!node.widgets) return

const nodeId = String(node.id)

node.widgets.forEach((widget) => {
const originalCallback = widget.callback
widget.callback = createWrappedWidgetCallback(
widget,
originalCallback,
nodeId
)
})
}

const syncWithGraph = () => {
if (!graph?._nodes) return

Expand All @@ -411,9 +344,6 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
// Store non-reactive reference
nodeRefs.set(id, node)

// Set up widget callbacks BEFORE extracting data (critical order)
setupNodeWidgetCallbacks(node)

// Extract and store safe data for Vue
vueNodeData.set(id, extractVueNodeData(node))
})
Expand All @@ -432,9 +362,6 @@ export function useGraphNodeManager(graph: LGraph): GraphNodeManager {
// Store non-reactive reference to original node
nodeRefs.set(id, node)

// Set up widget callbacks BEFORE extracting data (critical order)
setupNodeWidgetCallbacks(node)

// Extract initial data for Vue (may be incomplete during graph configure)
vueNodeData.set(id, extractVueNodeData(node))

Expand Down
1 change: 1 addition & 0 deletions src/extensions/core/widgetInputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ export class PrimitiveNode extends LGraphNode {
undefined,
inputData
)
if (this.widgets?.[1]) widget.linkedWidgets = [this.widgets[1]]
let filter = this.widgets_values?.[2]
if (filter && this.widgets && this.widgets.length === 3) {
this.widgets[2].value = filter
Expand Down
3 changes: 3 additions & 0 deletions src/lib/litegraph/src/types/widgets.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Ref } from 'vue'

import type { CanvasColour, Point, RequiredProps, Size } from '../interfaces'
import type { CanvasPointer, LGraphCanvas, LGraphNode } from '../litegraph'
import type { CanvasPointerEvent } from './events'
Expand Down Expand Up @@ -267,6 +269,7 @@ export interface IBaseWidget<
/** Widget type (see {@link TWidgetType}) */
type: TType
value?: TValue
valueRef?: () => Ref<boolean | number | string | object | undefined>

/**
* Whether the widget value should be serialized on node serialization.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { computed, ref } from 'vue'

import type { VueNodeData } from '@/composables/graph/useGraphNodeManager'
import type {
Expand Down Expand Up @@ -51,14 +51,16 @@ const nodeData = computed<VueNodeData>(() => {
.map(([name, input]) => ({
name,
type: input.widgetType || input.type,
value:
input.default !== undefined
? input.default
: input.type === 'COMBO' &&
Array.isArray(input.options) &&
input.options.length > 0
? input.options[0]
: '',
value: () =>
ref(
input.default !== undefined
? input.default
: input.type === 'COMBO' &&
Array.isArray(input.options) &&
input.options.length > 0
? input.options[0]
: ''
),
options: {
...input,
hidden: input.hidden,
Expand Down
Loading