p101111 commited on
Commit
6c5e599
Β·
verified Β·
1 Parent(s): 429fe48

custom_nodes

Browse files
custom_nodes/media_gallery/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .api import setup_routes
2
+
3
+ try:
4
+ from server import PromptServer
5
+
6
+ setup_routes(PromptServer.instance.routes)
7
+ except Exception as exc:
8
+ print(f"[MediaGallery] Could not register API routes: {exc}")
9
+
10
+ WEB_DIRECTORY = "./js"
11
+ NODE_CLASS_MAPPINGS = {}
12
+ NODE_DISPLAY_NAME_MAPPINGS = {}
13
+
14
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
custom_nodes/media_gallery/__pycache__/api.cpython-311.pyc ADDED
Binary file (11.5 kB). View file
 
custom_nodes/media_gallery/__pycache__/nodes.cpython-311.pyc ADDED
Binary file (4.71 kB). View file
 
custom_nodes/media_gallery/api.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ API routes for the Output Gallery.
3
+
4
+ GET /gallery/files – paginated file listing (images + videos)
5
+ POST /gallery/rate – set/clear a 1-5 star rating for a file
6
+ POST /gallery/download – download selected files as a ZIP archive
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import io
12
+ import json
13
+ import os
14
+ import zipfile
15
+ from pathlib import Path
16
+
17
+ from aiohttp import web
18
+
19
+ try:
20
+ import folder_paths
21
+ except ImportError:
22
+ folder_paths = None # type: ignore[assignment]
23
+
24
+ IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
25
+ VIDEO_EXTS = {".mp4", ".webm", ".mov", ".avi", ".mkv"}
26
+
27
+ # Directory names that are never scanned β€” they typically hold downscaled
28
+ # previews/thumbnails generated by external tools or ComfyUI plugins.
29
+ _SKIP_DIRS: set[str] = {
30
+ "_thumbs",
31
+ "thumbs",
32
+ "thumbnail",
33
+ "thumbnails",
34
+ "_thumbnail",
35
+ "_thumbnails",
36
+ "thumb",
37
+ ".thumbnails",
38
+ ".thumbs",
39
+ "preview",
40
+ "previews",
41
+ "_preview",
42
+ "_previews",
43
+ "cache",
44
+ ".cache",
45
+ }
46
+
47
+ _RATINGS_PATH = Path(__file__).parent / "ratings.json"
48
+
49
+
50
+ # ── Output directory ─────────────────────────────────────────────────────────
51
+
52
+
53
+ def _output_dir() -> str:
54
+ if folder_paths:
55
+ return folder_paths.get_output_directory()
56
+ return os.path.join(os.path.dirname(__file__), "output")
57
+
58
+
59
+ # ── Ratings persistence ───────────────────────────────────────────────────────
60
+
61
+
62
+ def _load_ratings() -> dict:
63
+ try:
64
+ if _RATINGS_PATH.exists():
65
+ return json.loads(_RATINGS_PATH.read_text(encoding="utf-8"))
66
+ except Exception:
67
+ pass
68
+ return {}
69
+
70
+
71
+ def _save_ratings(ratings: dict) -> None:
72
+ _RATINGS_PATH.write_text(
73
+ json.dumps(ratings, indent=2, ensure_ascii=False), encoding="utf-8"
74
+ )
75
+
76
+
77
+ def _rating_key(filename: str, subfolder: str) -> str:
78
+ return f"{subfolder}/{filename}" if subfolder else filename
79
+
80
+
81
+ # ── File scan ─────────────────────────────────────────────────────────────────
82
+
83
+
84
+ def _scan(
85
+ media_type: str = "all", min_rating: int = 0, exact_rating: int = 0
86
+ ) -> list[dict]:
87
+ """Walk the output directory and return metadata, sorted newest-first."""
88
+ base = _output_dir()
89
+ ratings = _load_ratings()
90
+ results: list[dict] = []
91
+
92
+ for root, dirs, filenames in os.walk(base):
93
+ dirs[:] = sorted(
94
+ d for d in dirs if not d.startswith(".") and d.lower() not in _SKIP_DIRS
95
+ )
96
+
97
+ for name in filenames:
98
+ if name.startswith("."):
99
+ continue
100
+
101
+ ext = os.path.splitext(name)[1].lower()
102
+ if ext in VIDEO_EXTS:
103
+ kind = "video"
104
+ elif ext in IMAGE_EXTS:
105
+ kind = "image"
106
+ else:
107
+ continue
108
+
109
+ if media_type == "image" and kind != "image":
110
+ continue
111
+ if media_type == "video" and kind != "video":
112
+ continue
113
+
114
+ full = os.path.join(root, name)
115
+ subfolder = os.path.relpath(root, base)
116
+ subfolder = "" if subfolder == "." else subfolder
117
+
118
+ rating = ratings.get(_rating_key(name, subfolder), 0)
119
+ if exact_rating > 0:
120
+ if rating != exact_rating:
121
+ continue
122
+ elif min_rating > 0 and rating < min_rating:
123
+ continue
124
+
125
+ try:
126
+ st = os.stat(full)
127
+ except OSError:
128
+ continue
129
+
130
+ results.append(
131
+ {
132
+ "filename": name,
133
+ "subfolder": subfolder,
134
+ "type": "output",
135
+ "kind": kind,
136
+ "mtime": st.st_mtime,
137
+ "size": st.st_size,
138
+ "rating": rating,
139
+ }
140
+ )
141
+
142
+ results.sort(key=lambda f: f["mtime"], reverse=True)
143
+ return results
144
+
145
+
146
+ # ── Route registration ────────────────────────────────────────────────────────
147
+
148
+
149
+ def setup_routes(routes) -> None:
150
+ # ── GET /gallery/files ───────────────────────────────────────────────────
151
+
152
+ @routes.get("/gallery/files")
153
+ async def get_files(request): # type: ignore[return]
154
+ try:
155
+ page = max(1, int(request.rel_url.query.get("page", 1)))
156
+ page_size = max(
157
+ 1, min(200, int(request.rel_url.query.get("page_size", 50)))
158
+ )
159
+ media_type = request.rel_url.query.get("type", "all")
160
+ min_rating = max(0, min(5, int(request.rel_url.query.get("min_rating", 0))))
161
+ exact_rating = max(
162
+ 0, min(5, int(request.rel_url.query.get("exact_rating", 0)))
163
+ )
164
+
165
+ if media_type not in ("all", "image", "video"):
166
+ media_type = "all"
167
+
168
+ files = _scan(media_type, min_rating, exact_rating)
169
+ total = len(files)
170
+ start = (page - 1) * page_size
171
+ end = start + page_size
172
+
173
+ return web.json_response(
174
+ {
175
+ "files": files[start:end],
176
+ "total": total,
177
+ "page": page,
178
+ "page_size": page_size,
179
+ "has_more": end < total,
180
+ }
181
+ )
182
+ except Exception as exc: # noqa: BLE001
183
+ return web.json_response({"error": str(exc)}, status=500)
184
+
185
+ # ── POST /gallery/rate ───────────────────────────────────────────────────
186
+
187
+ @routes.post("/gallery/rate")
188
+ async def rate_file(request): # type: ignore[return]
189
+ try:
190
+ data = await request.json()
191
+ filename = str(data.get("filename", "")).strip()
192
+ subfolder = str(data.get("subfolder", "")).strip()
193
+ rating = max(0, min(5, int(data.get("rating", 0))))
194
+
195
+ if not filename:
196
+ return web.json_response({"error": "filename required"}, status=400)
197
+
198
+ ratings = _load_ratings()
199
+ key = _rating_key(filename, subfolder)
200
+ if rating == 0:
201
+ ratings.pop(key, None)
202
+ else:
203
+ ratings[key] = rating
204
+ _save_ratings(ratings)
205
+
206
+ return web.json_response({"ok": True, "rating": rating})
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")
213
+ async def bulk_download(request): # type: ignore[return]
214
+ try:
215
+ data = await request.json()
216
+ items = data.get("files", [])
217
+
218
+ if not items:
219
+ return web.json_response({"error": "no files specified"}, status=400)
220
+
221
+ base = Path(_output_dir()).resolve()
222
+ buf = io.BytesIO()
223
+
224
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
225
+ for fi in items:
226
+ name = str(fi.get("filename", ""))
227
+ subfolder = str(fi.get("subfolder", ""))
228
+
229
+ # Security: keep resolved path inside the output directory
230
+ target = (base / subfolder / name).resolve()
231
+ base_str = str(base)
232
+ if not (
233
+ str(target) == base_str
234
+ or str(target).startswith(base_str + os.sep)
235
+ ):
236
+ continue
237
+ if not target.is_file():
238
+ continue
239
+
240
+ arcname = f"{subfolder}/{name}".lstrip("/") if subfolder else name
241
+ zf.write(target, arcname)
242
+
243
+ buf.seek(0)
244
+ return web.Response(
245
+ body=buf.getvalue(),
246
+ content_type="application/zip",
247
+ headers={
248
+ "Content-Disposition": 'attachment; filename="gallery_export.zip"'
249
+ },
250
+ )
251
+ except Exception as exc: # noqa: BLE001
252
+ return web.json_response({"error": str(exc)}, status=500)
custom_nodes/media_gallery/js/gallery.js ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Output Gallery β€” ComfyUI sidebar extension
3
+ * Features: browse output folder, star ratings, multi-select, bulk ZIP download
4
+ */
5
+
6
+ import { app } from "../../scripts/app.js";
7
+ import { api } from "../../scripts/api.js";
8
+
9
+ const API_PATH = "/gallery/files";
10
+ const PAGE_SIZE = 48;
11
+
12
+ // ─── DOM helper ───────────────────────────────────────────────────────────────
13
+
14
+ function $el(tag, attrs = {}, ...children) {
15
+ const el = document.createElement(tag);
16
+ for (const [k, v] of Object.entries(attrs)) {
17
+ if (k === "style" && typeof v === "object") {
18
+ Object.assign(el.style, v);
19
+ } else if (k.startsWith("on") && typeof v === "function") {
20
+ el.addEventListener(k.slice(2).toLowerCase(), v);
21
+ } else {
22
+ el[k] = v;
23
+ }
24
+ }
25
+ for (const child of children) {
26
+ if (child != null) el.appendChild(child);
27
+ }
28
+ return el;
29
+ }
30
+
31
+ // ─── Utilities ────────────────────────────────────────────────────────────────
32
+
33
+ /** Stable string key that uniquely identifies a file in the output tree. */
34
+ function fileKey(file) {
35
+ return file.subfolder ? `${file.subfolder}/${file.filename}` : file.filename;
36
+ }
37
+
38
+ function viewURL(filename, subfolder, type = "output") {
39
+ return api.apiURL(
40
+ `/view?filename=${encodeURIComponent(filename)}` +
41
+ `&subfolder=${encodeURIComponent(subfolder ?? "")}` +
42
+ `&type=${encodeURIComponent(type)}`,
43
+ );
44
+ }
45
+
46
+ function fmtBytes(n) {
47
+ if (n < 1024) return `${n} B`;
48
+ if (n < 1_048_576) return `${(n / 1024).toFixed(1)} KB`;
49
+ return `${(n / 1_048_576).toFixed(1)} MB`;
50
+ }
51
+
52
+ function fmtDate(mtime) {
53
+ return new Date(mtime * 1000).toLocaleString(undefined, {
54
+ year: "numeric",
55
+ month: "short",
56
+ day: "numeric",
57
+ hour: "2-digit",
58
+ minute: "2-digit",
59
+ });
60
+ }
61
+
62
+ // ─── Lightbox ─────────────────────────────────────────────────────────────────
63
+
64
+ class Lightbox {
65
+ /**
66
+ * @param {(item: object) => void} onRatingChange called when the user rates
67
+ * an image from the lightbox; receives the mutated file object.
68
+ */
69
+ constructor(onRatingChange) {
70
+ this._items = [];
71
+ this._idx = 0;
72
+ this._onRatingChange = onRatingChange ?? null;
73
+ this._build();
74
+ }
75
+
76
+ _build() {
77
+ this._overlay = $el("div", {
78
+ style: {
79
+ display: "none",
80
+ position: "fixed",
81
+ inset: "0",
82
+ background: "rgba(0,0,0,0.92)",
83
+ zIndex: "99999",
84
+ flexDirection: "column",
85
+ alignItems: "center",
86
+ justifyContent: "center",
87
+ },
88
+ onclick: (e) => {
89
+ if (e.target === this._overlay) this.close();
90
+ },
91
+ });
92
+
93
+ this._wrap = $el("div", {
94
+ style: {
95
+ maxWidth: "90vw",
96
+ maxHeight: "80vh",
97
+ display: "flex",
98
+ alignItems: "center",
99
+ justifyContent: "center",
100
+ },
101
+ });
102
+
103
+ const closeBtn = $el("button", {
104
+ textContent: "βœ•",
105
+ title: "Close (Esc)",
106
+ onclick: () => this.close(),
107
+ style: {
108
+ position: "absolute",
109
+ top: "14px",
110
+ right: "16px",
111
+ background: "rgba(50,50,50,0.85)",
112
+ color: "#ddd",
113
+ border: "none",
114
+ borderRadius: "6px",
115
+ padding: "5px 12px",
116
+ fontSize: "15px",
117
+ cursor: "pointer",
118
+ zIndex: "1",
119
+ },
120
+ });
121
+
122
+ this._prevBtn = this._arrow("β€Ή", "left", () => this._move(-1));
123
+ this._nextBtn = this._arrow("β€Ί", "right", () => this._move(+1));
124
+
125
+ this._nameEl = $el("span", {
126
+ style: { fontWeight: "bold", color: "#eee", marginRight: "8px" },
127
+ });
128
+ this._metaEl = $el("span", { style: { color: "#888" } });
129
+ this._countEl = $el("span", {
130
+ style: {
131
+ marginLeft: "auto",
132
+ color: "#666",
133
+ minWidth: "50px",
134
+ textAlign: "right",
135
+ },
136
+ });
137
+ this._dlBtn = $el("a", {
138
+ textContent: "⬇ Download",
139
+ style: {
140
+ background: "#2c2c2c",
141
+ color: "#bbb",
142
+ textDecoration: "none",
143
+ padding: "3px 10px",
144
+ borderRadius: "5px",
145
+ fontSize: "12px",
146
+ cursor: "pointer",
147
+ flexShrink: "0",
148
+ },
149
+ });
150
+
151
+ // ── Star rating widget ──────────────────────────────────────────────────
152
+ this._lbStars = [];
153
+ this._lbStarBar = $el("div", {
154
+ style: {
155
+ display: "flex",
156
+ gap: "1px",
157
+ alignItems: "center",
158
+ flexShrink: "0",
159
+ },
160
+ });
161
+
162
+ const refreshLbStars = (hover = -1) => {
163
+ const r = hover >= 0 ? hover : (this._items[this._idx]?.rating ?? 0);
164
+ this._lbStars.forEach((s, j) => {
165
+ const on = j < r;
166
+ s.style.color = on
167
+ ? hover >= 0
168
+ ? "#f4d03f"
169
+ : "#f1c40f"
170
+ : hover >= 0
171
+ ? "#666"
172
+ : "#444";
173
+ });
174
+ };
175
+ this._refreshLbStars = refreshLbStars;
176
+
177
+ for (let i = 1; i <= 5; i++) {
178
+ const star = $el("span", {
179
+ textContent: "β˜…",
180
+ title: `Rate ${i} star${i > 1 ? "s" : ""}`,
181
+ style: {
182
+ color: "#444",
183
+ fontSize: "20px",
184
+ cursor: "pointer",
185
+ lineHeight: "1",
186
+ padding: "0 2px",
187
+ transition: "color 0.1s",
188
+ },
189
+ });
190
+ star.addEventListener("mouseenter", () => refreshLbStars(i));
191
+ star.addEventListener("click", (e) => {
192
+ e.stopPropagation();
193
+ const item = this._items[this._idx];
194
+ if (!item) return;
195
+ item.rating = i === item.rating ? 0 : i;
196
+ refreshLbStars();
197
+ this._onRatingChange?.(item);
198
+ });
199
+ this._lbStars.push(star);
200
+ this._lbStarBar.appendChild(star);
201
+ }
202
+ this._lbStarBar.addEventListener("mouseleave", () => refreshLbStars());
203
+ // ───────────────────────────────────────────────────────────────────────
204
+
205
+ const infoBar = $el(
206
+ "div",
207
+ {
208
+ style: {
209
+ position: "absolute",
210
+ bottom: "0",
211
+ left: "0",
212
+ right: "0",
213
+ padding: "10px 16px",
214
+ display: "flex",
215
+ alignItems: "center",
216
+ gap: "8px",
217
+ background: "rgba(0,0,0,0.65)",
218
+ backdropFilter: "blur(6px)",
219
+ fontSize: "12px",
220
+ flexWrap: "wrap",
221
+ },
222
+ },
223
+ this._nameEl,
224
+ this._metaEl,
225
+ this._lbStarBar,
226
+ this._dlBtn,
227
+ this._countEl,
228
+ );
229
+
230
+ this._overlay.append(
231
+ this._wrap,
232
+ closeBtn,
233
+ this._prevBtn,
234
+ this._nextBtn,
235
+ infoBar,
236
+ );
237
+ document.body.appendChild(this._overlay);
238
+
239
+ document.addEventListener("keydown", (e) => {
240
+ if (this._overlay.style.display === "none") return;
241
+ if (e.key === "ArrowLeft" || e.key === "a") this._move(-1);
242
+ if (e.key === "ArrowRight" || e.key === "d") this._move(+1);
243
+ if (e.key === "Escape") this.close();
244
+ });
245
+ }
246
+
247
+ _arrow(text, side, onClick) {
248
+ return $el("button", {
249
+ textContent: text,
250
+ onclick: onClick,
251
+ style: {
252
+ position: "absolute",
253
+ [side]: "14px",
254
+ top: "50%",
255
+ transform: "translateY(-50%)",
256
+ background: "rgba(30,30,30,0.8)",
257
+ color: "#ddd",
258
+ border: "none",
259
+ borderRadius: "6px",
260
+ width: "46px",
261
+ height: "58px",
262
+ fontSize: "30px",
263
+ cursor: "pointer",
264
+ zIndex: "1",
265
+ lineHeight: "1",
266
+ },
267
+ });
268
+ }
269
+
270
+ open(items, index) {
271
+ this._items = items;
272
+ this._idx = index;
273
+ this._render();
274
+ }
275
+
276
+ close() {
277
+ this._overlay.style.display = "none";
278
+ this._wrap.innerHTML = "";
279
+ }
280
+
281
+ _move(dir) {
282
+ this._idx = (this._idx + dir + this._items.length) % this._items.length;
283
+ this._render();
284
+ }
285
+
286
+ _render() {
287
+ const item = this._items[this._idx];
288
+ this._overlay.style.display = "flex";
289
+
290
+ const single = this._items.length <= 1;
291
+ this._prevBtn.style.display = single ? "none" : "block";
292
+ this._nextBtn.style.display = single ? "none" : "block";
293
+ this._countEl.textContent = `${this._idx + 1} / ${this._items.length}`;
294
+ this._nameEl.textContent = item.filename;
295
+ this._metaEl.textContent = `${fmtDate(item.mtime)} β€’ ${fmtBytes(item.size)}`;
296
+ this._refreshLbStars();
297
+
298
+ const src = viewURL(item.filename, item.subfolder);
299
+ this._dlBtn.href = src;
300
+ this._dlBtn.download = item.filename;
301
+
302
+ this._wrap.innerHTML = "";
303
+ if (item.kind === "video") {
304
+ this._wrap.appendChild(
305
+ $el("video", {
306
+ src,
307
+ controls: true,
308
+ autoplay: true,
309
+ style: { maxWidth: "90vw", maxHeight: "80vh", borderRadius: "6px" },
310
+ }),
311
+ );
312
+ } else {
313
+ this._wrap.appendChild(
314
+ $el("img", {
315
+ src,
316
+ style: {
317
+ maxWidth: "90vw",
318
+ maxHeight: "80vh",
319
+ objectFit: "contain",
320
+ borderRadius: "6px",
321
+ },
322
+ }),
323
+ );
324
+ }
325
+ }
326
+ }
327
+
328
+ // ─── Gallery Panel ────────────────────────────────────────────────────────────
329
+
330
+ class GalleryPanel {
331
+ constructor(container) {
332
+ this._container = container;
333
+ this._files = []; // all loaded file objects (newest-first order)
334
+ this._fileKeys = new Set(); // Set<fileKey> for fast duplicate detection
335
+ this._tileRefs = new Map(); // Map<fileKey, { checkEl, selOverlay, applySelection }>
336
+ this._page = 1;
337
+ this._hasMore = false;
338
+ this._total = 0;
339
+ this._filter = "all"; // "all" | "image" | "video"
340
+ this._ratingValue = 0; // 0 = any, 1-5 = active star count
341
+ this._ratingExact = false; // false = "at least", true = "exactly"
342
+ this._selectMode = false;
343
+ this._selected = new Set();
344
+ this._loading = false;
345
+ this._lightbox = new Lightbox((file) => {
346
+ this._saveRating(file);
347
+ this._tileRefs.get(fileKey(file))?.syncRating();
348
+ });
349
+
350
+ this._build();
351
+ this.refresh();
352
+ }
353
+
354
+ // ── Layout ───────────────────────────────────────────────────────────────
355
+
356
+ _build() {
357
+ Object.assign(this._container.style, {
358
+ display: "flex",
359
+ flexDirection: "column",
360
+ height: "100%",
361
+ overflow: "hidden",
362
+ background: "var(--comfy-menu-bg, #181818)",
363
+ color: "var(--fg-color, #ddd)",
364
+ fontFamily: "sans-serif",
365
+ userSelect: "none",
366
+ });
367
+ this._container.append(
368
+ this._buildToolbar(),
369
+ this._buildSubbar(),
370
+ this._buildScrollArea(),
371
+ );
372
+ }
373
+
374
+ // ── Toolbar ───────────────────────────────────────────────────────────────
375
+
376
+ _buildToolbar() {
377
+ // ── normal bar ──────────────────────────────────────────────────────
378
+ const title = $el("span", {
379
+ textContent: "Output Gallery",
380
+ style: { fontWeight: "600", fontSize: "13px", color: "#ddd" },
381
+ });
382
+
383
+ this._badge = $el("span", {
384
+ style: {
385
+ position: "absolute",
386
+ top: "-5px",
387
+ right: "-5px",
388
+ background: "#e74c3c",
389
+ color: "#fff",
390
+ borderRadius: "50%",
391
+ width: "16px",
392
+ height: "16px",
393
+ fontSize: "9px",
394
+ fontWeight: "bold",
395
+ display: "none",
396
+ alignItems: "center",
397
+ justifyContent: "center",
398
+ pointerEvents: "none",
399
+ },
400
+ });
401
+
402
+ this._refreshBtn = $el(
403
+ "button",
404
+ {
405
+ title: "Refresh",
406
+ onclick: () => this.refresh(),
407
+ style: {
408
+ position: "relative",
409
+ background: "transparent",
410
+ color: "#999",
411
+ border: "none",
412
+ borderRadius: "5px",
413
+ width: "28px",
414
+ height: "28px",
415
+ fontSize: "17px",
416
+ cursor: "pointer",
417
+ display: "flex",
418
+ alignItems: "center",
419
+ justifyContent: "center",
420
+ },
421
+ },
422
+ $el("span", { textContent: "⟳" }),
423
+ this._badge,
424
+ );
425
+
426
+ const selectToggleBtn = $el("button", {
427
+ textContent: "β˜‘ Select",
428
+ title: "Enter selection mode",
429
+ onclick: () => this._enterSelectMode(),
430
+ style: {
431
+ background: "transparent",
432
+ color: "#999",
433
+ border: "1px solid #3a3a3a",
434
+ borderRadius: "5px",
435
+ padding: "2px 8px",
436
+ fontSize: "11px",
437
+ cursor: "pointer",
438
+ },
439
+ });
440
+
441
+ this._normalBar = $el(
442
+ "div",
443
+ {
444
+ style: {
445
+ display: "flex",
446
+ alignItems: "center",
447
+ padding: "10px 10px 6px",
448
+ gap: "6px",
449
+ flexShrink: "0",
450
+ },
451
+ },
452
+ title,
453
+ $el("span", { style: { flex: "1" } }),
454
+ selectToggleBtn,
455
+ this._refreshBtn,
456
+ );
457
+
458
+ // ── selection bar ───────────────────────────────────────────────────
459
+ this._selCountLabel = $el("span", {
460
+ style: {
461
+ color: "#ccc",
462
+ fontSize: "12px",
463
+ flex: "1",
464
+ textAlign: "center",
465
+ },
466
+ textContent: "0 selected",
467
+ });
468
+
469
+ const mkSelBtn = (text, title, onclick, extra = {}) =>
470
+ $el("button", {
471
+ textContent: text,
472
+ title,
473
+ onclick,
474
+ style: {
475
+ background: "transparent",
476
+ color: "#aaa",
477
+ border: "1px solid #3a3a3a",
478
+ borderRadius: "5px",
479
+ padding: "3px 7px",
480
+ fontSize: "11px",
481
+ cursor: "pointer",
482
+ whiteSpace: "nowrap",
483
+ ...extra,
484
+ },
485
+ });
486
+
487
+ const selectAllBtn = mkSelBtn("All", "Select all", () => this._selectAll());
488
+ const deselectBtn = mkSelBtn("None", "Deselect all", () =>
489
+ this._deselectAll(),
490
+ );
491
+
492
+ this._dlBtn = mkSelBtn(
493
+ "⬇ Download",
494
+ "Download selected files",
495
+ () => this._downloadSelected(),
496
+ { background: "#0e2a4a", color: "#5b9bd5", borderColor: "#1a4a7a" },
497
+ );
498
+
499
+ const doneBtn = mkSelBtn(
500
+ "βœ• Done",
501
+ "Exit selection mode",
502
+ () => this._exitSelectMode(),
503
+ { marginLeft: "4px" },
504
+ );
505
+
506
+ this._selectBar = $el(
507
+ "div",
508
+ {
509
+ style: {
510
+ display: "none",
511
+ alignItems: "center",
512
+ padding: "7px 8px",
513
+ gap: "4px",
514
+ flexShrink: "0",
515
+ },
516
+ },
517
+ selectAllBtn,
518
+ deselectBtn,
519
+ this._selCountLabel,
520
+ this._dlBtn,
521
+ doneBtn,
522
+ );
523
+
524
+ const wrap = document.createElement("div");
525
+ wrap.style.flexShrink = "0";
526
+ wrap.append(this._normalBar, this._selectBar);
527
+ return wrap;
528
+ }
529
+
530
+ // ── Subbar ────────────────────────────────────────────────────────────────
531
+
532
+ _buildSubbar() {
533
+ // Type filter pills
534
+ this._filterBtns = {};
535
+ const typePills = $el("div", { style: { display: "flex", gap: "3px" } });
536
+
537
+ for (const [key, label] of [
538
+ ["all", "All"],
539
+ ["image", "Img"],
540
+ ["video", "Vid"],
541
+ ]) {
542
+ const active = key === "all";
543
+ const btn = $el("button", {
544
+ textContent: label,
545
+ onclick: () => this._setFilter(key),
546
+ style: {
547
+ background: active ? "var(--comfy-input-bg,#3a3a3a)" : "transparent",
548
+ color: active ? "#eee" : "#777",
549
+ border: "1px solid " + (active ? "#555" : "#2e2e2e"),
550
+ borderRadius: "12px",
551
+ padding: "2px 9px",
552
+ fontSize: "11px",
553
+ cursor: "pointer",
554
+ },
555
+ });
556
+ this._filterBtns[key] = btn;
557
+ typePills.appendChild(btn);
558
+ }
559
+
560
+ this._countEl = $el("span", {
561
+ style: { marginLeft: "auto", fontSize: "11px", color: "#444" },
562
+ });
563
+
564
+ const row1 = $el(
565
+ "div",
566
+ {
567
+ style: {
568
+ display: "flex",
569
+ alignItems: "center",
570
+ gap: "5px",
571
+ marginBottom: "6px",
572
+ },
573
+ },
574
+ typePills,
575
+ this._countEl,
576
+ );
577
+
578
+ // Rating filter pills
579
+ this._ratingBtns = [];
580
+ const starPills = $el("div", {
581
+ style: { display: "flex", gap: "3px", alignItems: "center" },
582
+ });
583
+
584
+ starPills.appendChild(
585
+ $el("span", {
586
+ textContent: "β˜…",
587
+ style: { color: "#555", fontSize: "11px", marginRight: "1px" },
588
+ }),
589
+ );
590
+
591
+ const mkStarBtn = (baseLabel, value) => {
592
+ const btn = $el("button", {
593
+ textContent: baseLabel,
594
+ title:
595
+ value === 0
596
+ ? "Show all"
597
+ : `Click: at least ${value}β˜… β€’ Click again: exactly ${value}β˜…`,
598
+ onclick: () =>
599
+ value === 0 ? this._resetRating() : this._cycleRating(value),
600
+ style: {
601
+ background:
602
+ value === 0 ? "var(--comfy-input-bg,#3a3a3a)" : "transparent",
603
+ color: value === 0 ? "#eee" : "#666",
604
+ border: "1px solid " + (value === 0 ? "#555" : "#2e2e2e"),
605
+ borderRadius: "12px",
606
+ padding: "2px 6px",
607
+ fontSize: value === 0 ? "11px" : "10px",
608
+ cursor: "pointer",
609
+ letterSpacing: value > 2 ? "-1px" : "0",
610
+ },
611
+ });
612
+ this._ratingBtns.push({ el: btn, value, baseLabel });
613
+ return btn;
614
+ };
615
+
616
+ starPills.append(
617
+ mkStarBtn("Any", 0),
618
+ mkStarBtn("β˜…", 1),
619
+ mkStarBtn("β˜…β˜…", 2),
620
+ mkStarBtn("β˜…β˜…β˜…", 3),
621
+ mkStarBtn("β˜…β˜…β˜…β˜…", 4),
622
+ mkStarBtn("β˜…β˜…β˜…β˜…β˜…", 5),
623
+ );
624
+
625
+ const row2 = $el(
626
+ "div",
627
+ {
628
+ style: { display: "flex", alignItems: "center" },
629
+ },
630
+ starPills,
631
+ );
632
+
633
+ return $el(
634
+ "div",
635
+ {
636
+ style: {
637
+ padding: "6px 10px 8px",
638
+ borderBottom: "1px solid #232323",
639
+ flexShrink: "0",
640
+ },
641
+ },
642
+ row1,
643
+ row2,
644
+ );
645
+ }
646
+
647
+ // ── Scroll area ───────────────────────────────────────────────────────────
648
+
649
+ _buildScrollArea() {
650
+ this._grid = $el("div", {
651
+ style: {
652
+ display: "grid",
653
+ gridTemplateColumns: "repeat(auto-fill, minmax(100px, 1fr))",
654
+ gap: "4px",
655
+ padding: "8px",
656
+ },
657
+ });
658
+
659
+ this._emptyEl = $el(
660
+ "div",
661
+ {
662
+ style: {
663
+ display: "none",
664
+ flexDirection: "column",
665
+ alignItems: "center",
666
+ justifyContent: "center",
667
+ color: "#444",
668
+ fontSize: "13px",
669
+ textAlign: "center",
670
+ padding: "60px 20px",
671
+ },
672
+ },
673
+ $el("div", {
674
+ textContent: "πŸ–Ό",
675
+ style: { fontSize: "36px", marginBottom: "10px" },
676
+ }),
677
+ $el("div", { textContent: "No media in the output folder yet." }),
678
+ $el("div", {
679
+ textContent: "Run a workflow to see images here.",
680
+ style: { color: "#333", marginTop: "4px", fontSize: "12px" },
681
+ }),
682
+ );
683
+
684
+ this._loadingEl = $el("div", {
685
+ style: {
686
+ display: "none",
687
+ textAlign: "center",
688
+ padding: "16px",
689
+ color: "#555",
690
+ fontSize: "12px",
691
+ },
692
+ textContent: "Loading…",
693
+ });
694
+
695
+ this._scrollEl = $el(
696
+ "div",
697
+ {
698
+ style: { flex: "1", overflowY: "auto" },
699
+ onscroll: () => this._onScroll(),
700
+ },
701
+ this._grid,
702
+ this._emptyEl,
703
+ this._loadingEl,
704
+ );
705
+
706
+ return this._scrollEl;
707
+ }
708
+
709
+ // ── Filter ────────────────────────────────────────────────────────────────
710
+
711
+ _setFilter(key) {
712
+ if (this._filter === key) return;
713
+ this._filter = key;
714
+ for (const [k, btn] of Object.entries(this._filterBtns)) {
715
+ const a = k === key;
716
+ btn.style.background = a
717
+ ? "var(--comfy-input-bg,#3a3a3a)"
718
+ : "transparent";
719
+ btn.style.color = a ? "#eee" : "#777";
720
+ btn.style.borderColor = a ? "#555" : "#2e2e2e";
721
+ }
722
+ this.refresh();
723
+ }
724
+
725
+ _cycleRating(n) {
726
+ if (this._ratingValue !== n) {
727
+ // Activate as "at least N"
728
+ this._ratingValue = n;
729
+ this._ratingExact = false;
730
+ } else if (!this._ratingExact) {
731
+ // Switch to "exactly N"
732
+ this._ratingExact = true;
733
+ } else {
734
+ // Deactivate back to "Any"
735
+ this._ratingValue = 0;
736
+ this._ratingExact = false;
737
+ }
738
+ this._updateRatingBtns();
739
+ this.refresh();
740
+ }
741
+
742
+ _resetRating() {
743
+ this._ratingValue = 0;
744
+ this._ratingExact = false;
745
+ this._updateRatingBtns();
746
+ this.refresh();
747
+ }
748
+
749
+ _updateRatingBtns() {
750
+ for (const { el, value, baseLabel } of this._ratingBtns) {
751
+ if (value === 0) {
752
+ const a = this._ratingValue === 0;
753
+ el.textContent = baseLabel;
754
+ el.style.background = a
755
+ ? "var(--comfy-input-bg,#3a3a3a)"
756
+ : "transparent";
757
+ el.style.color = a ? "#eee" : "#666";
758
+ el.style.borderColor = a ? "#555" : "#2e2e2e";
759
+ } else {
760
+ const isActive = value === this._ratingValue;
761
+ const isExact = isActive && this._ratingExact;
762
+ if (!isActive) {
763
+ el.textContent = baseLabel;
764
+ el.style.background = "transparent";
765
+ el.style.color = "#666";
766
+ el.style.borderColor = "#2e2e2e";
767
+ } else if (!isExact) {
768
+ // "at least" mode
769
+ el.textContent = "\u2265" + baseLabel;
770
+ el.style.background = "var(--comfy-input-bg,#3a3a3a)";
771
+ el.style.color = "#eee";
772
+ el.style.borderColor = "#555";
773
+ } else {
774
+ // "exactly" mode β€” amber tint
775
+ el.textContent = "=" + baseLabel;
776
+ el.style.background = "#2d2200";
777
+ el.style.color = "#f1c40f";
778
+ el.style.borderColor = "#6a5200";
779
+ }
780
+ }
781
+ }
782
+ }
783
+
784
+ // ── Selection mode ────────────────────────────────────────────────────────
785
+
786
+ _enterSelectMode() {
787
+ this._selectMode = true;
788
+ this._selected.clear();
789
+ this._normalBar.style.display = "none";
790
+ this._selectBar.style.display = "flex";
791
+ this._tileRefs.forEach((ref) => ref.applySelection(false, true));
792
+ this._updateSelectBar();
793
+ }
794
+
795
+ _exitSelectMode() {
796
+ this._selectMode = false;
797
+ this._selected.clear();
798
+ this._selectBar.style.display = "none";
799
+ this._normalBar.style.display = "flex";
800
+ this._tileRefs.forEach((ref) => ref.applySelection(false, false));
801
+ }
802
+
803
+ _toggleSelect(key) {
804
+ if (this._selected.has(key)) {
805
+ this._selected.delete(key);
806
+ } else {
807
+ this._selected.add(key);
808
+ }
809
+ this._tileRefs.get(key)?.applySelection(this._selected.has(key), true);
810
+ this._updateSelectBar();
811
+ }
812
+
813
+ _selectAll() {
814
+ this._files.forEach((f) => this._selected.add(fileKey(f)));
815
+ this._tileRefs.forEach((ref, key) =>
816
+ ref.applySelection(this._selected.has(key), true),
817
+ );
818
+ this._updateSelectBar();
819
+ }
820
+
821
+ _deselectAll() {
822
+ this._selected.clear();
823
+ this._tileRefs.forEach((ref) => ref.applySelection(false, true));
824
+ this._updateSelectBar();
825
+ }
826
+
827
+ _updateSelectBar() {
828
+ const n = this._selected.size;
829
+ this._selCountLabel.textContent = `${n} selected`;
830
+ this._dlBtn.disabled = n === 0;
831
+ this._dlBtn.style.opacity = n === 0 ? "0.4" : "1";
832
+ this._dlBtn.style.cursor = n === 0 ? "default" : "pointer";
833
+ }
834
+
835
+ // ── Download ──────────────────────────────────────────────────────────────
836
+
837
+ async _downloadSelected() {
838
+ if (!this._selected.size) return;
839
+
840
+ const selectedFiles = this._files.filter((f) =>
841
+ this._selected.has(fileKey(f)),
842
+ );
843
+ if (!selectedFiles.length) return;
844
+
845
+ const files = selectedFiles.map((f) => ({
846
+ filename: f.filename,
847
+ subfolder: f.subfolder,
848
+ }));
849
+
850
+ // Single file β†’ direct link
851
+ if (files.length === 1) {
852
+ const f = selectedFiles[0];
853
+ const a = $el("a", {
854
+ href: viewURL(f.filename, f.subfolder),
855
+ download: f.filename,
856
+ });
857
+ document.body.appendChild(a);
858
+ a.click();
859
+ document.body.removeChild(a);
860
+ return;
861
+ }
862
+
863
+ // Multiple files β†’ ZIP via server
864
+ // Use native fetch (not api.fetchApi) so the binary response is never
865
+ // touched by ComfyUI's response interceptors, which can corrupt blob data.
866
+ const origText = this._dlBtn.textContent;
867
+ this._dlBtn.textContent = "⏳ Zipping…";
868
+ this._dlBtn.disabled = true;
869
+
870
+ try {
871
+ const res = await fetch(api.apiURL("/gallery/download"), {
872
+ method: "POST",
873
+ headers: { "Content-Type": "application/json" },
874
+ body: JSON.stringify({ files }),
875
+ });
876
+
877
+ if (!res.ok) {
878
+ const msg = await res.text().catch(() => res.status);
879
+ throw new Error(`Server error ${res.status}: ${msg}`);
880
+ }
881
+
882
+ const blob = await res.blob();
883
+ if (blob.size === 0) throw new Error("Server returned an empty ZIP.");
884
+
885
+ const url = URL.createObjectURL(blob);
886
+ const a = $el("a", { href: url, download: `gallery_${Date.now()}.zip` });
887
+ document.body.appendChild(a);
888
+ a.click();
889
+ document.body.removeChild(a);
890
+ // Revoke after a short delay so the browser has time to start the download
891
+ setTimeout(() => URL.revokeObjectURL(url), 10_000);
892
+ } catch (err) {
893
+ console.error("[Gallery] Download failed:", err);
894
+ alert(`Download failed:\n${err.message}`);
895
+ } finally {
896
+ this._dlBtn.textContent = origText;
897
+ this._updateSelectBar();
898
+ }
899
+ }
900
+
901
+ // ── Data loading ──────────────────────────────────────────────────────────
902
+
903
+ async refresh() {
904
+ this._files = [];
905
+ this._fileKeys = new Set();
906
+ this._tileRefs = new Map();
907
+ this._page = 1;
908
+ this._hasMore = false;
909
+ this._selected.clear();
910
+ this._grid.innerHTML = "";
911
+ this._hideBadge();
912
+ if (this._selectMode) this._updateSelectBar();
913
+ await this._fetch();
914
+ }
915
+
916
+ async _loadMore() {
917
+ if (!this._hasMore || this._loading) return;
918
+ await this._fetch();
919
+ }
920
+
921
+ async _fetch() {
922
+ if (this._loading) return;
923
+ this._loading = true;
924
+ this._loadingEl.style.display = "block";
925
+
926
+ try {
927
+ const qs = new URLSearchParams({
928
+ page: this._page,
929
+ page_size: PAGE_SIZE,
930
+ type: this._filter,
931
+ min_rating: this._ratingExact ? 0 : this._ratingValue,
932
+ exact_rating: this._ratingExact ? this._ratingValue : 0,
933
+ });
934
+ const res = await api.fetchApi(`${API_PATH}?${qs}`);
935
+ const data = await res.json();
936
+ if (data.error) throw new Error(data.error);
937
+
938
+ this._total = data.total;
939
+ this._hasMore = data.has_more;
940
+ this._page = data.page + 1;
941
+
942
+ for (const file of data.files) {
943
+ const key = fileKey(file);
944
+ this._files.push(file);
945
+ this._fileKeys.add(key);
946
+ const { el, refs } = this._makeTile(file);
947
+ this._tileRefs.set(key, refs);
948
+ this._grid.appendChild(el);
949
+ }
950
+
951
+ const shown = this._files.length;
952
+ this._emptyEl.style.display = shown === 0 ? "flex" : "none";
953
+ this._countEl.textContent =
954
+ shown < this._total
955
+ ? `${shown} / ${this._total}`
956
+ : `${this._total} item${this._total !== 1 ? "s" : ""}`;
957
+ } catch (err) {
958
+ console.error("[Gallery]", err);
959
+ } finally {
960
+ this._loading = false;
961
+ this._loadingEl.style.display = "none";
962
+ }
963
+ }
964
+
965
+ // ── Incremental update (no full re-render) ──────────────────────────────────
966
+
967
+ async incrementalUpdate() {
968
+ try {
969
+ const qs = new URLSearchParams({
970
+ page: 1,
971
+ page_size: PAGE_SIZE,
972
+ type: this._filter,
973
+ min_rating: this._ratingExact ? 0 : this._ratingValue,
974
+ exact_rating: this._ratingExact ? this._ratingValue : 0,
975
+ });
976
+ const res = await api.fetchApi(`${API_PATH}?${qs}`);
977
+ const data = await res.json();
978
+ if (data.error) throw new Error(data.error);
979
+
980
+ const newFiles = data.files.filter(
981
+ (f) => !this._fileKeys.has(fileKey(f)),
982
+ );
983
+ if (!newFiles.length) return;
984
+
985
+ // Prepend new tiles newest-first.
986
+ // data.files is already newest-first; iterate in reverse so the
987
+ // repeated insertBefore(el, firstChild) yields the correct final order.
988
+ for (let i = newFiles.length - 1; i >= 0; i--) {
989
+ const file = newFiles[i];
990
+ const key = fileKey(file);
991
+ this._fileKeys.add(key);
992
+ const { el, refs } = this._makeTile(file);
993
+ this._tileRefs.set(key, refs);
994
+ this._files.unshift(file);
995
+ this._grid.insertBefore(el, this._grid.firstChild);
996
+ if (this._selectMode)
997
+ refs.applySelection(this._selected.has(key), true);
998
+ }
999
+
1000
+ // Use the server's authoritative total (already includes new files).
1001
+ this._total = data.total;
1002
+ const shown = this._files.length;
1003
+ this._emptyEl.style.display = shown === 0 ? "flex" : "none";
1004
+ this._countEl.textContent =
1005
+ shown < this._total
1006
+ ? `${shown} / ${this._total}`
1007
+ : `${this._total} item${this._total !== 1 ? "s" : ""}`;
1008
+
1009
+ this._scrollEl.scrollTo({ top: 0, behavior: "smooth" });
1010
+ } catch (err) {
1011
+ console.error("[Gallery] incrementalUpdate:", err);
1012
+ }
1013
+ }
1014
+
1015
+ // ── Tile ──────────────────────────────────────────────────────────────────
1016
+
1017
+ _makeTile(file) {
1018
+ // Selection overlay (blue tint when selected)
1019
+ const selOverlay = $el("div", {
1020
+ style: {
1021
+ position: "absolute",
1022
+ inset: "0",
1023
+ background: "rgba(74,158,255,0.22)",
1024
+ display: "none",
1025
+ pointerEvents: "none",
1026
+ zIndex: "2",
1027
+ },
1028
+ });
1029
+
1030
+ // Circular checkbox badge (top-right)
1031
+ const checkEl = $el("div", {
1032
+ style: {
1033
+ position: "absolute",
1034
+ top: "5px",
1035
+ right: "5px",
1036
+ width: "18px",
1037
+ height: "18px",
1038
+ borderRadius: "50%",
1039
+ border: "1.5px solid rgba(200,200,200,0.35)",
1040
+ background: "rgba(20,20,20,0.6)",
1041
+ display: "none",
1042
+ alignItems: "center",
1043
+ justifyContent: "center",
1044
+ fontSize: "11px",
1045
+ fontWeight: "bold",
1046
+ color: "#fff",
1047
+ zIndex: "3",
1048
+ pointerEvents: "none",
1049
+ },
1050
+ });
1051
+
1052
+ // Closure: apply selection state + visibility of check badge
1053
+ function applySelection(selected, inSelectMode) {
1054
+ checkEl.style.display = inSelectMode ? "flex" : "none";
1055
+ checkEl.textContent = selected ? "βœ“" : "";
1056
+ checkEl.style.background = selected ? "#4a9eff" : "rgba(20,20,20,0.6)";
1057
+ checkEl.style.borderColor = selected
1058
+ ? "#4a9eff"
1059
+ : "rgba(200,200,200,0.35)";
1060
+ selOverlay.style.display = selected ? "block" : "none";
1061
+ }
1062
+
1063
+ // Rating bar
1064
+ const { bar: ratingBar, syncRating } = this._makeRatingBar(file);
1065
+
1066
+ // Media element
1067
+ const media = this._makeMedia(file);
1068
+
1069
+ // Tile container
1070
+ const tile = $el(
1071
+ "div",
1072
+ {
1073
+ title: `${file.filename}\n${fmtDate(file.mtime)} β€’ ${fmtBytes(file.size)}`,
1074
+ style: {
1075
+ position: "relative",
1076
+ aspectRatio: "1",
1077
+ overflow: "hidden",
1078
+ borderRadius: "5px",
1079
+ cursor: "pointer",
1080
+ background: "#1e1e1e",
1081
+ },
1082
+ onclick: (e) => {
1083
+ if (ratingBar.contains(e.target)) return;
1084
+ if (this._selectMode) {
1085
+ this._toggleSelect(fileKey(file));
1086
+ } else {
1087
+ // Dynamic indexOf so prepended items don't break existing tiles.
1088
+ this._lightbox.open(this._files, this._files.indexOf(file));
1089
+ }
1090
+ },
1091
+ },
1092
+ media,
1093
+ selOverlay,
1094
+ checkEl,
1095
+ ratingBar,
1096
+ );
1097
+
1098
+ // Hover scale (normal mode only)
1099
+ media.addEventListener("mouseenter", () => {
1100
+ if (this._selectMode) return;
1101
+ media.style.transform = "scale(1.06)";
1102
+ media.style.opacity = "0.85";
1103
+ });
1104
+ media.addEventListener("mouseleave", () => {
1105
+ media.style.transform = "scale(1)";
1106
+ media.style.opacity = "1";
1107
+ });
1108
+
1109
+ // If already in select mode, show checkbox immediately
1110
+ if (this._selectMode)
1111
+ applySelection(this._selected.has(fileKey(file)), true);
1112
+
1113
+ return {
1114
+ el: tile,
1115
+ refs: { checkEl, selOverlay, applySelection, syncRating },
1116
+ };
1117
+ }
1118
+
1119
+ _makeMedia(file) {
1120
+ const src = viewURL(file.filename, file.subfolder);
1121
+
1122
+ if (file.kind === "video") {
1123
+ const vid = $el("video", {
1124
+ src,
1125
+ preload: "metadata",
1126
+ muted: true,
1127
+ style: {
1128
+ width: "100%",
1129
+ height: "100%",
1130
+ objectFit: "cover",
1131
+ display: "block",
1132
+ },
1133
+ });
1134
+ const playOverlay = $el(
1135
+ "div",
1136
+ {
1137
+ style: {
1138
+ position: "absolute",
1139
+ inset: "0",
1140
+ display: "flex",
1141
+ alignItems: "center",
1142
+ justifyContent: "center",
1143
+ background: "rgba(0,0,0,0.38)",
1144
+ pointerEvents: "none",
1145
+ },
1146
+ },
1147
+ $el("span", {
1148
+ textContent: "β–Ά",
1149
+ style: { color: "rgba(255,255,255,0.85)", fontSize: "20px" },
1150
+ }),
1151
+ );
1152
+
1153
+ const wrap = $el(
1154
+ "div",
1155
+ {
1156
+ style: {
1157
+ position: "absolute",
1158
+ inset: "0",
1159
+ transition: "transform 0.13s, opacity 0.13s",
1160
+ },
1161
+ },
1162
+ vid,
1163
+ playOverlay,
1164
+ );
1165
+ wrap.addEventListener(
1166
+ "mouseenter",
1167
+ () => (playOverlay.style.background = "rgba(0,0,0,0.15)"),
1168
+ );
1169
+ wrap.addEventListener(
1170
+ "mouseleave",
1171
+ () => (playOverlay.style.background = "rgba(0,0,0,0.38)"),
1172
+ );
1173
+ return wrap;
1174
+ }
1175
+
1176
+ return $el("img", {
1177
+ src,
1178
+ loading: "lazy",
1179
+ style: {
1180
+ position: "absolute",
1181
+ inset: "0",
1182
+ width: "100%",
1183
+ height: "100%",
1184
+ objectFit: "cover",
1185
+ display: "block",
1186
+ transition: "transform 0.13s, opacity 0.13s",
1187
+ },
1188
+ });
1189
+ }
1190
+
1191
+ _makeRatingBar(file) {
1192
+ const stars = [];
1193
+ const rating = () => file.rating ?? 0;
1194
+
1195
+ function refreshStars(hover = -1) {
1196
+ const r = hover >= 0 ? hover : rating();
1197
+ stars.forEach((s, j) => {
1198
+ const on = j < r;
1199
+ s.style.color = on
1200
+ ? hover >= 0
1201
+ ? "#f4d03f"
1202
+ : "#f1c40f"
1203
+ : hover >= 0
1204
+ ? "#777"
1205
+ : "#3a3a3a";
1206
+ });
1207
+ }
1208
+
1209
+ // Exposed so the lightbox can sync the tile after rating from full view.
1210
+ const syncRating = () => refreshStars();
1211
+
1212
+ const bar = $el("div", {
1213
+ style: {
1214
+ position: "absolute",
1215
+ bottom: "0",
1216
+ left: "0",
1217
+ right: "0",
1218
+ display: "flex",
1219
+ justifyContent: "center",
1220
+ gap: "1px",
1221
+ padding: "4px 2px 3px",
1222
+ background: "rgba(0,0,0,0.65)",
1223
+ zIndex: "2",
1224
+ },
1225
+ });
1226
+
1227
+ for (let i = 1; i <= 5; i++) {
1228
+ const star = $el("span", {
1229
+ textContent: "β˜…",
1230
+ style: {
1231
+ color: i <= rating() ? "#f1c40f" : "#3a3a3a",
1232
+ fontSize: "12px",
1233
+ cursor: "pointer",
1234
+ lineHeight: "1",
1235
+ padding: "0 1px",
1236
+ },
1237
+ });
1238
+ star.addEventListener("click", (e) => {
1239
+ e.stopPropagation();
1240
+ file.rating = i === file.rating ? 0 : i;
1241
+ refreshStars();
1242
+ this._saveRating(file);
1243
+ });
1244
+ star.addEventListener("mouseenter", () => refreshStars(i));
1245
+ stars.push(star);
1246
+ bar.appendChild(star);
1247
+ }
1248
+
1249
+ bar.addEventListener("mouseleave", () => refreshStars());
1250
+ return { bar, syncRating };
1251
+ }
1252
+
1253
+ // ── Rating save ───────────────────────────────────────────────────────────
1254
+
1255
+ async _saveRating(file) {
1256
+ try {
1257
+ await api.fetchApi("/gallery/rate", {
1258
+ method: "POST",
1259
+ headers: { "Content-Type": "application/json" },
1260
+ body: JSON.stringify({
1261
+ filename: file.filename,
1262
+ subfolder: file.subfolder,
1263
+ rating: file.rating ?? 0,
1264
+ }),
1265
+ });
1266
+ } catch (err) {
1267
+ console.error("[Gallery] Rating save failed:", err);
1268
+ }
1269
+ }
1270
+
1271
+ // ── Scroll ────────────────────────────────────────────────────────────────
1272
+
1273
+ _onScroll() {
1274
+ const { scrollTop, scrollHeight, clientHeight } = this._scrollEl;
1275
+ if (scrollHeight - scrollTop - clientHeight < 300) this._loadMore();
1276
+ }
1277
+
1278
+ // ── Badge (new items) ─────────────────────────────────────────────────────
1279
+
1280
+ showBadge(n) {
1281
+ this._badge.textContent = n > 9 ? "9+" : String(n);
1282
+ this._badge.style.display = "flex";
1283
+ }
1284
+
1285
+ _hideBadge() {
1286
+ this._badge.style.display = "none";
1287
+ }
1288
+
1289
+ scrollToTop() {
1290
+ this._scrollEl.scrollTo({ top: 0, behavior: "smooth" });
1291
+ }
1292
+ }
1293
+
1294
+ // ─── Extension ────────────────────────────────────────────────────────────────
1295
+
1296
+ app.registerExtension({
1297
+ name: "Comfy.OutputGallery",
1298
+
1299
+ async setup() {
1300
+ let panel = null;
1301
+
1302
+ const tabDef = {
1303
+ id: "output-gallery",
1304
+ icon: "pi pi-images",
1305
+ title: "Gallery",
1306
+ tooltip: "Output Gallery β€” browse, rate, select & download",
1307
+ type: "custom",
1308
+ render(el) {
1309
+ panel = new GalleryPanel(el);
1310
+ },
1311
+ };
1312
+
1313
+ if (app.extensionManager?.registerSidebarTab) {
1314
+ app.extensionManager.registerSidebarTab(tabDef);
1315
+ } else {
1316
+ _attachFallback(() => {
1317
+ if (!panel) {
1318
+ const win = _floatingWindow();
1319
+ panel = new GalleryPanel(win.body);
1320
+ }
1321
+ });
1322
+ }
1323
+
1324
+ // Incrementally add new files after every completed workflow
1325
+ // without clearing or re-rendering the existing grid.
1326
+ api.addEventListener("execution_success", async () => {
1327
+ await new Promise((r) => setTimeout(r, 600));
1328
+ if (panel) panel.incrementalUpdate();
1329
+ });
1330
+ },
1331
+ });
1332
+
1333
+ // ─── Fallback helpers ─────────────────────────────────────────────────────────
1334
+
1335
+ function _attachFallback(onClick) {
1336
+ document.body.appendChild(
1337
+ $el("button", {
1338
+ textContent: "πŸ–Ό Gallery",
1339
+ onclick: onClick,
1340
+ style: {
1341
+ position: "fixed",
1342
+ bottom: "16px",
1343
+ right: "16px",
1344
+ zIndex: "9000",
1345
+ background: "#2a2a2a",
1346
+ color: "#ccc",
1347
+ border: "1px solid #444",
1348
+ borderRadius: "8px",
1349
+ padding: "8px 14px",
1350
+ fontSize: "13px",
1351
+ cursor: "pointer",
1352
+ },
1353
+ }),
1354
+ );
1355
+ }
1356
+
1357
+ function _floatingWindow() {
1358
+ const overlay = $el("div", {
1359
+ style: {
1360
+ position: "fixed",
1361
+ inset: "0",
1362
+ zIndex: "9500",
1363
+ background: "rgba(0,0,0,0.6)",
1364
+ display: "flex",
1365
+ alignItems: "center",
1366
+ justifyContent: "center",
1367
+ },
1368
+ onclick: (e) => {
1369
+ if (e.target === overlay) overlay.remove();
1370
+ },
1371
+ });
1372
+ const win = $el("div", {
1373
+ style: {
1374
+ width: "min(680px,92vw)",
1375
+ height: "min(780px,88vh)",
1376
+ background: "#181818",
1377
+ borderRadius: "10px",
1378
+ display: "flex",
1379
+ flexDirection: "column",
1380
+ overflow: "hidden",
1381
+ boxShadow: "0 20px 60px rgba(0,0,0,0.7)",
1382
+ },
1383
+ });
1384
+ overlay.appendChild(win);
1385
+ document.body.appendChild(overlay);
1386
+ return { body: win };
1387
+ }