Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ce9fb2ab9 | ||
|
|
baa3c32abd | ||
|
|
5fb843c6e2 | ||
|
|
76dc2cbbf6 |
@@ -1,5 +1,93 @@
|
||||
# DEVLOG - ComfyUI-Workflow-Studio
|
||||
|
||||
## 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`
|
||||
|
||||
@@ -18,7 +18,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
|
||||
- Built-in AI tools (translation and more)
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -208,6 +208,21 @@ 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); 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
|
||||
- **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), 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 +257,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 +349,12 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
|
||||
|
||||
## Changelog
|
||||
|
||||
### 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
|
||||
|
||||
|
||||
@@ -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
@@ -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.53"
|
||||
license = "MIT"
|
||||
requires-python = ">= 3.10"
|
||||
dependencies = ["jinja2"]
|
||||
|
||||
@@ -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
@@ -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");
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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: "单张",
|
||||
|
||||
@@ -0,0 +1,987 @@
|
||||
/**
|
||||
* Image Edit Tab
|
||||
* Canvas-based image editor with object-based layer support.
|
||||
* Phase 1: Draw, Text, Select (move/resize/rotate/flip), Layers, Save/Upload.
|
||||
*/
|
||||
|
||||
import { LayerManager, Layer } from "./image-edit/LayerManager.js";
|
||||
import { DrawTool } from "./image-edit/DrawTool.js";
|
||||
import { TextTool, TEXT_FONTS } from "./image-edit/TextTool.js";
|
||||
import { SelectTool } from "./image-edit/SelectTool.js";
|
||||
import { showToast } from "./app.js";
|
||||
|
||||
const TOOL_DEFS = [
|
||||
{ id: "select", icon: "▲", label: "Select", ready: true },
|
||||
{ id: "draw", icon: "✏", label: "Draw", ready: true },
|
||||
{ id: "text", icon: "T", label: "Text", ready: true },
|
||||
{ id: "mask", icon: "🎭", label: "Mask", ready: false },
|
||||
{ id: "blur", icon: "≈", label: "Blur", ready: false },
|
||||
{ id: "filter", icon: "★", label: "Filter", ready: false },
|
||||
{ id: "bgremove", icon: "⬚", label: "BG Remove", ready: false },
|
||||
];
|
||||
|
||||
const UNDO_LIMIT = 20;
|
||||
|
||||
function fitToCanvas(imgW, imgH, canvasW, canvasH) {
|
||||
const scale = Math.min(1, canvasW / imgW, canvasH / imgH);
|
||||
return { w: Math.round(imgW * scale), h: Math.round(imgH * scale) };
|
||||
}
|
||||
|
||||
class ImageEditTab {
|
||||
constructor() {
|
||||
this._layerMgr = null;
|
||||
this._activeTool = "select";
|
||||
this._drawTool = null;
|
||||
this._textTool = null;
|
||||
this._selectTool = null;
|
||||
this._zoom = 1.0;
|
||||
this._panOffset = { x: 0, y: 0 };
|
||||
this._canvasW = 512;
|
||||
this._canvasH = 512;
|
||||
this._baseName = "image";
|
||||
this._undoStack = [];
|
||||
this._redoStack = [];
|
||||
this._panning = false;
|
||||
this._panStart = null;
|
||||
this._spaceDown = false;
|
||||
this._compositeMode = false;
|
||||
this._editingTextLayer = null; // テキスト再編集中のレイヤー参照
|
||||
this._initialized = false;
|
||||
}
|
||||
|
||||
// ── 初期化 ────────────────────────────────────
|
||||
|
||||
init() {
|
||||
if (this._initialized) return;
|
||||
this._initialized = true;
|
||||
this._setupToolButtons();
|
||||
this._setupActionBar();
|
||||
this._setupCanvasEvents();
|
||||
this._setupLayerPanel();
|
||||
this._setupKeyboard();
|
||||
}
|
||||
|
||||
// ── ツールボタン ──────────────────────────────
|
||||
|
||||
_setupToolButtons() {
|
||||
document.querySelectorAll(".ie-tool-btn[data-tool]").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
const def = TOOL_DEFS.find(d => d.id === btn.dataset.tool);
|
||||
if (!def?.ready) { showToast(`${def?.label ?? btn.dataset.tool}: coming soon`, "info"); return; }
|
||||
this._setActiveTool(btn.dataset.tool);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
_setActiveTool(toolId) {
|
||||
if (this._activeTool === "draw") this._drawTool?.deactivate();
|
||||
if (this._activeTool === "text") this._textTool?.deactivate();
|
||||
if (this._activeTool === "select") this._selectTool?.deactivate();
|
||||
|
||||
this._activeTool = toolId;
|
||||
|
||||
document.querySelectorAll(".ie-tool-btn").forEach(btn =>
|
||||
btn.classList.toggle("active", btn.dataset.tool === toolId));
|
||||
|
||||
this._renderToolOptions(toolId);
|
||||
this._activateCurrentTool();
|
||||
}
|
||||
|
||||
_activateCurrentTool() {
|
||||
const drawCanvas = document.getElementById("ie-canvas-draw");
|
||||
const overlayCanvas = document.getElementById("ie-canvas-overlay");
|
||||
if (!drawCanvas || !this._layerMgr) return;
|
||||
|
||||
if (this._activeTool === "draw" && this._drawTool) {
|
||||
this._drawTool.setCanvas(drawCanvas);
|
||||
this._drawTool.activate();
|
||||
} else if (this._activeTool === "text" && this._textTool) {
|
||||
this._textTool.setCanvas(drawCanvas);
|
||||
this._textTool.activate();
|
||||
} else if (this._activeTool === "select" && this._selectTool) {
|
||||
this._selectTool.setCanvas(overlayCanvas);
|
||||
this._selectTool.activate();
|
||||
}
|
||||
}
|
||||
|
||||
_renderToolOptions(toolId) {
|
||||
const el = document.getElementById("ie-tool-options");
|
||||
if (!el) return;
|
||||
el.innerHTML = "";
|
||||
|
||||
if (toolId === "select" && this._selectTool) {
|
||||
el.innerHTML = `
|
||||
<div class="ie-opt-group">
|
||||
<button class="wfm-btn wfm-btn-sm" id="ie-flip-h-btn" title="Flip Horizontal">↔ Flip H</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="ie-flip-v-btn" title="Flip Vertical">↕ Flip V</button>
|
||||
</div>
|
||||
<div class="ie-opt-group" style="margin-left:8px;">
|
||||
<label style="font-size:11px;color:var(--wfm-text-secondary);">Rotate</label>
|
||||
<input type="number" id="ie-rotate-input" value="0" step="1" min="-360" max="360"
|
||||
style="width:56px;" class="ie-opt-input" title="Rotation angle (degrees)">°
|
||||
<button class="wfm-btn wfm-btn-sm" id="ie-rotate-apply-btn">Apply</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="ie-rotate-reset-btn">Reset</button>
|
||||
</div>
|
||||
`;
|
||||
document.getElementById("ie-flip-h-btn")?.addEventListener("click", () => {
|
||||
this._selectTool.flipH();
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
});
|
||||
document.getElementById("ie-flip-v-btn")?.addEventListener("click", () => {
|
||||
this._selectTool.flipV();
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
});
|
||||
document.getElementById("ie-rotate-apply-btn")?.addEventListener("click", () => {
|
||||
const layer = this._selectTool.getSelectedLayer();
|
||||
if (!layer) return;
|
||||
const deg = parseFloat(document.getElementById("ie-rotate-input").value) || 0;
|
||||
layer.rotation = deg;
|
||||
this._selectTool.setLayer(layer);
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
});
|
||||
document.getElementById("ie-rotate-reset-btn")?.addEventListener("click", () => {
|
||||
const layer = this._selectTool.getSelectedLayer();
|
||||
if (!layer) return;
|
||||
layer.rotation = 0;
|
||||
layer.flipX = false;
|
||||
layer.flipY = false;
|
||||
document.getElementById("ie-rotate-input").value = 0;
|
||||
this._selectTool.setLayer(layer);
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
});
|
||||
|
||||
} else if (toolId === "draw" && this._drawTool) {
|
||||
el.innerHTML = `
|
||||
<div class="ie-opt-group">
|
||||
<label>Color</label>
|
||||
<input type="color" id="ie-draw-color" value="${this._drawTool.color}"
|
||||
style="width:30px;height:24px;padding:0;border:1px solid var(--wfm-border);cursor:pointer;border-radius:3px;">
|
||||
</div>
|
||||
<div class="ie-opt-group">
|
||||
<label>Size</label>
|
||||
<input type="range" id="ie-draw-size" min="1" max="200" value="${this._drawTool.brushSize}" style="width:80px;">
|
||||
<span id="ie-draw-size-lbl">${this._drawTool.brushSize}px</span>
|
||||
</div>
|
||||
<div class="ie-opt-group">
|
||||
<label>Hardness</label>
|
||||
<input type="range" id="ie-draw-hard" min="0" max="100" value="${Math.round(this._drawTool.hardness*100)}" style="width:70px;">
|
||||
<span id="ie-draw-hard-lbl">${Math.round(this._drawTool.hardness*100)}%</span>
|
||||
</div>
|
||||
<div class="ie-opt-group">
|
||||
<label>Opacity</label>
|
||||
<input type="range" id="ie-draw-opacity" min="1" max="100" value="${Math.round(this._drawTool.opacity*100)}" style="width:70px;">
|
||||
<span id="ie-draw-opacity-lbl">${Math.round(this._drawTool.opacity*100)}%</span>
|
||||
</div>
|
||||
<div class="ie-opt-group">
|
||||
<label>Mode</label>
|
||||
<select id="ie-draw-mode" class="ie-opt-select">
|
||||
<option value="draw" ${this._drawTool.mode==="draw" ? "selected":""}>Draw</option>
|
||||
<option value="erase" ${this._drawTool.mode==="erase" ? "selected":""}>Erase</option>
|
||||
</select>
|
||||
</div>
|
||||
`;
|
||||
document.getElementById("ie-draw-color")?.addEventListener("input", e => {
|
||||
this._drawTool.color = e.target.value; this._drawTool._stamp = null;
|
||||
});
|
||||
document.getElementById("ie-draw-size")?.addEventListener("input", e => {
|
||||
this._drawTool.brushSize = parseInt(e.target.value);
|
||||
document.getElementById("ie-draw-size-lbl").textContent = e.target.value + "px";
|
||||
this._drawTool._stamp = null;
|
||||
});
|
||||
document.getElementById("ie-draw-hard")?.addEventListener("input", e => {
|
||||
this._drawTool.hardness = parseInt(e.target.value) / 100;
|
||||
document.getElementById("ie-draw-hard-lbl").textContent = e.target.value + "%";
|
||||
this._drawTool._stamp = null;
|
||||
});
|
||||
document.getElementById("ie-draw-opacity")?.addEventListener("input", e => {
|
||||
this._drawTool.opacity = parseInt(e.target.value) / 100;
|
||||
document.getElementById("ie-draw-opacity-lbl").textContent = e.target.value + "%";
|
||||
});
|
||||
document.getElementById("ie-draw-mode")?.addEventListener("change", e => {
|
||||
this._drawTool.mode = e.target.value;
|
||||
});
|
||||
|
||||
} else if (toolId === "text" && this._textTool) {
|
||||
el.innerHTML = `
|
||||
<div class="ie-opt-group">
|
||||
<label>Color</label>
|
||||
<input type="color" id="ie-text-color" value="${this._textTool.color}"
|
||||
style="width:30px;height:24px;padding:0;border:1px solid var(--wfm-border);cursor:pointer;border-radius:3px;">
|
||||
</div>
|
||||
<div class="ie-opt-group">
|
||||
<label>Size</label>
|
||||
<input type="number" id="ie-text-size" value="${this._textTool.fontSize}"
|
||||
min="6" max="500" style="width:56px;" class="ie-opt-input">
|
||||
</div>
|
||||
<div class="ie-opt-group">
|
||||
<label>Font</label>
|
||||
<select id="ie-text-font" class="ie-opt-select">
|
||||
${TEXT_FONTS.map(f => `<option value="${f}" ${this._textTool.fontFamily===f?"selected":""}>${f}</option>`).join("")}
|
||||
</select>
|
||||
</div>
|
||||
<div class="ie-opt-group" style="gap:4px;">
|
||||
<button class="wfm-btn wfm-btn-sm ${this._textTool.bold ? "ie-opt-active":""}" id="ie-text-bold"><b>B</b></button>
|
||||
<button class="wfm-btn wfm-btn-sm ${this._textTool.italic ? "ie-opt-active":""}" id="ie-text-italic"><i>I</i></button>
|
||||
<select id="ie-text-align" class="ie-opt-select" style="width:72px;">
|
||||
<option value="left" ${this._textTool.align==="left" ?"selected":""}>Left</option>
|
||||
<option value="center" ${this._textTool.align==="center" ?"selected":""}>Center</option>
|
||||
<option value="right" ${this._textTool.align==="right" ?"selected":""}>Right</option>
|
||||
</select>
|
||||
</div>
|
||||
`;
|
||||
document.getElementById("ie-text-color")?.addEventListener("input", e => { this._textTool.color = e.target.value; });
|
||||
document.getElementById("ie-text-size")?.addEventListener("change", e => { this._textTool.fontSize = parseInt(e.target.value) || 64; });
|
||||
document.getElementById("ie-text-font")?.addEventListener("change", e => { this._textTool.fontFamily = e.target.value; });
|
||||
document.getElementById("ie-text-bold")?.addEventListener("click", () => {
|
||||
this._textTool.bold = !this._textTool.bold; this._renderToolOptions("text");
|
||||
});
|
||||
document.getElementById("ie-text-italic")?.addEventListener("click", () => {
|
||||
this._textTool.italic = !this._textTool.italic; this._renderToolOptions("text");
|
||||
});
|
||||
document.getElementById("ie-text-align")?.addEventListener("change", e => { this._textTool.align = e.target.value; });
|
||||
} else {
|
||||
const def = TOOL_DEFS.find(d => d.id === toolId);
|
||||
el.innerHTML = `<span style="font-size:12px;color:var(--wfm-text-secondary);">${def?.label ?? toolId}: coming soon</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── アクションバー ─────────────────────────────
|
||||
|
||||
_setupActionBar() {
|
||||
document.getElementById("ie-upload-input")?.addEventListener("change", e => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) this._loadFile(file);
|
||||
e.target.value = "";
|
||||
});
|
||||
|
||||
document.getElementById("ie-new-btn")?.addEventListener("click", () => this._newCanvas());
|
||||
document.getElementById("ie-undo-btn")?.addEventListener("click", () => this._undo());
|
||||
document.getElementById("ie-redo-btn")?.addEventListener("click", () => this._redo());
|
||||
document.getElementById("ie-save-btn")?.addEventListener("click", () => this._savePng());
|
||||
document.getElementById("ie-save-gallery-btn")?.addEventListener("click", () => this._saveToGallery());
|
||||
document.getElementById("ie-upload-comfy-btn")?.addEventListener("click", () => this._uploadToComfyUI());
|
||||
document.getElementById("ie-zoom-fit")?.addEventListener("click", () => this._fitToView());
|
||||
document.getElementById("ie-zoom-100")?.addEventListener("click", () => {
|
||||
this._panOffset = { x: 0, y: 0 }; this._setZoom(1.0);
|
||||
});
|
||||
|
||||
const tab = document.getElementById("wfm-tab-image-edit");
|
||||
if (tab) {
|
||||
tab.addEventListener("dragover", e => { e.preventDefault(); e.dataTransfer.dropEffect = "copy"; });
|
||||
tab.addEventListener("drop", e => {
|
||||
e.preventDefault();
|
||||
const file = e.dataTransfer.files?.[0];
|
||||
if (file && file.type.startsWith("image/")) this._loadFile(file);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Canvas イベント ───────────────────────────
|
||||
|
||||
_setupCanvasEvents() {
|
||||
const wrap = document.getElementById("ie-canvas-wrap");
|
||||
if (!wrap) return;
|
||||
|
||||
wrap.addEventListener("wheel", e => {
|
||||
e.preventDefault();
|
||||
this._setZoom(this._zoom * (e.deltaY > 0 ? 0.9 : 1.1));
|
||||
}, { passive: false });
|
||||
|
||||
wrap.addEventListener("mousedown", e => {
|
||||
if (e.button === 1 || (e.button === 0 && this._spaceDown)) {
|
||||
e.preventDefault();
|
||||
this._panning = true;
|
||||
this._panStart = { x: e.clientX - this._panOffset.x, y: e.clientY - this._panOffset.y };
|
||||
wrap.style.cursor = "grabbing";
|
||||
}
|
||||
});
|
||||
window.addEventListener("mousemove", e => {
|
||||
if (!this._panning) return;
|
||||
this._panOffset.x = e.clientX - this._panStart.x;
|
||||
this._panOffset.y = e.clientY - this._panStart.y;
|
||||
this._applyTransform();
|
||||
});
|
||||
window.addEventListener("mouseup", e => {
|
||||
if (this._panning && (e.button === 1 || e.button === 0)) {
|
||||
this._panning = false;
|
||||
wrap.style.cursor = this._spaceDown ? "grab" : "";
|
||||
}
|
||||
});
|
||||
|
||||
// draw / text 用 mousedown
|
||||
const drawCanvas = document.getElementById("ie-canvas-draw");
|
||||
if (drawCanvas) {
|
||||
drawCanvas.addEventListener("mousedown", e => this._onToolMouseDown(e, drawCanvas));
|
||||
drawCanvas.addEventListener("mousemove", e => this._onToolMouseMove(e, drawCanvas));
|
||||
drawCanvas.addEventListener("mouseup", e => this._onToolMouseUp(e));
|
||||
drawCanvas.addEventListener("mouseleave", () => this._onToolMouseLeave());
|
||||
}
|
||||
|
||||
// select 用 mousedown(overlayCanvas)
|
||||
const overlay = document.getElementById("ie-canvas-overlay");
|
||||
if (overlay) {
|
||||
overlay.addEventListener("mousedown", e => this._onToolMouseDown(e, overlay));
|
||||
overlay.addEventListener("mousemove", e => this._onToolMouseMove(e, overlay));
|
||||
overlay.addEventListener("mouseup", e => this._onToolMouseUp(e));
|
||||
overlay.addEventListener("mouseleave", () => this._onToolMouseLeave());
|
||||
// テキストオブジェクトのダブルクリックで再編集
|
||||
overlay.addEventListener("dblclick", e => this._onOverlayDblClick(e, overlay));
|
||||
}
|
||||
}
|
||||
|
||||
_onToolMouseDown(e, refCanvas) {
|
||||
if (!this._layerMgr || e.button !== 0 || this._spaceDown) return;
|
||||
const pos = DrawTool.getCanvasPos(refCanvas, e);
|
||||
|
||||
if (this._activeTool === "draw" && this._drawTool) {
|
||||
this._saveUndo();
|
||||
this._loadActiveLayerToCanvas();
|
||||
this._drawTool.onMouseDown(pos.x, pos.y);
|
||||
|
||||
} else if (this._activeTool === "text" && this._textTool) {
|
||||
// undo・drawCanvasリセットはテキスト確定時(onChange)で行う
|
||||
this._textTool.onMouseDown(pos.x, pos.y);
|
||||
|
||||
} else if (this._activeTool === "select" && this._selectTool) {
|
||||
const result = this._selectTool.onMouseDown(pos.x, pos.y, this._layerMgr);
|
||||
if (result === "select") {
|
||||
const sel = this._selectTool.getSelectedLayer();
|
||||
if (sel) { this._layerMgr.setActive(sel.id); this._refreshLayerList(); }
|
||||
} else if (result && result !== null) {
|
||||
// move / resize / rotate → undo を事前に保存
|
||||
this._saveUndo();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_onToolMouseMove(e, refCanvas) {
|
||||
if (!this._layerMgr) return;
|
||||
const pos = DrawTool.getCanvasPos(refCanvas, e);
|
||||
if (this._activeTool === "draw") this._drawTool?.onMouseMove(pos.x, pos.y);
|
||||
if (this._activeTool === "select") this._selectTool?.onMouseMove(pos.x, pos.y);
|
||||
}
|
||||
|
||||
_onToolMouseUp(e) {
|
||||
if (!this._layerMgr || e.button !== 0) return;
|
||||
if (this._activeTool === "draw") this._drawTool?.onMouseUp();
|
||||
if (this._activeTool === "select") this._selectTool?.onMouseUp();
|
||||
}
|
||||
|
||||
_onToolMouseLeave() {
|
||||
if (this._activeTool === "draw") this._drawTool?.onMouseLeave();
|
||||
if (this._activeTool === "select") this._selectTool?.onMouseLeave();
|
||||
}
|
||||
|
||||
// ── 画像ロード ────────────────────────────────
|
||||
|
||||
async _loadFile(file) {
|
||||
const dataUrl = await new Promise(resolve => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => resolve(e.target.result);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
await this._loadFromDataUrl(dataUrl, file.name.replace(/\.[^.]+$/, ""));
|
||||
}
|
||||
|
||||
async _loadFromDataUrl(dataUrl, baseName = "image") {
|
||||
const img = await new Promise(resolve => {
|
||||
const i = new Image();
|
||||
i.onload = () => resolve(i);
|
||||
i.onerror = () => resolve(null);
|
||||
i.src = dataUrl;
|
||||
});
|
||||
if (!img) { showToast("Failed to load image", "error"); return; }
|
||||
|
||||
const hasLayers = this._layerMgr && this._layerMgr.layers.length > 0;
|
||||
|
||||
if (hasLayers) {
|
||||
// 既存キャンバスに画像オブジェクトとして追加(キャンバスにフィット)
|
||||
this._syncActiveLayerFromCanvas();
|
||||
this._saveUndo();
|
||||
const fit = fitToCanvas(img.width, img.height, this._canvasW, this._canvasH);
|
||||
const newLayer = this._layerMgr.addLayer("image", baseName, {
|
||||
contentW: img.width, contentH: img.height,
|
||||
displayW: fit.w, displayH: fit.h,
|
||||
x: Math.round((this._canvasW - fit.w) / 2),
|
||||
y: Math.round((this._canvasH - fit.h) / 2),
|
||||
});
|
||||
newLayer.ctx.drawImage(img, 0, 0);
|
||||
// 新しいオブジェクトをSelectToolで選択
|
||||
this._layerMgr.setActive(newLayer.id);
|
||||
if (this._activeTool !== "select") this._setActiveTool("select");
|
||||
this._selectTool?.setLayer(newLayer);
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
document.getElementById("ie-placeholder").style.display = "none";
|
||||
showToast(`Image added: ${img.width}×${img.height}`, "success");
|
||||
return;
|
||||
}
|
||||
|
||||
// 新規キャンバス(Layer 1に画像配置)
|
||||
this._canvasW = img.width;
|
||||
this._canvasH = img.height;
|
||||
this._baseName = baseName;
|
||||
this._initCanvases();
|
||||
|
||||
const layer1 = this._layerMgr.addLayer("image", "Layer 1", {
|
||||
contentW: img.width, contentH: img.height,
|
||||
displayW: img.width, displayH: img.height,
|
||||
x: 0, y: 0,
|
||||
});
|
||||
layer1.ctx.drawImage(img, 0, 0);
|
||||
layer1.locked = true; // 初期画像は誤操作防止のため自動ロック
|
||||
|
||||
this._undoStack = [];
|
||||
this._redoStack = [];
|
||||
|
||||
this._setActiveTool("select");
|
||||
this._selectTool?.setLayer(layer1);
|
||||
this._refreshLayerList();
|
||||
this._updateCompositeView();
|
||||
this._fitToView();
|
||||
|
||||
document.getElementById("ie-placeholder").style.display = "none";
|
||||
showToast(`Loaded: ${img.width}×${img.height}`, "success");
|
||||
}
|
||||
|
||||
_newCanvas() {
|
||||
const current = `${this._canvasW || 512}x${this._canvasH || 512}`;
|
||||
const input = prompt("Canvas size (WxH):", current);
|
||||
if (!input) return;
|
||||
const m = input.match(/^(\d+)\s*[x×]\s*(\d+)$/i);
|
||||
if (!m) { showToast("Invalid format. Use WxH (e.g. 512x512)", "error"); return; }
|
||||
const w = parseInt(m[1]), h = parseInt(m[2]);
|
||||
if (w < 1 || h < 1 || w > 8192 || h > 8192) { showToast("Size must be between 1 and 8192", "error"); return; }
|
||||
|
||||
this._canvasW = w;
|
||||
this._canvasH = h;
|
||||
this._baseName = "new-canvas";
|
||||
this._initCanvases();
|
||||
this._undoStack = [];
|
||||
this._redoStack = [];
|
||||
this._setActiveTool("select");
|
||||
this._refreshLayerList();
|
||||
this._updateCompositeView();
|
||||
this._fitToView();
|
||||
|
||||
document.getElementById("ie-placeholder").style.display = "none";
|
||||
showToast(`New canvas: ${w}×${h}`, "success");
|
||||
}
|
||||
|
||||
_initCanvases() {
|
||||
const drawCanvas = document.getElementById("ie-canvas-draw");
|
||||
const overlayCanvas = document.getElementById("ie-canvas-overlay");
|
||||
if (drawCanvas) { drawCanvas.width = this._canvasW; drawCanvas.height = this._canvasH; }
|
||||
if (overlayCanvas) { overlayCanvas.width = this._canvasW; overlayCanvas.height = this._canvasH; }
|
||||
|
||||
const container = document.getElementById("ie-canvas-container");
|
||||
if (container) {
|
||||
container.style.width = this._canvasW + "px";
|
||||
container.style.height = this._canvasH + "px";
|
||||
}
|
||||
|
||||
this._layerMgr = new LayerManager(this._canvasW, this._canvasH);
|
||||
this._layerMgr.on("change", () => this._refreshLayerList());
|
||||
|
||||
this._drawTool = new DrawTool(drawCanvas);
|
||||
this._drawTool.onChange(() => {
|
||||
this._syncActiveLayerFromCanvas();
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
});
|
||||
|
||||
this._textTool = new TextTool(drawCanvas);
|
||||
this._textTool.onChange((clickX, clickY) => {
|
||||
const data = this._textTool.createLayerData(clickX, clickY);
|
||||
const props = {
|
||||
text: this._textTool.text,
|
||||
fontFamily: this._textTool.fontFamily,
|
||||
fontSize: this._textTool.fontSize,
|
||||
bold: this._textTool.bold,
|
||||
italic: this._textTool.italic,
|
||||
align: this._textTool.align,
|
||||
color: this._textTool.color,
|
||||
nativeW: data.width,
|
||||
nativeH: data.height,
|
||||
};
|
||||
const label = (props.text.slice(0, 20).replace(/\n/g, " ").trim()) || "Text";
|
||||
|
||||
if (this._editingTextLayer) {
|
||||
// 既存テキストレイヤーの再編集
|
||||
const layer = this._editingTextLayer;
|
||||
this._editingTextLayer = null;
|
||||
this._saveUndo();
|
||||
layer.name = label;
|
||||
layer.textProps = props;
|
||||
// ネイティブサイズで canvas を再生成
|
||||
layer.canvas.width = data.width;
|
||||
layer.canvas.height = data.height;
|
||||
layer.ctx = layer.canvas.getContext("2d");
|
||||
layer.ctx.drawImage(data.canvas, 0, 0);
|
||||
// displayサイズもネイティブサイズに戻す
|
||||
layer.displayW = data.width;
|
||||
layer.displayH = data.height;
|
||||
this._selectTool?.setLayer(layer);
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
return;
|
||||
}
|
||||
|
||||
// 新規テキストレイヤーを追加
|
||||
this._saveUndo();
|
||||
const textLayer = this._layerMgr.addLayer("text", label, {
|
||||
contentW: data.width, contentH: data.height,
|
||||
displayW: data.width, displayH: data.height,
|
||||
x: Math.round(data.x), y: Math.round(data.y),
|
||||
});
|
||||
textLayer.ctx.drawImage(data.canvas, 0, 0);
|
||||
textLayer.textProps = props;
|
||||
this._layerMgr.setActive(textLayer.id);
|
||||
this._setActiveTool("select");
|
||||
this._selectTool?.setLayer(textLayer);
|
||||
this._updateCompositeView();
|
||||
this._refreshLayerList();
|
||||
});
|
||||
|
||||
this._selectTool = new SelectTool();
|
||||
this._selectTool.setCanvas(overlayCanvas);
|
||||
this._selectTool.onChange(eventType => {
|
||||
if (eventType === "transformEnd") {
|
||||
// テキストレイヤーをリサイズ後の displayW/H で再描画(ぼやけ防止)
|
||||
const sel = this._selectTool.getSelectedLayer();
|
||||
if (sel?.type === "text" && sel.textProps) {
|
||||
this._rerenderTextLayer(sel);
|
||||
}
|
||||
this._refreshLayerList();
|
||||
}
|
||||
this._updateCompositeView();
|
||||
});
|
||||
|
||||
this._compositeMode = false;
|
||||
}
|
||||
|
||||
// drawCanvas ← activeLayerのみ(描画前リセット、compositeMode = false)
|
||||
_loadActiveLayerToCanvas() {
|
||||
const layer = this._layerMgr?.activeLayer;
|
||||
const drawCanvas = document.getElementById("ie-canvas-draw");
|
||||
if (!layer || !drawCanvas) return;
|
||||
// draw レイヤーのみ対象(image/textオブジェクトには使わない)
|
||||
const ctx = drawCanvas.getContext("2d");
|
||||
ctx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
|
||||
// DrawLayerは変換なし(x=0, y=0, displayW=canvasW でスケール1:1)で描画
|
||||
ctx.drawImage(layer.canvas, 0, 0,
|
||||
layer.displayW, layer.displayH,
|
||||
layer.x, layer.y,
|
||||
layer.displayW, layer.displayH);
|
||||
this._compositeMode = false;
|
||||
}
|
||||
|
||||
// drawCanvas → activeLayer に保存(compositeMode=true時はスキップ)
|
||||
_syncActiveLayerFromCanvas() {
|
||||
if (this._compositeMode) return;
|
||||
const layer = this._layerMgr?.activeLayer;
|
||||
const drawCanvas = document.getElementById("ie-canvas-draw");
|
||||
if (!layer || !drawCanvas) return;
|
||||
layer.ctx.clearRect(0, 0, layer.canvas.width, layer.canvas.height);
|
||||
// スケールの逆変換でdrawCanvasの内容をlayer.canvasに戻す
|
||||
const scaleX = layer.canvas.width / layer.displayW;
|
||||
const scaleY = layer.canvas.height / layer.displayH;
|
||||
layer.ctx.save();
|
||||
layer.ctx.scale(scaleX, scaleY);
|
||||
layer.ctx.drawImage(drawCanvas, -layer.x * scaleX, -layer.y * scaleY);
|
||||
layer.ctx.restore();
|
||||
}
|
||||
|
||||
// 全可視レイヤーを変換付きで合成 → drawCanvas(compositeMode = true)
|
||||
_updateCompositeView() {
|
||||
const drawCanvas = document.getElementById("ie-canvas-draw");
|
||||
if (!drawCanvas || !this._layerMgr) return;
|
||||
const ctx = drawCanvas.getContext("2d");
|
||||
ctx.clearRect(0, 0, drawCanvas.width, drawCanvas.height);
|
||||
for (let i = this._layerMgr.layers.length - 1; i >= 0; i--) {
|
||||
const layer = this._layerMgr.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();
|
||||
}
|
||||
this._compositeMode = true;
|
||||
}
|
||||
|
||||
// ── ズーム・パン ──────────────────────────────
|
||||
|
||||
_fitToView() {
|
||||
const wrap = document.getElementById("ie-canvas-wrap");
|
||||
if (!wrap || !this._canvasW) return;
|
||||
this._zoom = Math.min((wrap.clientWidth - 40) / this._canvasW, (wrap.clientHeight - 40) / this._canvasH, 2.0);
|
||||
this._panOffset = { x: 0, y: 0 };
|
||||
this._applyTransform();
|
||||
}
|
||||
|
||||
_setZoom(z) {
|
||||
this._zoom = Math.max(0.05, Math.min(10, z));
|
||||
this._applyTransform();
|
||||
}
|
||||
|
||||
_applyTransform() {
|
||||
const container = document.getElementById("ie-canvas-container");
|
||||
const wrap = document.getElementById("ie-canvas-wrap");
|
||||
if (!container || !wrap) return;
|
||||
const tx = this._panOffset.x + (wrap.clientWidth - this._canvasW * this._zoom) / 2;
|
||||
const ty = this._panOffset.y + (wrap.clientHeight - this._canvasH * this._zoom) / 2;
|
||||
container.style.transform = `translate(${tx}px,${ty}px) scale(${this._zoom})`;
|
||||
const zl = document.getElementById("ie-zoom-label");
|
||||
if (zl) zl.textContent = Math.round(this._zoom * 100) + "%";
|
||||
}
|
||||
|
||||
// ── レイヤーパネル ────────────────────────────
|
||||
|
||||
_setupLayerPanel() {
|
||||
document.getElementById("ie-add-layer-btn")?.addEventListener("click", () => {
|
||||
if (!this._layerMgr) return;
|
||||
this._syncActiveLayerFromCanvas();
|
||||
this._saveUndo();
|
||||
const layer = this._layerMgr.addLayer("draw", `Layer ${this._layerMgr.layers.length + 1}`);
|
||||
// 新しいdrawレイヤーはキャンバスサイズ全体をカバー
|
||||
layer.displayW = this._canvasW; layer.displayH = this._canvasH;
|
||||
layer.x = 0; layer.y = 0;
|
||||
this._loadActiveLayerToCanvas();
|
||||
this._updateCompositeView();
|
||||
this._activateCurrentTool();
|
||||
});
|
||||
|
||||
document.getElementById("ie-del-layer-btn")?.addEventListener("click", () => {
|
||||
if (!this._layerMgr || this._layerMgr.layers.length <= 1) return;
|
||||
this._saveUndo();
|
||||
const active = this._layerMgr.activeLayer;
|
||||
if (active) this._layerMgr.deleteLayer(active.id);
|
||||
if (this._selectTool?.getSelectedLayer()?.id === active?.id) {
|
||||
this._selectTool.clearSelection();
|
||||
}
|
||||
this._updateCompositeView();
|
||||
this._activateCurrentTool();
|
||||
});
|
||||
|
||||
document.getElementById("ie-layer-up-btn")?.addEventListener("click", () => {
|
||||
if (!this._layerMgr) return;
|
||||
const active = this._layerMgr.activeLayer;
|
||||
if (active) { this._layerMgr.moveUp(active.id); this._updateCompositeView(); }
|
||||
});
|
||||
|
||||
document.getElementById("ie-layer-down-btn")?.addEventListener("click", () => {
|
||||
if (!this._layerMgr) return;
|
||||
const active = this._layerMgr.activeLayer;
|
||||
if (active) { this._layerMgr.moveDown(active.id); this._updateCompositeView(); }
|
||||
});
|
||||
|
||||
document.getElementById("ie-layer-opacity")?.addEventListener("input", e => {
|
||||
if (!this._layerMgr) return;
|
||||
const v = parseInt(e.target.value) / 100;
|
||||
const active = this._layerMgr.activeLayer;
|
||||
if (active) { this._layerMgr.setOpacity(active.id, v); this._updateCompositeView(); }
|
||||
const lbl = document.getElementById("ie-layer-opacity-label");
|
||||
if (lbl) lbl.textContent = e.target.value + "%";
|
||||
});
|
||||
}
|
||||
|
||||
_refreshLayerList() {
|
||||
const el = document.getElementById("ie-layer-list");
|
||||
if (!el || !this._layerMgr) return;
|
||||
|
||||
el.innerHTML = this._layerMgr.layers.map((layer, i) => {
|
||||
const isActive = i === this._layerMgr.activeIndex;
|
||||
const typeIcon = layer.type === "image" ? "🖼" : layer.type === "text" ? "T" : "✏";
|
||||
return `
|
||||
<div class="ie-layer-item ${isActive ? "active" : ""}" data-id="${layer.id}" data-action="select">
|
||||
<button class="ie-layer-vis-btn" data-id="${layer.id}" data-action="vis"
|
||||
title="${layer.visible ? "Hide" : "Show"}">${layer.visible ? "👁" : "🚫"}</button>
|
||||
<button class="ie-layer-vis-btn" data-id="${layer.id}" data-action="lock"
|
||||
title="${layer.locked ? "Unlock" : "Lock"}"
|
||||
style="color:${layer.locked ? "#e2a04a" : "inherit"}">${layer.locked ? "🔒" : "🔓"}</button>
|
||||
<img class="ie-layer-thumb" src="${layer.getThumbnailDataURL()}" draggable="false">
|
||||
<span class="ie-layer-type-icon" style="font-size:10px;opacity:0.7;flex-shrink:0;">${typeIcon}</span>
|
||||
<span class="ie-layer-name">${layer.name}</span>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
el.querySelectorAll("[data-action]").forEach(node => {
|
||||
node.addEventListener("click", e => {
|
||||
e.stopPropagation();
|
||||
const id = node.dataset.id;
|
||||
const action = node.dataset.action;
|
||||
if (action === "vis") {
|
||||
this._layerMgr.toggleVisible(id);
|
||||
this._updateCompositeView();
|
||||
} else if (action === "lock") {
|
||||
this._layerMgr.toggleLocked(id);
|
||||
// ロック変更はSelectToolのオーバーレイを再描画
|
||||
const sel = this._selectTool?.getSelectedLayer();
|
||||
if (sel?.id === id) this._selectTool?.setLayer(sel);
|
||||
this._refreshLayerList();
|
||||
} else if (action === "select") {
|
||||
this._syncActiveLayerFromCanvas();
|
||||
this._layerMgr.setActive(id);
|
||||
const layer = this._layerMgr.activeLayer;
|
||||
if (this._activeTool === "select" && layer) {
|
||||
this._selectTool?.setLayer(layer);
|
||||
} else {
|
||||
this._loadActiveLayerToCanvas();
|
||||
this._updateCompositeView();
|
||||
}
|
||||
this._refreshLayerList();
|
||||
if (layer) {
|
||||
const sl = document.getElementById("ie-layer-opacity");
|
||||
const lb = document.getElementById("ie-layer-opacity-label");
|
||||
if (sl) sl.value = Math.round(layer.opacity * 100);
|
||||
if (lb) lb.textContent = Math.round(layer.opacity * 100) + "%";
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ── Undo / Redo ──────────────────────────────
|
||||
|
||||
_saveUndo() {
|
||||
if (!this._layerMgr) return;
|
||||
this._syncActiveLayerFromCanvas();
|
||||
const state = JSON.stringify(this._layerMgr.toJSON());
|
||||
this._undoStack.push(state);
|
||||
if (this._undoStack.length > UNDO_LIMIT) this._undoStack.shift();
|
||||
this._redoStack = [];
|
||||
}
|
||||
|
||||
async _undo() {
|
||||
if (!this._layerMgr || this._undoStack.length === 0) return;
|
||||
this._syncActiveLayerFromCanvas();
|
||||
this._redoStack.push(JSON.stringify(this._layerMgr.toJSON()));
|
||||
await this._restoreState(this._undoStack.pop());
|
||||
}
|
||||
|
||||
async _redo() {
|
||||
if (!this._layerMgr || this._redoStack.length === 0) return;
|
||||
this._syncActiveLayerFromCanvas();
|
||||
this._undoStack.push(JSON.stringify(this._layerMgr.toJSON()));
|
||||
await this._restoreState(this._redoStack.pop());
|
||||
}
|
||||
|
||||
async _restoreState(jsonStr) {
|
||||
const json = JSON.parse(jsonStr);
|
||||
await this._layerMgr.fromJSON(json);
|
||||
this._selectTool?.clearSelection();
|
||||
this._updateCompositeView();
|
||||
this._activateCurrentTool();
|
||||
this._refreshLayerList();
|
||||
}
|
||||
|
||||
// ── 合成・保存 ─────────────────────────────────
|
||||
|
||||
_buildCompositeCanvas() {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = this._canvasW;
|
||||
canvas.height = this._canvasH;
|
||||
this._syncActiveLayerFromCanvas();
|
||||
if (this._layerMgr) this._layerMgr.composite(canvas);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
_savePng() {
|
||||
if (!this._layerMgr) { showToast("No image loaded", "error"); return; }
|
||||
const canvas = this._buildCompositeCanvas();
|
||||
const a = document.createElement("a");
|
||||
a.href = canvas.toDataURL("image/png");
|
||||
a.download = (this._baseName || "wfs-edit") + "-output.png";
|
||||
a.click();
|
||||
showToast("PNG saved", "success");
|
||||
}
|
||||
|
||||
async _saveToGallery() {
|
||||
if (!this._layerMgr) { showToast("No image loaded", "error"); return; }
|
||||
|
||||
// デフォルトファイル名: wfs-image-YYYYMMDDHHmmss
|
||||
const now = new Date();
|
||||
const pad = n => String(n).padStart(2, "0");
|
||||
const ts = `${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
|
||||
const defaultName = `wfs-image-${ts}`;
|
||||
|
||||
const filename = window.prompt("Save to Gallery — file name (without extension):", defaultName);
|
||||
if (filename === null) return; // キャンセル
|
||||
const safeName = filename.trim() || defaultName;
|
||||
|
||||
const canvas = this._buildCompositeCanvas();
|
||||
const imageData = canvas.toDataURL("image/png");
|
||||
|
||||
try {
|
||||
const r = await fetch("/wfm/gallery/image/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ filename: safeName, imageData }),
|
||||
});
|
||||
if (!r.ok) {
|
||||
const e = await r.json().catch(() => ({}));
|
||||
throw new Error(e.error || r.statusText);
|
||||
}
|
||||
showToast(`Saved to Gallery: ${safeName}.png`, "success");
|
||||
} catch (err) {
|
||||
showToast(`Gallery save failed: ${err.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async _uploadToComfyUI() {
|
||||
if (!this._layerMgr) { showToast("No image loaded", "error"); return; }
|
||||
const canvas = this._buildCompositeCanvas();
|
||||
const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
|
||||
const file = new File([blob], (this._baseName || "wfs-edit") + "-output.png", { type: "image/png" });
|
||||
const form = new FormData();
|
||||
form.append("image", file);
|
||||
form.append("overwrite", "true");
|
||||
try {
|
||||
const r = await fetch("/upload/image", { method: "POST", body: form });
|
||||
const data = await r.json();
|
||||
showToast(`Uploaded: ${data.name}`, "success");
|
||||
} catch {
|
||||
showToast("Upload failed", "error");
|
||||
}
|
||||
}
|
||||
|
||||
/** ギャラリーなど外部から画像URLをロード */
|
||||
async loadFromUrl(url, name) {
|
||||
try {
|
||||
const r = await fetch(url);
|
||||
const blob = await r.blob();
|
||||
const dataUrl = await new Promise(resolve => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => resolve(e.target.result);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
await this._loadFromDataUrl(dataUrl, name || url.split("/").pop().replace(/\.[^.]+$/, "") || "gallery-image");
|
||||
} catch {
|
||||
showToast("Failed to load image from URL", "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── キーボードショートカット ──────────────────
|
||||
|
||||
_setupKeyboard() {
|
||||
document.addEventListener("keydown", e => {
|
||||
if (!document.getElementById("wfm-tab-image-edit")?.classList.contains("active")) return;
|
||||
if (e.key === " " && !e.target.closest("input, textarea, select")) {
|
||||
e.preventDefault();
|
||||
this._spaceDown = true;
|
||||
const wrap = document.getElementById("ie-canvas-wrap");
|
||||
if (wrap && !this._panning) wrap.style.cursor = "grab";
|
||||
}
|
||||
if (e.ctrlKey && e.key === "z") { e.preventDefault(); this._undo(); }
|
||||
if (e.ctrlKey && e.key === "y") { e.preventDefault(); this._redo(); }
|
||||
if (!e.ctrlKey && !e.target.closest("input, textarea, select")) {
|
||||
if (e.key === "v") this._setActiveTool("select");
|
||||
if (e.key === "b") this._setActiveTool("draw");
|
||||
if (e.key === "t") this._setActiveTool("text");
|
||||
// Delete/Backspaceで選択オブジェクト削除
|
||||
if ((e.key === "Delete" || e.key === "Backspace") && this._activeTool === "select") {
|
||||
const layer = this._selectTool?.getSelectedLayer();
|
||||
if (layer && this._layerMgr && this._layerMgr.layers.length > 1) {
|
||||
this._saveUndo();
|
||||
this._selectTool.clearSelection();
|
||||
this._layerMgr.deleteLayer(layer.id);
|
||||
this._updateCompositeView();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("keyup", e => {
|
||||
if (e.key === " ") {
|
||||
this._spaceDown = false;
|
||||
if (!this._panning) {
|
||||
const wrap = document.getElementById("ie-canvas-wrap");
|
||||
if (wrap) wrap.style.cursor = "";
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ── テキストオブジェクト再編集 ────────────────────
|
||||
|
||||
/** overlayCanvas のダブルクリック: テキストレイヤー選択中なら再編集 */
|
||||
_onOverlayDblClick(e, refCanvas) {
|
||||
if (!this._layerMgr || this._activeTool !== "select") return;
|
||||
const pos = DrawTool.getCanvasPos(refCanvas, e);
|
||||
const layer = this._selectTool?.getSelectedLayer();
|
||||
if (!layer || !this._selectTool._isPointInLayer(pos.x, pos.y, layer)) return;
|
||||
if (layer.type === "text" && layer.textProps) {
|
||||
this._openTextEditForLayer(layer, pos.x, pos.y);
|
||||
}
|
||||
}
|
||||
|
||||
/** textProps を TextTool にセットしてオーバーレイを開く */
|
||||
_openTextEditForLayer(layer, canvasX, canvasY) {
|
||||
const p = layer.textProps;
|
||||
this._textTool.text = p.text;
|
||||
this._textTool.fontFamily = p.fontFamily;
|
||||
this._textTool.fontSize = p.fontSize;
|
||||
this._textTool.bold = p.bold;
|
||||
this._textTool.italic = p.italic;
|
||||
this._textTool.align = p.align;
|
||||
this._textTool.color = p.color;
|
||||
this._editingTextLayer = layer;
|
||||
this._textTool.openAt(canvasX, canvasY);
|
||||
}
|
||||
|
||||
/**
|
||||
* テキストレイヤーを displayW/H サイズで再描画する(拡大縮小後のぼやけ防止)。
|
||||
* canvas.width = displayW にするため applyTransform のスケールは常に 1:1 になる。
|
||||
*/
|
||||
_rerenderTextLayer(layer) {
|
||||
const p = layer.textProps;
|
||||
if (!p) return;
|
||||
|
||||
const newW = Math.max(1, Math.round(layer.displayW));
|
||||
const newH = Math.max(1, Math.round(layer.displayH));
|
||||
const sx = newW / p.nativeW;
|
||||
const sy = newH / p.nativeH;
|
||||
|
||||
layer.canvas.width = newW;
|
||||
layer.canvas.height = newH;
|
||||
layer.ctx = layer.canvas.getContext("2d");
|
||||
|
||||
const font = [
|
||||
p.italic ? "italic" : "",
|
||||
p.bold ? "bold" : "",
|
||||
`${p.fontSize}px`,
|
||||
`"${p.fontFamily}", sans-serif`,
|
||||
].filter(Boolean).join(" ");
|
||||
|
||||
const lines = p.text.split("\n");
|
||||
const lineH = p.fontSize * 1.2;
|
||||
const pad = 4;
|
||||
|
||||
const ctx = layer.ctx;
|
||||
ctx.save();
|
||||
ctx.scale(sx, sy);
|
||||
ctx.font = font;
|
||||
ctx.fillStyle = p.color;
|
||||
ctx.textBaseline = "top";
|
||||
ctx.textAlign = p.align;
|
||||
|
||||
let drawX = pad;
|
||||
if (p.align === "center") drawX = p.nativeW / 2;
|
||||
else if (p.align === "right") drawX = p.nativeW - pad;
|
||||
|
||||
lines.forEach((line, i) => {
|
||||
ctx.fillText(line, drawX, pad + i * lineH);
|
||||
});
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
export const imageEditTab = new ImageEditTab();
|
||||
window._wfmImageEditTab = imageEditTab;
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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,67 @@
|
||||
</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 & 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>
|
||||
</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 & 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 > 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>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 +1325,18 @@
|
||||
<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>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 +1408,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 +1520,82 @@
|
||||
</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 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 & 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">
|
||||
|
||||
Reference in New Issue
Block a user