ui.js 14.4 KB
Newer Older
1
2
3
4
5
import { api } from "./api.js";
import { ComfyDialog as _ComfyDialog } from "./ui/dialog.js";
import { ComfySettingsDialog } from "./ui/settings.js";

export const ComfyDialog = _ComfyDialog;
pythongosssss's avatar
pythongosssss committed
6

Jairo Correa's avatar
Jairo Correa committed
7
export function $el(tag, propsOrChildren, children) {
pythongosssss's avatar
pythongosssss committed
8
9
	const split = tag.split(".");
	const element = document.createElement(split.shift());
reaper47's avatar
reaper47 committed
10
11
12
13
	if (split.length > 0) {
		element.classList.add(...split);
	}

pythongosssss's avatar
pythongosssss committed
14
15
16
17
	if (propsOrChildren) {
		if (Array.isArray(propsOrChildren)) {
			element.append(...propsOrChildren);
		} else {
reaper47's avatar
reaper47 committed
18
			const {parent, $: cb, dataset, style} = propsOrChildren;
pythongosssss's avatar
pythongosssss committed
19
20
			delete propsOrChildren.parent;
			delete propsOrChildren.$;
21
22
			delete propsOrChildren.dataset;
			delete propsOrChildren.style;
pythongosssss's avatar
pythongosssss committed
23

reaper47's avatar
reaper47 committed
24
25
26
27
			if (Object.hasOwn(propsOrChildren, "for")) {
				element.setAttribute("for", propsOrChildren.for)
			}

28
29
30
31
32
33
			if (style) {
				Object.assign(element.style, style);
			}

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

pythongosssss's avatar
pythongosssss committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
			Object.assign(element, propsOrChildren);
			if (children) {
				element.append(...children);
			}

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

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

53
function dragElement(dragEl, settings) {
54
55
56
57
58
59
	var posDiffX = 0,
		posDiffY = 0,
		posStartX = 0,
		posStartY = 0,
		newPosX = 0,
		newPosY = 0;
60
	if (dragEl.getElementsByClassName("drag-handle")[0]) {
Jairo Correa's avatar
Jairo Correa committed
61
		// if present, the handle is where you move the DIV from:
62
		dragEl.getElementsByClassName("drag-handle")[0].onmousedown = dragMouseDown;
Jairo Correa's avatar
Jairo Correa committed
63
64
65
66
67
	} else {
		// otherwise, move the DIV from anywhere inside the DIV:
		dragEl.onmousedown = dragMouseDown;
	}

pythongosssss's avatar
pythongosssss committed
68
69
70
71
72
	// When the element resizes (e.g. view queue) ensure it is still in the windows bounds
	const resizeObserver = new ResizeObserver(() => {
		ensureInBounds();
	}).observe(dragEl);

73
	function ensureInBounds() {
pythongosssss's avatar
pythongosssss committed
74
		if (dragEl.classList.contains("comfy-menu-manual-pos")) {
pythongosssss's avatar
pythongosssss committed
75
76
			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));
77

pythongosssss's avatar
pythongosssss committed
78
79
			positionElement();
		}
pythongosssss's avatar
pythongosssss committed
80
	}
81
82
83
84
85
86
87
88
89
90
91
92
93

	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";
		}
94

pythongosssss's avatar
pythongosssss committed
95
96
		dragEl.style.top = newPosY + "px";
		dragEl.style.bottom = "unset";
97
98
99
100
101

		if (savePos) {
			localStorage.setItem(
				"Comfy.MenuPosition",
				JSON.stringify({
pythongosssss's avatar
pythongosssss committed
102
103
					x: dragEl.offsetLeft,
					y: dragEl.offsetTop,
104
105
106
107
108
109
110
111
112
				})
			);
		}
	}

	function restorePos() {
		let pos = localStorage.getItem("Comfy.MenuPosition");
		if (pos) {
			pos = JSON.parse(pos);
pythongosssss's avatar
pythongosssss committed
113
114
115
			newPosX = pos.x;
			newPosY = pos.y;
			positionElement();
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
			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;
		},
	});
reaper47's avatar
reaper47 committed
133

Jairo Correa's avatar
Jairo Correa committed
134
135
136
137
	function dragMouseDown(e) {
		e = e || window.event;
		e.preventDefault();
		// get the mouse cursor position at startup:
138
139
		posStartX = e.clientX;
		posStartY = e.clientY;
Jairo Correa's avatar
Jairo Correa committed
140
141
142
143
144
145
146
147
		document.onmouseup = closeDragElement;
		// call a function whenever the cursor moves:
		document.onmousemove = elementDrag;
	}

	function elementDrag(e) {
		e = e || window.event;
		e.preventDefault();
148
149
150

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

Jairo Correa's avatar
Jairo Correa committed
151
		// calculate the new cursor position:
152
153
154
155
		posDiffX = e.clientX - posStartX;
		posDiffY = e.clientY - posStartY;
		posStartX = e.clientX;
		posStartY = e.clientY;
156
157
158
159
160

		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
161
162
	}

163
	window.addEventListener("resize", () => {
164
		ensureInBounds();
165
166
	});

Jairo Correa's avatar
Jairo Correa committed
167
168
169
170
171
172
173
	function closeDragElement() {
		// stop moving when mouse button is released:
		document.onmouseup = null;
		document.onmousemove = null;
	}
}

pythongosssss's avatar
pythongosssss committed
174
class ComfyList {
pythongosssss's avatar
pythongosssss committed
175
176
	#type;
	#text;
177
	#reverse;
pythongosssss's avatar
pythongosssss committed
178

179
	constructor(text, type, reverse) {
pythongosssss's avatar
pythongosssss committed
180
181
		this.#text = text;
		this.#type = type || text.toLowerCase();
182
		this.#reverse = reverse || false;
pythongosssss's avatar
pythongosssss committed
183
		this.element = $el("div.comfy-list");
pythongosssss's avatar
pythongosssss committed
184
185
186
187
188
189
190
191
		this.element.style.display = "none";
	}

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

	async load() {
pythongosssss's avatar
pythongosssss committed
192
193
194
195
196
197
198
		const items = await api.getItems(this.#type);
		this.element.replaceChildren(
			...Object.keys(items).flatMap((section) => [
				$el("h4", {
					textContent: section,
				}),
				$el("div.comfy-list-items", [
199
					...(this.#reverse ? items[section].reverse() : items[section]).map((item) => {
pythongosssss's avatar
pythongosssss committed
200
201
202
203
204
						// 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]),
						};
reaper47's avatar
reaper47 committed
205
						return $el("div", {textContent: item.prompt[0] + ": "}, [
pythongosssss's avatar
pythongosssss committed
206
207
							$el("button", {
								textContent: "Load",
pythongosssss's avatar
pythongosssss committed
208
209
								onclick: async () => {
									await app.loadGraphData(item.prompt[3].extra_pnginfo.workflow);
pythongosssss's avatar
pythongosssss committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
									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();
					},
				}),
reaper47's avatar
reaper47 committed
234
				$el("button", {textContent: "Refresh", onclick: () => this.load()}),
pythongosssss's avatar
pythongosssss committed
235
236
			])
		);
pythongosssss's avatar
pythongosssss committed
237
238
239
240
241
242
243
244
245
246
	}

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

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

pythongosssss's avatar
pythongosssss committed
249
250
251
252
253
		await this.load();
	}

	hide() {
		this.element.style.display = "none";
comfyanonymous's avatar
comfyanonymous committed
254
		this.button.textContent = "View " + this.#text;
pythongosssss's avatar
pythongosssss committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
	}

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

m957ymj75urz's avatar
m957ymj75urz committed
274
		this.batchCount = 1;
comfyanonymous's avatar
comfyanonymous committed
275
		this.lastQueueSize = 0;
pythongosssss's avatar
pythongosssss committed
276
		this.queue = new ComfyList("Queue");
277
		this.history = new ComfyList("History", "history", true);
pythongosssss's avatar
pythongosssss committed
278

pythongosssss's avatar
pythongosssss committed
279
280
281
282
		api.addEventListener("status", () => {
			this.queue.update();
			this.history.update();
		});
pythongosssss's avatar
pythongosssss committed
283

284
285
286
287
288
289
		const confirmClear = this.settings.addSetting({
			id: "Comfy.ConfirmClear",
			name: "Require confirmation when clearing workflow",
			type: "boolean",
			defaultValue: true,
		});
290

291
292
293
294
295
296
297
		const promptFilename = this.settings.addSetting({
			id: "Comfy.PromptFilename",
			name: "Prompt for filename when saving workflow",
			type: "boolean",
			defaultValue: true,
		});

298
299
300
		/**
		 * file format for preview
		 *
301
		 * format;quality
302
303
		 *
		 * ex)
304
		 * webp;50 -> webp, quality 50
305
306
307
308
309
310
		 * jpeg;80 -> rgb, jpeg, quality 80
		 *
		 * @type {string}
		 */
		const previewImage = this.settings.addSetting({
			id: "Comfy.PreviewFormat",
reaper47's avatar
reaper47 committed
311
312
			name: "When displaying a preview in the image widget, convert it to a lightweight image, e.g. webp, jpeg, webp;50, etc.",
			type: "text",
313
314
315
			defaultValue: "",
		});

316
317
318
319
320
321
322
		this.settings.addSetting({
			id: "Comfy.DisableSliders",
			name: "Disable sliders.",
			type: "boolean",
			defaultValue: false,
		});

323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
		this.settings.addSetting({
			id: "Comfy.DisableFloatRounding",
			name: "Disable rounding floats (requires page reload).",
			type: "boolean",
			defaultValue: false,
		});

		this.settings.addSetting({
			id: "Comfy.FloatRoundingPrecision",
			name: "Decimal places [0 = auto] (requires page reload).",
			type: "slider",
			attrs: {
				min: 0,
				max: 6,
				step: 1,
			},
			defaultValue: 0,
		});

pythongosssss's avatar
pythongosssss committed
342
		const fileInput = $el("input", {
343
			id: "comfy-file-input",
pythongosssss's avatar
pythongosssss committed
344
			type: "file",
345
			accept: ".json,image/png,.latent,.safetensors,image/webp",
reaper47's avatar
reaper47 committed
346
			style: {display: "none"},
pythongosssss's avatar
pythongosssss committed
347
348
349
350
			parent: document.body,
			onchange: () => {
				app.handleFile(fileInput.files[0]);
			},
pythongosssss's avatar
pythongosssss committed
351
		});
pythongosssss's avatar
pythongosssss committed
352

reaper47's avatar
reaper47 committed
353
354
355
356
357
358
359
360
361
		this.menuContainer = $el("div.comfy-menu", {parent: document.body}, [
			$el("div.drag-handle", {
				style: {
					overflow: "hidden",
					position: "relative",
					width: "100%",
					cursor: "default"
				}
			}, [
Jairo Correa's avatar
Jairo Correa committed
362
				$el("span.drag-handle"),
reaper47's avatar
reaper47 committed
363
364
				$el("span", {$: (q) => (this.queueSize = q)}),
				$el("button.comfy-settings-btn", {textContent: "⚙️", onclick: () => this.settings.show()}),
pythongosssss's avatar
pythongosssss committed
365
			]),
366
			$el("button.comfy-queue-btn", {
367
				id: "queue-button",
368
369
370
				textContent: "Queue Prompt",
				onclick: () => app.queuePrompt(0, this.batchCount),
			}),
m957ymj75urz's avatar
m957ymj75urz committed
371
			$el("div", {}, [
reaper47's avatar
reaper47 committed
372
				$el("label", {innerHTML: "Extra options"}, [
373
374
375
376
377
378
379
380
381
					$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
382
			]),
reaper47's avatar
reaper47 committed
383
			$el("div", {id: "extraOptions", style: {width: "100%", display: "none"}}, [
384
385
386
				$el("div",[

					$el("label", {innerHTML: "Batch count"}),
387
388
389
390
391
					$el("input", {
						id: "batchCountInputNumber",
						type: "number",
						value: this.batchCount,
						min: "1",
reaper47's avatar
reaper47 committed
392
						style: {width: "35%", "margin-left": "0.4em"},
393
						oninput: (i) => {
m957ymj75urz's avatar
m957ymj75urz committed
394
							this.batchCount = i.target.value;
395
396
							document.getElementById("batchCountInputRange").value = this.batchCount;
						},
m957ymj75urz's avatar
m957ymj75urz committed
397
					}),
398
399
400
401
402
403
					$el("input", {
						id: "batchCountInputRange",
						type: "range",
						min: "1",
						max: "100",
						value: this.batchCount,
m957ymj75urz's avatar
m957ymj75urz committed
404
405
						oninput: (i) => {
							this.batchCount = i.srcElement.value;
406
407
							document.getElementById("batchCountInputNumber").value = i.srcElement.value;
						},
408
409
410
411
412
413
414
415
					}),		
				]),

				$el("div",[
					$el("label",{
						for:"autoQueueCheckbox",
						innerHTML: "Auto Queue"
						// textContent: "Auto Queue"
416
417
418
419
420
					}),
					$el("input", {
						id: "autoQueueCheckbox",
						type: "checkbox",
						checked: false,
421
422
						title: "Automatically queue prompt when the queue size hits 0",
						
m957ymj75urz's avatar
m957ymj75urz committed
423
					}),
424
				])
m957ymj75urz's avatar
m957ymj75urz committed
425
			]),
pythongosssss's avatar
pythongosssss committed
426
			$el("div.comfy-menu-btns", [
reaper47's avatar
reaper47 committed
427
428
429
430
431
				$el("button", {
					id: "queue-front-button",
					textContent: "Queue Front",
					onclick: () => app.queuePrompt(-1, this.batchCount)
				}),
pythongosssss's avatar
pythongosssss committed
432
433
				$el("button", {
					$: (b) => (this.queue.button = b),
434
					id: "comfy-view-queue-button",
pythongosssss's avatar
pythongosssss committed
435
436
437
438
439
440
441
442
					textContent: "View Queue",
					onclick: () => {
						this.history.hide();
						this.queue.toggle();
					},
				}),
				$el("button", {
					$: (b) => (this.history.button = b),
443
					id: "comfy-view-history-button",
pythongosssss's avatar
pythongosssss committed
444
445
446
447
448
449
450
451
452
453
					textContent: "View History",
					onclick: () => {
						this.queue.hide();
						this.history.toggle();
					},
				}),
			]),
			this.queue.element,
			this.history.element,
			$el("button", {
454
				id: "comfy-save-button",
pythongosssss's avatar
pythongosssss committed
455
456
				textContent: "Save",
				onclick: () => {
457
458
459
460
461
462
463
464
					let filename = "workflow.json";
					if (promptFilename.value) {
						filename = prompt("Save workflow as:", filename);
						if (!filename) return;
						if (!filename.toLowerCase().endsWith(".json")) {
							filename += ".json";
						}
					}
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
					app.graphToPrompt().then(p=>{
						const json = JSON.stringify(p.workflow, null, 2); // convert the data to a JSON string
						const blob = new Blob([json], {type: "application/json"});
						const url = URL.createObjectURL(blob);
						const a = $el("a", {
							href: url,
							download: filename,
							style: {display: "none"},
							parent: document.body,
						});
						a.click();
						setTimeout(function () {
							a.remove();
							window.URL.revokeObjectURL(url);
						}, 0);
pythongosssss's avatar
pythongosssss committed
480
481
482
					});
				},
			}),
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
			$el("button", {
				id: "comfy-dev-save-api-button",
				textContent: "Save (API Format)",
				style: {width: "100%", display: "none"},
				onclick: () => {
					let filename = "workflow_api.json";
					if (promptFilename.value) {
						filename = prompt("Save workflow (API) as:", filename);
						if (!filename) return;
						if (!filename.toLowerCase().endsWith(".json")) {
							filename += ".json";
						}
					}
					app.graphToPrompt().then(p=>{
						const json = JSON.stringify(p.output, null, 2); // convert the data to a JSON string
						const blob = new Blob([json], {type: "application/json"});
						const url = URL.createObjectURL(blob);
						const a = $el("a", {
							href: url,
							download: filename,
							style: {display: "none"},
							parent: document.body,
						});
						a.click();
						setTimeout(function () {
							a.remove();
							window.URL.revokeObjectURL(url);
						}, 0);
					});
				},
			}),
reaper47's avatar
reaper47 committed
514
515
516
517
518
519
520
521
522
523
524
525
526
			$el("button", {id: "comfy-load-button", textContent: "Load", onclick: () => fileInput.click()}),
			$el("button", {
				id: "comfy-refresh-button",
				textContent: "Refresh",
				onclick: () => app.refreshComboInNodes()
			}),
			$el("button", {id: "comfy-clipspace-button", textContent: "Clipspace", onclick: () => app.openClipspace()}),
			$el("button", {
				id: "comfy-clear-button", textContent: "Clear", onclick: () => {
					if (!confirmClear.value || confirm("Clear workflow?")) {
						app.clean();
						app.graph.clear();
					}
527
				}
reaper47's avatar
reaper47 committed
528
529
			}),
			$el("button", {
pythongosssss's avatar
pythongosssss committed
530
				id: "comfy-load-default-button", textContent: "Load Default", onclick: async () => {
reaper47's avatar
reaper47 committed
531
					if (!confirmClear.value || confirm("Load default workflow?")) {
pythongosssss's avatar
pythongosssss committed
532
						await app.loadGraphData()
reaper47's avatar
reaper47 committed
533
					}
534
				}
reaper47's avatar
reaper47 committed
535
			}),
pythongosssss's avatar
pythongosssss committed
536
		]);
pythongosssss's avatar
pythongosssss committed
537

538
539
540
541
542
543
544
545
		const devMode = this.settings.addSetting({
			id: "Comfy.DevMode",
			name: "Enable Dev mode Options",
			type: "boolean",
			defaultValue: false,
			onChange: function(value) { document.getElementById("comfy-dev-save-api-button").style.display = value ? "block" : "none"},
		});

546
		dragElement(this.menuContainer, this.settings);
Jairo Correa's avatar
Jairo Correa committed
547

reaper47's avatar
reaper47 committed
548
		this.setStatus({exec_info: {queue_remaining: "X"}});
pythongosssss's avatar
pythongosssss committed
549
550
551
552
	}

	setStatus(status) {
		this.queueSize.textContent = "Queue size: " + (status ? status.exec_info.queue_remaining : "ERR");
comfyanonymous's avatar
comfyanonymous committed
553
		if (status) {
554
555
556
			if (
				this.lastQueueSize != 0 &&
				status.exec_info.queue_remaining == 0 &&
Jairo Correa's avatar
Jairo Correa committed
557
558
				document.getElementById("autoQueueCheckbox").checked &&
				! app.lastExecutionError
559
			) {
comfyanonymous's avatar
comfyanonymous committed
560
561
				app.queuePrompt(0, this.batchCount);
			}
562
			this.lastQueueSize = status.exec_info.queue_remaining;
comfyanonymous's avatar
comfyanonymous committed
563
		}
pythongosssss's avatar
pythongosssss committed
564
565
	}
}