"ppocr/vscode:/vscode.git/clone" did not exist on "da84f0b15f5c32ab4823e67316bc670f10c43e82"
widgets.js 9.55 KB
Newer Older
pythongosssss's avatar
pythongosssss committed
1
2
3
4
5
6
7
8
9
10
11
12
function getNumberDefaults(inputData, defaultStep) {
	let defaultVal = inputData[1]["default"];
	let { min, max, step } = inputData[1];

	if (defaultVal == undefined) defaultVal = 0;
	if (min == undefined) min = 0;
	if (max == undefined) max = 2048;
	if (step == undefined) step = defaultStep;

	return { val: defaultVal, config: { min, max, step: 10.0 * step } };
}

13
14
export function addRandomizeWidget(node, targetWidget, name, defaultValue = false) {
	const randomize = node.addWidget("toggle", name, defaultValue, function (v) {}, {
pythongosssss's avatar
pythongosssss committed
15
16
17
18
19
20
21
		on: "enabled",
		off: "disabled",
		serialize: false, // Don't include this in prompt.
	});

	randomize.afterQueued = () => {
		if (randomize.value) {
22
			const min = targetWidget.options?.min;
23
			let max = targetWidget.options?.max;
24
			if (min != null || max != null) {
25
26
27
28
				if (max) {
					// limit max to something that javascript can handle
					max = Math.min(1125899906842624, max);
				}
29
30
31
32
				targetWidget.value = Math.floor(Math.random() * ((max ?? 9999999999) - (min ?? 0) + 1) + (min ?? 0));
			} else {
				targetWidget.value = Math.floor(Math.random() * 1125899906842624);
			}
pythongosssss's avatar
pythongosssss committed
33
34
		}
	};
35
36
37
38
39
40
	return randomize;
}

function seedWidget(node, inputName, inputData) {
	const seed = ComfyWidgets.INT(node, inputName, inputData);
	const randomize = addRandomizeWidget(node, seed.widget, "Random seed after every gen", true);
pythongosssss's avatar
pythongosssss committed
41

42
	seed.widget.linkedWidgets = [randomize];
pythongosssss's avatar
pythongosssss committed
43
44
45
	return { widget: seed, randomize };
}

46
const MultilineSymbol = Symbol();
47
const MultilineResizeSymbol = Symbol();
48
49
50
51

function addMultilineWidget(node, name, opts, app) {
	const MIN_SIZE = 50;

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
	function computeSize(size) {
		if (node.widgets[0].last_y == null) return;

		let y = node.widgets[0].last_y;
		let freeSpace = size[1] - y;

		// Compute the height of all non customtext widgets
		let widgetHeight = 0;
		const multi = [];
		for (let i = 0; i < node.widgets.length; i++) {
			const w = node.widgets[i];
			if (w.type === "customtext") {
				multi.push(w);
			} else {
				if (w.computeSize) {
					widgetHeight += w.computeSize()[1] + 4;
				} else {
					widgetHeight += LiteGraph.NODE_WIDGET_HEIGHT + 4;
				}
			}
		}

		// See how large each text input can be
		freeSpace -= widgetHeight;
		freeSpace /= multi.length;

		if (freeSpace < MIN_SIZE) {
			// There isnt enough space for all the widgets, increase the size of the node
			freeSpace = MIN_SIZE;
			node.size[1] = y + widgetHeight + freeSpace * multi.length;
82
			node.graph.setDirtyCanvas(true);
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
		}

		// Position each of the widgets
		for (const w of node.widgets) {
			w.y = y;
			if (w.type === "customtext") {
				y += freeSpace;
			} else if (w.computeSize) {
				y += w.computeSize()[1] + 4;
			} else {
				y += LiteGraph.NODE_WIDGET_HEIGHT + 4;
			}
		}

		node.inputHeight = freeSpace;
	}

pythongosssss's avatar
pythongosssss committed
100
101
102
103
104
105
106
107
108
109
	const widget = {
		type: "customtext",
		name,
		get value() {
			return this.inputEl.value;
		},
		set value(x) {
			this.inputEl.value = x;
		},
		draw: function (ctx, _, widgetWidth, y, widgetHeight) {
110
111
112
113
114
			if (!this.parent.inputHeight) {
				// If we are initially offscreen when created we wont have received a resize event
				// Calculate it here instead
				computeSize(node.size);
			}
115
			const visible = app.canvas.ds.scale > 0.5 && this.type === "customtext";
pythongosssss's avatar
pythongosssss committed
116
117
118
119
			const t = ctx.getTransform();
			const margin = 10;
			Object.assign(this.inputEl.style, {
				left: `${t.a * margin + t.e}px`,
120
				top: `${t.d * (y + widgetHeight - margin - 3) + t.f}px`,
pythongosssss's avatar
pythongosssss committed
121
				width: `${(widgetWidth - margin * 2 - 3) * t.a}px`,
122
				height: `${(this.parent.inputHeight - margin * 2 - 4) * t.d}px`,
pythongosssss's avatar
pythongosssss committed
123
124
125
126
127
128
129
130
131
				position: "absolute",
				zIndex: 1,
				fontSize: `${t.d * 10.0}px`,
			});
			this.inputEl.hidden = !visible;
		},
	};
	widget.inputEl = document.createElement("textarea");
	widget.inputEl.className = "comfy-multiline-input";
132
133
	widget.inputEl.value = opts.defaultVal;
	widget.inputEl.placeholder = opts.placeholder || "";
comfyanonymous's avatar
comfyanonymous committed
134
	document.addEventListener("mousedown", function (event) {
pythongosssss's avatar
pythongosssss committed
135
136
137
138
139
140
141
142
143
		if (!widget.inputEl.contains(event.target)) {
			widget.inputEl.blur();
		}
	});
	widget.parent = node;
	document.body.appendChild(widget.inputEl);

	node.addCustomWidget(widget);

144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
	app.canvas.onDrawBackground = function () {
		// Draw node isnt fired once the node is off the screen
		// if it goes off screen quickly, the input may not be removed
		// this shifts it off screen so it can be moved back if the node is visible.
		for (let n in app.graph._nodes) {
			n = graph._nodes[n];
			for (let w in n.widgets) {
				let wid = n.widgets[w];
				if (Object.hasOwn(wid, "inputEl")) {
					wid.inputEl.style.left = -8000 + "px";
					wid.inputEl.style.position = "absolute";
				}
			}
		}
	};

pythongosssss's avatar
pythongosssss committed
160
161
162
163
164
165
166
167
168
	node.onRemoved = function () {
		// When removing this node we need to remove the input from the DOM
		for (let y in this.widgets) {
			if (this.widgets[y].inputEl) {
				this.widgets[y].inputEl.remove();
			}
		}
	};

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
	widget.onRemove = () => {
		widget.inputEl?.remove();

		// Restore original size handler if we are the last
		if (!--node[MultilineSymbol]) {
			node.onResize = node[MultilineResizeSymbol];
			delete node[MultilineSymbol];
			delete node[MultilineResizeSymbol];
		}
	};

	if (node[MultilineSymbol]) {
		node[MultilineSymbol]++;
	} else {
		node[MultilineSymbol] = 1;
		const onResize = (node[MultilineResizeSymbol] = node.onResize);
pythongosssss's avatar
tidy  
pythongosssss committed
185

186
		node.onResize = function (size) {
187
			computeSize(size);
188
189
190
191
192
193
194
195

			// Call original resizer handler
			if (onResize) {
				onResize.apply(this, arguments);
			}
		};
	}

pythongosssss's avatar
pythongosssss committed
196
197
198
199
200
201
202
203
204
205
206
207
	return { minWidth: 400, minHeight: 200, widget };
}

export const ComfyWidgets = {
	"INT:seed": seedWidget,
	"INT:noise_seed": seedWidget,
	FLOAT(node, inputName, inputData) {
		const { val, config } = getNumberDefaults(inputData, 0.5);
		return { widget: node.addWidget("number", inputName, val, () => {}, config) };
	},
	INT(node, inputName, inputData) {
		const { val, config } = getNumberDefaults(inputData, 1);
208
		Object.assign(config, { precision: 0 });
pythongosssss's avatar
pythongosssss committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
		return {
			widget: node.addWidget(
				"number",
				inputName,
				val,
				function (v) {
					const s = this.options.step / 10;
					this.value = Math.round(v / s) * s;
				},
				config
			),
		};
	},
	STRING(node, inputName, inputData, app) {
		const defaultVal = inputData[1].default || "";
		const multiline = !!inputData[1].multiline;

		if (multiline) {
227
			return addMultilineWidget(node, inputName, { defaultVal, ...inputData[1] }, app);
pythongosssss's avatar
pythongosssss committed
228
		} else {
229
			return { widget: node.addWidget("text", inputName, defaultVal, () => {}, {}) };
pythongosssss's avatar
pythongosssss committed
230
231
		}
	},
232
233
234
235
236
237
238
239
	COMBO(node, inputName, inputData) {
		const type = inputData[0];
		let defaultValue = type[0];
		if (inputData[1] && inputData[1].default) {
			defaultValue = inputData[1].default;
		}
		return { widget: node.addWidget("combo", inputName, defaultValue, () => {}, { values: type }) };
	},
pythongosssss's avatar
pythongosssss committed
240
241
242
243
244
245
	IMAGEUPLOAD(node, inputName, inputData, app) {
		const imageWidget = node.widgets.find((w) => w.name === "image");
		let uploadWidget;

		function showImage(name) {
			// Position the image somewhere sensible
246
			if (!node.imageOffset) {
pythongosssss's avatar
pythongosssss committed
247
248
249
250
251
252
253
254
				node.imageOffset = uploadWidget.last_y ? uploadWidget.last_y + 25 : 75;
			}

			const img = new Image();
			img.onload = () => {
				node.imgs = [img];
				app.graph.setDirtyCanvas(true);
			};
m957ymj75urz's avatar
m957ymj75urz committed
255
			img.src = `/view?filename=${name}&type=input`;
pythongosssss's avatar
pythongosssss committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
		}

		// 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);
			}
		});

276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
		async function uploadFile(file, updateNode) {
			try {
				// Wrap file in formdata so it includes filename
				const body = new FormData();
				body.append("image", file);
				const resp = await fetch("/upload/image", {
					method: "POST",
					body,
				});

				if (resp.status === 200) {
					const data = await resp.json();
					// Add the file as an option and update the widget value
					if (!imageWidget.options.values.includes(data.name)) {
						imageWidget.options.values.push(data.name);
					}

					if (updateNode) {
						showImage(data.name);

						imageWidget.value = data.name;
					}
				} else {
					alert(resp.status + " - " + resp.statusText);
				}
			} catch (error) {
				alert(error);
			}
		}

pythongosssss's avatar
pythongosssss committed
306
307
308
		const fileInput = document.createElement("input");
		Object.assign(fileInput, {
			type: "file",
309
			accept: "image/jpeg,image/png,image/webp",
pythongosssss's avatar
pythongosssss committed
310
311
312
			style: "display: none",
			onchange: async () => {
				if (fileInput.files.length) {
313
					await uploadFile(fileInput.files[0], true);
pythongosssss's avatar
pythongosssss committed
314
315
316
317
318
319
320
321
322
323
324
				}
			},
		});
		document.body.append(fileInput);

		// Create the button widget for selecting the files
		uploadWidget = node.addWidget("button", "choose file to upload", "image", () => {
			fileInput.click();
		});
		uploadWidget.serialize = false;

325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
		// Add handler to check if an image is being dragged over our node
		node.onDragOver = function (e) {
			if (e.dataTransfer && e.dataTransfer.items) {
				const image = [...e.dataTransfer.items].find((f) => f.kind === "file" && f.type.startsWith("image/"));
				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;
		};

pythongosssss's avatar
pythongosssss committed
349
350
		return { widget: uploadWidget };
	},
pythongosssss's avatar
pythongosssss committed
351
};