Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0886ea6e2b | ||
|
|
226fc885d7 | ||
|
|
8d48c2276f |
@@ -1,5 +1,171 @@
|
||||
# DEVLOG - ComfyUI-Workflow-Studio
|
||||
|
||||
## 2026-04-28: v0.3.2 生成UIタブ — Checkpoint Batch・Seed UIレイアウト修正
|
||||
|
||||
### 概要
|
||||
|
||||
- 生成UIタブの右パネルに **Checkpoint Batch** 機能を追加
|
||||
- Seed行のレイアウトを2段構成に変更(seed値とモード選択が見切れる問題を解消)
|
||||
|
||||
### 変更内容
|
||||
|
||||
#### `templates/index.html` — UI要素追加・修正
|
||||
|
||||
**Checkpoint Batch パネル追加:**
|
||||
- 右パネル(Seed行の下・結果表示の上)に `wfm-ckpt-batch-panel` を追加
|
||||
- チェックボックス ON/OFF でバッチ設定欄を展開/折りたたみ
|
||||
- Include Folders テキスト入力 — カンマ区切りでサブフォルダ名を指定。空欄でcheckpointフォルダ内の全モデルを対象
|
||||
- Exclude Folders テキスト入力 — カンマ区切りで除外するサブフォルダ名を指定
|
||||
- 対象モデル数プレビュー表示 (`wfm-ckpt-batch-info`)
|
||||
- バッチ進捗エリア — 現在のモデル名、インデックス/総数、アンバー色プログレスバー (`wfm-ckpt-batch-bar`)
|
||||
|
||||
**Seed レイアウト修正:**
|
||||
- 横並び1行(`flex-direction: row`)→ 縦2行(`flex-direction: column`)に変更
|
||||
- 1行目: `Seed:` ラベル + 数値入力(`flex:1` で横幅いっぱい)
|
||||
- 2行目: モード選択セレクト(`width:100%`)
|
||||
|
||||
**ヘルプタブ:**
|
||||
- GenerateUI タブ説明に gen-11(Checkpoint Batch の説明)を追加
|
||||
- gen-8(Seed control)に2段レイアウト化の補足を追加
|
||||
|
||||
#### `static/js/generate-tab.js` — バッチロジック追加・生成処理リファクタリング
|
||||
|
||||
**新規追加:**
|
||||
- `_ckptBatch` — `{ aborted: false }` バッチ中断フラグ
|
||||
- `_parseFolderList(str)` — カンマ区切り文字列をトリム・小文字化して配列に変換
|
||||
- `_getModelFolder(modelPath)` — パスの最初の `/` より前を抽出してフォルダ名を取得。`\\` を `/` に正規化、ルート直下は `""` を返す
|
||||
- `_filterCheckpoints(checkpoints, includeStr, excludeStr)` — include/exclude フィルタを適用したチェックポイントリストを返す。大文字小文字を区別しない
|
||||
- `_updateBatchInfo()` — チェックポイントリストのフィルタ済み件数を `wfm-ckpt-batch-info` に即時反映
|
||||
- `initCheckpointBatch()` — チェックボックス・include/exclude 入力のイベントリスナーを登録
|
||||
- `_coreGenerate(silent)` — 1回の生成コア処理(`silent=true` のとき完了トーストを省略)。エラー時はスローする
|
||||
- `_runBatchGenerate()` — チェックポイントリストをループし `_coreGenerate` を順番に呼び出す。各反復でワークフロー内の全checkpointノードの `ckpt_name` を書き換える。エラーは件数カウントして継続。完了後に結果サマリをトースト表示
|
||||
|
||||
**変更:**
|
||||
- `handleGenerate()` — バッチが有効な場合は `_runBatchGenerate()` を、無効の場合は `_coreGenerate(false)` を呼び出すよう分岐。ボタン管理(disabled / Stop 表示)を共通 try/finally で処理
|
||||
- interrupt ボタンのハンドラ — `_ckptBatch.aborted = true` を設定してから `comfyUI.interrupt()` を呼び出し、単発生成とバッチの両方を停止できるように
|
||||
- Refresh Models ボタンのハンドラ — モデルリスト再取得後に `_updateBatchInfo()` を呼び出してバッチ件数を更新
|
||||
- `initGenerateTab()` — 末尾で `initCheckpointBatch()` を呼び出し。初期接続成功時に `_updateBatchInfo()` を呼び出し
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-27: v0.3.1 ギャラリー拡張(フォルダ/ファイル操作・ワークフロー保存)
|
||||
|
||||
### 概要
|
||||
|
||||
- ギャラリータブにフォルダ作成・削除機能を追加
|
||||
- ギャラリータブにファイル削除・移動機能を追加(単体・複数選択対応)
|
||||
- 操作後もフォルダツリーの展開状態を維持するよう改善
|
||||
- 生成UIタブで生成した画像のワークフローをギャラリーメタデータに自動保存
|
||||
- MetadataタブのワークフローJSON表示をComfyUI生成画像全般(`prompt`キー)に対応
|
||||
|
||||
### 変更内容
|
||||
|
||||
#### `py/services/gallery_metadata.py` — メタデータ操作追加
|
||||
|
||||
- `delete(image_path)` 追加 — 画像削除時にメタデータエントリを除去
|
||||
- `rename_path(old_path, new_path)` 追加 — ファイル移動後のパスキー付け替え
|
||||
- `allowed` セットに `"workflow"` を追加 — 生成UIからのワークフロー保存を受け付けるように
|
||||
|
||||
#### `py/services/gallery_service.py` — ファイル・フォルダ操作追加
|
||||
|
||||
- `create_folder(parent_path, name)` — 無効文字チェック付きでサブフォルダを作成。作成後にフォルダキャッシュを無効化
|
||||
- `delete_folder(folder_path)` — `shutil.rmtree` で再帰削除。ルートフォルダは保護
|
||||
- `delete_images(paths)` — 複数画像ファイルを削除。各ファイルのメタデータ削除・キャッシュ無効化も実行
|
||||
- `move_images(paths, dest_folder)` — 複数画像を別フォルダへ移動。ファイル名衝突時は連番サフィックス付与。メタデータのパスキーを `rename_path` で引き継ぎ
|
||||
- `extract_workflow_from_metadata` 修正 — PNG埋め込みの参照キーを `workflow` → `workflow / prompt` の順に拡張。どちらも存在しない場合は `gallery_metadata.json` の `workflow` フィールドへフォールバック
|
||||
|
||||
#### `py/routes/gallery_routes.py` — エンドポイント追加
|
||||
|
||||
- `POST /wfm/gallery/folder` — フォルダ作成
|
||||
- `DELETE /wfm/gallery/folder` — フォルダ削除
|
||||
- `POST /wfm/gallery/images/delete` — 画像削除(単体・複数)
|
||||
- `POST /wfm/gallery/images/move` — 画像移動(単体・複数)
|
||||
|
||||
#### `static/js/gallery-tab.js` — フロントエンド拡張
|
||||
|
||||
**API定数追加:**
|
||||
- `folderCreate`, `folderDelete`, `imagesDelete`, `imagesMove`
|
||||
|
||||
**state追加:**
|
||||
- `folderTree` — ツリー全体データを保持(移動先フォルダ一覧の生成に使用)
|
||||
|
||||
**フォルダツリー展開状態の保持:**
|
||||
- `_getExpandedPaths()` — 再構築前に展開済みフォルダのパスを `Set` で収集
|
||||
- `_restoreTreeState(expandedPaths, selectedPath)` — 再構築後に展開状態・選択ハイライトを復元。階層の浅い順に展開することで子ノードのDOM存在を保証
|
||||
- `renderTreeNode` — 各アイテムに `data-path` 属性を付与(復元の識別子)
|
||||
- `loadFolderTree` — 初回ロード判定(`isFirstLoad`)を追加。2回目以降は `_restoreTreeState` を呼び出して展開状態を維持
|
||||
|
||||
**フォルダ操作:**
|
||||
- `createFolder()` — `prompt()` でフォルダ名入力後、API呼び出し・ツリー再読み込み
|
||||
- `deleteFolder()` — 確認ダイアログ後、再帰削除・currentFolder リセット・ツリー再読み込み
|
||||
- フォルダラベルクリック時に Delete Folder ボタンの `disabled` 状態を更新(ルート選択時は削除不可)
|
||||
|
||||
**ファイル削除・移動:**
|
||||
- `performDeleteImages(paths)` — 削除後に `state.images` / `state.selectedImages` を即時更新。詳細パネルの選択中画像が削除された場合はパネルをリセット
|
||||
- `performMoveImages(paths, dest)` — 移動後に同様に state を即時更新
|
||||
- `flattenFolderTree(node)` — ツリーデータをフラットリストに変換(移動先選択に使用)
|
||||
- `openMoveModal(paths)` — 移動先フォルダ選択モーダルを動的生成。現在フォルダを除く全フォルダをドロップダウン表示
|
||||
- 詳細パネルの Move To... / Delete ボタンを画像選択時に有効化
|
||||
|
||||
#### `templates/index.html` — UI要素追加
|
||||
|
||||
- フォルダツリーヘッダーに「+ New」「Del」ボタン(`wfm-gallery-tree-actions`)
|
||||
- 詳細パネル Info タブに「Move To...」「Delete」ボタン(`wfm-gallery-file-actions`)
|
||||
- 一括バーに「Move To...」「Delete」ボタン
|
||||
- ヘルプ項目を10項目から11項目に更新
|
||||
|
||||
#### `static/css/gallery-tab.css` — スタイル追加
|
||||
|
||||
- `.wfm-gallery-tree-header` — `justify-content: space-between` でタイトルとボタンを両端配置
|
||||
- `.wfm-gallery-tree-actions` — フォルダ操作ボタンのフレックスコンテナ
|
||||
- `.wfm-gallery-file-actions` — 詳細パネルのファイル操作ボタン
|
||||
- `.wfm-gallery-move-modal` / `.wfm-gallery-move-modal-title` / `.wfm-gallery-move-dest-sel` / `.wfm-gallery-move-modal-footer` — 移動先選択モーダル
|
||||
|
||||
#### `static/js/generate-tab.js` — ワークフロー自動保存
|
||||
|
||||
- `_outputDir` モジュール変数 — outputパスをキャッシュ
|
||||
- `_fetchOutputDir()` — `/api/wfm/settings/output-dir` からoutputパスを取得
|
||||
- `saveGeneratedImagesMeta(images, workflow)` — 生成完了後、各画像のフルパスを組み立てて `/wfm/gallery/image/meta` にワークフローを保存。`type !== "output"` の一時ファイルはスキップ
|
||||
- `initGenerateTab` — 初期化時に `_fetchOutputDir()` を実行。`wfm-output-dir-changed` イベントで設定変更時にパスを同期
|
||||
- `handleGenerate` — 生成成功後に `saveGeneratedImagesMeta` を非同期呼び出し
|
||||
|
||||
### 技術的な判断
|
||||
|
||||
- **ツリー展開状態の復元**: `innerHTML = ""` による完全再構築を維持しつつ、展開パスを `Set` で保存して復元する方式を採用。差分DOMパッチより実装が単純で、フォルダ追加・削除後のツリー構造変化にも対応できる
|
||||
- **PNG `prompt` キーの参照**: ComfyUIのSaveImageノードはデフォルトでPNGに `prompt` キー(API形式)のみを埋め込む。`workflow` キー(UI形式)が埋め込まれるのは特定の操作時のみ。`prompt` を参照することで既存の全ComfyUI生成画像に対応
|
||||
- **フォールバック優先順位**: PNG埋め込み(`workflow` > `prompt`)> `gallery_metadata.json` の順とし、ComfyUI本体が埋め込んだデータを最優先に
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-18: v0.3.0 モデルグループ表示改善(全タイプ横断・サイドパネル修正)
|
||||
|
||||
### 概要
|
||||
|
||||
- モデルタブのグループフィルタードロップダウンを全タイプ横断表示に改善
|
||||
- ComfyUIサイドパネルのModel Groupsビューを v0.2.9 のタイプ別形式に対応させバグ修正
|
||||
|
||||
### 変更内容
|
||||
|
||||
#### `static/js/models-tab.js` — グループフィルター全タイプ横断表示
|
||||
|
||||
- `state.allModelGroups` 追加 — 全タイプのグループを `{ type: { groupName: [models] } }` 形式で保持
|
||||
- `fetchAllModelGroups()` 追加 — `type` パラメータなしで全タイプのグループをAPIから一括取得
|
||||
- `renderGroupFilter()` 改善 — ドロップダウンオプションを `[Checkpoint] GroupName` / `[LoRA] GroupName` 形式で全タイプ分表示。値は `type::groupName` としてエンコード
|
||||
- グループフィルター `change` ハンドラ更新 — 選択したグループが現在と異なるタイプの場合、モデルタイプタブを自動切り替えしてモデルを再ロード
|
||||
- `saveModelGroups()` — 保存時に `state.allModelGroups[type]` も更新
|
||||
- `loadModelsForCurrentType()` — ロード時に `state.allModelGroups[type]` を同期
|
||||
- `loadMetadataAndModels()` — 初回ロード時に `fetchAllModelGroups()` で全タイプのグループを一括取得
|
||||
|
||||
#### `web/comfyui/node_sets_menu.js` — サイドパネルのModel Groupsビュー修正
|
||||
|
||||
- `renderModelGroups()` を新タイプ別形式 `{ type: { groupName: [...] } }` に対応
|
||||
- 旧: `groups[groupName]` が配列を期待 → `TypeError: .filter is not a function` でクラッシュ
|
||||
- 新: `flatGroups = [{modelType, groupName, members}]` にフラット展開してから描画
|
||||
- グループヘッダーに `[Checkpoint]` / `[LoRA]` 等のタイプラベルを追加(`wfm-nlp-model-type-badge`クラス)
|
||||
- `typeOf[name] || modelType` — モデルリスト未取得時のフォールバックをグループのモデルタイプに変更
|
||||
|
||||
---
|
||||
|
||||
## 2026-04-18: v0.2.9 モデル有効/無効・複数選択・一括削除
|
||||
|
||||
### 概要
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -50,14 +50,15 @@ 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 (v0.2.4)
|
||||
### GenerateUI Tab (v0.3.2)
|
||||
- **3-tab layout** — Input / Model / Settings tabs, each with 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 (top) and LatentImage (bottom) in the left column; 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
|
||||
- **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; filter by include folders (comma-separated subfolder names, empty = all) and/or exclude folders; Stop button aborts after the current generation completes; amber progress bar tracks per-model progress
|
||||
- **UI-to-API conversion** — automatic conversion supporting subgraphs (nested workflows), COMBO types, and display-only node exclusion
|
||||
- **Eagle integration** — auto-save generated images to [Eagle](https://eagle.cool/) with metadata
|
||||
|
||||
@@ -85,16 +86,20 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **Data Management** — export all plugin data (settings, metadata, prompts, etc.) to a single JSON file; import to restore data (useful when migrating or reinstalling)
|
||||
- **Language** — English / Japanese / Chinese
|
||||
|
||||
### Gallery Tab (v0.2.7)
|
||||
### 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
|
||||
- **Multi-select** — Ctrl+click to select multiple images; Bulk Bar appears for batch tag/group/favorite operations
|
||||
- **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** — with folder-level mtime cache (30s TTL) for fast incremental refresh
|
||||
- **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
|
||||
@@ -210,6 +215,21 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
|
||||
|
||||
## Changelog
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -30,6 +30,11 @@ def setup_routes(app: web.Application):
|
||||
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)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
@@ -217,3 +222,61 @@ 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)
|
||||
|
||||
@@ -64,7 +64,7 @@ class GalleryMetadataStore:
|
||||
key = self._normalize_path(image_path)
|
||||
existing = self._data["images"].get(key, {})
|
||||
existing.update(data)
|
||||
allowed = {"favorite", "tags", "memo", "groups"}
|
||||
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()
|
||||
@@ -123,3 +123,20 @@ class GalleryMetadataStore:
|
||||
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
|
||||
|
||||
+126
-11
@@ -350,20 +350,35 @@ class GalleryService:
|
||||
return result
|
||||
|
||||
def extract_workflow_from_metadata(self, image_path: str) -> dict | None:
|
||||
"""PNG埋め込みメタデータからComfyUIワークフローを抽出"""
|
||||
"""ワークフローを抽出する。
|
||||
優先順位: PNG[workflow] > PNG[prompt] > gallery_metadata.json[workflow]
|
||||
"""
|
||||
path = Path(image_path).resolve()
|
||||
if path.suffix.lower() != ".png":
|
||||
return None
|
||||
if not self._check_path_allowed(path):
|
||||
return None
|
||||
embedded = self._read_png_metadata(path)
|
||||
workflow_str = embedded.get("workflow") or embedded.get("Workflow")
|
||||
if workflow_str:
|
||||
try:
|
||||
return json.loads(workflow_str)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
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
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# メタデータ保存
|
||||
@@ -414,6 +429,106 @@ class GalleryService:
|
||||
# 画像配信
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
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()
|
||||
|
||||
@@ -27,10 +27,12 @@
|
||||
.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 {
|
||||
@@ -39,6 +41,13 @@
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -592,3 +601,49 @@
|
||||
.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;
|
||||
}
|
||||
|
||||
+267
-2
@@ -22,6 +22,10 @@ const API = {
|
||||
groupDelete: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}`,
|
||||
groupAdd: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}/add`,
|
||||
groupRemove: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}/remove`,
|
||||
folderCreate: `/wfm/gallery/folder`,
|
||||
folderDelete: `/wfm/gallery/folder`,
|
||||
imagesDelete: `/wfm/gallery/images/delete`,
|
||||
imagesMove: `/wfm/gallery/images/move`,
|
||||
};
|
||||
|
||||
// ── 状態 ─────────────────────────────────────────────────────
|
||||
@@ -40,6 +44,7 @@ const state = {
|
||||
groups: [],
|
||||
embeddedWorkflow: null, // 選択画像のworkflow JSON
|
||||
selectedImages: new Set(), // 複数選択中のパス Set
|
||||
folderTree: null, // フォルダツリー全体(移動先選択に使用)
|
||||
};
|
||||
|
||||
// ── ヘルパー ──────────────────────────────────────────────────
|
||||
@@ -62,9 +67,49 @@ function formatDate(mtime) {
|
||||
|
||||
// ── フォルダツリー ────────────────────────────────────────────
|
||||
|
||||
function _getExpandedPaths() {
|
||||
const expanded = new Set();
|
||||
document.querySelectorAll(".wfm-gallery-tree-item").forEach(item => {
|
||||
const arrow = item.querySelector(".wfm-gallery-tree-arrow");
|
||||
if (arrow && arrow.dataset.expanded === "true") {
|
||||
expanded.add(item.dataset.path);
|
||||
}
|
||||
});
|
||||
return expanded;
|
||||
}
|
||||
|
||||
function _restoreTreeState(expandedPaths, selectedPath) {
|
||||
// 親→子の順で展開するため、階層の浅い順にソート
|
||||
const sorted = [...expandedPaths].sort(
|
||||
(a, b) => a.split("/").length - b.split("/").length
|
||||
);
|
||||
for (const path of sorted) {
|
||||
document.querySelectorAll(".wfm-gallery-tree-item").forEach(item => {
|
||||
if (item.dataset.path !== path) return;
|
||||
const arrow = item.querySelector(".wfm-gallery-tree-arrow");
|
||||
if (arrow && arrow.dataset.expanded !== "true" && arrow.style.visibility !== "hidden") {
|
||||
arrow.click();
|
||||
}
|
||||
});
|
||||
}
|
||||
// 選択状態を復元(labelクリックは画像リロードを伴うのでハイライトのみ)
|
||||
if (selectedPath) {
|
||||
document.querySelectorAll(".wfm-gallery-tree-item").forEach(item => {
|
||||
if (item.dataset.path === selectedPath) {
|
||||
document.querySelectorAll(".wfm-gallery-tree-item.selected").forEach(el => el.classList.remove("selected"));
|
||||
item.classList.add("selected");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFolderTree() {
|
||||
if (!state.outputRoot) return;
|
||||
|
||||
// 再構築前に展開状態を保存
|
||||
const expandedPaths = _getExpandedPaths();
|
||||
const isFirstLoad = expandedPaths.size === 0 && !state.currentFolder;
|
||||
|
||||
const tree = document.getElementById("wfm-gallery-tree");
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${t("loading")}</p>`;
|
||||
|
||||
@@ -74,12 +119,17 @@ async function loadFolderTree() {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${data.error}</p>`;
|
||||
return;
|
||||
}
|
||||
state.folderTree = data;
|
||||
tree.innerHTML = "";
|
||||
renderTreeNode(data, tree, 0, true);
|
||||
// root フォルダを自動選択(フォルダ未選択の場合のみ)
|
||||
if (!state.currentFolder) {
|
||||
|
||||
if (isFirstLoad) {
|
||||
// 初回のみ root を自動選択
|
||||
const firstLabel = tree.querySelector(".wfm-gallery-tree-label");
|
||||
if (firstLabel) firstLabel.click();
|
||||
} else {
|
||||
// 展開状態と選択ハイライトを復元
|
||||
_restoreTreeState(expandedPaths, state.currentFolder);
|
||||
}
|
||||
} catch (e) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">Error: ${e.message}</p>`;
|
||||
@@ -90,6 +140,7 @@ function renderTreeNode(node, container, depth, isRoot) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "wfm-gallery-tree-item";
|
||||
item.style.paddingLeft = `${depth * 12}px`;
|
||||
item.dataset.path = node.abs_path;
|
||||
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const absPath = node.abs_path;
|
||||
@@ -126,6 +177,11 @@ function renderTreeNode(node, container, depth, isRoot) {
|
||||
state.selectedImages.clear();
|
||||
updateBulkBar();
|
||||
loadImages();
|
||||
// Delete Folder ボタン: rootは削除不可
|
||||
const delBtn = document.getElementById("wfm-gallery-folder-delete-btn");
|
||||
if (delBtn) {
|
||||
delBtn.disabled = (absPath === state.outputRoot.replace(/\\/g, "/") || absPath === state.outputRoot);
|
||||
}
|
||||
});
|
||||
|
||||
// 矢印クリックで子ノード展開/折りたたみ
|
||||
@@ -424,6 +480,12 @@ function updateTagFilter(images) {
|
||||
// ── 詳細パネル ────────────────────────────────────────────────
|
||||
|
||||
async function loadImageDetail(img) {
|
||||
// ファイル操作ボタンを有効化
|
||||
const moveBtn = document.getElementById("wfm-gallery-img-move-btn");
|
||||
const delBtn = document.getElementById("wfm-gallery-img-delete-btn");
|
||||
if (moveBtn) moveBtn.disabled = false;
|
||||
if (delBtn) delBtn.disabled = false;
|
||||
|
||||
// プレビュー
|
||||
const preview = document.getElementById("wfm-gallery-detail-preview");
|
||||
preview.innerHTML = `<img src="${API.serveImage(img.path)}" class="wfm-gallery-detail-img" alt="${img.filename}" title="Double-click to enlarge">`;
|
||||
@@ -772,6 +834,181 @@ function escapeHtml(str) {
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
// ── フォルダ作成・削除 ────────────────────────────────────────
|
||||
|
||||
async function createFolder() {
|
||||
if (!state.currentFolder) {
|
||||
showToast("Please select a parent folder first", "error");
|
||||
return;
|
||||
}
|
||||
const name = prompt("New folder name:");
|
||||
if (!name || !name.trim()) return;
|
||||
try {
|
||||
const res = await fetch(API.folderCreate, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ parent: state.currentFolder, name: name.trim() }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.ok) {
|
||||
showToast(`Error: ${data.error}`, "error");
|
||||
return;
|
||||
}
|
||||
showToast(`Folder "${name.trim()}" created`, "success");
|
||||
await loadFolderTree();
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFolder() {
|
||||
if (!state.currentFolder) return;
|
||||
if (!confirm(`Delete folder "${state.currentFolder.split("/").pop()}" and all its contents?`)) return;
|
||||
try {
|
||||
const res = await fetch(API.folderDelete, {
|
||||
method: "DELETE",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: state.currentFolder }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.ok) {
|
||||
showToast(`Error: ${data.error}`, "error");
|
||||
return;
|
||||
}
|
||||
showToast("Folder deleted", "success");
|
||||
state.currentFolder = "";
|
||||
state.images = [];
|
||||
document.getElementById("wfm-gallery-grid").innerHTML = `<p class="wfm-placeholder">Select a folder to browse images.</p>`;
|
||||
await loadFolderTree();
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── ファイル削除・移動 ────────────────────────────────────────
|
||||
|
||||
async function performDeleteImages(paths) {
|
||||
try {
|
||||
const res = await fetch(API.imagesDelete, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ paths }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.deleted && data.deleted.length > 0) {
|
||||
showToast(`Deleted ${data.deleted.length} image(s)`, "success");
|
||||
// 削除された画像をstateから除去
|
||||
const deletedSet = new Set(data.deleted);
|
||||
state.images = state.images.filter(img => !deletedSet.has(img.path));
|
||||
state.selectedImages = new Set([...state.selectedImages].filter(p => !deletedSet.has(p)));
|
||||
if (state.selectedImage && deletedSet.has(state.selectedImage.path)) {
|
||||
state.selectedImage = null;
|
||||
document.getElementById("wfm-gallery-detail-preview").innerHTML = `<span class="wfm-placeholder">No selection</span>`;
|
||||
document.getElementById("wfm-gallery-detail-filename").textContent = "";
|
||||
const moveBtn = document.getElementById("wfm-gallery-img-move-btn");
|
||||
const delBtn = document.getElementById("wfm-gallery-img-delete-btn");
|
||||
if (moveBtn) moveBtn.disabled = true;
|
||||
if (delBtn) delBtn.disabled = true;
|
||||
}
|
||||
updateBulkBar();
|
||||
renderImages();
|
||||
// フォルダツリーのカウントを更新
|
||||
loadFolderTree();
|
||||
}
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
showToast(`Errors: ${data.errors.join(", ")}`, "error");
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function performMoveImages(paths, destFolder) {
|
||||
try {
|
||||
const res = await fetch(API.imagesMove, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ paths, dest: destFolder }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.moved && data.moved.length > 0) {
|
||||
showToast(`Moved ${data.moved.length} image(s)`, "success");
|
||||
const movedSet = new Set(data.moved.map(m => m.from));
|
||||
state.images = state.images.filter(img => !movedSet.has(img.path));
|
||||
state.selectedImages = new Set([...state.selectedImages].filter(p => !movedSet.has(p)));
|
||||
if (state.selectedImage && movedSet.has(state.selectedImage.path)) {
|
||||
state.selectedImage = null;
|
||||
document.getElementById("wfm-gallery-detail-preview").innerHTML = `<span class="wfm-placeholder">No selection</span>`;
|
||||
document.getElementById("wfm-gallery-detail-filename").textContent = "";
|
||||
const moveBtn = document.getElementById("wfm-gallery-img-move-btn");
|
||||
const delBtn = document.getElementById("wfm-gallery-img-delete-btn");
|
||||
if (moveBtn) moveBtn.disabled = true;
|
||||
if (delBtn) delBtn.disabled = true;
|
||||
}
|
||||
updateBulkBar();
|
||||
renderImages();
|
||||
loadFolderTree();
|
||||
}
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
showToast(`Errors: ${data.errors.join(", ")}`, "error");
|
||||
}
|
||||
if (data.error) {
|
||||
showToast(`Error: ${data.error}`, "error");
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── フォルダツリーを平坦なリストに変換 ──────────────────────────
|
||||
|
||||
function flattenFolderTree(node, result = []) {
|
||||
if (!node) return result;
|
||||
result.push({ name: node.name, abs_path: node.abs_path });
|
||||
if (node.children) {
|
||||
node.children.forEach(child => flattenFolderTree(child, result));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── 移動先選択モーダル ────────────────────────────────────────
|
||||
|
||||
function openMoveModal(paths) {
|
||||
const allFolders = flattenFolderTree(state.folderTree);
|
||||
const destinations = allFolders.filter(f => f.abs_path !== state.currentFolder);
|
||||
|
||||
if (destinations.length === 0) {
|
||||
showToast("No other folders available. Create a subfolder first.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "wfm-gallery-lightbox";
|
||||
overlay.innerHTML = `
|
||||
<div class="wfm-gallery-move-modal">
|
||||
<div class="wfm-gallery-move-modal-title">Move ${paths.length} image(s) to folder:</div>
|
||||
<select id="wfm-gallery-move-dest-sel" class="wfm-select wfm-gallery-move-dest-sel">
|
||||
${destinations.map(f => `<option value="${escapeHtml(f.abs_path)}">${escapeHtml(f.name)}</option>`).join("")}
|
||||
</select>
|
||||
<div class="wfm-gallery-move-modal-footer">
|
||||
<button id="wfm-gallery-move-confirm" class="wfm-btn wfm-btn-primary">Move</button>
|
||||
<button id="wfm-gallery-move-cancel" class="wfm-btn">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
overlay.querySelector("#wfm-gallery-move-cancel").addEventListener("click", () => overlay.remove());
|
||||
overlay.addEventListener("click", (e) => { if (e.target === overlay) overlay.remove(); });
|
||||
overlay.querySelector("#wfm-gallery-move-confirm").addEventListener("click", async () => {
|
||||
const dest = overlay.querySelector("#wfm-gallery-move-dest-sel").value;
|
||||
if (!dest) return;
|
||||
overlay.remove();
|
||||
await performMoveImages(paths, dest);
|
||||
});
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
// ── 一括操作 ─────────────────────────────────────────────────
|
||||
|
||||
async function bulkAddToGroup(groupName) {
|
||||
@@ -998,6 +1235,34 @@ function bindEvents() {
|
||||
bulkSetFavorite(false);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-move")?.addEventListener("click", () => {
|
||||
if (state.selectedImages.size === 0) return;
|
||||
openMoveModal([...state.selectedImages]);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-delete")?.addEventListener("click", () => {
|
||||
if (state.selectedImages.size === 0) return;
|
||||
const count = state.selectedImages.size;
|
||||
if (!confirm(`Delete ${count} selected image(s)? This cannot be undone.`)) return;
|
||||
performDeleteImages([...state.selectedImages]);
|
||||
});
|
||||
|
||||
// フォルダ作成・削除
|
||||
document.getElementById("wfm-gallery-folder-create-btn")?.addEventListener("click", createFolder);
|
||||
document.getElementById("wfm-gallery-folder-delete-btn")?.addEventListener("click", deleteFolder);
|
||||
|
||||
// 詳細パネル: 単体ファイル操作
|
||||
document.getElementById("wfm-gallery-img-move-btn")?.addEventListener("click", () => {
|
||||
if (!state.selectedImage) return;
|
||||
openMoveModal([state.selectedImage.path]);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-img-delete-btn")?.addEventListener("click", () => {
|
||||
if (!state.selectedImage) return;
|
||||
if (!confirm(`Delete "${state.selectedImage.filename}"? This cannot be undone.`)) return;
|
||||
performDeleteImages([state.selectedImage.path]);
|
||||
});
|
||||
|
||||
// 詳細タブ切り替え
|
||||
document.querySelectorAll(".wfm-gallery-detail-tab-btn").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
|
||||
+256
-71
@@ -50,6 +50,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
|
||||
// ============================================
|
||||
@@ -114,7 +150,199 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Generation
|
||||
// Checkpoint Batch
|
||||
// ============================================
|
||||
|
||||
const _ckptBatch = { aborted: false };
|
||||
|
||||
function _parseFolderList(str) {
|
||||
return str.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
|
||||
}
|
||||
|
||||
function _getModelFolder(modelPath) {
|
||||
const normalized = modelPath.replace(/\\/g, "/");
|
||||
const idx = normalized.indexOf("/");
|
||||
return idx === -1 ? "" : normalized.substring(0, idx).toLowerCase();
|
||||
}
|
||||
|
||||
function _filterCheckpoints(checkpoints, includeStr, excludeStr) {
|
||||
const inc = _parseFolderList(includeStr);
|
||||
const exc = _parseFolderList(excludeStr);
|
||||
return checkpoints.filter((m) => {
|
||||
const folder = _getModelFolder(m);
|
||||
if (inc.length > 0 && !inc.includes(folder)) return false;
|
||||
if (exc.length > 0 && exc.includes(folder)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function _updateBatchInfo() {
|
||||
const infoEl = document.getElementById("wfm-ckpt-batch-info");
|
||||
if (!infoEl) return;
|
||||
const inc = document.getElementById("wfm-ckpt-batch-include")?.value || "";
|
||||
const exc = document.getElementById("wfm-ckpt-batch-exclude")?.value || "";
|
||||
const n = _filterCheckpoints(comfyEditor.models.checkpoints, inc, exc).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");
|
||||
|
||||
checkbox?.addEventListener("change", () => {
|
||||
if (body) body.style.display = checkbox.checked ? "block" : "none";
|
||||
if (checkbox.checked) _updateBatchInfo();
|
||||
});
|
||||
|
||||
document.getElementById("wfm-ckpt-batch-include")?.addEventListener("input", _updateBatchInfo);
|
||||
document.getElementById("wfm-ckpt-batch-exclude")?.addEventListener("input", _updateBatchInfo);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 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 inc = document.getElementById("wfm-ckpt-batch-include")?.value || "";
|
||||
const exc = document.getElementById("wfm-ckpt-batch-exclude")?.value || "";
|
||||
const list = _filterCheckpoints(comfyEditor.models.checkpoints, inc, exc);
|
||||
|
||||
if (list.length === 0) {
|
||||
showToast("No checkpoints match the folder filter", "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";
|
||||
|
||||
let completed = 0;
|
||||
let failed = 0;
|
||||
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
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 +352,29 @@ 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;
|
||||
|
||||
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,13 +408,15 @@ export async function initGenerateTab() {
|
||||
comfyEditor.renderAll(comfyUI.currentAnalysis, comfyUI.currentWorkflow);
|
||||
}
|
||||
showToast("Model lists refreshed", "success");
|
||||
_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;
|
||||
await comfyUI.interrupt();
|
||||
showToast("Interrupted", "info");
|
||||
});
|
||||
@@ -303,11 +478,21 @@ 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();
|
||||
|
||||
// Auto-connect on init
|
||||
const connected = await comfyUI.checkConnection();
|
||||
updateStatus(connected);
|
||||
if (connected) {
|
||||
await comfyEditor.loadModelLists();
|
||||
_updateBatchInfo();
|
||||
}
|
||||
|
||||
// Auto-load default workflow (doesn't require ComfyUI connection)
|
||||
|
||||
+67
-8
@@ -23,6 +23,7 @@ const state = {
|
||||
},
|
||||
modelMetadata: {},
|
||||
modelGroups: {},
|
||||
allModelGroups: {}, // { type: { groupName: [models] } } — all types
|
||||
civitaiCache: {},
|
||||
disabledModels: {}, // { type: Set<modelName> }
|
||||
selectMode: false,
|
||||
@@ -657,11 +658,31 @@ function renderTagFilter() {
|
||||
function renderGroupFilter() {
|
||||
const select = document.getElementById("wfm-models-group-filter");
|
||||
if (!select) return;
|
||||
const groups = Object.keys(state.modelGroups).sort();
|
||||
|
||||
// Collect groups across all types with type labels
|
||||
const options = [];
|
||||
const typeOrder = Object.keys(TYPE_LABELS);
|
||||
typeOrder.forEach((type) => {
|
||||
const groups = state.allModelGroups[type];
|
||||
if (!groups) return;
|
||||
const names = Object.keys(groups).sort();
|
||||
names.forEach((g) => {
|
||||
options.push({ type, name: g });
|
||||
});
|
||||
});
|
||||
|
||||
const currentValue = state.groupFilter
|
||||
? `${state.activeModelType}::${state.groupFilter}`
|
||||
: "";
|
||||
|
||||
select.innerHTML =
|
||||
`<option value="">${t("modelsAllGroups")}</option>` +
|
||||
groups.map((g) => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("");
|
||||
select.value = state.groupFilter;
|
||||
options.map(({ type, name }) => {
|
||||
const typeLabel = TYPE_LABELS[type] || type;
|
||||
const value = `${type}::${name}`;
|
||||
const isActive = value === currentValue;
|
||||
return `<option value="${escapeHtml(value)}"${isActive ? " selected" : ""}>[${typeLabel}] ${escapeHtml(name)}</option>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
function renderDirFilter() {
|
||||
@@ -685,8 +706,16 @@ async function fetchModelGroups() {
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
async function fetchAllModelGroups() {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/models/groups");
|
||||
return res.ok ? await res.json() : {};
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
async function saveModelGroups(groups) {
|
||||
state.modelGroups = groups;
|
||||
state.allModelGroups[state.activeModelType] = groups;
|
||||
await fetch("/api/wfm/models/groups", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -1501,6 +1530,7 @@ async function loadModelsForCurrentType() {
|
||||
if (state.loaded[type] && state.modelsByType[type].length > 0) {
|
||||
// Reload groups for this type (groups are per-type)
|
||||
state.modelGroups = await fetchModelGroups();
|
||||
state.allModelGroups[type] = state.modelGroups;
|
||||
renderTagFilter();
|
||||
renderDirFilter();
|
||||
renderGroupFilter();
|
||||
@@ -1520,6 +1550,7 @@ async function loadModelsForCurrentType() {
|
||||
const disabledSet = new Set(Array.isArray(disabledList) ? disabledList : []);
|
||||
state.disabledModels[type] = disabledSet;
|
||||
state.modelGroups = groups;
|
||||
state.allModelGroups[type] = groups;
|
||||
|
||||
// Merge enabled + disabled into one list (dedup)
|
||||
// Guard: ensure models is an array (ComfyUI may return non-array on edge cases)
|
||||
@@ -1628,11 +1659,12 @@ async function batchFetchCivitai() {
|
||||
}
|
||||
|
||||
async function loadMetadataAndModels() {
|
||||
const [metadata, civitaiCache] = await Promise.all([
|
||||
fetchModelMetadata(), fetchCivitaiCache()
|
||||
const [metadata, civitaiCache, allGroups] = await Promise.all([
|
||||
fetchModelMetadata(), fetchCivitaiCache(), fetchAllModelGroups()
|
||||
]);
|
||||
state.modelMetadata = metadata;
|
||||
state.civitaiCache = civitaiCache;
|
||||
state.allModelGroups = allGroups;
|
||||
// groups are loaded per-type inside loadModelsForCurrentType
|
||||
await loadModelsForCurrentType();
|
||||
}
|
||||
@@ -1697,9 +1729,36 @@ export function initModelsTab() {
|
||||
renderModelGrid();
|
||||
});
|
||||
|
||||
// Group filter
|
||||
document.getElementById("wfm-models-group-filter")?.addEventListener("change", (e) => {
|
||||
state.groupFilter = e.target.value;
|
||||
// Group filter — value is "type::groupName" or "" for all
|
||||
document.getElementById("wfm-models-group-filter")?.addEventListener("change", async (e) => {
|
||||
const value = e.target.value;
|
||||
if (!value) {
|
||||
state.groupFilter = "";
|
||||
} else {
|
||||
const sepIdx = value.indexOf("::");
|
||||
const type = value.substring(0, sepIdx);
|
||||
const groupName = value.substring(sepIdx + 2);
|
||||
// Auto-switch model type if different
|
||||
if (type !== state.activeModelType) {
|
||||
document.querySelectorAll(".wfm-models-type-btn").forEach((b) => {
|
||||
b.classList.toggle("active", b.dataset.modelType === type);
|
||||
});
|
||||
state.activeModelType = type;
|
||||
state.searchText = "";
|
||||
state.tagFilter = "";
|
||||
state.badgeFilter = "";
|
||||
state.dirFilter = "";
|
||||
state.statusFilter = "all";
|
||||
state.selectedModel = null;
|
||||
const statusFilter = document.getElementById("wfm-models-status-filter");
|
||||
if (statusFilter) statusFilter.value = "all";
|
||||
const searchInput = document.getElementById("wfm-models-search");
|
||||
if (searchInput) searchInput.value = "";
|
||||
closeSidePanel();
|
||||
await loadModelsForCurrentType();
|
||||
}
|
||||
state.groupFilter = groupName;
|
||||
}
|
||||
state.currentPage = 0;
|
||||
renderModelGrid();
|
||||
});
|
||||
|
||||
+55
-11
@@ -330,10 +330,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:130px;">
|
||||
<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>
|
||||
@@ -342,6 +344,34 @@
|
||||
</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;">Include Folders (empty = all, comma-separated)</div>
|
||||
<input type="text" id="wfm-ckpt-batch-include" class="wfm-input" placeholder="e.g. sdxl, flux">
|
||||
</div>
|
||||
<div style="margin-bottom:6px;">
|
||||
<div style="font-size:11px;color:var(--wfm-text-secondary);margin-bottom:3px;">Exclude Folders (comma-separated)</div>
|
||||
<input type="text" id="wfm-ckpt-batch-exclude" class="wfm-input" placeholder="e.g. old, test">
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Result Display -->
|
||||
<div class="wfm-gen-result">
|
||||
<img id="wfm-gen-result-img" style="display:none;max-width:100%;border-radius:6px;">
|
||||
@@ -509,9 +539,10 @@
|
||||
<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 (top) and LatentImage (bottom) in the left column</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</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: enable via checkbox in the right panel to auto-generate once per checkpoint model; filter by include folders (comma-separated), exclude folders, or leave blank to use all checkpoints; Stop button aborts the loop after the current generation; per-model progress bar shown in amber</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -562,12 +593,13 @@
|
||||
<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">Multi-select with Ctrl+click — bulk operations: Add to Group, Favorite All, Unfavorite All</li>
|
||||
<li id="wfm-help-gallery-6">Detail panel — Info tab: filename, size, date, tags (add/remove), memo with save</li>
|
||||
<li id="wfm-help-gallery-7">Detail panel — Metadata tab: embedded ComfyUI workflow JSON viewer with one-click clipboard copy</li>
|
||||
<li id="wfm-help-gallery-8">Detail panel — Groups tab: create, assign, remove, rename, and delete groups per image</li>
|
||||
<li id="wfm-help-gallery-9">Supports PNG (tEXt/iTXt metadata), JPEG, WebP, GIF; PNG workflow extraction reads ComfyUI-embedded JSON</li>
|
||||
<li id="wfm-help-gallery-10">Folder tree: click a folder to load its images; expand subfolders with ▶ arrow</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>
|
||||
|
||||
@@ -694,6 +726,8 @@
|
||||
<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>
|
||||
|
||||
@@ -703,6 +737,10 @@
|
||||
<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>
|
||||
@@ -755,6 +793,12 @@
|
||||
<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;">
|
||||
|
||||
@@ -1324,10 +1324,21 @@ const renderModelFavorites = async (container) => {
|
||||
const renderModelGroups = async (container) => {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">Loading...</div>`;
|
||||
|
||||
const groups = state.modelGroups;
|
||||
const groupNames = Object.keys(groups);
|
||||
// allGroups is { type: { groupName: [modelName, ...] } }
|
||||
const allGroups = state.modelGroups;
|
||||
|
||||
if (groupNames.length === 0) {
|
||||
// Flatten into [{ modelType, groupName, members }]
|
||||
const flatGroups = [];
|
||||
for (const [modelType, groups] of Object.entries(allGroups)) {
|
||||
if (typeof groups !== "object" || Array.isArray(groups)) continue;
|
||||
for (const [groupName, members] of Object.entries(groups)) {
|
||||
if (Array.isArray(members) && members.length > 0) {
|
||||
flatGroups.push({ modelType, groupName, members });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (flatGroups.length === 0) {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">No groups found.</div>`;
|
||||
return;
|
||||
}
|
||||
@@ -1347,18 +1358,18 @@ const renderModelGroups = async (container) => {
|
||||
container.innerHTML = "";
|
||||
let hasAny = false;
|
||||
|
||||
for (const groupName of groupNames) {
|
||||
const members = (groups[groupName] || []).filter(name => matchesModelSearch(name));
|
||||
if (state.searchText && members.length === 0) continue;
|
||||
if ((groups[groupName] || []).length === 0) continue;
|
||||
for (const { modelType, groupName, members } of flatGroups) {
|
||||
const filtered = members.filter(name => matchesModelSearch(name));
|
||||
if (state.searchText && filtered.length === 0) continue;
|
||||
|
||||
hasAny = true;
|
||||
const section = document.createElement("div");
|
||||
section.className = "wfm-nlp-group-section";
|
||||
|
||||
const typeLabel = MODEL_TYPE_LABELS[modelType] || modelType;
|
||||
const header = document.createElement("div");
|
||||
header.className = "wfm-nlp-group-header collapsed";
|
||||
header.innerHTML = `<span>${esc(groupName)}</span> <span class="wfm-nlp-badge">${members.length}</span>`;
|
||||
header.innerHTML = `<span class="wfm-nlp-model-type-badge">[${esc(typeLabel)}]</span> <span>${esc(groupName)}</span> <span class="wfm-nlp-badge">${filtered.length}</span>`;
|
||||
header.addEventListener("click", () => {
|
||||
const listEl = section.querySelector(".wfm-nlp-group-list");
|
||||
listEl.style.display = listEl.style.display === "none" ? "block" : "none";
|
||||
@@ -1369,17 +1380,9 @@ const renderModelGroups = async (container) => {
|
||||
const listEl = document.createElement("div");
|
||||
listEl.className = "wfm-nlp-group-list";
|
||||
listEl.style.display = "none";
|
||||
for (const name of members) {
|
||||
const type = typeOf[name] || "checkpoint";
|
||||
for (const name of filtered) {
|
||||
const type = typeOf[name] || modelType;
|
||||
const item = createModelItem(name, type);
|
||||
const typeLabel = MODEL_TYPE_LABELS[type] || type;
|
||||
const typeBadgeEl = item.querySelector(".wfm-nlp-item-body");
|
||||
if (typeBadgeEl) {
|
||||
const tb = document.createElement("span");
|
||||
tb.className = "wfm-nlp-model-type-badge";
|
||||
tb.textContent = typeLabel;
|
||||
typeBadgeEl.prepend(tb);
|
||||
}
|
||||
listEl.appendChild(item);
|
||||
}
|
||||
section.appendChild(listEl);
|
||||
|
||||
Reference in New Issue
Block a user