p101111 commited on
Commit
d494935
·
verified ·
1 Parent(s): 40f2fb0

Upload 13 files

Browse files
custom_nodes/image_size_preset/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2
+
3
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
custom_nodes/image_size_preset/nodes.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Image Size Preset — a robust width/height helper for ComfyUI.
3
+
4
+ Outputs width / height (plus batch size, aspect-ratio label and a human
5
+ readable info string) from a named preset or custom values, with orientation
6
+ control, dimension swapping, scaling and rounding to a model-friendly multiple.
7
+ Wire the outputs to Empty Latent Image or anything that takes width / height.
8
+ """
9
+
10
+ from math import gcd
11
+
12
+ # ── Presets ───────────────────────────────────────────────────────────────────
13
+ # Grouped by common use. The original labels are preserved so existing
14
+ # workflows that reference them keep working.
15
+
16
+ PRESETS = {
17
+ # ── Legacy (kept for backward compatibility) ──────────────────────────
18
+ "9:16 tall (720x1280)": (720, 1280),
19
+ "2:3 tall (832x1248)": (832, 1248),
20
+ "3:4 tall (912x1216)": (912, 1216),
21
+ "4:5 tall (1024x1280)": (1024, 1280),
22
+ "1:1 square (1040x1040)": (1040, 1040),
23
+ "5:4 wide (1280x1024)": (1280, 1024),
24
+ "4:3 wide (1216x912)": (1216, 912),
25
+ "3:2 wide (1248x832)": (1248, 832),
26
+ "16:9 wide (1280x720)": (1280, 720),
27
+ # ── SD 1.5 (512 base) ─────────────────────────────────────────────────
28
+ "SD1.5 · 1:1 (512x512)": (512, 512),
29
+ "SD1.5 · 2:3 portrait (512x768)": (512, 768),
30
+ "SD1.5 · 3:2 landscape (768x512)": (768, 512),
31
+ # ── SDXL (1024 base, ~1MP) ────────────────────────────────────────────
32
+ "SDXL · 1:1 (1024x1024)": (1024, 1024),
33
+ "SDXL · 3:4 portrait (896x1152)": (896, 1152),
34
+ "SDXL · 4:3 landscape (1152x896)": (1152, 896),
35
+ "SDXL · 2:3 portrait (832x1216)": (832, 1216),
36
+ "SDXL · 3:2 landscape (1216x832)": (1216, 832),
37
+ "SDXL · 9:16 portrait (768x1344)": (768, 1344),
38
+ "SDXL · 16:9 landscape (1344x768)": (1344, 768),
39
+ "SDXL · 9:21 portrait (640x1536)": (640, 1536),
40
+ "SDXL · 21:9 landscape (1536x640)": (1536, 640),
41
+ # ── Flux / high-res ───────────────────────────────────────────────────
42
+ "Flux · 1:1 (1024x1024)": (1024, 1024),
43
+ "Flux · 3:4 portrait (1024x1365)": (1024, 1365),
44
+ "Flux · 16:9 landscape (1440x810)": (1440, 810),
45
+ # ── Social media ──────────────────────────────────────────────────────
46
+ "Instagram · 1:1 (1080x1080)": (1080, 1080),
47
+ "Instagram · 4:5 portrait (1080x1350)": (1080, 1350),
48
+ "Story/Reel · 9:16 (1080x1920)": (1080, 1920),
49
+ "YouTube · 16:9 (1920x1080)": (1920, 1080),
50
+ "Twitter/X · 16:9 (1600x900)": (1600, 900),
51
+ # ── Wallpaper ─────────────────────────────────────────────────────────
52
+ "Wallpaper · 1080p (1920x1080)": (1920, 1080),
53
+ "Wallpaper · 1440p (2560x1440)": (2560, 1440),
54
+ "Wallpaper · 4K (3840x2160)": (3840, 2160),
55
+ }
56
+
57
+ _CUSTOM = "Custom (use width/height below)"
58
+
59
+ MIN_DIM = 16
60
+ MAX_DIM = 8192
61
+
62
+
63
+ def _round_to_multiple(value: float, multiple: int) -> int:
64
+ """Round value to the nearest positive multiple (>= multiple)."""
65
+ if multiple <= 1:
66
+ return max(1, int(round(value)))
67
+ return max(multiple, int(round(value / multiple)) * multiple)
68
+
69
+
70
+ def _aspect_ratio(width: int, height: int) -> str:
71
+ g = gcd(width, height) or 1
72
+ return f"{width // g}:{height // g}"
73
+
74
+
75
+ class ImageSizePreset:
76
+ """
77
+ Outputs width / height (and batch size, aspect ratio, info string) from a
78
+ named preset or custom values, with orientation, swap, scale and rounding.
79
+ """
80
+
81
+ @classmethod
82
+ def INPUT_TYPES(cls):
83
+ return {
84
+ "required": {
85
+ "preset": ([_CUSTOM] + list(PRESETS.keys()), {"default": "SDXL · 1:1 (1024x1024)"}),
86
+ "orientation": (["preset", "landscape", "portrait"],),
87
+ "swap_dimensions": ("BOOLEAN", {"default": False}),
88
+ "scale": (
89
+ "FLOAT",
90
+ {"default": 1.0, "min": 0.1, "max": 8.0, "step": 0.05},
91
+ ),
92
+ "round_to": ([8, 1, 16, 32, 64],),
93
+ "batch_size": (
94
+ "INT",
95
+ {"default": 1, "min": 1, "max": 4096, "step": 1},
96
+ ),
97
+ "custom_width": (
98
+ "INT",
99
+ {"default": 1024, "min": MIN_DIM, "max": MAX_DIM, "step": 1},
100
+ ),
101
+ "custom_height": (
102
+ "INT",
103
+ {"default": 1024, "min": MIN_DIM, "max": MAX_DIM, "step": 1},
104
+ ),
105
+ }
106
+ }
107
+
108
+ RETURN_TYPES = ("INT", "INT", "INT", "STRING", "STRING")
109
+ RETURN_NAMES = ("width", "height", "batch_size", "aspect_ratio", "info")
110
+ FUNCTION = "get_size"
111
+ CATEGORY = "utils"
112
+ DESCRIPTION = (
113
+ "Pick a size preset (or Custom), adjust orientation/scale/rounding, "
114
+ "and output width, height, batch size, aspect ratio and an info string."
115
+ )
116
+
117
+ def get_size(
118
+ self,
119
+ preset,
120
+ orientation="preset",
121
+ swap_dimensions=False,
122
+ scale=1.0,
123
+ round_to=8,
124
+ batch_size=1,
125
+ custom_width=1024,
126
+ custom_height=1024,
127
+ ):
128
+ if preset == _CUSTOM:
129
+ width, height = int(custom_width), int(custom_height)
130
+ else:
131
+ # Fall back gracefully if an unknown preset name is supplied.
132
+ width, height = PRESETS.get(preset, (custom_width, custom_height))
133
+
134
+ # Orientation: force the longer/shorter side without changing the pair.
135
+ if orientation == "landscape" and height > width:
136
+ width, height = height, width
137
+ elif orientation == "portrait" and width > height:
138
+ width, height = height, width
139
+
140
+ if swap_dimensions:
141
+ width, height = height, width
142
+
143
+ # Scale then snap to a model-friendly multiple.
144
+ multiple = int(round_to)
145
+ width = _round_to_multiple(width * float(scale), multiple)
146
+ height = _round_to_multiple(height * float(scale), multiple)
147
+
148
+ # Clamp to sane bounds.
149
+ width = max(MIN_DIM, min(MAX_DIM, width))
150
+ height = max(MIN_DIM, min(MAX_DIM, height))
151
+
152
+ batch_size = max(1, int(batch_size))
153
+ ratio = _aspect_ratio(width, height)
154
+ info = f"{width}x{height} ({ratio}) x{batch_size}"
155
+
156
+ return (width, height, batch_size, ratio, info)
157
+
158
+
159
+ NODE_CLASS_MAPPINGS = {
160
+ "ImageSizePreset": ImageSizePreset,
161
+ }
162
+
163
+ NODE_DISPLAY_NAME_MAPPINGS = {
164
+ "ImageSizePreset": "Image Size Preset",
165
+ }
custom_nodes/media_gallery/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/media_gallery/api.py CHANGED
@@ -78,6 +78,93 @@ def _rating_key(filename: str, subfolder: str) -> str:
78
  return f"{subfolder}/{filename}" if subfolder else filename
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  # ── File scan ─────────────────────────────────────────────────────────────────
82
 
83
 
@@ -207,6 +294,32 @@ def setup_routes(routes) -> None:
207
  except Exception as exc: # noqa: BLE001
208
  return web.json_response({"error": str(exc)}, status=500)
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  # ── POST /gallery/download ───────────────────────────────────────────────
211
 
212
  @routes.post("/gallery/download")
 
78
  return f"{subfolder}/{filename}" if subfolder else filename
79
 
80
 
81
+ # ── Prompt metadata extraction ────────────────────────────────────────────────
82
+
83
+
84
+ def _split_a1111(params: str) -> tuple[str, str]:
85
+ """Split an A1111-style parameters string into (positive, negative)."""
86
+ positive, negative = params, ""
87
+ marker = "Negative prompt:"
88
+ if marker in params:
89
+ positive, rest = params.split(marker, 1)
90
+ # Negative text runs until the settings line (starts with "Steps:").
91
+ for stop in ("\nSteps:", "\nSampler:", "\nModel:"):
92
+ if stop in rest:
93
+ rest = rest.split(stop, 1)[0]
94
+ break
95
+ negative = rest.strip()
96
+ return positive.strip(), negative
97
+
98
+
99
+ def _extract_comfy_texts(prompt_json: str) -> list[str]:
100
+ """Best-effort pull of CLIP text-encode strings from a ComfyUI prompt."""
101
+ try:
102
+ data = json.loads(prompt_json)
103
+ except Exception:
104
+ return []
105
+ texts: list[str] = []
106
+ if isinstance(data, dict):
107
+ for node in data.values():
108
+ if not isinstance(node, dict):
109
+ continue
110
+ if "CLIPTextEncode" in str(node.get("class_type", "")):
111
+ value = (node.get("inputs") or {}).get("text")
112
+ if isinstance(value, str) and value.strip():
113
+ if value not in texts:
114
+ texts.append(value.strip())
115
+ return texts
116
+
117
+
118
+ def _read_prompt(full_path: str) -> dict:
119
+ """
120
+ Read the prompt used to create an image from its embedded metadata.
121
+
122
+ Priority: our SaveImageWithPrompt field -> A1111 'parameters' ->
123
+ heuristic extraction from the ComfyUI 'prompt' graph.
124
+ """
125
+ result = {"prompt": "", "negative": "", "source": ""}
126
+ ext = os.path.splitext(full_path)[1].lower()
127
+ if ext not in (".png", ".webp", ".jpg", ".jpeg"):
128
+ return result
129
+
130
+ try:
131
+ from PIL import Image
132
+ except Exception:
133
+ return result
134
+
135
+ try:
136
+ with Image.open(full_path) as im:
137
+ info = dict(getattr(im, "text", {}) or {})
138
+ if not info:
139
+ info = {
140
+ k: v for k, v in (im.info or {}).items() if isinstance(v, str)
141
+ }
142
+ except Exception:
143
+ return result
144
+
145
+ if info.get("generated_prompt"):
146
+ result["prompt"] = info["generated_prompt"]
147
+ result["negative"] = info.get("generated_negative_prompt", "")
148
+ result["source"] = "generated_prompt"
149
+ return result
150
+
151
+ if info.get("parameters"):
152
+ pos, neg = _split_a1111(info["parameters"])
153
+ result["prompt"], result["negative"], result["source"] = (
154
+ pos,
155
+ neg,
156
+ "parameters",
157
+ )
158
+ return result
159
+
160
+ if info.get("prompt"):
161
+ texts = _extract_comfy_texts(info["prompt"])
162
+ if texts:
163
+ result["prompt"] = "\n\n".join(texts)
164
+ result["source"] = "comfyui"
165
+ return result
166
+
167
+
168
  # ── File scan ─────────────────────────────────────────────────────────────────
169
 
170
 
 
294
  except Exception as exc: # noqa: BLE001
295
  return web.json_response({"error": str(exc)}, status=500)
296
 
297
+ # ── GET /gallery/prompt ──────────────────────────────────────────────────
298
+
299
+ @routes.get("/gallery/prompt")
300
+ async def get_prompt(request): # type: ignore[return]
301
+ try:
302
+ filename = str(request.rel_url.query.get("filename", "")).strip()
303
+ subfolder = str(request.rel_url.query.get("subfolder", "")).strip()
304
+ if not filename:
305
+ return web.json_response({"error": "filename required"}, status=400)
306
+
307
+ base = Path(_output_dir()).resolve()
308
+ target = (base / subfolder / filename).resolve()
309
+ base_str = str(base)
310
+ # Security: keep resolved path inside the output directory.
311
+ if not (
312
+ str(target) == base_str
313
+ or str(target).startswith(base_str + os.sep)
314
+ ):
315
+ return web.json_response({"error": "invalid path"}, status=400)
316
+ if not target.is_file():
317
+ return web.json_response({"error": "not found"}, status=404)
318
+
319
+ return web.json_response(_read_prompt(str(target)))
320
+ except Exception as exc: # noqa: BLE001
321
+ return web.json_response({"error": str(exc)}, status=500)
322
+
323
  # ── POST /gallery/download ───────────────────────────────────────────────
324
 
325
  @routes.post("/gallery/download")
custom_nodes/media_gallery/js/gallery.js CHANGED
@@ -282,7 +282,7 @@ class Lightbox {
282
  });
283
  this._dlBtn = $el("a", {
284
  textContent: "⬇ Download",
285
- title: "Download image",
286
  style: {
287
  background: "#2c2c2c",
288
  color: "#bbb",
@@ -329,6 +329,101 @@ class Lightbox {
329
  pointerEvents: "none",
330
  });
331
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
332
  // ── Star rating widget ──────────────────────────────────────────────────
333
  this._lbStars = [];
334
  this._lbStarBar = $el("div", {
@@ -383,11 +478,26 @@ class Lightbox {
383
  this._lbStarBar.addEventListener("mouseleave", () => refreshLbStars());
384
  // ───────────────────────────────────────────────────────────────────────
385
 
386
- // ── Zoom in / out / reset buttons ────────────────────────────────────────
387
  this._zoomInBtn = mkLbBtn("+", "Zoom in (+)", () => this._zoomAt(1.3, null, null));
388
  this._zoomOutBtn = mkLbBtn("−", "Zoom out (−)", () => this._zoomAt(1 / 1.3, null, null));
389
  this._resetZoomBtn = mkLbBtn("⊙ 1×", "Reset zoom (0)", () => this._resetZoom());
390
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
 
392
  const infoBar = $el(
393
  "div",
@@ -409,12 +519,16 @@ class Lightbox {
409
  },
410
  this._nameEl,
411
  this._metaEl,
 
412
  this._lbStarBar,
413
  this._selectBtn,
414
  this._compareBtn,
 
 
415
  this._zoomOutBtn,
416
  this._resetZoomBtn,
417
  this._zoomInBtn,
 
418
  this._dlBtn,
419
  this._deleteBtn,
420
  this._countEl,
@@ -428,30 +542,55 @@ class Lightbox {
428
  this._prevBtn,
429
  this._nextBtn,
430
  infoBar,
 
431
  );
432
  document.body.appendChild(this._overlay);
433
 
434
  document.addEventListener("keydown", (e) => {
435
  if (this._overlay.style.display === "none") return;
436
- // Zoom keys
437
- if (e.key === "+" || e.key === "=") { e.preventDefault(); this._zoomAt(1.3, null, null); return; }
438
- if (e.key === "-") { e.preventDefault(); this._zoomAt(1 / 1.3, null, null); return; }
439
- if (e.key === "0") { e.preventDefault(); this._resetZoom(); return; }
 
 
 
440
  // Nav — skip when panning to avoid conflict
441
  if (!this._isPanning) {
442
  if (e.key === "ArrowLeft" || e.key === "a") this._move(-1);
443
  if (e.key === "ArrowRight" || e.key === "d") this._move(+1);
444
  }
445
  if (e.key === "Escape") this.close();
446
- if (e.key === "s" || e.key === "S" || e.key === " ") {
447
  e.preventDefault();
448
  this._toggleCurrentSelect();
449
  }
 
 
 
 
 
 
 
 
 
 
 
450
  if (e.key === "b" || e.key === "B") this._toggleBg();
 
 
 
 
451
  if (e.key === "c" || e.key === "C") {
452
  e.preventDefault();
453
  this._triggerCompare();
454
  }
 
 
 
 
 
 
455
  if (e.key === "Delete" || e.key === "Backspace") {
456
  e.preventDefault();
457
  this._triggerDelete();
@@ -493,6 +632,83 @@ class Lightbox {
493
  : "Background: transparent — click or press B for solid";
494
  }
495
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496
  open(items, index, selectedCount = 0) {
497
  this._items = items;
498
  this._idx = index;
@@ -502,6 +718,9 @@ class Lightbox {
502
  }
503
 
504
  close() {
 
 
 
505
  this._overlay.style.display = "none";
506
  this._zoomEl.innerHTML = "";
507
  this._isPanning = false;
@@ -518,6 +737,7 @@ class Lightbox {
518
  this._overlay.style.display = "flex";
519
 
520
  const single = this._items.length <= 1;
 
521
  this._prevBtn.style.display = single ? "none" : "block";
522
  this._nextBtn.style.display = single ? "none" : "block";
523
  this._countEl.textContent = `${this._idx + 1} / ${this._items.length}`;
@@ -525,22 +745,49 @@ class Lightbox {
525
  this._metaEl.textContent = `${fmtDate(item.mtime)} • ${fmtBytes(item.size)}`;
526
  this._refreshLbStars();
527
  this._syncSelectBtn();
528
- this._resetZoom(false); // reset zoom without the badge flash on navigation
 
 
 
 
 
 
 
 
 
 
 
 
529
 
530
  const src = viewURL(item.filename, item.subfolder);
531
  this._dlBtn.href = src;
532
  this._dlBtn.download = item.filename;
 
533
 
534
  this._zoomEl.innerHTML = "";
535
- if (item.kind === "video") {
536
- this._zoomEl.appendChild(
537
- $el("video", {
538
- src,
539
- controls: true,
540
- autoplay: true,
541
- style: { maxWidth: "90vw", maxHeight: "80vh", borderRadius: "6px" },
542
- }),
543
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
  } else {
545
  this._zoomEl.appendChild(
546
  $el("img", {
@@ -608,6 +855,38 @@ class Lightbox {
608
  }, 900);
609
  }
610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
611
  // ── Touch utilities ─────────────────────────────────────────────────────────
612
 
613
  _touchDist(touches) {
@@ -712,6 +991,7 @@ class CompareView {
712
  this._stackIdx = 0; // current card index in stack mode
713
  this._onRatingChange = config.onRatingChange;
714
  this._onRemove = config.onRemove;
 
715
  this._build();
716
  }
717
 
@@ -751,6 +1031,26 @@ class CompareView {
751
  this._sbsBtn = mkPill("⧆⧆ Side by Side", "Auto-fit grid layout (T)", () => this._setMode("sidebyside"));
752
  this._stackBtn = mkPill("⧄ Card Stack", "Browse as a stack of cards (T)", () => this._setMode("stacked"));
753
  this._resetZoomBtn = mkPill("⟲ Reset Zoom", "Reset zoom on all images", () => this._resetAllZoom());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754
  this._countLabel = $el("span", {
755
  style: { color: "#555", fontSize: "12px", marginLeft: "8px" },
756
  });
@@ -787,12 +1087,13 @@ class CompareView {
787
  },
788
  },
789
  $el("span", {
790
- textContent: "Compare Images",
791
  style: { color: "#aaa", fontWeight: "600", fontSize: "13px", marginRight: "6px" },
792
  }),
793
  this._sbsBtn,
794
  this._stackBtn,
795
  this._resetZoomBtn,
 
796
  this._countLabel,
797
  closeBtn,
798
  );
@@ -820,6 +1121,11 @@ class CompareView {
820
  this._setMode(this._mode === "sidebyside" ? "stacked" : "sidebyside");
821
  return;
822
  }
 
 
 
 
 
823
  // Arrow navigation in card-stack mode
824
  if (this._mode === "stacked") {
825
  if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
@@ -843,11 +1149,15 @@ class CompareView {
843
  this._items = items;
844
  this._splitRatio = 0.5;
845
  this._stackIdx = 0;
 
846
  this._render();
847
  this._overlay.style.display = "flex";
848
  }
849
 
850
  close() {
 
 
 
851
  this._overlay.style.display = "none";
852
  this._paneArea.innerHTML = "";
853
  this._dragging = false;
@@ -862,6 +1172,30 @@ class CompareView {
862
  }
863
  }
864
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
865
  _removeItem(item) {
866
  this._items = this._items.filter(x => x !== item);
867
  this._onRemove?.(item);
@@ -895,9 +1229,16 @@ class CompareView {
895
  // ── Render ────────────────────────────────────────────────────────────────
896
 
897
  _render() {
 
 
 
898
  this._paneArea.innerHTML = "";
899
  this._updateModeButtons();
900
- this._countLabel.textContent = `${this._items.length} image${this._items.length !== 1 ? "s" : ""}`;
 
 
 
 
901
 
902
  // Reset layout styles to defaults to avoid cross-pollution between views
903
  Object.assign(this._paneArea.style, {
@@ -1378,6 +1719,7 @@ class CompareView {
1378
  src,
1379
  controls: true,
1380
  autoplay: false,
 
1381
  style: {
1382
  width: "100%",
1383
  height: "100%",
@@ -1445,52 +1787,55 @@ class CompareView {
1445
  badgeTimer = setTimeout(() => badge.style.opacity = "0", 900);
1446
  };
1447
 
1448
- // Wheel zoom
1449
- zoomEl.addEventListener("wheel", (e) => {
1450
- if (!e.ctrlKey) return;
1451
- e.preventDefault();
1452
- const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
1453
- const rect = zoomEl.getBoundingClientRect();
1454
- const ox = e.clientX - (rect.left + rect.width / 2);
1455
- const oy = e.clientY - (rect.top + rect.height / 2);
1456
- const newZoom = Math.max(0.5, Math.min(12, zoom * factor));
1457
- const ratio = newZoom / zoom;
1458
- panX = ox + (panX - ox) * ratio;
1459
- panY = oy + (panY - oy) * ratio;
1460
- zoom = newZoom;
1461
- applyT();
1462
- showBadge();
1463
- }, { passive: false });
 
 
1464
 
1465
- // Double-click reset
1466
- zoomEl.addEventListener("dblclick", () => {
1467
- zoom = 1; panX = 0; panY = 0; applyT(); showBadge();
1468
- });
1469
 
1470
- // Mouse pan
1471
- zoomEl.addEventListener("mousedown", (e) => {
1472
- if (e.button !== 0 || zoom <= 1) return;
1473
- e.preventDefault();
1474
- e.stopPropagation(); // don't start splitter drag
1475
- panning = true;
1476
- panStart = { x: e.clientX, y: e.clientY, panX, panY };
1477
- media.style.cursor = "grabbing";
1478
- });
1479
- window.addEventListener("mousemove", (e) => {
1480
- if (!panning) return;
1481
- panX = panStart.panX + (e.clientX - panStart.x);
1482
- panY = panStart.panY + (e.clientY - panStart.y);
1483
- applyT();
1484
- });
1485
- window.addEventListener("mouseup", () => {
1486
- if (!panning) return;
1487
- panning = false;
1488
- media.style.cursor = zoom > 1 ? "grab" : "default";
1489
- });
1490
 
1491
- media.style.transformOrigin = "center center";
1492
- media.style.willChange = "transform";
1493
- media.style.transition = "none";
 
1494
 
1495
  zoomEl.append(media, badge);
1496
 
@@ -2043,12 +2388,12 @@ class GalleryPanel {
2043
  },
2044
  },
2045
  $el("div", {
2046
- textContent: "🖼",
2047
- style: { fontSize: "36px", marginBottom: "10px" },
2048
  }),
2049
  $el("div", { textContent: "No media in the output folder yet." }),
2050
  $el("div", {
2051
- textContent: "Run a workflow to see images here.",
2052
  style: { color: "#333", marginTop: "4px", fontSize: "12px" },
2053
  }),
2054
  );
@@ -2207,7 +2552,7 @@ class GalleryPanel {
2207
  this._deleteBtn.disabled = n === 0;
2208
  this._deleteBtn.style.opacity = n === 0 ? "0.4" : "1";
2209
  this._deleteBtn.style.cursor = n === 0 ? "default" : "pointer";
2210
- // Compare needs at least 2 images selected
2211
  const canCompare = n >= 2;
2212
  this._compareBtn.disabled = !canCompare;
2213
  this._compareBtn.style.opacity = canCompare ? "1" : "0.35";
@@ -2518,16 +2863,18 @@ class GalleryPanel {
2518
  ratingBar,
2519
  );
2520
 
2521
- // Hover scale (normal mode only)
2522
- media.addEventListener("mouseenter", () => {
2523
- if (this._selectMode) return;
2524
- media.style.transform = "scale(1.06)";
2525
- media.style.opacity = "0.85";
2526
- });
2527
- media.addEventListener("mouseleave", () => {
2528
- media.style.transform = "scale(1)";
2529
- media.style.opacity = "1";
2530
- });
 
 
2531
 
2532
  // If already in select mode, show checkbox immediately
2533
  if (this._selectMode)
@@ -2547,6 +2894,7 @@ class GalleryPanel {
2547
  src,
2548
  preload: "metadata",
2549
  muted: true,
 
2550
  style: {
2551
  width: "100%",
2552
  height: "100%",
@@ -2554,6 +2902,17 @@ class GalleryPanel {
2554
  display: "block",
2555
  },
2556
  });
 
 
 
 
 
 
 
 
 
 
 
2557
  const playOverlay = $el(
2558
  "div",
2559
  {
@@ -2564,15 +2923,57 @@ class GalleryPanel {
2564
  alignItems: "center",
2565
  justifyContent: "center",
2566
  background: "rgba(0,0,0,0.38)",
 
2567
  pointerEvents: "none",
2568
  },
2569
  },
2570
- $el("span", {
2571
- textContent: "▶",
2572
- style: { color: "rgba(255,255,255,0.85)", fontSize: "20px" },
2573
- }),
2574
  );
2575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2576
  const wrap = $el(
2577
  "div",
2578
  {
@@ -2584,18 +2985,16 @@ class GalleryPanel {
2584
  },
2585
  vid,
2586
  playOverlay,
 
2587
  );
2588
- wrap.addEventListener(
2589
- "mouseenter",
2590
- () => (playOverlay.style.background = "rgba(0,0,0,0.15)"),
2591
- );
2592
- wrap.addEventListener(
2593
- "mouseleave",
2594
- () => (playOverlay.style.background = "rgba(0,0,0,0.38)"),
2595
- );
2596
  return wrap;
2597
  }
2598
 
 
2599
  return $el("img", {
2600
  src,
2601
  loading: "lazy",
 
282
  });
283
  this._dlBtn = $el("a", {
284
  textContent: "⬇ Download",
285
+ title: "Download file",
286
  style: {
287
  background: "#2c2c2c",
288
  color: "#bbb",
 
329
  pointerEvents: "none",
330
  });
331
 
332
+ this._promptBtn = mkLbBtn("📋 Prompt", "Show / copy the prompt used (P)", () => this._togglePrompt());
333
+
334
+ // ── Prompt panel (slides in from the right, holds the embedded prompt) ──
335
+ this._promptText = $el("textarea", {
336
+ readOnly: true,
337
+ style: {
338
+ flex: "1",
339
+ width: "100%",
340
+ boxSizing: "border-box",
341
+ background: "#161616",
342
+ color: "#ddd",
343
+ border: "1px solid #333",
344
+ borderRadius: "6px",
345
+ padding: "8px",
346
+ fontSize: "12px",
347
+ lineHeight: "1.45",
348
+ resize: "none",
349
+ fontFamily: "monospace",
350
+ whiteSpace: "pre-wrap",
351
+ },
352
+ });
353
+ this._promptNeg = $el("textarea", {
354
+ readOnly: true,
355
+ style: {
356
+ width: "100%",
357
+ boxSizing: "border-box",
358
+ background: "#161616",
359
+ color: "#c98",
360
+ border: "1px solid #333",
361
+ borderRadius: "6px",
362
+ padding: "8px",
363
+ fontSize: "12px",
364
+ lineHeight: "1.45",
365
+ resize: "none",
366
+ fontFamily: "monospace",
367
+ whiteSpace: "pre-wrap",
368
+ height: "80px",
369
+ display: "none",
370
+ },
371
+ });
372
+ this._promptNegLabel = $el("div", {
373
+ textContent: "Negative",
374
+ style: { color: "#888", fontSize: "11px", margin: "4px 0 2px", display: "none" },
375
+ });
376
+ this._promptSource = $el("div", {
377
+ style: { color: "#666", fontSize: "11px", marginTop: "6px" },
378
+ });
379
+ this._promptCopyBtn = mkLbBtn("⧉ Copy", "Copy prompt to clipboard", () => this._copyPrompt());
380
+ const promptClose = mkLbBtn("✕", "Close prompt panel (P)", () => this._togglePrompt(false));
381
+ this._promptPanel = $el(
382
+ "div",
383
+ {
384
+ style: {
385
+ position: "absolute",
386
+ top: "0",
387
+ right: "0",
388
+ width: "min(420px, 80vw)",
389
+ height: "100%",
390
+ boxSizing: "border-box",
391
+ background: "rgba(18,18,18,0.96)",
392
+ borderLeft: "1px solid #333",
393
+ backdropFilter: "blur(6px)",
394
+ padding: "48px 14px 70px",
395
+ display: "none",
396
+ flexDirection: "column",
397
+ gap: "6px",
398
+ zIndex: "5",
399
+ },
400
+ onclick: (e) => e.stopPropagation(),
401
+ },
402
+ $el(
403
+ "div",
404
+ {
405
+ style: {
406
+ display: "flex",
407
+ alignItems: "center",
408
+ gap: "8px",
409
+ marginBottom: "4px",
410
+ },
411
+ },
412
+ $el("span", {
413
+ textContent: "Prompt",
414
+ style: { color: "#eee", fontWeight: "bold", flex: "1" },
415
+ }),
416
+ this._promptCopyBtn,
417
+ promptClose,
418
+ ),
419
+ this._promptText,
420
+ this._promptNegLabel,
421
+ this._promptNeg,
422
+ this._promptSource,
423
+ );
424
+ this._promptCache = new Map();
425
+ this._promptOpen = false;
426
+
427
  // ── Star rating widget ──────────────────────────────────────────────────
428
  this._lbStars = [];
429
  this._lbStarBar = $el("div", {
 
478
  this._lbStarBar.addEventListener("mouseleave", () => refreshLbStars());
479
  // ───────────────────────────────────────────────────────────────────────
480
 
481
+ // ── Zoom in / out / reset buttons (hidden for video) ────────────────────
482
  this._zoomInBtn = mkLbBtn("+", "Zoom in (+)", () => this._zoomAt(1.3, null, null));
483
  this._zoomOutBtn = mkLbBtn("−", "Zoom out (−)", () => this._zoomAt(1 / 1.3, null, null));
484
  this._resetZoomBtn = mkLbBtn("⊙ 1×", "Reset zoom (0)", () => this._resetZoom());
485
 
486
+ // ── Video-specific controls ──────────────────────────────────────────────
487
+ this._muteBtn = mkLbBtn("🔊", "Toggle mute (M)", () => this._toggleMute());
488
+ this._loopBtn = mkLbBtn("↺ Loop", "Toggle loop (L)", () => this._toggleLoop());
489
+ this._vidDuration = $el("span", {
490
+ style: {
491
+ color: "#888",
492
+ fontSize: "12px",
493
+ flexShrink: "0",
494
+ fontVariantNumeric: "tabular-nums",
495
+ whiteSpace: "nowrap",
496
+ },
497
+ });
498
+ this._isMuted = false;
499
+ this._isLooped = false;
500
+
501
 
502
  const infoBar = $el(
503
  "div",
 
519
  },
520
  this._nameEl,
521
  this._metaEl,
522
+ this._vidDuration,
523
  this._lbStarBar,
524
  this._selectBtn,
525
  this._compareBtn,
526
+ this._muteBtn,
527
+ this._loopBtn,
528
  this._zoomOutBtn,
529
  this._resetZoomBtn,
530
  this._zoomInBtn,
531
+ this._promptBtn,
532
  this._dlBtn,
533
  this._deleteBtn,
534
  this._countEl,
 
542
  this._prevBtn,
543
  this._nextBtn,
544
  infoBar,
545
+ this._promptPanel,
546
  );
547
  document.body.appendChild(this._overlay);
548
 
549
  document.addEventListener("keydown", (e) => {
550
  if (this._overlay.style.display === "none") return;
551
+ const isVideo = this._items[this._idx]?.kind === "video";
552
+ // Zoom keys (image only)
553
+ if (!isVideo) {
554
+ if (e.key === "+" || e.key === "=") { e.preventDefault(); this._zoomAt(1.3, null, null); return; }
555
+ if (e.key === "-") { e.preventDefault(); this._zoomAt(1 / 1.3, null, null); return; }
556
+ if (e.key === "0") { e.preventDefault(); this._resetZoom(); return; }
557
+ }
558
  // Nav — skip when panning to avoid conflict
559
  if (!this._isPanning) {
560
  if (e.key === "ArrowLeft" || e.key === "a") this._move(-1);
561
  if (e.key === "ArrowRight" || e.key === "d") this._move(+1);
562
  }
563
  if (e.key === "Escape") this.close();
564
+ if (e.key === "s" || e.key === "S") {
565
  e.preventDefault();
566
  this._toggleCurrentSelect();
567
  }
568
+ // Space: select for images, play/pause for videos
569
+ if (e.key === " ") {
570
+ if (isVideo) {
571
+ e.preventDefault();
572
+ const vid = this._zoomEl.querySelector("video");
573
+ if (vid) { vid.paused ? vid.play() : vid.pause(); }
574
+ } else {
575
+ e.preventDefault();
576
+ this._toggleCurrentSelect();
577
+ }
578
+ }
579
  if (e.key === "b" || e.key === "B") this._toggleBg();
580
+ if (e.key === "p" || e.key === "P") {
581
+ e.preventDefault();
582
+ this._togglePrompt();
583
+ }
584
  if (e.key === "c" || e.key === "C") {
585
  e.preventDefault();
586
  this._triggerCompare();
587
  }
588
+ if (e.key === "m" || e.key === "M") {
589
+ if (isVideo) { e.preventDefault(); this._toggleMute(); }
590
+ }
591
+ if (e.key === "l" || e.key === "L") {
592
+ if (isVideo) { e.preventDefault(); this._toggleLoop(); }
593
+ }
594
  if (e.key === "Delete" || e.key === "Backspace") {
595
  e.preventDefault();
596
  this._triggerDelete();
 
632
  : "Background: transparent — click or press B for solid";
633
  }
634
 
635
+ // ── Prompt panel ──────────────────────────────────────────────────────────
636
+
637
+ _togglePrompt(force) {
638
+ this._promptOpen = force === undefined ? !this._promptOpen : force;
639
+ this._promptPanel.style.display = this._promptOpen ? "flex" : "none";
640
+ this._promptBtn.style.background = this._promptOpen ? "#0e2a4a" : "#2c2c2c";
641
+ this._promptBtn.style.color = this._promptOpen ? "#5b9bd5" : "#bbb";
642
+ this._promptBtn.style.borderColor = this._promptOpen ? "#1a4a7a" : "#444";
643
+ if (this._promptOpen) this._loadPrompt(this._items[this._idx]);
644
+ }
645
+
646
+ async _loadPrompt(item) {
647
+ if (!item) return;
648
+ const key = fileKey(item);
649
+ this._promptText.value = "Loading…";
650
+ this._promptNeg.style.display = "none";
651
+ this._promptNegLabel.style.display = "none";
652
+ this._promptSource.textContent = "";
653
+
654
+ let data = this._promptCache.get(key);
655
+ if (!data) {
656
+ if (item.kind === "video") {
657
+ data = { prompt: "", negative: "", source: "" };
658
+ } else {
659
+ try {
660
+ const qs = new URLSearchParams({
661
+ filename: item.filename,
662
+ subfolder: item.subfolder || "",
663
+ });
664
+ const res = await api.fetchApi(`/gallery/prompt?${qs}`);
665
+ data = await res.json();
666
+ } catch (err) {
667
+ console.error("[Gallery] prompt fetch failed", err);
668
+ data = { prompt: "", negative: "", source: "" };
669
+ }
670
+ }
671
+ this._promptCache.set(key, data);
672
+ }
673
+
674
+ // Ignore late responses if the user already navigated away.
675
+ if (fileKey(this._items[this._idx]) !== key) return;
676
+
677
+ if (data.prompt) {
678
+ this._promptText.value = data.prompt;
679
+ this._promptCopyBtn.style.display = "";
680
+ if (data.negative) {
681
+ this._promptNeg.value = data.negative;
682
+ this._promptNeg.style.display = "";
683
+ this._promptNegLabel.style.display = "";
684
+ }
685
+ const labels = {
686
+ generated_prompt: "from embedded prompt (Save Image with prompt)",
687
+ parameters: "from A1111 parameters",
688
+ comfyui: "extracted from workflow (best-effort)",
689
+ };
690
+ this._promptSource.textContent = labels[data.source] || "";
691
+ } else {
692
+ this._promptText.value = "No prompt found in this image's metadata.";
693
+ this._promptCopyBtn.style.display = "none";
694
+ }
695
+ }
696
+
697
+ async _copyPrompt() {
698
+ const text = this._promptText.value || "";
699
+ try {
700
+ await navigator.clipboard.writeText(text);
701
+ } catch {
702
+ // Fallback for insecure contexts / older browsers.
703
+ this._promptText.select();
704
+ document.execCommand("copy");
705
+ }
706
+ const btn = this._promptCopyBtn;
707
+ const orig = btn.textContent;
708
+ btn.textContent = "✓ Copied";
709
+ setTimeout(() => (btn.textContent = orig), 1200);
710
+ }
711
+
712
  open(items, index, selectedCount = 0) {
713
  this._items = items;
714
  this._idx = index;
 
718
  }
719
 
720
  close() {
721
+ // Pause any playing video before clearing
722
+ const vid = this._zoomEl.querySelector("video");
723
+ if (vid) { vid.pause(); vid.src = ""; }
724
  this._overlay.style.display = "none";
725
  this._zoomEl.innerHTML = "";
726
  this._isPanning = false;
 
737
  this._overlay.style.display = "flex";
738
 
739
  const single = this._items.length <= 1;
740
+ const isVideo = item.kind === "video";
741
  this._prevBtn.style.display = single ? "none" : "block";
742
  this._nextBtn.style.display = single ? "none" : "block";
743
  this._countEl.textContent = `${this._idx + 1} / ${this._items.length}`;
 
745
  this._metaEl.textContent = `${fmtDate(item.mtime)} • ${fmtBytes(item.size)}`;
746
  this._refreshLbStars();
747
  this._syncSelectBtn();
748
+ if (this._promptOpen) this._loadPrompt(item);
749
+
750
+ // Show/hide controls based on media type
751
+ const zoomDisplay = isVideo ? "none" : "";
752
+ this._zoomInBtn.style.display = zoomDisplay;
753
+ this._zoomOutBtn.style.display = zoomDisplay;
754
+ this._resetZoomBtn.style.display = zoomDisplay;
755
+ this._muteBtn.style.display = isVideo ? "" : "none";
756
+ this._loopBtn.style.display = isVideo ? "" : "none";
757
+ this._vidDuration.style.display = isVideo ? "" : "none";
758
+ this._vidDuration.textContent = "";
759
+
760
+ if (!isVideo) this._resetZoom(false); // reset zoom without the badge flash on navigation
761
 
762
  const src = viewURL(item.filename, item.subfolder);
763
  this._dlBtn.href = src;
764
  this._dlBtn.download = item.filename;
765
+ this._dlBtn.title = isVideo ? "Download video" : "Download image";
766
 
767
  this._zoomEl.innerHTML = "";
768
+ if (isVideo) {
769
+ // Stop any previously playing video
770
+ const vid = $el("video", {
771
+ src,
772
+ controls: true,
773
+ autoplay: true,
774
+ muted: this._isMuted,
775
+ loop: this._isLooped,
776
+ style: { maxWidth: "90vw", maxHeight: "80vh", borderRadius: "6px" },
777
+ });
778
+ // Sync mute/loop button states
779
+ this._syncMuteBtn();
780
+ this._syncLoopBtn();
781
+ // Update duration display when metadata loads
782
+ vid.addEventListener("loadedmetadata", () => {
783
+ const d = vid.duration;
784
+ if (isFinite(d)) {
785
+ const m = Math.floor(d / 60);
786
+ const s = Math.floor(d % 60).toString().padStart(2, "0");
787
+ this._vidDuration.textContent = `${m}:${s}`;
788
+ }
789
+ });
790
+ this._zoomEl.appendChild(vid);
791
  } else {
792
  this._zoomEl.appendChild(
793
  $el("img", {
 
855
  }, 900);
856
  }
857
 
858
+ // ── Video control helpers ────────────────────────────────────────────────
859
+
860
+ _toggleMute() {
861
+ this._isMuted = !this._isMuted;
862
+ const vid = this._zoomEl.querySelector("video");
863
+ if (vid) vid.muted = this._isMuted;
864
+ this._syncMuteBtn();
865
+ }
866
+
867
+ _toggleLoop() {
868
+ this._isLooped = !this._isLooped;
869
+ const vid = this._zoomEl.querySelector("video");
870
+ if (vid) vid.loop = this._isLooped;
871
+ this._syncLoopBtn();
872
+ }
873
+
874
+ _syncMuteBtn() {
875
+ this._muteBtn.textContent = this._isMuted ? "🔇" : "🔊";
876
+ this._muteBtn.title = this._isMuted ? "Unmute (M)" : "Mute (M)";
877
+ this._muteBtn.style.background = this._isMuted ? "#2d2200" : "#2c2c2c";
878
+ this._muteBtn.style.color = this._isMuted ? "#f1c40f" : "#bbb";
879
+ this._muteBtn.style.borderColor = this._isMuted ? "#6a5200" : "#444";
880
+ }
881
+
882
+ _syncLoopBtn() {
883
+ this._loopBtn.textContent = this._isLooped ? "↺ Looping" : "↺ Loop";
884
+ this._loopBtn.title = this._isLooped ? "Loop on — click to disable (L)" : "Loop off — click to enable (L)";
885
+ this._loopBtn.style.background = this._isLooped ? "#0e2a4a" : "#2c2c2c";
886
+ this._loopBtn.style.color = this._isLooped ? "#5b9bd5" : "#bbb";
887
+ this._loopBtn.style.borderColor = this._isLooped ? "#1a4a7a" : "#444";
888
+ }
889
+
890
  // ── Touch utilities ─────────────────────────────────────────────────────────
891
 
892
  _touchDist(touches) {
 
991
  this._stackIdx = 0; // current card index in stack mode
992
  this._onRatingChange = config.onRatingChange;
993
  this._onRemove = config.onRemove;
994
+ this._allPlaying = false; // shared play/pause state for all videos
995
  this._build();
996
  }
997
 
 
1031
  this._sbsBtn = mkPill("⧆⧆ Side by Side", "Auto-fit grid layout (T)", () => this._setMode("sidebyside"));
1032
  this._stackBtn = mkPill("⧄ Card Stack", "Browse as a stack of cards (T)", () => this._setMode("stacked"));
1033
  this._resetZoomBtn = mkPill("⟲ Reset Zoom", "Reset zoom on all images", () => this._resetAllZoom());
1034
+
1035
+ // Play/Pause All — only shown when there are videos in the comparison
1036
+ this._playAllBtn = $el("button", {
1037
+ textContent: "▶ Play All",
1038
+ title: "Play / pause all videos simultaneously (Space)",
1039
+ onclick: (e) => { e.stopPropagation(); this._togglePlayAll(); },
1040
+ style: {
1041
+ display: "none",
1042
+ background: "rgba(14,42,74,0.9)",
1043
+ color: "#5b9bd5",
1044
+ border: "1px solid #1a4a7a",
1045
+ borderRadius: "20px",
1046
+ padding: "4px 13px",
1047
+ fontSize: "12px",
1048
+ cursor: "pointer",
1049
+ transition: "background 0.15s, color 0.15s, border-color 0.15s",
1050
+ whiteSpace: "nowrap",
1051
+ },
1052
+ });
1053
+
1054
  this._countLabel = $el("span", {
1055
  style: { color: "#555", fontSize: "12px", marginLeft: "8px" },
1056
  });
 
1087
  },
1088
  },
1089
  $el("span", {
1090
+ textContent: "Compare Media",
1091
  style: { color: "#aaa", fontWeight: "600", fontSize: "13px", marginRight: "6px" },
1092
  }),
1093
  this._sbsBtn,
1094
  this._stackBtn,
1095
  this._resetZoomBtn,
1096
+ this._playAllBtn,
1097
  this._countLabel,
1098
  closeBtn,
1099
  );
 
1121
  this._setMode(this._mode === "sidebyside" ? "stacked" : "sidebyside");
1122
  return;
1123
  }
1124
+ // Space: play/pause all videos
1125
+ if (e.key === " ") {
1126
+ const hasVid = this._items.some(i => i.kind === "video");
1127
+ if (hasVid) { e.preventDefault(); this._togglePlayAll(); return; }
1128
+ }
1129
  // Arrow navigation in card-stack mode
1130
  if (this._mode === "stacked") {
1131
  if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
 
1149
  this._items = items;
1150
  this._splitRatio = 0.5;
1151
  this._stackIdx = 0;
1152
+ this._allPlaying = false; // reset play state whenever a new comparison opens
1153
  this._render();
1154
  this._overlay.style.display = "flex";
1155
  }
1156
 
1157
  close() {
1158
+ // Pause any playing videos before clearing
1159
+ this._paneArea.querySelectorAll("video").forEach(v => { v.pause(); v.src = ""; });
1160
+ this._allPlaying = false;
1161
  this._overlay.style.display = "none";
1162
  this._paneArea.innerHTML = "";
1163
  this._dragging = false;
 
1172
  }
1173
  }
1174
 
1175
+ /** Toggle play/pause on every <video> currently in the pane area. */
1176
+ _togglePlayAll() {
1177
+ this._allPlaying = !this._allPlaying;
1178
+ const videos = Array.from(this._paneArea.querySelectorAll("video"));
1179
+ videos.forEach(v => {
1180
+ if (this._allPlaying) {
1181
+ v.play().catch(() => {});
1182
+ } else {
1183
+ v.pause();
1184
+ }
1185
+ });
1186
+ this._syncPlayAllBtn();
1187
+ }
1188
+
1189
+ /** Sync the Play All button label and style to current state. */
1190
+ _syncPlayAllBtn() {
1191
+ const hasVid = this._items.some(i => i.kind === "video");
1192
+ this._playAllBtn.style.display = hasVid ? "" : "none";
1193
+ this._playAllBtn.textContent = this._allPlaying ? "⏸ Pause All" : "▶ Play All";
1194
+ this._playAllBtn.style.background = this._allPlaying ? "rgba(14,42,74,0.9)" : "rgba(50,50,50,0.85)";
1195
+ this._playAllBtn.style.color = this._allPlaying ? "#5b9bd5" : "#ccc";
1196
+ this._playAllBtn.style.borderColor = this._allPlaying ? "#1a4a7a" : "#444";
1197
+ }
1198
+
1199
  _removeItem(item) {
1200
  this._items = this._items.filter(x => x !== item);
1201
  this._onRemove?.(item);
 
1229
  // ── Render ────────────────────────────────────────────────────────────────
1230
 
1231
  _render() {
1232
+ // Pause all playing videos before clearing
1233
+ this._paneArea.querySelectorAll("video").forEach(v => { v.pause(); v.src = ""; });
1234
+ this._allPlaying = false;
1235
  this._paneArea.innerHTML = "";
1236
  this._updateModeButtons();
1237
+ this._syncPlayAllBtn();
1238
+ const hasVideos = this._items.some(i => i.kind === "video");
1239
+ const hasImages = this._items.some(i => i.kind === "image");
1240
+ const label = hasVideos && hasImages ? "items" : hasVideos ? "video" + (this._items.length !== 1 ? "s" : "") : "image" + (this._items.length !== 1 ? "s" : "");
1241
+ this._countLabel.textContent = `${this._items.length} ${label}`;
1242
 
1243
  // Reset layout styles to defaults to avoid cross-pollution between views
1244
  Object.assign(this._paneArea.style, {
 
1719
  src,
1720
  controls: true,
1721
  autoplay: false,
1722
+ muted: true,
1723
  style: {
1724
  width: "100%",
1725
  height: "100%",
 
1787
  badgeTimer = setTimeout(() => badge.style.opacity = "0", 900);
1788
  };
1789
 
1790
+ // Zoom/pan only applies to images in compare view
1791
+ if (item.kind !== "video") {
1792
+ // Wheel zoom
1793
+ zoomEl.addEventListener("wheel", (e) => {
1794
+ if (!e.ctrlKey) return;
1795
+ e.preventDefault();
1796
+ const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
1797
+ const rect = zoomEl.getBoundingClientRect();
1798
+ const ox = e.clientX - (rect.left + rect.width / 2);
1799
+ const oy = e.clientY - (rect.top + rect.height / 2);
1800
+ const newZoom = Math.max(0.5, Math.min(12, zoom * factor));
1801
+ const ratio = newZoom / zoom;
1802
+ panX = ox + (panX - ox) * ratio;
1803
+ panY = oy + (panY - oy) * ratio;
1804
+ zoom = newZoom;
1805
+ applyT();
1806
+ showBadge();
1807
+ }, { passive: false });
1808
 
1809
+ // Double-click reset
1810
+ zoomEl.addEventListener("dblclick", () => {
1811
+ zoom = 1; panX = 0; panY = 0; applyT(); showBadge();
1812
+ });
1813
 
1814
+ // Mouse pan
1815
+ zoomEl.addEventListener("mousedown", (e) => {
1816
+ if (e.button !== 0 || zoom <= 1) return;
1817
+ e.preventDefault();
1818
+ e.stopPropagation(); // don't start splitter drag
1819
+ panning = true;
1820
+ panStart = { x: e.clientX, y: e.clientY, panX, panY };
1821
+ media.style.cursor = "grabbing";
1822
+ });
1823
+ window.addEventListener("mousemove", (e) => {
1824
+ if (!panning) return;
1825
+ panX = panStart.panX + (e.clientX - panStart.x);
1826
+ panY = panStart.panY + (e.clientY - panStart.y);
1827
+ applyT();
1828
+ });
1829
+ window.addEventListener("mouseup", () => {
1830
+ if (!panning) return;
1831
+ panning = false;
1832
+ media.style.cursor = zoom > 1 ? "grab" : "default";
1833
+ });
1834
 
1835
+ media.style.transformOrigin = "center center";
1836
+ media.style.willChange = "transform";
1837
+ media.style.transition = "none";
1838
+ }
1839
 
1840
  zoomEl.append(media, badge);
1841
 
 
2388
  },
2389
  },
2390
  $el("div", {
2391
+ textContent: "🖼 🎬",
2392
+ style: { fontSize: "30px", marginBottom: "10px", letterSpacing: "4px" },
2393
  }),
2394
  $el("div", { textContent: "No media in the output folder yet." }),
2395
  $el("div", {
2396
+ textContent: "Run a workflow to see images or videos here.",
2397
  style: { color: "#333", marginTop: "4px", fontSize: "12px" },
2398
  }),
2399
  );
 
2552
  this._deleteBtn.disabled = n === 0;
2553
  this._deleteBtn.style.opacity = n === 0 ? "0.4" : "1";
2554
  this._deleteBtn.style.cursor = n === 0 ? "default" : "pointer";
2555
+ // Compare needs at least 2 items selected
2556
  const canCompare = n >= 2;
2557
  this._compareBtn.disabled = !canCompare;
2558
  this._compareBtn.style.opacity = canCompare ? "1" : "0.35";
 
2863
  ratingBar,
2864
  );
2865
 
2866
+ // Hover scale (images only, normal mode only — videos handle their own hover)
2867
+ if (file.kind !== "video") {
2868
+ media.addEventListener("mouseenter", () => {
2869
+ if (this._selectMode) return;
2870
+ media.style.transform = "scale(1.06)";
2871
+ media.style.opacity = "0.85";
2872
+ });
2873
+ media.addEventListener("mouseleave", () => {
2874
+ media.style.transform = "scale(1)";
2875
+ media.style.opacity = "1";
2876
+ });
2877
+ }
2878
 
2879
  // If already in select mode, show checkbox immediately
2880
  if (this._selectMode)
 
2894
  src,
2895
  preload: "metadata",
2896
  muted: true,
2897
+ loop: true,
2898
  style: {
2899
  width: "100%",
2900
  height: "100%",
 
2902
  display: "block",
2903
  },
2904
  });
2905
+
2906
+ // Play-button overlay (fades out while playing)
2907
+ const playIcon = $el("span", {
2908
+ textContent: "▶",
2909
+ style: {
2910
+ color: "rgba(255,255,255,0.85)",
2911
+ fontSize: "20px",
2912
+ transition: "opacity 0.2s",
2913
+ pointerEvents: "none",
2914
+ },
2915
+ });
2916
  const playOverlay = $el(
2917
  "div",
2918
  {
 
2923
  alignItems: "center",
2924
  justifyContent: "center",
2925
  background: "rgba(0,0,0,0.38)",
2926
+ transition: "background 0.2s",
2927
  pointerEvents: "none",
2928
  },
2929
  },
2930
+ playIcon,
 
 
 
2931
  );
2932
 
2933
+ // Thin progress bar at the bottom
2934
+ const progressBar = $el("div", {
2935
+ style: {
2936
+ position: "absolute",
2937
+ bottom: "0",
2938
+ left: "0",
2939
+ height: "3px",
2940
+ width: "0%",
2941
+ background: "rgba(91,155,213,0.9)",
2942
+ transition: "none",
2943
+ pointerEvents: "none",
2944
+ zIndex: "4",
2945
+ opacity: "0",
2946
+ },
2947
+ });
2948
+
2949
+ // Update progress bar every animation frame while playing
2950
+ let rafId = null;
2951
+ const tickProgress = () => {
2952
+ if (vid.duration > 0) {
2953
+ progressBar.style.width = (vid.currentTime / vid.duration * 100) + "%";
2954
+ }
2955
+ rafId = requestAnimationFrame(tickProgress);
2956
+ };
2957
+
2958
+ const startPlay = () => {
2959
+ vid.currentTime = 0;
2960
+ vid.play().catch(() => {});
2961
+ playOverlay.style.background = "rgba(0,0,0,0)";
2962
+ playIcon.style.opacity = "0";
2963
+ progressBar.style.opacity = "1";
2964
+ rafId = requestAnimationFrame(tickProgress);
2965
+ };
2966
+
2967
+ const stopPlay = () => {
2968
+ vid.pause();
2969
+ vid.currentTime = 0;
2970
+ playOverlay.style.background = "rgba(0,0,0,0.38)";
2971
+ playIcon.style.opacity = "1";
2972
+ progressBar.style.opacity = "0";
2973
+ progressBar.style.width = "0%";
2974
+ if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; }
2975
+ };
2976
+
2977
  const wrap = $el(
2978
  "div",
2979
  {
 
2985
  },
2986
  vid,
2987
  playOverlay,
2988
+ progressBar,
2989
  );
2990
+
2991
+ wrap.addEventListener("mouseenter", () => startPlay());
2992
+ wrap.addEventListener("mouseleave", () => stopPlay());
2993
+
 
 
 
 
2994
  return wrap;
2995
  }
2996
 
2997
+
2998
  return $el("img", {
2999
  src,
3000
  loading: "lazy",
custom_nodes/openai_prompt/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/openai_prompt/js/preview.js CHANGED
@@ -194,6 +194,60 @@ app.registerExtension({
194
  }
195
  }
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  const onNodeCreated = nodeType.prototype.onNodeCreated;
198
  nodeType.prototype.onNodeCreated = function () {
199
  onNodeCreated?.apply(this, arguments);
@@ -201,12 +255,14 @@ app.registerExtension({
201
  this.addWidget("button", "Reload from config", null, () =>
202
  reloadFromConfig.call(this),
203
  );
 
204
  };
205
 
206
  const onConfigure = nodeType.prototype.onConfigure;
207
  nodeType.prototype.onConfigure = function () {
208
  onConfigure?.apply(this, arguments);
209
  maskWidget.call(this);
 
210
  };
211
  },
212
  });
 
194
  }
195
  }
196
 
197
+ // Generation-only fields: greyed out and non-editable when generation is
198
+ // disabled, so the node reads as a clear on/off switch.
199
+ const GEN_FIELDS = [
200
+ "config_file",
201
+ "use_config",
202
+ "base_url",
203
+ "api_key",
204
+ "model",
205
+ "system_prompt",
206
+ "instruction",
207
+ "structured_output",
208
+ "count",
209
+ "temperature",
210
+ "max_tokens",
211
+ "seed",
212
+ ];
213
+
214
+ function setWidgetDisabled(w, disabled) {
215
+ if (!w) return;
216
+ w.disabled = disabled;
217
+ if (w.inputEl) {
218
+ w.inputEl.disabled = disabled;
219
+ w.inputEl.style.opacity = disabled ? "0.4" : "";
220
+ }
221
+ }
222
+
223
+ function applyEnabledState() {
224
+ const en = this.widgets?.find((x) => x.name === "enabled");
225
+ if (!en) return;
226
+ const on = !!en.value;
227
+ for (const w of this.widgets || []) {
228
+ if (w.name === "manual_prompt") {
229
+ setWidgetDisabled(w, on); // editable only when generation is OFF
230
+ } else if (GEN_FIELDS.includes(w.name)) {
231
+ setWidgetDisabled(w, !on);
232
+ }
233
+ }
234
+ this.setDirtyCanvas?.(true, true);
235
+ }
236
+
237
+ function wireEnabledToggle() {
238
+ const en = this.widgets?.find((x) => x.name === "enabled");
239
+ if (en && !en._wired) {
240
+ en._wired = true;
241
+ const orig = en.callback;
242
+ en.callback = (...args) => {
243
+ const r = orig?.apply(en, args);
244
+ applyEnabledState.call(this);
245
+ return r;
246
+ };
247
+ }
248
+ applyEnabledState.call(this);
249
+ }
250
+
251
  const onNodeCreated = nodeType.prototype.onNodeCreated;
252
  nodeType.prototype.onNodeCreated = function () {
253
  onNodeCreated?.apply(this, arguments);
 
255
  this.addWidget("button", "Reload from config", null, () =>
256
  reloadFromConfig.call(this),
257
  );
258
+ wireEnabledToggle.call(this);
259
  };
260
 
261
  const onConfigure = nodeType.prototype.onConfigure;
262
  nodeType.prototype.onConfigure = function () {
263
  onConfigure?.apply(this, arguments);
264
  maskWidget.call(this);
265
+ wireEnabledToggle.call(this);
266
  };
267
  },
268
  });
custom_nodes/openai_prompt/nodes.py CHANGED
@@ -383,6 +383,10 @@ class OpenAIPromptGenerator:
383
  {"default": _DEFAULT_CONFIG_NAME, "multiline": False},
384
  ),
385
  "use_config": ("BOOLEAN", {"default": True}),
 
 
 
 
386
  "base_url": (
387
  "STRING",
388
  {
@@ -426,6 +430,15 @@ class OpenAIPromptGenerator:
426
  "multiline": True,
427
  },
428
  ),
 
 
 
 
 
 
 
 
 
429
  "structured_output": (
430
  "BOOLEAN",
431
  {"default": bool(d("structured_output", False))},
@@ -481,11 +494,13 @@ class OpenAIPromptGenerator:
481
  self,
482
  config_file,
483
  use_config,
 
484
  base_url,
485
  api_key,
486
  model,
487
  system_prompt,
488
  instruction,
 
489
  structured_output,
490
  count,
491
  temperature,
@@ -522,6 +537,19 @@ class OpenAIPromptGenerator:
522
  temperature = float(temperature)
523
  max_tokens = int(max_tokens)
524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
  try:
526
  from openai import OpenAI
527
  except ImportError as exc:
@@ -650,12 +678,144 @@ class TextPreview:
650
  return {"ui": {"text": items}, "result": (items,)}
651
 
652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
  NODE_CLASS_MAPPINGS = {
654
  "OpenAIPromptGenerator": OpenAIPromptGenerator,
655
  "TextPreview": TextPreview,
 
656
  }
657
 
658
  NODE_DISPLAY_NAME_MAPPINGS = {
659
  "OpenAIPromptGenerator": "OpenAI Prompt Generator",
660
  "TextPreview": "Text Preview",
 
661
  }
 
383
  {"default": _DEFAULT_CONFIG_NAME, "multiline": False},
384
  ),
385
  "use_config": ("BOOLEAN", {"default": True}),
386
+ # Master switch. When off, the node skips the API call and
387
+ # outputs `manual_prompt` instead, which you can freely edit
388
+ # (e.g. paste back an embedded prompt to reproduce an image).
389
+ "enabled": ("BOOLEAN", {"default": True}),
390
  "base_url": (
391
  "STRING",
392
  {
 
430
  "multiline": True,
431
  },
432
  ),
433
+ "manual_prompt": (
434
+ "STRING",
435
+ {
436
+ "default": "",
437
+ "multiline": True,
438
+ "placeholder": "Used when 'enabled' is off — type or "
439
+ "paste a prompt here.",
440
+ },
441
+ ),
442
  "structured_output": (
443
  "BOOLEAN",
444
  {"default": bool(d("structured_output", False))},
 
494
  self,
495
  config_file,
496
  use_config,
497
+ enabled,
498
  base_url,
499
  api_key,
500
  model,
501
  system_prompt,
502
  instruction,
503
+ manual_prompt,
504
  structured_output,
505
  count,
506
  temperature,
 
537
  temperature = float(temperature)
538
  max_tokens = int(max_tokens)
539
 
540
+ # Master switch: when disabled, skip the API entirely and output the
541
+ # editable manual_prompt instead. This lets you turn off generation and
542
+ # type / paste an exact prompt (e.g. to reproduce a saved image).
543
+ if not enabled:
544
+ text = manual_prompt or ""
545
+ if structured_output and text.strip():
546
+ results = _split_plaintext(text) or [text]
547
+ if count >= 1 and len(results) > count:
548
+ results = results[:count]
549
+ else:
550
+ results = [text]
551
+ return {"ui": {"text": results}, "result": (results,)}
552
+
553
  try:
554
  from openai import OpenAI
555
  except ImportError as exc:
 
678
  return {"ui": {"text": items}, "result": (items,)}
679
 
680
 
681
+ class SaveImageWithPrompt:
682
+ """
683
+ Save images to the ComfyUI output folder, embedding the *actual* prompt
684
+ text used (e.g. the string produced by the OpenAI Prompt Generator) into
685
+ the PNG metadata.
686
+
687
+ Standard ComfyUI metadata only stores the node graph, so a workflow that
688
+ generates its prompt from an LLM cannot be reproduced exactly (the LLM
689
+ would return something different next time). This node writes the resolved
690
+ prompt string into the PNG so the exact text is always recoverable.
691
+
692
+ Written metadata keys:
693
+ * prompt / workflow - the usual ComfyUI graph (for loading back)
694
+ * generated_prompt - the resolved prompt text used for this image
695
+ * parameters - same text in A1111 style, for external viewers
696
+ """
697
+
698
+ def __init__(self):
699
+ import folder_paths
700
+
701
+ self.output_dir = folder_paths.get_output_directory()
702
+ self.type = "output"
703
+ self.prefix_append = ""
704
+ self.compress_level = 4
705
+
706
+ @classmethod
707
+ def INPUT_TYPES(cls):
708
+ return {
709
+ "required": {
710
+ "images": ("IMAGE",),
711
+ "prompt_text": ("STRING", {"forceInput": True}),
712
+ "filename_prefix": ("STRING", {"default": "ComfyUI"}),
713
+ },
714
+ "optional": {
715
+ "negative_text": ("STRING", {"forceInput": True}),
716
+ },
717
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
718
+ }
719
+
720
+ RETURN_TYPES = ("IMAGE",)
721
+ RETURN_NAMES = ("images",)
722
+ FUNCTION = "save_images"
723
+ OUTPUT_NODE = True
724
+ CATEGORY = "LLM"
725
+
726
+ def save_images(
727
+ self,
728
+ images,
729
+ prompt_text="",
730
+ filename_prefix="ComfyUI",
731
+ negative_text="",
732
+ prompt=None,
733
+ extra_pnginfo=None,
734
+ ):
735
+ import json as _json
736
+ import os as _os
737
+
738
+ import numpy as np
739
+ from PIL import Image
740
+ from PIL.PngImagePlugin import PngInfo
741
+
742
+ import folder_paths
743
+
744
+ try:
745
+ from comfy.cli_args import args
746
+
747
+ disable_metadata = args.disable_metadata
748
+ except Exception:
749
+ disable_metadata = False
750
+
751
+ # prompt_text / negative_text may arrive as lists; normalise to text.
752
+ def _as_text(v):
753
+ if isinstance(v, (list, tuple)):
754
+ return "\n".join(str(x) for x in v)
755
+ return "" if v is None else str(v)
756
+
757
+ pos = _as_text(prompt_text)
758
+ neg = _as_text(negative_text)
759
+
760
+ # A1111-style parameters block (helps external viewers like the PNG
761
+ # Info tab in various UIs).
762
+ parameters = pos
763
+ if neg:
764
+ parameters += f"\nNegative prompt: {neg}"
765
+
766
+ full_output_folder, filename, counter, subfolder, filename_prefix = (
767
+ folder_paths.get_save_image_path(
768
+ filename_prefix + self.prefix_append,
769
+ self.output_dir,
770
+ images[0].shape[1],
771
+ images[0].shape[0],
772
+ )
773
+ )
774
+
775
+ results = []
776
+ for batch_number, image in enumerate(images):
777
+ arr = 255.0 * image.cpu().numpy()
778
+ img = Image.fromarray(np.clip(arr, 0, 255).astype(np.uint8))
779
+
780
+ metadata = None
781
+ if not disable_metadata:
782
+ metadata = PngInfo()
783
+ if prompt is not None:
784
+ metadata.add_text("prompt", _json.dumps(prompt))
785
+ if extra_pnginfo is not None:
786
+ for key in extra_pnginfo:
787
+ metadata.add_text(key, _json.dumps(extra_pnginfo[key]))
788
+ if pos:
789
+ metadata.add_text("generated_prompt", pos)
790
+ metadata.add_text("parameters", parameters)
791
+ if neg:
792
+ metadata.add_text("generated_negative_prompt", neg)
793
+
794
+ filename_with_batch_num = filename.replace(
795
+ "%batch_num%", str(batch_number)
796
+ )
797
+ file = f"{filename_with_batch_num}_{counter:05}_.png"
798
+ img.save(
799
+ _os.path.join(full_output_folder, file),
800
+ pnginfo=metadata,
801
+ compress_level=self.compress_level,
802
+ )
803
+ results.append(
804
+ {"filename": file, "subfolder": subfolder, "type": self.type}
805
+ )
806
+ counter += 1
807
+
808
+ return {"ui": {"images": results}, "result": (images,)}
809
+
810
+
811
  NODE_CLASS_MAPPINGS = {
812
  "OpenAIPromptGenerator": OpenAIPromptGenerator,
813
  "TextPreview": TextPreview,
814
+ "SaveImageWithPrompt": SaveImageWithPrompt,
815
  }
816
 
817
  NODE_DISPLAY_NAME_MAPPINGS = {
818
  "OpenAIPromptGenerator": "OpenAI Prompt Generator",
819
  "TextPreview": "Text Preview",
820
+ "SaveImageWithPrompt": "Save Image (with prompt)",
821
  }