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

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

17
18
19
20
21
22
			if (style) {
				Object.assign(element.style, style);
			}

			if (dataset) {
				Object.assign(element.dataset, dataset);
pythongosssss's avatar
pythongosssss committed
23
24
			}

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

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

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

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

pythongosssss's avatar
pythongosssss committed
57
58
59
60
61
	// When the element resizes (e.g. view queue) ensure it is still in the windows bounds
	const resizeObserver = new ResizeObserver(() => {
		ensureInBounds();
	}).observe(dragEl);

62
	function ensureInBounds() {
pythongosssss's avatar
pythongosssss committed
63
		if (dragEl.classList.contains("comfy-menu-manual-pos")) {
pythongosssss's avatar
pythongosssss committed
64
65
			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));
66

pythongosssss's avatar
pythongosssss committed
67
68
			positionElement();
		}
pythongosssss's avatar
pythongosssss committed
69
	}
70
71
72
73
74
75
76
77
78
79
80
81
82

	function positionElement() {
		const halfWidth = document.body.clientWidth / 2;
		const anchorRight = newPosX + dragEl.clientWidth / 2 > halfWidth;

		// 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";
		}
83

pythongosssss's avatar
pythongosssss committed
84
85
		dragEl.style.top = newPosY + "px";
		dragEl.style.bottom = "unset";
86
87
88
89
90

		if (savePos) {
			localStorage.setItem(
				"Comfy.MenuPosition",
				JSON.stringify({
pythongosssss's avatar
pythongosssss committed
91
92
					x: dragEl.offsetLeft,
					y: dragEl.offsetTop,
93
94
95
96
97
98
99
100
101
				})
			);
		}
	}

	function restorePos() {
		let pos = localStorage.getItem("Comfy.MenuPosition");
		if (pos) {
			pos = JSON.parse(pos);
pythongosssss's avatar
pythongosssss committed
102
103
104
			newPosX = pos.x;
			newPosY = pos.y;
			positionElement();
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
			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
122
123
124
125
	function dragMouseDown(e) {
		e = e || window.event;
		e.preventDefault();
		// get the mouse cursor position at startup:
126
127
		posStartX = e.clientX;
		posStartY = e.clientY;
Jairo Correa's avatar
Jairo Correa committed
128
129
130
131
132
133
134
135
		document.onmouseup = closeDragElement;
		// call a function whenever the cursor moves:
		document.onmousemove = elementDrag;
	}

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

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

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

		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
149
150
	}

151
	window.addEventListener("resize", () => {
152
		ensureInBounds();
153
154
	});

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

162
export class ComfyDialog {
pythongosssss's avatar
pythongosssss committed
163
	constructor() {
pythongosssss's avatar
pythongosssss committed
164
		this.element = $el("div.comfy-modal", { parent: document.body }, [
165
			$el("div.comfy-modal-content", [$el("p", { $: (p) => (this.textElement = p) }), ...this.createButtons()]),
pythongosssss's avatar
pythongosssss committed
166
		]);
pythongosssss's avatar
pythongosssss committed
167
168
	}

169
170
171
172
173
174
175
176
177
178
	createButtons() {
		return [
			$el("button", {
				type: "button",
				textContent: "Close",
				onclick: () => this.close(),
			}),
		];
	}

pythongosssss's avatar
pythongosssss committed
179
180
181
182
183
	close() {
		this.element.style.display = "none";
	}

	show(html) {
184
185
186
187
188
		if (typeof html === "string") {
			this.textElement.innerHTML = html;
		} else {
			this.textElement.replaceChildren(html);
		}
pythongosssss's avatar
pythongosssss committed
189
190
191
192
		this.element.style.display = "flex";
	}
}

pythongosssss's avatar
pythongosssss committed
193
194
195
196
197
198
199
class ComfySettingsDialog extends ComfyDialog {
	constructor() {
		super();
		this.element.classList.add("comfy-settings");
		this.settings = [];
	}

Jairo Correa's avatar
Jairo Correa committed
200
201
202
203
204
205
206
207
208
209
210
	getSettingValue(id, defaultValue) {
		const settingId = "Comfy.Settings." + id;
		const v = localStorage[settingId];
		return v == null ? defaultValue : JSON.parse(v);
	}

	setSettingValue(id, value) {
		const settingId = "Comfy.Settings." + id;
		localStorage[settingId] = JSON.stringify(value);
	}

211
	addSetting({ id, name, type, defaultValue, onChange, attrs = {}, tooltip = "", }) {
pythongosssss's avatar
pythongosssss committed
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
		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;
				};

238
				let element;
239
				value = this.getSettingValue(id, defaultValue);
240

pythongosssss's avatar
pythongosssss committed
241
				if (typeof type === "function") {
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
					element = type(name, setter, value, attrs);
				} else {
					switch (type) {
						case "boolean":
							element = $el("div", [
								$el("label", { textContent: name || id }, [
									$el("input", {
										type: "checkbox",
										checked: !!value,
										oninput: (e) => {
											setter(e.target.checked);
										},
										...attrs
									}),
								]),
							]);
							break;
						case "number":
							element = $el("div", [
								$el("label", { textContent: name || id }, [
									$el("input", {
										type,
										value,
										oninput: (e) => {
											setter(e.target.value);
										},
										...attrs
									}),
								]),
							]);
							break;
missionfloyd's avatar
missionfloyd committed
273
						case "slider":
missionfloyd's avatar
missionfloyd committed
274
275
276
277
278
279
280
							element = $el("div", [
								$el("label", { textContent: name }, [
									$el("input", {
										type: "range",
										value,
										oninput: (e) => {
											setter(e.target.value);
missionfloyd's avatar
missionfloyd committed
281
											e.target.nextElementSibling.value = e.target.value;
missionfloyd's avatar
missionfloyd committed
282
283
284
										},
										...attrs
									}),
missionfloyd's avatar
missionfloyd committed
285
									$el("input", {
missionfloyd's avatar
missionfloyd committed
286
287
288
289
										type: "number",
										value,
										oninput: (e) => {
											setter(e.target.value);
missionfloyd's avatar
missionfloyd committed
290
											e.target.previousElementSibling.value = e.target.value;
missionfloyd's avatar
missionfloyd committed
291
292
293
294
295
296
										},
										...attrs
									}),
								]),
							]);
							break;
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
						default:
							console.warn("Unsupported setting type, defaulting to text");
							element = $el("div", [
								$el("label", { textContent: name || id }, [
									$el("input", {
										value,
										oninput: (e) => {
											setter(e.target.value);
										},
										...attrs
									}),
								]),
							]);
							break;
					}
pythongosssss's avatar
pythongosssss committed
312
				}
313
314
				if(tooltip) {
					element.title = tooltip;
pythongosssss's avatar
pythongosssss committed
315
				}
316
317

				return element;
pythongosssss's avatar
pythongosssss committed
318
319
			},
		});
320
321
322
323
324
325
326
327
328
329

		const self = this;
		return {
			get value() {
				return self.getSettingValue(id, defaultValue);
			},
			set value(v) {
				self.setSettingValue(id, v);
			},
		};
pythongosssss's avatar
pythongosssss committed
330
331
332
333
	}

	show() {
		super.show();
334
335
336
337
338
		Object.assign(this.textElement.style, {
			display: "flex",
			flexDirection: "column",
			gap: "10px"
		});
pythongosssss's avatar
pythongosssss committed
339
340
341
342
		this.textElement.replaceChildren(...this.settings.map((s) => s.render()));
	}
}

pythongosssss's avatar
pythongosssss committed
343
class ComfyList {
pythongosssss's avatar
pythongosssss committed
344
345
346
347
348
349
350
	#type;
	#text;

	constructor(text, type) {
		this.#text = text;
		this.#type = type || text.toLowerCase();
		this.element = $el("div.comfy-list");
pythongosssss's avatar
pythongosssss committed
351
352
353
354
355
356
357
358
		this.element.style.display = "none";
	}

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

	async load() {
pythongosssss's avatar
pythongosssss committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
		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: () => {
376
									app.loadGraphData(item.prompt[3].extra_pnginfo.workflow);
pythongosssss's avatar
pythongosssss committed
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
									if (item.outputs) {
										app.nodeOutputs = item.outputs;
									}
								},
							}),
							$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
404
405
406
407
408
409
410
411
412
413
	}

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

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

pythongosssss's avatar
pythongosssss committed
416
417
418
419
420
		await this.load();
	}

	hide() {
		this.element.style.display = "none";
pythongosssss's avatar
pythongosssss committed
421
		this.button.textContent = "See " + this.#text;
pythongosssss's avatar
pythongosssss committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
	}

	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
439
		this.settings = new ComfySettingsDialog();
pythongosssss's avatar
pythongosssss committed
440

m957ymj75urz's avatar
m957ymj75urz committed
441
		this.batchCount = 1;
comfyanonymous's avatar
comfyanonymous committed
442
		this.lastQueueSize = 0;
pythongosssss's avatar
pythongosssss committed
443
444
		this.queue = new ComfyList("Queue");
		this.history = new ComfyList("History");
pythongosssss's avatar
pythongosssss committed
445

pythongosssss's avatar
pythongosssss committed
446
447
448
449
		api.addEventListener("status", () => {
			this.queue.update();
			this.history.update();
		});
pythongosssss's avatar
pythongosssss committed
450

451
452
453
454
455
456
		const confirmClear = this.settings.addSetting({
			id: "Comfy.ConfirmClear",
			name: "Require confirmation when clearing workflow",
			type: "boolean",
			defaultValue: true,
		});
457

458
459
460
461
462
463
464
		const promptFilename = this.settings.addSetting({
			id: "Comfy.PromptFilename",
			name: "Prompt for filename when saving workflow",
			type: "boolean",
			defaultValue: true,
		});

465
466
467
		/**
		 * file format for preview
		 *
468
		 * format;quality
469
470
		 *
		 * ex)
471
		 * webp;50 -> webp, quality 50
472
473
474
475
476
477
478
479
480
481
482
		 * jpeg;80 -> rgb, jpeg, quality 80
		 *
		 * @type {string}
		 */
		const previewImage = this.settings.addSetting({
			id: "Comfy.PreviewFormat",
			name: "When displaying a preview in the image widget, convert it to a lightweight image. (webp, jpeg, webp;50, ...)",
			type: "string",
			defaultValue: "",
		});

pythongosssss's avatar
pythongosssss committed
483
		const fileInput = $el("input", {
484
			id: "comfy-file-input",
pythongosssss's avatar
pythongosssss committed
485
			type: "file",
486
			accept: ".json,image/png,.latent",
pythongosssss's avatar
pythongosssss committed
487
			style: { display: "none" },
pythongosssss's avatar
pythongosssss committed
488
489
490
491
			parent: document.body,
			onchange: () => {
				app.handleFile(fileInput.files[0]);
			},
pythongosssss's avatar
pythongosssss committed
492
		});
pythongosssss's avatar
pythongosssss committed
493

pythongosssss's avatar
pythongosssss committed
494
		this.menuContainer = $el("div.comfy-menu", { parent: document.body }, [
missionfloyd's avatar
missionfloyd committed
495
			$el("div.drag-handle", { style: { overflow: "hidden", position: "relative", width: "100%", cursor: "default" } }, [
Jairo Correa's avatar
Jairo Correa committed
496
				$el("span.drag-handle"),
pythongosssss's avatar
pythongosssss committed
497
498
499
				$el("span", { $: (q) => (this.queueSize = q) }),
				$el("button.comfy-settings-btn", { textContent: "⚙️", onclick: () => this.settings.show() }),
			]),
500
			$el("button.comfy-queue-btn", {
501
				id: "queue-button",
502
503
504
				textContent: "Queue Prompt",
				onclick: () => app.queuePrompt(0, this.batchCount),
			}),
m957ymj75urz's avatar
m957ymj75urz committed
505
			$el("div", {}, [
506
507
508
509
510
511
512
513
514
515
				$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
516
			]),
517
			$el("div", { id: "extraOptions", style: { width: "100%", display: "none" } }, [
m957ymj75urz's avatar
m957ymj75urz committed
518
				$el("label", { innerHTML: "Batch count" }, [
519
520
521
522
523
524
525
					$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
526
							this.batchCount = i.target.value;
527
528
							document.getElementById("batchCountInputRange").value = this.batchCount;
						},
m957ymj75urz's avatar
m957ymj75urz committed
529
					}),
530
531
532
533
534
535
					$el("input", {
						id: "batchCountInputRange",
						type: "range",
						min: "1",
						max: "100",
						value: this.batchCount,
m957ymj75urz's avatar
m957ymj75urz committed
536
537
						oninput: (i) => {
							this.batchCount = i.srcElement.value;
538
539
540
541
542
543
544
545
							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
546
					}),
m957ymj75urz's avatar
m957ymj75urz committed
547
548
				]),
			]),
pythongosssss's avatar
pythongosssss committed
549
			$el("div.comfy-menu-btns", [
550
				$el("button", { id: "queue-front-button", textContent: "Queue Front", onclick: () => app.queuePrompt(-1, this.batchCount) }),
pythongosssss's avatar
pythongosssss committed
551
552
				$el("button", {
					$: (b) => (this.queue.button = b),
553
					id: "comfy-view-queue-button",
pythongosssss's avatar
pythongosssss committed
554
555
556
557
558
559
560
561
					textContent: "View Queue",
					onclick: () => {
						this.history.hide();
						this.queue.toggle();
					},
				}),
				$el("button", {
					$: (b) => (this.history.button = b),
562
					id: "comfy-view-history-button",
pythongosssss's avatar
pythongosssss committed
563
564
565
566
567
568
569
570
571
572
					textContent: "View History",
					onclick: () => {
						this.queue.hide();
						this.history.toggle();
					},
				}),
			]),
			this.queue.element,
			this.history.element,
			$el("button", {
573
				id: "comfy-save-button",
pythongosssss's avatar
pythongosssss committed
574
575
				textContent: "Save",
				onclick: () => {
576
577
578
579
580
581
582
583
					let filename = "workflow.json";
					if (promptFilename.value) {
						filename = prompt("Save workflow as:", filename);
						if (!filename) return;
						if (!filename.toLowerCase().endsWith(".json")) {
							filename += ".json";
						}
					}
comfyanonymous's avatar
comfyanonymous committed
584
					const json = JSON.stringify(app.graph.serialize(), null, 2); // convert the data to a JSON string
pythongosssss's avatar
pythongosssss committed
585
586
587
588
					const blob = new Blob([json], { type: "application/json" });
					const url = URL.createObjectURL(blob);
					const a = $el("a", {
						href: url,
589
						download: filename,
pythongosssss's avatar
pythongosssss committed
590
						style: { display: "none" },
pythongosssss's avatar
pythongosssss committed
591
592
593
594
595
596
597
598
599
						parent: document.body,
					});
					a.click();
					setTimeout(function () {
						a.remove();
						window.URL.revokeObjectURL(url);
					}, 0);
				},
			}),
600
601
			$el("button", { id: "comfy-load-button", textContent: "Load", onclick: () => fileInput.click() }),
			$el("button", { id: "comfy-refresh-button", textContent: "Refresh", onclick: () => app.refreshComboInNodes() }),
602
			$el("button", { id: "comfy-clipspace-button", textContent: "Clipspace", onclick: () => app.openClipspace() }),
603
			$el("button", { id: "comfy-clear-button", textContent: "Clear", onclick: () => {
604
				if (!confirmClear.value || confirm("Clear workflow?")) {
605
606
607
608
					app.clean();
					app.graph.clear();
				}
			}}),
609
			$el("button", { id: "comfy-load-default-button", textContent: "Load Default", onclick: () => {
610
				if (!confirmClear.value || confirm("Load default workflow?")) {
611
612
					app.loadGraphData()
				}
613
			}}),
pythongosssss's avatar
pythongosssss committed
614
		]);
pythongosssss's avatar
pythongosssss committed
615

616
		dragElement(this.menuContainer, this.settings);
Jairo Correa's avatar
Jairo Correa committed
617

pythongosssss's avatar
pythongosssss committed
618
619
620
621
622
		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
623
		if (status) {
624
625
626
627
628
			if (
				this.lastQueueSize != 0 &&
				status.exec_info.queue_remaining == 0 &&
				document.getElementById("autoQueueCheckbox").checked
			) {
comfyanonymous's avatar
comfyanonymous committed
629
630
				app.queuePrompt(0, this.batchCount);
			}
631
			this.lastQueueSize = status.exec_info.queue_remaining;
comfyanonymous's avatar
comfyanonymous committed
632
		}
pythongosssss's avatar
pythongosssss committed
633
634
	}
}