widgetInputs.js 13.5 KB
Newer Older
1
2
import { ComfyWidgets, addValueControlWidget } from "../../scripts/widgets.js";
import { app } from "../../scripts/app.js";
3
4

const CONVERTED_TYPE = "converted-widget";
5
const VALID_TYPES = ["STRING", "combo", "number", "BOOLEAN"];
6

7
8
9
10
11
function getConfig(widgetName) {
	const { nodeData } = this.constructor;
	return nodeData?.input?.required[widgetName] ?? nodeData?.input?.optional?.[widgetName];
}

12
function isConvertableWidget(widget, config) {
13
	return (VALID_TYPES.includes(widget.type) || VALID_TYPES.includes(config[0])) && !widget.options?.forceInput;
14
15
16
17
18
19
20
21
22
23
}

function hideWidget(node, widget, suffix = "") {
	widget.origType = widget.type;
	widget.origComputeSize = widget.computeSize;
	widget.origSerializeValue = widget.serializeValue;
	widget.computeSize = () => [0, -4]; // -4 is due to the gap litegraph adds between widgets automatically
	widget.type = CONVERTED_TYPE + suffix;
	widget.serializeValue = () => {
		// Prevent serializing the widget if we have no input linked
24
25
26
		if (!node.inputs) {
			return undefined;
		}
27
28
29
		let node_input = node.inputs.find((i) => i.widget?.name === widget.name);

		if (!node_input || !node_input.link) {
30
31
			return undefined;
		}
32
		return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
33
34
	};

35
	// Hide any linked widgets, e.g. seed+seedControl
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
	if (widget.linkedWidgets) {
		for (const w of widget.linkedWidgets) {
			hideWidget(node, w, ":" + widget.name);
		}
	}
}

function showWidget(widget) {
	widget.type = widget.origType;
	widget.computeSize = widget.origComputeSize;
	widget.serializeValue = widget.origSerializeValue;

	delete widget.origType;
	delete widget.origComputeSize;
	delete widget.origSerializeValue;

52
	// Hide any linked widgets, e.g. seed+seedControl
53
54
55
56
57
58
59
60
61
62
	if (widget.linkedWidgets) {
		for (const w of widget.linkedWidgets) {
			showWidget(w);
		}
	}
}

function convertToInput(node, widget, config) {
	hideWidget(node, widget);

63
	const { linkType } = getWidgetType(config, `${node.comfyClass}|${widget.name}`);
64
65

	// Add input and store widget config for creating on primitive node
66
	const sz = node.size;
67
	node.addInput(widget.name, linkType, {
68
		widget: { name: widget.name, getConfig: () => config },
69
	});
70

71
72
73
74
	for (const widget of node.widgets) {
		widget.last_y += LiteGraph.NODE_SLOT_HEIGHT;
	}

75
76
	// Restore original size but grow if needed
	node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]);
77
78
79
80
}

function convertToWidget(node, widget) {
	showWidget(widget);
81
	const sz = node.size;
82
	node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name));
83

84
85
86
87
	for (const widget of node.widgets) {
		widget.last_y -= LiteGraph.NODE_SLOT_HEIGHT;
	}

88
89
	// Restore original size but grow if needed
	node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])]);
90
91
}

92
function getWidgetType(config, comboType) {
93
94
95
96
97
	// Special handling for COMBO so we restrict links based on the entries
	let type = config[0];
	let linkType = type;
	if (type instanceof Array) {
		type = "COMBO";
98
		linkType = comboType;
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
	}
	return { type, linkType };
}

app.registerExtension({
	name: "Comfy.WidgetInputs",
	async beforeRegisterNodeDef(nodeType, nodeData, app) {
		// Add menu options to conver to/from widgets
		const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
		nodeType.prototype.getExtraMenuOptions = function (_, options) {
			const r = origGetExtraMenuOptions ? origGetExtraMenuOptions.apply(this, arguments) : undefined;

			if (this.widgets) {
				let toInput = [];
				let toWidget = [];
				for (const w of this.widgets) {
115
116
117
					if (w.options?.forceInput) {
						continue;
					}
118
119
120
121
122
123
					if (w.type === CONVERTED_TYPE) {
						toWidget.push({
							content: `Convert ${w.name} to widget`,
							callback: () => convertToWidget(this, w),
						});
					} else {
124
						const config = getConfig.call(this, w.name) ?? [w.type, w.options || {}];
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
						if (isConvertableWidget(w, config)) {
							toInput.push({
								content: `Convert ${w.name} to input`,
								callback: () => convertToInput(this, w, config),
							});
						}
					}
				}
				if (toInput.length) {
					options.push(...toInput, null);
				}

				if (toWidget.length) {
					options.push(...toWidget, null);
				}
			}

			return r;
		};

145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
		nodeType.prototype.onGraphConfigured = function () {
			if (!this.inputs) return;

			for (const input of this.inputs) {
				if (input.widget) {
					// Cleanup old widget config
					delete input.widget.config;

					if (!input.widget.getConfig) {
						input.widget.getConfig = getConfig.bind(this, input.widget.name);
					}

					const config = input.widget.getConfig();
					if (config[1]?.forceInput) continue;

					const w = this.widgets.find((w) => w.name === input.widget.name);
					if (w) {
						hideWidget(this, w);
					} else {
						convertToWidget(this, input);
					}
				}
			}
		};

		const origOnNodeCreated = nodeType.prototype.onNodeCreated;
171
172
		nodeType.prototype.onNodeCreated = function () {
			const r = origOnNodeCreated ? origOnNodeCreated.apply(this) : undefined;
173
174
175

			// When node is created, convert any force/default inputs
			if (!app.configuringGraph && this.widgets) {
176
				for (const w of this.widgets) {
Chris's avatar
Chris committed
177
					if (w?.options?.forceInput || w?.options?.defaultInput) {
178
						const config = getConfig.call(this, w.name) ?? [w.type, w.options || {}];
179
180
181
182
						convertToInput(this, w, config);
					}
				}
			}
183

184
			return r;
185
		};
186

187
188
189
		const origOnConfigure = nodeType.prototype.onConfigure;
		nodeType.prototype.onConfigure = function () {
			const r = origOnConfigure ? origOnConfigure.apply(this, arguments) : undefined;
190
191
			if (!app.configuringGraph && this.inputs) {
				// On copy + paste of nodes, ensure that widget configs are set up
192
				for (const input of this.inputs) {
193
194
					if (input.widget && !input.widget.getConfig) {
						input.widget.getConfig = getConfig.bind(this, input.widget.name);
195
196
197
198
199
200
201
					}
				}
			}

			return r;
		};

202
203
204
205
206
207
208
209
210
		function isNodeAtPos(pos) {
			for (const n of app.graph._nodes) {
				if (n.pos[0] === pos[0] && n.pos[1] === pos[1]) {
					return true;
				}
			}
			return false;
		}

211
212
		// Double click a widget input to automatically attach a primitive
		const origOnInputDblClick = nodeType.prototype.onInputDblClick;
213
		const ignoreDblClick = Symbol();
214
215
216
		nodeType.prototype.onInputDblClick = function (slot) {
			const r = origOnInputDblClick ? origOnInputDblClick.apply(this, arguments) : undefined;

217
			const input = this.inputs[slot];
218
219
			if (!input.widget || !input[ignoreDblClick]) {
				// Not a widget input or already handled input
220
				if (!(input.type in ComfyWidgets) && !(input.widget.getConfig?.()?.[0] instanceof Array)) {
221
222
					return r; //also Not a ComfyWidgets input or combo (do nothing)
				}
223
			}
224

225
226
227
			// Create a primitive node
			const node = LiteGraph.createNode("PrimitiveNode");
			app.graph.add(node);
228

229
230
231
232
			// Calculate a position that wont directly overlap another node
			const pos = [this.pos[0] - node.size[0] - 30, this.pos[1]];
			while (isNodeAtPos(pos)) {
				pos[1] += LiteGraph.NODE_TITLE_HEIGHT;
233
234
			}

235
236
237
238
239
240
241
242
243
244
			node.pos = pos;
			node.connect(0, this, slot);
			node.title = input.name;

			// Prevent adding duplicates due to triple clicking
			input[ignoreDblClick] = true;
			setTimeout(() => {
				delete input[ignoreDblClick];
			}, 300);

245
246
247
248
249
250
251
252
253
254
255
256
257
258
			return r;
		};
	},
	registerCustomNodes() {
		class PrimitiveNode {
			constructor() {
				this.addOutput("connect to widget input", "*");
				this.serialize_widgets = true;
				this.isVirtualNode = true;
			}

			applyToGraph() {
				if (!this.outputs[0].links?.length) return;

259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
				function get_links(node) {
					let links = [];
					for (const l of node.outputs[0].links) {
						const linkInfo = app.graph.links[l];
						const n = node.graph.getNodeById(linkInfo.target_id);
						if (n.type == "Reroute") {
							links = links.concat(get_links(n));
						} else {
							links.push(l);
						}
					}
					return links;
				}

				let links = get_links(this);
274
				// For each output link copy our value over the original widget value
275
				for (const l of links) {
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
					const linkInfo = app.graph.links[l];
					const node = this.graph.getNodeById(linkInfo.target_id);
					const input = node.inputs[linkInfo.target_slot];
					const widgetName = input.widget.name;
					if (widgetName) {
						const widget = node.widgets.find((w) => w.name === widgetName);
						if (widget) {
							widget.value = this.widgets[0].value;
							if (widget.callback) {
								widget.callback(widget.value, app.canvas, node, app.canvas.graph_mouse, {});
							}
						}
					}
				}
			}

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
			refreshComboInNode() {
				const widget = this.widgets?.[0];
				if (widget?.type === "combo") {
					widget.options.values = this.outputs[0].widget.getConfig()[0];

					if (!widget.options.values.includes(widget.value)) {
						widget.value = widget.options.values[0];
						widget.callback(widget.value);
					}
				}
			}

			onAfterGraphConfigured() {
				if (this.outputs[0].links?.length && !this.widgets?.length) {
					this.#onFirstConnection();

					// Populate widget values from config data
					for (let i = 0; i < this.widgets_values.length; i++) {
						this.widgets[i].value = this.widgets_values[i];
					}
				}
			}

315
			onConnectionsChange(_, index, connected) {
316
317
318
319
320
				if (app.configuringGraph) {
					// Dont run while the graph is still setting up
					return;
				}

321
				if (connected) {
322
323
					if (this.outputs[0].links?.length && !this.widgets?.length) {
						this.#onFirstConnection();
324
325
326
327
328
329
330
331
332
333
					}
				} else if (!this.outputs[0].links?.length) {
					this.#onLastDisconnect();
				}
			}

			onConnectOutput(slot, type, input, target_node, target_slot) {
				// Fires before the link is made allowing us to reject it if it isn't valid

				// No widget, we cant connect
334
335
336
				if (!input.widget) {
					if (!(input.type in ComfyWidgets)) return false;
				}
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354

				if (this.outputs[slot].links?.length) {
					return this.#isValidConnection(input);
				}
			}

			#onFirstConnection() {
				// First connection can fire before the graph is ready on initial load so random things can be missing
				const linkId = this.outputs[0].links[0];
				const link = this.graph.links[linkId];
				if (!link) return;

				const theirNode = this.graph.getNodeById(link.target_id);
				if (!theirNode || !theirNode.inputs) return;

				const input = theirNode.inputs[link.target_slot];
				if (!input) return;

355
				let widget;
356
357
				if (!input.widget) {
					if (!(input.type in ComfyWidgets)) return;
358
					widget = { name: input.name, getConfig: () => [input.type, {}] }; //fake widget
359
				} else {
360
					widget = input.widget;
361
362
				}

363
				const { type, linkType } = getWidgetType(widget.getConfig(), `${theirNode.comfyClass}|${widget.name}`);
364
365
366
367
368
				// Update our output to restrict to the widget type
				this.outputs[0].type = linkType;
				this.outputs[0].name = type;
				this.outputs[0].widget = widget;

369
				this.#createWidget(widget.getConfig(), theirNode, widget.name);
370
371
372
373
374
375
376
377
378
379
380
381
382
			}

			#createWidget(inputData, node, widgetName) {
				let type = inputData[0];

				if (type instanceof Array) {
					type = "COMBO";
				}

				let widget;
				if (type in ComfyWidgets) {
					widget = (ComfyWidgets[type](this, "value", inputData, app) || {}).widget;
				} else {
383
					widget = this.addWidget(type, "value", null, () => {}, {});
384
385
386
387
388
389
390
391
392
				}

				if (node?.widgets && widget) {
					const theirWidget = node.widgets.find((w) => w.name === widgetName);
					if (theirWidget) {
						widget.value = theirWidget.value;
					}
				}

393
				if (widget.type === "number" || widget.type === "combo") {
394
					addValueControlWidget(this, widget, "fixed");
395
396
				}

pythongosssss's avatar
pythongosssss committed
397
398
399
400
401
402
403
404
405
406
				// When our value changes, update other widgets to reflect our changes
				// e.g. so LoadImage shows correct image
				const callback = widget.callback;
				const self = this;
				widget.callback = function () {
					const r = callback ? callback.apply(this, arguments) : undefined;
					self.applyToGraph();
					return r;
				};

407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
				// Grow our node if required
				const sz = this.computeSize();
				if (this.size[0] < sz[0]) {
					this.size[0] = sz[0];
				}
				if (this.size[1] < sz[1]) {
					this.size[1] = sz[1];
				}

				requestAnimationFrame(() => {
					if (this.onResize) {
						this.onResize(this.size);
					}
				});
			}

			#isValidConnection(input) {
				// Only allow connections where the configs match
425
426
				const config1 = this.outputs[0].widget.getConfig();
				const config2 = input.widget.getConfig();
427

428
429
430
431
432
433
434
435
436
437
438
439
440
441
				if (config1[0] instanceof Array) {
					// These checks shouldnt actually be necessary as the types should match
					// but double checking doesn't hurt

					// New input isnt a combo
					if (!(config2[0] instanceof Array)) return false;
					// New imput combo has a different size
					if (config1[0].length !== config2[0].length) return false;
					// New input combo has different elements
					if (config1[0].find((v, i) => config2[0][i] !== v)) return false;
				} else if (config1[0] !== config2[0]) {
					// Configs dont match
					return false;
				}
442
443

				for (const k in config1[1]) {
444
					if (k !== "default" && k !== "forceInput") {
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
						if (config1[1][k] !== config2[1][k]) {
							return false;
						}
					}
				}

				return true;
			}

			#onLastDisconnect() {
				// We cant remove + re-add the output here as if you drag a link over the same link
				// it removes, then re-adds, causing it to break
				this.outputs[0].type = "*";
				this.outputs[0].name = "connect to widget input";
				delete this.outputs[0].widget;

				if (this.widgets) {
					// Allow widgets to cleanup
					for (const w of this.widgets) {
						if (w.onRemove) {
							w.onRemove();
						}
					}
					this.widgets.length = 0;
				}
			}
		}

		LiteGraph.registerNodeType(
			"PrimitiveNode",
			Object.assign(PrimitiveNode, {
				title: "Primitive",
			})
		);
		PrimitiveNode.category = "utils";
	},
});