Line data Source code
1 : import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
2 : import type {
3 : IBaseWidget,
4 : IBoundingBoxWidget,
5 : IImageCropWidget,
6 : INumericWidget
7 : } from '@comfyorg/graph-model/widgets'
8 : import type { Bounds } from '@comfyorg/shared-frontend-utils/geometry'
9 : import type {
10 : BoundingBoxInputSpec,
11 : InputSpec as InputSpecV2
12 : } from '@comfyorg/object-info-parser/schemas/nodeDefSchemaV2'
13 : import type { ComfyWidgetConstructorV2 } from '@/types/widgetConstructor'
14 :
15 50 : function isBoundingBoxLikeWidget(
16 : widget: IBaseWidget
17 : ): widget is IBoundingBoxWidget | IImageCropWidget {
18 50 : return widget.type === 'boundingbox' || widget.type === 'imagecrop'
19 : }
20 :
21 200 : function isNumericWidget(widget: IBaseWidget): widget is INumericWidget {
22 200 : return widget.type === 'number'
23 : }
24 :
25 2356 : export const useBoundingBoxWidget = (): ComfyWidgetConstructorV2 => {
26 2356 : return (
27 : node: LGraphNode,
28 : inputSpec: InputSpecV2
29 : ): IBoundingBoxWidget | IImageCropWidget => {
30 50 : const spec = inputSpec as BoundingBoxInputSpec
31 50 : const { name, component } = spec
32 50 : const defaultValue: Bounds = spec.default ?? {
33 : x: 0,
34 : y: 0,
35 : width: 512,
36 : height: 512
37 : }
38 :
39 50 : const widgetType = component === 'ImageCrop' ? 'imagecrop' : 'boundingbox'
40 :
41 50 : const fields: (keyof Bounds)[] = ['x', 'y', 'width', 'height']
42 50 : const subWidgets: INumericWidget[] = []
43 :
44 50 : const rawWidget = node.addWidget(
45 : widgetType,
46 : name,
47 : { ...defaultValue },
48 : () => {
49 47 : for (let i = 0; i < fields.length; i++) {
50 188 : const field = fields[i]
51 188 : const subWidget = subWidgets.at(i)
52 188 : if (subWidget) {
53 188 : subWidget.value = widget.value[field]
54 : }
55 : }
56 : },
57 : { hideInPanel: true }
58 : )
59 :
60 50 : if (!isBoundingBoxLikeWidget(rawWidget)) {
61 0 : throw new Error(`Unexpected widget type: ${rawWidget.type}`)
62 : }
63 :
64 50 : const widget = rawWidget
65 :
66 50 : for (const field of fields) {
67 200 : const subWidget = node.addWidget(
68 : 'number',
69 : field,
70 : defaultValue[field],
71 : function (this: INumericWidget, v: number) {
72 0 : this.value = Math.round(v)
73 0 : widget.value[field] = this.value
74 0 : widget.callback?.(widget.value)
75 : },
76 : {
77 : min: field === 'width' || field === 'height' ? 1 : 0,
78 : max: 8192,
79 : step: 10,
80 : step2: 1,
81 : precision: 0,
82 : serialize: false,
83 : surfaces: { canvas: 'shown', vueNode: 'never', panel: 'never' }
84 : }
85 : )
86 :
87 200 : if (!isNumericWidget(subWidget)) {
88 0 : throw new Error(`Unexpected widget type: ${subWidget.type}`)
89 : }
90 :
91 200 : subWidgets.push(subWidget)
92 : }
93 :
94 50 : widget.linkedWidgets = subWidgets
95 :
96 50 : return widget
97 : }
98 : }
|