Compare commits

...
5 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 4.6 7360b17842 feat(image-edit): v0.3.54 — Shape ツール追加・Models overlay ボタン修正
- Image Edit タブに Shape ツール(□ / S キー)を追加
  - ShapeTool.js 新規作成: Rect / Ellipse / Line / FreeLine 対応
  - ドラッグ中は overlayCanvas に青い破線プレビュー表示
  - 確定ごとに独立した draw レイヤーとして追加(Undo 1操作で除去可)
  - Tool Options: Shape / Rounded / Fill / Stroke / Opacity / Undo
  - Line / FreeLine 時は Stroke None を非表示(常にストローク有効)
  - S キーショートカット追加
- Models タブ: Batch(B) / Stack(S) overlay ボタンが async await 後に
  e.currentTarget が null になり色が変わらないバグを修正
  → await 前に const btn = e.currentTarget で参照を保存
- ヘルプ更新: Shape ツール説明・S キーショートカットを追記
- DEVLOG / README / pyproject.toml を v0.3.54 に更新

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 17:24:58 +09:00
ketle-man 2ce9fb2ab9 Merge feature/image-edit-tab: v0.3.53 Image Edit Tab 強化 2026-06-25 15:16:33 +09:00
ketle-manandClaude Sonnet 4.6 baa3c32abd feat(image-edit): v0.3.53 — Image Edit Tab 強化(オブジェクト操作・レイヤーロック・ギャラリー保存)
- SelectTool: 移動・リサイズ・回転・Flip H/V によるオブジェクト操作
- TextTool: バウンディングボックスサイズで配置、リサイズ時に再描画(拡大ぼやけ防止)
- テキスト再編集: ダブルクリックで既存テキストレイヤーを再編集
- 回転ハンドル位置バグ修正: _getRotateHandle() の x 座標符号を修正
- レイヤーロック: 🔒/🔓 トグル、ロック中は SelectTool 操作無効(オレンジ表示)
- Layer 1 自動ロック: 初回画像読み込み時に誤移動を防止
- Save to Gallery ボタン: wfs-image-YYYYMMDDHHmmss デフォルト名でギャラリールートに保存
- Gallery タブ「Image Edit」ボタン追加
- Help に Image Edit ページ追加

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 15:16:01 +09:00
ketle-manandClaude Sonnet 4.6 5fb843c6e2 feat(image-edit): Phase 1 — Image Edit タブ追加(Draw・Text・レイヤー・保存)
- static/js/image-edit/LayerManager.js: Layer + LayerManager (追加/削除/順序/可視/不透明度/合成)
- static/js/image-edit/DrawTool.js: ソフトブラシ描画・消しゴム (PaintToolベース)
- static/js/image-edit/TextTool.js: Canvas直描きテキスト・フォント/サイズ/太字/斜体対応
- static/js/image-edit-tab.js: メインUI — ツールバー・アクションバー・ズーム/パン・Undo/Redo・PNG保存・ComfyUIアップロード・From Gallery連携
- static/css/image-edit-tab.css: タブ専用スタイル (ツールバー/キャンバス/レイヤーパネル/テキストオーバーレイ)
- templates/index.html: Image Editタブ追加 + CSS読み込み追加
- static/js/app.js: import・初期化・i18nマップ追加
- static/js/i18n.js: tabImageEdit キー追加 (3言語)

Mask/Blur/Filter/BG Removeはプレースホルダー(Phase 2以降)
キーボードショートカット: B=Draw, T=Text, Ctrl+Z=Undo, Ctrl+Y=Redo, Space+Drag=Pan, Wheel=Zoom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 12:16:04 +09:00
ketle-manandClaude Sonnet 4.6 76dc2cbbf6 feat(genui): LATENT IMAGEにプリセット機能を追加 — 正方形ボタン・解像度ドロップダウン・WHSet/HWSet・カスタムプリセット管理(+/-)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 11:51:14 +09:00
17 changed files with 3098 additions and 6 deletions
+133
View File
@@ -1,5 +1,138 @@
# DEVLOG - ComfyUI-Workflow-Studio
## 2026-06-25: v0.3.54 — Image Edit Shape ツール追加・Models タブ overlay バグ修正
**変更ファイル**: `static/js/image-edit/ShapeTool.js`(新規), `static/js/image-edit-tab.js`, `templates/index.html`, `static/js/models-tab.js`
### Image Edit Tab — Shape ツール(□ / S キー)
Eagle Comic Creator の画像編集タブ形状描画機能を移植。
**対応形状**
- **Rect** — 矩形(Rounded チェックで角丸)
- **Ellipse** — 楕円
- **Line** — 直線(Stroke None 非表示 / 常にストローク有効)
- **FreeLine** — フリーハンド曲線(旧 Curve。Stroke None 非表示 / 常にストローク有効)
**Tool Options バー**
- Shape ドロップダウン、Rounded チェック(Rect/Ellipse のみ表示)
- Fill: None チェック + カラーピッカー(Line/FreeLine 時は非表示)
- Stroke: None チェック + カラーピッカー + 幅入力(Line/FreeLine 時は None チェック非表示)
- Opacity スライダー、↩ Undo ボタン
**動作**
- ドラッグ中: overlayCanvas に青い破線でプレビュー表示(FreeLine はリアルタイム描画)
- ドラッグ離す: 確定 → 独立した draw レイヤーとして LayerManager に追加 → Undo 1操作で除去可
- `ShapeTool.drawShape(ctx, shapeObj)` スタティックメソッドでレイヤー canvas に描画
**実装ファイル**
- `static/js/image-edit/ShapeTool.js`(新規): ShapeTool クラス(プレビュー・確定・静的描画メソッド)
- `image-edit-tab.js`: import・TOOL_DEFS 追加・`_setActiveTool`/`_activateCurrentTool`/`_renderToolOptions`/マウスハンドラー/`_initCanvases` を更新
- `templates/index.html`: □ ツールボタン追加
**ヘルプ更新**
- Image Edit Tab Tools セクション: Shape ツールの説明を追加
- Image Edit Keyboard Shortcuts: `S: Shape tool` を追記(ヘルプ内・グローバル Shortcuts ページ)
- `image-edit-tab.js` キーボードハンドラーに `s` → `"shape"` を追加(ヘルプ記載と実装を一致)
### Models タブ — overlay ボタン非更新バグ修正
`async` イベントハンドラー内で `await` 後に `e.currentTarget` が `null` になる問題を 2箇所修正。
- **B(Batch)ボタン** — 前回修正済み
- **S(Stack)ボタン** — `await toggleStack()` 後に `e.currentTarget.classList.toggle()` を呼んでいたため `TypeError` が発生し黄色に変わらなかった → `const btn = e.currentTarget` を await 前に保存して修正
- **⏸ enable/disable ボタン** — 非 async ハンドラーで `renderModelGrid()` 経由の再描画を使用しており問題なし(確認のみ)
---
## 2026-06-25: v0.3.53 — Image Edit Tab 実装・レイヤーロック・ギャラリー保存
**変更ファイル**: `static/js/image-edit-tab.js`, `static/js/image-edit/LayerManager.js`, `static/js/image-edit/SelectTool.js`, `static/js/image-edit/TextTool.js`, `static/css/image-edit-tab.css`, `templates/index.html`, `static/js/gallery-tab.js`, `py/routes/gallery_routes.py`
### Image Edit Tab(新規タブ)
レイヤー合成ベースの画像編集タブを追加。
**ツール**
- **Select (V)** — クリック選択、ドラッグ移動、コーナーハンドルでリサイズ、上辺ハンドルで回転、Flip H / Flip V / Rotate 角度入力
- **Draw (B)** — フリーハンドブラシ。色・サイズ・ブレンドモード設定
- **Text (T)** — クリック位置にテキスト入力オーバーレイを表示。フォント・サイズ・スタイル・カラー・アライン設定。確定後はテキストのバウンディングボックスサイズのレイヤーとして配置
**レイヤー管理**
- レイヤーパネル(右側): 可視トグル(👁/🚫)、ロックトグル(🔒/🔓)、不透明度スライダー
- アクティブレイヤーのみ描画 vs 全レイヤー合成 を `_compositeMode` フラグで制御
- Undo / Redo(Ctrl+Z / Ctrl+Y、上限 30 ステップ)
**画像ロード**
- ドラッグ&ドロップ、Upload ボタン、Gallery タブ「Image Edit」ボタンで送信
- レイヤーなし → Layer 1 として配置(自動ロック)、レイヤーあり → fitToCanvas でスケールして追加レイヤーとして追加
- New ボタン: WxH プロンプトで新規キャンバス作成
**テキストオブジェクト品質改善**
- `measureText()` でバウンディングボックスサイズのオフスクリーン canvas を生成し、レイヤーの `contentW/H` に設定(余白ゼロ)
- リサイズ後(`transformEnd`)に `_rerenderTextLayer()` を呼び `canvas.width = displayW` で再描画 → 拡大時のぼやけを防止
- `layer.textProps` にテキストプロパティを保存。ダブルクリックで再編集ダイアログを開き、OK で既存レイヤーを上書き更新
- 回転ハンドル位置バグ修正: `_getRotateHandle()` の x 座標計算が `cx - sinR * dist` (符号逆) だったのを `cx + sinR * dist` に修正
### レイヤーロック機能
- `Layer.locked` プロパティ追加(`toJSON/fromJSON` 対応)
- `LayerManager.toggleLocked(id)` メソッド追加
- SelectTool: ロック中はドラッグ開始を禁止(選択・オーバーレイ表示は維持)
- SelectTool `_drawOverlay()`: ロック中はオレンジ破線バウンディングボックス + 中央🔒表示、ハンドル非表示
- Layer 1 読み込み時に `layer1.locked = true` で自動ロック(誤操作防止)
- レイヤーリストに🔒/🔓ボタン追加
### ギャラリーへ保存
- Image Edit タブアクションバーに「Save to Gallery」ボタンを追加(Save PNG 右隣)
- `_saveToGallery()`: `prompt()` でファイル名確認(デフォルト `wfs-image-YYYYMMDDHHmmss`)→ base64 PNG を `POST /wfm/gallery/image/save` へ送信
- `gallery_routes.py`: `save_image_to_gallery()` を追加 — base64 デコード → `_service._allowed_root` 直下に保存。ファイル名サニタイズ・`.png` 自動付与
### Gallery タブ連携
- Gallery ツールバーの Refresh ボタン右隣に「Image Edit」ボタンを追加
- 選択画像を Image Edit タブへ送信(レイヤーあり → 追加レイヤー、なし → Layer 1)
### ヘルプ更新
- Help タブナビに「Image Edit Tab」ページを追加(5カード構成: 概要・ツール・レイヤーパネル・テキスト品質・エクスポート&ナビ+ショートカット)
- Keyboard Shortcuts ページに Image Edit ショートカット(V/B/T/Delete/Ctrl+Z/Y/Space+ドラッグ/ホイール)を追記
- Gallery Tab ヘルプに「Image Edit ボタン」の説明を追記
---
## 2026-06-25: GenUI設定タブ LATENT IMAGE にプリセット機能を追加
**変更ファイル**: `static/js/comfyui-editor.js`
### 変更内容
**正方形プリセットボタン**
Applyボタン下部に固定サイズボタンを追加。クリックするとWidth・Height両方に同じ値をセットする。
- `512` `768` `1024` `2048` — よく使う正方形サイズ
- `1K`(1024) `2K`(2048) `4K`(4096) — 映像規格対応の正方形サイズ
**解像度ドロップダウン + WHSet / HWSet ボタン**
ドロップダウンからアスペクト比プリセットを選択し、横並びの2ボタンでWidth/Heightにセット。
- `WHSet` — 選択値をそのままWidth/Heightにセット(例: 720x1280 → W=720, H=1280)
- `HWSet` — W/Hを入れ替えてセット(例: 720x1280 → W=1280, H=720)
デフォルト10件(削除不可): `720x1280` `768x1024` `1152x896` `1344x768` `832x1216` `832x1248` `832x1280` `1920x1080` `2560x1440` `3840x2160`
**カスタムプリセット管理(+/-ボタン)**
- `+` — 現在のWidth/Height値をカスタムプリセットの先頭に追加。デフォルトや既存カスタムと重複する場合は無視
- `−` — 選択中のカスタムプリセットを削除。デフォルト行は削除不可(`data-default="1"` で判定)
カスタムプリセットは `wfm_latent_presets` キーでlocalStorageに永続化。ドロップダウンはカスタム→デフォルトの順で表示。
---
## 2026-06-24: GenUI ModelでLoRA適用後、Modelサブタブ再表示時に値がリセットされるバグ修正
**変更ファイル**: `static/js/comfyui-editor.js`
+28 -2
View File
@@ -18,7 +18,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.3.52-green)
![Version](https://img.shields.io/badge/version-0.3.54-green)
## Screenshots
@@ -208,6 +208,22 @@ Two independent modes selectable via **[Image Loop] / [Gallery]** toggle buttons
- **DB tab** — searchable SQLite database of all tagged images; click a row to open the edit panel and modify WD Tags / VLM Tags; Save updates the record, Delete removes it; Export CSV downloads all records
- **Dependencies** — install into ComfyUI's embedded Python: `python_embedded\python.exe -m pip install -r requirements.txt`; for GPU inference use `onnxruntime-gpu`; TensorFlow (DeepDanbooru) is optional and commented out in `requirements.txt`
### Image Edit Tab (v0.3.53)
- **Layer-based image editor** — compose images with multiple layers (Image, Text, Draw types) and export the composite as PNG
- **Loading images** — drag & drop onto the canvas, Upload button, or send from the Gallery tab via the **Image Edit** toolbar button; first image becomes Layer 1 (auto-locked), subsequent images are added as new layers scaled to fit the canvas
- **New button** — create a blank canvas with custom dimensions (WxH prompt); clears all existing layers
- **Tools** — Select (V), Draw (B), Text (T), Shape (S); tool options bar updates per active tool
- **Select** — click to select; drag to move; drag corner handles to resize; drag circle handle to rotate; Flip H / Flip V / Rotate angle in the options bar; double-click a text layer to re-edit its content
- **Draw** — freehand brush; options: color, brush size, blend mode
- **Text** — click to place; configure font, size, bold/italic, align, and color; placed as an exact-size text layer sized to the measured bounding box; double-click to re-edit
- **Shape** — drag to draw geometric shapes (Rect / Ellipse / Line / FreeLine); options: shape type, Rounded toggle (Rect/Ellipse), Fill color, Stroke color + width, Opacity; each committed shape becomes an independent draw layer; Stroke None hidden for Line/FreeLine (stroke always active)
- **Layer panel** — layer list with visibility (👁/🚫) and lock (🔒/🔓) toggles; opacity slider; type icons (🖼 image / T text / ✏ draw); Layer 1 is automatically locked on first image load
- **Layer lock** — locked layers show an orange bounding box and 🔒 icon on the canvas; move/resize/rotate are disabled while locked; click the 🔓 button in the layer row to unlock
- **Text quality** — text layers are rendered at their measured bounding-box size; resizing with the Select tool regenerates the canvas at the new display resolution so text stays sharp
- **Export** — Save PNG (download composite locally); **Save to Gallery** (saves to Gallery root folder with a timestamped default name `wfs-image-YYYYMMDDHHmmss`); **Send to ComfyUI** (uploads to ComfyUI input folder for use in Load Image nodes)
- **Canvas navigation** — scroll-wheel zoom, Space + drag to pan; zoom indicator in the bottom bar
- **Undo / Redo** — Ctrl+Z / Ctrl+Y (or toolbar buttons); keyboard shortcuts: V (Select), B (Draw), T (Text), S (Shape), Delete (remove selected layer when 2+ exist)
### AI TOOL Tab (v0.3.14)
- **4-pane layout** — Translation | Chat | TOOLS | Settings; all panes always visible simultaneously; no sub-tab switching required
- **Translation pane** — translate text between Japanese, English, Chinese, or a custom Free language using Ollama or LM Studio; language selectors with ⇄ swap button (swaps both language selectors and text content); selections saved automatically
@@ -242,7 +258,7 @@ Two independent modes selectable via **[Image Loop] / [Gallery]** toggle buttons
- **⚙ 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)
- **Sidebar navigation** — 2-column layout: left sidebar (14 topics) + right content pane; click any topic to switch the displayed content
- **Sidebar navigation** — 2-column layout: left sidebar (15 topics) + right content pane; click any topic to switch the displayed content
- **Support** — fixed at the bottom of the sidebar; shows GitHub and Ko-fi links in the right pane
- **Feature list** — overview of all features organized by tab
- **Keyboard Shortcuts** and **Troubleshooting** sections included
@@ -334,6 +350,16 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
## Changelog
### v0.3.54
- **Image Edit — Shape tool (S)** — new Shape tool added to the Image Edit toolbar; draw Rect, Ellipse, Line, and FreeLine shapes by dragging; each committed shape becomes an independent draw layer that can be undone in a single step; Tool Options: shape type selector, Rounded toggle (Rect/Ellipse only), Fill color + None toggle (hidden for Line/FreeLine), Stroke color + width (Stroke None hidden for Line/FreeLine where stroke is always active), Opacity slider, Undo button; blue dashed outline previews the shape during drag; keyboard shortcut **S** activates the tool
- **Models tab — fix B/S overlay buttons not highlighting** — the Batch (B) and Stack (S) card overlay buttons failed to turn yellow after clicking because `e.currentTarget` is nulled by the browser after an `async` event handler yields at `await`; fixed by capturing `const btn = e.currentTarget` before the await in both handlers
### v0.3.53
- **Image Edit Tab** — new layer-based image editing tab with Select / Draw / Text tools, multi-layer compositing, canvas zoom & pan, and Undo/Redo; text layers are sized to exact bounding-box dimensions and regenerated at display resolution on resize to prevent blurring; double-click a text layer to re-edit its content; Gallery tab gains an "Image Edit" toolbar button to send the selected image directly to the editor
- **Image Edit — Layer lock** — lock icon (🔒/🔓) on each layer row; locked layers display an orange bounding box and ignore all Select-tool transforms; Layer 1 is auto-locked when the first image is loaded to prevent accidental moves
- **Image Edit — Save to Gallery** — "Save to Gallery" button (next to Save PNG) saves the composite image to the Gallery root folder; filename defaults to `wfs-image-YYYYMMDDHHmmss`; backed by new `POST /wfm/gallery/image/save` API endpoint
- **Help tab — Image Edit page** — new dedicated help page covering tools, layer panel, text quality, export options, and keyboard shortcuts
### v0.3.52
- **GenerateUI Model tab — fix LoRA selection reset when switching subtabs** — applying a LoRA via "GenUI Model" button and then switching to another subTab (Prompt/Image/Settings) and back to Model caused the LoRA selector, syntax display, and trigger words to revert to the original workflow values; fixed by reading `currentVal` directly from `currentWorkflow` instead of the stale `currentAnalysis`, and by saving/restoring the Single tab's syntax and trigger words across re-renders
+37
View File
@@ -2,9 +2,11 @@
Gallery Routes - ギャラリータブ用APIエンドポイント
"""
import asyncio
import base64
import json
import mimetypes
import logging
import re
from pathlib import Path
from aiohttp import web
@@ -53,6 +55,7 @@ def setup_routes(app: web.Application):
app.router.add_get("/wfm/gallery/image/serve", serve_image)
app.router.add_get("/wfm/gallery/image/thumb", serve_thumb)
app.router.add_post("/wfm/gallery/image/meta", save_image_meta)
app.router.add_post("/wfm/gallery/image/save", save_image_to_gallery)
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)
@@ -257,6 +260,40 @@ async def toggle_favorite(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
async def save_image_to_gallery(request: web.Request) -> web.Response:
"""Image Edit Tab からの PNG をギャラリーのルートフォルダに保存する。"""
try:
body = await request.json()
filename = body.get("filename", "").strip()
image_data = body.get("imageData", "")
if not filename or not image_data:
return web.json_response({"error": "filename and imageData required"}, status=400)
if _service._allowed_root is None:
return web.json_response({"error": "Gallery root not configured. Open Gallery tab and set output folder first."}, status=500)
# ファイル名サニタイズ(OSで使えない文字を除去)
safe = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", filename)
if not safe.lower().endswith(".png"):
safe += ".png"
# base64 data URL をデコード
raw = image_data
if "," in raw:
raw = raw.split(",", 1)[1]
image_bytes = base64.b64decode(raw)
save_path = _service._allowed_root / safe
save_path.write_bytes(image_bytes)
logger.info("save_image_to_gallery: saved %s (%d bytes)", save_path, len(image_bytes))
return web.json_response({"ok": True, "path": str(save_path)})
except Exception as e:
logger.error("save_image_to_gallery error: %s", e)
return web.json_response({"error": str(e)}, status=500)
# ──────────────────────────────────────────────────────────────
# グループ管理
# ──────────────────────────────────────────────────────────────
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-workflow-studio"
description = "A comprehensive workflow, asset management, and generation UI plugin for ComfyUI. Manage workflows, models, images, and prompts; batch generation and Image Feeder in the GenerateUI tab; library side panel with canvas drag & drop and AI tools."
version = "0.3.52"
version = "0.3.54"
license = "MIT"
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+399
View File
@@ -0,0 +1,399 @@
/* =============================================
Image Edit Tab
============================================= */
#wfm-tab-image-edit {
padding: 0;
overflow: hidden;
}
.ie-editor {
display: flex;
height: 100%;
overflow: hidden;
background: var(--wfm-bg);
}
/* =============================================
Left Toolbar
============================================= */
.ie-toolbar {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 8px 5px;
background: var(--wfm-surface);
border-right: 1px solid var(--wfm-border);
width: 46px;
flex-shrink: 0;
}
.ie-tool-btn {
width: 34px;
height: 34px;
border: 1px solid transparent;
background: transparent;
border-radius: 6px;
cursor: pointer;
font-size: 15px;
font-weight: 600;
color: var(--wfm-text);
display: flex;
align-items: center;
justify-content: center;
transition: background 0.12s, border-color 0.12s;
user-select: none;
position: relative;
}
.ie-tool-btn:hover {
background: var(--wfm-surface-hover);
border-color: var(--wfm-border);
}
.ie-tool-btn.active {
background: var(--wfm-primary);
border-color: var(--wfm-primary);
color: #fff;
}
.ie-tool-placeholder {
opacity: 0.38;
}
.ie-tool-placeholder::after {
content: "";
position: absolute;
bottom: 3px;
right: 3px;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--wfm-text-secondary);
opacity: 0.5;
}
/* =============================================
Center column
============================================= */
.ie-center {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
min-width: 0;
}
/* Action bar */
.ie-action-bar {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
border-bottom: 1px solid var(--wfm-border);
background: var(--wfm-surface);
flex-shrink: 0;
flex-wrap: wrap;
}
/* Tool options bar */
.ie-tool-options {
display: flex;
align-items: center;
gap: 14px;
padding: 5px 10px;
border-bottom: 1px solid var(--wfm-border);
background: var(--wfm-surface);
flex-shrink: 0;
flex-wrap: wrap;
min-height: 36px;
font-size: 12px;
}
.ie-opt-group {
display: flex;
align-items: center;
gap: 5px;
}
.ie-opt-group label {
color: var(--wfm-text-secondary);
white-space: nowrap;
}
.ie-opt-select {
font-size: 12px;
padding: 2px 5px;
background: var(--wfm-surface);
color: var(--wfm-text);
border: 1px solid var(--wfm-border);
border-radius: 4px;
cursor: pointer;
}
.ie-opt-input {
font-size: 12px;
padding: 2px 5px;
background: var(--wfm-surface);
color: var(--wfm-text);
border: 1px solid var(--wfm-border);
border-radius: 4px;
}
.ie-opt-active {
background: var(--wfm-primary) !important;
color: #fff !important;
border-color: var(--wfm-primary) !important;
}
/* Canvas wrap */
.ie-canvas-wrap {
flex: 1;
overflow: hidden;
position: relative;
background: #1a1a1a;
background-image:
linear-gradient(45deg, #222 25%, transparent 25%),
linear-gradient(-45deg, #222 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #222 75%),
linear-gradient(-45deg, transparent 75%, #222 75%);
background-size: 20px 20px;
background-position: 0 0, 0 10px, 10px -10px, -10px 0;
}
.ie-canvas-container {
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
line-height: 0;
box-shadow: 0 2px 20px rgba(0,0,0,0.6);
}
.ie-canvas-container canvas {
position: absolute;
top: 0;
left: 0;
display: block;
}
#ie-canvas-bg {
z-index: 1;
}
#ie-canvas-draw {
z-index: 2;
cursor: crosshair;
}
#ie-canvas-overlay {
z-index: 3;
cursor: default;
pointer-events: none; /* SelectTool.activate()でautoに変更 */
}
.ie-placeholder {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--wfm-text-secondary);
font-size: 14px;
pointer-events: none;
gap: 8px;
}
.ie-placeholder-icon {
font-size: 40px;
opacity: 0.3;
}
/* Zoom bar */
.ie-zoom-bar {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-top: 1px solid var(--wfm-border);
background: var(--wfm-surface);
font-size: 12px;
flex-shrink: 0;
color: var(--wfm-text-secondary);
}
#ie-zoom-label {
min-width: 38px;
text-align: right;
color: var(--wfm-text);
}
/* =============================================
Right Panel (Layers)
============================================= */
.ie-right-panel {
width: 190px;
flex-shrink: 0;
display: flex;
flex-direction: column;
border-left: 1px solid var(--wfm-border);
background: var(--wfm-surface);
overflow: hidden;
}
.ie-layers-header {
display: flex;
align-items: center;
gap: 2px;
padding: 5px 6px;
border-bottom: 1px solid var(--wfm-border);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.4px;
color: var(--wfm-text-secondary);
flex-shrink: 0;
}
.ie-layers-header > span {
flex: 1;
}
.ie-layer-list {
flex: 1;
overflow-y: auto;
padding: 4px;
}
.ie-layer-item {
display: flex;
align-items: center;
gap: 5px;
padding: 4px 5px;
border-radius: 5px;
cursor: pointer;
font-size: 12px;
user-select: none;
transition: background 0.1s;
}
.ie-layer-item:hover {
background: var(--wfm-surface-hover);
}
.ie-layer-item.active {
background: rgba(90, 110, 220, 0.22);
outline: 1px solid rgba(90, 110, 220, 0.4);
}
.ie-layer-thumb {
width: 30px;
height: 30px;
border: 1px solid var(--wfm-border);
border-radius: 3px;
flex-shrink: 0;
object-fit: cover;
background:
repeating-conic-gradient(#888 0% 25%, transparent 0% 50%)
0 0 / 8px 8px;
}
.ie-layer-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.ie-layer-vis-btn {
background: none;
border: none;
cursor: pointer;
font-size: 13px;
padding: 0;
line-height: 1;
color: var(--wfm-text);
opacity: 0.5;
flex-shrink: 0;
transition: opacity 0.1s;
}
.ie-layer-vis-btn:hover {
opacity: 1;
}
.ie-opacity-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-top: 1px solid var(--wfm-border);
font-size: 12px;
flex-shrink: 0;
color: var(--wfm-text-secondary);
}
.ie-opacity-row input[type="range"] {
flex: 1;
}
#ie-layer-opacity-label {
min-width: 32px;
text-align: right;
color: var(--wfm-text);
}
/* =============================================
Text Tool Overlay
============================================= */
.ie-text-overlay {
position: absolute;
z-index: 100;
background: var(--wfm-surface);
border: 1px solid var(--wfm-border);
border-radius: 6px;
padding: 8px;
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
display: flex;
flex-direction: column;
gap: 6px;
min-width: 180px;
}
.ie-text-textarea {
width: 200px;
resize: vertical;
background: var(--wfm-bg);
color: var(--wfm-text);
border: 1px solid var(--wfm-border);
border-radius: 4px;
padding: 6px;
font-size: 13px;
font-family: inherit;
min-height: 60px;
}
.ie-text-btn-row {
display: flex;
gap: 6px;
justify-content: flex-end;
}
/* =============================================
Scrollbar
============================================= */
.ie-layer-list::-webkit-scrollbar {
width: 4px;
}
.ie-layer-list::-webkit-scrollbar-thumb {
background: var(--wfm-border);
border-radius: 2px;
}
+3 -1
View File
@@ -91,7 +91,7 @@ function initTabs() {
function applyI18nToHtml() {
// Tab labels
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", metadata: "tabMetadata", gallery: "tabGallery", settings: "tabSettings", help: "tabHelp", ai: "tabAi", tagger: "tabTagger" };
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", metadata: "tabMetadata", gallery: "tabGallery", "image-edit": "tabImageEdit", settings: "tabSettings", help: "tabHelp", ai: "tabAi", tagger: "tabTagger" };
document.querySelectorAll(".wfm-tab").forEach((tab) => {
const key = tabMap[tab.dataset.tab];
if (key) tab.textContent = t(key);
@@ -514,6 +514,7 @@ import { initGalleryTab } from "./gallery-tab.js";
import { initMetadataTab } from "./metadata-tab.js";
import { initAiTab } from "./ai-tab.js";
import { initTaggerTab } from "./tagger-tab.js";
import { imageEditTab } from "./image-edit-tab.js";
// Apply saved theme immediately to prevent flash of default theme
applyTheme(getSavedTheme());
@@ -552,6 +553,7 @@ document.addEventListener("DOMContentLoaded", () => {
initGalleryTab();
initAiTab();
initTaggerTab();
imageEditTab.init();
console.log("Workflow Studio: App initialized");
});
+117
View File
@@ -5,6 +5,42 @@
import { comfyUI } from "./comfyui-client.js";
import { syncJsonHighlight } from "./json-highlight.js";
// ── Latent Image preset state ─────────────────────────────
const _LATENT_PRESET_KEY = "wfm_latent_presets";
const _LATENT_DEFAULT_PRESETS = [
{ w: 720, h: 1280 }, { w: 768, h: 1024 }, { w: 1152, h: 896 },
{ w: 1344, h: 768 }, { w: 832, h: 1216 }, { w: 832, h: 1248 },
{ w: 832, h: 1280 }, { w: 1920, h: 1080 }, { w: 2560, h: 1440 },
{ w: 3840, h: 2160 },
];
function _loadLatentPresets() {
try {
const raw = localStorage.getItem(_LATENT_PRESET_KEY);
return raw ? JSON.parse(raw) : [];
} catch { return []; }
}
function _saveLatentPresets(list) {
localStorage.setItem(_LATENT_PRESET_KEY, JSON.stringify(list));
}
function _buildPresetOptions(customPresets) {
const customs = customPresets.map((p) =>
`<option value="${p.w}x${p.h}">${p.w}x${p.h}</option>`
).join("");
const defaults = _LATENT_DEFAULT_PRESETS.map((p) =>
`<option value="${p.w}x${p.h}" data-default="1">${p.w}x${p.h}</option>`
).join("");
return customs + defaults;
}
function _refreshPresetSelect(customPresets) {
const sel = document.getElementById("wfm-latent-preset-select");
if (!sel) return;
sel.innerHTML = _buildPresetOptions(customPresets);
}
// ── LoRA pane stack state ─────────────────────────────────
// { modelFullPath: { m: number, c: number } }
let _stackStrengths = {};
@@ -867,6 +903,25 @@ export const comfyEditor = {
<input type="number" class="wfm-input" id="wfm-settings-batch" value="${latent.batch_size ?? 1}" min="1" max="64">
</div>
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-latent-apply">Apply</button>
<div style="margin-top:10px;border-top:1px solid var(--wfm-border);padding-top:10px;">
<div style="display:flex;flex-wrap:wrap;gap:4px;margin-bottom:8px;">
${[512, 768, 1024, 2048].map((s) => `<button class="wfm-btn wfm-btn-sm wfm-latent-sq-btn" data-size="${s}">${s}</button>`).join("")}
<button class="wfm-btn wfm-btn-sm wfm-latent-sq-btn" data-size="1024">1K</button>
<button class="wfm-btn wfm-btn-sm wfm-latent-sq-btn" data-size="2048">2K</button>
<button class="wfm-btn wfm-btn-sm wfm-latent-sq-btn" data-size="4096">4K</button>
</div>
<div style="display:flex;align-items:center;gap:4px;margin-bottom:6px;">
<select id="wfm-latent-preset-select" style="flex:1;padding:4px 6px;font-size:12px;background:var(--wfm-surface);color:var(--wfm-text);border:1px solid var(--wfm-border);border-radius:4px;min-width:0;">
${_buildPresetOptions(_loadLatentPresets())}
</select>
<button class="wfm-btn wfm-btn-sm" id="wfm-latent-wh-set" title="Width→左、Height→右にセット">WHSet</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-latent-hw-set" title="Width→右、Height→左にセット">HWSet</button>
</div>
<div style="display:flex;gap:4px;">
<button class="wfm-btn wfm-btn-sm" id="wfm-latent-preset-add" title="現在のWidth/Heightをプリセットに追加">+</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-latent-preset-del" title="選択中のカスタムプリセットを削除">−</button>
</div>
</div>
` : "<p class='wfm-placeholder'>No EmptyLatentImage node found</p>"}
</div>
</div>
@@ -896,6 +951,68 @@ export const comfyEditor = {
inputs.batch_size = parseInt(document.getElementById("wfm-settings-batch")?.value) || 1;
_syncRawJson();
});
// 正方形プリセットボタン
document.querySelectorAll(".wfm-latent-sq-btn").forEach((btn) => {
btn.addEventListener("click", () => {
const size = parseInt(btn.dataset.size);
const w = document.getElementById("wfm-settings-width");
const h = document.getElementById("wfm-settings-height");
if (w) w.value = size;
if (h) h.value = size;
});
});
// ドロップダウン WHSet / HWSet
document.getElementById("wfm-latent-wh-set")?.addEventListener("click", () => {
const val = document.getElementById("wfm-latent-preset-select")?.value;
if (!val) return;
const [pw, ph] = val.split("x").map(Number);
const w = document.getElementById("wfm-settings-width");
const h = document.getElementById("wfm-settings-height");
if (w) w.value = pw;
if (h) h.value = ph;
});
document.getElementById("wfm-latent-hw-set")?.addEventListener("click", () => {
const val = document.getElementById("wfm-latent-preset-select")?.value;
if (!val) return;
const [pw, ph] = val.split("x").map(Number);
const w = document.getElementById("wfm-settings-width");
const h = document.getElementById("wfm-settings-height");
if (w) w.value = ph;
if (h) h.value = pw;
});
// + ボタン: 現在のW/Hをカスタムプリセットの先頭に追加
document.getElementById("wfm-latent-preset-add")?.addEventListener("click", () => {
const wVal = parseInt(document.getElementById("wfm-settings-width")?.value);
const hVal = parseInt(document.getElementById("wfm-settings-height")?.value);
if (!wVal || !hVal) return;
const customs = _loadLatentPresets();
const key = `${wVal}x${hVal}`;
const isDefault = _LATENT_DEFAULT_PRESETS.some((p) => p.w === wVal && p.h === hVal);
const alreadyCustom = customs.some((p) => p.w === wVal && p.h === hVal);
if (isDefault || alreadyCustom) return;
customs.unshift({ w: wVal, h: hVal });
_saveLatentPresets(customs);
_refreshPresetSelect(customs);
// 追加した項目を選択状態にする
const sel = document.getElementById("wfm-latent-preset-select");
if (sel) sel.value = key;
});
// − ボタン: 選択中のカスタムプリセットを削除(デフォルトは削除不可)
document.getElementById("wfm-latent-preset-del")?.addEventListener("click", () => {
const sel = document.getElementById("wfm-latent-preset-select");
if (!sel) return;
const opt = sel.options[sel.selectedIndex];
if (!opt || opt.dataset.default === "1") return;
const [dw, dh] = sel.value.split("x").map(Number);
const customs = _loadLatentPresets().filter((p) => !(p.w === dw && p.h === dh));
_saveLatentPresets(customs);
_refreshPresetSelect(customs);
});
},
renderImageTab(analysis, containerId) {
+14
View File
@@ -1457,6 +1457,20 @@ function bindEvents() {
loadImages();
});
// 選択画像を Image Edit タブへ送信
document.getElementById("wfm-gallery-send-image-edit-btn")?.addEventListener("click", () => {
if (!state.selectedImage) {
showToast("Please select an image first", "info");
return;
}
const url = API.serveImage(state.selectedImage.path);
const name = (state.selectedImage.filename || "gallery-image").replace(/\.[^.]+$/, "");
if (window._wfmImageEditTab) {
document.querySelector('[data-tab="image-edit"]')?.click();
window._wfmImageEditTab.loadFromUrl(url, name);
}
});
// 検索
document.getElementById("wfm-gallery-search")?.addEventListener("input", (e) => {
state.search = e.target.value;
+3
View File
@@ -485,6 +485,7 @@ const LANGUAGES = {
tabAi: "AI TOOL",
tabTagger: "Tagger",
tabImageEdit: "Image Edit",
// -- Tagger Tab --
taggerSingleTab: "Single",
@@ -1364,6 +1365,7 @@ const LANGUAGES = {
tabAi: "AI TOOL",
tabTagger: "Tagger",
tabImageEdit: "Image Edit",
// -- Tagger Tab --
taggerSingleTab: "シングル",
@@ -2243,6 +2245,7 @@ const LANGUAGES = {
tabAi: "AI TOOL",
tabTagger: "Tagger",
tabImageEdit: "Image Edit",
// -- Tagger Tab --
taggerSingleTab: "单张",
File diff suppressed because it is too large Load Diff
+134
View File
@@ -0,0 +1,134 @@
/**
* Image Edit Tab - Draw Tool
* Inspired by comfyui-mask-editor-one PaintTool.js
* Supports color drawing and erasing with a soft round brush.
*/
export class DrawTool {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.brushSize = 20;
this.hardness = 0.8; // 0.0 = very soft, 1.0 = hard edge
this.opacity = 1.0;
this.color = "#ff0000";
this.mode = "draw"; // "draw" | "erase"
this._drawing = false;
this._lastX = 0;
this._lastY = 0;
// Cached stamp canvas
this._stamp = null;
this._stampSize = 0;
this._stampHard = 0;
this._stampColor = null;
this._onChange = null;
}
setCanvas(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this._stamp = null;
}
onChange(fn) { this._onChange = fn; }
activate() {
this.canvas.style.cursor = "crosshair";
}
deactivate() {
this._drawing = false;
this.canvas.style.cursor = "";
}
onMouseDown(x, y) {
this._drawing = true;
this._lastX = x;
this._lastY = y;
this._paint(x, y);
}
onMouseMove(x, y) {
if (!this._drawing) return;
this._paintLine(this._lastX, this._lastY, x, y);
this._lastX = x;
this._lastY = y;
}
onMouseUp() {
if (this._drawing) {
this._drawing = false;
if (this._onChange) this._onChange();
}
}
onMouseLeave() {
if (this._drawing) this.onMouseUp();
}
_getStamp() {
if (
this._stamp &&
this._stampSize === this.brushSize &&
this._stampHard === this.hardness &&
this._stampColor === this.color
) return this._stamp;
const size = Math.max(1, Math.round(this.brushSize));
const sc = document.createElement("canvas");
sc.width = size;
sc.height = size;
const sctx = sc.getContext("2d");
const cx = size / 2, cy = size / 2, r = size / 2;
const innerR = r * (1 - Math.min(this.hardness, 0.99)) * 0.95;
const grd = sctx.createRadialGradient(cx, cy, innerR, cx, cy, r);
grd.addColorStop(0, this.color);
grd.addColorStop(1, this.color + "00");
sctx.fillStyle = grd;
sctx.beginPath();
sctx.arc(cx, cy, r, 0, Math.PI * 2);
sctx.fill();
this._stamp = sc;
this._stampSize = size;
this._stampHard = this.hardness;
this._stampColor = this.color;
return sc;
}
_paint(x, y) {
const stamp = this._getStamp();
const s = stamp.width;
this.ctx.save();
this.ctx.globalAlpha = this.opacity;
if (this.mode === "erase") {
this.ctx.globalCompositeOperation = "destination-out";
}
this.ctx.drawImage(stamp, x - s / 2, y - s / 2);
this.ctx.restore();
}
_paintLine(x0, y0, x1, y1) {
const dist = Math.hypot(x1 - x0, y1 - y0);
const spacing = Math.max(1, this.brushSize * 0.2);
const steps = Math.max(1, Math.ceil(dist / spacing));
for (let i = 1; i <= steps; i++) {
const t = i / steps;
this._paint(x0 + (x1 - x0) * t, y0 + (y1 - y0) * t);
}
}
static getCanvasPos(canvas, event) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
return {
x: (event.clientX - rect.left) * scaleX,
y: (event.clientY - rect.top) * scaleY,
};
}
}
+213
View File
@@ -0,0 +1,213 @@
/**
* Image Edit Tab - Layer & LayerManager
* Inspired by comfyui-mask-editor-one LayerManager.js
*/
export class Layer {
constructor(name, type, contentW, contentH) {
this.id = crypto.randomUUID();
this.name = name;
this.type = type; // 'draw' | 'image' | 'text'
// layer.canvas のサイズ = コンテンツのネイティブ解像度
this.canvas = document.createElement("canvas");
this.canvas.width = contentW;
this.canvas.height = contentH;
this.ctx = this.canvas.getContext("2d");
// 表示プロパティ
this.visible = true;
this.opacity = 1.0;
this.blendMode = "source-over";
// 変換プロパティ(キャンバス座標系での配置)
this.x = 0; // 左上X
this.y = 0; // 左上Y
this.displayW = contentW; // 表示幅
this.displayH = contentH; // 表示高さ
this.rotation = 0; // 度
this.flipX = false;
this.flipY = false;
this.textProps = null; // テキストレイヤー用プロパティ(再編集・再描画に使用)
this.locked = false; // ロック中は SelectTool の変形を禁止
}
clear() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
getThumbnailDataURL(size = 32) {
const thumb = document.createElement("canvas");
thumb.width = size;
thumb.height = size;
const ctx = thumb.getContext("2d");
ctx.fillStyle = "#aaa";
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = "#fff";
for (let x = 0; x < size; x += 8)
for (let y = 0; y < size; y += 8)
if ((x / 8 + y / 8) % 2 === 0) ctx.fillRect(x, y, 8, 8);
ctx.drawImage(this.canvas, 0, 0, size, size);
return thumb.toDataURL("image/png");
}
toJSON() {
return {
id: this.id, name: this.name, type: this.type,
imageData: this.canvas.toDataURL("image/png"),
visible: this.visible, opacity: this.opacity, blendMode: this.blendMode,
x: this.x, y: this.y, displayW: this.displayW, displayH: this.displayH,
rotation: this.rotation, flipX: this.flipX, flipY: this.flipY,
textProps: this.textProps ?? null,
locked: this.locked ?? false,
};
}
static fromJSON(json) {
const cw = json.contentW ?? json.displayW ?? 512;
const ch = json.contentH ?? json.displayH ?? 512;
const layer = new Layer(json.name, json.type, cw, ch);
layer.id = json.id;
layer.visible = json.visible ?? true;
layer.opacity = json.opacity ?? 1.0;
layer.blendMode = json.blendMode ?? "source-over";
layer.x = json.x ?? 0;
layer.y = json.y ?? 0;
layer.displayW = json.displayW ?? cw;
layer.displayH = json.displayH ?? ch;
layer.rotation = json.rotation ?? 0;
layer.flipX = json.flipX ?? false;
layer.flipY = json.flipY ?? false;
layer.textProps = json.textProps ?? null;
layer.locked = json.locked ?? false;
if (json.imageData) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => { layer.ctx.drawImage(img, 0, 0, cw, ch); resolve(layer); };
img.onerror = () => resolve(layer);
img.src = json.imageData;
});
}
return Promise.resolve(layer);
}
/** 変換行列を ctx に適用してから drawImage できる状態にする */
static applyTransform(ctx, layer) {
const cx = layer.x + layer.displayW / 2;
const cy = layer.y + layer.displayH / 2;
ctx.translate(cx, cy);
if (layer.rotation) ctx.rotate(layer.rotation * Math.PI / 180);
ctx.scale(
(layer.flipX ? -1 : 1) * (layer.displayW / layer.canvas.width),
(layer.flipY ? -1 : 1) * (layer.displayH / layer.canvas.height),
);
}
}
export class LayerManager {
constructor(width, height) {
this.width = width;
this.height = height;
this.layers = []; // 先頭 = 最前面
this.activeIndex = 0;
this._listeners = [];
}
get activeLayer() { return this.layers[this.activeIndex] ?? null; }
/**
* @param {string} type "draw" | "image" | "text"
* @param {string} name
* @param {object} opts { contentW, contentH, displayW, displayH, x, y }
*/
addLayer(type = "draw", name = null, opts = {}) {
const n = name ?? `Layer ${this.layers.length + 1}`;
const cw = opts.contentW ?? this.width;
const ch = opts.contentH ?? this.height;
const layer = new Layer(n, type, cw, ch);
layer.displayW = opts.displayW ?? cw;
layer.displayH = opts.displayH ?? ch;
layer.x = opts.x ?? 0;
layer.y = opts.y ?? 0;
this.layers.splice(this.activeIndex, 0, layer);
this._emit("change");
return layer;
}
deleteLayer(id) {
if (this.layers.length <= 1) return;
const idx = this.layers.findIndex(l => l.id === id);
if (idx < 0) return;
this.layers.splice(idx, 1);
this.activeIndex = Math.max(0, Math.min(this.activeIndex, this.layers.length - 1));
this._emit("change");
}
setActive(id) {
const idx = this.layers.findIndex(l => l.id === id);
if (idx >= 0) { this.activeIndex = idx; this._emit("activeChange", this.layers[idx]); }
}
moveUp(id) {
const idx = this.layers.findIndex(l => l.id === id);
if (idx <= 0) return;
[this.layers[idx - 1], this.layers[idx]] = [this.layers[idx], this.layers[idx - 1]];
if (this.activeIndex === idx) this.activeIndex = idx - 1;
else if (this.activeIndex === idx - 1) this.activeIndex = idx;
this._emit("change");
}
moveDown(id) {
const idx = this.layers.findIndex(l => l.id === id);
if (idx < 0 || idx >= this.layers.length - 1) return;
[this.layers[idx], this.layers[idx + 1]] = [this.layers[idx + 1], this.layers[idx]];
if (this.activeIndex === idx) this.activeIndex = idx + 1;
else if (this.activeIndex === idx + 1) this.activeIndex = idx;
this._emit("change");
}
toggleVisible(id) {
const layer = this.layers.find(l => l.id === id);
if (layer) { layer.visible = !layer.visible; this._emit("change"); }
}
toggleLocked(id) {
const layer = this.layers.find(l => l.id === id);
if (layer) { layer.locked = !layer.locked; this._emit("change"); }
}
setOpacity(id, opacity) {
const layer = this.layers.find(l => l.id === id);
if (layer) { layer.opacity = Math.max(0, Math.min(1, opacity)); this._emit("change"); }
}
/** 全レイヤーを下→上の順で target canvas に変換付きで合成 */
composite(target) {
const ctx = target.getContext("2d");
ctx.clearRect(0, 0, target.width, target.height);
for (let i = this.layers.length - 1; i >= 0; i--) {
const layer = this.layers[i];
if (!layer.visible) continue;
ctx.save();
ctx.globalAlpha = layer.opacity;
ctx.globalCompositeOperation = layer.blendMode;
Layer.applyTransform(ctx, layer);
ctx.drawImage(layer.canvas, -layer.canvas.width / 2, -layer.canvas.height / 2);
ctx.restore();
}
}
on(event, fn) { this._listeners.push({ event, fn }); }
_emit(event, data) {
for (const l of this._listeners) if (l.event === event) l.fn(data);
}
toJSON() {
return { layers: this.layers.map(l => l.toJSON()), width: this.width, height: this.height };
}
async fromJSON(json) {
this.layers = await Promise.all((json.layers || []).map(lj => Layer.fromJSON(lj)));
this.activeIndex = 0;
this._emit("change");
}
}
+336
View File
@@ -0,0 +1,336 @@
/**
* Image Edit Tab - Select Tool
* Handles object selection, move, resize, rotate, flip on the overlay canvas.
*/
const HANDLE_R = 5; // ハンドル半径(px)
const ROTATE_DIST = 32; // 回転ハンドルまでの距離(px)
const MIN_SIZE = 10; // 最小表示サイズ(px)
export class SelectTool {
constructor() {
this._overlay = null;
this._octx = null;
this._layer = null; // 選択中レイヤー
this._dragMode = null; // "move"|"rotate"|"resize-tl"|"resize-tr"|"resize-br"|"resize-bl"
this._dragStart = null;
this._origTransform = null;
this._onChange = null;
this._cursor = "default";
}
setCanvas(overlayCanvas) {
this._overlay = overlayCanvas;
this._octx = overlayCanvas.getContext("2d");
}
onChange(fn) { this._onChange = fn; }
activate() {
if (this._overlay) this._overlay.style.pointerEvents = "auto";
this._drawOverlay();
}
deactivate() {
this._clearOverlay();
if (this._overlay) this._overlay.style.pointerEvents = "none";
}
clearSelection() {
this._layer = null;
this._dragMode = null;
this._clearOverlay();
}
setLayer(layer) {
this._layer = layer;
this._drawOverlay();
}
getSelectedLayer() { return this._layer; }
// ── マウスイベント ───────────────────────────
onMouseDown(x, y, layerMgr) {
if (this._layer) {
const hit = this._hitHandle(x, y);
// ロック中はハンドル操作を禁止(選択済み表示は維持)
if (hit && !this._layer.locked) {
this._startDrag(hit, x, y);
return hit;
}
}
// レイヤーヒットテスト(前面から)
for (let i = 0; i < layerMgr.layers.length; i++) {
const layer = layerMgr.layers[i];
if (!layer.visible) continue;
if (this._isPointInLayer(x, y, layer)) {
this._layer = layer;
this._drawOverlay();
// ロック中は選択のみ(移動ドラッグは開始しない)
if (!layer.locked) this._startDrag("move", x, y);
return "select";
}
}
// 空白クリック → 選択解除
this._layer = null;
this._clearOverlay();
return null;
}
onMouseMove(x, y) {
if (!this._dragMode || !this._layer) {
// カーソル変更のみ
this._updateCursor(x, y);
return;
}
const dx = x - this._dragStart.x;
const dy = y - this._dragStart.y;
const ot = this._origTransform;
if (this._dragMode === "move") {
this._layer.x = ot.x + dx;
this._layer.y = ot.y + dy;
} else if (this._dragMode === "rotate") {
const cx = ot.x + ot.displayW / 2;
const cy = ot.y + ot.displayH / 2;
const a0 = Math.atan2(this._dragStart.y - cy, this._dragStart.x - cx);
const a1 = Math.atan2(y - cy, x - cx);
this._layer.rotation = ot.rotation + (a1 - a0) * 180 / Math.PI;
} else if (this._dragMode.startsWith("resize-")) {
this._applyResize(dx, dy);
}
this._drawOverlay();
if (this._onChange) this._onChange("transforming");
}
onMouseUp() {
if (this._dragMode) {
this._dragMode = null;
this._dragStart = null;
this._origTransform = null;
if (this._onChange) this._onChange("transformEnd");
}
}
onMouseLeave() { this.onMouseUp(); }
// ── 反転 ─────────────────────────────────────
flipH() {
if (!this._layer) return;
this._layer.flipX = !this._layer.flipX;
this._drawOverlay();
if (this._onChange) this._onChange("transformEnd");
}
flipV() {
if (!this._layer) return;
this._layer.flipY = !this._layer.flipY;
this._drawOverlay();
if (this._onChange) this._onChange("transformEnd");
}
// ── 内部ユーティリティ ─────────────────────────
_startDrag(mode, x, y) {
this._dragMode = mode;
this._dragStart = { x, y };
this._origTransform = {
x: this._layer.x, y: this._layer.y,
displayW: this._layer.displayW, displayH: this._layer.displayH,
rotation: this._layer.rotation,
};
}
// 回転を考慮した4頂点を返す(name: "tl"|"tr"|"br"|"bl")
_getCorners(layer) {
const hw = layer.displayW / 2;
const hh = layer.displayH / 2;
const cx = layer.x + hw;
const cy = layer.y + hh;
const r = (layer.rotation ?? 0) * Math.PI / 180;
const cosR = Math.cos(r), sinR = Math.sin(r);
return [
{ name: "tl", lx: -hw, ly: -hh },
{ name: "tr", lx: hw, ly: -hh },
{ name: "br", lx: hw, ly: hh },
{ name: "bl", lx: -hw, ly: hh },
].map(p => ({
name: p.name,
x: cx + p.lx * cosR - p.ly * sinR,
y: cy + p.lx * sinR + p.ly * cosR,
}));
}
// 上辺中央から ROTATE_DIST だけ上に出た回転ハンドル
_getRotateHandle(layer) {
const hw = layer.displayW / 2;
const hh = layer.displayH / 2;
const cx = layer.x + hw;
const cy = layer.y + hh;
const r = (layer.rotation ?? 0) * Math.PI / 180;
const cosR = Math.cos(r), sinR = Math.sin(r);
const dist = hh + ROTATE_DIST;
// ローカル座標 (0, -dist) を回転: x' = dist*sin(r), y' = -dist*cos(r)
return {
x: cx + sinR * dist,
y: cy - cosR * dist,
};
}
_hitHandle(x, y) {
if (!this._layer) return null;
const rh = this._getRotateHandle(this._layer);
if (Math.hypot(x - rh.x, y - rh.y) <= HANDLE_R * 2.5) return "rotate";
const corners = this._getCorners(this._layer);
for (const c of corners) {
if (Math.hypot(x - c.x, y - c.y) <= HANDLE_R * 2.5) return `resize-${c.name}`;
}
if (this._isPointInLayer(x, y, this._layer)) return "move";
return null;
}
_isPointInLayer(x, y, layer) {
const hw = layer.displayW / 2;
const hh = layer.displayH / 2;
const cx = layer.x + hw;
const cy = layer.y + hh;
// 逆回転で点をローカル座標に変換
const r = -(layer.rotation ?? 0) * Math.PI / 180;
const cosR = Math.cos(r), sinR = Math.sin(r);
const lx = (x - cx) * cosR - (y - cy) * sinR;
const ly = (x - cx) * sinR + (y - cy) * cosR;
return Math.abs(lx) <= hw && Math.abs(ly) <= hh;
}
_applyResize(dx, dy) {
const ot = this._origTransform;
const mode = this._dragMode;
// 回転の逆行列でdx/dyをローカル座標に変換
const r = -(ot.rotation ?? 0) * Math.PI / 180;
const cosR = Math.cos(r), sinR = Math.sin(r);
const ldx = dx * cosR - dy * sinR;
const ldy = dx * sinR + dy * cosR;
let { x, y, displayW, displayH } = ot;
if (mode === "resize-tl") { x += ldx; y += ldy; displayW -= ldx; displayH -= ldy; }
else if (mode === "resize-tr") { y += ldy; displayW += ldx; displayH -= ldy; }
else if (mode === "resize-br") { displayW += ldx; displayH += ldy; }
else if (mode === "resize-bl") { x += ldx; displayW -= ldx; displayH += ldy; }
if (displayW < MIN_SIZE) { if (mode.includes("l")) x -= MIN_SIZE - displayW; displayW = MIN_SIZE; }
if (displayH < MIN_SIZE) { if (mode.includes("t")) y -= MIN_SIZE - displayH; displayH = MIN_SIZE; }
// 回転あり: x/yのずれを回転軸中心に合わせて再計算
// ローカル左上の変位を逆回転して戻す
const r2 = (ot.rotation ?? 0) * Math.PI / 180;
const cosR2 = Math.cos(r2), sinR2 = Math.sin(r2);
const ox = ot.x + ot.displayW / 2;
const oy = ot.y + ot.displayH / 2;
// 新しい左上 (ローカル -hw2, -hh2 を回転して絶対座標)
const hw2 = displayW / 2;
const hh2 = displayH / 2;
const dx2 = -hw2 * cosR2 + hh2 * sinR2; // ローカル(-hw2, -hh2)を回転
const dy2 = -hw2 * sinR2 - hh2 * cosR2;
// ... でも回転付きリサイズは複雑なので、回転がほぼ0のときのみシンプル版を使用
if (Math.abs(ot.rotation ?? 0) < 1) {
this._layer.x = x; this._layer.y = y;
}
// 回転あり時は displayW/H のみ更新(位置は維持)
this._layer.displayW = displayW;
this._layer.displayH = displayH;
}
_updateCursor(x, y) {
if (!this._overlay) return;
const hit = this._layer ? this._hitHandle(x, y) : null;
const cursorMap = {
"move": "move", "rotate": "crosshair",
"resize-tl": "nwse-resize", "resize-br": "nwse-resize",
"resize-tr": "nesw-resize", "resize-bl": "nesw-resize",
};
this._overlay.style.cursor = hit ? (cursorMap[hit] ?? "default") : "default";
}
// ── オーバーレイ描画 ───────────────────────────
_drawOverlay() {
this._clearOverlay();
if (!this._layer || !this._octx) return;
const ctx = this._octx;
const layer = this._layer;
const locked = !!layer.locked;
const color = locked ? "#e2a04a" : "#4a90e2"; // ロック中はオレンジ
const corners = this._getCorners(layer);
const rh = this._getRotateHandle(layer);
const tl = corners[0], tr = corners[1];
const topMid = { x: (tl.x + tr.x) / 2, y: (tl.y + tr.y) / 2 };
ctx.save();
// バウンディングボックス
ctx.setLineDash([5, 3]);
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.beginPath();
corners.forEach((c, i) => i === 0 ? ctx.moveTo(c.x, c.y) : ctx.lineTo(c.x, c.y));
ctx.closePath();
ctx.stroke();
ctx.setLineDash([]);
if (!locked) {
// 回転ライン+ハンドル(ロック中は非表示)
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(topMid.x, topMid.y);
ctx.lineTo(rh.x, rh.y);
ctx.stroke();
ctx.fillStyle = "#fff";
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(rh.x, rh.y, HANDLE_R, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
// コーナーハンドル
for (const c of corners) {
ctx.fillStyle = "#fff";
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.rect(c.x - HANDLE_R, c.y - HANDLE_R, HANDLE_R * 2, HANDLE_R * 2);
ctx.fill();
ctx.stroke();
}
} else {
// ロック中: 中央に鍵アイコン
const cx = layer.x + layer.displayW / 2;
const cy = layer.y + layer.displayH / 2;
ctx.font = "18px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.fillText("🔒", cx, cy);
}
ctx.restore();
}
_clearOverlay() {
if (this._octx && this._overlay) {
this._octx.clearRect(0, 0, this._overlay.width, this._overlay.height);
}
}
}
+229
View File
@@ -0,0 +1,229 @@
/**
* ShapeTool — rect / ellipse / line / freeline drawing tool for Image Edit tab.
* Preview is drawn on the overlay canvas; committed shapes become new draw layers.
*/
export class ShapeTool {
constructor() {
// shape settings
this.shape = "rect";
this.rounded = false;
this.fillColor = "#ff0000";
this.fillNone = false;
this.strokeColor = "#000000";
this.strokeNone = true;
this.strokeWidth = 5;
this.opacity = 1.0;
// internal state
this._active = false;
this._canvas = null; // overlay canvas (preview)
this._ctx = null;
this._dragging = false;
this._dragStart = null;
this._curPt = null;
this._points = []; // freeline points
this._onChange = null;
}
// overlay canvas used for live preview
setCanvas(canvas) {
this._canvas = canvas;
this._ctx = canvas ? canvas.getContext("2d") : null;
}
onChange(cb) { this._onChange = cb; }
activate() {
this._active = true;
}
deactivate() {
this._active = false;
this._dragging = false;
this._clearOverlay();
if (this._canvas) this._canvas.style.cursor = "";
}
onMouseDown(x, y) {
if (!this._active) return;
this._dragging = true;
this._dragStart = { x, y };
this._curPt = { x, y };
this._points = this.shape === "freeline" ? [{ x, y }] : [];
}
onMouseMove(x, y) {
if (!this._dragging) return;
this._curPt = { x, y };
if (this.shape === "freeline") this._points.push({ x, y });
this._drawPreview(x, y);
}
onMouseUp() {
if (!this._dragging) return;
this._dragging = false;
this._clearOverlay();
this._commit();
}
onMouseLeave() {
if (!this._dragging) return;
this._dragging = false;
this._clearOverlay();
this._commit();
}
// ── private ───────────────────────────────────────
_clearOverlay() {
if (this._ctx && this._canvas) {
this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
}
}
_drawPreview(curX, curY) {
if (!this._ctx || !this._canvas) return;
const ctx = this._ctx;
ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
const s = this._dragStart;
ctx.save();
ctx.globalAlpha = this.opacity;
if (this.shape === "freeline") {
// freeline: always draw with stroke color (strokeNone has no meaning here)
if (this._points.length >= 2) {
ctx.strokeStyle = this.strokeColor;
ctx.lineWidth = this.strokeWidth;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(this._points[0].x, this._points[0].y);
for (let i = 1; i < this._points.length; i++) ctx.lineTo(this._points[i].x, this._points[i].y);
ctx.stroke();
}
} else {
// dashed blue outline for rect / ellipse / line
ctx.strokeStyle = "#0077ff";
ctx.lineWidth = Math.max(1, this.strokeWidth || 1);
ctx.setLineDash([4, 2]);
const x1 = Math.min(s.x, curX), y1 = Math.min(s.y, curY);
const w = Math.abs(curX - s.x), h = Math.abs(curY - s.y);
if (this.shape === "ellipse") {
ctx.beginPath();
ctx.ellipse(x1 + w / 2, y1 + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
ctx.stroke();
} else if (this.shape === "line") {
ctx.beginPath();
ctx.moveTo(s.x, s.y);
ctx.lineTo(curX, curY);
ctx.stroke();
} else {
// rect
if (this.rounded) {
const r = Math.min(w, h) * 0.15;
ctx.beginPath();
ctx.roundRect(x1, y1, w, h, r);
ctx.stroke();
} else {
ctx.strokeRect(x1, y1, w, h);
}
}
ctx.setLineDash([]);
}
ctx.restore();
}
_commit() {
const s = this._dragStart, c = this._curPt;
if (!s || !c) return;
const isFreehand = this.shape === "freeline";
const dx = Math.abs(c.x - s.x), dy = Math.abs(c.y - s.y);
if (!isFreehand && dx < 2 && dy < 2) return;
if (isFreehand && this._points.length < 2) return;
const isStrokeMandatory = ["line", "freeline"].includes(this.shape);
const shapeObj = {
kind: this.shape,
s: { ...s },
c: { ...c },
points: isFreehand ? this._points.map(p => ({ ...p })) : [],
fillColor: this.fillNone ? null : this.fillColor,
// line / freeline always use stroke; ignore strokeNone
strokeColor: (isStrokeMandatory || !this.strokeNone) ? this.strokeColor : null,
strokeWidth: (isStrokeMandatory || !this.strokeNone) ? this.strokeWidth : 0,
opacity: this.opacity,
rounded: this.rounded,
};
this._onChange?.(shapeObj);
}
// ── static renderer (used by onChange callback to bake shape into layer) ──
static drawShape(ctx, sh) {
const { kind, s, c, points, fillColor, strokeColor, strokeWidth, opacity, rounded } = sh;
ctx.save();
ctx.globalAlpha = opacity ?? 1;
if (kind === "freeline") {
if (strokeColor && strokeWidth > 0 && points.length >= 2) {
ctx.strokeStyle = strokeColor;
ctx.lineWidth = strokeWidth;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) ctx.lineTo(points[i].x, points[i].y);
ctx.stroke();
}
} else if (kind === "ellipse") {
const x1 = Math.min(s.x, c.x), y1 = Math.min(s.y, c.y);
const w = Math.abs(c.x - s.x), h = Math.abs(c.y - s.y);
ctx.beginPath();
ctx.ellipse(x1 + w / 2, y1 + h / 2, w / 2, h / 2, 0, 0, Math.PI * 2);
if (fillColor) { ctx.fillStyle = fillColor; ctx.fill(); }
if (strokeColor && strokeWidth > 0) { ctx.strokeStyle = strokeColor; ctx.lineWidth = strokeWidth; ctx.stroke(); }
} else if (kind === "line") {
if (strokeColor && strokeWidth > 0) {
ctx.strokeStyle = strokeColor;
ctx.lineWidth = strokeWidth;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(s.x, s.y);
ctx.lineTo(c.x, c.y);
ctx.stroke();
}
} else {
// rect
const x1 = Math.min(s.x, c.x), y1 = Math.min(s.y, c.y);
const w = Math.abs(c.x - s.x), h = Math.abs(c.y - s.y);
if (rounded) {
const r = Math.min(w, h) * 0.15;
ctx.beginPath();
ctx.roundRect(x1, y1, w, h, r);
} else {
ctx.beginPath();
ctx.rect(x1, y1, w, h);
}
if (fillColor) { ctx.fillStyle = fillColor; ctx.fill(); }
if (strokeColor && strokeWidth > 0) { ctx.strokeStyle = strokeColor; ctx.lineWidth = strokeWidth; ctx.stroke(); }
}
ctx.restore();
}
// coordinate helper (same signature as DrawTool.getCanvasPos)
static getCanvasPos(canvas, event) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
return {
x: (event.clientX - rect.left) * scaleX,
y: (event.clientY - rect.top) * scaleY,
};
}
}
+173
View File
@@ -0,0 +1,173 @@
/**
* Image Edit Tab - Text Tool
* Measures text bounding box, renders to an off-screen canvas,
* and calls onChange(clickX, clickY) so the caller can create
* a proper text layer with the exact content size.
*/
export const TEXT_FONTS = [
"Arial", "Arial Black", "Georgia", "Times New Roman",
"Courier New", "Verdana", "Trebuchet MS", "Impact",
"Comic Sans MS", "Tahoma",
];
const TEXT_PADDING = 4; // テキスト描画時の余白(px)
export class TextTool {
constructor(canvas) {
this.canvas = canvas;
this.text = "Hello";
this.fontFamily = "Arial";
this.fontSize = 64;
this.bold = false;
this.italic = false;
this.align = "left";
this.color = "#ffffff";
this._overlay = null;
this._onChange = null;
}
setCanvas(canvas) {
this._closeOverlay();
this.canvas = canvas;
}
onChange(fn) { this._onChange = fn; }
activate() {
if (this.canvas) this.canvas.style.cursor = "text";
}
deactivate() {
this._closeOverlay();
if (this.canvas) this.canvas.style.cursor = "";
}
onMouseDown(x, y) {
if (this._overlay) { this._closeOverlay(); return; }
this._showOverlay(x, y);
}
/** 既存テキスト再編集用: プロパティを外部でセット後に呼ぶ */
openAt(canvasX, canvasY) {
this._closeOverlay();
this._showOverlay(canvasX, canvasY);
}
onMouseMove() {}
onMouseLeave() {}
onMouseUp() {}
/** テキストのバウンディングボックスサイズのcanvasを返す */
createLayerData(clickX, clickY) {
const lines = this.text.split("\n");
const lineH = this.fontSize * 1.2;
const font = this._getCSSFont();
// measureText 用の仮canvas
const tmp = document.createElement("canvas");
const tmpCtx = tmp.getContext("2d");
tmpCtx.font = font;
let maxW = 0;
for (const line of lines) {
const w = line.length > 0 ? tmpCtx.measureText(line).width : this.fontSize * 0.3;
if (w > maxW) maxW = w;
}
const tw = Math.max(1, Math.ceil(maxW + TEXT_PADDING * 2));
const th = Math.max(1, Math.ceil(lines.length * lineH + TEXT_PADDING * 2));
const canvas = document.createElement("canvas");
canvas.width = tw;
canvas.height = th;
const ctx = canvas.getContext("2d");
ctx.font = font;
ctx.fillStyle = this.color;
ctx.textBaseline = "top";
ctx.textAlign = this.align;
let drawX = TEXT_PADDING;
if (this.align === "center") drawX = tw / 2;
else if (this.align === "right") drawX = tw - TEXT_PADDING;
lines.forEach((line, i) => {
ctx.fillText(line, drawX, TEXT_PADDING + i * lineH);
});
return {
canvas,
width: tw,
height: th,
x: clickX,
y: clickY,
};
}
// ── 内部 ──────────────────────────────────────
_getCSSFont() {
const parts = [];
if (this.italic) parts.push("italic");
if (this.bold) parts.push("bold");
parts.push(`${this.fontSize}px`);
parts.push(`"${this.fontFamily}", sans-serif`);
return parts.join(" ");
}
_showOverlay(canvasX, canvasY) {
const cv = this.canvas;
const rect = cv.getBoundingClientRect();
const scaleX = rect.width / cv.width;
const scaleY = rect.height / cv.height;
const cssX = Math.round(canvasX * scaleX);
const cssY = Math.round(canvasY * scaleY);
const container = cv.parentElement;
const overlay = document.createElement("div");
overlay.className = "ie-text-overlay";
overlay.style.left = cssX + "px";
overlay.style.top = cssY + "px";
const textarea = document.createElement("textarea");
textarea.className = "ie-text-textarea";
textarea.value = this.text;
textarea.rows = 3;
textarea.placeholder = "Enter text…";
overlay.appendChild(textarea);
const btnRow = document.createElement("div");
btnRow.className = "ie-text-btn-row";
const okBtn = document.createElement("button");
okBtn.className = "wfm-btn wfm-btn-sm wfm-btn-primary";
okBtn.textContent = "OK";
okBtn.onclick = () => {
this.text = textarea.value;
this._closeOverlay();
// drawCanvasには描画せず、呼び出し側でレイヤーとして処理する
if (this._onChange) this._onChange(canvasX, canvasY);
};
btnRow.appendChild(okBtn);
const cancelBtn = document.createElement("button");
cancelBtn.className = "wfm-btn wfm-btn-sm";
cancelBtn.textContent = "Cancel";
cancelBtn.onclick = () => this._closeOverlay();
btnRow.appendChild(cancelBtn);
overlay.appendChild(btnRow);
container.appendChild(overlay);
this._overlay = overlay;
textarea.focus();
textarea.addEventListener("keydown", e => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); okBtn.click(); }
else if (e.key === "Escape") this._closeOverlay();
});
}
_closeOverlay() {
if (this._overlay) { this._overlay.remove(); this._overlay = null; }
}
}
+4 -2
View File
@@ -1075,17 +1075,19 @@ function renderThumbView(grid, models) {
card.querySelector(".wfm-batch-btn")?.addEventListener("click", async (e) => {
e.stopPropagation();
const btn = e.currentTarget;
await toggleBatch(modelName);
if (state.showBatchOnly) {
renderModelGrid();
} else {
e.currentTarget.classList.toggle("active", isInBatch(modelName));
btn.classList.toggle("active", isInBatch(modelName));
}
});
card.querySelector(".wfm-stack-btn")?.addEventListener("click", async (e) => {
e.stopPropagation();
const btn = e.currentTarget;
await toggleStack(modelName);
e.currentTarget.classList.toggle("active", isInStack(modelName));
btn.classList.toggle("active", isInStack(modelName));
});
card.querySelector(".wfm-fav-btn").addEventListener("click", (e) => {
e.stopPropagation();
+158
View File
@@ -8,6 +8,7 @@
<link rel="stylesheet" href="/wfm_static/css/main.css">
<link rel="stylesheet" href="/wfm_static/css/gallery-tab.css">
<link rel="stylesheet" href="/wfm_static/css/tagger-tab.css">
<link rel="stylesheet" href="/wfm_static/css/image-edit-tab.css">
</head>
<body>
<!-- Header -->
@@ -23,6 +24,7 @@
<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="image-edit">Image Edit</button>
<button class="wfm-tab" data-tab="tagger">Tagger</button>
<button class="wfm-tab" data-tab="settings">Settings</button>
<button class="wfm-tab" data-tab="help">Help</button>
@@ -993,6 +995,7 @@
<button class="wfm-help-nav-item" data-help-page="sidepanel">Library (Side Panel)</button>
<button class="wfm-help-nav-item" data-help-page="aitool">AI TOOL Tab</button>
<button class="wfm-help-nav-item" data-help-page="tagger">Tagger Tab</button>
<button class="wfm-help-nav-item" data-help-page="imageedit">Image Edit Tab</button>
<button class="wfm-help-nav-item" data-help-page="shortcuts">Keyboard Shortcuts</button>
<button class="wfm-help-nav-item" data-help-page="trouble">Troubleshooting</button>
</div>
@@ -1170,6 +1173,7 @@
<li id="wfm-help-gallery-12"><b>Metadata</b> button (green, in the detail panel tab bar): opens the selected image in the Metadata tab for full embedded-data inspection; Alt+click on any image thumbnail has the same effect</li>
<li id="wfm-help-gallery-13"><b>Load GenUI</b> button (blue, in the detail panel tab bar): loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab and switches to it; shows a warning toast if no workflow is embedded or the format is not supported</li>
<li id="wfm-help-gallery-14"><b>Tagger</b> button (purple, in the detail panel action row): opens the selected image directly in the Tagger tab's Single mode for instant tagging</li>
<li id="wfm-help-gallery-16"><b>Image Edit</b> button (toolbar, next to Refresh): sends the currently selected image to the Image Edit tab; if layers already exist the image is added as a new layer scaled to fit the canvas, otherwise it becomes Layer 1</li>
</ul>
</div>
</div>
@@ -1250,6 +1254,69 @@
</div>
</div>
<div class="wfm-help-page" id="wfm-help-page-imageedit">
<div class="wfm-help-card">
<h3>Image Edit Tab</h3>
<ul>
<li>Layer-based image editor — compose images with multiple layers (Image, Text, Draw types) and export the composite</li>
<li><b>Loading images:</b> drag &amp; drop onto the canvas, Upload button, or send from the Gallery tab via the <b>Image Edit</b> button in the Gallery toolbar; the first image becomes Layer 1 (auto-locked); subsequent images are added as new layers scaled to fit the canvas</li>
<li><b>New</b> button: create a blank canvas — prompts for WxH size (e.g. 512x768); clears all existing layers</li>
</ul>
</div>
<div class="wfm-help-card">
<h3>Tools</h3>
<ul>
<li><b>Select (V):</b> click to select a layer; drag to move; drag corner handles to resize; drag the circle above the top edge to rotate; double-click a text layer to re-edit its content; Tool Options bar shows Flip H / Flip V / Rotate field</li>
<li><b>Draw (B):</b> freehand brush drawing onto the active draw layer; Tool Options: color, brush size, blend mode</li>
<li><b>Text (T):</b> click on the canvas to place a text input overlay; configure font family, size, bold/italic, align, color in the Tool Options bar; click OK to place the text as an exact-size Text layer; double-click an existing text layer with the Select tool to re-edit</li>
<li><b>Shape (S):</b> draw geometric shapes onto the canvas; each committed shape becomes an independent draw layer; Tool Options: <b>Shape</b> type (Rect / Ellipse / Line / FreeLine), <b>Rounded</b> checkbox (Rect / Ellipse only), <b>Fill</b> color + None toggle (hidden for Line / FreeLine), <b>Stroke</b> color + width + None toggle (None hidden for Line / FreeLine where stroke is always active), <b>Opacity</b> slider, <b>↩ Undo</b> button; drag to draw — a blue dashed outline previews the shape; release to commit</li>
</ul>
</div>
<div class="wfm-help-card">
<h3>Layer Panel</h3>
<ul>
<li>Layers are listed from front (top) to back (bottom); click a layer row to make it active</li>
<li><b>👁 / 🚫</b> button: toggle layer visibility</li>
<li><b>🔒 / 🔓</b> button: toggle layer lock — a locked layer cannot be moved, resized, or rotated (orange bounding box is shown); Layer 1 is locked automatically when the first image is loaded to prevent accidental moves</li>
<li>Opacity slider at the bottom adjusts the active layer's transparency</li>
<li>Type icons: 🖼 = image layer, T = text layer, ✏ = draw layer</li>
<li>Delete key: removes the selected layer (only when 2+ layers exist)</li>
</ul>
</div>
<div class="wfm-help-card">
<h3>Text Object Quality</h3>
<ul>
<li>Text layers are sized exactly to the measured text bounding box — no extra whitespace</li>
<li>When a text layer is resized with the Select tool, the canvas is regenerated at the new display size so the text remains sharp (no blurring)</li>
<li>Re-editing a text layer (double-click) resets it to native size; re-scale afterward if needed</li>
</ul>
</div>
<div class="wfm-help-card">
<h3>Export &amp; Navigation</h3>
<ul>
<li><b>Save PNG:</b> composites all visible layers and downloads the result as a PNG file</li>
<li><b>Save to Gallery:</b> prompts for a filename (default: <code>wfs-image-YYYYMMDDHHmmss</code>) and saves the composite PNG directly to the Gallery root folder (configured in Settings &gt; Gallery Output Folder); requires the Gallery tab to have been opened at least once to set the root</li>
<li><b>Send to ComfyUI:</b> uploads the composite PNG to ComfyUI's input folder via <code>/upload/image</code>, making it selectable in Load Image nodes</li>
<li><b>Canvas navigation:</b> scroll wheel to zoom, Space + drag to pan</li>
<li><b>Undo / Redo:</b> Ctrl+Z / Ctrl+Y (or toolbar buttons ↩ ↪)</li>
</ul>
</div>
<div class="wfm-help-card">
<h3>Image Edit Keyboard Shortcuts</h3>
<ul>
<li><b>V</b>: Select tool</li>
<li><b>B</b>: Draw tool</li>
<li><b>T</b>: Text tool</li>
<li><b>S</b>: Shape tool</li>
<li><b>Delete</b>: Delete selected layer (requires 2+ layers)</li>
<li><b>Ctrl+Z / Ctrl+Y</b>: Undo / Redo</li>
<li><b>Space + drag</b>: Pan canvas</li>
<li><b>Mouse wheel</b>: Zoom in / out</li>
<li><b>Double-click</b> (Select tool on text layer): Re-edit text</li>
</ul>
</div>
</div>
<div class="wfm-help-page" id="wfm-help-page-shortcuts">
<div class="wfm-help-card">
<h3 id="wfm-help-shortcuts-title">Keyboard Shortcuts</h3>
@@ -1260,6 +1327,19 @@
<li id="wfm-help-shortcuts-4">Double-click: Open detail modal</li>
</ul>
</div>
<div class="wfm-help-card">
<h3>Image Edit Tab Shortcuts</h3>
<ul>
<li>V: Select tool</li>
<li>B: Draw tool</li>
<li>T: Text tool</li>
<li>S: Shape tool</li>
<li>Delete: Delete selected layer (requires 2+ layers)</li>
<li>Ctrl+Z / Ctrl+Y: Undo / Redo</li>
<li>Space + drag: Pan canvas</li>
<li>Mouse wheel: Zoom in / out</li>
</ul>
</div>
</div>
<div class="wfm-help-page" id="wfm-help-page-trouble">
@@ -1331,6 +1411,7 @@
</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>
<button id="wfm-gallery-send-image-edit-btn" class="wfm-btn wfm-btn-sm" title="Send selected image to Image Edit tab">Image Edit</button>
</div>
<!-- 複数選択時の一括操作バー -->
<div id="wfm-gallery-bulk-bar" class="wfm-gallery-bulk-bar" style="display:none;">
@@ -1442,6 +1523,83 @@
</div>
</section>
<!-- Image Edit Tab -->
<section id="wfm-tab-image-edit" class="wfm-tab-content">
<div class="ie-editor">
<!-- Left Toolbar -->
<div class="ie-toolbar">
<button class="ie-tool-btn active" data-tool="select" title="Select (V)">▲</button>
<button class="ie-tool-btn" data-tool="draw" title="Draw (B)">✏</button>
<button class="ie-tool-btn" data-tool="text" title="Text (T)">T</button>
<button class="ie-tool-btn" data-tool="shape" title="Shape (S)">□</button>
<button class="ie-tool-btn ie-tool-placeholder" data-tool="mask" title="Mask">🎭</button>
<button class="ie-tool-btn ie-tool-placeholder" data-tool="blur" title="Blur">≈</button>
<button class="ie-tool-btn ie-tool-placeholder" data-tool="filter" title="Filter">★</button>
<button class="ie-tool-btn ie-tool-placeholder" data-tool="bgremove" title="BG Remove">⬚</button>
</div>
<!-- Center -->
<div class="ie-center">
<!-- Action bar -->
<div class="ie-action-bar">
<label class="wfm-btn wfm-btn-sm" style="cursor:pointer;">
Upload
<input type="file" id="ie-upload-input" accept="image/*" style="display:none;">
</label>
<button class="wfm-btn wfm-btn-sm" id="ie-new-btn">New</button>
<span style="flex:1;"></span>
<button class="wfm-btn wfm-btn-sm" id="ie-undo-btn" title="Undo (Ctrl+Z)">↩</button>
<button class="wfm-btn wfm-btn-sm" id="ie-redo-btn" title="Redo (Ctrl+Y)">↪</button>
<button class="wfm-btn wfm-btn-sm" id="ie-save-btn">Save PNG</button>
<button class="wfm-btn wfm-btn-sm" id="ie-save-gallery-btn" title="Save to Gallery root folder">Save to Gallery</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="ie-upload-comfy-btn">Send to ComfyUI</button>
</div>
<!-- Tool options -->
<div class="ie-tool-options" id="ie-tool-options"></div>
<!-- Canvas wrap -->
<div class="ie-canvas-wrap" id="ie-canvas-wrap">
<div class="ie-canvas-container" id="ie-canvas-container" style="width:512px;height:512px;">
<canvas id="ie-canvas-bg" width="512" height="512"></canvas>
<canvas id="ie-canvas-draw" width="512" height="512"></canvas>
<canvas id="ie-canvas-overlay" width="512" height="512"></canvas>
</div>
<div class="ie-placeholder" id="ie-placeholder">
<span class="ie-placeholder-icon">🖼</span>
<span>Upload an image or drop it here</span>
<span style="font-size:11px;opacity:0.6;">Drag &amp; drop · Upload · New</span>
</div>
</div>
<!-- Zoom bar -->
<div class="ie-zoom-bar">
<button class="wfm-btn wfm-btn-sm" id="ie-zoom-fit">Fit</button>
<button class="wfm-btn wfm-btn-sm" id="ie-zoom-100">100%</button>
<span style="flex:1;"></span>
<span id="ie-zoom-label">100%</span>
</div>
</div>
<!-- Right Panel (Layers) -->
<div class="ie-right-panel">
<div class="ie-layers-header">
<span>Layers</span>
<button class="wfm-btn wfm-btn-sm" id="ie-add-layer-btn" title="Add layer">+</button>
<button class="wfm-btn wfm-btn-sm" id="ie-del-layer-btn" title="Delete layer">−</button>
<button class="wfm-btn wfm-btn-sm" id="ie-layer-up-btn" title="Move up">↑</button>
<button class="wfm-btn wfm-btn-sm" id="ie-layer-down-btn" title="Move down">↓</button>
</div>
<div class="ie-layer-list" id="ie-layer-list"></div>
<div class="ie-opacity-row">
<label>Opacity</label>
<input type="range" id="ie-layer-opacity" min="0" max="100" value="100">
<span id="ie-layer-opacity-label">100%</span>
</div>
</div>
</div>
</section>
<!-- Tagger Tab -->
<section id="wfm-tab-tagger" class="wfm-tab-content">
<div class="wfm-tagger-subtab-nav">