"vscode:/vscode.git/clone" did not exist on "9bd33b6bd48dcdb5283b5ba578a57409276b470e"
widgets.js 14.7 KB
Newer Older
1
import { api } from "./api.js"
2
import "./domWidget.js";
3

4
let controlValueRunBefore = false;
pythongosssss's avatar
pythongosssss committed
5
export function updateControlWidgetLabel(widget) {
6
7
8
9
10
11
12
13
14
15
16
	let replacement = "after";
	let find = "before";
	if (controlValueRunBefore) {
		[find, replacement] = [replacement, find]
	}
	widget.label = (widget.label ?? widget.name).replace(find, replacement);
}

const IS_CONTROL_WIDGET = Symbol();
const HAS_EXECUTED = Symbol();

comfyanonymous's avatar
comfyanonymous committed
17
function getNumberDefaults(inputData, defaultStep, precision, enable_rounding) {
pythongosssss's avatar
pythongosssss committed
18
	let defaultVal = inputData[1]["default"];
19
	let { min, max, step, round} = inputData[1];
pythongosssss's avatar
pythongosssss committed
20
21
22
23
24

	if (defaultVal == undefined) defaultVal = 0;
	if (min == undefined) min = 0;
	if (max == undefined) max = 2048;
	if (step == undefined) step = defaultStep;
25
26
	// precision is the number of decimal places to show.
	// by default, display the the smallest number of decimal places such that changes of size step are visible.
comfyanonymous's avatar
comfyanonymous committed
27
28
	if (precision == undefined) {
		precision = Math.max(-Math.floor(Math.log10(step)),0);
29
	}
30

comfyanonymous's avatar
comfyanonymous committed
31
	if (enable_rounding && (round == undefined || round === true)) {
32
33
34
35
		// by default, round the value to those decimal places shown.
		round = Math.round(1000000*Math.pow(0.1,precision))/1000000;
	}

36
	return { val: defaultVal, config: { min, max, step: 10.0 * step, round, precision } };
pythongosssss's avatar
pythongosssss committed
37
38
}

pythongosssss's avatar
pythongosssss committed
39
40
41
42
43
44
export function addValueControlWidget(node, targetWidget, defaultValue = "randomize", values, widgetName, inputData) {
	let name = inputData[1]?.control_after_generate;
	if(typeof name !== "string") {
		name = widgetName;
	}
	const widgets = addValueControlWidgets(node, targetWidget, defaultValue, {
pythongosssss's avatar
pythongosssss committed
45
		addFilterList: false,
pythongosssss's avatar
pythongosssss committed
46
47
		controlAfterGenerateName: name
	}, inputData);
pythongosssss's avatar
pythongosssss committed
48
49
50
	return widgets[0];
}

pythongosssss's avatar
pythongosssss committed
51
52
export function addValueControlWidgets(node, targetWidget, defaultValue = "randomize", options, inputData) {
	if (!defaultValue) defaultValue = "randomize";
pythongosssss's avatar
pythongosssss committed
53
	if (!options) options = {};
pythongosssss's avatar
pythongosssss committed
54
55
56
57
58
59
60
61
62
63
64
65
66

	const getName = (defaultName, optionName) => {
		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;
	}

pythongosssss's avatar
pythongosssss committed
67
	const widgets = [];
pythongosssss's avatar
pythongosssss committed
68
69
70
71
72
73
74
75
76
77
	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.
		}
	);
78
79
	valueControl[IS_CONTROL_WIDGET] = true;
	updateControlWidgetLabel(valueControl);
pythongosssss's avatar
pythongosssss committed
80
	widgets.push(valueControl);
81

pythongosssss's avatar
pythongosssss committed
82
83
	const isCombo = targetWidget.type === "combo";
	let comboFilter;
84
85
86
	if (isCombo) {
		valueControl.options.values.push("increment-wrap");
	}
pythongosssss's avatar
pythongosssss committed
87
	if (isCombo && options.addFilterList !== false) {
pythongosssss's avatar
pythongosssss committed
88
89
90
91
92
93
94
95
96
		comboFilter = node.addWidget(
			"string",
			getName("control_filter_list", "controlFilterListName"),
			"",
			function () {},
			{
				serialize: false, // Don't include this in prompt.
			}
		);
97
98
		updateControlWidgetLabel(comboFilter);

pythongosssss's avatar
pythongosssss committed
99
100
		widgets.push(comboFilter);
	}
101

102
	const applyWidgetControl = () => {
103
104
		var v = valueControl.value;

pythongosssss's avatar
pythongosssss committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
		if (isCombo && v !== "fixed") {
			let values = targetWidget.options.values;
			const filter = comboFilter?.value;
			if (filter) {
				let check;
				if (filter.startsWith("/") && filter.endsWith("/")) {
					try {
						const regex = new RegExp(filter.substring(1, filter.length - 1));
						check = (item) => regex.test(item);
					} catch (error) {
						console.error("Error constructing RegExp filter for node " + node.id, filter, error);
					}
				}
				if (!check) {
					const lower = filter.toLocaleLowerCase();
					check = (item) => item.toLocaleLowerCase().includes(lower);
				}
				values = values.filter(item => check(item));
				if (!values.length && targetWidget.options.values.length) {
					console.warn("Filter for node " + node.id + " has filtered out all items", filter);
				}
			}
			let current_index = values.indexOf(targetWidget.value);
			let current_length = values.length;
129
130
131
132
133

			switch (v) {
				case "increment":
					current_index += 1;
					break;
134
135
136
137
138
139
				case "increment-wrap":
					current_index += 1;
					if ( current_index >= current_length ) {
					    current_index = 0;
					}
					break;
140
141
142
143
144
145
146
147
148
149
150
				case "decrement":
					current_index -= 1;
					break;
				case "randomize":
					current_index = Math.floor(Math.random() * current_length);
				default:
					break;
			}
			current_index = Math.max(0, current_index);
			current_index = Math.min(current_length - 1, current_index);
			if (current_index >= 0) {
pythongosssss's avatar
pythongosssss committed
151
				let value = values[current_index];
152
153
154
				targetWidget.value = value;
				targetWidget.callback(value);
			}
pythongosssss's avatar
pythongosssss committed
155
156
		} else {
			//number
157
158
159
160
161
162
			let min = targetWidget.options.min;
			let max = targetWidget.options.max;
			// limit to something that javascript can handle
			max = Math.min(1125899906842624, max);
			min = Math.max(-1125899906842624, min);
			let range = (max - min) / (targetWidget.options.step / 10);
163

164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
			//adjust values based on valueControl Behaviour
			switch (v) {
				case "fixed":
					break;
				case "increment":
					targetWidget.value += targetWidget.options.step / 10;
					break;
				case "decrement":
					targetWidget.value -= targetWidget.options.step / 10;
					break;
				case "randomize":
					targetWidget.value = Math.floor(Math.random() * range) * (targetWidget.options.step / 10) + min;
				default:
					break;
			}
pythongosssss's avatar
pythongosssss committed
179
180
181
			/*check if values are over or under their respective
			 * ranges and set them to min or max.*/
			if (targetWidget.value < min) targetWidget.value = min;
182
183
184

			if (targetWidget.value > max)
				targetWidget.value = max;
185
			targetWidget.callback(targetWidget.value);
186
		}
pythongosssss's avatar
pythongosssss committed
187
	};
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204

	valueControl.beforeQueued = () => {
		if (controlValueRunBefore) {
			// Don't run on first execution
			if (valueControl[HAS_EXECUTED]) {
				applyWidgetControl();
			}
		}
		valueControl[HAS_EXECUTED] = true;
	};

	valueControl.afterQueued = () => {
		if (!controlValueRunBefore) {
			applyWidgetControl();
		}
	};

pythongosssss's avatar
pythongosssss committed
205
	return widgets;
206
};
207

pythongosssss's avatar
pythongosssss committed
208
209
210
function seedWidget(node, inputName, inputData, app, widgetName) {
	const seed = createIntWidget(node, inputName, inputData, app, true);
	const seedControl = addValueControlWidget(node, seed.widget, "randomize", undefined, widgetName, inputData);
pythongosssss's avatar
pythongosssss committed
211

212
213
	seed.widget.linkedWidgets = [seedControl];
	return seed;
pythongosssss's avatar
pythongosssss committed
214
215
}

pythongosssss's avatar
pythongosssss committed
216
217
218
219
function createIntWidget(node, inputName, inputData, app, isSeedInput) {
	const control = inputData[1]?.control_after_generate;
	if (!isSeedInput && control) {
		return seedWidget(node, inputName, inputData, app, typeof control === "string" ? control : undefined);
220
221
	}

pythongosssss's avatar
pythongosssss committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
	let widgetType = isSlider(inputData[1]["display"], app);
	const { val, config } = getNumberDefaults(inputData, 1, 0, true);
	Object.assign(config, { precision: 0 });
	return {
		widget: node.addWidget(
			widgetType,
			inputName,
			val,
			function (v) {
				const s = this.options.step / 10;
				this.value = Math.round(v / s) * s;
			},
			config
		),
	};
}

239
function addMultilineWidget(node, name, opts, app) {
240
241
242
	const inputEl = document.createElement("textarea");
	inputEl.className = "comfy-multiline-input";
	inputEl.value = opts.defaultVal;
pythongosssss's avatar
pythongosssss committed
243
	inputEl.placeholder = opts.placeholder || name;
244
245
246
247

	const widget = node.addDOMWidget(name, "customtext", inputEl, {
		getValue() {
			return inputEl.value;
pythongosssss's avatar
pythongosssss committed
248
		},
249
250
		setValue(v) {
			inputEl.value = v;
pythongosssss's avatar
pythongosssss committed
251
252
		},
	});
253
	widget.inputEl = inputEl;
pythongosssss's avatar
pythongosssss committed
254

pythongosssss's avatar
pythongosssss committed
255
256
257
	inputEl.addEventListener("input", () => {
		widget.callback?.(widget.value);
	});
258

pythongosssss's avatar
pythongosssss committed
259
260
261
	return { minWidth: 400, minHeight: 200, widget };
}

262
263
264
265
266
function isSlider(display, app) {
	if (app.ui.settings.getSettingValue("Comfy.DisableSliders")) {
		return "number"
	}

comfyanonymous's avatar
comfyanonymous committed
267
	return (display==="slider") ? "slider" : "number"
Guillaume Faguet's avatar
Guillaume Faguet committed
268
269
}

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
export function initWidgets(app) {
	app.ui.settings.addSetting({
		id: "Comfy.WidgetControlMode",
		name: "Widget Value Control Mode",
		type: "combo",
		defaultValue: "after",
		options: ["before", "after"],
		tooltip: "Controls when widget values are updated (randomize/increment/decrement), either before the prompt is queued or after.",
		onChange(value) {
			controlValueRunBefore = value === "before";
			for (const n of app.graph._nodes) {
				if (!n.widgets) continue;
				for (const w of n.widgets) {
					if (w[IS_CONTROL_WIDGET]) {
						updateControlWidgetLabel(w);
						if (w.linkedWidgets) {
							for (const l of w.linkedWidgets) {
								updateControlWidgetLabel(l);
							}
						}
					}
				}
			}
			app.graph.setDirtyCanvas(true);
		},
	});
}

pythongosssss's avatar
pythongosssss committed
298
299
300
export const ComfyWidgets = {
	"INT:seed": seedWidget,
	"INT:noise_seed": seedWidget,
301
302
	FLOAT(node, inputName, inputData, app) {
		let widgetType = isSlider(inputData[1]["display"], app);
comfyanonymous's avatar
comfyanonymous committed
303
304
305
306
		let precision = app.ui.settings.getSettingValue("Comfy.FloatRoundingPrecision");
		let disable_rounding = app.ui.settings.getSettingValue("Comfy.DisableFloatRounding")
		if (precision == 0) precision = undefined;
		const { val, config } = getNumberDefaults(inputData, 0.5, precision, !disable_rounding);
307
		return { widget: node.addWidget(widgetType, inputName, val,
308
			function (v) {
309
310
311
312
313
				if (config.round) {
					this.value = Math.round(v/config.round)*config.round;
				} else {
					this.value = v;
				}
314
			}, config) };
pythongosssss's avatar
pythongosssss committed
315
	},
316
	INT(node, inputName, inputData, app) {
pythongosssss's avatar
pythongosssss committed
317
		return createIntWidget(node, inputName, inputData, app);
318
	},
comfyanonymous's avatar
comfyanonymous committed
319
	BOOLEAN(node, inputName, inputData) {
320
321
322
323
324
325
326
327
328
329
		let defaultVal = false;
		let options = {};
		if (inputData[1]) {
			if (inputData[1].default)
				defaultVal = inputData[1].default;
			if (inputData[1].label_on)
				options["on"] = inputData[1].label_on;
			if (inputData[1].label_off)
				options["off"] = inputData[1].label_off;
		}
330
331
332
333
334
335
		return {
			widget: node.addWidget(
				"toggle",
				inputName,
				defaultVal,
				() => {},
336
				options,
337
338
339
				)
		};
	},
pythongosssss's avatar
pythongosssss committed
340
341
342
343
	STRING(node, inputName, inputData, app) {
		const defaultVal = inputData[1].default || "";
		const multiline = !!inputData[1].multiline;

344
		let res;
pythongosssss's avatar
pythongosssss committed
345
		if (multiline) {
346
			res = addMultilineWidget(node, inputName, { defaultVal, ...inputData[1] }, app);
pythongosssss's avatar
pythongosssss committed
347
		} else {
348
			res = { widget: node.addWidget("text", inputName, defaultVal, () => {}, {}) };
pythongosssss's avatar
pythongosssss committed
349
		}
350
351
352
353
354

		if(inputData[1].dynamicPrompts != undefined)
			res.widget.dynamicPrompts = inputData[1].dynamicPrompts;

		return res;
pythongosssss's avatar
pythongosssss committed
355
	},
356
357
358
359
360
361
	COMBO(node, inputName, inputData) {
		const type = inputData[0];
		let defaultValue = type[0];
		if (inputData[1] && inputData[1].default) {
			defaultValue = inputData[1].default;
		}
pythongosssss's avatar
pythongosssss committed
362
363
364
365
366
		const res = { widget: node.addWidget("combo", inputName, defaultValue, () => {}, { values: type }) };
		if (inputData[1]?.control_after_generate) {
			res.widget.linkedWidgets = addValueControlWidgets(node, res.widget, undefined, undefined, inputData);
		}
		return res;
367
	},
pythongosssss's avatar
pythongosssss committed
368
	IMAGEUPLOAD(node, inputName, inputData, app) {
pythongosssss's avatar
pythongosssss committed
369
		const imageWidget = node.widgets.find((w) => w.name === (inputData[1]?.widget ?? "image"));
pythongosssss's avatar
pythongosssss committed
370
371
372
373
374
375
376
377
		let uploadWidget;

		function showImage(name) {
			const img = new Image();
			img.onload = () => {
				node.imgs = [img];
				app.graph.setDirtyCanvas(true);
			};
comfyanonymous's avatar
comfyanonymous committed
378
379
380
381
382
383
			let folder_separator = name.lastIndexOf("/");
			let subfolder = "";
			if (folder_separator > -1) {
				subfolder = name.substring(0, folder_separator);
				name = name.substring(folder_separator + 1);
			}
Jairo Correa's avatar
Jairo Correa committed
384
			img.src = api.apiURL(`/view?filename=${encodeURIComponent(name)}&type=input&subfolder=${subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`);
385
			node.setSizeForImage?.();
pythongosssss's avatar
pythongosssss committed
386
387
		}

comfyanonymous's avatar
comfyanonymous committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
		var default_value = imageWidget.value;
		Object.defineProperty(imageWidget, "value", {
			set : function(value) {
				this._real_value = value;
			},

			get : function() {
				let value = "";
				if (this._real_value) {
					value = this._real_value;
				} else {
					return default_value;
				}

				if (value.filename) {
					let real_value = value;
					value = "";
					if (real_value.subfolder) {
						value = real_value.subfolder + "/";
					}

					value += real_value.filename;

					if(real_value.type && real_value.type !== "input")
						value += ` [${real_value.type}]`;
				}
				return value;
			}
		});

pythongosssss's avatar
pythongosssss committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
		// Add our own callback to the combo widget to render an image when it changes
		const cb = node.callback;
		imageWidget.callback = function () {
			showImage(imageWidget.value);
			if (cb) {
				return cb.apply(this, arguments);
			}
		};

		// On load if we have a value then render the image
		// The value isnt set immediately so we need to wait a moment
		// No change callbacks seem to be fired on initial setting of the value
		requestAnimationFrame(() => {
			if (imageWidget.value) {
				showImage(imageWidget.value);
			}
		});

436
		async function uploadFile(file, updateNode, pasted = false) {
437
438
439
440
			try {
				// Wrap file in formdata so it includes filename
				const body = new FormData();
				body.append("image", file);
441
				if (pasted) body.append("subfolder", "pasted");
442
				const resp = await api.fetchApi("/upload/image", {
443
444
445
446
447
448
					method: "POST",
					body,
				});

				if (resp.status === 200) {
					const data = await resp.json();
449
450
451
452
453
454
					// Add the file to the dropdown list and update the widget value
					let path = data.name;
					if (data.subfolder) path = data.subfolder + "/" + path;

					if (!imageWidget.options.values.includes(path)) {
						imageWidget.options.values.push(path);
455
456
457
					}

					if (updateNode) {
458
459
						showImage(path);
						imageWidget.value = path;
460
461
462
463
464
465
466
467
468
					}
				} else {
					alert(resp.status + " - " + resp.statusText);
				}
			} catch (error) {
				alert(error);
			}
		}

pythongosssss's avatar
pythongosssss committed
469
470
471
		const fileInput = document.createElement("input");
		Object.assign(fileInput, {
			type: "file",
472
			accept: "image/jpeg,image/png,image/webp",
pythongosssss's avatar
pythongosssss committed
473
474
475
			style: "display: none",
			onchange: async () => {
				if (fileInput.files.length) {
476
					await uploadFile(fileInput.files[0], true);
pythongosssss's avatar
pythongosssss committed
477
478
479
480
481
482
				}
			},
		});
		document.body.append(fileInput);

		// Create the button widget for selecting the files
pythongosssss's avatar
pythongosssss committed
483
		uploadWidget = node.addWidget("button", inputName, "image", () => {
pythongosssss's avatar
pythongosssss committed
484
485
			fileInput.click();
		});
pythongosssss's avatar
pythongosssss committed
486
		uploadWidget.label = "choose file to upload";
pythongosssss's avatar
pythongosssss committed
487
488
		uploadWidget.serialize = false;

489
490
491
		// Add handler to check if an image is being dragged over our node
		node.onDragOver = function (e) {
			if (e.dataTransfer && e.dataTransfer.items) {
492
				const image = [...e.dataTransfer.items].find((f) => f.kind === "file");
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
				return !!image;
			}

			return false;
		};

		// On drop upload files
		node.onDragDrop = function (e) {
			console.log("onDragDrop called");
			let handled = false;
			for (const file of e.dataTransfer.files) {
				if (file.type.startsWith("image/")) {
					uploadFile(file, !handled); // Dont await these, any order is fine, only update on first one
					handled = true;
				}
			}

			return handled;
		};

513
514
515
516
517
518
519
520
521
522
		node.pasteFile = function(file) {
			if (file.type.startsWith("image/")) {
				const is_pasted = (file.name === "image.png") &&
								  (file.lastModified - Date.now() < 2000);
				uploadFile(file, true, is_pasted);
				return true;
			}
			return false;
		}

pythongosssss's avatar
pythongosssss committed
523
524
		return { widget: uploadWidget };
	},
pythongosssss's avatar
pythongosssss committed
525
};