Compare commits
@@ -0,0 +1,22 @@
|
||||
name: Publish to Comfy Registry
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "pyproject.toml"
|
||||
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Publish Custom Node
|
||||
uses: Comfy-Org/publish-node-action@main
|
||||
with:
|
||||
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
|
||||
@@ -5,7 +5,7 @@ A comprehensive workflow management and generation UI plugin for [ComfyUI](https
|
||||
Browse, organize, and execute workflows directly from a dedicated studio interface — without switching between windows or manually editing JSON.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -13,13 +13,21 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|
||||
| Prompt Tab | Settings Tab |
|
||||
| Prompt Tab | Metadata Tab |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| Nodes Tab | Help & Support Tab |
|
||||
| Settings Tab | Help & Support Tab |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| Nodes Tab | Models Tab |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|
||||
| Gallery Tab | Nodes Tab |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|
||||
| Workflow Studio Library (ComfyUI) | ComfyUI Integration |
|
||||
|:---:|:---:|
|
||||
@@ -32,10 +40,10 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
### Workflow Tab
|
||||
- **Thumbnail / Card / Table views** — switch between view modes to browse your workflow library
|
||||
- **Thumbnail side panel** — preview workflow canvas snapshots in the side panel
|
||||
- **Tag-based filtering** — filter by base model (SD1.5, SDXL, etc.) and custom groups
|
||||
- **Badge filtering** — filter by user-defined badges (free labels you assign to each workflow)
|
||||
- **Search** — full-text search across workflow names and metadata
|
||||
- **Side panel tabs** — Thumbnail preview, JSON viewer with syntax highlighting, and Group management
|
||||
- **Batch analysis** — auto-detect checkpoint, model type, prompt, and I/O node counts
|
||||
- **Badge management** — add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)
|
||||
- **AI summary** — generate workflow descriptions using Ollama
|
||||
- **Import / Export** — import workflows from files or clipboard, open in ComfyUI directly
|
||||
- **Default view setting** — persist your preferred view mode (Thumbnail / Card / Table)
|
||||
@@ -46,16 +54,33 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **Embedded workflow metadata** — workflow JSON is embedded in the PNG (tEXt chunk), compatible with ComfyUI's drag-and-drop import
|
||||
- **Auto-import** — the captured workflow is automatically imported and appears in the Workflow tab
|
||||
|
||||
### GenerateUI Tab
|
||||
- **Auto-generated parameter UI** — prompt, model, sampler, image, and other settings extracted from the workflow
|
||||
### GenerateUI Tab (v0.3.5)
|
||||
- **4-tab layout** — Input / Model / Settings / Feeder tabs; Input, Model, and Settings each include a Raw JSON column on the right for instant preview and direct editing
|
||||
- **Input tab** — Prompt (top) and Image drag-and-drop (bottom) in the left column; Raw JSON (540px) in the right column
|
||||
- **Model tab** — Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter; Raw JSON on the right
|
||||
- **Settings tab** — KSampler and Latent Image side by side at 50% width each; Raw JSON on the right
|
||||
- **Always-visible Raw JSON** — edit the API-format JSON directly from any tab with syntax highlighting; Apply button reloads the workflow
|
||||
- **One-click generation** — queue prompts to ComfyUI without leaving the studio
|
||||
- **Seed control** — randomize, lock, or manually set seeds
|
||||
- **Raw JSON editor** — view and edit the API-format JSON with syntax highlighting
|
||||
- **UI-to-API conversion** — automatic conversion supporting subgraphs (nested workflows), COMBO types, and display-only node exclusion
|
||||
- **Seed control** — randomize, lock, or manually set seeds; seed input and mode selector stacked vertically for readability
|
||||
- **Checkpoint Batch** — enable via checkbox in the right panel to sequentially generate with every checkpoint model; select checkpoints by folder from the dropdown (check a folder to select all its files, expand with ▶ for individual file selection, supports any subfolder depth); Filter input to search; All / None buttons for quick selection; **Pause/Resume** suspends processing between models; Stop aborts after the current generation; amber progress bar tracks per-model progress
|
||||
- **UI-to-API conversion** — automatic conversion supporting subgraphs (nested workflows), COMBO types, and display-only node exclusion; improved analysis covers SDXL multi-hop CONDITIONING chains, CLIPTextEncodeSDXL, SDXLPromptStyler, KSamplerAdvanced, and more
|
||||
- **Eagle integration** — auto-save generated images to [Eagle](https://eagle.cool/) with metadata
|
||||
|
||||
### Feeder subtab (v0.3.5)
|
||||
Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image-feeder)** custom node.
|
||||
- **ImageFeeder node control** — select the target node from a dropdown auto-populated from the loaded workflow; edit all node parameters (Directory, Sort Mode, Index, Start/End Index, Batch Size, Seed, Use Selection) and Apply to the workflow
|
||||
- **Image library** — 3-pane layout: folder tree (left) browsing `user/default/image-loop-data/`, image grid with checkbox selection (center), preview panel with resolution and file size (right)
|
||||
- **Selection management** — check individual images; All / None buttons for the current folder; selected files are reflected in `selected_files` on Apply
|
||||
- **Presets** — save the current directory + selection as a named preset; load or delete presets (server-side persistence via `image-feeder-presets.json`)
|
||||
- **Continuous Run loop** — Run / Stop buttons below the presets; **After gen** mode controls index behavior after each generation:
|
||||
- **Loop** — advance index and wrap back to 0 when all images are exhausted (runs indefinitely)
|
||||
- **Increment** — advance index and auto-stop when all images are consumed
|
||||
- **Fixed** — always use the same index
|
||||
- **Index sync** — after each generation the node returns `next_index` via WebSocket (`image_loop_node_sync`); the Index field updates automatically
|
||||
- **Seed** — Run loop uses the right-pane seed setting (Random / Fixed / Increment / Decrement); the node's own Seed field only affects random sort order
|
||||
|
||||
### Prompt Tab
|
||||
- **3-column layout** — AI Assistant, Presets editor, and Preset Manager displayed side-by-side
|
||||
- **3-column layout** — AI Assistant (left), Presets/Preset Manager tab-panel (center), Wildcard support (right)
|
||||
- **AI chat assistant** — powered by [Ollama](https://ollama.com/), generate and refine prompts interactively
|
||||
- **Image attachment** — attach reference images for vision-capable models
|
||||
- **Translation** — JA/EN/ZH translation buttons for multilingual prompt creation
|
||||
@@ -64,15 +89,48 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **Group management** — create groups, assign/remove presets, delete groups from the Presets panel
|
||||
- **Clipboard copy** — copy positive/negative prompts individually (PP Copy / NP Copy)
|
||||
- **GenUI Set** — apply preset prompts directly to the GenerateUI interface
|
||||
- **Wildcard input toolbar** — one-click buttons to insert `{|}`, `{n$|}`, `__|__`, `<lora::1:LBW=;>` and other wildcard syntax; wraps selected text when applicable
|
||||
- **Wildcard file manager** — create, view, and edit `.txt` / `.yaml` wildcard files stored in `user/default/Workflow-Studio/wildcard/`; click a filename in the file picker to insert `__filename__` at cursor
|
||||
|
||||
### Metadata Tab (v0.3.8)
|
||||
- **3-column layout** — Drop zone (left) | Model info (center) | LoRA + Prompt (right)
|
||||
- **File drop** — drop a ComfyUI-generated PNG / WebP or workflow JSON onto the drop zone (or click to open a file picker); PNG/WebP images are shown as a preview
|
||||
- **Model extraction** — automatically extracts Checkpoint, VAE, Diffusion Model, and Text Encoder names from the workflow; supports both standard and subgraph-based workflows (Flux.2 Dev/Klein, Qwen-Image-Edit/2511/Layered, Z-Image Base/Turbo, Ernie Image, WAN2.2)
|
||||
- **LoRA extraction** — lists all LoRA models with `strength_model / strength_clip` values
|
||||
- **Prompt extraction** — lists prompts with POS / NEG badges when positive/negative can be determined; when distinction is not possible (e.g. `SamplerCustomAdvanced`, intermediate nodes, cross-level connections), prompts are shown without a badge as plain **Text**; click any entry to view the full text below
|
||||
- **Prompt actions** — Copy to clipboard, **GenUI:P/N** (set GenerateUI positive/negative prompt), **Prompt:P/N** (set Prompt tab preset positive/negative)
|
||||
- **Format support** — ComfyUI PNG/WebP/JSON (standard + Flux.2 / Qwen-Image / Z-Image / Ernie Image / WAN2.2 subgraph workflows), SD WebUI, SD Forge, Fooocus
|
||||
- **Format note** — supported formats and covered model types are always shown in the left column
|
||||
|
||||
### Settings Tab
|
||||
- **2-column layout** — left column for all settings; right column shows the Theme panel fixed in place (sticky)
|
||||
- **Collapsible sections** — all settings organized in accordion panels for a clean layout
|
||||
- **Theme selection** — 13 built-in themes with visual swatch preview (Dark, Pop, Minimalist, Cyberpunk, Glassmorphism, Neumorphism, Retro Pixel, Pastel, Brutalism, Earthy, Material, Monotone, Corporate)
|
||||
- **Theme customization** — override colors (background, surface, text, primary, accent), add background patterns (horizontal/vertical/diagonal stripes, polka dot, checkerboard, custom SVG tiling with color/opacity/scale/gap controls), and select from 16 fonts including Japanese display fonts (Google Fonts)
|
||||
- **Workflows directory** — configure which folder to scan for workflows
|
||||
- **Gallery output directory** — configure which output folder the Gallery tab scans for images
|
||||
- **Eagle connection** — set Eagle API endpoint for auto-save
|
||||
- **Ollama connection** — configure Ollama server URL
|
||||
- **Badge display** — toggle metadata badges on workflow cards
|
||||
- **Default workflow** — set a workflow to auto-load on startup
|
||||
- **Data Management** — export all plugin data (settings, metadata, prompts, etc.) to a single JSON file; import to restore data (useful when migrating or reinstalling)
|
||||
- **Wildcard Integration** — link the WFS wildcard directory to ComfyUI-Impact-Pack's `wildcards/` directory (directory junction on Windows, symlink on other OS); existing WFS wildcard files are automatically migrated; requires [ComfyUI-Impact-Pack](https://github.com/ltdrdata/ComfyUI-Impact-Pack)
|
||||
- **Language** — English / Japanese / Chinese
|
||||
|
||||
### Gallery Tab (v0.3.1)
|
||||
- **Image browser** — browse ComfyUI output images (Thumbnail / Table views) with server-side scanning optimized for 6,000+ image libraries
|
||||
- **Thumbnail / Table views** — switch view modes; Favorites column shown leftmost in Table view
|
||||
- **Folder management** — create subfolders ("+ New") or delete the selected folder with all contents ("Del") from the folder tree header
|
||||
- **File operations** — move or delete individual images from the detail panel's Info tab; bulk Move To... and Delete from the multi-select bar
|
||||
- **Multi-select** — Ctrl+click to select multiple images; Bulk Bar appears for batch operations (group, favorite, move, delete)
|
||||
- **Server-side filtering** — filter by group, favorites, or tags with fast server-side set lookup (no full rescan)
|
||||
- **Group management** — create, rename, delete groups and assign/remove images using the same 4-section panel as Models tab
|
||||
- **Favorites** — star images inline without reopening the detail panel
|
||||
- **Detail panel** — view filename, path, tags, groups, and metadata in a slide-out panel
|
||||
- **Workflow viewer** — Metadata tab displays workflow JSON from PNG embedded data (`prompt` / `workflow` keys) or from workflow saved by the Generate UI tab
|
||||
- **Workflow auto-save** — images generated from the Generate UI tab have their workflow automatically saved to gallery metadata
|
||||
- **Output folder configurable** — set the scanned output folder from Settings tab
|
||||
- **Performance** — folder-level mtime cache (30s TTL) for fast incremental refresh; tree expansion state preserved across folder operations
|
||||
|
||||
### Nodes Tab (v0.1.7)
|
||||
- **Node Browser** — browse all installed ComfyUI nodes from `/object_info` API with Card/Table views
|
||||
- **Search & Filter** — full-text search, filter by category, package, tags, groups, and favorites
|
||||
@@ -81,9 +139,28 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **Node Sets** — save multiple nodes + connections as reusable sets from the ComfyUI canvas
|
||||
- **Right-click context menu** — "Save as Node Set" option on any node in ComfyUI
|
||||
|
||||
### Workflow Studio Library (ComfyUI Side Panel) (v0.1.8)
|
||||
- **Workflows tab** — browse favorite workflows, filter by model type, filter by group
|
||||
- **Nodes tab** — browse favorite nodes, node sets, and node groups
|
||||
### Models Tab (v0.2.3)
|
||||
- **Model Browser** — browse all installed ComfyUI models (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding) with sub-tab switching
|
||||
- **Thumbnail / Card / Table views** — switch between view modes with pagination (24 items per page)
|
||||
- **Search & Filter** — full-text search, filter by tags, groups, and favorites
|
||||
- **User-defined badges** — assign free-label badges to models; badge colors shared with the Workflow tab palette
|
||||
- **Side panel tabs** — Info (file path display with click-to-copy, tags, memo), Groups management, CivitAI integration
|
||||
- **CivitAI integration** — fetch model metadata by SHA256 hash, view base model, trained words, tags, and model page link
|
||||
- **Batch CivitAI fetch** — one-click batch fetch for all models of a type with SSE progress streaming
|
||||
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload
|
||||
- **GenUI Model button** — apply the selected model directly to the corresponding node in GenerateUI's current workflow (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder)
|
||||
- **Group management** — create, rename, delete groups and assign/remove models; groups are scoped per model type (checkpoint groups only appear in the Checkpoint tab)
|
||||
- **Table view memo** — memo column displayed in table view for quick reference
|
||||
- **Preview images** — auto-detect `{model_stem}.preview.png` next to model files
|
||||
- **Enable / Disable models** — hide models from ComfyUI by renaming the file extension (`.disabled` suffix); toggle per card (⏸ button), per group (Enable All / Disable All), or filter by status (All / Enabled / Disabled)
|
||||
- **Multi-select & bulk operations** — enter selection mode to check multiple models; bulk action bar supports add/remove from groups and permanent file deletion (model file + preview images + sidecar files such as `.json` / `.info`)
|
||||
|
||||
### Workflow Studio Library (ComfyUI Side Panel) (v0.2.5)
|
||||
- **Workflows tab** — browse favorite workflows (All / ★ Favorites / Groups / By Badge sub-tabs), ★ star shown for favorites in All view
|
||||
- **Nodes tab** — browse favorite nodes (All / ★ Favorites / Groups / Sets / 📂 Category / 🧩 Package sub-tabs), ★ star shown for favorites in All view
|
||||
- **Category sub-tab** — dropdown to filter nodes by top-level category
|
||||
- **Package sub-tab** — dropdown to filter nodes by custom node package name
|
||||
- **Models tab** — browse installed models (All / ★ Favorites / Groups / By Type sub-tabs)
|
||||
- **Prompts tab** — browse prompt presets with All / Favorites / Categories sub-tabs
|
||||
- **Drag & drop workflows** — drag a workflow onto the canvas to load it
|
||||
- **Drag & drop nodes** — drag nodes/node sets onto the canvas to place them
|
||||
@@ -91,6 +168,7 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **Copy prompts** — copy individual positive (P) or negative (N) prompts from sidebar items
|
||||
- **Double-click** — load workflows or place nodes without dragging
|
||||
- **Search** — search within each sub-tab to quickly find items
|
||||
- **⚙ Theme settings** — customize panel background, sub-header background, text, border, and secondary text colors; saved to localStorage and applied on every open
|
||||
|
||||
### Help & Support Tab (v0.1.3)
|
||||
- **Feature list** — overview of all features organized by tab
|
||||
@@ -167,6 +245,101 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
|
||||
|
||||
## Changelog
|
||||
|
||||
### v0.3.8
|
||||
- **Metadata Tab: extended subgraph support** — added extraction for Flux.2 Dev fp8 (`SamplerCustomAdvanced`), Flux.2 Klein 4B Distilled (image edit), Ernie Image, Qwen-Image-Edit 2511 (`TextEncodeQwenImageEditPlus`), and WAN2.2 14B Animate (top-level CLIPTextEncode + subgraph KSampler)
|
||||
- **Prompt type: Text (no badge)** — when positive/negative polarity cannot be determined (indirect sampler connections, cross-level links, `PrimitiveStringMultiline` etc.), prompts are listed without a POS/NEG badge; action buttons still work normally
|
||||
- **Prompt extraction improvements** — `extractPromptsFromNodeSet` now resolves link sources from any STRING-output node (e.g. `ComfySwitchNode`, `PrimitiveStringMultiline`) without type restriction; `PrimitiveStringMultiline` search and final text-encoder fallback both extended to include subgraph nodes via `collectAllNodes`
|
||||
- **i18n** — added `metaPromptText` key (EN: "Text" / JA: "テキスト" / ZH: "文本")
|
||||
|
||||
### v0.3.7
|
||||
- **Metadata Tab: subgraph workflow support** — Flux.2 (Dev fp8 / Klein), Qwen-Image-Edit (/ 2511 / Layered), and Z-Image (Base / Turbo) official templates now correctly extract models and prompts; these use ComfyUI's `definitions.subgraphs` format with `UNETLoader`, `CLIPLoader`, and `VAELoader` inside the subgraph
|
||||
- **Prompt extraction improvements** — 7-stage fallback chain: ImageMetadataPromptLoader → WFS_PromptText → top-level CLIPTextEncode+KSampler → `PrimitiveStringMultiline` (flux2-klein) → subgraph CLIPTextEncode+KSampler → PromptStyler → all CLIPTextEncode text
|
||||
- **MarkdownNote model fallback** — `extractMarkdownNoteModels()` parses `**section** → - [model](url)` patterns from MarkdownNote nodes as a supplemental model source
|
||||
- **Format note updated** — "Flux.2 / Qwen-Image / Z-Image subgraph workflows supported" (EN/JA/ZH)
|
||||
|
||||
### v0.3.6
|
||||
- **Metadata Tab** — new tab (between Prompt and Gallery) that extracts model and prompt information from ComfyUI-generated PNG/WebP images and workflow JSON files; 3-column layout: drop zone with image preview (left), Checkpoint/VAE/Diffusion Model/Text Encoder lists (center), LoRA list with strength values + Prompt list with full-text viewer (right)
|
||||
- **Prompt action buttons** — Copy, GenUI:P/N (set GenerateUI prompts), Prompt:P/N (set Prompt tab preset prompts) directly from the extracted prompt text
|
||||
- **SDXL Prompt Styler support** — improved prompt extraction resolves `PromptStyler → CLIPTextEncode` link chains in both LiteGraph and API workflow formats
|
||||
- **Format support** — ComfyUI (PNG/WebP/JSON), SD WebUI, SD Forge, Fooocus
|
||||
|
||||
### v0.3.5
|
||||
- **Feeder subtab** — new subtab in GenerateUI for controlling [comfyui-image-feeder](https://github.com/ketle-man/comfyui-image-feeder) nodes; left pane: node selector + all ImageFeeder parameters + presets + Run/Stop controls; center pane: folder tree, image grid with checkbox selection, and preview panel
|
||||
- **Run loop with After gen modes** — Loop (wrap and continue), Increment (advance and auto-stop), Fixed (constant index); index updates automatically via WebSocket `image_loop_node_sync` after each generation; seed comes from the right-pane seed setting
|
||||
- **Workflow analysis improvements** — `analyzeWorkflow` now handles multi-hop CONDITIONING chains via BFS (up to 5 iterations), CLIPTextEncodeSDXL / CLIPTextEncodeSDXLRefiner, SDXLPromptStyler / SDXLPromptStylerAdvanced, KSamplerAdvanced (`noise_seed`), TextEncodeQwenImageEditPlus, PrimitiveStringMultiline, Power Lora Loader (rgthree), and `Checkpoint Loader` (WAS) with space in the class name
|
||||
|
||||
### v0.3.4
|
||||
- **Wildcard support panel** — new right column in the Prompt tab with a one-click toolbar for inserting wildcard syntax (`{|}`, `{n$|}`, `__|__`, `:`, `;`, `$`, `<lora::1:LBW=;>`, `[]`, single/multi pick) and wrapping selected text; dedicated prompt textarea and wildcard file picker (click to insert `__filename__`)
|
||||
- **Wildcard file manager** — create, view, edit, and delete `.txt` / `.yaml` wildcard files stored in `user/default/Workflow-Studio/wildcard/`; editor opens inline with filename input and save/cancel controls
|
||||
- **Preset/Preset Manager tab switch** — the center pane of the Prompt tab is now a two-tab panel (Presets / Preset Manager) to reclaim horizontal space for the new wildcard panel
|
||||
- **Wildcard Integration setting** — new accordion section in Settings tab; auto-detects ComfyUI-Impact-Pack; when installed, provides a button to create a directory junction (Windows) or symlink (other OS) from the WFS wildcard directory to Impact Pack's `wildcards/` directory; existing WFS files are migrated automatically; a Remove Link button reverses the operation
|
||||
|
||||
### v0.3.2
|
||||
- **Checkpoint Batch** — new panel in the GenerateUI right column (below Seed, above results); enable via checkbox to auto-generate once per checkpoint model; filter included/excluded subfolders by comma-separated names (empty = all checkpoints); real-time preview of matched model count; amber progress bar shows current model name and index; Stop button aborts the loop after the current generation completes; failed models are counted and reported in the summary toast
|
||||
- **Seed layout fix** — seed value input and mode selector (Random / Fixed / Increment / Decrement) now stacked vertically so neither is clipped in narrow panels
|
||||
|
||||
### v0.3.1
|
||||
- **Folder operations** — create subfolders and delete folders (with all contents) directly from the folder tree header buttons
|
||||
- **File operations** — move or delete individual images from the detail panel; bulk move and bulk delete from the multi-select bar
|
||||
- **Tree state preserved** — folder expansion state is maintained after create/delete/move/refresh operations
|
||||
- **Workflow viewer improved** — Metadata tab now reads both `prompt` (API format, the default for most ComfyUI-generated images) and `workflow` (UI format) keys from PNG metadata, covering virtually all ComfyUI output
|
||||
- **Workflow auto-save** — after each generation in the Generate UI tab, the current workflow is automatically saved to gallery metadata for the generated images; shown in the Metadata tab even if PNG embedding is absent
|
||||
|
||||
### v0.3.0
|
||||
- **Cross-type group filter** — the group filter dropdown in the Models tab now shows groups from all model types simultaneously, each prefixed with a type label (`[Checkpoint]`, `[LoRA]`, etc.); selecting a group automatically switches to the corresponding model type
|
||||
- **Sidebar group display fixed** — the ComfyUI sidebar "Model Groups" view now correctly renders per-type groups (introduced in v0.2.9) with a type label on each group header; fixes a crash where `.filter is not a function` was thrown on the new nested group structure
|
||||
|
||||
### v0.2.9
|
||||
- **Model Enable/Disable** — hide models from ComfyUI by renaming the file extension to `.disabled`; toggle per model (⏸ button on each card/row), per group (Enable All / Disable All buttons in the Group panel), or filter the grid by status (All / Enabled only / Disabled only). Changes take effect after ComfyUI refresh.
|
||||
- **Per-type model groups** — groups are now scoped to each model type; checkpoint groups only appear in the Checkpoint tab, LoRA groups only in the LoRA tab, etc. Existing flat groups are automatically migrated.
|
||||
- **Multi-select mode** — click the Select button in the toolbar to enter selection mode; check individual models across Thumbnail / Card / Table views
|
||||
- **Bulk group operations** — with models selected, add or remove them from any group in one click, or create a new group and add them simultaneously
|
||||
- **Bulk file delete** — permanently delete selected model files along with all associated preview images and sidecar files (`.json`, `.civitai.info`, `.info`); requires confirmation before deleting
|
||||
- **Bug fix** — models in subdirectories could not be disabled due to a path-doubling error; fixed by computing the rename target from `path.name` instead of `model_name`
|
||||
- **Bug fix** — Hypernetwork tab showed `C`, `O`, `M`, `B` as fake model items; caused by the new ComfyUI API format returning `"COMBO"` as the first element; fixed in `comfyui-client.js`
|
||||
|
||||
### v0.2.8
|
||||
- **Data storage moved** — plugin data (settings, metadata, prompts, etc.) is now stored in `ComfyUI/user/default/Workflow-Studio/` instead of `custom_nodes/ComfyUI-Workflow-Studio/data/`; falls back to the old `data/` directory if `user/default/` does not exist
|
||||
- **Data Management section** — new Settings tab section to export all plugin data to a single JSON file and import it back; useful for migration, backup, and reinstallation
|
||||
|
||||
### v0.2.7
|
||||
- **Gallery tab** — new image browser for ComfyUI output folder; Thumbnail/Table views, multi-select with Bulk Bar, server-side group/tag/favorite filtering, group management (rename support), performance-optimized with + mtime folder cache
|
||||
- **Group UI unified** — Workflow, Nodes, and Gallery group panels rebuilt to match the Models tab 4-section pattern (Current Groups / Add to Group / Create New Group / Manage Groups); Rename support added to Workflow and Nodes tabs
|
||||
- **Settings 2-column layout** — Theme panel fixed on the right (50% width, sticky); all other settings flow continuously on the left with no visual gap
|
||||
- **Gallery output directory setting** — configure the output folder scanned by Gallery tab from Settings
|
||||
- **Help tab** — Gallery tab description card added
|
||||
|
||||
### v0.2.5
|
||||
- **Sidebar Category/Package sub-tabs** — added 📂 Category and 🧩 Package sub-tabs to the Nodes tab in Workflow Studio Library; each shows a dropdown to filter nodes by category or custom node package (reads `/object_info` for accurate package detection)
|
||||
- **Sidebar theme settings** — added ⚙ button in the panel header to customize background, sub-header background, text, border, and secondary text colors with live preview; settings saved to localStorage
|
||||
- **Sidebar TextEncoder (By Type)** — fixed TextEncoder not appearing in Models → By Type; now uses `DualCLIPLoader` → `CLIPLoader` fallback to retrieve `clip_name1` list
|
||||
- **Hide `.index.json`** — excluded `.index.json` from both the Workflow tab and the Workflow Studio Library side panel
|
||||
|
||||
### v0.2.4
|
||||
- **GenerateUI tab redesign** — reorganized from 5 tabs (Prompt/Image/Model/Settings/Raw JSON) to 3 tabs (Input/Model/Settings); each tab shows a Raw JSON column (540px) for instant JSON preview and direct editing from any tab
|
||||
- **Input tab** — Prompt and Image stacked vertically in the left column
|
||||
- **Settings tab** — KSampler and LatentImage stacked vertically in the left column
|
||||
- **Raw JSON tab removed** — Raw JSON is now always visible as a right-column panel within each tab
|
||||
|
||||
### v0.2.3
|
||||
- **Badge system unified** — Workflow and Models tabs now share a single badge palette (`⚙ Badge` button); workflow auto-analysis model type system removed in favor of user-defined free-label badges
|
||||
- **GenUI Model button** — apply any model from the Models tab directly to the corresponding node in GenerateUI's current workflow (available in detail modal and side panel; Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)
|
||||
- **Sidebar Models tab** — added All / ★ Favorites / Groups / By Type sub-tabs to the Models section of Workflow Studio Library
|
||||
- **Sidebar All views** — ★ star displayed for favorite items in Workflows and Nodes All sub-tabs
|
||||
- **Sidebar panel width** — widened from 280px to 310px
|
||||
|
||||
### v0.2.2
|
||||
- **Models tab** — browse, search, and manage all installed ComfyUI models (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder) with Thumbnail/Card/Table views
|
||||
- **CivitAI integration** — fetch model metadata by SHA256 hash (individual or batch per model type) with SSE progress streaming
|
||||
- **Model groups** — create, rename, delete groups and assign/remove models for organization
|
||||
- **Model metadata** — persistent favorites, tags, memo, and SHA256 hash per model
|
||||
- **Preview images** — auto-detect and display preview images, change via file upload in detail modal
|
||||
- **Table view memo column** — memo displayed in table view with compact subdir/extension columns
|
||||
- **Side panel file path** — display full file path with click-to-copy in model info panel
|
||||
- **Node card redesign** — removed package badge, added left border color-coding by package
|
||||
- **Toolbar pagination** — pagination controls moved to toolbar for all tabs (Models, Workflows, Nodes)
|
||||
- **Help tab updated** — Models Tab section added to feature list
|
||||
|
||||
### v0.2.0
|
||||
- **Prompt presets in sidebar** — added Prompts tab to Workflow Studio Library (ComfyUI side panel) with All / Favorites / Categories sub-tabs
|
||||
- **WFS_PromptText custom node** — drag prompt presets onto the canvas to create nodes with positive/negative prompt outputs
|
||||
@@ -237,6 +410,7 @@ ComfyUI-Workflow-Studio/
|
||||
│ ├── routes/
|
||||
│ │ ├── workflow_routes.py # Workflow CRUD & analysis API
|
||||
│ │ ├── nodes_routes.py # Nodes metadata & node sets API
|
||||
│ │ ├── models_routes.py # Model metadata, preview, CivitAI API
|
||||
│ │ ├── prompts_routes.py # Prompt presets CRUD API
|
||||
│ │ ├── settings_routes.py # Settings API
|
||||
│ │ ├── ollama_routes.py # Ollama proxy API
|
||||
@@ -244,12 +418,14 @@ ComfyUI-Workflow-Studio/
|
||||
│ └── services/
|
||||
│ ├── workflow_service.py # Workflow file operations
|
||||
│ ├── nodes_service.py # Node metadata & node sets
|
||||
│ ├── models_service.py # Model metadata & preview images
|
||||
│ ├── civitai_service.py # CivitAI API integration & cache
|
||||
│ ├── prompts_service.py # Prompt presets persistence
|
||||
│ ├── workflow_analyzer.py # Model/node detection
|
||||
│ ├── settings_service.py # Settings persistence
|
||||
│ └── png_extractor.py # PNG metadata extraction
|
||||
├── templates/
|
||||
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Settings/Help)
|
||||
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Metadata/Gallery/Nodes/Models/Settings/Help)
|
||||
├── static/
|
||||
│ ├── favicon.svg # Browser tab icon (W+S Wave)
|
||||
│ ├── css/main.css # Styles
|
||||
@@ -257,10 +433,13 @@ ComfyUI-Workflow-Studio/
|
||||
│ ├── app.js # App initialization & routing
|
||||
│ ├── workflow-tab.js # Workflow browser
|
||||
│ ├── generate-tab.js # Generation UI
|
||||
│ ├── feeder-tab.js # Feeder subtab (ImageFeeder node control + image library)
|
||||
│ ├── prompt-tab.js # AI assistant & presets
|
||||
│ ├── metadata-tab.js # Metadata extraction & display (PNG/WebP/JSON)
|
||||
│ ├── settings-tab.js # Settings panel
|
||||
│ ├── comfyui-client.js # ComfyUI WebSocket/API client
|
||||
│ ├── nodes-tab.js # Node browser & node sets
|
||||
│ ├── models-tab.js # Model browser & CivitAI integration
|
||||
│ ├── comfyui-workflow.js # UI-to-API format conversion
|
||||
│ ├── comfyui-editor.js # Dynamic parameter editor
|
||||
│ ├── json-highlight.js # JSON syntax highlighting
|
||||
@@ -268,7 +447,7 @@ ComfyUI-Workflow-Studio/
|
||||
├── web/comfyui/
|
||||
│ ├── top_menu_extension.js # ComfyUI menu bar integration
|
||||
│ └── node_sets_menu.js # Workflow Studio Library side panel
|
||||
└── data/ # Metadata & settings storage (incl. prompts.json)
|
||||
└── data/ # Fallback data dir (used when ComfyUI user/default/ is not found)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2100 900" fill="none">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="2100" y2="900" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#1a1a2e"/>
|
||||
<stop offset="50%" stop-color="#16213e"/>
|
||||
<stop offset="100%" stop-color="#1a1a2e"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="wStroke" x1="0" y1="0" x2="600" y2="600" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#4a9eff"/>
|
||||
<stop offset="100%" stop-color="#7b68ee"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sWave" x1="0" y1="0" x2="600" y2="600" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#7b68ee"/>
|
||||
<stop offset="100%" stop-color="#4a9eff"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="textGrad" x1="0" y1="0" x2="1200" y2="0" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#e0e0ff"/>
|
||||
<stop offset="100%" stop-color="#b0b0d0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<!-- Background -->
|
||||
<rect width="2100" height="900" fill="url(#bg)"/>
|
||||
<!-- Subtle grid -->
|
||||
<line x1="0" y1="225" x2="2100" y2="225" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="0" y1="450" x2="2100" y2="450" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="0" y1="675" x2="2100" y2="675" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<!-- Decorative wave lines in background -->
|
||||
<path d="M0 750 Q262 700 525 750 Q787 800 1050 750 Q1312 700 1575 750 Q1837 800 2100 750" stroke="#4a9eff" stroke-opacity="0.08" stroke-width="2" fill="none"/>
|
||||
<path d="M0 780 Q262 730 525 780 Q787 830 1050 780 Q1312 730 1575 780 Q1837 830 2100 780" stroke="#7b68ee" stroke-opacity="0.06" stroke-width="2" fill="none"/>
|
||||
<!-- W+S Logo (left side) -->
|
||||
<g transform="translate(180, 180)">
|
||||
<!-- W -->
|
||||
<path d="M60 80 L120 280 L180 130 L240 280 L300 80" stroke="url(#wStroke)" stroke-width="26" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
||||
<!-- S wave -->
|
||||
<path d="M80 340 Q140 300 200 340 Q260 380 320 340" stroke="url(#sWave)" stroke-width="18" stroke-linecap="round" fill="none"/>
|
||||
</g>
|
||||
<!-- Title text -->
|
||||
<text x="720" y="380" font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-size="120" font-weight="700" fill="url(#textGrad)" letter-spacing="-2">Workflow Studio</text>
|
||||
<!-- Subtitle -->
|
||||
<text x="720" y="470" font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-size="42" fill="#8888aa" letter-spacing="1">Workflow Management & Generation UI for ComfyUI</text>
|
||||
<!-- Feature pills -->
|
||||
<g font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-size="28" fill="#a0a0c0">
|
||||
<rect x="720" y="530" width="200" height="44" rx="22" fill="#4a9eff" fill-opacity="0.12" stroke="#4a9eff" stroke-opacity="0.3" stroke-width="1"/>
|
||||
<text x="820" y="559" text-anchor="middle" fill="#4a9eff">Workflows</text>
|
||||
<rect x="940" y="530" width="200" height="44" rx="22" fill="#7b68ee" fill-opacity="0.12" stroke="#7b68ee" stroke-opacity="0.3" stroke-width="1"/>
|
||||
<text x="1040" y="559" text-anchor="middle" fill="#7b68ee">GenerateUI</text>
|
||||
<rect x="1160" y="530" width="200" height="44" rx="22" fill="#4a9eff" fill-opacity="0.12" stroke="#4a9eff" stroke-opacity="0.3" stroke-width="1"/>
|
||||
<text x="1260" y="559" text-anchor="middle" fill="#4a9eff">AI Prompts</text>
|
||||
<rect x="1380" y="530" width="180" height="44" rx="22" fill="#7b68ee" fill-opacity="0.12" stroke="#7b68ee" stroke-opacity="0.3" stroke-width="1"/>
|
||||
<text x="1470" y="559" text-anchor="middle" fill="#7b68ee">Themes</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.7 KiB |
@@ -0,0 +1,29 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 400" fill="none">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="400" y2="400" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#1a1a2e"/>
|
||||
<stop offset="100%" stop-color="#16213e"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="wStroke" x1="0" y1="0" x2="400" y2="400" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#4a9eff"/>
|
||||
<stop offset="100%" stop-color="#7b68ee"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="sWave" x1="0" y1="0" x2="400" y2="400" gradientUnits="userSpaceOnUse">
|
||||
<stop offset="0%" stop-color="#7b68ee"/>
|
||||
<stop offset="100%" stop-color="#4a9eff"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<!-- Background -->
|
||||
<rect width="400" height="400" rx="48" fill="url(#bg)"/>
|
||||
<!-- Subtle grid pattern -->
|
||||
<line x1="0" y1="100" x2="400" y2="100" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="0" y1="200" x2="400" y2="200" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="0" y1="300" x2="400" y2="300" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="100" y1="0" x2="100" y2="400" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="200" y1="0" x2="200" y2="400" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<line x1="300" y1="0" x2="300" y2="400" stroke="#ffffff" stroke-opacity="0.03" stroke-width="1"/>
|
||||
<!-- W letterform -->
|
||||
<path d="M80 110 L140 290 L200 150 L260 290 L320 110" stroke="url(#wStroke)" stroke-width="28" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
|
||||
<!-- S wave -->
|
||||
<path d="M100 330 Q150 295 200 330 Q250 365 300 330" stroke="url(#sWave)" stroke-width="20" stroke-linecap="round" fill="none"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 975 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 1.7 MiB |
@@ -10,13 +10,22 @@ PLUGIN_DIR = Path(__file__).resolve().parent.parent
|
||||
# Directory paths
|
||||
TEMPLATES_DIR = PLUGIN_DIR / "templates"
|
||||
STATIC_DIR = PLUGIN_DIR / "static"
|
||||
DATA_DIR = PLUGIN_DIR / "data"
|
||||
|
||||
# Default workflows directory: ComfyUI's user/default/workflows
|
||||
# PLUGIN_DIR is custom_nodes/ComfyUI-Workflow-Studio
|
||||
# ComfyUI root is custom_nodes/../../ = two levels up
|
||||
_COMFYUI_ROOT = PLUGIN_DIR.parent.parent
|
||||
_COMFYUI_WORKFLOWS = _COMFYUI_ROOT / "user" / "default" / "workflows"
|
||||
COMFYUI_ROOT = _COMFYUI_ROOT # exposed for external use
|
||||
|
||||
# Data directory: prefer ComfyUI's user/default/Workflow-Studio/, fallback to plugin data/
|
||||
_COMFYUI_USER_DEFAULT = _COMFYUI_ROOT / "user" / "default"
|
||||
if _COMFYUI_USER_DEFAULT.is_dir():
|
||||
DATA_DIR = _COMFYUI_USER_DEFAULT / "Workflow-Studio"
|
||||
logger.info("Workflow Studio: Using user data dir: %s", DATA_DIR)
|
||||
else:
|
||||
DATA_DIR = PLUGIN_DIR / "data"
|
||||
logger.info("Workflow Studio: user/default not found, using plugin data dir: %s", DATA_DIR)
|
||||
|
||||
# Default workflows directory: ComfyUI's user/default/workflows
|
||||
_COMFYUI_WORKFLOWS = _COMFYUI_USER_DEFAULT / "workflows"
|
||||
|
||||
# Use ComfyUI workflows dir if it exists, otherwise fallback to plugin data dir
|
||||
if _COMFYUI_WORKFLOWS.is_dir():
|
||||
@@ -58,3 +67,5 @@ SETTINGS_FILE = DATA_DIR / "settings.json"
|
||||
NODE_METADATA_FILE = DATA_DIR / "node_metadata.json"
|
||||
NODE_SETS_FILE = DATA_DIR / "node_sets.json"
|
||||
PROMPTS_FILE = DATA_DIR / "prompts.json"
|
||||
MODEL_METADATA_FILE = DATA_DIR / "model_metadata.json"
|
||||
WILDCARD_DIR = DATA_DIR / "wildcard"
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
"""
|
||||
Gallery Routes - ギャラリータブ用APIエンドポイント
|
||||
"""
|
||||
import json
|
||||
import mimetypes
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from aiohttp import web
|
||||
|
||||
from ..config import DATA_DIR
|
||||
from ..services.gallery_service import GalleryService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_service = GalleryService(DATA_DIR)
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
app.router.add_get("/wfm/gallery/folders", list_folders)
|
||||
app.router.add_get("/wfm/gallery/images", list_images)
|
||||
app.router.add_get("/wfm/gallery/image/meta", get_image_meta)
|
||||
app.router.add_get("/wfm/gallery/image/workflow", get_image_workflow)
|
||||
app.router.add_get("/wfm/gallery/image/serve", serve_image)
|
||||
app.router.add_post("/wfm/gallery/image/meta", save_image_meta)
|
||||
app.router.add_post("/wfm/gallery/image/favorite", toggle_favorite)
|
||||
app.router.add_get("/wfm/gallery/groups", list_groups)
|
||||
app.router.add_post("/wfm/gallery/groups", create_group)
|
||||
app.router.add_put("/wfm/gallery/groups/{name}", rename_group)
|
||||
app.router.add_delete("/wfm/gallery/groups/{name}", delete_group)
|
||||
app.router.add_post("/wfm/gallery/groups/{name}/add", add_to_group)
|
||||
app.router.add_post("/wfm/gallery/groups/{name}/remove", remove_from_group)
|
||||
app.router.add_get("/wfm/gallery/groups/{name}/images", list_group_images)
|
||||
# フォルダ・ファイル操作
|
||||
app.router.add_post("/wfm/gallery/folder", create_folder_route)
|
||||
app.router.add_delete("/wfm/gallery/folder", delete_folder_route)
|
||||
app.router.add_post("/wfm/gallery/images/delete", delete_images_route)
|
||||
app.router.add_post("/wfm/gallery/images/move", move_images_route)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# フォルダツリー
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def list_folders(request: web.Request) -> web.Response:
|
||||
root = request.rel_url.query.get("root", "")
|
||||
if not root:
|
||||
return web.json_response({"error": "root parameter required"}, status=400)
|
||||
try:
|
||||
tree = _service.list_folder_tree(root)
|
||||
return web.json_response(tree)
|
||||
except Exception as e:
|
||||
logger.error("list_folders error: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像一覧
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def list_images(request: web.Request) -> web.Response:
|
||||
folder = request.rel_url.query.get("folder", "")
|
||||
search = request.rel_url.query.get("search", "")
|
||||
sort_by = request.rel_url.query.get("sort", "date_desc")
|
||||
favorite_only = request.rel_url.query.get("favorite", "false") == "true"
|
||||
tag_filter = request.rel_url.query.get("tag", "")
|
||||
group_filter = request.rel_url.query.get("group", "")
|
||||
|
||||
if not folder:
|
||||
return web.json_response({"error": "folder parameter required"}, status=400)
|
||||
|
||||
try:
|
||||
images = _service.list_images(
|
||||
folder,
|
||||
search=search,
|
||||
sort_by=sort_by,
|
||||
favorite_only=favorite_only,
|
||||
tag_filter=tag_filter,
|
||||
group_filter=group_filter,
|
||||
)
|
||||
return web.json_response({"images": images, "total": len(images)})
|
||||
except Exception as e:
|
||||
logger.error("list_images error: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像メタデータ
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def get_image_meta(request: web.Request) -> web.Response:
|
||||
path = request.rel_url.query.get("path", "")
|
||||
if not path:
|
||||
return web.json_response({"error": "path required"}, status=400)
|
||||
try:
|
||||
meta = _service.get_image_metadata(path)
|
||||
return web.json_response(meta)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def get_image_workflow(request: web.Request) -> web.Response:
|
||||
path = request.rel_url.query.get("path", "")
|
||||
if not path:
|
||||
return web.json_response({"error": "path required"}, status=400)
|
||||
try:
|
||||
wf = _service.extract_workflow_from_metadata(path)
|
||||
if wf is None:
|
||||
return web.json_response({"workflow": None, "has_workflow": False})
|
||||
return web.json_response({"workflow": wf, "has_workflow": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def serve_image(request: web.Request) -> web.Response:
|
||||
path = request.rel_url.query.get("path", "")
|
||||
if not path:
|
||||
return web.Response(status=400)
|
||||
|
||||
img_path = _service.serve_image(path)
|
||||
if img_path is None:
|
||||
return web.Response(status=404)
|
||||
|
||||
content_type, _ = mimetypes.guess_type(str(img_path))
|
||||
return web.FileResponse(img_path, headers={
|
||||
"Content-Type": content_type or "image/png",
|
||||
"Cache-Control": "max-age=3600",
|
||||
})
|
||||
|
||||
|
||||
async def save_image_meta(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
img_path = body.get("path", "")
|
||||
if not img_path:
|
||||
return web.json_response({"error": "path required"}, status=400)
|
||||
data = {k: v for k, v in body.items() if k != "path"}
|
||||
ok = _service.save_image_meta(img_path, data)
|
||||
return web.json_response({"ok": ok})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def toggle_favorite(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
img_path = body.get("path", "")
|
||||
if not img_path:
|
||||
return web.json_response({"error": "path required"}, status=400)
|
||||
new_val = _service.toggle_favorite(img_path)
|
||||
return web.json_response({"favorite": new_val})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# グループ管理
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def list_groups(request: web.Request) -> web.Response:
|
||||
return web.json_response({"groups": _service.list_groups()})
|
||||
|
||||
|
||||
async def create_group(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
name = body.get("name", "").strip()
|
||||
if not name:
|
||||
return web.json_response({"error": "name required"}, status=400)
|
||||
ok = _service.create_group(name)
|
||||
if not ok:
|
||||
return web.json_response({"error": "Group already exists"}, status=409)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def rename_group(request: web.Request) -> web.Response:
|
||||
"""PUT /wfm/gallery/groups/{name} - グループ名変更"""
|
||||
try:
|
||||
old_name = request.match_info.get("name", "")
|
||||
body = await request.json()
|
||||
new_name = body.get("new_name", "").strip()
|
||||
if not old_name or not new_name:
|
||||
return web.json_response({"error": "old_name and new_name required"}, status=400)
|
||||
ok = _service.rename_group(old_name, new_name)
|
||||
if not ok:
|
||||
return web.json_response({"error": "Rename failed (not found or name conflict)"}, status=400)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def delete_group(request: web.Request) -> web.Response:
|
||||
name = request.match_info.get("name", "")
|
||||
ok = _service.delete_group(name)
|
||||
return web.json_response({"ok": ok})
|
||||
|
||||
|
||||
async def add_to_group(request: web.Request) -> web.Response:
|
||||
try:
|
||||
name = request.match_info.get("name", "")
|
||||
body = await request.json()
|
||||
img_path = body.get("path", "")
|
||||
ok = _service.add_to_group(img_path, name)
|
||||
return web.json_response({"ok": ok})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def remove_from_group(request: web.Request) -> web.Response:
|
||||
try:
|
||||
name = request.match_info.get("name", "")
|
||||
body = await request.json()
|
||||
img_path = body.get("path", "")
|
||||
ok = _service.remove_from_group(img_path, name)
|
||||
return web.json_response({"ok": ok})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def list_group_images(request: web.Request) -> web.Response:
|
||||
name = request.match_info.get("name", "")
|
||||
images = _service.list_images_in_group(name)
|
||||
return web.json_response({"images": images})
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# フォルダ・ファイル操作
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def create_folder_route(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/folder - 新規フォルダ作成"""
|
||||
try:
|
||||
body = await request.json()
|
||||
parent = body.get("parent", "")
|
||||
name = body.get("name", "").strip()
|
||||
if not parent or not name:
|
||||
return web.json_response({"ok": False, "error": "parent and name required"}, status=400)
|
||||
result = _service.create_folder(parent, name)
|
||||
return web.json_response(result, status=200 if result["ok"] else 400)
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def delete_folder_route(request: web.Request) -> web.Response:
|
||||
"""DELETE /wfm/gallery/folder - フォルダ削除"""
|
||||
try:
|
||||
body = await request.json()
|
||||
folder = body.get("path", "")
|
||||
if not folder:
|
||||
return web.json_response({"ok": False, "error": "path required"}, status=400)
|
||||
result = _service.delete_folder(folder)
|
||||
return web.json_response(result, status=200 if result["ok"] else 400)
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def delete_images_route(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/images/delete - 画像削除(単体・複数)"""
|
||||
try:
|
||||
body = await request.json()
|
||||
paths = body.get("paths", [])
|
||||
if not paths:
|
||||
return web.json_response({"deleted": [], "errors": ["paths required"]}, status=400)
|
||||
result = _service.delete_images(paths)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"deleted": [], "errors": [str(e)]}, status=500)
|
||||
|
||||
|
||||
async def move_images_route(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/images/move - 画像移動(単体・複数)"""
|
||||
try:
|
||||
body = await request.json()
|
||||
paths = body.get("paths", [])
|
||||
dest = body.get("dest", "")
|
||||
if not paths or not dest:
|
||||
return web.json_response({"moved": [], "errors": ["paths and dest required"]}, status=400)
|
||||
result = _service.move_images(paths, dest)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"moved": [], "errors": [str(e)]}, status=500)
|
||||
@@ -0,0 +1,531 @@
|
||||
"""Model metadata API routes."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import mimetypes
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from ..services.models_service import ModelsService
|
||||
from ..services.civitai_service import CivitaiService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_service = ModelsService()
|
||||
_civitai = CivitaiService()
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
"""Register all model management API routes."""
|
||||
app.router.add_get("/api/wfm/models/metadata", handle_get_metadata)
|
||||
app.router.add_post("/api/wfm/models/metadata", handle_save_metadata)
|
||||
app.router.add_get("/api/wfm/models/preview", handle_get_preview)
|
||||
app.router.add_get("/api/wfm/models/groups", handle_get_groups)
|
||||
app.router.add_post("/api/wfm/models/groups", handle_save_groups)
|
||||
app.router.add_post("/api/wfm/models/civitai/fetch", handle_civitai_fetch)
|
||||
app.router.add_get("/api/wfm/models/civitai/cache", handle_civitai_cache)
|
||||
app.router.add_post("/api/wfm/models/civitai/batch", handle_civitai_batch)
|
||||
app.router.add_post("/api/wfm/models/change-preview", handle_change_preview)
|
||||
app.router.add_get("/api/wfm/models/filepath", handle_get_filepath)
|
||||
app.router.add_get("/api/wfm/models/disabled", handle_get_disabled)
|
||||
app.router.add_post("/api/wfm/models/toggle", handle_toggle_model)
|
||||
app.router.add_post("/api/wfm/models/group-toggle", handle_toggle_group)
|
||||
app.router.add_post("/api/wfm/models/delete", handle_delete_models)
|
||||
|
||||
|
||||
# ── Model Metadata ─────────────────────────────────────────
|
||||
|
||||
|
||||
async def handle_get_metadata(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/metadata"""
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.get_all_metadata)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error loading model metadata: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_save_metadata(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/metadata"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_name = body.get("modelName", "")
|
||||
if not model_name:
|
||||
return web.json_response({"error": "modelName is required"}, status=400)
|
||||
updates = {k: v for k, v in body.items() if k != "modelName"}
|
||||
result = await asyncio.to_thread(_service.update_metadata, model_name, updates)
|
||||
return web.json_response({"status": "ok", "metadata": result})
|
||||
except Exception as e:
|
||||
logger.error("Error saving model metadata: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ── Model Groups ──────────────────────────────────────────
|
||||
|
||||
|
||||
async def handle_get_groups(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/groups?type=checkpoint"""
|
||||
model_type = request.query.get("type", "")
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.get_model_groups, model_type or None)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error loading model groups: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_save_groups(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/groups
|
||||
|
||||
Body: { "model_type": "checkpoint", "groups": { "groupName": [...] } }
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_type = body.get("model_type", "")
|
||||
groups = body.get("groups", {})
|
||||
if not model_type:
|
||||
return web.json_response({"error": "model_type required"}, status=400)
|
||||
result = await asyncio.to_thread(_service.save_model_groups, groups, model_type)
|
||||
return web.json_response({"status": "ok", "groups": result})
|
||||
except Exception as e:
|
||||
logger.error("Error saving model groups: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ── CivitAI Integration ──────────────────────────────────
|
||||
|
||||
|
||||
async def handle_civitai_fetch(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/civitai/fetch
|
||||
|
||||
Body: { "type": "checkpoint", "name": "model.safetensors" }
|
||||
Calculates SHA256 hash and fetches model info from CivitAI.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_type = body.get("type", "")
|
||||
model_name = body.get("name", "")
|
||||
if not model_type or not model_name:
|
||||
return web.json_response({"error": "type and name required"}, status=400)
|
||||
if ".." in model_name:
|
||||
return web.json_response({"error": "Invalid model name"}, status=400)
|
||||
|
||||
# Resolve file path
|
||||
from ..services.models_service import _get_model_dirs
|
||||
dirs = _get_model_dirs(model_type)
|
||||
file_path = None
|
||||
for d in dirs:
|
||||
candidate = d / model_name
|
||||
if candidate.is_file():
|
||||
file_path = candidate
|
||||
break
|
||||
|
||||
if not file_path:
|
||||
return web.json_response({"error": "Model file not found"}, status=404)
|
||||
|
||||
# Check if we already have a cached hash in metadata
|
||||
meta = _service.get_all_metadata()
|
||||
model_meta = meta.get(model_name, {})
|
||||
sha256 = model_meta.get("sha256")
|
||||
|
||||
if not sha256:
|
||||
# Calculate hash (can be slow for large files)
|
||||
sha256 = await asyncio.to_thread(
|
||||
CivitaiService.calculate_sha256, file_path
|
||||
)
|
||||
if not sha256:
|
||||
return web.json_response({"error": "Failed to calculate hash"}, status=500)
|
||||
# Cache the hash in model metadata
|
||||
await asyncio.to_thread(
|
||||
_service.update_metadata, model_name, {"sha256": sha256}
|
||||
)
|
||||
|
||||
# Fetch from CivitAI
|
||||
info = await asyncio.to_thread(_civitai.fetch_by_hash, sha256)
|
||||
if not info:
|
||||
return web.json_response({
|
||||
"status": "not_found",
|
||||
"sha256": sha256,
|
||||
"message": "Model not found on CivitAI"
|
||||
})
|
||||
|
||||
return web.json_response({
|
||||
"status": "ok",
|
||||
"sha256": sha256,
|
||||
"civitai": info,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error("CivitAI fetch error: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_civitai_cache(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/civitai/cache - Return all cached CivitAI data."""
|
||||
try:
|
||||
result = await asyncio.to_thread(_civitai.get_all_cached)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error loading CivitAI cache: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_civitai_batch(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/civitai/batch - SSE stream for batch CivitAI fetch.
|
||||
|
||||
Body: { "type": "checkpoint", "models": ["model1.safetensors", ...] }
|
||||
Streams SSE events: progress, result, done.
|
||||
"""
|
||||
import json as _json
|
||||
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return web.Response(status=400, text="Invalid JSON body")
|
||||
|
||||
model_type = body.get("type", "")
|
||||
model_names = body.get("models", [])
|
||||
if not model_type or not model_names:
|
||||
return web.Response(status=400, text="type and models required")
|
||||
|
||||
# Resolve file paths
|
||||
from ..services.models_service import _get_model_dirs
|
||||
dirs = _get_model_dirs(model_type)
|
||||
model_files = []
|
||||
for name in model_names:
|
||||
if ".." in name:
|
||||
continue
|
||||
for d in dirs:
|
||||
p = d / name
|
||||
if p.is_file():
|
||||
model_files.append((name, p))
|
||||
break
|
||||
|
||||
if not model_files:
|
||||
return web.Response(status=404, text="No model files found")
|
||||
|
||||
# Set up SSE response
|
||||
response = web.StreamResponse(
|
||||
status=200,
|
||||
headers={
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
},
|
||||
)
|
||||
await response.prepare(request)
|
||||
|
||||
def send_sse(event, data):
|
||||
"""Format SSE message (returns bytes)."""
|
||||
msg = f"event: {event}\ndata: {_json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
return msg.encode("utf-8")
|
||||
|
||||
# Run batch fetch in thread with progress callback via queue
|
||||
import queue
|
||||
progress_q = queue.Queue()
|
||||
|
||||
def on_progress(current, total, model_name, status):
|
||||
progress_q.put({"current": current, "total": total, "model": model_name, "status": status})
|
||||
|
||||
# Start batch in background thread
|
||||
loop = asyncio.get_event_loop()
|
||||
fetch_task = loop.run_in_executor(None, _civitai.batch_fetch, model_files, on_progress)
|
||||
|
||||
# Stream progress events
|
||||
import time as _time
|
||||
|
||||
while not fetch_task.done():
|
||||
# Drain queue
|
||||
while not progress_q.empty():
|
||||
try:
|
||||
p = progress_q.get_nowait()
|
||||
await response.write(send_sse("progress", p))
|
||||
except queue.Empty:
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
# Drain remaining events
|
||||
while not progress_q.empty():
|
||||
try:
|
||||
p = progress_q.get_nowait()
|
||||
await response.write(send_sse("progress", p))
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
# Get results and update metadata
|
||||
results = fetch_task.result()
|
||||
meta_updates = {}
|
||||
for model_name, result in results.items():
|
||||
sha256 = result.get("sha256")
|
||||
if sha256:
|
||||
meta_updates[model_name] = sha256
|
||||
|
||||
# Bulk update sha256 in metadata
|
||||
if meta_updates:
|
||||
all_meta = _service.get_all_metadata()
|
||||
for mname, sha in meta_updates.items():
|
||||
if mname not in all_meta:
|
||||
all_meta[mname] = {"tags": [], "favorite": False, "memo": ""}
|
||||
all_meta[mname]["sha256"] = sha
|
||||
_service._save_metadata(all_meta)
|
||||
|
||||
# Send final result
|
||||
summary = {
|
||||
"total": len(model_files),
|
||||
"found": sum(1 for r in results.values() if r.get("civitai")),
|
||||
"not_found": sum(1 for r in results.values() if r.get("sha256") and not r.get("civitai")),
|
||||
"errors": sum(1 for r in results.values() if r.get("error")),
|
||||
"hashes": {name: r.get("sha256") for name, r in results.items() if r.get("sha256")},
|
||||
}
|
||||
await response.write(send_sse("done", summary))
|
||||
await response.write_eof()
|
||||
return response
|
||||
|
||||
|
||||
# ── Model Preview Image ───────────────────────────────────
|
||||
|
||||
|
||||
async def handle_get_preview(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/preview?type=checkpoint&name=model.safetensors"""
|
||||
model_type = request.query.get("type", "")
|
||||
model_name = request.query.get("name", "")
|
||||
if not model_type or not model_name:
|
||||
return web.Response(status=400, text="type and name are required")
|
||||
|
||||
# Security: reject path traversal
|
||||
if ".." in model_name:
|
||||
return web.Response(status=400, text="Invalid model name")
|
||||
|
||||
try:
|
||||
preview_path = await asyncio.to_thread(
|
||||
_service.find_preview_image, model_type, model_name
|
||||
)
|
||||
if not preview_path:
|
||||
return web.Response(status=404)
|
||||
|
||||
content_type, _ = mimetypes.guess_type(str(preview_path))
|
||||
return web.FileResponse(
|
||||
preview_path,
|
||||
headers={"Content-Type": content_type or "image/png",
|
||||
"Cache-Control": "public, max-age=3600"},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Error serving model preview: %s", e)
|
||||
return web.Response(status=500, text=str(e))
|
||||
|
||||
|
||||
async def handle_change_preview(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/change-preview - Upload/change model preview image.
|
||||
|
||||
Multipart form: type, name, file
|
||||
Saves as {model_stem}.preview.png next to the model file.
|
||||
"""
|
||||
from pathlib import Path as _Path
|
||||
|
||||
try:
|
||||
reader = await request.multipart()
|
||||
model_type = None
|
||||
model_name = None
|
||||
image_data = None
|
||||
|
||||
while True:
|
||||
part = await reader.next()
|
||||
if part is None:
|
||||
break
|
||||
if part.name == "type":
|
||||
model_type = (await part.read()).decode("utf-8")
|
||||
elif part.name == "name":
|
||||
model_name = (await part.read()).decode("utf-8")
|
||||
elif part.name == "file":
|
||||
image_data = await part.read()
|
||||
|
||||
if not model_type or not model_name:
|
||||
return web.json_response({"error": "type and name required"}, status=400)
|
||||
if ".." in model_name:
|
||||
return web.json_response({"error": "Invalid model name"}, status=400)
|
||||
if image_data is None:
|
||||
return web.json_response({"error": "file required"}, status=400)
|
||||
|
||||
# Resolve model file path
|
||||
from ..services.models_service import _get_model_dirs
|
||||
dirs = _get_model_dirs(model_type)
|
||||
model_path = None
|
||||
for d in dirs:
|
||||
candidate = d / model_name
|
||||
if candidate.is_file():
|
||||
model_path = candidate
|
||||
break
|
||||
|
||||
if not model_path:
|
||||
return web.json_response({"error": "Model file not found"}, status=404)
|
||||
|
||||
# Save as {stem}.preview.png next to model file
|
||||
preview_path = model_path.parent / (model_path.stem + ".preview.png")
|
||||
|
||||
def _write():
|
||||
with open(preview_path, "wb") as f:
|
||||
f.write(image_data)
|
||||
|
||||
await asyncio.to_thread(_write)
|
||||
logger.info("Saved preview image: %s", preview_path)
|
||||
|
||||
return web.json_response({"status": "ok"})
|
||||
except Exception as e:
|
||||
logger.error("Error changing model preview: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_get_filepath(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/filepath?type=checkpoint&name=model.safetensors
|
||||
|
||||
Returns the full file path of the model.
|
||||
"""
|
||||
model_type = request.query.get("type", "")
|
||||
model_name = request.query.get("name", "")
|
||||
if not model_type or not model_name:
|
||||
return web.json_response({"error": "type and name required"}, status=400)
|
||||
if ".." in model_name:
|
||||
return web.json_response({"error": "Invalid model name"}, status=400)
|
||||
|
||||
try:
|
||||
from ..services.models_service import _get_model_dirs
|
||||
dirs = _get_model_dirs(model_type)
|
||||
for d in dirs:
|
||||
candidate = d / model_name
|
||||
if candidate.is_file():
|
||||
return web.json_response({"path": str(candidate)})
|
||||
return web.json_response({"error": "Model file not found"}, status=404)
|
||||
except Exception as e:
|
||||
logger.error("Error resolving model filepath: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ── Model Enable / Disable ────────────────────────────────
|
||||
|
||||
|
||||
async def handle_get_disabled(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/disabled?type=checkpoint
|
||||
|
||||
Returns list of disabled model names (normalized, without .disabled suffix).
|
||||
"""
|
||||
model_type = request.query.get("type", "")
|
||||
if not model_type:
|
||||
return web.json_response({"error": "type required"}, status=400)
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.scan_disabled_models, model_type)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error scanning disabled models: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_toggle_model(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/toggle
|
||||
|
||||
Body: { "model_type": "checkpoint", "model_name": "v1-5.safetensors", "enabled": false }
|
||||
Renames the model file to add/remove .disabled suffix.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_type = body.get("model_type", "")
|
||||
model_name = body.get("model_name", "")
|
||||
enabled = body.get("enabled", True)
|
||||
|
||||
if not model_type or not model_name:
|
||||
return web.json_response({"error": "model_type and model_name required"}, status=400)
|
||||
if ".." in model_name:
|
||||
return web.json_response({"error": "Invalid model name"}, status=400)
|
||||
|
||||
if enabled:
|
||||
await asyncio.to_thread(_service.enable_model, model_type, model_name)
|
||||
else:
|
||||
await asyncio.to_thread(_service.disable_model, model_type, model_name)
|
||||
|
||||
return web.json_response({"status": "ok", "enabled": enabled})
|
||||
except FileNotFoundError as e:
|
||||
return web.json_response({"error": str(e)}, status=404)
|
||||
except OSError as e:
|
||||
logger.error("OS error toggling model: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
except Exception as e:
|
||||
logger.error("Error toggling model: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_toggle_group(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/group-toggle
|
||||
|
||||
Body: { "model_type": "checkpoint", "group_name": "MyGroup", "enabled": true }
|
||||
Enables or disables all models belonging to the specified group.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_type = body.get("model_type", "")
|
||||
group_name = body.get("group_name", "")
|
||||
enabled = body.get("enabled", True)
|
||||
|
||||
if not model_type or not group_name:
|
||||
return web.json_response({"error": "model_type and group_name required"}, status=400)
|
||||
|
||||
groups = await asyncio.to_thread(_service.get_model_groups, model_type)
|
||||
members = groups.get(group_name, [])
|
||||
|
||||
ok_list = []
|
||||
error_list = []
|
||||
for model_name in members:
|
||||
if ".." in model_name:
|
||||
continue
|
||||
try:
|
||||
if enabled:
|
||||
await asyncio.to_thread(_service.enable_model, model_type, model_name)
|
||||
else:
|
||||
await asyncio.to_thread(_service.disable_model, model_type, model_name)
|
||||
ok_list.append(model_name)
|
||||
except Exception as e:
|
||||
error_list.append({"model": model_name, "error": str(e)})
|
||||
|
||||
return web.json_response({
|
||||
"status": "ok",
|
||||
"enabled": enabled,
|
||||
"ok": ok_list,
|
||||
"errors": error_list,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error("Error toggling group: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_delete_models(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/delete
|
||||
|
||||
Body: { "model_type": "checkpoint", "model_names": ["a.safetensors", "b.safetensors"] }
|
||||
Deletes each model file and associated preview/sidecar files, then removes metadata.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_type = body.get("model_type", "")
|
||||
model_names = body.get("model_names", [])
|
||||
|
||||
if not model_type or not isinstance(model_names, list) or not model_names:
|
||||
return web.json_response({"error": "model_type and model_names[] required"}, status=400)
|
||||
|
||||
ok_list = []
|
||||
error_list = []
|
||||
for model_name in model_names:
|
||||
if ".." in str(model_name):
|
||||
error_list.append({"model": model_name, "error": "Invalid model name"})
|
||||
continue
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.delete_model, model_type, model_name)
|
||||
ok_list.append({"model": model_name, "deleted": result["deleted"]})
|
||||
logger.info("Deleted model: %s (%s files)", model_name, len(result["deleted"]))
|
||||
except FileNotFoundError as e:
|
||||
error_list.append({"model": model_name, "error": str(e)})
|
||||
except Exception as e:
|
||||
logger.error("Error deleting model %s: %s", model_name, e)
|
||||
error_list.append({"model": model_name, "error": str(e)})
|
||||
|
||||
return web.json_response({"status": "ok", "ok": ok_list, "errors": error_list})
|
||||
except Exception as e:
|
||||
logger.error("Error in delete_models: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
@@ -1,18 +1,30 @@
|
||||
"""Settings API routes."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from ..services.settings_service import SettingsService
|
||||
from ..config import DEFAULT_WORKFLOWS_DIR
|
||||
from ..config import DEFAULT_WORKFLOWS_DIR, DATA_DIR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_service = SettingsService()
|
||||
|
||||
# Data files included in export/import
|
||||
_DATA_FILES = [
|
||||
"settings.json",
|
||||
"metadata.json",
|
||||
"node_metadata.json",
|
||||
"node_sets.json",
|
||||
"prompts.json",
|
||||
"model_metadata.json",
|
||||
"gallery_metadata.json",
|
||||
]
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
"""Register settings API routes."""
|
||||
@@ -20,6 +32,10 @@ def setup_routes(app: web.Application):
|
||||
app.router.add_post("/api/wfm/settings", handle_post)
|
||||
app.router.add_get("/api/wfm/settings/workflows-dir", handle_get_workflows_dir)
|
||||
app.router.add_post("/api/wfm/settings/workflows-dir", handle_set_workflows_dir)
|
||||
app.router.add_get("/api/wfm/settings/output-dir", handle_get_output_dir)
|
||||
app.router.add_post("/api/wfm/settings/output-dir", handle_set_output_dir)
|
||||
app.router.add_get("/api/wfm/settings/export", handle_export)
|
||||
app.router.add_post("/api/wfm/settings/import", handle_import)
|
||||
|
||||
|
||||
async def handle_get(request: web.Request) -> web.Response:
|
||||
@@ -92,3 +108,129 @@ async def handle_set_workflows_dir(request: web.Request) -> web.Response:
|
||||
except Exception as e:
|
||||
logger.error("Error setting workflows dir: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
def _get_comfyui_output_dir() -> str:
|
||||
"""ComfyUIのデフォルトoutputフォルダを取得する。"""
|
||||
try:
|
||||
import folder_paths # type: ignore
|
||||
return str(folder_paths.get_output_directory())
|
||||
except Exception:
|
||||
pass
|
||||
# fallback: config.pyのCOMFYUI_ROOTから推測
|
||||
from ..config import PLUGIN_DIR
|
||||
comfyui_root = PLUGIN_DIR.parent.parent
|
||||
output_dir = comfyui_root / "output"
|
||||
if output_dir.is_dir():
|
||||
return str(output_dir)
|
||||
return ""
|
||||
|
||||
|
||||
async def handle_get_output_dir(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/settings/output-dir - Get gallery output directory."""
|
||||
try:
|
||||
server_settings = await asyncio.to_thread(_service.load)
|
||||
saved = server_settings.get("gallery_output_dir", "").strip()
|
||||
default_dir = await asyncio.to_thread(_get_comfyui_output_dir)
|
||||
return web.json_response({
|
||||
"current": saved or default_dir,
|
||||
"default": default_dir,
|
||||
"saved": saved,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error("Error getting output dir: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_set_output_dir(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/settings/output-dir - Save gallery output directory."""
|
||||
try:
|
||||
body = await request.json()
|
||||
new_dir = body.get("gallery_output_dir", "").strip()
|
||||
await asyncio.to_thread(_service.update, {"gallery_output_dir": new_dir})
|
||||
|
||||
default_dir = await asyncio.to_thread(_get_comfyui_output_dir)
|
||||
resolved = new_dir or default_dir
|
||||
|
||||
# GalleryServiceの許可ルートを更新
|
||||
from ..routes.gallery_routes import _service as gallery_service
|
||||
gallery_service.update_output_root(resolved)
|
||||
|
||||
return web.json_response({
|
||||
"status": "ok",
|
||||
"current": resolved,
|
||||
"default": default_dir,
|
||||
"saved": new_dir,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error("Error setting output dir: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
def _load_data_file(filename: str):
|
||||
"""Load a single data file, return empty dict/list if missing."""
|
||||
path = DATA_DIR / filename
|
||||
if not path.exists():
|
||||
return None
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _build_export_bundle() -> dict:
|
||||
"""Collect all data files into a single export bundle."""
|
||||
bundle = {"__version": 1, "__source": "ComfyUI-Workflow-Studio"}
|
||||
for filename in _DATA_FILES:
|
||||
data = _load_data_file(filename)
|
||||
if data is not None:
|
||||
bundle[filename] = data
|
||||
return bundle
|
||||
|
||||
|
||||
async def handle_export(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/settings/export - Download all data as a single JSON bundle."""
|
||||
try:
|
||||
bundle = await asyncio.to_thread(_build_export_bundle)
|
||||
body = json.dumps(bundle, ensure_ascii=False, indent=2)
|
||||
return web.Response(
|
||||
body=body.encode("utf-8"),
|
||||
content_type="application/json",
|
||||
headers={"Content-Disposition": 'attachment; filename="wfm-data-export.json"'},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Error exporting data: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
def _apply_import_bundle(bundle: dict) -> dict:
|
||||
"""Write imported bundle back to individual data files. Returns summary."""
|
||||
summary = {"imported": [], "skipped": []}
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
for filename in _DATA_FILES:
|
||||
if filename not in bundle:
|
||||
summary["skipped"].append(filename)
|
||||
continue
|
||||
try:
|
||||
path = DATA_DIR / filename
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(bundle[filename], f, ensure_ascii=False, indent=2)
|
||||
summary["imported"].append(filename)
|
||||
except Exception as e:
|
||||
logger.error("Import failed for %s: %s", filename, e)
|
||||
summary["skipped"].append(filename)
|
||||
return summary
|
||||
|
||||
|
||||
async def handle_import(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/settings/import - Upload and restore a JSON bundle."""
|
||||
try:
|
||||
bundle = await request.json()
|
||||
if not isinstance(bundle, dict):
|
||||
return web.json_response({"error": "Invalid bundle format"}, status=400)
|
||||
summary = await asyncio.to_thread(_apply_import_bundle, bundle)
|
||||
return web.json_response({"status": "ok", **summary})
|
||||
except Exception as e:
|
||||
logger.error("Error importing data: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Wildcard file management API routes."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from ..config import DATA_DIR, COMFYUI_ROOT
|
||||
from ..services.wildcard_service import WildcardService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_service = WildcardService(DATA_DIR / "wildcard")
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
app.router.add_get("/api/wfm/wildcards", handle_list)
|
||||
app.router.add_get("/api/wfm/wildcards/content", handle_get_content)
|
||||
app.router.add_post("/api/wfm/wildcards/save", handle_save)
|
||||
app.router.add_post("/api/wfm/wildcards/delete", handle_delete)
|
||||
app.router.add_get("/api/wfm/wildcards/link-status", handle_link_status)
|
||||
app.router.add_post("/api/wfm/wildcards/create-link", handle_create_link)
|
||||
app.router.add_post("/api/wfm/wildcards/remove-link", handle_remove_link)
|
||||
|
||||
|
||||
async def handle_list(request: web.Request) -> web.Response:
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.list_wildcards)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error listing wildcards: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_get_content(request: web.Request) -> web.Response:
|
||||
filename = request.rel_url.query.get("filename", "")
|
||||
try:
|
||||
content = await asyncio.to_thread(_service.get_content, filename)
|
||||
return web.json_response({"content": content})
|
||||
except FileNotFoundError:
|
||||
return web.json_response({"error": "not found"}, status=404)
|
||||
except Exception as e:
|
||||
logger.error("Error getting wildcard content: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_save(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
filename = body.get("filename", "")
|
||||
content = body.get("content", "")
|
||||
result = await asyncio.to_thread(_service.save_file, filename, content)
|
||||
return web.json_response({"status": "ok", "file": result})
|
||||
except Exception as e:
|
||||
logger.error("Error saving wildcard: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_delete(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
filename = body.get("filename", "")
|
||||
await asyncio.to_thread(_service.delete_file, filename)
|
||||
return web.json_response({"status": "ok"})
|
||||
except Exception as e:
|
||||
logger.error("Error deleting wildcard: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_link_status(request: web.Request) -> web.Response:
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.get_link_status, COMFYUI_ROOT)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error getting wildcard link status: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_create_link(request: web.Request) -> web.Response:
|
||||
try:
|
||||
result = await asyncio.to_thread(_service.create_link, COMFYUI_ROOT)
|
||||
return web.json_response({"status": "ok", **result})
|
||||
except RuntimeError as e:
|
||||
return web.json_response({"error": str(e)}, status=400)
|
||||
except Exception as e:
|
||||
logger.error("Error creating wildcard link: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_remove_link(request: web.Request) -> web.Response:
|
||||
try:
|
||||
await asyncio.to_thread(_service.remove_link)
|
||||
return web.json_response({"status": "ok"})
|
||||
except RuntimeError as e:
|
||||
return web.json_response({"error": str(e)}, status=400)
|
||||
except Exception as e:
|
||||
logger.error("Error removing wildcard link: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
@@ -0,0 +1,206 @@
|
||||
"""CivitAI API integration service."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import URLError, HTTPError
|
||||
|
||||
from ..config import DATA_DIR
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CIVITAI_API_BASE = "https://civitai.com/api/v1"
|
||||
CIVITAI_CACHE_FILE = DATA_DIR / "civitai_cache.json"
|
||||
|
||||
|
||||
class CivitaiService:
|
||||
"""Fetch and cache CivitAI model metadata."""
|
||||
|
||||
def __init__(self):
|
||||
self._cache = None
|
||||
|
||||
def _load_cache(self):
|
||||
if self._cache is not None:
|
||||
return self._cache
|
||||
if CIVITAI_CACHE_FILE.exists():
|
||||
try:
|
||||
with open(CIVITAI_CACHE_FILE, "r", encoding="utf-8") as f:
|
||||
self._cache = json.load(f)
|
||||
return self._cache
|
||||
except Exception:
|
||||
pass
|
||||
self._cache = {}
|
||||
return self._cache
|
||||
|
||||
def _save_cache(self):
|
||||
CIVITAI_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(CIVITAI_CACHE_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(self._cache, f, ensure_ascii=False, indent=2)
|
||||
|
||||
def get_cached(self, sha256_hash):
|
||||
"""Return cached CivitAI data for a given hash, or None."""
|
||||
cache = self._load_cache()
|
||||
return cache.get(sha256_hash)
|
||||
|
||||
def get_all_cached(self):
|
||||
"""Return the full cache dict."""
|
||||
return self._load_cache()
|
||||
|
||||
@staticmethod
|
||||
def calculate_sha256(file_path, chunk_size=65536):
|
||||
"""Calculate SHA256 hash of a file."""
|
||||
h = hashlib.sha256()
|
||||
path = Path(file_path)
|
||||
if not path.is_file():
|
||||
return None
|
||||
with open(path, "rb") as f:
|
||||
while True:
|
||||
chunk = f.read(chunk_size)
|
||||
if not chunk:
|
||||
break
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def fetch_by_hash(self, sha256_hash):
|
||||
"""Fetch model version info from CivitAI by SHA256 hash.
|
||||
|
||||
Returns dict with model info, or None if not found.
|
||||
Caches successful results.
|
||||
"""
|
||||
# Check cache first
|
||||
cache = self._load_cache()
|
||||
if sha256_hash in cache:
|
||||
return cache[sha256_hash]
|
||||
|
||||
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash}"
|
||||
try:
|
||||
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
|
||||
with urlopen(req, timeout=15) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
if not data or "id" not in data:
|
||||
return None
|
||||
|
||||
# Extract useful fields
|
||||
info = self._extract_info(data)
|
||||
cache[sha256_hash] = info
|
||||
self._save_cache()
|
||||
return info
|
||||
|
||||
except HTTPError as e:
|
||||
if e.code == 404:
|
||||
logger.debug("CivitAI: model not found for hash %s", sha256_hash[:16])
|
||||
return None
|
||||
logger.warning("CivitAI API error: %s %s", e.code, e.reason)
|
||||
return None
|
||||
except (URLError, Exception) as e:
|
||||
logger.warning("CivitAI request failed: %s", e)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _extract_info(data):
|
||||
"""Extract relevant fields from CivitAI API response."""
|
||||
model = data.get("model", {})
|
||||
images = data.get("images", [])
|
||||
files = data.get("files", [])
|
||||
|
||||
# Get primary file info
|
||||
primary_file = None
|
||||
for f in files:
|
||||
if f.get("primary"):
|
||||
primary_file = f
|
||||
break
|
||||
if not primary_file and files:
|
||||
primary_file = files[0]
|
||||
|
||||
# Get image URLs (first 5)
|
||||
image_urls = []
|
||||
for img in images[:5]:
|
||||
url = img.get("url", "")
|
||||
if url:
|
||||
# Optimize for thumbnail
|
||||
optimized = url.replace("/original=true", "/width=450,optimized=true")
|
||||
image_urls.append(optimized)
|
||||
|
||||
return {
|
||||
"versionId": data.get("id"),
|
||||
"modelId": model.get("id"),
|
||||
"modelName": model.get("name", ""),
|
||||
"versionName": data.get("name", ""),
|
||||
"type": model.get("type", ""),
|
||||
"description": data.get("description") or model.get("description", ""),
|
||||
"tags": model.get("tags", []),
|
||||
"nsfw": model.get("nsfw", False),
|
||||
"creator": data.get("creator", {}).get("username", ""),
|
||||
"images": image_urls,
|
||||
"trainedWords": data.get("trainedWords", []),
|
||||
"baseModel": data.get("baseModel", ""),
|
||||
"fileSize": primary_file.get("sizeKB", 0) if primary_file else 0,
|
||||
"downloadUrl": data.get("downloadUrl", ""),
|
||||
"modelUrl": f"https://civitai.com/models/{model.get('id', '')}?modelVersionId={data.get('id', '')}",
|
||||
}
|
||||
|
||||
def batch_fetch(self, model_files, progress_callback=None):
|
||||
"""Batch fetch CivitAI info for multiple model files.
|
||||
|
||||
Args:
|
||||
model_files: list of (model_name, file_path) tuples
|
||||
progress_callback: fn(current, total, model_name, status) called per model
|
||||
|
||||
Returns: dict of { model_name: { sha256, civitai_info_or_none } }
|
||||
"""
|
||||
import time
|
||||
|
||||
results = {}
|
||||
total = len(model_files)
|
||||
cache = self._load_cache()
|
||||
|
||||
for i, (model_name, file_path) in enumerate(model_files):
|
||||
if progress_callback:
|
||||
progress_callback(i, total, model_name, "hashing")
|
||||
|
||||
# Calculate hash
|
||||
sha256 = self.calculate_sha256(file_path)
|
||||
if not sha256:
|
||||
results[model_name] = {"sha256": None, "civitai": None, "error": "hash_failed"}
|
||||
continue
|
||||
|
||||
results[model_name] = {"sha256": sha256, "civitai": None}
|
||||
|
||||
# Check cache
|
||||
if sha256 in cache:
|
||||
results[model_name]["civitai"] = cache[sha256]
|
||||
if progress_callback:
|
||||
progress_callback(i, total, model_name, "cached")
|
||||
continue
|
||||
|
||||
# Fetch from API
|
||||
if progress_callback:
|
||||
progress_callback(i, total, model_name, "fetching")
|
||||
|
||||
info = self.fetch_by_hash(sha256)
|
||||
if info:
|
||||
results[model_name]["civitai"] = info
|
||||
|
||||
if progress_callback:
|
||||
status = "found" if info else "not_found"
|
||||
progress_callback(i, total, model_name, status)
|
||||
|
||||
# Rate limit: small delay between API calls
|
||||
time.sleep(0.5)
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(total, total, "", "done")
|
||||
|
||||
return results
|
||||
|
||||
def clear_cache(self, sha256_hash=None):
|
||||
"""Clear cache for a specific hash or all."""
|
||||
cache = self._load_cache()
|
||||
if sha256_hash:
|
||||
cache.pop(sha256_hash, None)
|
||||
else:
|
||||
cache.clear()
|
||||
self._save_cache()
|
||||
@@ -0,0 +1,142 @@
|
||||
"""
|
||||
Gallery Metadata Store - ギャラリー画像のメタデータ永続化
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GalleryMetadataStore:
|
||||
"""
|
||||
gallery_metadata.json の構造:
|
||||
{
|
||||
"images": {
|
||||
"<abs_path>": {
|
||||
"favorite": bool,
|
||||
"tags": [str, ...],
|
||||
"memo": str,
|
||||
"groups": [str, ...]
|
||||
}
|
||||
},
|
||||
"groups": [
|
||||
{"name": str}
|
||||
]
|
||||
}
|
||||
"""
|
||||
|
||||
def __init__(self, file_path: Path):
|
||||
self.file_path = file_path
|
||||
self._data: dict = {"images": {}, "groups": []}
|
||||
self._load()
|
||||
|
||||
def _load(self):
|
||||
if self.file_path.exists():
|
||||
try:
|
||||
with open(self.file_path, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
self._data = {
|
||||
"images": loaded.get("images", {}),
|
||||
"groups": loaded.get("groups", []),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("GalleryMetadataStore: load error: %s", e)
|
||||
|
||||
def _save_to_disk(self):
|
||||
try:
|
||||
self.file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(self.file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(self._data, f, ensure_ascii=False, indent=2)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error("GalleryMetadataStore: save error: %s", e)
|
||||
return False
|
||||
|
||||
def _normalize_path(self, image_path: str) -> str:
|
||||
return str(Path(image_path)).replace("\\", "/")
|
||||
|
||||
def get(self, image_path: str) -> dict:
|
||||
key = self._normalize_path(image_path)
|
||||
return dict(self._data["images"].get(key, {}))
|
||||
|
||||
def save(self, image_path: str, data: dict) -> bool:
|
||||
key = self._normalize_path(image_path)
|
||||
existing = self._data["images"].get(key, {})
|
||||
existing.update(data)
|
||||
allowed = {"favorite", "tags", "memo", "groups", "workflow"}
|
||||
existing = {k: v for k, v in existing.items() if k in allowed}
|
||||
self._data["images"][key] = existing
|
||||
return self._save_to_disk()
|
||||
|
||||
# ── グループ管理 ──────────────────────────────────────────────
|
||||
|
||||
def list_groups(self) -> list[dict]:
|
||||
return list(self._data.get("groups", []))
|
||||
|
||||
def create_group(self, name: str) -> bool:
|
||||
groups = self._data.get("groups", [])
|
||||
if any(g["name"] == name for g in groups):
|
||||
return False
|
||||
groups.append({"name": name})
|
||||
self._data["groups"] = groups
|
||||
return self._save_to_disk()
|
||||
|
||||
def rename_group(self, old_name: str, new_name: str) -> bool:
|
||||
"""グループ名を変更し、全画像のgroupsフィールドも更新する"""
|
||||
groups = self._data.get("groups", [])
|
||||
if not any(g["name"] == old_name for g in groups):
|
||||
return False
|
||||
if any(g["name"] == new_name for g in groups):
|
||||
return False # 新名前が既に存在
|
||||
# グループリスト更新
|
||||
for g in groups:
|
||||
if g["name"] == old_name:
|
||||
g["name"] = new_name
|
||||
break
|
||||
# 全画像のgroupsフィールドを更新
|
||||
for meta in self._data["images"].values():
|
||||
img_groups = meta.get("groups", [])
|
||||
if old_name in img_groups:
|
||||
meta["groups"] = [new_name if g == old_name else g for g in img_groups]
|
||||
return self._save_to_disk()
|
||||
|
||||
def delete_group(self, name: str) -> bool:
|
||||
groups = [g for g in self._data.get("groups", []) if g["name"] != name]
|
||||
self._data["groups"] = groups
|
||||
# 画像のgroupsからも削除
|
||||
for meta in self._data["images"].values():
|
||||
if name in meta.get("groups", []):
|
||||
meta["groups"] = [g for g in meta["groups"] if g != name]
|
||||
return self._save_to_disk()
|
||||
|
||||
def list_images_in_group(self, group_name: str) -> list[str]:
|
||||
result = []
|
||||
for key, meta in self._data["images"].items():
|
||||
if group_name in meta.get("groups", []):
|
||||
result.append(key)
|
||||
return result
|
||||
|
||||
def get_group_member_set(self, group_name: str) -> set:
|
||||
"""グループメンバーのパスをsetで返す(高速フィルタ用)"""
|
||||
return {
|
||||
key for key, meta in self._data["images"].items()
|
||||
if group_name in meta.get("groups", [])
|
||||
}
|
||||
|
||||
def delete(self, image_path: str) -> bool:
|
||||
"""画像のメタデータエントリを削除する"""
|
||||
key = self._normalize_path(image_path)
|
||||
if key in self._data["images"]:
|
||||
del self._data["images"][key]
|
||||
return self._save_to_disk()
|
||||
return True
|
||||
|
||||
def rename_path(self, old_path: str, new_path: str) -> bool:
|
||||
"""画像のパスキーを変更する(ファイル移動後のメタデータ引継ぎ)"""
|
||||
old_key = self._normalize_path(old_path)
|
||||
new_key = self._normalize_path(new_path)
|
||||
if old_key in self._data["images"]:
|
||||
self._data["images"][new_key] = self._data["images"].pop(old_key)
|
||||
return self._save_to_disk()
|
||||
return True
|
||||
@@ -0,0 +1,542 @@
|
||||
"""
|
||||
Gallery Service - outputフォルダの画像管理、メタデータ閲覧
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# サポートする画像拡張子
|
||||
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif"}
|
||||
|
||||
# メタデータ保存ファイル (gallery専用)
|
||||
from .gallery_metadata import GalleryMetadataStore
|
||||
|
||||
|
||||
# PNGチャンク1個の最大許容サイズ (32MB)
|
||||
_PNG_CHUNK_MAX = 32 * 1024 * 1024
|
||||
# JPEGを読む際の最大ファイルサイズ (64MB)
|
||||
_JPEG_READ_MAX = 64 * 1024 * 1024
|
||||
|
||||
# フォルダキャッシュのTTL秒(フォルダmtimeが同じでも念のため)
|
||||
_CACHE_TTL = 30.0
|
||||
|
||||
|
||||
class _FolderCache:
|
||||
"""フォルダ単位の画像スキャン結果キャッシュ。
|
||||
フォルダのmtimeが変わった場合、またはTTL超過時に再スキャンする。"""
|
||||
|
||||
def __init__(self):
|
||||
# folder_path -> (mtime, scan_time, [(name, path_str, size, mtime_f), ...])
|
||||
self._cache: dict[str, tuple[float, float, list]] = {}
|
||||
|
||||
def get(self, folder: Path) -> list | None:
|
||||
key = str(folder)
|
||||
if key not in self._cache:
|
||||
return None
|
||||
cached_mtime, scan_time, entries = self._cache[key]
|
||||
# TTL チェック
|
||||
if time.monotonic() - scan_time > _CACHE_TTL:
|
||||
return None
|
||||
# フォルダ自体のmtimeチェック
|
||||
try:
|
||||
current_mtime = folder.stat().st_mtime
|
||||
except OSError:
|
||||
return None
|
||||
if current_mtime != cached_mtime:
|
||||
return None
|
||||
return entries
|
||||
|
||||
def set(self, folder: Path, entries: list):
|
||||
key = str(folder)
|
||||
try:
|
||||
folder_mtime = folder.stat().st_mtime
|
||||
except OSError:
|
||||
folder_mtime = 0.0
|
||||
self._cache[key] = (folder_mtime, time.monotonic(), entries)
|
||||
|
||||
def invalidate(self, folder: Path):
|
||||
self._cache.pop(str(folder), None)
|
||||
|
||||
|
||||
class GalleryService:
|
||||
def __init__(self, data_dir: Path):
|
||||
self.data_dir = data_dir
|
||||
self.metadata_store = GalleryMetadataStore(data_dir / "gallery_metadata.json")
|
||||
self._allowed_root: Path | None = None
|
||||
self._folder_cache = _FolderCache()
|
||||
|
||||
def update_output_root(self, root_path: str) -> None:
|
||||
"""許可するルートパスを更新する(Settings変更時に呼ぶ)"""
|
||||
p = Path(root_path).resolve() if root_path else None
|
||||
self._allowed_root = p
|
||||
|
||||
def _check_path_allowed(self, path: Path) -> bool:
|
||||
"""パスが許可ルート配下かチェック(パストラバーサル防止)"""
|
||||
if self._allowed_root is None:
|
||||
resolved = path.resolve()
|
||||
return resolved == path.resolve()
|
||||
try:
|
||||
path.resolve().relative_to(self._allowed_root)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# フォルダツリー
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def list_folder_tree(self, root_path: str) -> dict:
|
||||
"""outputフォルダのフォルダツリーを返す"""
|
||||
root = Path(root_path).resolve()
|
||||
if not root.is_dir():
|
||||
return {"error": f"Directory not found: {root_path}"}
|
||||
if self._allowed_root is None:
|
||||
self._allowed_root = root
|
||||
|
||||
def build_tree(path: Path, rel_base: Path) -> dict:
|
||||
rel = str(path.relative_to(rel_base)).replace("\\", "/")
|
||||
image_count = 0
|
||||
children = []
|
||||
try:
|
||||
with os.scandir(path) as it:
|
||||
for entry in it:
|
||||
if entry.is_file(follow_symlinks=True):
|
||||
if Path(entry.name).suffix.lower() in IMAGE_EXTENSIONS:
|
||||
image_count += 1
|
||||
elif entry.is_dir(follow_symlinks=True) and not entry.name.startswith("."):
|
||||
children.append(entry.name)
|
||||
except PermissionError:
|
||||
pass
|
||||
children_nodes = [build_tree(path / name, rel_base) for name in sorted(children)]
|
||||
return {
|
||||
"name": path.name,
|
||||
"path": rel if rel != "." else "",
|
||||
"abs_path": str(path).replace("\\", "/"),
|
||||
"image_count": image_count,
|
||||
"children": children_nodes,
|
||||
}
|
||||
|
||||
return build_tree(root, root)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像一覧
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def _scan_folder(self, folder: Path) -> list[tuple[str, str, int, float]]:
|
||||
"""os.scandir() で画像ファイルを1回のシステムコールで列挙。
|
||||
キャッシュがあればそれを返す。
|
||||
Returns: [(name, abs_path_str, size, mtime), ...]
|
||||
"""
|
||||
cached = self._folder_cache.get(folder)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
entries = []
|
||||
try:
|
||||
with os.scandir(folder) as it:
|
||||
for entry in it:
|
||||
if not entry.is_file(follow_symlinks=True):
|
||||
continue
|
||||
if Path(entry.name).suffix.lower() not in IMAGE_EXTENSIONS:
|
||||
continue
|
||||
try:
|
||||
st = entry.stat(follow_symlinks=True)
|
||||
entries.append((
|
||||
entry.name,
|
||||
str(Path(entry.path).resolve()).replace("\\", "/"),
|
||||
st.st_size,
|
||||
st.st_mtime,
|
||||
))
|
||||
except OSError:
|
||||
continue
|
||||
except PermissionError:
|
||||
pass
|
||||
|
||||
self._folder_cache.set(folder, entries)
|
||||
return entries
|
||||
|
||||
def list_images(
|
||||
self,
|
||||
folder_path: str,
|
||||
search: str = "",
|
||||
sort_by: str = "date_desc",
|
||||
favorite_only: bool = False,
|
||||
tag_filter: str = "",
|
||||
group_filter: str = "",
|
||||
) -> list[dict]:
|
||||
"""指定フォルダ内の画像一覧を返す(サブフォルダなし)"""
|
||||
folder = Path(folder_path).resolve()
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
if not self._check_path_allowed(folder):
|
||||
logger.warning("list_images: path not allowed: %s", folder)
|
||||
return []
|
||||
|
||||
# グループフィルタ: サーバーサイドで先にパスSetを取得(転送量削減)
|
||||
group_member_set: set | None = None
|
||||
if group_filter:
|
||||
group_member_set = self.metadata_store.get_group_member_set(group_filter)
|
||||
|
||||
# os.scandir() でファイル情報を一括取得(stat()の個別呼び出しを排除)
|
||||
raw_entries = self._scan_folder(folder)
|
||||
|
||||
results = []
|
||||
for name, abs_path, size, mtime in raw_entries:
|
||||
# グループフィルタ(サーバーサイド)
|
||||
if group_member_set is not None and abs_path not in group_member_set:
|
||||
continue
|
||||
|
||||
meta = self.metadata_store.get(abs_path)
|
||||
|
||||
# お気に入りフィルタ(サーバーサイド、早期スキップ)
|
||||
if favorite_only and not meta.get("favorite", False):
|
||||
continue
|
||||
|
||||
# タグフィルタ(サーバーサイド、早期スキップ)
|
||||
tags = meta.get("tags", [])
|
||||
if tag_filter and tag_filter not in tags:
|
||||
continue
|
||||
|
||||
ext = Path(name).suffix.lower()
|
||||
item = {
|
||||
"filename": name,
|
||||
"path": abs_path,
|
||||
"size": size,
|
||||
"mtime": mtime,
|
||||
"ext": ext,
|
||||
"favorite": meta.get("favorite", False),
|
||||
"tags": tags,
|
||||
"memo": meta.get("memo", ""),
|
||||
"groups": meta.get("groups", []),
|
||||
}
|
||||
|
||||
# 検索フィルタ
|
||||
if search:
|
||||
s = search.lower()
|
||||
if not (
|
||||
s in name.lower()
|
||||
or s in item["memo"].lower()
|
||||
or any(s in t.lower() for t in tags)
|
||||
):
|
||||
continue
|
||||
|
||||
results.append(item)
|
||||
|
||||
# ソート
|
||||
if sort_by == "name_asc":
|
||||
results.sort(key=lambda x: x["filename"].lower())
|
||||
elif sort_by == "name_desc":
|
||||
results.sort(key=lambda x: x["filename"].lower(), reverse=True)
|
||||
elif sort_by == "date_asc":
|
||||
results.sort(key=lambda x: x["mtime"])
|
||||
else: # date_desc (default)
|
||||
results.sort(key=lambda x: x["mtime"], reverse=True)
|
||||
|
||||
return results
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像メタデータ
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def get_image_metadata(self, image_path: str) -> dict:
|
||||
"""PNG/JPEGからメタデータを抽出し、保存済みメタと合わせて返す"""
|
||||
path = Path(image_path).resolve()
|
||||
if not path.is_file():
|
||||
return {"error": "File not found"}
|
||||
if not self._check_path_allowed(path):
|
||||
return {"error": "Access denied"}
|
||||
|
||||
embedded = {}
|
||||
ext = path.suffix.lower()
|
||||
if ext == ".png":
|
||||
embedded = self._read_png_metadata(path)
|
||||
elif ext in {".jpg", ".jpeg"}:
|
||||
embedded = self._read_jpeg_metadata(path)
|
||||
|
||||
saved = self.metadata_store.get(str(path))
|
||||
|
||||
stat = path.stat()
|
||||
return {
|
||||
"filename": path.name,
|
||||
"path": str(path).replace("\\", "/"),
|
||||
"size": stat.st_size,
|
||||
"mtime": stat.st_mtime,
|
||||
"ext": ext,
|
||||
"embedded": embedded,
|
||||
"favorite": saved.get("favorite", False),
|
||||
"tags": saved.get("tags", []),
|
||||
"memo": saved.get("memo", ""),
|
||||
"groups": saved.get("groups", []),
|
||||
}
|
||||
|
||||
def _read_png_metadata(self, path: Path) -> dict:
|
||||
"""PNGのtEXtチャンクからメタデータを抽出"""
|
||||
result = {}
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
sig = f.read(8)
|
||||
if sig != b"\x89PNG\r\n\x1a\n":
|
||||
return result
|
||||
while True:
|
||||
chunk_len_bytes = f.read(4)
|
||||
if len(chunk_len_bytes) < 4:
|
||||
break
|
||||
chunk_len = struct.unpack(">I", chunk_len_bytes)[0]
|
||||
chunk_type = f.read(4).decode("ascii", errors="ignore")
|
||||
if chunk_len > _PNG_CHUNK_MAX:
|
||||
f.seek(chunk_len + 4, 1)
|
||||
if chunk_type == "IEND":
|
||||
break
|
||||
continue
|
||||
chunk_data = f.read(chunk_len)
|
||||
f.read(4) # CRC
|
||||
|
||||
if chunk_type in ("tEXt", "iTXt"):
|
||||
try:
|
||||
if chunk_type == "tEXt":
|
||||
null_idx = chunk_data.index(b"\x00")
|
||||
key = chunk_data[:null_idx].decode("latin-1")
|
||||
value = chunk_data[null_idx + 1:].decode("latin-1")
|
||||
else:
|
||||
null_idx = chunk_data.index(b"\x00")
|
||||
key = chunk_data[:null_idx].decode("utf-8")
|
||||
rest = chunk_data[null_idx + 1:]
|
||||
rest = rest[2:]
|
||||
null_idx2 = rest.index(b"\x00")
|
||||
rest = rest[null_idx2 + 1:]
|
||||
null_idx3 = rest.index(b"\x00")
|
||||
value = rest[null_idx3 + 1:].decode("utf-8", errors="replace")
|
||||
result[key] = value
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
pass
|
||||
|
||||
if chunk_type == "IEND":
|
||||
break
|
||||
except Exception as e:
|
||||
logger.debug("PNG metadata read error: %s", e)
|
||||
return result
|
||||
|
||||
def _read_jpeg_metadata(self, path: Path) -> dict:
|
||||
"""JPEGのEXIF/commentからメタデータを抽出(簡易)"""
|
||||
result = {}
|
||||
try:
|
||||
file_size = path.stat().st_size
|
||||
read_size = min(file_size, _JPEG_READ_MAX)
|
||||
with open(path, "rb") as f:
|
||||
data = f.read(read_size)
|
||||
idx = 0
|
||||
while idx < len(data) - 3:
|
||||
if data[idx] == 0xFF:
|
||||
marker = data[idx + 1]
|
||||
if marker == 0xFE: # COM
|
||||
length = struct.unpack(">H", data[idx + 2:idx + 4])[0]
|
||||
end = idx + 2 + length
|
||||
comment = data[idx + 4:end].decode("utf-8", errors="replace")
|
||||
result["Comment"] = comment
|
||||
break
|
||||
idx += 2
|
||||
else:
|
||||
idx += 1
|
||||
except Exception as e:
|
||||
logger.debug("JPEG metadata read error: %s", e)
|
||||
return result
|
||||
|
||||
def extract_workflow_from_metadata(self, image_path: str) -> dict | None:
|
||||
"""ワークフローを抽出する。
|
||||
優先順位: PNG[workflow] > PNG[prompt] > gallery_metadata.json[workflow]
|
||||
"""
|
||||
path = Path(image_path).resolve()
|
||||
if not self._check_path_allowed(path):
|
||||
return None
|
||||
|
||||
if path.suffix.lower() == ".png":
|
||||
embedded = self._read_png_metadata(path)
|
||||
# 1. workflow キー (ComfyUI UI形式)
|
||||
for key in ("workflow", "Workflow"):
|
||||
s = embedded.get(key)
|
||||
if s:
|
||||
try:
|
||||
return json.loads(s)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
# 2. prompt キー (ComfyUI API形式 — 大多数の生成画像)
|
||||
for key in ("prompt", "Prompt"):
|
||||
s = embedded.get(key)
|
||||
if s:
|
||||
try:
|
||||
return json.loads(s)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# 3. gallery_metadata.json に保存されたworkflow
|
||||
saved = self.metadata_store.get(str(path))
|
||||
return saved.get("workflow") or None
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# メタデータ保存
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def save_image_meta(self, image_path: str, data: dict) -> bool:
|
||||
return self.metadata_store.save(image_path, data)
|
||||
|
||||
def toggle_favorite(self, image_path: str) -> bool:
|
||||
meta = self.metadata_store.get(image_path)
|
||||
new_val = not meta.get("favorite", False)
|
||||
self.metadata_store.save(image_path, {"favorite": new_val})
|
||||
return new_val
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# グループ管理
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def list_groups(self) -> list[dict]:
|
||||
return self.metadata_store.list_groups()
|
||||
|
||||
def create_group(self, name: str) -> bool:
|
||||
return self.metadata_store.create_group(name)
|
||||
|
||||
def rename_group(self, old_name: str, new_name: str) -> bool:
|
||||
return self.metadata_store.rename_group(old_name, new_name)
|
||||
|
||||
def delete_group(self, name: str) -> bool:
|
||||
return self.metadata_store.delete_group(name)
|
||||
|
||||
def add_to_group(self, image_path: str, group_name: str) -> bool:
|
||||
meta = self.metadata_store.get(image_path)
|
||||
groups = meta.get("groups", [])
|
||||
if group_name not in groups:
|
||||
groups.append(group_name)
|
||||
return self.metadata_store.save(image_path, {"groups": groups})
|
||||
return True
|
||||
|
||||
def remove_from_group(self, image_path: str, group_name: str) -> bool:
|
||||
meta = self.metadata_store.get(image_path)
|
||||
groups = [g for g in meta.get("groups", []) if g != group_name]
|
||||
return self.metadata_store.save(image_path, {"groups": groups})
|
||||
|
||||
def list_images_in_group(self, group_name: str) -> list[str]:
|
||||
return self.metadata_store.list_images_in_group(group_name)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像配信
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def create_folder(self, parent_path: str, name: str) -> dict:
|
||||
"""選択フォルダ内に新しいサブフォルダを作成する"""
|
||||
parent = Path(parent_path).resolve()
|
||||
if not parent.is_dir():
|
||||
return {"ok": False, "error": "Parent directory not found"}
|
||||
if not self._check_path_allowed(parent):
|
||||
return {"ok": False, "error": "Access denied"}
|
||||
name = name.strip()
|
||||
invalid_chars = set(r'\/:*?"<>|')
|
||||
if not name or any(c in invalid_chars for c in name):
|
||||
return {"ok": False, "error": "Invalid folder name"}
|
||||
new_folder = parent / name
|
||||
if new_folder.exists():
|
||||
return {"ok": False, "error": "Folder already exists"}
|
||||
try:
|
||||
new_folder.mkdir()
|
||||
self._folder_cache.invalidate(parent)
|
||||
return {"ok": True, "path": str(new_folder).replace("\\", "/")}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
def delete_folder(self, folder_path: str) -> dict:
|
||||
"""フォルダを再帰的に削除する"""
|
||||
import shutil
|
||||
folder = Path(folder_path).resolve()
|
||||
if not folder.is_dir():
|
||||
return {"ok": False, "error": "Directory not found"}
|
||||
if not self._check_path_allowed(folder):
|
||||
return {"ok": False, "error": "Access denied"}
|
||||
if self._allowed_root and folder == self._allowed_root:
|
||||
return {"ok": False, "error": "Cannot delete root folder"}
|
||||
try:
|
||||
parent = folder.parent
|
||||
shutil.rmtree(folder)
|
||||
self._folder_cache.invalidate(parent)
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
def delete_images(self, paths: list) -> dict:
|
||||
"""画像ファイルを削除する(複数対応)"""
|
||||
deleted = []
|
||||
errors = []
|
||||
for img_path in paths:
|
||||
p = Path(img_path).resolve()
|
||||
if not p.is_file():
|
||||
errors.append(f"{Path(img_path).name}: not found")
|
||||
continue
|
||||
if p.suffix.lower() not in IMAGE_EXTENSIONS:
|
||||
errors.append(f"{p.name}: not an image")
|
||||
continue
|
||||
if not self._check_path_allowed(p):
|
||||
errors.append(f"{p.name}: access denied")
|
||||
continue
|
||||
try:
|
||||
p.unlink()
|
||||
self.metadata_store.delete(str(p))
|
||||
self._folder_cache.invalidate(p.parent)
|
||||
deleted.append(str(p).replace("\\", "/"))
|
||||
except Exception as e:
|
||||
errors.append(f"{p.name}: {e}")
|
||||
return {"deleted": deleted, "errors": errors}
|
||||
|
||||
def move_images(self, paths: list, dest_folder: str) -> dict:
|
||||
"""画像ファイルを別フォルダへ移動する(複数対応)"""
|
||||
dest = Path(dest_folder).resolve()
|
||||
if not dest.is_dir():
|
||||
return {"ok": False, "error": "Destination folder not found", "moved": [], "errors": []}
|
||||
if not self._check_path_allowed(dest):
|
||||
return {"ok": False, "error": "Access denied", "moved": [], "errors": []}
|
||||
moved = []
|
||||
errors = []
|
||||
for img_path in paths:
|
||||
p = Path(img_path).resolve()
|
||||
if not p.is_file():
|
||||
errors.append(f"{Path(img_path).name}: not found")
|
||||
continue
|
||||
if p.suffix.lower() not in IMAGE_EXTENSIONS:
|
||||
errors.append(f"{p.name}: not an image")
|
||||
continue
|
||||
if not self._check_path_allowed(p):
|
||||
errors.append(f"{p.name}: access denied")
|
||||
continue
|
||||
dest_path = dest / p.name
|
||||
counter = 1
|
||||
while dest_path.exists():
|
||||
dest_path = dest / f"{p.stem}_{counter}{p.suffix}"
|
||||
counter += 1
|
||||
try:
|
||||
p.rename(dest_path)
|
||||
old_str = str(p).replace("\\", "/")
|
||||
new_str = str(dest_path).replace("\\", "/")
|
||||
self.metadata_store.rename_path(old_str, new_str)
|
||||
self._folder_cache.invalidate(p.parent)
|
||||
self._folder_cache.invalidate(dest)
|
||||
moved.append({"from": old_str, "to": new_str, "filename": dest_path.name})
|
||||
except Exception as e:
|
||||
errors.append(f"{p.name}: {e}")
|
||||
return {"moved": moved, "errors": errors}
|
||||
|
||||
def serve_image(self, image_path: str):
|
||||
"""画像のPathオブジェクトを返す(ルートで使用)"""
|
||||
p = Path(image_path).resolve()
|
||||
if not p.is_file():
|
||||
return None
|
||||
if p.suffix.lower() not in IMAGE_EXTENSIONS:
|
||||
return None
|
||||
if not self._check_path_allowed(p):
|
||||
logger.warning("serve_image: path not allowed: %s", p)
|
||||
return None
|
||||
return p
|
||||
@@ -0,0 +1,276 @@
|
||||
"""Model metadata management service."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from ..config import MODEL_METADATA_FILE
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Preview image extensions to search for (in priority order)
|
||||
_PREVIEW_EXTENSIONS = [".preview.png", ".preview.jpg", ".preview.jpeg", ".preview.webp",
|
||||
".png", ".jpg", ".jpeg", ".webp"]
|
||||
|
||||
# All sidecar extensions to delete when a model is deleted
|
||||
_SIDECAR_EXTENSIONS = [
|
||||
".preview.png", ".preview.jpg", ".preview.jpeg", ".preview.webp",
|
||||
".png", ".jpg", ".jpeg", ".webp",
|
||||
".json", ".civitai.info", ".info",
|
||||
]
|
||||
|
||||
_DISABLED_SUFFIX = ".disabled"
|
||||
|
||||
# ComfyUI model type → folder_paths key mapping
|
||||
MODEL_TYPE_FOLDER_KEYS = {
|
||||
"checkpoint": "checkpoints",
|
||||
"lora": "loras",
|
||||
"vae": "vae",
|
||||
"controlnet": "controlnet",
|
||||
"unet": "diffusion_models",
|
||||
"textencoder": "text_encoders",
|
||||
"hypernetwork": "hypernetworks",
|
||||
"embedding": "embeddings",
|
||||
}
|
||||
|
||||
|
||||
def _get_model_dirs(model_type):
|
||||
"""Get all model directories for a type using ComfyUI's folder_paths.
|
||||
|
||||
Returns a list of Path objects for all configured model directories
|
||||
(includes extra_model_paths.yaml settings).
|
||||
Falls back to plugin-relative path if folder_paths is unavailable.
|
||||
"""
|
||||
folder_key = MODEL_TYPE_FOLDER_KEYS.get(model_type)
|
||||
if not folder_key:
|
||||
return []
|
||||
|
||||
try:
|
||||
import folder_paths # type: ignore # ComfyUI module
|
||||
paths = folder_paths.get_folder_paths(folder_key)
|
||||
result = [Path(p) for p in paths if Path(p).is_dir()]
|
||||
if result:
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.debug("folder_paths unavailable (%s), using fallback", e)
|
||||
|
||||
# Fallback: custom_nodes/../../models/{folder_key}
|
||||
plugin_dir = Path(__file__).resolve().parent.parent.parent
|
||||
models_dir = plugin_dir.parent.parent / "models" / folder_key
|
||||
if models_dir.is_dir():
|
||||
return [models_dir]
|
||||
return []
|
||||
|
||||
|
||||
class ModelsService:
|
||||
"""Manages user-defined model metadata (favorites, tags, memo)."""
|
||||
|
||||
def __init__(self):
|
||||
self.metadata_file = MODEL_METADATA_FILE
|
||||
|
||||
def _now_iso(self):
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
def _load_metadata(self):
|
||||
if self.metadata_file.exists():
|
||||
try:
|
||||
with open(self.metadata_file, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def _save_metadata(self, data):
|
||||
self.metadata_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(self.metadata_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
def get_all_metadata(self):
|
||||
return self._load_metadata()
|
||||
|
||||
def update_metadata(self, model_name, updates):
|
||||
data = self._load_metadata()
|
||||
if model_name not in data:
|
||||
data[model_name] = {"tags": [], "favorite": False, "memo": ""}
|
||||
entry = data[model_name]
|
||||
if "tags" in updates:
|
||||
entry["tags"] = updates["tags"]
|
||||
if "favorite" in updates:
|
||||
entry["favorite"] = updates["favorite"]
|
||||
if "memo" in updates:
|
||||
entry["memo"] = updates["memo"]
|
||||
if "sha256" in updates:
|
||||
entry["sha256"] = updates["sha256"]
|
||||
if "badges" in updates:
|
||||
entry["badges"] = updates["badges"]
|
||||
entry["updatedAt"] = self._now_iso()
|
||||
data[model_name] = entry
|
||||
self._save_metadata(data)
|
||||
return entry
|
||||
|
||||
def get_model_groups(self, model_type=None):
|
||||
data = self._load_metadata()
|
||||
raw = data.get("_groups", {})
|
||||
|
||||
# Migrate old flat format { "groupName": [...] } → per-type { "checkpoint": {...} }
|
||||
if raw and not any(k in MODEL_TYPE_FOLDER_KEYS for k in raw):
|
||||
logger.info("Migrating groups to per-type format (old data moved to _groups_legacy)")
|
||||
data["_groups_legacy"] = raw
|
||||
data["_groups"] = {}
|
||||
self._save_metadata(data)
|
||||
raw = {}
|
||||
|
||||
if model_type:
|
||||
return raw.get(model_type, {})
|
||||
return raw
|
||||
|
||||
def save_model_groups(self, groups, model_type):
|
||||
data = self._load_metadata()
|
||||
if not isinstance(data.get("_groups"), dict):
|
||||
data["_groups"] = {}
|
||||
data["_groups"][model_type] = groups
|
||||
self._save_metadata(data)
|
||||
return groups
|
||||
|
||||
def find_model_file(self, model_type, model_name):
|
||||
"""Find a model file, checking both enabled and disabled states.
|
||||
|
||||
Returns (Path, is_enabled) or (None, None) if not found.
|
||||
"""
|
||||
dirs = _get_model_dirs(model_type)
|
||||
for d in dirs:
|
||||
enabled = d / model_name
|
||||
if enabled.is_file():
|
||||
return enabled, True
|
||||
disabled = d / (model_name + _DISABLED_SUFFIX)
|
||||
if disabled.is_file():
|
||||
return disabled, False
|
||||
return None, None
|
||||
|
||||
def enable_model(self, model_type, model_name):
|
||||
"""Rename model.safetensors.disabled → model.safetensors."""
|
||||
path, is_enabled = self.find_model_file(model_type, model_name)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"Model not found: {model_name}")
|
||||
if is_enabled:
|
||||
return
|
||||
target = path.parent / path.name[: -len(_DISABLED_SUFFIX)]
|
||||
path.rename(target)
|
||||
logger.info("Enabled model: %s", model_name)
|
||||
|
||||
def disable_model(self, model_type, model_name):
|
||||
"""Rename model.safetensors → model.safetensors.disabled."""
|
||||
path, is_enabled = self.find_model_file(model_type, model_name)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"Model not found: {model_name}")
|
||||
if not is_enabled:
|
||||
return
|
||||
target = path.parent / (path.name + _DISABLED_SUFFIX)
|
||||
path.rename(target)
|
||||
logger.info("Disabled model: %s", model_name)
|
||||
|
||||
def scan_disabled_models(self, model_type):
|
||||
"""Scan directories for .disabled files.
|
||||
|
||||
Returns list of normalized model names (without .disabled suffix).
|
||||
"""
|
||||
dirs = _get_model_dirs(model_type)
|
||||
disabled = []
|
||||
for d in dirs:
|
||||
if not d.is_dir():
|
||||
continue
|
||||
for f in d.rglob("*"):
|
||||
if f.is_file() and f.name.endswith(_DISABLED_SUFFIX):
|
||||
try:
|
||||
rel = str(f.relative_to(d))
|
||||
if rel.endswith(_DISABLED_SUFFIX):
|
||||
rel = rel[: -len(_DISABLED_SUFFIX)]
|
||||
disabled.append(rel.replace("\\", "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
return disabled
|
||||
|
||||
def find_preview_image(self, model_type, model_name):
|
||||
"""Find preview image for a model file.
|
||||
|
||||
Searches all configured directories for the model type
|
||||
(via ComfyUI's folder_paths, which includes extra_model_paths.yaml).
|
||||
|
||||
Looks for files like:
|
||||
modelname.preview.png, modelname.png, etc.
|
||||
next to the model file.
|
||||
|
||||
Returns: absolute Path to preview image, or None.
|
||||
"""
|
||||
dirs = _get_model_dirs(model_type)
|
||||
if not dirs:
|
||||
logger.debug("Preview: no dirs for model_type=%s", model_type)
|
||||
return None
|
||||
|
||||
for type_dir in dirs:
|
||||
# model_name can include subdirectory (e.g., "subdir/model.safetensors")
|
||||
model_path = type_dir / model_name
|
||||
if not model_path.is_file():
|
||||
continue
|
||||
|
||||
stem = model_path.stem
|
||||
parent = model_path.parent
|
||||
|
||||
for ext in _PREVIEW_EXTENSIONS:
|
||||
preview = parent / (stem + ext)
|
||||
if preview.is_file():
|
||||
logger.debug("Preview found: %s", preview)
|
||||
return preview
|
||||
|
||||
logger.debug("Preview: no preview for %s (stem=%s, dir=%s)",
|
||||
model_name, stem, parent)
|
||||
return None
|
||||
|
||||
logger.debug("Preview: model file not found in any dir: %s", model_name)
|
||||
return None
|
||||
|
||||
def delete_model(self, model_type, model_name):
|
||||
"""Delete a model file and all associated preview/sidecar files.
|
||||
|
||||
Also removes the model's metadata entry.
|
||||
Returns dict with deleted file paths.
|
||||
"""
|
||||
if ".." in model_name:
|
||||
raise ValueError(f"Invalid model name: {model_name}")
|
||||
|
||||
path, _ = self.find_model_file(model_type, model_name)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"Model not found: {model_name}")
|
||||
|
||||
deleted = []
|
||||
parent = path.parent
|
||||
|
||||
# Compute stem from the original (non-disabled) filename.
|
||||
# path.name for a disabled file is e.g. "model.safetensors.disabled"
|
||||
# so we strip the .disabled suffix first, then take Path.stem.
|
||||
orig_name = path.name
|
||||
if orig_name.endswith(_DISABLED_SUFFIX):
|
||||
orig_name = orig_name[: -len(_DISABLED_SUFFIX)]
|
||||
stem = Path(orig_name).stem # "model.safetensors" -> "model"
|
||||
|
||||
# Delete the model file itself
|
||||
path.unlink()
|
||||
deleted.append(str(path))
|
||||
logger.info("Deleted model file: %s", path)
|
||||
|
||||
# Delete all sidecar files (previews, metadata, info)
|
||||
for ext in _SIDECAR_EXTENSIONS:
|
||||
sidecar = parent / (stem + ext)
|
||||
if sidecar.is_file():
|
||||
sidecar.unlink()
|
||||
deleted.append(str(sidecar))
|
||||
logger.info("Deleted sidecar: %s", sidecar)
|
||||
|
||||
# Remove metadata entry
|
||||
data = self._load_metadata()
|
||||
if model_name in data:
|
||||
del data[model_name]
|
||||
self._save_metadata(data)
|
||||
|
||||
return {"deleted": deleted}
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Wildcard file management service."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ALLOWED_EXTS = {"txt", "yaml", "yml"}
|
||||
|
||||
|
||||
class WildcardService:
|
||||
def __init__(self, wildcard_dir: Path):
|
||||
self.wildcard_dir = wildcard_dir
|
||||
# Only mkdir if it is a real directory (not a junction/symlink)
|
||||
if not self.wildcard_dir.exists() and not self._is_junction(self.wildcard_dir):
|
||||
self.wildcard_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# File CRUD
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def list_wildcards(self) -> list[dict]:
|
||||
"""Return sorted list of wildcard files recursively (follows junction/symlink)."""
|
||||
if not self.wildcard_dir.exists():
|
||||
return []
|
||||
files = []
|
||||
for path in sorted(self.wildcard_dir.rglob("*")):
|
||||
if path.is_file() and path.suffix.lstrip(".").lower() in ALLOWED_EXTS:
|
||||
rel = path.relative_to(self.wildcard_dir)
|
||||
dir_posix = rel.parent.as_posix()
|
||||
if dir_posix == ".":
|
||||
dir_posix = ""
|
||||
files.append({
|
||||
"name": path.stem,
|
||||
"filename": rel.as_posix(),
|
||||
"ext": path.suffix.lstrip(".").lower(),
|
||||
"size": path.stat().st_size,
|
||||
"dir": dir_posix,
|
||||
"wc_name": rel.with_suffix("").as_posix(),
|
||||
})
|
||||
return files
|
||||
|
||||
def get_content(self, filename: str) -> str:
|
||||
path = self._safe_path(filename)
|
||||
if path is None:
|
||||
raise ValueError(f"Invalid filename: {filename}")
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"File not found: {filename}")
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
def save_file(self, filename: str, content: str) -> dict:
|
||||
path = self._safe_path(filename)
|
||||
if path is None:
|
||||
raise ValueError(f"Invalid filename: {filename}")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
rel = path.relative_to(self.wildcard_dir)
|
||||
dir_posix = rel.parent.as_posix()
|
||||
if dir_posix == ".":
|
||||
dir_posix = ""
|
||||
return {
|
||||
"name": path.stem,
|
||||
"filename": rel.as_posix(),
|
||||
"ext": path.suffix.lstrip(".").lower(),
|
||||
"size": path.stat().st_size,
|
||||
"dir": dir_posix,
|
||||
"wc_name": rel.with_suffix("").as_posix(),
|
||||
}
|
||||
|
||||
def delete_file(self, filename: str) -> None:
|
||||
path = self._safe_path(filename)
|
||||
if path is None:
|
||||
raise ValueError(f"Invalid filename: {filename}")
|
||||
if path.is_file():
|
||||
path.unlink()
|
||||
|
||||
def _safe_path(self, filename: str) -> Path | None:
|
||||
if not filename or not filename.strip():
|
||||
return None
|
||||
# Normalize to forward slashes and strip leading/trailing slashes
|
||||
filename = filename.replace("\\", "/").strip("/")
|
||||
# Validate each path component — block traversal and empty parts
|
||||
parts = filename.split("/")
|
||||
for p in parts:
|
||||
if not p or p == ".." or p == ".":
|
||||
return None
|
||||
ext = Path(parts[-1]).suffix.lstrip(".").lower()
|
||||
if ext not in ALLOWED_EXTS:
|
||||
return None
|
||||
return self.wildcard_dir.joinpath(*parts)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Impact Pack integration
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def find_impact_pack_wildcards(comfyui_root: Path) -> Path | None:
|
||||
"""Return Impact Pack wildcards directory path, or None if not installed."""
|
||||
custom_nodes = comfyui_root / "custom_nodes"
|
||||
if not custom_nodes.is_dir():
|
||||
return None
|
||||
for d in custom_nodes.iterdir():
|
||||
if d.is_dir() and "impact-pack" in d.name.lower():
|
||||
wildcards = d / "wildcards"
|
||||
if wildcards.is_dir():
|
||||
return wildcards
|
||||
return None
|
||||
|
||||
def get_link_status(self, comfyui_root: Path) -> dict:
|
||||
"""Return current Impact Pack integration status."""
|
||||
impact_dir = self.find_impact_pack_wildcards(comfyui_root)
|
||||
is_linked = self._is_junction(self.wildcard_dir) or self.wildcard_dir.is_symlink()
|
||||
|
||||
resolved_target = None
|
||||
if is_linked:
|
||||
try:
|
||||
resolved_target = str(self.wildcard_dir.resolve())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return {
|
||||
"impact_pack_installed": impact_dir is not None,
|
||||
"impact_pack_wildcards_dir": str(impact_dir) if impact_dir else None,
|
||||
"wfs_wildcard_dir": str(self.wildcard_dir),
|
||||
"is_linked": is_linked,
|
||||
"link_target": resolved_target,
|
||||
}
|
||||
|
||||
def create_link(self, comfyui_root: Path) -> dict:
|
||||
"""Replace WFS wildcard dir with a junction/symlink → Impact Pack wildcards."""
|
||||
impact_dir = self.find_impact_pack_wildcards(comfyui_root)
|
||||
if impact_dir is None:
|
||||
raise RuntimeError("ComfyUI-Impact-Pack is not installed.")
|
||||
|
||||
if self._is_junction(self.wildcard_dir) or self.wildcard_dir.is_symlink():
|
||||
raise RuntimeError("Link already exists.")
|
||||
|
||||
# Migrate existing WFS files to Impact Pack dir
|
||||
migrated: list[str] = []
|
||||
if self.wildcard_dir.is_dir():
|
||||
for f in self.wildcard_dir.iterdir():
|
||||
if f.is_file():
|
||||
dest = impact_dir / f.name
|
||||
if not dest.exists():
|
||||
shutil.copy2(str(f), str(dest))
|
||||
migrated.append(f.name)
|
||||
shutil.rmtree(str(self.wildcard_dir))
|
||||
|
||||
# Create junction (Windows) or symlink (others)
|
||||
self._create_junction_or_symlink(self.wildcard_dir, impact_dir)
|
||||
logger.info("Wildcard link created: %s -> %s", self.wildcard_dir, impact_dir)
|
||||
return {"migrated_files": migrated}
|
||||
|
||||
def remove_link(self) -> None:
|
||||
"""Remove junction/symlink and restore WFS wildcard dir as a plain directory."""
|
||||
if not (self._is_junction(self.wildcard_dir) or self.wildcard_dir.is_symlink()):
|
||||
raise RuntimeError("No link to remove.")
|
||||
self._remove_junction_or_symlink(self.wildcard_dir)
|
||||
self.wildcard_dir.mkdir(parents=True, exist_ok=True)
|
||||
logger.info("Wildcard link removed, restored plain dir: %s", self.wildcard_dir)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Platform helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _is_junction(path: Path) -> bool:
|
||||
"""Return True if path is a Windows directory junction."""
|
||||
if platform.system() != "Windows":
|
||||
return False
|
||||
try:
|
||||
import ctypes
|
||||
FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
|
||||
attrs = ctypes.windll.kernel32.GetFileAttributesW(str(path))
|
||||
return attrs != 0xFFFFFFFF and bool(attrs & FILE_ATTRIBUTE_REPARSE_POINT)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _create_junction_or_symlink(link: Path, target: Path) -> None:
|
||||
if platform.system() == "Windows":
|
||||
result = subprocess.run(
|
||||
["cmd", "/c", "mklink", "/J", str(link), str(target)],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"mklink /J failed: {result.stderr.strip()}")
|
||||
else:
|
||||
os.symlink(target, link, target_is_directory=True)
|
||||
|
||||
@staticmethod
|
||||
def _remove_junction_or_symlink(path: Path) -> None:
|
||||
if platform.system() == "Windows":
|
||||
result = subprocess.run(
|
||||
["cmd", "/c", "rmdir", str(path)],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"rmdir failed: {result.stderr.strip()}")
|
||||
else:
|
||||
os.unlink(str(path))
|
||||
@@ -112,6 +112,7 @@ class WorkflowService:
|
||||
"summary": meta.get("summary", ""),
|
||||
"modelTypesOverride": override_types,
|
||||
"favorite": bool(meta.get("favorite", False)),
|
||||
"badges": meta.get("badges", []),
|
||||
},
|
||||
"mtime": stat.st_mtime,
|
||||
"thumbnail": thumbnail,
|
||||
@@ -132,7 +133,7 @@ class WorkflowService:
|
||||
"""Save metadata (tags, memo, summary, etc.) for a workflow."""
|
||||
metadata = self._load_metadata()
|
||||
entry = metadata.get(filename, {})
|
||||
for key in ("tags", "memo", "summary", "modelTypesOverride", "favorite"):
|
||||
for key in ("tags", "memo", "summary", "modelTypesOverride", "favorite", "badges"):
|
||||
if key in updates:
|
||||
entry[key] = updates[key]
|
||||
entry["updatedAt"] = self._now_iso()
|
||||
|
||||
@@ -61,7 +61,7 @@ class WorkflowStudio:
|
||||
app.router.add_get("/wfm", serve_index_page)
|
||||
|
||||
# API routes
|
||||
from .routes import workflow_routes, settings_routes, ollama_routes, eagle_routes, nodes_routes, prompts_routes
|
||||
from .routes import workflow_routes, settings_routes, ollama_routes, eagle_routes, nodes_routes, prompts_routes, models_routes, gallery_routes, wildcard_routes
|
||||
|
||||
workflow_routes.setup_routes(app)
|
||||
settings_routes.setup_routes(app)
|
||||
@@ -69,5 +69,8 @@ class WorkflowStudio:
|
||||
eagle_routes.setup_routes(app)
|
||||
nodes_routes.setup_routes(app)
|
||||
prompts_routes.setup_routes(app)
|
||||
models_routes.setup_routes(app)
|
||||
gallery_routes.setup_routes(app)
|
||||
wildcard_routes.setup_routes(app)
|
||||
|
||||
logger.info("Workflow Studio: Routes registered successfully")
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[project]
|
||||
name = "comfyui-workflow-studio"
|
||||
description = "A comprehensive workflow management and generation UI plugin for ComfyUI. Browse, organize, and execute workflows from a dedicated studio interface."
|
||||
version = "0.3.7"
|
||||
license = "MIT"
|
||||
requires-python = ">= 3.10"
|
||||
dependencies = ["jinja2"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/ketle-man/ComfyUI-Workflow-Studio"
|
||||
|
||||
[tool.comfy]
|
||||
PublisherId = "statsu"
|
||||
DisplayName = "Workflow Studio"
|
||||
Icon = "https://raw.githubusercontent.com/ketle-man/ComfyUI-Workflow-Studio/main/docs/thumb.png"
|
||||
Banner = "https://raw.githubusercontent.com/ketle-man/ComfyUI-Workflow-Studio/main/assets/banner.svg"
|
||||
@@ -0,0 +1,649 @@
|
||||
/* ============================================================
|
||||
Gallery Tab Styles
|
||||
============================================================ */
|
||||
|
||||
/* ── 3カラムレイアウト ──────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-layout {
|
||||
display: flex;
|
||||
height: calc(100vh - var(--wfm-header-height, 96px));
|
||||
overflow: hidden;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
/* ── 左: フォルダツリーパネル ──────────────────────────────── */
|
||||
|
||||
.wfm-gallery-tree-panel {
|
||||
width: 250px;
|
||||
min-width: 250px;
|
||||
max-width: 250px;
|
||||
border-right: 1px solid var(--wfm-border);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--wfm-bg-secondary, #1a1a2e);
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-title {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
|
||||
.wfm-gallery-tree {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px 8px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-primary);
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-item:hover {
|
||||
background: var(--wfm-bg-hover, rgba(255,255,255,0.06));
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-item.selected {
|
||||
background: var(--wfm-accent, #4f8ef7);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-item.selected .wfm-gallery-tree-count {
|
||||
background: rgba(255,255,255,0.25);
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-arrow {
|
||||
font-size: 10px;
|
||||
width: 14px;
|
||||
flex-shrink: 0;
|
||||
cursor: pointer;
|
||||
color: var(--wfm-text-secondary);
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-label {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-count {
|
||||
font-size: 10px;
|
||||
background: var(--wfm-accent-muted, rgba(79,142,247,0.2));
|
||||
color: var(--wfm-accent, #4f8ef7);
|
||||
border-radius: 8px;
|
||||
padding: 0 5px;
|
||||
line-height: 1.4;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-gallery-tree-children {
|
||||
/* 子ノードコンテナ */
|
||||
}
|
||||
|
||||
/* ── 中: 画像一覧パネル ────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-list-panel {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
min-width: 0;
|
||||
border-right: 1px solid var(--wfm-border);
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
}
|
||||
|
||||
.wfm-gallery-grid {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
/* サムネイルビュー */
|
||||
.wfm-gallery-view-thumb {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 8px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-card {
|
||||
position: relative;
|
||||
background: var(--wfm-bg-secondary, #1a1a2e);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-card:hover {
|
||||
border-color: var(--wfm-accent, #4f8ef7);
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-card.selected {
|
||||
border-color: var(--wfm-accent, #4f8ef7);
|
||||
box-shadow: 0 0 0 2px var(--wfm-accent, #4f8ef7);
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-card.multi-selected {
|
||||
border-color: #f59e0b;
|
||||
box-shadow: 0 0 0 2px #f59e0b;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-img {
|
||||
width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
background: var(--wfm-bg-hover, #111);
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-placeholder {
|
||||
width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--wfm-bg-hover, #222);
|
||||
color: var(--wfm-text-secondary);
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
/* お気に入りボタン(サムネイルカード右上) */
|
||||
.wfm-gallery-thumb-fav-btn {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
background: rgba(0,0,0,0.5);
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
color: rgba(255,255,255,0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-card:hover .wfm-gallery-thumb-fav-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-fav-btn.active {
|
||||
color: #fbbf24;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-fav-btn:hover {
|
||||
background: rgba(0,0,0,0.75);
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
/* テーブルビューのお気に入りボタン */
|
||||
.wfm-gallery-table-fav-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
color: rgba(255,255,255,0.3);
|
||||
padding: 2px 4px;
|
||||
transition: color 0.15s;
|
||||
}
|
||||
|
||||
.wfm-gallery-table-fav-btn:hover,
|
||||
.wfm-gallery-table-fav-btn.active {
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px;
|
||||
padding: 4px 6px;
|
||||
}
|
||||
|
||||
/* テーブルビュー */
|
||||
.wfm-gallery-view-table {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.wfm-gallery-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.wfm-gallery-table thead th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--wfm-bg-secondary, #1a1a2e);
|
||||
color: var(--wfm-text-secondary);
|
||||
font-weight: 600;
|
||||
padding: 6px 8px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.wfm-gallery-table tbody tr {
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.wfm-gallery-table tbody tr:hover {
|
||||
background: var(--wfm-bg-hover, rgba(255,255,255,0.05));
|
||||
}
|
||||
|
||||
.wfm-gallery-table tbody tr.selected {
|
||||
background: rgba(79,142,247,0.15);
|
||||
}
|
||||
|
||||
.wfm-gallery-table tbody tr.multi-selected {
|
||||
background: rgba(245,158,11,0.15);
|
||||
}
|
||||
|
||||
.wfm-gallery-table td {
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
color: var(--wfm-text-primary);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.wfm-gallery-table-thumb {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
object-fit: cover;
|
||||
border-radius: 3px;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.wfm-gallery-table-name {
|
||||
max-width: 200px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ── タグバッジ共通 ────────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-tag-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
background: rgba(79,142,247,0.15);
|
||||
color: var(--wfm-accent, #4f8ef7);
|
||||
border: 1px solid rgba(79,142,247,0.3);
|
||||
border-radius: 10px;
|
||||
padding: 1px 7px;
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-gallery-tag-remove {
|
||||
background: none;
|
||||
border: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
opacity: 0.7;
|
||||
margin-left: 1px;
|
||||
}
|
||||
|
||||
.wfm-gallery-tag-remove:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* ── 右: 詳細パネル ────────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-detail-panel {
|
||||
width: 280px;
|
||||
min-width: 280px;
|
||||
max-width: 280px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
background: var(--wfm-bg-secondary, #1a1a2e);
|
||||
}
|
||||
|
||||
.wfm-gallery-detail-header {
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
}
|
||||
|
||||
.wfm-gallery-detail-filename {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-primary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* プレビュー */
|
||||
.wfm-gallery-detail-preview {
|
||||
width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
max-height: 200px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-gallery-detail-img {
|
||||
max-width: 100%;
|
||||
max-height: 200px;
|
||||
object-fit: contain;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* タブコンテンツ */
|
||||
.wfm-gallery-detail-tab-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.wfm-gallery-section-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-primary);
|
||||
margin-bottom: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.wfm-gallery-info-section {
|
||||
margin-bottom: 4px;
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
.wfm-gallery-info-row {
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-primary);
|
||||
margin-bottom: 3px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-gallery-tags-display {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.wfm-gallery-memo {
|
||||
width: 100%;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 4px;
|
||||
color: var(--wfm-text-primary);
|
||||
font-size: 12px;
|
||||
padding: 6px 8px;
|
||||
resize: vertical;
|
||||
box-sizing: border-box;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.wfm-gallery-memo:focus {
|
||||
outline: none;
|
||||
border-color: var(--wfm-accent, #4f8ef7);
|
||||
}
|
||||
|
||||
/* ── Metadataタブ(Workflow全幅表示) ─────────────────────── */
|
||||
|
||||
.wfm-gallery-meta-tab {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0 !important;
|
||||
overflow: hidden;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.wfm-gallery-meta-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.wfm-gallery-meta-status {
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-gallery-workflow-json {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
padding: 10px;
|
||||
font-family: "Consolas", "Monaco", monospace;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
color: var(--wfm-text-primary);
|
||||
background: var(--wfm-bg-secondary, #1a1a2e);
|
||||
overflow: auto;
|
||||
white-space: pre;
|
||||
word-break: normal;
|
||||
border: none;
|
||||
}
|
||||
|
||||
/* グループ */
|
||||
.wfm-gallery-current-groups {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-bottom: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-secondary);
|
||||
}
|
||||
|
||||
.wfm-gallery-groups-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.wfm-gallery-group-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 6px;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.wfm-gallery-group-name {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--wfm-text-primary);
|
||||
}
|
||||
|
||||
/* ── 一括操作バー ──────────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-bulk-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 10px;
|
||||
background: rgba(245,158,11,0.12);
|
||||
border-bottom: 1px solid rgba(245,158,11,0.35);
|
||||
flex-shrink: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.wfm-gallery-bulk-count {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #f59e0b;
|
||||
white-space: nowrap;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
/* ── ライトボックス ─────────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.9);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.wfm-gallery-lightbox-inner {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
.wfm-gallery-lightbox-img {
|
||||
max-width: 90vw;
|
||||
max-height: 85vh;
|
||||
object-fit: contain;
|
||||
border-radius: 4px;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.wfm-gallery-lightbox-footer {
|
||||
margin-top: 8px;
|
||||
color: rgba(255,255,255,0.7);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wfm-gallery-lightbox-close {
|
||||
position: absolute;
|
||||
top: -12px;
|
||||
right: -12px;
|
||||
background: rgba(0,0,0,0.7);
|
||||
border: 1px solid rgba(255,255,255,0.2);
|
||||
color: #fff;
|
||||
border-radius: 50%;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
line-height: 1;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.wfm-gallery-lightbox-close:hover {
|
||||
background: rgba(255,255,255,0.2);
|
||||
}
|
||||
|
||||
/* ── ファイル操作ボタン (詳細パネル) ─────────────────────────── */
|
||||
|
||||
.wfm-gallery-file-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.wfm-gallery-file-actions .wfm-btn {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ── 移動先選択モーダル ──────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-move-modal {
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
min-width: 320px;
|
||||
max-width: 480px;
|
||||
width: 90%;
|
||||
box-shadow: 0 8px 32px rgba(0,0,0,0.5);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.wfm-gallery-move-modal-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-primary);
|
||||
}
|
||||
|
||||
.wfm-gallery-move-dest-sel {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.wfm-gallery-move-modal-footer {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
@@ -90,7 +90,7 @@ function initTabs() {
|
||||
|
||||
function applyI18nToHtml() {
|
||||
// Tab labels
|
||||
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", generate: "tabGenerate", prompt: "tabPrompt", settings: "tabSettings", help: "tabHelp" };
|
||||
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", metadata: "tabMetadata", gallery: "tabGallery", settings: "tabSettings", help: "tabHelp" };
|
||||
document.querySelectorAll(".wfm-tab").forEach((tab) => {
|
||||
const key = tabMap[tab.dataset.tab];
|
||||
if (key) tab.textContent = t(key);
|
||||
@@ -163,6 +163,39 @@ function applyI18nToHtml() {
|
||||
const nodesPlaceholder = document.getElementById("wfm-nodes-placeholder");
|
||||
if (nodesPlaceholder) nodesPlaceholder.textContent = t("nodesClickToLoad");
|
||||
|
||||
// Models tab
|
||||
const modelsTypeBtns = document.querySelectorAll(".wfm-models-type-btn");
|
||||
modelsTypeBtns.forEach(btn => {
|
||||
const key = "models" + btn.dataset.modelType.charAt(0).toUpperCase() + btn.dataset.modelType.slice(1);
|
||||
const label = t(key);
|
||||
if (label && label !== key) btn.textContent = label;
|
||||
});
|
||||
const modelsSearch = document.getElementById("wfm-models-search");
|
||||
if (modelsSearch) modelsSearch.placeholder = t("modelsSearchPlaceholder");
|
||||
const modelsRefreshBtn = document.getElementById("wfm-models-refresh-btn");
|
||||
if (modelsRefreshBtn) modelsRefreshBtn.textContent = t("modelsRefresh");
|
||||
const modelsPlaceholder = document.getElementById("wfm-models-placeholder");
|
||||
if (modelsPlaceholder) modelsPlaceholder.textContent = t("modelsClickToLoad");
|
||||
const modelsTagFilter = document.getElementById("wfm-models-tag-filter");
|
||||
if (modelsTagFilter) {
|
||||
const firstOpt = modelsTagFilter.querySelector("option[value='']");
|
||||
if (firstOpt) firstOpt.textContent = t("modelsAllTags");
|
||||
}
|
||||
const modelsSideTabBtns = document.querySelectorAll(".wfm-models-side-tab-btn");
|
||||
modelsSideTabBtns.forEach(btn => {
|
||||
if (btn.dataset.sideTab === "info") btn.textContent = t("modelsSideInfo");
|
||||
if (btn.dataset.sideTab === "group") btn.textContent = t("modelsSideGroup");
|
||||
if (btn.dataset.sideTab === "civitai") btn.textContent = t("modelsSideCivitai");
|
||||
});
|
||||
|
||||
// Gallery tab
|
||||
const gallerySideTabBtns = document.querySelectorAll(".wfm-gallery-detail-tab-btn");
|
||||
gallerySideTabBtns.forEach(btn => {
|
||||
if (btn.dataset.detailTab === "info") btn.textContent = t("modelsSideInfo");
|
||||
if (btn.dataset.detailTab === "meta") btn.textContent = t("gallerySideMetadata");
|
||||
if (btn.dataset.detailTab === "group") btn.textContent = t("modelsSideGroup");
|
||||
});
|
||||
|
||||
// Prompt tab
|
||||
const assistantHeader = document.querySelector(".wfm-prompt-split-left .wfm-prompt-split-header");
|
||||
if (assistantHeader) assistantHeader.textContent = t("assistantSubtab");
|
||||
@@ -227,26 +260,52 @@ function applyI18nToHtml() {
|
||||
"wfm-help-about-1": "helpAbout1", "wfm-help-about-2": "helpAbout2",
|
||||
"wfm-help-wf-1": "helpWf1", "wfm-help-wf-2": "helpWf2", "wfm-help-wf-3": "helpWf3",
|
||||
"wfm-help-wf-4": "helpWf4", "wfm-help-wf-5": "helpWf5", "wfm-help-wf-6": "helpWf6",
|
||||
"wfm-help-wf-7": "helpWf7", "wfm-help-wf-8": "helpWf8",
|
||||
"wfm-help-wf-7": "helpWf7",
|
||||
"wfm-help-gen-1": "helpGen1", "wfm-help-gen-2": "helpGen2",
|
||||
"wfm-help-gen-3": "helpGen3", "wfm-help-gen-4": "helpGen4",
|
||||
"wfm-help-gen-5": "helpGen5", "wfm-help-gen-6": "helpGen6", "wfm-help-gen-7": "helpGen7",
|
||||
"wfm-help-gen-8": "helpGen8", "wfm-help-gen-9": "helpGen9", "wfm-help-gen-10": "helpGen10",
|
||||
"wfm-help-gen-11": "helpGen11",
|
||||
"wfm-help-feeder-title": "helpFeederTitle",
|
||||
"wfm-help-feeder-desc": "helpFeederDesc",
|
||||
"wfm-help-feeder-1": "helpFeeder1", "wfm-help-feeder-2": "helpFeeder2",
|
||||
"wfm-help-feeder-3": "helpFeeder3", "wfm-help-feeder-4": "helpFeeder4",
|
||||
"wfm-help-feeder-5": "helpFeeder5", "wfm-help-feeder-6": "helpFeeder6",
|
||||
"wfm-help-feeder-7": "helpFeeder7", "wfm-help-feeder-8": "helpFeeder8",
|
||||
"wfm-help-feeder-9": "helpFeeder9",
|
||||
"wfm-help-prompt-1": "helpPrompt1", "wfm-help-prompt-2": "helpPrompt2",
|
||||
"wfm-help-prompt-3": "helpPrompt3", "wfm-help-prompt-4": "helpPrompt4",
|
||||
"wfm-help-prompt-5": "helpPrompt5", "wfm-help-prompt-6": "helpPrompt6",
|
||||
"wfm-help-prompt-7": "helpPrompt7",
|
||||
"wfm-help-prompt-7": "helpPrompt7", "wfm-help-prompt-8": "helpPrompt8",
|
||||
"wfm-help-prompt-9": "helpPrompt9",
|
||||
"wfm-help-settings-1": "helpSettings1", "wfm-help-settings-2": "helpSettings2",
|
||||
"wfm-help-settings-3": "helpSettings3", "wfm-help-settings-4": "helpSettings4",
|
||||
"wfm-help-settings-5": "helpSettings5", "wfm-help-settings-6": "helpSettings6",
|
||||
"wfm-help-settings-7": "helpSettings7", "wfm-help-settings-8": "helpSettings8",
|
||||
"wfm-help-settings-9": "helpSettings9", "wfm-help-settings-10": "helpSettings10",
|
||||
"wfm-help-nodes-1": "helpNodes1", "wfm-help-nodes-2": "helpNodes2",
|
||||
"wfm-help-nodes-3": "helpNodes3", "wfm-help-nodes-4": "helpNodes4",
|
||||
"wfm-help-nodes-5": "helpNodes5", "wfm-help-nodes-6": "helpNodes6",
|
||||
"wfm-help-models-1": "helpModels1", "wfm-help-models-2": "helpModels2",
|
||||
"wfm-help-models-3": "helpModels3", "wfm-help-models-4": "helpModels4",
|
||||
"wfm-help-models-5": "helpModels5", "wfm-help-models-6": "helpModels6",
|
||||
"wfm-help-models-7": "helpModels7", "wfm-help-models-8": "helpModels8",
|
||||
"wfm-help-models-9": "helpModels9", "wfm-help-models-10": "helpModels10",
|
||||
"wfm-help-models-11": "helpModels11",
|
||||
"wfm-help-gallery-title": "helpGalleryTitle",
|
||||
"wfm-help-gallery-1": "helpGallery1", "wfm-help-gallery-2": "helpGallery2",
|
||||
"wfm-help-gallery-3": "helpGallery3", "wfm-help-gallery-4": "helpGallery4",
|
||||
"wfm-help-gallery-5": "helpGallery5", "wfm-help-gallery-6": "helpGallery6",
|
||||
"wfm-help-gallery-7": "helpGallery7", "wfm-help-gallery-8": "helpGallery8",
|
||||
"wfm-help-gallery-9": "helpGallery9", "wfm-help-gallery-10": "helpGallery10",
|
||||
"wfm-help-gallery-11": "helpGallery11",
|
||||
"wfm-help-sidepanel-title": "helpSidepanelTitle",
|
||||
"wfm-help-sidepanel-1": "helpSidepanel1", "wfm-help-sidepanel-2": "helpSidepanel2",
|
||||
"wfm-help-sidepanel-3": "helpSidepanel3", "wfm-help-sidepanel-4": "helpSidepanel4",
|
||||
"wfm-help-sidepanel-5": "helpSidepanel5", "wfm-help-sidepanel-6": "helpSidepanel6",
|
||||
"wfm-help-sidepanel-7": "helpSidepanel7", "wfm-help-sidepanel-8": "helpSidepanel8",
|
||||
"wfm-help-sidepanel-9": "helpSidepanel9", "wfm-help-sidepanel-10": "helpSidepanel10",
|
||||
"wfm-help-sidepanel-11": "helpSidepanel11", "wfm-help-sidepanel-12": "helpSidepanel12",
|
||||
"wfm-help-shortcuts-title": "helpShortcutsTitle",
|
||||
"wfm-help-shortcuts-1": "helpShortcuts1", "wfm-help-shortcuts-2": "helpShortcuts2",
|
||||
"wfm-help-shortcuts-3": "helpShortcuts3", "wfm-help-shortcuts-4": "helpShortcuts4",
|
||||
@@ -301,6 +360,9 @@ import { initNodesTab } from "./nodes-tab.js";
|
||||
import { initGenerateTab } from "./generate-tab.js";
|
||||
import { initPromptTab } from "./prompt-tab.js";
|
||||
import { initSettingsTab, applyTheme, getSavedTheme } from "./settings-tab.js";
|
||||
import { initModelsTab } from "./models-tab.js";
|
||||
import { initGalleryTab } from "./gallery-tab.js";
|
||||
import { initMetadataTab } from "./metadata-tab.js";
|
||||
|
||||
// Apply saved theme immediately to prevent flash of default theme
|
||||
applyTheme(getSavedTheme());
|
||||
@@ -312,8 +374,11 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
initSettingsTab(); // Settings first (applies saved URL)
|
||||
initWorkflowTab();
|
||||
initNodesTab();
|
||||
initModelsTab();
|
||||
initGenerateTab();
|
||||
initPromptTab();
|
||||
initMetadataTab();
|
||||
initGalleryTab();
|
||||
|
||||
console.log("Workflow Studio: App initialized");
|
||||
});
|
||||
|
||||
@@ -88,7 +88,13 @@ export const comfyUI = {
|
||||
try {
|
||||
const info = await this.fetchObjectInfo(cls);
|
||||
if (info?.[cls]?.input?.required?.[inputKey]) {
|
||||
return info[cls].input.required[inputKey][0] || [];
|
||||
const inputDef = info[cls].input.required[inputKey];
|
||||
const first = inputDef[0];
|
||||
if (Array.isArray(first)) return first;
|
||||
// Newer ComfyUI format: ["COMBO", { "values": [...] }]
|
||||
if (typeof first === "string" && Array.isArray(inputDef[1]?.values)) {
|
||||
return inputDef[1].values;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
@@ -134,6 +140,25 @@ export const comfyUI = {
|
||||
);
|
||||
},
|
||||
|
||||
async fetchHypernetworks() {
|
||||
return this._fetchModelList(
|
||||
["HypernetworkLoader"],
|
||||
"hypernetwork_name"
|
||||
);
|
||||
},
|
||||
|
||||
async fetchEmbeddings() {
|
||||
// ComfyUI exposes embeddings via /embeddings endpoint
|
||||
try {
|
||||
const res = await fetch(`${this.baseUrl}/embeddings`);
|
||||
if (res.ok) {
|
||||
const list = await res.json();
|
||||
return Array.isArray(list) ? list : [];
|
||||
}
|
||||
} catch {}
|
||||
return [];
|
||||
},
|
||||
|
||||
async fetchSamplers() {
|
||||
return this._fetchModelList(["KSampler"], "sampler_name");
|
||||
},
|
||||
|
||||
@@ -61,6 +61,7 @@ export const comfyEditor = {
|
||||
this.renderImageTab(analysis, "wfm-gen-image-fields");
|
||||
this.renderModelTab(analysis, "wfm-gen-model-fields");
|
||||
this.renderSettingsTab(analysis, "wfm-gen-settings-fields");
|
||||
_syncRawJson();
|
||||
},
|
||||
|
||||
renderPromptTab(analysis, containerId) {
|
||||
@@ -76,7 +77,7 @@ export const comfyEditor = {
|
||||
<label>Positive Prompt</label>
|
||||
<div style="display:flex;gap:8px;margin-bottom:6px;">
|
||||
<select id="wfm-prompt-pos-target" class="wfm-select" style="width:auto;flex:1">
|
||||
${positiveNodes.map((n) => `<option value="${n.id}" selected>ID:${n.id} (${n.title})</option>`).join("")}
|
||||
${positiveNodes.map((n) => `<option value="${n.id}" data-text-key="${n.textKey || "text"}" selected>ID:${n.id} (${n.title})</option>`).join("")}
|
||||
${nodeOpts}
|
||||
</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-prompt-pos-apply">Apply</button>
|
||||
@@ -87,7 +88,7 @@ export const comfyEditor = {
|
||||
<label>Negative Prompt</label>
|
||||
<div style="display:flex;gap:8px;margin-bottom:6px;">
|
||||
<select id="wfm-prompt-neg-target" class="wfm-select" style="width:auto;flex:1">
|
||||
${negativeNodes.map((n) => `<option value="${n.id}" selected>ID:${n.id} (${n.title})</option>`).join("")}
|
||||
${negativeNodes.map((n) => `<option value="${n.id}" data-text-key="${n.textKey || "text"}" selected>ID:${n.id} (${n.title})</option>`).join("")}
|
||||
${nodeOpts}
|
||||
</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-prompt-neg-apply">Apply</button>
|
||||
@@ -100,7 +101,9 @@ export const comfyEditor = {
|
||||
const nodeId = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
const text = document.getElementById("wfm-prompt-pos-text")?.value;
|
||||
if (nodeId && comfyUI.currentWorkflow?.[nodeId]) {
|
||||
comfyUI.currentWorkflow[nodeId].inputs.text = text;
|
||||
const promptNode = (analysis.prompt_nodes || []).find(n => n.id === nodeId);
|
||||
const textKey = promptNode?.textKey || "text";
|
||||
comfyUI.currentWorkflow[nodeId].inputs[textKey] = text;
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
@@ -109,7 +112,9 @@ export const comfyEditor = {
|
||||
const nodeId = document.getElementById("wfm-prompt-neg-target")?.value;
|
||||
const text = document.getElementById("wfm-prompt-neg-text")?.value;
|
||||
if (nodeId && comfyUI.currentWorkflow?.[nodeId]) {
|
||||
comfyUI.currentWorkflow[nodeId].inputs.text = text;
|
||||
const promptNode = (analysis.prompt_nodes || []).find(n => n.id === nodeId);
|
||||
const textKey = promptNode?.textKey || "text";
|
||||
comfyUI.currentWorkflow[nodeId].inputs[textKey] = text;
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
@@ -208,11 +213,11 @@ export const comfyEditor = {
|
||||
const latent = analysis.latent_nodes?.[0];
|
||||
|
||||
el.innerHTML = `
|
||||
<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
|
||||
<div>
|
||||
<h3 style="font-size:14px;margin-bottom:12px;">KSampler</h3>
|
||||
<div style="display:flex;flex-direction:row;gap:0;align-items:flex-start;">
|
||||
<div style="flex:1;min-width:0;padding-right:14px;border-right:1px solid var(--wfm-border);">
|
||||
<h3 style="font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;color:var(--wfm-text-secondary);margin:0 0 12px;">KSampler</h3>
|
||||
${sampler ? `
|
||||
<input type="hidden" id="wfm-settings-sampler-id" value="${sampler.id}">
|
||||
<input type="hidden" id="wfm-settings-sampler-id" value="${sampler.id}" data-seed-key="${sampler.seedKey || "seed"}">
|
||||
<div class="wfm-form-group">
|
||||
<label>Seed</label>
|
||||
<input type="number" class="wfm-input" id="wfm-settings-seed" value="${sampler.seed ?? -1}">
|
||||
@@ -244,8 +249,8 @@ export const comfyEditor = {
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-sampler-apply">Apply</button>
|
||||
` : "<p class='wfm-placeholder'>No KSampler node found</p>"}
|
||||
</div>
|
||||
<div>
|
||||
<h3 style="font-size:14px;margin-bottom:12px;">Latent Image</h3>
|
||||
<div style="flex:1;min-width:0;padding-left:14px;">
|
||||
<h3 style="font-size:13px;font-weight:600;text-transform:uppercase;letter-spacing:0.5px;color:var(--wfm-text-secondary);margin:0 0 12px;">Latent Image</h3>
|
||||
${latent ? `
|
||||
<input type="hidden" id="wfm-settings-latent-id" value="${latent.id}">
|
||||
<div class="wfm-form-group">
|
||||
@@ -270,7 +275,9 @@ export const comfyEditor = {
|
||||
const nodeId = document.getElementById("wfm-settings-sampler-id")?.value;
|
||||
if (!nodeId || !comfyUI.currentWorkflow?.[nodeId]) return;
|
||||
const inputs = comfyUI.currentWorkflow[nodeId].inputs;
|
||||
inputs.seed = parseInt(document.getElementById("wfm-settings-seed")?.value) || -1;
|
||||
// KSamplerAdvanced uses noise_seed; fall back to seed
|
||||
const seedKey = document.getElementById("wfm-settings-sampler-id")?.dataset?.seedKey || "seed";
|
||||
inputs[seedKey] = parseInt(document.getElementById("wfm-settings-seed")?.value) || -1;
|
||||
inputs.steps = parseInt(document.getElementById("wfm-settings-steps")?.value) || 20;
|
||||
inputs.cfg = parseFloat(document.getElementById("wfm-settings-cfg")?.value) || 7;
|
||||
inputs.sampler_name = document.getElementById("wfm-settings-sampler-name")?.value;
|
||||
@@ -401,16 +408,20 @@ export const comfyEditor = {
|
||||
|
||||
syncToWorkflow() {
|
||||
// Sync prompt texts before generation
|
||||
const posTarget = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
const posSelect = document.getElementById("wfm-prompt-pos-target");
|
||||
const posTarget = posSelect?.value;
|
||||
const posText = document.getElementById("wfm-prompt-pos-text")?.value;
|
||||
if (posTarget && comfyUI.currentWorkflow?.[posTarget]) {
|
||||
comfyUI.currentWorkflow[posTarget].inputs.text = posText;
|
||||
const posTextKey = posSelect.selectedOptions[0]?.dataset?.textKey || "text";
|
||||
comfyUI.currentWorkflow[posTarget].inputs[posTextKey] = posText;
|
||||
}
|
||||
|
||||
const negTarget = document.getElementById("wfm-prompt-neg-target")?.value;
|
||||
const negSelect = document.getElementById("wfm-prompt-neg-target");
|
||||
const negTarget = negSelect?.value;
|
||||
const negText = document.getElementById("wfm-prompt-neg-text")?.value;
|
||||
if (negTarget && comfyUI.currentWorkflow?.[negTarget]) {
|
||||
comfyUI.currentWorkflow[negTarget].inputs.text = negText;
|
||||
const negTextKey = negSelect.selectedOptions[0]?.dataset?.textKey || "text";
|
||||
comfyUI.currentWorkflow[negTarget].inputs[negTextKey] = negText;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@@ -343,6 +343,24 @@ export const comfyWorkflow = {
|
||||
wIdx++;
|
||||
}
|
||||
}
|
||||
// For COMBO inputs, validate the value against the available choices.
|
||||
// Dynamic COMBO options (e.g. Impact Pack's "Select to add Wildcard") may
|
||||
// differ between the saved workflow and the current ComfyUI instance
|
||||
// (e.g. "Select Wildcard 🟢 Full Cache" vs "Select Wildcard"), causing
|
||||
// "Prompt outputs failed validation". Fall back to first choice when mismatch.
|
||||
if (expectedType === "COMBO") {
|
||||
const allInputDefs = {
|
||||
...(objectInfo[node.type]?.input?.required || {}),
|
||||
...(objectInfo[node.type]?.input?.optional || {}),
|
||||
};
|
||||
const spec = allInputDefs[name];
|
||||
if (spec) {
|
||||
const choices = Array.isArray(spec[0]) ? spec[0] : null;
|
||||
if (choices && choices.length > 0 && !choices.includes(val)) {
|
||||
val = choices[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
inputs[name] = val;
|
||||
}
|
||||
} else {
|
||||
@@ -446,7 +464,7 @@ export const comfyWorkflow = {
|
||||
|
||||
if (!workflow) return result;
|
||||
|
||||
// Build sampler connections for prompt classification
|
||||
// === Pass 1: Collect sampler refs + all_nodes ===
|
||||
const samplerPositiveRef = {};
|
||||
const samplerNegativeRef = {};
|
||||
|
||||
@@ -462,40 +480,174 @@ export const comfyWorkflow = {
|
||||
if (Array.isArray(inputs.positive)) samplerPositiveRef[inputs.positive[0]] = true;
|
||||
if (Array.isArray(inputs.negative)) samplerNegativeRef[inputs.negative[0]] = true;
|
||||
|
||||
// KSamplerAdvanced uses noise_seed instead of seed
|
||||
const seedKey = "seed" in inputs ? "seed" : "noise_seed";
|
||||
result.sampler_nodes.push({
|
||||
id, type: ct, title,
|
||||
seed: inputs.seed, steps: inputs.steps, cfg: inputs.cfg,
|
||||
seed: inputs.seed ?? inputs.noise_seed,
|
||||
seedKey,
|
||||
steps: inputs.steps, cfg: inputs.cfg,
|
||||
sampler_name: inputs.sampler_name, scheduler: inputs.scheduler,
|
||||
denoise: inputs.denoise,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// === Pass 1b: Expand refs through CONDITIONING graph (BFS, 5 iterations) ===
|
||||
// Nodes that pass CONDITIONING through without changing positive/negative role
|
||||
const COND_PASSTHROUGH = new Set([
|
||||
"ConditioningCombine", "ConditioningConcat", "ConditioningAverage",
|
||||
"ConditioningZeroOut", "ConditioningSetTimestepRange",
|
||||
"ControlNetApply", "ControlNetApplyAdvanced",
|
||||
"IPAdapterApply", "IPAdapterApplyFaceID",
|
||||
"StyleModelApply",
|
||||
]);
|
||||
|
||||
for (let iter = 0; iter < 5; iter++) {
|
||||
for (const [id, node] of Object.entries(workflow)) {
|
||||
if (!node?.class_type) continue;
|
||||
const ct = node.class_type;
|
||||
const inputs = node.inputs || {};
|
||||
const isPos = !!samplerPositiveRef[id];
|
||||
const isNeg = !!samplerNegativeRef[id];
|
||||
if (!isPos && !isNeg) continue;
|
||||
|
||||
if (COND_PASSTHROUGH.has(ct)) {
|
||||
for (const v of Object.values(inputs)) {
|
||||
if (Array.isArray(v)) {
|
||||
if (isPos) samplerPositiveRef[v[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[v[0]] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Propagate role through text encoder linked inputs (CLIPTextEncode → upstream text source)
|
||||
if (ct === "CLIPTextEncode") {
|
||||
const tv = inputs.text;
|
||||
if (Array.isArray(tv)) {
|
||||
if (isPos) samplerPositiveRef[tv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
if (ct === "CLIPTextEncodeSDXL" || ct === "CLIPTextEncodeSDXLRefiner") {
|
||||
for (const key of ["text_g", "text_l"]) {
|
||||
const tv = inputs[key];
|
||||
if (Array.isArray(tv)) {
|
||||
if (isPos) samplerPositiveRef[tv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ct === "ImpactWildcardEncode" || ct === "ImpactWildcardProcessor") {
|
||||
const tv = inputs.wildcard_text;
|
||||
if (Array.isArray(tv)) {
|
||||
if (isPos) samplerPositiveRef[tv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// === Pass 2: Main analysis ===
|
||||
for (const [id, node] of Object.entries(workflow)) {
|
||||
if (!node?.class_type) continue;
|
||||
const ct = node.class_type;
|
||||
const inputs = node.inputs || {};
|
||||
const title = node._meta?.title || ct;
|
||||
|
||||
if (ct.includes("CheckpointLoader")) {
|
||||
const isPos = !!samplerPositiveRef[id];
|
||||
const isNeg = !!samplerNegativeRef[id];
|
||||
|
||||
const getRole = () => {
|
||||
if (isPos && !isNeg) return "positive";
|
||||
if (isNeg && !isPos) return "negative";
|
||||
if (/pos|正/i.test(title)) return "positive";
|
||||
if (/neg|負/i.test(title)) return "negative";
|
||||
return "unknown";
|
||||
};
|
||||
|
||||
// --- Checkpoint nodes ---
|
||||
// Matches: CheckpointLoaderSimple, CheckpointLoader, "Checkpoint Loader" (WAS), etc.
|
||||
if (ct.includes("CheckpointLoader") || ct === "Checkpoint Loader") {
|
||||
result.checkpoint_nodes.push({
|
||||
id, type: ct, title,
|
||||
ckpt_name: inputs.ckpt_name,
|
||||
});
|
||||
}
|
||||
|
||||
// --- Prompt nodes ---
|
||||
|
||||
if (ct === "CLIPTextEncode") {
|
||||
let role = "unknown";
|
||||
if (samplerPositiveRef[id]) role = "positive";
|
||||
else if (samplerNegativeRef[id]) role = "negative";
|
||||
else if (/pos|正/i.test(title)) role = "positive";
|
||||
else if (/neg|負/i.test(title)) role = "negative";
|
||||
// Only add when text is a direct string (if linked, upstream node will be detected)
|
||||
const textVal = inputs.text;
|
||||
if (typeof textVal === "string") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: textVal, textKey: "text",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// SDXL dual-text encoder
|
||||
if (ct === "CLIPTextEncodeSDXL" || ct === "CLIPTextEncodeSDXLRefiner") {
|
||||
const textG = inputs.text_g;
|
||||
const textL = inputs.text_l;
|
||||
// Add only if at least one text field is a direct string
|
||||
if (typeof textG === "string" || typeof textL === "string") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: typeof textG === "string" ? textG : (typeof textL === "string" ? textL : ""),
|
||||
textKey: typeof textG === "string" ? "text_g" : "text_l",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Qwen-based image+text encoder
|
||||
if (ct === "TextEncodeQwenImageEditPlus") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role,
|
||||
text: inputs.text,
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: inputs.prompt || "",
|
||||
textKey: "prompt",
|
||||
});
|
||||
}
|
||||
|
||||
// SDXLPromptStyler / SDXLPromptStylerAdvanced — contains both pos & neg in one node
|
||||
if (ct === "SDXLPromptStyler" || ct === "SDXLPromptStylerAdvanced") {
|
||||
if (inputs.text_positive !== undefined) {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title: `${title} [positive]`, role: "positive",
|
||||
text: inputs.text_positive || "", textKey: "text_positive",
|
||||
});
|
||||
}
|
||||
if (inputs.text_negative !== undefined) {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title: `${title} [negative]`, role: "negative",
|
||||
text: inputs.text_negative || "", textKey: "text_negative",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ImpactWildcardEncode / ImpactWildcardProcessor — treat wildcard_text as prompt
|
||||
if (ct === "ImpactWildcardEncode" || ct === "ImpactWildcardProcessor") {
|
||||
const textVal = inputs.wildcard_text;
|
||||
if (typeof textVal === "string") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: textVal, textKey: "wildcard_text",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// PrimitiveStringMultiline / PrimitiveString — when feeding a prompt node
|
||||
if ((ct === "PrimitiveStringMultiline" || ct === "PrimitiveString") && (isPos || isNeg)) {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: inputs.value || "",
|
||||
textKey: "value",
|
||||
});
|
||||
}
|
||||
|
||||
// --- Latent nodes ---
|
||||
if (ct === "EmptyLatentImage" || ct === "EmptySD3LatentImage") {
|
||||
result.latent_nodes.push({
|
||||
id, type: ct, title,
|
||||
@@ -504,6 +656,7 @@ export const comfyWorkflow = {
|
||||
});
|
||||
}
|
||||
|
||||
// --- LoRA nodes ---
|
||||
if (ct === "LoraLoader" || ct === "LoraLoaderModelOnly") {
|
||||
result.lora_nodes.push({
|
||||
id, type: ct, title,
|
||||
@@ -513,14 +666,31 @@ export const comfyWorkflow = {
|
||||
});
|
||||
}
|
||||
|
||||
// Power Lora Loader (rgthree) — dynamic lora_N inputs in API format
|
||||
if (ct === "Power Lora Loader (rgthree)") {
|
||||
for (const [k, v] of Object.entries(inputs)) {
|
||||
if (/^lora_\d+$/.test(k) && typeof v === "string") {
|
||||
result.lora_nodes.push({
|
||||
id, type: ct, title,
|
||||
lora_name: v,
|
||||
strength_model: inputs[k.replace("lora_", "strength_")] ?? 1,
|
||||
strength_clip: inputs[k.replace("lora_", "strength_clip_")] ?? 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- VAE nodes ---
|
||||
if (ct === "VAELoader") {
|
||||
result.vae_nodes.push({ id, type: ct, title, vae_name: inputs.vae_name });
|
||||
}
|
||||
|
||||
// --- Save/preview nodes ---
|
||||
if (ct === "SaveImage" || ct === "PreviewImage") {
|
||||
result.save_nodes.push({ id, type: ct, title });
|
||||
}
|
||||
|
||||
// --- Load image nodes ---
|
||||
if (ct === "LoadImage" || ct === "LoadImageMask"
|
||||
|| (ct.toLowerCase().includes("load") && ct.toLowerCase().includes("image") && inputs.image !== undefined)) {
|
||||
result.load_image_nodes.push({
|
||||
@@ -528,6 +698,7 @@ export const comfyWorkflow = {
|
||||
});
|
||||
}
|
||||
|
||||
// --- Text encoder (CLIP) nodes ---
|
||||
if (ct === "DualCLIPLoader" || ct === "CLIPLoader") {
|
||||
result.text_encoder_nodes.push({
|
||||
id, type: ct, title,
|
||||
@@ -536,12 +707,14 @@ export const comfyWorkflow = {
|
||||
});
|
||||
}
|
||||
|
||||
// --- Diffusion model nodes ---
|
||||
if (ct === "UNETLoader" || ct === "UnetLoaderGGUF") {
|
||||
result.diffusion_model_nodes.push({
|
||||
id, type: ct, title, unet_name: inputs.unet_name,
|
||||
});
|
||||
}
|
||||
|
||||
// --- ControlNet loader nodes ---
|
||||
if (ct.includes("ControlNetLoader")) {
|
||||
result.controlnet_nodes.push({
|
||||
id, type: ct, title,
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
/**
|
||||
* Feeder Tab - ImageFeeder node control with embedded image library
|
||||
*/
|
||||
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { showToast } from "./app.js";
|
||||
|
||||
// ── Module State ──────────────────────────────────────────────────
|
||||
const _s = {
|
||||
dir: "", // current folder relative path
|
||||
images: [], // filenames in current folder
|
||||
selected: new Set(),// selected filenames (across all interactions)
|
||||
presets: {}, // {presetName: {directory, selected_files}}
|
||||
running: false, // feeder run loop active
|
||||
};
|
||||
|
||||
// ── Node helpers ──────────────────────────────────────────────────
|
||||
|
||||
function _feederNodes() {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!wf) return [];
|
||||
return Object.entries(wf)
|
||||
.filter(([, n]) => n?.class_type === "ImageFeeder")
|
||||
.map(([id, n]) => ({ id, title: n._meta?.title || `ImageFeeder` }));
|
||||
}
|
||||
|
||||
export function refreshFeederNodeList() {
|
||||
const sel = document.getElementById("wfm-feeder-node-sel");
|
||||
if (!sel) return;
|
||||
const nodes = _feederNodes();
|
||||
if (nodes.length === 0) {
|
||||
sel.innerHTML = `<option value="">-- No ImageFeeder node --</option>`;
|
||||
return;
|
||||
}
|
||||
const prevVal = sel.value;
|
||||
sel.innerHTML = nodes.map(n =>
|
||||
`<option value="${n.id}">${n.title} (ID:${n.id})</option>`
|
||||
).join("");
|
||||
if (prevVal && nodes.find(n => n.id === prevVal)) sel.value = prevVal;
|
||||
_loadFromNode(sel.value || nodes[0].id);
|
||||
}
|
||||
|
||||
function _loadFromNode(nodeId) {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!wf?.[nodeId]) return;
|
||||
const inp = wf[nodeId].inputs || {};
|
||||
|
||||
_setVal("wfm-feeder-dir-input", inp.directory || "");
|
||||
_setVal("wfm-feeder-sort", inp.sort_mode || "ascending");
|
||||
_setVal("wfm-feeder-index", inp.index ?? 0);
|
||||
_setVal("wfm-feeder-start", inp.start_index ?? 0);
|
||||
_setVal("wfm-feeder-end", inp.end_index ?? 0);
|
||||
_setVal("wfm-feeder-batch", inp.batch_size ?? 1);
|
||||
_setVal("wfm-feeder-seed", inp.seed ?? 0);
|
||||
_setCheck("wfm-feeder-use-sel", inp.use_selection ?? true);
|
||||
|
||||
// Restore selected_files
|
||||
_s.selected.clear();
|
||||
try {
|
||||
const arr = JSON.parse(inp.selected_files || "[]");
|
||||
if (Array.isArray(arr)) arr.forEach(f => _s.selected.add(f));
|
||||
} catch {}
|
||||
|
||||
const dir = inp.directory || "";
|
||||
if (_s.dir !== dir) {
|
||||
_s.dir = dir;
|
||||
_loadImages(dir);
|
||||
_highlightTreeRow(dir);
|
||||
} else {
|
||||
_refreshGridCbs();
|
||||
}
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
function _applyToWorkflow() {
|
||||
const nodeId = document.getElementById("wfm-feeder-node-sel")?.value;
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!nodeId || !wf?.[nodeId]) {
|
||||
showToast("No ImageFeeder node selected", "error");
|
||||
return;
|
||||
}
|
||||
_applyToNode(nodeId);
|
||||
showToast("Applied to workflow", "success");
|
||||
}
|
||||
|
||||
// ── Run Loop ──────────────────────────────────────────────────────
|
||||
|
||||
function _setRunUI(running) {
|
||||
const runBtn = document.getElementById("wfm-feeder-run-btn");
|
||||
const stopBtn = document.getElementById("wfm-feeder-stop-btn");
|
||||
if (runBtn) runBtn.disabled = running;
|
||||
if (stopBtn) stopBtn.disabled = !running;
|
||||
}
|
||||
|
||||
function _applyToNode(nodeId) {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
const inp = wf[nodeId].inputs;
|
||||
inp.directory = _s.dir;
|
||||
inp.sort_mode = document.getElementById("wfm-feeder-sort")?.value || "ascending";
|
||||
inp.index = parseInt(document.getElementById("wfm-feeder-index")?.value) || 0;
|
||||
inp.start_index = parseInt(document.getElementById("wfm-feeder-start")?.value) || 0;
|
||||
inp.end_index = parseInt(document.getElementById("wfm-feeder-end")?.value) || 0;
|
||||
inp.batch_size = parseInt(document.getElementById("wfm-feeder-batch")?.value) || 1;
|
||||
inp.seed = parseInt(document.getElementById("wfm-feeder-seed")?.value) || 0;
|
||||
inp.use_selection = document.getElementById("wfm-feeder-use-sel")?.checked ?? true;
|
||||
inp.selected_files = JSON.stringify([..._s.selected]);
|
||||
}
|
||||
|
||||
async function _startRun() {
|
||||
if (_s.running) return;
|
||||
if (!comfyUI.currentWorkflow) { showToast("No workflow loaded", "error"); return; }
|
||||
if (!comfyUI.connected) { showToast("Not connected to ComfyUI", "error"); return; }
|
||||
|
||||
const nodeId = document.getElementById("wfm-feeder-node-sel")?.value;
|
||||
if (!nodeId || !comfyUI.currentWorkflow[nodeId]) {
|
||||
showToast("No ImageFeeder node selected", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// WebSocket を先に接続してノード sync メッセージを受け取れるようにする
|
||||
const wsOk = await comfyUI.connectWebSocket();
|
||||
if (!wsOk) { showToast("WebSocket connection failed", "error"); return; }
|
||||
|
||||
_s.running = true;
|
||||
_setRunUI(true);
|
||||
|
||||
const progressBar = document.getElementById("wfm-gen-progress-bar");
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
const resultImg = document.getElementById("wfm-gen-result-img");
|
||||
|
||||
// image_loop_node_sync メッセージを捕捉するリスナー
|
||||
let _lastSync = null;
|
||||
const _syncHandler = (ev) => {
|
||||
try {
|
||||
const msg = JSON.parse(ev.data);
|
||||
if (msg.type === "image_loop_node_sync" && String(msg.data?.node_id) === String(nodeId)) {
|
||||
_lastSync = msg.data;
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
comfyUI.socket.addEventListener("message", _syncHandler);
|
||||
|
||||
let count = 0;
|
||||
try {
|
||||
while (_s.running) {
|
||||
_lastSync = null;
|
||||
_applyToNode(nodeId);
|
||||
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
const inp = wf[nodeId].inputs;
|
||||
|
||||
if (progressBar) progressBar.style.width = "0%";
|
||||
if (progressText) progressText.textContent = `#${++count} 0%`;
|
||||
|
||||
// 右ペインのseed設定を使用(KSamplerに適用される)
|
||||
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
|
||||
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
|
||||
|
||||
const { images, seed } = await comfyUI.generate(
|
||||
{ ...wf },
|
||||
{
|
||||
seedMode,
|
||||
seedValue,
|
||||
onProgress: (pct) => {
|
||||
if (progressBar) progressBar.style.width = `${(pct * 100).toFixed(1)}%`;
|
||||
if (progressText) progressText.textContent = `#${count} ${(pct * 100).toFixed(0)}%`;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 右ペインのseed表示を更新(通常の生成と同じ挙動)
|
||||
const seedEl = document.getElementById("wfm-gen-seed-value");
|
||||
if (seedEl) seedEl.value = seed;
|
||||
|
||||
if (progressBar) progressBar.style.width = "100%";
|
||||
|
||||
if (images.length > 0 && resultImg) {
|
||||
const blob = await comfyUI.getImageBlob(images[0]);
|
||||
resultImg.src = URL.createObjectURL(blob);
|
||||
resultImg.style.display = "block";
|
||||
}
|
||||
|
||||
if (!_s.running) break;
|
||||
|
||||
// control after generate: ノードから返された next_index を反映
|
||||
const control = document.getElementById("wfm-feeder-control-after")?.value || "loop";
|
||||
if (control === "fixed") {
|
||||
// index を変えない
|
||||
} else if (_lastSync) {
|
||||
const indexEl = document.getElementById("wfm-feeder-index");
|
||||
if (indexEl) indexEl.value = _lastSync.next_index;
|
||||
if (control === "increment" && !_lastSync.has_next) {
|
||||
_s.running = false;
|
||||
showToast(`Feeder complete (${count} generated)`, "success");
|
||||
break;
|
||||
}
|
||||
// loop: has_next=false でも次は index=0 からなので続行
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (_s.running) showToast("Feeder run error: " + err.message, "error");
|
||||
} finally {
|
||||
comfyUI.socket?.removeEventListener("message", _syncHandler);
|
||||
_s.running = false;
|
||||
_setRunUI(false);
|
||||
if (progressText) progressText.textContent = `Done (${count} generated)`;
|
||||
}
|
||||
}
|
||||
|
||||
async function _stopRun() {
|
||||
_s.running = false;
|
||||
try { await comfyUI.interrupt(); } catch {}
|
||||
_setRunUI(false);
|
||||
showToast("Feeder stopped", "info");
|
||||
}
|
||||
|
||||
// ── Folder Tree ───────────────────────────────────────────────────
|
||||
|
||||
async function _loadTree() {
|
||||
const container = document.getElementById("wfm-feeder-tree");
|
||||
if (!container) return;
|
||||
container.innerHTML = `<div class="wfm-feeder-tree-msg">Loading...</div>`;
|
||||
try {
|
||||
const res = await fetch("/image_loop/tree");
|
||||
if (!res.ok) throw new Error(res.status);
|
||||
const data = await res.json();
|
||||
_renderTree(data.tree || [], container);
|
||||
} catch (err) {
|
||||
container.innerHTML = `<div class="wfm-feeder-tree-msg">Cannot reach image-loop API</div>`;
|
||||
console.warn("[Feeder] tree load failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function _renderTree(items, container, depth = 0) {
|
||||
if (depth === 0) {
|
||||
container.innerHTML = "";
|
||||
container.appendChild(_makeTreeRow("", "🏠 (root)", 0));
|
||||
}
|
||||
for (const item of items) {
|
||||
const icon = item.children?.length > 0 ? "📂" : "📁";
|
||||
container.appendChild(_makeTreeRow(item.path, `${icon} ${item.name}`, depth + 1));
|
||||
if (item.children?.length > 0) _renderTree(item.children, container, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
function _makeTreeRow(path, label, depth) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "wfm-feeder-tree-row" + (_s.dir === path ? " active" : "");
|
||||
row.style.paddingLeft = `${8 + depth * 12}px`;
|
||||
row.dataset.path = path;
|
||||
row.textContent = label;
|
||||
row.title = path || "(root)";
|
||||
row.addEventListener("click", () => _selectDir(path));
|
||||
return row;
|
||||
}
|
||||
|
||||
function _selectDir(path) {
|
||||
if (_s.dir !== path) {
|
||||
_s.selected.clear();
|
||||
_s.dir = path;
|
||||
_setVal("wfm-feeder-dir-input", path);
|
||||
}
|
||||
_highlightTreeRow(path);
|
||||
_loadImages(path);
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
function _highlightTreeRow(path) {
|
||||
document.querySelectorAll(".wfm-feeder-tree-row").forEach(el => {
|
||||
el.classList.toggle("active", el.dataset.path === path);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Image Grid ────────────────────────────────────────────────────
|
||||
|
||||
async function _loadImages(dir) {
|
||||
const grid = document.getElementById("wfm-feeder-grid");
|
||||
if (!grid) return;
|
||||
grid.innerHTML = `<div class="wfm-feeder-grid-msg">Loading...</div>`;
|
||||
try {
|
||||
const url = "/image_loop/images" + (dir ? `?dir=${encodeURIComponent(dir)}` : "");
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error(res.status);
|
||||
const data = await res.json();
|
||||
_s.images = data.images || [];
|
||||
_renderGrid();
|
||||
} catch (err) {
|
||||
_s.images = [];
|
||||
grid.innerHTML = `<div class="wfm-feeder-grid-msg" style="color:var(--wfm-danger)">Load failed: ${err.message}</div>`;
|
||||
}
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
function _renderGrid() {
|
||||
const grid = document.getElementById("wfm-feeder-grid");
|
||||
if (!grid) return;
|
||||
if (_s.images.length === 0) {
|
||||
grid.innerHTML = `<div class="wfm-feeder-grid-msg">No images found</div>`;
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = "";
|
||||
for (const fname of _s.images) grid.appendChild(_makeCard(fname));
|
||||
}
|
||||
|
||||
function _makeCard(fname) {
|
||||
const relPath = _s.dir ? `${_s.dir}/${fname}` : fname;
|
||||
const checked = _s.selected.has(fname);
|
||||
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-feeder-card" + (checked ? " selected" : "");
|
||||
card.dataset.name = fname;
|
||||
|
||||
const cb = document.createElement("input");
|
||||
cb.type = "checkbox";
|
||||
cb.className = "wfm-feeder-card-cb";
|
||||
cb.checked = checked;
|
||||
cb.addEventListener("change", e => {
|
||||
e.stopPropagation();
|
||||
if (cb.checked) _s.selected.add(fname);
|
||||
else _s.selected.delete(fname);
|
||||
card.classList.toggle("selected", cb.checked);
|
||||
_updateStatus();
|
||||
});
|
||||
|
||||
const img = document.createElement("img");
|
||||
img.className = "wfm-feeder-card-img";
|
||||
img.loading = "lazy";
|
||||
img.src = `/image_loop/thumbnail?path=${encodeURIComponent(relPath)}`;
|
||||
img.onerror = () => { img.style.display = "none"; card.style.minHeight = "110px"; };
|
||||
|
||||
const name = document.createElement("div");
|
||||
name.className = "wfm-feeder-card-name";
|
||||
name.textContent = fname;
|
||||
name.title = fname;
|
||||
|
||||
card.append(cb, img, name);
|
||||
card.addEventListener("click", e => {
|
||||
if (e.target === cb) return;
|
||||
_showPreview(relPath, fname);
|
||||
});
|
||||
return card;
|
||||
}
|
||||
|
||||
function _refreshGridCbs() {
|
||||
document.querySelectorAll(".wfm-feeder-card").forEach(card => {
|
||||
const sel = _s.selected.has(card.dataset.name);
|
||||
card.classList.toggle("selected", sel);
|
||||
const cb = card.querySelector("input[type=checkbox]");
|
||||
if (cb) cb.checked = sel;
|
||||
});
|
||||
}
|
||||
|
||||
function _selectAll() {
|
||||
_s.images.forEach(f => _s.selected.add(f));
|
||||
_refreshGridCbs();
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
function _deselectAll() {
|
||||
_s.images.forEach(f => _s.selected.delete(f));
|
||||
_refreshGridCbs();
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
// ── Status Bar ───────────────────────────────────────────────────
|
||||
|
||||
function _updateStatus() {
|
||||
const el = document.getElementById("wfm-feeder-status");
|
||||
if (!el) return;
|
||||
const inCurrent = _s.images.filter(f => _s.selected.has(f)).length;
|
||||
el.textContent = `📂 ${_s.dir || "(root)"} | ${inCurrent} / ${_s.images.length} selected`;
|
||||
}
|
||||
|
||||
// ── Preview Panel ────────────────────────────────────────────────
|
||||
|
||||
async function _showPreview(relPath, fname) {
|
||||
const imgEl = document.getElementById("wfm-feeder-preview-img");
|
||||
const nameEl = document.getElementById("wfm-feeder-preview-name");
|
||||
const infoEl = document.getElementById("wfm-feeder-preview-info");
|
||||
|
||||
if (imgEl) {
|
||||
imgEl.src = `/image_loop/thumbnail?path=${encodeURIComponent(relPath)}`;
|
||||
imgEl.style.display = "block";
|
||||
}
|
||||
if (nameEl) nameEl.textContent = fname;
|
||||
if (infoEl) infoEl.textContent = "Loading...";
|
||||
|
||||
try {
|
||||
const res = await fetch(`/image_loop/image_info?path=${encodeURIComponent(relPath)}`);
|
||||
if (res.ok && infoEl) {
|
||||
const d = await res.json();
|
||||
const kb = d.size_bytes ? (d.size_bytes / 1024).toFixed(1) + " KB" : "";
|
||||
infoEl.textContent = `${d.width ?? "?"}×${d.height ?? "?"} px\n${kb}`;
|
||||
}
|
||||
} catch { if (infoEl) infoEl.textContent = ""; }
|
||||
}
|
||||
|
||||
// ── Presets ──────────────────────────────────────────────────────
|
||||
|
||||
async function _loadPresets() {
|
||||
try {
|
||||
const res = await fetch("/image_feeder/presets");
|
||||
if (!res.ok) return;
|
||||
_s.presets = await res.json();
|
||||
} catch { _s.presets = {}; }
|
||||
_renderPresets();
|
||||
}
|
||||
|
||||
function _renderPresets() {
|
||||
const sel = document.getElementById("wfm-feeder-preset-sel");
|
||||
if (!sel) return;
|
||||
const names = Object.keys(_s.presets).sort();
|
||||
sel.innerHTML = `<option value="">-- Select preset --</option>` +
|
||||
names.map(n => `<option value="${n}">${n}</option>`).join("");
|
||||
}
|
||||
|
||||
async function _savePreset() {
|
||||
const name = document.getElementById("wfm-feeder-preset-name")?.value.trim();
|
||||
if (!name) { showToast("Enter a preset name", "error"); return; }
|
||||
const sel = _s.images.filter(f => _s.selected.has(f));
|
||||
try {
|
||||
const res = await fetch("/image_feeder/presets", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, directory: _s.dir, selected_files: sel }),
|
||||
});
|
||||
if (res.ok) {
|
||||
showToast(`Preset saved: ${name}`, "success");
|
||||
const nameInput = document.getElementById("wfm-feeder-preset-name");
|
||||
if (nameInput) nameInput.value = "";
|
||||
await _loadPresets();
|
||||
const selEl = document.getElementById("wfm-feeder-preset-sel");
|
||||
if (selEl) selEl.value = name;
|
||||
} else { showToast("Save failed", "error"); }
|
||||
} catch (err) { showToast("Save error: " + err.message, "error"); }
|
||||
}
|
||||
|
||||
async function _applyPreset() {
|
||||
const selEl = document.getElementById("wfm-feeder-preset-sel");
|
||||
const name = selEl?.value;
|
||||
if (!name || !_s.presets[name]) { showToast("Select a preset first", "error"); return; }
|
||||
const preset = _s.presets[name];
|
||||
const dir = preset.directory || "";
|
||||
|
||||
_s.selected.clear();
|
||||
(preset.selected_files || []).forEach(f => _s.selected.add(f));
|
||||
_setVal("wfm-feeder-dir-input", dir);
|
||||
|
||||
if (_s.dir !== dir) {
|
||||
_s.dir = dir;
|
||||
_highlightTreeRow(dir);
|
||||
await _loadImages(dir);
|
||||
}
|
||||
_refreshGridCbs();
|
||||
_updateStatus();
|
||||
showToast(`Preset loaded: ${name}`, "success");
|
||||
}
|
||||
|
||||
async function _deletePreset() {
|
||||
const name = document.getElementById("wfm-feeder-preset-sel")?.value;
|
||||
if (!name) return;
|
||||
try {
|
||||
await fetch(`/image_feeder/presets/${encodeURIComponent(name)}`, { method: "DELETE" });
|
||||
showToast(`Preset deleted: ${name}`, "info");
|
||||
await _loadPresets();
|
||||
} catch (err) { showToast("Delete error", "error"); }
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────
|
||||
|
||||
function _setVal(id, val) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.value = val ?? "";
|
||||
}
|
||||
function _setCheck(id, val) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.checked = !!val;
|
||||
}
|
||||
|
||||
// ── Init ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function initFeederTab() {
|
||||
document.getElementById("wfm-feeder-node-sel")?.addEventListener("change", e => {
|
||||
_loadFromNode(e.target.value);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-feeder-apply-btn")?.addEventListener("click", _applyToWorkflow);
|
||||
|
||||
document.getElementById("wfm-feeder-dir-input")?.addEventListener("change", e => {
|
||||
const val = e.target.value.trim();
|
||||
if (_s.dir !== val) {
|
||||
_s.dir = val;
|
||||
_highlightTreeRow(val);
|
||||
_loadImages(val);
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("wfm-feeder-reload-tree")?.addEventListener("click", _loadTree);
|
||||
document.getElementById("wfm-feeder-sel-all")?.addEventListener("click", _selectAll);
|
||||
document.getElementById("wfm-feeder-desel-all")?.addEventListener("click", _deselectAll);
|
||||
|
||||
document.getElementById("wfm-feeder-preset-save")?.addEventListener("click", _savePreset);
|
||||
document.getElementById("wfm-feeder-preset-load")?.addEventListener("click", _applyPreset);
|
||||
document.getElementById("wfm-feeder-preset-del")?.addEventListener("click", _deletePreset);
|
||||
|
||||
document.getElementById("wfm-feeder-run-btn")?.addEventListener("click", _startRun);
|
||||
document.getElementById("wfm-feeder-stop-btn")?.addEventListener("click", _stopRun);
|
||||
|
||||
await Promise.all([_loadTree(), _loadPresets()]);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { comfyWorkflow } from "./comfyui-workflow.js";
|
||||
import { comfyEditor } from "./comfyui-editor.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { syncJsonHighlight, syncScroll } from "./json-highlight.js";
|
||||
import { initFeederTab, refreshFeederNodeList } from "./feeder-tab.js";
|
||||
|
||||
// ============================================
|
||||
// Eagle Auto-Save
|
||||
@@ -50,6 +51,42 @@ async function saveToEagle(imageUrl, name, tags = []) {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Gallery Metadata - ワークフロー保存
|
||||
// ============================================
|
||||
|
||||
let _outputDir = "";
|
||||
|
||||
async function _fetchOutputDir() {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/settings/output-dir");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
_outputDir = (data.current || "").replace(/\\/g, "/").replace(/\/$/, "");
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async function saveGeneratedImagesMeta(images, workflow) {
|
||||
if (!_outputDir) await _fetchOutputDir();
|
||||
if (!_outputDir) return;
|
||||
|
||||
for (const img of images) {
|
||||
if (img.type !== "output") continue;
|
||||
const parts = [_outputDir];
|
||||
if (img.subfolder) parts.push(img.subfolder);
|
||||
parts.push(img.filename);
|
||||
const path = parts.join("/");
|
||||
try {
|
||||
await fetch("/wfm/gallery/image/meta", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path, workflow }),
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Status & Connection
|
||||
// ============================================
|
||||
@@ -109,12 +146,462 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
const genBtn = document.getElementById("wfm-gen-generate-btn");
|
||||
if (genBtn) genBtn.disabled = !comfyUI.connected;
|
||||
|
||||
refreshFeederNodeList();
|
||||
|
||||
showToast(`Workflow loaded: ${filename || ""}`, "success");
|
||||
return true;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Generation
|
||||
// Checkpoint Batch
|
||||
// ============================================
|
||||
|
||||
const _ckptBatch = { aborted: false, paused: false, _resumeResolve: null };
|
||||
|
||||
async function _waitIfPaused() {
|
||||
if (!_ckptBatch.paused) return;
|
||||
await new Promise((resolve) => { _ckptBatch._resumeResolve = resolve; });
|
||||
}
|
||||
|
||||
function _setPauseBtnState(paused) {
|
||||
const btn = document.getElementById("wfm-ckpt-batch-pause-btn");
|
||||
if (!btn) return;
|
||||
btn.textContent = paused ? "Resume" : "Pause";
|
||||
btn.style.background = paused ? "var(--wfm-success, #22c55e)" : "";
|
||||
btn.style.color = paused ? "#fff" : "";
|
||||
}
|
||||
|
||||
// mode: "all" = 全選択, "some" = 一部選択, "none" = 全解除
|
||||
const _ckptState = { mode: "all", selected: new Set() };
|
||||
|
||||
function _getSelectedCheckpoints() {
|
||||
const all = comfyEditor.models.checkpoints || [];
|
||||
if (_ckptState.mode === "all") return all;
|
||||
if (_ckptState.mode === "none") return [];
|
||||
return all.filter((m) => _ckptState.selected.has(m));
|
||||
}
|
||||
|
||||
function _updateDropdownLabel() {
|
||||
const labelEl = document.getElementById("wfm-ckpt-dropdown-label");
|
||||
if (!labelEl) return;
|
||||
const total = (comfyEditor.models.checkpoints || []).length;
|
||||
if (_ckptState.mode === "all") {
|
||||
labelEl.textContent = total > 0 ? `All (${total})` : "All checkpoints";
|
||||
} else if (_ckptState.mode === "none") {
|
||||
labelEl.textContent = `0 / ${total} selected`;
|
||||
} else {
|
||||
labelEl.textContent = `${_ckptState.selected.size} / ${total} selected`;
|
||||
}
|
||||
}
|
||||
|
||||
// モデルパスリストをフォルダ → [modelPath, ...] のMapに変換
|
||||
function _buildFolderTree(models) {
|
||||
const map = new Map();
|
||||
for (const m of models) {
|
||||
const normalized = m.replace(/\\/g, "/");
|
||||
const lastSlash = normalized.lastIndexOf("/");
|
||||
const folder = lastSlash === -1 ? "" : normalized.substring(0, lastSlash);
|
||||
if (!map.has(folder)) map.set(folder, []);
|
||||
map.get(folder).push(m);
|
||||
}
|
||||
return new Map([...map.entries()].sort((a, b) => {
|
||||
if (a[0] === b[0]) return 0;
|
||||
if (a[0] === "") return -1;
|
||||
if (b[0] === "") return 1;
|
||||
return a[0].localeCompare(b[0]);
|
||||
}));
|
||||
}
|
||||
|
||||
// フォルダ内の選択状態を返す: "checked" | "indeterminate" | "unchecked"
|
||||
function _getFolderCheckState(folderModels) {
|
||||
if (_ckptState.mode === "all") return "checked";
|
||||
if (_ckptState.mode === "none") return "unchecked";
|
||||
const selCount = folderModels.filter((m) => _ckptState.selected.has(m)).length;
|
||||
if (selCount === 0) return "unchecked";
|
||||
if (selCount === folderModels.length) return "checked";
|
||||
return "indeterminate";
|
||||
}
|
||||
|
||||
// 単一モデルの選択トグル(_ckptState を更新)
|
||||
function _toggleSingleModel(m, checked, all) {
|
||||
if (_ckptState.mode === "all" && !checked) {
|
||||
_ckptState.mode = "some";
|
||||
_ckptState.selected.clear();
|
||||
all.forEach((x) => _ckptState.selected.add(x));
|
||||
} else if (_ckptState.mode === "none" && checked) {
|
||||
_ckptState.mode = "some";
|
||||
_ckptState.selected.clear();
|
||||
}
|
||||
if (checked) _ckptState.selected.add(m);
|
||||
else _ckptState.selected.delete(m);
|
||||
if (_ckptState.selected.size === all.length) { _ckptState.mode = "all"; _ckptState.selected.clear(); }
|
||||
if (_ckptState.mode === "some" && _ckptState.selected.size === 0) _ckptState.mode = "none";
|
||||
}
|
||||
|
||||
// フォルダ単位の一括トグル(_ckptState を更新)
|
||||
function _toggleFolderModels(folderModels, checked, all) {
|
||||
if (_ckptState.mode === "all" && !checked) {
|
||||
_ckptState.mode = "some";
|
||||
_ckptState.selected.clear();
|
||||
all.forEach((x) => _ckptState.selected.add(x));
|
||||
} else if (_ckptState.mode === "none" && checked) {
|
||||
_ckptState.mode = "some";
|
||||
_ckptState.selected.clear();
|
||||
}
|
||||
folderModels.forEach((m) => { if (checked) _ckptState.selected.add(m); else _ckptState.selected.delete(m); });
|
||||
if (_ckptState.selected.size === all.length) { _ckptState.mode = "all"; _ckptState.selected.clear(); }
|
||||
if (_ckptState.mode === "some" && _ckptState.selected.size === 0) _ckptState.mode = "none";
|
||||
}
|
||||
|
||||
function _rebuildCkptList() {
|
||||
const listEl = document.getElementById("wfm-ckpt-list");
|
||||
if (!listEl) return;
|
||||
const all = comfyEditor.models.checkpoints || [];
|
||||
const search = document.getElementById("wfm-ckpt-search")?.value.toLowerCase() || "";
|
||||
const filtered = search ? all.filter((m) => m.toLowerCase().includes(search)) : all;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
listEl.innerHTML = `<div style="padding:8px 10px;font-size:11px;color:var(--wfm-text-secondary);">No checkpoints</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const folderTree = _buildFolderTree(filtered);
|
||||
listEl.innerHTML = "";
|
||||
|
||||
for (const [folder, models] of folderTree) {
|
||||
const group = document.createElement("div");
|
||||
group.className = "wfm-ckpt-folder-group open";
|
||||
|
||||
// --- フォルダヘッダー ---
|
||||
const header = document.createElement("div");
|
||||
header.className = "wfm-ckpt-folder-header";
|
||||
|
||||
const folderCb = document.createElement("input");
|
||||
folderCb.type = "checkbox";
|
||||
const folderState = _getFolderCheckState(models);
|
||||
folderCb.checked = folderState === "checked";
|
||||
folderCb.indeterminate = folderState === "indeterminate";
|
||||
|
||||
const toggle = document.createElement("span");
|
||||
toggle.className = "wfm-ckpt-folder-toggle";
|
||||
toggle.textContent = "▶";
|
||||
|
||||
const nameSpan = document.createElement("span");
|
||||
nameSpan.className = "wfm-ckpt-folder-name";
|
||||
nameSpan.textContent = folder || "(root)";
|
||||
nameSpan.title = folder || "(root)";
|
||||
|
||||
const countSpan = document.createElement("span");
|
||||
countSpan.className = "wfm-ckpt-folder-count";
|
||||
countSpan.textContent = models.length;
|
||||
|
||||
// --- ファイルリスト ---
|
||||
const filesDiv = document.createElement("div");
|
||||
filesDiv.className = "wfm-ckpt-folder-files";
|
||||
|
||||
for (const m of models) {
|
||||
const itemLabel = document.createElement("label");
|
||||
itemLabel.className = "wfm-ckpt-item wfm-ckpt-item--indented";
|
||||
|
||||
const fileCb = document.createElement("input");
|
||||
fileCb.type = "checkbox";
|
||||
fileCb.value = m;
|
||||
if (_ckptState.mode === "all") fileCb.checked = true;
|
||||
else if (_ckptState.mode === "none") fileCb.checked = false;
|
||||
else fileCb.checked = _ckptState.selected.has(m);
|
||||
|
||||
const normalized = m.replace(/\\/g, "/");
|
||||
const lastSlash = normalized.lastIndexOf("/");
|
||||
const fileName = lastSlash === -1 ? m : m.substring(lastSlash + 1);
|
||||
const fileSpan = document.createElement("span");
|
||||
fileSpan.className = "wfm-ckpt-item-label";
|
||||
fileSpan.textContent = fileName;
|
||||
fileSpan.title = m;
|
||||
|
||||
fileCb.addEventListener("change", () => {
|
||||
_toggleSingleModel(m, fileCb.checked, all);
|
||||
const s = _getFolderCheckState(models);
|
||||
folderCb.checked = s === "checked";
|
||||
folderCb.indeterminate = s === "indeterminate";
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
});
|
||||
|
||||
itemLabel.appendChild(fileCb);
|
||||
itemLabel.appendChild(fileSpan);
|
||||
filesDiv.appendChild(itemLabel);
|
||||
}
|
||||
|
||||
// フォルダCBのchange
|
||||
folderCb.addEventListener("change", () => {
|
||||
_toggleFolderModels(models, folderCb.checked, all);
|
||||
folderCb.indeterminate = false;
|
||||
filesDiv.querySelectorAll("input[type=checkbox]").forEach((cb) => { cb.checked = folderCb.checked; });
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
});
|
||||
|
||||
// フォルダ名 / トグル矢印クリックで展開・折りたたみ
|
||||
[toggle, nameSpan].forEach((el) => {
|
||||
el.addEventListener("click", () => group.classList.toggle("open"));
|
||||
});
|
||||
|
||||
header.appendChild(folderCb);
|
||||
header.appendChild(toggle);
|
||||
header.appendChild(nameSpan);
|
||||
header.appendChild(countSpan);
|
||||
group.appendChild(header);
|
||||
group.appendChild(filesDiv);
|
||||
listEl.appendChild(group);
|
||||
}
|
||||
}
|
||||
|
||||
function _updateBatchInfo() {
|
||||
const infoEl = document.getElementById("wfm-ckpt-batch-info");
|
||||
if (!infoEl) return;
|
||||
const n = _getSelectedCheckpoints().length;
|
||||
infoEl.textContent = `${n} checkpoint${n !== 1 ? "s" : ""} will be processed`;
|
||||
}
|
||||
|
||||
function initCheckpointBatch() {
|
||||
const checkbox = document.getElementById("wfm-ckpt-batch-enabled");
|
||||
const body = document.getElementById("wfm-ckpt-batch-body");
|
||||
const wrap = document.getElementById("wfm-ckpt-dropdown-wrap");
|
||||
const btn = document.getElementById("wfm-ckpt-dropdown-btn");
|
||||
const panel = document.getElementById("wfm-ckpt-dropdown-panel");
|
||||
|
||||
checkbox?.addEventListener("change", () => {
|
||||
if (body) body.style.display = checkbox.checked ? "block" : "none";
|
||||
if (checkbox.checked) {
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
}
|
||||
});
|
||||
|
||||
// ドロップダウン開閉
|
||||
btn?.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const isOpen = panel.style.display !== "none";
|
||||
if (isOpen) {
|
||||
panel.style.display = "none";
|
||||
wrap.classList.remove("open");
|
||||
} else {
|
||||
_rebuildCkptList();
|
||||
panel.style.display = "block";
|
||||
wrap.classList.add("open");
|
||||
document.getElementById("wfm-ckpt-search")?.focus();
|
||||
}
|
||||
});
|
||||
|
||||
// 外側クリックで閉じる
|
||||
document.addEventListener("click", (e) => {
|
||||
if (panel && panel.style.display !== "none" && !wrap?.contains(e.target)) {
|
||||
panel.style.display = "none";
|
||||
wrap?.classList.remove("open");
|
||||
}
|
||||
});
|
||||
|
||||
// 検索フィルター
|
||||
document.getElementById("wfm-ckpt-search")?.addEventListener("input", _rebuildCkptList);
|
||||
|
||||
// 全選択
|
||||
document.getElementById("wfm-ckpt-select-all")?.addEventListener("click", () => {
|
||||
_ckptState.mode = "all";
|
||||
_ckptState.selected.clear();
|
||||
_rebuildCkptList();
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
});
|
||||
|
||||
// 全解除
|
||||
document.getElementById("wfm-ckpt-deselect-all")?.addEventListener("click", () => {
|
||||
_ckptState.mode = "none";
|
||||
_ckptState.selected.clear();
|
||||
_rebuildCkptList();
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
});
|
||||
|
||||
// Pause / Resume
|
||||
document.getElementById("wfm-ckpt-batch-pause-btn")?.addEventListener("click", () => {
|
||||
if (!_ckptBatch.paused) {
|
||||
_ckptBatch.paused = true;
|
||||
_setPauseBtnState(true);
|
||||
} else {
|
||||
_ckptBatch.paused = false;
|
||||
_setPauseBtnState(false);
|
||||
if (_ckptBatch._resumeResolve) {
|
||||
_ckptBatch._resumeResolve();
|
||||
_ckptBatch._resumeResolve = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Generation (core — throws on error)
|
||||
// ============================================
|
||||
|
||||
async function _coreGenerate(silent = false) {
|
||||
const progressBar = document.getElementById("wfm-gen-progress-bar");
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
const resultImg = document.getElementById("wfm-gen-result-img");
|
||||
const resultThumbs = document.getElementById("wfm-gen-result-thumbs");
|
||||
|
||||
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
|
||||
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
|
||||
|
||||
if (progressBar) progressBar.style.width = "0%";
|
||||
if (progressText) progressText.textContent = "Starting...";
|
||||
|
||||
const { images, seed } = await comfyUI.generate(
|
||||
{ ...comfyUI.currentWorkflow },
|
||||
{
|
||||
seedMode,
|
||||
seedValue,
|
||||
onProgress: (pct) => {
|
||||
if (progressBar) progressBar.style.width = `${(pct * 100).toFixed(1)}%`;
|
||||
if (progressText) progressText.textContent = `${(pct * 100).toFixed(0)}%`;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const seedEl = document.getElementById("wfm-gen-seed-value");
|
||||
if (seedEl) seedEl.value = seed;
|
||||
|
||||
if (progressText) progressText.textContent = `Done (${images.length} image${images.length !== 1 ? "s" : ""})`;
|
||||
if (progressBar) progressBar.style.width = "100%";
|
||||
|
||||
if (images.length > 0) {
|
||||
const blob = await comfyUI.getImageBlob(images[0]);
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (resultImg) {
|
||||
resultImg.src = url;
|
||||
resultImg.style.display = "block";
|
||||
}
|
||||
|
||||
if (resultThumbs && images.length > 1) {
|
||||
resultThumbs.innerHTML = "";
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
const b = i === 0 ? blob : await comfyUI.getImageBlob(images[i]);
|
||||
const u = i === 0 ? url : URL.createObjectURL(b);
|
||||
const thumb = document.createElement("img");
|
||||
thumb.src = u;
|
||||
thumb.className = `wfm-gen-thumb ${i === 0 ? "active" : ""}`;
|
||||
thumb.addEventListener("click", () => {
|
||||
resultImg.src = u;
|
||||
resultThumbs.querySelectorAll(".wfm-gen-thumb").forEach((t) => t.classList.remove("active"));
|
||||
thumb.classList.add("active");
|
||||
});
|
||||
resultThumbs.appendChild(thumb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (getEagleSettings().autoSave && images.length > 0) {
|
||||
for (const img of images) {
|
||||
const viewUrl = `/view?filename=${encodeURIComponent(img.filename)}&subfolder=${encodeURIComponent(img.subfolder || "")}&type=${encodeURIComponent(img.type || "output")}`;
|
||||
saveToEagle(viewUrl, img.filename);
|
||||
}
|
||||
}
|
||||
|
||||
if (images.length > 0) {
|
||||
saveGeneratedImagesMeta(images, { ...comfyUI.currentWorkflow }).catch(() => {});
|
||||
}
|
||||
|
||||
if (!silent) showToast("Generation complete", "success");
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Batch generation loop
|
||||
// ============================================
|
||||
|
||||
async function _runBatchGenerate() {
|
||||
const ckptNodes = comfyUI.currentAnalysis?.checkpoint_nodes || [];
|
||||
if (ckptNodes.length === 0) {
|
||||
showToast("No checkpoint node found in workflow", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const list = _getSelectedCheckpoints();
|
||||
|
||||
if (list.length === 0) {
|
||||
showToast("No checkpoints selected", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const batchProgress = document.getElementById("wfm-ckpt-batch-progress");
|
||||
const batchCurrentName = document.getElementById("wfm-ckpt-batch-current-name");
|
||||
const batchCount = document.getElementById("wfm-ckpt-batch-count");
|
||||
const batchBar = document.getElementById("wfm-ckpt-batch-bar");
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
|
||||
if (batchProgress) batchProgress.style.display = "block";
|
||||
const pauseBtn = document.getElementById("wfm-ckpt-batch-pause-btn");
|
||||
if (pauseBtn) { pauseBtn.style.display = "block"; pauseBtn.disabled = false; }
|
||||
_setPauseBtnState(false);
|
||||
|
||||
let completed = 0;
|
||||
let failed = 0;
|
||||
|
||||
try {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (_ckptBatch.aborted) break;
|
||||
|
||||
// 一時停止中は次のモデルへ進む前に待機
|
||||
if (_ckptBatch.paused) {
|
||||
if (batchCurrentName) batchCurrentName.textContent = "Paused...";
|
||||
if (progressText) progressText.textContent = "Paused";
|
||||
}
|
||||
await _waitIfPaused();
|
||||
if (_ckptBatch.aborted) break;
|
||||
|
||||
const model = list[i];
|
||||
if (batchCurrentName) batchCurrentName.textContent = model;
|
||||
if (batchCount) batchCount.textContent = `${i + 1} / ${list.length}`;
|
||||
if (batchBar) batchBar.style.width = `${((i / list.length) * 100).toFixed(1)}%`;
|
||||
if (progressText) progressText.textContent = `[${i + 1}/${list.length}] Loading...`;
|
||||
|
||||
for (const node of ckptNodes) {
|
||||
if (comfyUI.currentWorkflow?.[node.id]) {
|
||||
comfyUI.currentWorkflow[node.id].inputs.ckpt_name = model;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await _coreGenerate(true);
|
||||
completed++;
|
||||
} catch (err) {
|
||||
if (_ckptBatch.aborted) break;
|
||||
failed++;
|
||||
showToast(`[${i + 1}/${list.length}] Failed: ${err.message}`, "error");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (pauseBtn) pauseBtn.disabled = true;
|
||||
_ckptBatch.paused = false;
|
||||
if (_ckptBatch._resumeResolve) {
|
||||
_ckptBatch._resumeResolve();
|
||||
_ckptBatch._resumeResolve = null;
|
||||
}
|
||||
_setPauseBtnState(false);
|
||||
}
|
||||
|
||||
if (batchBar) batchBar.style.width = "100%";
|
||||
if (batchCurrentName) batchCurrentName.textContent = _ckptBatch.aborted ? "Stopped" : "Done";
|
||||
|
||||
if (_ckptBatch.aborted) {
|
||||
showToast(`Batch stopped — ${completed} completed, ${failed} failed`, "info");
|
||||
} else {
|
||||
showToast(
|
||||
`Batch complete: ${completed}/${list.length}${failed > 0 ? ` (${failed} failed)` : ""}`,
|
||||
failed > 0 ? "error" : "success"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Generate entry point
|
||||
// ============================================
|
||||
|
||||
async function handleGenerate() {
|
||||
@@ -124,84 +611,31 @@ async function handleGenerate() {
|
||||
}
|
||||
if (comfyUI.generating) return;
|
||||
|
||||
const genBtn = document.getElementById("wfm-gen-generate-btn");
|
||||
const progressBar = document.getElementById("wfm-gen-progress-bar");
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
const interruptBtn = document.getElementById("wfm-gen-interrupt-btn");
|
||||
const resultImg = document.getElementById("wfm-gen-result-img");
|
||||
const resultThumbs = document.getElementById("wfm-gen-result-thumbs");
|
||||
|
||||
// Sync prompts to workflow
|
||||
comfyEditor.syncToWorkflow();
|
||||
|
||||
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
|
||||
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
|
||||
const genBtn = document.getElementById("wfm-gen-generate-btn");
|
||||
const interruptBtn = document.getElementById("wfm-gen-interrupt-btn");
|
||||
|
||||
genBtn.disabled = true;
|
||||
if (interruptBtn) interruptBtn.style.display = "inline-block";
|
||||
if (progressBar) progressBar.style.width = "0%";
|
||||
if (progressText) progressText.textContent = "Starting...";
|
||||
_ckptBatch.aborted = false;
|
||||
_ckptBatch.paused = false;
|
||||
_ckptBatch._resumeResolve = null;
|
||||
|
||||
const batchEnabled = document.getElementById("wfm-ckpt-batch-enabled")?.checked;
|
||||
|
||||
try {
|
||||
const { images, seed } = await comfyUI.generate(
|
||||
{ ...comfyUI.currentWorkflow },
|
||||
{
|
||||
seedMode,
|
||||
seedValue,
|
||||
onProgress: (pct) => {
|
||||
if (progressBar) progressBar.style.width = `${(pct * 100).toFixed(1)}%`;
|
||||
if (progressText) progressText.textContent = `${(pct * 100).toFixed(0)}%`;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// Update seed display
|
||||
const seedEl = document.getElementById("wfm-gen-seed-value");
|
||||
if (seedEl) seedEl.value = seed;
|
||||
|
||||
if (progressText) progressText.textContent = `Done (${images.length} image${images.length !== 1 ? "s" : ""})`;
|
||||
if (progressBar) progressBar.style.width = "100%";
|
||||
|
||||
// Display results
|
||||
if (images.length > 0) {
|
||||
const blob = await comfyUI.getImageBlob(images[0]);
|
||||
const url = URL.createObjectURL(blob);
|
||||
if (resultImg) {
|
||||
resultImg.src = url;
|
||||
resultImg.style.display = "block";
|
||||
}
|
||||
|
||||
// Thumbnails for multiple images
|
||||
if (resultThumbs && images.length > 1) {
|
||||
resultThumbs.innerHTML = "";
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
const b = i === 0 ? blob : await comfyUI.getImageBlob(images[i]);
|
||||
const u = i === 0 ? url : URL.createObjectURL(b);
|
||||
const thumb = document.createElement("img");
|
||||
thumb.src = u;
|
||||
thumb.className = `wfm-gen-thumb ${i === 0 ? "active" : ""}`;
|
||||
thumb.addEventListener("click", () => {
|
||||
resultImg.src = u;
|
||||
resultThumbs.querySelectorAll(".wfm-gen-thumb").forEach((t) => t.classList.remove("active"));
|
||||
thumb.classList.add("active");
|
||||
});
|
||||
resultThumbs.appendChild(thumb);
|
||||
}
|
||||
if (batchEnabled) {
|
||||
await _runBatchGenerate();
|
||||
} else {
|
||||
try {
|
||||
await _coreGenerate(false);
|
||||
} catch (err) {
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
if (progressText) progressText.textContent = "Error";
|
||||
showToast("Generation error: " + err.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// Eagle auto-save
|
||||
if (getEagleSettings().autoSave && images.length > 0) {
|
||||
for (const img of images) {
|
||||
const viewUrl = `/view?filename=${encodeURIComponent(img.filename)}&subfolder=${encodeURIComponent(img.subfolder || "")}&type=${encodeURIComponent(img.type || "output")}`;
|
||||
saveToEagle(viewUrl, img.filename);
|
||||
}
|
||||
}
|
||||
|
||||
showToast("Generation complete", "success");
|
||||
} catch (err) {
|
||||
if (progressText) progressText.textContent = "Error";
|
||||
showToast("Generation error: " + err.message, "error");
|
||||
} finally {
|
||||
genBtn.disabled = false;
|
||||
if (interruptBtn) interruptBtn.style.display = "none";
|
||||
@@ -235,17 +669,41 @@ export async function initGenerateTab() {
|
||||
comfyEditor.renderAll(comfyUI.currentAnalysis, comfyUI.currentWorkflow);
|
||||
}
|
||||
showToast("Model lists refreshed", "success");
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
});
|
||||
|
||||
// Generate button
|
||||
document.getElementById("wfm-gen-generate-btn")?.addEventListener("click", handleGenerate);
|
||||
|
||||
// Interrupt button
|
||||
// Interrupt button (stops both single generation and batch loop)
|
||||
document.getElementById("wfm-gen-interrupt-btn")?.addEventListener("click", async () => {
|
||||
_ckptBatch.aborted = true;
|
||||
// 一時停止中でもループを抜けられるよう待機を解除
|
||||
_ckptBatch.paused = false;
|
||||
if (_ckptBatch._resumeResolve) {
|
||||
_ckptBatch._resumeResolve();
|
||||
_ckptBatch._resumeResolve = null;
|
||||
}
|
||||
await comfyUI.interrupt();
|
||||
showToast("Interrupted", "info");
|
||||
});
|
||||
|
||||
// Move shared Raw JSON widget into the active tab's rawjson-col
|
||||
function moveRawJsonToTab(tabKey) {
|
||||
const widget = document.getElementById("wfm-gen-rawjson-widget");
|
||||
if (!widget) return;
|
||||
if (tabKey === "feeder") {
|
||||
widget.style.display = "none";
|
||||
return;
|
||||
}
|
||||
const col = document.getElementById(`wfm-gen-rawjson-col-${tabKey}`);
|
||||
if (col) {
|
||||
col.appendChild(widget);
|
||||
widget.style.display = "flex";
|
||||
}
|
||||
}
|
||||
|
||||
// Subtab navigation
|
||||
document.querySelectorAll(".wfm-gen-subtab-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
@@ -254,10 +712,14 @@ export async function initGenerateTab() {
|
||||
btn.classList.add("active");
|
||||
document.querySelectorAll(".wfm-gen-subtab-content").forEach((c) => c.classList.remove("active"));
|
||||
document.getElementById(`wfm-gen-subtab-${target}`)?.classList.add("active");
|
||||
moveRawJsonToTab(target);
|
||||
});
|
||||
});
|
||||
|
||||
// Raw JSON apply
|
||||
// Initial placement: move to first active tab (input)
|
||||
moveRawJsonToTab("input");
|
||||
|
||||
// Raw JSON apply (always-visible panel in right column)
|
||||
document.getElementById("wfm-gen-apply-raw-btn")?.addEventListener("click", async () => {
|
||||
const textarea = document.getElementById("wfm-gen-raw-json");
|
||||
if (!textarea) return;
|
||||
@@ -289,11 +751,25 @@ export async function initGenerateTab() {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// outputDir を事前取得(生成後の保存に使用)
|
||||
_fetchOutputDir();
|
||||
window.addEventListener("wfm-output-dir-changed", (e) => {
|
||||
_outputDir = (e.detail?.path || "").replace(/\\/g, "/").replace(/\/$/, "");
|
||||
});
|
||||
|
||||
// Checkpoint batch UI
|
||||
initCheckpointBatch();
|
||||
|
||||
// Feeder tab
|
||||
await initFeederTab();
|
||||
|
||||
// Auto-connect on init
|
||||
const connected = await comfyUI.checkConnection();
|
||||
updateStatus(connected);
|
||||
if (connected) {
|
||||
await comfyEditor.loadModelLists();
|
||||
_updateDropdownLabel();
|
||||
_updateBatchInfo();
|
||||
}
|
||||
|
||||
// Auto-load default workflow (doesn't require ComfyUI connection)
|
||||
|
||||
@@ -0,0 +1,749 @@
|
||||
/**
|
||||
* Metadata Tab
|
||||
* Drop a PNG/WebP/JSON file to extract and display model/prompt metadata.
|
||||
* Parsing logic adapted from model-and-prompt-from-metadata (workflow_utils.js).
|
||||
*/
|
||||
|
||||
import { t } from "./i18n.js";
|
||||
|
||||
// ── File size limit ───────────────────────────────────────────
|
||||
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
||||
|
||||
// ── Sanitize JSON (NaN/Infinity → null) ──────────────────────
|
||||
function sanitizeJSON(text) {
|
||||
return text
|
||||
.replace(/-Infinity\b/g, "null")
|
||||
.replace(/\bInfinity\b/g, "null")
|
||||
.replace(/\bNaN\b/g, "null");
|
||||
}
|
||||
|
||||
// ── WebP EXIF ────────────────────────────────────────────────
|
||||
async function readWebPEXIFChunk(file) {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const view = new DataView(buffer);
|
||||
const ascii = new TextDecoder("latin1");
|
||||
if (bytes.byteLength < 12) return null;
|
||||
if (ascii.decode(bytes.slice(0, 4)) !== "RIFF") return null;
|
||||
if (ascii.decode(bytes.slice(8, 12)) !== "WEBP") return null;
|
||||
let offset = 12;
|
||||
while (offset + 8 <= buffer.byteLength) {
|
||||
const fourcc = ascii.decode(bytes.slice(offset, offset + 4));
|
||||
const chunkSize = view.getUint32(offset + 4, true);
|
||||
if (fourcc === "EXIF") return bytes.slice(offset + 8, offset + 8 + chunkSize);
|
||||
offset += 8 + chunkSize;
|
||||
if (chunkSize % 2 === 1) offset++;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractWorkflowFromEXIF(exifBytes) {
|
||||
const utf8 = new TextDecoder("utf-8", { fatal: false });
|
||||
const text = utf8.decode(exifBytes);
|
||||
for (const key of ["workflow:", "prompt:"]) {
|
||||
const idx = text.indexOf(key + "{");
|
||||
if (idx < 0) continue;
|
||||
let jsonStr = text.slice(idx + key.length);
|
||||
const nullIdx = jsonStr.indexOf("\x00");
|
||||
if (nullIdx >= 0) jsonStr = jsonStr.slice(0, nullIdx);
|
||||
try { return JSON.parse(sanitizeJSON(jsonStr)); } catch {
|
||||
const lb = jsonStr.lastIndexOf("}");
|
||||
if (lb > 0) { try { return JSON.parse(sanitizeJSON(jsonStr.slice(0, lb + 1))); } catch {} }
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── PNG text chunks ───────────────────────────────────────────
|
||||
function findNull(arr, start = 0) {
|
||||
for (let i = start; i < arr.length; i++) if (arr[i] === 0) return i;
|
||||
return -1;
|
||||
}
|
||||
function parseTEXtChunk(data, latin1) {
|
||||
const np = findNull(data);
|
||||
if (np === -1) return null;
|
||||
return { keyword: latin1.decode(data.slice(0, np)), text: latin1.decode(data.slice(np + 1)) };
|
||||
}
|
||||
function parseITXtChunk(data, latin1, utf8) {
|
||||
const np = findNull(data);
|
||||
if (np === -1) return null;
|
||||
const keyword = latin1.decode(data.slice(0, np));
|
||||
let pos = np + 3;
|
||||
pos = findNull(data, pos); if (pos === -1) return null; pos++;
|
||||
pos = findNull(data, pos); if (pos === -1) return null; pos++;
|
||||
return { keyword, text: utf8.decode(data.slice(pos)) };
|
||||
}
|
||||
async function readAllPNGTextChunks(file) {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
for (let i = 0; i < 8; i++) if (bytes[i] !== PNG_SIG[i]) return null;
|
||||
const view = new DataView(buffer);
|
||||
const latin1 = new TextDecoder("latin1");
|
||||
const utf8 = new TextDecoder("utf-8");
|
||||
let offset = 8;
|
||||
const chunks = {};
|
||||
while (offset + 12 <= buffer.byteLength) {
|
||||
const length = view.getUint32(offset);
|
||||
if (offset + 12 + length > buffer.byteLength) break;
|
||||
const type = latin1.decode(bytes.slice(offset + 4, offset + 8));
|
||||
const data = bytes.slice(offset + 8, offset + 8 + length);
|
||||
if (type === "tEXt") { const c = parseTEXtChunk(data, latin1); if (c) chunks[c.keyword] = c.text; }
|
||||
else if (type === "iTXt") { const c = parseITXtChunk(data, latin1, utf8); if (c) chunks[c.keyword] = c.text; }
|
||||
offset += 12 + length;
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
// ── Workflow extraction helpers ───────────────────────────────
|
||||
function collectUnique(arr) {
|
||||
const seen = new Set(), out = [];
|
||||
for (const v of arr) { if (v && typeof v === "string" && !seen.has(v)) { seen.add(v); out.push(v); } }
|
||||
return out;
|
||||
}
|
||||
function collectAllNodes(workflow) {
|
||||
if (!Array.isArray(workflow.nodes)) return [];
|
||||
const all = [...workflow.nodes];
|
||||
for (const sg of workflow.definitions?.subgraphs ?? []) if (Array.isArray(sg.nodes)) all.push(...sg.nodes);
|
||||
return all;
|
||||
}
|
||||
const META_NODE_TYPES = new Set(["ImageMetadataCheckpointLoader", "ImageMetadataPromptLoader"]);
|
||||
const VAE_NONE = "None";
|
||||
|
||||
function extractCheckpoints(wf) {
|
||||
if (!wf || typeof wf !== "object") return [];
|
||||
if (Array.isArray(wf.nodes)) return collectUnique(collectAllNodes(wf).filter(n => n.type?.toLowerCase().includes("checkpoint") || META_NODE_TYPES.has(n.type)).map(n => n.widgets_values?.[0]));
|
||||
return collectUnique(Object.values(wf).filter(n => n?.class_type?.toLowerCase().includes("checkpoint") || META_NODE_TYPES.has(n?.class_type)).map(n => n.inputs?.ckpt_name));
|
||||
}
|
||||
function extractVAEs(wf) {
|
||||
if (!wf || typeof wf !== "object") return [];
|
||||
if (Array.isArray(wf.nodes)) return collectUnique(collectAllNodes(wf).flatMap(n => { if (n.type === "VAELoader") return [n.widgets_values?.[0]]; if (META_NODE_TYPES.has(n.type ?? "")) { const v = n.widgets_values?.[1]; return v && v !== VAE_NONE ? [v] : []; } return []; }));
|
||||
return collectUnique(Object.values(wf).flatMap(n => { if (!n || typeof n !== "object") return []; if (n.class_type === "VAELoader") return [n.inputs?.vae_name]; if (META_NODE_TYPES.has(n.class_type ?? "")) { const v = n.inputs?.vae_name; return v && v !== VAE_NONE ? [v] : []; } return []; }));
|
||||
}
|
||||
function extractDiffusionModels(wf) {
|
||||
if (!wf || typeof wf !== "object") return [];
|
||||
if (Array.isArray(wf.nodes)) return collectUnique(collectAllNodes(wf).filter(n => n.type === "UNETLoader").map(n => n.widgets_values?.[0]));
|
||||
return collectUnique(Object.values(wf).filter(n => n?.class_type === "UNETLoader").map(n => n.inputs?.unet_name));
|
||||
}
|
||||
function extractTextEncoders(wf) {
|
||||
if (!wf || typeof wf !== "object") return [];
|
||||
const names = [];
|
||||
if (Array.isArray(wf.nodes)) {
|
||||
for (const n of collectAllNodes(wf)) {
|
||||
if (n.type === "CLIPLoader") { if (n.widgets_values?.[0]) names.push(n.widgets_values[0]); }
|
||||
else if (n.type === "DualCLIPLoader") { [0,1].forEach(i => { if (n.widgets_values?.[i]) names.push(n.widgets_values[i]); }); }
|
||||
else if (n.type === "TripleCLIPLoader") { [0,1,2].forEach(i => { if (n.widgets_values?.[i]) names.push(n.widgets_values[i]); }); }
|
||||
}
|
||||
} else {
|
||||
for (const n of Object.values(wf)) {
|
||||
if (!n || typeof n !== "object") continue;
|
||||
const ct = n.class_type ?? "";
|
||||
if (ct === "CLIPLoader") { if (n.inputs?.clip_name) names.push(n.inputs.clip_name); }
|
||||
else if (ct === "DualCLIPLoader") { if (n.inputs?.clip_name1) names.push(n.inputs.clip_name1); if (n.inputs?.clip_name2) names.push(n.inputs.clip_name2); }
|
||||
else if (ct === "TripleCLIPLoader") { ["clip_name1","clip_name2","clip_name3"].forEach(k => { if (n.inputs?.[k]) names.push(n.inputs[k]); }); }
|
||||
}
|
||||
}
|
||||
return collectUnique(names);
|
||||
}
|
||||
function extractLoRAs(wf) {
|
||||
if (!wf || typeof wf !== "object") return [];
|
||||
const results = [], seen = new Set();
|
||||
function add(name, sm, sc) {
|
||||
if (!name || typeof name !== "string" || name === "None" || seen.has(name)) return;
|
||||
seen.add(name);
|
||||
results.push({ name, strength_model: typeof sm === "number" ? sm : 1.0, strength_clip: typeof sc === "number" ? sc : 1.0 });
|
||||
}
|
||||
if (Array.isArray(wf.nodes)) {
|
||||
for (const n of collectAllNodes(wf)) {
|
||||
const type = n.type ?? "";
|
||||
if (type === "LoraLoader") add(n.widgets_values?.[0], n.widgets_values?.[1], n.widgets_values?.[2]);
|
||||
else if (type === "LoraLoaderModelOnly") add(n.widgets_values?.[0], n.widgets_values?.[1], 1.0);
|
||||
else if (type === "ImageMetadataLoRALoader") { for (let i = 0; i < 3; i++) add(n.widgets_values?.[i*3], n.widgets_values?.[i*3+1], n.widgets_values?.[i*3+2]); }
|
||||
else if (type === "Lora Loader (LoraManager)") { const list = n.widgets_values?.find(v => Array.isArray(v)); if (list) for (const l of list) { if (l?.active !== false) add(l?.name, l?.strength ?? 1.0, l?.clipStrength ?? l?.strength ?? 1.0); } }
|
||||
}
|
||||
} else {
|
||||
for (const n of Object.values(wf)) {
|
||||
if (!n || typeof n !== "object") continue;
|
||||
const ct = n.class_type ?? "";
|
||||
if (ct === "LoraLoader") add(n.inputs?.lora_name, n.inputs?.strength_model, n.inputs?.strength_clip);
|
||||
else if (ct === "LoraLoaderModelOnly") add(n.inputs?.lora_name, n.inputs?.strength, 1.0);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function isTextEncoderNode(ct) { return ct === "CLIPTextEncode" || ct.includes("TextEncode") || ct.includes("TextEncoderSD"); }
|
||||
function isSamplerNode(ct) { return ct === "KSampler" || ct === "KSamplerAdvanced" || ct.includes("KSampler") || ct.includes("Sampler"); }
|
||||
function isPromptStylerNode(ct) { return ct.includes("PromptStyler"); }
|
||||
|
||||
function extractPrompts(wf) {
|
||||
if (!wf || typeof wf !== "object") return { positives: [], negatives: [] };
|
||||
return Array.isArray(wf.nodes) ? extractPromptsLiteGraph(wf) : extractPromptsAPI(wf);
|
||||
}
|
||||
|
||||
// CLIPTextEncode + KSampler でプロンプト抽出(トップレベル・サブグラフ共用)
|
||||
// サンプラーが見つかりテキストが取れた場合のみ非null を返す
|
||||
function extractPromptsFromNodeSet(nodes, links) {
|
||||
const nodeMap = new Map();
|
||||
for (const n of nodes) nodeMap.set(n.id, n);
|
||||
const linkOrigin = new Map(), linkSlot = new Map();
|
||||
if (Array.isArray(links)) {
|
||||
for (const lk of links) {
|
||||
if (Array.isArray(lk)) {
|
||||
linkOrigin.set(lk[0], lk[1]);
|
||||
linkSlot.set(lk[0], lk[2] ?? 0);
|
||||
} else if (lk && typeof lk === "object") {
|
||||
const id = lk.id ?? lk[0], origin = lk.origin_id ?? lk[1], slot = lk.origin_slot ?? lk[2] ?? 0;
|
||||
if (id != null && origin != null) { linkOrigin.set(id, origin); linkSlot.set(id, slot); }
|
||||
}
|
||||
}
|
||||
}
|
||||
const textMap = new Map();
|
||||
for (const n of nodes) {
|
||||
if (!isTextEncoderNode(n.type ?? "")) continue;
|
||||
const text = n.widgets_values?.[0];
|
||||
if (text && typeof text === "string") {
|
||||
textMap.set(n.id, text);
|
||||
} else if (Array.isArray(n.inputs)) {
|
||||
const textInput = n.inputs.find(inp => inp.name === "text" || inp.name === "text_g" || inp.name === "prompt");
|
||||
if (textInput?.link != null) {
|
||||
const originId = linkOrigin.get(textInput.link);
|
||||
const originSlot = linkSlot.get(textInput.link) ?? 0;
|
||||
const srcNode = originId != null ? nodeMap.get(originId) : null;
|
||||
if (srcNode) {
|
||||
const srcType = srcNode.type ?? "";
|
||||
if (isPromptStylerNode(srcType)) {
|
||||
const v = srcNode.widgets_values?.[originSlot];
|
||||
if (v && typeof v === "string") textMap.set(n.id, v);
|
||||
} else {
|
||||
// WFS_PromptText, PrimitiveStringMultiline, ComfySwitchNode 等、任意の STRING 出力ノード
|
||||
const v = srcNode.widgets_values?.[originSlot] ?? srcNode.widgets_values?.[0];
|
||||
if (v && typeof v === "string") textMap.set(n.id, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const pos = new Set(), neg = new Set();
|
||||
let foundSampler = false;
|
||||
for (const n of nodes) {
|
||||
if (!isSamplerNode(n.type ?? "") || !Array.isArray(n.inputs)) continue;
|
||||
foundSampler = true;
|
||||
for (const inp of n.inputs) {
|
||||
if (!inp || inp.link == null) continue;
|
||||
const originId = linkOrigin.get(inp.link);
|
||||
if (originId == null) continue;
|
||||
const text = textMap.get(originId);
|
||||
if (!text) continue;
|
||||
const name = inp.name ?? "";
|
||||
if (name === "positive" || name.startsWith("positive")) pos.add(text);
|
||||
else if (name === "negative" || name.startsWith("negative")) neg.add(text);
|
||||
}
|
||||
}
|
||||
if (!foundSampler) return null;
|
||||
// SamplerCustomAdvanced などで positive/negative 直結がない場合、判別不能テキストとして返す
|
||||
if (pos.size === 0 && neg.size === 0) {
|
||||
const allTexts = [...textMap.values()].filter(t => t.trim());
|
||||
if (allTexts.length > 0) return { positives: [], negatives: [], texts: allTexts };
|
||||
return null;
|
||||
}
|
||||
return { positives: [...pos], negatives: [...neg] };
|
||||
}
|
||||
|
||||
// MarkdownNote の **section** → - [name](url) パターンからモデルを抽出
|
||||
// flux/qwen/z-image などのサブグラフ形式ワークフロー向け補完用
|
||||
function extractMarkdownNoteModels(wf) {
|
||||
const allNodes = [];
|
||||
if (Array.isArray(wf.nodes)) allNodes.push(...wf.nodes);
|
||||
for (const sg of wf.definitions?.subgraphs ?? []) if (Array.isArray(sg.nodes)) allNodes.push(...sg.nodes);
|
||||
const result = { checkpoints: [], vaes: [], diffusionModels: [], textEncoders: [], loras: [] };
|
||||
const seen = { checkpoints: new Set(), vaes: new Set(), diffusionModels: new Set(), textEncoders: new Set(), loras: new Set() };
|
||||
function addU(arr, set, name) { if (name && typeof name === "string" && !set.has(name)) { set.add(name); arr.push(name); } }
|
||||
for (const n of allNodes) {
|
||||
if (n.type !== "MarkdownNote") continue;
|
||||
const raw = n.widgets_values;
|
||||
const text = Array.isArray(raw) ? raw[0] : (typeof raw === "string" ? raw : null);
|
||||
if (!text) continue;
|
||||
const sRe = /\*\*([^*\n]+)\*\*/g;
|
||||
let sm;
|
||||
while ((sm = sRe.exec(text)) !== null) {
|
||||
const sec = sm[1].trim().toLowerCase().replace(/\s+/g, "_");
|
||||
if (!["text_encoders", "diffusion_models", "vae", "checkpoints", "loras"].includes(sec)) continue;
|
||||
const rest = text.slice(sm.index + sm[0].length);
|
||||
const end = rest.search(/\n\*\*|\n##/);
|
||||
const content = end >= 0 ? rest.slice(0, end) : rest;
|
||||
const lRe = /^- \[([^\]]+)\]/gm;
|
||||
let lm;
|
||||
while ((lm = lRe.exec(content)) !== null) {
|
||||
const name = lm[1].trim();
|
||||
if (sec === "text_encoders") addU(result.textEncoders, seen.textEncoders, name);
|
||||
else if (sec === "diffusion_models") addU(result.diffusionModels, seen.diffusionModels, name);
|
||||
else if (sec === "vae") addU(result.vaes, seen.vaes, name);
|
||||
else if (sec === "checkpoints") addU(result.checkpoints, seen.checkpoints, name);
|
||||
else if (sec === "loras") addU(result.loras, seen.loras, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
const hasAny = result.checkpoints.length || result.vaes.length || result.diffusionModels.length || result.textEncoders.length || result.loras.length;
|
||||
return hasAny ? result : null;
|
||||
}
|
||||
|
||||
// API形式: リンク参照 [srcNodeId, slot] からテキストを解決
|
||||
function resolveLinkedText(wf, srcId, slot) {
|
||||
const src = wf[String(srcId)];
|
||||
if (!src || typeof src !== "object") return null;
|
||||
const ct = src.class_type ?? "";
|
||||
// PromptStyler系: slot 0 = text_positive, slot 1 = text_negative
|
||||
if (isPromptStylerNode(ct)) {
|
||||
const v = slot === 0 ? src.inputs?.text_positive : src.inputs?.text_negative;
|
||||
return (v && typeof v === "string") ? v : null;
|
||||
}
|
||||
// 汎用テキストキー
|
||||
const keys = slot === 0
|
||||
? ["text_positive", "text", "text_g", "prompt"]
|
||||
: ["text_negative", "text_l"];
|
||||
for (const k of keys) {
|
||||
const v = src.inputs?.[k];
|
||||
if (v && typeof v === "string") return v;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractPromptsAPI(wf) {
|
||||
const metaNodes = Object.values(wf).filter(n => n?.class_type === "ImageMetadataPromptLoader");
|
||||
if (metaNodes.length > 0) {
|
||||
const pos = new Set(), neg = new Set();
|
||||
for (const n of metaNodes) { if (n.inputs?.positive_text) pos.add(n.inputs.positive_text); if (n.inputs?.negative_text) neg.add(n.inputs.negative_text); }
|
||||
if (pos.size > 0 || neg.size > 0) return { positives: [...pos], negatives: [...neg] };
|
||||
}
|
||||
const textMap = new Map();
|
||||
for (const [id, n] of Object.entries(wf)) {
|
||||
if (!n || !isTextEncoderNode(n.class_type ?? "")) continue;
|
||||
const raw = n.inputs?.text ?? n.inputs?.text_g ?? null;
|
||||
if (raw && typeof raw === "string") {
|
||||
textMap.set(id, raw);
|
||||
} else if (Array.isArray(raw)) {
|
||||
// リンク参照 [srcNodeId, slot] → 解決
|
||||
const text = resolveLinkedText(wf, raw[0], raw[1] ?? 0);
|
||||
if (text) textMap.set(id, text);
|
||||
}
|
||||
}
|
||||
const pos = new Set(), neg = new Set();
|
||||
let foundSampler = false;
|
||||
for (const n of Object.values(wf)) {
|
||||
if (!n || !isSamplerNode(n.class_type ?? "")) continue;
|
||||
foundSampler = true;
|
||||
for (const [key, val] of Object.entries(n.inputs ?? {})) {
|
||||
if (!Array.isArray(val)) continue;
|
||||
const text = textMap.get(String(val[0]));
|
||||
if (!text) continue;
|
||||
if (key === "positive" || key.startsWith("positive")) pos.add(text);
|
||||
else if (key === "negative" || key.startsWith("negative")) neg.add(text);
|
||||
}
|
||||
}
|
||||
if (!foundSampler || (pos.size === 0 && neg.size === 0)) { const all = [...textMap.values()].filter(t => t && t.trim()); return { positives: [], negatives: [], texts: all }; }
|
||||
return { positives: [...pos], negatives: [...neg] };
|
||||
}
|
||||
|
||||
function extractPromptsLiteGraph(wf) {
|
||||
const { nodes, links } = wf;
|
||||
if (!Array.isArray(nodes)) return { positives: [], negatives: [] };
|
||||
|
||||
// 1. ImageMetadataPromptLoader (WFS専用)
|
||||
const metaNodes = nodes.filter(n => n.type === "ImageMetadataPromptLoader");
|
||||
if (metaNodes.length > 0) {
|
||||
const pos = new Set(), neg = new Set();
|
||||
for (const n of metaNodes) { const p = n.widgets_values?.[2], ng = n.widgets_values?.[3]; if (p) pos.add(p); if (ng) neg.add(ng); }
|
||||
if (pos.size > 0 || neg.size > 0) return { positives: [...pos], negatives: [...neg] };
|
||||
}
|
||||
|
||||
// 2. WFS_PromptText (WFS専用)
|
||||
const wfsNodes = nodes.filter(n => n.type === "WFS_PromptText");
|
||||
if (wfsNodes.length > 0) {
|
||||
const pos = new Set(), neg = new Set();
|
||||
for (const n of wfsNodes) { const p = n.widgets_values?.[0], ng = n.widgets_values?.[1]; if (p) pos.add(p); if (ng) neg.add(ng); }
|
||||
if (pos.size > 0 || neg.size > 0) return { positives: [...pos], negatives: [...neg] };
|
||||
}
|
||||
|
||||
// 3. トップレベルの CLIPTextEncode + KSampler
|
||||
const topResult = extractPromptsFromNodeSet(nodes, links ?? []);
|
||||
if (topResult) return topResult;
|
||||
|
||||
// 4. PrimitiveStringMultiline(flux2-klein / ernie など)- サブグラフ内も探す
|
||||
const primTexts = [];
|
||||
for (const n of collectAllNodes(wf)) {
|
||||
if (n.type !== "PrimitiveStringMultiline") continue;
|
||||
const t = Array.isArray(n.widgets_values) ? n.widgets_values[0] : n.widgets_values;
|
||||
if (t && typeof t === "string" && t.trim()) primTexts.push(t.trim());
|
||||
}
|
||||
if (primTexts.length > 0) return { positives: [], negatives: [], texts: primTexts };
|
||||
|
||||
// 5. サブグラフ内の CLIPTextEncode + KSampler(z-image / qwen / flux など)
|
||||
for (const sg of wf.definitions?.subgraphs ?? []) {
|
||||
if (!Array.isArray(sg.nodes)) continue;
|
||||
const sgResult = extractPromptsFromNodeSet(sg.nodes, sg.links ?? []);
|
||||
if (sgResult) return sgResult;
|
||||
}
|
||||
|
||||
// 6. PromptStyler フォールバック
|
||||
const stylerPos = new Set(), stylerNeg = new Set();
|
||||
for (const n of nodes) {
|
||||
if (!isPromptStylerNode(n.type ?? "")) continue;
|
||||
const vals = n.widgets_values ?? [];
|
||||
for (let i = 0; i < vals.length; i++) {
|
||||
if (typeof vals[i] !== "string" || !vals[i].trim()) continue;
|
||||
if (i % 2 === 0) stylerPos.add(vals[i]);
|
||||
else stylerNeg.add(vals[i]);
|
||||
}
|
||||
}
|
||||
if (stylerPos.size > 0 || stylerNeg.size > 0) return { positives: [...stylerPos], negatives: [...stylerNeg] };
|
||||
|
||||
// 7. テキストエンコーダー全テキスト(最終フォールバック)- サブグラフも含む・判別不能
|
||||
const all = [];
|
||||
for (const n of collectAllNodes(wf)) {
|
||||
if (!isTextEncoderNode(n.type ?? "")) continue;
|
||||
const t = n.widgets_values?.[0];
|
||||
if (t && typeof t === "string" && t.trim()) all.push(t);
|
||||
}
|
||||
return { positives: [], negatives: [], texts: all };
|
||||
}
|
||||
|
||||
// ── SD/Fooocus prompt extraction ──────────────────────────────
|
||||
function parseSDAParameters(raw) {
|
||||
const text = raw.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
||||
const stepsMatch = text.match(/\nSteps:\s+\d/);
|
||||
if (!stepsMatch) return null;
|
||||
const paramsStart = stepsMatch.index + 1;
|
||||
const promptSection = text.slice(0, paramsStart - 1);
|
||||
const paramsLine = text.slice(paramsStart);
|
||||
const negSep = "\nNegative prompt: ";
|
||||
const negIdx = promptSection.indexOf(negSep);
|
||||
let positive = "", negative = "";
|
||||
if (negIdx !== -1) { positive = promptSection.slice(0, negIdx).trim(); negative = promptSection.slice(negIdx + negSep.length).trim(); }
|
||||
else positive = promptSection.trim();
|
||||
const params = {};
|
||||
const re = /,?\s*([A-Za-z][A-Za-z0-9 ]*):\s*("(?:[^"\\]|\\.)*"|[^,]+)/g;
|
||||
let m;
|
||||
while ((m = re.exec(paramsLine)) !== null) params[m[1].trim()] = m[2].trim().replace(/^"|"$/g, "");
|
||||
return { positive, negative, params };
|
||||
}
|
||||
function parseFooocusMetadata(raw) {
|
||||
let obj; try { obj = JSON.parse(raw); } catch { return null; }
|
||||
if (!obj?.base_model) return null;
|
||||
const toArray = v => !v ? [] : Array.isArray(v) ? v.filter(Boolean) : [String(v)];
|
||||
return { checkpoint: obj.base_model, vae: (obj.vae && obj.vae !== "Default") ? obj.vae : null, positives: toArray(obj.full_prompt ?? obj.prompt), negatives: toArray(obj.full_negative_prompt ?? obj.negative_prompt) };
|
||||
}
|
||||
|
||||
// ── Master extractAllMetadata ─────────────────────────────────
|
||||
async function extractAllMetadata(file) {
|
||||
const name = file.name.toLowerCase();
|
||||
const isJSON = file.type === "application/json" || name.endsWith(".json");
|
||||
const isWebP = file.type === "image/webp" || name.endsWith(".webp");
|
||||
|
||||
function fromWorkflow(wf, source) {
|
||||
const base = { source, checkpoints: extractCheckpoints(wf), vaes: extractVAEs(wf), diffusionModels: extractDiffusionModels(wf), textEncoders: extractTextEncoders(wf), loras: extractLoRAs(wf), ...extractPrompts(wf) };
|
||||
// MarkdownNote からモデル情報を補完(subgraph形式の flux/qwen/z-image など)
|
||||
const mdm = extractMarkdownNoteModels(wf);
|
||||
if (mdm) {
|
||||
if (!base.checkpoints.length) base.checkpoints = mdm.checkpoints;
|
||||
if (!base.vaes.length) base.vaes = mdm.vaes;
|
||||
if (!base.diffusionModels.length) base.diffusionModels = mdm.diffusionModels;
|
||||
if (!base.textEncoders.length) base.textEncoders = mdm.textEncoders;
|
||||
if (!base.loras.length) base.loras = mdm.loras;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
if (isJSON) {
|
||||
let wf; try { wf = JSON.parse(sanitizeJSON(await file.text())); } catch { return null; }
|
||||
return wf ? fromWorkflow(wf, "comfyui") : null;
|
||||
}
|
||||
if (isWebP) {
|
||||
const exif = await readWebPEXIFChunk(file);
|
||||
if (!exif) return null;
|
||||
const wf = extractWorkflowFromEXIF(exif);
|
||||
return wf ? fromWorkflow(wf, "comfyui") : null;
|
||||
}
|
||||
// PNG
|
||||
const chunks = await readAllPNGTextChunks(file);
|
||||
if (!chunks) return null;
|
||||
|
||||
if (chunks.prompt) { let wf; try { wf = JSON.parse(sanitizeJSON(chunks.prompt)); } catch { return null; } return wf ? fromWorkflow(wf, "comfyui") : null; }
|
||||
if (chunks.workflow) { let wf; try { wf = JSON.parse(sanitizeJSON(chunks.workflow)); } catch { return null; } return wf ? fromWorkflow(wf, "comfyui") : null; }
|
||||
|
||||
if (chunks.fooocus_scheme === "fooocus" && chunks.parameters) {
|
||||
const f = parseFooocusMetadata(chunks.parameters);
|
||||
if (!f) return null;
|
||||
return { source: "fooocus", checkpoints: [f.checkpoint], vaes: f.vae ? [f.vae] : [], diffusionModels: [], textEncoders: [], loras: [], positives: f.positives, negatives: f.negatives };
|
||||
}
|
||||
if (chunks.parameters) {
|
||||
const p = parseSDAParameters(chunks.parameters);
|
||||
if (!p) return null;
|
||||
const { positive, negative, params } = p;
|
||||
const modelName = params["Model"];
|
||||
if (!modelName) return null;
|
||||
if (params["Module 2"] != null) {
|
||||
const textEncoders = [];
|
||||
for (let i = 2; i <= 9; i++) { const mod = params[`Module ${i}`]; if (!mod) break; textEncoders.push(mod); }
|
||||
return { source: "sd_forge", checkpoints: [], vaes: params["Module 1"] ? [params["Module 1"]] : [], diffusionModels: [modelName], textEncoders, loras: [], positives: positive ? [positive] : [], negatives: negative ? [negative] : [] };
|
||||
}
|
||||
const vaeValue = params["Module 1"] ?? params["VAE"] ?? null;
|
||||
return { source: "sd", checkpoints: [modelName], vaes: vaeValue ? [vaeValue] : [], diffusionModels: [], textEncoders: [], loras: [], positives: positive ? [positive] : [], negatives: negative ? [negative] : [] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── UI helpers ────────────────────────────────────────────────
|
||||
function escapeHtml(s) { return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }
|
||||
|
||||
function buildModelItem(label) {
|
||||
const el = document.createElement("div");
|
||||
el.className = "wfm-meta-item";
|
||||
el.title = label;
|
||||
el.innerHTML = `<span class="wfm-meta-item-name">${escapeHtml(label)}</span>`;
|
||||
return el;
|
||||
}
|
||||
|
||||
function buildLoRAItem(lora) {
|
||||
const el = document.createElement("div");
|
||||
el.className = "wfm-meta-item";
|
||||
el.title = lora.name;
|
||||
const sm = lora.strength_model.toFixed(2);
|
||||
const sc = lora.strength_clip.toFixed(2);
|
||||
el.innerHTML = `<span class="wfm-meta-item-name">${escapeHtml(lora.name)}</span><span class="wfm-meta-item-badge">${sm}/${sc}</span>`;
|
||||
return el;
|
||||
}
|
||||
|
||||
function buildPromptItem(label, type, full, fullArea, fullLabel, listEl) {
|
||||
const el = document.createElement("div");
|
||||
el.className = "wfm-meta-item wfm-meta-item-clickable";
|
||||
const snippet = label.length > 60 ? label.slice(0, 60) + "…" : label;
|
||||
const typeBadge = type === "positive" ? `<span class="wfm-meta-badge-pos">POS</span>`
|
||||
: type === "negative" ? `<span class="wfm-meta-badge-neg">NEG</span>`
|
||||
: ``;
|
||||
el.innerHTML = `${typeBadge}<span class="wfm-meta-item-name">${escapeHtml(snippet)}</span>`;
|
||||
el.addEventListener("click", () => {
|
||||
listEl.querySelectorAll(".wfm-meta-item-clickable").forEach(e => e.classList.remove("selected"));
|
||||
el.classList.add("selected");
|
||||
fullArea.value = full;
|
||||
fullLabel.textContent = type === "positive" ? t("metaPromptPositive")
|
||||
: type === "negative" ? t("metaPromptNegative")
|
||||
: t("metaPromptText") || "Text";
|
||||
});
|
||||
return el;
|
||||
}
|
||||
|
||||
function renderSection(sectionEl, listEl, items, buildFn) {
|
||||
listEl.innerHTML = "";
|
||||
if (items.length === 0) { sectionEl.classList.add("wfm-meta-section-empty"); return; }
|
||||
sectionEl.classList.remove("wfm-meta-section-empty");
|
||||
for (const item of items) listEl.appendChild(buildFn(item));
|
||||
}
|
||||
|
||||
// ── Tab initialization ────────────────────────────────────────
|
||||
export function initMetadataTab() {
|
||||
const dropZone = document.getElementById("wfm-meta-drop");
|
||||
const dropLabel = document.getElementById("wfm-meta-drop-label");
|
||||
const previewImg = document.getElementById("wfm-meta-preview-img");
|
||||
const fileInfo = document.getElementById("wfm-meta-file-info");
|
||||
const fileInput = document.getElementById("wfm-meta-file-input");
|
||||
|
||||
const ckptSection = document.getElementById("wfm-meta-ckpt-section");
|
||||
const vaeSection = document.getElementById("wfm-meta-vae-section");
|
||||
const diffSection = document.getElementById("wfm-meta-diff-section");
|
||||
const teSection = document.getElementById("wfm-meta-te-section");
|
||||
const loraSection = document.getElementById("wfm-meta-lora-section");
|
||||
const promptSection = document.getElementById("wfm-meta-prompt-section");
|
||||
|
||||
const ckptList = document.getElementById("wfm-meta-ckpt-list");
|
||||
const vaeList = document.getElementById("wfm-meta-vae-list");
|
||||
const diffList = document.getElementById("wfm-meta-diff-list");
|
||||
const teList = document.getElementById("wfm-meta-te-list");
|
||||
const loraList = document.getElementById("wfm-meta-lora-list");
|
||||
const promptList = document.getElementById("wfm-meta-prompt-list");
|
||||
const promptFull = document.getElementById("wfm-meta-prompt-full");
|
||||
const promptFullLabel = document.getElementById("wfm-meta-prompt-full-label");
|
||||
|
||||
if (!dropZone) return;
|
||||
|
||||
// Apply i18n to section titles
|
||||
const titleMap = {
|
||||
"wfm-meta-ckpt-section": "metaSectionCkpt",
|
||||
"wfm-meta-vae-section": "metaSectionVae",
|
||||
"wfm-meta-diff-section": "metaSectionDiff",
|
||||
"wfm-meta-te-section": "metaSectionTe",
|
||||
"wfm-meta-lora-section": "metaSectionLora",
|
||||
"wfm-meta-prompt-section": "metaSectionPrompt",
|
||||
};
|
||||
for (const [id, key] of Object.entries(titleMap)) {
|
||||
const title = document.querySelector(`#${id} .wfm-meta-section-title`);
|
||||
if (title) { const tx = t(key); if (tx && tx !== key) title.textContent = tx; }
|
||||
}
|
||||
|
||||
// Apply i18n to format note
|
||||
const i18nIds = {
|
||||
"wfm-meta-format-note-title": "metaFormatNoteTitle",
|
||||
"wfm-meta-fmt-comfyui": "metaFmtComfyui",
|
||||
"wfm-meta-fmt-sdwebui": "metaFmtSdwebui",
|
||||
"wfm-meta-fmt-fooocus": "metaFmtFooocus",
|
||||
"wfm-meta-format-todo": "metaFormatTodo",
|
||||
};
|
||||
for (const [id, key] of Object.entries(i18nIds)) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) { const tx = t(key); if (tx && tx !== key) el.textContent = tx; }
|
||||
}
|
||||
|
||||
// Apply i18n to help card
|
||||
const helpIds = {
|
||||
"wfm-help-metadata-title": "helpMetadataTitle",
|
||||
"wfm-help-metadata-desc": "helpMetadataDesc",
|
||||
"wfm-help-metadata-1": "helpMetadata1",
|
||||
"wfm-help-metadata-2": "helpMetadata2",
|
||||
"wfm-help-metadata-3": "helpMetadata3",
|
||||
"wfm-help-metadata-4": "helpMetadata4",
|
||||
"wfm-help-metadata-5": "helpMetadata5",
|
||||
};
|
||||
for (const [id, key] of Object.entries(helpIds)) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) { const tx = t(key); if (tx && tx !== key) el.textContent = tx; }
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
[ckptList, vaeList, diffList, teList, loraList, promptList].forEach(l => { if (l) l.innerHTML = ""; });
|
||||
[ckptSection, vaeSection, diffSection, teSection, loraSection, promptSection].forEach(s => { if (s) s.classList.add("wfm-meta-section-empty"); });
|
||||
if (promptFull) promptFull.value = "";
|
||||
if (promptFullLabel) promptFullLabel.textContent = "";
|
||||
}
|
||||
|
||||
async function handleFile(file) {
|
||||
if (!file) return;
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
fileInfo.textContent = t("metaFileTooLarge");
|
||||
fileInfo.style.color = "var(--wfm-warning)";
|
||||
return;
|
||||
}
|
||||
|
||||
fileInfo.textContent = t("metaParsing");
|
||||
fileInfo.style.color = "var(--wfm-text-secondary)";
|
||||
clearAll();
|
||||
|
||||
// Show preview for images
|
||||
const isImage = file.type.startsWith("image/") || file.name.toLowerCase().match(/\.(png|webp|jpg|jpeg)$/);
|
||||
if (isImage) {
|
||||
const url = URL.createObjectURL(file);
|
||||
previewImg.src = url;
|
||||
previewImg.style.display = "block";
|
||||
dropLabel.style.display = "none";
|
||||
previewImg.onload = () => URL.revokeObjectURL(url);
|
||||
} else {
|
||||
previewImg.style.display = "none";
|
||||
dropLabel.style.display = "flex";
|
||||
}
|
||||
|
||||
let meta;
|
||||
try {
|
||||
meta = await extractAllMetadata(file);
|
||||
} catch (err) {
|
||||
console.error("[MetadataTab]", err);
|
||||
fileInfo.textContent = t("metaParseError");
|
||||
fileInfo.style.color = "var(--wfm-danger)";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!meta) {
|
||||
fileInfo.textContent = t("metaNoMetadata");
|
||||
fileInfo.style.color = "var(--wfm-warning)";
|
||||
return;
|
||||
}
|
||||
|
||||
const sizeKB = (file.size / 1024).toFixed(1);
|
||||
const sourceLabel = { comfyui: "ComfyUI", sd: "SD WebUI", sd_forge: "SD Forge", fooocus: "Fooocus" }[meta.source] ?? meta.source;
|
||||
fileInfo.textContent = `${file.name} (${sizeKB} KB · ${sourceLabel})`;
|
||||
fileInfo.style.color = "var(--wfm-text-secondary)";
|
||||
|
||||
renderSection(ckptSection, ckptList, meta.checkpoints, n => buildModelItem(n));
|
||||
renderSection(vaeSection, vaeList, meta.vaes, n => buildModelItem(n));
|
||||
renderSection(diffSection, diffList, meta.diffusionModels, n => buildModelItem(n));
|
||||
renderSection(teSection, teList, meta.textEncoders, n => buildModelItem(n));
|
||||
renderSection(loraSection, loraList, meta.loras, l => buildLoRAItem(l));
|
||||
|
||||
// Prompts
|
||||
promptList.innerHTML = "";
|
||||
const allPrompts = [
|
||||
...meta.positives.map(p => ({ type: "positive", text: p })),
|
||||
...meta.negatives.map(p => ({ type: "negative", text: p })),
|
||||
...(meta.texts ?? []).map(p => ({ type: "text", text: p })),
|
||||
];
|
||||
if (allPrompts.length > 0) {
|
||||
promptSection.classList.remove("wfm-meta-section-empty");
|
||||
for (const { type, text } of allPrompts) {
|
||||
promptList.appendChild(buildPromptItem(text, type, text, promptFull, promptFullLabel, promptList));
|
||||
}
|
||||
// Auto-select first positive
|
||||
const firstPositive = promptList.querySelector(".wfm-meta-item-clickable");
|
||||
if (firstPositive) firstPositive.click();
|
||||
} else {
|
||||
promptSection.classList.add("wfm-meta-section-empty");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Prompt action buttons ─────────────────────────────────
|
||||
function getPromptText() { return promptFull?.value ?? ""; }
|
||||
|
||||
function flashBtn(btn) {
|
||||
btn.classList.add("wfm-meta-btn-flash");
|
||||
setTimeout(() => btn.classList.remove("wfm-meta-btn-flash"), 600);
|
||||
}
|
||||
|
||||
function setTextareaValue(id, text) {
|
||||
const el = document.getElementById(id);
|
||||
if (!el) return false;
|
||||
el.value = text;
|
||||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
return true;
|
||||
}
|
||||
|
||||
document.getElementById("wfm-meta-copy-btn")?.addEventListener("click", function () {
|
||||
const text = getPromptText();
|
||||
if (!text) return;
|
||||
navigator.clipboard.writeText(text).then(() => flashBtn(this));
|
||||
});
|
||||
|
||||
document.getElementById("wfm-meta-genui-pos-btn")?.addEventListener("click", function () {
|
||||
const text = getPromptText();
|
||||
if (!text) return;
|
||||
if (setTextareaValue("wfm-prompt-pos-text", text)) flashBtn(this);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-meta-genui-neg-btn")?.addEventListener("click", function () {
|
||||
const text = getPromptText();
|
||||
if (!text) return;
|
||||
if (setTextareaValue("wfm-prompt-neg-text", text)) flashBtn(this);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-meta-preset-pos-btn")?.addEventListener("click", function () {
|
||||
const text = getPromptText();
|
||||
if (!text) return;
|
||||
if (setTextareaValue("wfm-preset-pos", text)) flashBtn(this);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-meta-preset-neg-btn")?.addEventListener("click", function () {
|
||||
const text = getPromptText();
|
||||
if (!text) return;
|
||||
if (setTextareaValue("wfm-preset-neg", text)) flashBtn(this);
|
||||
});
|
||||
|
||||
// Drag & Drop
|
||||
dropZone.addEventListener("dragover", e => { e.preventDefault(); e.stopPropagation(); dropZone.classList.add("drag-over"); });
|
||||
dropZone.addEventListener("dragleave", e => { e.stopPropagation(); dropZone.classList.remove("drag-over"); });
|
||||
dropZone.addEventListener("drop", e => { e.preventDefault(); e.stopPropagation(); dropZone.classList.remove("drag-over"); handleFile(e.dataTransfer.files?.[0]); });
|
||||
dropZone.addEventListener("click", e => { if (e.target === previewImg) return; fileInput.click(); });
|
||||
fileInput.addEventListener("change", () => { handleFile(fileInput.files?.[0]); fileInput.value = ""; });
|
||||
|
||||
// Prevent scroll passthrough in lists
|
||||
[ckptList, vaeList, diffList, teList, loraList, promptList].forEach(l => {
|
||||
if (l) l.addEventListener("wheel", e => e.stopPropagation(), { passive: true });
|
||||
});
|
||||
|
||||
clearAll();
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import { t } from "./i18n.js";
|
||||
|
||||
// ── State ─────────────────────────────────────────────────
|
||||
|
||||
const NODES_PER_PAGE = 50;
|
||||
|
||||
const state = {
|
||||
allNodes: [],
|
||||
@@ -257,111 +256,50 @@ function renderNodeGrid() {
|
||||
|
||||
if (filtered.length === 0) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">${t("noNodesFound")}</p>`;
|
||||
removePagination();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.viewMode === "table") {
|
||||
renderNodeTableView(grid, filtered);
|
||||
removePagination();
|
||||
return;
|
||||
}
|
||||
|
||||
// Card view with pagination
|
||||
const totalPages = Math.ceil(filtered.length / NODES_PER_PAGE);
|
||||
if (state.currentPage >= totalPages) state.currentPage = totalPages - 1;
|
||||
if (state.currentPage < 0) state.currentPage = 0;
|
||||
|
||||
const start = state.currentPage * NODES_PER_PAGE;
|
||||
const pageItems = filtered.slice(start, start + NODES_PER_PAGE);
|
||||
|
||||
grid.innerHTML = "";
|
||||
pageItems.forEach(node => {
|
||||
const meta = state.nodeMetadata[node.name] || {};
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-card wfm-node-card";
|
||||
if (state.selectedNode && state.selectedNode.name === node.name) {
|
||||
card.classList.add("wfm-card-selected");
|
||||
}
|
||||
card.dataset.nodeName = node.name;
|
||||
filtered.forEach(node => grid.appendChild(createNodeCard(node)));
|
||||
}
|
||||
|
||||
const inputCount = Object.keys(node.input.required || {}).length +
|
||||
Object.keys(node.input.optional || {}).length;
|
||||
const outputCount = (node.output || []).length;
|
||||
const tags = (meta.tags || []).map(tg => `<span class="wfm-tag">#${escapeHtml(tg)}</span>`).join("");
|
||||
const favStar = meta.favorite ? "\u2605" : "\u2606";
|
||||
const favClass = meta.favorite ? "wfm-fav-btn active" : "wfm-fav-btn";
|
||||
function createNodeCard(node) {
|
||||
const meta = state.nodeMetadata[node.name] || {};
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-card wfm-node-card";
|
||||
if (state.selectedNode && state.selectedNode.name === node.name) {
|
||||
card.classList.add("wfm-card-selected");
|
||||
}
|
||||
card.dataset.nodeName = node.name;
|
||||
card.style.borderLeft = `3px solid ${packageColor(node.package)}`;
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="wfm-card-body">
|
||||
<div class="wfm-card-title" title="${escapeHtml(node.name)}">${escapeHtml(node.display_name)}</div>
|
||||
<div class="wfm-card-meta">
|
||||
${packageBadgeHtml(node.package)}
|
||||
${categoryBadgeHtml(node.category)}
|
||||
</div>
|
||||
<div class="wfm-node-card-io">In: ${inputCount} / Out: ${outputCount}</div>
|
||||
${tags ? `<div class="wfm-card-tags">${tags}</div>` : ""}
|
||||
const tags = (meta.tags || []).map(tg => `<span class="wfm-tag">#${escapeHtml(tg)}</span>`).join("");
|
||||
const favStar = meta.favorite ? "\u2605" : "\u2606";
|
||||
const favClass = meta.favorite ? "wfm-fav-btn active" : "wfm-fav-btn";
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="wfm-card-body">
|
||||
<div class="wfm-card-title" title="${escapeHtml(node.name)}">${escapeHtml(node.display_name)}</div>
|
||||
<div class="wfm-card-meta">
|
||||
${categoryBadgeHtml(node.category)}
|
||||
</div>
|
||||
<button class="${favClass}" title="Favorite">${favStar}</button>`;
|
||||
${tags ? `<div class="wfm-card-tags">${tags}</div>` : ""}
|
||||
</div>
|
||||
<button class="${favClass}" title="Favorite">${favStar}</button>`;
|
||||
|
||||
card.querySelector(".wfm-fav-btn").addEventListener("click", e => {
|
||||
e.stopPropagation();
|
||||
toggleFavorite(node.name, e.currentTarget);
|
||||
});
|
||||
card.addEventListener("click", () => showNodeSidePanel(node));
|
||||
grid.appendChild(card);
|
||||
card.querySelector(".wfm-fav-btn").addEventListener("click", e => {
|
||||
e.stopPropagation();
|
||||
toggleFavorite(node.name, e.currentTarget);
|
||||
});
|
||||
|
||||
renderPagination(filtered.length, totalPages);
|
||||
card.addEventListener("click", () => showNodeSidePanel(node));
|
||||
return card;
|
||||
}
|
||||
|
||||
function renderPagination(totalItems, totalPages) {
|
||||
removePagination();
|
||||
if (totalPages <= 1) return;
|
||||
|
||||
const grid = document.getElementById("wfm-nodes-grid");
|
||||
if (!grid) return;
|
||||
|
||||
const pager = document.createElement("div");
|
||||
pager.id = "wfm-nodes-pagination";
|
||||
pager.className = "wfm-pagination";
|
||||
|
||||
const prevBtn = document.createElement("button");
|
||||
prevBtn.className = "wfm-btn wfm-btn-sm";
|
||||
prevBtn.textContent = "\u25C0";
|
||||
prevBtn.disabled = state.currentPage === 0;
|
||||
prevBtn.addEventListener("click", () => {
|
||||
if (state.currentPage > 0) { state.currentPage--; renderNodeGrid(); scrollGridToTop(); }
|
||||
});
|
||||
|
||||
const nextBtn = document.createElement("button");
|
||||
nextBtn.className = "wfm-btn wfm-btn-sm";
|
||||
nextBtn.textContent = "\u25B6";
|
||||
nextBtn.disabled = state.currentPage >= totalPages - 1;
|
||||
nextBtn.addEventListener("click", () => {
|
||||
if (state.currentPage < totalPages - 1) { state.currentPage++; renderNodeGrid(); scrollGridToTop(); }
|
||||
});
|
||||
|
||||
const info = document.createElement("span");
|
||||
info.className = "wfm-pagination-info";
|
||||
const start = state.currentPage * NODES_PER_PAGE + 1;
|
||||
const end = Math.min((state.currentPage + 1) * NODES_PER_PAGE, totalItems);
|
||||
info.textContent = `${start}-${end} / ${totalItems}`;
|
||||
|
||||
pager.appendChild(prevBtn);
|
||||
pager.appendChild(info);
|
||||
pager.appendChild(nextBtn);
|
||||
|
||||
grid.parentElement.insertBefore(pager, grid.nextSibling);
|
||||
}
|
||||
|
||||
function removePagination() {
|
||||
document.getElementById("wfm-nodes-pagination")?.remove();
|
||||
}
|
||||
|
||||
function scrollGridToTop() {
|
||||
document.getElementById("wfm-nodes-grid")?.scrollTo(0, 0);
|
||||
}
|
||||
|
||||
function renderNodeTableView(grid, filtered) {
|
||||
grid.innerHTML = "";
|
||||
@@ -419,9 +357,6 @@ async function toggleFavorite(nodeName, btnEl) {
|
||||
|
||||
function showNodeSidePanel(node) {
|
||||
state.selectedNode = node;
|
||||
const panel = document.getElementById("wfm-nodes-side-panel");
|
||||
if (!panel) return;
|
||||
panel.style.display = "flex";
|
||||
|
||||
// Highlight selected card
|
||||
document.querySelectorAll("#wfm-nodes-grid .wfm-card, #wfm-nodes-grid tr").forEach(el => {
|
||||
@@ -565,42 +500,61 @@ function renderSideGroups(node) {
|
||||
const el = document.getElementById("wfm-nodes-side-group");
|
||||
if (!el) return;
|
||||
|
||||
const groupNames = Object.keys(state.nodeGroups).sort();
|
||||
const memberOf = groupNames.filter(g => (state.nodeGroups[g] || []).includes(node.name));
|
||||
const allGroups = Object.keys(state.nodeGroups).sort();
|
||||
const memberOf = allGroups.filter(g => (state.nodeGroups[g] || []).includes(node.name));
|
||||
const available = allGroups.filter(g => !memberOf.includes(g));
|
||||
|
||||
let html = `<h4 style="margin:0 0 8px;">${t("nodesGroups")}</h4>`;
|
||||
el.innerHTML = `
|
||||
<div style="padding:0 4px;">
|
||||
<div style="margin-bottom:12px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsCurrentGroups")}</div>
|
||||
${memberOf.length === 0
|
||||
? `<p style="color:var(--wfm-text-secondary);font-size:12px;">${t("modelsNoGroup")}</p>`
|
||||
: memberOf.map(g =>
|
||||
`<div style="display:flex;align-items:center;justify-content:space-between;padding:3px 0;">
|
||||
<span style="font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHtml(g)}</span>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger wfm-node-remove-group" data-group="${escapeHtml(g)}" title="${t("modelsRemoveFromGroup")}">×</button>
|
||||
</div>`
|
||||
).join("")}
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsAssignGroup")}</div>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<select id="wfm-nodes-assign-group-select" class="wfm-select" style="flex:1;font-size:12px;padding:3px 6px;">
|
||||
${available.length === 0
|
||||
? `<option value="">${t("modelsNoGroupAvailable")}</option>`
|
||||
: available.map(g => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("")}
|
||||
</select>
|
||||
<button id="wfm-nodes-assign-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary"
|
||||
${available.length === 0 ? "disabled" : ""}>${t("modelsAdd")}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsCreateGroup")}</div>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<input type="text" id="wfm-nodes-new-group-input" class="wfm-input"
|
||||
style="flex:1;font-size:12px;padding:3px 6px;" placeholder="${t("modelsGroupName")}">
|
||||
<button id="wfm-nodes-create-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">${t("modelsCreate")}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="border-top:1px solid var(--wfm-border);padding-top:10px;margin-top:4px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsManageGroups")}</div>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<select id="wfm-nodes-manage-group-select" class="wfm-select" style="flex:1;font-size:12px;padding:3px 6px;">
|
||||
${allGroups.length === 0
|
||||
? `<option value="">${t("modelsNoGroupAvailable")}</option>`
|
||||
: allGroups.map(g => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("")}
|
||||
</select>
|
||||
<button id="wfm-nodes-rename-group-btn" class="wfm-btn wfm-btn-sm"
|
||||
${allGroups.length === 0 ? "disabled" : ""} title="${t("modelsRename")}">✎</button>
|
||||
<button id="wfm-nodes-delete-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger"
|
||||
${allGroups.length === 0 ? "disabled" : ""} title="${t("modelsDelete")}">×</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Current groups
|
||||
if (memberOf.length) {
|
||||
html += memberOf.map(g =>
|
||||
`<div class="wfm-node-group-item">
|
||||
<span>${escapeHtml(g)}</span>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger wfm-node-remove-group" data-group="${escapeHtml(g)}">${t("nodesRemoveGroup")}</button>
|
||||
</div>`
|
||||
).join("");
|
||||
} else {
|
||||
html += `<p style="color:var(--wfm-text-secondary);font-size:12px;">No groups assigned</p>`;
|
||||
}
|
||||
|
||||
// Assign to group
|
||||
const available = groupNames.filter(g => !memberOf.includes(g));
|
||||
html += `<div style="margin-top:12px;display:flex;gap:4px;">
|
||||
<select id="wfm-nodes-assign-group-select" class="wfm-select" style="flex:1;">
|
||||
<option value="">${t("nodesAssignGroup")}</option>
|
||||
${available.map(g => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("")}
|
||||
</select>
|
||||
<button id="wfm-nodes-assign-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">+</button>
|
||||
</div>`;
|
||||
|
||||
// Create new group
|
||||
html += `<div style="margin-top:8px;display:flex;gap:4px;">
|
||||
<input type="text" id="wfm-nodes-new-group-input" class="wfm-input" style="flex:1;" placeholder="${t("nodesGroupName")}">
|
||||
<button id="wfm-nodes-create-group-btn" class="wfm-btn wfm-btn-sm">${t("nodesCreateGroup")}</button>
|
||||
</div>`;
|
||||
|
||||
el.innerHTML = html;
|
||||
|
||||
// Event listeners
|
||||
// グループから除外
|
||||
el.querySelectorAll(".wfm-node-remove-group").forEach(btn => {
|
||||
btn.addEventListener("click", async () => {
|
||||
const group = btn.dataset.group;
|
||||
@@ -612,8 +566,9 @@ function renderSideGroups(node) {
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById("wfm-nodes-assign-group-btn")?.addEventListener("click", async () => {
|
||||
const sel = document.getElementById("wfm-nodes-assign-group-select");
|
||||
// グループに追加
|
||||
el.querySelector("#wfm-nodes-assign-group-btn")?.addEventListener("click", async () => {
|
||||
const sel = el.querySelector("#wfm-nodes-assign-group-select");
|
||||
const group = sel?.value;
|
||||
if (!group) return;
|
||||
if (!state.nodeGroups[group]) state.nodeGroups[group] = [];
|
||||
@@ -625,25 +580,61 @@ function renderSideGroups(node) {
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("wfm-nodes-create-group-btn")?.addEventListener("click", async () => {
|
||||
const input = document.getElementById("wfm-nodes-new-group-input");
|
||||
// グループ作成(作成後に現在のノードに追加)
|
||||
el.querySelector("#wfm-nodes-create-group-btn")?.addEventListener("click", async () => {
|
||||
const input = el.querySelector("#wfm-nodes-new-group-input");
|
||||
const name = input?.value?.trim();
|
||||
if (!name) return;
|
||||
if (!state.nodeGroups[name]) state.nodeGroups[name] = [];
|
||||
if (!state.nodeGroups[name].includes(node.name)) {
|
||||
state.nodeGroups[name].push(node.name);
|
||||
if (state.nodeGroups[name]) {
|
||||
showToast("Group already exists", "warning");
|
||||
return;
|
||||
}
|
||||
state.nodeGroups[name] = [node.name];
|
||||
await saveNodeGroups(state.nodeGroups);
|
||||
input.value = "";
|
||||
renderSideGroups(node);
|
||||
renderFilters();
|
||||
});
|
||||
|
||||
// グループ名変更
|
||||
el.querySelector("#wfm-nodes-rename-group-btn")?.addEventListener("click", async () => {
|
||||
const sel = el.querySelector("#wfm-nodes-manage-group-select");
|
||||
const oldName = sel?.value;
|
||||
if (!oldName) return;
|
||||
const newName = prompt(`Rename group "${oldName}" to:`, oldName);
|
||||
if (!newName || newName === oldName) return;
|
||||
if (state.nodeGroups[newName] !== undefined) {
|
||||
showToast("Group name already exists", "warning");
|
||||
return;
|
||||
}
|
||||
state.nodeGroups[newName] = state.nodeGroups[oldName];
|
||||
delete state.nodeGroups[oldName];
|
||||
await saveNodeGroups(state.nodeGroups);
|
||||
if (state.groupFilter === oldName) state.groupFilter = newName;
|
||||
renderSideGroups(node);
|
||||
renderFilters();
|
||||
showToast(`Renamed to "${newName}"`, "success");
|
||||
});
|
||||
|
||||
// グループ削除
|
||||
el.querySelector("#wfm-nodes-delete-group-btn")?.addEventListener("click", async () => {
|
||||
const sel = el.querySelector("#wfm-nodes-manage-group-select");
|
||||
const name = sel?.value;
|
||||
if (!name) return;
|
||||
if (!confirm(`Delete group "${name}"?`)) return;
|
||||
delete state.nodeGroups[name];
|
||||
await saveNodeGroups(state.nodeGroups);
|
||||
if (state.groupFilter === name) state.groupFilter = "";
|
||||
renderSideGroups(node);
|
||||
renderFilters();
|
||||
showToast(`Group "${name}" deleted`, "success");
|
||||
});
|
||||
}
|
||||
|
||||
function closeNodeSidePanel() {
|
||||
const panel = document.getElementById("wfm-nodes-side-panel");
|
||||
if (panel) panel.style.display = "none";
|
||||
state.selectedNode = null;
|
||||
const titleEl = document.getElementById("wfm-nodes-panel-title");
|
||||
if (titleEl) titleEl.textContent = "";
|
||||
document.querySelectorAll("#wfm-nodes-grid .wfm-card, #wfm-nodes-grid tr").forEach(el => {
|
||||
el.classList.remove("wfm-card-selected");
|
||||
});
|
||||
@@ -1103,8 +1094,6 @@ export function initNodesTab() {
|
||||
loadNodesData();
|
||||
});
|
||||
|
||||
// Side panel close
|
||||
document.getElementById("wfm-nodes-panel-close")?.addEventListener("click", closeNodeSidePanel);
|
||||
|
||||
// Side panel tab switching
|
||||
document.querySelectorAll(".wfm-nodes-side-tab-btn").forEach(btn => {
|
||||
|
||||
@@ -593,6 +593,233 @@ function applyToGenerateUI(text) {
|
||||
showToast(t("appliedToGenerateUI"), "success");
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Wildcard API helpers
|
||||
// ============================================
|
||||
|
||||
async function wcFetchFiles() {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/wildcards");
|
||||
return res.ok ? await res.json() : [];
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
async function wcFetchContent(filename) {
|
||||
try {
|
||||
const res = await fetch(`/api/wfm/wildcards/content?filename=${encodeURIComponent(filename)}`);
|
||||
const data = await res.json();
|
||||
return data.content ?? null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async function wcSaveFile(filename, content) {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/wildcards/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ filename, content }),
|
||||
});
|
||||
const data = await res.json();
|
||||
return data.status === "ok" ? data.file : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
async function wcDeleteFile(filename) {
|
||||
try {
|
||||
await fetch("/api/wfm/wildcards/delete", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ filename }),
|
||||
});
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Wildcard state & helpers
|
||||
// ============================================
|
||||
|
||||
let wcFiles = [];
|
||||
let wcEditingFilename = null; // null = new file
|
||||
|
||||
// Insert text at cursor; if open+close provided wraps selection
|
||||
function wcInsertAtCursor(textarea, open, close = "") {
|
||||
const start = textarea.selectionStart;
|
||||
const end = textarea.selectionEnd;
|
||||
const selected = textarea.value.substring(start, end);
|
||||
let inserted, cursorStart, cursorEnd;
|
||||
|
||||
if (selected && close) {
|
||||
inserted = open + selected + close;
|
||||
cursorStart = start + open.length;
|
||||
cursorEnd = cursorStart + selected.length;
|
||||
} else if (close) {
|
||||
inserted = open + close;
|
||||
cursorStart = start + open.length;
|
||||
cursorEnd = cursorStart;
|
||||
} else {
|
||||
inserted = open;
|
||||
cursorStart = start + open.length;
|
||||
cursorEnd = cursorStart;
|
||||
}
|
||||
|
||||
textarea.value =
|
||||
textarea.value.substring(0, start) +
|
||||
inserted +
|
||||
textarea.value.substring(end);
|
||||
textarea.setSelectionRange(cursorStart, cursorEnd);
|
||||
textarea.focus();
|
||||
textarea.dispatchEvent(new Event("input"));
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Wildcard file list rendering
|
||||
// ============================================
|
||||
|
||||
function wcRenderFileList() {
|
||||
const list = document.getElementById("wfm-wc-file-list");
|
||||
if (!list) return;
|
||||
list.innerHTML = "";
|
||||
|
||||
if (wcFiles.length === 0) {
|
||||
list.innerHTML = `<div class="wfm-pm-empty" style="font-size:12px;">No wildcard files yet.<br><small>Click "+ New" to create one.</small></div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Group by directory; root ("") first, then alphabetical
|
||||
const grouped = {};
|
||||
for (const f of wcFiles) {
|
||||
const dir = f.dir || "";
|
||||
if (!grouped[dir]) grouped[dir] = [];
|
||||
grouped[dir].push(f);
|
||||
}
|
||||
const dirs = Object.keys(grouped).sort((a, b) => {
|
||||
if (a === "") return -1;
|
||||
if (b === "") return 1;
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
|
||||
function addFileItem(f, indented) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "wfm-wc-file-item" + (indented ? " wfm-wc-file-item--sub" : "");
|
||||
item.innerHTML = `
|
||||
<div class="wfm-wc-file-item-info">
|
||||
<span class="wfm-wc-file-name">${esc(f.name)}</span>
|
||||
<span class="wfm-wc-file-ext">.${esc(f.ext)}</span>
|
||||
</div>
|
||||
<div class="wfm-wc-file-item-actions">
|
||||
<button class="wfm-pm-action-btn wfm-wc-use-btn" title="Insert __${esc(f.wc_name)}__ at cursor">Use</button>
|
||||
<button class="wfm-pm-action-btn wfm-wc-edit-btn" title="Edit file">✎</button>
|
||||
</div>
|
||||
`;
|
||||
item.querySelector(".wfm-wc-use-btn").addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (ta) wcInsertAtCursor(ta, `__${f.wc_name}__`);
|
||||
});
|
||||
item.querySelector(".wfm-wc-edit-btn").addEventListener("click", async (e) => {
|
||||
e.stopPropagation();
|
||||
const content = await wcFetchContent(f.filename);
|
||||
wcOpenEditor(f.wc_name, f.ext, content ?? "", f.filename);
|
||||
});
|
||||
item.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (ta) wcInsertAtCursor(ta, `__${f.wc_name}__`);
|
||||
});
|
||||
list.appendChild(item);
|
||||
}
|
||||
|
||||
for (const dir of dirs) {
|
||||
if (dir) {
|
||||
const header = document.createElement("div");
|
||||
header.className = "wfm-wc-dir-header";
|
||||
header.textContent = dir + "/";
|
||||
list.appendChild(header);
|
||||
}
|
||||
for (const f of grouped[dir]) {
|
||||
addFileItem(f, dir !== "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Wildcard file editor
|
||||
// ============================================
|
||||
|
||||
function wcOpenEditor(name, ext, content, existingFilename) {
|
||||
wcEditingFilename = existingFilename || null;
|
||||
|
||||
const editor = document.getElementById("wfm-wc-editor");
|
||||
const nameInput = document.getElementById("wfm-wc-editor-name");
|
||||
const extSelect = document.getElementById("wfm-wc-editor-ext");
|
||||
const contentTA = document.getElementById("wfm-wc-editor-content");
|
||||
const deleteBtn = document.getElementById("wfm-wc-editor-delete-btn");
|
||||
|
||||
if (!editor) return;
|
||||
nameInput.value = name || "";
|
||||
extSelect.value = ext || "txt";
|
||||
contentTA.value = content || "";
|
||||
deleteBtn.style.display = existingFilename ? "" : "none";
|
||||
editor.style.display = "";
|
||||
nameInput.focus();
|
||||
}
|
||||
|
||||
function wcCloseEditor() {
|
||||
wcEditingFilename = null;
|
||||
const editor = document.getElementById("wfm-wc-editor");
|
||||
if (editor) editor.style.display = "none";
|
||||
}
|
||||
|
||||
async function wcRefreshFiles() {
|
||||
wcFiles = await wcFetchFiles();
|
||||
wcRenderFileList();
|
||||
wcUpdateFilePicker();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Wildcard file picker popup
|
||||
// ============================================
|
||||
|
||||
function wcUpdateFilePicker() {
|
||||
const picker = document.getElementById("wfm-wc-file-picker");
|
||||
if (!picker) return;
|
||||
picker.innerHTML = "";
|
||||
if (wcFiles.length === 0) {
|
||||
picker.innerHTML = `<div style="padding:8px;font-size:11px;color:var(--wfm-text-secondary);">No wildcard files</div>`;
|
||||
return;
|
||||
}
|
||||
// Group by directory same as file list
|
||||
const grouped = {};
|
||||
for (const f of wcFiles) {
|
||||
const dir = f.dir || "";
|
||||
if (!grouped[dir]) grouped[dir] = [];
|
||||
grouped[dir].push(f);
|
||||
}
|
||||
const dirs = Object.keys(grouped).sort((a, b) => {
|
||||
if (a === "") return -1;
|
||||
if (b === "") return 1;
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
for (const dir of dirs) {
|
||||
if (dir) {
|
||||
const sep = document.createElement("div");
|
||||
sep.className = "wfm-wc-picker-dir";
|
||||
sep.textContent = dir + "/";
|
||||
picker.appendChild(sep);
|
||||
}
|
||||
for (const f of grouped[dir]) {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "wfm-wc-picker-item" + (dir ? " wfm-wc-picker-item--sub" : "");
|
||||
btn.textContent = `__${f.wc_name}__`;
|
||||
btn.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (ta) wcInsertAtCursor(ta, `__${f.wc_name}__`);
|
||||
picker.style.display = "none";
|
||||
});
|
||||
picker.appendChild(btn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Initialize
|
||||
// ============================================
|
||||
@@ -853,4 +1080,157 @@ export function initPromptTab() {
|
||||
pmSearchText = e.target.value.trim();
|
||||
renderPresetManager();
|
||||
});
|
||||
|
||||
// ── Center column tab switching ──────────────────────────
|
||||
document.querySelectorAll(".wfm-prompt-center-tab").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
const target = btn.dataset.ptab;
|
||||
document.querySelectorAll(".wfm-prompt-center-tab").forEach(b => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
document.querySelectorAll(".wfm-prompt-center-pane").forEach(p => {
|
||||
p.style.display = p.id === `wfm-ptab-${target}` ? "" : "none";
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ── Wildcard syntax buttons ──────────────────────────────
|
||||
document.querySelectorAll(".wfm-wc-btn[data-wc-open]").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (!ta) return;
|
||||
const open = btn.dataset.wcOpen || "";
|
||||
const close = btn.dataset.wcClose || "";
|
||||
wcInsertAtCursor(ta, open, close);
|
||||
});
|
||||
});
|
||||
|
||||
// LoRA LBW template button
|
||||
document.getElementById("wfm-wc-lora-btn")?.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (!ta) return;
|
||||
wcInsertAtCursor(ta, "<lora::1:LBW=;>");
|
||||
// Move cursor to after "lora:" for the name
|
||||
const pos = ta.selectionStart - "<lora::1:LBW=;>".length + 6;
|
||||
ta.setSelectionRange(pos, pos);
|
||||
ta.focus();
|
||||
});
|
||||
|
||||
// n$${ } button — asks for n then inserts multi-pick template
|
||||
document.getElementById("wfm-wc-nset-btn")?.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (!ta) return;
|
||||
const n = prompt("Number of items to pick (n):", "2");
|
||||
if (n === null) return;
|
||||
const num = parseInt(n, 10);
|
||||
if (isNaN(num) || num < 1) { showToast("Enter a positive integer", "error"); return; }
|
||||
const template = "{" + num + "$$|}";
|
||||
const start = ta.selectionStart;
|
||||
wcInsertAtCursor(ta, template);
|
||||
// Move cursor between $$ and |
|
||||
const inner = start + ("{" + num + "$$").length;
|
||||
ta.setSelectionRange(inner, inner);
|
||||
ta.focus();
|
||||
});
|
||||
|
||||
// File picker toggle
|
||||
const filePickBtn = document.getElementById("wfm-wc-filepick-btn");
|
||||
const filePicker = document.getElementById("wfm-wc-file-picker");
|
||||
filePickBtn?.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
if (!filePicker) return;
|
||||
const isOpen = filePicker.style.display !== "none";
|
||||
filePicker.style.display = isOpen ? "none" : "";
|
||||
if (!isOpen) wcUpdateFilePicker();
|
||||
});
|
||||
document.addEventListener("click", () => {
|
||||
if (filePicker) filePicker.style.display = "none";
|
||||
});
|
||||
|
||||
// ── Wildcard prompt actions ──────────────────────────────
|
||||
document.getElementById("wfm-wc-copy-btn")?.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
const text = ta?.value || "";
|
||||
if (!text.trim()) { showToast(t("noTextToCopy"), "error"); return; }
|
||||
navigator.clipboard.writeText(text).then(() => showToast(t("copiedToClipboard"), "success"));
|
||||
});
|
||||
|
||||
document.getElementById("wfm-wc-to-pos-btn")?.addEventListener("click", () => {
|
||||
const src = document.getElementById("wfm-wc-prompt");
|
||||
const dst = document.getElementById("wfm-preset-pos");
|
||||
if (!src || !dst) return;
|
||||
dst.value = src.value;
|
||||
dst.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
showToast("Sent to Positive Prompt", "success");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-wc-to-neg-btn")?.addEventListener("click", () => {
|
||||
const src = document.getElementById("wfm-wc-prompt");
|
||||
const dst = document.getElementById("wfm-preset-neg");
|
||||
if (!src || !dst) return;
|
||||
dst.value = src.value;
|
||||
dst.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
showToast("Sent to Negative Prompt", "success");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-wc-clear-btn")?.addEventListener("click", () => {
|
||||
const ta = document.getElementById("wfm-wc-prompt");
|
||||
if (ta) { ta.value = ""; ta.focus(); }
|
||||
});
|
||||
|
||||
// ── Wildcard file manager ────────────────────────────────
|
||||
document.getElementById("wfm-wc-new-file-btn")?.addEventListener("click", () => {
|
||||
wcOpenEditor("", "txt", "", null);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-wc-files-refresh-btn")?.addEventListener("click", () => {
|
||||
wcRefreshFiles();
|
||||
});
|
||||
|
||||
// Editor: save
|
||||
document.getElementById("wfm-wc-editor-save-btn")?.addEventListener("click", async () => {
|
||||
const nameInput = document.getElementById("wfm-wc-editor-name");
|
||||
const extSelect = document.getElementById("wfm-wc-editor-ext");
|
||||
const contentTA = document.getElementById("wfm-wc-editor-content");
|
||||
|
||||
// Normalize separators and strip leading/trailing slashes
|
||||
const rawName = (nameInput?.value || "").trim().replace(/\\/g, "/").replace(/\/+/g, "/").replace(/^\/|\/$/g, "");
|
||||
const ext = extSelect?.value || "txt";
|
||||
const content = contentTA?.value || "";
|
||||
|
||||
if (!rawName) { showToast("Enter a filename", "error"); return; }
|
||||
// Validate each path component (allow letters, numbers, -, _, ., space)
|
||||
const nameParts = rawName.split("/");
|
||||
if (nameParts.some(p => !p || !/^[\w\-. ]+$/.test(p))) {
|
||||
showToast("Invalid path. Use folder/name format, each part: letters, numbers, -, _, . only", "error");
|
||||
return;
|
||||
}
|
||||
const name = rawName;
|
||||
const filename = `${name}.${ext}`;
|
||||
const saved = await wcSaveFile(filename, content);
|
||||
if (saved) {
|
||||
showToast(`Saved: ${filename}`, "success");
|
||||
wcCloseEditor();
|
||||
wcRefreshFiles();
|
||||
} else {
|
||||
showToast("Failed to save file", "error");
|
||||
}
|
||||
});
|
||||
|
||||
// Editor: delete
|
||||
document.getElementById("wfm-wc-editor-delete-btn")?.addEventListener("click", async () => {
|
||||
if (!wcEditingFilename) return;
|
||||
if (!confirm(`Delete "${wcEditingFilename}"?`)) return;
|
||||
await wcDeleteFile(wcEditingFilename);
|
||||
showToast(`Deleted: ${wcEditingFilename}`, "success");
|
||||
wcCloseEditor();
|
||||
wcRefreshFiles();
|
||||
});
|
||||
|
||||
// Editor: cancel
|
||||
document.getElementById("wfm-wc-editor-cancel-btn")?.addEventListener("click", () => {
|
||||
wcCloseEditor();
|
||||
});
|
||||
|
||||
// Initial wildcard file load
|
||||
wcRefreshFiles();
|
||||
}
|
||||
|
||||
@@ -8,6 +8,12 @@ import { t, getLang, getSummaryLang, setLang, setSummaryLang, getLanguageOptions
|
||||
|
||||
const SETTINGS_KEY = "wfm_settings";
|
||||
|
||||
function rgbToHex(rgb) {
|
||||
const m = rgb.match(/(\d+)/g);
|
||||
if (!m || m.length < 3) return "#000000";
|
||||
return "#" + m.slice(0, 3).map(n => parseInt(n).toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function loadLocalSettings() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SETTINGS_KEY) || "{}");
|
||||
@@ -67,12 +73,259 @@ const THEMES = [
|
||||
{ id: "corporate", key: "themeCorporate", colors: ["#F0F4F8", "#FFFFFF", "#2563EB", "#7C3AED"] },
|
||||
];
|
||||
|
||||
// --- Background pattern definitions ---
|
||||
const BG_PATTERNS = [
|
||||
{ id: "none", key: "themePatternNone" },
|
||||
{ id: "stripe-h", key: "themePatternStripeH" },
|
||||
{ id: "stripe-v", key: "themePatternStripeV" },
|
||||
{ id: "stripe-d", key: "themePatternStripeD" },
|
||||
{ id: "dot", key: "themePatternDot" },
|
||||
{ id: "check", key: "themePatternCheck" },
|
||||
{ id: "svg", key: "themePatternSvg" },
|
||||
];
|
||||
|
||||
// Font definitions: id, label key, CSS value, Google Fonts family name (if web font)
|
||||
const FONT_OPTIONS = [
|
||||
{ id: "", key: "themeFontDefault", css: "", google: "" },
|
||||
{ id: "noto-sans-jp", key: "themeFontNotoSans", css: "'Noto Sans JP', sans-serif", google: "Noto+Sans+JP:wght@400;700" },
|
||||
{ id: "zen-maru", key: "themeFontZenMaru", css: "'Zen Maru Gothic', sans-serif", google: "Zen+Maru+Gothic:wght@400;700" },
|
||||
{ id: "m-plus-rounded", key: "themeFontMPlusRound", css: "'M PLUS Rounded 1c', sans-serif", google: "M+PLUS+Rounded+1c:wght@400;700" },
|
||||
{ id: "kosugi-maru", key: "themeFontKosugiMaru", css: "'Kosugi Maru', sans-serif", google: "Kosugi+Maru" },
|
||||
{ id: "sawarabi-gothic",key: "themeFontSawarabi", css: "'Sawarabi Gothic', sans-serif", google: "Sawarabi+Gothic" },
|
||||
{ id: "biz-udp", key: "themeFontBizUdp", css: "'BIZ UDPGothic', sans-serif", google: "BIZ+UDPGothic:wght@400;700" },
|
||||
{ id: "dot-gothic", key: "themeFontDotGothic", css: "'DotGothic16', monospace", google: "DotGothic16" },
|
||||
{ id: "hachi-maru", key: "themeFontHachiMaru", css: "'Hachi Maru Pop', cursive", google: "Hachi+Maru+Pop" },
|
||||
{ id: "dela-gothic", key: "themeFontDelaGothic", css: "'Dela Gothic One', sans-serif", google: "Dela+Gothic+One" },
|
||||
{ id: "reggae-one", key: "themeFontReggaeOne", css: "'Reggae One', cursive", google: "Reggae+One" },
|
||||
{ id: "rocknroll", key: "themeFontRocknRoll", css: "'RocknRoll One', sans-serif", google: "RocknRoll+One" },
|
||||
{ id: "stick", key: "themeFontStick", css: "'Stick', sans-serif", google: "Stick" },
|
||||
{ id: "train-one", key: "themeFontTrainOne", css: "'Train One', cursive", google: "Train+One" },
|
||||
{ id: "space-mono", key: "themeFontSpaceMono", css: "'Space Mono', monospace", google: "Space+Mono:wght@400;700" },
|
||||
{ id: "fira-code", key: "themeFontFiraCode", css: "'Fira Code', monospace", google: "Fira+Code:wght@400;700" },
|
||||
];
|
||||
|
||||
// Load Google Font dynamically
|
||||
const _loadedFonts = new Set();
|
||||
function loadGoogleFont(googleFamily) {
|
||||
if (!googleFamily || _loadedFonts.has(googleFamily)) return;
|
||||
_loadedFonts.add(googleFamily);
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
link.href = `https://fonts.googleapis.com/css2?family=${googleFamily}&display=swap`;
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
|
||||
function applyCustomFont(fontId) {
|
||||
const font = FONT_OPTIONS.find(f => f.id === fontId);
|
||||
let styleEl = document.getElementById("wfm-custom-font-style");
|
||||
if (!font || !font.css) {
|
||||
if (styleEl) styleEl.remove();
|
||||
return;
|
||||
}
|
||||
if (font.google) loadGoogleFont(font.google);
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement("style");
|
||||
styleEl.id = "wfm-custom-font-style";
|
||||
document.head.appendChild(styleEl);
|
||||
}
|
||||
styleEl.textContent = `body, .wfm-input, .wfm-select, .wfm-textarea, button { font-family: ${font.css} !important; }`;
|
||||
}
|
||||
|
||||
// Color customization targets
|
||||
const COLOR_TARGETS = [
|
||||
{ varName: "--wfm-bg", key: "themeColorBg" },
|
||||
{ varName: "--wfm-bg-secondary", key: "themeColorBgSec" },
|
||||
{ varName: "--wfm-surface", key: "themeColorSurface" },
|
||||
{ varName: "--wfm-text", key: "themeColorText" },
|
||||
{ varName: "--wfm-primary", key: "themeColorPrimary" },
|
||||
{ varName: "--wfm-accent", key: "themeColorAccent" },
|
||||
];
|
||||
|
||||
function generatePatternCSS(patternId, color, opacity, scale) {
|
||||
const o = opacity ?? 0.1;
|
||||
const s = scale ?? 20;
|
||||
const c = color || "#ffffff";
|
||||
// Convert hex to rgba
|
||||
const r = parseInt(c.slice(1,3),16), g = parseInt(c.slice(3,5),16), b = parseInt(c.slice(5,7),16);
|
||||
const rgba = `rgba(${r},${g},${b},${o})`;
|
||||
|
||||
switch (patternId) {
|
||||
case "stripe-h":
|
||||
return `repeating-linear-gradient(0deg, ${rgba} 0px, ${rgba} 1px, transparent 1px, transparent ${s}px)`;
|
||||
case "stripe-v":
|
||||
return `repeating-linear-gradient(90deg, ${rgba} 0px, ${rgba} 1px, transparent 1px, transparent ${s}px)`;
|
||||
case "stripe-d":
|
||||
return `repeating-linear-gradient(45deg, ${rgba} 0px, ${rgba} 1px, transparent 1px, transparent ${s}px)`;
|
||||
case "dot": {
|
||||
const half = s / 2;
|
||||
const dotR = Math.max(1, s * 0.12);
|
||||
return `radial-gradient(circle ${dotR}px at ${half}px ${half}px, ${rgba} 100%, transparent 100%)`;
|
||||
}
|
||||
case "check": {
|
||||
const half = s / 2;
|
||||
return `linear-gradient(45deg, ${rgba} 25%, transparent 25%, transparent 75%, ${rgba} 75%), ` +
|
||||
`linear-gradient(45deg, ${rgba} 25%, transparent 25%, transparent 75%, ${rgba} 75%)`;
|
||||
}
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function generatePatternBgSize(patternId, scale) {
|
||||
const s = scale ?? 20;
|
||||
if (patternId === "dot") return `${s}px ${s}px`;
|
||||
if (patternId === "check") {
|
||||
const half = s / 2;
|
||||
return `${s}px ${s}px`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function generatePatternBgPosition(patternId, scale) {
|
||||
const s = scale ?? 20;
|
||||
if (patternId === "check") {
|
||||
const half = s / 2;
|
||||
return `0 0, ${half}px ${half}px`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function generatePatternPreviewSVG(patternId) {
|
||||
const fg = "#8cb4ff";
|
||||
const bg = "#1a1a2e";
|
||||
const encode = (svg) => `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
||||
switch (patternId) {
|
||||
case "none":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><line x1="10" y1="10" x2="50" y2="50" stroke="#555" stroke-width="2"/><line x1="50" y1="10" x2="10" y2="50" stroke="#555" stroke-width="2"/></svg>`);
|
||||
case "stripe-h":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><rect y="4" width="60" height="4" fill="${fg}" opacity="0.7"/><rect y="16" width="60" height="4" fill="${fg}" opacity="0.7"/><rect y="28" width="60" height="4" fill="${fg}" opacity="0.7"/><rect y="40" width="60" height="4" fill="${fg}" opacity="0.7"/><rect y="52" width="60" height="4" fill="${fg}" opacity="0.7"/></svg>`);
|
||||
case "stripe-v":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><rect x="4" width="4" height="60" fill="${fg}" opacity="0.7"/><rect x="16" width="4" height="60" fill="${fg}" opacity="0.7"/><rect x="28" width="4" height="60" fill="${fg}" opacity="0.7"/><rect x="40" width="4" height="60" fill="${fg}" opacity="0.7"/><rect x="52" width="4" height="60" fill="${fg}" opacity="0.7"/></svg>`);
|
||||
case "stripe-d":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><line x1="-5" y1="7" x2="53" y2="-5" stroke="${fg}" stroke-width="3" opacity="0.7"/><line x1="7" y1="19" x2="65" y2="7" stroke="${fg}" stroke-width="3" opacity="0.7"/><line x1="-5" y1="31" x2="53" y2="19" stroke="${fg}" stroke-width="3" opacity="0.7"/><line x1="7" y1="43" x2="65" y2="31" stroke="${fg}" stroke-width="3" opacity="0.7"/><line x1="-5" y1="55" x2="53" y2="43" stroke="${fg}" stroke-width="3" opacity="0.7"/><line x1="7" y1="67" x2="65" y2="55" stroke="${fg}" stroke-width="3" opacity="0.7"/></svg>`);
|
||||
case "dot":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><circle cx="10" cy="10" r="4" fill="${fg}" opacity="0.8"/><circle cx="30" cy="10" r="4" fill="${fg}" opacity="0.8"/><circle cx="50" cy="10" r="4" fill="${fg}" opacity="0.8"/><circle cx="20" cy="25" r="4" fill="${fg}" opacity="0.8"/><circle cx="40" cy="25" r="4" fill="${fg}" opacity="0.8"/><circle cx="10" cy="40" r="4" fill="${fg}" opacity="0.8"/><circle cx="30" cy="40" r="4" fill="${fg}" opacity="0.8"/><circle cx="50" cy="40" r="4" fill="${fg}" opacity="0.8"/><circle cx="20" cy="55" r="4" fill="${fg}" opacity="0.8"/><circle cx="40" cy="55" r="4" fill="${fg}" opacity="0.8"/></svg>`);
|
||||
case "check":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><rect x="0" y="0" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="15" y="15" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="30" y="0" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="45" y="15" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="0" y="30" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="15" y="45" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="30" y="30" width="15" height="15" fill="${fg}" opacity="0.35"/><rect x="45" y="45" width="15" height="15" fill="${fg}" opacity="0.35"/></svg>`);
|
||||
case "svg":
|
||||
return encode(`<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="${bg}"/><rect x="10" y="10" width="40" height="40" rx="4" fill="none" stroke="${fg}" stroke-width="2" stroke-dasharray="6 3" opacity="0.6"/><text x="30" y="36" text-anchor="middle" fill="${fg}" font-size="20" font-weight="bold" opacity="0.8">+</text></svg>`);
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Apply custom overrides (colors + pattern) on top of the current theme
|
||||
function applyCustomOverrides(custom) {
|
||||
const root = document.documentElement;
|
||||
// Remove old custom style element
|
||||
let styleEl = document.getElementById("wfm-custom-theme-style");
|
||||
|
||||
// Color overrides
|
||||
if (custom && custom.colors) {
|
||||
for (const [varName, value] of Object.entries(custom.colors)) {
|
||||
if (value) root.style.setProperty(varName, value);
|
||||
}
|
||||
}
|
||||
|
||||
// Pattern
|
||||
if (custom && custom.pattern && custom.pattern.id && custom.pattern.id !== "none") {
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement("style");
|
||||
styleEl.id = "wfm-custom-theme-style";
|
||||
document.head.appendChild(styleEl);
|
||||
}
|
||||
const p = custom.pattern;
|
||||
if (p.id === "svg" && p.svgData) {
|
||||
const s = p.scale ?? 40;
|
||||
const o = p.opacity ?? 1;
|
||||
const c = p.color || null;
|
||||
const gap = p.gap ?? 0;
|
||||
// Recolor SVG: inject a global style override into the SVG
|
||||
let svgStr = p.svgData;
|
||||
if (c) {
|
||||
// 1. Replace fill/stroke attributes (but not "none")
|
||||
svgStr = svgStr
|
||||
.replace(/fill="(?!none)[^"]*"/gi, `fill="${c}"`)
|
||||
.replace(/stroke="(?!none)[^"]*"/gi, `stroke="${c}"`);
|
||||
// 2. Replace inline style fill/stroke
|
||||
svgStr = svgStr
|
||||
.replace(/fill:\s*(?!none)[^;"]+/gi, `fill:${c}`)
|
||||
.replace(/stroke:\s*(?!none)[^;"]+/gi, `stroke:${c}`);
|
||||
// 3. Inject a <style> block for elements with no explicit fill/stroke
|
||||
const styleBlock = `<style>*:not([fill="none"]){fill:${c}!important}*:not([stroke="none"])[stroke]{stroke:${c}!important}</style>`;
|
||||
svgStr = svgStr.replace(/<svg([^>]*)>/i, `<svg$1>${styleBlock}`);
|
||||
}
|
||||
// Extract original viewBox/width/height, then create wrapper SVG with padding
|
||||
const tileSize = s + gap;
|
||||
let tiledSvg;
|
||||
if (gap > 0) {
|
||||
// Extract the original viewBox to preserve it in the inner SVG
|
||||
const vbMatch = svgStr.match(/viewBox="([^"]*)"/i);
|
||||
const origViewBox = vbMatch ? vbMatch[1] : `0 0 ${s} ${s}`;
|
||||
// Wrap: outer SVG with tileSize, inner SVG with original viewBox
|
||||
tiledSvg = svgStr.replace(
|
||||
/<svg([^>]*)>/i,
|
||||
(match, attrs) => {
|
||||
// Remove existing width/height/viewBox from outer
|
||||
let clean = attrs
|
||||
.replace(/\s*width="[^"]*"/gi, '')
|
||||
.replace(/\s*height="[^"]*"/gi, '')
|
||||
.replace(/\s*viewBox="[^"]*"/gi, '');
|
||||
return `<svg${clean} width="${tileSize}" height="${tileSize}" viewBox="0 0 ${tileSize} ${tileSize}">
|
||||
<svg width="${s}" height="${s}" x="0" y="0" viewBox="${origViewBox}">`;
|
||||
}
|
||||
) + '</svg>';
|
||||
} else {
|
||||
tiledSvg = svgStr;
|
||||
}
|
||||
const encoded = `url("data:image/svg+xml,${encodeURIComponent(tiledSvg)}")`;
|
||||
styleEl.textContent = `body::after { content: ""; position: fixed; inset: 0; z-index: -1; background-image: ${encoded}; background-size: ${tileSize}px ${tileSize}px; background-repeat: repeat; opacity: ${o}; pointer-events: none; }`;
|
||||
} else if (p.id !== "svg") {
|
||||
const bg = generatePatternCSS(p.id, p.color, p.opacity, p.scale);
|
||||
const bgSize = generatePatternBgSize(p.id, p.scale);
|
||||
const bgPos = generatePatternBgPosition(p.id, p.scale);
|
||||
let css = `body { background-image: ${bg} !important;`;
|
||||
if (bgSize) css += ` background-size: ${bgSize} !important;`;
|
||||
if (bgPos) css += ` background-position: ${bgPos} !important;`;
|
||||
css += ` }`;
|
||||
styleEl.textContent = css;
|
||||
}
|
||||
} else {
|
||||
if (styleEl) styleEl.remove();
|
||||
}
|
||||
|
||||
// Font
|
||||
if (custom && custom.fontId) {
|
||||
applyCustomFont(custom.fontId);
|
||||
} else {
|
||||
const fontEl = document.getElementById("wfm-custom-font-style");
|
||||
if (fontEl) fontEl.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function clearCustomOverrides() {
|
||||
const root = document.documentElement;
|
||||
for (const ct of COLOR_TARGETS) {
|
||||
root.style.removeProperty(ct.varName);
|
||||
}
|
||||
const styleEl = document.getElementById("wfm-custom-theme-style");
|
||||
if (styleEl) styleEl.remove();
|
||||
const fontEl = document.getElementById("wfm-custom-font-style");
|
||||
if (fontEl) fontEl.remove();
|
||||
}
|
||||
|
||||
export function applyTheme(themeId) {
|
||||
if (themeId) {
|
||||
document.documentElement.setAttribute("data-theme", themeId);
|
||||
} else {
|
||||
document.documentElement.removeAttribute("data-theme");
|
||||
}
|
||||
// Apply saved custom overrides
|
||||
const settings = loadLocalSettings();
|
||||
clearCustomOverrides();
|
||||
if (settings.themeCustom) {
|
||||
applyCustomOverrides(settings.themeCustom);
|
||||
}
|
||||
}
|
||||
|
||||
export function getSavedTheme() {
|
||||
@@ -93,6 +346,12 @@ export async function initSettingsTab() {
|
||||
workflowsDirInfo = await res.json();
|
||||
} catch {}
|
||||
|
||||
// Load gallery output dir info
|
||||
let outputDirInfo = { current: "", default: "", saved: "" };
|
||||
try {
|
||||
const res = await fetch("/api/wfm/settings/output-dir");
|
||||
outputDirInfo = await res.json();
|
||||
} catch {}
|
||||
|
||||
const uiLang = getLang();
|
||||
const summaryLang = getSummaryLang();
|
||||
@@ -100,9 +359,115 @@ export async function initSettingsTab() {
|
||||
container.innerHTML = `
|
||||
<h2 style="font-size:18px;margin-bottom:20px;">${t("settingsTitle")}</h2>
|
||||
|
||||
<div class="wfm-settings-layout">
|
||||
|
||||
<!-- Right column: Theme (floated right) -->
|
||||
<div class="wfm-settings-right-col">
|
||||
<!-- Theme -->
|
||||
<details class="wfm-settings-section" open>
|
||||
<summary class="wfm-settings-summary">${t("themeLabel")}</summary>
|
||||
<div class="wfm-theme-grid" id="wfm-theme-grid">
|
||||
${THEMES.map(th => `
|
||||
<div class="wfm-theme-card ${(settings.theme || "") === th.id ? "active" : ""}" data-theme-id="${th.id}">
|
||||
<div class="wfm-theme-swatch">
|
||||
${th.colors.map(c => `<span style="background:${c};"></span>`).join("")}
|
||||
</div>
|
||||
<div class="wfm-theme-card-label">${t(th.key)}</div>
|
||||
</div>
|
||||
`).join("")}
|
||||
</div>
|
||||
|
||||
<!-- Theme Customizer -->
|
||||
<button class="wfm-customizer-toggle" id="wfm-customizer-toggle">
|
||||
<span class="arrow">▶</span> ${t("themeCustomize")}
|
||||
</button>
|
||||
<div class="wfm-customizer-panel" id="wfm-customizer-panel">
|
||||
<!-- Color overrides -->
|
||||
<div class="wfm-customizer-section">
|
||||
<h4>${t("themeCustomizeColors")}</h4>
|
||||
<div class="wfm-color-grid" id="wfm-color-grid">
|
||||
${COLOR_TARGETS.map(ct => {
|
||||
const saved = settings.themeCustom?.colors?.[ct.varName] || "";
|
||||
return `<div class="wfm-color-item">
|
||||
<label>${t(ct.key)}</label>
|
||||
<input type="color" data-var="${ct.varName}" value="${saved || getComputedStyle(document.documentElement).getPropertyValue(ct.varName).trim()}" title="${ct.varName}">
|
||||
</div>`;
|
||||
}).join("")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Background pattern -->
|
||||
<div class="wfm-customizer-section">
|
||||
<h4>${t("themeCustomizeBgPattern")}</h4>
|
||||
<div class="wfm-pattern-grid" id="wfm-pattern-grid">
|
||||
${BG_PATTERNS.map(p => {
|
||||
const active = (settings.themeCustom?.pattern?.id || "none") === p.id ? "active" : "";
|
||||
const preview = generatePatternPreviewSVG(p.id);
|
||||
const bgStyle = preview
|
||||
? `background:url('${preview}') no-repeat center/cover;`
|
||||
: "background:#333;";
|
||||
return `<div class="wfm-pattern-item ${active} ${p.id === 'svg' ? 'wfm-svg-upload-btn' : ''}" data-pattern-id="${p.id}" style="${bgStyle}">
|
||||
<span class="wfm-pattern-item-label">${t(p.key)}</span>
|
||||
</div>`;
|
||||
}).join("")}
|
||||
</div>
|
||||
<input type="file" id="wfm-svg-upload" accept=".svg" style="display:none;">
|
||||
|
||||
<!-- Pattern options -->
|
||||
<div class="wfm-pattern-options" id="wfm-pattern-options" style="${(!settings.themeCustom?.pattern?.id || settings.themeCustom?.pattern?.id === 'none') ? 'display:none;' : ''}">
|
||||
<label>
|
||||
${t("themePatternColor")}
|
||||
<input type="color" id="wfm-pattern-color" value="${settings.themeCustom?.pattern?.color || '#ffffff'}">
|
||||
</label>
|
||||
<label>
|
||||
${t("themePatternOpacity")}
|
||||
<input type="range" id="wfm-pattern-opacity" min="0.02" max="0.5" step="0.02" value="${settings.themeCustom?.pattern?.opacity ?? 0.1}">
|
||||
<span id="wfm-pattern-opacity-val">${settings.themeCustom?.pattern?.opacity ?? 0.1}</span>
|
||||
</label>
|
||||
<label>
|
||||
${t("themePatternScale")}
|
||||
<input type="range" id="wfm-pattern-scale" min="8" max="80" step="2" value="${settings.themeCustom?.pattern?.scale ?? 20}">
|
||||
<span id="wfm-pattern-scale-val">${settings.themeCustom?.pattern?.scale ?? 20}px</span>
|
||||
</label>
|
||||
<label>
|
||||
${t("themePatternGap")}
|
||||
<input type="range" id="wfm-pattern-gap" min="0" max="60" step="2" value="${settings.themeCustom?.pattern?.gap ?? 0}">
|
||||
<span id="wfm-pattern-gap-val">${settings.themeCustom?.pattern?.gap ?? 0}px</span>
|
||||
</label>
|
||||
</div>
|
||||
<div id="wfm-svg-name" style="font-size:11px;color:var(--wfm-text-secondary);margin-top:6px;${settings.themeCustom?.pattern?.id === 'svg' ? '' : 'display:none;'}">
|
||||
${settings.themeCustom?.pattern?.svgName ? `SVG: ${settings.themeCustom.pattern.svgName}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Font -->
|
||||
<div class="wfm-customizer-section">
|
||||
<h4>${t("themeCustomizeFont")}</h4>
|
||||
<div class="wfm-font-grid" id="wfm-font-grid">
|
||||
${FONT_OPTIONS.map(f => {
|
||||
const active = (settings.themeCustom?.fontId || "") === f.id ? "active" : "";
|
||||
return `<div class="wfm-font-item ${active}" data-font-id="${f.id}" title="${f.css || 'System Default'}">
|
||||
<span class="wfm-font-preview" style="${f.css ? `font-family:${f.css};` : ''}">${t(f.key)}</span>
|
||||
</div>`;
|
||||
}).join("")}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Actions -->
|
||||
<div class="wfm-customizer-actions">
|
||||
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-customizer-apply">${t("themeCustomizerApply")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-customizer-reset">${t("themeCustomizerReset")}</button>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
</div><!-- /wfm-settings-right-col -->
|
||||
|
||||
<!-- Left column: all settings (Language + rest), flows left of floated Theme -->
|
||||
<div class="wfm-settings-left-col">
|
||||
<!-- Language Settings -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("langLabel")} / ${t("summaryLangLabel")}</h3>
|
||||
<details class="wfm-settings-section" open>
|
||||
<summary class="wfm-settings-summary">${t("langLabel")} / ${t("summaryLangLabel")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("langLabel")}</label>
|
||||
<select class="wfm-select" id="wfm-settings-ui-lang">
|
||||
@@ -118,26 +483,11 @@ export async function initSettingsTab() {
|
||||
⚠ ${t("summaryLangNote")}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Theme -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("themeLabel")}</h3>
|
||||
<div class="wfm-theme-grid" id="wfm-theme-grid">
|
||||
${THEMES.map(th => `
|
||||
<div class="wfm-theme-card ${(settings.theme || "") === th.id ? "active" : ""}" data-theme-id="${th.id}">
|
||||
<div class="wfm-theme-swatch">
|
||||
${th.colors.map(c => `<span style="background:${c};"></span>`).join("")}
|
||||
</div>
|
||||
<div class="wfm-theme-card-label">${t(th.key)}</div>
|
||||
</div>
|
||||
`).join("")}
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Workflow Data Folder -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("workflowsDir")}</h3>
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("workflowsDir")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("workflowsDirLabel")}</label>
|
||||
<div style="display:flex;gap:8px;">
|
||||
@@ -154,11 +504,32 @@ export async function initSettingsTab() {
|
||||
${t("workflowsDirCurrent")}: <code id="wfm-settings-workflows-dir-current" style="color:var(--wfm-primary);word-break:break-all;">${workflowsDirInfo.current}</code>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Gallery Output Folder -->
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("galleryOutputDir")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("galleryOutputDirLabel")}</label>
|
||||
<div style="display:flex;gap:8px;">
|
||||
<input type="text" class="wfm-input" id="wfm-settings-output-dir"
|
||||
value="${serverSettings.gallery_output_dir || ""}"
|
||||
placeholder="${outputDirInfo.default}">
|
||||
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-settings-output-dir-apply">${t("workflowsDirApply")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-output-dir-reset">${t("workflowsDirDefault")}</button>
|
||||
</div>
|
||||
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
|
||||
${t("galleryOutputDirHint")}
|
||||
</small>
|
||||
<div style="font-size:11px;color:var(--wfm-text-secondary);margin-top:6px;">
|
||||
${t("workflowsDirCurrent")}: <code id="wfm-settings-output-dir-current" style="color:var(--wfm-primary);word-break:break-all;">${outputDirInfo.current}</code>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- ComfyUI Settings -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("comfyuiConnection")}</h3>
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("comfyuiConnection")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("comfyuiUrl")}</label>
|
||||
<div style="display:flex;gap:8px;">
|
||||
@@ -172,11 +543,11 @@ export async function initSettingsTab() {
|
||||
</small>
|
||||
</div>
|
||||
<div id="wfm-settings-url-status" style="font-size:12px;margin-top:4px;"></div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Ollama Settings -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("ollamaSettings")}</h3>
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("ollamaSettings")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("ollamaUrl")}</label>
|
||||
<input type="text" class="wfm-input" id="wfm-settings-ollama-url"
|
||||
@@ -197,11 +568,11 @@ export async function initSettingsTab() {
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-ollama-test">${t("testConnection")}</button>
|
||||
<span id="wfm-settings-ollama-status" style="font-size:12px;line-height:28px;"></span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Default Workflow -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("defaultWorkflow")}</h3>
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("defaultWorkflow")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<div style="display:flex;align-items:center;gap:8px;">
|
||||
<span style="font-size:13px;" id="wfm-settings-default-wf-name">${settings.defaultWorkflow || t("defaultWorkflowNone")}</span>
|
||||
@@ -211,11 +582,11 @@ export async function initSettingsTab() {
|
||||
${t("defaultWorkflowHint")}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Eagle Integration (optional) -->
|
||||
<div style="border:1px solid var(--wfm-border);border-radius:var(--wfm-radius);padding:16px;margin-bottom:20px;">
|
||||
<h3 style="font-size:15px;margin-bottom:12px;">${t("eagleIntegration")}</h3>
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("eagleIntegration")}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("eagleUrl")}</label>
|
||||
<div style="display:flex;gap:8px;">
|
||||
@@ -233,10 +604,35 @@ export async function initSettingsTab() {
|
||||
${t("eagleAutoSave")}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Data Management -->
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("dataManagement")}</summary>
|
||||
<p style="font-size:12px;color:var(--wfm-text-secondary);margin-bottom:12px;">${t("dataManagementHint")}</p>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-export">${t("exportData")}</button>
|
||||
<label class="wfm-btn wfm-btn-sm" style="cursor:pointer;margin:0;">
|
||||
${t("importData")}
|
||||
<input type="file" id="wfm-settings-import-file" accept=".json" style="display:none;">
|
||||
</label>
|
||||
</div>
|
||||
<div id="wfm-settings-data-status" style="font-size:12px;margin-top:8px;"></div>
|
||||
</details>
|
||||
|
||||
<!-- Wildcard Integration -->
|
||||
<details class="wfm-settings-section" id="wfm-wildcard-integration-section">
|
||||
<summary class="wfm-settings-summary">Wildcard Integration</summary>
|
||||
<div id="wfm-wildcard-link-status" style="font-size:13px;color:var(--wfm-text-secondary);">Loading...</div>
|
||||
</details>
|
||||
|
||||
<!-- Save Button -->
|
||||
<button class="wfm-btn wfm-btn-primary" id="wfm-settings-save" style="min-width:120px;">${t("saveSettings")}</button>
|
||||
|
||||
</div><!-- /wfm-settings-left-col -->
|
||||
|
||||
<div style="clear:both;"></div>
|
||||
</div><!-- /wfm-settings-layout -->
|
||||
`;
|
||||
|
||||
// --- Theme change handler ---
|
||||
@@ -244,11 +640,193 @@ export async function initSettingsTab() {
|
||||
const card = e.target.closest(".wfm-theme-card");
|
||||
if (!card) return;
|
||||
const themeId = card.dataset.themeId;
|
||||
// Clear custom overrides when switching theme base
|
||||
clearCustomOverrides();
|
||||
const cur = loadLocalSettings();
|
||||
delete cur.themeCustom;
|
||||
cur.theme = themeId;
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(cur));
|
||||
applyTheme(themeId);
|
||||
saveLocalSettings({ theme: themeId });
|
||||
// Update active state
|
||||
document.querySelectorAll(".wfm-theme-card").forEach(c => c.classList.remove("active"));
|
||||
card.classList.add("active");
|
||||
// Update color pickers to reflect new theme's computed values
|
||||
requestAnimationFrame(() => {
|
||||
document.querySelectorAll("#wfm-color-grid input[type=color]").forEach(inp => {
|
||||
const v = getComputedStyle(document.documentElement).getPropertyValue(inp.dataset.var).trim();
|
||||
if (v) inp.value = v.startsWith("#") ? v : rgbToHex(v);
|
||||
});
|
||||
});
|
||||
showToast(t("settingsSaved"), "success");
|
||||
});
|
||||
|
||||
// --- Theme Customizer handlers ---
|
||||
// State for live editing
|
||||
let customizerState = {
|
||||
colors: { ...(settings.themeCustom?.colors || {}) },
|
||||
pattern: { ...(settings.themeCustom?.pattern || { id: "none", color: "#ffffff", opacity: 0.1, scale: 20 }) },
|
||||
fontId: settings.themeCustom?.fontId || "",
|
||||
};
|
||||
|
||||
// Toggle panel
|
||||
document.getElementById("wfm-customizer-toggle")?.addEventListener("click", () => {
|
||||
const toggle = document.getElementById("wfm-customizer-toggle");
|
||||
const panel = document.getElementById("wfm-customizer-panel");
|
||||
toggle.classList.toggle("open");
|
||||
panel.classList.toggle("open");
|
||||
});
|
||||
|
||||
// Live color change
|
||||
document.getElementById("wfm-color-grid")?.addEventListener("input", (e) => {
|
||||
if (e.target.type !== "color") return;
|
||||
const varName = e.target.dataset.var;
|
||||
const value = e.target.value;
|
||||
customizerState.colors[varName] = value;
|
||||
document.documentElement.style.setProperty(varName, value);
|
||||
});
|
||||
|
||||
// Pattern selection
|
||||
document.getElementById("wfm-pattern-grid")?.addEventListener("click", (e) => {
|
||||
const item = e.target.closest(".wfm-pattern-item");
|
||||
if (!item) return;
|
||||
const patternId = item.dataset.patternId;
|
||||
|
||||
// SVG file upload
|
||||
if (patternId === "svg") {
|
||||
document.getElementById("wfm-svg-upload")?.click();
|
||||
return;
|
||||
}
|
||||
|
||||
customizerState.pattern.id = patternId;
|
||||
// Update active state
|
||||
document.querySelectorAll(".wfm-pattern-item").forEach(i => i.classList.remove("active"));
|
||||
item.classList.add("active");
|
||||
|
||||
// Show/hide options
|
||||
const optionsEl = document.getElementById("wfm-pattern-options");
|
||||
const svgNameEl = document.getElementById("wfm-svg-name");
|
||||
if (patternId === "none") {
|
||||
optionsEl.style.display = "none";
|
||||
svgNameEl.style.display = "none";
|
||||
} else {
|
||||
optionsEl.style.display = "";
|
||||
svgNameEl.style.display = "none";
|
||||
}
|
||||
|
||||
// Live preview
|
||||
applyCustomOverrides(customizerState);
|
||||
});
|
||||
|
||||
// SVG file upload handler
|
||||
document.getElementById("wfm-svg-upload")?.addEventListener("change", (e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => {
|
||||
const svgData = ev.target.result;
|
||||
customizerState.pattern.id = "svg";
|
||||
customizerState.pattern.svgData = svgData;
|
||||
customizerState.pattern.svgName = file.name;
|
||||
|
||||
// Update active state
|
||||
document.querySelectorAll(".wfm-pattern-item").forEach(i => i.classList.remove("active"));
|
||||
document.querySelector('.wfm-pattern-item[data-pattern-id="svg"]')?.classList.add("active");
|
||||
|
||||
// Show options + name
|
||||
document.getElementById("wfm-pattern-options").style.display = "";
|
||||
const svgNameEl = document.getElementById("wfm-svg-name");
|
||||
svgNameEl.textContent = `SVG: ${file.name}`;
|
||||
svgNameEl.style.display = "";
|
||||
|
||||
applyCustomOverrides(customizerState);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
e.target.value = "";
|
||||
});
|
||||
|
||||
// Pattern option changes (live)
|
||||
document.getElementById("wfm-pattern-color")?.addEventListener("input", (e) => {
|
||||
customizerState.pattern.color = e.target.value;
|
||||
applyCustomOverrides(customizerState);
|
||||
});
|
||||
document.getElementById("wfm-pattern-opacity")?.addEventListener("input", (e) => {
|
||||
const v = parseFloat(e.target.value);
|
||||
customizerState.pattern.opacity = v;
|
||||
document.getElementById("wfm-pattern-opacity-val").textContent = v;
|
||||
applyCustomOverrides(customizerState);
|
||||
});
|
||||
document.getElementById("wfm-pattern-scale")?.addEventListener("input", (e) => {
|
||||
const v = parseInt(e.target.value);
|
||||
customizerState.pattern.scale = v;
|
||||
document.getElementById("wfm-pattern-scale-val").textContent = v + "px";
|
||||
applyCustomOverrides(customizerState);
|
||||
});
|
||||
document.getElementById("wfm-pattern-gap")?.addEventListener("input", (e) => {
|
||||
const v = parseInt(e.target.value);
|
||||
customizerState.pattern.gap = v;
|
||||
document.getElementById("wfm-pattern-gap-val").textContent = v + "px";
|
||||
applyCustomOverrides(customizerState);
|
||||
});
|
||||
|
||||
// Font selection
|
||||
document.getElementById("wfm-font-grid")?.addEventListener("click", (e) => {
|
||||
const item = e.target.closest(".wfm-font-item");
|
||||
if (!item) return;
|
||||
const fontId = item.dataset.fontId;
|
||||
customizerState.fontId = fontId;
|
||||
// Load web font for preview
|
||||
const font = FONT_OPTIONS.find(f => f.id === fontId);
|
||||
if (font?.google) loadGoogleFont(font.google);
|
||||
applyCustomFont(fontId);
|
||||
// Update active state
|
||||
document.querySelectorAll(".wfm-font-item").forEach(i => i.classList.remove("active"));
|
||||
item.classList.add("active");
|
||||
});
|
||||
|
||||
// Apply & Save
|
||||
document.getElementById("wfm-customizer-apply")?.addEventListener("click", () => {
|
||||
// Clean empty color overrides
|
||||
const cleanColors = {};
|
||||
for (const [k, v] of Object.entries(customizerState.colors)) {
|
||||
if (v) cleanColors[k] = v;
|
||||
}
|
||||
const custom = {
|
||||
colors: Object.keys(cleanColors).length ? cleanColors : undefined,
|
||||
pattern: customizerState.pattern.id !== "none" ? { ...customizerState.pattern } : undefined,
|
||||
fontId: customizerState.fontId || undefined,
|
||||
};
|
||||
saveLocalSettings({ themeCustom: (custom.colors || custom.pattern || custom.fontId) ? custom : undefined });
|
||||
showToast(t("settingsSaved"), "success");
|
||||
});
|
||||
|
||||
// Reset
|
||||
document.getElementById("wfm-customizer-reset")?.addEventListener("click", () => {
|
||||
clearCustomOverrides();
|
||||
customizerState = {
|
||||
colors: {},
|
||||
pattern: { id: "none", color: "#ffffff", opacity: 0.1, scale: 20, gap: 0 },
|
||||
fontId: "",
|
||||
};
|
||||
// Remove themeCustom from localStorage directly (spread merge won't delete keys)
|
||||
const cur = loadLocalSettings();
|
||||
delete cur.themeCustom;
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(cur));
|
||||
applyTheme(cur.theme || "");
|
||||
|
||||
// Reset UI
|
||||
requestAnimationFrame(() => {
|
||||
document.querySelectorAll("#wfm-color-grid input[type=color]").forEach(inp => {
|
||||
const v = getComputedStyle(document.documentElement).getPropertyValue(inp.dataset.var).trim();
|
||||
if (v) inp.value = v.startsWith("#") ? v : rgbToHex(v);
|
||||
});
|
||||
});
|
||||
document.querySelectorAll(".wfm-pattern-item").forEach(i => i.classList.remove("active"));
|
||||
document.querySelector('.wfm-pattern-item[data-pattern-id="none"]')?.classList.add("active");
|
||||
document.getElementById("wfm-pattern-options").style.display = "none";
|
||||
document.getElementById("wfm-svg-name").style.display = "none";
|
||||
// Reset font UI
|
||||
document.querySelectorAll(".wfm-font-item").forEach(i => i.classList.remove("active"));
|
||||
document.querySelector('.wfm-font-item[data-font-id=""]')?.classList.add("active");
|
||||
showToast(t("settingsSaved"), "success");
|
||||
});
|
||||
|
||||
@@ -310,6 +888,50 @@ export async function initSettingsTab() {
|
||||
}
|
||||
});
|
||||
|
||||
// --- Gallery output dir handlers ---
|
||||
document.getElementById("wfm-settings-output-dir-apply")?.addEventListener("click", async () => {
|
||||
const dirInput = document.getElementById("wfm-settings-output-dir");
|
||||
const currentEl = document.getElementById("wfm-settings-output-dir-current");
|
||||
const newDir = dirInput.value.trim();
|
||||
try {
|
||||
const res = await fetch("/api/wfm/settings/output-dir", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ gallery_output_dir: newDir }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
showToast(`${t("workflowsDirError")}: ${data.error}`, "error");
|
||||
} else {
|
||||
if (currentEl) currentEl.textContent = data.current;
|
||||
showToast(t("workflowsDirChanged"), "success");
|
||||
// gallery-tab に通知して再ロード
|
||||
window.dispatchEvent(new CustomEvent("wfm-output-dir-changed", { detail: { path: data.current } }));
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(`${t("workflowsDirError")}: ${err.message}`, "error");
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("wfm-settings-output-dir-reset")?.addEventListener("click", async () => {
|
||||
const dirInput = document.getElementById("wfm-settings-output-dir");
|
||||
const currentEl = document.getElementById("wfm-settings-output-dir-current");
|
||||
dirInput.value = "";
|
||||
try {
|
||||
const res = await fetch("/api/wfm/settings/output-dir", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ gallery_output_dir: "" }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (currentEl) currentEl.textContent = data.current;
|
||||
showToast(t("workflowsDirChanged"), "success");
|
||||
window.dispatchEvent(new CustomEvent("wfm-output-dir-changed", { detail: { path: data.current } }));
|
||||
} catch (err) {
|
||||
showToast(`${t("workflowsDirError")}: ${err.message}`, "error");
|
||||
}
|
||||
});
|
||||
|
||||
// --- Ollama model list loader ---
|
||||
async function loadOllamaModels() {
|
||||
const select = document.getElementById("wfm-settings-ollama-model");
|
||||
@@ -434,4 +1056,134 @@ export async function initSettingsTab() {
|
||||
if (savedUrl) {
|
||||
comfyUI.updateUrl(savedUrl);
|
||||
}
|
||||
|
||||
// --- Wildcard Integration ---
|
||||
async function wcLoadLinkStatus() {
|
||||
const el = document.getElementById("wfm-wildcard-link-status");
|
||||
if (!el) return;
|
||||
try {
|
||||
const res = await fetch("/api/wfm/wildcards/link-status");
|
||||
const data = await res.json();
|
||||
wcRenderLinkStatus(el, data);
|
||||
} catch (e) {
|
||||
el.innerHTML = `<span style="color:var(--wfm-error,#f44336)">Error: ${e.message}</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
function wcRenderLinkStatus(el, data) {
|
||||
if (!data.impact_pack_installed) {
|
||||
el.innerHTML = `
|
||||
<p style="margin:0 0 8px;">ComfyUI-Impact-Pack がインストールされていません。</p>
|
||||
<p style="margin:0;font-size:12px;color:var(--wfm-text-secondary);">
|
||||
ワイルドカードを Impact Pack と共有するには、先に
|
||||
<a href="https://github.com/ltdrdata/ComfyUI-Impact-Pack" target="_blank" rel="noopener"
|
||||
style="color:var(--wfm-accent);">ComfyUI-Impact-Pack</a>
|
||||
をインストールしてください。
|
||||
</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.is_linked) {
|
||||
el.innerHTML = `
|
||||
<p style="margin:0 0 4px;color:var(--wfm-success,#4caf50);">✓ リンク済み</p>
|
||||
<p style="margin:0 0 8px;font-size:12px;color:var(--wfm-text-secondary);">
|
||||
WFS wildcard → ${data.link_target || data.impact_pack_wildcards_dir}
|
||||
</p>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-wc-remove-link">リンクを解除</button>
|
||||
<div id="wfm-wc-link-msg" style="font-size:12px;margin-top:8px;"></div>`;
|
||||
document.getElementById("wfm-wc-remove-link")?.addEventListener("click", async () => {
|
||||
const msg = document.getElementById("wfm-wc-link-msg");
|
||||
try {
|
||||
const r = await fetch("/api/wfm/wildcards/remove-link", { method: "POST" });
|
||||
const d = await r.json();
|
||||
if (!r.ok) throw new Error(d.error || r.statusText);
|
||||
msg.textContent = "リンクを解除しました。";
|
||||
msg.style.color = "var(--wfm-success,#4caf50)";
|
||||
setTimeout(wcLoadLinkStatus, 800);
|
||||
} catch (e) {
|
||||
msg.textContent = "エラー: " + e.message;
|
||||
msg.style.color = "var(--wfm-error,#f44336)";
|
||||
}
|
||||
});
|
||||
} else {
|
||||
el.innerHTML = `
|
||||
<p style="margin:0 0 4px;">Impact Pack wildcards ディレクトリ:</p>
|
||||
<p style="margin:0 0 8px;font-size:12px;color:var(--wfm-text-secondary);">${data.impact_pack_wildcards_dir}</p>
|
||||
<p style="margin:0 0 8px;font-size:12px;color:var(--wfm-text-secondary);">
|
||||
WFS の wildcard ディレクトリを Impact Pack の wildcards ディレクトリへのリンクに置き換えます。
|
||||
既存の WFS ワイルドカードファイルは Impact Pack ディレクトリへ移行されます。
|
||||
</p>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-wc-create-link">リンクを作成</button>
|
||||
<div id="wfm-wc-link-msg" style="font-size:12px;margin-top:8px;"></div>`;
|
||||
document.getElementById("wfm-wc-create-link")?.addEventListener("click", async () => {
|
||||
const msg = document.getElementById("wfm-wc-link-msg");
|
||||
try {
|
||||
const r = await fetch("/api/wfm/wildcards/create-link", { method: "POST" });
|
||||
const d = await r.json();
|
||||
if (!r.ok) throw new Error(d.error || r.statusText);
|
||||
const migrated = d.migrated_files?.length
|
||||
? ` (移行: ${d.migrated_files.join(", ")})`
|
||||
: "";
|
||||
msg.textContent = "リンクを作成しました。" + migrated;
|
||||
msg.style.color = "var(--wfm-success,#4caf50)";
|
||||
setTimeout(wcLoadLinkStatus, 800);
|
||||
} catch (e) {
|
||||
msg.textContent = "エラー: " + e.message;
|
||||
msg.style.color = "var(--wfm-error,#f44336)";
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Load wildcard link status when section is opened
|
||||
document.getElementById("wfm-wildcard-integration-section")?.addEventListener("toggle", (e) => {
|
||||
if (e.target.open) wcLoadLinkStatus();
|
||||
});
|
||||
|
||||
// --- Data Export ---
|
||||
document.getElementById("wfm-settings-export")?.addEventListener("click", async () => {
|
||||
const statusEl = document.getElementById("wfm-settings-data-status");
|
||||
try {
|
||||
const res = await fetch("/api/wfm/settings/export");
|
||||
if (!res.ok) throw new Error(await res.text());
|
||||
const blob = await res.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "wfm-data-export.json";
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
statusEl.textContent = t("exportSuccess");
|
||||
statusEl.style.color = "var(--wfm-success, #4caf50)";
|
||||
} catch (e) {
|
||||
statusEl.textContent = t("exportError") + ": " + e.message;
|
||||
statusEl.style.color = "var(--wfm-error, #f44336)";
|
||||
}
|
||||
});
|
||||
|
||||
// --- Data Import ---
|
||||
document.getElementById("wfm-settings-import-file")?.addEventListener("change", async (e) => {
|
||||
const statusEl = document.getElementById("wfm-settings-data-status");
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
const text = await file.text();
|
||||
const bundle = JSON.parse(text);
|
||||
const res = await fetch("/api/wfm/settings/import", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(bundle),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (!res.ok) throw new Error(result.error || res.statusText);
|
||||
const imported = result.imported?.join(", ") || "-";
|
||||
statusEl.textContent = t("importSuccess") + ": " + imported;
|
||||
statusEl.style.color = "var(--wfm-success, #4caf50)";
|
||||
} catch (e) {
|
||||
statusEl.textContent = t("importError") + ": " + e.message;
|
||||
statusEl.style.color = "var(--wfm-error, #f44336)";
|
||||
}
|
||||
// Reset file input so same file can be re-selected
|
||||
e.target.value = "";
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { comfyWorkflow } from "./comfyui-workflow.js";
|
||||
import { loadWorkflowIntoEditor } from "./generate-tab.js";
|
||||
import { t, getSummaryPrompt } from "./i18n.js";
|
||||
import { highlightJSON } from "./json-highlight.js";
|
||||
import { openBadgeEditModal } from "./models-tab.js";
|
||||
|
||||
// ============================================
|
||||
// State
|
||||
@@ -16,26 +17,31 @@ import { highlightJSON } from "./json-highlight.js";
|
||||
|
||||
const state = {
|
||||
workflows: [],
|
||||
activeModel: "ALL",
|
||||
activeBadge: "ALL",
|
||||
searchText: "",
|
||||
viewMode: localStorage.getItem("wfm_default_view") || "thumb", // thumb | card | table
|
||||
selectedWf: null,
|
||||
groupFilter: "", // empty = all groups
|
||||
badgeColors: (() => {
|
||||
try { return JSON.parse(localStorage.getItem("wfm_badge_colors") || "{}"); }
|
||||
catch { return {}; }
|
||||
})(),
|
||||
currentPage: 0,
|
||||
};
|
||||
|
||||
const BADGE_DEFAULT_COLORS = {
|
||||
"SD1.5": "#e67e22",
|
||||
SDXL: "#2ecc71",
|
||||
Flux: "#9b59b6",
|
||||
Flux2: "#8e44ad",
|
||||
SD3: "#3498db",
|
||||
Qwen: "#e74c3c",
|
||||
"Z-IMAGE": "#1abc9c",
|
||||
};
|
||||
|
||||
function getBadgePalette() {
|
||||
try { return JSON.parse(localStorage.getItem("wfm_models_badge_palette") || "{}"); }
|
||||
catch { return {}; }
|
||||
}
|
||||
|
||||
function saveBadgePalette(palette) {
|
||||
localStorage.setItem("wfm_models_badge_palette", JSON.stringify(palette));
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Open in ComfyUI
|
||||
@@ -214,15 +220,22 @@ async function getRawWorkflow(filename) {
|
||||
// Rendering Helpers
|
||||
// ============================================
|
||||
|
||||
function badgeHtml(type) {
|
||||
const color = state.badgeColors[type] || BADGE_DEFAULT_COLORS[type] || "#0077ff";
|
||||
return `<span class="wfm-badge wfm-badge-model" style="background:${color}">${type}</span>`;
|
||||
function badgeHtml(label) {
|
||||
const palette = getBadgePalette();
|
||||
const color = palette[label] || "";
|
||||
const style = color ? ` style="background:${color};color:#fff;"` : "";
|
||||
return `<span class="wfm-badge wfm-badge-model"${style}>${escapeHtml(label)}</span>`;
|
||||
}
|
||||
|
||||
function getAllModelTypes() {
|
||||
function wfBadgesHtml(wf) {
|
||||
const badges = wf.metadata?.badges || [];
|
||||
return badges.map(label => badgeHtml(label)).join("");
|
||||
}
|
||||
|
||||
function getAllBadges() {
|
||||
const set = new Set();
|
||||
state.workflows.forEach((wf) =>
|
||||
(wf.analysis.modelTypes || []).forEach((t) => set.add(t))
|
||||
(wf.metadata?.badges || []).forEach((b) => set.add(b))
|
||||
);
|
||||
return [...set].sort();
|
||||
}
|
||||
@@ -231,17 +244,23 @@ function renderModelFilters() {
|
||||
const container = document.getElementById("wfm-model-filters");
|
||||
if (!container) return;
|
||||
|
||||
const types = getAllModelTypes();
|
||||
const palette = getBadgePalette();
|
||||
const badges = Object.keys(palette).sort();
|
||||
|
||||
container.innerHTML = `
|
||||
<button class="wfm-filter-btn ${state.activeModel === "ALL" ? "active" : ""}" data-filter="ALL">ALL</button>
|
||||
<button class="wfm-filter-btn ${state.activeModel === "FAVORITE" ? "active" : ""}" data-filter="FAVORITE">★</button>
|
||||
${types.map((t) => `<button class="wfm-filter-btn ${state.activeModel === t ? "active" : ""}" data-filter="${t}">${t}</button>`).join("")}
|
||||
<button class="wfm-filter-btn ${state.activeBadge === "ALL" ? "active" : ""}" data-filter="ALL">ALL</button>
|
||||
<button class="wfm-filter-btn ${state.activeBadge === "FAVORITE" ? "active" : ""}" data-filter="FAVORITE">★</button>
|
||||
${badges.map((b) => {
|
||||
const color = palette[b] || "";
|
||||
const style = color ? ` style="background:${color};color:#fff;"` : "";
|
||||
return `<button class="wfm-filter-btn ${state.activeBadge === b ? "active" : ""}" data-filter="${escapeHtml(b)}"${style}>${escapeHtml(b)}</button>`;
|
||||
}).join("")}
|
||||
`;
|
||||
|
||||
container.querySelectorAll(".wfm-filter-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
state.activeModel = btn.dataset.filter;
|
||||
state.activeBadge = btn.dataset.filter;
|
||||
state.currentPage = 0;
|
||||
renderModelFilters();
|
||||
renderGrid();
|
||||
});
|
||||
@@ -250,10 +269,12 @@ function renderModelFilters() {
|
||||
|
||||
function filterWorkflows() {
|
||||
return state.workflows.filter((wf) => {
|
||||
if (state.activeModel === "FAVORITE") {
|
||||
if (wf.filename === ".index.json") return false;
|
||||
|
||||
if (state.activeBadge === "FAVORITE") {
|
||||
if (!wf.metadata.favorite) return false;
|
||||
} else if (state.activeModel !== "ALL") {
|
||||
if (!(wf.analysis.modelTypes || []).includes(state.activeModel))
|
||||
} else if (state.activeBadge !== "ALL") {
|
||||
if (!(wf.metadata?.badges || []).includes(state.activeBadge))
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -305,14 +326,13 @@ function renderGrid() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Thumbnail / Card view
|
||||
grid.innerHTML = "";
|
||||
filtered.forEach((wf) => {
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-card";
|
||||
card.dataset.filename = wf.filename;
|
||||
const hasThumb = !!wf.thumbnail;
|
||||
const badges = (wf.analysis.modelTypes || []).map((t) => badgeHtml(t)).join("");
|
||||
const badges = wfBadgesHtml(wf);
|
||||
const tags = (wf.metadata.tags || []).map((t) => `<span class="wfm-tag">#${t}</span>`).join("");
|
||||
const favStar = wf.metadata.favorite ? "\u2605" : "\u2606";
|
||||
const favClass = wf.metadata.favorite ? "wfm-fav-btn active" : "wfm-fav-btn";
|
||||
@@ -357,6 +377,7 @@ function renderGrid() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function renderTableView(grid, filtered) {
|
||||
const table = document.createElement("table");
|
||||
table.className = "wfm-table";
|
||||
@@ -376,7 +397,7 @@ function renderTableView(grid, filtered) {
|
||||
const tr = document.createElement("tr");
|
||||
tr.className = "wfm-table-row";
|
||||
tr.dataset.filename = wf.filename;
|
||||
const badges = (wf.analysis.modelTypes || []).map((t) => badgeHtml(t)).join("");
|
||||
const badges = wfBadgesHtml(wf);
|
||||
const tags = (wf.metadata.tags || []).map((t) => `<span class="wfm-tag">#${t}</span>`).join("");
|
||||
const thumbHtml = wf.thumbnail
|
||||
? `<img src="${wf.thumbnail}" class="wfm-table-thumb" loading="lazy" />`
|
||||
@@ -442,7 +463,6 @@ async function showSidePanel(wf, cardEl) {
|
||||
|
||||
titleEl.textContent = wf.filename.replace(/\.json$/, "");
|
||||
contentEl.textContent = t("loading");
|
||||
panel.style.display = "flex";
|
||||
|
||||
state.selectedWf = wf;
|
||||
|
||||
@@ -462,7 +482,7 @@ async function showSidePanel(wf, cardEl) {
|
||||
sidePanelThumbUpdate(wf);
|
||||
|
||||
// Update group tab
|
||||
sidePanelGroupUpdate();
|
||||
renderSideGroup(wf);
|
||||
|
||||
const badgeEl = document.getElementById("wfm-json-format-badge");
|
||||
try {
|
||||
@@ -486,17 +506,17 @@ async function showSidePanel(wf, cardEl) {
|
||||
}
|
||||
|
||||
function closeSidePanel() {
|
||||
const panel = document.getElementById("wfm-side-panel");
|
||||
if (panel) panel.style.display = "none";
|
||||
document.querySelectorAll(".wfm-card, .wfm-table-row").forEach((c) =>
|
||||
c.classList.remove("wfm-card-selected")
|
||||
);
|
||||
state.selectedWf = null;
|
||||
const titleEl = document.getElementById("wfm-side-panel-title");
|
||||
if (titleEl) titleEl.textContent = "";
|
||||
const listLoadBtn = document.getElementById("wfm-list-load-btn");
|
||||
if (listLoadBtn) { listLoadBtn.disabled = true; listLoadBtn.title = t("selectCardFirst"); }
|
||||
const listOpenComfyBtn = document.getElementById("wfm-list-open-comfyui-btn");
|
||||
if (listOpenComfyBtn) { listOpenComfyBtn.disabled = true; listOpenComfyBtn.title = t("selectCardFirst"); }
|
||||
sidePanelGroupUpdate();
|
||||
renderSideGroup(null);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -519,7 +539,7 @@ function sidePanelThumbUpdate(wf) {
|
||||
nameEl.textContent = wf ? wf.filename.replace(/\.json$/, "") : "";
|
||||
}
|
||||
if (metaEl && wf) {
|
||||
const badges = (wf.analysis.modelTypes || []).map((mt) => badgeHtml(mt)).join(" ");
|
||||
const badges = wfBadgesHtml(wf);
|
||||
const io = `P:${wf.analysis.inputs?.prompts || 0} I:${wf.analysis.inputs?.images || 0} → ${wf.analysis.outputs?.images || 0}`;
|
||||
metaEl.innerHTML = `${badges} <span style="margin-left:4px;">${io}</span>`;
|
||||
} else if (metaEl) {
|
||||
@@ -531,60 +551,166 @@ function sidePanelThumbUpdate(wf) {
|
||||
// Group Tab in Side Panel
|
||||
// ============================================
|
||||
|
||||
function sidePanelGroupUpdate() {
|
||||
const nameEl = document.getElementById("wfm-grp-prop-name");
|
||||
const groupEl = document.getElementById("wfm-grp-prop-group");
|
||||
const assignBtn = document.getElementById("wfm-assign-group-btn");
|
||||
const removeBtn = document.getElementById("wfm-remove-group-btn");
|
||||
function renderSideGroup(wf) {
|
||||
const el = document.getElementById("wfm-side-tab-group");
|
||||
if (!el) return;
|
||||
|
||||
if (!state.selectedWf) {
|
||||
if (nameEl) nameEl.textContent = t("noSelection");
|
||||
if (groupEl) groupEl.textContent = "";
|
||||
if (assignBtn) assignBtn.disabled = true;
|
||||
if (removeBtn) removeBtn.disabled = true;
|
||||
const allGroups = groups.groupNames();
|
||||
|
||||
if (!wf) {
|
||||
el.innerHTML = `<p style="padding:12px;color:var(--wfm-text-secondary);font-size:12px;">${t("noSelection")}</p>`;
|
||||
_refreshGroupFilter();
|
||||
return;
|
||||
}
|
||||
|
||||
const filename = state.selectedWf.filename;
|
||||
if (nameEl) nameEl.textContent = filename.replace(/\.json$/, "");
|
||||
const grps = groups.groupsOf(filename);
|
||||
if (groupEl) groupEl.textContent = grps.length > 0 ? `${t("groupsLabel")}: ${grps.join(", ")}` : `${t("groupsLabel")}: ${t("groupsNone")}`;
|
||||
if (assignBtn) assignBtn.disabled = false;
|
||||
const filename = wf.filename;
|
||||
const memberOf = groups.groupsOf(filename);
|
||||
const available = allGroups.filter(g => !memberOf.includes(g));
|
||||
|
||||
const selGroup = document.getElementById("wfm-group-select")?.value;
|
||||
if (removeBtn) removeBtn.disabled = !selGroup || !grps.includes(selGroup);
|
||||
}
|
||||
el.innerHTML = `
|
||||
<div style="padding:8px;">
|
||||
<div style="margin-bottom:12px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsCurrentGroups")}</div>
|
||||
${memberOf.length === 0
|
||||
? `<p style="color:var(--wfm-text-secondary);font-size:12px;">${t("modelsNoGroup")}</p>`
|
||||
: memberOf.map(g =>
|
||||
`<div style="display:flex;align-items:center;justify-content:space-between;padding:3px 0;">
|
||||
<span style="font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${escapeHtml(g)}</span>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger wfm-wf-grp-remove" data-group="${escapeHtml(g)}" title="${t("modelsRemoveFromGroup")}">×</button>
|
||||
</div>`
|
||||
).join("")}
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsAssignGroup")}</div>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<select id="wfm-grp-assign-sel" class="wfm-select" style="flex:1;font-size:12px;padding:3px 6px;">
|
||||
${available.length === 0
|
||||
? `<option value="">${t("modelsNoGroupAvailable")}</option>`
|
||||
: available.map(g => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("")}
|
||||
</select>
|
||||
<button id="wfm-grp-assign-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary"
|
||||
${available.length === 0 ? "disabled" : ""}>${t("modelsAdd")}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-bottom:12px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsCreateGroup")}</div>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<input type="text" id="wfm-grp-new-input" class="wfm-input"
|
||||
style="flex:1;font-size:12px;padding:3px 6px;" placeholder="${t("modelsGroupName")}">
|
||||
<button id="wfm-grp-create-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">${t("modelsCreate")}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div style="border-top:1px solid var(--wfm-border);padding-top:10px;margin-top:4px;">
|
||||
<div style="font-weight:600;font-size:13px;margin-bottom:6px;">${t("modelsManageGroups")}</div>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<select id="wfm-grp-manage-sel" class="wfm-select" style="flex:1;font-size:12px;padding:3px 6px;">
|
||||
${allGroups.length === 0
|
||||
? `<option value="">${t("modelsNoGroupAvailable")}</option>`
|
||||
: allGroups.map(g => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("")}
|
||||
</select>
|
||||
<button id="wfm-grp-rename-btn" class="wfm-btn wfm-btn-sm"
|
||||
${allGroups.length === 0 ? "disabled" : ""} title="${t("modelsRename")}">✎</button>
|
||||
<button id="wfm-grp-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger"
|
||||
${allGroups.length === 0 ? "disabled" : ""} title="${t("modelsDelete")}">×</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
function refreshGroupSelects() {
|
||||
const sideSel = document.getElementById("wfm-group-select");
|
||||
const filterSel = document.getElementById("wfm-group-filter");
|
||||
const grpNames = groups.groupNames();
|
||||
|
||||
[filterSel, sideSel].forEach((sel, i) => {
|
||||
if (!sel) return;
|
||||
const prevVal = sel.value;
|
||||
sel.innerHTML = i === 0
|
||||
? `<option value="">${t("allGroups")}</option>`
|
||||
: `<option value="">${t("selectGroup")}</option>`;
|
||||
grpNames.forEach((g) => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = g;
|
||||
opt.textContent = g;
|
||||
sel.appendChild(opt);
|
||||
// グループから除外
|
||||
el.querySelectorAll(".wfm-wf-grp-remove").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
groups.remove(filename, btn.dataset.group);
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Removed from "${btn.dataset.group}"`, "success");
|
||||
});
|
||||
if (grpNames.includes(prevVal)) sel.value = prevVal;
|
||||
});
|
||||
|
||||
// グループに追加
|
||||
el.querySelector("#wfm-grp-assign-btn")?.addEventListener("click", () => {
|
||||
const g = el.querySelector("#wfm-grp-assign-sel")?.value;
|
||||
if (!g) return;
|
||||
groups.assign(filename, g);
|
||||
renderSideGroup(wf);
|
||||
showToast(`Added to "${g}"`, "success");
|
||||
});
|
||||
|
||||
// グループ作成(作成後に現在のWFに追加)
|
||||
el.querySelector("#wfm-grp-create-btn")?.addEventListener("click", () => {
|
||||
const input = el.querySelector("#wfm-grp-new-input");
|
||||
const name = input?.value.trim();
|
||||
if (!name) return;
|
||||
if (!groups.createGroup(name)) {
|
||||
showToast(`"${name}" already exists`, "warning");
|
||||
return;
|
||||
}
|
||||
groups.assign(filename, name);
|
||||
input.value = "";
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Group "${name}" created`, "success");
|
||||
});
|
||||
|
||||
// グループ名変更
|
||||
el.querySelector("#wfm-grp-rename-btn")?.addEventListener("click", () => {
|
||||
const oldName = el.querySelector("#wfm-grp-manage-sel")?.value;
|
||||
if (!oldName) return;
|
||||
const newName = prompt(`Rename group "${oldName}" to:`, oldName);
|
||||
if (!newName || newName === oldName) return;
|
||||
if (!groups.renameGroup(oldName, newName)) {
|
||||
showToast("Rename failed", "error");
|
||||
return;
|
||||
}
|
||||
if (state.groupFilter === oldName) state.groupFilter = newName;
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Renamed to "${newName}"`, "success");
|
||||
});
|
||||
|
||||
// グループ削除
|
||||
el.querySelector("#wfm-grp-delete-btn")?.addEventListener("click", () => {
|
||||
const name = el.querySelector("#wfm-grp-manage-sel")?.value;
|
||||
if (!name) return;
|
||||
if (!confirm(`Delete group "${name}"?`)) return;
|
||||
groups.deleteGroup(name);
|
||||
if (state.groupFilter === name) {
|
||||
state.groupFilter = "";
|
||||
const filterSel = document.getElementById("wfm-group-filter");
|
||||
if (filterSel) filterSel.value = "";
|
||||
}
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Group "${name}" deleted`, "success");
|
||||
});
|
||||
|
||||
_refreshGroupFilter();
|
||||
}
|
||||
|
||||
/** ツールバーのグループフィルタセレクトのみ更新 */
|
||||
function _refreshGroupFilter() {
|
||||
const filterSel = document.getElementById("wfm-group-filter");
|
||||
if (!filterSel) return;
|
||||
const prevVal = filterSel.value;
|
||||
const grpNames = groups.groupNames();
|
||||
filterSel.innerHTML = `<option value="">${t("allGroups")}</option>`;
|
||||
grpNames.forEach(g => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = g;
|
||||
opt.textContent = g;
|
||||
filterSel.appendChild(opt);
|
||||
});
|
||||
if (grpNames.includes(prevVal)) filterSel.value = prevVal;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Badge Color Settings
|
||||
// View Settings Panel
|
||||
// ============================================
|
||||
|
||||
function renderBadgeSettings() {
|
||||
function renderViewSettings() {
|
||||
const panel = document.getElementById("wfm-badge-settings-panel");
|
||||
if (!panel) return;
|
||||
|
||||
// === Default View section ===
|
||||
const currentView = localStorage.getItem("wfm_default_view") || "thumb";
|
||||
const viewOptions = [
|
||||
{ value: "thumb", label: t("viewThumbnail") },
|
||||
@@ -598,57 +724,20 @@ function renderBadgeSettings() {
|
||||
</label>`
|
||||
).join("");
|
||||
|
||||
// === Badge Colors section ===
|
||||
const types = getAllModelTypes();
|
||||
const allKnown = new Set([...Object.keys(BADGE_DEFAULT_COLORS), ...types]);
|
||||
const rows = [...allKnown].sort().map((type) => {
|
||||
const color = state.badgeColors[type] || BADGE_DEFAULT_COLORS[type] || "#0077ff";
|
||||
return `<div class="wfm-badge-color-row" data-type="${type}">
|
||||
<span class="wfm-badge wfm-badge-model" style="background:${color}">${type}</span>
|
||||
<input type="color" class="wfm-badge-color-input" value="${color}" data-type="${type}" title="Change color for ${type}" />
|
||||
</div>`;
|
||||
}).join("");
|
||||
|
||||
panel.innerHTML = `
|
||||
<div class="wfm-badge-settings-title">${t("defaultView")}</div>
|
||||
<div class="wfm-settings-radio-group">${viewRadios}</div>
|
||||
<hr style="border:none;border-top:1px solid var(--wfm-border);margin:8px 0;">
|
||||
<div class="wfm-badge-settings-title">${t("badgeColors")}</div>
|
||||
${rows}
|
||||
<button id="wfm-badge-color-reset" class="wfm-btn wfm-btn-sm" style="margin-top:6px;width:100%;">${t("resetColors")}</button>`;
|
||||
<div class="wfm-settings-radio-group">${viewRadios}</div>`;
|
||||
|
||||
// Default view change
|
||||
panel.querySelectorAll('input[name="wfm-default-view"]').forEach((radio) => {
|
||||
radio.addEventListener("change", () => {
|
||||
localStorage.setItem("wfm_default_view", radio.value);
|
||||
state.viewMode = radio.value;
|
||||
// Update active state on view mode buttons
|
||||
document.querySelectorAll(".wfm-view-btn").forEach((b) => {
|
||||
b.classList.toggle("active", b.dataset.view === radio.value);
|
||||
});
|
||||
renderGrid();
|
||||
});
|
||||
});
|
||||
|
||||
// Badge color change
|
||||
panel.querySelectorAll(".wfm-badge-color-input").forEach((input) => {
|
||||
input.addEventListener("input", (e) => {
|
||||
const type = e.target.dataset.type;
|
||||
const color = e.target.value;
|
||||
state.badgeColors[type] = color;
|
||||
localStorage.setItem("wfm_badge_colors", JSON.stringify(state.badgeColors));
|
||||
const badge = e.target.closest(".wfm-badge-color-row")?.querySelector(".wfm-badge");
|
||||
if (badge) badge.style.background = color;
|
||||
renderGrid();
|
||||
});
|
||||
});
|
||||
|
||||
panel.querySelector("#wfm-badge-color-reset")?.addEventListener("click", () => {
|
||||
state.badgeColors = {};
|
||||
localStorage.removeItem("wfm_badge_colors");
|
||||
renderBadgeSettings();
|
||||
renderGrid();
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -673,10 +762,21 @@ async function saveModalMeta(wf) {
|
||||
|
||||
function openDetailModal(wf) {
|
||||
const meta = wf.metadata;
|
||||
const types = (wf.analysis.modelTypes || []).map((t) => badgeHtml(t)).join(" ");
|
||||
const io = `P:${wf.analysis.inputs?.prompts || 0} I:${wf.analysis.inputs?.images || 0} → ${wf.analysis.outputs?.images || 0}`;
|
||||
const overrideText = (meta.modelTypesOverride || []).join(", ");
|
||||
const isFav = !!meta.favorite;
|
||||
const palette = getBadgePalette();
|
||||
const allBadgeLabels = Object.keys(palette).sort();
|
||||
const activeBadges = meta.badges || [];
|
||||
const badgeCheckboxes = allBadgeLabels.length === 0
|
||||
? `<span style="color:var(--wfm-text-secondary);font-size:12px;">${t("badgeNoneHint")}</span>`
|
||||
: allBadgeLabels.map((label) => {
|
||||
const color = palette[label] || "";
|
||||
const style = color ? ` style="background:${color};color:#fff;"` : "";
|
||||
const checked = activeBadges.includes(label) ? " checked" : "";
|
||||
return `<label class="wfm-badge-check-label">
|
||||
<input type="checkbox" class="wfm-badge-checkbox" value="${escapeHtml(label)}"${checked}>
|
||||
<span class="wfm-badge wfm-badge-model"${style}>${escapeHtml(label)}</span>
|
||||
</label>`;
|
||||
}).join("");
|
||||
|
||||
const thumbSrc = wf.thumbnail || "";
|
||||
const html = `
|
||||
@@ -689,23 +789,9 @@ function openDetailModal(wf) {
|
||||
<div class="wfm-modal-two-col">
|
||||
<div class="wfm-modal-left">
|
||||
<section>
|
||||
<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">
|
||||
<h4>${t("analysis")}</h4>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-detail-analyze">${t("analyze")}</button>
|
||||
</div>
|
||||
<div id="wfm-detail-analysis" class="wfm-detail-analysis">
|
||||
<div>${types || `<span style="color:var(--wfm-text-secondary)">${t("noModelDetected")}</span>`}</div>
|
||||
<div style="font-size:11px;color:var(--wfm-text-secondary);margin-top:4px;">${io}</div>
|
||||
</div>
|
||||
<div id="wfm-detail-override-row" style="margin-top:8px;">
|
||||
<div style="display:flex;gap:4px;align-items:center;">
|
||||
<span style="font-size:12px;color:var(--wfm-text-secondary);white-space:nowrap;">${t("modelCategory")}</span>
|
||||
<input type="text" class="wfm-input" id="wfm-detail-model-override"
|
||||
value="${overrideText}"
|
||||
placeholder="${t("modelOverridePlaceholder")}" style="flex:1;font-size:12px;padding:4px 6px;min-width:0;">
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-detail-override-save">${t("save")}</button>
|
||||
</div>
|
||||
</div>
|
||||
<h4>${t("modelsBadges")} <button class="wfm-btn wfm-btn-sm" id="wfm-detail-badge-manage">⚙ ${t("badgeManage")}</button></h4>
|
||||
<div id="wfm-detail-badge-checkboxes" class="wfm-badge-checkboxes">${badgeCheckboxes}</div>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-detail-badges-save" style="margin-top:6px;">${t("save")}</button>
|
||||
</section>
|
||||
<section>
|
||||
<h4>${t("tags")} <span style="font-weight:normal;font-size:11px;">${t("tagsHint")}</span></h4>
|
||||
@@ -813,51 +899,40 @@ function openDetailModal(wf) {
|
||||
document.getElementById(id)?.addEventListener("blur", () => saveModalMeta(wf));
|
||||
});
|
||||
|
||||
// Analyze button
|
||||
document.getElementById("wfm-detail-analyze")?.addEventListener("click", async () => {
|
||||
const btn = document.getElementById("wfm-detail-analyze");
|
||||
btn.disabled = true;
|
||||
btn.textContent = t("analyzing");
|
||||
try {
|
||||
const res = await fetch("/api/wfm/workflows/analyze", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ filename: wf.filename }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
wf.analysis = data.analysis;
|
||||
const cached = state.workflows.find((w) => w.filename === wf.filename);
|
||||
if (cached) cached.analysis = data.analysis;
|
||||
// Re-render analysis section
|
||||
const analysisEl = document.getElementById("wfm-detail-analysis");
|
||||
if (analysisEl) {
|
||||
const newTypes = (data.analysis.modelTypes || []).map((mt) => badgeHtml(mt)).join(" ");
|
||||
const newIo = `P:${data.analysis.inputs?.prompts || 0} I:${data.analysis.inputs?.images || 0} → ${data.analysis.outputs?.images || 0}`;
|
||||
analysisEl.innerHTML = `<div>${newTypes || `<span style="color:var(--wfm-text-secondary)">${t("noModelDetected")}</span>`}</div>
|
||||
<div style="font-size:11px;color:var(--wfm-text-secondary);margin-top:4px;">${newIo}</div>`;
|
||||
}
|
||||
renderGrid();
|
||||
showToast(t("analysisComplete"), "success");
|
||||
} catch (err) {
|
||||
showToast(t("analyzeError") + ": " + err.message, "error");
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = t("analyze");
|
||||
}
|
||||
// Badge manage button
|
||||
document.getElementById("wfm-detail-badge-manage")?.addEventListener("click", () => {
|
||||
openBadgeEditModal(() => {
|
||||
// Rebuild checkboxes after palette changes
|
||||
const palette = getBadgePalette();
|
||||
const allLabels = Object.keys(palette).sort();
|
||||
const currentBadges = [...document.querySelectorAll(".wfm-badge-checkbox:checked")].map(cb => cb.value);
|
||||
const el = document.getElementById("wfm-detail-badge-checkboxes");
|
||||
if (!el) return;
|
||||
el.innerHTML = allLabels.length === 0
|
||||
? `<span style="color:var(--wfm-text-secondary);font-size:12px;">${t("badgeNoneHint")}</span>`
|
||||
: allLabels.map((label) => {
|
||||
const color = palette[label] || "";
|
||||
const style = color ? ` style="background:${color};color:#fff;"` : "";
|
||||
const checked = currentBadges.includes(label) ? " checked" : "";
|
||||
return `<label class="wfm-badge-check-label">
|
||||
<input type="checkbox" class="wfm-badge-checkbox" value="${escapeHtml(label)}"${checked}>
|
||||
<span class="wfm-badge wfm-badge-model"${style}>${escapeHtml(label)}</span>
|
||||
</label>`;
|
||||
}).join("");
|
||||
});
|
||||
});
|
||||
|
||||
// Model type override save
|
||||
document.getElementById("wfm-detail-override-save")?.addEventListener("click", async () => {
|
||||
const overrideStr = document.getElementById("wfm-detail-model-override")?.value || "";
|
||||
const modelTypesOverride = overrideStr.split(",").map((t) => t.trim()).filter(Boolean);
|
||||
// Badge save
|
||||
document.getElementById("wfm-detail-badges-save")?.addEventListener("click", async () => {
|
||||
const badges = [...document.querySelectorAll(".wfm-badge-checkbox:checked")].map(cb => cb.value);
|
||||
try {
|
||||
await saveMetadata(wf.filename, { modelTypesOverride });
|
||||
wf.metadata.modelTypesOverride = modelTypesOverride;
|
||||
await saveMetadata(wf.filename, { badges });
|
||||
wf.metadata.badges = badges;
|
||||
const cached = state.workflows.find((w) => w.filename === wf.filename);
|
||||
if (cached) cached.metadata.modelTypesOverride = modelTypesOverride;
|
||||
if (cached) cached.metadata.badges = badges;
|
||||
renderGrid();
|
||||
showToast(t("overrideSaved"), "success");
|
||||
renderModelFilters();
|
||||
showToast(t("modelsSaved"), "success");
|
||||
} catch (err) {
|
||||
showToast(t("saveError") + ": " + err.message, "error");
|
||||
}
|
||||
@@ -1070,6 +1145,7 @@ export function initWorkflowTab() {
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener("input", () => {
|
||||
state.searchText = searchInput.value;
|
||||
state.currentPage = 0;
|
||||
renderGrid();
|
||||
});
|
||||
}
|
||||
@@ -1097,9 +1173,6 @@ export function initWorkflowTab() {
|
||||
});
|
||||
}
|
||||
|
||||
// Side panel: close button
|
||||
document.getElementById("wfm-side-panel-close")?.addEventListener("click", closeSidePanel);
|
||||
|
||||
// Side panel: tab switching
|
||||
document.querySelectorAll(".wfm-side-tab-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
@@ -1133,78 +1206,12 @@ export function initWorkflowTab() {
|
||||
|
||||
// Group management
|
||||
groups.load();
|
||||
refreshGroupSelects();
|
||||
|
||||
// Add group
|
||||
document.getElementById("wfm-group-add-btn")?.addEventListener("click", () => {
|
||||
const input = document.getElementById("wfm-group-name-input");
|
||||
const name = input?.value.trim();
|
||||
if (!name) return;
|
||||
if (!groups.createGroup(name)) {
|
||||
showToast(`"${name}" already exists`, "error");
|
||||
return;
|
||||
}
|
||||
input.value = "";
|
||||
refreshGroupSelects();
|
||||
showToast(`Group "${name}" created`, "success");
|
||||
});
|
||||
|
||||
// Rename group
|
||||
document.getElementById("wfm-group-rename-btn")?.addEventListener("click", () => {
|
||||
const sel = document.getElementById("wfm-group-select");
|
||||
const oldName = sel?.value;
|
||||
if (!oldName) return;
|
||||
const newName = prompt("New group name:", oldName);
|
||||
if (!newName || newName === oldName) return;
|
||||
if (!groups.renameGroup(oldName, newName)) {
|
||||
showToast("Rename failed", "error");
|
||||
return;
|
||||
}
|
||||
refreshGroupSelects();
|
||||
sidePanelGroupUpdate();
|
||||
showToast(`Group renamed to "${newName}"`, "success");
|
||||
});
|
||||
|
||||
// Delete group
|
||||
document.getElementById("wfm-group-delete-btn")?.addEventListener("click", () => {
|
||||
const sel = document.getElementById("wfm-group-select");
|
||||
const name = sel?.value;
|
||||
if (!name) return;
|
||||
if (!confirm(`Delete group "${name}"?`)) return;
|
||||
groups.deleteGroup(name);
|
||||
refreshGroupSelects();
|
||||
sidePanelGroupUpdate();
|
||||
showToast(`Group "${name}" deleted`, "success");
|
||||
});
|
||||
|
||||
// Assign to group
|
||||
document.getElementById("wfm-assign-group-btn")?.addEventListener("click", () => {
|
||||
const sel = document.getElementById("wfm-group-select");
|
||||
const groupName = sel?.value;
|
||||
if (!groupName || !state.selectedWf) return;
|
||||
groups.assign(state.selectedWf.filename, groupName);
|
||||
sidePanelGroupUpdate();
|
||||
showToast(`Added to "${groupName}"`, "success");
|
||||
});
|
||||
|
||||
// Remove from group
|
||||
document.getElementById("wfm-remove-group-btn")?.addEventListener("click", () => {
|
||||
const sel = document.getElementById("wfm-group-select");
|
||||
const groupName = sel?.value;
|
||||
if (!groupName || !state.selectedWf) return;
|
||||
groups.remove(state.selectedWf.filename, groupName);
|
||||
sidePanelGroupUpdate();
|
||||
showToast(`Removed from "${groupName}"`, "success");
|
||||
});
|
||||
|
||||
// Update remove button state when group select changes
|
||||
document.getElementById("wfm-group-select")?.addEventListener("change", () => {
|
||||
sidePanelGroupUpdate();
|
||||
});
|
||||
_refreshGroupFilter();
|
||||
|
||||
// Toolbar: group filter dropdown
|
||||
document.getElementById("wfm-group-filter")?.addEventListener("change", (e) => {
|
||||
state.groupFilter = e.target.value;
|
||||
state.currentPage = 0;
|
||||
renderGrid();
|
||||
});
|
||||
|
||||
@@ -1238,7 +1245,7 @@ export function initWorkflowTab() {
|
||||
showToast("Refreshed", "success");
|
||||
});
|
||||
|
||||
// Toolbar: Badge color settings
|
||||
// Toolbar: ⚙ settings button (view settings panel)
|
||||
const badgeSettingsBtn = document.getElementById("wfm-badge-settings-btn");
|
||||
const badgeSettingsPanel = document.getElementById("wfm-badge-settings-panel");
|
||||
if (badgeSettingsBtn && badgeSettingsPanel) {
|
||||
@@ -1249,7 +1256,7 @@ export function initWorkflowTab() {
|
||||
badgeSettingsPanel.style.display = "none";
|
||||
return;
|
||||
}
|
||||
renderBadgeSettings();
|
||||
renderViewSettings();
|
||||
badgeSettingsPanel.style.display = "";
|
||||
});
|
||||
document.addEventListener("click", (e) => {
|
||||
@@ -1259,15 +1266,9 @@ export function initWorkflowTab() {
|
||||
});
|
||||
}
|
||||
|
||||
// Toolbar: Reanalyze All button
|
||||
document.getElementById("wfm-reanalyze-btn")?.addEventListener("click", async () => {
|
||||
try {
|
||||
const result = await reanalyzeAll();
|
||||
showToast(`Reanalyzed ${result.count ?? 0} workflows`, "success");
|
||||
await loadWorkflows();
|
||||
} catch (err) {
|
||||
showToast("Reanalyze error: " + err.message, "error");
|
||||
}
|
||||
// Toolbar: ⚙ Badge button
|
||||
document.getElementById("wfm-badge-btn")?.addEventListener("click", () => {
|
||||
openBadgeEditModal(() => renderGrid());
|
||||
});
|
||||
|
||||
// Initial load
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
<title>Workflow Studio</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/wfm_static/favicon.svg">
|
||||
<link rel="stylesheet" href="/wfm_static/css/main.css">
|
||||
<link rel="stylesheet" href="/wfm_static/css/gallery-tab.css">
|
||||
</head>
|
||||
<body>
|
||||
<!-- Header -->
|
||||
@@ -16,8 +17,11 @@
|
||||
<nav class="wfm-tabs">
|
||||
<button class="wfm-tab active" data-tab="workflow">Workflow</button>
|
||||
<button class="wfm-tab" data-tab="nodes">Nodes</button>
|
||||
<button class="wfm-tab" data-tab="models">Models</button>
|
||||
<button class="wfm-tab" data-tab="generate">GenerateUI</button>
|
||||
<button class="wfm-tab" data-tab="prompt">Prompt</button>
|
||||
<button class="wfm-tab" data-tab="metadata">Metadata</button>
|
||||
<button class="wfm-tab" data-tab="gallery">Gallery</button>
|
||||
<button class="wfm-tab" data-tab="settings">Settings</button>
|
||||
<button class="wfm-tab" data-tab="help">Help</button>
|
||||
</nav>
|
||||
@@ -49,13 +53,13 @@
|
||||
<button class="wfm-view-btn" data-view="table" title="Table">≡</button>
|
||||
</div>
|
||||
<button id="wfm-refresh-btn" class="wfm-btn wfm-btn-sm">Refresh</button>
|
||||
<button id="wfm-reanalyze-btn" class="wfm-btn wfm-btn-sm" title="Re-analyze all workflows">Reanalyze All</button>
|
||||
<label class="wfm-btn wfm-btn-sm" style="cursor:pointer;">
|
||||
Import
|
||||
<input type="file" id="wfm-import-input" multiple accept=".json,.png" style="display:none">
|
||||
</label>
|
||||
<button id="wfm-badge-btn" class="wfm-btn wfm-btn-sm" title="Badge settings">⚙ Badge</button>
|
||||
<div class="wfm-badge-settings-wrap">
|
||||
<button id="wfm-badge-settings-btn" class="wfm-btn wfm-btn-sm" title="Badge color settings">⚙</button>
|
||||
<button id="wfm-badge-settings-btn" class="wfm-btn wfm-btn-sm" title="View settings">⚙</button>
|
||||
<div id="wfm-badge-settings-panel" class="wfm-badge-settings-panel" style="display:none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -65,10 +69,9 @@
|
||||
<p class="wfm-placeholder">Loading workflows...</p>
|
||||
</div>
|
||||
<!-- Side Panel -->
|
||||
<div id="wfm-side-panel" class="wfm-side-panel" style="display:none;">
|
||||
<div id="wfm-side-panel" class="wfm-side-panel">
|
||||
<div class="wfm-side-panel-header">
|
||||
<span id="wfm-side-panel-title" class="wfm-side-panel-title"></span>
|
||||
<button id="wfm-side-panel-close" class="wfm-side-panel-close">×</button>
|
||||
</div>
|
||||
<div class="wfm-side-tab-nav">
|
||||
<button class="wfm-side-tab-btn active" data-side-tab="thumb">Thumbnail</button>
|
||||
@@ -96,35 +99,8 @@
|
||||
<pre id="wfm-json-content" class="wfm-json-content"></pre>
|
||||
</div>
|
||||
<!-- Group Tab -->
|
||||
<div id="wfm-side-tab-group" class="wfm-side-tab-content" style="display:none;">
|
||||
<div class="wfm-group-panel">
|
||||
<div class="wfm-group-section">
|
||||
<div class="wfm-group-section-title">Properties</div>
|
||||
<div id="wfm-grp-prop-name" class="wfm-group-prop">No selection</div>
|
||||
<div id="wfm-grp-prop-group" class="wfm-group-prop"></div>
|
||||
</div>
|
||||
<hr class="wfm-group-divider">
|
||||
<div class="wfm-group-section">
|
||||
<div class="wfm-group-section-title">Group Management</div>
|
||||
<div style="display:flex;gap:4px;margin-bottom:6px;">
|
||||
<input type="text" id="wfm-group-name-input" class="wfm-input" placeholder="Group name" style="flex:1;min-width:0;padding:4px 6px;font-size:12px;">
|
||||
<button id="wfm-group-add-btn" class="wfm-btn wfm-btn-sm" title="Create group">Add</button>
|
||||
</div>
|
||||
<div style="display:flex;gap:4px;margin-bottom:6px;">
|
||||
<select id="wfm-group-select" class="wfm-select" style="flex:1;min-width:0;padding:4px 6px;font-size:12px;">
|
||||
<option value="">Select group</option>
|
||||
</select>
|
||||
<button id="wfm-group-rename-btn" class="wfm-btn wfm-btn-sm" title="Rename group">✎</button>
|
||||
<button id="wfm-group-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" title="Delete group" style="padding:4px 8px;font-size:12px;">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<hr class="wfm-group-divider">
|
||||
<div class="wfm-group-section">
|
||||
<div class="wfm-group-section-title">Workflow Actions</div>
|
||||
<button id="wfm-assign-group-btn" class="wfm-btn wfm-btn-sm" style="width:100%;margin-bottom:4px;" disabled>Add to Group</button>
|
||||
<button id="wfm-remove-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" style="width:100%;margin-bottom:4px;font-size:12px;" disabled>Remove from Group</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wfm-side-tab-group" class="wfm-side-tab-content" style="display:none;overflow-y:auto;">
|
||||
<!-- JS動的生成: renderSideGroup() -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -163,10 +139,9 @@
|
||||
<p class="wfm-placeholder" id="wfm-nodes-placeholder">Click to load nodes...</p>
|
||||
</div>
|
||||
<!-- Side Panel -->
|
||||
<div id="wfm-nodes-side-panel" class="wfm-side-panel" style="display:none;">
|
||||
<div id="wfm-nodes-side-panel" class="wfm-side-panel">
|
||||
<div class="wfm-side-panel-header">
|
||||
<span id="wfm-nodes-panel-title" class="wfm-side-panel-title"></span>
|
||||
<button id="wfm-nodes-panel-close" class="wfm-side-panel-close">×</button>
|
||||
</div>
|
||||
<div class="wfm-side-tab-nav">
|
||||
<button class="wfm-nodes-side-tab-btn active" data-side-tab="details">Details</button>
|
||||
@@ -193,6 +168,80 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Models Tab -->
|
||||
<section id="wfm-tab-models" class="wfm-tab-content">
|
||||
<div class="wfm-toolbar">
|
||||
<!-- Row 1: Model type sub-tabs + badge filter -->
|
||||
<div class="wfm-toolbar-row" style="gap:8px;flex-wrap:wrap;align-items:center;">
|
||||
<div class="wfm-models-type-nav">
|
||||
<button class="wfm-models-type-btn active" data-model-type="checkpoint">Checkpoint</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="lora">LoRA</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="vae">VAE</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="controlnet">ControlNet</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="unet">UNET</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="textencoder">TextEncoder</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="hypernetwork">Hypernetwork</button>
|
||||
<button class="wfm-models-type-btn" data-model-type="embedding">Embedding</button>
|
||||
</div>
|
||||
<div class="wfm-models-type-divider"></div>
|
||||
<div id="wfm-models-badge-filter-bar" class="wfm-badge-filter-bar"></div>
|
||||
</div>
|
||||
<!-- Row 2: Search / filter toolbar -->
|
||||
<div id="wfm-models-toolbar" class="wfm-toolbar-row" style="gap:6px;flex-wrap:wrap;">
|
||||
<button class="wfm-filter-btn" id="wfm-models-fav-btn" title="Favorites">★</button>
|
||||
<input type="text" id="wfm-models-search" class="wfm-search-input" placeholder="Search models...">
|
||||
<select id="wfm-models-tag-filter" class="wfm-select wfm-toolbar-select"><option value="">All Tags</option></select>
|
||||
<select id="wfm-models-dir-filter" class="wfm-select wfm-toolbar-select"><option value="">All Folders</option></select>
|
||||
<select id="wfm-models-group-filter" class="wfm-select wfm-toolbar-select"><option value="">All Groups</option></select>
|
||||
<select id="wfm-models-status-filter" class="wfm-select wfm-toolbar-select">
|
||||
<option value="all">All</option>
|
||||
<option value="enabled">Enabled only</option>
|
||||
<option value="disabled">Disabled only</option>
|
||||
</select>
|
||||
<div class="wfm-view-btns">
|
||||
<button class="wfm-view-btn active" data-models-view="thumb" title="Thumbnail">⊞</button>
|
||||
<button class="wfm-view-btn" data-models-view="card" title="Card">☰</button>
|
||||
<button class="wfm-view-btn" data-models-view="table" title="Table">≡</button>
|
||||
</div>
|
||||
<span id="wfm-models-count" class="wfm-nodes-count"></span>
|
||||
<button id="wfm-models-refresh-btn" class="wfm-btn wfm-btn-sm">Refresh</button>
|
||||
<button id="wfm-models-civitai-batch-btn" class="wfm-btn wfm-btn-sm" title="Fetch CivitAI info for all models">CivitAI</button>
|
||||
<span id="wfm-models-civitai-progress" style="font-size:12px;color:var(--wfm-text-secondary);"></span>
|
||||
<button id="wfm-models-badge-settings-btn" class="wfm-btn wfm-btn-sm" title="Badge settings">⚙ Badge</button>
|
||||
<button id="wfm-models-select-btn" class="wfm-btn wfm-btn-sm" title="Multi-select models">Select</button>
|
||||
</div>
|
||||
<!-- Bulk action bar (shown in select mode) -->
|
||||
<div id="wfm-models-bulk-bar" class="wfm-bulk-bar" style="display:none;"></div>
|
||||
</div>
|
||||
|
||||
<!-- Grid + Side Panel -->
|
||||
<div class="wfm-workflow-area">
|
||||
<div id="wfm-models-grid" class="wfm-grid wfm-view-thumb">
|
||||
<p class="wfm-placeholder" id="wfm-models-placeholder">Click Refresh to load models...</p>
|
||||
</div>
|
||||
<!-- Side Panel -->
|
||||
<div id="wfm-models-side-panel" class="wfm-side-panel">
|
||||
<div class="wfm-side-panel-header">
|
||||
<span id="wfm-models-panel-title" class="wfm-side-panel-title"></span>
|
||||
</div>
|
||||
<div class="wfm-side-tab-nav">
|
||||
<button class="wfm-models-side-tab-btn active" data-side-tab="info">Info</button>
|
||||
<button class="wfm-models-side-tab-btn" data-side-tab="group">Group</button>
|
||||
<button class="wfm-models-side-tab-btn" data-side-tab="civitai">CivitAI</button>
|
||||
</div>
|
||||
<!-- Info Tab -->
|
||||
<div id="wfm-models-side-info" class="wfm-models-side-content active" style="overflow-y:auto;padding:12px;">
|
||||
</div>
|
||||
<!-- Group Tab -->
|
||||
<div id="wfm-models-side-group" class="wfm-models-side-content" style="display:none;overflow-y:auto;padding:12px;">
|
||||
</div>
|
||||
<!-- CivitAI Tab -->
|
||||
<div id="wfm-models-side-civitai" class="wfm-models-side-content" style="display:none;overflow-y:auto;padding:12px;">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- GenerateUI Tab -->
|
||||
<section id="wfm-tab-generate" class="wfm-tab-content">
|
||||
<!-- Header Row -->
|
||||
@@ -209,53 +258,173 @@
|
||||
|
||||
<!-- Editor Layout -->
|
||||
<div class="wfm-gen-layout">
|
||||
<!-- Left Column: Parameter Editor -->
|
||||
<!-- Left Column: Parameter Tabs -->
|
||||
<div class="wfm-gen-left">
|
||||
<!-- Subtab Navigation -->
|
||||
<!-- Tab Navigation -->
|
||||
<div class="wfm-gen-subtab-nav">
|
||||
<button class="wfm-gen-subtab-btn active" data-subtab="prompt">Prompt</button>
|
||||
<button class="wfm-gen-subtab-btn" data-subtab="image">Image</button>
|
||||
<button class="wfm-gen-subtab-btn active" data-subtab="input">Input</button>
|
||||
<button class="wfm-gen-subtab-btn" data-subtab="model">Model</button>
|
||||
<button class="wfm-gen-subtab-btn" data-subtab="settings">Settings</button>
|
||||
<button class="wfm-gen-subtab-btn" data-subtab="raw">Raw JSON</button>
|
||||
<button class="wfm-gen-subtab-btn" data-subtab="feeder">Feeder</button>
|
||||
</div>
|
||||
|
||||
<!-- Subtab: Prompt -->
|
||||
<div id="wfm-gen-subtab-prompt" class="wfm-gen-subtab-content active">
|
||||
<div id="wfm-gen-prompt-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to edit prompts</p>
|
||||
<!-- Tab: Input — left sub-col: Prompt(top)+Image(bottom), right sub-col: Raw JSON -->
|
||||
<div id="wfm-gen-subtab-input" class="wfm-gen-subtab-content active">
|
||||
<div class="wfm-gen-tab-cols">
|
||||
<div class="wfm-gen-params-col">
|
||||
<div class="wfm-gen-params-section">
|
||||
<h3 class="wfm-gen-col-title">Prompt</h3>
|
||||
<div id="wfm-gen-prompt-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to edit prompts</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-gen-params-section wfm-gen-params-section--top-border">
|
||||
<h3 class="wfm-gen-col-title">Image</h3>
|
||||
<div id="wfm-gen-image-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to set input images</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-gen-rawjson-col" id="wfm-gen-rawjson-col-input"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtab: Image Input -->
|
||||
<div id="wfm-gen-subtab-image" class="wfm-gen-subtab-content">
|
||||
<div id="wfm-gen-image-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to set input images</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtab: Model -->
|
||||
<!-- Tab: Model — left sub-col: model selects, right sub-col: Raw JSON -->
|
||||
<div id="wfm-gen-subtab-model" class="wfm-gen-subtab-content">
|
||||
<div id="wfm-gen-model-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to edit models</p>
|
||||
<div class="wfm-gen-tab-cols">
|
||||
<div class="wfm-gen-params-col wfm-gen-params-col--scroll">
|
||||
<div id="wfm-gen-model-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to edit models</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-gen-rawjson-col" id="wfm-gen-rawjson-col-model"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtab: Settings -->
|
||||
<!-- Tab: Settings — left sub-col: KSampler(top)+LatentImage(bottom), right sub-col: Raw JSON -->
|
||||
<div id="wfm-gen-subtab-settings" class="wfm-gen-subtab-content">
|
||||
<div id="wfm-gen-settings-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to edit settings</p>
|
||||
<div class="wfm-gen-tab-cols">
|
||||
<div class="wfm-gen-params-col wfm-gen-params-col--scroll">
|
||||
<div id="wfm-gen-settings-fields">
|
||||
<p class="wfm-placeholder">Load a workflow to edit settings</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-gen-rawjson-col" id="wfm-gen-rawjson-col-settings"></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Tab: Feeder — full-width: settings(left) + library(center) -->
|
||||
<div id="wfm-gen-subtab-feeder" class="wfm-gen-subtab-content">
|
||||
<div class="wfm-feeder-layout">
|
||||
<!-- Left: Node selector + params + presets -->
|
||||
<div class="wfm-feeder-settings">
|
||||
<div class="wfm-feeder-pane-header">ImageFeeder Node</div>
|
||||
<div style="display:flex;gap:6px;align-items:center;margin-bottom:8px;">
|
||||
<select id="wfm-feeder-node-sel" class="wfm-select" style="flex:1;min-width:0;"></select>
|
||||
<button id="wfm-feeder-apply-btn" class="wfm-btn wfm-btn-primary" style="white-space:nowrap;">Apply</button>
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Directory</label>
|
||||
<input type="text" id="wfm-feeder-dir-input" class="wfm-input wfm-feeder-input" placeholder="e.g. subdir">
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Sort Mode</label>
|
||||
<select id="wfm-feeder-sort" class="wfm-select wfm-feeder-input">
|
||||
<option value="ascending">ascending</option>
|
||||
<option value="descending">descending</option>
|
||||
<option value="random">random</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Index</label>
|
||||
<input type="number" id="wfm-feeder-index" class="wfm-input wfm-feeder-input" value="0" min="0">
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Start Index</label>
|
||||
<input type="number" id="wfm-feeder-start" class="wfm-input wfm-feeder-input" value="0" min="0">
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">End Index</label>
|
||||
<input type="number" id="wfm-feeder-end" class="wfm-input wfm-feeder-input" value="0" min="0">
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Batch Size</label>
|
||||
<input type="number" id="wfm-feeder-batch" class="wfm-input wfm-feeder-input" value="1" min="1">
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Seed</label>
|
||||
<input type="number" id="wfm-feeder-seed" class="wfm-input wfm-feeder-input" value="0">
|
||||
</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">Use Selection</label>
|
||||
<input type="checkbox" id="wfm-feeder-use-sel" checked style="width:16px;height:16px;accent-color:var(--wfm-primary);">
|
||||
</div>
|
||||
|
||||
<!-- Subtab: Raw JSON -->
|
||||
<div id="wfm-gen-subtab-raw" class="wfm-gen-subtab-content">
|
||||
<div style="margin-bottom:8px;">
|
||||
<button id="wfm-gen-apply-raw-btn" class="wfm-btn wfm-btn-sm">Apply JSON</button>
|
||||
</div>
|
||||
<div class="wfm-json-container" style="height:500px;">
|
||||
<pre id="wfm-gen-raw-json-highlight" class="wfm-json-highlight"></pre>
|
||||
<textarea id="wfm-gen-raw-json" class="wfm-json-editor" spellcheck="false" placeholder="Paste workflow JSON here..."></textarea>
|
||||
<div class="wfm-feeder-pane-header" style="margin-top:12px;">Presets</div>
|
||||
<div style="display:flex;gap:6px;margin-bottom:6px;">
|
||||
<input type="text" id="wfm-feeder-preset-name" class="wfm-input" style="flex:1;min-width:0;" placeholder="Preset name">
|
||||
<button id="wfm-feeder-preset-save" class="wfm-btn wfm-btn-sm" style="white-space:nowrap;">Save</button>
|
||||
</div>
|
||||
<div style="display:flex;gap:6px;">
|
||||
<select id="wfm-feeder-preset-sel" class="wfm-select" style="flex:1;min-width:0;"></select>
|
||||
<button id="wfm-feeder-preset-load" class="wfm-btn wfm-btn-sm wfm-btn-primary" style="white-space:nowrap;">Load</button>
|
||||
<button id="wfm-feeder-preset-del" class="wfm-btn wfm-btn-sm wfm-btn-danger" style="white-space:nowrap;">Del</button>
|
||||
</div>
|
||||
|
||||
<div class="wfm-feeder-pane-header" style="margin-top:12px;">Run</div>
|
||||
<div class="wfm-feeder-field-row">
|
||||
<label class="wfm-feeder-label">After gen</label>
|
||||
<select id="wfm-feeder-control-after" class="wfm-select wfm-feeder-input">
|
||||
<option value="loop">Loop</option>
|
||||
<option value="increment">Increment</option>
|
||||
<option value="fixed">Fixed</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;margin-top:4px;">
|
||||
<button id="wfm-feeder-run-btn" class="wfm-btn wfm-btn-primary" style="flex:1;">▶ Run</button>
|
||||
<button id="wfm-feeder-stop-btn" class="wfm-btn wfm-btn-danger" style="flex:1;" disabled>■ Stop</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Center: Image Library -->
|
||||
<div class="wfm-feeder-library">
|
||||
<!-- Status bar -->
|
||||
<div id="wfm-feeder-status" class="wfm-feeder-status-bar">Select a folder</div>
|
||||
|
||||
<div class="wfm-feeder-library-body">
|
||||
<!-- Folder tree -->
|
||||
<div class="wfm-feeder-tree-pane">
|
||||
<div class="wfm-feeder-pane-header" style="display:flex;align-items:center;justify-content:space-between;">
|
||||
<span>Folders</span>
|
||||
<button id="wfm-feeder-reload-tree" class="wfm-btn wfm-btn-sm" title="Reload">↺</button>
|
||||
</div>
|
||||
<div id="wfm-feeder-tree" class="wfm-feeder-tree-scroll">
|
||||
<div class="wfm-feeder-tree-msg">Loading...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Image grid -->
|
||||
<div class="wfm-feeder-grid-pane">
|
||||
<div class="wfm-feeder-pane-header" style="display:flex;align-items:center;justify-content:space-between;">
|
||||
<span>Images</span>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<button id="wfm-feeder-sel-all" class="wfm-btn wfm-btn-sm">All</button>
|
||||
<button id="wfm-feeder-desel-all" class="wfm-btn wfm-btn-sm">None</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wfm-feeder-grid" class="wfm-feeder-grid">
|
||||
<div class="wfm-feeder-grid-msg">Select a folder</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Preview -->
|
||||
<div class="wfm-feeder-preview-pane">
|
||||
<div class="wfm-feeder-pane-header">Preview</div>
|
||||
<img id="wfm-feeder-preview-img" class="wfm-feeder-preview-img" style="display:none;" alt="">
|
||||
<div id="wfm-feeder-preview-name" class="wfm-feeder-preview-name"></div>
|
||||
<pre id="wfm-feeder-preview-info" class="wfm-feeder-preview-info"></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -278,10 +447,12 @@
|
||||
</div>
|
||||
|
||||
<!-- Seed -->
|
||||
<div style="display:flex;gap:8px;align-items:center;margin-top:8px;">
|
||||
<label style="font-size:12px;color:var(--wfm-text-secondary);white-space:nowrap;">Seed:</label>
|
||||
<input type="number" id="wfm-gen-seed-value" class="wfm-input" value="-1" style="width:140px;">
|
||||
<select id="wfm-gen-seed-mode" class="wfm-select" style="width:auto;">
|
||||
<div style="display:flex;flex-direction:column;gap:4px;margin-top:8px;">
|
||||
<div style="display:flex;gap:8px;align-items:center;">
|
||||
<label style="font-size:12px;color:var(--wfm-text-secondary);white-space:nowrap;">Seed:</label>
|
||||
<input type="number" id="wfm-gen-seed-value" class="wfm-input" value="-1" style="flex:1;min-width:0;">
|
||||
</div>
|
||||
<select id="wfm-gen-seed-mode" class="wfm-select" style="width:100%;">
|
||||
<option value="random">Random</option>
|
||||
<option value="fixed">Fixed</option>
|
||||
<option value="increment">Increment</option>
|
||||
@@ -290,6 +461,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Checkpoint Batch Panel -->
|
||||
<div class="wfm-gen-panel" id="wfm-ckpt-batch-panel">
|
||||
<div style="display:flex;align-items:center;gap:8px;">
|
||||
<input type="checkbox" id="wfm-ckpt-batch-enabled" style="width:14px;height:14px;cursor:pointer;accent-color:var(--wfm-primary);">
|
||||
<label for="wfm-ckpt-batch-enabled" style="font-weight:600;font-size:13px;cursor:pointer;">Checkpoint Batch</label>
|
||||
</div>
|
||||
<div id="wfm-ckpt-batch-body" style="display:none;margin-top:8px;">
|
||||
<div style="margin-bottom:6px;">
|
||||
<div style="font-size:11px;color:var(--wfm-text-secondary);margin-bottom:3px;">Checkpoints</div>
|
||||
<div class="wfm-ckpt-dropdown-wrap" id="wfm-ckpt-dropdown-wrap">
|
||||
<button type="button" id="wfm-ckpt-dropdown-btn" class="wfm-ckpt-dropdown-trigger">
|
||||
<span id="wfm-ckpt-dropdown-label">All checkpoints</span>
|
||||
<span class="wfm-ckpt-dropdown-arrow">▼</span>
|
||||
</button>
|
||||
<div id="wfm-ckpt-dropdown-panel" class="wfm-ckpt-dropdown-panel" style="display:none;">
|
||||
<div style="padding:6px 8px 4px;">
|
||||
<input type="text" id="wfm-ckpt-search" class="wfm-input" style="height:28px;padding:4px 8px;font-size:11px;" placeholder="Filter...">
|
||||
</div>
|
||||
<div style="display:flex;gap:4px;padding:0 8px 4px;">
|
||||
<button type="button" id="wfm-ckpt-select-all" class="wfm-btn wfm-btn-sm" style="flex:1;font-size:10px;">All</button>
|
||||
<button type="button" id="wfm-ckpt-deselect-all" class="wfm-btn wfm-btn-sm" style="flex:1;font-size:10px;">None</button>
|
||||
</div>
|
||||
<div id="wfm-ckpt-list" class="wfm-ckpt-dropdown-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wfm-ckpt-batch-info" style="font-size:11px;color:var(--wfm-text-secondary);"></div>
|
||||
<div id="wfm-ckpt-batch-progress" style="margin-top:8px;display:none;">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;font-size:11px;">
|
||||
<span id="wfm-ckpt-batch-current-name" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:75%;color:var(--wfm-text-primary);"></span>
|
||||
<span id="wfm-ckpt-batch-count" style="color:var(--wfm-text-secondary);white-space:nowrap;margin-left:8px;"></span>
|
||||
</div>
|
||||
<div class="wfm-gen-progress-track">
|
||||
<div id="wfm-ckpt-batch-bar" class="wfm-gen-progress-bar" style="background:var(--wfm-warning,#f59e0b);"></div>
|
||||
</div>
|
||||
<div style="margin-top:6px;">
|
||||
<button id="wfm-ckpt-batch-pause-btn" class="wfm-btn wfm-btn-sm" style="width:100%;">Pause</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Result Display -->
|
||||
<div class="wfm-gen-result">
|
||||
<img id="wfm-gen-result-img" style="display:none;max-width:100%;border-radius:6px;">
|
||||
@@ -297,6 +510,18 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Raw JSON shared widget (moved into active tab's rawjson-col by JS) -->
|
||||
<div id="wfm-gen-rawjson-widget" style="display:none;flex-direction:column;height:100%;">
|
||||
<div class="wfm-gen-rawjson-header">
|
||||
<span class="wfm-gen-rawjson-label">Raw JSON</span>
|
||||
<button id="wfm-gen-apply-raw-btn" class="wfm-btn wfm-btn-sm">Apply</button>
|
||||
</div>
|
||||
<div class="wfm-json-container wfm-gen-rawjson-editor">
|
||||
<pre id="wfm-gen-raw-json-highlight" class="wfm-json-highlight"></pre>
|
||||
<textarea id="wfm-gen-raw-json" class="wfm-json-editor" spellcheck="false" placeholder="Paste workflow JSON here..."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Prompt Tab -->
|
||||
@@ -340,61 +565,209 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Col 2: Preset Editor -->
|
||||
<!-- Col 2: Presets + Preset Manager (tabbed) -->
|
||||
<div class="wfm-prompt-split-col">
|
||||
<div class="wfm-prompt-split-header">Presets</div>
|
||||
<div class="wfm-preset-panel">
|
||||
<div style="display:flex;gap:6px;margin-bottom:10px;align-items:center;">
|
||||
<select id="wfm-preset-select" class="wfm-select" style="flex:1;">
|
||||
<option value="">New Preset (none selected)</option>
|
||||
</select>
|
||||
<button id="wfm-preset-apply-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">GenUI Set</button>
|
||||
<!-- Center column tab navigation -->
|
||||
<div class="wfm-prompt-center-tabnav">
|
||||
<button class="wfm-prompt-center-tab active" data-ptab="presets">Presets</button>
|
||||
<button class="wfm-prompt-center-tab" data-ptab="manager">Preset Manager</button>
|
||||
</div>
|
||||
|
||||
<!-- Presets pane -->
|
||||
<div id="wfm-ptab-presets" class="wfm-prompt-center-pane">
|
||||
<div class="wfm-preset-panel">
|
||||
<div style="display:flex;gap:6px;margin-bottom:10px;align-items:center;">
|
||||
<select id="wfm-preset-select" class="wfm-select" style="flex:1;">
|
||||
<option value="">New Preset (none selected)</option>
|
||||
</select>
|
||||
<button id="wfm-preset-apply-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">GenUI Set</button>
|
||||
</div>
|
||||
<div class="wfm-form-group">
|
||||
<label>Preset Name</label>
|
||||
<input type="text" id="wfm-preset-name" class="wfm-input" placeholder="Enter preset name...">
|
||||
</div>
|
||||
<div class="wfm-form-group">
|
||||
<label>Category</label>
|
||||
<input type="text" id="wfm-preset-category" class="wfm-input" placeholder="e.g. Portrait, Landscape...">
|
||||
</div>
|
||||
<div class="wfm-form-group" style="flex:1;min-height:0;display:flex;flex-direction:column;">
|
||||
<label>Positive Prompt</label>
|
||||
<textarea id="wfm-preset-pos" class="wfm-textarea" style="flex:1;" placeholder="Positive prompt..."></textarea>
|
||||
</div>
|
||||
<div class="wfm-form-group" style="flex:1;min-height:0;display:flex;flex-direction:column;">
|
||||
<label>Negative Prompt</label>
|
||||
<textarea id="wfm-preset-neg" class="wfm-textarea" style="flex:1;" placeholder="Negative prompt..."></textarea>
|
||||
</div>
|
||||
<div style="display:flex; gap:4px;">
|
||||
<button id="wfm-preset-copy-pos-btn" class="wfm-btn" style="flex:2;" title="Copy Positive Prompt">PP Copy</button>
|
||||
<button id="wfm-preset-copy-neg-btn" class="wfm-btn" style="flex:2;" title="Copy Negative Prompt">NP Copy</button>
|
||||
<button id="wfm-preset-save-btn" class="wfm-btn wfm-btn-primary" style="flex:1;">Save</button>
|
||||
</div>
|
||||
<div style="display:flex; gap:4px; margin-top:4px;">
|
||||
<select id="wfm-preset-group-select" class="wfm-select" style="flex:1;">
|
||||
<option value="">Select group...</option>
|
||||
</select>
|
||||
<button id="wfm-preset-add-to-group-btn" class="wfm-btn wfm-btn-sm">Add to Group</button>
|
||||
<button id="wfm-preset-new-group-btn" class="wfm-btn wfm-btn-sm">+ Group</button>
|
||||
<button id="wfm-preset-del-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" title="Delete selected group">Del Group</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-form-group">
|
||||
<label>Preset Name</label>
|
||||
<input type="text" id="wfm-preset-name" class="wfm-input" placeholder="Enter preset name...">
|
||||
</div>
|
||||
<div class="wfm-form-group">
|
||||
<label>Category</label>
|
||||
<input type="text" id="wfm-preset-category" class="wfm-input" placeholder="e.g. Portrait, Landscape...">
|
||||
</div>
|
||||
<div class="wfm-form-group" style="flex:1;min-height:0;display:flex;flex-direction:column;">
|
||||
<label>Positive Prompt</label>
|
||||
<textarea id="wfm-preset-pos" class="wfm-textarea" style="flex:1;" placeholder="Positive prompt..."></textarea>
|
||||
</div>
|
||||
<div class="wfm-form-group" style="flex:1;min-height:0;display:flex;flex-direction:column;">
|
||||
<label>Negative Prompt</label>
|
||||
<textarea id="wfm-preset-neg" class="wfm-textarea" style="flex:1;" placeholder="Negative prompt..."></textarea>
|
||||
</div>
|
||||
<div style="display:flex; gap:4px;">
|
||||
<button id="wfm-preset-copy-pos-btn" class="wfm-btn" style="flex:2;" title="Copy Positive Prompt">PP Copy</button>
|
||||
<button id="wfm-preset-copy-neg-btn" class="wfm-btn" style="flex:2;" title="Copy Negative Prompt">NP Copy</button>
|
||||
<button id="wfm-preset-save-btn" class="wfm-btn wfm-btn-primary" style="flex:1;">Save</button>
|
||||
</div>
|
||||
<div style="display:flex; gap:4px; margin-top:4px;">
|
||||
<select id="wfm-preset-group-select" class="wfm-select" style="flex:1;">
|
||||
<option value="">Select group...</option>
|
||||
</select>
|
||||
<button id="wfm-preset-add-to-group-btn" class="wfm-btn wfm-btn-sm">Add to Group</button>
|
||||
<button id="wfm-preset-new-group-btn" class="wfm-btn wfm-btn-sm">+ Group</button>
|
||||
<button id="wfm-preset-del-group-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" title="Delete selected group">Del Group</button>
|
||||
</div>
|
||||
|
||||
<!-- Preset Manager pane -->
|
||||
<div id="wfm-ptab-manager" class="wfm-prompt-center-pane" style="display:none;">
|
||||
<div class="wfm-preset-manager">
|
||||
<div class="wfm-pm-tabs">
|
||||
<button class="wfm-pm-tab active" data-pmtab="all">All</button>
|
||||
<button class="wfm-pm-tab" data-pmtab="favorites">★</button>
|
||||
<button class="wfm-pm-tab" data-pmtab="groups">Groups</button>
|
||||
</div>
|
||||
<div class="wfm-pm-search">
|
||||
<input type="text" id="wfm-pm-search-input" class="wfm-input" placeholder="Search presets...">
|
||||
</div>
|
||||
<div id="wfm-pm-list" class="wfm-pm-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Col 3: Preset Manager (list, favorites, groups) -->
|
||||
<!-- Col 3: Wildcard support -->
|
||||
<div class="wfm-prompt-split-col">
|
||||
<div class="wfm-prompt-split-header">Preset Manager</div>
|
||||
<div class="wfm-preset-manager">
|
||||
<div class="wfm-pm-tabs">
|
||||
<button class="wfm-pm-tab active" data-pmtab="all">All</button>
|
||||
<button class="wfm-pm-tab" data-pmtab="favorites">★</button>
|
||||
<button class="wfm-pm-tab" data-pmtab="groups">Groups</button>
|
||||
<div class="wfm-prompt-split-header">Wildcard</div>
|
||||
<div class="wfm-wc-panel">
|
||||
|
||||
<!-- Input assistance section -->
|
||||
<div class="wfm-wc-input-section">
|
||||
<!-- Wildcard syntax buttons -->
|
||||
<div class="wfm-wc-toolbar">
|
||||
<button class="wfm-wc-btn" data-wc-open="{" data-wc-close="}" title="Random pick set e.g. {cat|dog}">{ }</button>
|
||||
<button class="wfm-wc-btn" data-wc-open="|" title="Separator">|</button>
|
||||
<button class="wfm-wc-btn" data-wc-open="__" data-wc-close="__" title="Wildcard file reference e.g. __animals__">__</button>
|
||||
<button class="wfm-wc-btn" data-wc-open=":" title="Colon">:</button>
|
||||
<button class="wfm-wc-btn" data-wc-open=";" title="Semicolon">;</button>
|
||||
<button class="wfm-wc-btn" data-wc-open="$$" title="Multi-pick e.g. {2$$cat|dog|bird}">$$</button>
|
||||
<button class="wfm-wc-btn" data-wc-open="[" data-wc-close="]" title="Bracket set e.g. [cat|dog]">[ ]</button>
|
||||
<button class="wfm-wc-btn" id="wfm-wc-lora-btn" title="LoRA with LBW e.g. <lora:name:1:LBW=...;...>"><lora></button>
|
||||
<button class="wfm-wc-btn" id="wfm-wc-nset-btn" title="Multi-pick set e.g. {2$$cat|dog|bird}">n$${ }</button>
|
||||
<div class="wfm-wc-file-picker-wrap">
|
||||
<button class="wfm-wc-btn" id="wfm-wc-filepick-btn" title="Insert wildcard file reference">📂 File</button>
|
||||
<div id="wfm-wc-file-picker" class="wfm-wc-file-picker" style="display:none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Prompt textarea -->
|
||||
<textarea id="wfm-wc-prompt" class="wfm-textarea wfm-wc-prompt-ta" rows="4" placeholder="Compose wildcard prompt here... e.g. a photo of {cat|dog}, __colors__ background"></textarea>
|
||||
<!-- Action buttons -->
|
||||
<div class="wfm-wc-prompt-actions">
|
||||
<button id="wfm-wc-copy-btn" class="wfm-btn wfm-btn-sm">Copy</button>
|
||||
<button id="wfm-wc-to-pos-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" title="Send to Preset Positive Prompt">→ Pos</button>
|
||||
<button id="wfm-wc-to-neg-btn" class="wfm-btn wfm-btn-sm" title="Send to Preset Negative Prompt">→ Neg</button>
|
||||
<button id="wfm-wc-clear-btn" class="wfm-btn wfm-btn-sm" style="margin-left:auto;">Clear</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-pm-search">
|
||||
<input type="text" id="wfm-pm-search-input" class="wfm-input" placeholder="Search presets...">
|
||||
|
||||
<!-- Wildcard file manager section -->
|
||||
<div class="wfm-wc-files-section">
|
||||
<div class="wfm-wc-files-header">
|
||||
<span class="wfm-wc-files-title">Wildcard Files</span>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<button id="wfm-wc-new-file-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">+ New</button>
|
||||
<button id="wfm-wc-files-refresh-btn" class="wfm-btn wfm-btn-sm" title="Reload file list">↻</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- File list -->
|
||||
<div id="wfm-wc-file-list" class="wfm-wc-file-list">
|
||||
<p class="wfm-placeholder" style="padding:12px;font-size:12px;">Loading...</p>
|
||||
</div>
|
||||
<!-- Editor (shown when a file is selected or New is clicked) -->
|
||||
<div id="wfm-wc-editor" class="wfm-wc-editor" style="display:none;">
|
||||
<div class="wfm-wc-editor-header">
|
||||
<input type="text" id="wfm-wc-editor-name" class="wfm-input" placeholder="name or folder/name" style="flex:1;min-width:0;">
|
||||
<select id="wfm-wc-editor-ext" class="wfm-select" style="width:70px;">
|
||||
<option value="txt">txt</option>
|
||||
<option value="yaml">yaml</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="wfm-wc-editor-hint">
|
||||
txt: one item per line | yaml: key: [item1, item2, ...]
|
||||
</div>
|
||||
<textarea id="wfm-wc-editor-content" class="wfm-textarea wfm-wc-editor-ta" rows="8" placeholder="one item per line (txt) or YAML format (yaml)"></textarea>
|
||||
<div class="wfm-wc-editor-actions">
|
||||
<button id="wfm-wc-editor-save-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">Save</button>
|
||||
<button id="wfm-wc-editor-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" style="display:none;">Delete</button>
|
||||
<button id="wfm-wc-editor-cancel-btn" class="wfm-btn wfm-btn-sm" style="margin-left:auto;">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Metadata Tab -->
|
||||
<section id="wfm-tab-metadata" class="wfm-tab-content">
|
||||
<div class="wfm-metadata-layout">
|
||||
<!-- Col1: Drop zone + preview -->
|
||||
<div class="wfm-metadata-col1">
|
||||
<div class="wfm-metadata-drop-zone" id="wfm-meta-drop">
|
||||
<div class="wfm-meta-drop-label" id="wfm-meta-drop-label">
|
||||
<div class="wfm-meta-drop-main">Drop image / JSON</div>
|
||||
<div class="wfm-meta-drop-sub">PNG · WebP · JSON</div>
|
||||
</div>
|
||||
<img id="wfm-meta-preview-img" class="wfm-meta-preview-img" style="display:none;" alt="preview">
|
||||
</div>
|
||||
<div class="wfm-meta-file-info" id="wfm-meta-file-info"></div>
|
||||
<div class="wfm-meta-format-note" id="wfm-meta-format-note">
|
||||
<div class="wfm-meta-format-note-title" id="wfm-meta-format-note-title">Supported formats</div>
|
||||
<ul class="wfm-meta-format-list">
|
||||
<li id="wfm-meta-fmt-comfyui">ComfyUI — PNG / WebP / JSON</li>
|
||||
<li id="wfm-meta-fmt-sdwebui">SD WebUI / SD Forge — PNG (parameters)</li>
|
||||
<li id="wfm-meta-fmt-fooocus">Fooocus — PNG (fooocus_scheme)</li>
|
||||
</ul>
|
||||
<div class="wfm-meta-format-todo" id="wfm-meta-format-todo">Flux.2 / Qwen-Image / Z-Image subgraph workflows supported</div>
|
||||
</div>
|
||||
<input type="file" id="wfm-meta-file-input" accept="image/png,image/webp,.json,application/json" style="display:none;">
|
||||
</div>
|
||||
|
||||
<!-- Col2: Model info -->
|
||||
<div class="wfm-metadata-col2">
|
||||
<div class="wfm-meta-section" id="wfm-meta-ckpt-section">
|
||||
<div class="wfm-meta-section-title">Checkpoint</div>
|
||||
<div class="wfm-meta-list" id="wfm-meta-ckpt-list"></div>
|
||||
</div>
|
||||
<div class="wfm-meta-section" id="wfm-meta-vae-section">
|
||||
<div class="wfm-meta-section-title">VAE</div>
|
||||
<div class="wfm-meta-list" id="wfm-meta-vae-list"></div>
|
||||
</div>
|
||||
<div class="wfm-meta-section" id="wfm-meta-diff-section">
|
||||
<div class="wfm-meta-section-title">Diffusion Model</div>
|
||||
<div class="wfm-meta-list" id="wfm-meta-diff-list"></div>
|
||||
</div>
|
||||
<div class="wfm-meta-section" id="wfm-meta-te-section">
|
||||
<div class="wfm-meta-section-title">Text Encoder</div>
|
||||
<div class="wfm-meta-list" id="wfm-meta-te-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Col3: LoRA + Prompt -->
|
||||
<div class="wfm-metadata-col3">
|
||||
<div class="wfm-meta-section" id="wfm-meta-lora-section">
|
||||
<div class="wfm-meta-section-title">LoRA</div>
|
||||
<div class="wfm-meta-list" id="wfm-meta-lora-list"></div>
|
||||
</div>
|
||||
<div class="wfm-meta-section wfm-meta-prompt-section" id="wfm-meta-prompt-section">
|
||||
<div class="wfm-meta-section-title">Prompt</div>
|
||||
<div class="wfm-meta-list" id="wfm-meta-prompt-list"></div>
|
||||
<div class="wfm-meta-prompt-full-wrap">
|
||||
<div class="wfm-meta-prompt-full-label" id="wfm-meta-prompt-full-label"></div>
|
||||
<textarea class="wfm-meta-prompt-full" id="wfm-meta-prompt-full" readonly placeholder="Select a prompt above to view full text..."></textarea>
|
||||
<div class="wfm-meta-prompt-actions">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-meta-copy-btn">Copy</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-meta-genui-pos-btn">GenUI:P</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-meta-genui-neg-btn">GenUI:N</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-meta-preset-pos-btn">Prompt:P</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-meta-preset-neg-btn">Prompt:N</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wfm-pm-list" class="wfm-pm-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -430,9 +803,8 @@
|
||||
<li id="wfm-help-wf-3">Create, rename, delete groups and assign/remove workflows</li>
|
||||
<li id="wfm-help-wf-4">Import JSON/PNG files via button or drag & drop</li>
|
||||
<li id="wfm-help-wf-5">Side panel: thumbnail, JSON viewer (format badge: UI/API/App), clipboard copy, group management</li>
|
||||
<li id="wfm-help-wf-6">Detail modal: rename, favorite, thumbnail change, analysis, category override, tags, memo, AI summary, open in ComfyUI, load in GenerateUI, set as default, delete</li>
|
||||
<li id="wfm-help-wf-7">Customize badge colors per category</li>
|
||||
<li id="wfm-help-wf-8">Batch re-analysis of all workflow I/O (P: prompt nodes, I: image nodes, output: save nodes)</li>
|
||||
<li id="wfm-help-wf-6">Detail modal: rename, favorite, thumbnail change, badge assignment, tags, memo, AI summary, open in ComfyUI, load in GenerateUI, set as default, delete</li>
|
||||
<li id="wfm-help-wf-7">Badge management: add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -441,11 +813,31 @@
|
||||
<ul>
|
||||
<li id="wfm-help-gen-1">Connect/disconnect ComfyUI and check connection status</li>
|
||||
<li id="wfm-help-gen-2">Load workflows from Workflow tab (App format .app.json not supported)</li>
|
||||
<li id="wfm-help-gen-3">Edit parameters: Prompt, Image (drag & drop), Model (checkpoint/VAE/LoRA/ControlNet with filter), Settings (steps/CFG/sampler/scheduler/resolution), Raw JSON</li>
|
||||
<li id="wfm-help-gen-4">Seed control: random, fixed, increment, decrement</li>
|
||||
<li id="wfm-help-gen-5">Generate, progress display, and stop</li>
|
||||
<li id="wfm-help-gen-6">View results with main image and thumbnail history</li>
|
||||
<li id="wfm-help-gen-7">Eagle integration: auto-save generated images to Eagle</li>
|
||||
<li id="wfm-help-gen-3">4-tab layout — Input (Prompt + Image), Model, Settings, Feeder — Input/Model/Settings each include a Raw JSON column for instant preview and direct editing</li>
|
||||
<li id="wfm-help-gen-4">Input tab: Prompt (top) and Image drag-and-drop (bottom) in the left column</li>
|
||||
<li id="wfm-help-gen-5">Model tab: Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter</li>
|
||||
<li id="wfm-help-gen-6">Settings tab: KSampler and Latent Image side by side, each at 50% width</li>
|
||||
<li id="wfm-help-gen-7">Raw JSON always visible in the right column of each tab — edit directly and Apply to reload the workflow</li>
|
||||
<li id="wfm-help-gen-8">Seed control: random, fixed, increment, decrement — seed input and mode selector stacked vertically for readability</li>
|
||||
<li id="wfm-help-gen-9">Generate, progress display, stop, and view results</li>
|
||||
<li id="wfm-help-gen-10">Eagle integration: auto-save generated images to Eagle</li>
|
||||
<li id="wfm-help-gen-11">Checkpoint Batch: select checkpoints by folder from the dropdown — check a folder to select all its files, or expand with ▶ to check individual files; use Filter to search; Pause/Resume suspends and continues between models; Stop aborts after the current generation</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-feeder-title">GenerateUI Tab — Feeder subtab</h3>
|
||||
<p id="wfm-help-feeder-desc">Requires the comfyui-image-feeder custom node. Controls ImageFeeder nodes and runs continuous generation loops over an image library stored in user/default/image-loop-data/.</p>
|
||||
<ul>
|
||||
<li id="wfm-help-feeder-1">Left pane — Node settings: select the target ImageFeeder node from the dropdown; edit all node parameters (Directory, Sort Mode, Index, Start/End Index, Batch Size, Seed, Use Selection); click Apply to write changes to the loaded workflow</li>
|
||||
<li id="wfm-help-feeder-2">Left pane — Presets: save the current directory + selection as a named preset; load or delete saved presets</li>
|
||||
<li id="wfm-help-feeder-3">Left pane — Run: After gen mode determines index behavior after each generation — Loop (wrap back to 0 and continue indefinitely), Increment (advance index and stop when all images are exhausted), Fixed (always use the same index); click Run to start the loop, Stop to interrupt</li>
|
||||
<li id="wfm-help-feeder-4">Center pane — Folder tree: browse subfolders inside image-loop-data; click a folder to load its images; click ↺ to reload the tree</li>
|
||||
<li id="wfm-help-feeder-5">Center pane — Image grid: displays thumbnails of all images in the selected folder; check individual images to add them to the selection; All / None buttons select or clear the entire folder; click an image to open the preview panel</li>
|
||||
<li id="wfm-help-feeder-6">Center pane — Preview panel: shows the clicked image at larger size with filename, resolution, and file size</li>
|
||||
<li id="wfm-help-feeder-7">Status bar: shows the current folder path and how many images are selected out of the total in the folder</li>
|
||||
<li id="wfm-help-feeder-8">Seed during Run: uses the right-pane seed setting (Random / Fixed / Increment / Decrement) — the ImageFeeder's own Seed field controls random sort order only</li>
|
||||
<li id="wfm-help-feeder-9">Index sync: after each generation the node returns the next index via WebSocket; the Index field updates automatically so the display stays in sync</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -459,6 +851,20 @@
|
||||
<li id="wfm-help-prompt-5">Preset Manager: browse all presets, favorites, and group-based filtering</li>
|
||||
<li id="wfm-help-prompt-6">Group management: create groups, assign/remove presets, delete groups</li>
|
||||
<li id="wfm-help-prompt-7">GenUI Set: apply preset prompts directly to GenerateUI</li>
|
||||
<li id="wfm-help-prompt-8">Wildcard toolbar: one-click buttons to insert wildcard syntax ({|}, {n$|}, __|__, <lora:>, etc.); wraps selected text</li>
|
||||
<li id="wfm-help-prompt-9">Wildcard file manager: create/edit/delete .txt/.yaml wildcard files; click filename to insert __filename__ at cursor</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-metadata-title">Metadata Tab</h3>
|
||||
<p id="wfm-help-metadata-desc">Drop a ComfyUI-generated PNG/WebP or workflow JSON to instantly extract and view the embedded model and prompt information.</p>
|
||||
<ul>
|
||||
<li id="wfm-help-metadata-1">Left column: drop zone (image preview for PNG/WebP) and file info; click or drop to load</li>
|
||||
<li id="wfm-help-metadata-2">Center column: Checkpoint, VAE, Diffusion Model, and Text Encoder lists extracted from the workflow</li>
|
||||
<li id="wfm-help-metadata-3">Right column: LoRA list (with strength values) and Prompt list (click to view full text below)</li>
|
||||
<li id="wfm-help-metadata-4">Prompt actions — Copy: copy to clipboard; GenUI:P/N: set GenerateUI positive/negative prompt; Prompt:P/N: set Prompt tab preset positive/negative</li>
|
||||
<li id="wfm-help-metadata-5">Supported: ComfyUI PNG/WebP/JSON (standard + Flux.2 / Qwen-Image / Z-Image subgraph workflows), SD WebUI, SD Forge, Fooocus.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -466,11 +872,15 @@
|
||||
<h3>Settings Tab</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-settings-1">UI language and summary language</li>
|
||||
<li id="wfm-help-settings-2">Workflow data folder path</li>
|
||||
<li id="wfm-help-settings-3">ComfyUI connection URL and test</li>
|
||||
<li id="wfm-help-settings-4">Ollama URL, default model, and connection test</li>
|
||||
<li id="wfm-help-settings-5">Default workflow setting</li>
|
||||
<li id="wfm-help-settings-6">Eagle integration URL and auto-save toggle</li>
|
||||
<li id="wfm-help-settings-2">Theme selection (13 presets) with customization: color overrides, background patterns (stripes, polka dot, checkerboard, SVG tiling), and font selection (16 Google Fonts including Japanese display fonts)</li>
|
||||
<li id="wfm-help-settings-3">Workflow data folder path</li>
|
||||
<li id="wfm-help-settings-4">ComfyUI connection URL and test</li>
|
||||
<li id="wfm-help-settings-5">Ollama URL, default model, and connection test</li>
|
||||
<li id="wfm-help-settings-6">Default workflow setting</li>
|
||||
<li id="wfm-help-settings-7">Eagle integration URL and auto-save toggle</li>
|
||||
<li id="wfm-help-settings-8">Data Management: export all plugin data to JSON / import to restore</li>
|
||||
<li id="wfm-help-settings-9">All sections are collapsible accordion panels</li>
|
||||
<li id="wfm-help-settings-10">Wildcard Integration: link WFS wildcard dir to ComfyUI-Impact-Pack wildcards (junction/symlink); existing files migrated automatically</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -486,12 +896,47 @@
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-gallery-title">Gallery Tab</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-gallery-1">Browse images in the ComfyUI output folder — set the folder path in Settings > Gallery Output Folder</li>
|
||||
<li id="wfm-help-gallery-2">3-column layout: folder tree (left) | image grid (center) | detail panel (right)</li>
|
||||
<li id="wfm-help-gallery-3">Thumbnail and Table view modes; double-click any image to open fullscreen lightbox</li>
|
||||
<li id="wfm-help-gallery-4">Toolbar filters: favorites (★), text search, tag filter, group filter, sort by date/name</li>
|
||||
<li id="wfm-help-gallery-5">Folder tree: click to load images, expand with ▶; "+ New" creates a subfolder inside the selected folder, "Del" deletes it with all contents</li>
|
||||
<li id="wfm-help-gallery-6">Multi-select with Ctrl+click — bulk operations: Add to Group, Favorite All, Unfavorite All, Move To..., Delete</li>
|
||||
<li id="wfm-help-gallery-7">Detail panel — Info tab: filename, size, date, tags (add/remove), memo; "Move To..." moves the image to another folder, "Delete" removes it permanently</li>
|
||||
<li id="wfm-help-gallery-8">Detail panel — Metadata tab: displays workflow JSON from PNG embedded data (prompt / workflow keys) or from metadata saved by the Generate UI tab; one-click clipboard copy</li>
|
||||
<li id="wfm-help-gallery-9">Detail panel — Groups tab: create, assign, remove, rename, and delete groups per image</li>
|
||||
<li id="wfm-help-gallery-10">Workflow auto-save: images generated in the Generate UI tab automatically have their workflow saved to gallery metadata and shown in the Metadata tab</li>
|
||||
<li id="wfm-help-gallery-11">Supports PNG (tEXt/iTXt), JPEG, WebP, GIF; workflow extraction reads ComfyUI prompt and workflow keys embedded in PNG metadata</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-card">
|
||||
<h3>Models Tab</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-models-1">Browse installed models: Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding with sub-tab switching</li>
|
||||
<li id="wfm-help-models-2">Thumbnail, Card, and Table view modes with pagination</li>
|
||||
<li id="wfm-help-models-3">Search, tag filter, group filter, favorites filter, and status filter (All / Enabled only / Disabled only)</li>
|
||||
<li id="wfm-help-models-4">Side panel: Info (file path, tags, memo), Groups management, CivitAI integration</li>
|
||||
<li id="wfm-help-models-5">CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type</li>
|
||||
<li id="wfm-help-models-6">Detail modal: preview image, CivitAI info (base model, trained words, tags), thumbnail change</li>
|
||||
<li id="wfm-help-models-7">Group management: create, rename, delete groups and assign/remove models</li>
|
||||
<li id="wfm-help-models-8">GenUI Model button: apply the selected model to the corresponding node in GenerateUI's current workflow (Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)</li>
|
||||
<li id="wfm-help-models-9">User-defined badges: assign free-label badges with custom colors shared with the Workflow tab</li>
|
||||
<li id="wfm-help-models-10">Enable/Disable models: toggle visibility in ComfyUI by renaming file extension (.disabled suffix). Disable per model (⏸ button on each card) or per group (Enable All / Disable All in Group panel). Changes take effect after ComfyUI refresh.</li>
|
||||
<li id="wfm-help-models-11">Multi-select & bulk operations: click Select to enter selection mode, check multiple models, then use the bulk action bar to add/remove from groups or permanently delete files (model file + preview images + sidecar files such as .json/.info).</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-sidepanel-title">Workflow Studio Library (ComfyUI Side Panel)</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-sidepanel-1">Open from the Workflow Studio Library button in the ComfyUI toolbar</li>
|
||||
<li id="wfm-help-sidepanel-2">Workflows tab: browse favorite workflows, filter by model type, and filter by group</li>
|
||||
<li id="wfm-help-sidepanel-3">Nodes tab: browse favorite nodes, node sets, and node groups</li>
|
||||
<li id="wfm-help-sidepanel-2">Workflows tab: All / ★ Favorites / Groups sub-tabs; ★ shown for favorites in All view</li>
|
||||
<li id="wfm-help-sidepanel-3">Nodes tab: All / ★ Favorites / Groups / Sets / 📂 Category / 🧩 Package sub-tabs; Category and Package show a dropdown to filter nodes</li>
|
||||
<li id="wfm-help-sidepanel-11">Models tab: All / ★ Favorites / Groups / By Type sub-tabs</li>
|
||||
<li id="wfm-help-sidepanel-4">Prompts tab: browse prompt presets with All/Favorites/Categories sub-tabs</li>
|
||||
<li id="wfm-help-sidepanel-5">Drag & drop workflows onto the canvas to load them</li>
|
||||
<li id="wfm-help-sidepanel-6">Drag & drop nodes/node sets onto the canvas to place them</li>
|
||||
@@ -499,6 +944,7 @@
|
||||
<li id="wfm-help-sidepanel-8">Copy individual positive (P) or negative (N) prompts from sidebar items</li>
|
||||
<li id="wfm-help-sidepanel-9">Double-click items to load/place without dragging</li>
|
||||
<li id="wfm-help-sidepanel-10">Search within each sub-tab to quickly find items</li>
|
||||
<li id="wfm-help-sidepanel-12">⚙ Theme button (header): customize panel background, text, border colors — saved to localStorage</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -553,6 +999,133 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Gallery Tab -->
|
||||
<section id="wfm-tab-gallery" class="wfm-tab-content">
|
||||
<!-- Toolbar -->
|
||||
<div class="wfm-toolbar">
|
||||
<div class="wfm-toolbar-row" style="gap:6px;flex-wrap:wrap;align-items:center;">
|
||||
<button id="wfm-gallery-fav-btn" class="wfm-filter-btn" title="Favorites">★</button>
|
||||
<input type="text" id="wfm-gallery-search" class="wfm-search-input" placeholder="Search images...">
|
||||
<select id="wfm-gallery-tag-filter" class="wfm-select wfm-toolbar-select">
|
||||
<option value="">All Tags</option>
|
||||
</select>
|
||||
<select id="wfm-gallery-group-filter" class="wfm-select wfm-toolbar-select">
|
||||
<option value="">All Groups</option>
|
||||
</select>
|
||||
<select id="wfm-gallery-sort" class="wfm-select wfm-toolbar-select">
|
||||
<option value="date_desc">Date (Newest)</option>
|
||||
<option value="date_asc">Date (Oldest)</option>
|
||||
<option value="name_asc">Name A-Z</option>
|
||||
<option value="name_desc">Name Z-A</option>
|
||||
</select>
|
||||
<div class="wfm-view-btns">
|
||||
<button class="wfm-view-btn active" data-gallery-view="thumb" title="Thumbnail">⊞</button>
|
||||
<button class="wfm-view-btn" data-gallery-view="table" title="Table">≡</button>
|
||||
</div>
|
||||
<span id="wfm-gallery-count" class="wfm-nodes-count"></span>
|
||||
<button id="wfm-gallery-refresh-btn" class="wfm-btn wfm-btn-sm">Refresh</button>
|
||||
</div>
|
||||
<!-- 複数選択時の一括操作バー -->
|
||||
<div id="wfm-gallery-bulk-bar" class="wfm-gallery-bulk-bar" style="display:none;">
|
||||
<span id="wfm-gallery-bulk-count" class="wfm-gallery-bulk-count"></span>
|
||||
<button id="wfm-gallery-bulk-deselect" class="wfm-btn wfm-btn-sm">Deselect All</button>
|
||||
<select id="wfm-gallery-bulk-group-select" class="wfm-select" style="font-size:12px;padding:3px 6px;">
|
||||
<option value="">Add to Group...</option>
|
||||
</select>
|
||||
<button id="wfm-gallery-bulk-group-add" class="wfm-btn wfm-btn-sm wfm-btn-primary">Add</button>
|
||||
<button id="wfm-gallery-bulk-fav" class="wfm-btn wfm-btn-sm">★ Favorite All</button>
|
||||
<button id="wfm-gallery-bulk-unfav" class="wfm-btn wfm-btn-sm">☆ Unfavorite All</button>
|
||||
<button id="wfm-gallery-bulk-move" class="wfm-btn wfm-btn-sm">Move To...</button>
|
||||
<button id="wfm-gallery-bulk-delete" class="wfm-btn wfm-btn-sm wfm-btn-danger">Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 3カラムレイアウト -->
|
||||
<div class="wfm-gallery-layout">
|
||||
<!-- 左: フォルダツリー -->
|
||||
<div id="wfm-gallery-tree-panel" class="wfm-gallery-tree-panel">
|
||||
<div class="wfm-gallery-tree-header">
|
||||
<span class="wfm-gallery-tree-title">Folders</span>
|
||||
<div class="wfm-gallery-tree-actions">
|
||||
<button id="wfm-gallery-folder-create-btn" class="wfm-btn wfm-btn-sm" title="Create subfolder in selected folder">+ New</button>
|
||||
<button id="wfm-gallery-folder-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" title="Delete selected folder" disabled>Del</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="wfm-gallery-tree" class="wfm-gallery-tree">
|
||||
<p class="wfm-placeholder" id="wfm-gallery-tree-placeholder">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 中: 画像一覧 -->
|
||||
<div id="wfm-gallery-list-panel" class="wfm-gallery-list-panel">
|
||||
<div id="wfm-gallery-grid" class="wfm-gallery-grid wfm-gallery-view-thumb">
|
||||
<p class="wfm-placeholder" id="wfm-gallery-list-placeholder">Select a folder to browse images.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右: 詳細情報サイドパネル -->
|
||||
<div id="wfm-gallery-detail-panel" class="wfm-gallery-detail-panel">
|
||||
<div class="wfm-gallery-detail-header">
|
||||
<span id="wfm-gallery-detail-filename" class="wfm-gallery-detail-filename"></span>
|
||||
</div>
|
||||
<!-- サムネイルプレビュー -->
|
||||
<div id="wfm-gallery-detail-preview" class="wfm-gallery-detail-preview">
|
||||
<span class="wfm-placeholder">No selection</span>
|
||||
</div>
|
||||
<!-- タブナビ -->
|
||||
<div class="wfm-side-tab-nav">
|
||||
<button class="wfm-gallery-detail-tab-btn active" data-detail-tab="info">Info</button>
|
||||
<button class="wfm-gallery-detail-tab-btn" data-detail-tab="meta">Metadata</button>
|
||||
<button class="wfm-gallery-detail-tab-btn" data-detail-tab="group">Groups</button>
|
||||
</div>
|
||||
<!-- Info タブ -->
|
||||
<div id="wfm-gallery-detail-info" class="wfm-gallery-detail-tab-content active">
|
||||
<div class="wfm-gallery-info-section">
|
||||
<div class="wfm-gallery-info-row" id="wfm-gallery-info-name"></div>
|
||||
<div class="wfm-gallery-info-row" id="wfm-gallery-info-size"></div>
|
||||
<div class="wfm-gallery-info-row" id="wfm-gallery-info-date"></div>
|
||||
</div>
|
||||
<hr class="wfm-group-divider">
|
||||
<!-- タグ -->
|
||||
<div class="wfm-gallery-info-section">
|
||||
<div class="wfm-gallery-section-title">Tags</div>
|
||||
<div id="wfm-gallery-tags-display" class="wfm-gallery-tags-display"></div>
|
||||
<div style="display:flex;gap:4px;margin-top:4px;">
|
||||
<input type="text" id="wfm-gallery-tag-input" class="wfm-input" placeholder="Add tag..." style="flex:1;min-width:0;font-size:12px;padding:4px 6px;">
|
||||
<button id="wfm-gallery-tag-add-btn" class="wfm-btn wfm-btn-sm">Add</button>
|
||||
</div>
|
||||
</div>
|
||||
<hr class="wfm-group-divider">
|
||||
<!-- メモ -->
|
||||
<div class="wfm-gallery-info-section">
|
||||
<div class="wfm-gallery-section-title">Memo</div>
|
||||
<textarea id="wfm-gallery-memo" class="wfm-gallery-memo" placeholder="Write a memo..." rows="3"></textarea>
|
||||
<button id="wfm-gallery-memo-save-btn" class="wfm-btn wfm-btn-sm" style="margin-top:4px;width:100%;">Save Memo</button>
|
||||
</div>
|
||||
<hr class="wfm-group-divider">
|
||||
<!-- ファイル操作 -->
|
||||
<div class="wfm-gallery-info-section wfm-gallery-file-actions">
|
||||
<button id="wfm-gallery-img-move-btn" class="wfm-btn wfm-btn-sm" disabled>Move To...</button>
|
||||
<button id="wfm-gallery-img-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" disabled>Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Metadata タブ -->
|
||||
<div id="wfm-gallery-detail-meta" class="wfm-gallery-detail-tab-content wfm-gallery-meta-tab" style="display:none;">
|
||||
<div class="wfm-gallery-meta-toolbar">
|
||||
<span id="wfm-gallery-meta-status" class="wfm-gallery-meta-status"></span>
|
||||
<button id="wfm-gallery-copy-workflow-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" disabled title="Copy embedded workflow JSON">Copy Workflow</button>
|
||||
</div>
|
||||
<pre id="wfm-gallery-workflow-json" class="wfm-gallery-workflow-json">No workflow found in this image.</pre>
|
||||
</div>
|
||||
|
||||
<!-- Group タブ -->
|
||||
<div id="wfm-gallery-detail-group" class="wfm-gallery-detail-tab-content" style="display:none;overflow-y:auto;">
|
||||
<!-- JS動的生成: renderDetailGroup() -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- Workflow Detail Modal -->
|
||||
|
||||
@@ -0,0 +1,818 @@
|
||||
/**
|
||||
* Node Library Sidebar Panel
|
||||
*
|
||||
* Fixed sidebar panel injected into ComfyUI DOM.
|
||||
* Three tabs: Favorites (single nodes), Node Sets (multi-node), Groups.
|
||||
* Items are draggable onto the canvas or click-to-place.
|
||||
*/
|
||||
console.log("[WFM] node_sets_menu.js loading...");
|
||||
import { app } from "../../scripts/app.js";
|
||||
console.log("[WFM] node_sets_menu.js: app imported");
|
||||
|
||||
export const NODE_SETS_TOOLTIP = "Node Library – Browse & drag nodes onto canvas";
|
||||
|
||||
// ============================================
|
||||
// State
|
||||
// ============================================
|
||||
|
||||
const state = {
|
||||
visible: false,
|
||||
activeTab: "favorites", // favorites | sets | groups
|
||||
favorites: [], // [{name, display_name}]
|
||||
nodeSets: [],
|
||||
groups: {}, // {groupName: [nodeName, ...]}
|
||||
metadata: {},
|
||||
searchText: "",
|
||||
loaded: false,
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// API
|
||||
// ============================================
|
||||
|
||||
const fetchNodeSets = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/node-sets");
|
||||
return res.ok ? await res.json() : [];
|
||||
} catch { return []; }
|
||||
};
|
||||
|
||||
const fetchMetadata = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/nodes/metadata");
|
||||
return res.ok ? await res.json() : {};
|
||||
} catch { return {}; }
|
||||
};
|
||||
|
||||
const fetchGroups = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/nodes/groups");
|
||||
return res.ok ? await res.json() : {};
|
||||
} catch { return {}; }
|
||||
};
|
||||
|
||||
const loadData = async () => {
|
||||
const [metadata, nodeSets, groups] = await Promise.all([
|
||||
fetchMetadata(), fetchNodeSets(), fetchGroups(),
|
||||
]);
|
||||
state.metadata = metadata;
|
||||
state.nodeSets = nodeSets;
|
||||
state.groups = groups;
|
||||
|
||||
// Extract favorites from metadata
|
||||
state.favorites = [];
|
||||
for (const [name, meta] of Object.entries(metadata)) {
|
||||
if (name === "_groups") continue;
|
||||
if (meta.favorite) {
|
||||
state.favorites.push({ name, display_name: name });
|
||||
}
|
||||
}
|
||||
state.loaded = true;
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Canvas placement helpers
|
||||
// ============================================
|
||||
|
||||
const getCanvasDropPos = (e) => {
|
||||
const canvas = app.canvas;
|
||||
if (!canvas) return [100, 100];
|
||||
const rect = canvas.canvas.getBoundingClientRect();
|
||||
const x = (e.clientX - rect.left) / canvas.ds.scale - canvas.ds.offset[0];
|
||||
const y = (e.clientY - rect.top) / canvas.ds.scale - canvas.ds.offset[1];
|
||||
return [x, y];
|
||||
};
|
||||
|
||||
const placeSingleNode = (classType, pos) => {
|
||||
const graph = app.graph;
|
||||
if (!graph) return;
|
||||
const node = LiteGraph.createNode(classType);
|
||||
if (!node) {
|
||||
showToast(`Unknown node: ${classType}`, "error");
|
||||
return;
|
||||
}
|
||||
node.pos = pos || [100, 100];
|
||||
graph.add(node);
|
||||
app.canvas.setDirty(true, true);
|
||||
showToast(`Placed: ${node.title || classType}`, "success");
|
||||
};
|
||||
|
||||
const placeNodeSet = (nodeSet, pos) => {
|
||||
const graph = app.graph;
|
||||
const canvas = app.canvas;
|
||||
if (!graph || !canvas) return;
|
||||
|
||||
const nodes = nodeSet.nodes || [];
|
||||
if (nodes.length === 0) return;
|
||||
|
||||
const baseX = pos ? pos[0] : (-canvas.ds.offset[0] + canvas.canvas.width / 2 / canvas.ds.scale);
|
||||
const baseY = pos ? pos[1] : (-canvas.ds.offset[1] + canvas.canvas.height / 2 / canvas.ds.scale);
|
||||
|
||||
const positions = nodes.map(n => n.rel_pos || [0, 0]);
|
||||
const minX = Math.min(...positions.map(p => p[0]));
|
||||
const minY = Math.min(...positions.map(p => p[1]));
|
||||
|
||||
const createdNodes = [];
|
||||
for (const nodeDef of nodes) {
|
||||
if (!nodeDef.class_type) { createdNodes.push(null); continue; }
|
||||
const node = LiteGraph.createNode(nodeDef.class_type);
|
||||
if (!node) { createdNodes.push(null); continue; }
|
||||
const rp = nodeDef.rel_pos || [0, 0];
|
||||
node.pos = [baseX + rp[0] - minX, baseY + rp[1] - minY];
|
||||
if (nodeDef.title) node.title = nodeDef.title;
|
||||
if (nodeDef.widget_values && node.widgets) {
|
||||
for (const [k, v] of Object.entries(nodeDef.widget_values)) {
|
||||
const w = node.widgets.find(ww => ww.name === k);
|
||||
if (w) w.value = v;
|
||||
}
|
||||
}
|
||||
graph.add(node);
|
||||
createdNodes.push(node);
|
||||
}
|
||||
|
||||
for (const link of (nodeSet.links || [])) {
|
||||
const from = createdNodes[link.from_node];
|
||||
const to = createdNodes[link.to_node];
|
||||
if (from && to) {
|
||||
try { from.connect(link.from_slot ?? 0, to, link.to_slot ?? 0); } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
canvas.setDirty(true, true);
|
||||
showToast(`Placed "${nodeSet.name}" (${createdNodes.filter(Boolean).length} nodes)`, "success");
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Drag & Drop onto canvas
|
||||
// ============================================
|
||||
|
||||
let dropHandlerInstalled = false;
|
||||
|
||||
const installCanvasDropHandler = () => {
|
||||
if (dropHandlerInstalled) return;
|
||||
dropHandlerInstalled = true;
|
||||
|
||||
const canvasEl = document.getElementById("graph-canvas");
|
||||
if (!canvasEl) return;
|
||||
|
||||
canvasEl.addEventListener("dragover", (e) => {
|
||||
if (e.dataTransfer.types.includes("application/x-wfm-node")) {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "copy";
|
||||
}
|
||||
});
|
||||
|
||||
canvasEl.addEventListener("drop", (e) => {
|
||||
const raw = e.dataTransfer.getData("application/x-wfm-node");
|
||||
if (!raw) return;
|
||||
e.preventDefault();
|
||||
|
||||
const data = JSON.parse(raw);
|
||||
const pos = getCanvasDropPos(e);
|
||||
|
||||
if (data.type === "single") {
|
||||
placeSingleNode(data.classType, pos);
|
||||
} else if (data.type === "set") {
|
||||
const set = state.nodeSets.find(s => s.id === data.setId);
|
||||
if (set) placeNodeSet(set, pos);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Sidebar Panel DOM
|
||||
// ============================================
|
||||
|
||||
let panelEl = null;
|
||||
|
||||
const PANEL_ID = "wfm-node-library-panel";
|
||||
|
||||
const createPanel = () => {
|
||||
if (panelEl) return panelEl;
|
||||
|
||||
const panel = document.createElement("div");
|
||||
panel.id = PANEL_ID;
|
||||
panel.innerHTML = `
|
||||
<div class="wfm-nlp-header">
|
||||
<span class="wfm-nlp-title">Node Library</span>
|
||||
<button class="wfm-nlp-refresh" title="Refresh">↻</button>
|
||||
<button class="wfm-nlp-close" title="Close">×</button>
|
||||
</div>
|
||||
<div class="wfm-nlp-tabs">
|
||||
<button class="wfm-nlp-tab active" data-tab="favorites">★ Favorites</button>
|
||||
<button class="wfm-nlp-tab" data-tab="sets">☰ Sets</button>
|
||||
<button class="wfm-nlp-tab" data-tab="groups">📁 Groups</button>
|
||||
</div>
|
||||
<div class="wfm-nlp-search">
|
||||
<input type="text" class="wfm-nlp-search-input" placeholder="Search...">
|
||||
</div>
|
||||
<div class="wfm-nlp-content"></div>
|
||||
`;
|
||||
|
||||
document.body.appendChild(panel);
|
||||
panelEl = panel;
|
||||
|
||||
// Tab switching
|
||||
panel.querySelectorAll(".wfm-nlp-tab").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
state.activeTab = btn.dataset.tab;
|
||||
panel.querySelectorAll(".wfm-nlp-tab").forEach(b => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
renderContent();
|
||||
});
|
||||
});
|
||||
|
||||
// Close
|
||||
panel.querySelector(".wfm-nlp-close").addEventListener("click", () => togglePanel());
|
||||
|
||||
// Search
|
||||
panel.querySelector(".wfm-nlp-search-input").addEventListener("input", (e) => {
|
||||
state.searchText = e.target.value.toLowerCase().trim();
|
||||
renderContent();
|
||||
});
|
||||
|
||||
// Refresh
|
||||
panel.querySelector(".wfm-nlp-refresh").addEventListener("click", async () => {
|
||||
await loadData();
|
||||
renderContent();
|
||||
showToast("Node Library refreshed", "success");
|
||||
});
|
||||
|
||||
injectStyles();
|
||||
return panel;
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Render content
|
||||
// ============================================
|
||||
|
||||
const renderContent = () => {
|
||||
const content = panelEl?.querySelector(".wfm-nlp-content");
|
||||
if (!content) return;
|
||||
|
||||
if (!state.loaded) {
|
||||
content.innerHTML = `<div class="wfm-nlp-empty">Loading...</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (state.activeTab) {
|
||||
case "favorites": renderFavorites(content); break;
|
||||
case "sets": renderSets(content); break;
|
||||
case "groups": renderGroups(content); break;
|
||||
}
|
||||
};
|
||||
|
||||
const renderFavorites = (container) => {
|
||||
let items = state.favorites;
|
||||
if (state.searchText) {
|
||||
items = items.filter(n => n.name.toLowerCase().includes(state.searchText));
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">
|
||||
${state.favorites.length === 0 ? "No favorites yet.<br><small>Star nodes in Workflow Studio → Nodes tab</small>" : "No matches"}
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = "";
|
||||
for (const node of items) {
|
||||
const el = createDraggableItem(node.display_name || node.name, "single", { classType: node.name });
|
||||
el.addEventListener("dblclick", () => {
|
||||
placeSingleNode(node.name);
|
||||
});
|
||||
container.appendChild(el);
|
||||
}
|
||||
};
|
||||
|
||||
const renderSets = (container) => {
|
||||
let items = state.nodeSets;
|
||||
if (state.searchText) {
|
||||
items = items.filter(s =>
|
||||
s.name.toLowerCase().includes(state.searchText) ||
|
||||
(s.tags || []).some(t => t.toLowerCase().includes(state.searchText))
|
||||
);
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">
|
||||
${state.nodeSets.length === 0 ? "No node sets.<br><small>Create sets in Workflow Studio → Nodes tab</small>" : "No matches"}
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = "";
|
||||
for (const set of items) {
|
||||
const count = (set.nodes || []).length;
|
||||
const el = createDraggableItem(
|
||||
`${esc(set.name)} <span class="wfm-nlp-badge">${count} nodes</span>`,
|
||||
"set",
|
||||
{ setId: set.id },
|
||||
set.description
|
||||
);
|
||||
el.addEventListener("dblclick", () => {
|
||||
placeNodeSet(set);
|
||||
});
|
||||
container.appendChild(el);
|
||||
}
|
||||
};
|
||||
|
||||
const renderGroups = (container) => {
|
||||
const groupNames = Object.keys(state.groups).sort();
|
||||
|
||||
if (groupNames.length === 0) {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">
|
||||
No groups.<br><small>Create groups in Workflow Studio → Nodes tab</small>
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
let filtered = groupNames;
|
||||
if (state.searchText) {
|
||||
filtered = groupNames.filter(g =>
|
||||
g.toLowerCase().includes(state.searchText) ||
|
||||
(state.groups[g] || []).some(n => n.toLowerCase().includes(state.searchText))
|
||||
);
|
||||
}
|
||||
|
||||
container.innerHTML = "";
|
||||
for (const groupName of filtered) {
|
||||
const nodes = state.groups[groupName] || [];
|
||||
|
||||
const section = document.createElement("div");
|
||||
section.className = "wfm-nlp-group-section";
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "wfm-nlp-group-header";
|
||||
header.innerHTML = `<span>${esc(groupName)}</span> <span class="wfm-nlp-badge">${nodes.length}</span>`;
|
||||
header.addEventListener("click", () => {
|
||||
const list = section.querySelector(".wfm-nlp-group-list");
|
||||
list.style.display = list.style.display === "none" ? "block" : "none";
|
||||
header.classList.toggle("collapsed");
|
||||
});
|
||||
section.appendChild(header);
|
||||
|
||||
const list = document.createElement("div");
|
||||
list.className = "wfm-nlp-group-list";
|
||||
for (const nodeName of nodes) {
|
||||
const el = createDraggableItem(nodeName, "single", { classType: nodeName });
|
||||
el.addEventListener("dblclick", () => placeSingleNode(nodeName));
|
||||
list.appendChild(el);
|
||||
}
|
||||
section.appendChild(list);
|
||||
container.appendChild(section);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Draggable item factory
|
||||
// ============================================
|
||||
|
||||
const createDraggableItem = (label, type, data, subtitle) => {
|
||||
const el = document.createElement("div");
|
||||
el.className = "wfm-nlp-item";
|
||||
el.draggable = true;
|
||||
el.innerHTML = `
|
||||
<div class="wfm-nlp-item-label">${label}</div>
|
||||
${subtitle ? `<div class="wfm-nlp-item-sub">${esc(subtitle)}</div>` : ""}
|
||||
`;
|
||||
|
||||
el.addEventListener("dragstart", (e) => {
|
||||
e.dataTransfer.effectAllowed = "copy";
|
||||
e.dataTransfer.setData("application/x-wfm-node", JSON.stringify({ type, ...data }));
|
||||
el.classList.add("dragging");
|
||||
});
|
||||
|
||||
el.addEventListener("dragend", () => {
|
||||
el.classList.remove("dragging");
|
||||
});
|
||||
|
||||
return el;
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Toggle & exports
|
||||
// ============================================
|
||||
|
||||
export const togglePanel = async () => {
|
||||
const panel = createPanel();
|
||||
state.visible = !state.visible;
|
||||
panel.style.display = state.visible ? "flex" : "none";
|
||||
|
||||
if (state.visible && !state.loaded) {
|
||||
await loadData();
|
||||
renderContent();
|
||||
}
|
||||
|
||||
installCanvasDropHandler();
|
||||
};
|
||||
|
||||
export const getNodeSetsIcon = () => `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
|
||||
<rect x="3" y="3" width="7" height="7" rx="1"/>
|
||||
<rect x="14" y="3" width="7" height="7" rx="1"/>
|
||||
<rect x="3" y="14" width="7" height="7" rx="1"/>
|
||||
<path d="M17.5 14v7M14 17.5h7"/>
|
||||
</svg>
|
||||
`;
|
||||
|
||||
// ============================================
|
||||
// Toast
|
||||
// ============================================
|
||||
|
||||
const showToast = (message, type = "info") => {
|
||||
const existing = document.getElementById("wfm-ns-toast");
|
||||
if (existing) existing.remove();
|
||||
|
||||
const toast = document.createElement("div");
|
||||
toast.id = "wfm-ns-toast";
|
||||
const colors = {
|
||||
success: { bg: "rgba(46,213,115,0.95)" },
|
||||
error: { bg: "rgba(255,71,87,0.95)" },
|
||||
info: { bg: "rgba(74,158,255,0.95)" },
|
||||
};
|
||||
Object.assign(toast.style, {
|
||||
position: "fixed", bottom: "24px", left: "50%", transform: "translateX(-50%)",
|
||||
padding: "10px 24px", background: (colors[type] || colors.info).bg, color: "#fff",
|
||||
borderRadius: "8px", fontSize: "14px", fontWeight: "500", zIndex: "99999",
|
||||
boxShadow: "0 4px 16px rgba(0,0,0,0.3)", transition: "opacity 0.3s", whiteSpace: "nowrap",
|
||||
});
|
||||
toast.textContent = message;
|
||||
document.body.appendChild(toast);
|
||||
setTimeout(() => { toast.style.opacity = "0"; setTimeout(() => toast.remove(), 300); }, 3000);
|
||||
};
|
||||
|
||||
const esc = (s) => s ? String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """) : "";
|
||||
|
||||
// ============================================
|
||||
// Save selected nodes as Node Set (context menu)
|
||||
// ============================================
|
||||
|
||||
const saveSelectedAsNodeSet = async () => {
|
||||
const selectedNodes = Object.values(app.canvas.selected_nodes || {});
|
||||
if (selectedNodes.length === 0) {
|
||||
showToast("Select at least one node first", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Prompt for name
|
||||
const name = prompt("Node Set name:");
|
||||
if (!name || !name.trim()) return;
|
||||
|
||||
// Build node list with relative positions
|
||||
// Use the top-left of the bounding box as origin
|
||||
const minX = Math.min(...selectedNodes.map(n => n.pos[0]));
|
||||
const minY = Math.min(...selectedNodes.map(n => n.pos[1]));
|
||||
|
||||
const nodeIdToIndex = new Map();
|
||||
const nodes = [];
|
||||
selectedNodes.forEach((node, i) => {
|
||||
nodeIdToIndex.set(node.id, i);
|
||||
nodes.push({
|
||||
class_type: node.type || node.comfyClass || "",
|
||||
title: node.title || "",
|
||||
rel_pos: [Math.round(node.pos[0] - minX), Math.round(node.pos[1] - minY)],
|
||||
});
|
||||
});
|
||||
|
||||
// Extract links between selected nodes
|
||||
const links = [];
|
||||
const graph = app.graph;
|
||||
|
||||
for (const node of selectedNodes) {
|
||||
if (!node.inputs) continue;
|
||||
for (let slotIdx = 0; slotIdx < node.inputs.length; slotIdx++) {
|
||||
const input = node.inputs[slotIdx];
|
||||
if (input.link == null) continue;
|
||||
|
||||
// Resolve link data
|
||||
let linkData = null;
|
||||
if (graph.links instanceof Map) {
|
||||
linkData = graph.links.get(input.link);
|
||||
} else if (graph.links) {
|
||||
linkData = graph.links[input.link];
|
||||
}
|
||||
if (!linkData) continue;
|
||||
|
||||
// linkData: [id, origin_id, origin_slot, target_id, target_slot, type]
|
||||
// or object with .origin_id, .origin_slot, etc.
|
||||
const originId = linkData.origin_id ?? linkData[1];
|
||||
const originSlot = linkData.origin_slot ?? linkData[2];
|
||||
const targetSlot = linkData.target_slot ?? linkData[4];
|
||||
|
||||
// Only include if both source and target are in the selection
|
||||
if (nodeIdToIndex.has(originId) && nodeIdToIndex.has(node.id)) {
|
||||
links.push({
|
||||
from_node: nodeIdToIndex.get(originId),
|
||||
from_slot: originSlot,
|
||||
to_node: nodeIdToIndex.get(node.id),
|
||||
to_slot: targetSlot,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save via API
|
||||
try {
|
||||
const res = await fetch("/api/wfm/node-sets", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: name.trim(), description: "", tags: [], nodes, links }),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.status === "ok") {
|
||||
showToast(`Node Set "${name.trim()}" saved (${nodes.length} nodes, ${links.length} links)`, "success");
|
||||
// Refresh sidebar if open
|
||||
if (state.loaded) {
|
||||
await loadData();
|
||||
renderContent();
|
||||
}
|
||||
} else {
|
||||
showToast("Failed to save: " + (result.error || "Unknown error"), "error");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("Failed to save: " + err.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
// Register context menu item on all nodes
|
||||
app.registerExtension({
|
||||
name: "WorkflowStudio.NodeSetContextMenu",
|
||||
beforeRegisterNodeDef(nodeType, _nodeData, _app) {
|
||||
const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
|
||||
nodeType.prototype.getExtraMenuOptions = function(_, options) {
|
||||
origGetExtraMenuOptions?.apply(this, arguments);
|
||||
|
||||
const selectedCount = Object.keys(app.canvas.selected_nodes || {}).length;
|
||||
|
||||
// Add separator + menu item
|
||||
options.push(null);
|
||||
options.push({
|
||||
content: `Save as Node Set${selectedCount > 1 ? ` (${selectedCount} nodes)` : ""}`,
|
||||
callback: saveSelectedAsNodeSet,
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// ============================================
|
||||
// Styles
|
||||
// ============================================
|
||||
|
||||
const injectStyles = () => {
|
||||
if (document.getElementById("wfm-nlp-styles")) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = "wfm-nlp-styles";
|
||||
style.textContent = `
|
||||
#${PANEL_ID} {
|
||||
position: fixed;
|
||||
right: 0;
|
||||
top: 0;
|
||||
width: 280px;
|
||||
height: 100vh;
|
||||
background: var(--comfy-menu-bg, #1e1e1e);
|
||||
border-left: 1px solid var(--border-color, #4e4e4e);
|
||||
z-index: 9999;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
font-family: sans-serif;
|
||||
font-size: 13px;
|
||||
color: var(--input-text, #ddd);
|
||||
box-shadow: -4px 0 16px rgba(0,0,0,0.3);
|
||||
}
|
||||
.wfm-nlp-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--border-color, #4e4e4e);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wfm-nlp-title {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
flex: 1;
|
||||
}
|
||||
.wfm-nlp-close {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--input-text, #ddd);
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
padding: 0 4px;
|
||||
opacity: 0.6;
|
||||
}
|
||||
.wfm-nlp-close:hover { opacity: 1; }
|
||||
.wfm-nlp-tabs {
|
||||
display: flex;
|
||||
border-bottom: 1px solid var(--border-color, #4e4e4e);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wfm-nlp-tab {
|
||||
flex: 1;
|
||||
padding: 8px 4px;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--input-text, #ddd);
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
opacity: 0.6;
|
||||
transition: all 0.15s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.wfm-nlp-tab:hover { opacity: 0.9; }
|
||||
.wfm-nlp-tab.active {
|
||||
opacity: 1;
|
||||
border-bottom-color: var(--p-button-background, #4a9eff);
|
||||
}
|
||||
.wfm-nlp-search {
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--border-color, #4e4e4e);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wfm-nlp-search-input {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
background: var(--comfy-input-bg, #2a2a2a);
|
||||
border: 1px solid var(--border-color, #4e4e4e);
|
||||
border-radius: 4px;
|
||||
color: var(--input-text, #ddd);
|
||||
font-size: 12px;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.wfm-nlp-search-input:focus {
|
||||
border-color: var(--p-button-background, #4a9eff);
|
||||
}
|
||||
.wfm-nlp-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 4px 0;
|
||||
}
|
||||
.wfm-nlp-empty {
|
||||
padding: 24px 16px;
|
||||
text-align: center;
|
||||
color: var(--descrip-text, #999);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.wfm-nlp-item {
|
||||
padding: 7px 12px;
|
||||
cursor: grab;
|
||||
border-bottom: 1px solid var(--border-color, #3a3a3a);
|
||||
transition: background 0.12s;
|
||||
user-select: none;
|
||||
}
|
||||
.wfm-nlp-item:hover {
|
||||
background: var(--comfy-input-bg, #333);
|
||||
}
|
||||
.wfm-nlp-item.dragging {
|
||||
opacity: 0.5;
|
||||
background: var(--comfy-input-bg, #333);
|
||||
}
|
||||
.wfm-nlp-item-label {
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.wfm-nlp-item-sub {
|
||||
font-size: 10px;
|
||||
color: var(--descrip-text, #888);
|
||||
margin-top: 2px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.wfm-nlp-badge {
|
||||
display: inline-block;
|
||||
font-size: 10px;
|
||||
padding: 1px 5px;
|
||||
background: var(--comfy-input-bg, #444);
|
||||
border-radius: 3px;
|
||||
color: var(--descrip-text, #aaa);
|
||||
margin-left: 4px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.wfm-nlp-group-section {
|
||||
border-bottom: 1px solid var(--border-color, #3a3a3a);
|
||||
}
|
||||
.wfm-nlp-group-header {
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
transition: background 0.12s;
|
||||
}
|
||||
.wfm-nlp-group-header:hover {
|
||||
background: var(--comfy-input-bg, #333);
|
||||
}
|
||||
.wfm-nlp-group-header::before {
|
||||
content: "\\25BC";
|
||||
font-size: 8px;
|
||||
margin-right: 6px;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.wfm-nlp-group-header.collapsed::before {
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
.wfm-nlp-group-list {
|
||||
padding-left: 8px;
|
||||
}
|
||||
.wfm-nlp-group-list .wfm-nlp-item {
|
||||
padding: 5px 12px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.wfm-nlp-refresh {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--input-text, #ddd);
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.wfm-nlp-refresh:hover { opacity: 1; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Context Menu — Save selected nodes as Node Set
|
||||
// ============================================
|
||||
|
||||
const saveSelectedAsNodeSet = async () => {
|
||||
const selectedNodes = Object.values(app.canvas.selected_nodes || {});
|
||||
if (selectedNodes.length === 0) {
|
||||
showToast("Select at least one node first", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const name = prompt("Node Set name:");
|
||||
if (!name || !name.trim()) return;
|
||||
|
||||
const minX = Math.min(...selectedNodes.map(n => n.pos[0]));
|
||||
const minY = Math.min(...selectedNodes.map(n => n.pos[1]));
|
||||
|
||||
const nodeIdToIndex = new Map();
|
||||
const nodes = [];
|
||||
selectedNodes.forEach((node, i) => {
|
||||
nodeIdToIndex.set(node.id, i);
|
||||
nodes.push({
|
||||
class_type: node.type || node.comfyClass || "",
|
||||
title: node.title || "",
|
||||
rel_pos: [Math.round(node.pos[0] - minX), Math.round(node.pos[1] - minY)],
|
||||
});
|
||||
});
|
||||
|
||||
const links = [];
|
||||
const graph = app.graph;
|
||||
for (const node of selectedNodes) {
|
||||
if (!node.inputs) continue;
|
||||
for (let slotIdx = 0; slotIdx < node.inputs.length; slotIdx++) {
|
||||
const input = node.inputs[slotIdx];
|
||||
if (input.link == null) continue;
|
||||
|
||||
let linkData = null;
|
||||
if (graph.links instanceof Map) {
|
||||
linkData = graph.links.get(input.link);
|
||||
} else if (graph.links) {
|
||||
linkData = graph.links[input.link];
|
||||
}
|
||||
if (!linkData) continue;
|
||||
|
||||
const originId = linkData.origin_id ?? linkData[1];
|
||||
const originSlot = linkData.origin_slot ?? linkData[2];
|
||||
const targetSlot = linkData.target_slot ?? linkData[4];
|
||||
|
||||
if (nodeIdToIndex.has(originId) && nodeIdToIndex.has(node.id)) {
|
||||
links.push({
|
||||
from_node: nodeIdToIndex.get(originId),
|
||||
from_slot: originSlot,
|
||||
to_node: nodeIdToIndex.get(node.id),
|
||||
to_slot: targetSlot,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/wfm/node-sets", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: name.trim(), description: "", tags: [], nodes, links }),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.status === "ok") {
|
||||
showToast(`Node Set "${name.trim()}" saved (${nodes.length} nodes, ${links.length} links)`, "success");
|
||||
if (state.loaded) { await loadData(); renderContent(); }
|
||||
} else {
|
||||
showToast("Failed to save: " + (result.error || "Unknown error"), "error");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("Failed to save: " + err.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
export { saveSelectedAsNodeSet };
|
||||
@@ -605,51 +605,50 @@ app.registerExtension({
|
||||
};
|
||||
injectStyles();
|
||||
|
||||
const replaceButtonIcon = () => {
|
||||
const wfmButtons = document.querySelectorAll(`button[aria-label="${BUTTON_TOOLTIP}"]`);
|
||||
wfmButtons.forEach((button) => {
|
||||
button.classList.add("wfm-top-menu-button");
|
||||
button.innerHTML = getWfmIcon();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
button.style.backgroundColor = "var(--primary-bg)";
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
});
|
||||
|
||||
const snapButtons = document.querySelectorAll(`button[aria-label="${SNAPSHOT_TOOLTIP}"]`);
|
||||
snapButtons.forEach((button) => {
|
||||
button.classList.add("wfm-snapshot-button");
|
||||
button.innerHTML = getSnapshotIcon();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
});
|
||||
|
||||
const nsButtons = document.querySelectorAll(`button[aria-label="${NODE_SETS_TOOLTIP}"]`);
|
||||
nsButtons.forEach((button) => {
|
||||
button.classList.add("wfm-node-sets-btn");
|
||||
button.innerHTML = getNodeSetsIcon();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
});
|
||||
|
||||
if (wfmButtons.length === 0) {
|
||||
requestAnimationFrame(replaceButtonIcon);
|
||||
const applyButtonIcon = (button, className, getIconFn, extraStyles) => {
|
||||
if (button.querySelector("svg")) return;
|
||||
button.classList.add(className);
|
||||
button.innerHTML = getIconFn();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
if (extraStyles) Object.assign(button.style, extraStyles);
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(replaceButtonIcon);
|
||||
|
||||
const buttonConfigs = [
|
||||
{ tooltip: BUTTON_TOOLTIP, className: "wfm-top-menu-button", getIcon: getWfmIcon, styles: { backgroundColor: "var(--primary-bg)" } },
|
||||
{ tooltip: SNAPSHOT_TOOLTIP, className: "wfm-snapshot-button", getIcon: getSnapshotIcon, styles: null },
|
||||
{ tooltip: NODE_SETS_TOOLTIP, className: "wfm-node-sets-btn", getIcon: getNodeSetsIcon, styles: null },
|
||||
];
|
||||
|
||||
const replaceAllIcons = () => {
|
||||
for (const cfg of buttonConfigs) {
|
||||
document.querySelectorAll(`button[aria-label="${cfg.tooltip}"]`).forEach((btn) => {
|
||||
applyButtonIcon(btn, cfg.className, cfg.getIcon, cfg.styles);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const waitAndObserve = () => {
|
||||
const firstBtn = document.querySelector(`button[aria-label="${BUTTON_TOOLTIP}"]`);
|
||||
if (!firstBtn) {
|
||||
requestAnimationFrame(waitAndObserve);
|
||||
return;
|
||||
}
|
||||
replaceAllIcons();
|
||||
|
||||
const container = firstBtn.closest(".actionbar-container") || firstBtn.parentElement;
|
||||
if (container) {
|
||||
new MutationObserver(() => replaceAllIcons()).observe(container, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(waitAndObserve);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
console.log("[WFM] top_menu_extension.js loading...");
|
||||
import { app } from "../../scripts/app.js";
|
||||
console.log("[WFM] app imported:", !!app);
|
||||
import { togglePanel, getNodeSetsIcon, NODE_SETS_TOOLTIP, saveSelectedAsNodeSet } from "./node_sets_menu.js";
|
||||
console.log("[WFM] node_sets_menu imports loaded");
|
||||
|
||||
const BUTTON_TOOLTIP = "Launch Workflow Studio (Shift+Click opens in new window)";
|
||||
const SNAPSHOT_TOOLTIP = "Save workflow canvas image as thumbnail";
|
||||
const WFM_PATH = "/wfm";
|
||||
const NEW_WINDOW_FEATURES = "width=1400,height=900,resizable=yes,scrollbars=yes,status=yes";
|
||||
const MAX_ATTACH_ATTEMPTS = 120;
|
||||
const BUTTON_GROUP_CLASS = "wfm-top-menu-group";
|
||||
|
||||
const MIN_VERSION_FOR_ACTION_BAR = [1, 33, 9];
|
||||
|
||||
const openWorkflowStudio = (event) => {
|
||||
const url = `${window.location.origin}${WFM_PATH}`;
|
||||
|
||||
if (event.shiftKey) {
|
||||
window.open(url, "_blank", NEW_WINDOW_FEATURES);
|
||||
return;
|
||||
}
|
||||
|
||||
window.open(url, "_blank");
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Canvas Snapshot - Export workflow as PNG thumbnail
|
||||
// ============================================
|
||||
|
||||
const getWorkflowFilename = () => {
|
||||
const now = new Date();
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
||||
return `wf_${stamp}.json`;
|
||||
};
|
||||
|
||||
// ---- PNG tEXt chunk embedding helpers ----
|
||||
|
||||
const n2b = (n) => new Uint8Array([(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);
|
||||
|
||||
const joinArrayBuffer = (...bufs) => {
|
||||
const result = new Uint8Array(bufs.reduce((total, buf) => total + buf.byteLength, 0));
|
||||
bufs.reduce((offset, buf) => {
|
||||
result.set(buf, offset);
|
||||
return offset + buf.byteLength;
|
||||
}, 0);
|
||||
return result;
|
||||
};
|
||||
|
||||
let _crcTable = null;
|
||||
const crc32 = (data) => {
|
||||
if (!_crcTable) {
|
||||
_crcTable = [];
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
}
|
||||
_crcTable[n] = c;
|
||||
}
|
||||
}
|
||||
let crc = 0 ^ -1;
|
||||
for (let i = 0; i < data.byteLength; i++) {
|
||||
crc = (crc >>> 8) ^ _crcTable[(crc ^ data[i]) & 0xff];
|
||||
}
|
||||
return (crc ^ -1) >>> 0;
|
||||
};
|
||||
|
||||
const embedWorkflowInPng = async (blob, workflowJson) => {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const typedArr = new Uint8Array(buffer);
|
||||
const view = new DataView(buffer);
|
||||
|
||||
// Create tEXt chunk: "tEXtworkflow\0{json}"
|
||||
const data = new TextEncoder().encode(`tEXtworkflow\0${workflowJson}`);
|
||||
const chunk = joinArrayBuffer(n2b(data.byteLength - 4), data, n2b(crc32(data)));
|
||||
|
||||
// Insert after IHDR chunk (8-byte signature + IHDR length field(4) + IHDR type(4) + IHDR data + CRC(4))
|
||||
const ihdrDataLen = view.getUint32(8);
|
||||
const sz = ihdrDataLen + 20; // 8(sig) + 4(len) + 4(type) + ihdrDataLen + 4(crc)
|
||||
const result = joinArrayBuffer(typedArr.subarray(0, sz), chunk, typedArr.subarray(sz));
|
||||
|
||||
return new Blob([result], { type: "image/png" });
|
||||
};
|
||||
|
||||
// ---- Canvas capture ----
|
||||
|
||||
const captureCanvasSnapshot = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const graph = app.graph;
|
||||
const canvas = app.canvas;
|
||||
if (!graph || !canvas || !graph._nodes?.length) {
|
||||
reject(new Error("No workflow loaded"));
|
||||
return;
|
||||
}
|
||||
|
||||
// Serialize workflow data before changing canvas state
|
||||
const workflowJson = JSON.stringify(graph.serialize());
|
||||
|
||||
// Calculate bounds of all nodes
|
||||
const bounds = graph._nodes.reduce(
|
||||
(p, n) => {
|
||||
if (n.pos[0] < p[0]) p[0] = n.pos[0];
|
||||
if (n.pos[1] < p[1]) p[1] = n.pos[1];
|
||||
const b = n.getBounding();
|
||||
const r = n.pos[0] + b[2];
|
||||
const bot = n.pos[1] + b[3];
|
||||
if (r > p[2]) p[2] = r;
|
||||
if (bot > p[3]) p[3] = bot;
|
||||
return p;
|
||||
},
|
||||
[99999, 99999, -99999, -99999]
|
||||
);
|
||||
|
||||
// Add padding
|
||||
const padding = 80;
|
||||
bounds[0] -= padding;
|
||||
bounds[1] -= padding;
|
||||
bounds[2] += padding;
|
||||
bounds[3] += padding;
|
||||
|
||||
// Save current canvas state
|
||||
const savedState = {
|
||||
scale: canvas.ds.scale,
|
||||
width: canvas.canvas.width,
|
||||
height: canvas.canvas.height,
|
||||
offset: [...canvas.ds.offset],
|
||||
transform: canvas.canvas.getContext("2d").getTransform(),
|
||||
};
|
||||
|
||||
// Set canvas to render full workflow
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
canvas.ds.scale = 1;
|
||||
canvas.canvas.width = (bounds[2] - bounds[0]) * dpr;
|
||||
canvas.canvas.height = (bounds[3] - bounds[1]) * dpr;
|
||||
canvas.ds.offset = [-bounds[0], -bounds[1]];
|
||||
canvas.canvas.getContext("2d").setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
|
||||
// Render
|
||||
canvas.draw(true, true);
|
||||
|
||||
// Capture to blob
|
||||
canvas.canvas.toBlob(async (rawBlob) => {
|
||||
// Restore canvas state
|
||||
canvas.ds.scale = savedState.scale;
|
||||
canvas.canvas.width = savedState.width;
|
||||
canvas.canvas.height = savedState.height;
|
||||
canvas.ds.offset = savedState.offset;
|
||||
canvas.canvas.getContext("2d").setTransform(savedState.transform);
|
||||
canvas.draw(true, true);
|
||||
|
||||
if (!rawBlob) {
|
||||
reject(new Error("Failed to generate canvas image"));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Embed workflow JSON into PNG tEXt chunk
|
||||
const blob = await embedWorkflowInPng(rawBlob, workflowJson);
|
||||
resolve(blob);
|
||||
} catch (embedErr) {
|
||||
console.warn("Workflow Studio: failed to embed workflow metadata, saving without it:", embedErr);
|
||||
resolve(rawBlob);
|
||||
}
|
||||
}, "image/png");
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const saveCanvasToWorkflowStudio = async () => {
|
||||
const filename = getWorkflowFilename();
|
||||
|
||||
try {
|
||||
showNotification("Capturing workflow image...", "info");
|
||||
const blob = await captureCanvasSnapshot();
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append("filename", filename);
|
||||
fd.append("image", blob, "canvas.png");
|
||||
|
||||
const res = await fetch("/api/wfm/workflows/save-canvas-image", {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
throw new Error(data.error);
|
||||
}
|
||||
|
||||
showNotification(`Workflow saved: ${filename.replace(/\.json$/, "")}`, "success");
|
||||
} catch (err) {
|
||||
showNotification("Error: " + err.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
const showNotification = (message, type = "info") => {
|
||||
// Try using ComfyUI's built-in toast if available
|
||||
try {
|
||||
if (app.ui?.dialog) {
|
||||
// Fallback: use a simple temporary notification
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
// Simple toast notification
|
||||
const existing = document.getElementById("wfm-snapshot-toast");
|
||||
if (existing) existing.remove();
|
||||
|
||||
const toast = document.createElement("div");
|
||||
toast.id = "wfm-snapshot-toast";
|
||||
const colors = {
|
||||
success: { bg: "rgba(46,213,115,0.95)", color: "#fff" },
|
||||
error: { bg: "rgba(255,71,87,0.95)", color: "#fff" },
|
||||
info: { bg: "rgba(74,158,255,0.95)", color: "#fff" },
|
||||
};
|
||||
const c = colors[type] || colors.info;
|
||||
Object.assign(toast.style, {
|
||||
position: "fixed",
|
||||
bottom: "24px",
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
padding: "10px 24px",
|
||||
background: c.bg,
|
||||
color: c.color,
|
||||
borderRadius: "8px",
|
||||
fontSize: "14px",
|
||||
fontWeight: "500",
|
||||
zIndex: "99999",
|
||||
boxShadow: "0 4px 16px rgba(0,0,0,0.3)",
|
||||
transition: "opacity 0.3s ease",
|
||||
whiteSpace: "nowrap",
|
||||
});
|
||||
toast.textContent = message;
|
||||
document.body.appendChild(toast);
|
||||
|
||||
if (type !== "info") {
|
||||
setTimeout(() => {
|
||||
toast.style.opacity = "0";
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}, 3000);
|
||||
} else {
|
||||
// Info messages will be replaced by success/error
|
||||
setTimeout(() => {
|
||||
if (toast.parentNode) {
|
||||
toast.style.opacity = "0";
|
||||
setTimeout(() => toast.remove(), 300);
|
||||
}
|
||||
}, 10000);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Version Detection & UI
|
||||
// ============================================
|
||||
|
||||
const getComfyUIFrontendVersion = async () => {
|
||||
try {
|
||||
if (window["__COMFYUI_FRONTEND_VERSION__"]) {
|
||||
return window["__COMFYUI_FRONTEND_VERSION__"];
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Workflow Studio: unable to read __COMFYUI_FRONTEND_VERSION__:", error);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch("/system_stats");
|
||||
const data = await response.json();
|
||||
|
||||
if (data?.system?.comfyui_frontend_version) {
|
||||
return data.system.comfyui_frontend_version;
|
||||
}
|
||||
|
||||
if (data?.system?.required_frontend_version) {
|
||||
return data.system.required_frontend_version;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Workflow Studio: unable to fetch system_stats:", error);
|
||||
}
|
||||
|
||||
return "0.0.0";
|
||||
};
|
||||
|
||||
const parseVersion = (versionStr) => {
|
||||
if (!versionStr || typeof versionStr !== "string") {
|
||||
return [0, 0, 0];
|
||||
}
|
||||
|
||||
const cleanVersion = versionStr.replace(/^[vV]/, "").split("-")[0];
|
||||
const parts = cleanVersion.split(".").map((part) => parseInt(part, 10) || 0);
|
||||
|
||||
while (parts.length < 3) {
|
||||
parts.push(0);
|
||||
}
|
||||
|
||||
return parts;
|
||||
};
|
||||
|
||||
const compareVersions = (version1, version2) => {
|
||||
const v1 = typeof version1 === "string" ? parseVersion(version1) : version1;
|
||||
const v2 = typeof version2 === "string" ? parseVersion(version2) : version2;
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (v1[i] > v2[i]) return 1;
|
||||
if (v1[i] < v2[i]) return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
const supportsActionBarButtons = async () => {
|
||||
const version = await getComfyUIFrontendVersion();
|
||||
return compareVersions(version, MIN_VERSION_FOR_ACTION_BAR) >= 0;
|
||||
};
|
||||
|
||||
const getWfmIcon = () => {
|
||||
return `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M3 5 L7 17 L12 7 L17 17 L21 5" stroke-width="2.3"/>
|
||||
<path d="M5 20 Q9 17 12 20 Q15 23 19 20" stroke-width="1.8"/>
|
||||
</svg>
|
||||
`;
|
||||
};
|
||||
|
||||
const getSnapshotIcon = () => {
|
||||
return `
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
|
||||
<rect x="3" y="5" width="18" height="14" rx="2"/>
|
||||
<circle cx="12" cy="12" r="3"/>
|
||||
<path d="M8 5 L9 3 L15 3 L16 5"/>
|
||||
</svg>
|
||||
`;
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Button Creation
|
||||
// ============================================
|
||||
|
||||
const createTopMenuButton = async () => {
|
||||
const { ComfyButton } = await import("../../scripts/ui/components/button.js");
|
||||
|
||||
const button = new ComfyButton({
|
||||
icon: "wfm",
|
||||
tooltip: BUTTON_TOOLTIP,
|
||||
app,
|
||||
enabled: true,
|
||||
classList: "comfyui-button comfyui-menu-mobile-collapse primary",
|
||||
});
|
||||
|
||||
button.element.setAttribute("aria-label", BUTTON_TOOLTIP);
|
||||
button.element.title = BUTTON_TOOLTIP;
|
||||
|
||||
if (button.iconElement) {
|
||||
button.iconElement.innerHTML = getWfmIcon();
|
||||
button.iconElement.style.width = "1.2rem";
|
||||
button.iconElement.style.height = "1.2rem";
|
||||
}
|
||||
|
||||
button.element.addEventListener("click", openWorkflowStudio);
|
||||
return button;
|
||||
};
|
||||
|
||||
const createSnapshotButton = async () => {
|
||||
const { ComfyButton } = await import("../../scripts/ui/components/button.js");
|
||||
|
||||
const button = new ComfyButton({
|
||||
icon: "snapshot",
|
||||
tooltip: SNAPSHOT_TOOLTIP,
|
||||
app,
|
||||
enabled: true,
|
||||
classList: "comfyui-button comfyui-menu-mobile-collapse",
|
||||
});
|
||||
|
||||
button.element.setAttribute("aria-label", SNAPSHOT_TOOLTIP);
|
||||
button.element.title = SNAPSHOT_TOOLTIP;
|
||||
|
||||
if (button.iconElement) {
|
||||
button.iconElement.innerHTML = getSnapshotIcon();
|
||||
button.iconElement.style.width = "1.2rem";
|
||||
button.iconElement.style.height = "1.2rem";
|
||||
}
|
||||
|
||||
button.element.addEventListener("click", saveCanvasToWorkflowStudio);
|
||||
return button;
|
||||
};
|
||||
|
||||
const createNodeSetsButton = async () => {
|
||||
const { ComfyButton } = await import("../../scripts/ui/components/button.js");
|
||||
|
||||
const button = new ComfyButton({
|
||||
icon: "node-sets",
|
||||
tooltip: NODE_SETS_TOOLTIP,
|
||||
app,
|
||||
enabled: true,
|
||||
classList: "comfyui-button comfyui-menu-mobile-collapse wfm-node-sets-btn",
|
||||
});
|
||||
|
||||
button.element.setAttribute("aria-label", NODE_SETS_TOOLTIP);
|
||||
button.element.title = NODE_SETS_TOOLTIP;
|
||||
|
||||
if (button.iconElement) {
|
||||
button.iconElement.innerHTML = getNodeSetsIcon();
|
||||
button.iconElement.style.width = "1.2rem";
|
||||
button.iconElement.style.height = "1.2rem";
|
||||
}
|
||||
|
||||
button.element.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
togglePanel();
|
||||
});
|
||||
|
||||
return button;
|
||||
};
|
||||
|
||||
const attachTopMenuButton = async (attempt = 0) => {
|
||||
if (document.querySelector(`.${BUTTON_GROUP_CLASS}`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Try settingsGroup first (legacy ComfyUI)
|
||||
const settingsGroup = app.menu?.settingsGroup;
|
||||
// Fallback: find the legacy topbar container used by newer ComfyUI
|
||||
const legacyContainer = document.querySelector('[data-testid="legacy-topbar-container"] .flex');
|
||||
|
||||
if (!settingsGroup?.element?.parentElement && !legacyContainer) {
|
||||
if (attempt >= MAX_ATTACH_ATTEMPTS) {
|
||||
console.warn("Workflow Studio: unable to locate the ComfyUI menu container.");
|
||||
return;
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => attachTopMenuButton(attempt + 1));
|
||||
return;
|
||||
}
|
||||
|
||||
const wfmButton = await createTopMenuButton();
|
||||
const snapshotButton = await createSnapshotButton();
|
||||
const nodeSetsButton = await createNodeSetsButton();
|
||||
const { ComfyButtonGroup } = await import("../../scripts/ui/components/buttonGroup.js");
|
||||
|
||||
const buttonGroup = new ComfyButtonGroup(wfmButton, snapshotButton, nodeSetsButton);
|
||||
buttonGroup.element.classList.add(BUTTON_GROUP_CLASS);
|
||||
|
||||
if (settingsGroup?.element?.parentElement) {
|
||||
settingsGroup.element.before(buttonGroup.element);
|
||||
} else if (legacyContainer) {
|
||||
legacyContainer.prepend(buttonGroup.element);
|
||||
}
|
||||
};
|
||||
|
||||
app.registerExtension({
|
||||
name: "WorkflowStudio.TopMenu",
|
||||
actionBarButtons: [
|
||||
{
|
||||
icon: "icon-[mdi--file-document-multiple] size-4",
|
||||
tooltip: BUTTON_TOOLTIP,
|
||||
onClick: openWorkflowStudio,
|
||||
},
|
||||
{
|
||||
icon: "icon-[mdi--camera] size-4",
|
||||
tooltip: SNAPSHOT_TOOLTIP,
|
||||
onClick: saveCanvasToWorkflowStudio,
|
||||
},
|
||||
{
|
||||
icon: "icon-[mdi--view-grid-plus] size-4",
|
||||
tooltip: NODE_SETS_TOOLTIP,
|
||||
onClick: () => togglePanel(),
|
||||
},
|
||||
],
|
||||
beforeRegisterNodeDef(nodeType, _nodeData, _app) {
|
||||
const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
|
||||
nodeType.prototype.getExtraMenuOptions = function (_, options) {
|
||||
origGetExtraMenuOptions?.apply(this, arguments);
|
||||
const selectedCount = Object.keys(app.canvas.selected_nodes || {}).length;
|
||||
options.push(null);
|
||||
options.push({
|
||||
content: `Save as Node Set${selectedCount > 1 ? ` (${selectedCount} nodes)` : ""}`,
|
||||
callback: saveSelectedAsNodeSet,
|
||||
});
|
||||
};
|
||||
},
|
||||
async setup() {
|
||||
const injectStyles = () => {
|
||||
const styleId = "wfm-top-menu-button-styles";
|
||||
if (document.getElementById(styleId)) return;
|
||||
|
||||
const style = document.createElement("style");
|
||||
style.id = styleId;
|
||||
style.textContent = `
|
||||
button[aria-label="${BUTTON_TOOLTIP}"].wfm-top-menu-button {
|
||||
transition: all 0.2s ease;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
button[aria-label="${BUTTON_TOOLTIP}"].wfm-top-menu-button:hover {
|
||||
background-color: var(--primary-hover-bg) !important;
|
||||
}
|
||||
button[aria-label="${SNAPSHOT_TOOLTIP}"].wfm-snapshot-button {
|
||||
transition: all 0.2s ease;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
button[aria-label="${SNAPSHOT_TOOLTIP}"].wfm-snapshot-button:hover {
|
||||
background-color: var(--primary-hover-bg) !important;
|
||||
}
|
||||
button[aria-label="${NODE_SETS_TOOLTIP}"].wfm-node-sets-btn {
|
||||
transition: all 0.2s ease;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
button[aria-label="${NODE_SETS_TOOLTIP}"].wfm-node-sets-btn:hover {
|
||||
background-color: var(--primary-hover-bg) !important;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
};
|
||||
injectStyles();
|
||||
|
||||
const replaceButtonIcon = () => {
|
||||
const wfmButtons = document.querySelectorAll(`button[aria-label="${BUTTON_TOOLTIP}"]`);
|
||||
wfmButtons.forEach((button) => {
|
||||
button.classList.add("wfm-top-menu-button");
|
||||
button.innerHTML = getWfmIcon();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
button.style.backgroundColor = "var(--primary-bg)";
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
});
|
||||
|
||||
const snapButtons = document.querySelectorAll(`button[aria-label="${SNAPSHOT_TOOLTIP}"]`);
|
||||
snapButtons.forEach((button) => {
|
||||
button.classList.add("wfm-snapshot-button");
|
||||
button.innerHTML = getSnapshotIcon();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
});
|
||||
|
||||
const nsButtons = document.querySelectorAll(`button[aria-label="${NODE_SETS_TOOLTIP}"]`);
|
||||
nsButtons.forEach((button) => {
|
||||
button.classList.add("wfm-node-sets-btn");
|
||||
button.innerHTML = getNodeSetsIcon();
|
||||
button.style.borderRadius = "4px";
|
||||
button.style.padding = "6px";
|
||||
const svg = button.querySelector("svg");
|
||||
if (svg) {
|
||||
svg.style.width = "20px";
|
||||
svg.style.height = "20px";
|
||||
}
|
||||
});
|
||||
|
||||
if (wfmButtons.length === 0) {
|
||||
requestAnimationFrame(replaceButtonIcon);
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(replaceButtonIcon);
|
||||
},
|
||||
});
|
||||