ui.js 12.5 KB
Newer Older
pythongosssss's avatar
pythongosssss committed
1
2
import { api } from "./api.js";

pythongosssss's avatar
pythongosssss committed
3
4
5
6
7
8
9
10
11
12
13
14
15
function $el(tag, propsOrChildren, children) {
	const split = tag.split(".");
	const element = document.createElement(split.shift());
	element.classList.add(...split);
	if (propsOrChildren) {
		if (Array.isArray(propsOrChildren)) {
			element.append(...propsOrChildren);
		} else {
			const parent = propsOrChildren.parent;
			delete propsOrChildren.parent;
			const cb = propsOrChildren.$;
			delete propsOrChildren.$;

pythongosssss's avatar
pythongosssss committed
16
17
18
19
20
			if (propsOrChildren.style) {
				Object.assign(element.style, propsOrChildren.style);
				delete propsOrChildren.style;
			}

pythongosssss's avatar
pythongosssss committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
			Object.assign(element, propsOrChildren);
			if (children) {
				element.append(...children);
			}

			if (parent) {
				parent.append(element);
			}

			if (cb) {
				cb(element);
			}
		}
	}
	return element;
}

38
function dragElement(dragEl, settings) {
39
40
41
42
43
44
	var posDiffX = 0,
		posDiffY = 0,
		posStartX = 0,
		posStartY = 0,
		newPosX = 0,
		newPosY = 0;
45
	if (dragEl.getElementsByClassName("drag-handle")[0]) {
Jairo Correa's avatar
Jairo Correa committed
46
		// if present, the handle is where you move the DIV from:
47
		dragEl.getElementsByClassName("drag-handle")[0].onmousedown = dragMouseDown;
Jairo Correa's avatar
Jairo Correa committed
48
49
50
51
52
	} else {
		// otherwise, move the DIV from anywhere inside the DIV:
		dragEl.onmousedown = dragMouseDown;
	}

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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
	function ensureInBounds() {
		newPosX = Math.min(document.body.clientWidth - dragEl.clientWidth, Math.max(0, dragEl.offsetLeft));
		newPosY = Math.min(document.body.clientHeight - dragEl.clientHeight, Math.max(0, dragEl.offsetTop));

		positionElement();
	}

	function positionElement() {
		const halfWidth = document.body.clientWidth / 2;
		const halfHeight = document.body.clientHeight / 2;

		const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth;
		const anchorBottom = newPosY + dragEl.clientHeight / 2 > halfHeight;

		// set the element's new position:
		if (anchorRight) {
			dragEl.style.left = "unset";
			dragEl.style.right = document.body.clientWidth - newPosX - dragEl.clientWidth + "px";
		} else {
			dragEl.style.left = newPosX + "px";
			dragEl.style.right = "unset";
		}
		if (anchorBottom) {
			dragEl.style.top = "unset";
			dragEl.style.bottom = document.body.clientHeight - newPosY - dragEl.clientHeight + "px";
		} else {
			dragEl.style.top = newPosY + "px";
			dragEl.style.bottom = "unset";
		}

		if (savePos) {
			localStorage.setItem(
				"Comfy.MenuPosition",
				JSON.stringify({
					left: dragEl.style.left,
					right: dragEl.style.right,
					top: dragEl.style.top,
					bottom: dragEl.style.bottom,
				})
			);
		}
	}

	function restorePos() {
		let pos = localStorage.getItem("Comfy.MenuPosition");
		if (pos) {
			pos = JSON.parse(pos);
			dragEl.style.left = pos.left;
			dragEl.style.right = pos.right;
			dragEl.style.top = pos.top;
			dragEl.style.bottom = pos.bottom;
104
			dragEl.classList.add("comfy-menu-manual-pos");
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
			ensureInBounds();
		}
	}

	let savePos = undefined;
	settings.addSetting({
		id: "Comfy.MenuPosition",
		name: "Save menu position",
		type: "boolean",
		defaultValue: savePos,
		onChange(value) {
			if (savePos === undefined && value) {
				restorePos();
			}
			savePos = value;
		},
	});

Jairo Correa's avatar
Jairo Correa committed
123
124
125
126
	function dragMouseDown(e) {
		e = e || window.event;
		e.preventDefault();
		// get the mouse cursor position at startup:
127
128
		posStartX = e.clientX;
		posStartY = e.clientY;
Jairo Correa's avatar
Jairo Correa committed
129
130
131
132
133
134
135
136
		document.onmouseup = closeDragElement;
		// call a function whenever the cursor moves:
		document.onmousemove = elementDrag;
	}

	function elementDrag(e) {
		e = e || window.event;
		e.preventDefault();
137
138
139

		dragEl.classList.add("comfy-menu-manual-pos");

Jairo Correa's avatar
Jairo Correa committed
140
		// calculate the new cursor position:
141
142
143
144
		posDiffX = e.clientX - posStartX;
		posDiffY = e.clientY - posStartY;
		posStartX = e.clientX;
		posStartY = e.clientY;
145
146
147
148
149

		newPosX = Math.min(document.body.clientWidth - dragEl.clientWidth, Math.max(0, dragEl.offsetLeft + posDiffX));
		newPosY = Math.min(document.body.clientHeight - dragEl.clientHeight, Math.max(0, dragEl.offsetTop + posDiffY));

		positionElement();
Jairo Correa's avatar
Jairo Correa committed
150
151
	}

152
153
154
155
156
157
	window.addEventListener("resize", () => {
		if (dragEl.classList.contains("comfy-menu-manual-pos")) {
			ensureInBounds();
		}
	});

Jairo Correa's avatar
Jairo Correa committed
158
159
160
161
162
163
164
	function closeDragElement() {
		// stop moving when mouse button is released:
		document.onmouseup = null;
		document.onmousemove = null;
	}
}

pythongosssss's avatar
pythongosssss committed
165
166
class ComfyDialog {
	constructor() {
pythongosssss's avatar
pythongosssss committed
167
168
169
170
171
172
173
174
175
176
		this.element = $el("div.comfy-modal", { parent: document.body }, [
			$el("div.comfy-modal-content", [
				$el("p", { $: (p) => (this.textElement = p) }),
				$el("button", {
					type: "button",
					textContent: "CLOSE",
					onclick: () => this.close(),
				}),
			]),
		]);
pythongosssss's avatar
pythongosssss committed
177
178
179
180
181
182
183
184
185
186
187
188
	}

	close() {
		this.element.style.display = "none";
	}

	show(html) {
		this.textElement.innerHTML = html;
		this.element.style.display = "flex";
	}
}

pythongosssss's avatar
pythongosssss committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
class ComfySettingsDialog extends ComfyDialog {
	constructor() {
		super();
		this.element.classList.add("comfy-settings");
		this.settings = [];
	}

	addSetting({ id, name, type, defaultValue, onChange }) {
		if (!id) {
			throw new Error("Settings must have an ID");
		}
		if (this.settings.find((s) => s.id === id)) {
			throw new Error("Setting IDs must be unique");
		}

		const settingId = "Comfy.Settings." + id;
		const v = localStorage[settingId];
		let value = v == null ? defaultValue : JSON.parse(v);

		// Trigger initial setting of value
		if (onChange) {
			onChange(value, undefined);
		}

		this.settings.push({
			render: () => {
				const setter = (v) => {
					if (onChange) {
						onChange(v, value);
					}
					localStorage[settingId] = JSON.stringify(v);
					value = v;
				};

				if (typeof type === "function") {
					return type(name, setter);
				}

				switch (type) {
					case "boolean":
						return $el("div", [
							$el("label", { textContent: name || id }, [
								$el("input", {
									type: "checkbox",
									checked: !!value,
									oninput: (e) => {
										setter(e.target.checked);
									},
								}),
							]),
						]);
					default:
						console.warn("Unsupported setting type, defaulting to text");
						return $el("div", [
							$el("label", { textContent: name || id }, [
								$el("input", {
									value,
									oninput: (e) => {
										setter(e.target.value);
									},
								}),
							]),
						]);
				}
			},
		});
	}

	show() {
		super.show();
		this.textElement.replaceChildren(...this.settings.map((s) => s.render()));
	}
}

pythongosssss's avatar
pythongosssss committed
263
class ComfyList {
pythongosssss's avatar
pythongosssss committed
264
265
266
267
268
269
270
	#type;
	#text;

	constructor(text, type) {
		this.#text = text;
		this.#type = type || text.toLowerCase();
		this.element = $el("div.comfy-list");
pythongosssss's avatar
pythongosssss committed
271
272
273
274
275
276
277
278
		this.element.style.display = "none";
	}

	get visible() {
		return this.element.style.display !== "none";
	}

	async load() {
pythongosssss's avatar
pythongosssss committed
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
		const items = await api.getItems(this.#type);
		this.element.replaceChildren(
			...Object.keys(items).flatMap((section) => [
				$el("h4", {
					textContent: section,
				}),
				$el("div.comfy-list-items", [
					...items[section].map((item) => {
						// Allow items to specify a custom remove action (e.g. for interrupt current prompt)
						const removeAction = item.remove || {
							name: "Delete",
							cb: () => api.deleteItem(this.#type, item.prompt[1]),
						};
						return $el("div", { textContent: item.prompt[0] + ": " }, [
							$el("button", {
								textContent: "Load",
								onclick: () => {
									if (item.outputs) {
										app.nodeOutputs = item.outputs;
									}
									app.loadGraphData(item.prompt[3].extra_pnginfo.workflow);
								},
							}),
							$el("button", {
								textContent: removeAction.name,
								onclick: async () => {
									await removeAction.cb();
									await this.update();
								},
							}),
						]);
					}),
				]),
			]),
			$el("div.comfy-list-actions", [
				$el("button", {
					textContent: "Clear " + this.#text,
					onclick: async () => {
						await api.clearItems(this.#type);
						await this.load();
					},
				}),
				$el("button", { textContent: "Refresh", onclick: () => this.load() }),
			])
		);
pythongosssss's avatar
pythongosssss committed
324
325
326
327
328
329
330
331
332
333
	}

	async update() {
		if (this.visible) {
			await this.load();
		}
	}

	async show() {
		this.element.style.display = "block";
pythongosssss's avatar
pythongosssss committed
334
335
		this.button.textContent = "Close";

pythongosssss's avatar
pythongosssss committed
336
337
338
339
340
		await this.load();
	}

	hide() {
		this.element.style.display = "none";
pythongosssss's avatar
pythongosssss committed
341
		this.button.textContent = "See " + this.#text;
pythongosssss's avatar
pythongosssss committed
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
	}

	toggle() {
		if (this.visible) {
			this.hide();
			return false;
		} else {
			this.show();
			return true;
		}
	}
}

export class ComfyUI {
	constructor(app) {
		this.app = app;
		this.dialog = new ComfyDialog();
pythongosssss's avatar
pythongosssss committed
359
		this.settings = new ComfySettingsDialog();
pythongosssss's avatar
pythongosssss committed
360

m957ymj75urz's avatar
m957ymj75urz committed
361
		this.batchCount = 1;
comfyanonymous's avatar
comfyanonymous committed
362
		this.lastQueueSize = 0;
pythongosssss's avatar
pythongosssss committed
363
364
		this.queue = new ComfyList("Queue");
		this.history = new ComfyList("History");
pythongosssss's avatar
pythongosssss committed
365

pythongosssss's avatar
pythongosssss committed
366
367
368
369
		api.addEventListener("status", () => {
			this.queue.update();
			this.history.update();
		});
pythongosssss's avatar
pythongosssss committed
370

pythongosssss's avatar
pythongosssss committed
371
372
373
		const fileInput = $el("input", {
			type: "file",
			accept: ".json,image/png",
pythongosssss's avatar
pythongosssss committed
374
			style: { display: "none" },
pythongosssss's avatar
pythongosssss committed
375
376
377
378
			parent: document.body,
			onchange: () => {
				app.handleFile(fileInput.files[0]);
			},
pythongosssss's avatar
pythongosssss committed
379
		});
pythongosssss's avatar
pythongosssss committed
380

pythongosssss's avatar
pythongosssss committed
381
		this.menuContainer = $el("div.comfy-menu", { parent: document.body }, [
pythongosssss's avatar
pythongosssss committed
382
			$el("div", { style: { overflow: "hidden", position: "relative", width: "100%" } }, [
Jairo Correa's avatar
Jairo Correa committed
383
				$el("span.drag-handle"),
pythongosssss's avatar
pythongosssss committed
384
385
386
				$el("span", { $: (q) => (this.queueSize = q) }),
				$el("button.comfy-settings-btn", { textContent: "⚙️", onclick: () => this.settings.show() }),
			]),
387
388
389
390
			$el("button.comfy-queue-btn", {
				textContent: "Queue Prompt",
				onclick: () => app.queuePrompt(0, this.batchCount),
			}),
m957ymj75urz's avatar
m957ymj75urz committed
391
			$el("div", {}, [
392
393
394
395
396
397
398
399
400
401
				$el("label", { innerHTML: "Extra options" }, [
					$el("input", {
						type: "checkbox",
						onchange: (i) => {
							document.getElementById("extraOptions").style.display = i.srcElement.checked ? "block" : "none";
							this.batchCount = i.srcElement.checked ? document.getElementById("batchCountInputRange").value : 1;
							document.getElementById("autoQueueCheckbox").checked = false;
						},
					}),
				]),
m957ymj75urz's avatar
m957ymj75urz committed
402
			]),
403
			$el("div", { id: "extraOptions", style: { width: "100%", display: "none" } }, [
m957ymj75urz's avatar
m957ymj75urz committed
404
				$el("label", { innerHTML: "Batch count" }, [
405
406
407
408
409
410
411
					$el("input", {
						id: "batchCountInputNumber",
						type: "number",
						value: this.batchCount,
						min: "1",
						style: { width: "35%", "margin-left": "0.4em" },
						oninput: (i) => {
m957ymj75urz's avatar
m957ymj75urz committed
412
							this.batchCount = i.target.value;
413
414
							document.getElementById("batchCountInputRange").value = this.batchCount;
						},
m957ymj75urz's avatar
m957ymj75urz committed
415
					}),
416
417
418
419
420
421
					$el("input", {
						id: "batchCountInputRange",
						type: "range",
						min: "1",
						max: "100",
						value: this.batchCount,
m957ymj75urz's avatar
m957ymj75urz committed
422
423
						oninput: (i) => {
							this.batchCount = i.srcElement.value;
424
425
426
427
428
429
430
431
							document.getElementById("batchCountInputNumber").value = i.srcElement.value;
						},
					}),
					$el("input", {
						id: "autoQueueCheckbox",
						type: "checkbox",
						checked: false,
						title: "automatically queue prompt when the queue size hits 0",
m957ymj75urz's avatar
m957ymj75urz committed
432
					}),
m957ymj75urz's avatar
m957ymj75urz committed
433
434
				]),
			]),
pythongosssss's avatar
pythongosssss committed
435
			$el("div.comfy-menu-btns", [
m957ymj75urz's avatar
m957ymj75urz committed
436
				$el("button", { textContent: "Queue Front", onclick: () => app.queuePrompt(-1, this.batchCount) }),
pythongosssss's avatar
pythongosssss committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
				$el("button", {
					$: (b) => (this.queue.button = b),
					textContent: "View Queue",
					onclick: () => {
						this.history.hide();
						this.queue.toggle();
					},
				}),
				$el("button", {
					$: (b) => (this.history.button = b),
					textContent: "View History",
					onclick: () => {
						this.queue.hide();
						this.history.toggle();
					},
				}),
			]),
			this.queue.element,
			this.history.element,
			$el("button", {
				textContent: "Save",
				onclick: () => {
comfyanonymous's avatar
comfyanonymous committed
459
					const json = JSON.stringify(app.graph.serialize(), null, 2); // convert the data to a JSON string
pythongosssss's avatar
pythongosssss committed
460
461
462
463
464
					const blob = new Blob([json], { type: "application/json" });
					const url = URL.createObjectURL(blob);
					const a = $el("a", {
						href: url,
						download: "workflow.json",
pythongosssss's avatar
pythongosssss committed
465
						style: { display: "none" },
pythongosssss's avatar
pythongosssss committed
466
467
468
469
470
471
472
473
474
						parent: document.body,
					});
					a.click();
					setTimeout(function () {
						a.remove();
						window.URL.revokeObjectURL(url);
					}, 0);
				},
			}),
pythongosssss's avatar
pythongosssss committed
475
			$el("button", { textContent: "Load", onclick: () => fileInput.click() }),
476
			$el("button", { textContent: "Refresh", onclick: () => app.refreshComboInNodes() }),
pythongosssss's avatar
pythongosssss committed
477
478
479
			$el("button", { textContent: "Clear", onclick: () => app.graph.clear() }),
			$el("button", { textContent: "Load Default", onclick: () => app.loadGraphData() }),
		]);
pythongosssss's avatar
pythongosssss committed
480

481
		dragElement(this.menuContainer, this.settings);
Jairo Correa's avatar
Jairo Correa committed
482

pythongosssss's avatar
pythongosssss committed
483
484
485
486
487
		this.setStatus({ exec_info: { queue_remaining: "X" } });
	}

	setStatus(status) {
		this.queueSize.textContent = "Queue size: " + (status ? status.exec_info.queue_remaining : "ERR");
comfyanonymous's avatar
comfyanonymous committed
488
		if (status) {
489
490
491
492
493
			if (
				this.lastQueueSize != 0 &&
				status.exec_info.queue_remaining == 0 &&
				document.getElementById("autoQueueCheckbox").checked
			) {
comfyanonymous's avatar
comfyanonymous committed
494
495
				app.queuePrompt(0, this.batchCount);
			}
496
			this.lastQueueSize = status.exec_info.queue_remaining;
comfyanonymous's avatar
comfyanonymous committed
497
		}
pythongosssss's avatar
pythongosssss committed
498
499
	}
}