Compare commits

...
48 Commits
Author SHA1 Message Date
m0rtus59 1a848e2b00 theme consistency fix 2026-11-08 20:34:49 +05:00
m0rtus59 700b85408c DRYing 2026-11-08 20:24:09 +05:00
m0rtus59 6a0b0cd71a wtf, single button keybindings don't work in comfy frontend, did nothing to fix it, just removed some junk 2026-11-08 19:16:44 +05:00
m0rtus59 56452eb855 API optimizations 2026-11-08 18:18:50 +05:00
m0rtus59 81d98f908b Improved themes 2026-11-07 21:56:15 +05:00
M0rtus59 cad4098496 UI/UX improvements 2026-11-06 16:35:46 +05:00
m0rtus59 6c3422e5c0 gallery improve nav panel usability 2026-11-05 23:57:51 +05:00
m0rtus59 2554e6dc45 New Gallery sidebar (optional) 2026-11-05 23:20:44 +05:00
m0rtus59 cc8337f6e6 Update compatibility with the latest frontend version 2026-11-04 17:34:28 +05:00
m0rtus59 b4a21ef852 update node renumber script for latest backend 2026-10-25 22:28:51 +05:00
M0rtus59 65e53946d2 fix 'properties' button dupe 2026-10-18 21:47:14 +05:00
m0rtus59 b1d784e9e4 version bump 2026-10-17 11:14:57 +05:00
m0rtus59 2b91e5ef72 update locales 2026-10-17 11:13:53 +05:00
m0rtus59 717bb901e5 add locales 2026-10-17 09:53:10 +05:00
m0rtus59 426c7d5bd0 better compatibility with the recent frontend UI update 2026-10-14 22:56:51 +05:00
m0rtus59 4707921f81 improve ghost cards cleaning 2026-10-14 22:42:02 +05:00
m0rtus59 01b5b36522 improve 'comfy layout' toggle logic 2026-10-09 20:53:18 +05:00
m0rtus59 5068f155bc improved canvas toolbar docking logic 2026-10-09 20:10:20 +05:00
m0rtus59 f5074d5aec Fix preview memory leaks, false cancelled runs, and double-decker cards
- Fixed memory leak by revoking live preview blob URLs

- Fixed race condition that falsely marked completed runs as Cancelled

- Fixed double-decker card layout: 3D, Audio, and File cards now embed workflow images as background thumbnails

- Fixed Runtime Preview mode failing to deactivate after closing Text or 3D viewers

- Prevented video dimensions from leaking onto 3D and Audio cards

- Sorted workflow outputs by canvas execution order so final node output is always prioritized

- Fixed Windows Explorer failing to highlight files when paths have spaces
2026-10-02 22:45:24 +05:00
m0rtus59 bbbbb7b686 add hide canvas controls panel toggle 2026-10-02 21:09:34 +05:00
m0rtus59 daadd7c2ac Improvement 2026-10-01 20:54:33 +05:00
m0rtus59 9a7981d675 Add a toggle to unfloat the bottom floating toolbar 2026-09-28 00:05:49 +05:00
m0rtus59 d4bc6b1849 Improved tab stacking layout. Restored 'avatar' button with an optional toggle 2026-09-27 22:28:51 +05:00
m0rtus59 78264c385a Update readme 2026-09-26 20:57:13 +05:00
m0rtus59 479ae0b73f Update readme 2026-09-26 20:55:43 +05:00
m0rtus59 25520c8612 Update readme. Fix compare slider. Version bump 2026-09-26 20:19:06 +05:00
m0rtus59 949220a260 New 'runtime preview' mode 2026-09-26 00:09:42 +05:00
m0rtus59 e3d943a353 More fullscreen preview improvements 2026-09-25 22:09:07 +05:00
m0rtus59 929928aa97 Fullscreen preview improvements 2026-09-25 21:52:16 +05:00
m0rtus59 dc868f298f Cache integrity check fix 2026-09-25 21:13:14 +05:00
m0rtus59 cdd4d399c8 Add comfy registry icon 2026-09-18 21:41:12 +05:00
m0rtus59 70c8e64c4e More hardening. File deletion logic improvements 2026-09-18 21:04:55 +05:00
m0rtus59 1f3c3cb598 hardening 2026-09-17 22:11:32 +05:00
m0rtus59 0238cf109d New 'reset node IDs' function to ensure the final output node is always prioritized as the primary preview 2026-09-17 02:04:43 +05:00
m0rtus59 869d3b9a28 fixes 2026-09-13 19:37:54 +05:00
m0rtus59 f09e2c7921 Improve card stacking for multiple column setup 2026-09-13 11:37:31 +05:00
m0rtus59 9adfb2a53f Improve 'view intermediate' button logic 2026-09-12 22:04:51 +05:00
m0rtus59 a17314673e Job preview fixes and improvements 2026-09-11 00:59:32 +05:00
m0rtus59 8343f216fc Refactor. Improve light theme compatibility. Add offline 3D viewer & CSP support. Improve file deletion logic 2026-09-10 21:57:14 +05:00
m0rtus59 3e7448dd80 fix: workflow persistence on restart, card copy button, and submenu stability 2026-09-06 20:57:34 +05:00
m0rtus59 b93413a729 fixes and improvements 2026-08-28 23:02:52 +05:00
m0rtus59 782d30b490 add ctrl+click for alt actions on cards 2026-08-28 22:02:42 +05:00
m0rtus59 0a2db6b85f add support for misc files 2026-08-28 21:32:46 +05:00
m0rtus59 5a4c9f99a5 improve preview, drag-drop, and queue handling 2026-08-28 20:38:46 +05:00
m0rtus59 141a0872d5 minor fixes 2026-08-22 18:12:03 +05:00
m0rtus59 108ac61bec bump 2026-08-22 17:50:24 +05:00
m0rtus59 b31cfb5f8a remove duplicate tip 2026-08-22 15:48:22 +05:00
M0rtus59 fe154b7787 Refactor overlay system, debounce state saving, and fix pending card controls
- Unified Overlay System: Reusable SidebarOverlay for all viewers.

- Performance: Debounced localStorage persistence to prevent UI stutters.

- Memory Cleanup: Proper disposal of global document/API listeners.

- UI Fix: Pending/active cards only show cancel button on hover.
2026-08-14 23:40:07 +05:00
72 changed files with 11875 additions and 4077 deletions
+4 -1
View File
@@ -1,2 +1,5 @@
__pycache__/
*.pyc
*.pyc
Thumbs.db
.DS_Store
desktop.ini
+50 -31
View File
@@ -1,65 +1,84 @@
# ComfyUI-ComfySidebar
A compact sidebar for ComfyUI that replaces the stock queue/history UI with a faster way to browse, preview, compare, and manage generation results.
> ⚠️ **Note:** This repository was developed collaboratively with AI. While it is fully functional and has been tested, there is always room for optimization. If you have ideas for improvements, contributions via Pull Requests are highly welcome!
A compact and powerful layout overhaul for ComfyUI that makes generation results easier to browse, preview, compare, and manage.
## ✨ Features
* Browse generation results in a compact grid.
* Drag results back onto the canvas to restore workflows.
* Drag images directly into `LoadImage` and compatible input nodes.
* Preview images, videos, and text outputs.
* Compare two results side by side with `Shift+Click`.
* Download generated files or workflow JSON directly from result cards.
* Show queue progress and the node currently being executed.
* Hide sidebar tabs and UI elements you don't use.
* Optionally replace the stock Job History sidebar.
* Optional unified top bar for workflow tabs and controls.
* Exclude selected nodes from sidebar results with `Ctrl+Q`.
* **Compact, information-dense layout** with visual previews that let you see what is happening at a glance. Optional UI elements and sidebar tabs can be hidden when you don't need them.
<img width="385" height="336" alt="image" src="https://github.com/user-attachments/assets/743fbf85-9281-4561-9dd0-cd9af4d8c0e4" />
<img src="assets/layout.png" alt="ComfySidebar layout" width="100%">
* **Left or right side:** Choose which side the sidebar appears on in ComfyUI settings.
* **Simplified mouse-friendly workflow** with drag-and-drop support and convenient actions for moving results back into the workflow, opening files, and managing outputs. Hold `Ctrl` for extra actions such as opening an image's location or deleting it directly from your device.
<img src="assets/controls.png" alt="ComfySidebar controls overview" width="100%">
* **Built-in comparison tool** for quickly comparing two generated results side by side.
<img src="assets/compare.png" alt="ComfySidebar compare" width="100%">
* **[NEW] Output Gallery sidebar:** Browse files and subfolders directly from your ComfyUI `output` directory without leaving the interface. Features dedicated cards for images, videos, audio, and 3D assets (`.glb`/`.gltf`), breadcrumb navigation, prompt metadata search across subfolders, and persistent sorting.
* **Runtime preview mode** combined with workflow overview makes ComfyUI practical for running and monitoring workflows in a more streamlined, queue-oriented way.
<img src="assets/runtime.png" alt="ComfySidebar runtime mode" width="100%">
## 🛠️ Installation
Clone the repository directly into your ComfyUI custom nodes directory:
### ComfyUI Registry
Install directly from the ComfyUI Manager or run:
```bash
comfy node install comfy-sidebar
```
ComfySidebar is available on the [ComfyUI Registry](https://registry.comfy.org/publishers/soundslikethunder/nodes/comfy-sidebar).
### Manual installation
Clone the repository into your ComfyUI custom nodes directory:
```bash
cd /path/to/ComfyUI/custom_nodes
git clone https://github.com/m0rtus59/ComfyUI-ComfySidebar.git
```
Restart your ComfyUI server and refresh the browser tab.
Restart ComfyUI and refresh the browser.
## ⚙️ Configuration
## ⚙️ Settings
Open **Settings → Comfy Sidebar** to configure:
* Queue grid layout
* Result aspect ratio
* Queue layout and column width
* Queue display mode
* Working node display
* Automatic cleanup of cancelled/failed jobs
* Automatic cleanup of cancelled or failed jobs
* Sidebar tabs to hide
* Stock Job History replacement
* Graph button visibility
* Unified top bar layout
* Permanent deletion behavior
* Output Gallery sidebar toggle
## ⌨️ Shortcuts
## ⌨️ Controls
| Shortcut | Action |
| ------------- | -------------------------------------------------- |
| `Q` | Toggle ComfySidebar |
| `Ctrl+Q` | Toggle sidebar output filtering for selected nodes |
| `Click` | Open result preview |
| `Shift+Click` | Compare another result |
| Shortcut | Action |
| ------------- | ---------------------------------------------- |
| `Q` | Toggle ComfySidebar |
| `Ctrl+Q` | Exclude the selected node from sidebar results |
| `Alt+R` | Renumber nodes in execution order |
| `Click` | Open result preview |
| `Shift+Click` | Compare another result |
| `Ctrl+Click` | Open the file location / alternative action |
You can also use the available actions from result cards, the sidebar header, and the node/canvas context menus.
## 📝 Notes
ComfySidebar integrates with the ComfyUI frontend and therefore depends on parts of its UI structure. Frontend changes in ComfyUI may require corresponding updates to this extension.
ComfySidebar integrates with the ComfyUI frontend and depends on parts of its UI structure. Frontend changes in ComfyUI may require updates to this extension.
## License
See [LICENSE](LICENSE).
See [LICENSE](LICENSE).
+332 -4
View File
@@ -1,8 +1,336 @@
# Standard ComfyUI extension loader
import os
import platform
import subprocess
import json
from aiohttp import web
from server import PromptServer
import folder_paths
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
# Tells ComfyUI to serve and load the contents of the js/ folder
WEB_DIRECTORY = "./js"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
def is_path_safe(base_dir, target_path):
"""Prevents Path Traversal attacks."""
real_base = os.path.realpath(base_dir)
real_target = os.path.realpath(target_path)
try:
# commonpath reliably handles OS-specific case sensitivity and slash logic
return os.path.commonpath([real_base, real_target]) == real_base
except ValueError:
# Raised if paths are on different drives on Windows
return False
def get_all_candidate_roots(subfolder="", folder_type="output"):
"""Gathers all potential ComfyUI base directories (output, model folders, extra paths)."""
roots = []
try:
roots.append(folder_paths.get_output_directory())
except Exception:
pass
# Include specific model categories (loras, checkpoints, etc.)
categories = ["loras", "checkpoints", "vae", "unet", "clip", "embeddings", "upscale_models"]
if subfolder and subfolder in folder_paths.folder_names_and_paths:
try:
roots.extend(folder_paths.get_folder_paths(subfolder))
except Exception:
pass
for cat in categories:
try:
roots.extend(folder_paths.get_folder_paths(cat))
except Exception:
pass
try:
roots.append(folder_paths.get_input_directory())
roots.append(folder_paths.get_temp_directory())
except Exception:
pass
# Deduplicate while preserving existence
unique = []
for r in roots:
if r and r not in unique and os.path.exists(r):
unique.append(r)
return unique
def resolve_existing_path(filename="", subfolder="", folder_type="output", candidate_roots=None):
"""Finds the actual location of a file or folder across all candidate root directories."""
candidates = candidate_roots if candidate_roots is not None else get_all_candidate_roots(subfolder, folder_type)
if filename:
for root in candidates:
if subfolder:
p1 = os.path.join(root, subfolder, filename)
if os.path.isfile(p1) and is_path_safe(root, p1):
return p1, root
p2 = os.path.join(root, filename)
if os.path.isfile(p2) and is_path_safe(root, p2):
return p2, root
for root in candidates:
if subfolder:
d1 = os.path.join(root, subfolder)
if os.path.isdir(d1) and is_path_safe(root, d1):
return d1, root
if os.path.isdir(root):
return root, root
return None, None
def open_file_in_os(target_path):
"""Fast, native cross-platform explorer launch."""
system = platform.system()
if system == "Windows":
norm_path = os.path.normpath(target_path)
if not os.path.exists(norm_path):
raise FileNotFoundError(f"Path not found: {norm_path}")
if os.path.isfile(norm_path):
# Use raw command string so Windows Explorer correctly parses /select,"path"
subprocess.Popen(f'explorer /select,"{norm_path}"')
else:
subprocess.Popen(f'explorer "{norm_path}"')
elif system == "Darwin": # macOS
if not os.path.exists(target_path):
raise FileNotFoundError(f"Path not found: {target_path}")
if os.path.isfile(target_path):
subprocess.Popen(["open", "-R", target_path])
else:
subprocess.Popen(["open", target_path])
else: # Linux / Unix
folder = os.path.dirname(target_path) if os.path.isfile(target_path) else target_path
if not os.path.exists(folder):
raise FileNotFoundError(f"Path not found: {folder}")
if "DISPLAY" in os.environ or "WAYLAND_DISPLAY" in os.environ:
subprocess.Popen(["xdg-open", folder], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
raise RuntimeError("Headless Linux server detected (no desktop GUI available).")
def check_png_prompt_match(filepath, search_term):
"""Checks PNG prompt metadata strictly for text inputs matching search."""
try:
with open(filepath, "rb") as f:
if f.read(8) != b"\x89PNG\r\n\x1a\n":
return False
while True:
len_b = f.read(4)
if len(len_b) < 4:
break
length = int.from_bytes(len_b, "big")
ctype = f.read(4)
if ctype in (b"tEXt", b"iTXt"):
data = f.read(length)
if data.startswith(b"prompt\x00") or b'"inputs"' in data:
text = data.decode("utf-8", errors="ignore")
idx = text.find("{")
if idx != -1:
try:
prompt_dict = json.loads(text[idx:])
for node in prompt_dict.values():
if isinstance(node, dict) and "inputs" in node:
for val in node["inputs"].values():
if isinstance(val, str) and search_term in val.lower():
return True
except Exception:
pass
elif ctype in (b"IDAT", b"IEND"):
break
else:
f.seek(length, 1)
f.seek(4, 1)
return False
except Exception:
return False
@PromptServer.instance.routes.get("/comfy-sidebar/gallery/list")
async def gallery_list_handler(request):
try:
subfolder = request.query.get("subfolder", "").strip().strip("/\\")
search = request.query.get("search", "").strip().lower()
output_dir = folder_paths.get_output_directory()
target_dir = os.path.realpath(os.path.join(output_dir, subfolder)) if subfolder else os.path.realpath(output_dir)
if not is_path_safe(output_dir, target_dir):
return web.json_response({"error": "Unsafe path"}, status=403)
if not os.path.exists(target_dir) or not os.path.isdir(target_dir):
return web.json_response({"subfolder": subfolder, "folders": [], "files": []})
folders = []
files = []
supported_exts = {
".png", ".jpg", ".jpeg", ".webp", ".gif", ".avif",
".mp4", ".webm", ".mov", ".mkv",
".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac",
".glb", ".gltf", ".obj", ".fbx", ".stl",
".json"
}
if search:
# Recursive search in current directory and all subfolders
for root, dirs, fnames in os.walk(target_dir):
dirs[:] = [d for d in dirs if not d.startswith(".")]
for fname in fnames:
if fname.startswith("."):
continue
ext = os.path.splitext(fname)[1].lower()
if ext in supported_exts:
fpath = os.path.join(root, fname)
matched = search in fname.lower()
if not matched and ext == ".png":
matched = check_png_prompt_match(fpath, search)
if matched:
rel_sub = os.path.relpath(root, output_dir).replace("\\", "/")
if rel_sub == ".":
rel_sub = ""
stat = os.stat(fpath)
files.append({
"filename": fname,
"subfolder": rel_sub,
"type": "output",
"mtime": stat.st_mtime,
"size": stat.st_size
})
else:
# Instant single-directory listing without reading files from disk
with os.scandir(target_dir) as entries:
for entry in entries:
if entry.name.startswith("."):
continue
try:
if entry.is_dir(follow_symlinks=False):
rel_sub = os.path.relpath(entry.path, output_dir).replace("\\", "/")
folders.append({
"name": entry.name,
"subfolder": rel_sub,
"mtime": entry.stat().st_mtime
})
elif entry.is_file(follow_symlinks=False):
ext = os.path.splitext(entry.name)[1].lower()
if ext in supported_exts:
rel_sub = os.path.relpath(os.path.dirname(entry.path), output_dir).replace("\\", "/")
if rel_sub == ".":
rel_sub = ""
stat = entry.stat()
files.append({
"filename": entry.name,
"subfolder": rel_sub,
"type": "output",
"mtime": stat.st_mtime,
"size": stat.st_size
})
except (PermissionError, FileNotFoundError):
continue
folders.sort(key=lambda x: x["name"].lower())
files.sort(key=lambda x: x["mtime"], reverse=True)
return web.json_response({
"subfolder": subfolder.replace("\\", "/"),
"folders": folders,
"files": files
})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
@PromptServer.instance.routes.post("/comfy-sidebar/open-folder")
async def open_folder_handler(request):
try:
data = await request.json()
filename = (data.get("filename") or "").strip()
subfolder = (data.get("subfolder") or "").strip()
folder_type = (data.get("type") or "output").strip()
target_path, _ = resolve_existing_path(filename, subfolder, folder_type)
if not target_path:
target_path = folder_paths.get_output_directory()
open_file_in_os(target_path)
return web.json_response({"success": True, "path": target_path})
except Exception as e:
return web.json_response({"error": str(e)}, status=400)
@PromptServer.instance.routes.post("/comfy-sidebar/delete-file")
async def delete_file_handler(request):
try:
data = await request.json()
filename = (data.get("filename") or "").strip()
subfolder = (data.get("subfolder") or "").strip()
folder_type = (data.get("type") or "output").strip()
if not filename:
return web.json_response({"error": "No filename provided"}, status=400)
# Strictly restrict deletion to generated output and temp files (protects models/checkpoints)
delete_roots = [
folder_paths.get_output_directory(),
folder_paths.get_temp_directory()
]
delete_roots = [os.path.realpath(r) for r in delete_roots if r and os.path.exists(r)]
target_file, root = resolve_existing_path(filename, subfolder, folder_type, candidate_roots=delete_roots)
if not target_file or not os.path.isfile(target_file) or not is_path_safe(root, target_file):
return web.json_response({"error": "File not found or outside output directory"}, status=404)
# Try moving to Recycle Bin / Trash first, fallback to os.remove
permanent = bool(data.get("permanent", False))
action = "deleted"
if not permanent:
try:
import send2trash
send2trash.send2trash(target_file)
action = "trashed"
except Exception:
os.remove(target_file)
action = "deleted"
else:
os.remove(target_file)
action = "deleted"
return web.json_response({"success": True, "deleted": target_file, "action": action})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
@PromptServer.instance.routes.post("/comfy-sidebar/promote-output")
async def promote_output_handler(request):
try:
import shutil
data = await request.json()
raw_filename = (data.get("filename") or "").strip()
filename = os.path.basename(raw_filename)
subfolder = (data.get("subfolder") or "").strip()
folder_type = (data.get("type") or "output").strip()
target_file, root = resolve_existing_path(raw_filename, subfolder, folder_type)
if not target_file or not os.path.isfile(target_file):
return web.json_response({"error": "File not found"}, status=404)
input_dir = folder_paths.get_input_directory()
dest_path = os.path.join(input_dir, filename)
if not is_path_safe(input_dir, dest_path):
return web.json_response({"error": "Unsafe destination path"}, status=403)
shutil.copy2(target_file, dest_path)
return web.json_response({"name": filename})
except Exception as e:
return web.json_response({"error": str(e)}, status=500)
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 789 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 631 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

+385
View File
@@ -0,0 +1,385 @@
import { app } from "/scripts/app.js";
import { SettingIds } from "../core/constants.js";
import { getSetting } from "../core/settings.js";
export function findOriginalPropertiesButton() {
const byTestId = document.querySelector('[data-testid="properties-panel-toggle"]');
if (byTestId && !byTestId.classList.contains("comfy-sidebar-custom-properties-toggle")) {
return byTestId;
}
const icons = document.querySelectorAll('[class*="lucide--panel-right"], [class*="lucide--panel-left"], [class*="lucide--panel-bottom"]');
for (const icon of icons) {
const btn = icon.closest('button, [role="button"], .comfyui-menu-item, .p-button');
if (btn && !btn.classList.contains("comfy-sidebar-custom-properties-toggle")) {
return btn;
}
}
const buttons = document.querySelectorAll('button, [role="button"], .p-button');
for (const btn of buttons) {
if (btn.classList.contains("comfy-sidebar-custom-properties-toggle")) continue;
const title = (btn.getAttribute("title") || btn.getAttribute("aria-label") || "").toLowerCase();
if (title.includes("workflow overview") || title.includes("properties") || title.includes("toggle panel")) {
return btn;
}
}
return null;
}
export function findTopbarContainer() {
const container = document.querySelector('.actionbar-container, [data-testid="action-bar-buttons"], [class*="actionbar-buttons"], .actionbar-buttons, [class*="actionbar"]');
if (container) return container;
const orig = findOriginalPropertiesButton();
if (orig?.parentNode) return orig.parentNode;
const buttons = document.querySelectorAll("button, .p-button");
for (const btn of buttons) {
if (btn.classList.contains("comfy-sidebar-custom-properties-toggle")) continue;
const title = (btn.getAttribute("title") || btn.getAttribute("aria-label") || "").toLowerCase();
if (title.includes("run") || title.includes("manager")) {
if (btn.parentNode) return btn.parentNode;
}
}
return null;
}
export function findPropertiesPanel() {
const testIdPanel = document.querySelector('[data-testid="properties-panel"], [data-testid="workflow-overview-panel"], .properties-panel, [class*="properties-panel"]');
if (testIdPanel && testIdPanel.offsetWidth > 0 && testIdPanel.offsetHeight > 0 && testIdPanel.isConnected) {
return testIdPanel;
}
const headings = document.querySelectorAll('h1, h2, h3, h4, [class*="title"]');
for (const h of headings) {
if (h.textContent.trim().toLowerCase() === "workflow overview" && h.offsetWidth > 0 && h.offsetHeight > 0) {
const container = h.closest('.p-sidebar, .sidebar, aside, [class*="side-panel"], [class*="panel"], [class*="properties"]') || h.parentElement;
if (container && container.offsetWidth > 0 && container !== document.body) {
return container;
}
}
}
const rightSidebars = document.querySelectorAll('.p-sidebar-right, aside.p-sidebar, [class*="p-sidebar-right"]');
for (const sb of rightSidebars) {
if (sb.offsetWidth > 0 && sb.offsetHeight > 0) {
return sb;
}
}
return null;
}
export function isPropertiesPanelOpen() {
const modernOpen = getSetting("Comfy.RightSidePanel.IsOpen");
if (typeof modernOpen === "boolean") {
return modernOpen;
}
const panel = findPropertiesPanel();
if (panel) return true;
const origBtn = findOriginalPropertiesButton();
if (origBtn) {
if (origBtn.classList.contains("p-button-active") ||
origBtn.classList.contains("active") ||
origBtn.getAttribute("aria-expanded") === "true" ||
origBtn.getAttribute("aria-pressed") === "true") {
return true;
}
}
return false;
}
export function findActiveSidebars() {
const leftPanels = [];
const rightPanels = [];
const winW = window.innerWidth;
const midX = winW / 2;
// 1. Check if our Queue sidebar is open and visible
const queueHeader = document.querySelector('.comfy-sidebar-header-root');
if (queueHeader) {
const queueDrawer = queueHeader.closest('.sidebar-content-container, .comfyui-sidebar-content, .p-sidebar, aside') || queueHeader.parentElement;
if (queueDrawer && queueDrawer.offsetWidth > 0 && queueDrawer.offsetHeight > 0 && queueDrawer.isConnected) {
const r = queueDrawer.getBoundingClientRect();
if (r.right > 0 && r.right < midX) {
leftPanels.push(queueDrawer);
}
}
}
// 2. Query all active sidebars and panels across ComfyUI & third-party extensions
const candidates = document.querySelectorAll(
'aside, nav, .comfyui-sidebar, .side-tool-bar-container, .sidebar-content-container, ' +
'.comfyui-sidebar-content, .p-sidebar, [data-testid="properties-panel"], ' +
'[data-testid="workflow-overview-panel"], [data-testid*="sidebar"], .p-sidebar-right'
);
const seen = new Set(leftPanels);
for (const el of candidates) {
if (!el.isConnected || el.offsetWidth < 30 || el.offsetHeight < 120) continue;
if (el.closest('.comfy-sidebar-comparison-overlay, .p-dialog, [role="dialog"], .comfy-modal, .comfy-menu')) continue;
if (seen.has(el)) continue;
seen.add(el);
const rect = el.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0 || rect.top > 150) continue;
// Left-docked panels (Icon bar or an open drawer on the left)
if (rect.left <= 100 && rect.right > 0 && rect.right < midX) {
leftPanels.push(el);
}
// Right-docked panels (Workflow Overview or right inspector drawers)
else if (rect.right >= winW - 80 && rect.left > midX && rect.left < winW) {
rightPanels.push(el);
}
}
return { leftPanels, rightPanels };
}
export function findActiveQueueIndicator() {
const container = findTopbarContainer();
if (!container) return null;
const buttons = container.querySelectorAll("button, .p-button, .comfyui-menu-item");
for (const btn of buttons) {
if (btn.classList.contains("comfy-sidebar-custom-properties-toggle")) continue;
const text = (btn.textContent || "").toLowerCase();
if (text.includes("active") || text.includes("queued") || text.includes("running") || text.includes("pending")) {
return btn;
}
}
return null;
}
export function findNativeExtensionsPanel() {
return Array.from(document.querySelectorAll('.shadow-interface:not(.actionbar-container)'))
.find(el => el.textContent.toLowerCase().includes('extensions') || el.querySelector('button')?.textContent.toLowerCase().includes('extensions'));
}
export function findGraphButton() {
const byTestId = document.querySelector('[data-testid="view-mode-toggle"]');
if (byTestId && !byTestId.closest('.p-dialog, .comfy-modal, [role="dialog"], .p-sidebar, .comfy-settings, .comfyui-sidebar, .comfy-sidebar')) {
return byTestId;
}
const elements = document.querySelectorAll('.p-1.bg-base-background.rounded-lg, .bg-base-background.rounded-lg, .bg-secondary-background.rounded-lg.items-center.inline-flex.pointer-events-auto, [data-testid="graph-view-button"]');
for (const el of elements) {
if (el.closest('.p-dialog, .comfy-modal, [role="dialog"], .p-sidebar, .comfy-settings, .comfyui-sidebar, .comfy-sidebar')) continue;
return el.closest('.group, .p-1') || el;
}
const fallbacks = document.querySelectorAll('button, .bg-base-background, .bg-secondary-background');
for (const el of fallbacks) {
if (el.closest('.p-dialog, .comfy-modal, [role="dialog"], .p-sidebar, .comfy-settings, .comfyui-sidebar, .comfy-sidebar')) continue;
const text = (el.textContent || el.getAttribute("title") || el.getAttribute("aria-label") || "").toLowerCase();
if (text.includes("graph") || text.includes("workflow") || el.querySelector('[class*="sitemap"], [class*="workflow"]')) {
return el.closest('.group, .p-1, .bg-base-background, .bg-secondary-background') || el;
}
}
return null;
}
export function findOurSidebarButton() {
const byTestId = document.querySelector('[data-testid="classic-comfy-sidebar-tab-button"]');
if (byTestId) return byTestId;
const icon = document.querySelector('.pi-images');
return icon ? icon.closest('.comfyui-sidebar-tab, button, [role="tab"]') : null;
}
export function findStandardQueueButton() {
const byTestId = document.querySelector('[data-testid="queue-tab-button"], [data-testid="job-history-tab-button"]');
if (byTestId && !byTestId.id?.includes('classic-comfy-sidebar') && !byTestId.querySelector('.pi-images')) {
return byTestId;
}
for (const iconSelector of [".pi-history", ".pi-clock", ".pi-server", ".pi-list", ".pi-sliders-h", '[class*="lucide--history"]']) {
const icon = document.querySelector(iconSelector);
if (icon) {
const btn = icon.closest('.comfyui-sidebar-tab, button, [role="tab"]');
if (btn && !btn.querySelector('.pi-images')) return btn;
}
}
const buttons = document.querySelectorAll('.comfyui-sidebar-tab, button, [role="tab"]');
for (const btn of buttons) {
const title = btn.title || btn.getAttribute('aria-label') || '';
if ((title.toLowerCase().includes('queue') || title.toLowerCase().includes('history')) &&
!btn.querySelector('.pi-images') &&
!btn.id?.includes('classic-comfy-sidebar')) {
return btn;
}
}
return null;
}
export function updateSidebarBadge(count) {
const btn = findOurSidebarButton();
if (btn) {
let badge = btn.querySelector('.comfy-sidebar-badge');
if (count > 0) {
if (!badge) {
btn.style.position = 'relative';
badge = document.createElement('div');
badge.className = 'comfy-sidebar-badge';
Object.assign(badge.style, {
position: 'absolute', top: '2px', right: '2px', background: '#0ea5e9', color: '#fff',
borderRadius: '50%', width: '16px', height: '16px', fontSize: '10px', display: 'flex',
alignItems: 'center', justifyContent: 'center', fontWeight: 'bold', pointerEvents: 'none'
});
btn.appendChild(badge);
}
badge.textContent = count > 99 ? '99+' : count;
} else if (badge) {
badge.remove();
}
}
}
let isApplyingSidebarOverride = false;
export function findSidebarMenuButton(sidebar) {
const root = sidebar || document.querySelector('[data-testid="sidebar-top-group"]') ||
document.querySelector('.comfyui-sidebar, .comfy-sidebar, .sidebar');
if (!root) return null;
// 1. Look for explicit menu or logo test ID
const byTestId = root.querySelector(
'[data-testid*="menu-button"], [data-testid*="app-menu"], [data-testid*="comfy-logo"], [data-testid="sidebar-menu-button"]'
);
if (byTestId) {
return byTestId.closest('button, [role="button"], .comfyui-sidebar-tab, .comfyui-sidebar-item') || byTestId;
}
// 2. Look for title, tooltip, or aria-label containing "menu"
const candidates = Array.from(root.querySelectorAll('button, [role="button"], a, .comfyui-sidebar-tab, .comfyui-sidebar-item'));
const menuBtn = candidates.find(el => {
if (el.classList.contains('comfy-sidebar-tab') || el.id?.includes('classic-comfy-sidebar')) return false;
const title = (el.getAttribute('title') || el.getAttribute('aria-label') || el.textContent || '').trim().toLowerCase();
return title === 'menu' || title.startsWith('menu');
});
if (menuBtn) return menuBtn;
// 3. Fallback: the first child element that is not our button and not the stock queue button
const ourBtn = findOurSidebarButton();
const stdBtn = findStandardQueueButton();
for (const child of root.children) {
if (child !== ourBtn && child !== stdBtn) {
return child;
}
}
return null;
}
export function applySidebarOverride() {
if (isApplyingSidebarOverride) return;
isApplyingSidebarOverride = true;
try {
const overrideStock = (
getSetting(SettingIds.OVERRIDE_STOCK_HISTORY) ??
getSetting("Comfy Sidebar.Hide Junk.Override Stock Job History Tab") ??
getSetting("Comfy Sidebar.Override Stock History", false)
);
const stdBtn = findStandardQueueButton();
const ourBtn = findOurSidebarButton();
const topGroup = document.querySelector('[data-testid="sidebar-top-group"]') ||
(ourBtn ? ourBtn.closest('[data-testid="sidebar-top-group"]') : null);
if (ourBtn && !ourBtn._capturedOriginal) {
ourBtn._capturedOriginal = true;
ourBtn._originalParent = ourBtn.parentNode;
ourBtn._originalNextSibling = ourBtn.nextSibling;
}
if (overrideStock) {
if (stdBtn) {
if (!stdBtn._originalDisplay) {
stdBtn._originalDisplay = window.getComputedStyle(stdBtn).display || "block";
}
if (stdBtn.style.display !== "none") {
stdBtn.style.setProperty("display", "none", "important");
}
if (!stdBtn._overrideClickListener) {
stdBtn._overrideClickListener = (e) => {
e.preventDefault();
e.stopPropagation();
const b = findOurSidebarButton();
if (b) b.click();
};
stdBtn.addEventListener('click', stdBtn._overrideClickListener, true);
}
}
if (ourBtn) {
const parent = (topGroup && topGroup.contains(ourBtn)) ? topGroup : (stdBtn ? stdBtn.parentNode : ourBtn.parentNode);
if (parent) {
const menuBtn = findSidebarMenuButton(parent);
if (menuBtn && menuBtn.parentNode === parent) {
// Place Queue immediately below the Menu button
if (menuBtn.nextSibling !== ourBtn) {
parent.insertBefore(ourBtn, menuBtn.nextSibling);
}
} else if (stdBtn && stdBtn.parentNode === parent) {
// Place Queue right where stock Job History was
if (stdBtn.previousSibling !== ourBtn && stdBtn !== ourBtn) {
parent.insertBefore(ourBtn, stdBtn);
}
} else {
// Fallback: top of the group
const first = parent.firstElementChild;
if (first && first !== ourBtn) {
parent.insertBefore(ourBtn, first);
}
}
}
}
} else {
if (stdBtn) {
if (stdBtn.style.display === "none") {
stdBtn.style.removeProperty("display");
if (stdBtn._originalDisplay && stdBtn._originalDisplay !== "none") {
stdBtn.style.display = stdBtn._originalDisplay;
}
}
if (stdBtn._overrideClickListener) {
stdBtn.removeEventListener('click', stdBtn._overrideClickListener, true);
stdBtn._overrideClickListener = null;
}
}
if (ourBtn) {
if (ourBtn._originalNextSibling && ourBtn._originalNextSibling.parentNode === ourBtn.parentNode) {
if (ourBtn.nextSibling !== ourBtn._originalNextSibling) {
ourBtn.parentNode.insertBefore(ourBtn, ourBtn._originalNextSibling);
}
} else if (ourBtn._originalParent && ourBtn.parentNode === ourBtn._originalParent) {
if (ourBtn !== ourBtn.parentNode.lastElementChild) {
ourBtn.parentNode.appendChild(ourBtn);
}
}
}
}
} finally {
isApplyingSidebarOverride = false;
}
}
export function centerAndSelectCanvasNode(nodeId) {
if (!app.graph || !app.canvas) return false;
const id = typeof nodeId === "string" ? Number(nodeId) : nodeId;
const node = app.graph.getNodeById ? (app.graph.getNodeById(id) || app.graph.getNodeById(String(nodeId))) : null;
if (node) {
if (app.canvas.centerOnNode) app.canvas.centerOnNode(node);
if (app.canvas.selectNode) app.canvas.selectNode(node);
return true;
}
return false;
}
+1096
View File
File diff suppressed because it is too large Load Diff
+184
View File
@@ -0,0 +1,184 @@
import { app } from "/scripts/app.js";
import { applySidebarOverride } from "./adapter.js";
let nodeDOMObserver = null;
function findHeaderByText(parent, text) {
if (!text) return null;
const cleanText = text.trim();
const elements = parent.querySelectorAll("span, div, h1, h2, h3, h4, p, [class*='title'], [class*='text']");
for (const el of elements) {
if (el.textContent.trim() === cleanText) {
if (el.offsetWidth > 0 && el.offsetHeight > 0 && el.offsetWidth < parent.offsetWidth * 0.9) {
return el;
}
}
}
return null;
}
export function syncNodeVueBadge(node, isIgnored) {
const nodeEl = document.querySelector(
`.comfy-node[data-node-id="${node.id}"], ` +
`[data-node-id="${node.id}"], ` +
`[data-id="${node.id}"]`
);
if (!nodeEl) return;
const titleTextNode = findHeaderByText(nodeEl, node.title || node.type);
if (!titleTextNode) {
const badge = nodeEl.querySelector(".comfy-sidebar-ignore-badge");
if (badge && !isIgnored) badge.remove();
return;
}
const headerEl = titleTextNode.parentNode;
let badge = headerEl.querySelector(".comfy-sidebar-ignore-badge");
if (isIgnored) {
if (!badge) {
badge = document.createElement("div");
badge.className = "comfy-sidebar-ignore-badge";
badge.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/>
<path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/>
<path d="M6.61 6.61A13.52 13.52 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/>
<line x1="2" y1="2" x2="22" y2="22"/>
</svg>
`;
Object.assign(badge.style, {
marginLeft: "auto",
marginRight: "6px",
float: "right",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
color: "inherit",
pointerEvents: "none"
});
headerEl.appendChild(badge);
}
} else {
if (badge) badge.remove();
}
}
export function syncAllNodeBadges() {
applySidebarOverride();
if (!app.graph || !app.graph._nodes) return;
app.graph._nodes.forEach(node => {
if (!node.properties) node.properties = {};
const isIgnored = !!node.properties.ignoreInQueue;
if (isIgnored) {
if (node.boxcolor !== "#ff3333") {
node._oldBoxcolor = node.boxcolor || "";
node.boxcolor = "#ff3333";
if (app.graph) app.graph.setDirtyCanvas(true, true);
}
} else {
if (node.boxcolor === "#ff3333") {
node.boxcolor = node._oldBoxcolor || "";
delete node._oldBoxcolor;
if (app.graph) app.graph.setDirtyCanvas(true, true);
}
}
syncNodeVueBadge(node, isIgnored);
});
}
export function setupVueNodeObserver() {
if (nodeDOMObserver) nodeDOMObserver.disconnect();
let timeoutId = null;
nodeDOMObserver = new MutationObserver((mutations) => {
let hasNodeMutation = false;
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.nodeType === 1) {
if (node.hasAttribute?.("data-node-id") ||
node.classList?.contains("comfy-node") ||
node.querySelector?.('[data-node-id], .comfy-node')) {
hasNodeMutation = true;
break;
}
}
}
if (hasNodeMutation) break;
}
if (hasNodeMutation) {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
syncAllNodeBadges();
}, 50);
}
});
nodeDOMObserver.observe(document.body, {
childList: true,
subtree: true
});
return () => {
if (nodeDOMObserver) {
nodeDOMObserver.disconnect();
nodeDOMObserver = null;
}
};
}
function getSelectedCanvasNodes() {
const canvas = app.canvas;
if (!canvas) return [];
const raw = canvas.selected_nodes;
if (raw instanceof Map || raw instanceof Set) {
return Array.from(raw.values());
}
if (Array.isArray(raw)) return raw;
if (raw && typeof raw === "object") return Object.values(raw);
if (canvas.current_active_node) return [canvas.current_active_node];
return [];
}
export function toggleIgnoreActiveNode(onModified) {
const canvas = app.canvas;
if (!canvas) return;
const nodes = getSelectedCanvasNodes();
if (nodes.length === 0) return;
nodes.forEach(node => {
if (!node.properties) node.properties = {};
node.properties.ignoreInQueue = !node.properties.ignoreInQueue;
const isIgnored = !!node.properties.ignoreInQueue;
if (isIgnored) {
if (node.boxcolor !== "#ff3333") {
node._oldBoxcolor = node.boxcolor || "";
node.boxcolor = "#ff3333";
}
} else {
if (node.boxcolor === "#ff3333") {
node.boxcolor = node._oldBoxcolor || "";
delete node._oldBoxcolor;
}
}
syncNodeVueBadge(node, isIgnored);
});
if (app.graph) {
if (app.graph.change) app.graph.change();
app.graph.setDirtyCanvas(true, true);
}
if (app.canvas) app.canvas.setDirty(true, true);
if (typeof onModified === "function") {
onModified();
}
}
+32
View File
@@ -0,0 +1,32 @@
export const PromptStatus = Object.freeze({
PENDING: "pending",
ACTIVE: "active",
COMPLETED: "completed",
CANCELLED: "cancelled",
ERROR: "error"
});
export const StoreEvents = Object.freeze({
PROMPT_ADDED: "prompt:added",
PROMPT_UPDATED: "prompt:updated",
PROMPT_DELETED: "prompt:deleted",
PROMPTS_CLEARED: "prompts:cleared",
ACTIVE_PROMPT_CHANGED: "activePrompt:changed",
SEARCH_CHANGED: "search:changed",
SUBMENU_CHANGED: "submenu:changed",
QUEUE_SYNCED: "queue:synced"
});
export const SettingIds = Object.freeze({
GRID_COLUMNS_THRESHOLD: "Comfy Sidebar.Grid Columns Threshold",
SHOW_PENDING_COUNT_ONLY: "Comfy Sidebar.Show Pending Count Only",
SHOW_WORKING_NODE_NAME: "Comfy Sidebar.Show Working Node Name",
AUTO_CLEAR_INTERRUPTED: "Comfy Sidebar.Auto Clear Interrupted",
OVERRIDE_STOCK_HISTORY: "Comfy Sidebar.Hide Junk.Override Stock Job History Tab",
HIDE_GRAPH_BUTTON: "Comfy Sidebar.Hide Junk.Graph Button",
CLASSIC_LAYOUT: "Comfy Sidebar.Comfy Layout",
MAX_HISTORY_ITEMS: "Comfy.Queue.MaxHistoryItems",
DOCK_QUEUE: "Comfy.Queue.QPOV2",
SHOW_PROGRESS_BAR: "Comfy.Queue.ShowRunProgressBar",
TAB_POSITION: "Comfy.Workflow.WorkflowTabsPosition"
});
+70
View File
@@ -0,0 +1,70 @@
import { app } from "/scripts/app.js";
let currentLocale = "en";
let translations = {};
let fallbackTranslations = {};
async function fetchLocaleFiles(lang) {
const data = {};
for (const file of ["main.json", "settings.json"]) {
try {
const url = new URL(`../locales/${lang}/${file}`, import.meta.url).href;
const res = await fetch(url);
if (res.ok) {
const json = await res.json();
Object.assign(data, json);
}
} catch (e) {}
}
return data;
}
export async function initI18n() {
try {
let settingVal = app?.extensionManager?.setting?.get?.("Comfy.Locale")
|| app?.ui?.settings?.getSettingValue?.("Comfy.Locale")
|| app?.extensionManager?.setting?.get?.("Comfy.Locale.Language")
|| app?.ui?.settings?.getSettingValue?.("Comfy.Locale.Language");
if (!settingVal) {
try {
settingVal = localStorage.getItem("Comfy.Settings.Comfy.Locale")
|| localStorage.getItem("Comfy.Locale");
} catch (e) {}
}
const raw = (settingVal || "en").toLowerCase().replace("_", "-");
const candidates = [raw];
const base = raw.split("-")[0];
if (base !== raw) candidates.push(base);
currentLocale = candidates[0];
console.log("[ComfySidebar] Detected locale:", currentLocale);
// 1. Load English fallback
fallbackTranslations = await fetchLocaleFiles("en");
// 2. Load active locale if not English
if (base !== "en") {
for (const cand of candidates) {
const locData = await fetchLocaleFiles(cand);
if (Object.keys(locData).length > 0) {
translations = locData;
console.log(`[ComfySidebar] Loaded ${cand} with ${Object.keys(translations).length} translations`);
break;
}
}
}
} catch (e) {
console.warn("[ComfySidebar] i18n initialization failed", e);
}
}
export function t(key, vars = {}) {
if (!key) return "";
let str = translations[key] || fallbackTranslations[key] || key;
for (const [k, v] of Object.entries(vars)) {
str = str.replaceAll(`{${k}}`, v);
}
return str;
}
+87
View File
@@ -0,0 +1,87 @@
import { PromptStatus } from "./constants.js";
const STORAGE_KEY = "comfy_sidebar_prompt_states";
export const PersistenceAdapter = {
load() {
try {
const data = localStorage.getItem(STORAGE_KEY);
if (!data) return [];
const list = JSON.parse(data);
return Array.isArray(list) ? list : [];
} catch (e) {
console.warn("Comfy Sidebar: Failed to load states from localStorage", e);
return [];
}
},
save(promptsMap) {
try {
const serializable = [];
for (const [pid, state] of promptsMap.entries()) {
const cleanedImages = (state.images || []).map(img => {
if (img && img.url && img.url.startsWith("blob:")) return null;
return img;
}).filter(Boolean);
const includeWorkflow = cleanedImages.length === 0 || state.status !== PromptStatus.COMPLETED;
serializable.push({
pid: String(state.pid),
status: state.status,
images: cleanedImages,
texts: state.texts || [],
nodeOutputs: state.nodeOutputs || {},
nodeTitles: state.nodeTitles || {}, // Always preserved across restarts
workflow: includeWorkflow ? state.workflow : null,
progress: state.progress || 0,
queueNumber: state.queueNumber,
progressText: state.progressText || "",
timestamp: state.timestamp,
activeNodeName: state.activeNodeName || "",
rendered: !!state.rendered,
startTime: state.startTime,
endTime: state.endTime,
duration: state.duration
});
}
if (serializable.length === 0) {
localStorage.removeItem(STORAGE_KEY);
return;
}
serializable.sort((a, b) => a.timestamp - b.timestamp);
while (serializable.length > 0) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(serializable));
break;
} catch (e) {
if (e.name === "QuotaExceededError" || e.code === 22 || e.code === 1014) {
serializable.shift();
} else {
console.warn("Comfy Sidebar: LocalStorage error", e);
break;
}
}
}
} catch (e) {
console.warn("Comfy Sidebar: Failed to serialize states", e);
}
},
getPruneCandidates(promptsMap, maxItems = 64) {
const finished = Array.from(promptsMap.entries())
.filter(([_, state]) => state.status !== PromptStatus.PENDING && state.status !== PromptStatus.ACTIVE);
finished.sort((a, b) => (a[1].timestamp || 0) - (b[1].timestamp || 0));
if (finished.length > maxItems) {
const deleteCount = finished.length - maxItems;
return finished.slice(0, deleteCount).map(([pid]) => pid);
}
return [];
}
};
+80
View File
@@ -0,0 +1,80 @@
import { PromptStatus } from "./constants.js";
export function createPromptState(pid, initial = {}) {
return {
pid: String(pid),
status: initial.status || PromptStatus.PENDING,
images: Array.isArray(initial.images) ? [...initial.images] : [],
texts: Array.isArray(initial.texts) ? [...initial.texts] : [],
nodeOutputs: initial.nodeOutputs ? { ...initial.nodeOutputs } : {},
nodeTitles: initial.nodeTitles ? { ...initial.nodeTitles } : {},
progress: typeof initial.progress === "number" ? initial.progress : 0,
progressText: initial.progressText || "",
queueNumber: initial.queueNumber || null,
timestamp: typeof initial.timestamp === "number" ? initial.timestamp : Date.now(),
workflow: initial.workflow || null,
activeNodeName: initial.activeNodeName || "",
startTime: initial.startTime || null,
endTime: initial.endTime || null,
duration: typeof initial.duration === "number" ? initial.duration : null,
rendered: !!initial.rendered,
_previewBlobUrl: initial._previewBlobUrl || null,
_oldPreviewBlobUrl: initial._oldPreviewBlobUrl || null
};
}
export function revokePromptBlobs(state) {
if (!state) return;
if (state._previewBlobUrl) {
try { URL.revokeObjectURL(state._previewBlobUrl); } catch (e) {}
state._previewBlobUrl = null;
}
if (state._oldPreviewBlobUrl) {
try { URL.revokeObjectURL(state._oldPreviewBlobUrl); } catch (e) {}
state._oldPreviewBlobUrl = null;
}
}
export function activatePrompt(state, patch = {}) {
state.status = PromptStatus.ACTIVE;
state.progress = 0;
state.progressText = "Processing...";
state.rendered = false;
state.startTime = state.startTime || Date.now();
state.duration = null;
state._hasValidatedIntermediates = true; // New live prompt; files are fresh
if (patch.workflow) state.workflow = patch.workflow;
if (patch.activeNodeName !== undefined) state.activeNodeName = patch.activeNodeName;
if (patch.nodeTitles) Object.assign(state.nodeTitles, patch.nodeTitles);
if (typeof patch.timestamp === "number") state.timestamp = patch.timestamp;
return state;
}
export function updatePromptProgress(state, progress, activeNodeName = null) {
state.progress = Math.max(0, Math.min(100, Math.round(progress)));
if (activeNodeName !== null) {
state.activeNodeName = activeNodeName;
}
return state;
}
export function finalizePrompt(state, targetStatus, patch = {}) {
// Only revoke blobs if not cancelled; preserve the preview so the user can inspect the cancelled step
if (targetStatus !== PromptStatus.CANCELLED && state.status !== PromptStatus.CANCELLED) {
revokePromptBlobs(state);
}
state.status = targetStatus;
state.progressText = "";
state.rendered = false;
state._hasValidatedIntermediates = true; // Live session generation; files are fresh
state.endTime = patch.endTime || Date.now();
if (state.startTime) {
state.duration = (state.endTime - state.startTime) / 1000;
}
if (patch.workflow) state.workflow = patch.workflow;
if (patch.nodeOutputs) state.nodeOutputs = patch.nodeOutputs;
if (patch.nodeTitles) Object.assign(state.nodeTitles, patch.nodeTitles);
if (patch.images && patch.images.length > 0) state.images = patch.images;
if (patch.texts && patch.texts.length > 0) state.texts = patch.texts;
return state;
}
+27
View File
@@ -0,0 +1,27 @@
import { app } from "/scripts/app.js";
/**
* Safely retrieves a setting value from ComfyUI's extension manager or legacy settings.
*/
export function getSetting(id, fallback = undefined) {
const settings = app.extensionManager?.setting;
if (settings?.get) {
const val = settings.get(id);
if (val !== undefined && val !== null) return val;
}
const legacyVal = app.ui?.settings?.getSettingValue?.(id);
if (legacyVal !== undefined && legacyVal !== null) return legacyVal;
return fallback;
}
/**
* Safely sets a setting value across modern extensionManager and legacy UI settings.
*/
export function setSetting(id, value) {
const settings = app.extensionManager?.setting;
if (settings?.set) {
settings.set(id, value);
return;
}
app.ui?.settings?.setSettingValue?.(id, value);
}
+189
View File
@@ -0,0 +1,189 @@
import { PromptStatus, StoreEvents } from "./constants.js";
import { createPromptState, revokePromptBlobs } from "./promptState.js";
import { PersistenceAdapter } from "./persistence.js";
class Store {
constructor() {
this.prompts = new Map();
this.ui = {
searchQuery: "",
currentlyActivePromptId: null,
activeSubmenuPromptId: null,
activeSubmenuBatchImages: null,
mainQueueScrollTop: null,
sequenceNumber: 0,
sidebarContainer: null,
cardStack: null
};
this.listeners = new Map();
this._saveTimer = null;
this.init();
}
init() {
const saved = PersistenceAdapter.load();
for (const item of saved) {
const state = createPromptState(item.pid, item);
this.prompts.set(String(state.pid), state);
if (state.timestamp > this.ui.sequenceNumber) {
this.ui.sequenceNumber = state.timestamp;
}
}
}
on(event, callback) {
if (!this.listeners.has(event)) {
this.listeners.set(event, new Set());
}
this.listeners.get(event).add(callback);
return () => this.off(event, callback);
}
off(event, callback) {
if (this.listeners.has(event)) {
this.listeners.get(event).delete(callback);
}
}
emit(event, payload) {
if (this.listeners.has(event)) {
for (const callback of this.listeners.get(event)) {
try {
callback(payload);
} catch (err) {
console.error(`Store error during event '${event}':`, err);
}
}
}
}
nextSequence() {
return ++this.ui.sequenceNumber;
}
scheduleSave(delay = 250) {
if (this._saveTimer) clearTimeout(this._saveTimer);
this._saveTimer = setTimeout(() => {
this._saveTimer = null;
PersistenceAdapter.save(this.prompts);
}, delay);
}
getPrompt(pid) {
return this.prompts.get(String(pid)) || null;
}
hasPrompt(pid) {
return this.prompts.has(String(pid));
}
getAllPrompts() {
return Array.from(this.prompts.values());
}
setPrompt(pid, state) {
const key = String(pid);
const isNew = !this.prompts.has(key);
this.prompts.set(key, state);
this.scheduleSave();
this.emit(isNew ? StoreEvents.PROMPT_ADDED : StoreEvents.PROMPT_UPDATED, { pid: key, prompt: state });
return state;
}
updatePrompt(pid, patch) {
const key = String(pid);
const state = this.prompts.get(key);
if (!state) return null;
Object.assign(state, patch);
this.scheduleSave();
this.emit(StoreEvents.PROMPT_UPDATED, { pid: key, prompt: state, patch });
return state;
}
deletePrompt(pid) {
const key = String(pid);
const state = this.prompts.get(key);
if (state) {
revokePromptBlobs(state);
this.prompts.delete(key);
if (this.ui.currentlyActivePromptId === key) {
this.ui.currentlyActivePromptId = null;
}
if (this.ui.activeSubmenuPromptId === key) {
this.ui.activeSubmenuPromptId = null;
}
this.scheduleSave();
this.emit(StoreEvents.PROMPT_DELETED, { pid: key });
return true;
}
return false;
}
pruneHistory(maxItems = 64) {
const candidates = PersistenceAdapter.getPruneCandidates(this.prompts, maxItems);
for (const pid of candidates) {
this.deletePrompt(pid);
}
}
clearFinished() {
const toDelete = [];
for (const [pid, state] of this.prompts.entries()) {
if (state.status !== PromptStatus.PENDING && state.status !== PromptStatus.ACTIVE) {
toDelete.push(pid);
}
}
for (const pid of toDelete) {
this.deletePrompt(pid);
}
this.emit(StoreEvents.PROMPTS_CLEARED, { count: toDelete.length });
return toDelete;
}
clearCancelledOrFailed() {
const toDelete = [];
for (const [pid, state] of this.prompts.entries()) {
if (state.status === PromptStatus.CANCELLED || state.status === PromptStatus.ERROR) {
toDelete.push(pid);
}
}
for (const pid of toDelete) {
this.deletePrompt(pid);
}
this.emit(StoreEvents.PROMPTS_CLEARED, { count: toDelete.length });
return toDelete;
}
setSearchQuery(query) {
this.ui.searchQuery = (query || "").trim();
this.emit(StoreEvents.SEARCH_CHANGED, { query: this.ui.searchQuery });
}
setActivePromptId(pid) {
this.ui.currentlyActivePromptId = pid ? String(pid) : null;
this.emit(StoreEvents.ACTIVE_PROMPT_CHANGED, { pid: this.ui.currentlyActivePromptId });
}
openBatchSubmenu(batchInfo) {
this.ui.activeSubmenuBatchImages = batchInfo;
this.ui.activeSubmenuPromptId = null;
this.emit(StoreEvents.SUBMENU_CHANGED, { type: "batch", data: batchInfo });
}
openOutputsSubmenu(pid) {
this.ui.activeSubmenuPromptId = String(pid);
this.ui.activeSubmenuBatchImages = null;
this.emit(StoreEvents.SUBMENU_CHANGED, { type: "outputs", pid: this.ui.activeSubmenuPromptId });
}
closeSubmenu() {
const hadSubmenu = this.ui.activeSubmenuPromptId !== null || this.ui.activeSubmenuBatchImages !== null;
this.ui.activeSubmenuPromptId = null;
this.ui.activeSubmenuBatchImages = null;
if (hadSubmenu) {
this.emit(StoreEvents.SUBMENU_CHANGED, { type: null });
}
}
}
export const store = new Store();
-141
View File
@@ -1,141 +0,0 @@
import { app } from "/scripts/app.js";
import { State } from "./state.js";
async function uploadDroppedImageToInput(imageObj) {
const src = `/view?filename=${encodeURIComponent(imageObj.filename)}&type=${imageObj.type || 'output'}&subfolder=${encodeURIComponent(imageObj.subfolder || '')}`;
try {
const response = await fetch(src);
if (!response.ok) return null;
const blob = await response.blob();
const file = new File([blob], imageObj.filename || "dropped_file", { type: blob.type });
const formData = new FormData();
formData.append("image", file);
formData.append("overwrite", "true");
formData.append("type", "input");
const uploadRes = await fetch("/upload/image", { method: "POST", body: formData });
if (!uploadRes.ok) return null;
const uploadData = await uploadRes.json();
return uploadData.name;
} catch(e) {
console.error("Comfy Sidebar: Failed to copy file to input.", e);
return null;
}
}
export function setupDragAndDrop() {
document.addEventListener("dragover", (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
});
document.addEventListener("drop", async (e) => {
const isSidebarDrop = e.target.closest('.comfyui-sidebar, .comfy-sidebar, [class*="sidebar"]') ||
(State.sidebarContainer && State.sidebarContainer.contains(e.target));
if (isSidebarDrop) {
e.preventDefault();
e.stopPropagation();
return;
}
const canvas = app.canvas;
if (!canvas || !canvas.graph) return;
// 1. Check for workflow JSON drop
const jsonStr = e.dataTransfer.getData("application/json");
if (jsonStr) {
try {
const workflow = JSON.parse(jsonStr);
if (workflow && workflow.nodes) {
e.preventDefault();
e.stopPropagation();
if (app.loadGraphData) {
app.loadGraphData(workflow);
} else if (app.handleFile) {
const file = new File([jsonStr], "workflow.json", { type: "application/json" });
await app.handleFile(file);
}
return;
}
} catch (err) {}
}
// 2. Check for image / video / 3D / audio URL drop
const url = e.dataTransfer.getData("text/uri-list") || e.dataTransfer.getData("text/plain");
if (url) {
try {
const urlObj = new URL(url, window.location.origin);
if (urlObj.pathname === "/view") {
const filename = urlObj.searchParams.get("filename");
const type = urlObj.searchParams.get("type") || "output";
const subfolder = urlObj.searchParams.get("subfolder") || "";
if (filename) {
e.preventDefault();
e.stopPropagation();
let targetNode = null;
if (canvas.convertEventToCanvasOffset) {
const pos = canvas.convertEventToCanvasOffset(e);
targetNode = canvas.graph.getNodeOnPos(pos[0], pos[1]);
} else if (canvas.canvas) {
const rect = canvas.canvas.getBoundingClientRect();
targetNode = canvas.graph.getNodeOnPos((e.clientX - rect.left - canvas.ds.offset[0]) / canvas.ds.scale, (e.clientY - rect.top - canvas.ds.offset[1]) / canvas.ds.scale);
}
// Check if dropped on a LoadImage, LoadVideo, Load3D, LoadAudio, or widget node
const widget = targetNode?.widgets?.find(w =>
w.name === "image" || w.name === "video" || w.name === "audio" || w.name === "audio_file" ||
w.name === "file" || w.name === "video_path" || w.name === "model_file" || w.name === "3d_file" ||
w.type === "image" || w.type === "customtext"
);
const isLoadNode = targetNode && (
widget ||
targetNode.type?.includes("LoadImage") ||
targetNode.type?.includes("LoadVideo") ||
targetNode.type?.includes("VHS_LoadVideo") ||
targetNode.type?.includes("Load3D") ||
targetNode.type?.includes("Load 3D") ||
targetNode.type?.includes("LoadAudio") ||
targetNode.type?.includes("Load Audio") ||
targetNode.type?.includes("VHS_LoadAudio") ||
targetNode.type?.includes("Preview3D")
);
if (isLoadNode) {
const targetWidget = widget || targetNode.widgets?.[0];
if (targetWidget) {
const newFilename = await uploadDroppedImageToInput({ filename, type, subfolder });
if (newFilename) {
if (targetWidget.options && Array.isArray(targetWidget.options.values)) {
if (!targetWidget.options.values.includes(newFilename)) {
targetWidget.options.values.push(newFilename);
}
}
targetWidget.value = newFilename;
if (targetWidget.callback) targetWidget.callback(targetWidget.value);
targetNode.imgs = null;
app.graph.setDirtyCanvas(true, true);
return;
}
}
} else {
// Dropped on empty canvas area
const src = `/view?filename=${encodeURIComponent(filename)}&type=${type}&subfolder=${encodeURIComponent(subfolder)}`;
const res = await fetch(src);
if (res.ok) {
const blob = await res.blob();
const file = new File([blob], filename, { type: blob.type });
if (app.handleFile) await app.handleFile(file);
else if (app.canvas?.handleDropItem) app.canvas.handleDropItem({ getAsFile: () => file });
}
}
}
}
} catch (err) {
console.error("Comfy Sidebar: Failed to handle dropped native URL:", err);
}
}
}, true);
}
-559
View File
@@ -1,559 +0,0 @@
import { app } from "/scripts/app.js";
const STYLE_ID = "comfy-sidebar-classic-layout-override";
const CLASSIC_LAYOUT_CSS_MEDIA = `
/* Remove the ghost underlay container border & background (the oval) without affecting the topbar header */
.actionbar-container,
.shadow-interface.rounded-lg.bg-comfy-menu-bg,
.shadow-interface.rounded-lg.border-interface-stroke,
.shadow-interface.border.rounded-lg:has([class*="actionbar-buttons"]),
.shadow-interface.border.rounded-lg:has(.actionbar-buttons),
div.border-interface-stroke.rounded-lg:has([class*="actionbar-buttons"]) {
border: none !important;
background: transparent !important;
box-shadow: none !important;
}
/* Style and align the custom plugins bar (Manager, LoRA, etc.) */
[class*="actionbar"]:not(.actionbar),
[class*="actionbar-buttons"],
.actionbar-buttons {
position: fixed !important;
top: 3px !important;
right: 4px !important;
left: auto !important;
transform: none !important;
z-index: 1010 !important;
background: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
display: flex !important;
align-items: center !important;
}
/* Style overrides for the new native Extensions button container when embedded in top actionbar */
.comfy-sidebar-extensions-override {
background: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 8px 0 0 !important;
height: auto !important;
position: static !important;
order: -10 !important;
display: inline-flex !important;
align-items: center !important;
}
/* Scale down performance indicators (Crystools) uniformly */
#crysmonitor-monitors-root,
#crystools-monitors-root,
.crysmonitor-monitors-container {
zoom: 0.8 !important;
display: inline-flex !important;
align-items: center !important;
}
/* Hide user account profile button and PrimeVue components */
img[alt*="User Avatar"],
img[alt*="user avatar"],
button:has(img[alt*="User Avatar"]),
[role="button"]:has(img[alt*="User Avatar"]),
button:has(img[alt*="user avatar"]),
[role="button"]:has(img[alt*="user avatar"]),
.p-avatar,
[data-pc-name="avatar"],
button:has(.p-avatar),
[role="button"]:has(.p-avatar),
button:has([data-pc-name="avatar"]),
[role="button"]:has([data-pc-name="avatar"]) {
display: none !important;
}
/* Base rules: Large/Wide desktop screens (>= 1600px width) */
.p-tabview-nav-content,
[class*="tabview"] {
padding-left: 150px !important;
padding-right: 580px !important;
}
/* Medium desktop screens (between 1200px and 1599px width) */
@media (max-width: 1599px) {
.p-tabview-nav-content,
[class*="tabview"] {
padding-left: 100px !important;
padding-right: 420px !important;
}
}
/* Standard laptops / small monitors (between 900px and 1199px width) */
@media (max-width: 1199px) {
.p-tabview-nav-content,
[class*="tabview"] {
padding-left: 40px !important;
padding-right: 280px !important;
}
}
/* Very narrow or heavily zoomed displays (< 900px width) */
@media (max-width: 899px) {
.p-tabview-nav-content,
[class*="tabview"] {
padding-left: 10px !important;
padding-right: 180px !important;
}
}
`;
/**
* Native settings synchronization without direct DOM element querying or simulated clicks.
*/
export function syncStockHistoryAndProgressSettings(enable) {
const dockedVal = !!enable;
const progressVal = !enable;
const QPOV2_ID = "Comfy.Queue.QPOV2";
const progressKey = "Comfy.Queue.ShowRunProgressBar";
// Use official extensionManager setting API if present, with fallback to app.ui.settings
if (app.extensionManager?.setting) {
try { app.extensionManager.setting.set(QPOV2_ID, dockedVal); } catch (e) {}
try { app.extensionManager.setting.set(progressKey, progressVal); } catch (e) {}
} else if (app.ui?.settings) {
try { app.ui.settings.setSettingValue(QPOV2_ID, dockedVal); } catch (e) {}
try { app.ui.settings.setSettingValue(progressKey, progressVal); } catch (e) {}
}
try { localStorage.setItem(QPOV2_ID, JSON.stringify(dockedVal)); } catch (e) {}
try { localStorage.setItem(progressKey, JSON.stringify(progressVal)); } catch (e) {}
try { window.dispatchEvent(new Event("storage")); } catch (e) {}
}
export function applyClassicLayout(enable, updateSetting = false) {
let styleEl = document.getElementById(STYLE_ID);
if (enable) {
if (updateSetting) {
if (app.extensionManager?.setting) {
app.extensionManager.setting.set("Comfy.Workflow.WorkflowTabsPosition", "Topbar");
} else if (app.ui?.settings) {
app.ui.settings.setSettingValue("Comfy.Workflow.WorkflowTabsPosition", "Topbar");
}
}
if (!styleEl) {
styleEl = document.createElement("style");
styleEl.id = STYLE_ID;
document.head.appendChild(styleEl);
}
styleEl.textContent = CLASSIC_LAYOUT_CSS_MEDIA;
} else {
if (styleEl) styleEl.remove();
if (updateSetting) {
if (app.extensionManager?.setting) {
app.extensionManager.setting.set("Comfy.Workflow.WorkflowTabsPosition", "Sidebar");
} else if (app.ui?.settings) {
app.ui.settings.setSettingValue("Comfy.Workflow.WorkflowTabsPosition", "Sidebar");
}
}
}
}
let savedButtonData = null;
let domObserver = null;
let syncScheduled = false;
function findOriginalButton() {
const byTestId = document.querySelector('[data-testid="properties-panel-toggle"]');
if (byTestId && !byTestId.classList.contains("comfy-sidebar-custom-properties-toggle")) {
return byTestId;
}
const icons = document.querySelectorAll('[class*="lucide--panel-right"], [class*="lucide--panel-left"], [class*="lucide--panel-bottom"]');
for (const icon of icons) {
const btn = icon.closest('button, [role="button"], .comfyui-menu-item, .p-button');
if (btn && !btn.classList.contains("comfy-sidebar-custom-properties-toggle")) {
return btn;
}
}
const buttons = document.querySelectorAll('button, [role="button"], .p-button');
for (const btn of buttons) {
if (btn.classList.contains("comfy-sidebar-custom-properties-toggle")) continue;
const title = (btn.getAttribute("title") || btn.getAttribute("aria-label") || "").toLowerCase();
if (title.includes("workflow overview") || title.includes("properties") || title.includes("toggle panel")) {
return btn;
}
}
return null;
}
function findTopbarContainer() {
const container = document.querySelector('[data-testid="action-bar-buttons"], [class*="actionbar-buttons"], .actionbar-buttons, [class*="actionbar"]');
if (container) return container;
const orig = findOriginalButton();
if (orig?.parentNode) return orig.parentNode;
const buttons = document.querySelectorAll("button, .p-button");
for (const btn of buttons) {
if (btn.classList.contains("comfy-sidebar-custom-properties-toggle")) continue;
const title = (btn.getAttribute("title") || btn.getAttribute("aria-label") || "").toLowerCase();
if (title.includes("run") || title.includes("manager")) {
if (btn.parentNode) return btn.parentNode;
}
}
return null;
}
function isPropertiesPanelOpen() {
const panel = document.querySelector('[data-testid="properties-panel"]');
if (panel && panel.offsetWidth > 0 && panel.offsetHeight > 0) {
return true;
}
const headings = document.querySelectorAll('h1, h2, h3, h4');
for (const h of headings) {
if (h.textContent.trim() === "Workflow Overview" && h.offsetWidth > 0 && h.offsetHeight > 0) {
return true;
}
}
const origBtn = findOriginalButton();
if (origBtn) {
if (origBtn.classList.contains("p-button-active") ||
origBtn.classList.contains("active") ||
origBtn.getAttribute("aria-expanded") === "true" ||
origBtn.getAttribute("aria-pressed") === "true") {
return true;
}
}
return false;
}
function findActiveQueueIndicator() {
const container = findTopbarContainer();
if (!container) return null;
const buttons = container.querySelectorAll("button, .p-button, .comfyui-menu-item");
for (const btn of buttons) {
if (btn.classList.contains("comfy-sidebar-custom-properties-toggle")) continue;
const text = (btn.textContent || "").toLowerCase();
if (text.includes("active") || text.includes("queued") || text.includes("running") || text.includes("pending")) {
return btn;
}
}
return null;
}
function findNativeExtensionsPanel() {
return Array.from(document.querySelectorAll('.shadow-interface:not(.actionbar-container)'))
.find(el => el.textContent.toLowerCase().includes('extensions') || el.querySelector('button')?.textContent.toLowerCase().includes('extensions'));
}
function updateSidebarTabsVisibility() {
const sidebar = document.querySelector('.comfyui-sidebar, .comfy-sidebar, .sidebar, [class*="sidebar-nav"], [class*="sidebar"]');
if (!sidebar) return;
const tabIconSelectors = {
"Assets": '[class*="comfy--image-ai-edit"]',
"Nodes": '[class*="comfy--node"]',
"Models": '[class*="comfy--ai-model"]',
"Workflows": '[class*="comfy--workflow"], [class*="workflow"]',
"Apps": '[class*="lucide--panels-top-left"]',
"Templates": '[class*="comfy--template"]'
};
Object.entries(tabIconSelectors).forEach(([tab, selector]) => {
const shouldHide = app.ui?.settings?.getSettingValue(`Comfy Sidebar.Hide Junk.${tab}`) ?? false;
const icon = sidebar.querySelector(selector);
if (icon) {
const tabBtn = icon.closest('.comfyui-sidebar-tab, button, [role="tab"], li, a, .comfyui-sidebar-item') || icon;
if (shouldHide) {
if (tabBtn.style.display !== "none") tabBtn.style.setProperty("display", "none", "important");
} else {
if (tabBtn.style.display === "none") tabBtn.style.removeProperty("display");
}
}
});
const hideStockHistory = app.ui?.settings?.getSettingValue("Comfy Sidebar.Hide Junk.Override Stock Job History Tab") ?? false;
const historyIcon = sidebar.querySelector('[class*="lucide--history"]');
if (historyIcon) {
const historyBtn = historyIcon.closest('.comfyui-sidebar-tab, button, [role="tab"], li, a, .comfyui-sidebar-item') || historyIcon;
if (hideStockHistory) {
if (historyBtn.style.display !== "none") historyBtn.style.setProperty("display", "none", "important");
} else {
if (historyBtn.style.display === "none") historyBtn.style.removeProperty("display");
}
}
}
function findGraphButton() {
const elements = document.querySelectorAll('.p-1.bg-base-background.rounded-lg, .bg-base-background.rounded-lg, .bg-secondary-background.rounded-lg.items-center.inline-flex.pointer-events-auto, [data-testid="graph-view-button"]');
for (const el of elements) {
if (el.closest('.p-dialog, .comfy-modal, [role="dialog"], .p-sidebar, .comfy-settings, .comfyui-sidebar, .comfy-sidebar')) continue;
return el.closest('.group, .p-1') || el;
}
const fallbacks = document.querySelectorAll('button, .bg-base-background, .bg-secondary-background');
for (const el of fallbacks) {
if (el.closest('.p-dialog, .comfy-modal, [role="dialog"], .p-sidebar, .comfy-settings, .comfyui-sidebar, .comfy-sidebar')) continue;
const text = (el.textContent || el.getAttribute("title") || el.getAttribute("aria-label") || "").toLowerCase();
if (text.includes("graph") || text.includes("workflow") || el.querySelector('[class*="sitemap"], [class*="workflow"]')) {
return el.closest('.group, .p-1, .bg-base-background, .bg-secondary-background') || el;
}
}
return null;
}
function syncErrorBadge(originalBtn, customBtn) {
if (!customBtn) return;
const stockDot = document.querySelector('.comfy-sidebar-hide-original-properties-btn ~ span, .comfy-sidebar-hide-original-properties-btn + span');
let customDot = customBtn.querySelector('.comfy-sidebar-error-dot');
if (stockDot) {
if (!customDot) {
customDot = document.createElement("span");
customDot.className = "comfy-sidebar-error-dot inline-flex items-center justify-center rounded-full bg-destructive-background text-white size-2 absolute -top-1 -right-1";
customBtn.appendChild(customDot);
}
} else if (customDot) {
customDot.remove();
}
}
function cleanHTML(html) {
if (!html) return "";
const tempDiv = document.createElement("div");
tempDiv.innerHTML = html;
const tempDot = tempDiv.querySelector('[class*="destructive"]');
if (tempDot) tempDot.remove();
return tempDiv.innerHTML;
}
export function syncClassicLayout() {
if (domObserver) domObserver.disconnect();
try {
const isClassicLayoutEnabled = app.ui?.settings?.getSettingValue("Comfy Sidebar.Comfy Layout") ?? false;
const hideGraphBtn = app.ui?.settings?.getSettingValue("Comfy Sidebar.Hide Junk.Graph Button") ?? false;
const graphBtn = findGraphButton();
if (graphBtn) {
if (hideGraphBtn) {
if (graphBtn.style.display !== "none") graphBtn.style.setProperty("display", "none", "important");
} else {
if (graphBtn.style.display === "none") graphBtn.style.removeProperty("display");
}
}
const extensionsPanel = findNativeExtensionsPanel();
if (extensionsPanel) {
if (isClassicLayoutEnabled) {
const container = findTopbarContainer();
if (container && extensionsPanel.parentNode !== container) {
if (!extensionsPanel._originalParent) {
extensionsPanel._originalParent = extensionsPanel.parentNode;
extensionsPanel._originalNextSibling = extensionsPanel.nextSibling;
}
container.appendChild(extensionsPanel);
extensionsPanel.classList.add("comfy-sidebar-extensions-override");
}
} else if (extensionsPanel._originalParent && extensionsPanel.parentNode !== extensionsPanel._originalParent) {
extensionsPanel._originalParent.insertBefore(extensionsPanel, extensionsPanel._originalNextSibling || null);
extensionsPanel.classList.remove("comfy-sidebar-extensions-override");
}
}
if (!isClassicLayoutEnabled) {
const originalBtn = findOriginalButton();
if (originalBtn?.classList.contains("comfy-sidebar-hide-original-properties-btn")) {
originalBtn.classList.remove("comfy-sidebar-hide-original-properties-btn");
}
const customBtn = document.querySelector(".comfy-sidebar-custom-properties-toggle");
if (customBtn) customBtn.remove();
const indicator = findActiveQueueIndicator();
if (indicator && indicator.style.display === "none") indicator.style.removeProperty("display");
updateSidebarTabsVisibility();
return;
}
const originalBtn = findOriginalButton();
const container = findTopbarContainer();
const openState = isPropertiesPanelOpen();
if (originalBtn) {
if (!originalBtn.classList.contains("comfy-sidebar-hide-original-properties-btn")) {
originalBtn.classList.add("comfy-sidebar-hide-original-properties-btn");
}
savedButtonData = {
className: originalBtn.className.replace("comfy-sidebar-hide-original-properties-btn", "").trim(),
innerHTML: originalBtn.innerHTML,
tagName: originalBtn.tagName,
attributes: Array.from(originalBtn.attributes).map(attr => ({
name: attr.name,
value: attr.value
}))
};
}
let customBtn = document.querySelector(".comfy-sidebar-custom-properties-toggle");
if (!customBtn && savedButtonData && container) {
customBtn = document.createElement(savedButtonData.tagName);
customBtn.className = savedButtonData.className + " comfy-sidebar-custom-properties-toggle";
customBtn.innerHTML = cleanHTML(savedButtonData.innerHTML);
for (const attr of savedButtonData.attributes) {
if (attr.name !== "class" && attr.name !== "id" && attr.name !== "style") {
customBtn.setAttribute(attr.name, attr.value);
}
}
customBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const nativeBtn = findOriginalButton();
if (nativeBtn) {
nativeBtn.click();
requestAnimationFrame(() => syncClassicLayout());
}
});
container.appendChild(customBtn);
}
if (customBtn) {
if (originalBtn) {
const cleanedHTML = cleanHTML(originalBtn.innerHTML);
if (cleanedHTML && customBtn.innerHTML !== cleanedHTML) {
const existingDot = customBtn.querySelector('.comfy-sidebar-error-dot');
customBtn.innerHTML = cleanedHTML;
if (existingDot) customBtn.appendChild(existingDot);
}
const titleVal = originalBtn.getAttribute("title") || originalBtn.getAttribute("aria-label") || "Toggle properties panel";
customBtn.setAttribute("title", titleVal);
customBtn.setAttribute("aria-label", titleVal);
for (const cls of originalBtn.classList) {
if (cls !== "comfy-sidebar-hide-original-properties-btn" && !customBtn.classList.contains(cls)) {
customBtn.classList.add(cls);
}
}
syncErrorBadge(originalBtn, customBtn);
} else if (!customBtn.getAttribute("title")) {
customBtn.setAttribute("title", "Toggle properties panel");
customBtn.setAttribute("aria-label", "Toggle properties panel");
}
customBtn.classList.toggle("comfy-panel-open", openState);
customBtn.style.display = "inline-flex";
}
const hideQueueIndicator = app.ui?.settings?.getSettingValue("Comfy Sidebar.Hide Junk.Override Stock Job History Tab") ?? false;
const indicator = findActiveQueueIndicator();
if (indicator) {
if (hideQueueIndicator) {
if (indicator.style.display !== "none") indicator.style.setProperty("display", "none", "important");
} else if (indicator.style.display === "none") {
indicator.style.removeProperty("display");
}
}
updateSidebarTabsVisibility();
} catch (err) {
console.error("Comfy Sidebar: Error inside layout sync routine:", err);
} finally {
if (domObserver) {
domObserver.observe(document.body, {
childList: true,
subtree: true
});
}
}
}
export function setupPropertiesPanelToggleFix() {
if (!document.getElementById("comfy-sidebar-layout-fix-styles")) {
const style = document.createElement("style");
style.id = "comfy-sidebar-layout-fix-styles";
style.textContent = `
.comfy-sidebar-hide-original-properties-btn {
display: none !important;
}
.comfy-sidebar-hide-original-properties-btn ~ span,
.comfy-sidebar-hide-original-properties-btn + span {
display: none !important;
}
.comfy-sidebar-custom-properties-toggle {
order: 99999 !important;
position: relative !important;
overflow: visible !important;
margin-left: -8px !important;
margin-right: 0px !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
padding: 0 !important;
}
.comfy-sidebar-custom-properties-toggle.comfy-panel-open {
margin-left: 0px !important;
}
.comfy-sidebar-custom-properties-toggle > span.comfy-sidebar-error-dot {
display: inline-flex !important;
}
`;
document.head.appendChild(style);
}
if (domObserver) domObserver.disconnect();
domObserver = new MutationObserver((mutations) => {
let shouldSync = false;
const isInternalSidebarMutation = (node) => {
if (!node || node.nodeType !== 1) return false;
return node.closest?.('.comfyui-sidebar, .comfy-sidebar, .comfy-sidebar-comparison-overlay') ||
node.classList?.contains('comfy-sidebar-card');
};
for (const mutation of mutations) {
if (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0) {
const hasExternalElementMutation =
Array.from(mutation.addedNodes).some(node => node.nodeType === 1 && !isInternalSidebarMutation(node)) ||
Array.from(mutation.removedNodes).some(node => node.nodeType === 1 && !isInternalSidebarMutation(node));
if (hasExternalElementMutation) {
shouldSync = true;
break;
}
}
}
if (shouldSync && !syncScheduled) {
syncScheduled = true;
requestAnimationFrame(() => {
syncClassicLayout();
syncScheduled = false;
});
}
});
domObserver.observe(document.body, {
childList: true,
subtree: true
});
syncClassicLayout();
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "قائمة الانتظار",
"Search History": "البحث في السجل",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "تجاهل/تضمين العقد المحددة (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "لم يتم تحديد أي عقدة. انقر فوق عقدة في اللوحة أولاً.",
"Renumber All Nodes by Execution Order (Alt+R)": "إعادة ترقيم العقد وفقاً لترتيب التنفيذ (Alt+R)",
"Clear Cancelled & Failed": "مسح الملغاة والفاشلة",
"Clear All History": "مسح كل السجل",
"Filter by text, images, nodes...": "تصفية حسب النص، الصور، العقد...",
"Clear & Close Search": "مسح وإغلاق البحث",
"Scroll to Top": "التمرير إلى الأعلى",
"Batch of #": "دفعة #",
"Go Back": "رجوع",
"Go Back to Queue": "العودة إلى القائمة",
"Outputs of #": "مخرجات #",
"No separate intermediate outputs found.": "لم يتم العثور على مخرجات وسيطة منفصلة.",
"Cancel All Pending": "إلغاء جميع المهام المعلقة",
"Pending Queue:": "في الانتظار:",
"tasks": "مهام",
"Download Object": "تنزيل العنصر",
"Copy to Clipboard": "نسخ إلى الحافظة",
"Download JSON": "تنزيل JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "حذف البطاقة (اضغط Ctrl للحذف من القرص)",
"Delete Card": "حذف البطاقة",
"Delete File": "حذف الملف",
"Delete Files": "حذف الملفات",
"Show Node": "إظهار العقدة",
"Show Stopped/Failed Node": "إظهار العقدة المتوقفة أو الفاشلة",
"View all intermediate outputs": "عرض جميع المخرجات الوسيطة",
"Delete Card (Ctrl+Click to delete from disk)": "حذف البطاقة (Ctrl+نقر للحذف من القرص)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+نقر مجدداً للحذف النهائي من القرص",
"Click again to confirm removing card": "انقر مجدداً لتأكيد الإزالة",
"Remove from batch (Hold Ctrl to delete file from disk)": "إزالة من الدفعة (Ctrl للحذف من القرص)",
"Click again to confirm removing from batch": "انقر مجدداً لتأكيد الإزالة من الدفعة",
"Delete node output (Hold Ctrl to delete file from disk)": "حذف مخرج العقدة (Ctrl للحذف من القرص)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+نقر مجدداً لحذف ملفات العقدة من القرص",
"Click again to confirm removing output": "انقر مجدداً لتأكيد إزالة المخرج",
"Moved file to Recycle Bin.": "تم نقل الملف إلى سلة المحذوفات.",
"Permanently deleted file.": "تم حذف الملف نهائياً.",
"Cancelled": "ملغى",
"Error": "خطأ",
"Warning": "تحذير",
"Cancel Queued Task": "إلغاء المهمة في القائمة",
"Interrupt Execution": "إيقاف التنفيذ",
"Click to read full text": "انقر لقراءة النص كاملاً",
"No Outputs": "لا توجد مخرجات",
"Processing...": "جارٍ المعالجة...",
"Finishing...": "جارٍ الإنهاء...",
"No workflow metadata found in this file.": "لم يتم العثور على بيانات سير العمل في هذا الملف.",
"Open Folder": "فتح المجلد",
"Open Location": "فتح المسار",
"View all images in this batch": "عرض جميع صور هذه الدفعة",
"No nodes found on canvas to renumber.": "لم يتم العثور على عقد لإعادة ترقيمها.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "ستؤدي إعادة الترقيم إلى إعادة كتابة معرفات العقد حسب ترتيب التنفيذ.\n\nيحل هذا مشكلة المخرجات الوسيطة المعروضة كنتائج نهائية، ولكنه قد يؤثر على النصوص الخارجية المعتمدة على المعرفات.\n\nهل تريد المتابعة؟",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "تمت إعادة ترقيم {count} عقدة وفقاً للترتيب. آخر عقدة: #{id} ({name}).",
"Failed to renumber nodes: ": "فشلت إعادة ترقيم العقد: ",
"Please select a node first to change its ID.": "يرجى تحديد عقدة أولاً لتغيير معرّفها.",
"Enter new ID for node #{id} ({name}):": "أدخل المعرف الجديد للعقدة #{id} ({name}):",
"Please enter a valid positive number.": "يرجى إدخال رقم صحيح موجب.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "المعرف #{id} مستخدم بالفعل بواسطة \"{name}\". هل تريد تبديل المعرفات؟",
"Assigned node ID #{id} to \"{name}\".": "تم تعيين المعرف #{id} للعقدة \"{name}\".",
"Failed to set node ID: ": "فشل تعيين معرف العقدة: ",
"Video playback. Press Esc to close.": "تشغيل الفيديو. اضغط Esc للإغلاق.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "انقر للتكبير (100%/ملاءمة) | Shift+نقر على بطاقة أخرى للمقارنة.",
"Toggle Loop": "تبديل التكرار",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "عدم تطابق في الأبعاد ({wA}x{hA} مقابل {wB}x{hB}). يجب أن تكون الصور بنفس النسبة للمقارنة.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "انقر للتكبير | اسحب شريط التمرير للمقارنة | Esc للإغلاق.",
"Copy": "نسخ",
"Copied!": "تم النسخ!",
"Text Output": "مخرج نصي",
"Text Output #": "مخرج نصي #",
"Raw Text": "النص الأصلي",
"{wc} words • {chars} chars": "{wc} كلمة • {chars} حرف",
"3D Model": "نموذج 3D",
"Loading 3D Asset...": "جارٍ تحميل العنصر ثلاثي الأبعاد...",
"Exporting {format}...": "جارٍ التصدير بتنسيق {format}...",
"Failed to load 3D engine.": "فشل تحميل محرك 3D.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "تعذر تنزيل مكتبات 3D. تأكد من اتصال جهازك بالإنترنت.",
"Background Color": "لون الخلفية",
"Up Direction": "الاتجاه للأعلى",
"Material Mode": "وضع الخامة",
"Camera Type": "نوع الكاميرا",
"FOV": "مجال الرؤية (FOV)",
"Light Intensity": "شدة الإضاءة",
"Original (Y-Up)": "أصلي (Y للأعلى)",
"Z-Up (+90°)": "Z للأعلى (+90°)",
"Inverted (-90°)": "معكوس (-90°)",
"Original / Textured": "أصلي / إكساء",
"Clay / Studio Matte": "طين / استوديو غير لامع",
"Normals": "النواظم (Normals)",
"Perspective": "منظور",
"Orthographic": "إسقاط متوازي",
"Grid": "الشبكة",
"Auto-Rotate": "تدوير تلقائي",
"Wireframe": "إطار شبكي",
"Reset View": "إعادة ضبط المنظور",
"Settings": "الإعدادات",
"Export As...": "تصدير كـ...",
"Failed to load 3D format": "فشل تحميل تنسيق 3D",
"Toggle Comfy Queue Sidebar": "تبديل الشريط الجانبي لـ Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "تجاهل/تضمين العقد المحددة في قائمة الانتظار",
"Renumber All Nodes (Execution Order)": "إعادة ترقيم جميع العقد (ترتيب التنفيذ)",
"Set Selected Node ID...": "تعيين معرف العقدة المحددة...",
"Set Node ID...": "تعيين معرف العقدة...",
"Gallery": "المعرض",
"Gallery (Outputs)": "المعرض (المخرجات)",
"Go Up One Level": "الانتقال لمستوى أعلى",
"Open Current Folder in File Manager": "فتح المجلد الحالي في مدير الملفات",
"Refresh Gallery": "تحديث المعرض",
"Filter gallery files...": "تصفية ملفات المعرض...",
"Loading files...": "جاري تحميل الملفات...",
"No files found in this folder.": "لم يتم العثور على ملفات في هذا المجلد.",
"Failed to load gallery from disk.": "فشل تحميل المعرض من القرص.",
"Sort: Newest First": "الترتيب: الأحدث أولاً",
"Sort: Oldest First": "الترتيب: الأقدم أولاً",
"Search Gallery (Filename or Prompt)": "البحث في المعرض (اسم الملف أو الموجه)",
"Search filenames or prompt metadata...": "البحث في أسماء الملفات أو بيانات الموجه..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "حد أعمدة قائمة الانتظار",
"Width Threshold for Queue Columns (px)": "العرض بالبكسل لتقسيم القائمة إلى عدة أعمدة",
"Show Pending Count Only": "إظهار عدد المهام المعلقة فقط",
"If disabled, each queued job will have a separate individual card": "في حال التعطيل، ستظهر كل مهمة في القائمة ببطاقة مستقلة",
"Show Working Node Name": "إظهار اسم العقدة النشطة",
"Shows the name of the node which is currently in the process": "يعرض اسم العقدة التي تتم معالجتها حالياً",
"Auto Clear Interrupted": "مسح تلقائي للمهام المقاطعة",
"Auto-clear cancelled & failed jobs on new generation": "مسح المهام الملغاة والفاشلة تلقائياً عند بدء توليد جديد",
"Permanent Delete on Disk Deletion": "حذف دائم من القرص",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "حذف الملفات نهائياً عند المسح من القرص (دون نقلها لسلة المحذوفات)",
"Hide Tab: {tab}": "إخفاء التبويب: {tab}",
"Assets": "الأصول",
"Nodes": "العقد",
"Models": "النماذج",
"Workflows": "مخططات العمل",
"Apps": "التطبيقات",
"Templates": "القوالب",
"Override Stock History": "استبدال السجل الافتراضي",
"Replace the stock Job History sidebar with Comfy Queue": "استبدال الشريط الجانبي لسجل المهام الافتراضي بـ Comfy Queue",
"Hide Graph Button": "إخفاء زر 'المخطط'",
"Hide floating 'Graph' (Workflow/Node Map) button": "إخفاء الزر العائم 'المخطط' (خريطة العقد)",
"Hide Avatar": "إخفاء الصورة الرمزية",
"Floating Canvas Controls": "أدوات التحكم العائمة في اللوحة",
"Classic Layout": "المظهر الكلاسيكي",
"Places the controls and the open workflow tabs on a single unified top bar": "وضع عناصر التحكم وتبويبات العمل المفتوحة في شريط علوي موحد",
"Comfy Layout": "مظهر مدمج",
"Hide Junk": "إخفاء العناصر غير المرغوبة",
"Default": "افتراضي",
"Dock": "إرساء",
"Hide": "إخفاء",
"Enable Output Gallery Sidebar": "تمكين الشريط الجانبي لمعرض المخرجات"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "Queue",
"Search History": "Search History",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "No nodes selected. Click a node on the canvas first to toggle ignore.",
"Renumber All Nodes by Execution Order (Alt+R)": "Renumber All Nodes by Execution Order (Alt+R)",
"Clear Cancelled & Failed": "Clear Cancelled & Failed",
"Clear All History": "Clear All History",
"Filter by text, images, nodes...": "Filter by text, images, nodes...",
"Clear & Close Search": "Clear & Close Search",
"Scroll to Top": "Scroll to Top",
"Batch of #": "Batch of #",
"Go Back": "Go Back",
"Go Back to Queue": "Go Back to Queue",
"Outputs of #": "Outputs of #",
"No separate intermediate outputs found.": "No separate intermediate outputs found.",
"Cancel All Pending": "Cancel All Pending",
"Pending Queue:": "Pending Queue:",
"tasks": "tasks",
"Download Object": "Download Object",
"Copy to Clipboard": "Copy to Clipboard",
"Download JSON": "Download JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "Delete Card (Hold Ctrl to delete file from disk)",
"Delete Card": "Delete Card",
"Delete File": "Delete File",
"Delete Files": "Delete Files",
"Show Node": "Show Node",
"Show Stopped/Failed Node": "Show Stopped/Failed Node",
"View all intermediate outputs": "View all intermediate outputs",
"Delete Card (Ctrl+Click to delete from disk)": "Delete Card (Ctrl+Click to delete from disk)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+Click again to delete file from DISK / TRASH",
"Click again to confirm removing card": "Click again to confirm removing card",
"Remove from batch (Hold Ctrl to delete file from disk)": "Remove from batch (Hold Ctrl to delete file from disk)",
"Click again to confirm removing from batch": "Click again to confirm removing from batch",
"Delete node output (Hold Ctrl to delete file from disk)": "Delete node output (Hold Ctrl to delete file from disk)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+Click again to delete this node's files from DISK / TRASH",
"Click again to confirm removing output": "Click again to confirm removing output",
"Moved file to Recycle Bin.": "Moved file to Recycle Bin.",
"Permanently deleted file.": "Permanently deleted file.",
"Cancelled": "Cancelled",
"Error": "Error",
"Warning": "Warning",
"Cancel Queued Task": "Cancel Queued Task",
"Interrupt Execution": "Interrupt Execution",
"Click to read full text": "Click to read full text",
"No Outputs": "No Outputs",
"Processing...": "Processing...",
"Finishing...": "Finishing...",
"No workflow metadata found in this file.": "No workflow metadata found in this file.",
"Open Folder": "Open Folder",
"Open Location": "Open Location",
"View all images in this batch": "View all images in this batch",
"No nodes found on canvas to renumber.": "No nodes found on canvas to renumber.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).",
"Failed to renumber nodes: ": "Failed to renumber nodes: ",
"Please select a node first to change its ID.": "Please select a node first to change its ID.",
"Enter new ID for node #{id} ({name}):": "Enter new ID for node #{id} ({name}):",
"Please enter a valid positive number.": "Please enter a valid positive number.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "Node ID #{id} is already used by \"{name}\". Swap their IDs?",
"Assigned node ID #{id} to \"{name}\".": "Assigned node ID #{id} to \"{name}\".",
"Failed to set node ID: ": "Failed to set node ID: ",
"Video playback. Press Esc to close.": "Video playback. Press Esc to close.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Click image to zoom (100%/Fit) | Shift+Click another card to compare.",
"Toggle Loop": "Toggle Loop",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Click image to zoom | Drag image to compare slider | Esc to close.",
"Copy": "Copy",
"Copied!": "Copied!",
"Text Output": "Text Output",
"Text Output #": "Text Output #",
"Raw Text": "Raw Text",
"{wc} words • {chars} chars": "{wc} words • {chars} chars",
"3D Model": "3D Model",
"Loading 3D Asset...": "Loading 3D Asset...",
"Exporting {format}...": "Exporting {format}...",
"Failed to load 3D engine.": "Failed to load 3D engine.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.",
"Background Color": "Background Color",
"Up Direction": "Up Direction",
"Material Mode": "Material Mode",
"Camera Type": "Camera Type",
"FOV": "FOV",
"Light Intensity": "Light Intensity",
"Original (Y-Up)": "Original (Y-Up)",
"Z-Up (+90°)": "Z-Up (+90°)",
"Inverted (-90°)": "Inverted (-90°)",
"Original / Textured": "Original / Textured",
"Clay / Studio Matte": "Clay / Studio Matte",
"Normals": "Normals",
"Perspective": "Perspective",
"Orthographic": "Orthographic",
"Grid": "Grid",
"Auto-Rotate": "Auto-Rotate",
"Wireframe": "Wireframe",
"Reset View": "Reset View",
"Settings": "Settings",
"Export As...": "Export As...",
"Failed to load 3D format": "Failed to load 3D format",
"Toggle Comfy Queue Sidebar": "Toggle Comfy Queue Sidebar",
"Toggle Ignore Selected Node(s) in Queue": "Toggle Ignore Selected Node(s) in Queue",
"Renumber All Nodes (Execution Order)": "Renumber All Nodes (Execution Order)",
"Set Selected Node ID...": "Set Selected Node ID...",
"Set Node ID...": "Set Node ID...",
"Gallery": "Gallery",
"Gallery (Outputs)": "Gallery (Outputs)",
"Go Up One Level": "Go Up One Level",
"Open Current Folder in File Manager": "Open Current Folder in File Manager",
"Refresh Gallery": "Refresh Gallery",
"Filter gallery files...": "Filter gallery files...",
"Loading files...": "Loading files...",
"No files found in this folder.": "No files found in this folder.",
"Failed to load gallery from disk.": "Failed to load gallery from disk.",
"Sort: Newest First": "Sort: Newest First",
"Sort: Oldest First": "Sort: Oldest First",
"Search Gallery (Filename or Prompt)": "Search Gallery (Filename or Prompt)",
"Search filenames or prompt metadata...": "Search filenames or prompt metadata..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "Grid Columns Threshold",
"Width Threshold for Queue Columns (px)": "Width Threshold for Queue Columns (px)",
"Show Pending Count Only": "Show Pending Count Only",
"If disabled, each queued job will have a separate individual card": "If disabled, each queued job will have a separate individual card",
"Show Working Node Name": "Show Working Node Name",
"Shows the name of the node which is currently in the process": "Shows the name of the node which is currently in the process",
"Auto Clear Interrupted": "Auto Clear Interrupted",
"Auto-clear cancelled & failed jobs on new generation": "Auto-clear cancelled & failed jobs on new generation",
"Permanent Delete on Disk Deletion": "Permanent Delete on Disk Deletion",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)",
"Hide Tab: {tab}": "Hide Tab: {tab}",
"Assets": "Assets",
"Nodes": "Nodes",
"Models": "Models",
"Workflows": "Workflows",
"Apps": "Apps",
"Templates": "Templates",
"Override Stock History": "Override Stock History",
"Replace the stock Job History sidebar with Comfy Queue": "Replace the stock Job History sidebar with Comfy Queue",
"Hide Graph Button": "Hide Graph Button",
"Hide floating 'Graph' (Workflow/Node Map) button": "Hide floating 'Graph' (Workflow/Node Map) button",
"Hide Avatar": "Hide Avatar",
"Floating Canvas Controls": "Floating Canvas Controls",
"Classic Layout": "Classic Layout",
"Places the controls and the open workflow tabs on a single unified top bar": "Places the controls and the open workflow tabs on a single unified top bar",
"Comfy Layout": "Comfy Layout",
"Hide Junk": "Hide Junk",
"Default": "Default",
"Dock": "Dock",
"Hide": "Hide",
"Enable Output Gallery Sidebar": "Enable Output Gallery Sidebar"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "Cola",
"Search History": "Buscar en el historial",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Ignorar/Incluir nodo(s) seleccionado(s) (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "No hay nodos seleccionados. Haz clic primero en un nodo del lienzo.",
"Renumber All Nodes by Execution Order (Alt+R)": "Renumerar nodos por orden de ejecución (Alt+R)",
"Clear Cancelled & Failed": "Limpiar cancelados y fallidos",
"Clear All History": "Limpiar todo el historial",
"Filter by text, images, nodes...": "Filtrar por texto, imágenes, nodos...",
"Clear & Close Search": "Limpiar y cerrar búsqueda",
"Scroll to Top": "Volver arriba",
"Batch of #": "Lote de #",
"Go Back": "Atrás",
"Go Back to Queue": "Volver a la cola",
"Outputs of #": "Salidas de #",
"No separate intermediate outputs found.": "No se encontraron salidas intermedias separadas.",
"Cancel All Pending": "Cancelar todos los pendientes",
"Pending Queue:": "Cola pendiente:",
"tasks": "tareas",
"Download Object": "Descargar objeto",
"Copy to Clipboard": "Copiar al portapapeles",
"Download JSON": "Descargar JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "Eliminar tarjeta (Ctrl para borrar del disco)",
"Delete Card": "Eliminar tarjeta",
"Delete File": "Eliminar archivo",
"Delete Files": "Eliminar archivos",
"Show Node": "Mostrar nodo",
"Show Stopped/Failed Node": "Mostrar nodo detenido o fallido",
"View all intermediate outputs": "Ver todas las salidas intermedias",
"Delete Card (Ctrl+Click to delete from disk)": "Eliminar tarjeta (Ctrl+Clic para borrar del disco)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+Clic de nuevo para borrar del DISCO",
"Click again to confirm removing card": "Haz clic de nuevo para confirmar la eliminación",
"Remove from batch (Hold Ctrl to delete file from disk)": "Quitar del lote (Ctrl para borrar del disco)",
"Click again to confirm removing from batch": "Haz clic de nuevo para quitar del lote",
"Delete node output (Hold Ctrl to delete file from disk)": "Eliminar salida (Ctrl para borrar del disco)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+Clic de nuevo para borrar del DISCO",
"Click again to confirm removing output": "Haz clic de nuevo para eliminar la salida",
"Moved file to Recycle Bin.": "Archivo movido a la papelera.",
"Permanently deleted file.": "Archivo eliminado permanentemente.",
"Cancelled": "Cancelado",
"Error": "Error",
"Warning": "Advertencia",
"Cancel Queued Task": "Cancelar tarea en cola",
"Interrupt Execution": "Interrumpir ejecución",
"Click to read full text": "Haz clic para leer el texto completo",
"No Outputs": "Sin salidas",
"Processing...": "Procesando...",
"Finishing...": "Finalizando...",
"No workflow metadata found in this file.": "No se encontraron metadatos de flujo en este archivo.",
"Open Folder": "Abrir carpeta",
"Open Location": "Abrir ubicación",
"View all images in this batch": "Ver todas las imágenes de este lote",
"No nodes found on canvas to renumber.": "No se encontraron nodos para renumerar en el lienzo.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "Renumerar reescribirá los ID de todos los nodos según el orden de ejecución.\n\nEsto arregla salidas intermedias mostradas como resultado final, pero puede afectar a scripts externos.\n\n¿Deseas continuar?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "{count} nodos renumerados por orden de ejecución. Último nodo: #{id} ({name}).",
"Failed to renumber nodes: ": "Error al renumerar nodos: ",
"Please select a node first to change its ID.": "Selecciona primero un nodo para cambiar su ID.",
"Enter new ID for node #{id} ({name}):": "Introduce nuevo ID para el nodo #{id} ({name}):",
"Please enter a valid positive number.": "Introduce un número entero positivo válido.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "El ID #{id} ya está en uso por \"{name}\". ¿Intercambiar sus ID?",
"Assigned node ID #{id} to \"{name}\".": "Asignado ID #{id} al nodo \"{name}\".",
"Failed to set node ID: ": "Error al asignar ID de nodo: ",
"Video playback. Press Esc to close.": "Reproducción de video. Pulsa Esc para cerrar.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Clic para zoom (100%/Ajustar) | Shift+Clic en otra tarjeta para comparar.",
"Toggle Loop": "Bucle continuo",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "Proporciones incompatibles ({wA}x{hA} vs {wB}x{hB}). Las imágenes deben tener la misma relación de aspecto para compararse.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Clic para zoom | Arrastra para comparar | Esc para cerrar.",
"Copy": "Copiar",
"Copied!": "¡Copiado!",
"Text Output": "Salida de texto",
"Text Output #": "Salida de texto #",
"Raw Text": "Texto sin formato",
"{wc} words • {chars} chars": "{wc} palabras • {chars} car.",
"3D Model": "Modelo 3D",
"Loading 3D Asset...": "Cargando modelo 3D...",
"Exporting {format}...": "Exportando a {format}...",
"Failed to load 3D engine.": "Error al cargar el motor 3D.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "No se pudieron descargar las bibliotecas 3D. Comprueba tu conexión a Internet.",
"Background Color": "Color de fondo",
"Up Direction": "Orientación vertical",
"Material Mode": "Modo de material",
"Camera Type": "Tipo de cámara",
"FOV": "Campo de visión (FOV)",
"Light Intensity": "Intensidad de luz",
"Original (Y-Up)": "Original (Y arriba)",
"Z-Up (+90°)": "Z arriba (+90°)",
"Inverted (-90°)": "Invertido (-90°)",
"Original / Textured": "Original / Textura",
"Clay / Studio Matte": "Arcilla / Mate",
"Normals": "Normales",
"Perspective": "Perspectiva",
"Orthographic": "Ortográfica",
"Grid": "Cuadrícula",
"Auto-Rotate": "Rotación automática",
"Wireframe": "Malla / Alambre",
"Reset View": "Restablecer vista",
"Settings": "Ajustes",
"Export As...": "Exportar como...",
"Failed to load 3D format": "Error al cargar el formato 3D",
"Toggle Comfy Queue Sidebar": "Alternar barra lateral Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "Ignorar/Incluir nodo(s) seleccionado(s) en la cola",
"Renumber All Nodes (Execution Order)": "Renumerar todos los nodos (orden de ejecución)",
"Set Selected Node ID...": "Establecer ID del nodo seleccionado...",
"Set Node ID...": "Establecer ID de nodo...",
"Gallery": "Galería",
"Gallery (Outputs)": "Galería (Salidas)",
"Go Up One Level": "Subir un nivel",
"Open Current Folder in File Manager": "Abrir carpeta actual en el explorador de archivos",
"Refresh Gallery": "Actualizar galería",
"Filter gallery files...": "Filtrar archivos de la galería...",
"Loading files...": "Cargando archivos...",
"No files found in this folder.": "No se encontraron archivos en esta carpeta.",
"Failed to load gallery from disk.": "Error al cargar la galería desde el disco.",
"Sort: Newest First": "Ordenar: más recientes primero",
"Sort: Oldest First": "Ordenar: más antiguos primero",
"Search Gallery (Filename or Prompt)": "Buscar en galería (nombre de archivo o prompt)",
"Search filenames or prompt metadata...": "Buscar nombres de archivo o metadatos de prompt..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "Umbral de columnas de la cola",
"Width Threshold for Queue Columns (px)": "Ancho en píxeles para dividir la cola en varias columnas",
"Show Pending Count Only": "Mostrar solo total en espera",
"If disabled, each queued job will have a separate individual card": "Si se desactiva, cada tarea en cola tendrá una tarjeta individual",
"Show Working Node Name": "Mostrar nombre del nodo en proceso",
"Shows the name of the node which is currently in the process": "Muestra el nombre del nodo que se está procesando actualmente",
"Auto Clear Interrupted": "Limpieza auto de interrumpidos",
"Auto-clear cancelled & failed jobs on new generation": "Borrar automáticamente tareas canceladas y fallidas al iniciar una nueva generación",
"Permanent Delete on Disk Deletion": "Eliminación permanente del disco",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Eliminar permanentemente archivos al borrarlos (sin pasar por la papelera)",
"Hide Tab: {tab}": "Ocultar pestaña: {tab}",
"Assets": "Recursos",
"Nodes": "Nodos",
"Models": "Modelos",
"Workflows": "Flujos",
"Apps": "Apps",
"Templates": "Plantillas",
"Override Stock History": "Reemplazar historial estándar",
"Replace the stock Job History sidebar with Comfy Queue": "Reemplaza la barra de historial estándar con Comfy Queue",
"Hide Graph Button": "Ocultar botón 'Grafo'",
"Hide floating 'Graph' (Workflow/Node Map) button": "Oculta el botón flotante 'Grafo' (mapa de nodos)",
"Hide Avatar": "Ocultar avatar",
"Floating Canvas Controls": "Controles flotantes del lienzo",
"Classic Layout": "Diseño clásico",
"Places the controls and the open workflow tabs on a single unified top bar": "Coloca los controles y las pestañas abiertas en una barra superior unificada",
"Comfy Layout": "Diseño compacto",
"Hide Junk": "Ocultar elementos innecesarios",
"Default": "Por defecto",
"Dock": "Acoplar",
"Hide": "Ocultar",
"Enable Output Gallery Sidebar": "Habilitar barra lateral de galería de salidas"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "صف",
"Search History": "جستجو در تاریخچه",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "نادیده گرفتن گره‌های انتخابی در صف (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "هیچ گرهی انتخاب نشده است. ابتدا روی یک گره در بوم کلیک کنید.",
"Renumber All Nodes by Execution Order (Alt+R)": "شماره‌گذاری مجدد گره‌ها بر اساس ترتیب اجرا (Alt+R)",
"Clear Cancelled & Failed": "پاک کردن موارد لغو شده و ناموفق",
"Clear All History": "پاک کردن تمام تاریخچه",
"Filter by text, images, nodes...": "فیلتر بر اساس متن، تصویر، گره...",
"Clear & Close Search": "پاک کردن و بستن جستجو",
"Scroll to Top": "رفتن به بالا",
"Batch of #": "دسته #",
"Go Back": "بازگشت",
"Go Back to Queue": "بازگشت به صف",
"Outputs of #": "خروجی‌های #",
"No separate intermediate outputs found.": "هیچ خروجی میانی مجزایی پیدا نشد.",
"Cancel All Pending": "لغو تمام کارهای در انتظار",
"Pending Queue:": "صف در انتظار:",
"tasks": "کار",
"Download Object": "دانلود فایل",
"Copy to Clipboard": "کپی در کلیپ‌بورد",
"Download JSON": "دانلود JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "حذف کارت (Ctrl برای حذف از دیسک)",
"Delete Card": "حذف کارت",
"Delete File": "حذف فایل",
"Delete Files": "حذف فایل‌ها",
"Show Node": "نمایش گره",
"Show Stopped/Failed Node": "نمایش گره متوقف یا ناموفق",
"View all intermediate outputs": "مشاهده تمام خروجی‌های میانی",
"Delete Card (Ctrl+Click to delete from disk)": "حذف کارت (Ctrl+کلیک برای حذف از دیسک)",
"Ctrl+Click again to delete file from DISK / TRASH": "برای حذف نهایی از دیسک مجدداً Ctrl+کلیک کنید",
"Click again to confirm removing card": "برای تأیید حذف مجدداً کلیک کنید",
"Remove from batch (Hold Ctrl to delete file from disk)": "حذف از دسته (Ctrl برای حذف از دیسک)",
"Click again to confirm removing from batch": "برای تأیید حذف از دسته مجدداً کلیک کنید",
"Delete node output (Hold Ctrl to delete file from disk)": "حذف خروجی گره (Ctrl برای حذف از دیسک)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "برای حذف فایل‌های این گره از دیسک مجدداً Ctrl+کلیک کنید",
"Click again to confirm removing output": "برای تأیید حذف خروجی مجدداً کلیک کنید",
"Moved file to Recycle Bin.": "فایل به سطل بازیافت منتقل شد.",
"Permanently deleted file.": "فایل به طور دائمی حذف شد.",
"Cancelled": "لغو شد",
"Error": "خطا",
"Warning": "هشدار",
"Cancel Queued Task": "لغو کار در صف",
"Interrupt Execution": "توقف اجرا",
"Click to read full text": "برای خواندن متن کامل کلیک کنید",
"No Outputs": "بدون خروجی",
"Processing...": "در حال پردازش...",
"Finishing...": "در حال اتمام...",
"No workflow metadata found in this file.": "متاداده جریان کاری در این فایل یافت نشد.",
"Open Folder": "باز کردن پوشه",
"Open Location": "باز کردن مسیر",
"View all images in this batch": "مشاهده تمام تصاویر این دسته",
"No nodes found on canvas to renumber.": "گرهی برای شماره‌گذاری مجدد روی بوم یافت نشد.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "شماره‌گذاری مجدد، شناسه تمام گره‌ها را طبق ترتیب اجرا بازنویسی می‌کند.\n\nاین کار خروجی‌های میانی را اصلاح می‌کند اما ممکن است اسکریپت‌های وابسته به شناسه‌ها را مختل کند.\n\nآیا ادامه می‌دهید؟",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "{count} گره طبق ترتیب اجرا شماره‌گذاری شدند. آخرین گره: #{id} ({name}).",
"Failed to renumber nodes: ": "شماره‌گذاری مجدد گره‌ها ناموفق بود: ",
"Please select a node first to change its ID.": "لطفاً ابتدا یک گره را برای تغییر شناسه انتخاب کنید.",
"Enter new ID for node #{id} ({name}):": "شناسه جدید برای گره #{id} ({name}) را وارد کنید:",
"Please enter a valid positive number.": "لطفاً یک عدد صحیح مثبت معتبر وارد کنید.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "شناسه #{id} قبلاً توسط \"{name}\" استفاده شده است. آیا می‌خواهید شناسه‌ها جابجا شوند؟",
"Assigned node ID #{id} to \"{name}\".": "شناسه #{id} به گره \"{name}\" اختصاص یافت.",
"Failed to set node ID: ": "تنظیم شناسه گره ناموفق بود: ",
"Video playback. Press Esc to close.": "پخش ویدیو. برای بستن Esc را بزنید.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "کلیک برای بزرگنمایی (100%/تناسب) | Shift+کلیک روی کارت دیگر برای مقایسه.",
"Toggle Loop": "تکرار پخش",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "عدم تطابق نسبت ابعاد ({wA}x{hA} در برابر {wB}x{hB}). تصاویر برای مقایسه باید نسبت برابری داشته باشند.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "کلیک برای بزرگنمایی | کشیدن اسلایدر برای مقایسه | Esc برای بستن.",
"Copy": "کپی",
"Copied!": "کپی شد!",
"Text Output": "خروجی متنی",
"Text Output #": "خروجی متنی #",
"Raw Text": "متن خام",
"{wc} words • {chars} chars": "{wc} کلمه • {chars} نویسه",
"3D Model": "مدل 3D",
"Loading 3D Asset...": "در حال بارگذاری مدل سه‌بعدی...",
"Exporting {format}...": "در حال صدور به فرمت {format}...",
"Failed to load 3D engine.": "موتور سه‌بعدی بارگذاری نشد.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "امکان دانلود کتابخانه‌های 3D وجود ندارد. اتصال اینترنت خود را بررسی کنید.",
"Background Color": "رنگ پس‌زمینه",
"Up Direction": "جهت بالا",
"Material Mode": "حالت متریال",
"Camera Type": "نوع دوربین",
"FOV": "میدان دید (FOV)",
"Light Intensity": "شدت نور",
"Original (Y-Up)": "اصلی (Y رو به بالا)",
"Z-Up (+90°)": "Z رو به بالا (+90°)",
"Inverted (-90°)": "معکوس (-90°)",
"Original / Textured": "اصلی / بافت‌دار",
"Clay / Studio Matte": "گلی / مات استودیویی",
"Normals": "نرمال‌ها",
"Perspective": "پرسپکتیو",
"Orthographic": "ارتوگرافیک",
"Grid": "شبکه",
"Auto-Rotate": "چرخش خودکار",
"Wireframe": "قاب سیمی (Wireframe)",
"Reset View": "بازنشانی دید",
"Settings": "تنظیمات",
"Export As...": "صادرات به عنوان...",
"Failed to load 3D format": "بارگذاری فرمت 3D ناموفق بود",
"Toggle Comfy Queue Sidebar": "تغییر وضعیت نوار کناری Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "نادیده گرفتن/فعال‌سازی گره‌های انتخاب‌شده در صف",
"Renumber All Nodes (Execution Order)": "شماره‌گذاری مجدد همه گره‌ها (ترتیب اجرا)",
"Set Selected Node ID...": "تنظیم شناسه گره انتخاب‌شده...",
"Set Node ID...": "تنظیم شناسه گره...",
"Gallery": "گالری",
"Gallery (Outputs)": "گالری (خروجی‌ها)",
"Go Up One Level": "یک سطح به بالا",
"Open Current Folder in File Manager": "باز کردن پوشه فعلی در مدیریت فایل",
"Refresh Gallery": "به‌روزرسانی گالری",
"Filter gallery files...": "فیلتر کردن فایل‌های گالری...",
"Loading files...": "در حال بارگذاری فایل‌ها...",
"No files found in this folder.": "هیچ فایلی در این پوشه یافت نشد.",
"Failed to load gallery from disk.": "بارگذاری گالری از دیسک ناموفق بود.",
"Sort: Newest First": "مرتب‌سازی: جدیدترین‌ها در ابتدا",
"Sort: Oldest First": "مرتب‌سازی: قدیمی‌ترین‌ها در ابتدا",
"Search Gallery (Filename or Prompt)": "جستجو در گالری (نام فایل یا پرامپت)",
"Search filenames or prompt metadata...": "جستجوی نام فایل‌ها یا متادیتای پرامپت..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "آستانه ستون‌های صف",
"Width Threshold for Queue Columns (px)": "عرض بر حسب پیکسل برای تقسیم صف به چند ستون",
"Show Pending Count Only": "فقط نمایش تعداد در انتظار",
"If disabled, each queued job will have a separate individual card": "در صورت غیرفعال بودن، هر کار در صف یک کارت جداگانه خواهد داشت",
"Show Working Node Name": "نمایش نام گره در حال پردازش",
"Shows the name of the node which is currently in the process": "نام گرهی را که در حال حاضر پردازش می‌شود نشان می‌دهد",
"Auto Clear Interrupted": "پاکسازی خودکار متوقف‌شده‌ها",
"Auto-clear cancelled & failed jobs on new generation": "پاک کردن خودکار کارهای لغو شده و ناموفق در تولید جدید",
"Permanent Delete on Disk Deletion": "حذف دائمی از دیسک",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "حذف دائمی فایل‌ها هنگام پاک کردن از دیسک (بدون انتقال به سطل بازیافت)",
"Hide Tab: {tab}": "پنهان کردن برگه: {tab}",
"Assets": "دارایی‌ها",
"Nodes": "گره‌ها",
"Models": "مدل‌ها",
"Workflows": "جریان‌های کاری",
"Apps": "برنامه‌ها",
"Templates": "الگوها",
"Override Stock History": "جایگزینی تاریخچه پیش‌فرض",
"Replace the stock Job History sidebar with Comfy Queue": "نوار کناری تاریخچه کارهای پیش‌فرض را با Comfy Queue جایگزین می‌کند",
"Hide Graph Button": "پنهان کردن دکمه 'نمودار'",
"Hide floating 'Graph' (Workflow/Node Map) button": "دکمه شناور 'نمودار' (نقشه گره‌ها) را پنهان می‌کند",
"Hide Avatar": "پنهان کردن آواتار",
"Floating Canvas Controls": "کنترل‌های شناور بوم",
"Classic Layout": "طرح‌بندی کلاسیک",
"Places the controls and the open workflow tabs on a single unified top bar": "کنترل‌ها و برگه‌های باز جریان کار را در یک نوار بالایی یکپارچه قرار می‌دهد",
"Comfy Layout": "طرح‌بندی فشرده",
"Hide Junk": "پنهان کردن موارد غیرضروری",
"Default": "پیش‌فرض",
"Dock": "اتصال",
"Hide": "پنهان",
"Enable Output Gallery Sidebar": "فعال‌سازی نوار کناری گالری خروجی‌ها"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "File d'attente",
"Search History": "Rechercher dans l'historique",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Ignorer/Activer les nœuds sélectionnés (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "Aucun nœud sélectionné. Cliquez d'abord sur un nœud du canevas.",
"Renumber All Nodes by Execution Order (Alt+R)": "Renuméroter tous les nœuds selon l'ordre d'exécution (Alt+R)",
"Clear Cancelled & Failed": "Effacer annulés et échoués",
"Clear All History": "Effacer tout l'historique",
"Filter by text, images, nodes...": "Filtrer par texte, image, nœud...",
"Clear & Close Search": "Effacer et fermer la recherche",
"Scroll to Top": "Haut de page",
"Batch of #": "Lot de #",
"Go Back": "Retour",
"Go Back to Queue": "Retour à la file",
"Outputs of #": "Sorties de #",
"No separate intermediate outputs found.": "Aucune sortie intermédiaire distincte trouvée.",
"Cancel All Pending": "Tout annuler en attente",
"Pending Queue:": "File d'attente:",
"tasks": "tâches",
"Download Object": "Télécharger l'objet",
"Copy to Clipboard": "Copier dans le presse-papier",
"Download JSON": "Télécharger le JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "Supprimer la carte (Ctrl pour supprimer du disque)",
"Delete Card": "Supprimer la carte",
"Delete File": "Supprimer le fichier",
"Delete Files": "Supprimer les fichiers",
"Show Node": "Afficher le nœud",
"Show Stopped/Failed Node": "Afficher le nœud arrêté/échoué",
"View all intermediate outputs": "Voir toutes les sorties intermédiaires",
"Delete Card (Ctrl+Click to delete from disk)": "Supprimer la carte (Ctrl+Clic pour supprimer du disque)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+Clic à nouveau pour supprimer du DISQUE",
"Click again to confirm removing card": "Cliquez à nouveau pour confirmer la suppression",
"Remove from batch (Hold Ctrl to delete file from disk)": "Retirer du lot (Ctrl pour supprimer du disque)",
"Click again to confirm removing from batch": "Cliquez à nouveau pour confirmer le retrait",
"Delete node output (Hold Ctrl to delete file from disk)": "Supprimer la sortie (Ctrl pour supprimer du disque)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+Clic à nouveau pour supprimer les fichiers du DISQUE",
"Click again to confirm removing output": "Cliquez à nouveau pour supprimer la sortie",
"Moved file to Recycle Bin.": "Fichier déplacé dans la corbeille.",
"Permanently deleted file.": "Fichier définitivement supprimé.",
"Cancelled": "Annulé",
"Error": "Erreur",
"Warning": "Avertissement",
"Cancel Queued Task": "Annuler la tâche",
"Interrupt Execution": "Interrompre l'exécution",
"Click to read full text": "Cliquer pour lire le texte complet",
"No Outputs": "Aucune sortie",
"Processing...": "Traitement...",
"Finishing...": "Finalisation...",
"No workflow metadata found in this file.": "Aucune métadonnée de workflow trouvée dans ce fichier.",
"Open Folder": "Ouvrir le dossier",
"Open Location": "Emplacement du fichier",
"View all images in this batch": "Voir toutes les images de ce lot",
"No nodes found on canvas to renumber.": "Aucun nœud à renuméroter sur le canevas.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "La renumérotation réécrira tous les identifiants de nœuds selon l'ordre d'exécution.\n\nCela corrige l'affichage des sorties intermédiaires, mais peut affecter les scripts externes dépendant d'identifiants précis.\n\nVoulez-vous continuer ?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "{count} nœuds renumérotés par ordre d'exécution. Dernier nœud : #{id} ({name}).",
"Failed to renumber nodes: ": "Échec de la renumérotation : ",
"Please select a node first to change its ID.": "Veuillez d'abord sélectionner un nœud pour modifier son ID.",
"Enter new ID for node #{id} ({name}):": "Entrez le nouvel ID pour le nœud #{id} ({name}) :",
"Please enter a valid positive number.": "Veuillez entrer un entier positif valide.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "L'ID #{id} est déjà utilisé par \"{name}\". Échanger leurs ID ?",
"Assigned node ID #{id} to \"{name}\".": "ID #{id} assigné au nœud \"{name}\".",
"Failed to set node ID: ": "Échec de l'assignation de l'ID : ",
"Video playback. Press Esc to close.": "Lecture vidéo. Appuyez sur Échap pour fermer.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Cliquer pour zoomer (100%/Ajuster) | Shift+Clic sur une autre carte pour comparer.",
"Toggle Loop": "Lecture en boucle",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "Proportions incompatibles ({wA}x{hA} vs {wB}x{hB}). Les images doivent avoir le même ratio pour être comparées.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Cliquer pour zoomer | Glisser le curseur pour comparer | Échap pour fermer.",
"Copy": "Copier",
"Copied!": "Copié !",
"Text Output": "Sortie texte",
"Text Output #": "Sortie texte #",
"Raw Text": "Texte brut",
"{wc} words • {chars} chars": "{wc} mots • {chars} car.",
"3D Model": "Modèle 3D",
"Loading 3D Asset...": "Chargement de l'élément 3D...",
"Exporting {format}...": "Exportation au format {format}...",
"Failed to load 3D engine.": "Échec du chargement du moteur 3D.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "Impossible de télécharger les bibliothèques 3D. Vérifiez votre connexion Internet.",
"Background Color": "Couleur d'arrière-plan",
"Up Direction": "Orientation vers le haut",
"Material Mode": "Mode de rendu",
"Camera Type": "Type de caméra",
"FOV": "Champ de vision (FOV)",
"Light Intensity": "Intensité de la lumière",
"Original (Y-Up)": "Original (Y-Haut)",
"Z-Up (+90°)": "Z-Haut (+90°)",
"Inverted (-90°)": "Inversé (-90°)",
"Original / Textured": "Original / Texturé",
"Clay / Studio Matte": "Argile / Mat",
"Normals": "Normales",
"Perspective": "Perspective",
"Orthographic": "Orthographique",
"Grid": "Grille",
"Auto-Rotate": "Rotation auto",
"Wireframe": "Filaire",
"Reset View": "Réinitialiser la vue",
"Settings": "Paramètres",
"Export As...": "Exporter sous...",
"Failed to load 3D format": "Échec du chargement du format 3D",
"Toggle Comfy Queue Sidebar": "Basculer la barre latérale Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "Ignorer/Activer les nœuds sélectionnés dans la file",
"Renumber All Nodes (Execution Order)": "Renuméroter tous les nœuds (ordre d'exécution)",
"Set Selected Node ID...": "Définir l'ID du nœud sélectionné...",
"Set Node ID...": "Définir l'ID du nœud...",
"Gallery": "Galerie",
"Gallery (Outputs)": "Galerie (Sorties)",
"Go Up One Level": "Dossier parent",
"Open Current Folder in File Manager": "Ouvrir le dossier actuel dans le gestionnaire de fichiers",
"Refresh Gallery": "Actualiser la galerie",
"Filter gallery files...": "Filtrer les fichiers de la galerie...",
"Loading files...": "Chargement des fichiers...",
"No files found in this folder.": "Aucun fichier trouvé dans ce dossier.",
"Failed to load gallery from disk.": "Échec du chargement de la galerie depuis le disque.",
"Sort: Newest First": "Trier : Plus récents d'abord",
"Sort: Oldest First": "Trier : Plus anciens d'abord",
"Search Gallery (Filename or Prompt)": "Rechercher dans la galerie (nom de fichier ou prompt)",
"Search filenames or prompt metadata...": "Rechercher des noms de fichiers ou métadonnées de prompt..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "Seuil de colonnes",
"Width Threshold for Queue Columns (px)": "Largeur en pixels pour diviser la file en plusieurs colonnes",
"Show Pending Count Only": "Afficher uniquement le total en attente",
"If disabled, each queued job will have a separate individual card": "Si désactivé, chaque tâche en file aura une carte individuelle",
"Show Working Node Name": "Afficher le nom du nœud actif",
"Shows the name of the node which is currently in the process": "Affiche le nom du nœud en cours de traitement",
"Auto Clear Interrupted": "Nettoyage auto des interruptions",
"Auto-clear cancelled & failed jobs on new generation": "Effacer automatiquement les tâches annulées et échouées lors d'une nouvelle génération",
"Permanent Delete on Disk Deletion": "Suppression définitive du disque",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Supprimer définitivement les fichiers lors de la suppression (sans passer par la corbeille)",
"Hide Tab: {tab}": "Masquer l'onglet : {tab}",
"Assets": "Ressources",
"Nodes": "Nœuds",
"Models": "Modèles",
"Workflows": "Workflows",
"Apps": "Applications",
"Templates": "Modèles",
"Override Stock History": "Remplacer l'historique par défaut",
"Replace the stock Job History sidebar with Comfy Queue": "Remplace la barre latérale d'historique par défaut par Comfy Queue",
"Hide Graph Button": "Masquer le bouton 'Graphe'",
"Hide floating 'Graph' (Workflow/Node Map) button": "Masque le bouton flottant 'Graphe' (carte des nœuds)",
"Hide Avatar": "Masquer l'avatar",
"Floating Canvas Controls": "Contrôles flottants du canevas",
"Classic Layout": "Disposition classique",
"Places the controls and the open workflow tabs on a single unified top bar": "Regroupe les contrôles et les onglets ouverts dans une barre supérieure unique",
"Comfy Layout": "Disposition compacte",
"Hide Junk": "Masquer les éléments inutiles",
"Default": "Par défaut",
"Dock": "Ancrer",
"Hide": "Masquer",
"Enable Output Gallery Sidebar": "Activer la barre latérale de la galerie de sorties"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "תור",
"Search History": "חיפוש בהיסטוריה",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "התעלם/כלול צמתים נבחרים בתור (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "לא נבחר צומת. לחץ תחילה על צומת בלוח.",
"Renumber All Nodes by Execution Order (Alt+R)": "מספר מחדש את כל הצמתים לפי סדר ביצוע (Alt+R)",
"Clear Cancelled & Failed": "נקה מבוטלים ונכשלים",
"Clear All History": "נקה את כל ההיסטוריה",
"Filter by text, images, nodes...": "סנן לפי טקסט, תמונה, צומת...",
"Clear & Close Search": "נקה וסגור חיפוש",
"Scroll to Top": "גלול למעלה",
"Batch of #": "אצווה #",
"Go Back": "חזור",
"Go Back to Queue": "חזור לתור",
"Outputs of #": "תוצרים של #",
"No separate intermediate outputs found.": "לא נמצאו תוצרי ביניים נפרדים.",
"Cancel All Pending": "בטל את כל המשימות הממתינות",
"Pending Queue:": "ממתינים בתור:",
"tasks": "משימות",
"Download Object": "הורד קובץ",
"Copy to Clipboard": "העתק ללוח",
"Download JSON": "הורד JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "מחק כרטיס (Ctrl למחיקה מהדיסק)",
"Delete Card": "מחק כרטיס",
"Delete File": "מחק קובץ",
"Delete Files": "מחק קבצים",
"Show Node": "הצג צומת",
"Show Stopped/Failed Node": "הצג צומת שנעצר או נכשל",
"View all intermediate outputs": "הצג את כל תוצרי הביניים",
"Delete Card (Ctrl+Click to delete from disk)": "מחק כרטיס (Ctrl+לחיצה למחיקה מהדיסק)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+לחיצה שוב למחיקה לצמיתות מהדיסק",
"Click again to confirm removing card": "לחץ שוב לאישור ההסרה",
"Remove from batch (Hold Ctrl to delete file from disk)": "הסר מהאצווה (Ctrl למחיקה מהדיסק)",
"Click again to confirm removing from batch": "לחץ שוב לאישור הסרה מהאצווה",
"Delete node output (Hold Ctrl to delete file from disk)": "מחק תוצר צומת (Ctrl למחיקה מהדיסק)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+לחיצה שוב למחיקת קבצי הצומת מהדיסק",
"Click again to confirm removing output": "לחץ שוב לאישור הסרת התוצר",
"Moved file to Recycle Bin.": "הקובץ הועבר לסל המיחזור.",
"Permanently deleted file.": "הקובץ נמחק לצמיתות.",
"Cancelled": "בוטל",
"Error": "שגיאה",
"Warning": "אזהרה",
"Cancel Queued Task": "בטל משימה בתור",
"Interrupt Execution": "הפסק ביצוע",
"Click to read full text": "לחץ לקריאת הטקסט המלא",
"No Outputs": "אין תוצרים",
"Processing...": "מעבד...",
"Finishing...": "מסיים...",
"No workflow metadata found in this file.": "לא נמצאו מטא-נתוני תהליך עבודה בקובץ זה.",
"Open Folder": "פתח תיקייה",
"Open Location": "פתח מיקום קובץ",
"View all images in this batch": "הצג את כל התמונות באצווה זו",
"No nodes found on canvas to renumber.": "לא נמצאו צמתים למספור מחדש בלוח.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "מספור מחדש ישכתב את מזהי כל הצמתים לפי סדר הביצוע.\n\nפעולה זו מתקנת תוצרי ביניים שמופיעים כתוצאה סופית, אך עלולה לפגוע בסקריפטים חיצוניים המסתמכים על מזהים קבועים.\n\nהאם להמשיך?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "מוספרו מחדש {count} צמתים לפי סדר ביצוע. צומת אחרון: #{id} ({name}).",
"Failed to renumber nodes: ": "נכשל מספור מחדש של צמתים: ",
"Please select a node first to change its ID.": "אנא בחר צומת תחילה כדי לשנות את המזהה שלו.",
"Enter new ID for node #{id} ({name}):": "הזן מזהה חדש לצומת #{id} ({name}):",
"Please enter a valid positive number.": "אנא הזן מספר חיובי שלם תקין.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "המזהה #{id} כבר בשימוש על ידי \"{name}\". האם להחליף ביניהם?",
"Assigned node ID #{id} to \"{name}\".": "המזהה #{id} הוקצה לצומת \"{name}\".",
"Failed to set node ID: ": "נכשל בהגדרת מזהה צומת: ",
"Video playback. Press Esc to close.": "הפעלת וידאו. לחץ Esc לסגירה.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "לחץ להגדלה (100%/התאמה) | Shift+לחיצה על כרטיס אחר להשוואה.",
"Toggle Loop": "הפעל/השבת חזרה",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "חוסר התאמה ביחס הגבהים ({wA}x{hA} מול {wB}x{hB}). התמונות חייבות להיות באותו יחס כדי להשוות.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "לחץ להגדלה | גרור את המחוון להשוואה | Esc לסגירה.",
"Copy": "העתק",
"Copied!": "הועתק!",
"Text Output": "תוצר טקסט",
"Text Output #": "תוצר טקסט #",
"Raw Text": "טקסט גולמי",
"{wc} words • {chars} chars": "{wc} מילים • {chars} תווים",
"3D Model": "דגם 3D",
"Loading 3D Asset...": "טוען אלמנט תלת-ממדי...",
"Exporting {format}...": "מייצא בפורמט {format}...",
"Failed to load 3D engine.": "טעינת מנוע 3D נכשלה.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "לא ניתן להוריד ספריות 3D. ודא שהמחשב מחובר לאינטרנט.",
"Background Color": "צבע רקע",
"Up Direction": "כיוון למעלה",
"Material Mode": "מצב חומר",
"Camera Type": "סוג מצלמה",
"FOV": "שדה ראייה (FOV)",
"Light Intensity": "עוצמת תאורה",
"Original (Y-Up)": "מקורי (Y למעלה)",
"Z-Up (+90°)": "Z למעלה (+90°)",
"Inverted (-90°)": "הפוך (-90°)",
"Original / Textured": "מקורי / טקסטורה",
"Clay / Studio Matte": "חימר / מט",
"Normals": "נורמלים",
"Perspective": "פרספקטיבה",
"Orthographic": "אורתוגרפי",
"Grid": "רשת",
"Auto-Rotate": "סיבוב אוטומטי",
"Wireframe": "שלד קווי (Wireframe)",
"Reset View": "אפס תצוגה",
"Settings": "הגדרות",
"Export As...": "ייצא כ...",
"Failed to load 3D format": "טעינת פורמט 3D נכשלה",
"Toggle Comfy Queue Sidebar": "הפעל/השבת סרגל צד Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "התעלם/כלול צמתים נבחרים בתור",
"Renumber All Nodes (Execution Order)": "מספר מחדש את כל הצמתים (סדר ביצוע)",
"Set Selected Node ID...": "הגדר מזהה צומת נבחר...",
"Set Node ID...": "הגדר מזהה צומת...",
"Gallery": "גלריה",
"Gallery (Outputs)": "גלריה (תוצרים)",
"Go Up One Level": "עלה שלב אחד למעלה",
"Open Current Folder in File Manager": "פתח תיקייה נוכחית בסייר הקבצים",
"Refresh Gallery": "רענן גלריה",
"Filter gallery files...": "סנן קבצי גלריה...",
"Loading files...": "טוען קבצים...",
"No files found in this folder.": "לא נמצאו קבצים בתיקייה זו.",
"Failed to load gallery from disk.": "טעינת הגלריה מהכונן נכשלה.",
"Sort: Newest First": "מיון: החדשים ביותר קודם",
"Sort: Oldest First": "מיון: הישנים ביותר קודם",
"Search Gallery (Filename or Prompt)": "חיפוש בגלריה (שם קובץ או פרומפט)",
"Search filenames or prompt metadata...": "חיפוש שמות קבצים או מטא-דאטה של פרומפט..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "סף עמודות תור",
"Width Threshold for Queue Columns (px)": "רוחב בפיקסלים לחלוקת התור לעמודות מרובות",
"Show Pending Count Only": "הצג רק ספירת ממתינים",
"If disabled, each queued job will have a separate individual card": "אם מושבת, לכל משימה בתור יהיה כרטיס נפרד",
"Show Working Node Name": "הצג שם צומת פעיל",
"Shows the name of the node which is currently in the process": "מציג את שם הצומת המעובד כעת",
"Auto Clear Interrupted": "ניקוי אוטומטי של משימות שהופסקו",
"Auto-clear cancelled & failed jobs on new generation": "נקה אוטומטית משימות שבוטלו או נכשלו בעת יצירה חדשה",
"Permanent Delete on Disk Deletion": "מחיקה לצמיתות מהדיסק",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "מחק קבצים לצמיתות בעת מחיקה (עוקף את סל המיחזור)",
"Hide Tab: {tab}": "הסתר לשונית: {tab}",
"Assets": "נכסים",
"Nodes": "צמתים",
"Models": "מודלים",
"Workflows": "תהליכי עבודה",
"Apps": "יישומים",
"Templates": "תבניות",
"Override Stock History": "החלף היסטוריית ברירת מחדל",
"Replace the stock Job History sidebar with Comfy Queue": "מחליף את סרגל הצד של היסטוריית העבודות הרגילה ב-Comfy Queue",
"Hide Graph Button": "הסתר כפתור 'גרף'",
"Hide floating 'Graph' (Workflow/Node Map) button": "מסתיר את הכפתור הצף 'גרף' (מפת הצמתים)",
"Hide Avatar": "הסתר אווטאר",
"Floating Canvas Controls": "פקדי לוח צפים",
"Classic Layout": "פריסה קלאסית",
"Places the controls and the open workflow tabs on a single unified top bar": "ממקם את הפקדים ואת לשוניות תהליך העבודה הפתוחות בסרגל עליון מאוחד",
"Comfy Layout": "פריסה קומפקטית",
"Hide Junk": "הסתר פריטים מיותרים",
"Default": "ברירת מחדל",
"Dock": "הצמד",
"Hide": "הסתר",
"Enable Output Gallery Sidebar": "הפעל סרגל צד של גלריית תוצרים"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "Coda",
"Search History": "Cerca nella cronologia",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Ignora/Attiva nodo/i selezionato/i (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "Nessun nodo selezionato. Clicca prima su un nodo nell'area di lavoro.",
"Renumber All Nodes by Execution Order (Alt+R)": "Rinumera i nodi per ordine di esecuzione (Alt+R)",
"Clear Cancelled & Failed": "Cancella annullati e falliti",
"Clear All History": "Cancella tutta la cronologia",
"Filter by text, images, nodes...": "Filtra per testo, immagini, nodi...",
"Clear & Close Search": "Cancella e chiudi ricerca",
"Scroll to Top": "Torna in cima",
"Batch of #": "Lotto di #",
"Go Back": "Indietro",
"Go Back to Queue": "Torna alla coda",
"Outputs of #": "Uscite di #",
"No separate intermediate outputs found.": "Nessuna uscita intermedia separata trovata.",
"Cancel All Pending": "Annulla tutti i task in attesa",
"Pending Queue:": "In attesa:",
"tasks": "attività",
"Download Object": "Scarica elemento",
"Copy to Clipboard": "Copia negli appunti",
"Download JSON": "Scarica JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "Elimina scheda (Ctrl per eliminare dal disco)",
"Delete Card": "Elimina scheda",
"Delete File": "Elimina file",
"Delete Files": "Elimina file",
"Show Node": "Mostra nodo",
"Show Stopped/Failed Node": "Mostra nodo fermato o fallito",
"View all intermediate outputs": "Visualizza tutte le uscite intermedie",
"Delete Card (Ctrl+Click to delete from disk)": "Elimina scheda (Ctrl+Clic per cancellare dal disco)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+Clic di nuovo per eliminare definitivamente",
"Click again to confirm removing card": "Clicca di nuovo per confermare l'eliminazione",
"Remove from batch (Hold Ctrl to delete file from disk)": "Rimuovi dal lotto (Ctrl per eliminare dal disco)",
"Click again to confirm removing from batch": "Clicca di nuovo per rimuovere dal lotto",
"Delete node output (Hold Ctrl to delete file from disk)": "Elimina uscita nodo (Ctrl per eliminare dal disco)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+Clic di nuovo per eliminare i file dal disco",
"Click again to confirm removing output": "Clicca di nuovo per confermare l'eliminazione",
"Moved file to Recycle Bin.": "File spostato nel cestino.",
"Permanently deleted file.": "File eliminato definitivamente.",
"Cancelled": "Annullato",
"Error": "Errore",
"Warning": "Avviso",
"Cancel Queued Task": "Annulla task in coda",
"Interrupt Execution": "Interrompi esecuzione",
"Click to read full text": "Clicca per leggere il testo completo",
"No Outputs": "Nessuna uscita",
"Processing...": "Elaborazione...",
"Finishing...": "Completamento...",
"No workflow metadata found in this file.": "Nessun metadato di workflow trovato in questo file.",
"Open Folder": "Apri cartella",
"Open Location": "Apri percorso",
"View all images in this batch": "Mostra tutte le immagini del lotto",
"No nodes found on canvas to renumber.": "Nessun nodo trovato da rinumerare.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "La rinumerazione riscriverà gli ID di tutti i nodi nell'ordine di esecuzione.\n\nQuesto risolverà le uscite intermedie mostrate come risultato finale, ma potrebbe interferire con script esterni.\n\nVuoi continuare?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "Rinumerati {count} nodi in ordine di esecuzione. Ultimo nodo: #{id} ({name}).",
"Failed to renumber nodes: ": "Errore nella rinumerazione dei nodi: ",
"Please select a node first to change its ID.": "Seleziona prima un nodo per cambiarne l'ID.",
"Enter new ID for node #{id} ({name}):": "Inserisci il nuovo ID per il nodo #{id} ({name}):",
"Please enter a valid positive number.": "Inserisci un numero intero positivo valido.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "L'ID #{id} è già utilizzato da \"{name}\". Vuoi scambiarli?",
"Assigned node ID #{id} to \"{name}\".": "Assegnato ID #{id} al nodo \"{name}\".",
"Failed to set node ID: ": "Errore nell'impostazione dell'ID: ",
"Video playback. Press Esc to close.": "Riproduzione video. Premi Esc per chiudere.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Clicca per ingrandire (100%/Adatta) | Shift+Clic su un'altra scheda per confrontare.",
"Toggle Loop": "Riproduzione continua",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "Proporzioni diverse ({wA}x{hA} vs {wB}x{hB}). Le immagini devono avere lo stesso formato per essere confrontate.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Clicca per ingrandire | Trascina per confrontare | Esc per chiudere.",
"Copy": "Copia",
"Copied!": "Copiato!",
"Text Output": "Uscita testo",
"Text Output #": "Uscita testo #",
"Raw Text": "Testo non formattato",
"{wc} words • {chars} chars": "{wc} parole • {chars} car.",
"3D Model": "Modello 3D",
"Loading 3D Asset...": "Caricamento modello 3D...",
"Exporting {format}...": "Esportazione in {format}...",
"Failed to load 3D engine.": "Caricamento motore 3D non riuscito.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "Impossibile scaricare le librerie 3D. Verifica la connessione Internet.",
"Background Color": "Colore di sfondo",
"Up Direction": "Direzione verso l'alto",
"Material Mode": "Modalità materiale",
"Camera Type": "Tipo di telecamera",
"FOV": "Campo visivo (FOV)",
"Light Intensity": "Intensità luce",
"Original (Y-Up)": "Originale (Y verso l'alto)",
"Z-Up (+90°)": "Z verso l'alto (+90°)",
"Inverted (-90°)": "Invertito (-90°)",
"Original / Textured": "Originale / Texture",
"Clay / Studio Matte": "Argilla / Opaco",
"Normals": "Normali",
"Perspective": "Prospettiva",
"Orthographic": "Ortografica",
"Grid": "Griglia",
"Auto-Rotate": "Rotazione automatica",
"Wireframe": "Reticolo / Wireframe",
"Reset View": "Ripristina visuale",
"Settings": "Impostazioni",
"Export As...": "Esporta come...",
"Failed to load 3D format": "Caricamento formato 3D non riuscito",
"Toggle Comfy Queue Sidebar": "Attiva/Disattiva barra laterale Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "Ignora/Attiva nodi selezionati nella coda",
"Renumber All Nodes (Execution Order)": "Rinumera tutti i nodi (ordine di esecuzione)",
"Set Selected Node ID...": "Imposta ID nodo selezionato...",
"Set Node ID...": "Imposta ID nodo...",
"Gallery": "Galleria",
"Gallery (Outputs)": "Galleria (Output)",
"Go Up One Level": "Sali di un livello",
"Open Current Folder in File Manager": "Apri cartella corrente in Esplora file",
"Refresh Gallery": "Aggiorna galleria",
"Filter gallery files...": "Filtra file della galleria...",
"Loading files...": "Caricamento file...",
"No files found in this folder.": "Nessun file trovato in questa cartella.",
"Failed to load gallery from disk.": "Impossibile caricare la galleria dal disco.",
"Sort: Newest First": "Ordina: Più recenti prima",
"Sort: Oldest First": "Ordina: Più vecchi prima",
"Search Gallery (Filename or Prompt)": "Cerca nella galleria (nome file o prompt)",
"Search filenames or prompt metadata...": "Cerca nomi di file o metadati del prompt..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "Soglia colonne coda",
"Width Threshold for Queue Columns (px)": "Larghezza in pixel per dividere la coda in più colonne",
"Show Pending Count Only": "Mostra solo conteggio in attesa",
"If disabled, each queued job will have a separate individual card": "Se disabilitato, ogni task in coda avrà una scheda separata",
"Show Working Node Name": "Mostra nome nodo in elaborazione",
"Shows the name of the node which is currently in the process": "Mostra il nome del nodo attualmente in elaborazione",
"Auto Clear Interrupted": "Pulizia automatica interrotti",
"Auto-clear cancelled & failed jobs on new generation": "Cancella automaticamente i task annullati e falliti a ogni nuova generazione",
"Permanent Delete on Disk Deletion": "Eliminazione definitiva dal disco",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Elimina definitivamente i file al momento della cancellazione (senza passare dal cestino)",
"Hide Tab: {tab}": "Nascondi scheda: {tab}",
"Assets": "Risorse",
"Nodes": "Nodi",
"Models": "Modelli",
"Workflows": "Flussi di lavoro",
"Apps": "Applicazioni",
"Templates": "Modelli predefiniti",
"Override Stock History": "Sostituisci cronologia standard",
"Replace the stock Job History sidebar with Comfy Queue": "Sostituisce la barra laterale della cronologia standard con Comfy Queue",
"Hide Graph Button": "Nascondi pulsante 'Grafo'",
"Hide floating 'Graph' (Workflow/Node Map) button": "Nasconde il pulsante mobile 'Grafo' (mappa dei nodi)",
"Hide Avatar": "Nascondi avatar",
"Floating Canvas Controls": "Controlli mobili dell'area di lavoro",
"Classic Layout": "Layout classico",
"Places the controls and the open workflow tabs on a single unified top bar": "Posiziona i controlli e le schede aperte su una barra superiore unificata",
"Comfy Layout": "Layout compatto",
"Hide Junk": "Nascondi elementi inutili",
"Default": "Predefinito",
"Dock": "Aggancia",
"Hide": "Nascondi",
"Enable Output Gallery Sidebar": "Abilita barra laterale galleria di output"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "キュー",
"Search History": "履歴を検索",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "選択したノードをキューで無視/解除 (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "ノードが選択されていません。キャンバス上のノードをクリックしてください。",
"Renumber All Nodes by Execution Order (Alt+R)": "実行順にすべてのノード番号を振り直す (Alt+R)",
"Clear Cancelled & Failed": "キャンセルと失敗をクリア",
"Clear All History": "すべての履歴を消去",
"Filter by text, images, nodes...": "テキスト、画像、ノードで絞り込み...",
"Clear & Close Search": "検索をクリアして閉じる",
"Scroll to Top": "トップへスクロール",
"Batch of #": "バッチ #",
"Go Back": "戻る",
"Go Back to Queue": "キューに戻る",
"Outputs of #": "出力 #",
"No separate intermediate outputs found.": "個別のノード中間出力が見つかりません。",
"Cancel All Pending": "待機中のタスクをすべてキャンセル",
"Pending Queue:": "待機キュー:",
"tasks": "件のタスク",
"Download Object": "ファイルをダウンロード",
"Copy to Clipboard": "クリップボードにコピー",
"Download JSON": "JSONをダウンロード",
"Delete Card (Hold Ctrl to delete file from disk)": "カードを削除 (Ctrl長押しでディスクから削除)",
"Delete Card": "カードを削除",
"Delete File": "ファイルを削除",
"Delete Files": "ファイルを削除",
"Show Node": "ノードを表示",
"Show Stopped/Failed Node": "停止・失敗したノードを表示",
"View all intermediate outputs": "すべての中間出力を表示",
"Delete Card (Ctrl+Click to delete from disk)": "カードを削除 (Ctrl+クリックでディスクから削除)",
"Ctrl+Click again to delete file from DISK / TRASH": "ファイルをディスクから削除するには再度Ctrl+クリック",
"Click again to confirm removing card": "再度クリックして削除を確認",
"Remove from batch (Hold Ctrl to delete file from disk)": "バッチから削除 (Ctrlでディスクから削除)",
"Click again to confirm removing from batch": "再度クリックしてバッチからの削除を確認",
"Delete node output (Hold Ctrl to delete file from disk)": "ノード出力を削除 (Ctrlでディスクから削除)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "このノードのファイルを削除するには再度Ctrl+クリック",
"Click again to confirm removing output": "再度クリックして出力を削除",
"Moved file to Recycle Bin.": "ファイルをゴミ箱に移動しました。",
"Permanently deleted file.": "ファイルを完全に削除しました。",
"Cancelled": "キャンセル済み",
"Error": "エラー",
"Warning": "警告",
"Cancel Queued Task": "タスクをキャンセル",
"Interrupt Execution": "実行を中断",
"Click to read full text": "クリックして全文を読む",
"No Outputs": "出力なし",
"Processing...": "処理中...",
"Finishing...": "完了中...",
"No workflow metadata found in this file.": "このファイルにワークフローのメタデータが見つかりません。",
"Open Folder": "フォルダを開く",
"Open Location": "ファイルの場所を開く",
"View all images in this batch": "このバッチのすべての画像を表示",
"No nodes found on canvas to renumber.": "キャンバス上に番号を振り直すノードが見つかりません。",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "ノードの再番号付けは、トポロジカルな実行順序ですべてのIDを書き換えます。\n\nこれにより中間出力が最終結果として表示される問題が修正されますが、特定のIDに依存するスクリプトが動作しなくなる可能性があります。\n\n続行しますか?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "実行順に {count} 個のノードを再番号付けしました。最新ノード: #{id} ({name})。",
"Failed to renumber nodes: ": "ノードの再番号付けに失敗しました: ",
"Please select a node first to change its ID.": "IDを変更するノードを1つ選択してください。",
"Enter new ID for node #{id} ({name}):": "ノード #{id} ({name}) の新しいIDを入力してください:",
"Please enter a valid positive number.": "正の整数を入力してください。",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "ノードID #{id} はすでに \"{name}\" で使用されています。IDを入れ替えますか?",
"Assigned node ID #{id} to \"{name}\".": "ノード \"{name}\" にID #{id} を割り当てました。",
"Failed to set node ID: ": "ノードIDの設定に失敗しました: ",
"Video playback. Press Esc to close.": "動画再生。Escキーで閉じる。",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "画像クリックでズーム (100%/フィット) | Shift+クリックで他のカードと比較",
"Toggle Loop": "ループ再生の切り替え",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "アスペクト比が一致しません ({wA}x{hA} と {wB}x{hB})。比較するには同じ縦横比である必要があります。",
"Click image to zoom | Drag image to compare slider | Esc to close.": "クリックでズーム | ドラッグでスライダー操作 | Escキーで閉じる",
"Copy": "コピー",
"Copied!": "コピーしました!",
"Text Output": "テキスト出力",
"Text Output #": "テキスト出力 #",
"Raw Text": "プレーンテキスト",
"{wc} words • {chars} chars": "{wc} 単語 • {chars} 文字",
"3D Model": "3Dモデル",
"Loading 3D Asset...": "3Dアセットを読み込み中...",
"Exporting {format}...": "{format} 形式でエクスポート中...",
"Failed to load 3D engine.": "3Dエンジンの読み込みに失敗しました。",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "3Dライブラリをダウンロードできません。インターネット接続を確認してください。",
"Background Color": "背景色",
"Up Direction": "上方向の軸",
"Material Mode": "マテリアルモード",
"Camera Type": "カメラの種類",
"FOV": "視野角 (FOV)",
"Light Intensity": "光の強さ",
"Original (Y-Up)": "標準 (Y軸が上)",
"Z-Up (+90°)": "Z軸が上 (+90°)",
"Inverted (-90°)": "反転 (-90°)",
"Original / Textured": "オリジナル / テクスチャ",
"Clay / Studio Matte": "クレイ / スタジオマット",
"Normals": "法線 (ノーマル)",
"Perspective": "透視投影 (Perspective)",
"Orthographic": "正投影 (Orthographic)",
"Grid": "グリッド",
"Auto-Rotate": "自動回転",
"Wireframe": "ワイヤーフレーム",
"Reset View": "視点をリセット",
"Settings": "設定",
"Export As...": "エクスポート...",
"Failed to load 3D format": "3D形式の読み込みに失敗しました",
"Toggle Comfy Queue Sidebar": "Comfy Queue サイドバーの切り替え",
"Toggle Ignore Selected Node(s) in Queue": "キューで選択したノードを無視/解除",
"Renumber All Nodes (Execution Order)": "すべてのノード番号を再割り当て (実行順)",
"Set Selected Node ID...": "選択したノードIDを設定...",
"Set Node ID...": "ノードIDを設定...",
"Gallery": "ギャラリー",
"Gallery (Outputs)": "ギャラリー (出力)",
"Go Up One Level": "1つ上の階層へ",
"Open Current Folder in File Manager": "現在のフォルダーをファイルマネージャーで開く",
"Refresh Gallery": "ギャラリーを更新",
"Filter gallery files...": "ギャラリーファイルを絞り込み...",
"Loading files...": "ファイルを読み込み中...",
"No files found in this folder.": "このフォルダーにはファイルがありません。",
"Failed to load gallery from disk.": "ディスクからギャラリーを読み込めませんでした。",
"Sort: Newest First": "並び替え:新しい順",
"Sort: Oldest First": "並び替え:古い順",
"Search Gallery (Filename or Prompt)": "ギャラリーを検索 (ファイル名またはプロンプト)",
"Search filenames or prompt metadata...": "ファイル名またはプロンプトを検索..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "列分割の幅しきい値",
"Width Threshold for Queue Columns (px)": "キューを複数列に分割する幅のしきい値 (px)",
"Show Pending Count Only": "待機数のみ表示",
"If disabled, each queued job will have a separate individual card": "無効にすると、キュー内の各タスクが個別のカードとして表示されます",
"Show Working Node Name": "処理中のノード名を表示",
"Shows the name of the node which is currently in the process": "現在処理されているノードの名前を表示します",
"Auto Clear Interrupted": "中断タスクの自動クリア",
"Auto-clear cancelled & failed jobs on new generation": "新規生成時にキャンセルおよび失敗したタスクを自動的に消去します",
"Permanent Delete on Disk Deletion": "ディスクから完全消去",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "ディスクからの削除時にゴミ箱を経由せず完全に消去します",
"Hide Tab: {tab}": "タブを非表示: {tab}",
"Assets": "アセット",
"Nodes": "ノード",
"Models": "モデル",
"Workflows": "ワークフロー",
"Apps": "アプリ",
"Templates": "テンプレート",
"Override Stock History": "標準の履歴を置き換える",
"Replace the stock Job History sidebar with Comfy Queue": "標準の履歴サイドバーを Comfy Queue に置き換えます",
"Hide Graph Button": "「グラフ」ボタンを非表示",
"Hide floating 'Graph' (Workflow/Node Map) button": "フローティングの「グラフ」(ノードマップ) ボタンを非表示にします",
"Hide Avatar": "アバターを非表示",
"Floating Canvas Controls": "フローティングキャンバス操作",
"Classic Layout": "クラシックレイアウト",
"Places the controls and the open workflow tabs on a single unified top bar": "操作ボタンと開いているワークフロータブを統合された単一の上部バーに配置します",
"Comfy Layout": "コンパクトレイアウト",
"Hide Junk": "不要な項目を非表示",
"Default": "デフォルト",
"Dock": "ドック",
"Hide": "非表示",
"Enable Output Gallery Sidebar": "出力ギャラリーのサイドバーを有効化"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "대기열",
"Search History": "기록 검색",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "대기열에서 선택한 노드 무시/해제 (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "선택된 노드가 없습니다. 캔버스에서 노드를 먼저 클릭하세요.",
"Renumber All Nodes by Execution Order (Alt+R)": "실행 순서대로 모든 노드 재번호 매기기 (Alt+R)",
"Clear Cancelled & Failed": "취소 및 실패 항목 삭제",
"Clear All History": "모든 기록 삭제",
"Filter by text, images, nodes...": "텍스트, 이미지, 노드로 필터링...",
"Clear & Close Search": "검색 지우기 및 닫기",
"Scroll to Top": "맨 위로 이동",
"Batch of #": "배치 #",
"Go Back": "뒤로 가기",
"Go Back to Queue": "대기열로 돌아가기",
"Outputs of #": "출력 #",
"No separate intermediate outputs found.": "별도의 중간 노드 출력이 없습니다.",
"Cancel All Pending": "모든 대기 작업 취소",
"Pending Queue:": "대기열:",
"tasks": "개의 작업",
"Download Object": "파일 다운로드",
"Copy to Clipboard": "클립보드에 복사",
"Download JSON": "JSON 다운로드",
"Delete Card (Hold Ctrl to delete file from disk)": "카드 삭제 (Ctrl 누른 채 클릭 시 디스크에서 삭제)",
"Delete Card": "카드 삭제",
"Delete File": "파일 삭제",
"Delete Files": "파일 삭제",
"Show Node": "노드 표시",
"Show Stopped/Failed Node": "중단/실패한 노드 표시",
"View all intermediate outputs": "모든 중간 출력 보기",
"Delete Card (Ctrl+Click to delete from disk)": "카드 삭제 (Ctrl+클릭으로 디스크에서 삭제)",
"Ctrl+Click again to delete file from DISK / TRASH": "디스크에서 파일을 영구 삭제하려면 다시 Ctrl+클릭",
"Click again to confirm removing card": "카드를 제거하려면 다시 클릭",
"Remove from batch (Hold Ctrl to delete file from disk)": "배치에서 제거 (Ctrl 누른 채 디스크에서 삭제)",
"Click again to confirm removing from batch": "배치에서 제거하려면 다시 클릭",
"Delete node output (Hold Ctrl to delete file from disk)": "노드 출력 삭제 (Ctrl 누른 채 디스크에서 삭제)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "이 노드의 파일을 디스크에서 삭제하려면 다시 Ctrl+클릭",
"Click again to confirm removing output": "출력을 제거하려면 다시 클릭",
"Moved file to Recycle Bin.": "휴지통으로 파일을 이동했습니다.",
"Permanently deleted file.": "파일을 영구 삭제했습니다.",
"Cancelled": "취소됨",
"Error": "오류",
"Warning": "경고",
"Cancel Queued Task": "작업 취소",
"Interrupt Execution": "실행 중단",
"Click to read full text": "전체 텍스트 읽기",
"No Outputs": "출력 없음",
"Processing...": "처리 중...",
"Finishing...": "마무리 중...",
"No workflow metadata found in this file.": "이 파일에서 워크플로 메타데이터를 찾을 수 없습니다.",
"Open Folder": "폴더 열기",
"Open Location": "파일 위치 열기",
"View all images in this batch": "이 배치의 모든 이미지 보기",
"No nodes found on canvas to renumber.": "캔버스에 재번호를 매길 노드가 없습니다.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "노드 재번호 매기기는 실행 순서에 따라 캔버스의 모든 노드 ID를 다시 씁니다.\n\n중간 노드 출력이 최종 결과로 표시되는 문제를 해결하지만, 특정 ID에 의존하는 외부 스크립트가 손상될 수 있습니다.\n\n계속하시겠습니까?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "실행 순서대로 {count}개의 노드 번호를 다시 매겼습니다. 최신 노드: #{id} ({name}).",
"Failed to renumber nodes: ": "노드 재번호 매기기 실패: ",
"Please select a node first to change its ID.": "ID를 변경할 노드를 먼저 선택하세요.",
"Enter new ID for node #{id} ({name}):": "노드 #{id} ({name})의 새 ID 입력:",
"Please enter a valid positive number.": "올바른 양의 정수를 입력하세요.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "노드 ID #{id}는 이미 \"{name}\"에서 사용 중입니다. 두 노드의 ID를 맞바꾸시겠습니까?",
"Assigned node ID #{id} to \"{name}\".": "\"{name}\"에 노드 ID #{id}를 할당했습니다.",
"Failed to set node ID: ": "노드 ID 설정 실패: ",
"Video playback. Press Esc to close.": "동영상 재생 중. Esc를 눌러 닫기.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "이미지 클릭 시 확대 (100%/맞춤) | Shift+클릭으로 다른 카드와 비교",
"Toggle Loop": "반복 재생 전환",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "가로세로 비율이 다릅니다 ({wA}x{hA} vs {wB}x{hB}). 비교하려면 비율이 같아야 합니다.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "클릭하여 확대 | 슬라이더를 드래그하여 비교 | Esc로 닫기",
"Copy": "복사",
"Copied!": "복사됨!",
"Text Output": "텍스트 출력",
"Text Output #": "텍스트 출력 #",
"Raw Text": "원본 텍스트",
"{wc} words • {chars} chars": "{wc} 단어 • {chars} 글자",
"3D Model": "3D 모델",
"Loading 3D Asset...": "3D 에셋 로드 중...",
"Exporting {format}...": "{format} 내보내는 중...",
"Failed to load 3D engine.": "3D 엔진 로드 실패.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "3D 라이브러리를 다운로드할 수 없습니다. 인터넷 연결을 확인하세요.",
"Background Color": "배경색",
"Up Direction": "상향 축",
"Material Mode": "머티리얼 모드",
"Camera Type": "카메라 종류",
"FOV": "시야각 (FOV)",
"Light Intensity": "조명 강도",
"Original (Y-Up)": "기본 (Y축 위)",
"Z-Up (+90°)": "Z축 위 (+90°)",
"Inverted (-90°)": "반전 (-90°)",
"Original / Textured": "기본 / 텍스처",
"Clay / Studio Matte": "클레이 / 스튜디오 무광",
"Normals": "노멀 (법선)",
"Perspective": "원근 투영",
"Orthographic": "직교 투영",
"Grid": "격자",
"Auto-Rotate": "자동 회전",
"Wireframe": "와이어프레임",
"Reset View": "시점 초기화",
"Settings": "설정",
"Export As...": "내보내기...",
"Failed to load 3D format": "3D 형식 로드 실패",
"Toggle Comfy Queue Sidebar": "Comfy Queue 사이드바 전환",
"Toggle Ignore Selected Node(s) in Queue": "대기열에서 선택한 노드 무시/해제",
"Renumber All Nodes (Execution Order)": "모든 노드 재번호 매기기 (실행 순서)",
"Set Selected Node ID...": "선택한 노드 ID 설정...",
"Set Node ID...": "노드 ID 설정...",
"Gallery": "갤러리",
"Gallery (Outputs)": "갤러리 (출력)",
"Go Up One Level": "한 수준 위로",
"Open Current Folder in File Manager": "파일 탐색기에서 현재 폴더 열기",
"Refresh Gallery": "갤러리 새로고침",
"Filter gallery files...": "갤러리 파일 필터링...",
"Loading files...": "파일 로딩 중...",
"No files found in this folder.": "이 폴더에 파일이 없습니다.",
"Failed to load gallery from disk.": "디스크에서 갤러리를 불러오지 못했습니다.",
"Sort: Newest First": "정렬: 최신순",
"Sort: Oldest First": "정렬: 오래된순",
"Search Gallery (Filename or Prompt)": "갤러리 검색 (파일명 또는 프롬프트)",
"Search filenames or prompt metadata...": "파일명 또는 프롬프트 메타데이터 검색..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "열 분할 너비 기준값",
"Width Threshold for Queue Columns (px)": "대기열을 여러 열로 나눌 너비 기준값 (px)",
"Show Pending Count Only": "대기 수량만 표시",
"If disabled, each queued job will have a separate individual card": "비활성화 시 대기열의 각 작업이 개별 카드로 표시됩니다",
"Show Working Node Name": "진행 중인 노드 이름 표시",
"Shows the name of the node which is currently in the process": "현재 처리 중인 노드의 이름을 표시합니다",
"Auto Clear Interrupted": "중단된 작업 자동 삭제",
"Auto-clear cancelled & failed jobs on new generation": "새 생성 시 취소되거나 실패한 작업을 자동으로 삭제합니다",
"Permanent Delete on Disk Deletion": "디스크에서 완전 삭제",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "디스크에서 삭제 시 휴지통을 거치지 않고 영구 삭제합니다",
"Hide Tab: {tab}": "탭 숨기기: {tab}",
"Assets": "에셋",
"Nodes": "노드",
"Models": "모델",
"Workflows": "워크플로",
"Apps": "앱",
"Templates": "템플릿",
"Override Stock History": "기본 작업 기록 대체",
"Replace the stock Job History sidebar with Comfy Queue": "기본 작업 기록 사이드바를 Comfy Queue로 대체합니다",
"Hide Graph Button": "'그래프' 버튼 숨기기",
"Hide floating 'Graph' (Workflow/Node Map) button": "플로팅 '그래프'(워크플로 맵) 버튼을 숨깁니다",
"Hide Avatar": "아바타 숨기기",
"Floating Canvas Controls": "플로팅 캔버스 제어 도구",
"Classic Layout": "클래식 레이아웃",
"Places the controls and the open workflow tabs on a single unified top bar": "제어 도구와 열린 워크플로 탭을 하나의 상단 바로 통합합니다",
"Comfy Layout": "컴팩트 레이아웃",
"Hide Junk": "불필요한 항목 숨기기",
"Default": "기본값",
"Dock": "도킹",
"Hide": "숨기기",
"Enable Output Gallery Sidebar": "출력 갤러리 사이드바 활성화"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "Fila",
"Search History": "Pesquisar histórico",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Ignorar/Incluir nó(s) selecionado(s) na fila (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "Nenhum nó selecionado. Clique primeiro em um nó na tela.",
"Renumber All Nodes by Execution Order (Alt+R)": "Renumerar todos os nós por ordem de execução (Alt+R)",
"Clear Cancelled & Failed": "Limpar cancelados e com falha",
"Clear All History": "Limpar todo o histórico",
"Filter by text, images, nodes...": "Filtrar por texto, imagens, nós...",
"Clear & Close Search": "Limpar e fechar busca",
"Scroll to Top": "Voltar ao topo",
"Batch of #": "Lote de #",
"Go Back": "Voltar",
"Go Back to Queue": "Voltar para a fila",
"Outputs of #": "Saídas de #",
"No separate intermediate outputs found.": "Nenhuma saída intermediária separada encontrada.",
"Cancel All Pending": "Cancelar todas as tarefas pendentes",
"Pending Queue:": "Fila pendente:",
"tasks": "tarefas",
"Download Object": "Baixar objeto",
"Copy to Clipboard": "Copiar para a área de transferência",
"Download JSON": "Baixar JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "Excluir cartão (Ctrl para apagar do disco)",
"Delete Card": "Excluir cartão",
"Delete File": "Excluir arquivo",
"Delete Files": "Excluir arquivos",
"Show Node": "Mostrar nó",
"Show Stopped/Failed Node": "Mostrar nó interrompido ou com falha",
"View all intermediate outputs": "Ver todas as saídas intermediárias",
"Delete Card (Ctrl+Click to delete from disk)": "Excluir cartão (Ctrl+Clique para apagar do disco)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+Clique novamente para excluir permanentemente",
"Click again to confirm removing card": "Clique novamente para confirmar a remoção",
"Remove from batch (Hold Ctrl to delete file from disk)": "Remover do lote (Ctrl para apagar do disco)",
"Click again to confirm removing from batch": "Clique novamente para remover do lote",
"Delete node output (Hold Ctrl to delete file from disk)": "Excluir saída (Ctrl para apagar do disco)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+Clique novamente para apagar do disco",
"Click again to confirm removing output": "Clique novamente para confirmar a exclusão",
"Moved file to Recycle Bin.": "Arquivo movido para a Lixeira.",
"Permanently deleted file.": "Arquivo excluído permanentemente.",
"Cancelled": "Cancelado",
"Error": "Erro",
"Warning": "Aviso",
"Cancel Queued Task": "Cancelar tarefa da fila",
"Interrupt Execution": "Interromper execução",
"Click to read full text": "Clique para ler o texto completo",
"No Outputs": "Sem saídas",
"Processing...": "Processando...",
"Finishing...": "Finalizando...",
"No workflow metadata found in this file.": "Nenhum metadado de fluxo de trabalho encontrado.",
"Open Folder": "Abrir pasta",
"Open Location": "Abrir local do arquivo",
"View all images in this batch": "Ver todas as imagens deste lote",
"No nodes found on canvas to renumber.": "Nenhum nó encontrado na tela para renumerar.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "A renumeração reescreverá os IDs de todos os nós de acordo com a ordem de execução.\n\nIsso corrige saídas intermediárias mostradas como resultado final, mas pode interferir em scripts externos.\n\nDeseja continuar?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "{count} nós renumerados por ordem de execução. Último nó: #{id} ({name}).",
"Failed to renumber nodes: ": "Falha ao renumerar nós: ",
"Please select a node first to change its ID.": "Selecione primeiro um nó para alterar o ID.",
"Enter new ID for node #{id} ({name}):": "Digite o novo ID para o nó #{id} ({name}):",
"Please enter a valid positive number.": "Insira um número inteiro positivo válido.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "O ID #{id} já está em uso por \"{name}\". Deseja inverter os IDs?",
"Assigned node ID #{id} to \"{name}\".": "ID #{id} atribuído ao nó \"{name}\".",
"Failed to set node ID: ": "Falha ao definir o ID do nó: ",
"Video playback. Press Esc to close.": "Reprodução de vídeo. Pressione Esc para fechar.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Clique na imagem para zoom (100%/Ajustar) | Shift+Clique em outro cartão para comparar.",
"Toggle Loop": "Repetição contínua",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "Proporção incompatível ({wA}x{hA} vs {wB}x{hB}). Imagens devem ter o mesmo formato para comparação.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Clique para zoom | Arraste para comparar | Esc para fechar.",
"Copy": "Copiar",
"Copied!": "Copiado!",
"Text Output": "Saída de texto",
"Text Output #": "Saída de texto #",
"Raw Text": "Texto puro",
"{wc} words • {chars} chars": "{wc} palavras • {chars} car.",
"3D Model": "Modelo 3D",
"Loading 3D Asset...": "Carregando modelo 3D...",
"Exporting {format}...": "Exportando para {format}...",
"Failed to load 3D engine.": "Falha ao carregar o motor 3D.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "Não foi possível baixar bibliotecas 3D. Verifique sua conexão com a Internet.",
"Background Color": "Cor de fundo",
"Up Direction": "Eixo superior",
"Material Mode": "Modo de material",
"Camera Type": "Tipo de câmera",
"FOV": "Campo de visão (FOV)",
"Light Intensity": "Intensidade da luz",
"Original (Y-Up)": "Original (Y para cima)",
"Z-Up (+90°)": "Z para cima (+90°)",
"Inverted (-90°)": "Invertido (-90°)",
"Original / Textured": "Original / Texturizado",
"Clay / Studio Matte": "Argila / Fosco",
"Normals": "Normais",
"Perspective": "Perspectiva",
"Orthographic": "Ortográfica",
"Grid": "Grade",
"Auto-Rotate": "Rotação automática",
"Wireframe": "Aramado",
"Reset View": "Redefinir visão",
"Settings": "Configurações",
"Export As...": "Exportar como...",
"Failed to load 3D format": "Falha ao carregar formato 3D",
"Toggle Comfy Queue Sidebar": "Alternar barra lateral Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "Ignorar/Incluir nós selecionados na fila",
"Renumber All Nodes (Execution Order)": "Renumerar todos os nós (ordem de execução)",
"Set Selected Node ID...": "Definir ID do nó selecionado...",
"Set Node ID...": "Definir ID do nó...",
"Gallery": "Galeria",
"Gallery (Outputs)": "Galeria (Saídas)",
"Go Up One Level": "Subir um nível",
"Open Current Folder in File Manager": "Abrir pasta atual no gerenciador de arquivos",
"Refresh Gallery": "Atualizar galeria",
"Filter gallery files...": "Filtrar arquivos da galeria...",
"Loading files...": "Carregando arquivos...",
"No files found in this folder.": "Nenhum arquivo encontrado nesta pasta.",
"Failed to load gallery from disk.": "Falha ao carregar a galeria do disco.",
"Sort: Newest First": "Ordenar: Mais recentes primeiro",
"Sort: Oldest First": "Ordenar: Mais antigos primeiro",
"Search Gallery (Filename or Prompt)": "Pesquisar na galeria (nome do arquivo ou prompt)",
"Search filenames or prompt metadata...": "Pesquisar nomes de arquivos ou metadados de prompt..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "Limite de colunas da fila",
"Width Threshold for Queue Columns (px)": "Largura em pixels para dividir a fila em várias colunas",
"Show Pending Count Only": "Mostrar apenas contagem pendente",
"If disabled, each queued job will have a separate individual card": "Se desativado, cada tarefa na fila terá um cartão individual",
"Show Working Node Name": "Mostrar nome do nó em execução",
"Shows the name of the node which is currently in the process": "Mostra o nome do nó que está sendo processado no momento",
"Auto Clear Interrupted": "Limpeza automática de interrompidos",
"Auto-clear cancelled & failed jobs on new generation": "Limpar automaticamente tarefas canceladas e com falha ao iniciar nova geração",
"Permanent Delete on Disk Deletion": "Exclusão permanente do disco",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Excluir arquivos permanentemente (sem passar pela Lixeira)",
"Hide Tab: {tab}": "Ocultar aba: {tab}",
"Assets": "Recursos",
"Nodes": "Nós",
"Models": "Modelos",
"Workflows": "Fluxos de trabalho",
"Apps": "Aplicativos",
"Templates": "Modelos prévios",
"Override Stock History": "Substituir histórico padrão",
"Replace the stock Job History sidebar with Comfy Queue": "Substitui a barra lateral de histórico padrão pelo Comfy Queue",
"Hide Graph Button": "Ocultar botão 'Grafo'",
"Hide floating 'Graph' (Workflow/Node Map) button": "Oculta o botão flutuante 'Grafo' (mapa de nós)",
"Hide Avatar": "Ocultar avatar",
"Floating Canvas Controls": "Controles flutuantes da tela",
"Classic Layout": "Layout clássico",
"Places the controls and the open workflow tabs on a single unified top bar": "Posiciona os controles e as abas abertas em uma barra superior unificada",
"Comfy Layout": "Layout compacto",
"Hide Junk": "Ocultar itens desnecessários",
"Default": "Padrão",
"Dock": "Fixar",
"Hide": "Ocultar",
"Enable Output Gallery Sidebar": "Ativar barra lateral da galeria de saídas"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "Очередь",
"Search History": "Поиск по истории",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Игнорировать выбранные ноды в очереди (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "Ноды не выбраны. Сначала выберите ноду на холсте.",
"Renumber All Nodes by Execution Order (Alt+R)": "Перенумеровать ноды по порядку выполнения (Alt+R)",
"Clear Cancelled & Failed": "Очистить отменённые и с ошибкой",
"Clear All History": "Очистить всю историю",
"Filter by text, images, nodes...": "Поиск по тексту, файлам, нодам...",
"Clear & Close Search": "Очистить и закрыть поиск",
"Scroll to Top": "Наверх",
"Batch of #": "Пакет #",
"Go Back": "Назад",
"Go Back to Queue": "Назад в очередь",
"Outputs of #": "Результаты #",
"No separate intermediate outputs found.": "Промежуточные результаты не найдены.",
"Cancel All Pending": "Отменить все в очереди",
"Pending Queue:": "Очередь ожидания:",
"tasks": "задач",
"Download Object": "Скачать объект",
"Copy to Clipboard": "Скопировать в буфер",
"Download JSON": "Скачать JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "Удалить карточку (Ctrl для удаления с диска)",
"Delete Card": "Удалить карточку",
"Delete File": "Удалить файл",
"Delete Files": "Удалить файлы",
"Show Node": "Показать ноду",
"Show Stopped/Failed Node": "Показать ноду с ошибкой",
"View all intermediate outputs": "Показать промежуточные результаты",
"Delete Card (Ctrl+Click to delete from disk)": "Удалить карточку (Ctrl+Клик для удаления с диска)",
"Ctrl+Click again to delete file from DISK / TRASH": "Ctrl+Клик еще раз для удаления с ДИСКА",
"Click again to confirm removing card": "Нажмите еще раз для подтверждения удаления",
"Remove from batch (Hold Ctrl to delete file from disk)": "Удалить из пакета (Ctrl для удаления с диска)",
"Click again to confirm removing from batch": "Нажмите еще раз для удаления из пакета",
"Delete node output (Hold Ctrl to delete file from disk)": "Удалить результат ноды (Ctrl для удаления с диска)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Ctrl+Клик еще раз для удаления файлов с ДИСКА",
"Click again to confirm removing output": "Нажмите еще раз для подтверждения удаления",
"Moved file to Recycle Bin.": "Файл перемещен в корзину.",
"Permanently deleted file.": "Файл удален навсегда.",
"Cancelled": "Отменено",
"Error": "Ошибка",
"Warning": "Предупреждение",
"Cancel Queued Task": "Отменить задачу в очереди",
"Interrupt Execution": "Прервать выполнение",
"Click to read full text": "Нажмите, чтобы прочитать полный текст",
"No Outputs": "Нет результатов",
"Processing...": "Обработка...",
"Finishing...": "Завершение...",
"No workflow metadata found in this file.": "В этом файле не найдены метаданные рабочего процесса.",
"Open Folder": "Открыть папку",
"Open Location": "Открыть папку",
"View all images in this batch": "Все изображения этого пакета",
"No nodes found on canvas to renumber.": "Ноды для перенумерации на холсте не найдены.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "Перенумерация перезапишет ID всех нод на холсте по порядку выполнения.\n\nЭто исправит отображение промежуточных нод как финального результата, но может нарушить работу внешних скриптов, зависящих от конкретных ID.\n\nПродолжить?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "Перенумеровано {count} нод по порядку выполнения. Последняя нода: #{id} ({name}).",
"Failed to renumber nodes: ": "Не удалось перенумеровать ноды: ",
"Please select a node first to change its ID.": "Сначала выберите ноду для изменения её ID.",
"Enter new ID for node #{id} ({name}):": "Введите новый ID для ноды #{id} ({name}):",
"Please enter a valid positive number.": "Пожалуйста, введите положительное число.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "ID ноды #{id} уже используется нодой \"{name}\". Поменять их местами?",
"Assigned node ID #{id} to \"{name}\".": "Ноде \"{name}\" присвоен ID #{id}.",
"Failed to set node ID: ": "Не удалось установить ID ноды: ",
"Video playback. Press Esc to close.": "Воспроизведение видео. Нажмите Esc для закрытия.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Клик для масштабирования (100%/Вписать) | Shift+Клик по другой карточке для сравнения.",
"Toggle Loop": "Зациклить",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "Несовпадение пропорций ({wA}x{hA} против {wB}x{hB}). Изображения должны иметь одинаковые пропорции для сравнения.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Клик для масштабирования | Перетащите слайдер для сравнения | Esc для закрытия.",
"Copy": "Копировать",
"Copied!": "Скопировано!",
"Text Output": "Текстовый результат",
"Text Output #": "Текстовый результат #",
"Raw Text": "Исходный текст",
"{wc} words • {chars} chars": "{wc} слов • {chars} симв.",
"3D Model": "3D-модель",
"Loading 3D Asset...": "Загрузка 3D-модели...",
"Exporting {format}...": "Экспорт в {format}...",
"Failed to load 3D engine.": "Не удалось загрузить 3D-движок.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "Не удалось скачать библиотеки 3D. Убедитесь, что компьютер подключен к интернету, или проверьте, не блокирует ли флаг <code>--disable-api-nodes</code> сетевые запросы.",
"Background Color": "Цвет фона",
"Up Direction": "Направление вверх",
"Material Mode": "Режим материала",
"Camera Type": "Тип камеры",
"FOV": "Угол обзора (FOV)",
"Light Intensity": "Интенсивность света",
"Original (Y-Up)": "Оригинал (Y-Вверх)",
"Z-Up (+90°)": "Z-Вверх (+90°)",
"Inverted (-90°)": "Инвертировано (-90°)",
"Original / Textured": "Оригинал / Текстуры",
"Clay / Studio Matte": "Глина / Студийный",
"Normals": "Нормали",
"Perspective": "Перспектива",
"Orthographic": "Ортогональная",
"Grid": "Сетка",
"Auto-Rotate": "Автоповорот",
"Wireframe": "Каркас",
"Reset View": "Сброс вида",
"Settings": "Настройки",
"Export As...": "Экспорт...",
"Failed to load 3D format": "Не удалось загрузить 3D-формат",
"Toggle Comfy Queue Sidebar": "Переключить боковую панель Comfy Queue",
"Toggle Ignore Selected Node(s) in Queue": "Игнорировать выбранные ноды в очереди",
"Renumber All Nodes (Execution Order)": "Перенумеровать ноды (порядок выполнения)",
"Set Selected Node ID...": "Задать ID выбранной ноды...",
"Set Node ID...": "Задать ID ноды...",
"Gallery": "Галерея",
"Gallery (Outputs)": "Галерея (Результаты)",
"Go Up One Level": "На один уровень вверх",
"Open Current Folder in File Manager": "Открыть текущую папку в проводнике",
"Refresh Gallery": "Обновить галерею",
"Filter gallery files...": "Фильтр файлов галереи...",
"Loading files...": "Загрузка файлов...",
"No files found in this folder.": "В этой папке нет файлов.",
"Failed to load gallery from disk.": "Не удалось загрузить галерею с диска.",
"Sort: Newest First": "Сортировка: сначала новые",
"Sort: Oldest First": "Сортировка: сначала старые",
"Search Gallery (Filename or Prompt)": "Поиск по галерее (имя файла или промпт)",
"Search filenames or prompt metadata...": "Поиск по именам файлов или промптам..."
}
+34
View File
@@ -0,0 +1,34 @@
{
"Grid Columns Threshold": "Порог колонок очереди",
"Width Threshold for Queue Columns (px)": "Ширина в пикселях для разделения очереди на несколько колонок",
"Show Pending Count Only": "Только количество в очереди",
"If disabled, each queued job will have a separate individual card": "Если выключено, каждая задача в очереди будет отдельной карточкой",
"Show Working Node Name": "Имя выполняющейся ноды",
"Shows the name of the node which is currently in the process": "Показывать имя ноды, выполняющейся в данный момент",
"Auto Clear Interrupted": "Автоочистка отменённых",
"Auto-clear cancelled & failed jobs on new generation": "Автоматически очищать отменённые и неудачные задачи при новой генерации",
"Permanent Delete on Disk Deletion": "Безвозвратное удаление с диска",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Удалять файлы навсегда при удалении с диска (минуя корзину)",
"Hide Tab: {tab}": "Скрыть вкладку: {tab}",
"Assets": "Ресурсы",
"Nodes": "Ноды",
"Models": "Модели",
"Workflows": "Рабочие процессы",
"Apps": "Приложения",
"Templates": "Шаблоны",
"Override Stock History": "Замена стандартной истории",
"Replace the stock Job History sidebar with Comfy Queue": "Заменить стандартную панель истории на Comfy Queue",
"Hide Graph Button": "Скрыть кнопку 'Граф'",
"Hide floating 'Graph' (Workflow/Node Map) button": "Скрыть плавающую кнопку 'Граф' (карта нод)",
"Hide Avatar": "Скрыть аватар",
"Floating Canvas Controls": "Плавающие элементы управления",
"Classic Layout": "Классический интерфейс",
"Places the controls and the open workflow tabs on a single unified top bar": "Разместить элементы управления и открытые вкладки на единой верхней панели",
"Comfy Layout": "Компактный интерфейс",
"Classic Layout": "Компактный интерфейс",
"Hide Junk": "Скрыть лишнее",
"Default": "По умолчанию",
"Dock": "Закрепить",
"Hide": "Скрыть",
"Enable Output Gallery Sidebar": "Включить боковую панель галереи результатов"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "Kuyruk",
"Search History": "Geçmişte ara",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "Seçili düğümleri kuyrukta yoksay/etkinleştir (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "Düğüm seçilmedi. Önce tuvalde bir düğüme tıklayın.",
"Renumber All Nodes by Execution Order (Alt+R)": "Düğümleri çalıştırma sırasına göre yeniden numaralandır (Alt+R)",
"Clear Cancelled & Failed": "İptal edilenleri ve hatalıları temizle",
"Clear All History": "Tüm geçmişi temizle",
"Filter by text, images, nodes...": "Metin, görsel, düğüme göre filtrele...",
"Clear & Close Search": "Aramayı temizle ve kapat",
"Scroll to Top": "Yukarı kaydır",
"Batch of #": "Toplu işlem #",
"Go Back": "Geri",
"Go Back to Queue": "Kuyruğa dön",
"Outputs of #": "Çıktıları #",
"No separate intermediate outputs found.": "Ayrı bir ara çıktı bulunamadı.",
"Cancel All Pending": "Bekleyen tüm görevleri iptal et",
"Pending Queue:": "Bekleyen kuyruk:",
"tasks": "görev",
"Download Object": "Dosyayı indir",
"Copy to Clipboard": "Panoya kopyala",
"Download JSON": "JSON indir",
"Delete Card (Hold Ctrl to delete file from disk)": "Kartı sil (Diskten silmek için Ctrl'ye basılı tutun)",
"Delete Card": "Kartı sil",
"Delete File": "Dosyayı sil",
"Delete Files": "Dosyaları sil",
"Show Node": "Düğümü göster",
"Show Stopped/Failed Node": "Durdurulan/hatalı düğümü göster",
"View all intermediate outputs": "Tüm ara çıktıları görüntüle",
"Delete Card (Ctrl+Click to delete from disk)": "Kartı sil (Diskten silmek için Ctrl+Tıklama)",
"Ctrl+Click again to delete file from DISK / TRASH": "Dosyayı diskten tamamen silmek için tekrar Ctrl+Tıklama yapın",
"Click again to confirm removing card": "Kaldırmayı onaylamak için tekrar tıklayın",
"Remove from batch (Hold Ctrl to delete file from disk)": "Gruptan çıkar (Diskten silmek için Ctrl)",
"Click again to confirm removing from batch": "Gruptan çıkarmayı onaylamak için tekrar tıklayın",
"Delete node output (Hold Ctrl to delete file from disk)": "Çıktıyı sil (Diskten silmek için Ctrl)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "Bu düğümün dosyalarını diskten silmek için tekrar Ctrl+Tıklayın",
"Click again to confirm removing output": "Çıktıyı kaldırmayı onaylamak için tekrar tıklayın",
"Moved file to Recycle Bin.": "Dosya Geri Dönüşüm Kutusu'na taşındı.",
"Permanently deleted file.": "Dosya kalıcı olarak silindi.",
"Cancelled": "İptal edildi",
"Error": "Hata",
"Warning": "Uyarı",
"Cancel Queued Task": "Kuyruktaki görevi iptal et",
"Interrupt Execution": "Çalıştırmayı durdur",
"Click to read full text": "Metnin tamamını okumak için tıklayın",
"No Outputs": "Çıktı yok",
"Processing...": "İşleniyor...",
"Finishing...": "Tamamlanıyor...",
"No workflow metadata found in this file.": "Bu dosyada iş akışı meta verisi bulunamadı.",
"Open Folder": "Klasörü aç",
"Open Location": "Dosya konumunu aç",
"View all images in this batch": "Bu gruptaki tüm resimleri görüntüle",
"No nodes found on canvas to renumber.": "Tuvalde numaralandırılacak düğüm bulunamadı.",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "Yeniden numaralandırma, tüm düğüm kimliklerini çalıştırma sırasına göre yeniden yazar.\n\nBu işlem ara çıktıların nihai sonuç olarak görünmesini düzeltir ancak belirli kimliklere bağımlı harici betikleri bozabilir.\n\nDevam etmek istiyor musunuz?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "{count} düğüm çalıştırma sırasına göre numaralandırıldı. Son düğüm: #{id} ({name}).",
"Failed to renumber nodes: ": "Düğümler yeniden numaralandırılamadı: ",
"Please select a node first to change its ID.": "Kimliğini değiştirmek için lütfen önce bir düğüm seçin.",
"Enter new ID for node #{id} ({name}):": "#{id} ({name}) düğümü için yeni kimlik girin:",
"Please enter a valid positive number.": "Lütfen geçerli bir pozitif tamsayı girin.",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "#{id} kimliği zaten \"{name}\" tarafından kullanılıyor. Değiştirilsin mi?",
"Assigned node ID #{id} to \"{name}\".": "\"{name}\" düğümüne #{id} kimliği atandı.",
"Failed to set node ID: ": "Düğüm kimliği ayarlanamadı: ",
"Video playback. Press Esc to close.": "Video oynatılıyor. Kapatmak için Esc'ye basın.",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "Yakınlaştırmak için tıkla (100%/Sığdır) | Karşılaştırmak için başka bir karta Shift+Tıkla.",
"Toggle Loop": "Döngüyü aç/kapat",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "En-boy oranı uyumsuzluğu ({wA}x{hA} ile {wB}x{hB}). Karşılaştırma için görseller aynı oranda olmalıdır.",
"Click image to zoom | Drag image to compare slider | Esc to close.": "Yakınlaştırmak için tıkla | Karşılaştırmak için kaydır | Kapatmak için Esc.",
"Copy": "Kopyala",
"Copied!": "Kopyalandı!",
"Text Output": "Metin çıktısı",
"Text Output #": "Metin çıktısı #",
"Raw Text": "Ham metin",
"{wc} words • {chars} chars": "{wc} kelime • {chars} karakter",
"3D Model": "3D Model",
"Loading 3D Asset...": "3D model yükleniyor...",
"Exporting {format}...": "{format} formatında dışa aktarılıyor...",
"Failed to load 3D engine.": "3D motoru yüklenemedi.",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "3D kütüphaneleri indirilemedi. İnternet bağlantınızı kontrol edin.",
"Background Color": "Arka plan rengi",
"Up Direction": "Yukarı yön",
"Material Mode": "Materyal modu",
"Camera Type": "Kamera türü",
"FOV": "Görüş açısı (FOV)",
"Light Intensity": "Işık yoğunluğu",
"Original (Y-Up)": "Orijinal (Y yukarı)",
"Z-Up (+90°)": "Z yukarı (+90°)",
"Inverted (-90°)": "Ters (-90°)",
"Original / Textured": "Orijinal / Dokulu",
"Clay / Studio Matte": "Kil / Mat",
"Normals": "Normaller",
"Perspective": "Perspektif",
"Orthographic": "Ortografik",
"Grid": "Izgara",
"Auto-Rotate": "Otomatik döndür",
"Wireframe": "Tel kafes",
"Reset View": "Görünümü sıfırla",
"Settings": "Ayarlar",
"Export As...": "Farklı dışa aktar...",
"Failed to load 3D format": "3D formatı yüklenemedi",
"Toggle Comfy Queue Sidebar": "Comfy Queue Kenar Çubuğunu Aç/Kapat",
"Toggle Ignore Selected Node(s) in Queue": "Kuyrukta Seçili Düğümleri Yoksay/Etkinleştir",
"Renumber All Nodes (Execution Order)": "Tüm Düğümleri Yeniden Numaralandır (Çalıştırma Sırası)",
"Set Selected Node ID...": "Seçili Düğüm Kimliğini Belirle...",
"Set Node ID...": "Düğüm Kimliğini Belirle...",
"Gallery": "Galeri",
"Gallery (Outputs)": "Galeri (Çıktılar)",
"Go Up One Level": "Bir Düzey Yukarı Çık",
"Open Current Folder in File Manager": "Mevcut Klasörü Dosya Yöneticisinde Aç",
"Refresh Gallery": "Galeriyi Yenile",
"Filter gallery files...": "Galeri dosyalarını filtrele...",
"Loading files...": "Dosyalar yükleniyor...",
"No files found in this folder.": "Bu klasörde dosya bulunamadı.",
"Failed to load gallery from disk.": "Galeri diskten yüklenemedi.",
"Sort: Newest First": "Sıralama: Önce En Yeniler",
"Sort: Oldest First": "Sıralama: Önce En Eskiler",
"Search Gallery (Filename or Prompt)": "Galeride Ara (Dosya Adı veya Prompt)",
"Search filenames or prompt metadata...": "Dosya adlarını veya prompt meta verilerini ara..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "Kuyruk sütun genişliği eşiği",
"Width Threshold for Queue Columns (px)": "Kuyruğu birden fazla sütuna bölmek için piksel genişliği",
"Show Pending Count Only": "Yalnızca bekleyen sayısını göster",
"If disabled, each queued job will have a separate individual card": "Devre dışı bırakılırsa kuyruktaki her görev ayrı bir karta sahip olur",
"Show Working Node Name": "Çalışan düğüm adını göster",
"Shows the name of the node which is currently in the process": "Şu anda işlenmekte olan düğümün adını gösterir",
"Auto Clear Interrupted": "Kesilenleri otomatik temizle",
"Auto-clear cancelled & failed jobs on new generation": "Yeni üretimde iptal edilen ve başarısız olan görevleri otomatik olarak temizle",
"Permanent Delete on Disk Deletion": "Diskten kalıcı silme",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "Diskten silerken dosyaları kalıcı olarak sil (Geri Dönüşüm Kutusu'nu atlar)",
"Hide Tab: {tab}": "Sekmeyi gizle: {tab}",
"Assets": "Varlıklar",
"Nodes": "Düğümler",
"Models": "Modeller",
"Workflows": "İş Akışları",
"Apps": "Uygulamalar",
"Templates": "Şablonlar",
"Override Stock History": "Varsayılan geçmişi değiştir",
"Replace the stock Job History sidebar with Comfy Queue": "Varsayılan Görev Geçmişi kenar çubuğunu Comfy Queue ile değiştirir",
"Hide Graph Button": "'Grafik' düğmesini gizle",
"Hide floating 'Graph' (Workflow/Node Map) button": "Kayan 'Grafik' (İş akışı haritası) düğmesini gizler",
"Hide Avatar": "Avatarı gizle",
"Floating Canvas Controls": "Kayan tuval kontrolleri",
"Classic Layout": "Klasik düzen",
"Places the controls and the open workflow tabs on a single unified top bar": "Kontrolleri ve açık iş akışı sekmelerini tek bir birleşik üst çubukta toplar",
"Comfy Layout": "Kompakt Düzen",
"Hide Junk": "Gereksiz Öğeleri Gizle",
"Default": "Varsayılan",
"Dock": "Sabitle",
"Hide": "Gizle",
"Enable Output Gallery Sidebar": "Çıktı Galerisi Kenar Çubuğunu Etkinleştir"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "隊列",
"Search History": "搜尋歷史",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "在隊列中忽略選取節點 (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "未選取任何節點。請先在畫布上點選節點。",
"Renumber All Nodes by Execution Order (Alt+R)": "按執行順序重新編號所有節點 (Alt+R)",
"Clear Cancelled & Failed": "清除已取消與失敗任務",
"Clear All History": "清除所有歷史",
"Filter by text, images, nodes...": "按文字、影像、節點篩選...",
"Clear & Close Search": "清除並關閉搜尋",
"Scroll to Top": "回到頂部",
"Batch of #": "批次 #",
"Go Back": "返回",
"Go Back to Queue": "返回隊列",
"Outputs of #": "輸出 #",
"No separate intermediate outputs found.": "未找到獨立的中間輸出。",
"Cancel All Pending": "取消所有等待任務",
"Pending Queue:": "等待隊列:",
"tasks": "個任務",
"Download Object": "下載檔案",
"Copy to Clipboard": "複製到剪貼簿",
"Download JSON": "下載 JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "刪除卡片 (按住 Ctrl 從磁碟刪除檔案)",
"Delete Card": "刪除卡片",
"Delete File": "刪除檔案",
"Delete Files": "刪除檔案",
"Show Node": "顯示節點",
"Show Stopped/Failed Node": "顯示停止/失敗的節點",
"View all intermediate outputs": "檢視所有中間輸出",
"Delete Card (Ctrl+Click to delete from disk)": "刪除卡片 (Ctrl+點擊 從磁碟刪除)",
"Ctrl+Click again to delete file from DISK / TRASH": "再次 Ctrl+點擊 以徹底刪除檔案",
"Click again to confirm removing card": "再次點擊確認移除卡片",
"Remove from batch (Hold Ctrl to delete file from disk)": "從批次中移除 (按住 Ctrl 從磁碟刪除)",
"Click again to confirm removing from batch": "再次點擊確認從批次中移除",
"Delete node output (Hold Ctrl to delete file from disk)": "刪除節點輸出 (按住 Ctrl 從磁碟刪除)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "再次 Ctrl+點擊 從磁碟刪除此節點的檔案",
"Click again to confirm removing output": "再次點擊確認移除輸出",
"Moved file to Recycle Bin.": "檔案已移至資源回收筒。",
"Permanently deleted file.": "檔案已永久刪除。",
"Cancelled": "已取消",
"Error": "錯誤",
"Warning": "警告",
"Cancel Queued Task": "取消排隊任務",
"Interrupt Execution": "中斷執行",
"Click to read full text": "點擊檢視全文",
"No Outputs": "無輸出",
"Processing...": "處理中...",
"Finishing...": "完成中...",
"No workflow metadata found in this file.": "此檔案中未找到工作流元資料。",
"Open Folder": "開啟資料夾",
"Open Location": "開啟檔案位置",
"View all images in this batch": "檢視此批次中的所有影像",
"No nodes found on canvas to renumber.": "畫布上未找到可重新編號的節點。",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "重新編號將按拓撲執行順序重寫畫布上的所有節點 ID。\n\n這將修復中間節點輸出顯示為最終結果的問題,但可能會影響依賴特定節點 ID 的外部腳本。\n\n是否繼續?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "已按執行順序對 {count} 個節點重新編號。最新節點: #{id} ({name})。",
"Failed to renumber nodes: ": "節點重新編號失敗: ",
"Please select a node first to change its ID.": "請先選擇一個節點以更改其 ID。",
"Enter new ID for node #{id} ({name}):": "輸入節點 #{id} ({name}) 的新 ID:",
"Please enter a valid positive number.": "請輸入有效的正整數。",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "節點 ID #{id} 已被 \"{name}\" 使用。是否對調它們的 ID?",
"Assigned node ID #{id} to \"{name}\".": "已將節點 ID #{id} 分配給 \"{name}\"。",
"Failed to set node ID: ": "設定節點 ID 失敗: ",
"Video playback. Press Esc to close.": "影片播放。按 Esc 關閉。",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "點擊影像縮放 (100%/適應) | Shift+點擊 另一張卡片進行對比。",
"Toggle Loop": "循環播放",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "長寬比不符合 ({wA}x{hA} 對比 {wB}x{hB})。影像必須具有相同比例才能對比。",
"Click image to zoom | Drag image to compare slider | Esc to close.": "點擊縮放 | 拖曳滑塊對比 | Esc 關閉。",
"Copy": "複製",
"Copied!": "已複製!",
"Text Output": "文字輸出",
"Text Output #": "文字輸出 #",
"Raw Text": "原始文字",
"{wc} words • {chars} chars": "{wc} 個詞 • {chars} 個字元",
"3D Model": "3D 模型",
"Loading 3D Asset...": "正在載入 3D 資產...",
"Exporting {format}...": "正在匯出 {format}...",
"Failed to load 3D engine.": "載入 3D 引擎失敗。",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "無法下載 3D 函式庫。請確保連線正常,或檢查是否啟用了 <code>--disable-api-nodes</code>。",
"Background Color": "背景顏色",
"Up Direction": "朝上方向",
"Material Mode": "材質模式",
"Camera Type": "相機類型",
"FOV": "視野 (FOV)",
"Light Intensity": "光照強度",
"Original (Y-Up)": "原始 (Y 軸向上)",
"Z-Up (+90°)": "Z 軸向上 (+90°)",
"Inverted (-90°)": "反轉 (-90°)",
"Original / Textured": "原始 / 貼圖",
"Clay / Studio Matte": "黏土 / 啞光",
"Normals": "法線",
"Perspective": "透視",
"Orthographic": "正交",
"Grid": "格線",
"Auto-Rotate": "自動旋轉",
"Wireframe": "線框",
"Reset View": "重設視角",
"Settings": "設定",
"Export As...": "匯出為...",
"Failed to load 3D format": "載入 3D 格式失敗",
"Toggle Comfy Queue Sidebar": "切換 Comfy Queue 側邊欄",
"Toggle Ignore Selected Node(s) in Queue": "在隊列中忽略選取節點",
"Renumber All Nodes (Execution Order)": "重新編號所有節點 (按執行順序)",
"Set Selected Node ID...": "設定選取節點 ID...",
"Set Node ID...": "設定節點 ID...",
"Gallery": "圖庫",
"Gallery (Outputs)": "圖庫 (輸出)",
"Go Up One Level": "返回上一層",
"Open Current Folder in File Manager": "在檔案管理器中開啟目前資料夾",
"Refresh Gallery": "重新整理圖庫",
"Filter gallery files...": "篩選圖庫檔案...",
"Loading files...": "正在載入檔案...",
"No files found in this folder.": "此資料夾中未找到檔案。",
"Failed to load gallery from disk.": "從磁碟載入圖庫失敗。",
"Sort: Newest First": "排序:最新優先",
"Sort: Oldest First": "排序:最舊優先",
"Search Gallery (Filename or Prompt)": "搜尋圖庫 (檔案名稱或提示詞)",
"Search filenames or prompt metadata...": "搜尋檔案名稱或提示詞元資料..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "隊列欄寬閾值",
"Width Threshold for Queue Columns (px)": "隊列顯示多欄的寬度閾值 (像素)",
"Show Pending Count Only": "僅顯示等待數量",
"If disabled, each queued job will have a separate individual card": "若停用,每個排隊任務將顯示為獨立卡片",
"Show Working Node Name": "顯示執行中節點名稱",
"Shows the name of the node which is currently in the process": "顯示目前正在處理的節點名稱",
"Auto Clear Interrupted": "自動清除中斷任務",
"Auto-clear cancelled & failed jobs on new generation": "新生成時自動清除已取消與失敗的任務",
"Permanent Delete on Disk Deletion": "從磁碟永久刪除",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "從磁碟刪除時永久刪除檔案 (略過資源回收筒)",
"Hide Tab: {tab}": "隱藏標籤頁: {tab}",
"Assets": "資產",
"Nodes": "節點",
"Models": "模型",
"Workflows": "工作流",
"Apps": "應用",
"Templates": "範本",
"Override Stock History": "取代原生任務歷史",
"Replace the stock Job History sidebar with Comfy Queue": "使用 Comfy Queue 取代原生任務歷史側邊欄",
"Hide Graph Button": "隱藏「圖」按鈕",
"Hide floating 'Graph' (Workflow/Node Map) button": "隱藏懸浮的「圖」(工作流/節點圖) 按鈕",
"Hide Avatar": "隱藏頭像",
"Floating Canvas Controls": "懸浮畫布控制項",
"Classic Layout": "經典版面配置",
"Places the controls and the open workflow tabs on a single unified top bar": "將控制項與已開啟的工作流標籤頁整合於統一的頂端列",
"Comfy Layout": "緊湊版面配置",
"Hide Junk": "隱藏雜項",
"Default": "預設",
"Dock": "停靠",
"Hide": "隱藏",
"Enable Output Gallery Sidebar": "啟用輸出圖庫側邊欄"
}
+118
View File
@@ -0,0 +1,118 @@
{
"Queue": "队列",
"Search History": "搜索历史",
"Toggle Ignore Selected Node(s) in Queue (Ctrl+Q)": "在队列中忽略所选节点 (Ctrl+Q)",
"No nodes selected. Click a node on the canvas first to toggle ignore.": "未选择任何节点。请先在画布上点击节点。",
"Renumber All Nodes by Execution Order (Alt+R)": "按执行顺序重新编号所有节点 (Alt+R)",
"Clear Cancelled & Failed": "清除已取消和失败的任务",
"Clear All History": "清除所有历史",
"Filter by text, images, nodes...": "按文本、图像、节点过滤...",
"Clear & Close Search": "清空并关闭搜索",
"Scroll to Top": "回到顶部",
"Batch of #": "批次 #",
"Go Back": "返回",
"Go Back to Queue": "返回队列",
"Outputs of #": "输出 #",
"No separate intermediate outputs found.": "未找到单独的中间输出。",
"Cancel All Pending": "取消所有等待任务",
"Pending Queue:": "等待队列:",
"tasks": "个任务",
"Download Object": "下载文件",
"Copy to Clipboard": "复制到剪贴板",
"Download JSON": "下载 JSON",
"Delete Card (Hold Ctrl to delete file from disk)": "删除卡片 (按住 Ctrl 从磁盘删除文件)",
"Delete Card": "删除卡片",
"Delete File": "删除文件",
"Delete Files": "删除文件",
"Show Node": "显示节点",
"Show Stopped/Failed Node": "显示停止/失败的节点",
"View all intermediate outputs": "查看所有中间输出",
"Delete Card (Ctrl+Click to delete from disk)": "删除卡片 (Ctrl+点击 从磁盘删除)",
"Ctrl+Click again to delete file from DISK / TRASH": "再次 Ctrl+点击 以彻底删除文件",
"Click again to confirm removing card": "再次点击确认移除卡片",
"Remove from batch (Hold Ctrl to delete file from disk)": "从批次中移除 (按住 Ctrl 从磁盘删除)",
"Click again to confirm removing from batch": "再次点击确认从批次中移除",
"Delete node output (Hold Ctrl to delete file from disk)": "删除节点输出 (按住 Ctrl 从磁盘删除)",
"Ctrl+Click again to delete this node's files from DISK / TRASH": "再次 Ctrl+点击 从磁盘删除此节点的文件",
"Click again to confirm removing output": "再次点击确认移除输出",
"Moved file to Recycle Bin.": "文件已移至回收站。",
"Permanently deleted file.": "文件已永久删除。",
"Cancelled": "已取消",
"Error": "错误",
"Warning": "警告",
"Cancel Queued Task": "取消排队任务",
"Interrupt Execution": "中断执行",
"Click to read full text": "点击查看全文",
"No Outputs": "无输出",
"Processing...": "处理中...",
"Finishing...": "完成中...",
"No workflow metadata found in this file.": "此文件中未找到工作流元数据。",
"Open Folder": "打开文件夹",
"Open Location": "打开位置",
"View all images in this batch": "查看此批次中的所有图像",
"No nodes found on canvas to renumber.": "画布上未找到可重新编号的节点。",
"Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?": "重新编号将按拓扑执行顺序重写画布上的所有节点 ID。\n\n这将修复中间节点输出被显示为最终结果的问题,但可能会破坏依赖于特定节点 ID 的外部脚本。\n\n是否继续?",
"Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).": "已按执行顺序对 {count} 个节点重新编号。最新节点: #{id} ({name})。",
"Failed to renumber nodes: ": "节点重新编号失败: ",
"Please select a node first to change its ID.": "请先选择一个节点以更改其 ID。",
"Enter new ID for node #{id} ({name}):": "输入节点 #{id} ({name}) 的新 ID:",
"Please enter a valid positive number.": "请输入有效的正整数。",
"Node ID #{id} is already used by \"{name}\". Swap their IDs?": "节点 ID #{id} 已被 \"{name}\" 使用。是否交换它们的 ID?",
"Assigned node ID #{id} to \"{name}\".": "已将节点 ID #{id} 分配给 \"{name}\"。",
"Failed to set node ID: ": "设置节点 ID 失败: ",
"Video playback. Press Esc to close.": "视频播放。按 Esc 关闭。",
"Click image to zoom (100%/Fit) | Shift+Click another card to compare.": "点击图像缩放 (100%/适应) | Shift+点击 另一张卡片进行对比。",
"Toggle Loop": "循环播放",
"Aspect ratio mismatch ({wA}x{hA} vs {wB}x{hB}). Images must have matching proportions to compare.": "宽高比不匹配 ({wA}x{hA} 对比 {wB}x{hB})。图像必须具有相同的比例才能进行对比。",
"Click image to zoom | Drag image to compare slider | Esc to close.": "点击缩放 | 拖动滑块对比 | Esc 关闭。",
"Copy": "复制",
"Copied!": "已复制!",
"Text Output": "文本输出",
"Text Output #": "文本输出 #",
"Raw Text": "原始文本",
"{wc} words • {chars} chars": "{wc} 个词 • {chars} 个字符",
"3D Model": "3D 模型",
"Loading 3D Asset...": "正在加载 3D 资产...",
"Exporting {format}...": "正在导出 {format}...",
"Failed to load 3D engine.": "加载 3D 引擎失败。",
"Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.": "无法下载 3D 库。请确保网络连接正常,或检查是否开启了 <code>--disable-api-nodes</code>。",
"Background Color": "背景颜色",
"Up Direction": "向上方向",
"Material Mode": "材质模式",
"Camera Type": "相机类型",
"FOV": "视场角 (FOV)",
"Light Intensity": "光照强度",
"Original (Y-Up)": "原始 (Y 轴向上)",
"Z-Up (+90°)": "Z 轴向上 (+90°)",
"Inverted (-90°)": "反转 (-90°)",
"Original / Textured": "原始 / 纹理",
"Clay / Studio Matte": "黏土 / 哑光",
"Normals": "法线",
"Perspective": "透视",
"Orthographic": "正交",
"Grid": "网格",
"Auto-Rotate": "自动旋转",
"Wireframe": "线框",
"Reset View": "重置视角",
"Settings": "设置",
"Export As...": "导出为...",
"Failed to load 3D format": "加载 3D 格式失败",
"Toggle Comfy Queue Sidebar": "切换 Comfy Queue 侧边栏",
"Toggle Ignore Selected Node(s) in Queue": "在队列中忽略所选节点",
"Renumber All Nodes (Execution Order)": "重新编号所有节点 (按执行顺序)",
"Set Selected Node ID...": "设置所选节点 ID...",
"Set Node ID...": "设置节点 ID...",
"Gallery": "图库",
"Gallery (Outputs)": "图库 (输出)",
"Go Up One Level": "返回上一级",
"Open Current Folder in File Manager": "在文件管理器中打开当前文件夹",
"Refresh Gallery": "刷新图库",
"Filter gallery files...": "筛选图库文件...",
"Loading files...": "正在加载文件...",
"No files found in this folder.": "此文件夹中未找到文件。",
"Failed to load gallery from disk.": "从磁盘加载图库失败。",
"Sort: Newest First": "排序:最新优先",
"Sort: Oldest First": "排序:最早优先",
"Search Gallery (Filename or Prompt)": "搜索图库 (文件名或提示词)",
"Search filenames or prompt metadata...": "搜索文件名或提示词元数据..."
}
+33
View File
@@ -0,0 +1,33 @@
{
"Grid Columns Threshold": "队列列宽阈值",
"Width Threshold for Queue Columns (px)": "队列显示多列的宽度阈值 (像素)",
"Show Pending Count Only": "仅显示等待数量",
"If disabled, each queued job will have a separate individual card": "如果禁用,每个排队的任务将拥有单独的卡片",
"Show Working Node Name": "显示正在执行的节点名称",
"Shows the name of the node which is currently in the process": "显示当前正在处理的节点名称",
"Auto Clear Interrupted": "自动清除中断任务",
"Auto-clear cancelled & failed jobs on new generation": "新生成时自动清除已取消和失败的任务",
"Permanent Delete on Disk Deletion": "从磁盘永久删除",
"Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)": "从磁盘删除时永久删除文件 (绕过回收站)",
"Hide Tab: {tab}": "隐藏标签页: {tab}",
"Assets": "资产",
"Nodes": "节点",
"Models": "模型",
"Workflows": "工作流",
"Apps": "应用",
"Templates": "模板",
"Override Stock History": "替换原生任务历史",
"Replace the stock Job History sidebar with Comfy Queue": "使用 Comfy Queue 替换原生任务历史侧边栏",
"Hide Graph Button": "隐藏'图'按钮",
"Hide floating 'Graph' (Workflow/Node Map) button": "隐藏悬浮的'图' (工作流/节点图) 按钮",
"Hide Avatar": "隐藏头像",
"Floating Canvas Controls": "悬浮画布控件",
"Classic Layout": "经典布局",
"Places the controls and the open workflow tabs on a single unified top bar": "将控件与已打开的工作流标签页整合在统一的顶部栏",
"Comfy Layout": "紧凑布局",
"Hide Junk": "隐藏杂项",
"Default": "默认",
"Dock": "停靠",
"Hide": "隐藏",
"Enable Output Gallery Sidebar": "启用输出图库侧边栏"
}
-295
View File
@@ -1,295 +0,0 @@
import { app } from "/scripts/app.js";
import { api } from "/scripts/api.js";
import { State, promptStates, pruneHistory, cardElements, saveStatesToLocalStorage } from "./state.js";
import { findImagesInOutputs, findTextsInOutputs, parseWorkflow, getPrimaryOutputImages } from "./utils.js";
export let renderDOMFn = () => {};
export let updateSidebarBadgeFn = () => {};
export function setUIDependencies(renderFn, badgeFn) {
renderDOMFn = renderFn;
updateSidebarBadgeFn = badgeFn;
}
export async function syncQueue() {
try {
const q = await api.getQueue();
const runningList = q.Running || q.queue_running || [];
const pendingList = q.Pending || q.queue_pending || [];
const pendingIds = new Set();
const normalizedPending = pendingList.map((p, idx) => {
let pid = null, seq = idx;
if (Array.isArray(p)) {
seq = typeof p[0] === 'number' ? p[0] : idx;
pid = p[1];
} else if (p && typeof p === "object") {
pid = p.prompt_id || p.id || p.uuid;
seq = typeof p.number === 'number' ? p.number : (typeof p.prompt_number === 'number' ? p.prompt_number : idx);
}
return { pid: pid ? String(pid) : null, seq, original: p };
});
normalizedPending.sort((a, b) => a.seq - b.seq);
normalizedPending.forEach((item, index) => {
const pid = item.pid;
const number = index + 1;
if (pid) {
pendingIds.add(pid);
if (!promptStates.has(pid)) {
State.globalOrderCounter++;
promptStates.set(pid, {
pid: pid, status: "pending", images: [], progress: 0, queueNumber: number,
progressText: `Pending... (#${number})`, timestamp: State.globalOrderCounter,
workflow: app.graph.serialize()
});
} else {
const st = promptStates.get(pid);
if (st.status === "pending") {
st.queueNumber = number;
st.progressText = `Pending... (#${number})`;
}
}
}
});
for (const [pid, state] of promptStates.entries()) {
if (state.status === "pending" && !pendingIds.has(pid)) promptStates.delete(pid);
}
updateSidebarBadgeFn(pendingIds.size + (runningList.length > 0 ? 1 : 0));
renderDOMFn();
} catch (err) {
console.error("Comfy Sidebar: Failed to sync queue state", err);
}
}
const concludeRun = async (pid, statusStr) => {
const key = String(pid);
if (!key || !promptStates.has(key)) return;
if (State.currentlyActivePromptId === key) State.currentlyActivePromptId = null;
const st = promptStates.get(key);
if (st._previewBlobUrl) {
try { URL.revokeObjectURL(st._previewBlobUrl); } catch(e){}
delete st._previewBlobUrl;
}
if (st._oldPreviewBlobUrl) {
try { URL.revokeObjectURL(st._oldPreviewBlobUrl); } catch(e){}
delete st._oldPreviewBlobUrl;
}
st.status = statusStr;
st.progressText = "";
st.rendered = false;
st.endTime = Date.now();
if (st.startTime) st.duration = (st.endTime - st.startTime) / 1000;
for (let attempt = 0; attempt < 3; attempt++) {
try {
const res = await fetch(`/history/${key}`);
const hItem = await res.json();
if (hItem && hItem[key]) {
const rawWf = hItem[key].extra_data?.extra_pnginfo?.workflow || hItem[key].prompt?.[3]?.extra_pnginfo?.workflow || null;
st.workflow = parseWorkflow(rawWf) || st.workflow;
st.nodeOutputs = hItem[key].outputs;
const primaryImgs = getPrimaryOutputImages(hItem[key].outputs, st.workflow);
if (primaryImgs.length > 0) st.images = primaryImgs;
const fetchedTexts = findTextsInOutputs(hItem[key].outputs, st.workflow);
if (fetchedTexts.length > 0) st.texts = fetchedTexts;
break;
}
} catch (err) {}
await new Promise(r => setTimeout(r, 200));
}
pruneHistory(app);
saveStatesToLocalStorage();
syncQueue();
};
export function setupApiListeners() {
api.addEventListener("status", syncQueue);
api.addEventListener("reconnected", async () => {
console.log("Comfy Sidebar: Server reconnected, syncing state and history");
await initSessionAndHistory();
await syncQueue();
});
api.addEventListener("execution_start", (e) => {
if (app.ui.settings.getSettingValue("Comfy Sidebar.Auto Clear Interrupted") ?? false) {
const toDelete = [];
for (const [p, s] of promptStates.entries()) {
if (s.status === "cancelled" || s.status === "error") {
toDelete.push(p);
promptStates.delete(p);
}
}
if (toDelete.length > 0) {
api.fetchApi("/history", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delete: toDelete }) }).catch(()=>{});
saveStatesToLocalStorage();
}
}
const pid = String(e.detail.prompt_id);
State.currentlyActivePromptId = pid;
const activeWorkspaceWorkflow = app.graph.serialize();
if (promptStates.has(pid)) {
const st = promptStates.get(pid);
st.status = "active"; st.progressText = "Sampling..."; st.workflow = activeWorkspaceWorkflow;
st.rendered = false; st.startTime = Date.now(); st.duration = null;
} else {
State.globalOrderCounter++;
promptStates.set(pid, {
pid: pid, status: "active", images: [], progress: 0,
progressText: "Sampling...", timestamp: State.globalOrderCounter,
workflow: activeWorkspaceWorkflow, startTime: Date.now(), duration: null
});
}
renderDOMFn();
syncQueue();
});
api.addEventListener("progress", (e) => {
const pid = e.detail.prompt_id ? String(e.detail.prompt_id) : null;
if (pid && promptStates.has(pid)) {
const st = promptStates.get(pid);
st.progress = Math.round((e.detail.value / e.detail.max) * 100);
const cardObj = cardElements.get(pid);
if (cardObj && cardObj.progressBar) {
cardObj.progressBar.style.width = `${st.progress}%`;
if (cardObj.statusText && cardObj.statusText.style.display !== "none") {
const nodeName = st.activeNodeName ? (st.activeNodeName === "Finishing..." ? "Finishing..." : `[${st.activeNodeName}]`) : "Sampling...";
cardObj.statusText.textContent = `${nodeName} ${st.progress}%`;
}
} else {
renderDOMFn();
}
}
});
api.addEventListener("executing", (e) => {
const nodeId = e.detail;
const showWorkingNode = app.ui.settings.getSettingValue("Comfy Sidebar.Show Working Node Name") ?? true;
if (showWorkingNode && State.currentlyActivePromptId && promptStates.has(State.currentlyActivePromptId)) {
const st = promptStates.get(State.currentlyActivePromptId);
if (nodeId) {
const node = app.graph.getNodeById(nodeId);
st.activeNodeName = node ? (node.title || node.type) : `Node #${nodeId}`;
} else {
st.activeNodeName = "Finishing...";
}
renderDOMFn();
}
});
api.addEventListener("b_preview", (e) => {
const activeTasks = Array.from(promptStates.values()).filter(t => t.status === "active");
if (activeTasks.length > 0) {
const st = activeTasks[0];
const newBlobUrl = URL.createObjectURL(e.detail);
st._oldPreviewBlobUrl = st._previewBlobUrl;
st._previewBlobUrl = newBlobUrl;
st.images = [{ url: newBlobUrl }];
renderDOMFn();
}
});
api.addEventListener("executed", (e) => {
const pid = e.detail.prompt_id ? String(e.detail.prompt_id) : null;
if (pid && promptStates.has(pid)) {
const st = promptStates.get(pid);
const nodeImgs = findImagesInOutputs({ [e.detail.node]: e.detail.output }, st.workflow);
if (nodeImgs.length > 0) {
st.images = nodeImgs;
}
const nodeTexts = findTextsInOutputs({ [e.detail.node]: e.detail.output }, st.workflow);
if (nodeTexts.length > 0) {
st.texts = nodeTexts;
}
if (!st.nodeOutputs) st.nodeOutputs = {};
st.nodeOutputs[e.detail.node] = e.detail.output;
renderDOMFn();
}
});
api.addEventListener("execution_success", (e) => concludeRun(e.detail.prompt_id, "completed"));
api.addEventListener("execution_error", (e) => concludeRun(e.detail.prompt_id, "error"));
api.addEventListener("execution_interrupted", () => {
Array.from(promptStates.values()).filter(t => t.status === "active").forEach(t => concludeRun(t.pid, "cancelled"));
syncQueue();
});
}
export async function initSessionAndHistory() {
try {
const historyData = await api.getHistory();
if (!historyData) return;
const rawItems = [];
if (Array.isArray(historyData.History)) {
historyData.History.forEach(item => {
if (item && item.prompt_id) rawItems.push({ pid: String(item.prompt_id), data: item });
});
} else if (typeof historyData === 'object') {
Object.keys(historyData).forEach(pidKey => {
const item = historyData[pidKey];
rawItems.push({ pid: String(pidKey), data: Array.isArray(item) ? { prompt: item[0], outputs: item[1], status: item[2] } : item });
});
}
rawItems.sort((a, b) => {
const numA = a.data.prompt?.[0] ?? 0;
const numB = b.data.prompt?.[0] ?? 0;
return numA - numB;
});
rawItems.forEach(({ pid, data }) => {
if (promptStates.has(pid)) return;
const extraData = data.extra_data || data.prompt?.[3] || {};
const workflow = parseWorkflow(extraData.extra_pnginfo?.workflow || extraData.workflow);
const outputs = data.outputs || {};
const images = getPrimaryOutputImages(outputs, workflow);
const texts = findTextsInOutputs(outputs, workflow);
const statusStr = data.status?.status_str || "completed";
const status = (statusStr === "success" || statusStr === "completed") ? "completed" :
(statusStr === "error" ? "error" : "cancelled");
// Filter out empty records from history so dummy "No Outputs" cards don't pollute queue
if (images.length === 0 && texts.length === 0 && status === "completed") return;
State.globalOrderCounter++;
promptStates.set(pid, {
pid: pid,
status: status,
images: images,
texts: texts,
nodeOutputs: outputs,
workflow: workflow,
progressText: "",
timestamp: State.globalOrderCounter,
rendered: true
});
});
pruneHistory(app);
saveStatesToLocalStorage();
await syncQueue();
} catch (err) {
console.error("Comfy Sidebar: Failed to initialize history from server API", err);
}
}
+195
View File
@@ -0,0 +1,195 @@
import { api } from "/scripts/api.js";
import { app } from "/scripts/app.js";
import { store } from "../core/store.js";
import { PromptStatus } from "../core/constants.js";
import { createPromptState, activatePrompt, updatePromptProgress } from "../core/promptState.js";
import { syncQueue, concludeRun, initSessionAndHistory, clearCancelledOrFailed } from "./queueService.js";
import { findImagesInOutputs, findTextsInOutputs } from "../utils/utils.js";
import { updateActiveComparisonPreview, isRuntimePreviewEnabled, focusRuntimePreviewTarget, getActiveComparisonViewer, showFullscreenPreview } from "../utils/comparison.js";
import { getSetting } from "../core/settings.js";
export function setupExecutionTracker(onTargetedProgressUpdate) {
const onStatus = () => syncQueue();
const onReconnected = async () => {
console.log("Comfy Sidebar: Server reconnected, syncing state and history");
await initSessionAndHistory();
await syncQueue();
};
const onExecutionStart = (e) => {
const autoClear = getSetting(SettingIds.AUTO_CLEAR_INTERRUPTED, false);
if (autoClear) {
clearCancelledOrFailed();
}
const pid = String(e.detail.prompt_id);
store.setActivePromptId(pid);
const activeWorkspaceWorkflow = app.graph?.serialize ? app.graph.serialize() : null;
const existing = store.getPrompt(pid);
if (existing) {
activatePrompt(existing, { workflow: activeWorkspaceWorkflow });
store.updatePrompt(pid, existing);
} else {
const seq = store.nextSequence();
const newState = createPromptState(pid, {
status: PromptStatus.ACTIVE,
images: [],
progress: 0,
progressText: "Processing...",
timestamp: seq,
workflow: activeWorkspaceWorkflow,
startTime: Date.now()
});
store.setPrompt(pid, newState);
}
if (isRuntimePreviewEnabled()) {
focusRuntimePreviewTarget();
}
syncQueue();
};
const onProgress = (e) => {
const pid = e.detail.prompt_id ? String(e.detail.prompt_id) : null;
if (pid && store.hasPrompt(pid)) {
const prompt = store.getPrompt(pid);
const percent = Math.round((e.detail.value / e.detail.max) * 100);
updatePromptProgress(prompt, percent);
store.updatePrompt(pid, prompt);
if (typeof onTargetedProgressUpdate === "function") {
onTargetedProgressUpdate(pid, percent, prompt.activeNodeName);
}
} else if (pid && !store.hasPrompt(pid)) {
syncQueue();
}
};
const onExecuting = (e) => {
const nodeId = e.detail;
const showWorkingNode = getSetting(SettingIds.SHOW_WORKING_NODE_NAME, true);
const activePid = store.ui.currentlyActivePromptId;
if (activePid && store.hasPrompt(activePid)) {
const prompt = store.getPrompt(activePid);
if (nodeId) {
prompt.activeNodeId = String(nodeId);
const node = app.graph?.getNodeById ? app.graph.getNodeById(nodeId) : null;
prompt.activeNodeName = node ? (node.title || node.type) : `Node #${nodeId}`;
} else {
prompt.activeNodeName = "Finishing...";
}
store.updatePrompt(activePid, prompt);
if (showWorkingNode && typeof onTargetedProgressUpdate === "function") {
onTargetedProgressUpdate(activePid, prompt.progress, prompt.activeNodeName);
}
}
};
const onBPreview = (e) => {
const activeTasks = store.getAllPrompts().filter(t => t.status === PromptStatus.ACTIVE);
if (activeTasks.length > 0) {
const prompt = activeTasks[0];
const newBlobUrl = URL.createObjectURL(e.detail);
// Clean up the previous unreferenced blob immediately to prevent browser memory leaks
if (prompt._oldPreviewBlobUrl && prompt._oldPreviewBlobUrl !== prompt._previewBlobUrl) {
try { URL.revokeObjectURL(prompt._oldPreviewBlobUrl); } catch (_) {}
}
prompt._oldPreviewBlobUrl = prompt._previewBlobUrl;
prompt._previewBlobUrl = newBlobUrl;
prompt.images = [{ url: newBlobUrl }];
store.updatePrompt(prompt.pid, prompt);
// Update live fullscreen preview if currently open
updateActiveComparisonPreview(prompt.pid, newBlobUrl);
// If Runtime Preview mode is enabled but the overlay was closed, auto-open it
if (isRuntimePreviewEnabled() && !getActiveComparisonViewer()) {
showFullscreenPreview([newBlobUrl], false, prompt.pid);
}
// Update the active card in the sidebar
if (typeof onTargetedProgressUpdate === "function") {
onTargetedProgressUpdate(prompt.pid, prompt.progress, prompt.activeNodeName);
}
}
};
const onExecuted = (e) => {
const pid = e.detail.prompt_id ? String(e.detail.prompt_id) : null;
if (pid && store.hasPrompt(pid)) {
const prompt = store.getPrompt(pid);
const nodeImgs = findImagesInOutputs({ [e.detail.node]: e.detail.output }, prompt.workflow);
// Only update prompt.images if this node actually produced real output images
const hasRealNewImgs = nodeImgs.some(img => !img.isFallback);
if (hasRealNewImgs) {
prompt.images = nodeImgs;
// If fullscreen is open, smoothly transition to the final saved image
const finalImg = nodeImgs[0];
const finalSrc = finalImg.url || (window.location.origin + `/view?filename=${encodeURIComponent(finalImg.filename)}&type=${finalImg.type || 'output'}&subfolder=${encodeURIComponent(finalImg.subfolder || '')}&rand=${encodeURIComponent(pid)}`);
updateActiveComparisonPreview(pid, finalSrc);
}
const nodeTexts = findTextsInOutputs({ [e.detail.node]: e.detail.output }, prompt.workflow);
if (nodeTexts.length > 0) {
prompt.texts = nodeTexts;
}
if (!prompt.nodeOutputs) prompt.nodeOutputs = {};
prompt.nodeOutputs[e.detail.node] = e.detail.output;
store.updatePrompt(pid, prompt);
}
};
const onExecutionSuccess = (e) => {
const pid = e.detail?.prompt_id;
if (pid) concludeRun(pid, PromptStatus.COMPLETED);
};
const onExecutionError = (e) => {
const pid = e.detail?.prompt_id;
const nodeId = e.detail?.node_id;
if (pid && nodeId && store.hasPrompt(String(pid))) {
const prompt = store.getPrompt(String(pid));
prompt.activeNodeId = String(nodeId);
store.updatePrompt(String(pid), prompt);
}
if (pid) concludeRun(pid, PromptStatus.ERROR);
};
const onExecutionInterrupted = () => {
store.getAllPrompts()
.filter(t => t.status === PromptStatus.ACTIVE)
.forEach(t => concludeRun(t.pid, PromptStatus.CANCELLED));
syncQueue();
};
api.addEventListener("status", onStatus);
api.addEventListener("reconnected", onReconnected);
api.addEventListener("execution_start", onExecutionStart);
api.addEventListener("progress", onProgress);
api.addEventListener("executing", onExecuting);
api.addEventListener("b_preview", onBPreview);
api.addEventListener("executed", onExecuted);
api.addEventListener("execution_success", onExecutionSuccess);
api.addEventListener("execution_error", onExecutionError);
api.addEventListener("execution_interrupted", onExecutionInterrupted);
return () => {
api.removeEventListener("status", onStatus);
api.removeEventListener("reconnected", onReconnected);
api.removeEventListener("execution_start", onExecutionStart);
api.removeEventListener("progress", onProgress);
api.removeEventListener("executing", onExecuting);
api.removeEventListener("b_preview", onBPreview);
api.removeEventListener("executed", onExecuted);
api.removeEventListener("execution_success", onExecutionSuccess);
api.removeEventListener("execution_error", onExecutionError);
api.removeEventListener("execution_interrupted", onExecutionInterrupted);
};
}
+75
View File
@@ -0,0 +1,75 @@
import { parseWorkflow } from "../utils/utils.js";
import { PromptStatus } from "../core/constants.js";
export function normalizeQueueItem(p, defaultIndex = 0) {
let pid = null;
let seq = defaultIndex;
let rawWorkflow = null;
let outputs = {};
if (Array.isArray(p)) {
seq = typeof p[0] === "number" ? p[0] : defaultIndex;
pid = p[1] ? String(p[1]) : null;
const extraData = p[3] || {};
rawWorkflow = extraData.extra_pnginfo?.workflow || extraData.workflow || null;
outputs = p[4] || {};
} else if (p && typeof p === "object") {
pid = (p.prompt_id || p.id || p.uuid) ? String(p.prompt_id || p.id || p.uuid) : null;
seq = typeof p.number === "number" ? p.number : (typeof p.prompt_number === "number" ? p.prompt_number : defaultIndex);
const extraData = p.extra_data || {};
rawWorkflow = extraData.extra_pnginfo?.workflow || extraData.workflow || null;
outputs = p.outputs || {};
}
return {
pid,
seq,
workflow: parseWorkflow(rawWorkflow),
outputs
};
}
export function normalizeHistoryItem(pidKey, rawData) {
const pid = String(pidKey);
let item = rawData;
if (Array.isArray(item)) {
item = {
prompt: item[0],
outputs: item[1] || {},
status: item[2] || {}
};
} else if (!item || typeof item !== "object") {
item = { outputs: {}, status: {} };
}
const extraData = item.extra_data || item.prompt?.[3] || {};
const rawWf = extraData.extra_pnginfo?.workflow || extraData.workflow || null;
const workflow = parseWorkflow(rawWf);
const outputs = item.outputs || {};
const queueNumber = item.prompt?.[0] ?? 0;
const serverStatus = item.status?.status_str || "completed";
const isInterrupted = serverStatus === "interrupted" ||
(item.status?.messages && JSON.stringify(item.status.messages).toLowerCase().includes("interrupted"));
let status = PromptStatus.COMPLETED;
if (serverStatus === "success" || serverStatus === "completed") {
status = PromptStatus.COMPLETED;
} else if (isInterrupted) {
status = PromptStatus.CANCELLED;
} else if (serverStatus === "error") {
status = PromptStatus.ERROR;
} else {
status = PromptStatus.CANCELLED;
}
return {
pid,
queueNumber,
workflow,
outputs,
status,
serverStatus
};
}
+329
View File
@@ -0,0 +1,329 @@
import { api } from "/scripts/api.js";
import { app } from "/scripts/app.js";
import { store } from "../core/store.js";
import { PromptStatus, StoreEvents, SettingIds } from "../core/constants.js";
import { getSetting } from "../core/settings.js";
import { createPromptState, activatePrompt, finalizePrompt } from "../core/promptState.js";
import { normalizeQueueItem, normalizeHistoryItem } from "./queueNormalizer.js";
import { findImagesInOutputs, findTextsInOutputs, getPrimaryOutputImages, getNodeTitle } from "../utils/utils.js";
function extractNodeTitles(outputs, workflow, promptGraph = null) {
const titles = {};
if (!outputs) return titles;
for (const nodeId in outputs) {
const title = getNodeTitle(nodeId, workflow, promptGraph);
if (title) {
titles[nodeId] = title;
}
}
return titles;
}
export function extractPromptOutputs(outputs, workflow, promptGraph = null) {
return {
images: getPrimaryOutputImages(outputs, workflow),
texts: findTextsInOutputs(outputs, workflow),
nodeTitles: extractNodeTitles(outputs, workflow, promptGraph)
};
}
export async function syncQueue() {
try {
const q = await api.getQueue();
const runningList = q.Running || q.queue_running || [];
const pendingList = q.Pending || q.queue_pending || [];
const runningIds = new Set();
const pendingIds = new Set();
runningList.forEach((raw, idx) => {
const item = normalizeQueueItem(raw, idx);
if (!item.pid) return;
runningIds.add(item.pid);
store.setActivePromptId(item.pid);
const existing = store.getPrompt(item.pid);
const activeWorkflow = item.workflow || (app.graph?.serialize?.() || null);
if (!existing) {
const seq = store.nextSequence();
const { images, texts, nodeTitles } = extractPromptOutputs(item.outputs, activeWorkflow);
const newState = createPromptState(item.pid, {
status: PromptStatus.ACTIVE,
images,
texts,
nodeOutputs: item.outputs,
nodeTitles,
progress: 0,
progressText: "Processing...",
timestamp: seq,
workflow: activeWorkflow,
startTime: Date.now()
});
store.setPrompt(item.pid, newState);
} else {
const titles = extractNodeTitles(item.outputs, activeWorkflow);
if (existing.status !== PromptStatus.ACTIVE) {
activatePrompt(existing, { workflow: activeWorkflow, nodeTitles: titles });
store.updatePrompt(item.pid, existing);
} else {
if (!existing.workflow && activeWorkflow) existing.workflow = activeWorkflow;
if (Object.keys(titles).length > 0) Object.assign(existing.nodeTitles, titles);
store.updatePrompt(item.pid, existing);
}
}
});
const normalizedPending = pendingList
.map((raw, idx) => normalizeQueueItem(raw, idx))
.filter(item => Boolean(item.pid))
.sort((a, b) => a.seq - b.seq);
normalizedPending.forEach((item, index) => {
const number = index + 1;
pendingIds.add(item.pid);
const existing = store.getPrompt(item.pid);
if (!existing) {
const seq = store.nextSequence();
const newState = createPromptState(item.pid, {
status: PromptStatus.PENDING,
images: [],
progress: 0,
queueNumber: number,
progressText: `Pending... (#${number})`,
timestamp: seq,
workflow: app.graph?.serialize ? app.graph.serialize() : null
});
store.setPrompt(item.pid, newState);
} else if (existing.status === PromptStatus.PENDING) {
if (existing.queueNumber !== number) {
store.updatePrompt(item.pid, {
queueNumber: number,
progressText: `Pending... (#${number})`
});
}
}
});
for (const prompt of store.getAllPrompts()) {
if (prompt.status === PromptStatus.PENDING && !pendingIds.has(prompt.pid)) {
store.deletePrompt(prompt.pid);
} else if (prompt.status === PromptStatus.ACTIVE && !runningIds.has(prompt.pid)) {
// Do not prematurely mark as CANCELLED; let concludeRun verify via /history
concludeRun(prompt.pid, PromptStatus.COMPLETED);
}
}
store.emit(StoreEvents.QUEUE_SYNCED, {
pendingCount: pendingIds.size,
runningCount: runningIds.size
});
} catch (err) {
console.error("Comfy Sidebar: Failed to sync queue state", err);
}
}
export async function concludeRun(pid, fallbackStatus = PromptStatus.CANCELLED) {
const key = String(pid);
if (!key || !store.hasPrompt(key)) return;
if (store.ui.currentlyActivePromptId === key) {
store.setActivePromptId(null);
}
const state = store.getPrompt(key);
finalizePrompt(state, fallbackStatus);
// If cancelled while actively sampling, preserve the exact step preview where it was cancelled
const isCancelled = fallbackStatus === PromptStatus.CANCELLED || state.status === PromptStatus.CANCELLED;
const hasActivePreviewBlob = Boolean(state._previewBlobUrl || state.images?.some(img => img.url?.startsWith("blob:")));
for (let attempt = 0; attempt < 3; attempt++) {
try {
const res = await fetch(`/history/${key}`);
const hItem = await res.json();
if (hItem && hItem[key]) {
const norm = normalizeHistoryItem(key, hItem[key]);
state.workflow = norm.workflow || state.workflow;
state.nodeOutputs = norm.outputs || state.nodeOutputs;
state.status = norm.status;
const promptGraph = hItem[key].prompt?.[2] || null;
const { images: primaryImgs, texts: fetchedTexts, nodeTitles: titles } = extractPromptOutputs(norm.outputs, state.workflow, promptGraph);
Object.assign(state.nodeTitles, titles);
const hasActualSavedOutputs = primaryImgs.some(img => !img.isFallback);
// If cancelled while sampling, do NOT overwrite with older nodes; keep the exact step preview!
if (!isCancelled || !hasActivePreviewBlob) {
if (hasActualSavedOutputs || (state.status === PromptStatus.COMPLETED && primaryImgs.length > 0)) {
state.images = primaryImgs;
}
}
if (fetchedTexts.length > 0) state.texts = fetchedTexts;
break;
}
} catch (err) {}
await new Promise(r => setTimeout(r, 200));
}
// Ensure cancelled prompt keeps its preview blob if it had one
if (isCancelled && hasActivePreviewBlob) {
if (state._previewBlobUrl && (!state.images || state.images.length === 0 || !state.images[0].url?.startsWith("blob:"))) {
state.images = [{ url: state._previewBlobUrl }];
}
}
const maxItems = getSetting(SettingIds.MAX_HISTORY_ITEMS, 64);
store.pruneHistory(maxItems);
store.updatePrompt(key, state);
syncQueue();
}
export async function initSessionAndHistory() {
try {
const historyData = await api.getHistory();
if (!historyData) return;
const rawEntries = [];
if (Array.isArray(historyData.History)) {
historyData.History.forEach(item => {
if (item && item.prompt_id) {
rawEntries.push({ pid: String(item.prompt_id), data: item });
}
});
} else if (typeof historyData === "object") {
Object.keys(historyData).forEach(pidKey => {
rawEntries.push({ pid: String(pidKey), data: historyData[pidKey] });
});
}
const normalized = rawEntries.map(e => ({
norm: normalizeHistoryItem(e.pid, e.data),
promptGraph: e.data.prompt?.[2] || null
}));
normalized.sort((a, b) => a.norm.queueNumber - b.norm.queueNumber);
normalized.forEach(({ norm: item, promptGraph }) => {
const { images, texts, nodeTitles: titles } = extractPromptOutputs(item.outputs, item.workflow, promptGraph);
if (images.length === 0 && texts.length === 0 && item.status === PromptStatus.COMPLETED) {
return;
}
const existing = store.getPrompt(item.pid);
if (existing) {
if (existing.status === PromptStatus.ACTIVE || existing.status === PromptStatus.PENDING) {
existing.status = item.status;
existing.images = images;
existing.texts = texts;
existing.nodeOutputs = item.outputs;
existing.workflow = item.workflow || existing.workflow;
Object.assign(existing.nodeTitles, titles);
existing.progressText = "";
existing.rendered = false;
store.updatePrompt(item.pid, existing);
} else {
if (!existing.workflow && item.workflow) existing.workflow = item.workflow;
if ((!existing.images || existing.images.length === 0) && images.length > 0) existing.images = images;
if (!existing.nodeOutputs || Object.keys(existing.nodeOutputs).length === 0) {
existing.nodeOutputs = item.outputs;
}
if (!existing.nodeTitles) existing.nodeTitles = {};
Object.assign(existing.nodeTitles, titles);
if ((!existing.texts || existing.texts.length === 0) && texts && texts.length > 0) existing.texts = texts;
store.updatePrompt(item.pid, existing);
}
return;
}
const seq = store.nextSequence();
const newState = createPromptState(item.pid, {
status: item.status,
images,
texts,
nodeOutputs: item.outputs,
nodeTitles: titles,
workflow: item.workflow,
progressText: "",
timestamp: seq,
rendered: true
});
store.setPrompt(item.pid, newState);
});
const maxItems = getSetting(SettingIds.MAX_HISTORY_ITEMS, 64);
store.pruneHistory(maxItems);
await syncQueue();
} catch (err) {
console.error("Comfy Sidebar: Failed to initialize history from server API", err);
}
}
export async function cancelPendingTask(pid) {
try {
await api.fetchApi("/queue", { method: "POST", body: JSON.stringify({ delete: [pid] }) });
await syncQueue();
} catch (e) {
console.error("Comfy Sidebar: Failed to cancel pending task", e);
}
}
export async function cancelAllPending() {
try {
await api.fetchApi("/queue", { method: "POST", body: JSON.stringify({ clear: true }) });
await syncQueue();
} catch (e) {
console.error("Comfy Sidebar: Failed to cancel all pending tasks", e);
}
}
export async function interruptActive() {
try {
await api.interrupt();
await syncQueue();
} catch (e) {
console.error("Comfy Sidebar: Failed to interrupt active run", e);
}
}
export async function deleteHistoryItem(pid) {
try {
store.deletePrompt(pid);
await api.fetchApi("/history", { method: "POST", body: JSON.stringify({ delete: [pid] }) });
await syncQueue();
} catch (e) {
console.error("Comfy Sidebar: Failed to delete history item", e);
}
}
export async function clearAllHistory() {
try {
store.clearFinished();
await api.fetchApi("/history", { method: "POST", body: JSON.stringify({ clear: true }) });
await syncQueue();
} catch (e) {
console.error("Comfy Sidebar: Failed to clear all history", e);
}
}
export async function clearCancelledOrFailed() {
try {
const toDelete = store.clearCancelledOrFailed();
if (toDelete.length > 0) {
await api.fetchApi("/history", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ delete: toDelete })
});
}
await syncQueue();
} catch (e) {
console.error("Comfy Sidebar: Failed to clear cancelled or failed tasks", e);
}
}
+471 -341
View File
@@ -1,342 +1,472 @@
import { app } from "/scripts/app.js";
import { injectStyles } from "./styles.js";
import { setupDragAndDrop } from "./dragdrop.js";
import { setupSidebarUI, applySidebarOverride, findOurSidebarButton, setSyncQueue, updateSidebarBadge, renderDOM } from "./ui.js";
import { setupApiListeners, initSessionAndHistory, syncQueue, setUIDependencies } from "./queue.js";
import { applyClassicLayout, setupPropertiesPanelToggleFix, syncClassicLayout, syncStockHistoryAndProgressSettings } from "./layout.js";
let isInitialized = false;
let activeKeydownHandler = null;
let nodeDOMObserver = null;
function findHeaderByText(parent, text) {
if (!text) return null;
const cleanText = text.trim();
const elements = parent.querySelectorAll("span, div, h1, h2, h3, h4, p, [class*='title'], [class*='text']");
for (const el of elements) {
if (el.textContent.trim() === cleanText) {
if (el.offsetWidth > 0 && el.offsetHeight > 0 && el.offsetWidth < parent.offsetWidth * 0.9) {
return el;
}
}
}
return null;
}
function syncNodeVueBadge(node, isIgnored) {
const nodeEl = document.querySelector(
`.comfy-node[data-node-id="${node.id}"], ` +
`[data-node-id="${node.id}"], ` +
`[data-id="${node.id}"]`
);
if (!nodeEl) return;
const titleTextNode = findHeaderByText(nodeEl, node.title || node.type);
if (!titleTextNode) {
const badge = nodeEl.querySelector(".comfy-sidebar-ignore-badge");
if (badge && !isIgnored) badge.remove();
return;
}
const headerEl = titleTextNode.parentNode;
let badge = headerEl.querySelector(".comfy-sidebar-ignore-badge");
if (isIgnored) {
if (!badge) {
badge = document.createElement("div");
badge.className = "comfy-sidebar-ignore-badge";
badge.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/>
<path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/>
<path d="M6.61 6.61A13.52 13.52 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/>
<line x1="2" y1="2" x2="22" y2="22"/>
</svg>
`;
Object.assign(badge.style, {
marginLeft: "auto",
marginRight: "6px",
float: "right",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
color: "inherit",
pointerEvents: "none"
});
headerEl.appendChild(badge);
}
} else {
if (badge) badge.remove();
}
}
export function syncAllNodeBadges() {
applySidebarOverride();
if (!app.graph || !app.graph._nodes) return;
app.graph._nodes.forEach(node => {
if (!node.properties) node.properties = {};
const isIgnored = !!node.properties.ignoreInQueue;
if (isIgnored) {
if (node.boxcolor !== "#ff3333") {
node._oldBoxcolor = node.boxcolor || "";
node.boxcolor = "#ff3333";
if (app.graph) app.graph.setDirtyCanvas(true, true);
}
} else {
if (node.boxcolor === "#ff3333") {
node.boxcolor = node._oldBoxcolor || "";
delete node._oldBoxcolor;
if (app.graph) app.graph.setDirtyCanvas(true, true);
}
}
syncNodeVueBadge(node, isIgnored);
});
}
function setupVueNodeObserver() {
if (nodeDOMObserver) nodeDOMObserver.disconnect();
let timeoutId = null;
nodeDOMObserver = new MutationObserver((mutations) => {
let hasNodeMutation = false;
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node.nodeType === 1) {
if (node.hasAttribute?.("data-node-id") ||
node.classList?.contains("comfy-node") ||
node.querySelector?.('[data-node-id], .comfy-node')) {
hasNodeMutation = true;
break;
}
}
}
if (hasNodeMutation) break;
}
if (hasNodeMutation) {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
syncAllNodeBadges();
}, 50);
}
});
nodeDOMObserver.observe(document.body, {
childList: true,
subtree: true
});
}
function toggleIgnoreActiveNode() {
const canvas = app.canvas;
if (!canvas) return;
let nodes = [];
if (canvas.selected_nodes && Object.keys(canvas.selected_nodes).length > 0) {
nodes = Object.values(canvas.selected_nodes);
} else if (canvas.current_active_node) {
nodes = [canvas.current_active_node];
}
if (nodes.length === 0) return;
nodes.forEach(node => {
if (!node.properties) node.properties = {};
node.properties.ignoreInQueue = !node.properties.ignoreInQueue;
const isIgnored = !!node.properties.ignoreInQueue;
if (isIgnored) {
if (node.boxcolor !== "#ff3333") {
node._oldBoxcolor = node.boxcolor || "";
node.boxcolor = "#ff3333";
}
} else {
if (node.boxcolor === "#ff3333") {
node.boxcolor = node._oldBoxcolor || "";
delete node._oldBoxcolor;
}
}
syncNodeVueBadge(node, isIgnored);
});
if (app.graph) app.graph.setDirtyCanvas(true, true);
if (app.canvas) app.canvas.setDirty(true, true);
}
app.registerExtension({
name: "ComfySidebar.ClassicRestore",
init() {
app.ui.settings.addSetting({ id: "Comfy Sidebar.Grid Columns Threshold", name: "Width Threshold for Queue Columns (px)", type: "number", defaultValue: 350 });
app.ui.settings.addSetting({ id: "Comfy Sidebar.Show Pending Count Only", name: "If disabled, each queued job will have a separate individual card", type: "boolean", defaultValue: true });
app.ui.settings.addSetting({ id: "Comfy Sidebar.Show Working Node Name", name: "Shows the name of the node which is currently in the process", type: "boolean", defaultValue: true });
app.ui.settings.addSetting({ id: "Comfy Sidebar.Auto Clear Interrupted", name: "Auto-clear cancelled & failed jobs on new generation", type: "boolean", defaultValue: false });
const sidebarTabs = ["Assets", "Nodes", "Models", "Workflows", "Apps", "Templates"];
sidebarTabs.forEach(tab => {
app.ui.settings.addSetting({
id: `Comfy Sidebar.Hide Junk.${tab}`,
name: `Hide Tab: ${tab}`,
type: "boolean",
defaultValue: false,
onChange: () => {
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
});
app.ui.settings.addSetting({
id: "Comfy Sidebar.Hide Junk.Override Stock Job History Tab",
name: "Replace the stock Job History sidebar with Comfy Queue",
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (isInitialized && app.ui && app.ui.settings) {
syncStockHistoryAndProgressSettings(value);
}
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
app.ui.settings.addSetting({
id: "Comfy Sidebar.Hide Junk.Graph Button",
name: "Hide floating 'Graph' (Workflow/Node Map) button",
type: "boolean",
defaultValue: false,
onChange: () => {
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
app.ui.settings.addSetting({
id: "Comfy Sidebar.Comfy Layout",
name: "Places the controls and the open workflow tabs on a single unified top bar",
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (isInitialized) {
applyClassicLayout(value, true);
}
}
});
},
commands: [
{
id: "ComfySidebar.ToggleSidebar",
label: "Toggle Comfy Queue Sidebar",
function: () => {
const ourBtn = findOurSidebarButton();
if (ourBtn) ourBtn.click();
}
},
{
id: "ComfySidebar.ToggleIgnoreNode",
label: "Toggle Ignore Selected Node(s) in Queue",
function: () => toggleIgnoreActiveNode()
}
],
nodeCreated(node) {
if (node && node.properties?.ignoreInQueue) {
node.boxcolor = "#ff3333";
syncNodeVueBadge(node, true);
}
},
afterConfigureGraph() {
requestAnimationFrame(() => syncAllNodeBadges());
},
async setup() {
if (!app.extensionManager || !app.extensionManager.registerSidebarTab) return;
const isClassicLayoutEnabled = app.ui.settings.getSettingValue("Comfy Sidebar.Comfy Layout") ?? false;
applyClassicLayout(isClassicLayoutEnabled, false);
const isHistoryOverrideEnabled = app.ui.settings.getSettingValue("Comfy Sidebar.Hide Junk.Override Stock Job History Tab") ?? false;
if (isHistoryOverrideEnabled) {
syncStockHistoryAndProgressSettings(true);
}
isInitialized = true;
setupPropertiesPanelToggleFix();
setSyncQueue(syncQueue);
setUIDependencies(renderDOM, updateSidebarBadge);
injectStyles();
setupDragAndDrop();
const sidebarContainer = setupSidebarUI();
setupApiListeners();
await initSessionAndHistory();
setupVueNodeObserver();
if (activeKeydownHandler) {
document.removeEventListener("keydown", activeKeydownHandler, true);
activeKeydownHandler = null;
}
activeKeydownHandler = (e) => {
const activeEl = document.activeElement;
if (activeEl && (
activeEl.tagName === "INPUT" ||
activeEl.tagName === "TEXTAREA" ||
activeEl.isContentEditable ||
activeEl.tagName === "SELECT"
)) return;
if (e.key.toLowerCase() === "q" && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
const ourBtn = findOurSidebarButton();
if (ourBtn) ourBtn.click();
}
if (e.key.toLowerCase() === "q" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
toggleIgnoreActiveNode();
}
};
document.addEventListener("keydown", activeKeydownHandler, true);
applySidebarOverride();
app.extensionManager.registerSidebarTab({
id: "classic-comfy-sidebar",
icon: "pi pi-images",
title: "Queue",
tooltip: "Comfy Queue (Q)",
type: "custom",
render: (el) => { el.appendChild(sidebarContainer); }
});
},
destroy() {
if (nodeDOMObserver) {
nodeDOMObserver.disconnect();
nodeDOMObserver = null;
}
if (activeKeydownHandler) {
document.removeEventListener("keydown", activeKeydownHandler, true);
activeKeydownHandler = null;
}
if (app.extensionManager?.unregisterSidebarTab) {
app.extensionManager.unregisterSidebarTab("classic-comfy-sidebar");
}
}
import { app } from "/scripts/app.js";
import { SettingIds } from "./core/constants.js";
import { injectStyles } from "./utils/styles.js";
import { setupDragAndDrop } from "./utils/dragdrop.js";
import { renumberNodesTopologically, setManualNodeId } from "./utils/nodeRenumber.js";
import { findOurSidebarButton, applySidebarOverride } from "./comfy/adapter.js";
import { syncAllNodeBadges, setupVueNodeObserver, toggleIgnoreActiveNode } from "./comfy/nodes.js";
import { applyClassicLayout, setupPropertiesPanelToggleFix, syncClassicLayout, syncStockHistoryAndProgressSettings, destroyLayoutFix } from "./comfy/layout.js";
import { initSessionAndHistory, syncQueue } from "./queue/queueService.js";
import { setupExecutionTracker } from "./queue/executionTracker.js";
import { setupSidebarView, renderSidebar, teardownSidebarView } from "./ui/sidebarView.js";
import { setupGalleryView, teardownGalleryView } from "./ui/galleryView.js";
import { initI18n, t } from "./core/i18n.js";
import { updateCardProgressTargeted, cardPool } from "./ui/cardRenderer.js";
import { getScrollContainer } from "./utils/utils.js";
import { store } from "./core/store.js";
import { getSetting, setSetting } from "./core/settings.js";
let isInitialized = false;
let activeKeydownHandler = null;
let cleanupFns = [];
function setupKeydownShortcuts() {
activeKeydownHandler = (e) => {
const activeEl = document.activeElement;
if (activeEl && (
activeEl.tagName === "INPUT" ||
activeEl.tagName === "TEXTAREA" ||
activeEl.isContentEditable ||
activeEl.tagName === "SELECT"
)) return;
// Q: Toggle Queue Sidebar
if (e.key.toLowerCase() === "q" && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
if (app.extensionManager?.command?.hasCommand?.("Workspace.ToggleSidebarTab.classic-comfy-sidebar")) {
app.extensionManager.command.execute("Workspace.ToggleSidebarTab.classic-comfy-sidebar");
} else {
const ourBtn = findOurSidebarButton();
if (ourBtn) ourBtn.click();
}
}
// Ctrl+Q / Cmd+Q: Toggle Ignore Selected Node
if (e.key.toLowerCase() === "q" && (e.ctrlKey || e.metaKey) && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
toggleIgnoreActiveNode(() => renderSidebar());
}
// Alt+R: Renumber all nodes in execution order
if (e.key.toLowerCase() === "r" && e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey) {
e.preventDefault();
e.stopPropagation();
renumberNodesTopologically();
}
};
document.addEventListener("keydown", activeKeydownHandler, true);
}
function registerSettings() {
app.ui.settings.addSetting({
id: SettingIds.GRID_COLUMNS_THRESHOLD,
name: t("Width Threshold for Queue Columns (px)"),
type: "number",
defaultValue: 350
});
app.ui.settings.addSetting({
id: SettingIds.SHOW_PENDING_COUNT_ONLY,
name: t("If disabled, each queued job will have a separate individual card"),
type: "boolean",
defaultValue: true
});
app.ui.settings.addSetting({
id: SettingIds.SHOW_WORKING_NODE_NAME,
name: t("Shows the name of the node which is currently in the process"),
type: "boolean",
defaultValue: true
});
app.ui.settings.addSetting({
id: SettingIds.AUTO_CLEAR_INTERRUPTED,
name: t("Auto-clear cancelled & failed jobs on new generation"),
type: "boolean",
defaultValue: false
});
const setGalleryButtonVisible = (visible) => {
try {
const buttons = document.querySelectorAll(".side-bar-button, [data-tab-id]");
for (const btn of buttons) {
if (btn.getAttribute("data-tab-id") === "classic-comfy-gallery" ||
btn.getAttribute("title")?.includes("Gallery") ||
btn.querySelector(".pi-folder")) {
btn.style.display = visible ? "" : "none";
break;
}
}
} catch (e) {
console.warn("[ComfySidebar] Error toggling gallery tab button:", e);
}
};
app.ui.settings.addSetting({
id: "Comfy Sidebar.Enable Gallery",
name: t("Enable Output Gallery Sidebar"),
type: "boolean",
defaultValue: true,
onChange: (val) => {
setGalleryButtonVisible(val ?? true);
}
});
app.ui.settings.addSetting({
id: "Comfy Sidebar.Permanent Delete on Disk Deletion",
name: t("Permanently delete files on disk deletion (bypasses Recycle Bin / Trash)"),
type: "boolean",
defaultValue: false
});
const sidebarTabs = ["Assets", "Nodes", "Models", "Workflows", "Apps", "Templates"];
sidebarTabs.forEach(tab => {
app.ui.settings.addSetting({
id: `Comfy Sidebar.Hide Junk.${tab}`,
name: t("Hide Tab: {tab}", { tab: t(tab) }),
type: "boolean",
defaultValue: false,
onChange: () => {
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
});
app.ui.settings.addSetting({
id: SettingIds.OVERRIDE_STOCK_HISTORY,
name: t("Replace the stock Job History sidebar with Comfy Queue"),
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (isInitialized && app.ui?.settings) {
syncStockHistoryAndProgressSettings(value);
}
applySidebarOverride();
setTimeout(() => {
applySidebarOverride();
syncClassicLayout();
}, 50);
}
});
app.ui.settings.addSetting({
id: SettingIds.HIDE_GRAPH_BUTTON,
name: t("Hide floating 'Graph' (Workflow/Node Map) button"),
type: "boolean",
defaultValue: false,
onChange: () => {
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
app.ui.settings.addSetting({
id: "Comfy Sidebar.Hide Junk.Avatar",
name: t("Hide Avatar"),
type: "boolean",
defaultValue: false,
onChange: () => {
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
app.ui.settings.addSetting({
id: "Comfy Sidebar.Hide Junk.Floating Canvas Controls",
name: t("Floating Canvas Controls"),
type: "combo",
options: ["Default", "Dock", "Hide"],
defaultValue: "Default",
onChange: () => {
setTimeout(() => { syncClassicLayout(); }, 0);
}
});
app.ui.settings.addSetting({
id: SettingIds.CLASSIC_LAYOUT,
name: t("Places the controls and the open workflow tabs on a single unified top bar"),
type: "boolean",
defaultValue: false,
onChange: (value) => {
if (isInitialized) {
applyClassicLayout(value, true);
}
}
});
}
function setupWorkflowTabsPositionWatcher() {
let isSyncing = false;
const TARGET_SETTING = "Comfy.Workflow.WorkflowTabsPosition";
const checkAndDisableIfSidebar = (val) => {
if (isSyncing) return;
if (val === "Sidebar") {
const isClassicEnabled = getSetting(SettingIds.CLASSIC_LAYOUT, false);
if (isClassicEnabled) {
isSyncing = true;
try {
setSetting(SettingIds.CLASSIC_LAYOUT, false);
applyClassicLayout(false, false);
} finally {
isSyncing = false;
}
}
}
};
const cleanups = [];
const attachNativeOnChange = (settingObj) => {
if (!settingObj || settingObj._classicWatcherAttached) return;
settingObj._classicWatcherAttached = true;
const origOnChange = settingObj.onChange;
settingObj.onChange = (val) => {
if (origOnChange) origOnChange(val);
checkAndDisableIfSidebar(val);
};
cleanups.push(() => {
settingObj.onChange = origOnChange;
delete settingObj._classicWatcherAttached;
});
};
attachNativeOnChange(app.ui?.settings?.settings?.[TARGET_SETTING]);
attachNativeOnChange(app.extensionManager?.setting?.getSetting?.(TARGET_SETTING));
attachNativeOnChange(app.extensionManager?.setting?.settings?.[TARGET_SETTING]);
const settingStore = app.extensionManager?.setting?.settingStore;
if (settingStore?.$subscribe) {
const unsubscribe = settingStore.$subscribe(() => {
const val = getSetting(TARGET_SETTING);
checkAndDisableIfSidebar(val);
});
cleanups.push(unsubscribe);
}
if (app.ui?.settings?.addSetting) {
const origAdd = app.ui.settings.addSetting.bind(app.ui.settings);
app.ui.settings.addSetting = (setting) => {
if (setting?.id === TARGET_SETTING) {
attachNativeOnChange(setting);
}
return origAdd(setting);
};
cleanups.push(() => {
app.ui.settings.addSetting = origAdd;
});
}
if (app.ui?.settings?.setSettingValue) {
const origSetSettingValue = app.ui.settings.setSettingValue.bind(app.ui.settings);
app.ui.settings.setSettingValue = (id, value) => {
origSetSettingValue(id, value);
if (id === TARGET_SETTING) checkAndDisableIfSidebar(value);
};
cleanups.push(() => {
app.ui.settings.setSettingValue = origSetSettingValue;
});
}
if (app.extensionManager?.setting?.set) {
const origExtSet = app.extensionManager.setting.set.bind(app.extensionManager.setting);
app.extensionManager.setting.set = (id, value) => {
origExtSet(id, value);
if (id === TARGET_SETTING) checkAndDisableIfSidebar(value);
};
cleanups.push(() => {
app.extensionManager.setting.set = origExtSet;
});
}
return () => {
cleanups.forEach(fn => fn());
};
}
app.registerExtension({
name: "ComfySidebar.ClassicRestore",
async init() {
await initI18n();
registerSettings();
},
commands: [
{
id: "ComfySidebar.ToggleIgnoreNode",
label: t("Toggle Ignore Selected Node(s) in Queue"),
function: () => toggleIgnoreActiveNode(() => renderSidebar())
},
{
id: "ComfySidebar.RenumberNodes",
label: t("Renumber All Nodes (Execution Order)"),
function: () => renumberNodesTopologically()
},
{
id: "ComfySidebar.SetNodeId",
label: t("Set Selected Node ID..."),
function: () => setManualNodeId()
}
],
getNodeMenuItems(node) {
return [
null,
{
content: t("Set Node ID..."),
callback: () => setManualNodeId(node)
}
];
},
getCanvasMenuItems() {
return [
null,
{
content: t("Renumber All Nodes (Execution Order)"),
callback: () => renumberNodesTopologically()
}
];
},
nodeCreated(node) {
if (node && node.properties?.ignoreInQueue) {
node.boxcolor = "#ff3333";
syncAllNodeBadges();
}
},
afterConfigureGraph() {
requestAnimationFrame(() => {
syncAllNodeBadges();
renderSidebar();
});
},
async setup() {
if (!app.extensionManager || !app.extensionManager.registerSidebarTab) return;
await initI18n();
const tabsPos = getSetting("Comfy.Workflow.WorkflowTabsPosition");
let isClassicLayoutEnabled = getSetting(SettingIds.CLASSIC_LAYOUT, false);
if (isClassicLayoutEnabled && tabsPos === "Sidebar") {
isClassicLayoutEnabled = false;
setSetting(SettingIds.CLASSIC_LAYOUT, false);
}
applyClassicLayout(isClassicLayoutEnabled, false);
const isHistoryOverrideEnabled = getSetting(SettingIds.OVERRIDE_STOCK_HISTORY, false);
if (isHistoryOverrideEnabled) {
syncStockHistoryAndProgressSettings(true);
}
isInitialized = true;
setupPropertiesPanelToggleFix();
injectStyles();
cleanupFns.push(setupWorkflowTabsPositionWatcher());
cleanupFns.push(setupDragAndDrop());
cleanupFns.push(setupVueNodeObserver());
cleanupFns.push(setupExecutionTracker((pid, progress, nodeName) => {
const cardObj = cardPool.get(pid);
const state = store.getPrompt(pid);
if (cardObj && state) {
const showWorkingNode = getSetting(SettingIds.SHOW_WORKING_NODE_NAME, true);
updateCardProgressTargeted(cardObj, progress, nodeName, showWorkingNode, state);
} else {
renderSidebar();
}
}));
const sidebarContainer = setupSidebarView();
await initSessionAndHistory();
setupKeydownShortcuts();
syncAllNodeBadges();
let queueScrollPos = 0;
let galleryScrollPos = 0;
let activeSidebarTab = "queue";
app.extensionManager.registerSidebarTab({
id: "classic-comfy-sidebar",
icon: "pi pi-images",
title: t("Queue"),
tooltip: `${t("Queue")} (Q)`,
type: "custom",
render: (el) => {
document.querySelectorAll(".comfy-sidebar-scroll-top-btn").forEach(btn => { btn.style.display = "none"; });
const scrollParent = getScrollContainer(el);
if (activeSidebarTab === "gallery" && scrollParent) {
galleryScrollPos = scrollParent.scrollTop;
}
activeSidebarTab = "queue";
el.replaceChildren(sidebarContainer);
requestAnimationFrame(() => {
const sp = getScrollContainer(el);
if (sp) sp.scrollTop = queueScrollPos;
});
}
});
const galleryContainer = setupGalleryView();
app.extensionManager.registerSidebarTab({
id: "classic-comfy-gallery",
icon: "pi pi-folder",
title: t("Gallery"),
tooltip: t("Gallery (Outputs)"),
type: "custom",
render: (el) => {
document.querySelectorAll(".comfy-sidebar-scroll-top-btn").forEach(btn => { btn.style.display = "none"; });
const scrollParent = getScrollContainer(el);
if (activeSidebarTab === "queue" && scrollParent) {
queueScrollPos = scrollParent.scrollTop;
}
activeSidebarTab = "gallery";
el.replaceChildren(galleryContainer);
requestAnimationFrame(() => {
const sp = getScrollContainer(el);
if (sp) sp.scrollTop = galleryScrollPos;
});
}
});
const isGalleryEnabled = getSetting("Comfy Sidebar.Enable Gallery", true);
if (!isGalleryEnabled) {
setTimeout(() => setGalleryButtonVisible(false), 50);
}
requestAnimationFrame(() => {
applySidebarOverride();
});
},
destroy() {
for (const fn of cleanupFns.splice(0)) {
try { if (typeof fn === "function") fn(); } catch (e) {}
}
destroyLayoutFix();
teardownSidebarView();
teardownGalleryView();
if (app.extensionManager?.unregisterSidebarTab) {
app.extensionManager.unregisterSidebarTab("classic-comfy-gallery");
}
if (activeKeydownHandler) {
document.removeEventListener("keydown", activeKeydownHandler, true);
activeKeydownHandler = null;
}
if (app.extensionManager?.unregisterSidebarTab) {
app.extensionManager.unregisterSidebarTab("classic-comfy-sidebar");
}
}
});
-114
View File
@@ -1,114 +0,0 @@
export const promptStates = new Map();
export const cardElements = new Map();
export const State = {
currentSearchQuery: "",
globalOrderCounter: 0,
sidebarContainer: null,
cardStack: null, // Main queue scroll container
submenuStack: null, // Submenu scroll container
currentlyActivePromptId: null,
activeSubmenuPromptId: null, // Active run/outputs explorer pointer
activeSubmenuBatchImages: null // Active batch images explorer pointer
};
export function deletePromptState(pid) {
const key = String(pid);
const state = promptStates.get(key);
if (state) {
if (state._previewBlobUrl) {
try { URL.revokeObjectURL(state._previewBlobUrl); } catch (e) {}
}
if (state._oldPreviewBlobUrl) {
try { URL.revokeObjectURL(state._oldPreviewBlobUrl); } catch (e) {}
}
}
promptStates.delete(key);
cardElements.delete(key);
}
export function pruneHistory(app) {
const maxItems = app.ui.settings.getSettingValue("Comfy.Queue.MaxHistoryItems") ?? 64;
const tasks = Array.from(promptStates.entries())
.filter(([pid, state]) => state.status !== "pending" && state.status !== "active");
tasks.sort((a, b) => a[1].timestamp - b[1].timestamp);
if (tasks.length > maxItems) {
const deleteCount = tasks.length - maxItems;
for (let i = 0; i < deleteCount; i++) {
const [pid] = tasks[i];
deletePromptState(pid);
}
}
}
export function saveStatesToLocalStorage() {
try {
let serializable = [];
for (const [pid, state] of promptStates.entries()) {
const cleanedImages = (state.images || []).map(img => {
if (img.url && img.url.startsWith("blob:")) return null;
return img;
}).filter(Boolean);
// Include workflow JSON ONLY for image-less / unfinished / failed tasks
// so users can load or save their workflows even after browser reloads!
const includeWorkflow = cleanedImages.length === 0 || state.status !== "completed";
serializable.push({
pid: String(state.pid),
status: state.status,
images: cleanedImages,
texts: state.texts || [],
nodeOutputs: state.nodeOutputs,
workflow: includeWorkflow ? state.workflow : null,
progress: state.progress || 0,
queueNumber: state.queueNumber,
progressText: state.progressText || "",
timestamp: state.timestamp,
activeNodeName: state.activeNodeName || "",
rendered: state.rendered || false,
startTime: state.startTime,
endTime: state.endTime,
duration: state.duration
});
}
if (serializable.length === 0) {
localStorage.removeItem("comfy_sidebar_prompt_states");
return;
}
serializable.sort((a, b) => a.timestamp - b.timestamp);
while (serializable.length > 0) {
try {
localStorage.setItem("comfy_sidebar_prompt_states", JSON.stringify(serializable));
break;
} catch (e) {
if (e.name === "QuotaExceededError" || e.code === 22 || e.code === 1014) {
serializable.shift();
} else {
break;
}
}
}
} catch (e) {}
}
export function loadStatesFromLocalStorage() {
try {
const data = localStorage.getItem("comfy_sidebar_prompt_states");
if (data) {
const list = JSON.parse(data);
list.forEach(state => {
const key = String(state.pid);
promptStates.set(key, state);
if (state.timestamp > State.globalOrderCounter) State.globalOrderCounter = state.timestamp;
});
}
} catch (e) {}
}
loadStatesFromLocalStorage();
-354
View File
@@ -1,354 +0,0 @@
export function injectStyles() {
if (document.getElementById("comfy-sidebar-styles")) return;
const style = document.createElement("style");
style.id = "comfy-sidebar-styles";
style.textContent = `
.comfy-sidebar-card {
background: var(--comfy-input-bg, #181818);
border-radius: 4px; padding: 8px; position: relative;
min-height: 80px; margin-bottom: 12px; break-inside: avoid;
user-select: none; -webkit-user-select: none;
border: 2px solid var(--border-color, #333);
color: var(--comfy-input-color, var(--fg-color, #eee));
}
.comfy-sidebar-card:hover {
border-color: var(--p-primary-color, var(--primary-color, #555)) !important;
transition: border-color 0.2s, background-color 0.2s;
}
.comfy-sidebar-card.active { --border-color: #3b82f6; --hover-color: #60a5fa; }
.comfy-sidebar-card.pending { --border-color: #6c757d; --hover-color: #adb5bd; }
.comfy-sidebar-card.cancelled { --border-color: #ffc107; --hover-color: #ffe082; }
.comfy-sidebar-card.error { --border-color: #dc3545; --hover-color: #f87171; }
.comfy-sidebar-card.pending .comfy-sidebar-queue-cancel-btn,
.comfy-sidebar-card.active .comfy-sidebar-queue-cancel-btn {
display: none !important;
}
.comfy-sidebar-card.pending:hover .comfy-sidebar-queue-cancel-btn,
.comfy-sidebar-card.active:hover .comfy-sidebar-queue-cancel-btn {
display: flex !important;
}
.comfy-sidebar-card-timer {
position: absolute; top: 6px; left: 8px; font-size: 10px;
font-family: monospace; opacity: 0.7; background: rgba(0, 0, 0, 0.6);
padding: 2px 4px; border-radius: 3px; pointer-events: none; z-index: 5; color: #fff;
}
.comfy-sidebar-queue-cancel-btn {
display: none;
align-items: center !important;
justify-content: center !important;
width: 32px !important;
height: 32px !important;
background-color: #7f1d1d !important;
color: #e2e8f0 !important;
font-size: 11px !important;
border-radius: 6px !important;
cursor: pointer !important;
transition: background-color 0.15s ease, color 0.15s ease !important;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
}
.comfy-sidebar-queue-cancel-btn:hover {
background-color: #991b1b !important;
color: #ffffff !important;
}
/* Hover Panels CSS Hover Control */
.comfy-sidebar-hover-panel,
.comfy-sidebar-left-hover-panel {
display: none !important;
}
.comfy-sidebar-card:hover .comfy-sidebar-hover-panel,
.comfy-sidebar-card:hover .comfy-sidebar-left-hover-panel {
display: flex !important;
}
/* Card Action Buttons */
.comfy-sidebar-card-action-btn {
display: inline-flex;
align-items: center !important;
justify-content: center !important;
width: 30px !important;
height: 30px !important;
background-color: rgba(0, 0, 0, 0.75) !important;
color: #e2e8f0 !important;
font-size: 13px !important;
border-radius: 6px !important;
cursor: pointer !important;
transition: all 0.15s ease !important;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
z-index: 20 !important;
transform: translateZ(0);
}
.comfy-sidebar-card-action-btn:hover {
background-color: rgba(0, 0, 0, 0.95) !important;
color: #ffffff !important;
}
/* Delete Confirmation Active State */
.comfy-sidebar-card-action-btn.confirm-delete,
.comfy-sidebar-card-action-btn.confirm-delete:hover {
background-color: #dc3545 !important;
color: #ffffff !important;
box-shadow: 0 0 8px rgba(220, 53, 69, 0.6) !important;
}
/* Header Icons & Header Action Buttons */
.comfy-sidebar-header-btn {
background: transparent;
color: var(--desc-color, #aaa);
border: 1px solid var(--border-color, #555);
border-radius: 3px;
padding: 4px 8px;
cursor: pointer;
font-size: 13px;
transition: all 0.15s ease-in-out;
}
.comfy-sidebar-header-btn:hover {
border-color: var(--fg-color, #eee);
color: var(--fg-color, #eee);
}
.comfy-sidebar-icon-btn {
cursor: pointer;
font-size: 13px;
opacity: 0.6;
transition: opacity 0.15s ease-in-out;
}
.comfy-sidebar-icon-btn:hover {
opacity: 1;
}
/* Scroll To Top Floating Button */
.comfy-sidebar-scroll-top-btn {
position: absolute;
bottom: 14px;
right: 28px;
width: 32px;
height: 32px;
border-radius: 50%;
background: rgba(30, 30, 30, 0.9);
color: #eee;
border: 1px solid var(--border-color, #555);
cursor: pointer;
font-size: 13px;
display: none;
align-items: center;
justify-content: center;
z-index: 999;
box-shadow: 0 4px 12px rgba(0,0,0,0.6);
transition: all 0.15s ease-in-out;
opacity: 0.85;
}
.comfy-sidebar-scroll-top-btn:hover {
opacity: 1;
background: var(--p-primary-color, #3b82f6);
color: #fff;
border-color: var(--p-primary-color, #3b82f6);
}
/* 3D Preview Cards */
.comfy-sidebar-3d-wrapper {
width: 100%;
height: 160px;
background: linear-gradient(135deg, #1e1e2e 0%, #0f172a 100%);
border-radius: 4px;
display: flex;
position: relative;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
transition: all 0.2s ease-in-out;
user-select: none;
cursor: pointer;
}
.comfy-sidebar-3d-wrapper:hover {
border-color: #3b82f6;
box-shadow: 0 0 12px rgba(59, 130, 246, 0.35);
}
.comfy-sidebar-3d-preview-img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
filter: brightness(0.45);
transition: filter 0.2s ease, transform 0.2s ease;
pointer-events: none;
z-index: 1;
}
.comfy-sidebar-3d-wrapper:hover .comfy-sidebar-3d-preview-img {
filter: brightness(0.6);
transform: scale(1.03);
}
.comfy-sidebar-3d-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 2;
pointer-events: none;
}
.comfy-sidebar-3d-icon {
font-size: 38px;
color: #60a5fa;
margin-bottom: 6px;
filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.8));
transition: transform 0.2s ease;
}
.comfy-sidebar-3d-wrapper:hover .comfy-sidebar-3d-icon {
transform: scale(1.1) rotate(6deg);
}
.comfy-sidebar-3d-badge {
position: absolute;
top: 6px;
right: 6px;
background: rgba(59, 130, 246, 0.9);
color: #fff;
font-size: 9px;
font-weight: bold;
padding: 2px 6px;
border-radius: 3px;
text-transform: uppercase;
letter-spacing: 0.5px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
z-index: 3;
}
.comfy-sidebar-3d-title {
font-size: 10px;
color: #f1f5f9;
font-family: monospace;
max-width: 85%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background: rgba(0, 0, 0, 0.65);
padding: 2px 6px;
border-radius: 3px;
backdrop-filter: blur(2px);
z-index: 3;
}
/* Audio Preview Cards */
.comfy-sidebar-audio-wrapper {
width: 100%;
min-height: 110px;
background: linear-gradient(135deg, #1e1333 0%, #0f172a 100%);
border-radius: 4px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 10px 12px 12px 12px;
box-sizing: border-box;
position: relative;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
transition: all 0.2s ease-in-out;
user-select: none;
cursor: pointer;
}
.comfy-sidebar-audio-wrapper:hover {
border-color: #a855f7;
box-shadow: 0 0 12px rgba(168, 85, 247, 0.35);
}
.comfy-sidebar-audio-badge {
background: rgba(168, 85, 247, 0.9);
color: #fff;
font-size: 9px;
font-weight: bold;
padding: 2px 6px;
border-radius: 3px;
text-transform: uppercase;
letter-spacing: 0.5px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
z-index: 3;
}
.comfy-sidebar-audio-title {
font-size: 10px;
color: #f1f5f9;
font-family: monospace;
max-width: 65%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
z-index: 3;
}
.comfy-sidebar-soundwave-container {
display: flex;
align-items: center;
justify-content: center;
gap: 3px;
height: 36px;
margin: 4px 0;
}
.comfy-sidebar-soundwave-bar {
width: 3px;
background: #a855f7;
border-radius: 2px;
height: 8px;
transition: height 0.1s ease, background-color 0.2s ease;
}
.comfy-sidebar-audio-wrapper.playing .comfy-sidebar-soundwave-bar {
background: #c084fc;
animation: comfySidebarWave 1s ease-in-out infinite alternate;
}
@keyframes comfySidebarWave {
0% { transform: scaleY(0.4); }
100% { transform: scaleY(1.3); }
}
/* Text Output Card Clamping */
.comfy-sidebar-text-clamp {
font-size: 11px;
line-height: 1.45;
color: #cbd5e1;
max-height: 84px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
cursor: pointer;
padding: 8px 10px;
background: rgba(255, 255, 255, 0.04);
border-radius: 4px;
border: 1px solid rgba(255, 255, 255, 0.08);
margin-top: 18px;
word-break: break-word;
transition: all 0.15s ease-in-out;
}
.comfy-sidebar-text-clamp:hover {
border-color: #3b82f6;
background: rgba(59, 130, 246, 0.08);
}
`;
document.head.appendChild(style);
}
-1457
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
import { isAudioViewerOpen as checkAudioViewerOpen } from "../utils/comparison.js";
let currentlyPlayingAudio = null;
export function stopAllAudioPlayback() {
if (currentlyPlayingAudio) {
currentlyPlayingAudio.pause();
currentlyPlayingAudio.currentTime = 0;
if (typeof currentlyPlayingAudio._onResetUI === "function") {
currentlyPlayingAudio._onResetUI();
}
currentlyPlayingAudio = null;
}
}
export function setCurrentlyPlayingAudio(audio) {
stopAllAudioPlayback();
currentlyPlayingAudio = audio;
}
export function getCurrentlyPlayingAudio() {
return currentlyPlayingAudio;
}
export function isAudioViewerOpen() {
return checkAudioViewerOpen();
}
+677
View File
@@ -0,0 +1,677 @@
import { app } from "/scripts/app.js";
import { PromptStatus } from "../core/constants.js";
import { t } from "../core/i18n.js";
import { store } from "../core/store.js";
import { renderCardImages } from "./mediaPreview.js";
import { copyImageToClipboard, openFileOrFolder, deleteFileOnServer, findNodeIdForImage, removeImageFromNodeOutputs } from "./mediaActions.js";
import { centerAndSelectCanvasNode } from "../comfy/adapter.js";
import { getRunOutputs, extractWorkflowFromPng, isImageFormat, animateCardRemoval, downloadJson, getScrollContainer, attachDeleteConfirmation } from "../utils/utils.js";
import { showFullscreenPreview } from "../utils/comparison.js";
import { stopAllAudioPlayback } from "./audioController.js";
import { deleteHistoryItem, cancelPendingTask, interruptActive } from "../queue/queueService.js";
import { showNotification } from "../utils/nodeRenumber.js";
export const cardPool = new Map();
export function resetAllCardHoverStates() {
for (const cardObj of cardPool.values()) {
if (cardObj.hoverPanel) cardObj.hoverPanel.style.display = "none";
if (cardObj.leftHoverPanel) cardObj.leftHoverPanel.style.display = "none";
}
}
export function syncCardButtonVisibility(cardObj, state) {
if (!cardObj) return;
const isPendingOrActive = state.status === PromptStatus.PENDING || state.status === PromptStatus.ACTIVE;
if (isPendingOrActive) {
if (cardObj.hoverPanel) cardObj.hoverPanel.style.setProperty("display", "none", "important");
if (cardObj.leftHoverPanel) cardObj.leftHoverPanel.style.setProperty("display", "none", "important");
return;
} else {
if (cardObj.hoverPanel) cardObj.hoverPanel.style.removeProperty("display");
if (cardObj.leftHoverPanel) cardObj.leftHoverPanel.style.removeProperty("display");
}
const randParam = state?.pid ? `&rand=${encodeURIComponent(state.pid)}` : "";
// Check if the card has an actual verified file saved on disk
const hasRealDiskFiles = state.images && state.images.length > 0 &&
state.images.some(img => img.filename && !img.isFallback && (!img.url || !img.url.startsWith("blob:")));
const hasRealImages = hasRealDiskFiles && !state.images.some(img => img.url && img.url.startsWith("blob:"));
const currentImg = hasRealImages ? state.images[cardObj.currentImageIndex || 0] : null;
const isPng = currentImg && (currentImg.filename || "").toLowerCase().endsWith(".png");
if (cardObj.btnImg) {
if (hasRealImages) {
cardObj.btnImg.style.removeProperty("display");
cardObj.btnImg.style.display = "inline-flex";
cardObj.btnImg.onclick = (ev) => {
ev.stopPropagation();
state.images.forEach(img => {
const a = document.createElement("a");
a.href = img.url ? img.url : `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
a.download = img.filename || "output";
a.click();
});
};
} else {
cardObj.btnImg.style.setProperty("display", "none", "important");
}
}
if (cardObj.btnCopy) {
const isCopyableImage = hasRealImages && currentImg && isImageFormat(currentImg.filename || currentImg.url);
if (isCopyableImage) {
cardObj.btnCopy.style.removeProperty("display");
cardObj.btnCopy.style.display = "inline-flex";
cardObj.btnCopy.onclick = async (ev) => {
ev.stopPropagation();
const src = currentImg.url ? currentImg.url : `/view?filename=${encodeURIComponent(currentImg.filename)}&type=${currentImg.type || 'output'}&subfolder=${encodeURIComponent(currentImg.subfolder || '')}${randParam}`;
const success = await copyImageToClipboard(src);
if (success) {
cardObj.btnCopy.className = "pi pi-check comfy-sidebar-card-action-btn";
cardObj.btnCopy.style.color = "#4ade80";
setTimeout(() => {
cardObj.btnCopy.className = "pi pi-copy comfy-sidebar-card-action-btn";
cardObj.btnCopy.style.color = "";
}, 1500);
}
};
} else {
cardObj.btnCopy.style.setProperty("display", "none", "important");
}
}
if (cardObj.btnJson) {
if (state.workflow || isPng) {
cardObj.btnJson.style.removeProperty("display");
cardObj.btnJson.style.display = "inline-flex";
cardObj.btnJson.onclick = async (ev) => {
ev.stopPropagation();
let wf = state.workflow;
if (!wf && currentImg) {
const src = currentImg.url ? currentImg.url : `/view?filename=${encodeURIComponent(currentImg.filename)}&type=${currentImg.type || 'output'}&subfolder=${encodeURIComponent(currentImg.subfolder || '')}${randParam}`;
wf = await extractWorkflowFromPng(src);
if (wf) state.workflow = wf;
}
if (!wf) {
alert(t("No workflow metadata found in this file."));
return;
}
downloadJson(wf, `workflow_${state.pid || "comfy"}.json`);
};
} else {
cardObj.btnJson.style.setProperty("display", "none", "important");
}
}
if (cardObj.btnDel) {
cardObj.btnDel.style.removeProperty("display");
cardObj.btnDel.style.display = "inline-flex";
cardObj.canDeleteFromDisk = hasRealDiskFiles;
if (cardObj.btnDelLabel) {
cardObj.btnDelLabel.style.display = hasRealDiskFiles ? "" : "none";
}
cardObj.btnDel.title = hasRealDiskFiles
? t("Delete Card (Hold Ctrl to delete file from disk)")
: t("Delete Card");
}
if (cardObj.btnFocus) {
const nodeId = (currentImg ? findNodeIdForImage(state, currentImg) : null) || state.activeNodeId;
if (nodeId) {
cardObj.btnFocus.style.removeProperty("display");
cardObj.btnFocus.style.display = "inline-flex";
cardObj.btnFocus.title = (!currentImg && state.activeNodeId) ? t("Show Stopped/Failed Node") : t("Show Node");
cardObj.btnFocus.onclick = (ev) => {
ev.stopPropagation();
centerAndSelectCanvasNode(nodeId);
};
} else {
cardObj.btnFocus.style.setProperty("display", "none", "important");
}
}
if (cardObj.leftHoverBtn) {
const outputs = getRunOutputs(state.nodeOutputs, state.workflow);
const validOutputs = outputs
.map(o => ({
...o,
images: (o.images || []).filter(img => img && img.filename && !img.isFallback)
}))
.filter(o => o.images.length > 0);
const primarySignatures = new Set((state.images || []).map(i => `${i.subfolder || ""}/${i.filename}`));
const distinctOutputs = [];
for (const out of validOutputs) {
const distinctImages = out.images.filter(img => !primarySignatures.has(`${img.subfolder || ""}/${img.filename}`));
if (distinctImages.length > 0) {
distinctOutputs.push({ ...out, images: distinctImages });
}
}
const hasIntermediates = (validOutputs.length > 1 && distinctOutputs.length > 0) ||
(state.status !== PromptStatus.COMPLETED && validOutputs.length > 0);
if (!hasIntermediates) {
cardObj.leftHoverBtn.style.setProperty("display", "none", "important");
} else {
// If already verified (or freshly generated), display button immediately
if (state._hasValidatedIntermediates) {
cardObj.leftHoverBtn.style.removeProperty("display");
cardObj.leftHoverBtn.style.display = "inline-flex";
} else {
// Old restored card: keep hidden by default while stealthily testing files
cardObj.leftHoverBtn.style.setProperty("display", "none", "important");
if (!cardObj._isCheckingIntermediates) {
cardObj._isCheckingIntermediates = true;
const checkPromises = [];
const missingImages = [];
for (const out of distinctOutputs) {
for (const img of out.images) {
if (!img.filename || (img.url && img.url.startsWith("blob:"))) continue;
const src = img.url ? img.url : `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
checkPromises.push(
fetch(src, { method: "HEAD" })
.then(res => {
if (res.status === 404) {
missingImages.push(img);
}
})
.catch(() => {
missingImages.push(img);
})
);
}
}
const finalizeCheck = () => {
cardObj._isCheckingIntermediates = false;
const liveState = store.getPrompt(state.pid) || state;
liveState._hasValidatedIntermediates = true;
if (missingImages.length > 0 && liveState && liveState.nodeOutputs) {
for (const img of missingImages) {
removeImageFromNodeOutputs(liveState.nodeOutputs, img);
}
for (const nodeId in liveState.nodeOutputs) {
const nodeVal = liveState.nodeOutputs[nodeId];
if (nodeVal && typeof nodeVal === "object") {
const hasAny = Object.values(nodeVal).some(v => Array.isArray(v) ? v.length > 0 : Boolean(v));
if (!hasAny) {
delete liveState.nodeOutputs[nodeId];
}
}
}
store.updatePrompt(liveState.pid, liveState);
}
const curOutputs = getRunOutputs(liveState.nodeOutputs, liveState.workflow);
const curValid = curOutputs
.map(o => ({
...o,
images: (o.images || []).filter(i => i && i.filename && !i.isFallback)
}))
.filter(o => o.images.length > 0);
const curDistinct = curValid.filter(o => o.images.some(i => !primarySignatures.has(`${i.subfolder || ""}/${i.filename}`)));
const stillHas = (curValid.length > 1 && curDistinct.length > 0) ||
(liveState.status !== PromptStatus.COMPLETED && curValid.length > 0);
if (stillHas) {
cardObj.leftHoverBtn.style.removeProperty("display");
cardObj.leftHoverBtn.style.display = "inline-flex";
} else {
cardObj.leftHoverBtn.style.setProperty("display", "none", "important");
}
};
if (checkPromises.length > 0) {
Promise.all(checkPromises).then(finalizeCheck).catch(finalizeCheck);
} else {
finalizeCheck();
}
}
}
cardObj.leftHoverBtn.onclick = async (ev) => {
ev.stopPropagation();
const liveState = store.getPrompt(state.pid) || state;
const curOutputs = getRunOutputs(liveState.nodeOutputs, liveState.workflow);
const curValid = curOutputs
.map(o => ({
...o,
images: (o.images || []).filter(i => i && i.filename && !i.isFallback)
}))
.filter(o => o.images.length > 0);
const primSigs = new Set((liveState.images || []).map(i => `${i.subfolder || ""}/${i.filename}`));
const curDistinct = curValid.filter(o => o.images.some(img => !primSigs.has(`${img.subfolder || ""}/${img.filename}`)));
if (curDistinct.length === 0) {
cardObj.leftHoverBtn.style.setProperty("display", "none", "important");
return;
}
let anyMissing = false;
for (const out of curDistinct) {
for (const img of out.images) {
if (primSigs.has(`${img.subfolder || ""}/${img.filename}`)) continue;
const src = img.url ? img.url : `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
if (!src.startsWith("blob:")) {
try {
const res = await fetch(src, { method: "HEAD" });
if (res.status === 404) {
removeImageFromNodeOutputs(liveState.nodeOutputs, img);
anyMissing = true;
}
} catch (e) {}
}
}
}
if (anyMissing) {
for (const nodeId in liveState.nodeOutputs) {
const nodeVal = liveState.nodeOutputs[nodeId];
if (nodeVal && typeof nodeVal === "object") {
const hasAny = Object.values(nodeVal).some(v => Array.isArray(v) ? v.length > 0 : Boolean(v));
if (!hasAny) {
delete liveState.nodeOutputs[nodeId];
}
}
}
store.updatePrompt(liveState.pid, liveState);
syncCardButtonVisibility(cardObj, liveState);
const remainingOutputs = getRunOutputs(liveState.nodeOutputs, liveState.workflow);
const remaining = remainingOutputs
.map(o => ({ ...o, images: (o.images || []).filter(i => i && i.filename && !i.isFallback) }))
.filter(o => o.images.some(img => !primSigs.has(`${img.subfolder || ""}/${img.filename}`)));
if (remaining.length === 0) {
return;
}
}
const scrollEl = getScrollContainer(store.ui.cardStack);
if (scrollEl) {
store.ui.mainQueueScrollTop = scrollEl.scrollTop;
}
store.openOutputsSubmenu(liveState.pid);
};
}
}
}
export function updateCardProgressTargeted(cardObj, progress, activeNodeName, showWorkingNode = true, state = null) {
if (!cardObj) return;
if (cardObj.progressBar) {
cardObj.progressBar.style.width = `${progress}%`;
}
if (cardObj.statusText && showWorkingNode) {
cardObj.statusText.style.display = "block";
const nodeText = activeNodeName ? (activeNodeName === "Finishing..." ? t("Finishing...") : `[${activeNodeName}]`) : t("Processing...");
cardObj.statusText.textContent = `${nodeText} ${progress}%`;
}
if (state && state.images && state.images.length > 0) {
const firstImg = state.images[0];
const randParam = state?.pid ? `&rand=${encodeURIComponent(state.pid)}` : "";
const previewUrl = firstImg.url || (firstImg.filename ? `/view?filename=${encodeURIComponent(firstImg.filename)}&type=${firstImg.type || 'output'}&subfolder=${encodeURIComponent(firstImg.subfolder || '')}${randParam}` : null);
if (previewUrl && cardObj.firstImgElement && cardObj.firstImgElement.tagName === "IMG") {
const currentSrc = cardObj.firstImgElement.getAttribute("src") || cardObj.firstImgElement.src;
if (currentSrc !== previewUrl && !cardObj.firstImgElement.src.endsWith(previewUrl)) {
cardObj.firstImgElement.src = previewUrl;
}
} else {
updateCardDOM(cardObj, state, true, showWorkingNode);
}
}
}
export function getOrCreateCard(state, callbacks = {}) {
let cardObj = cardPool.get(state.pid);
if (cardObj) return cardObj;
const card = document.createElement("div");
card.id = `card-${state.pid}`;
card.className = `comfy-sidebar-card ${state.status || "completed"}`;
card.style.position = "relative";
const timerEl = document.createElement("div");
timerEl.className = "comfy-sidebar-card-timer";
const cancelX = document.createElement("span");
cancelX.className = "pi pi-times comfy-sidebar-queue-cancel-btn";
Object.assign(cancelX.style, {
position: "absolute", top: "4px", right: "4px", display: "none", zIndex: "25"
});
const sBadge = document.createElement("div");
sBadge.className = "comfy-sidebar-status-badge";
Object.assign(sBadge.style, {
position: "absolute", top: "6px", right: "8px", fontSize: "10px", fontWeight: "bold",
padding: "3px 7px", borderRadius: "3px", textTransform: "uppercase", display: "none",
pointerEvents: "none", zIndex: "30", letterSpacing: "0.5px", boxShadow: "0 2px 6px rgba(0,0,0,0.6)"
});
const dimEl = document.createElement("div");
Object.assign(dimEl.style, {
position: "absolute", top: "6px", right: "8px", fontSize: "10px",
fontFamily: "monospace", opacity: "0.7", background: "rgba(0, 0, 0, 0.6)",
padding: "2px 4px", borderRadius: "3px", pointerEvents: "none", zIndex: "5", color: "#fff",
display: "none", transform: "translateZ(0)"
});
const grid = document.createElement("div");
grid.style.display = "flex";
grid.style.flexDirection = "column";
grid.style.gap = "6px";
const p = document.createElement("div");
p.className = "comfy-sidebar-text-clamp";
const pt = document.createElement("div");
Object.assign(pt.style, {
width: "100%", height: "4px", background: "var(--border, #333)", borderRadius: "2px", marginTop: "8px",
overflow: "hidden", display: "none"
});
const pb = document.createElement("div");
Object.assign(pb.style, {
width: "0%", height: "100%", background: "var(--primary, var(--p-primary-color, #ea580c))", transition: "width 0.1s linear"
});
pt.appendChild(pb);
const statusText = document.createElement("div");
Object.assign(statusText.style, {
fontSize: "11px", opacity: "0.9", color: "var(--primary, var(--p-primary-color, #ea580c))", textAlign: "center", marginTop: "6px",
display: "none", fontWeight: "bold"
});
const hoverPanel = document.createElement("div");
hoverPanel.className = "comfy-sidebar-hover-panel";
Object.assign(hoverPanel.style, {
position: "absolute", bottom: "4px", right: "4px", flexDirection: "column", gap: "4px", zIndex: "20"
});
const btnImg = document.createElement("span");
btnImg.className = "pi pi-image comfy-sidebar-card-action-btn";
btnImg.title = t("Download Object");
const btnCopy = document.createElement("span");
btnCopy.className = "pi pi-copy comfy-sidebar-card-action-btn";
btnCopy.title = t("Copy to Clipboard");
btnCopy.style.display = "none";
const btnJson = document.createElement("span");
btnJson.className = "pi pi-file comfy-sidebar-card-action-btn";
btnJson.title = t("Download JSON");
const btnDel = document.createElement("span");
btnDel.className = "pi pi-trash comfy-sidebar-card-action-btn comfy-sidebar-btn-del";
btnDel.title = t("Delete Card (Hold Ctrl to delete file from disk)");
const btnDelLabel = document.createElement("span");
btnDelLabel.className = "comfy-sidebar-del-label";
btnDelLabel.textContent = t("Delete File");
btnDel.appendChild(btnDelLabel);
const leftHoverPanel = document.createElement("div");
leftHoverPanel.className = "comfy-sidebar-left-hover-panel";
Object.assign(leftHoverPanel.style, {
position: "absolute", bottom: "4px", left: "4px", flexDirection: "column", gap: "4px", zIndex: "20"
});
const btnFocus = document.createElement("span");
btnFocus.className = "pi pi-eye comfy-sidebar-card-action-btn";
btnFocus.title = t("Show Node");
const leftHoverBtn = document.createElement("span");
leftHoverBtn.className = "pi pi-images comfy-sidebar-card-action-btn";
leftHoverBtn.title = t("View all intermediate outputs");
hoverPanel.append(btnImg, btnJson, btnDel);
leftHoverPanel.append(btnCopy, btnFocus, leftHoverBtn);
// Appending grid FIRST ensures overlays (badges, cancel button) naturally render on top
card.append(grid, p, pt, statusText, timerEl, cancelX, dimEl, sBadge, hoverPanel, leftHoverPanel);
cardObj = {
element: card,
timerEl,
statusBadge: sBadge,
dimEl,
grid,
placeholder: p,
progressContainer: pt,
progressBar: pb,
cancelBtn: cancelX,
hoverPanel,
leftHoverPanel,
btnFocus,
leftHoverBtn,
btnImg,
btnCopy,
btnJson,
btnDel,
btnDelLabel,
canDeleteFromDisk: true,
statusText,
firstImgElement: null,
lastImagesSignature: "",
currentImageIndex: 0,
_isCheckingIntermediates: false
};
card.addEventListener("mouseenter", () => {
if (store.hasPrompt(state.pid)) {
const liveState = store.getPrompt(state.pid);
syncCardButtonVisibility(cardObj, liveState);
}
});
card.addEventListener("dragstart", (e) => {
const liveState = store.getPrompt(state.pid) || state;
const isUnfinished = liveState.status && liveState.status !== PromptStatus.COMPLETED;
const hasNoImages = !liveState.images || liveState.images.length === 0;
if (liveState.workflow && (hasNoImages || isUnfinished)) {
if (cardObj.firstImgElement) {
try { e.dataTransfer.setDragImage(cardObj.firstImgElement, 15, 15); } catch(err){}
}
const jsonStr = JSON.stringify(liveState.workflow, null, 2);
const filename = `workflow_${liveState.pid}.json`;
const base64Data = btoa(unescape(encodeURIComponent(jsonStr)));
try {
e.dataTransfer.setData("DownloadURL", `application/json:${filename}:data:application/json;base64,${base64Data}`);
e.dataTransfer.setData("application/json", jsonStr);
} catch (err) {}
e.dataTransfer.effectAllowed = "copy";
}
});
attachDeleteConfirmation(btnDel, {
canDiskDelete: () => cardObj.canDeleteFromDisk !== false,
idleTitle: () => cardObj.canDeleteFromDisk ? t("Delete Card (Hold Ctrl to delete file from disk)") : t("Delete Card"),
confirmTitle: t("Click again to confirm removing card"),
confirmDiskTitle: t("Ctrl+Click again to delete file from DISK / TRASH"),
onConfirm: async (shouldDeleteFromDisk) => {
animateCardRemoval(card, async () => {
const liveState = store.getPrompt(state.pid) || state;
if (shouldDeleteFromDisk) {
const filesToDelete = [];
const seen = new Set();
const addFile = (item) => {
if (item && item.filename) {
const key = `${item.type || ""}/${item.subfolder || ""}/${item.filename}`;
if (!seen.has(key)) {
seen.add(key);
filesToDelete.push(item);
}
}
};
(liveState.images || []).forEach(addFile);
const allOutputs = getRunOutputs(liveState.nodeOutputs, liveState.workflow);
allOutputs.forEach(out => (out.images || []).forEach(addFile));
let deletedCount = 0;
let lastAction = "trashed";
for (const fileItem of filesToDelete) {
const action = await deleteFileOnServer(fileItem);
if (action) {
deletedCount++;
lastAction = action;
}
}
if (deletedCount > 0) {
const msg = lastAction === "trashed"
? `Moved ${deletedCount} file${deletedCount > 1 ? "s" : ""} to Recycle Bin.`
: `Permanently deleted ${deletedCount} file${deletedCount > 1 ? "s" : ""}.`;
showNotification(msg, "success", "Delete Files");
}
}
deleteHistoryItem(state.pid);
});
}
});
cardPool.set(state.pid, cardObj);
return cardObj;
}
export function updateCardDOM(cardObj, state, showPendingSummary = true, showWorkingNode = true) {
cardObj.element.className = `comfy-sidebar-card ${state.status}`;
cardObj.element.style.position = "relative";
const isUnfinished = state.status && state.status !== PromptStatus.COMPLETED;
if (state.images && state.images.length > 0 && !isUnfinished) {
cardObj.element.removeAttribute("draggable");
} else {
cardObj.element.setAttribute("draggable", "true");
}
if (state.status === PromptStatus.ACTIVE) {
cardObj.timerEl.textContent = state.startTime ? ((Date.now() - state.startTime) / 1000).toFixed(2) + "s" : "...";
cardObj.timerEl.style.display = "block";
} else if (state.duration !== undefined && state.duration !== null) {
cardObj.timerEl.textContent = state.duration.toFixed(2) + "s";
cardObj.timerEl.style.display = "block";
} else {
cardObj.timerEl.style.display = "none";
}
if (state.status === PromptStatus.CANCELLED) {
Object.assign(cardObj.statusBadge.style, {
display: "block",
background: "#eab308",
color: "#000",
zIndex: "30"
});
cardObj.statusBadge.textContent = t("Cancelled");
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
} else if (state.status === PromptStatus.ERROR) {
Object.assign(cardObj.statusBadge.style, {
display: "block",
background: "#dc3545",
color: "#fff",
zIndex: "30"
});
cardObj.statusBadge.textContent = t("Error");
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
} else {
cardObj.statusBadge.style.display = "none";
}
if (state.status === PromptStatus.PENDING && !showPendingSummary) {
cardObj.cancelBtn.style.display = "flex";
cardObj.cancelBtn.title = t("Cancel Queued Task");
cardObj.cancelBtn.onclick = async (ev) => {
ev.stopPropagation();
cancelPendingTask(state.pid);
};
} else if (state.status === PromptStatus.ACTIVE) {
cardObj.cancelBtn.style.display = "flex";
cardObj.cancelBtn.title = t("Interrupt Execution");
cardObj.cancelBtn.onclick = async (ev) => {
ev.stopPropagation();
interruptActive();
};
} else {
cardObj.cancelBtn.style.display = "none";
}
const currentImagesSignature = `${state.status || ""}:${state.images ? state.images.map(img => img.url || img.filename).join("|") : ""}`;
if (cardObj.lastImagesSignature !== currentImagesSignature) {
if (!state.images || state.images.length === 0) {
cardObj.grid.innerHTML = "";
cardObj.firstImgElement = null;
cardObj.placeholder.style.display = "block";
} else {
cardObj.placeholder.style.display = "none";
renderCardImages(cardObj, state, (st) => {
const scrollEl = getScrollContainer(store.ui.cardStack);
if (scrollEl) {
store.ui.mainQueueScrollTop = scrollEl.scrollTop;
}
store.openBatchSubmenu({
pid: st.pid,
images: st.images,
workflow: st.workflow,
nodeOutputs: st.nodeOutputs
});
});
}
cardObj.lastImagesSignature = currentImagesSignature;
}
if (state.images.length === 0) {
if (state.texts && state.texts.length > 0) {
const fullText = state.texts.join("\n\n");
cardObj.placeholder.textContent = fullText;
cardObj.placeholder.title = t("Click to read full text");
cardObj.placeholder.className = "comfy-sidebar-text-clamp";
cardObj.placeholder.style.cssText = "";
cardObj.placeholder.style.display = "-webkit-box";
cardObj.placeholder.onclick = (e) => {
e.stopPropagation();
stopAllAudioPlayback();
showFullscreenPreview([{ text: fullText, pid: state.pid }], false, state.pid);
};
} else {
cardObj.placeholder.textContent = state.progressText || t("No Outputs");
cardObj.placeholder.className = "";
Object.assign(cardObj.placeholder.style, {
fontSize: "11px", opacity: "0.5", textAlign: "center", padding: "12px", marginTop: "12px",
userSelect: "none", whiteSpace: "normal", maxHeight: "none", display: "block", cursor: "default"
});
cardObj.placeholder.onclick = null;
}
}
if (state.status === PromptStatus.ACTIVE) {
if (showWorkingNode) {
cardObj.statusText.style.display = "block";
const nodeText = state.activeNodeName ? (state.activeNodeName === "Finishing..." ? t("Finishing...") : `[${state.activeNodeName}]`) : t("Processing...");
cardObj.statusText.textContent = `${nodeText}${state.progress ? ` ${state.progress}%` : ""}`;
} else {
cardObj.statusText.style.display = "none";
}
cardObj.progressContainer.style.display = "block";
cardObj.progressBar.style.width = `${state.progress || 0}%`;
} else {
cardObj.statusText.style.display = "none";
cardObj.progressContainer.style.display = "none";
}
syncCardButtonVisibility(cardObj, state);
return cardObj.element;
}
+695
View File
@@ -0,0 +1,695 @@
import { app } from "/scripts/app.js";
import { SettingIds, PromptStatus } from "../core/constants.js";
import { t } from "../core/i18n.js";
import { deleteFileOnServer, openFileOrFolder } from "./mediaActions.js";
import { extractWorkflowFromPng, isImageFormat, animateCardRemoval, getScrollContainer, calculateGridColumns, downloadJson, setupSpotlightTracker, attachDeleteConfirmation } from "../utils/utils.js";
import { getSetting } from "../core/settings.js";
import { renderCardImages } from "./mediaPreview.js";
import { showNotification } from "../utils/nodeRenumber.js";
let galleryContainerEl = null;
let cardStackEl = null;
let scrollToTopBtnEl = null;
let currentColumnCount = 1;
let currentSubfolder = "";
let currentSearchQuery = "";
let stickyHeaderGroupEl = null;
let lastScrollTop = 0;
let scrollDeltaAccumulator = 0;
let isHeaderHidden = false;
// Persistent sort order
let sortOrder = "newest";
try {
sortOrder = localStorage.getItem("ComfySidebar.GallerySortOrder") || "newest";
} catch (e) {}
let cachedFolders = [];
let cachedFiles = [];
let displayedFilesCount = 0;
const BATCH_SIZE = 36;
let isLoading = false;
function formatFileSize(bytes) {
if (!bytes || bytes <= 0) return "";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}
function updateScrollTopVisibility() {
if (!galleryContainerEl || !galleryContainerEl.isConnected) {
if (scrollToTopBtnEl) scrollToTopBtnEl.style.display = "none";
return;
}
const scrollEl = getScrollContainer(cardStackEl);
if (scrollEl) {
if (scrollToTopBtnEl) {
scrollToTopBtnEl.style.display = scrollEl.scrollTop > 200 ? "flex" : "none";
}
// Handle smart scroll-up reveal for header & navigation
handleHeaderScroll(scrollEl);
if (scrollEl.scrollTop + scrollEl.clientHeight >= scrollEl.scrollHeight - 300) {
loadNextBatch();
}
}
}
function handleHeaderScroll(scrollEl) {
if (!stickyHeaderGroupEl) return;
// Never hide header if search bar is currently active
const searchContainer = stickyHeaderGroupEl.querySelector(".comfy-sidebar-search-container");
if (currentSearchQuery || (searchContainer && searchContainer.style.display !== "none")) {
stickyHeaderGroupEl.style.transform = "translateY(0)";
isHeaderHidden = false;
return;
}
const currentScroll = scrollEl.scrollTop;
const delta = currentScroll - lastScrollTop;
lastScrollTop = currentScroll;
// Near the very top: always keep visible & transparent
if (currentScroll <= 35) {
stickyHeaderGroupEl.classList.remove("is-scrolled");
if (isHeaderHidden) {
stickyHeaderGroupEl.style.transform = "translateY(0)";
isHeaderHidden = false;
}
scrollDeltaAccumulator = 0;
return;
}
stickyHeaderGroupEl.classList.add("is-scrolled");
if (delta > 0) {
// Scrolling DOWN: hide after small buffer
if (scrollDeltaAccumulator < 0) scrollDeltaAccumulator = 0;
scrollDeltaAccumulator += delta;
if (scrollDeltaAccumulator > 25 && !isHeaderHidden) {
stickyHeaderGroupEl.style.transform = "translateY(-100%)";
isHeaderHidden = true;
}
} else if (delta < 0) {
// Scrolling UP: reveal as soon as user scrolls up a little bit (~15px)
if (scrollDeltaAccumulator > 0) scrollDeltaAccumulator = 0;
scrollDeltaAccumulator += delta;
if (scrollDeltaAccumulator < -15 && isHeaderHidden) {
stickyHeaderGroupEl.style.transform = "translateY(0)";
isHeaderHidden = false;
}
}
}
async function fetchGalleryData(subfolder = "", searchQuery = "") {
try {
isLoading = true;
const normalized = subfolder.replace(/\\/g, "/");
const queryParams = new URLSearchParams({ subfolder: normalized });
if (searchQuery) queryParams.set("search", searchQuery);
const res = await fetch(`/comfy-sidebar/gallery/list?${queryParams.toString()}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
cachedFolders = data.folders || [];
cachedFiles = data.files || [];
currentSubfolder = (data.subfolder || "").replace(/\\/g, "/");
applySorting();
displayedFilesCount = 0;
} catch (e) {
console.error("[ComfySidebar] Failed to load gallery", e);
showNotification(t("Failed to load gallery from disk."), "error");
} finally {
isLoading = false;
}
}
function applySorting() {
if (sortOrder === "newest") {
cachedFiles.sort((a, b) => b.mtime - a.mtime);
} else {
cachedFiles.sort((a, b) => a.mtime - b.mtime);
}
}
function mountGalleryCards(cardStack, folderWrapperEl, cardEls, cols = 1, append = false) {
if (!cardStack) return;
const oldEmpty = cardStack.querySelector(".comfy-sidebar-gallery-empty-notice");
if (oldEmpty) oldEmpty.remove();
if (!append) {
let subfolderArea = cardStack.querySelector(".comfy-sidebar-subfolders-area");
if (!subfolderArea) {
subfolderArea = document.createElement("div");
subfolderArea.className = "comfy-sidebar-subfolders-area";
cardStack.insertBefore(subfolderArea, cardStack.firstChild);
}
subfolderArea.innerHTML = "";
if (folderWrapperEl) {
subfolderArea.appendChild(folderWrapperEl);
subfolderArea.style.display = "block";
} else {
subfolderArea.style.display = "none";
}
}
let columnsWrapper = cardStack.querySelector(".comfy-sidebar-masonry-wrapper");
if (!columnsWrapper) {
columnsWrapper = document.createElement("div");
columnsWrapper.className = "comfy-sidebar-masonry-wrapper";
Object.assign(columnsWrapper.style, { display: "flex", gap: "12px", alignItems: "flex-start", width: "100%" });
cardStack.appendChild(columnsWrapper);
}
if (!append && cardEls.length === 0 && !folderWrapperEl) {
columnsWrapper.innerHTML = "";
const emptyEl = document.createElement("div");
emptyEl.className = "comfy-sidebar-card comfy-sidebar-gallery-empty-notice";
Object.assign(emptyEl.style, {
padding: "24px", textAlign: "center", color: "var(--desc-color, #888)", fontSize: "12px", width: "100%"
});
emptyEl.textContent = isLoading ? t("Loading files...") : t("No files found in this folder.");
cardStack.appendChild(emptyEl);
return;
}
while (columnsWrapper.children.length < cols) {
const colDiv = document.createElement("div");
colDiv.className = "comfy-sidebar-masonry-col";
Object.assign(colDiv.style, { flex: "1", display: "flex", flexDirection: "column", gap: "12px", minWidth: "0" });
columnsWrapper.appendChild(colDiv);
}
while (columnsWrapper.children.length > cols) {
columnsWrapper.removeChild(columnsWrapper.lastChild);
}
const colHeights = Array.from(columnsWrapper.children).map(c => c.scrollHeight || 0);
cardEls.forEach((cardEl) => {
let shortestCol = 0;
for (let c = 1; c < cols; c++) {
if (colHeights[c] < colHeights[shortestCol]) shortestCol = c;
}
columnsWrapper.children[shortestCol].appendChild(cardEl);
const cardH = cardEl.offsetHeight > 0 ? cardEl.offsetHeight : 160;
colHeights[shortestCol] += cardH + 12;
});
}
function createFileCard(file) {
const card = document.createElement("div");
card.className = "comfy-sidebar-card completed";
card.style.position = "relative";
card.style.cursor = "pointer";
const previewUrl = `/view?filename=${encodeURIComponent(file.filename)}&type=output&subfolder=${encodeURIComponent(file.subfolder || "")}`;
const isPng = file.filename.toLowerCase().endsWith(".png");
const grid = document.createElement("div");
grid.style.display = "flex";
grid.style.flexDirection = "column";
grid.style.width = "100%";
const cardObj = {
element: card,
grid: grid,
dimEl: null,
currentImageIndex: 0,
firstImgElement: null
};
const fileAsset = {
filename: file.filename,
subfolder: file.subfolder,
type: "output",
url: previewUrl
};
// Render using Queue's exact media pipeline (Images, Videos, 3D, Audio, Files)
renderCardImages(cardObj, {
pid: `gallery-${file.filename}`,
status: PromptStatus.COMPLETED,
images: [fileAsset],
workflow: null
});
const sizeBadge = document.createElement("div");
sizeBadge.className = "comfy-sidebar-card-timer";
sizeBadge.textContent = formatFileSize(file.size);
sizeBadge.style.display = file.size ? "block" : "none";
const isMedia = isImageFormat(file.filename) || /\.(mp4|webm|mov|mkv|avi)$/i.test(file.filename);
let nameBadge = null;
if (isMedia) {
nameBadge = document.createElement("div");
nameBadge.className = "comfy-sidebar-card-filename-badge";
nameBadge.textContent = file.filename;
nameBadge.title = file.filename;
}
const hoverPanel = document.createElement("div");
hoverPanel.className = "comfy-sidebar-hover-panel";
Object.assign(hoverPanel.style, {
position: "absolute", bottom: "4px", right: "4px", flexDirection: "column", gap: "4px", zIndex: "20"
});
const btnDownload = document.createElement("span");
btnDownload.className = "pi pi-download comfy-sidebar-card-action-btn";
btnDownload.title = t("Download Object");
btnDownload.onclick = (ev) => {
ev.stopPropagation();
const a = document.createElement("a");
a.href = previewUrl;
a.download = file.filename;
a.click();
};
let btnJson = null;
if (isPng) {
btnJson = document.createElement("span");
btnJson.className = "pi pi-file comfy-sidebar-card-action-btn";
btnJson.title = t("Download JSON");
btnJson.onclick = async (ev) => {
ev.stopPropagation();
const wf = await extractWorkflowFromPng(previewUrl);
if (!wf) {
alert(t("No workflow metadata found in this file."));
return;
}
downloadJson(wf, `workflow_${file.filename.replace(/\.[^/.]+$/, "")}.json`);
};
}
const btnDel = document.createElement("span");
btnDel.className = "pi pi-trash comfy-sidebar-card-action-btn comfy-sidebar-btn-del comfy-sidebar-gallery-btn-del";
const btnDelLabel = document.createElement("span");
btnDelLabel.className = "comfy-sidebar-del-label";
btnDelLabel.textContent = t("Delete File");
btnDel.appendChild(btnDelLabel);
attachDeleteConfirmation(btnDel, {
idleTitle: t("Delete file (Hold Ctrl to delete file from disk)"),
confirmTitle: t("Click again to confirm deleting file"),
confirmDiskTitle: t("Ctrl+Click again to delete file from DISK / TRASH"),
onConfirm: async () => {
const action = await deleteFileOnServer(fileAsset);
if (action) {
const msg = action === "trashed" ? t("Moved file to Recycle Bin.") : t("Permanently deleted file.");
showNotification(msg, "success", t("Delete File"));
cachedFiles = cachedFiles.filter(f => f.filename !== file.filename || f.subfolder !== file.subfolder);
displayedFilesCount = Math.max(0, displayedFilesCount - 1);
animateCardRemoval(card, () => {
card.remove();
if (cachedFiles.length === 0) {
renderGallery();
}
});
}
}
});
hoverPanel.appendChild(btnDownload);
if (btnJson) hoverPanel.appendChild(btnJson);
hoverPanel.appendChild(btnDel);
const leftHoverPanel = document.createElement("div");
leftHoverPanel.className = "comfy-sidebar-left-hover-panel";
Object.assign(leftHoverPanel.style, {
position: "absolute", bottom: "4px", left: "4px", flexDirection: "column", gap: "4px", zIndex: "20"
});
const isImage = isImageFormat(file.filename);
const btnCopy = document.createElement("span");
btnCopy.className = "pi pi-copy comfy-sidebar-card-action-btn";
btnCopy.title = t("Copy to Clipboard");
if (!isImage) {
btnCopy.style.display = "none";
} else {
btnCopy.onclick = async (ev) => {
ev.stopPropagation();
const success = await copyImageToClipboard(previewUrl);
if (success) {
btnCopy.className = "pi pi-check comfy-sidebar-card-action-btn";
btnCopy.style.color = "#4ade80";
setTimeout(() => {
btnCopy.className = "pi pi-copy comfy-sidebar-card-action-btn";
btnCopy.style.color = "";
}, 1500);
}
};
}
leftHoverPanel.appendChild(btnCopy);
card.append(grid, sizeBadge);
if (nameBadge) card.append(nameBadge);
card.append(hoverPanel, leftHoverPanel);
return card;
}
function updateBreadcrumbUI() {
if (!galleryContainerEl) return;
const breadcrumbBar = galleryContainerEl.querySelector(".comfy-sidebar-breadcrumb-bar");
if (!breadcrumbBar) return;
breadcrumbBar.innerHTML = "";
const rootBtn = document.createElement("span");
rootBtn.className = "comfy-sidebar-breadcrumb-item";
rootBtn.innerHTML = `<i class="pi pi-home" style="margin-right: 4px; font-size: 11px; color: var(--primary, var(--p-primary-color, var(--primary-color, #a855f7)));"></i>output`;
rootBtn.onclick = () => navigateToSubfolder("");
breadcrumbBar.appendChild(rootBtn);
const normalized = (currentSubfolder || "").replace(/\\/g, "/");
if (normalized) {
const parts = normalized.split("/").filter(Boolean);
let accumulated = "";
parts.forEach((part) => {
accumulated = accumulated ? `${accumulated}/${part}` : part;
const targetPath = accumulated;
const sep = document.createElement("span");
sep.className = "comfy-sidebar-breadcrumb-sep";
sep.textContent = "/";
breadcrumbBar.appendChild(sep);
const crumb = document.createElement("span");
crumb.className = "comfy-sidebar-breadcrumb-item";
crumb.textContent = part;
crumb.onclick = () => navigateToSubfolder(targetPath);
breadcrumbBar.appendChild(crumb);
});
}
}
function loadNextBatch() {
if (displayedFilesCount >= cachedFiles.length) return;
const nextFiles = cachedFiles.slice(displayedFilesCount, displayedFilesCount + BATCH_SIZE);
displayedFilesCount += nextFiles.length;
const cardElements = nextFiles.map(file => createFileCard(file));
mountGalleryCards(cardStackEl, null, cardElements, currentColumnCount, true);
}
export function renderGallery() {
if (!galleryContainerEl || !cardStackEl) return;
updateBreadcrumbUI();
let subfolderWrapper = null;
if (cachedFolders.length > 0 && !currentSearchQuery) {
subfolderWrapper = document.createElement("div");
subfolderWrapper.className = "comfy-sidebar-folders-grid";
cachedFolders.forEach(folder => {
const folderCard = document.createElement("div");
folderCard.className = "comfy-sidebar-folder-card";
folderCard.title = folder.name;
const icon = document.createElement("span");
icon.className = "pi pi-folder comfy-sidebar-folder-icon";
const name = document.createElement("span");
name.className = "comfy-sidebar-folder-name";
name.textContent = folder.name;
const ctrlOverlay = document.createElement("div");
ctrlOverlay.className = "comfy-sidebar-ctrl-overlay";
ctrlOverlay.innerHTML = `<i class="pi pi-folder-open"></i><span>${t("Open Folder")}</span>`;
folderCard.appendChild(icon);
folderCard.appendChild(name);
folderCard.appendChild(ctrlOverlay);
folderCard.onclick = async (e) => {
if (e.ctrlKey || e.metaKey) {
e.stopPropagation();
await openFileOrFolder({ subfolder: folder.subfolder, type: "output" });
return;
}
await navigateToSubfolder(folder.subfolder);
};
subfolderWrapper.appendChild(folderCard);
});
}
const threshold = getSetting(SettingIds.GRID_COLUMNS_THRESHOLD, 350);
const containerWidth = galleryContainerEl.clientWidth || 0;
if (containerWidth > 0) {
currentColumnCount = calculateGridColumns(containerWidth, threshold);
}
let columnsWrapper = cardStackEl.querySelector(".comfy-sidebar-masonry-wrapper");
if (columnsWrapper) columnsWrapper.innerHTML = "";
const initialFiles = cachedFiles.slice(0, BATCH_SIZE);
displayedFilesCount = initialFiles.length;
const cardElements = initialFiles.map(file => createFileCard(file));
mountGalleryCards(cardStackEl, subfolderWrapper, cardElements, currentColumnCount, false);
updateScrollTopVisibility();
}
async function navigateToSubfolder(subfolder) {
currentSubfolder = (subfolder || "").replace(/\\/g, "/");
currentSearchQuery = "";
await fetchGalleryData(currentSubfolder);
const scrollEl = getScrollContainer(cardStackEl);
if (scrollEl) scrollEl.scrollTop = 0;
renderGallery();
}
export function setupGalleryView() {
const container = document.createElement("div");
galleryContainerEl = container;
Object.assign(container.style, {
display: "flex", flexDirection: "column", height: "100%", padding: "14px", boxSizing: "border-box",
background: "transparent",
color: "var(--fg-color, var(--p-text-color, #eee))", position: "relative"
});
const header = document.createElement("div");
header.className = "comfy-sidebar-header-root";
Object.assign(header.style, { position: "relative", marginBottom: "8px", height: "26px", display: "flex", alignItems: "center" });
const standardHeader = document.createElement("div");
Object.assign(standardHeader.style, { display: "flex", width: "100%", alignItems: "center", justifyContent: "space-between" });
const titleGroup = document.createElement("div");
Object.assign(titleGroup.style, { display: "flex", alignItems: "center", gap: "8px" });
const searchIcon = document.createElement("span");
searchIcon.className = "pi pi-search comfy-sidebar-icon-btn";
searchIcon.title = t("Search Gallery (Filename or Prompt)");
const title = document.createElement("h3");
title.textContent = t("Gallery");
Object.assign(title.style, { margin: "0", fontSize: "14px", fontWeight: "bold", opacity: "0.9", color: "var(--fg-color, #eee)" });
titleGroup.appendChild(searchIcon);
titleGroup.appendChild(title);
standardHeader.appendChild(titleGroup);
const actionsGroup = document.createElement("div");
Object.assign(actionsGroup.style, { display: "flex", gap: "5px", alignItems: "center" });
const createHeaderBtn = (iconClass, tooltip, onClickFn) => {
const btn = document.createElement("button");
btn.className = `${iconClass} comfy-sidebar-header-btn`;
btn.title = tooltip;
btn.onclick = async (ev) => {
ev.stopPropagation();
btn.style.transform = "scale(0.88)";
setTimeout(() => { btn.style.transform = ""; }, 120);
await onClickFn();
};
return btn;
};
const initialSortIcon = sortOrder === "newest" ? "pi-sort-amount-down" : "pi-sort-amount-up";
const initialSortTitle = sortOrder === "newest" ? t("Sort: Newest First") : t("Sort: Oldest First");
const btnSort = createHeaderBtn(`pi ${initialSortIcon}`, initialSortTitle, () => {
sortOrder = sortOrder === "newest" ? "oldest" : "newest";
try { localStorage.setItem("ComfySidebar.GallerySortOrder", sortOrder); } catch (e) {}
btnSort.className = `pi ${sortOrder === "newest" ? "pi-sort-amount-down" : "pi-sort-amount-up"} comfy-sidebar-header-btn`;
btnSort.title = sortOrder === "newest" ? t("Sort: Newest First") : t("Sort: Oldest First");
applySorting();
renderGallery();
});
const btnUp = createHeaderBtn("pi pi-arrow-up", t("Go Up One Level"), async () => {
if (!currentSubfolder) return;
const parts = currentSubfolder.split("/").filter(Boolean);
parts.pop();
await navigateToSubfolder(parts.join("/"));
});
const btnOpenFolder = createHeaderBtn("pi pi-folder-open", t("Open Current Folder in File Manager"), async () => {
await openFileOrFolder({ subfolder: currentSubfolder, type: "output" });
});
const btnRefresh = createHeaderBtn("pi pi-refresh", t("Refresh Gallery"), async () => {
await fetchGalleryData(currentSubfolder, currentSearchQuery);
renderGallery();
});
actionsGroup.append(btnSort, btnUp, btnOpenFolder, btnRefresh);
standardHeader.appendChild(actionsGroup);
const searchContainer = document.createElement("div");
searchContainer.className = "comfy-sidebar-search-container";
Object.assign(searchContainer.style, {
display: "none", width: "100%", alignItems: "center",
background: "var(--card, var(--secondary, var(--comfy-input-bg, #181818)))",
border: "1px solid var(--border, var(--border-color, #555))", borderRadius: "4px", padding: "2px 8px",
boxSizing: "border-box", height: "26px"
});
const sIcon = document.createElement("span");
sIcon.className = "pi pi-search";
Object.assign(sIcon.style, { fontSize: "11px", opacity: "0.6", marginRight: "6px", transition: "transform 0.2s" });
const sInput = document.createElement("input");
Object.assign(sInput, { type: "text", placeholder: t("Search filenames or prompt metadata...") });
Object.assign(sInput.style, {
flex: "1", background: "transparent", border: "none", outline: "none",
color: "var(--comfy-input-color, var(--fg-color, #eee))", fontSize: "11px", padding: "0"
});
const sClear = document.createElement("span");
sClear.className = "pi pi-times comfy-sidebar-icon-btn";
sClear.title = t("Clear & Close Search");
Object.assign(sClear.style, { marginLeft: "6px" });
searchContainer.append(sIcon, sInput, sClear);
header.append(standardHeader, searchContainer);
const stickyHeaderGroup = document.createElement("div");
stickyHeaderGroup.className = "comfy-sidebar-sticky-header-group";
stickyHeaderGroupEl = stickyHeaderGroup;
stickyHeaderGroup.appendChild(header);
let scrollBeforeSearch = 0;
searchIcon.onclick = (e) => {
e.stopPropagation();
const scrollEl = getScrollContainer(cardStackEl);
scrollBeforeSearch = scrollEl ? scrollEl.scrollTop : 0;
standardHeader.style.display = "none";
searchContainer.style.display = "flex";
sInput.focus();
};
let searchDebounce = null;
const closeSearch = () => {
const hadFilter = Boolean(currentSearchQuery || sInput.value.trim());
sInput.value = "";
currentSearchQuery = "";
sIcon.className = "pi pi-search";
searchContainer.style.display = "none";
standardHeader.style.display = "flex";
// If the user didn't type a search query, do NOT re-fetch or wipe cards.
// The scroll position stays right where you are.
if (hadFilter) {
fetchGalleryData(currentSubfolder, "").then(() => {
renderGallery();
const scrollEl = getScrollContainer(cardStackEl);
if (scrollEl && scrollBeforeSearch > 0) {
scrollEl.scrollTop = scrollBeforeSearch;
requestAnimationFrame(() => { scrollEl.scrollTop = scrollBeforeSearch; });
}
});
}
};
sClear.onclick = (e) => { e.stopPropagation(); closeSearch(); };
sInput.onkeydown = (e) => { if (e.key === "Escape") closeSearch(); };
sInput.oninput = () => {
currentSearchQuery = sInput.value.trim();
if (searchDebounce) clearTimeout(searchDebounce);
sIcon.className = "pi pi-spin pi-spinner";
searchDebounce = setTimeout(async () => {
try {
await fetchGalleryData(currentSubfolder, currentSearchQuery);
renderGallery();
} finally {
sIcon.className = "pi pi-search";
}
}, 350);
};
const breadcrumbBar = document.createElement("div");
breadcrumbBar.className = "comfy-sidebar-breadcrumb-bar";
stickyHeaderGroup.appendChild(breadcrumbBar);
container.appendChild(stickyHeaderGroup);
const cardStack = document.createElement("div");
cardStackEl = cardStack;
Object.assign(cardStack.style, {
flex: "1", overflowY: "visible", display: "flex", flexDirection: "column", paddingBottom: "28px"
});
container.appendChild(cardStack);
scrollToTopBtnEl = document.createElement("button");
scrollToTopBtnEl.className = "pi pi-chevron-up comfy-sidebar-scroll-top-btn";
scrollToTopBtnEl.title = t("Scroll to Top");
Object.assign(scrollToTopBtnEl.style, {
position: "sticky",
bottom: "14px",
marginLeft: "auto",
zIndex: "30"
});
scrollToTopBtnEl.onclick = (e) => {
e.stopPropagation();
const scrollEl = getScrollContainer(cardStackEl);
if (scrollEl) scrollEl.scrollTo({ top: 0, behavior: "smooth" });
};
container.appendChild(scrollToTopBtnEl);
const handleCtrlDown = (e) => {
if (e.key === "Control" || e.key === "Meta") document.body.classList.add("comfy-sidebar-ctrl-active");
};
const handleCtrlUp = (e) => {
if (e.key === "Control" || e.key === "Meta") document.body.classList.remove("comfy-sidebar-ctrl-active");
};
window.addEventListener("keydown", handleCtrlDown);
window.addEventListener("keyup", handleCtrlUp);
// Reveal Spotlight: track cursor position over Gallery card and folder borders
setupSpotlightTracker(container, ".comfy-sidebar-card, .comfy-sidebar-folder-card");
document.addEventListener("scroll", updateScrollTopVisibility, { capture: true, passive: true });
new ResizeObserver((entries) => {
const threshold = getSetting(SettingIds.GRID_COLUMNS_THRESHOLD, 350);
const cols = calculateGridColumns(entries[0].contentRect.width, threshold);
if (cols !== currentColumnCount) {
currentColumnCount = cols;
renderGallery();
}
}).observe(container);
fetchGalleryData("").then(() => renderGallery());
return container;
}
export function teardownGalleryView() {
document.removeEventListener("scroll", updateScrollTopVisibility, { capture: true, passive: true });
cachedFolders = [];
cachedFiles = [];
stickyHeaderGroupEl = null;
galleryContainerEl = null;
cardStackEl = null;
scrollToTopBtnEl = null;
}
+127
View File
@@ -0,0 +1,127 @@
import { getSetting } from "../core/settings.js";
export async function copyImageToClipboard(src) {
try {
const res = await fetch(src);
let blob = await res.blob();
if (blob.type !== "image/png") {
const img = new Image();
img.crossOrigin = "anonymous";
await new Promise((resolve, reject) => {
img.onload = resolve;
img.onerror = reject;
img.src = src;
});
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
canvas.getContext("2d").drawImage(img, 0, 0);
blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
}
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
return true;
} catch (err) {
console.error("Comfy Sidebar: Failed to copy image to clipboard", err);
return false;
}
}
export async function openFileOrFolder(img) {
if (!img) return;
try {
const res = await fetch("/comfy-sidebar/open-folder", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
filename: img.filename,
subfolder: img.subfolder || "",
type: img.type || "output"
})
});
if (res.ok) return;
} catch (e) {}
const src = img.url || `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}`;
const a = document.createElement("a");
a.href = src;
a.target = "_blank";
a.download = img.filename || "file";
document.body.appendChild(a);
a.click();
a.remove();
}
export async function deleteFileOnServer(fileItem) {
if (!fileItem || !fileItem.filename) return null;
const isPermanent = getSetting("Comfy Sidebar.Permanent Delete on Disk Deletion", false);
try {
const res = await fetch("/comfy-sidebar/delete-file", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
filename: fileItem.filename,
subfolder: fileItem.subfolder || "",
type: fileItem.type || "output",
permanent: isPermanent
})
});
if (res.ok) {
const data = await res.json();
return data.action || (isPermanent ? "deleted" : "trashed");
}
return null;
} catch (e) {
console.error("Comfy Sidebar: Failed to delete file on server", e);
return null;
}
}
export function removeImageFromNodeOutputs(nodeOutputs, targetImg) {
if (!nodeOutputs || !targetImg || !targetImg.filename) return;
const scanAndRemove = (obj) => {
if (!obj || typeof obj !== "object") return;
for (const key in obj) {
const val = obj[key];
if (Array.isArray(val)) {
for (let i = val.length - 1; i >= 0; i--) {
const item = val[i];
if (item && typeof item === "object") {
if (item.filename === targetImg.filename && (item.subfolder || "") === (targetImg.subfolder || "")) {
val.splice(i, 1);
} else {
scanAndRemove(item);
}
} else if (typeof item === "string" && (item === targetImg.filename || item.endsWith("/" + targetImg.filename))) {
val.splice(i, 1);
}
}
} else if (typeof val === "object") {
scanAndRemove(val);
}
}
};
for (const nodeId in nodeOutputs) {
scanAndRemove(nodeOutputs[nodeId]);
}
}
export function findNodeIdForImage(state, img) {
if (!state || !state.nodeOutputs || !img) return null;
for (const nodeId in state.nodeOutputs) {
const out = state.nodeOutputs[nodeId];
for (const key in out) {
const val = out[key];
if (Array.isArray(val)) {
if (val.some(i => i && typeof i === "object" && i.filename === img.filename)) {
return nodeId;
}
} else if (val && typeof val === "object" && val.filename === img.filename) {
return nodeId;
}
}
}
return null;
}
+822
View File
@@ -0,0 +1,822 @@
import { isImageFormat, isVideoFormat, is3DFormat, isAudioFormat, getFilenameFromUrl, findImagesInOutputs } from "../utils/utils.js";
import { openFileOrFolder, removeImageFromNodeOutputs } from "./mediaActions.js";
import { stopAllAudioPlayback, isAudioViewerOpen, setCurrentlyPlayingAudio, getCurrentlyPlayingAudio } from "./audioController.js";
import { showFullscreenPreview } from "../utils/comparison.js";
import { store } from "../core/store.js";
import { PromptStatus } from "../core/constants.js";
import { t } from "../core/i18n.js";
import { deleteHistoryItem } from "../queue/queueService.js";
export function findWorkflowBackgroundThumbnail(state, randParam = "") {
if (!state) return null;
// 1. Check if state.images already has a valid image asset
const imgs = (state.images || []).filter(i => isImageFormat(i.filename || i.url) && !i.isFallback);
let lastImg = imgs.length > 0 ? imgs[imgs.length - 1] : null;
// 2. Search all workflow node outputs for any generated image
if (!lastImg && state.nodeOutputs) {
const allOutputs = findImagesInOutputs(state.nodeOutputs, state.workflow);
const validImgs = allOutputs.filter(i => isImageFormat(i.filename || i.url) && !i.isFallback);
if (validImgs.length > 0) lastImg = validImgs[validImgs.length - 1];
}
if (lastImg) {
return lastImg.url || (window.location.origin + `/view?filename=${encodeURIComponent(lastImg.filename)}&type=${lastImg.type || 'output'}&subfolder=${encodeURIComponent(lastImg.subfolder || '')}${randParam}`);
}
return null;
}
export function render3DCardPreview(cardObj, wrapper, src, img, state) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
let preview3D = wrapper.querySelector(".comfy-sidebar-3d-wrapper");
const randParam = state?.pid ? `&rand=${encodeURIComponent(state.pid)}` : "";
const fullUrl = img.url ? img.url : window.location.origin + `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
const bgImgSrc = findWorkflowBackgroundThumbnail(state, randParam);
if (!preview3D) {
wrapper.innerHTML = "";
preview3D = document.createElement("div");
preview3D.className = "comfy-sidebar-3d-wrapper";
if (bgImgSrc) {
const bgImg = document.createElement("img");
bgImg.className = "comfy-sidebar-3d-preview-img";
bgImg.src = bgImgSrc;
bgImg.alt = "3D Thumbnail Preview";
preview3D.appendChild(bgImg);
}
const overlay = document.createElement("div");
overlay.className = "comfy-sidebar-3d-overlay";
const badge = document.createElement("span");
badge.className = "comfy-sidebar-3d-badge";
const ext = (img.filename || src).split('.').pop().toUpperCase();
badge.textContent = ext || "3D";
const icon = document.createElement("span");
icon.className = "pi pi-box comfy-sidebar-3d-icon";
const title = document.createElement("span");
title.className = "comfy-sidebar-3d-title";
title.textContent = img.filename || "3D Model";
overlay.append(badge, icon, title);
preview3D.appendChild(overlay);
wrapper.appendChild(preview3D);
} else {
const bgImg = preview3D.querySelector(".comfy-sidebar-3d-preview-img");
if (bgImg && bgImgSrc && bgImg.src !== bgImgSrc) {
bgImg.src = bgImgSrc;
} else if (!bgImg && bgImgSrc) {
const newBgImg = document.createElement("img");
newBgImg.className = "comfy-sidebar-3d-preview-img";
newBgImg.src = bgImgSrc;
newBgImg.alt = "3D Thumbnail Preview";
preview3D.insertBefore(newBgImg, preview3D.firstChild);
} else if (bgImg && !bgImgSrc) {
bgImg.remove();
}
const title = preview3D.querySelector(".comfy-sidebar-3d-title");
if (title) title.textContent = img.filename || "3D Model";
}
cardObj.firstImgElement = preview3D;
preview3D.onclick = (ev) => {
ev.stopPropagation();
if (ev.ctrlKey || ev.metaKey) {
openFileOrFolder(img);
return;
}
showFullscreenPreview([fullUrl], ev.shiftKey, state?.pid);
};
preview3D.setAttribute("draggable", "true");
preview3D.ondragstart = (e) => {
e.stopPropagation();
const filename = img.filename || "model.glb";
const mimeType = "application/octet-stream";
try {
e.dataTransfer.setData("text/uri-list", fullUrl);
e.dataTransfer.setData("text/plain", fullUrl);
e.dataTransfer.setData("DownloadURL", `${mimeType}:${filename}:${fullUrl}`);
if (state && state.workflow) {
e.dataTransfer.setData("application/json", JSON.stringify(state.workflow));
}
} catch (err) {}
e.dataTransfer.effectAllowed = "copy";
};
}
export function renderAudioCardPreview(cardObj, wrapper, src, img, state) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
let previewAudio = wrapper.querySelector(".comfy-sidebar-audio-wrapper");
const randParam = state?.pid ? `&rand=${encodeURIComponent(state.pid)}` : "";
const fullUrl = img.url ? img.url : window.location.origin + `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
const filename = img.filename || getFilenameFromUrl(src) || "audio.wav";
const ext = filename.split('.').pop().toUpperCase();
const bgImgSrc = findWorkflowBackgroundThumbnail(state, randParam);
const playIconSvg = `<svg viewBox="0 0 24 24" width="14" height="14" style="margin-left: 2px; pointer-events: none;"><polygon points="6,4 20,12 6,20" fill="#ffffff"/></svg>`;
const stopIconSvg = `<svg viewBox="0 0 24 24" width="12" height="12" style="pointer-events: none;"><rect x="5" y="5" width="14" height="14" rx="2" fill="#ffffff"/></svg>`;
if (!previewAudio) {
wrapper.innerHTML = "";
previewAudio = document.createElement("div");
previewAudio.className = "comfy-sidebar-audio-wrapper";
if (bgImgSrc) {
const bgImg = document.createElement("img");
bgImg.className = "comfy-sidebar-card-bg-img";
bgImg.src = bgImgSrc;
bgImg.alt = "Audio Cover Preview";
previewAudio.appendChild(bgImg);
}
const topRow = document.createElement("div");
Object.assign(topRow.style, { display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%", paddingLeft: "42px", position: "relative", zIndex: "2" });
const title = document.createElement("span");
title.className = "comfy-sidebar-audio-title";
title.textContent = filename;
const badge = document.createElement("span");
badge.className = "comfy-sidebar-audio-badge";
badge.textContent = ext || "AUDIO";
topRow.append(title, badge);
const centerArea = document.createElement("div");
Object.assign(centerArea.style, { position: "relative", width: "100%", display: "flex", alignItems: "center", justifyContent: "center", margin: "6px 0", zIndex: "2" });
const soundwave = document.createElement("div");
soundwave.className = "comfy-sidebar-soundwave-container";
soundwave.style.width = "100%";
const barHeights = [10, 16, 24, 18, 30, 22, 14, 28, 34, 20, 12, 26, 32, 18, 14, 22, 30, 16, 12];
barHeights.forEach((h, i) => {
const bar = document.createElement("div");
bar.className = "comfy-sidebar-soundwave-bar";
bar.style.height = `${h}px`;
bar.style.animationDelay = `${(i * 0.08).toFixed(2)}s`;
soundwave.appendChild(bar);
});
const playBtn = document.createElement("button");
Object.assign(playBtn.style, {
position: "absolute", width: "36px", height: "36px", borderRadius: "50%",
background: "rgba(22, 22, 30, 0.88)", border: "1px solid rgba(255, 255, 255, 0.25)",
color: "#ffffff", cursor: "pointer", display: "flex", alignItems: "center",
justifyContent: "center", boxShadow: "0 4px 12px rgba(0, 0, 0, 0.65)", zIndex: "5",
transition: "all 0.15s ease", outline: "none"
});
playBtn.innerHTML = playIconSvg;
centerArea.append(soundwave, playBtn);
const bottomRow = document.createElement("div");
Object.assign(bottomRow.style, { display: "flex", flexDirection: "column", gap: "4px", width: "100%", padding: "0 34px", boxSizing: "border-box", position: "relative", zIndex: "2" });
const scrubber = document.createElement("div");
Object.assign(scrubber.style, {
width: "100%", height: "4px", background: "#334155", borderRadius: "2px",
position: "relative", cursor: "pointer"
});
const scrubberFill = document.createElement("div");
Object.assign(scrubberFill.style, { width: "0%", height: "100%", background: "#c084fc", borderRadius: "2px" });
scrubber.appendChild(scrubberFill);
const timeLabel = document.createElement("div");
Object.assign(timeLabel.style, { fontSize: "9px", fontFamily: "monospace", color: "#94a3b8", textAlign: "center" });
timeLabel.textContent = "0:00 / 0:00";
bottomRow.append(scrubber, timeLabel);
const audioEl = document.createElement("audio");
audioEl.src = fullUrl;
audioEl.preload = "metadata";
const formatTime = (t) => {
const m = Math.floor(t / 60);
const s = Math.floor(t % 60);
return `${m}:${s < 10 ? '0' : ''}${s}`;
};
const resetAudioUI = () => {
playBtn.innerHTML = playIconSvg;
previewAudio.classList.remove("playing");
scrubberFill.style.width = "0%";
timeLabel.textContent = `0:00 / ${formatTime(audioEl.duration || 0)}`;
};
audioEl._onResetUI = resetAudioUI;
audioEl.onloadedmetadata = () => {
timeLabel.textContent = `0:00 / ${formatTime(audioEl.duration || 0)}`;
};
audioEl.ontimeupdate = () => {
if (audioEl.duration > 0) {
const percent = (audioEl.currentTime / audioEl.duration) * 100;
scrubberFill.style.width = `${percent}%`;
timeLabel.textContent = `${formatTime(audioEl.currentTime)} / ${formatTime(audioEl.duration)}`;
}
};
audioEl.onended = () => {
resetAudioUI();
if (getCurrentlyPlayingAudio() === audioEl) stopAllAudioPlayback();
};
const togglePlay = (e) => {
e.stopPropagation();
if (isAudioViewerOpen()) {
stopAllAudioPlayback();
showFullscreenPreview([fullUrl], false, state?.pid);
return;
}
if (audioEl.paused) {
setCurrentlyPlayingAudio(audioEl);
audioEl.play().catch(()=>{});
playBtn.innerHTML = stopIconSvg;
previewAudio.classList.add("playing");
} else {
audioEl.pause();
audioEl.currentTime = 0;
resetAudioUI();
stopAllAudioPlayback();
}
};
playBtn.onclick = togglePlay;
playBtn.onmouseenter = () => {
playBtn.style.background = "#9333ea";
playBtn.style.borderColor = "#c084fc";
playBtn.style.transform = "scale(1.08)";
};
playBtn.onmouseleave = () => {
playBtn.style.background = previewAudio.classList.contains("playing") ? "rgba(147, 51, 234, 0.85)" : "rgba(22, 22, 30, 0.88)";
playBtn.style.borderColor = "rgba(255, 255, 255, 0.25)";
playBtn.style.transform = "scale(1.0)";
};
scrubber.onclick = (e) => {
e.stopPropagation();
const rect = scrubber.getBoundingClientRect();
const pos = (e.clientX - rect.left) / rect.width;
if (audioEl.duration > 0) audioEl.currentTime = pos * audioEl.duration;
};
previewAudio.append(topRow, centerArea, bottomRow, audioEl);
wrapper.appendChild(previewAudio);
previewAudio.onclick = (e) => {
if (e.target.closest('button, input') || e.target === scrubber || e.target === scrubberFill) return;
stopAllAudioPlayback();
if (e.ctrlKey || e.metaKey) {
openFileOrFolder(img);
return;
}
showFullscreenPreview([fullUrl], false, state?.pid);
};
} else {
const bgImg = previewAudio.querySelector(".comfy-sidebar-card-bg-img");
if (bgImg && bgImgSrc && bgImg.src !== bgImgSrc) {
bgImg.src = bgImgSrc;
} else if (!bgImg && bgImgSrc) {
const newBgImg = document.createElement("img");
newBgImg.className = "comfy-sidebar-card-bg-img";
newBgImg.src = bgImgSrc;
newBgImg.alt = "Audio Cover Preview";
previewAudio.insertBefore(newBgImg, previewAudio.firstChild);
} else if (bgImg && !bgImgSrc) {
bgImg.remove();
}
const title = previewAudio.querySelector(".comfy-sidebar-audio-title");
if (title) title.textContent = filename;
}
cardObj.firstImgElement = previewAudio;
previewAudio.setAttribute("draggable", "true");
previewAudio.ondragstart = (e) => {
e.stopPropagation();
const mimeType = "audio/wav";
try {
e.dataTransfer.setData("text/uri-list", fullUrl);
e.dataTransfer.setData("text/plain", fullUrl);
e.dataTransfer.setData("DownloadURL", `${mimeType}:${filename}:${fullUrl}`);
if (state && state.workflow) {
e.dataTransfer.setData("application/json", JSON.stringify(state.workflow));
}
} catch (err) {}
e.dataTransfer.effectAllowed = "copy";
};
}
export function renderGenericFileCardPreview(cardObj, wrapper, src, img, state) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
const playIcon = wrapper.querySelector(".comfy-sidebar-play-icon");
if (playIcon) playIcon.remove();
let previewFile = wrapper.querySelector(".comfy-sidebar-file-wrapper");
const randParam = state?.pid ? `&rand=${encodeURIComponent(state.pid)}` : "";
const fullUrl = img.url ? img.url : window.location.origin + `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
const filename = img.filename || getFilenameFromUrl(src) || "output_file";
const ext = (filename.split('.').pop() || "FILE").toUpperCase();
const folderName = img.subfolder ? `${img.subfolder}/` : (img.type || "output");
const bgImgSrc = findWorkflowBackgroundThumbnail(state, randParam);
if (!previewFile) {
wrapper.innerHTML = "";
previewFile = document.createElement("div");
previewFile.className = "comfy-sidebar-file-wrapper";
if (bgImgSrc) {
const bgImg = document.createElement("img");
bgImg.className = "comfy-sidebar-card-bg-img";
bgImg.src = bgImgSrc;
bgImg.alt = "File Thumbnail Preview";
previewFile.appendChild(bgImg);
}
const topRow = document.createElement("div");
Object.assign(topRow.style, { display: "flex", justifyContent: "flex-end", width: "100%", minHeight: "18px", position: "relative", zIndex: "2" });
const badge = document.createElement("span");
badge.className = "comfy-sidebar-file-badge";
badge.textContent = ext;
topRow.appendChild(badge);
const centerArea = document.createElement("div");
Object.assign(centerArea.style, { display: "flex", alignItems: "center", gap: "8px", width: "100%", margin: "2px 0 6px 0", position: "relative", zIndex: "2" });
const icon = document.createElement("span");
icon.className = "pi pi-file comfy-sidebar-file-icon";
const title = document.createElement("span");
title.className = "comfy-sidebar-file-title";
title.textContent = filename;
title.title = filename;
centerArea.append(icon, title);
const bottomRow = document.createElement("div");
Object.assign(bottomRow.style, { display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%", position: "relative", zIndex: "2" });
const folderInfo = document.createElement("div");
folderInfo.className = "comfy-sidebar-file-subtext";
folderInfo.innerHTML = `<i class="pi pi-folder" style="font-size: 10px;"></i><span>${folderName}</span>`;
const openHint = document.createElement("div");
openHint.className = "comfy-sidebar-file-subtext";
openHint.innerHTML = `<i class="pi pi-external-link" style="font-size: 9px;"></i><span>${t("Open Folder")}</span>`;
bottomRow.append(folderInfo, openHint);
previewFile.append(topRow, centerArea, bottomRow);
wrapper.appendChild(previewFile);
} else {
const bgImg = previewFile.querySelector(".comfy-sidebar-card-bg-img");
if (bgImg && bgImgSrc && bgImg.src !== bgImgSrc) {
bgImg.src = bgImgSrc;
} else if (!bgImg && bgImgSrc) {
const newBgImg = document.createElement("img");
newBgImg.className = "comfy-sidebar-card-bg-img";
newBgImg.src = bgImgSrc;
newBgImg.alt = "File Thumbnail Preview";
previewFile.insertBefore(newBgImg, previewFile.firstChild);
} else if (bgImg && !bgImgSrc) {
bgImg.remove();
}
const title = previewFile.querySelector(".comfy-sidebar-file-title");
if (title) { title.textContent = filename; title.title = filename; }
const badge = previewFile.querySelector(".comfy-sidebar-file-badge");
if (badge) badge.textContent = ext;
}
cardObj.firstImgElement = previewFile;
previewFile.onclick = (ev) => {
ev.stopPropagation();
openFileOrFolder(img);
};
previewFile.setAttribute("draggable", "true");
previewFile.ondragstart = (e) => {
e.stopPropagation();
const mimeType = "application/octet-stream";
try {
e.dataTransfer.setData("text/uri-list", fullUrl);
e.dataTransfer.setData("text/plain", fullUrl);
e.dataTransfer.setData("DownloadURL", `${mimeType}:${filename}:${fullUrl}`);
if (state && state.workflow) {
e.dataTransfer.setData("application/json", JSON.stringify(state.workflow));
}
} catch (err) {}
e.dataTransfer.effectAllowed = "copy";
};
}
export function renderCardImages(cardObj, state, onNavigateBatch) {
cardObj.currentImageIndex = cardObj.currentImageIndex || 0;
if (cardObj.currentImageIndex >= state.images.length) {
cardObj.currentImageIndex = 0;
}
const idx = cardObj.currentImageIndex;
const img = state.images[idx];
if (!img) {
cardObj.grid.innerHTML = "";
cardObj.firstImgElement = null;
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
return;
}
const randParam = state?.pid ? `&rand=${encodeURIComponent(state.pid)}` : "";
const src = img.url ? img.url : window.location.origin + `/view?filename=${encodeURIComponent(img.filename)}&type=${img.type || 'output'}&subfolder=${encodeURIComponent(img.subfolder || '')}${randParam}`;
const isVideo = isVideoFormat(src) || isVideoFormat(img.filename);
const is3D = is3DFormat(src) || is3DFormat(img.filename);
const isAudio = isAudioFormat(src) || isAudioFormat(img.filename);
const isImage = isImageFormat(src) || isImageFormat(img.filename) || (!isVideo && !is3D && !isAudio && !img.filename?.includes("."));
let wrapper = cardObj.grid.querySelector(".comfy-sidebar-media-wrapper");
if (!wrapper) {
cardObj.grid.innerHTML = "";
wrapper = document.createElement("div");
wrapper.className = "comfy-sidebar-media-wrapper";
Object.assign(wrapper.style, { position: "relative", width: "100%", display: "block" });
cardObj.grid.appendChild(wrapper);
}
let ctrlOverlay = wrapper.querySelector(".comfy-sidebar-ctrl-overlay");
if (!ctrlOverlay) {
ctrlOverlay = document.createElement("div");
ctrlOverlay.className = "comfy-sidebar-ctrl-overlay";
ctrlOverlay.innerHTML = `<i class="pi pi-folder-open"></i><span>${t("Open Location")}</span>`;
wrapper.appendChild(ctrlOverlay);
}
// Direct children check: safely disconnect any loading event listeners on previous media
const existingTopImg = wrapper.querySelector(":scope > img, :scope > video");
const existing3D = wrapper.querySelector(".comfy-sidebar-3d-wrapper");
const existingAudio = wrapper.querySelector(".comfy-sidebar-audio-wrapper");
const existingFile = wrapper.querySelector(".comfy-sidebar-file-wrapper");
if (existingTopImg) {
if (existingTopImg.tagName === "VIDEO") {
existingTopImg.onloadedmetadata = null;
existingTopImg.pause();
existingTopImg.src = "";
existingTopImg.load();
} else {
existingTopImg.onload = null;
existingTopImg.src = "";
}
}
if (is3D) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
if (existingTopImg) existingTopImg.remove();
if (existingAudio) existingAudio.remove();
if (existingFile) existingFile.remove();
render3DCardPreview(cardObj, wrapper, src, img, state);
return;
}
if (isAudio) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
if (existingTopImg) existingTopImg.remove();
if (existing3D) existing3D.remove();
if (existingFile) existingFile.remove();
renderAudioCardPreview(cardObj, wrapper, src, img, state);
return;
}
if (!isImage && !isVideo) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
if (existingTopImg) existingTopImg.remove();
if (existing3D) existing3D.remove();
if (existingAudio) existingAudio.remove();
renderGenericFileCardPreview(cardObj, wrapper, src, img, state);
return;
}
// Standard Image/Video mode: remove any 3D, audio, or file preview boxes
if (existing3D) existing3D.remove();
if (existingAudio) existingAudio.remove();
if (existingFile) existingFile.remove();
let mediaEl = wrapper.querySelector(":scope > img, :scope > video");
const needsRebuild = !mediaEl || (isVideo !== (mediaEl.tagName.toLowerCase() === "video"));
if (needsRebuild) {
if (mediaEl) mediaEl.remove();
mediaEl = isVideo ? document.createElement("video") : document.createElement("img");
Object.assign(mediaEl.style, {
width: "100%",
borderRadius: "2px",
display: "block",
cursor: "zoom-in",
webkitUserDrag: "element",
zIndex: "1"
});
wrapper.insertBefore(mediaEl, wrapper.firstChild);
}
cardObj.firstImgElement = mediaEl;
mediaEl.onclick = (ev) => {
ev.stopPropagation();
if (ev.ctrlKey || ev.metaKey) {
openFileOrFolder(img);
return;
}
let activeSrc = mediaEl.currentSrc || mediaEl.src || src;
if (activeSrc && activeSrc.startsWith("blob:") && mediaEl.naturalWidth > 0) {
try {
const canvas = document.createElement("canvas");
canvas.width = mediaEl.naturalWidth;
canvas.height = mediaEl.naturalHeight;
canvas.getContext("2d").drawImage(mediaEl, 0, 0);
activeSrc = canvas.toDataURL("image/png");
} catch (_) {}
}
showFullscreenPreview([activeSrc], ev.shiftKey, state?.pid);
};
mediaEl.onerror = () => {
mediaEl.onerror = null;
if ((src && src.startsWith("blob:")) || is3D || isAudio) return;
const cardId = cardObj.element?.id || "";
// 1. If an intermediate output item is missing, remove only this item
if (cardId.startsWith("card-submenu-")) {
const parentState = store.getPrompt(state.pid);
if (parentState && parentState.nodeOutputs) {
if (state.nodeId && parentState.nodeOutputs[state.nodeId]) {
delete parentState.nodeOutputs[state.nodeId];
} else {
removeImageFromNodeOutputs(parentState.nodeOutputs, img);
}
store.updatePrompt(parentState.pid, parentState);
}
cardObj.element?.remove();
const remaining = store.ui.cardStack?.querySelectorAll('.comfy-sidebar-card');
if (!remaining || remaining.length === 0) {
store.closeSubmenu();
}
return;
}
// 2. If a batch item is missing, remove only this item from the batch
if (cardId.startsWith("card-batch-")) {
const parentPid = state.parentPromptId || state.pid;
const parentState = store.getPrompt(parentPid);
if (parentState) {
if (Array.isArray(parentState.images)) {
const idx = parentState.images.findIndex(i => i.filename === img.filename && (i.subfolder || "") === (img.subfolder || ""));
if (idx > -1) parentState.images.splice(idx, 1);
}
if (parentState.nodeOutputs) {
removeImageFromNodeOutputs(parentState.nodeOutputs, img);
}
if ((!parentState.images || parentState.images.length === 0) && parentState.status === PromptStatus.COMPLETED) {
deleteHistoryItem(parentPid);
} else {
store.updatePrompt(parentPid, parentState);
}
}
cardObj.element?.remove();
const remaining = store.ui.cardStack?.querySelectorAll('.comfy-sidebar-card');
if (!remaining || remaining.length === 0) {
store.closeSubmenu();
}
return;
}
// 3. Main card: if this file is gone, clean it up
const liveState = store.getPrompt(state.pid);
if (liveState) {
if (Array.isArray(liveState.images)) {
liveState.images = liveState.images.filter(i =>
!(i.filename === img.filename && (i.subfolder || "") === (img.subfolder || ""))
);
}
if (liveState.nodeOutputs) {
removeImageFromNodeOutputs(liveState.nodeOutputs, img);
}
if (liveState.images && liveState.images.length > 0) {
cardObj.currentImageIndex = 0;
cardObj.lastImagesSignature = "";
store.updatePrompt(liveState.pid, liveState);
return;
}
// If the job is still actively generating/running, keep it
if (liveState.status && liveState.status !== PromptStatus.COMPLETED) {
cardObj.lastImagesSignature = "";
store.updatePrompt(liveState.pid, liveState);
return;
}
// Temp image preview was deleted and only intermediate prompt text remains: delete card for good
deleteHistoryItem(liveState.pid);
cardObj.element?.remove();
return;
}
renderGenericFileCardPreview(cardObj, wrapper, src, img, state);
};
const applyDimensions = (width, height) => {
// Strictly forbid dimension badges on 3D, Audio, or File cards
if (is3D || isAudio || (!isImage && !isVideo)) {
if (cardObj.dimEl) cardObj.dimEl.style.display = "none";
return;
}
if (cardObj.dimEl && width && height) {
if (state.status === "active" || state.status === "cancelled" || state.status === "error") {
cardObj.dimEl.style.display = "none";
return;
}
cardObj.dimEl.textContent = `${width}x${height}`;
cardObj.dimEl.style.display = "block";
}
};
const isUnfinished = state.status ? (state.status !== "completed") : false;
if (isUnfinished) {
mediaEl.setAttribute("draggable", "false");
mediaEl.style.cursor = "grab";
if (mediaEl._currentDragStart) {
mediaEl.removeEventListener("dragstart", mediaEl._currentDragStart);
delete mediaEl._currentDragStart;
}
} else {
mediaEl.setAttribute("draggable", "true");
mediaEl.style.cursor = "zoom-in";
if (isVideo) {
const fullSrc = src.startsWith("http") ? src : window.location.origin + src;
const filename = img.filename || "output.mp4";
const mimeType = src.includes(".webm") ? "video/webm" : "video/mp4";
const videoDragHandler = (e) => {
try {
e.dataTransfer.setData("text/uri-list", fullSrc);
e.dataTransfer.setData("text/plain", fullSrc);
e.dataTransfer.setData("DownloadURL", `${mimeType}:${filename}:${fullSrc}`);
if (state && state.workflow) {
e.dataTransfer.setData("application/json", JSON.stringify(state.workflow));
}
} catch (err) {}
e.dataTransfer.effectAllowed = "copy";
e.stopPropagation();
};
if (mediaEl._currentDragStart) {
mediaEl.removeEventListener("dragstart", mediaEl._currentDragStart);
}
mediaEl.addEventListener("dragstart", videoDragHandler);
mediaEl._currentDragStart = videoDragHandler;
} else {
if (mediaEl._currentDragStart) {
mediaEl.removeEventListener("dragstart", mediaEl._currentDragStart);
delete mediaEl._currentDragStart;
}
}
}
if (isVideo) {
mediaEl.muted = true;
mediaEl.playsInline = true;
mediaEl.preload = "metadata";
mediaEl.loop = true;
mediaEl.onloadedmetadata = () => {
applyDimensions(mediaEl.videoWidth, mediaEl.videoHeight);
};
if (mediaEl.readyState >= 1) {
applyDimensions(mediaEl.videoWidth, mediaEl.videoHeight);
}
let playIcon = wrapper.querySelector(".comfy-sidebar-play-icon");
if (!playIcon) {
playIcon = document.createElement("div");
playIcon.className = "comfy-sidebar-play-icon";
Object.assign(playIcon.style, {
position: "absolute", top: "0", left: "0", width: "100%", height: "100%",
pointerEvents: "none", zIndex: "2", transition: "opacity 0.2s ease"
});
playIcon.innerHTML = `
<svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" style="width: 100%; height: 100%; filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3));">
<circle cx="50" cy="50" r="16.65" fill="rgba(0, 0, 0, 0.55)" />
<polygon points="45.7,42.5 45.7,57.5 58.7,50" fill="rgba(255, 255, 255, 0.9)" />
</svg>
`;
wrapper.appendChild(playIcon);
}
mediaEl.onmouseenter = () => { playIcon.style.opacity = "0"; mediaEl.play().catch(()=>{}); };
mediaEl.onmouseleave = () => { playIcon.style.opacity = "1"; mediaEl.pause(); };
} else {
mediaEl.onload = () => {
applyDimensions(mediaEl.naturalWidth, mediaEl.naturalHeight);
if (state._oldPreviewBlobUrl) {
try { URL.revokeObjectURL(state._oldPreviewBlobUrl); } catch(e){}
delete state._oldPreviewBlobUrl;
}
};
if (mediaEl.complete && mediaEl.naturalWidth) {
applyDimensions(mediaEl.naturalWidth, mediaEl.naturalHeight);
}
const playIcon = wrapper.querySelector(".comfy-sidebar-play-icon");
if (playIcon) playIcon.remove();
}
const currentSrc = mediaEl.getAttribute("src") || mediaEl.src;
if (currentSrc !== src && currentSrc !== (currentSrc + "#t=0.001")) {
if (src.startsWith("blob:") && !isVideo) {
const tempImg = new Image();
tempImg.onload = () => {
const oldBlob = mediaEl._lastBlob;
mediaEl.src = src;
mediaEl._lastBlob = src;
applyDimensions(tempImg.naturalWidth, tempImg.naturalHeight);
if (oldBlob && oldBlob !== src && oldBlob.startsWith("blob:")) {
try { URL.revokeObjectURL(oldBlob); } catch(e){}
}
};
tempImg.src = src;
} else {
mediaEl.src = isVideo ? src + "#t=0.001" : src;
}
} else {
if (isVideo) {
if (mediaEl.videoWidth) applyDimensions(mediaEl.videoWidth, mediaEl.videoHeight);
} else {
if (mediaEl.naturalWidth) applyDimensions(mediaEl.naturalWidth, mediaEl.naturalHeight);
}
}
let navBar = wrapper.querySelector(".comfy-sidebar-batch-navbar");
if (state.images.length > 1) {
if (!navBar) {
navBar = document.createElement("div");
navBar.className = "comfy-sidebar-batch-navbar";
Object.assign(navBar.style, {
position: "absolute", bottom: "6px", left: "50%",
display: "flex", alignItems: "center", gap: "8px", background: "rgba(0,0,0,0.75)",
padding: "4px 10px", borderRadius: "12px", zIndex: "15", fontSize: "10px",
fontFamily: "monospace", color: "#eee", userSelect: "none", pointerEvents: "auto",
boxShadow: "0 1px 3px rgba(0,0,0,0.4)", transform: "translate3d(-50%, 0, 0)"
});
const prevBtn = document.createElement("span");
prevBtn.className = "pi pi-chevron-left";
prevBtn.style.cursor = "pointer";
prevBtn.onclick = (ev) => {
ev.stopPropagation();
cardObj.currentImageIndex = (cardObj.currentImageIndex - 1 + state.images.length) % state.images.length;
renderCardImages(cardObj, state, onNavigateBatch);
};
const label = document.createElement("span");
label.className = "comfy-sidebar-batch-label";
label.textContent = `${idx + 1}/${state.images.length}`;
label.style.cursor = "pointer";
label.title = t("View all images in this batch");
label.onclick = (ev) => {
ev.stopPropagation();
if (typeof onNavigateBatch === "function") {
onNavigateBatch(state);
}
};
const nextBtn = document.createElement("span");
nextBtn.className = "pi pi-chevron-right";
nextBtn.style.cursor = "pointer";
nextBtn.onclick = (ev) => {
ev.stopPropagation();
cardObj.currentImageIndex = (cardObj.currentImageIndex + 1) % state.images.length;
renderCardImages(cardObj, state, onNavigateBatch);
};
navBar.append(prevBtn, label, nextBtn);
wrapper.appendChild(navBar);
}
const label = navBar.querySelector(".comfy-sidebar-batch-label");
if (label) label.textContent = `${idx + 1}/${state.images.length}`;
} else {
if (navBar) navBar.remove();
}
}
+1000
View File
File diff suppressed because it is too large Load Diff
-163
View File
@@ -1,163 +0,0 @@
import { app } from "/scripts/app.js";
export const isVideoFormat = (url) => {
if (!url) return false;
const s = String(url).toLowerCase();
return s.includes(".mp4") || s.includes(".webm");
};
export const is3DFormat = (url) => {
if (!url) return false;
const s = String(url).toLowerCase();
return s.includes(".glb") || s.includes(".gltf") || s.includes(".obj") ||
s.includes(".ply") || s.includes(".stl") || s.includes(".splat") ||
s.includes(".spz") || s.includes(".ksplat") || s.includes(".fbx");
};
export const isAudioFormat = (url) => {
if (!url) return false;
const s = String(url).toLowerCase();
return s.includes(".wav") || s.includes(".mp3") || s.includes(".ogg") ||
s.includes(".flac") || s.includes(".m4a") || s.includes(".aac") ||
s.includes(".opus");
};
export function getFilenameFromUrl(url) {
if (!url) return "";
try {
const u = new URL(url, window.location.origin);
if (u.searchParams && u.searchParams.get("filename")) {
return u.searchParams.get("filename");
}
const pathname = u.pathname || "";
return pathname.split("/").pop() || "";
} catch (e) {
return String(url).split("?")[0].split("/").pop() || "";
}
}
export function parseWorkflow(workflow) {
if (!workflow) return null;
if (typeof workflow === "object") return workflow;
if (typeof workflow === "string") {
try { return JSON.parse(workflow); } catch (e) { return null; }
}
return null;
}
function isNodeIgnored(nodeId, rawWorkflow) {
const workflow = parseWorkflow(rawWorkflow);
if (!workflow || !Array.isArray(workflow.nodes)) {
return false;
}
const node = workflow.nodes.find(n => String(n.id) === String(nodeId));
return !!(node && node.properties && node.properties.ignoreInQueue);
}
export function findImagesInOutputs(outputs, rawWorkflow) {
const list = [];
if (!outputs) return list;
const scan = (obj) => {
if (!obj) return;
if (Array.isArray(obj)) {
obj.forEach(item => scan(item));
} else if (typeof obj === "object") {
if (obj.filename || obj.name) {
const fname = obj.filename || obj.name;
if (typeof fname === "string" && (fname.includes(".") || obj.type)) {
list.push({
filename: fname,
subfolder: obj.subfolder || "",
type: obj.type || "output"
});
return;
}
}
for (const key in obj) {
scan(obj[key]);
}
}
};
const workflow = parseWorkflow(rawWorkflow);
for (const nodeId in outputs) {
if (isNodeIgnored(nodeId, workflow)) continue;
scan(outputs[nodeId]);
}
return list;
}
export function findTextsInOutputs(outputs, rawWorkflow) {
const workflow = parseWorkflow(rawWorkflow);
const list = [];
if (!outputs) return list;
for (const nodeId in outputs) {
if (isNodeIgnored(nodeId, workflow)) continue;
for (const key in outputs[nodeId]) {
const val = outputs[nodeId][key];
if (Array.isArray(val)) {
val.forEach(item => {
if (typeof item === 'string') {
list.push(item);
} else if (item && typeof item === 'object' && item.text) {
if (Array.isArray(item.text)) list.push(...item.text);
else if (typeof item.text === 'string') list.push(item.text);
}
});
} else if (typeof val === 'string') {
list.push(val);
} else if (val && typeof val === 'object' && val.text) {
if (Array.isArray(val.text)) list.push(...val.text);
else if (typeof val.text === 'string') list.push(val.text);
}
}
}
return list;
}
export function getRunOutputs(nodeOutputs, rawWorkflow) {
const workflow = parseWorkflow(rawWorkflow);
const list = [];
if (!nodeOutputs) return list;
for (const nodeId in nodeOutputs) {
const imgs = findImagesInOutputs({ [nodeId]: nodeOutputs[nodeId] }, workflow);
if (imgs.length > 0) {
list.push({ nodeId, images: imgs });
}
}
return list;
}
export function getPrimaryOutputImages(nodeOutputs, rawWorkflow) {
if (!nodeOutputs) return [];
const runOutputs = getRunOutputs(nodeOutputs, rawWorkflow);
if (runOutputs.length === 0) return [];
return runOutputs[runOutputs.length - 1].images || [];
}
export function matchesFilter(state, query) {
if (!query) return true;
const q = query.toLowerCase();
if (state.pid && String(state.pid).toLowerCase().includes(q)) return true;
if (state.texts && state.texts.some(t => String(t).toLowerCase().includes(q))) return true;
if (state.images && state.images.some(img => (img.filename || "").toLowerCase().includes(q))) return true;
if (state.activeNodeName && state.activeNodeName.toLowerCase().includes(q)) return true;
const workflow = parseWorkflow(state.workflow);
if (workflow && Array.isArray(workflow.nodes)) {
for (const node of workflow.nodes) {
if (node.title && node.title.toLowerCase().includes(q)) return true;
if (node.type && node.type.toLowerCase().includes(q)) return true;
if (Array.isArray(node.widgets)) {
for (const w of node.widgets) {
if (w && w.value !== undefined && w.value !== null) {
if (String(w.value).toLowerCase().includes(q)) return true;
}
}
}
}
}
return false;
}
File diff suppressed because it is too large Load Diff
+185
View File
@@ -0,0 +1,185 @@
import { app } from "/scripts/app.js";
import { store } from "../core/store.js";
async function promoteOrUploadToInput(imageObj) {
// 1. Try server-side promotion first (no browser RAM/re-upload overhead)
try {
const promoteRes = await fetch("/comfy-sidebar/promote-output", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(imageObj)
});
if (promoteRes.ok) {
const data = await promoteRes.json();
if (data.name) return data.name;
}
} catch (e) {}
// 2. Fallback to browser blob pipeline if backend promotion endpoint is unavailable
const src = `/view?filename=${encodeURIComponent(imageObj.filename)}&type=${imageObj.type || 'output'}&subfolder=${encodeURIComponent(imageObj.subfolder || '')}`;
try {
const response = await fetch(src);
if (!response.ok) return null;
const blob = await response.blob();
const file = new File([blob], imageObj.filename || "dropped_file", { type: blob.type });
const formData = new FormData();
formData.append("image", file);
formData.append("overwrite", "true");
formData.append("type", "input");
const uploadRes = await fetch("/upload/image", { method: "POST", body: formData });
if (!uploadRes.ok) return null;
const uploadData = await uploadRes.json();
return uploadData.name;
} catch(e) {
console.error("Comfy Sidebar: Failed to copy file to input.", e);
return null;
}
}
async function handleWorkflowDrop(e) {
const jsonStr = e.dataTransfer.getData("application/json");
if (!jsonStr) return false;
try {
const workflow = JSON.parse(jsonStr);
if (workflow && workflow.nodes) {
if (app.loadGraphData) {
app.loadGraphData(workflow);
} else if (app.handleFile) {
const file = new File([jsonStr], "workflow.json", { type: "application/json" });
await app.handleFile(file);
}
return true;
}
} catch (err) {}
return false;
}
async function handleMediaDrop(e) {
const url = e.dataTransfer.getData("text/uri-list") || e.dataTransfer.getData("text/plain");
if (!url) return false;
try {
const urlObj = new URL(url, window.location.origin);
if (urlObj.pathname !== "/view") return false;
const filename = urlObj.searchParams.get("filename");
const type = urlObj.searchParams.get("type") || "output";
const subfolder = urlObj.searchParams.get("subfolder") || "";
if (!filename) return false;
const canvas = app.canvas;
if (!canvas || !canvas.graph) return false;
let targetNode = null;
if (canvas.convertEventToCanvasOffset) {
const pos = canvas.convertEventToCanvasOffset(e);
targetNode = canvas.graph.getNodeOnPos(pos[0], pos[1]);
} else if (canvas.canvas) {
const rect = canvas.canvas.getBoundingClientRect();
targetNode = canvas.graph.getNodeOnPos((e.clientX - rect.left - canvas.ds.offset[0]) / canvas.ds.scale, (e.clientY - rect.top - canvas.ds.offset[1]) / canvas.ds.scale);
}
const widget = targetNode?.widgets?.find(w =>
w.name === "image" || w.name === "video" || w.name === "audio" || w.name === "audio_file" ||
w.name === "file" || w.name === "video_path" || w.name === "model_file" || w.name === "3d_file" ||
w.type === "image" || w.type === "customtext"
);
const isLoadNode = targetNode && (
widget ||
targetNode.type?.includes("LoadImage") ||
targetNode.type?.includes("LoadVideo") ||
targetNode.type?.includes("VHS_LoadVideo") ||
targetNode.type?.includes("Load3D") ||
targetNode.type?.includes("Load 3D") ||
targetNode.type?.includes("LoadAudio") ||
targetNode.type?.includes("Load Audio") ||
targetNode.type?.includes("VHS_LoadAudio") ||
targetNode.type?.includes("Preview3D")
);
if (isLoadNode) {
const targetWidget = widget || targetNode.widgets?.[0];
if (targetWidget) {
const newFilename = await promoteOrUploadToInput({ filename, type, subfolder });
if (newFilename) {
if (targetWidget.options && Array.isArray(targetWidget.options.values)) {
if (!targetWidget.options.values.includes(newFilename)) {
targetWidget.options.values.push(newFilename);
}
}
targetWidget.value = newFilename;
if (targetWidget.callback) targetWidget.callback(targetWidget.value);
targetNode.imgs = null;
app.graph.setDirtyCanvas(true, true);
return true;
}
}
} else {
const src = `/view?filename=${encodeURIComponent(filename)}&type=${type}&subfolder=${encodeURIComponent(subfolder)}`;
const res = await fetch(src);
if (res.ok) {
const blob = await res.blob();
const file = new File([blob], filename, { type: blob.type });
if (app.handleFile) await app.handleFile(file);
else if (app.canvas?.handleDropItem) app.canvas.handleDropItem({ getAsFile: () => file });
return true;
}
}
} catch (err) {
console.error("Comfy Sidebar: Failed to handle dropped native URL:", err);
}
return false;
}
const dropHandlers = [
handleWorkflowDrop,
handleMediaDrop
];
export function setupDragAndDrop() {
const onDragOver = (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
};
const onDrop = async (e) => {
const isSidebarDrop = e.target.closest('.comfyui-sidebar, .comfy-sidebar, [class*="sidebar"]') ||
(store.ui.sidebarContainer && store.ui.sidebarContainer.contains(e.target));
if (isSidebarDrop) {
e.preventDefault();
e.stopPropagation();
return;
}
const url = e.dataTransfer.getData("text/uri-list") || e.dataTransfer.getData("text/plain");
const jsonStr = e.dataTransfer.getData("application/json");
const isOurMedia = url && url.includes("/view?");
const isOurWorkflow = jsonStr && jsonStr.includes('"nodes"');
// If it's an external file drop from outside the browser, let ComfyUI handle it natively
if (!isOurMedia && !isOurWorkflow) {
return;
}
// Synchronously stop ComfyUI core drop listeners from double-handling
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
for (const handler of dropHandlers) {
if (await handler(e)) {
return;
}
}
};
document.addEventListener("dragover", onDragOver);
document.addEventListener("drop", onDrop, true);
return () => {
document.removeEventListener("dragover", onDragOver);
document.removeEventListener("drop", onDrop, true);
};
}
+274
View File
@@ -0,0 +1,274 @@
import { app } from "/scripts/app.js";
import { t } from "../core/i18n.js";
import { syncAllNodeBadges } from "../comfy/nodes.js";
export function showNotification(message, type = "success", title = null) {
const summary = title || (type === "error" ? t("Error") : type === "warn" ? t("Warning") : "Comfy Sidebar");
if (app.extensionManager?.toast?.add) {
app.extensionManager.toast.add({
severity: type === "error" ? "error" : type === "warn" ? "warn" : "success",
summary,
detail: message,
life: 4000
});
return;
}
// Elegant non-blocking fallback if native toast is unavailable
const id = "comfy-sidebar-toast";
let toast = document.getElementById(id);
if (!toast) {
toast = document.createElement("div");
toast.id = id;
document.body.appendChild(toast);
}
toast.style.cssText = `
position: fixed;
bottom: 24px;
right: 24px;
background: #18181b;
color: #f4f4f5;
padding: 12px 18px;
border-radius: 8px;
border-left: 4px solid ${type === "error" ? "#ef4444" : type === "warn" ? "#f59e0b" : "#10b981"};
box-shadow: 0 8px 24px rgba(0,0,0,0.5);
z-index: 99999;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 13px;
line-height: 1.4;
max-width: 380px;
transition: opacity 0.25s ease, transform 0.25s ease;
opacity: 0;
transform: translateY(10px);
pointer-events: none;
`;
toast.innerHTML = `<strong style="color:${type === "error" ? "#f87171" : type === "warn" ? "#fbbf24" : "#34d399"}">${summary}</strong><div style="margin-top:2px;">${message}</div>`;
requestAnimationFrame(() => {
toast.style.opacity = "1";
toast.style.transform = "translateY(0)";
});
clearTimeout(toast._timeout);
toast._timeout = setTimeout(() => {
toast.style.opacity = "0";
toast.style.transform = "translateY(10px)";
setTimeout(() => toast.remove(), 300);
}, 3500);
}
function remapWidgetValue(val, oldToNew) {
if (typeof val === "string") {
const match = val.match(/^\$([^-]+)-(.*)$/);
if (match) {
const mapped = oldToNew.get(match[1]) ?? oldToNew.get(Number(match[1]));
if (mapped != null) {
return `$${mapped}-${match[2]}`;
}
}
}
return val;
}
function applyIdMappingToGraph(oldToNew) {
if (!app.graph) return;
const graphData = app.graph.serialize();
if (!graphData) return;
// 1. Remap node IDs and internal widget references
if (Array.isArray(graphData.nodes)) {
for (const node of graphData.nodes) {
const oldId = node.id;
const newId = oldToNew.get(oldId) ?? oldToNew.get(String(oldId)) ?? oldToNew.get(Number(oldId));
if (newId != null) {
node.id = newId;
}
if (Array.isArray(node.widgets_values)) {
node.widgets_values = node.widgets_values.map(val => remapWidgetValue(val, oldToNew));
} else if (node.widgets_values && typeof node.widgets_values === "object") {
for (const key of Object.keys(node.widgets_values)) {
node.widgets_values[key] = remapWidgetValue(node.widgets_values[key], oldToNew);
}
}
}
}
// 2. Remap link endpoints (both array tuples and object representations)
const linkList = Array.isArray(graphData.links)
? graphData.links
: (graphData.links && typeof graphData.links === "object" ? Object.values(graphData.links) : []);
for (const link of linkList) {
if (!link) continue;
if (Array.isArray(link)) {
// [id, origin_id, origin_slot, target_id, target_slot, type]
const originId = link[1];
const targetId = link[3];
const newOrigin = oldToNew.get(originId) ?? oldToNew.get(String(originId)) ?? oldToNew.get(Number(originId));
if (newOrigin != null) link[1] = newOrigin;
const newTarget = oldToNew.get(targetId) ?? oldToNew.get(String(targetId)) ?? oldToNew.get(Number(targetId));
if (newTarget != null) link[3] = newTarget;
} else if (typeof link === "object") {
const originId = link.origin_id;
const targetId = link.target_id;
const newOrigin = oldToNew.get(originId) ?? oldToNew.get(String(originId)) ?? oldToNew.get(Number(originId));
if (newOrigin != null) link.origin_id = newOrigin;
const newTarget = oldToNew.get(targetId) ?? oldToNew.get(String(targetId)) ?? oldToNew.get(Number(targetId));
if (newTarget != null) link.target_id = newTarget;
}
}
// 3. Remap group membership if defined
if (Array.isArray(graphData.groups)) {
for (const group of graphData.groups) {
if (Array.isArray(group.nodes)) {
group.nodes = group.nodes.map(id => oldToNew.get(id) ?? oldToNew.get(String(id)) ?? oldToNew.get(Number(id)) ?? id);
}
}
}
// 4. Update graph last_node_id counter
let maxId = 0;
for (const val of oldToNew.values()) {
const num = Number(val);
if (!isNaN(num) && num > maxId) maxId = num;
}
graphData.last_node_id = Math.max(graphData.last_node_id || 0, maxId, graphData.nodes?.length || 0);
// 5. Preserve canvas pan/zoom coordinates so the screen doesn't jump
const currentScale = app.canvas?.ds?.scale;
const currentOffset = app.canvas?.ds?.offset ? [...app.canvas.ds.offset] : null;
app.graph.configure(graphData);
if (app.canvas?.ds && currentScale != null && currentOffset != null) {
app.canvas.ds.scale = currentScale;
app.canvas.ds.offset[0] = currentOffset[0];
app.canvas.ds.offset[1] = currentOffset[1];
}
if (typeof app.graph.afterChange === "function") {
app.graph.afterChange();
}
app.graph.setDirtyCanvas(true, true);
if (app.canvas?.draw) {
app.canvas.draw(true, true);
}
syncAllNodeBadges();
}
export async function renumberNodesTopologically() {
if (!app.graph || !app.graph._nodes || app.graph._nodes.length === 0) {
showNotification(t("No nodes found on canvas to renumber."), "warn");
return;
}
const confirmed = confirm(
t("Renumbering will rewrite all node IDs on the canvas in topological execution order.\n\nThis will fix intermediate node outputs showing as the final result, but may break external scripts that rely on specific node IDs\n\nDo you want to proceed?")
);
if (!confirmed) return;
try {
// Compute LiteGraph's topological execution order
if (typeof app.graph.computeExecutionOrder === "function") {
app.graph.computeExecutionOrder(false);
}
// Sort nodes by order (lowest executes first; highest executes last)
const sortedNodes = [...app.graph._nodes].sort((a, b) => {
const orderA = typeof a.order === "number" ? a.order : Infinity;
const orderB = typeof b.order === "number" ? b.order : Infinity;
if (orderA !== orderB) return orderA - orderB;
const posXA = Array.isArray(a.pos) ? a.pos[0] : 0;
const posXB = Array.isArray(b.pos) ? b.pos[0] : 0;
if (posXA !== posXB) return posXA - posXB;
const posYA = Array.isArray(a.pos) ? a.pos[1] : 0;
const posYB = Array.isArray(b.pos) ? b.pos[1] : 0;
return posYA - posYB;
});
const isStringId = typeof sortedNodes[0]?.id === "string";
const oldToNew = new Map();
sortedNodes.forEach((node, index) => {
const newId = isStringId ? String(index + 1) : (index + 1);
oldToNew.set(node.id, newId);
oldToNew.set(String(node.id), newId);
oldToNew.set(Number(node.id), newId);
});
applyIdMappingToGraph(oldToNew);
const lastNode = sortedNodes[sortedNodes.length - 1];
const lastNodeName = lastNode ? (lastNode.title || lastNode.type) : "SaveImage";
const lastNewId = lastNode ? oldToNew.get(lastNode.id) : "";
showNotification(t("Renumbered {count} nodes by execution order. Latest node: #{id} ({name}).", { count: sortedNodes.length, id: lastNewId, name: lastNodeName }), "success");
} catch (err) {
console.error("ComfySidebar: Failed to renumber nodes", err);
showNotification(t("Failed to renumber nodes: ") + err.message, "error");
}
}
export async function setManualNodeId(targetNode = null) {
if (!app.graph) return;
const rawSelected = app.canvas?.selected_nodes;
const selectedList = rawSelected instanceof Map || rawSelected instanceof Set
? Array.from(rawSelected.values())
: (Array.isArray(rawSelected) ? rawSelected : (rawSelected && typeof rawSelected === "object" ? Object.values(rawSelected) : []));
const node = targetNode || selectedList[0] || app.canvas?.current_active_node || null;
if (!node) {
showNotification(t("Please select a node first to change its ID."), "warn");
return;
}
const currentId = node.id;
const input = prompt(t("Enter new ID for node #{id} ({name}):", { id: currentId, name: node.title || node.type }), String(currentId));
if (!input) return;
const newIdNum = parseInt(input.trim(), 10);
if (isNaN(newIdNum) || newIdNum <= 0) {
showNotification(t("Please enter a valid positive number."), "error");
return;
}
if (String(newIdNum) === String(currentId)) return;
try {
const existingNode = app.graph.getNodeById ? (app.graph.getNodeById(newIdNum) || app.graph.getNodeById(String(newIdNum))) : null;
if (existingNode && existingNode !== node) {
const confirmSwap = confirm(t("Node ID #{id} is already used by \"{name}\". Swap their IDs?", { id: newIdNum, name: existingNode.title || existingNode.type }));
if (!confirmSwap) return;
}
const isStringId = typeof currentId === "string";
const newId = isStringId ? String(newIdNum) : newIdNum;
const oldId = currentId;
const oldToNew = new Map();
if (existingNode && existingNode !== node) {
const existingId = existingNode.id;
oldToNew.set(oldId, newId);
oldToNew.set(String(oldId), newId);
oldToNew.set(Number(oldId), newId);
oldToNew.set(existingId, oldId);
oldToNew.set(String(existingId), oldId);
oldToNew.set(Number(existingId), oldId);
} else {
oldToNew.set(oldId, newId);
oldToNew.set(String(oldId), newId);
oldToNew.set(Number(oldId), newId);
}
applyIdMappingToGraph(oldToNew);
const updatedNode = app.graph.getNodeById ? (app.graph.getNodeById(newId) || app.graph.getNodeById(String(newId))) : null;
if (updatedNode && app.canvas?.selectNode) {
app.canvas.selectNode(updatedNode);
}
showNotification(t("Assigned node ID #{id} to \"{name}\".", { id: newId, name: node.title || node.type }), "success");
} catch (err) {
console.error("ComfySidebar: Failed to set node ID", err);
showNotification(t("Failed to set node ID: ") + err.message, "error");
}
}
+189
View File
@@ -0,0 +1,189 @@
import { store } from "../core/store.js";
import { findActiveSidebars, findPropertiesPanel } from "../comfy/adapter.js";
export class SidebarOverlay {
constructor(options = {}) {
this.onDestroy = options.onDestroy || (() => {});
this.onUserClose = options.onUserClose || (() => {});
this.cleanupFns = [];
this.observedElements = new Set();
// Elevate sidebars above overlay
document.body.classList.add("comfy-sidebar-overlay-active");
// Root container: visual backdrop (covers 100% flush from sidebar to sidebar, zero gap)
this.container = document.createElement("div");
this.container.className = `comfy-sidebar-comparison-overlay ${options.className || ""}`;
Object.assign(this.container.style, {
position: "fixed", top: "0", left: "0", width: "100vw", height: "100vh",
background: options.background || "color-mix(in srgb, var(--comfy-menu-bg, #121212) 95%, transparent)",
backdropFilter: "blur(8px)",
color: "var(--fg-color, #eee)",
display: "flex", flexDirection: "column", alignItems: "center",
justifyContent: "center", zIndex: "1000", boxSizing: "border-box",
overflow: "hidden", pointerEvents: "none", userSelect: "none"
});
// Interactive backdrop: insets 6px from each sidebar so the border zones pass clicks to the resizers
this.backdrop = document.createElement("div");
Object.assign(this.backdrop.style, {
position: "absolute", top: "0", bottom: "0", left: "6px", right: "6px",
pointerEvents: "auto", zIndex: "1"
});
this.backdrop.addEventListener("click", (e) => {
if (e.target === this.backdrop) {
this.onUserClose();
this.destroy();
}
});
this.container.appendChild(this.backdrop);
// Close button
this.closeBtn = document.createElement("span");
this.closeBtn.className = "pi pi-times";
this.closeBtn.title = "Close (Esc)";
Object.assign(this.closeBtn.style, {
position: "absolute", top: "16px", right: "24px", zIndex: "30",
cursor: "pointer", fontSize: "18px",
color: "var(--desc-color, #aaa)",
transition: "all 0.15s ease",
background: "var(--comfy-input-bg, rgba(20, 20, 20, 0.6))",
border: "1px solid var(--border-color, rgba(255, 255, 255, 0.1))",
borderRadius: "50%", padding: "6px", pointerEvents: "auto"
});
this.closeBtn.onmouseenter = () => {
this.closeBtn.style.color = "var(--fg-color, #fff)";
this.closeBtn.style.borderColor = "var(--fg-color, #fff)";
};
this.closeBtn.onmouseleave = () => {
this.closeBtn.style.color = "var(--desc-color, #aaa)";
this.closeBtn.style.borderColor = "var(--border-color, rgba(255, 255, 255, 0.1))";
};
this.closeBtn.onclick = () => {
this.onUserClose();
this.destroy();
};
this.container.appendChild(this.closeBtn);
// ResizeObserver to track live drag-resizing on all active sidebars
if (window.ResizeObserver) {
this.ro = new ResizeObserver(() => {
this.updateOverlayBounds();
});
this.cleanupFns.push(() => this.ro.disconnect());
}
// Sidebar boundary alignment
this.updateOverlayBounds = this.updateOverlayBounds.bind(this);
this.updateOverlayBounds();
window.addEventListener("resize", this.updateOverlayBounds);
this.cleanupFns.push(() => window.removeEventListener("resize", this.updateOverlayBounds));
// Live observer for opening/closing panels or layout changes
if (window.MutationObserver) {
let updateScheduled = false;
const mo = new MutationObserver(() => {
if (!updateScheduled) {
updateScheduled = true;
requestAnimationFrame(() => {
this.updateOverlayBounds();
updateScheduled = false;
});
}
});
mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["style", "class"] });
this.cleanupFns.push(() => mo.disconnect());
}
// Global Key Handler (Esc to close)
const onKeyDown = (e) => {
if (e.key === "Escape") {
e.preventDefault();
this.onUserClose();
this.destroy();
}
if (options.onKeyDown) options.onKeyDown(e);
};
document.addEventListener("keydown", onKeyDown);
this.cleanupFns.push(() => document.removeEventListener("keydown", onKeyDown));
document.body.appendChild(this.container);
}
observeElement(el) {
if (!el || !this.ro || this.observedElements.has(el)) return;
this.observedElements.add(el);
this.ro.observe(el);
}
updateOverlayBounds() {
let leftOffset = 0;
let rightOffset = 0;
let topOffset = 0;
const winW = window.innerWidth;
const midX = winW / 2;
try {
// Dynamically detect any top header/tab bar docked to the top of the screen
const potentialTopBars = document.querySelectorAll("header, .comfyui-header, .comfyui-menu, .comfy-menu, [class*='tab-bar'], [class*='workflow-tab'], [class*='workspace-tab'], [class*='header']");
for (const bar of potentialTopBars) {
// Must be an element sitting at the top of the viewport
const r = bar.getBoundingClientRect();
if (r.top <= 2 && r.bottom > 20 && r.bottom < 120 && r.width > 200) {
topOffset = Math.max(topOffset, Math.round(r.bottom));
}
}
const { leftPanels, rightPanels } = findActiveSidebars();
[...leftPanels, ...rightPanels].forEach(p => this.observeElement(p));
for (const el of leftPanels) {
const rect = el.getBoundingClientRect();
if (rect.right > 0 && rect.right < midX) {
leftOffset = Math.max(leftOffset, Math.round(rect.right));
}
}
for (const el of rightPanels) {
const rect = el.getBoundingClientRect();
if (rect.left > midX && rect.left < winW) {
rightOffset = Math.max(rightOffset, Math.round(winW - rect.left));
}
}
} catch (e) {
console.error("Comfy Sidebar: Error finding active sidebars:", e);
}
// Safety clamp: offsets can never exceed half screen width
leftOffset = Math.min(midX - 50, Math.max(0, leftOffset));
rightOffset = Math.min(midX - 50, Math.max(0, rightOffset));
topOffset = Math.max(0, topOffset);
this.container.style.left = `${leftOffset}px`;
this.container.style.right = `${rightOffset}px`;
this.container.style.width = `calc(100vw - ${leftOffset + rightOffset}px)`;
this.container.style.top = `${topOffset}px`;
this.container.style.height = `calc(100vh - ${topOffset}px)`;
// Crisp 1px visible separator lines along active sidebar borders
this.container.style.borderLeft = leftOffset > 0 ? "1px solid var(--border-color, rgba(255, 255, 255, 0.22))" : "none";
this.container.style.borderRight = rightOffset > 0 ? "1px solid var(--border-color, rgba(255, 255, 255, 0.22))" : "none";
}
addCleanup(fn) {
this.cleanupFns.push(fn);
}
destroy() {
document.body.classList.remove("comfy-sidebar-overlay-active");
for (const fn of this.cleanupFns.splice(0)) {
try { fn(); } catch (e) {}
}
this.container.remove();
this.onDestroy();
}
}
+923
View File
@@ -0,0 +1,923 @@
export function injectStyles() {
if (document.getElementById("comfy-sidebar-styles")) return;
const style = document.createElement("style");
style.id = "comfy-sidebar-styles";
style.textContent = `
.comfy-sidebar-card {
/* Uses the theme's main elevated surface color (matches folder background identically) */
background: var(--card, var(--secondary, var(--p-surface-800, color-mix(in srgb, var(--bg-color, var(--comfy-menu-bg, #181818)) 85%, var(--fg-color, #fff) 15%))));
border-radius: 4px; padding: 8px; position: relative;
min-height: 80px; margin-bottom: 0px; break-inside: avoid;
user-select: none; -webkit-user-select: none;
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.12)));
color: var(--foreground, var(--comfy-input-color, var(--fg-color, #eee)));
overflow: hidden;
}
.comfy-sidebar-card:hover {
border-color: color-mix(in srgb, var(--border, var(--border-color, #555)) 50%, var(--foreground, var(--fg-color, #fff)) 50%) !important;
background: color-mix(in srgb, var(--card, var(--secondary, var(--p-surface-800, var(--comfy-menu-bg, #262626)))) 85%, var(--foreground, var(--fg-color, #fff)) 15%) !important;
transition: border-color 0.2s, background-color 0.2s;
}
/* Border & Frame Spotlight (Uses the theme's main hue) */
.comfy-sidebar-card::before,
.comfy-sidebar-folder-card::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
background: radial-gradient(
160px circle at var(--mouse-x, -999px) var(--mouse-y, -999px),
color-mix(in srgb, var(--primary, var(--p-primary-color, var(--primary-color, var(--accent, currentColor)))) 60%, transparent),
transparent 70%
);
opacity: 0;
transition: opacity 0.25s ease;
pointer-events: none;
z-index: 1;
}
.comfy-sidebar-card:hover::before,
.comfy-sidebar-folder-card:hover::before {
opacity: 0.65;
}
/* Active job uses the theme accent (orange); Cancelled & Error remain standout Yellow & Red */
.comfy-sidebar-card.active { border-color: var(--primary, var(--p-primary-color, #ea580c)) !important; --hover-color: var(--primary, var(--p-primary-color, #ea580c)); }
.comfy-sidebar-card.pending { border-color: #6c757d !important; --hover-color: #adb5bd; }
.comfy-sidebar-card.cancelled { border-color: #ffc107 !important; --hover-color: #ffe082; }
.comfy-sidebar-card.error { border-color: #dc3545 !important; --hover-color: #f87171; }
/* Progress bar track & fill on active cards */
.comfy-sidebar-card.active [class*="progress"] > div,
.comfy-sidebar-card.active [class*="progress-fill"],
.comfy-sidebar-card.active [class*="bar-fill"] {
background: var(--primary, var(--p-primary-color, #ea580c)) !important;
}
.comfy-sidebar-card.pending .comfy-sidebar-queue-cancel-btn,
.comfy-sidebar-card.active .comfy-sidebar-queue-cancel-btn {
display: none !important;
}
.comfy-sidebar-card.pending:hover .comfy-sidebar-queue-cancel-btn,
.comfy-sidebar-card.active:hover .comfy-sidebar-queue-cancel-btn {
display: flex !important;
}
/* Prevent action hover buttons from showing on pending & running cards */
.comfy-sidebar-card.pending .comfy-sidebar-hover-panel,
.comfy-sidebar-card.active .comfy-sidebar-hover-panel,
.comfy-sidebar-card.pending .comfy-sidebar-left-hover-panel,
.comfy-sidebar-card.active .comfy-sidebar-left-hover-panel {
display: none !important;
}
.comfy-sidebar-card-timer {
position: absolute; top: 6px; left: 8px; font-size: 10px;
font-family: monospace; opacity: 0.7; background: rgba(0, 0, 0, 0.6);
padding: 2px 4px; border-radius: 3px; pointer-events: none; z-index: 10; color: #fff;
}
/* Card Cancel / Interrupt Button - matches native ComfyUI Topbar Cancel */
.comfy-sidebar-queue-cancel-btn {
display: none;
align-items: center !important;
justify-content: center !important;
width: 28px !important;
height: 28px !important;
background: var(--destructive, var(--p-button-danger-background, #ef4444)) !important;
color: var(--foreground, var(--fg-color, inherit)) !important;
border: 1px solid var(--destructive-border, transparent) !important;
font-size: 12px !important;
border-radius: 6px !important;
cursor: pointer !important;
transition: background-color 0.15s ease, filter 0.15s ease !important;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25) !important;
z-index: 25 !important;
}
.comfy-sidebar-queue-cancel-btn:hover {
background: color-mix(in srgb, var(--destructive, var(--p-button-danger-background, #ef4444)) 88%, var(--foreground, #fff) 12%) !important;
color: var(--foreground, var(--fg-color, inherit)) !important;
filter: brightness(1.06);
}
/* Cancel All Pending Button */
.comfy-sidebar-cancel-all-btn {
background: var(--destructive, var(--p-button-danger-background, #ef4444)) !important;
color: var(--foreground, var(--fg-color, inherit)) !important;
border: 1px solid var(--destructive-border, transparent) !important;
border-radius: 6px !important;
padding: 6px 12px !important;
cursor: pointer !important;
font-size: 11px !important;
font-weight: bold !important;
width: 100% !important;
box-sizing: border-box !important;
transition: background-color 0.15s ease, filter 0.15s ease !important;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2) !important;
}
.comfy-sidebar-cancel-all-btn:hover {
background: color-mix(in srgb, var(--destructive, var(--p-button-danger-background, #ef4444)) 88%, var(--foreground, #fff) 12%) !important;
filter: brightness(1.06);
}
.comfy-sidebar-cancel-all-btn:active {
filter: brightness(0.95);
}
.comfy-sidebar-hover-panel,
.comfy-sidebar-left-hover-panel {
display: none !important;
}
.comfy-sidebar-card:not(.pending):not(.active):hover .comfy-sidebar-hover-panel,
.comfy-sidebar-card:not(.pending):not(.active):hover .comfy-sidebar-left-hover-panel {
display: flex !important;
}
/* Card Action Buttons */
.comfy-sidebar-card-action-btn {
display: inline-flex;
align-items: center !important;
justify-content: center !important;
width: 30px !important;
height: 30px !important;
background-color: rgba(0, 0, 0, 0.75) !important;
color: #e2e8f0 !important;
font-size: 13px !important;
border-radius: 6px !important;
cursor: pointer !important;
transition: all 0.15s ease !important;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
z-index: 20 !important;
transform: translateZ(0);
}
.comfy-sidebar-card-action-btn:hover {
background-color: rgba(0, 0, 0, 0.95) !important;
color: #ffffff !important;
}
/* Delete Confirmation Active State */
.comfy-sidebar-card-action-btn.confirm-delete,
.comfy-sidebar-card-action-btn.confirm-delete:hover {
background-color: #dc3545 !important;
color: #ffffff !important;
box-shadow: 0 0 8px rgba(220, 53, 69, 0.6) !important;
}
/* Disk Delete Confirmation */
.comfy-sidebar-card-action-btn.confirm-delete-disk,
.comfy-sidebar-card-action-btn.confirm-delete-disk:hover {
background-color: #7f1d1d !important;
color: #ffc9c9 !important;
box-shadow: 0 0 10px rgba(220, 38, 38, 0.85) !important;
border: 1px solid #ef4444 !important;
}
/* Dynamic Ctrl Key Hover State */
.comfy-sidebar-del-label {
display: none;
margin-left: 5px;
font-size: 10px;
font-weight: bold;
white-space: nowrap;
font-family: sans-serif;
letter-spacing: 0.3px;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-card-action-btn:not(.comfy-sidebar-btn-del) {
display: none !important;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-left-hover-panel {
display: none !important;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-btn-del {
background-color: #991b1b !important;
color: #ffffff !important;
border: 1px solid #ef4444 !important;
width: auto !important;
padding: 0 8px !important;
border-radius: 6px !important;
box-shadow: 0 0 10px rgba(239, 68, 68, 0.6) !important;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-btn-del .comfy-sidebar-del-label {
display: inline;
}
/* Translucent Folder Indicator on Ctrl Press */
.comfy-sidebar-ctrl-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: color-mix(in srgb, var(--card, var(--secondary, #12071f)) 85%, transparent);
backdrop-filter: blur(3px);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
color: var(--primary, var(--p-primary-color, #ea580c));
z-index: 15;
opacity: 0;
pointer-events: none;
transition: opacity 0.15s ease;
border-radius: 4px;
}
.comfy-sidebar-ctrl-overlay i {
font-size: 26px;
filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.6));
}
.comfy-sidebar-ctrl-overlay span {
font-size: 11px;
font-weight: bold;
color: #f1f5f9;
font-family: sans-serif;
letter-spacing: 0.5px;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.8);
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-card:not(.pending):not(.active):hover .comfy-sidebar-ctrl-overlay {
opacity: 1;
}
.comfy-sidebar-header-btn {
background: var(--card, var(--secondary, var(--p-surface-800, rgba(255, 255, 255, 0.05))));
color: var(--muted-foreground, var(--desc-color, #aaa));
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)));
border-radius: 4px;
padding: 4px 8px;
cursor: pointer;
font-size: 13px;
transition: all 0.15s ease-in-out;
}
.comfy-sidebar-header-btn:hover {
border-color: color-mix(in srgb, var(--border, var(--border-color, #a855f7)) 65%, var(--foreground, #fff) 35%);
color: var(--foreground, #fff);
background: color-mix(in srgb, var(--card, var(--secondary, rgba(255, 255, 255, 0.12))) 65%, var(--border, var(--border-color, #a855f7)) 35%);
}
.comfy-sidebar-icon-btn {
cursor: pointer;
font-size: 13px;
opacity: 0.6;
color: var(--foreground, var(--fg-color, inherit));
transition: opacity 0.15s ease-in-out, color 0.15s ease-in-out;
}
.comfy-sidebar-icon-btn:hover {
opacity: 1;
color: var(--primary, var(--p-primary-color, inherit));
}
.comfy-sidebar-scroll-top-btn {
position: absolute;
bottom: 14px;
right: 28px;
width: 32px;
height: 32px;
border-radius: 50%;
background: var(--card, var(--secondary, rgba(30, 30, 30, 0.9)));
color: var(--foreground, #eee);
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)));
cursor: pointer;
font-size: 13px;
display: none;
align-items: center;
justify-content: center;
z-index: 999;
box-shadow: 0 4px 12px rgba(0,0,0,0.5);
transition: all 0.15s ease-in-out;
opacity: 0.85;
}
.comfy-sidebar-scroll-top-btn:hover {
opacity: 1;
background: var(--primary, var(--p-primary-color, #ea580c));
color: #fff;
border-color: var(--primary, var(--p-primary-color, #ea580c));
}
/* 3D Preview Cards */
.comfy-sidebar-3d-wrapper {
width: 100%;
height: 160px;
background: linear-gradient(135deg, #1e1e2e 0%, #0f172a 100%);
border-radius: 4px;
display: flex;
position: relative;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
transition: all 0.2s ease-in-out;
user-select: none;
cursor: pointer;
}
.comfy-sidebar-3d-wrapper:hover {
border-color: var(--primary, var(--p-primary-color, #ea580c));
box-shadow: 0 0 12px color-mix(in srgb, var(--primary, #ea580c) 35%, transparent);
}
.comfy-sidebar-3d-preview-img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
filter: brightness(0.45);
transition: filter 0.2s ease, transform 0.2s ease;
pointer-events: none;
z-index: 1;
}
.comfy-sidebar-3d-wrapper:hover .comfy-sidebar-3d-preview-img {
filter: brightness(0.6);
transform: scale(1.03);
}
.comfy-sidebar-3d-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 2;
pointer-events: none;
}
.comfy-sidebar-3d-icon {
font-size: 38px;
color: #60a5fa;
margin-bottom: 6px;
filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.8));
transition: transform 0.2s ease;
}
.comfy-sidebar-3d-wrapper:hover .comfy-sidebar-3d-icon {
transform: scale(1.1) rotate(6deg);
}
.comfy-sidebar-3d-badge {
position: absolute;
top: 6px;
right: 6px;
background: rgba(59, 130, 246, 0.9);
color: #fff;
font-size: 9px;
font-weight: bold;
padding: 2px 6px;
border-radius: 3px;
text-transform: uppercase;
letter-spacing: 0.5px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
z-index: 3;
}
.comfy-sidebar-3d-title {
font-size: 10px;
color: #f1f5f9;
font-family: monospace;
max-width: 85%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background: rgba(0, 0, 0, 0.65);
padding: 2px 6px;
border-radius: 3px;
backdrop-filter: blur(2px);
z-index: 3;
}
/* Audio Preview Cards */
/* Generic Background Thumbnail for Non-Image Cards (Audio, 3D, File) */
.comfy-sidebar-card-bg-img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
filter: brightness(0.35);
transition: filter 0.2s ease, transform 0.2s ease;
pointer-events: none;
z-index: 1;
}
.comfy-sidebar-audio-wrapper:hover .comfy-sidebar-card-bg-img,
.comfy-sidebar-file-wrapper:hover .comfy-sidebar-card-bg-img {
filter: brightness(0.5);
transform: scale(1.03);
}
.comfy-sidebar-audio-wrapper {
width: 100%;
min-height: 110px;
background: linear-gradient(135deg, #1e1333 0%, #0f172a 100%);
border-radius: 4px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 10px 12px 12px 12px;
box-sizing: border-box;
position: relative;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
transition: all 0.2s ease-in-out;
user-select: none;
cursor: pointer;
}
.comfy-sidebar-audio-wrapper:hover {
border-color: #a855f7;
box-shadow: 0 0 12px rgba(168, 85, 247, 0.35);
}
.comfy-sidebar-audio-badge {
background: rgba(168, 85, 247, 0.9);
color: #fff;
font-size: 9px;
font-weight: bold;
padding: 2px 6px;
border-radius: 3px;
text-transform: uppercase;
letter-spacing: 0.5px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
z-index: 3;
}
.comfy-sidebar-audio-title {
font-size: 10px;
color: #f1f5f9;
font-family: monospace;
max-width: 65%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
z-index: 3;
}
.comfy-sidebar-soundwave-container {
display: flex;
align-items: center;
justify-content: center;
gap: 3px;
height: 36px;
margin: 4px 0;
}
.comfy-sidebar-soundwave-bar {
width: 3px;
background: #a855f7;
border-radius: 2px;
height: 8px;
transition: height 0.1s ease, background-color 0.2s ease;
}
.comfy-sidebar-audio-wrapper.playing .comfy-sidebar-soundwave-bar {
background: #c084fc;
animation: comfySidebarWave 1s ease-in-out infinite alternate;
}
@keyframes comfySidebarWave {
0% { transform: scaleY(0.4); }
100% { transform: scaleY(1.3); }
}
/* Generic File Preview Cards */
.comfy-sidebar-file-wrapper {
width: 100%;
min-height: 88px;
background: linear-gradient(135deg, #131d2e 0%, #0b1120 100%);
border-radius: 4px;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 8px 10px;
box-sizing: border-box;
position: relative;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.12);
transition: all 0.2s ease-in-out;
user-select: none;
cursor: pointer;
gap: 8px;
}
.comfy-sidebar-file-wrapper:hover {
border-color: var(--primary, var(--p-primary-color, #ea580c));
box-shadow: 0 0 14px color-mix(in srgb, var(--primary, #ea580c) 35%, transparent);
transform: translateY(-1px);
}
.comfy-sidebar-file-badge {
background: var(--primary, var(--p-primary-color, #ea580c));
color: #fff;
font-size: 9px;
font-weight: bold;
padding: 0 6px;
height: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
line-height: 1;
border-radius: 3px;
text-transform: uppercase;
letter-spacing: 0.5px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.5);
flex-shrink: 0;
white-space: nowrap;
}
.comfy-sidebar-file-title {
font-size: 11px;
color: #f1f5f9;
font-family: monospace;
font-weight: 600;
word-break: break-all;
line-height: 1.4;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.comfy-sidebar-file-icon {
font-size: 14px;
color: #38bdf8;
flex-shrink: 0;
display: inline-flex;
align-items: center;
justify-content: center;
transform: translateY(-3px);
}
.comfy-sidebar-file-subtext {
font-size: 9px;
color: #94a3b8;
font-family: sans-serif;
display: flex;
align-items: center;
gap: 4px;
opacity: 0.9;
}
.comfy-sidebar-text-clamp {
font-size: 11px;
line-height: 1.45;
color: var(--foreground, #cbd5e1);
max-height: 84px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
cursor: pointer;
padding: 8px 10px;
/* Solid theme surface that sits above the spotlight, keeping text crisp and readable */
background: var(--card, var(--secondary, var(--p-surface-800, #181818)));
border-radius: 4px;
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.12)));
margin-top: 18px;
word-break: break-word;
transition: all 0.15s ease-in-out;
position: relative;
z-index: 2;
}
.comfy-sidebar-text-clamp:hover {
/* Follows the theme accent (orange) */
border-color: var(--primary, var(--p-primary-color, #ea580c));
background: color-mix(in srgb, var(--primary, var(--p-primary-color, #ea580c)) 6%, var(--card, var(--secondary, #181818)) 94%);
}
/* Translucent theme backdrop behind Text Reader & Fullscreen Previews */
.comfy-sidebar-comparison-overlay,
.comfy-sidebar-overlay,
body.comfy-sidebar-overlay-active > div[style*="position: fixed"],
body.comfy-sidebar-overlay-active > div[style*="position:fixed"] {
background: color-mix(in srgb, var(--background, var(--card, var(--comfy-menu-bg, #13091f))) 82%, transparent) !important;
backdrop-filter: blur(10px) !important;
-webkit-backdrop-filter: blur(10px) !important;
}
/* Round (X) Close Button across all preview overlays (matches button, div, or span) */
body.comfy-sidebar-overlay-active [style*="50%"],
.comfy-sidebar-comparison-overlay [style*="50%"],
.comfy-sidebar-3d-overlay-root [style*="50%"],
div[class*="sidebar-overlay"] [style*="50%"] {
background: var(--card, var(--secondary, rgba(28, 28, 35, 0.9))) !important;
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.2))) !important;
color: var(--muted-foreground, #cbd5e1) !important;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.5) !important;
transition: all 0.15s ease-in-out !important;
}
body.comfy-sidebar-overlay-active [style*="50%"]:hover,
.comfy-sidebar-comparison-overlay [style*="50%"]:hover,
.comfy-sidebar-3d-overlay-root [style*="50%"]:hover,
div[class*="sidebar-overlay"] [style*="50%"]:hover {
color: #ffffff !important;
border-color: var(--primary, var(--p-primary-color, #ea580c)) !important;
background: color-mix(in srgb, var(--primary, var(--p-primary-color, #ea580c)) 25%, var(--card, var(--secondary, #222)) 75%) !important;
transform: scale(1.08) !important;
}
body.comfy-sidebar-overlay-active [style*="50%"] svg,
body.comfy-sidebar-overlay-active [style*="50%"] i,
body.comfy-sidebar-overlay-active [style*="50%"] line,
body.comfy-sidebar-overlay-active [style*="50%"] path {
stroke: currentColor !important;
color: inherit !important;
}
/* Elevate outer sidebar dock containers above the preview overlay */
body.comfy-sidebar-overlay-active aside,
body.comfy-sidebar-overlay-active nav,
body.comfy-sidebar-overlay-active .comfyui-sidebar,
body.comfy-sidebar-overlay-active .side-tool-bar-container,
body.comfy-sidebar-overlay-active .sidebar-content-container,
body.comfy-sidebar-overlay-active .comfyui-sidebar-content,
body.comfy-sidebar-overlay-active .p-sidebar,
body.comfy-sidebar-overlay-active .p-sidebar-right,
body.comfy-sidebar-overlay-active [data-testid="properties-panel"],
body.comfy-sidebar-overlay-active [data-testid="workflow-overview-panel"],
body.comfy-sidebar-overlay-active [class*="properties-panel"],
body.comfy-sidebar-overlay-active [class*="resize-handle"],
body.comfy-sidebar-overlay-active [class*="resizer"],
body.comfy-sidebar-overlay-active [class*="splitter"],
body.comfy-sidebar-overlay-active [class*="gutter"],
body.comfy-sidebar-overlay-active [role="separator"] {
z-index: 1005 !important;
}
/* Media and text wrappers sit on z-index 2 so the spotlight shines on the border behind them */
.comfy-sidebar-card .comfy-sidebar-media-wrapper,
.comfy-sidebar-card .comfy-sidebar-text-clamp {
z-index: 2 !important;
position: relative;
}
.comfy-sidebar-card-timer {
z-index: 10 !important;
}
.comfy-sidebar-queue-cancel-btn {
z-index: 25 !important;
}
.comfy-sidebar-status-badge {
z-index: 30 !important;
}
/* Sidebar Tab Counter Badge (Queue count) */
.side-tool-bar-container [class*="badge"],
.comfyui-sidebar [class*="badge"],
nav [class*="badge"],
aside [class*="badge"],
.side-tool-bar-end [class*="badge"],
button:has(.pi-images) + span,
button:has([class*="queue"]) + span {
background-color: var(--primary, var(--p-primary-color, #ea580c)) !important;
background: var(--primary, var(--p-primary-color, #ea580c)) !important;
color: var(--primary-foreground, #ffffff) !important;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4) !important;
}
/* Slim down the Queue sidebar scrollbar so it stops colliding with the separator */
.comfyui-sidebar ::-webkit-scrollbar,
.comfy-sidebar ::-webkit-scrollbar,
[class*="sidebar-content"] ::-webkit-scrollbar,
.sidebar-content-container ::-webkit-scrollbar {
width: 6px !important;
}
.comfyui-sidebar ::-webkit-scrollbar-thumb,
.comfy-sidebar ::-webkit-scrollbar-thumb,
[class*="sidebar-content"] ::-webkit-scrollbar-thumb,
.sidebar-content-container ::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.25) !important;
border-radius: 3px !important;
}
/* Gallery delete button only shows in the Ctrl alternative actions menu */
.comfy-sidebar-gallery-btn-del {
display: none !important;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-gallery-btn-del,
.comfy-sidebar-gallery-btn-del.confirm-delete,
.comfy-sidebar-gallery-btn-del.confirm-delete-disk {
display: inline-flex !important;
}
/* Sticky Header & Nav Reveal (Seamlessly transparent at rest, frosted on scroll) */
.comfy-sidebar-sticky-header-group {
position: sticky;
top: 0;
margin: -14px -14px 6px -14px;
padding: 14px 14px 0 14px;
background: transparent;
z-index: 35;
transition: transform 0.22s cubic-bezier(0.16, 1, 0.3, 1), background 0.2s ease, box-shadow 0.2s ease;
will-change: transform;
}
.comfy-sidebar-sticky-header-group.is-scrolled {
background: color-mix(in srgb, var(--card, var(--secondary, var(--background, var(--bg-color, #181818)))) 75%, transparent);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.25);
border-bottom: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.08)));
}
/* Gallery Subfolders & Breadcrumb Styles */
.comfy-sidebar-breadcrumb-bar {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
color: var(--muted-foreground, var(--desc-color, #aaa));
overflow-x: auto;
white-space: nowrap;
padding: 4px 0 8px 0;
border-bottom: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.08)));
margin-bottom: 10px;
}
.comfy-sidebar-breadcrumb-item {
cursor: pointer;
padding: 2px 6px;
border-radius: 3px;
background: var(--card, var(--secondary, var(--p-surface-800, rgba(255, 255, 255, 0.05))));
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.08)));
transition: all 0.15s ease-in-out;
color: var(--foreground, var(--fg-color, #eee));
text-decoration: none;
}
.comfy-sidebar-breadcrumb-item:hover {
background: color-mix(in srgb, var(--primary, var(--p-primary-color, #38bdf8)) 25%, transparent);
border-color: var(--primary, var(--p-primary-color, #38bdf8));
color: #fff;
}
.comfy-sidebar-breadcrumb-sep {
opacity: 0.4;
font-size: 10px;
}
.comfy-sidebar-folders-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 8px;
margin-bottom: 12px;
width: 100%;
}
.comfy-sidebar-folder-card {
/* Uses the theme's main elevated surface color */
background: var(--card, var(--secondary, var(--p-surface-800, color-mix(in srgb, var(--bg-color, var(--comfy-menu-bg, #181818)) 85%, var(--fg-color, #fff) 15%))));
border-radius: 4px;
padding: 8px 10px;
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.12)));
color: var(--foreground, var(--comfy-input-color, var(--fg-color, #eee)));
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
transition: border-color 0.15s ease, background-color 0.15s ease, transform 0.1s ease;
user-select: none;
min-width: 0;
position: relative;
overflow: hidden;
}
.comfy-sidebar-folder-card:hover {
border-color: color-mix(in srgb, var(--border, var(--border-color, #555)) 50%, var(--foreground, var(--fg-color, #fff)) 50%);
background: color-mix(in srgb, var(--card, var(--secondary, var(--p-surface-800, var(--comfy-menu-bg, #262626)))) 85%, var(--foreground, var(--fg-color, #fff)) 15%);
}
.comfy-sidebar-folder-icon {
font-size: 16px;
/* Keeps the accent color (orange, blue, or purple) strictly for the icon */
color: var(--primary, var(--p-primary-color, var(--primary-color, #38bdf8)));
flex-shrink: 0;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-folder-card:hover {
cursor: alias !important;
border-color: var(--primary, var(--p-primary-color, var(--primary-color, #a855f7))) !important;
box-shadow: 0 0 0 1px var(--primary, var(--p-primary-color, var(--primary-color, #a855f7))), 0 0 10px rgba(168, 85, 247, 0.3) !important;
background: color-mix(in srgb, var(--primary, var(--p-primary-color, var(--primary-color, #a855f7))) 15%, transparent) !important;
}
.comfy-sidebar-folder-name {
font-size: 11px;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
}
.comfy-sidebar-card-filename-badge {
position: absolute;
top: 6px;
right: 8px;
font-size: 10px;
font-family: monospace;
opacity: 0.7;
background: rgba(0, 0, 0, 0.6);
padding: 2px 4px;
border-radius: 3px;
pointer-events: none;
z-index: 5;
color: #fff;
max-width: 62%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
transform: translateZ(0);
}
/* Folder card layout & Ctrl overlay support */
.comfy-sidebar-folder-card {
position: relative;
overflow: hidden;
}
body.comfy-sidebar-ctrl-active .comfy-sidebar-folder-card:hover .comfy-sidebar-ctrl-overlay {
display: flex;
}
/* Comparison selected image */
.comfy-sidebar-card.comfy-sidebar-comparison-source {
outline: 2px solid #eab308 !important;
box-shadow: 0 0 12px rgba(234, 179, 8, 0.5);
}
/* Smooth animation for the circular loader */
@keyframes comfy-sidebar-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* Runtime Preview Dock in Properties Panel */
.comfy-sidebar-runtime-preview-dock {
position: sticky;
bottom: 0px;
left: 0px;
width: 100%;
padding: 8px 12px;
box-sizing: border-box;
background: color-mix(in srgb, var(--card, var(--bg-color, var(--comfy-menu-bg, #181818))) 85%, transparent);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-top: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.12)));
z-index: 20;
display: flex;
align-items: center;
justify-content: center;
margin-top: auto;
}
.comfy-sidebar-runtime-preview-btn {
width: 100%;
height: 34px;
border-radius: 6px;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 12px;
font-weight: 600;
font-family: inherit;
transition: all 0.15s ease-in-out;
outline: none;
box-sizing: border-box;
background: var(--card, var(--secondary, rgba(255, 255, 255, 0.05)));
border: 1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)));
color: var(--muted-foreground, var(--desc-color, #aaa));
box-shadow: none;
}
.comfy-sidebar-runtime-preview-btn:hover {
border-color: color-mix(in srgb, var(--primary, var(--p-primary-color, #ea580c)) 65%, var(--border, #666) 35%);
color: var(--foreground, #fff);
background: color-mix(in srgb, var(--primary, var(--p-primary-color, #ea580c)) 8%, var(--card, rgba(255, 255, 255, 0.08)) 92%);
}
.comfy-sidebar-runtime-preview-btn.active {
background: color-mix(in srgb, var(--primary, var(--p-primary-color, var(--primary-color, #ea580c))) 18%, transparent) !important;
border: 1px solid var(--primary, var(--p-primary-color, var(--primary-color, #ea580c))) !important;
color: var(--primary, var(--p-primary-color, var(--primary-color, #ea580c))) !important;
box-shadow: 0 0 10px color-mix(in srgb, var(--primary, var(--p-primary-color, var(--primary-color, #ea580c))) 35%, transparent) !important;
}
.comfy-sidebar-runtime-preview-btn.active:hover {
filter: brightness(1.1);
}
`;
document.head.appendChild(style);
}
+84 -115
View File
@@ -1,6 +1,5 @@
import { State } from "./state.js";
let globalKeydownHandler = null;
import { SidebarOverlay } from "./overlay.js";
import { t } from "../core/i18n.js";
// Global helper for code block copying in Markdown view
window.moonCopyCode = function(button) {
@@ -12,23 +11,23 @@ window.moonCopyCode = function(button) {
const text = codeEl.innerText;
navigator.clipboard.writeText(text).then(() => {
button.innerText = "Copied!";
button.innerText = t("Copied!");
button.style.backgroundColor = "#4CAF50";
button.style.borderColor = "#45a049";
button.style.color = "#ffffff";
setTimeout(() => {
button.innerText = "Copy";
button.innerText = t("Copy");
button.style.backgroundColor = "#333333";
button.style.borderColor = "#555555";
button.style.color = "#aaaaaa";
}, 1500);
}).catch(() => {
button.innerText = "Error";
setTimeout(() => button.innerText = "Copy", 1500);
button.innerText = t("Error");
setTimeout(() => button.innerText = t("Copy"), 1500);
});
} catch (e) {
button.innerText = "Error";
setTimeout(() => button.innerText = "Copy", 1500);
button.innerText = t("Error");
setTimeout(() => button.innerText = t("Copy"), 1500);
}
};
@@ -41,7 +40,7 @@ function parseInlineMarkdown(html) {
html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
html = html.replace(/_(.*?)_/g, '<em>$1</em>');
html = html.replace(/~~(.*?)~~/g, '<span style="text-decoration:line-through;color:#888;">$1</span>');
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" style="color:#61afef;text-decoration:none;border-bottom:1px dashed #61afef;cursor:pointer;">$1</a>');
html = html.replace(/\[([^\]]+)\]\(((?:https?:\/\/|\/)[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer" style="color:var(--primary, #ea580c);text-decoration:none;border-bottom:1px dashed var(--primary, #ea580c);cursor:pointer;">$1</a>');
html = html.replace(/\$(?!\s)([^\$]+?)(?<!\s)\$/g, '<span style="font-family:\'Times New Roman\',Times,serif;font-size:14px;color:#e5c07b;font-style:italic;padding:0 2px;">$1</span>');
return html;
}
@@ -92,8 +91,8 @@ function parseMarkdown(text) {
if (inCodeBlock) {
const rCode = codeContent.join("\n");
const langBadge = codeLang ? `<div style="position:absolute;top:6px;left:10px;color:#85c5ec;font-size:10px;font-family:sans-serif;font-weight:bold;text-transform:uppercase;opacity:0.8;user-select:none;">${codeLang}</div>` : '';
const btnStyle = "position:absolute;top:6px;right:6px;background:#333;color:#aaa;border:1px solid #555;border-radius:3px;padding:3px 8px;font-size:10px;cursor:pointer;";
htmlLines.push(`<div class="code-block-container" style="position:relative;margin:8px 0;">${langBadge}<button onclick="window.moonCopyCode(this)" style="${btnStyle}">Copy</button><pre style="background:#1e1e1e;padding:10px;padding-top:28px;border-radius:4px;border:1px solid #333;font-family:monospace;overflow-x:auto;margin:0;color:#85c5ec;"><code>${rCode}</code></pre></div>`);
const btnStyle = "position:absolute;top:6px;right:6px;background:var(--secondary, #333);color:var(--muted-foreground, #aaa);border:1px solid var(--border, #555);border-radius:3px;padding:3px 8px;font-size:10px;cursor:pointer;";
htmlLines.push(`<div class="code-block-container" style="position:relative;margin:8px 0;">${langBadge}<button onclick="window.moonCopyCode(this)" style="${btnStyle}">${t("Copy")}</button><pre style="background:color-mix(in srgb, var(--card, #1e1e1e) 90%, black 10%);padding:10px;padding-top:28px;border-radius:4px;border:1px solid var(--border, #333);font-family:monospace;overflow-x:auto;margin:0;color:#85c5ec;"><code>${rCode}</code></pre></div>`);
codeContent = []; codeLang = ""; inCodeBlock = false;
} else {
inCodeBlock = true; codeLang = trimmed.slice(3).trim();
@@ -194,94 +193,72 @@ function parseMarkdown(text) {
return htmlLines.join("\n");
}
export function createTextReader(textData, onSwitchMedia = () => {}, onDestroy = () => {}) {
if (globalKeydownHandler) {
document.removeEventListener("keydown", globalKeydownHandler);
globalKeydownHandler = null;
}
export function createTextReader(textData, onSwitchMedia = () => {}, onDestroy = () => {}, onUserClose = () => {}) {
let rawText = typeof textData === "object" ? (textData.text || "") : String(textData);
let pid = typeof textData === "object" ? textData.pid : "";
let isMarkdownMode = true;
const container = document.createElement("div");
container.className = "comfy-sidebar-comparison-overlay";
Object.assign(container.style, {
position: "fixed", top: "0", left: "0", width: "100vw", height: "100vh",
background: "rgba(10, 10, 10, 0.95)", display: "flex", flexDirection: "column",
alignItems: "center", justifyContent: "center", zIndex: "1000",
boxSizing: "border-box", overflow: "hidden", pointerEvents: "auto", userSelect: "none"
});
const updateOverlayBounds = () => {
const sidebarEl = State.sidebarContainer?.closest('.comfyui-sidebar, .comfy-sidebar, .p-sidebar, [class*="sidebar"]') || State.sidebarContainer;
if (sidebarEl && sidebarEl.offsetWidth > 0 && sidebarEl.isConnected) {
const rect = sidebarEl.getBoundingClientRect();
if (rect.left < window.innerWidth / 2) {
const leftOffset = Math.max(0, rect.right);
container.style.left = `${leftOffset}px`;
container.style.width = `calc(100vw - ${leftOffset}px)`;
container.style.right = "0px";
} else {
const rightOffset = Math.max(0, window.innerWidth - rect.left);
container.style.left = "0px";
container.style.width = `calc(100vw - ${rightOffset}px)`;
container.style.right = `${rightOffset}px`;
}
container.style.top = `${Math.max(0, rect.top)}px`;
container.style.height = `calc(100vh - ${Math.max(0, rect.top)}px)`;
} else {
container.style.left = "0px";
container.style.width = "100vw";
container.style.top = "0px";
container.style.height = "100vh";
}
};
updateOverlayBounds();
window.addEventListener("resize", updateOverlayBounds);
const closeBtn = document.createElement("span");
closeBtn.className = "pi pi-times";
closeBtn.title = "Close (Esc)";
Object.assign(closeBtn.style, {
position: "absolute", top: "16px", right: "24px", zIndex: "30",
cursor: "pointer", fontSize: "20px", color: "#aaa", transition: "color 0.15s ease",
background: "rgba(10,10,10,0.6)", borderRadius: "50%", padding: "4px"
});
closeBtn.onmouseenter = () => closeBtn.style.color = "#fff";
closeBtn.onmouseleave = () => closeBtn.style.color = "#aaa";
container.appendChild(closeBtn);
const overlay = new SidebarOverlay({ onDestroy, onUserClose });
const readerBox = document.createElement("div");
Object.assign(readerBox.style, {
background: "rgba(18, 18, 24, 0.95)", backdropFilter: "blur(12px)",
border: "1px solid rgba(255, 255, 255, 0.15)", borderRadius: "12px",
background: "color-mix(in srgb, var(--card, var(--secondary, var(--p-surface-800, #181818))) 94%, var(--background, #000) 6%)",
backdropFilter: "blur(16px)",
border: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)))",
borderRadius: "12px",
padding: "20px 24px", width: "85%", maxWidth: "840px", height: "80vh",
boxShadow: "0 12px 40px rgba(0,0,0,0.8)", display: "flex",
flexDirection: "column", gap: "14px", zIndex: "20"
boxShadow: "0 12px 40px rgba(0,0,0,0.5)", display: "flex",
flexDirection: "column", gap: "14px", zIndex: "20",
color: "var(--foreground, var(--fg-color, #eee))",
pointerEvents: "auto"
});
const formatTitle = (id) => {
if (!id) return t("Text Output");
const shortId = id.length > 10 ? `${id.slice(0, 8)}…` : id;
return `${t("Text Output #")}${shortId}`;
};
const headerRow = document.createElement("div");
Object.assign(headerRow.style, { display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: "1px solid rgba(255,255,255,0.1)", paddingBottom: "12px" });
Object.assign(headerRow.style, {
display: "flex", alignItems: "center", justifyContent: "space-between",
borderBottom: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.12)))", paddingBottom: "12px",
flexWrap: "wrap", gap: "10px"
});
const titleInfo = document.createElement("div");
Object.assign(titleInfo.style, { display: "flex", alignItems: "center", gap: "10px" });
Object.assign(titleInfo.style, {
display: "flex", alignItems: "center", gap: "10px",
minWidth: "0", flex: "1 1 auto", overflow: "hidden"
});
const title = document.createElement("span");
title.textContent = pid ? `Text Output #${pid}` : "Text Output";
Object.assign(title.style, { fontSize: "14px", fontWeight: "bold", color: "#f8fafc", whiteSpace: "nowrap" });
title.textContent = formatTitle(pid);
title.title = pid ? `${t("Text Output #")}${pid}` : t("Text Output");
Object.assign(title.style, {
fontSize: "14px", fontWeight: "bold", color: "#f8fafc",
whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", flexShrink: "1"
});
const statsBadge = document.createElement("span");
Object.assign(statsBadge.style, { fontSize: "10px", color: "#94a3b8", background: "rgba(255,255,255,0.06)", padding: "3px 8px", borderRadius: "4px", fontFamily: "monospace", whiteSpace: "nowrap" });
Object.assign(statsBadge.style, {
fontSize: "10px", color: "var(--muted-foreground, #94a3b8)",
background: "var(--secondary, rgba(255,255,255,0.06))",
border: "1px solid var(--border, transparent)",
padding: "3px 8px", borderRadius: "4px", fontFamily: "monospace",
whiteSpace: "nowrap", flexShrink: "0"
});
titleInfo.append(title, statsBadge);
const actionsRow = document.createElement("div");
Object.assign(actionsRow.style, { display: "flex", gap: "8px", alignItems: "center" });
Object.assign(actionsRow.style, { display: "flex", gap: "8px", alignItems: "center", flexShrink: "0" });
const modeBtn = document.createElement("button");
Object.assign(modeBtn.style, {
background: "#334155", border: "1px solid #64748b", color: "#f8fafc",
background: "var(--primary, var(--p-primary-color, #a855f7))",
border: "1px solid var(--primary, var(--p-primary-color, #a855f7))",
color: "#ffffff",
borderRadius: "6px", padding: "5px 12px", fontSize: "11px", cursor: "pointer",
display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "6px",
whiteSpace: "nowrap", minWidth: "96px", height: "28px", boxSizing: "border-box"
@@ -290,16 +267,20 @@ export function createTextReader(textData, onSwitchMedia = () => {}, onDestroy =
const copyBtn = document.createElement("button");
Object.assign(copyBtn.style, {
background: "#1e293b", border: "1px solid #475569", color: "#e2e8f0",
background: "var(--secondary, var(--p-surface-800, #1e293b))",
border: "1px solid var(--border, var(--border-color, #475569))",
color: "var(--foreground, #e2e8f0)",
borderRadius: "6px", padding: "5px 10px", fontSize: "11px", cursor: "pointer",
display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "6px",
whiteSpace: "nowrap", height: "28px", boxSizing: "border-box"
});
copyBtn.innerHTML = `<i class="pi pi-copy"></i><span>Copy</span>`;
copyBtn.innerHTML = `<i class="pi pi-copy"></i><span>${t("Copy")}</span>`;
const downloadBtn = document.createElement("button");
Object.assign(downloadBtn.style, {
background: "#1e293b", border: "1px solid #475569", color: "#e2e8f0",
background: "var(--secondary, var(--p-surface-800, #1e293b))",
border: "1px solid var(--border, var(--border-color, #475569))",
color: "var(--foreground, #e2e8f0)",
borderRadius: "6px", padding: "5px 10px", fontSize: "11px", cursor: "pointer",
display: "inline-flex", alignItems: "center", justifyContent: "center", gap: "6px",
whiteSpace: "nowrap", height: "28px", boxSizing: "border-box"
@@ -312,27 +293,33 @@ export function createTextReader(textData, onSwitchMedia = () => {}, onDestroy =
const textArea = document.createElement("div");
Object.assign(textArea.style, {
flex: "1", overflowY: "auto", fontSize: "13px",
lineHeight: "1.6", color: "#e2e8f0", wordBreak: "break-word",
userSelect: "text", "-webkit-user-select": "text", background: "rgba(0,0,0,0.35)",
padding: "16px 20px", borderRadius: "6px", border: "1px solid rgba(255,255,255,0.06)",
scrollbarWidth: "thin", scrollbarColor: "#475569 rgba(0,0,0,0.2)"
lineHeight: "1.6",
color: "var(--foreground, var(--fg-color, #e2e8f0))",
wordBreak: "break-word",
userSelect: "text", "-webkit-user-select": "text",
background: "color-mix(in srgb, var(--background, var(--comfy-input-bg, #000)) 75%, transparent)",
padding: "16px 20px", borderRadius: "6px",
border: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.1)))",
scrollbarWidth: "thin"
});
const updateView = () => {
const wc = rawText.trim() ? rawText.trim().split(/\s+/).length : 0;
statsBadge.textContent = `${wc} words • ${rawText.length} chars`;
statsBadge.textContent = t("{wc} words • {chars} chars", { wc, chars: rawText.length });
if (isMarkdownMode) {
modeBtn.innerHTML = `<i class="pi pi-code"></i><span>Markdown</span>`;
modeBtn.style.background = "#3b82f6";
modeBtn.style.borderColor = "#60a5fa";
modeBtn.style.background = "var(--primary, var(--p-primary-color, #a855f7))";
modeBtn.style.borderColor = "var(--primary, var(--p-primary-color, #a855f7))";
modeBtn.style.color = "#ffffff";
textArea.style.fontFamily = "sans-serif";
textArea.style.whiteSpace = "normal";
textArea.innerHTML = parseMarkdown(rawText);
} else {
modeBtn.innerHTML = `<i class="pi pi-align-left"></i><span>Raw Text</span>`;
modeBtn.style.background = "#334155";
modeBtn.style.borderColor = "#64748b";
modeBtn.innerHTML = `<i class="pi pi-align-left"></i><span>${t("Raw Text")}</span>`;
modeBtn.style.background = "var(--secondary, #334155)";
modeBtn.style.borderColor = "var(--border, #64748b)";
modeBtn.style.color = "var(--muted-foreground, #f8fafc)";
textArea.style.fontFamily = "monospace";
textArea.style.whiteSpace = "pre-wrap";
textArea.textContent = rawText;
@@ -346,8 +333,8 @@ export function createTextReader(textData, onSwitchMedia = () => {}, onDestroy =
copyBtn.onclick = () => {
navigator.clipboard.writeText(rawText);
copyBtn.innerHTML = `<i class="pi pi-check" style="color:#10b981;"></i><span style="color:#10b981;">Copied!</span>`;
setTimeout(() => { copyBtn.innerHTML = `<i class="pi pi-copy"></i><span>Copy</span>`; }, 1800);
copyBtn.innerHTML = `<i class="pi pi-check" style="color:#10b981;"></i><span style="color:#10b981;">${t("Copied!")}</span>`;
setTimeout(() => { copyBtn.innerHTML = `<i class="pi pi-copy"></i><span>${t("Copy")}</span>`; }, 1800);
};
downloadBtn.onclick = () => {
@@ -363,40 +350,22 @@ export function createTextReader(textData, onSwitchMedia = () => {}, onDestroy =
updateView();
readerBox.append(headerRow, textArea);
container.appendChild(readerBox);
const destroy = () => {
window.removeEventListener("resize", updateOverlayBounds);
if (globalKeydownHandler) {
document.removeEventListener("keydown", globalKeydownHandler);
globalKeydownHandler = null;
}
container.remove();
onDestroy();
};
closeBtn.onclick = destroy;
container.onclick = (e) => { if (e.target === container) destroy(); };
const handleKeys = (e) => { if (e.key === "Escape") destroy(); };
globalKeydownHandler = handleKeys;
document.addEventListener("keydown", globalKeydownHandler);
document.body.appendChild(container);
overlay.container.appendChild(readerBox);
return {
isText: true,
loadTarget(targetData) {
if (typeof targetData !== "object" || !targetData.text) {
destroy();
overlay.destroy();
onSwitchMedia(targetData);
return;
}
rawText = targetData.text || "";
pid = targetData.pid || "";
title.textContent = pid ? `Text Output #${pid}` : "Text Output";
title.textContent = formatTitle(pid);
title.title = pid ? `${t("Text Output #")}${pid}` : t("Text Output");
updateView();
},
destroy
destroy: () => overlay.destroy()
};
}
+584
View File
@@ -0,0 +1,584 @@
import { app } from "/scripts/app.js";
import { t } from "../core/i18n.js";
const FILE_EXT_REGEX = /\.(safetensors|ckpt|pt|pth|bin|latent|onnx|engine|gguf|lora|zip|tar|gz|7z|json|csv|parquet|txt|yaml|yml|xml|pdf|blend|fbx|obj|glb|gltf|stl|ply|splat|spz|ksplat|png|jpg|jpeg|webp|gif|bmp|tiff|svg|mp4|webm|wav|mp3|ogg|flac|m4a|aac|opus)$/i;
export function getFilenameFromUrl(url) {
if (!url) return "";
if (typeof url === "object") {
url = url.filename || url.url || "";
}
const str = String(url);
try {
const origin = window.location?.origin && window.location.origin !== "null" ? window.location.origin : "http://localhost";
const u = new URL(str, origin);
if (u.searchParams && u.searchParams.get("filename")) {
return u.searchParams.get("filename");
}
const pathname = u.pathname || "";
return pathname.split("/").pop() || "";
} catch (e) {
const m = str.match(/[?&]filename=([^&#]+)/);
if (m) {
try { return decodeURIComponent(m[1]); } catch (err) { return m[1]; }
}
return str.split("?")[0].split("#")[0].split("/").pop() || "";
}
}
const checkExt = (url, extensions) => {
if (!url) return false;
const name = getFilenameFromUrl(url).toLowerCase();
const s = String(url).toLowerCase().split("?")[0].split("#")[0];
return extensions.some(ext => name.endsWith(ext) || s.endsWith(ext));
};
export const isImageFormat = (url) => {
if (!url) return false;
if (String(url).startsWith("blob:") || String(url).startsWith("data:image/")) return true;
return checkExt(url, [
".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp",
".tiff", ".tif", ".svg", ".avif", ".ico", ".apng"
]);
};
export const isVideoFormat = (url) => {
return checkExt(url, [".mp4", ".webm", ".mov", ".mkv"]);
};
export const is3DFormat = (url) => {
return checkExt(url, [
".glb", ".gltf", ".obj", ".ply", ".stl",
".splat", ".spz", ".ksplat", ".fbx"
]);
};
export const isAudioFormat = (url) => {
return checkExt(url, [
".wav", ".mp3", ".ogg", ".flac", ".m4a", ".aac", ".opus"
]);
};
export function parseWorkflow(workflow) {
if (!workflow) return null;
if (typeof workflow === "object") return workflow;
if (typeof workflow === "string") {
try { return JSON.parse(workflow); } catch (e) { return null; }
}
return null;
}
export function getWorkflowNodeMap(rawWorkflow) {
const workflow = parseWorkflow(rawWorkflow);
if (!workflow || !Array.isArray(workflow.nodes)) return null;
if (workflow._nodeMap instanceof Map) {
return workflow._nodeMap;
}
const map = new Map();
for (const node of workflow.nodes) {
if (node && node.id !== undefined && node.id !== null) {
map.set(String(node.id), node);
}
}
// Attach as non-enumerable so JSON.stringify and Object.keys never see it
if (typeof workflow === "object") {
try {
Object.defineProperty(workflow, "_nodeMap", {
value: map,
writable: true,
configurable: true,
enumerable: false
});
} catch (_) {
workflow._nodeMap = map;
}
}
return map;
}
export function isNodeIgnored(nodeId, rawWorkflow) {
const idStr = String(nodeId);
const nodeMap = getWorkflowNodeMap(rawWorkflow);
if (nodeMap) {
const node = nodeMap.get(idStr);
if (node?.properties?.ignoreInQueue !== undefined) {
return !!node.properties.ignoreInQueue;
}
} else {
const workflow = parseWorkflow(rawWorkflow);
if (workflow && Array.isArray(workflow.nodes)) {
const node = workflow.nodes.find(n => String(n.id) === idStr);
if (node?.properties?.ignoreInQueue !== undefined) {
return !!node.properties.ignoreInQueue;
}
}
}
if (app.graph) {
const canvasNode = app.graph.getNodeById ? (app.graph.getNodeById(Number(nodeId)) || app.graph.getNodeById(idStr)) : null;
if (canvasNode?.properties?.ignoreInQueue !== undefined) {
return !!canvasNode.properties.ignoreInQueue;
}
}
return false;
}
export function getNodeTitle(nodeId, rawWorkflow, promptGraph = null) {
const idStr = String(nodeId);
const nodeMap = getWorkflowNodeMap(rawWorkflow);
if (nodeMap) {
const node = nodeMap.get(idStr);
if (node) {
return node.title || node.type || null;
}
} else {
const workflow = parseWorkflow(rawWorkflow);
if (workflow && Array.isArray(workflow.nodes)) {
const node = workflow.nodes.find(n => String(n.id) === idStr);
if (node) {
return node.title || node.type || null;
}
}
}
if (promptGraph && promptGraph[idStr]) {
const pNode = promptGraph[idStr];
if (pNode._meta?.title) return pNode._meta.title;
if (pNode.class_type) return pNode.class_type;
}
if (app.graph) {
const canvasNode = app.graph.getNodeById ? (app.graph.getNodeById(Number(nodeId)) || app.graph.getNodeById(idStr)) : null;
if (canvasNode) {
return canvasNode.title || canvasNode.type || null;
}
}
return null;
}
function cleanSubfolder(subfolder) {
if (!subfolder) return "";
let s = String(subfolder).replace(/\\/g, "/").trim();
s = s.replace(/^\/+|\/+$/g, ""); // Strip leading/trailing slashes
if (s.toLowerCase() === "output") return "";
if (s.toLowerCase().startsWith("output/")) {
s = s.substring(7);
}
return s;
}
function extractFileCandidate(val, subfolder = "", type = "output", nodeType = "") {
if (!val || typeof val !== "string") return null;
let trimmed = val.replace(/\\/g, "/").trim();
if (trimmed === "." || trimmed === ".." || trimmed === "./" || trimmed === "../" || trimmed === "") {
return null;
}
if (!isNaN(Number(trimmed))) {
return null;
}
// Extract any path ending with a known media or model extension from text messages
const fileMatch = trimmed.match(/([a-zA-Z0-9_\-\.\/]+\.(?:safetensors|ckpt|pt|bin|latent|png|jpg|jpeg|webp|mp4|webm|wav|mp3|glb|gltf))/i);
if (fileMatch) {
trimmed = fileMatch[1];
}
// Auto-append .safetensors if this is a LoRA node/subfolder without an extension
if (!trimmed.includes(".")) {
const typeLower = (nodeType || "").toLowerCase();
const subLower = (subfolder || "").toLowerCase();
const isLora = typeLower.includes("lora") || subLower.includes("lora") || trimmed.includes("lora");
const isLatent = typeLower.includes("latent");
if (isLora) {
trimmed += ".safetensors";
} else if (isLatent) {
trimmed += ".latent";
} else {
return null;
}
}
const cleanName = trimmed.split("/").pop()?.trim() || "";
if (!cleanName || cleanName === "." || cleanName === "..") return null;
const dotIndex = cleanName.lastIndexOf(".");
if (dotIndex <= 0 || dotIndex === cleanName.length - 1) {
return null;
}
const ext = cleanName.substring(dotIndex + 1).toLowerCase();
const base = cleanName.substring(0, dotIndex).trim();
if (!base || !ext) return null;
const isValidExt = FILE_EXT_REGEX.test("." + ext) || (/^[a-z0-9]{1,8}$/i.test(ext) && !trimmed.includes(" ") && trimmed.length < 100);
if (!isValidExt) return null;
let detectedSub = subfolder;
if (trimmed.includes("/")) {
detectedSub = trimmed.substring(0, trimmed.lastIndexOf("/"));
}
detectedSub = cleanSubfolder(detectedSub);
return {
filename: cleanName,
subfolder: detectedSub,
type: type || "output"
};
}
export function findImagesInOutputs(outputs, rawWorkflow) {
const list = [];
const seen = new Set();
const workflow = parseWorkflow(rawWorkflow);
const addCandidate = (item) => {
if (!item || !item.filename) return;
const key = `${item.type || "output"}/${item.subfolder || ""}/${item.filename}`;
if (!seen.has(key)) {
seen.add(key);
list.push(item);
}
};
const scan = (obj, sub = "", typ = "output", nodeType = "") => {
if (!obj) return;
if (typeof obj === "string") {
const cand = extractFileCandidate(obj, sub, typ, nodeType);
if (cand) addCandidate(cand);
return;
}
if (Array.isArray(obj)) {
obj.forEach(item => scan(item, sub, typ, nodeType));
return;
}
if (typeof obj === "object") {
const targetSub = obj.subfolder !== undefined ? obj.subfolder : sub;
const targetTyp = obj.type || typ || "output";
const fname = obj.filename || obj.name || obj.file || obj.path ||
obj.lora_name || obj.model_name || obj.save_name ||
obj.saved_file || obj.output_path || obj.file_name ||
obj.output || obj.saved;
if (fname && typeof fname === "string") {
const cand = extractFileCandidate(fname, targetSub, targetTyp, nodeType);
if (cand) {
addCandidate(cand);
return;
}
}
for (const key in obj) {
scan(obj[key], targetSub, targetTyp, nodeType || key);
}
}
};
if (outputs) {
const nodeMap = getWorkflowNodeMap(workflow);
for (const nodeId in outputs) {
if (isNodeIgnored(nodeId, workflow)) continue;
const node = nodeMap ? nodeMap.get(String(nodeId)) : workflow?.nodes?.find(n => String(n.id) === String(nodeId));
const nodeType = node ? (node.type || "") : "";
scan(outputs[nodeId], "", "output", nodeType);
}
}
if (list.length > 0) return list;
// Fallback: Check workflow nodes for Save / Extract / Export nodes
if (workflow && Array.isArray(workflow.nodes)) {
const targetNodeIds = outputs ? Object.keys(outputs).map(String) : null;
for (const node of workflow.nodes) {
if (node && !node.properties?.ignoreInQueue) {
if (targetNodeIds && targetNodeIds.length > 0 && !targetNodeIds.includes(String(node.id))) {
continue;
}
const typeStr = (node.type || "").toLowerCase();
const isLoaderNode = typeStr.includes("load") || typeStr.includes("loader") || typeStr.includes("input");
const isSaveNode = !isLoaderNode && (
typeStr.includes("save") ||
typeStr.includes("extract") ||
typeStr.includes("export") ||
typeStr.includes("writer")
);
if (isSaveNode && Array.isArray(node.widgets_values)) {
for (const val of node.widgets_values) {
if (typeof val === "string" && val.trim().length > 0) {
let defaultSub = "";
if (typeStr.includes("lora")) defaultSub = "loras";
const cand = extractFileCandidate(val, defaultSub, "output", typeStr);
if (cand) {
cand.isFallback = true;
addCandidate(cand);
}
}
}
}
}
}
}
return list;
}
export function findTextsInOutputs(outputs, rawWorkflow) {
const workflow = parseWorkflow(rawWorkflow);
const list = [];
if (!outputs) return list;
for (const nodeId in outputs) {
if (isNodeIgnored(nodeId, workflow)) continue;
for (const key in outputs[nodeId]) {
const val = outputs[nodeId][key];
if (Array.isArray(val)) {
val.forEach(item => {
if (typeof item === 'string' && item.trim().length > 0 && !FILE_EXT_REGEX.test(item.trim())) {
list.push(item);
} else if (item && typeof item === 'object' && item.text) {
if (Array.isArray(item.text)) list.push(...item.text.filter(t => typeof t === 'string' && t.trim().length > 0));
else if (typeof item.text === 'string' && item.text.trim().length > 0) list.push(item.text);
}
});
} else if (typeof val === 'string' && val.trim().length > 0 && !FILE_EXT_REGEX.test(val.trim())) {
list.push(val);
} else if (val && typeof val === 'object' && val.text) {
if (Array.isArray(val.text)) list.push(...val.text.filter(t => typeof t === 'string' && t.trim().length > 0));
else if (typeof val.text === 'string' && val.text.trim().length > 0) list.push(val.text);
}
}
}
return list;
}
export function getRunOutputs(nodeOutputs, rawWorkflow, promptGraph = null) {
const workflow = parseWorkflow(rawWorkflow);
const list = [];
if (!nodeOutputs) return list;
// Track node execution order so the final executed node is always sorted last
const nodeOrderMap = new Map();
if (workflow && Array.isArray(workflow.nodes)) {
workflow.nodes.forEach((n, idx) => {
const order = typeof n.order === "number" ? n.order : idx;
nodeOrderMap.set(String(n.id), order);
});
}
const nodeIds = Object.keys(nodeOutputs);
// Sort node IDs by real execution order (lowest executes first; highest executes last)
nodeIds.sort((a, b) => {
const orderA = nodeOrderMap.has(String(a)) ? nodeOrderMap.get(String(a)) : Infinity;
const orderB = nodeOrderMap.has(String(b)) ? nodeOrderMap.get(String(b)) : Infinity;
if (orderA !== orderB) return orderA - orderB;
return 0;
});
for (const nodeId of nodeIds) {
if (isNodeIgnored(nodeId, workflow)) continue;
const nodeOut = nodeOutputs[nodeId];
if (!nodeOut || (typeof nodeOut === "object" && Object.keys(nodeOut).length === 0)) {
// Even if the output dict is empty, check if this node was a Save/Extract node
const imgs = findImagesInOutputs({ [nodeId]: nodeOut }, workflow);
if (imgs.length > 0) {
const title = getNodeTitle(nodeId, workflow, promptGraph);
list.push({ nodeId, images: imgs, nodeTitle: title });
}
continue;
}
const imgs = findImagesInOutputs({ [nodeId]: nodeOut }, workflow);
if (imgs.length > 0) {
const title = getNodeTitle(nodeId, workflow, promptGraph);
list.push({ nodeId, images: imgs, nodeTitle: title });
}
}
return list;
}
export function getPrimaryOutputImages(nodeOutputs, rawWorkflow) {
if (!nodeOutputs) return findImagesInOutputs(null, rawWorkflow);
const runOutputs = getRunOutputs(nodeOutputs, rawWorkflow);
if (runOutputs.length === 0) return findImagesInOutputs(nodeOutputs, rawWorkflow);
// Find the latest executed node that actually produced real output images
for (let i = runOutputs.length - 1; i >= 0; i--) {
const imgs = runOutputs[i].images || [];
if (imgs.some(img => !img.isFallback)) {
return imgs;
}
}
return runOutputs[runOutputs.length - 1].images || [];
}
export function matchesFilter(state, query) {
if (!query) return true;
const q = query.toLowerCase();
if (state.pid && String(state.pid).toLowerCase().includes(q)) return true;
if (state.texts && state.texts.some(t => String(t).toLowerCase().includes(q))) return true;
if (state.images && state.images.some(img => (img.filename || "").toLowerCase().includes(q))) return true;
if (state.activeNodeName && state.activeNodeName.toLowerCase().includes(q)) return true;
const workflow = parseWorkflow(state.workflow);
if (workflow && Array.isArray(workflow.nodes)) {
for (const node of workflow.nodes) {
if (node.title && node.title.toLowerCase().includes(q)) return true;
if (node.type && node.type.toLowerCase().includes(q)) return true;
if (Array.isArray(node.widgets)) {
for (const w of node.widgets) {
if (w && w.value !== undefined && w.value !== null) {
if (String(w.value).toLowerCase().includes(q)) return true;
}
}
}
}
}
return false;
}
export async function extractWorkflowFromPng(imageUrl) {
try {
const res = await fetch(imageUrl);
const buffer = await res.arrayBuffer();
const view = new DataView(buffer);
if (view.getUint32(0) !== 0x89504E47 || view.getUint32(4) !== 0x0D0A1A0A) {
return null;
}
let offset = 8;
const utf8Decoder = new TextDecoder("utf-8");
while (offset < buffer.byteLength) {
const length = view.getUint32(offset);
const type = utf8Decoder.decode(new Uint8Array(buffer, offset + 4, 4));
if (type === "tEXt") {
const chunkData = new Uint8Array(buffer, offset + 8, length);
const nullIdx = chunkData.indexOf(0);
if (nullIdx !== -1) {
const keyword = utf8Decoder.decode(chunkData.subarray(0, nullIdx));
if (keyword === "workflow") {
const text = utf8Decoder.decode(chunkData.subarray(nullIdx + 1));
return JSON.parse(text);
}
}
} else if (type === "IEND") {
break;
}
offset += 12 + length;
}
} catch (e) {
console.warn("Comfy Sidebar: Could not extract workflow from PNG", e);
}
return null;
}
export function animateCardRemoval(cardEl, callback, duration = 200) {
if (!cardEl) {
if (callback) callback();
return;
}
cardEl.style.transition = `opacity ${duration}ms ease, transform ${duration}ms ease`;
cardEl.style.opacity = "0";
cardEl.style.transform = "scale(0.85)";
setTimeout(() => {
if (callback) callback();
}, duration);
}
export function getScrollContainer(element) {
if (!element) return null;
return element.closest('.sidebar-content-container, [class*="sidebar-content-container"], [class*="overflow-y-auto"]')
|| element.parentElement
|| element;
}
export function calculateGridColumns(width, threshold = 350) {
if (!width || width <= 0) return 1;
return Math.max(1, Math.floor(width / ((threshold || 350) / 2)));
}
export function downloadJson(data, filename) {
if (!data) return;
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename || "workflow.json";
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1500);
}
export function setupSpotlightTracker(container, cardSelector = ".comfy-sidebar-card") {
if (!container) return;
container.addEventListener("pointermove", (e) => {
const card = e.target.closest(cardSelector);
if (card) {
const rect = card.getBoundingClientRect();
card.style.setProperty("--mouse-x", `${e.clientX - rect.left}px`);
card.style.setProperty("--mouse-y", `${e.clientY - rect.top}px`);
}
}, { passive: true });
}
export function attachDeleteConfirmation(btn, options = {}) {
if (!btn) return () => {};
const {
canDiskDelete = true,
timeout = 2000,
idleTitle = t("Delete"),
confirmTitle = t("Click again to confirm"),
confirmDiskTitle = t("Ctrl+Click again to delete from disk"),
onConfirm
} = options;
let isPending = false;
let isDisk = false;
let timer = null;
const reset = () => {
isPending = false;
isDisk = false;
btn.classList.remove("confirm-delete", "confirm-delete-disk");
btn.title = typeof idleTitle === "function" ? idleTitle() : idleTitle;
if (timer) {
clearTimeout(timer);
timer = null;
}
};
reset();
btn.onclick = async (ev) => {
ev.stopPropagation();
const wantsDisk = (ev.ctrlKey || ev.metaKey) && (typeof canDiskDelete === "function" ? canDiskDelete() : !!canDiskDelete);
if (!isPending) {
isPending = true;
isDisk = wantsDisk;
btn.classList.add(wantsDisk ? "confirm-delete-disk" : "confirm-delete");
btn.title = wantsDisk
? (typeof confirmDiskTitle === "function" ? confirmDiskTitle() : confirmDiskTitle)
: (typeof confirmTitle === "function" ? confirmTitle() : confirmTitle);
timer = setTimeout(reset, timeout);
} else {
const finalDisk = isDisk || wantsDisk;
reset();
if (onConfirm) await onConfirm(finalDisk);
}
};
return reset;
}
+172 -182
View File
@@ -1,140 +1,115 @@
import { is3DFormat } from "./utils.js";
import { State } from "./state.js";
import { is3DFormat, getFilenameFromUrl } from "./utils.js";
import { SidebarOverlay } from "./overlay.js";
import { t } from "../core/i18n.js";
let globalKeydownHandler = null;
let cachedThreeLibs = null;
async function getThreeLibs() {
if (cachedThreeLibs) return cachedThreeLibs;
if (window.THREE && window.THREE.GLTFLoader && window.THREE.OrbitControls) {
cachedThreeLibs = window.THREE;
return cachedThreeLibs;
// Check if Three.js was already loaded on window by another ComfyUI 3D node
if (window.THREE) {
const OrbitControls = window.THREE.OrbitControls || window.OrbitControls;
const GLTFLoader = window.THREE.GLTFLoader || window.GLTFLoader;
if (OrbitControls && GLTFLoader) {
cachedThreeLibs = {
...window.THREE,
OrbitControls,
GLTFLoader,
OBJLoader: window.THREE.OBJLoader || window.OBJLoader,
STLLoader: window.THREE.STLLoader || window.STLLoader,
PLYLoader: window.THREE.PLYLoader || window.PLYLoader
};
return cachedThreeLibs;
}
}
try {
const loadFromBase = async (base) => {
const [three, controls, gltf, obj, stl, ply] = await Promise.all([
import("https://esm.sh/three@0.170.0"),
import("https://esm.sh/three@0.170.0/examples/jsm/controls/OrbitControls.js"),
import("https://esm.sh/three@0.170.0/examples/jsm/loaders/GLTFLoader.js"),
import("https://esm.sh/three@0.170.0/examples/jsm/loaders/OBJLoader.js"),
import("https://esm.sh/three@0.170.0/examples/jsm/loaders/STLLoader.js"),
import("https://esm.sh/three@0.170.0/examples/jsm/loaders/PLYLoader.js")
import(`${base}three@0.170.0`),
import(`${base}three@0.170.0/examples/jsm/controls/OrbitControls.js`),
import(`${base}three@0.170.0/examples/jsm/loaders/GLTFLoader.js`),
import(`${base}three@0.170.0/examples/jsm/loaders/OBJLoader.js`).catch(() => null),
import(`${base}three@0.170.0/examples/jsm/loaders/STLLoader.js`).catch(() => null),
import(`${base}three@0.170.0/examples/jsm/loaders/PLYLoader.js`).catch(() => null)
]);
return { three, controls, gltf, obj, stl, ply };
};
try {
const base = "https://esm.sh/";
window.__COMFY_SIDEBAR_THREE_BASE = base;
const { three, controls, gltf, obj, stl, ply } = await loadFromBase(base);
cachedThreeLibs = {
...three,
OrbitControls: controls.OrbitControls,
GLTFLoader: gltf.GLTFLoader,
OBJLoader: obj.OBJLoader,
STLLoader: stl.STLLoader,
PLYLoader: ply.PLYLoader
OrbitControls: controls.OrbitControls || controls.default || controls,
GLTFLoader: gltf.GLTFLoader || gltf.default || gltf,
OBJLoader: obj?.OBJLoader || obj?.default || obj,
STLLoader: stl?.STLLoader || stl?.default || stl,
PLYLoader: ply?.PLYLoader || ply?.default || ply
};
return cachedThreeLibs;
} catch (err) {
console.error("Comfy Sidebar: Failed to load Three.js libraries", err);
console.error("Comfy Sidebar: Failed to load Three.js libraries:", err);
return null;
}
}
export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = () => {}) {
if (globalKeydownHandler) {
document.removeEventListener("keydown", globalKeydownHandler);
globalKeydownHandler = null;
}
const container = document.createElement("div");
container.className = "comfy-sidebar-comparison-overlay comfy-sidebar-3d-overlay-root";
Object.assign(container.style, {
position: "fixed", top: "0", left: "0", width: "100vw", height: "100vh",
background: "rgba(10, 10, 10, 0.95)", display: "flex", flexDirection: "column",
zIndex: "1000", boxSizing: "border-box", overflow: "hidden",
pointerEvents: "auto", userSelect: "none", "-webkit-user-select": "none"
export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = () => {}, onUserClose = () => {}) {
const overlay = new SidebarOverlay({
className: "comfy-sidebar-3d-overlay-root",
onDestroy,
onUserClose
});
const updateOverlayBounds = () => {
const sidebarEl = State.sidebarContainer?.closest('.comfyui-sidebar, .comfy-sidebar, .p-sidebar, [class*="sidebar"]') || State.sidebarContainer;
if (sidebarEl && sidebarEl.offsetWidth > 0 && sidebarEl.isConnected) {
const rect = sidebarEl.getBoundingClientRect();
if (rect.left < window.innerWidth / 2) {
const leftOffset = Math.max(0, rect.right);
container.style.left = `${leftOffset}px`;
container.style.width = `calc(100vw - ${leftOffset}px)`;
container.style.right = "0px";
} else {
const rightOffset = Math.max(0, window.innerWidth - rect.left);
container.style.left = "0px";
container.style.width = `calc(100vw - ${rightOffset}px)`;
container.style.right = `${rightOffset}px`;
}
container.style.top = `${Math.max(0, rect.top)}px`;
container.style.height = `calc(100vh - ${Math.max(0, rect.top)}px)`;
} else {
container.style.left = "0px";
container.style.width = "100vw";
container.style.top = "0px";
container.style.height = "100vh";
}
};
updateOverlayBounds();
window.addEventListener("resize", updateOverlayBounds);
let resizeObserver = null;
const sidebarEl = State.sidebarContainer?.closest('.comfyui-sidebar, .comfy-sidebar, .p-sidebar, [class*="sidebar"]') || State.sidebarContainer;
if (sidebarEl && window.ResizeObserver) {
resizeObserver = new ResizeObserver(() => updateOverlayBounds());
resizeObserver.observe(sidebarEl);
}
const header = document.createElement("div");
Object.assign(header.style, {
position: "absolute", top: "16px", left: "50%", transform: "translateX(-50%)",
display: "flex", gap: "16px", zIndex: "30", color: "#aaa", fontSize: "12px",
fontFamily: "monospace", pointerEvents: "none", background: "rgba(10,10,10,0.75)",
padding: "6px 14px", borderRadius: "6px", backdropFilter: "blur(4px)",
boxShadow: "0 2px 6px rgba(0,0,0,0.4)", maxWidth: "85%", textAlign: "center"
display: "flex", gap: "16px", zIndex: "30",
color: "var(--muted-foreground, var(--desc-color, #aaa))",
fontSize: "12px",
fontFamily: "monospace", pointerEvents: "none",
background: "color-mix(in srgb, var(--card, var(--secondary, #181818)) 90%, transparent)",
border: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)))",
padding: "6px 14px", borderRadius: "6px", backdropFilter: "blur(8px)",
boxShadow: "0 2px 8px rgba(0,0,0,0.4)", maxWidth: "85%", textAlign: "center"
});
const titleText = document.createElement("span");
titleText.textContent = baseSrc.split("/").pop().split("?")[0] || "3D Model";
titleText.textContent = getFilenameFromUrl(baseSrc) || t("3D Model");
header.appendChild(titleText);
container.appendChild(header);
const closeBtn = document.createElement("span");
closeBtn.className = "pi pi-times";
closeBtn.title = "Close (Esc)";
Object.assign(closeBtn.style, {
position: "absolute", top: "16px", right: "24px", zIndex: "30",
cursor: "pointer", fontSize: "20px", color: "#aaa", transition: "color 0.15s ease",
background: "rgba(10,10,10,0.6)", borderRadius: "50%", padding: "4px"
});
closeBtn.onmouseenter = () => closeBtn.style.color = "#fff";
closeBtn.onmouseleave = () => closeBtn.style.color = "#aaa";
container.appendChild(closeBtn);
overlay.container.appendChild(header);
const canvasContainer = document.createElement("div");
Object.assign(canvasContainer.style, {
width: "100%", height: "100%", position: "relative",
display: "flex", alignItems: "center", justifyContent: "center"
});
container.appendChild(canvasContainer);
overlay.container.appendChild(canvasContainer);
const loadingSpinner = document.createElement("div");
Object.assign(loadingSpinner.style, {
position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)",
color: "#60a5fa", fontSize: "14px", fontFamily: "sans-serif", zIndex: "20",
background: "rgba(0,0,0,0.8)", padding: "10px 18px", borderRadius: "8px",
display: "flex", alignItems: "center", gap: "10px"
color: "var(--primary, var(--p-primary-color, #ea580c))",
fontSize: "14px", fontFamily: "sans-serif", zIndex: "20",
background: "color-mix(in srgb, var(--card, var(--secondary, #181818)) 92%, transparent)",
border: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)))",
padding: "10px 18px", borderRadius: "8px",
display: "flex", alignItems: "center", gap: "10px",
boxShadow: "0 8px 24px rgba(0,0,0,0.5)"
});
loadingSpinner.innerHTML = `<span class="pi pi-spin pi-spinner" style="font-size: 18px;"></span> Loading 3D Asset...`;
container.appendChild(loadingSpinner);
loadingSpinner.innerHTML = `<span class="pi pi-spin pi-spinner" style="font-size: 18px;"></span> ${t("Loading 3D Asset...")}`;
overlay.container.appendChild(loadingSpinner);
const settingsPanel = document.createElement("div");
Object.assign(settingsPanel.style, {
position: "absolute", top: "60px", right: "20px", width: "230px",
background: "rgba(18, 18, 24, 0.9)", backdropFilter: "blur(8px)",
border: "1px solid rgba(255, 255, 255, 0.12)", borderRadius: "8px",
padding: "14px", zIndex: "35", color: "#e2e8f0", fontSize: "11px",
background: "color-mix(in srgb, var(--card, var(--secondary, #181818)) 94%, transparent)",
backdropFilter: "blur(12px)",
border: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)))",
borderRadius: "8px",
padding: "14px", zIndex: "35",
color: "var(--foreground, #e2e8f0)",
fontSize: "11px",
boxShadow: "0 8px 24px rgba(0,0,0,0.6)", display: "none", flexDirection: "column", gap: "12px"
});
@@ -143,7 +118,7 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
Object.assign(row.style, { display: "flex", flexDirection: "column", gap: "4px" });
const lbl = document.createElement("label");
lbl.textContent = label;
Object.assign(lbl.style, { color: "#94a3b8", fontSize: "10px", textTransform: "uppercase", fontWeight: "bold" });
Object.assign(lbl.style, { color: "var(--muted-foreground, #94a3b8)", fontSize: "10px", textTransform: "uppercase", fontWeight: "bold" });
row.append(lbl, inputEl);
return row;
};
@@ -151,7 +126,9 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
const createSelect = (options, value, onChange) => {
const sel = document.createElement("select");
Object.assign(sel.style, {
background: "#252530", color: "#eee", border: "1px solid #444",
background: "var(--secondary, #252530)",
color: "var(--foreground, #eee)",
border: "1px solid var(--border, var(--border-color, #444))",
borderRadius: "4px", padding: "4px 6px", fontSize: "11px", outline: "none"
});
options.forEach(opt => {
@@ -168,9 +145,11 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
const toolbar = document.createElement("div");
Object.assign(toolbar.style, {
position: "absolute", bottom: "20px", left: "50%", transform: "translateX(-50%)",
display: "flex", gap: "8px", zIndex: "30", background: "rgba(20,20,25,0.85)",
padding: "6px 12px", borderRadius: "8px", backdropFilter: "blur(6px)",
boxShadow: "0 4px 12px rgba(0,0,0,0.6)", border: "1px solid rgba(255,255,255,0.1)",
display: "flex", gap: "8px", zIndex: "30",
background: "color-mix(in srgb, var(--card, var(--secondary, #181818)) 92%, transparent)",
padding: "6px 12px", borderRadius: "8px", backdropFilter: "blur(8px)",
boxShadow: "0 4px 12px rgba(0,0,0,0.6)",
border: "1px solid var(--border, var(--border-color, rgba(255, 255, 255, 0.15)))",
alignItems: "center"
});
@@ -178,19 +157,25 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
const btn = document.createElement("button");
let active = activeDefault;
btn.className = "comfy-sidebar-3d-tool-btn";
const updateBtnTheme = () => {
btn.style.background = active ? "var(--primary, var(--p-primary-color, #ea580c))" : "transparent";
btn.style.color = active ? "#ffffff" : "var(--muted-foreground, #aaa)";
btn.style.borderColor = active ? "var(--primary, var(--p-primary-color, #ea580c))" : "var(--border, var(--border-color, #444))";
};
Object.assign(btn.style, {
background: active ? "#3b82f6" : "transparent", color: active ? "#fff" : "#aaa",
border: "1px solid " + (active ? "#3b82f6" : "#444"), borderRadius: "4px",
padding: "4px 10px", fontSize: "11px", cursor: "pointer", display: "flex",
alignItems: "center", gap: "6px", transition: "all 0.15s ease"
borderRadius: "4px", padding: "4px 10px", fontSize: "11px",
cursor: "pointer", display: "flex", alignItems: "center", gap: "6px",
transition: "all 0.15s ease", border: "1px solid"
});
updateBtnTheme();
btn.innerHTML = `<i class="${iconClass}"></i><span>${label}</span>`;
btn.onclick = (e) => {
e.stopPropagation();
active = !active;
btn.style.background = active ? "#3b82f6" : "transparent";
btn.style.color = active ? "#fff" : "#aaa";
btn.style.borderColor = active ? "#3b82f6" : "#444";
updateBtnTheme();
onClick(active);
};
return btn;
@@ -259,23 +244,27 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
try {
loadingSpinner.style.display = "flex";
loadingSpinner.innerHTML = `<span class="pi pi-spin pi-spinner"></span> Exporting ${format}...`;
loadingSpinner.innerHTML = `<span class="pi pi-spin pi-spinner"></span> ${t("Exporting {format}...", { format })}`;
const base = window.__COMFY_SIDEBAR_THREE_BASE || "https://esm.sh/";
if (format === "OBJ") {
const { OBJExporter } = await import("https://esm.sh/three@0.170.0/examples/jsm/exporters/OBJExporter.js");
const mod = await import(`${base}three@0.170.0/examples/jsm/exporters/OBJExporter.js`);
const OBJExporter = mod.OBJExporter || mod.default || mod;
const exporter = new OBJExporter();
const result = exporter.parse(currentModel);
const blob = new Blob([result], { type: "text/plain" });
downloadBlob(blob, `${baseName}.obj`);
} else if (format === "GLB") {
const { GLTFExporter } = await import("https://esm.sh/three@0.170.0/examples/jsm/exporters/GLTFExporter.js");
const mod = await import(`${base}three@0.170.0/examples/jsm/exporters/GLTFExporter.js`);
const GLTFExporter = mod.GLTFExporter || mod.default || mod;
const exporter = new GLTFExporter();
exporter.parse(currentModel, (gltf) => {
const blob = new Blob([gltf], { type: "application/octet-stream" });
downloadBlob(blob, `${baseName}.glb`);
}, (err) => { console.error(err); }, { binary: true });
} else if (format === "STL") {
const { STLExporter } = await import("https://esm.sh/three@0.170.0/examples/jsm/exporters/STLExporter.js");
const mod = await import(`${base}three@0.170.0/examples/jsm/exporters/STLExporter.js`);
const STLExporter = mod.STLExporter || mod.default || mod;
const exporter = new STLExporter();
const result = exporter.parse(currentModel, { binary: true });
const blob = new Blob([result], { type: "application/octet-stream" });
@@ -298,39 +287,23 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
}
};
const destroy = () => {
window.removeEventListener("resize", updateOverlayBounds);
if (resizeObserver) resizeObserver.disconnect();
if (globalKeydownHandler) {
document.removeEventListener("keydown", globalKeydownHandler);
globalKeydownHandler = null;
}
cleanup3D();
container.remove();
onDestroy();
};
closeBtn.onclick = destroy;
container.onclick = (e) => {
if (e.target === container || e.target === canvasContainer) destroy();
};
const handleKeys = (e) => {
if (e.key === "Escape") destroy();
};
globalKeydownHandler = handleKeys;
document.addEventListener("keydown", globalKeydownHandler);
document.body.appendChild(container);
overlay.addCleanup(cleanup3D);
const initSceneAndLoad = async (srcUrl) => {
loadingSpinner.style.display = "flex";
loadingSpinner.innerHTML = `<span class="pi pi-spin pi-spinner" style="font-size: 18px;"></span> Loading 3D Asset...`;
titleText.textContent = srcUrl.split("/").pop().split("?")[0] || "3D Model";
loadingSpinner.innerHTML = `<span class="pi pi-spin pi-spinner" style="font-size: 18px;"></span> ${t("Loading 3D Asset...")}`;
titleText.textContent = getFilenameFromUrl(srcUrl) || t("3D Model");
THREE = await getThreeLibs();
if (!THREE) {
loadingSpinner.textContent = "Failed to load 3D engine.";
loadingSpinner.innerHTML = `
<div style="text-align: center; max-width: 340px; line-height: 1.4; padding: 6px;">
<span style="color: #f87171; font-weight: bold; font-size: 13px;">${t("Failed to load 3D engine.")}</span><br>
<span style="font-size: 11px; color: #cbd5e1; display: inline-block; margin-top: 4px;">
${t("Unable to download 3D libraries. Make sure your computer is online, or check if <code>--disable-api-nodes</code> is blocking external network requests.")}
</span>
</div>
`;
return;
}
@@ -370,7 +343,19 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
dirLight2.position.set(-5, -5, -5);
scene.add(dirLight2);
gridHelper = new THREE.GridHelper(10, 20, 0x3b82f6, 0x22222a);
let gridPrimaryColor = 0xea580c;
try {
const tempDiv = document.createElement("div");
tempDiv.style.color = "var(--primary, var(--p-primary-color, #ea580c))";
document.body.appendChild(tempDiv);
const rgb = getComputedStyle(tempDiv).color.match(/\d+/g);
tempDiv.remove();
if (rgb && rgb.length >= 3) {
gridPrimaryColor = (Number(rgb[0]) << 16) + (Number(rgb[1]) << 8) + Number(rgb[2]);
}
} catch (e) {}
gridHelper = new THREE.GridHelper(10, 20, gridPrimaryColor, 0x22222a);
gridHelper.position.y = 0;
scene.add(gridHelper);
@@ -381,35 +366,33 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
bgColorInput.oninput = (e) => { scene.background.set(e.target.value); };
const upDirSelect = createSelect([
{ value: "y-up", label: "Original (Y-Up)" },
{ value: "z-up", label: "Z-Up (+90°)" },
{ value: "z-down", label: "Inverted (-90°)" }
{ value: "y-up", label: t("Original (Y-Up)") },
{ value: "z-up", label: t("Z-Up (+90°)") },
{ value: "z-down", label: t("Inverted (-90°)") }
], currentUpDirection, (val) => {
currentUpDirection = val;
applyUpDirection();
});
const matModeSelect = createSelect([
{ value: "original", label: "Original / Textured" },
{ value: "clay", label: "Clay / Studio Matte" },
{ value: "normal", label: "Normals" }
{ value: "original", label: t("Original / Textured") },
{ value: "clay", label: t("Clay / Studio Matte") },
{ value: "normal", label: t("Normals") }
], currentMaterialMode, (val) => {
currentMaterialMode = val;
applyMaterialMode();
});
const camTypeSelect = createSelect([
{ value: "perspective", label: "Perspective" },
{ value: "orthographic", label: "Orthographic" }
{ value: "perspective", label: t("Perspective") },
{ value: "orthographic", label: t("Orthographic") }
], "perspective", (val) => {
const prevPos = camera.position.clone();
const prevTarget = controls.target.clone();
if (val === "orthographic") {
camera = cameraOrtho;
} else {
camera = cameraPersp;
}
if (val === "orthographic") camera = cameraOrtho;
else camera = cameraPersp;
camera.position.copy(prevPos);
controls.object = camera;
controls.target.copy(prevTarget);
@@ -448,40 +431,50 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
lightContainer.append(lightSlider, lightVal);
settingsPanel.append(
createFormGroup("Background Color", bgColorInput),
createFormGroup("Up Direction", upDirSelect),
createFormGroup("Material Mode", matModeSelect),
createFormGroup("Camera Type", camTypeSelect),
createFormGroup("FOV", fovContainer),
createFormGroup("Light Intensity", lightContainer)
createFormGroup(t("Background Color"), bgColorInput),
createFormGroup(t("Up Direction"), upDirSelect),
createFormGroup(t("Material Mode"), matModeSelect),
createFormGroup(t("Camera Type"), camTypeSelect),
createFormGroup(t("FOV"), fovContainer),
createFormGroup(t("Light Intensity"), lightContainer)
);
container.appendChild(settingsPanel);
overlay.container.appendChild(settingsPanel);
const btnGrid = createToolbarBtn("pi pi-table", "Grid", true, (v) => { gridHelper.visible = v; });
const btnRotate = createToolbarBtn("pi pi-sync", "Auto-Rotate", false, (v) => { autoRotate = v; });
const btnWire = createToolbarBtn("pi pi-box", "Wireframe", false, (v) => {
const btnGrid = createToolbarBtn("pi pi-table", t("Grid"), true, (v) => { gridHelper.visible = v; });
const btnRotate = createToolbarBtn("pi pi-sync", t("Auto-Rotate"), false, (v) => { autoRotate = v; });
const btnWire = createToolbarBtn("pi pi-box", t("Wireframe"), false, (v) => {
showWireframe = v;
applyMaterialMode();
});
const btnResetCam = document.createElement("button");
Object.assign(btnResetCam.style, {
background: "transparent", color: "#aaa", border: "1px solid #444",
background: "transparent",
color: "var(--muted-foreground, #aaa)",
border: "1px solid var(--border, var(--border-color, #444))",
borderRadius: "4px", padding: "4px 10px", fontSize: "11px", cursor: "pointer",
display: "flex", alignItems: "center", gap: "6px"
display: "flex", alignItems: "center", gap: "6px", transition: "all 0.15s ease"
});
btnResetCam.innerHTML = `<i class="pi pi-compass"></i><span>Reset View</span>`;
btnResetCam.innerHTML = `<i class="pi pi-compass"></i><span>${t("Reset View")}</span>`;
btnResetCam.onmouseenter = () => {
btnResetCam.style.borderColor = "var(--primary, var(--border-color, #fff))";
btnResetCam.style.color = "var(--foreground, #fff)";
};
btnResetCam.onmouseleave = () => {
btnResetCam.style.borderColor = "var(--border, var(--border-color, #444))";
btnResetCam.style.color = "var(--muted-foreground, #aaa)";
};
btnResetCam.onclick = (e) => {
e.stopPropagation();
if (currentModel) fitCameraToObject(camera, currentModel, controls, THREE);
};
const btnSettings = createToolbarBtn("pi pi-sliders-h", "Settings", false, (v) => {
const btnSettings = createToolbarBtn("pi pi-sliders-h", t("Settings"), false, (v) => {
settingsPanel.style.display = v ? "flex" : "none";
});
const exportSelect = createSelect([
{ value: "", label: "Export As..." },
{ value: "", label: t("Export As...") },
{ value: "OBJ", label: "OBJ (.obj)" },
{ value: "GLB", label: "GLB / GLTF" },
{ value: "STL", label: "STL (.stl)" }
@@ -491,12 +484,12 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
exportSelect.value = "";
}
});
exportSelect.style.background = "#1e293b";
exportSelect.style.borderColor = "#3b82f6";
exportSelect.style.color = "#93c5fd";
exportSelect.style.background = "var(--secondary, var(--card, #1e293b))";
exportSelect.style.borderColor = "var(--primary, var(--p-primary-color, #ea580c))";
exportSelect.style.color = "var(--foreground, #fff)";
toolbar.append(btnGrid, btnWire, btnRotate, btnResetCam, btnSettings, exportSelect);
container.appendChild(toolbar);
overlay.container.appendChild(toolbar);
const onResize = () => {
if (!canvasContainer || !renderer || !cameraPersp || !cameraOrtho) return;
@@ -517,6 +510,7 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
renderer.setSize(width, height);
};
window.addEventListener("resize", onResize);
overlay.addCleanup(() => window.removeEventListener("resize", onResize));
const animate = () => {
animId = requestAnimationFrame(animate);
@@ -533,7 +527,8 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
}
try {
const ext = (srcUrl.split("?")[0].split(".").pop() || "glb").toLowerCase();
const filename = getFilenameFromUrl(srcUrl);
const ext = (filename.split(".").pop() || "glb").toLowerCase();
let loadedObj = null;
if (ext === "obj" && THREE.OBJLoader) {
@@ -542,12 +537,12 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
} else if (ext === "stl" && THREE.STLLoader) {
const loader = new THREE.STLLoader();
const geometry = await loader.loadAsync(srcUrl);
const material = new THREE.MeshStandardMaterial({ color: 0x90caf9, roughness: 0.4, metalness: 0.2 });
const material = new THREE.MeshStandardMaterial({ color: 0xd1d5db, roughness: 0.4, metalness: 0.2 });
loadedObj = new THREE.Mesh(geometry, material);
} else if (ext === "ply" && THREE.PLYLoader) {
const loader = new THREE.PLYLoader();
const geometry = await loader.loadAsync(srcUrl);
const material = new THREE.MeshStandardMaterial({ color: 0x90caf9, roughness: 0.4 });
const material = new THREE.MeshStandardMaterial({ color: 0xd1d5db, roughness: 0.4 });
loadedObj = new THREE.Mesh(geometry, material);
} else if (THREE.GLTFLoader) {
const loader = new THREE.GLTFLoader();
@@ -557,23 +552,18 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
if (loadedObj) {
currentModel = loadedObj;
currentModel.traverse((child) => {
if (child.isMesh && child.material) {
child._originalMaterial = child.material;
}
if (child.isMesh && child.material) child._originalMaterial = child.material;
});
applyMaterialMode();
applyUpDirection();
scene.add(currentModel);
fitCameraToObject(camera, currentModel, controls, THREE);
gridHelper.position.y = new THREE.Box3().setFromObject(currentModel).min.y;
}
} catch (err) {
console.error("Comfy Sidebar: Failed to parse 3D model", err);
loadingSpinner.innerHTML = `<span style="color:#f87171;">Failed to load 3D format</span>`;
loadingSpinner.innerHTML = `<span style="color:#f87171;">${t("Failed to load 3D format")}</span>`;
return;
}
@@ -605,12 +595,12 @@ export function create3DViewer(baseSrc, onSwitchMedia = () => {}, onDestroy = ()
is3D: true,
loadTarget(targetSrc) {
if (!is3DFormat(targetSrc)) {
destroy();
overlay.destroy();
onSwitchMedia(targetSrc);
return;
}
initSceneAndLoad(targetSrc);
},
destroy
destroy: () => overlay.destroy()
};
}
+7 -4
View File
@@ -1,13 +1,16 @@
[project]
name = "comfy-sidebar"
description = "A custom queue sidebar and image comparison extension that reintroduces and improves a sidebar queue menu and unified compact topbar layout for ComfyUI."
version = "1.3.1"
description = "A compact and powerful layout overhaul for ComfyUI that makes generation results easier to browse, preview, compare, and manage."
version = "1.8.2"
license = { file = "LICENSE" }
dependencies = []
dependencies = [
"send2trash>=1.8.0",
]
[project.urls]
Repository = "https://github.com/m0rtus59/ComfyUI-ComfySidebar"
[tool.comfy]
PublisherId = "soundslikethunder"
DisplayName = "Comfy Sidebar"
DisplayName = "Comfy Sidebar"
Icon = "https://raw.githubusercontent.com/m0rtus59/ComfyUI-ComfySidebar/main/assets/icon.png"
+1
View File
@@ -0,0 +1 @@
send2trash>=1.8.0