Line data Source code
1 : import { computed } from 'vue'
2 :
3 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
4 : import { useWidgetValueStore } from '@/stores/widgetValueStore'
5 : import type { Bounds } from '@comfyorg/shared-frontend-utils/geometry'
6 : import { isBoundsObject } from '@/renderer/core/layout/utils/geometry'
7 : import type { LinkedUpstreamInfo, WidgetValue } from '@/types/simplifiedWidget'
8 : import type { WidgetState } from '@comfyorg/graph-model/widgetState'
9 :
10 : type ValueExtractor<T = unknown> = (
11 : widgets: WidgetState[],
12 : outputName: string | undefined
13 : ) => T | undefined
14 :
15 52 : export function useUpstreamValue<T>(
16 : getLinkedUpstream: () => LinkedUpstreamInfo | undefined,
17 : extractValue: ValueExtractor<T>
18 : ) {
19 52 : const canvasStore = useCanvasStore()
20 52 : const widgetValueStore = useWidgetValueStore()
21 :
22 52 : return computed(() => {
23 4 : const upstream = getLinkedUpstream()
24 4 : if (!upstream) return undefined
25 0 : const graphId = canvasStore.rootGraphId
26 0 : if (!graphId) return undefined
27 : const widgets = widgetValueStore.getNodeWidgets(graphId, upstream.nodeId)
28 0 : return extractValue(widgets, upstream.outputName)
29 : })
30 : }
31 :
32 52 : export function singleValueExtractor<T extends WidgetValue>(
33 : isValid: (value: unknown) => value is T
34 : ): ValueExtractor<T> {
35 52 : return (widgets, outputName) => {
36 0 : if (outputName) {
37 0 : const matched = widgets.find((w) => w.name === outputName)
38 0 : if (matched && isValid(matched.value)) return matched.value
39 : }
40 0 : const validValues = widgets.map((w) => w.value).filter(isValid)
41 0 : return validValues.length === 1 ? validValues[0] : undefined
42 : }
43 : }
44 :
45 49 : export function boundsExtractor(): ValueExtractor<Bounds> {
46 49 : const single = singleValueExtractor(isBoundsObject)
47 49 : return (widgets, outputName) => {
48 0 : const singleResult = single(widgets, outputName)
49 0 : if (singleResult) return singleResult
50 :
51 : // Fallback: assemble from individual widgets matching BoundingBoxInputSpec field names
52 0 : const getNum = (name: string): number | undefined => {
53 0 : const w = widgets.find((w) => w.name === name)
54 0 : return typeof w?.value === 'number' ? w.value : undefined
55 : }
56 0 : const x = getNum('x')
57 0 : const y = getNum('y')
58 0 : const width = getNum('width')
59 0 : const height = getNum('height')
60 0 : if (
61 : x !== undefined &&
62 : y !== undefined &&
63 : width !== undefined &&
64 : height !== undefined
65 : ) {
66 0 : return { x, y, width, height }
67 : }
68 : return undefined
69 : }
70 : }
|