diff --git a/.gitignore b/.gitignore index 2b998d0..e568f09 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,8 @@ coverage/ # 其他 agent 的本地记忆目录(不入库) .workbuddy/ + +# 桌面版本地构建缓存(sandbox 内 npm cache 只能落在仓库里) +.npm-cache/ +.cargo-home/ +release/ diff --git a/DESKTOP_BUILD.md b/DESKTOP_BUILD.md new file mode 100644 index 0000000..56e5927 --- /dev/null +++ b/DESKTOP_BUILD.md @@ -0,0 +1,79 @@ +# 构建与打包(桌面版) + +## 一、依赖 + +| 项 | 版本 | 说明 | +|---|---|---| +| Node.js | ≥ 20 | 前端构建(esbuild 逐文件压缩 + 拼接) | +| Rust | ≥ 1.90 | Tauri 后端;macOS 用默认 toolchain,Windows 必须 **MSVC** | +| Xcode CLT | — | 仅 macOS:`xcode-select --install` | +| VS Build Tools | 2019/2022 + 「使用 C++ 的桌面开发」 | 仅 Windows | +| WebView2 Runtime | — | Windows 10 需安装;Win11 自带 | + +## 二、日常命令 + +```bash +npm ci # 首次 +npm run build # 只出前端 dist/(含运行时插件) +npm run app:dev # 开发(启动前自动 build,改完源码需手动再 build) +npm run app:build # 打包当前平台(mac:.app + .dmg;Win:.exe + .msi) +``` + +首次 `app:build` 要编译 ~250 个 Rust crate,约 2–5 分钟;之后增量很快。 + +> 本机(沙箱)里 cargo/npm 的缓存目录被限制在仓库内,所以 build 时用 +> `CARGO_HOME=$PWD/.cargo-home npm_config_cache=$PWD/.npm-cache`; +> 在你自己的机器上不需要,直接用默认缓存即可。 + +## 三、产物位置 + +| 平台 | 路径 | +|---|---| +| macOS | `src-tauri/target/release/bundle/macos/image-workbench.app` | +| macOS dmg | `src-tauri/target/release/bundle/dmg/image-workbench_3.24.85_*.dmg` | +| Windows msi | `src-tauri/target/release/bundle/msi/*.msi` | +| Windows exe(setup) | `src-tauri/target/release/bundle/nsis/*-setup.exe` | + +## 四、Windows 打包(只能在 Windows 上做) + +Tauri 不支持从 macOS 交叉编译 Windows 产物,必须在 Windows 机器上跑: + +```powershell +# 1) 一次性环境(有 winget 的话) +winget install OpenJS.NodeJS.LTS +winget install Rustlang.Rustup +winget install Microsoft.VisualStudio.2022.BuildTools --override "--quiet --add Microsoft.VisualStudio.Workload.VCTools" +winget install Microsoft.EdgeWebView2Runtime + +# 2) 确认 Rust 走的是 MSVC +rustup default stable-msvc +rustc -V + +# 3) 构建 +git clone <本仓库地址> image-workbench-desktop +cd image-workbench-desktop +npm ci +npm run app:build +``` + +产物在 `src-tauri\target\release\bundle\` 下的 `msi\` 与 `nsis` 目录。 + +常见坑: +- `link.exe not found` → VS Build Tools 没装「使用 C++ 的桌面开发」工作负载 +- 中文路径 / 空格路径可能让 NSIS 失败 → 仓库放在 `C:\work\` 这类纯英文路径 +- 没签名 → SmartScreen 会提示「未知发布者」,点「更多信息 → 仍要运行」 + +## 五、签名与分发(本次不做) + +macOS 未签名:首次打开要 **右键 → 打开**(或在「系统设置 → 隐私与安全性」里放行)。 +Windows 未签名:SmartScreen 提示,仅影响首次运行体验。 +要正式分发再考虑 Apple Developer ID / Windows 代码签名证书,与本次迁移无关。 + +## 六、插件资源的来路 + +网页版插件由 Cloudflare KV 在 `/plugins/*` 提供;桌面版没有服务端,所以把 +**发布产物**(`plugins/runtime/*.js`,文件名带内容哈希)随仓库带走,构建后由 +`scripts/copy-plugins.js` 拷进 `dist/plugins/`。每个文件的 SHA-256 与 +`plugins/index.json` 里的 `integrity` 一致(已校验)。 + +升级插件时:换掉 `plugins/runtime/` 里的文件 + 同步 `plugins/index.json` 即可,代码不用动。 diff --git a/DESKTOP_FORK.md b/DESKTOP_FORK.md index 37cdf40..c90ccf1 100644 --- a/DESKTOP_FORK.md +++ b/DESKTOP_FORK.md @@ -19,13 +19,29 @@ 除 `src-tauri/`(纯新增,不会冲突)外,业务代码只改了这些地方: -| 文件 | 位置 | 改了什么 | -|---|---|---| -| `app.js` | 保存图片入口 `downloadUrl` / `downloadBlob` / `clickDownload` | Tauri 下改走「原生另存为 + fs 写二进制」 | -| `app.js` | `wDownloadBlob`(备份/导出) | 同上 | -| `app.js` | `/api/img` 代理处(3 处) | Tauri 下改走 `plugin-http` 直取字节 | -| `package.json` | 依赖与脚本 | 加 `@tauri-apps/*` 与 `tauri` 脚本 | -| `.upstream-base` / `scripts/sync-upstream.sh` | 新增 | 同步机制本身 | +| # | 文件 | 位置 | 改了什么 | +|---|---|---|---| +| P1 | `app.js` | 文件顶部 | 新增「桌面端适配层」:`wIsTauri()` / `wSaveBlobNative()` / `window.__IWB_SAVE_BLOB__` | +| P2 | `app.js` | 输出缩略图归档 | 桌面端用 `plugin-http` 取字节,替代 `/api/img` 代理 | +| P3 | `app.js` | `downloadUrl` 内 `downloadBlob` | 桌面端弹系统「另存为」,`fs.writeFile` 写 Uint8Array | +| P4 | `app.js` | `downloadUrl` 的 `data:`/`blob:` 分支 | 桌面端先取 Blob 再走原生保存(`` 在桌面无效) | +| P5 | `app.js` | `downloadUrl` 第③段代理兜底 | 桌面端换 `plugin-http` 直连 | +| P6 | `app.js` | 预览派生 `viaUrl` | 桌面端不拼代理地址,直连(失败则负缓存回退原图) | +| P7 | `app.js` | 显示缩略图 `img.src` | 桌面端直接用原地址 | +| P8 | `app.js` | `wDownloadBlob`(备份 zip 等) | 统一走 `__IWB_SAVE_BLOB__` | +| P9 | `app.js` | 运行诊断导出 | 同上 | +| P10 | `app.js` | 节点组导出 | 同上 | +| P11 | `src/runtime-workbench-logic.js` | 画布导出 `.iwb.json` | 同上 | + +新增的配套文件(都不碰业务逻辑): + +| 路径 | 作用 | +|---|---| +| `src-tauri/` | 壳层:conf / capabilities / lib.rs(只注册 dialog、fs、http 三个官方插件,零自定义命令) | +| `plugins/runtime/*.js` | 7 个运行时插件的发布产物(从线上抓取,SHA-256 与 `plugins/index.json` 逐一校验通过) | +| `scripts/copy-plugins.js` | 构建后把插件拷进 `dist/plugins/`(网页版由 KV 提供,桌面端只能随包) | +| `scripts/sync-upstream.sh` + `.upstream-base` | 同步机制 | +| `package.json` | 加 `@tauri-apps/*` 依赖、`tauri`/`app:dev`/`app:build` 脚本,`build` 链上 copy-plugins | **红线:除上表外不要再改业务代码。** 差异每多一处,以后同步冲突的概率就高一分。 diff --git a/app.js b/app.js index 8c21c71..7ea15d0 100644 --- a/app.js +++ b/app.js @@ -10,6 +10,38 @@ // 页面加载时就会跑一次保存,声明若在后面会命中 TDZ(异常被 catch 吞掉 ⇒ 落盘退回未精简的 result)。 const GenerationResults = (typeof window !== 'undefined' && window.IWBGenerationResults) || null + // ========== 桌面端(Tauri v2)适配层 ========== + // 仅在 Tauri 内生效:网页版没有 window.__TAURI__ ⇒ 所有分支都走原逻辑,行为零变化。 + // 用 withGlobalTauri 注入的官方 API(无需打包器),权限仍由 src-tauri/capabilities 约束。 + const wTauri = (typeof window !== 'undefined' && window.__TAURI__) ? window.__TAURI__ : null + const wIsTauri = () => !!(wTauri && wTauri.core) + // 桌面端保存二进制:弹系统「另存为」→ fs 直接写 Uint8Array。 + // 刻意不经 base64:Blob → arrayBuffer → Uint8Array,省掉一次全量编码/解码。 + const wSaveBlobNative = async (blob, name, title) => { + const save = wTauri && wTauri.dialog && wTauri.dialog.save + const writeFile = wTauri && wTauri.fs && wTauri.fs.writeFile + if (!save || !writeFile) throw new Error('Tauri 保存接口不可用(检查 dialog/fs 插件是否初始化)') + const fileName = String(name || 'image.png') + const ext = (fileName.split('.').pop() || 'png').toLowerCase() + // 路径来自 save() 的返回值:tauri-plugin-dialog 会把该路径动态加入 fs scope, + // 因此 capabilities 里不需要静态放开任何目录(不放开 $HOME 这类宽权限)。 + const path = await save({ title: title || '保存', defaultPath: fileName, filters: [{ name: ext.toUpperCase() + ' 文件', extensions: [ext] }] }) + if (!path) return false + await writeFile(path, new Uint8Array(await blob.arrayBuffer())) + return true + } + // 统一保存出口:桌面端交系统另存为,网页端沿用 。 + // 挂到 window 供 IIFE 深处的导出/诊断/备份复用,避免到处写分支。 + const wSaveBlob = (blob, name) => { + if (wIsTauri()) return wSaveBlobNative(blob, name).catch((e) => { console.error('[iwb][tauri] 保存失败', e) }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url; a.download = name + document.body.appendChild(a); a.click(); a.remove() + setTimeout(() => URL.revokeObjectURL(url), 5000) + } + if (typeof window !== 'undefined') window.__IWB_SAVE_BLOB__ = wSaveBlob + // ========== 浏览器本地模式(Cloudflare Pages 免费版)========== // 数据层:localStorage + IndexedDB;网络层:直连兼容 API(CORS 已验证允许) function storageRuntime() { return typeof window !== 'undefined' && window.IWBStorageRuntime } @@ -1655,7 +1687,10 @@ if (fkEarly && /^https:/i.test(fkEarly) && !wThumbProxyTried.has(fkEarly)) { wThumbProxyTried.add(fkEarly) try { - const pr = await fetch('/api/img?url=' + encodeURIComponent(fkEarly), { mode: 'cors' }) + // 桌面端没有 /api/img 代理(无服务端)⇒ 用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制) + const pr = wIsTauri() + ? await wTauri.http.fetch(fkEarly) + : await fetch('/api/img?url=' + encodeURIComponent(fkEarly), { mode: 'cors' }) // v3.87.52(丙方案 C5):交给 wRegisterBlobUrl(入参是 Blob,内部创建并登记 objectURL), // 避免此前的"创建了 blob URL 却不登记、不回收"✗ if (pr.ok) return storeOutputThumb(Object.assign({}, item, { url: wRegisterBlobUrl(await pr.blob()) })) @@ -4092,13 +4127,24 @@ } const downloadBlob = (blob) => { if (blob && blob.type) outName = nameOf(blob.type) + // 桌面端:替换原来的 ,弹系统「另存为」后 fs 写二进制 + if (wIsTauri()) { + wSaveBlobNative(blob, outName, '保存图片') + .then((ok) => { if (ok) wDownloadToast('已保存:' + outName) }) + .catch((e) => wDownloadToast('保存失败:' + ((e && e.message) || e))) + return + } const obj = URL.createObjectURL(blob) clickDownload(obj) setTimeout(() => URL.revokeObjectURL(obj), 5000) } // data URL / blob: URL(同源,已被浏览器解析过):直接用 。 // 注意 blob: 也必须走这条路:线上 CSP connect-src 'self' https: 会拦掉 fetch(blob:...)。 - if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) { clickDownload(url); return } + if (su.indexOf('data:') === 0 || su.indexOf('blob:') === 0) { + // 桌面端没有「浏览器下载目录」这回事 ⇒ 先取回字节,再走原生另存为 + if (wIsTauri()) { try { downloadBlob(await (await fetch(url)).blob()); return } catch (e) { /* 落到后面的兜底 */ } } + else { clickDownload(url); return } + } // ① 直连(图床允许跨域时最快、最保真) try { const resp = await fetch(url, { mode: 'cors' }) @@ -4124,8 +4170,11 @@ } catch (e) { /* 继续兜底 */ } // ③ **本站同源代理**兜底(functions/api/img.js;跨域图床专用。不经任何第三方) try { - const r2 = await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' }) - if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast('该图床不支持直连下载,已通过本站代理保存'); return } + // 桌面端没有同源代理:改用 plugin-http 直连(Rust 侧请求,不受 CORS 限制) + const r2 = wIsTauri() + ? await wTauri.http.fetch(su) + : await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' }) + if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast(wIsTauri() ? '已通过原生 HTTP 取图保存' : '该图床不支持直连下载,已通过本站代理保存'); return } } catch (e) { /* 继续兜底 */ } // ④ 最后兜底:新标签打开(右键/长按另存)——绝不静默失败 try { @@ -4437,7 +4486,8 @@ const tbCenterSeed = (type, refs) => { if (!Derive || typeof Derive.create !== 'function' || typeof document === 'undefined') return v previewPending.add(key) // 跨域图必须走同源代理(否则 fetch 必失败 ⇒ 负缓存后等于没做 ✗,见 §8.3 坑 2) - const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0)) + // 桌面端没有 /api/img 代理:不给 viaUrl,让派生器直连(失败即负缓存并回退原图,不影响显示) + const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0) && !wIsTauri()) ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : undefined let inst = null try { inst = Derive.create({ maxEdge: PREVIEW_MAX_EDGE, quality: 0.82 }) } catch (e) { inst = null } @@ -4478,7 +4528,9 @@ const tbCenterSeed = (type, refs) => { displayThumbs.set(key, val) } const isRemoteHttp = /^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0) - img.src = isRemoteHttp ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : v + // 桌面端没有代理:直接给原地址( 不受 CORS 限制,能正常显示;canvas 降采样失败会回退原图) + img.src = (isRemoteHttp && wIsTauri()) ? v + : (isRemoteHttp ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : v) img.onload = () => { try { const iw = img.naturalWidth || 0, ih = img.naturalHeight || 0 @@ -5074,6 +5126,8 @@ const tbCenterSeed = (type, refs) => { const wOpenZipBlob = (blob) => _zipFn('wOpenZipBlob')(blob) const wCreateStoreZip = () => _zipFn('wCreateStoreZip')() function wDownloadBlob(blob, name) { + // 备份/导出统一走同一个出口:桌面端弹系统另存为,网页端仍用 + if (typeof window !== 'undefined' && window.__IWB_SAVE_BLOB__) { window.__IWB_SAVE_BLOB__(blob, name); return } const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = name @@ -5770,7 +5824,10 @@ const tbCenterSeed = (type, refs) => { }) const meta = (typeof window !== 'undefined' && window.__IWB_BUILD_META__) || {} const text = buildRuntimeDiagnosticsText(tasks, meta) - const blob = new Blob([text], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 5000) + const blob = new Blob([text], { type: 'application/json' }) + const fileName = 'image-workbench-diagnostics-' + new Date().toISOString().slice(0, 10) + '.json' + // 统一出口:桌面端原生另存为,网页端 + window.__IWB_SAVE_BLOB__(blob, fileName) showToast('已导出运行诊断(不含 Key、提示词和图片)') } catch (e) { setNotice({ type: 'err', text: '诊断导出失败:' + String((e && e.message) || e) }) } } @@ -7213,7 +7270,13 @@ const tbCenterSeed = (type, refs) => { // C3 第2步:节点组导出同样要自带字节(按需解析,不写回画布) const nodesForExport = await wResolveImagesForExport(withoutGenerationResults({ nodes: selectedNodes }).nodes) const data = { app: 'image-workbench', version: 2, schemaVersion: SchemaVersions.canvas, exportType: 'group', exportedAt: new Date().toISOString(), exportSummary: { nodes: selectedNodes.length, edges: selectedEdges.length, groups: completeGroups.length }, group: Object.assign({ id: uid('g'), name: safeName, memberIds: sel.slice() }, exportedGroupPad ? { pad: exportedGroupPad } : null), groups: completeGroups, nodes: nodesForExport, edges: selectedEdges } - try { const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json'; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(a.href), 5000); setNotice({ type: 'ok', text: '已导出节点组:' + a.download }) } catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) } + try { + const blob = new Blob([JSON.stringify(data, null, 1)], { type: 'application/json' }) + const outName = safeName.replace(/\\.iwb\\.json$/i, '') + '.iwb.json' + // 统一出口:桌面端弹系统另存为,网页端仍走 + window.__IWB_SAVE_BLOB__(blob, outName) + setNotice({ type: 'ok', text: '已导出节点组:' + outName }) + } catch (e) { setNotice({ type: 'err', text: '导出节点组失败:' + String((e && e.message) || e) }) } } }) } // importCanvasFile 已搬到 src/runtime-workbench-logic.js(2026-10-29) diff --git a/package.json b/package.json index 02b34d8..7827b82 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,10 @@ "version": "3.24.85", "description": "Browser-based node canvas image workbench", "scripts": { - "build": "node scripts/build.js", + "build": "node scripts/build.js && node scripts/copy-plugins.js", + "tauri": "tauri", + "app:dev": "tauri dev", + "app:build": "tauri build", "lint": "eslint src app.js", "test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js && node tests/iwb-v32-web-test.js", "test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/functions-api-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js", diff --git a/plugins/runtime/plugin-batch-export.b7d13ba66cf9.js b/plugins/runtime/plugin-batch-export.b7d13ba66cf9.js new file mode 100644 index 0000000..e7edfa9 --- /dev/null +++ b/plugins/runtime/plugin-batch-export.b7d13ba66cf9.js @@ -0,0 +1,1063 @@ +// iwb-plugin: 批量出图 —— 资源中心面板里勾选画布上的 ref 节点,串行跑「(可选)本机抠图 → 白底/透明合成 → +// 单版或双版本编码(≤maxKB 自动降质)」,全部完成后打包成 ZIP 下载(不进画布,避免一次多出几十个节点)。 +// 合成/编码逻辑与 white-bg-800 同源(几何逐字对齐上游 iwb-plaus 的 fitRect);插件彼此独立, +// 宿主不允许跨插件调用,故此处自带一份,改动需与 white-bg-800 同步。 +;(function (global) { + 'use strict' + + if (!global.IWBPluginHost) return + + var DEFAULT_API = 'http://localhost:30092' + var DEFAULT_TIMEOUT = 120000 + var MIN_QUALITY = 0.2 + + var FORMATS = { + png: { mime: 'image/png', ext: 'png', lossy: false, alpha: true }, + jpeg: { mime: 'image/jpeg', ext: 'jpg', lossy: true, alpha: false }, + } + // toBlob 的 blob.type 才是真实产出格式,命名按它走 + var TYPE_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg' } + + var SIZE_OPTIONS = [800, 1000, 1200, 1600, 2000] + var DEFAULT_OPTS = { size: 800, ratioPct: 80, mode: 'dual', prefix: '', maxKB: 500, cutout: false } + + // ---------- 小工具 ---------- + + function clamp(v, min, max) { + return Math.max(min, Math.min(max, v)) + } + + function toPositive(v, fallback) { + var n = Number(v) + return Number.isFinite(n) && n > 0 ? n : fallback + } + + function trimUrl(v) { + return String(v || DEFAULT_API).trim().replace(/\/+$/, '') || DEFAULT_API + } + + function kb(bytes) { + if (!bytes) return '0KB' + return (Math.round(bytes / 1024 * 10) / 10) + 'KB' + } + + function el(tag, attrs, kids) { + var node = document.createElement(tag) + if (attrs) { + for (var key in attrs) { + if (!Object.prototype.hasOwnProperty.call(attrs, key)) continue + var value = attrs[key] + if (value === null || value === undefined) continue + if (key === 'class') node.className = value + else if (key === 'text') node.textContent = String(value) + else if (key.slice(0, 2) === 'on') node.addEventListener(key.slice(2).toLowerCase(), value) + // ⚠️ checked / disabled 这类是布尔属性:setAttribute('checked','false') 依然是「有值」⇒ 仍被勾上。 + // 点「清空」后勾选框不取消的根因就是这个,必须走 property。 + else if (key === 'checked' || key === 'disabled' || key === 'selected' || key === 'readOnly') node[key] = Boolean(value) + else node.setAttribute(key, String(value)) + } + } + if (kids) { + for (var i = 0; i < kids.length; i++) if (kids[i]) node.appendChild(kids[i]) + } + return node + } + + // ---------- ZIP(STORE,无外部依赖) ---------- + // 为什么手写:CDN 引 JSZip 会被宿主 CSP script-src 'self' 拦死(宿主 storage-zip.js 记着这条教训); + // 图片本身已是 png/jpg,再 DEFLATE 几乎不减体积,STORE 更快且字节数可预测。 + + var CRC_TABLE = (function () { + var table = new Uint32Array(256) + for (var i = 0; i < 256; i++) { + var c = i + for (var k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1) + table[i] = c >>> 0 + } + return table + })() + + function crcUpdate(crc, bytes) { + var c = crc + for (var i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8) + return c + } + + // 分片读、分片算 CRC:图片字节始终留在浏览器 blob 存储里,不进 JS 堆(20 张大图也不会顶爆内存) + async function crcOfBlob(blob) { + var crc = 0xffffffff + var chunk = 1024 * 1024 + for (var off = 0; off < blob.size; off += chunk) { + var buf = await blob.slice(off, Math.min(off + chunk, blob.size)).arrayBuffer() + crc = crcUpdate(crc, new Uint8Array(buf)) + } + return (crc ^ 0xffffffff) >>> 0 + } + + function dosStamp(d) { + return { + time: ((d.getHours() & 31) << 11) | ((d.getMinutes() & 63) << 5) | ((Math.floor(d.getSeconds() / 2)) & 31), + date: (((d.getFullYear() - 1980) & 127) << 9) | (((d.getMonth() + 1) & 15) << 5) | (d.getDate() & 31), + } + } + + async function makeStoreZip(files) { + var encoder = new global.TextEncoder() + var stamp = dosStamp(new Date()) + var parts = [] + var central = [] + var centralSize = 0 + var offset = 0 + + for (var i = 0; i < files.length; i++) { + var file = files[i] + var nameBytes = encoder.encode(file.name) + var crc = await crcOfBlob(file.blob) + var size = file.blob.size + + var local = new DataView(new ArrayBuffer(30)) + local.setUint32(0, 0x04034b50, true) + local.setUint16(4, 20, true) + local.setUint16(6, 0x0800, true) // bit 11:文件名为 UTF-8(中文名不乱码的关键) + local.setUint16(8, 0, true) // 0 = STORE + local.setUint16(10, stamp.time, true) + local.setUint16(12, stamp.date, true) + local.setUint32(14, crc, true) + local.setUint32(18, size, true) + local.setUint32(22, size, true) + local.setUint16(26, nameBytes.length, true) + local.setUint16(28, 0, true) + + var cen = new DataView(new ArrayBuffer(46)) + cen.setUint32(0, 0x02014b50, true) + cen.setUint16(4, 20, true) + cen.setUint16(6, 20, true) + cen.setUint16(8, 0x0800, true) + cen.setUint16(10, 0, true) + cen.setUint16(12, stamp.time, true) + cen.setUint16(14, stamp.date, true) + cen.setUint32(16, crc, true) + cen.setUint32(20, size, true) + cen.setUint32(24, size, true) + cen.setUint16(28, nameBytes.length, true) + cen.setUint16(30, 0, true) + cen.setUint16(32, 0, true) + cen.setUint16(34, 0, true) + cen.setUint16(36, 0, true) + cen.setUint32(38, 0, true) + cen.setUint32(42, offset, true) + + parts.push(local, nameBytes, file.blob) + central.push(cen, nameBytes) + centralSize += 46 + nameBytes.length + offset += 30 + nameBytes.length + size + } + + var eocd = new DataView(new ArrayBuffer(22)) + eocd.setUint32(0, 0x06054b50, true) + eocd.setUint16(4, 0, true) + eocd.setUint16(6, 0, true) + eocd.setUint16(8, files.length, true) + eocd.setUint16(10, files.length, true) + eocd.setUint32(12, centralSize, true) + eocd.setUint32(16, offset, true) + eocd.setUint16(20, 0, true) + + return new Blob(parts.concat(central, [eocd]), { type: 'application/zip' }) + } + + // ---------- 图像 ---------- + + // 上游 shared/image-math.js 的 fitRect:内容最长边 = min(boxW, boxH) * ratio,等比缩放并居中(不裁剪) + function fitRect(srcW, srcH, boxW, boxH, ratio) { + if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) { + return { x: 0, y: 0, w: 0, h: 0, scale: 0 } + } + var r = Math.max(0.01, Math.min(1, ratio)) + var maxLen = Math.min(boxW, boxH) * r + var scale = Math.min(maxLen / srcW, maxLen / srcH) + var w = srcW * scale + var h = srcH * scale + return { x: (boxW - w) / 2, y: (boxH - h) / 2, w: w, h: h, scale: scale } + } + + function loadImage(src) { + return new Promise(function (resolve, reject) { + var img = new Image() + img.onload = function () { resolve(img) } + img.onerror = function () { reject(new Error('图片解码失败')) } + img.src = src + }) + } + + function bytesFromDataUrl(dataUrl) { + var s = String(dataUrl || '') + var comma = s.indexOf(',') + var bin = global.atob(comma >= 0 ? s.slice(comma + 1) : s) + var out = new Uint8Array(bin.length) + for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i) + return out + } + + function blobFromDataUrl(dataUrl) { + var s = String(dataUrl || '') + var match = /^data:([^;,]+)/.exec(s) + return new Blob([bytesFromDataUrl(s)], { type: (match && match[1]) || 'image/png' }) + } + + async function decodeBlob(blob) { + var url = URL.createObjectURL(blob) + try { + return await loadImage(url) + } finally { + URL.revokeObjectURL(url) + } + } + + function composeCanvas(img, size, ratio, transparent) { + var canvas = document.createElement('canvas') + canvas.width = size + canvas.height = size + var ctx2d = canvas.getContext('2d') + if (!transparent) { + ctx2d.fillStyle = '#ffffff' + ctx2d.fillRect(0, 0, size, size) + } + var rect = fitRect(img.naturalWidth || img.width, img.naturalHeight || img.height, size, size, ratio) + ctx2d.drawImage(img, rect.x, rect.y, rect.w, rect.h) + return canvas + } + + function canvasToBlob(canvas, mime, quality) { + return new Promise(function (resolve, reject) { + try { + canvas.toBlob(function (blob) { + if (!blob) { reject(new Error('图片编码失败')); return } + resolve(blob) + }, mime, quality) + } catch (error) { + reject(error) + } + }) + } + + // 体积上限:先按基准质量编码;超限就有损格式向下二分(下限 0.2),取能进上限的最高质量。 + // 不偷偷降采样 —— 尺寸是硬规范,缩了比超体积更难排查。 + async function encodeWithLimit(canvas, format, quality, maxBytes, allowOversize) { + var spec = FORMATS[format] + var first = await canvasToBlob(canvas, spec.mime, quality) + if (!maxBytes || first.size <= maxBytes) return first + + // 双版本的透明 PNG 走这条:透明图是必需产物,PNG 又无压缩参数,超限也只能照常输出(不阻断 JPG 那一版) + if (allowOversize) return first + + if (!spec.lossy) { + throw new Error('PNG 体积 ' + kb(first.size) + ' 超过上限 ' + kb(maxBytes) + '(PNG 无压缩参数:请改输出 jpg,或调大上限)') + } + + var floor = await canvasToBlob(canvas, spec.mime, MIN_QUALITY) + if (floor.size > maxBytes) { + throw new Error('已压到质量 20 仍有 ' + kb(floor.size) + ',超过上限 ' + kb(maxBytes) + '(请调小尺寸或调大上限)') + } + + var lo = MIN_QUALITY + var hi = quality + var pick = floor + for (var i = 0; i < 6 && hi - lo > 0.01; i++) { + var mid = (lo + hi) / 2 + var cur = await canvasToBlob(canvas, spec.mime, mid) + if (cur.size <= maxBytes) { + pick = cur + lo = mid + } else { + hi = mid + } + } + return pick + } + + function uniqueName(used, name) { + if (!used[name]) { used[name] = 1; return name } + var dot = name.lastIndexOf('.') + var stem = dot > 0 ? name.slice(0, dot) : name + var ext = dot > 0 ? name.slice(dot) : '' + var n = used[name] + 1 + while (used[stem + '_' + n + ext]) n++ + used[name] = n + used[stem + '_' + n + ext] = 1 + return stem + '_' + n + ext + } + + function fileStamp() { + var d = new Date() + var p = function (n) { return String(n).length < 2 ? '0' + n : String(n) } + return '' + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '_' + p(d.getHours()) + p(d.getMinutes()) + } + + function downloadBlob(blob, filename) { + var url = URL.createObjectURL(blob) + var a = document.createElement('a') + a.href = url + a.download = filename + a.style.display = 'none' + document.body.appendChild(a) + a.click() + document.body.removeChild(a) + global.setTimeout(function () { URL.revokeObjectURL(url) }, 10000) + } + + // 点击缩略图放大:产物留在内存里,先用 overlay 看,避免开新窗口被弹窗拦截 + var previewBox = null + var previewKey = null + + function closePreview() { + if (previewBox && previewBox.parentNode) previewBox.parentNode.removeChild(previewBox) + if (previewKey) document.removeEventListener('keydown', previewKey) + previewBox = null + previewKey = null + } + + function showPreview(url) { + if (!url) return + closePreview() + var box = document.createElement('div') + box.className = 'iwb-bx-zoom' + var img = document.createElement('img') + img.src = url + box.appendChild(img) + var onKey = function (e) { if (e.key === 'Escape') closePreview() } + box.addEventListener('click', closePreview) + document.addEventListener('keydown', onKey) + previewBox = box + previewKey = onKey + document.body.appendChild(box) + } + + // 每个产物只建一次 blob URL;重跑该行时先释放旧的 + function thumbOf(item) { + if (!item || !item.files || !item.files.length) return null + var blob = item.files[0].blob + if (!blob) return null + if (item.thumbUrl) { + try { URL.revokeObjectURL(item.thumbUrl) } catch (error) { /* ignore */ } + } + try { item.thumbUrl = URL.createObjectURL(blob) } catch (error) { item.thumbUrl = null } + return item.thumbUrl + } + + // ---------- 源图缩略图(列表行首常驻,30px 显示 / 64px 位图,retina 够用) ---------- + + var srcThumbCache = {} // nodeId -> dataURL('' 表示取不到,避免反复重试) + var srcThumbBusy = false + + function loadImageEl(src) { + return new Promise(function (resolve, reject) { + var img = new Image() + img.onload = function () { resolve(img) } + img.onerror = function () { reject(new Error('图片解码失败')) } + img.src = src + }) + } + + // 行首缩略图:未跑显示原图,跑完显示产物(绿框),都没有时占位保持行高一致 + function rowThumb(item) { + if (item.status === 'done' && item.thumbUrl) { + return el('img', { + class: 'iwb-bx-thumb iwb-bx-thumb-out', + src: item.thumbUrl, + alt: '', + title: '产物预览' + (item.files && item.files[0] ? ':' + item.files[0].name : ''), + onclick: function () { showPreview(item.thumbUrl) }, + }) + } + if (item.srcThumb) { + return el('img', { + class: 'iwb-bx-thumb', + src: item.srcThumb, + alt: '', + title: '原图预览:' + item.name, + onclick: function () { showPreview(item.srcThumb) }, + }) + } + return el('span', { class: 'iwb-bx-thumb iwb-bx-thumb-ph', title: '缩略图读取中…' }) + } + + // ---------- 单张下载(行内 JPG / PNG) ---------- + + // 按扩展名取产物:判据是**真实文件名**(processOne 用 blob.type 定扩展名),不看当前设置。 + // 为什么不用 opts.mode:用户跑完双版本后把「版本」改成仅 JPG,旧 PNG 依然在内存里、依然该能下; + // 反过来若按设置判断,会出现「按钮亮着但点下去没有文件」。 + function fileOf(item, ext) { + var files = (item && item.files) || [] + var suffix = '.' + ext + for (var i = 0; i < files.length; i++) { + var name = String(files[i].name || '') + if (name.length > suffix.length && name.slice(-suffix.length).toLowerCase() === suffix) return files[i] + } + return null + } + + // 灰态有四种原因,必须分开说,否则用户分不清「还没跑」和「这次本来就不出这个格式」 + function dlHint(item, label, file) { + if (file) return '下载 ' + file.name + '(' + kb(file.size) + ')' + if (item.status === 'running') return '处理中,完成后可下载 ' + label + if (item.status === 'fail') return '该节点处理失败,点「重试」成功后即可下载' + if (item.status === 'done') return '本次设置不产出 ' + label + ';把「版本」切到双版本后重跑即可' + return '处理完成后可下载 ' + label + } + + function dlBtn(item, ext, label) { + var file = fileOf(item, ext) + var btn = el('button', { + class: 'iwb-bx-dl' + (file ? ' iwb-bx-dl-on' : ''), + text: label, + disabled: !file, + title: dlHint(item, label, file), + }) + if (file) { + btn.addEventListener('click', function (e) { + e.stopPropagation() + // 复用同一条 Blob,不再编码;downloadBlob 内部负责建 URL 并在 10s 后 revoke + downloadBlob(file.blob, file.name) + }) + } + return btn + } + + // ---------- 样式(沿用宿主 CSS 变量,明暗主题自适应) ---------- + + var CSS = [ + '.iwb-bx{height:100%;width:100%;display:flex;flex-direction:column;min-height:0;', + 'font:12px/1.5 system-ui,-apple-system,"PingFang SC",sans-serif;color:var(--iwb-text,#1c2333)}', + '.iwb-bx-bar{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;padding:12px;', + 'border-bottom:1px solid var(--iwb-border,#d5d9e0)}', + // 配置区与列表之间的隔断:灰底小节头 + 上下各一条线,比单根淡线明显得多 + '.iwb-bx-sec{display:flex;align-items:center;gap:6px;padding:6px 12px;', + 'background:var(--iwb-layer,#f0f1f4);border-bottom:1px solid var(--iwb-border,#d5d9e0);', + 'font-size:11px;color:var(--iwb-text2,#4d5668)}', + '.iwb-bx-sec-title{font-weight:600;color:var(--iwb-text,#1c2333)}', + '.iwb-bx-sec .iwb-bx-btn{padding:3px 8px;font-size:11px}', + '.iwb-bx-spacer{flex:1}', + '.iwb-bx-f{display:flex;flex-direction:column;gap:3px;min-width:0}', + '.iwb-bx-f>span{font-size:11px;color:var(--iwb-text2,#4d5668)}', + '.iwb-bx-f select,.iwb-bx-f input{width:100%;box-sizing:border-box;padding:4px 6px;border-radius:6px;', + 'border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);color:inherit;font:inherit}', + '.iwb-bx-rowchk{flex-direction:row;align-items:center;gap:6px;grid-column:span 2;cursor:pointer}', + // checkbox 必须显式收回 width:上面的 .iwb-bx-f input{width:100%} 会把它撑满整行,把标签挤到最右 + '.iwb-bx-rowchk input[type=checkbox]{width:auto;flex:0 0 auto;margin:0;padding:0}', + '.iwb-bx-rowchk>span{font-size:11px;white-space:nowrap}', + '.iwb-bx-list{flex:1;min-height:0;overflow:auto}', + '.iwb-bx-item{display:flex;align-items:center;gap:8px;padding:7px 12px;', + 'border-bottom:1px solid var(--iwb-border,#d5d9e0)}', + '.iwb-bx-item:hover{background:var(--iwb-layer,#f0f1f4)}', + // 名称/状态都要能被压缩:加了行内下载按钮后,窄面板里若只有 tag 不缩,名称会被挤成 0 宽 + '.iwb-bx-name{flex:1;min-width:70px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}', + '.iwb-bx-tag{font-size:11px;white-space:nowrap;color:var(--iwb-text2,#4d5668);', + 'max-width:46%;min-width:0;overflow:hidden;text-overflow:ellipsis}', + '.iwb-bx-tag-ok{color:#1d9e75}', + '.iwb-bx-tag-err{color:#d85a30}', + // 行内单张下载:常驻不悬浮(要一眼看出「这行能下什么」),无产物时灰掉但保留占位, + // 避免产物出现时行宽突然变化导致列表跳动。 + '.iwb-bx-dl{flex:0 0 auto;padding:2px 6px;border-radius:5px;font-size:11px;line-height:1.5;', + 'font-family:ui-monospace,SFMono-Regular,Menlo,monospace;border:1px solid var(--iwb-border,#d5d9e0);', + 'background:transparent;color:var(--iwb-text2,#4d5668);cursor:pointer}', + '.iwb-bx-dl-on{background:var(--iwb-layer,#f0f1f4);color:var(--iwb-text,#1c2333);border-color:var(--iwb-text2,#4d5668)}', + '.iwb-bx-dl-on:hover{border-color:#2f6fed;color:#2f6fed}', + '.iwb-bx-dl[disabled]{opacity:.45;cursor:not-allowed;border-color:var(--iwb-border,#d5d9e0)}', + '.iwb-bx-empty{padding:24px 12px;text-align:center;color:var(--iwb-text2,#4d5668)}', + // 缩略图:小方图(30px)常驻在行首,跑完换成产物本身,一眼能对上「哪张图、出了什么」 + '.iwb-bx-thumb{width:30px;height:30px;flex:0 0 auto;object-fit:contain;border-radius:5px;', + 'border:1px solid var(--iwb-border,#d5d9e0);background:#fff;cursor:zoom-in;padding:1px}', + '.iwb-bx-thumb-out{border-color:#1d9e75;cursor:zoom-in}', + '.iwb-bx-thumb-ph{background:var(--iwb-layer,#f0f1f4);cursor:default}', + '.iwb-bx-done{display:none;align-items:center;gap:6px;padding:9px 12px;font-size:11px;', + 'color:#1d9e75;background:rgba(29,158,117,.08);border-top:1px solid var(--iwb-border,#d5d9e0)}', + '.iwb-bx-zoom{position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;', + 'background:rgba(0,0,0,.72);cursor:zoom-out}', + '.iwb-bx-zoom img{max-width:86vw;max-height:86vh;border-radius:8px;background:#fff}', + // 双类选择器:单靠 .iwb-bx-btn-hot 会被后定义的 .iwb-bx-btn 背景覆盖(同特异性,后者胜) + '.iwb-bx-btn.iwb-bx-btn-hot{background:#1d9e75;border-color:#1d9e75;color:#fff}', + '.iwb-bx-foot{display:flex;align-items:center;gap:8px;padding:10px 12px;', + 'border-top:1px solid var(--iwb-border,#d5d9e0)}', + '.iwb-bx-prog{flex:1;height:4px;border-radius:2px;background:var(--iwb-border,#d5d9e0);overflow:hidden}', + '.iwb-bx-prog i{display:block;height:100%;width:0;background:#2f6fed;transition:width .15s}', + '.iwb-bx-btn{padding:5px 10px;border-radius:6px;border:1px solid var(--iwb-border,#d5d9e0);', + 'background:var(--iwb-layer,#f0f1f4);color:inherit;font:inherit;cursor:pointer;white-space:nowrap}', + '.iwb-bx-btn[disabled]{opacity:.45;cursor:not-allowed}', + '.iwb-bx-btn-primary{background:#2f6fed;border-color:#2f6fed;color:#fff}', + ].join('') + + function ensureStyle() { + try { + if (document.querySelector('style[data-iwb-batch]')) return + var style = document.createElement('style') + style.setAttribute('data-iwb-batch', '1') + style.textContent = CSS + ;(document.head || document.documentElement).appendChild(style) + } catch (error) { /* 样式注入失败不影响功能 */ } + } + + global.IWBPluginHost.register({ + id: 'batch-export', + name: '批量出图', + version: '1.2.0', + apiVersion: 1, + capabilities: ['panels', 'canvas'], + settings: { + apiUrl: { type: 'text', label: '抠图服务地址', desc: '面板勾了「先抠图」才用。CSP 仅放行 127.0.0.1 / localhost 的 30092 端口。', default: DEFAULT_API }, + timeoutMs: { type: 'number', label: '抠图超时(毫秒)', desc: '单张抠图的超时;服务卡住时按失败处理,继续下一张。', default: DEFAULT_TIMEOUT }, + }, + }, function (ctx) { + var state = { + items: [], + running: false, + lastZip: null, + sig: "", + opts: loadOpts(), + } + var dom = null + + function store() { + try { + return ctx.storage && typeof ctx.storage.namespace === 'function' ? ctx.storage.namespace('opts') : null + } catch (error) { + return null + } + } + + function loadOpts() { + var bucket = null + try { bucket = store() } catch (error) { bucket = null } + var saved = bucket ? bucket.get('panel') : null + var out = {} + for (var key in DEFAULT_OPTS) out[key] = DEFAULT_OPTS[key] + if (saved && typeof saved === 'object') { + for (var k in DEFAULT_OPTS) { + if (Object.prototype.hasOwnProperty.call(saved, k) && saved[k] !== undefined && saved[k] !== null) out[k] = saved[k] + } + } + return out + } + + function saveOpts() { + try { + var bucket = store() + if (bucket) bucket.set('panel', state.opts) + } catch (error) { + ctx.log('batch: 保存参数失败', error && error.message) + } + } + + // ---------- 数据 ---------- + + // 画布节点签名:只关心 id + 文件名,用来判断面板打开期间是否新拖入了图 + function nodeSig() { + var nodes = [] + try { nodes = ctx.canvas.getNodes() || [] } catch (error) { nodes = [] } + var parts = [] + for (var i = 0; i < nodes.length; i++) { + var n = nodes[i] + if (!n || n.type !== 'ref') continue + var d = n.data || {} + if (!d.data && !d.url) continue + parts.push(n.id + ':' + String(d.name || d.title || '')) + } + return parts.join('|') + } + + async function makeSrcThumb(nodeId) { + if (!ctx.canvas || typeof ctx.canvas.getNodeImage !== 'function') return null + var image = await ctx.canvas.getNodeImage(nodeId) + var src = image && (image.dataUrl || image.url) + if (!src) return null + var img = await loadImageEl(src) + var w = img.naturalWidth || img.width + var h = img.naturalHeight || img.height + if (!w || !h) return null + var edge = 64 + var scale = Math.min(1, edge / Math.max(w, h)) + var canvas = document.createElement('canvas') + canvas.width = Math.max(1, Math.round(w * scale)) + canvas.height = Math.max(1, Math.round(h * scale)) + var g = canvas.getContext('2d') + if (!g) return null + // 透明图在浅色底上看不清,缩略图统一垫白 + g.fillStyle = '#ffffff' + g.fillRect(0, 0, canvas.width, canvas.height) + g.drawImage(img, 0, 0, canvas.width, canvas.height) + return canvas.toDataURL('image/png') + } + + // 串行补齐源图缩略图:一次解一张,避免几十张大图同时解码把主线程顶住 + function fillSrcThumbs() { + if (srcThumbBusy) return + srcThumbBusy = true + ;(async function () { + try { + for (var i = 0; i < state.items.length; i++) { + var item = state.items[i] + if (!item || item.srcThumb) continue + if (Object.prototype.hasOwnProperty.call(srcThumbCache, item.id)) { + item.srcThumb = srcThumbCache[item.id] || null + continue + } + srcThumbCache[item.id] = '' + var url = null + try { url = await makeSrcThumb(item.id) } catch (error) { url = null } + srcThumbCache[item.id] = url || '' + item.srcThumb = url || null + if (dom) render() + } + } finally { + srcThumbBusy = false + } + })() + } + + function refreshNodes() { + var nodes = [] + try { nodes = ctx.canvas.getNodes() || [] } catch (error) { nodes = [] } + var prev = {} + for (var i = 0; i < state.items.length; i++) prev[state.items[i].id] = state.items[i] + + var next = [] + var sig = [] + for (var j = 0; j < nodes.length; j++) { + var node = nodes[j] + if (!node || node.type !== 'ref') continue + var data = node.data || {} + if (!data.data && !data.url) continue + sig.push(node.id + ':' + String(data.name || data.title || '')) + var old = prev[node.id] + next.push({ + id: node.id, + name: String(data.name || data.title || '未命名'), + checked: old ? old.checked : true, + status: old ? old.status : 'idle', + error: old ? old.error : null, + files: old ? old.files : null, + thumbUrl: old ? old.thumbUrl : null, + srcThumb: old ? old.srcThumb : null, + }) + } + state.sig = sig.join('|') + state.items = next + render() + fillSrcThumbs() + } + + // ---------- 单张处理 ---------- + + async function sourceBlob(nodeId) { + var image = await ctx.canvas.getNodeImage(nodeId) + if (!image) throw new Error('该节点没有可编码的图片') + if (image.dataUrl) return blobFromDataUrl(image.dataUrl) + if (!image.url) throw new Error('该节点没有可编码的图片') + + var resp + try { resp = await global.fetch(image.url) } catch (error) { + throw new Error('远程图片读取失败(可能跨域受限):请先转存为本地位图') + } + if (!resp.ok) throw new Error('远程图片读取失败:HTTP ' + resp.status) + return resp.blob() + } + + async function cutout(blob) { + var apiUrl = trimUrl(ctx.settings.get('apiUrl')) + var timeoutMs = toPositive(ctx.settings.get('timeoutMs'), DEFAULT_TIMEOUT) + var controller = typeof global.AbortController === 'function' ? new global.AbortController() : null + var timer = controller ? global.setTimeout(function () { + try { controller.abort() } catch (error) { /* ignore */ } + }, timeoutMs) : null + + var resp + try { + resp = await global.fetch(apiUrl + '/rmbg?crop=true', { + method: 'POST', + headers: { 'Content-Type': 'application/octet-stream' }, + body: blob, + signal: controller ? controller.signal : undefined, + }) + } catch (error) { + throw new Error('连不上本地抠图服务(' + apiUrl + '):' + String((error && error.message) || error)) + } finally { + if (timer) global.clearTimeout(timer) + } + + if (!resp.ok) { + var detail = '' + try { detail = await resp.text() } catch (error) { detail = '' } + throw new Error('抠图服务返回 ' + resp.status + (detail ? ':' + String(detail).slice(0, 120) : '')) + } + return new Blob([await resp.arrayBuffer()], { type: 'image/png' }) + } + + async function processOne(item, used) { + var opts = state.opts + var blob = await sourceBlob(item.id) + if (opts.cutout) blob = await cutout(blob) + var img = await decodeBlob(blob) + + var size = Math.round(clamp(Number(opts.size) || 800, 64, 4096)) + var ratio = clamp(Number(opts.ratioPct) || 80, 10, 100) / 100 + var maxKB = Number(opts.maxKB) + var maxBytes = Number.isFinite(maxKB) && maxKB > 0 ? Math.round(maxKB * 1024) : 0 + var base = String(item.name || 'image').replace(/\.[^.]+$/, '') || 'image' + var prefix = String(opts.prefix || '') + var quality = 0.82 + + var targets + if (opts.mode === 'dual') { + targets = [ + { format: 'png', transparent: true, allowOversize: true }, + { format: 'jpeg', transparent: false, allowOversize: false }, + ] + } else if (opts.mode === 'png') { + targets = [{ format: 'png', transparent: true, allowOversize: false }] + } else { + targets = [{ format: 'jpeg', transparent: false, allowOversize: false }] + } + + var files = [] + for (var i = 0; i < targets.length; i++) { + var target = targets[i] + var canvas = composeCanvas(img, size, ratio, target.transparent) + var out = await encodeWithLimit(canvas, target.format, quality, maxBytes, target.allowOversize) + var ext = TYPE_EXT[out.type] || FORMATS[target.format].ext + var name = uniqueName(used, prefix + base + '_' + size + 'x' + size + '.' + ext) + files.push({ name: name, blob: out, size: out.size }) + } + return files + } + + async function runQueue(only) { + if (state.running) return + var targets = only ? [only] : state.items.filter(function (item) { return item.checked }) + if (!targets.length) return + + state.running = true + state.lastZip = null + var used = {} + // 只重置本轮要跑的项:单张「重试」不该把其它已完成项的结果擦掉 + for (var i = 0; i < targets.length; i++) { + targets[i].files = null + targets[i].error = null + if (targets[i].thumbUrl) { + try { URL.revokeObjectURL(targets[i].thumbUrl) } catch (error) { /* ignore */ } + targets[i].thumbUrl = null + } + } + render() + + var okCount = 0 + for (var j = 0; j < targets.length; j++) { + var item = targets[j] + item.status = 'running' + item.error = null + render() + try { + item.files = await processOne(item, used) + item.status = 'done' + thumbOf(item) + okCount++ + } catch (error) { + item.status = 'fail' + item.error = String((error && error.message) || error) + ctx.log('batch: ' + item.name + ' 失败:' + item.error) + } + render() + } + + state.running = false + render() + ctx.log('batch: 完成 ' + okCount + '/' + targets.length) + } + + async function exportZip() { + var files = [] + for (var i = 0; i < state.items.length; i++) { + var item = state.items[i] + if (item.status !== 'done' || !item.files) continue + for (var j = 0; j < item.files.length; j++) files.push(item.files[j]) + } + if (!files.length) return + var zip = await makeStoreZip(files) + var zipName = 'batch_' + fileStamp() + '.zip' + downloadBlob(zip, zipName) + state.lastZip = zipName + render() + } + + // ---------- 视图 ---------- + + function statusText(item) { + if (item.status === 'running') return '处理中…' + if (item.status === 'done') { + var total = 0 + for (var i = 0; i < (item.files || []).length; i++) total += item.files[i].size + return (item.files || []).length + ' 个文件 · ' + kb(total) + } + if (item.status === 'fail') return '失败' + return '待处理' + } + + function build() { + var sizeSel = el('select', {}) + for (var i = 0; i < SIZE_OPTIONS.length; i++) { + sizeSel.appendChild(el('option', { value: SIZE_OPTIONS[i], text: SIZE_OPTIONS[i] + ' × ' + SIZE_OPTIONS[i] })) + } + var modeSel = el('select', {}, + [el('option', { value: 'dual', text: '双版本 PNG + JPG' }), + el('option', { value: 'jpeg', text: '仅白底 JPG' }), + el('option', { value: 'png', text: '仅透明 PNG' })]) + var ratioIn = el('input', { type: 'number', min: 10, max: 100, step: 1 }) + var maxIn = el('input', { type: 'number', min: 0, step: 10 }) + var prefixIn = el('input', { type: 'text', placeholder: '如 DQ_' }) + var cutChk = el('input', { type: 'checkbox' }) + + var listEl = el('div', { class: 'iwb-bx-list' }) + var secCount = el('span', { class: 'iwb-bx-sec-count', text: '0' }) + var doneBar = el('div', { class: 'iwb-bx-done' }) + var progFill = el('i') + var progText = el('span', { class: 'iwb-bx-tag' }) + var btnStart = el('button', { class: 'iwb-bx-btn iwb-bx-btn-primary', text: '开始出图' }) + var btnZip = el('button', { class: 'iwb-bx-btn', text: '导出 ZIP' }) + var btnAll = el('button', { class: 'iwb-bx-btn', text: '全选' }) + var btnNone = el('button', { class: 'iwb-bx-btn', text: '清空' }) + var btnRefresh = el('button', { class: 'iwb-bx-btn', text: '刷新' }) + + sizeSel.addEventListener('change', function () { state.opts.size = Number(sizeSel.value); saveOpts() }) + modeSel.addEventListener('change', function () { state.opts.mode = String(modeSel.value); saveOpts() }) + ratioIn.addEventListener('change', function () { state.opts.ratioPct = Number(ratioIn.value); saveOpts() }) + maxIn.addEventListener('change', function () { state.opts.maxKB = Number(maxIn.value); saveOpts() }) + prefixIn.addEventListener('input', function () { state.opts.prefix = String(prefixIn.value); saveOpts() }) + cutChk.addEventListener('change', function () { state.opts.cutout = Boolean(cutChk.checked); saveOpts() }) + + btnAll.addEventListener('click', function () { + for (var i = 0; i < state.items.length; i++) state.items[i].checked = true + render() + }) + btnNone.addEventListener('click', function () { + for (var i = 0; i < state.items.length; i++) state.items[i].checked = false + render() + }) + btnRefresh.addEventListener('click', function () { refreshNodes() }) + btnStart.addEventListener('click', function () { runQueue() }) + btnZip.addEventListener('click', function () { + exportZip().catch(function (error) { + ctx.log('batch: 导出失败', error && error.message) + if (dom && dom.progText) { + dom.progText.className = 'iwb-bx-tag iwb-bx-tag-err' + dom.progText.textContent = '打包失败' + dom.progText.title = String((error && error.message) || error) + } + }) + }) + + var root = el('div', { class: 'iwb-bx' }, [ + el('div', { class: 'iwb-bx-bar' }, [ + el('label', { class: 'iwb-bx-f' }, [el('span', { text: '尺寸' }), sizeSel]), + el('label', { class: 'iwb-bx-f' }, [el('span', { text: '版本' }), modeSel]), + el('label', { class: 'iwb-bx-f' }, [el('span', { text: '内容占比 %' }), ratioIn]), + el('label', { class: 'iwb-bx-f' }, [el('span', { text: '体积上限 KB(0=不限)' }), maxIn]), + el('label', { class: 'iwb-bx-f' }, [el('span', { text: '文件名前缀' }), prefixIn]), + el('label', { + class: 'iwb-bx-f iwb-bx-rowchk', + title: '勾选后先 POST localhost:30092/rmbg 抠成透明底再合成;本机服务没启动时请勿勾选(每张会多等几秒)', + }, [cutChk, el('span', { text: '走本地鲜艺抠图(localhost:30092)' })]), + ]), + // 隔断 + 小节头:把「配置」和「节点列表」明确分开,以前只有一根淡灰线,看不出分界 + el('div', { class: 'iwb-bx-sec' }, [ + el('span', { class: 'iwb-bx-sec-title', text: '待处理节点' }), + secCount, + el('span', { class: 'iwb-bx-spacer' }), + btnAll, + btnNone, + btnRefresh, + ]), + listEl, + doneBar, + el('div', { class: 'iwb-bx-foot' }, [ + el('div', { class: 'iwb-bx-prog' }, [progFill]), + progText, + btnStart, + btnZip, + ]), + ]) + + sizeSel.value = String(state.opts.size) + modeSel.value = String(state.opts.mode) + ratioIn.value = String(state.opts.ratioPct) + maxIn.value = String(state.opts.maxKB) + prefixIn.value = String(state.opts.prefix || '') + cutChk.checked = Boolean(state.opts.cutout) + + return { + root: root, listEl: listEl, doneBar: doneBar, progFill: progFill, progText: progText, + secCount: secCount, + btnStart: btnStart, btnZip: btnZip, btnAll: btnAll, btnNone: btnNone, btnRefresh: btnRefresh, + } + } + + function render() { + if (!dom) return + var total = 0 + var settled = 0 + var zipCount = 0 + var zipBytes = 0 + for (var i = 0; i < state.items.length; i++) { + var item = state.items[i] + if (item.checked) total++ + if (item.checked && (item.status === 'done' || item.status === 'fail')) settled++ + if (item.status === 'done' && item.files) { + zipCount += item.files.length + for (var f = 0; f < item.files.length; f++) zipBytes += item.files[f].size || 0 + } + } + + // 列表只在结构变化时重建代价可接受(节点数 ≤ 几十),但运行中避免整体重绘导致闪烁 + var list = dom.listEl + list.textContent = '' + if (!state.items.length) { + list.appendChild(el('div', { class: 'iwb-bx-empty', text: '画布上没有可处理的参考图节点:把图片拖进画布后点「刷新」' })) + } else { + for (var j = 0; j < state.items.length; j++) { + ;(function (item) { + var chk = el('input', { type: 'checkbox', checked: item.checked }) + chk.addEventListener('change', function () { item.checked = Boolean(chk.checked); render() }) + + var tag = el('span', { + class: 'iwb-bx-tag' + (item.status === 'done' ? ' iwb-bx-tag-ok' : item.status === 'fail' ? ' iwb-bx-tag-err' : ''), + text: item.status === 'fail' && item.error ? '失败 · ' + item.error : statusText(item), + title: item.error || statusText(item), + }) + + var row = el('div', { class: 'iwb-bx-item' }, [ + chk, + rowThumb(item), + el('span', { class: 'iwb-bx-name', text: item.name, title: item.name }), + tag, + ]) + if (item.status === 'fail') { + row.appendChild(el('button', { + class: 'iwb-bx-btn', + text: '重试', + onclick: function () { + item.checked = true + runQueue(item) + }, + })) + } + // 单张下载常驻在行尾:JPG 在前、PNG 在后(与常用顺序一致)。 + // 有产物亮起,没有则灰着 —— 用户要求的「默认就有,但要有图才能点」。 + row.appendChild(dlBtn(item, 'jpg', 'JPG')) + row.appendChild(dlBtn(item, 'png', 'PNG')) + list.appendChild(row) + })(state.items[j]) + } + } + + if (dom.secCount) dom.secCount.textContent = '共 ' + state.items.length + ' 个' + var pct = total ? Math.round(settled / total * 100) : 0 + dom.progFill.style.width = pct + '%' + dom.progText.textContent = settled + '/' + total + dom.btnStart.disabled = state.running || total === 0 + dom.btnZip.disabled = state.running || zipCount === 0 + dom.btnAll.disabled = state.running || state.items.length === 0 + dom.btnNone.disabled = state.running || state.items.length === 0 + dom.btnRefresh.disabled = state.running + + // 跑完给一条明确的「图在哪」:产物在内存里,必须点导出才会落盘(不进画布) + if (dom.doneBar) { + if (!state.running && zipCount > 0) { + dom.doneBar.style.display = 'flex' + dom.doneBar.textContent = state.lastZip + ? '已下载 ' + state.lastZip + '(' + zipCount + ' 个文件 · ' + kb(zipBytes) + '),可再次导出' + : '已生成 ' + zipCount + ' 个文件 · ' + kb(zipBytes) + ',点「导出 ZIP」下载到本机(不写入画布)' + } else { + dom.doneBar.style.display = 'none' + } + } + dom.btnZip.className = 'iwb-bx-btn' + (zipCount > 0 && !state.running ? ' iwb-bx-btn-hot' : '') + } + + // 面板打开期间用户可能继续往画布拖图;宿主没有画布变更事件,只能轻量轮询签名 + var syncTimer = null + + // ---------- 挂载 / 宿主容器守卫 ---------- + + // 宿主切 tab 时会把同一个 div 复用给「图库 / 节点组」:React 对同类型且无 key 的子节点直接复用, + // 只清理它自己管理的子节点,插件手动 append 的根节点不会被清掉 ⇒ 面板会「串页」到图库上方。 + // 这里监听容器:一旦容器不再属于插件面板(class 变了,或混进了别人的子节点),立刻自行摘除。 + var hostEl = null + var mounting = false + var hostGuard = typeof global.MutationObserver === 'function' ? new global.MutationObserver(onHostChange) : null + + function isPanelHost(node) { + return Boolean(node && node.classList && node.classList.contains('iwb-full-panel-plugin')) + } + + function detachFromHost() { + if (syncTimer) { global.clearInterval(syncTimer); syncTimer = null } + closePreview() + if (dom && dom.root && dom.root.parentNode) { + try { dom.root.parentNode.removeChild(dom.root) } catch (error) { /* ignore */ } + } + dom = null + } + + function onHostChange() { + if (!hostEl || mounting) return + if (!isPanelHost(hostEl)) { detachFromHost(); return } + var mine = dom && dom.root && dom.root.parentNode === hostEl + if (mine) { + // 同一个容器里混进了别人的子节点(另一个 tab 的内容)⇒ 让位 + if (hostEl.children.length > 1) detachFromHost() + return + } + // 只有容器已经清空、且归插件使用时才重新挂载;还有别人的子节点时绝不动它(避免误删宿主 DOM) + if (hostEl.children.length === 0) mount(hostEl) + else dom = null + } + + function mount(host) { + if (!host) return + mounting = true + try { + ensureStyle() + // 宿主的 .iwb-full-main 是 flex 行容器,只给图库/节点组容器 width:100%,插件容器不给 ⇒ + // 会按内容宽度收缩(按钮一少整块只剩一半宽)。这里直接把容器撑满,避免依赖宿主补样式。 + host.style.width = '100%' + host.style.flex = '1 1 auto' + host.style.minWidth = '0' + host.style.minHeight = '0' + host.textContent = '' + dom = build() + host.appendChild(dom.root) + if (hostGuard) { + hostGuard.disconnect() + hostGuard.observe(host, { childList: true, attributes: true, attributeFilter: ['class'] }) + } + hostEl = host + refreshNodes() + } finally { + mounting = false + } + + if (syncTimer) { global.clearInterval(syncTimer); syncTimer = null } + syncTimer = global.setInterval(function () { + if (!dom || !dom.root || !document.body.contains(dom.root)) { + global.clearInterval(syncTimer) + syncTimer = null + return + } + if (state.running) return + if (nodeSig() !== state.sig) refreshNodes() + }, 2000) + } + + ctx.ui.registerPanel({ id: 'batch-panel', title: '批量出图', icon: 'download', mount: mount }) + + return {} + }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/plugins/runtime/plugin-blank-canvas.67763893fa99.js b/plugins/runtime/plugin-blank-canvas.67763893fa99.js new file mode 100644 index 0000000..79ebb1f --- /dev/null +++ b/plugins/runtime/plugin-blank-canvas.67763893fa99.js @@ -0,0 +1,137 @@ +// iwb-plugin: 空白画布 —— 给「空白的参考图节点」填入指定尺寸(1K)的纯白图片,作为插图/标注的起点。 +// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/content.js 的 BLANK_RATIOS / performBlankCanvas / showBlankMenu。 +// 有意差异:只保留 1K 档(上游菜单实际也只用 1K);只填当前节点(不新建);不联动编辑器。 +;(function (global) { + 'use strict' + + // 与宿主 app.js 的 RATIOS 表 1K 档逐字一致。插件不能 import 宿主内部,故照抄数值; + // 上游扩展也是这么做的(BLANK_RATIOS 抄自宿主)。 + var SIZES = [ + { label: '1:1 方形', w: 1024, h: 1024 }, + { label: '2:3 竖版', w: 832, h: 1248 }, + { label: '3:2 横版', w: 1248, h: 832 }, + { label: '3:4 竖版', w: 880, h: 1168 }, + { label: '4:3 横版', w: 1184, h: 880 }, + { label: '4:5 竖版', w: 912, h: 1136 }, + { label: '5:4 横版', w: 1136, h: 896 }, + { label: '9:16 竖版', w: 768, h: 1360 }, + { label: '16:9 横版', w: 1360, h: 752 }, + { label: '21:9 超宽', w: 1552, h: 656 }, + { label: '9:21 超宽竖版', w: 656, h: 1520 }, + ] + + var CSS = [ + '.iwb-blankcanvas-menu{position:fixed;left:50%;top:64px;transform:translateX(-50%);z-index:2147483000;', + 'width:312px;padding:10px;border-radius:10px;box-sizing:border-box;', + 'background:var(--iwb-panel,#fff);color:var(--iwb-text,#1c2333);', + 'border:1px solid var(--iwb-border,#d5d9e0);box-shadow:0 12px 32px rgba(0,0,0,.28);', + 'font:12px/1.4 system-ui,-apple-system,"PingFang SC",sans-serif}', + '.iwb-blankcanvas-title{font-weight:600;margin:2px 2px 8px}', + '.iwb-blankcanvas-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}', + '.iwb-blankcanvas-item{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 4px;', + 'border-radius:8px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);', + 'color:inherit;font:inherit;cursor:pointer}', + '.iwb-blankcanvas-item:hover{background:var(--iwb-layer2,#fff)}', + '.iwb-blankcanvas-item b{font-weight:600}', + '.iwb-blankcanvas-item i{font-style:normal;font-size:11px;color:var(--iwb-text2,#4d5668)}', + ].join('') + + global.IWBPluginHost.register({ + id: 'blank-canvas', + name: '空白画布', + version: '1.0.0', + apiVersion: 1, + capabilities: ['nodeActions', 'canvas', 'canvasWrite'], + }, function (ctx) { + var STYLE_ID = 'iwb-blankcanvas-style' + var menuEl = null + var outsideHandler = null + + function injectStyle() { + if (document.getElementById(STYLE_ID)) return + var style = document.createElement('style') + style.id = STYLE_ID + style.textContent = CSS + ;(document.head || document.documentElement).appendChild(style) + } + + // 与上游 isEmptyRefNode 等价:ref 节点且既无本地数据也无 URL({__blob}/{__cache} 引用是对象,天然为真) + function isEmptyImageNode(node) { + if (!node || node.type !== 'ref') return false + var d = node.data || {} + return !d.data && !d.url + } + + function whitePng(w, h) { + var canvas = document.createElement('canvas') + canvas.width = w + canvas.height = h + var ctx2d = canvas.getContext('2d') + ctx2d.fillStyle = '#ffffff' + ctx2d.fillRect(0, 0, w, h) + return canvas.toDataURL('image/png') + } + + function closeMenu() { + if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl) + menuEl = null + if (outsideHandler) { document.removeEventListener('pointerdown', outsideHandler, true); outsideHandler = null } + document.removeEventListener('keydown', onKeyDown, true) + } + + function onKeyDown(e) { if (e.key === 'Escape') closeMenu() } + + function apply(nodeId, w, h) { + var nodes = (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? ctx.canvas.getNodes() : [] + var target = null + for (var i = 0; i < nodes.length; i++) if (nodes[i] && nodes[i].id === nodeId) target = nodes[i] + if (!target || !isEmptyImageNode(target)) throw new Error('该节点不是空白的图片节点') + // 宿主把 canvasWrite 的 API 合并进 ctx.canvas(plugin-host.js 的 CAPABILITY_API_KEYS)⇒ 写接口在 ctx.canvas 上 + if (!ctx.canvas.setNodeImage(nodeId, whitePng(w, h))) throw new Error('写入节点失败') + } + + function openMenu(nodeId) { + injectStyle() + closeMenu() + var menu = document.createElement('div') + menu.className = 'iwb-blankcanvas-menu' + var title = document.createElement('div') + title.className = 'iwb-blankcanvas-title' + title.textContent = '创建空白画布(1K)' + menu.appendChild(title) + var grid = document.createElement('div') + grid.className = 'iwb-blankcanvas-grid' + SIZES.forEach(function (size) { + var btn = document.createElement('button') + btn.type = 'button' + btn.className = 'iwb-blankcanvas-item' + btn.setAttribute('data-size', size.w + 'x' + size.h) + btn.innerHTML = '' + size.label + '' + size.w + '×' + size.h + '' + btn.addEventListener('pointerdown', function (e) { e.stopPropagation() }) + btn.addEventListener('click', function (e) { + e.stopPropagation() + e.preventDefault() + closeMenu() + apply(nodeId, size.w, size.h) + }) + grid.appendChild(btn) + }) + menu.appendChild(grid) + document.body.appendChild(menu) + menuEl = menu + outsideHandler = function (e) { if (!menuEl || !menuEl.contains(e.target)) closeMenu() } + document.addEventListener('pointerdown', outsideHandler, true) + document.addEventListener('keydown', onKeyDown, true) + } + + ctx.nodeActions.register({ + id: 'blank-canvas-open', + title: '空白画布', + icon: 'plus', + appliesTo: function (node) { return isEmptyImageNode(node) }, + run: function (node) { openMenu(node.id); return true }, + }) + + return { dispose: closeMenu } + }) +})(typeof window !== 'undefined' ? window : globalThis) diff --git a/plugins/runtime/plugin-image-annotate.86ccc161901c.js b/plugins/runtime/plugin-image-annotate.86ccc161901c.js new file mode 100644 index 0000000..4deea93 --- /dev/null +++ b/plugins/runtime/plugin-image-annotate.86ccc161901c.js @@ -0,0 +1,9132 @@ +// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号, +// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。 +// +// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id, +// 排在 bundle 之前才能保证取到的是下面这份 manifest,而不是打包代码里的同形字面量。 +// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。 +// +// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。 +var __IWB_ANNOTATE_MANIFEST__ = { + id: 'image-annotate', + name: '标注 / 修图', + version: '1.20.1', + apiVersion: 1, + capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'], + settings: { + exportPreset: { type: 'string', default: 'original' }, + exportFormat: { type: 'string', default: 'png' }, + exportBg: { type: 'string', default: 'transparent' }, + exportMaxKB: { type: 'number', default: 0 }, + exportSize: { type: 'number', default: 800 }, + panelsCollapsed: { type: 'boolean', default: false } + }, +} + +"use strict"; +(() => { + // image-annotate/plugin/editor/text.js + var TEXT_LINE_HEIGHT = 1.25; + var TEXT_DEFAULTS = { + color: "#ff4444", + strokeWidth: 0, + strokeColor: "#ffffff", + bgFill: false, + bgColor: "#101014", + bgAlpha: 0.68 + }; + var BG_PAD_RATIO = 0.3; + var _measureCtx = null; + function measureCtx() { + if (!_measureCtx) { + const c = document.createElement("canvas"); + c.width = 8; + c.height = 8; + _measureCtx = c.getContext("2d"); + } + return _measureCtx; + } + function weightOf(t) { + const w = t && t.fontWeight; + return w == null || w === "" ? "bold" : String(w); + } + var TEXT_FONTS = { + sans: { + label: "黑体", + stack: '"PingFang SC", "Microsoft YaHei", "Heiti SC", "Hiragino Sans GB", "Source Han Sans SC", "Noto Sans SC", sans-serif' + }, + serif: { + label: "宋体", + stack: '"Songti SC", "SimSun", "STSong", "Source Han Serif SC", "Noto Serif SC", serif' + }, + kai: { + label: "楷体", + stack: '"Kaiti SC", "KaiTi", "STKaiti", "AR PL UKai CN", "Noto Serif SC", serif' + }, + round: { + label: "圆体", + stack: '"Yuanti SC", "YouYuan", "STYuanti", "PingFang SC", sans-serif' + } + }; + var TEXT_FONT_KEYS = ["sans", "serif", "kai", "round"]; + var TEXT_FONT_DEFAULT = "sans"; + function fontKeyOf(t) { + const k = t && t.fontFamily; + return TEXT_FONTS[k] ? k : TEXT_FONT_DEFAULT; + } + function fontStackOf(t) { + return TEXT_FONTS[fontKeyOf(t)].stack; + } + function fontOf(t) { + const size = Math.max(4, Number(t && t.fontSize) || 32); + return weightOf(t) + " " + size + "px " + fontStackOf(t); + } + function textMetrics(t) { + const ctx = measureCtx(); + const font = fontOf(t); + ctx.font = font; + const raw = (t && t.text) == null ? "" : String(t.text); + const lines = raw.split("\n"); + const widths = lines.map((line) => ctx.measureText(line).width); + const size = Math.max(4, Number(t && t.fontSize) || 32); + const lh = size * (Number(t && t.lineHeight) || TEXT_LINE_HEIGHT); + const w = lines.length ? Math.max.apply(null, widths) : 0; + const pad = t && t.bgFill ? Math.round(size * BG_PAD_RATIO) : 0; + const sw = Math.max(0, Number(t && t.strokeWidth) || 0); + return { lines, widths, w, h: lh * lines.length, lh, pad, sw, font, size }; + } + function textBox(t) { + const m = textMetrics(t); + const half = m.sw / 2; + return { + x: t.x - half, + y: t.y - half, + w: Math.max(m.w, 2) + m.pad * 2 + m.sw, + h: Math.max(m.h, 1) + m.pad * 2 + m.sw + }; + } + function alignOf(t) { + const a = t && t.align; + return a === "center" || a === "right" ? a : "left"; + } + function drawTextObject(ctx, t) { + const m = textMetrics(t); + ctx.save(); + ctx.textBaseline = "top"; + ctx.globalAlpha = t.opacity != null ? t.opacity : 1; + const b = textBox(t); + const rot = t.rotation || 0; + if (rot) { + const cx = b.x + b.w / 2; + const cy = b.y + b.h / 2; + ctx.translate(cx, cy); + ctx.rotate(rot * Math.PI / 180); + ctx.translate(-cx, -cy); + } + ctx.font = m.font; + const align = alignOf(t); + const boxW = m.w + m.pad * 2; + if (t.bgFill) { + const r = Math.min(m.pad + 2, Math.min(boxW, m.h + m.pad * 2) / 2); + ctx.globalAlpha = (t.opacity != null ? t.opacity : 1) * (t.bgAlpha == null ? TEXT_DEFAULTS.bgAlpha : t.bgAlpha); + ctx.fillStyle = t.bgColor || TEXT_DEFAULTS.bgColor; + const bx = t.x, by = t.y; + const bw = boxW, bh = m.h + m.pad * 2; + ctx.beginPath(); + if (typeof ctx.roundRect === "function") { + ctx.roundRect(bx, by, bw, bh, r); + } else { + ctx.moveTo(bx + r, by); + ctx.arcTo(bx + bw, by, bx + bw, by + bh, r); + ctx.arcTo(bx + bw, by + bh, bx, by + bh, r); + ctx.arcTo(bx, by + bh, bx, by, r); + ctx.arcTo(bx, by, bx + bw, by, r); + ctx.closePath(); + } + ctx.fill(); + ctx.globalAlpha = t.opacity != null ? t.opacity : 1; + } + ctx.textAlign = align; + const left = t.x + m.pad; + const ox = align === "center" ? left + m.w / 2 : align === "right" ? left + m.w : left; + ctx.lineJoin = "round"; + ctx.miterLimit = 2; + for (let i = 0; i < m.lines.length; i++) { + const y = t.y + m.pad + i * m.lh; + if (m.sw > 0) { + ctx.lineWidth = m.sw; + ctx.strokeStyle = t.strokeColor || TEXT_DEFAULTS.strokeColor; + ctx.strokeText(m.lines[i], ox, y); + } + ctx.fillStyle = t.color || TEXT_DEFAULTS.color; + ctx.fillText(m.lines[i], ox, y); + } + ctx.restore(); + } + function newTextStyle(src) { + const s = src || {}; + return { + fontWeight: weightOf(s), + // 字体 key 过一遍收敛:外部传进来不认识的字符串不会进 ctx.font(脏值会让整个 + // 字体串失效、静默退回浏览器默认,文件本身看不出问题,极难排查) + fontFamily: fontKeyOf(s), + align: alignOf(s), + lineHeight: Number(s.lineHeight) || TEXT_LINE_HEIGHT, + strokeWidth: Math.max(0, Number(s.strokeWidth) || 0), + strokeColor: s.strokeColor || TEXT_DEFAULTS.strokeColor, + bgFill: !!s.bgFill, + bgColor: s.bgColor || TEXT_DEFAULTS.bgColor, + bgAlpha: s.bgAlpha == null ? TEXT_DEFAULTS.bgAlpha : Number(s.bgAlpha) + }; + } + + // image-annotate/plugin/editor/state.js + var ZOOM_MIN = 0.1; + var ZOOM_MAX = 10; + var ZOOM_STEP = 1.15; + var S = { + open: false, + tool: "brush", + color: "#ff4444", + brushSize: 3, + brushHardness: 100, + // 画笔硬度 0~100:100=硬边描边,<100=径向渐变软边章 + brushOpacity: 1, + // 画笔透明度 0.05~1(一笔整体透明度,笔划内不叠加) + prevTool: null, + // 吸管工具激活前的工具(取色后切回) + // 画布内最后一次悬停点(图片坐标):用 [ ] 调笔刷大小时要按这个点立刻重画笔刷环, + // 否则光标环会停在旧尺寸,直到用户再动一下鼠标才更新(v1.6) + hoverPos: null, + lastClick: null, + // 上一次画布按下 {t,x,y}:自算双击用(dblclick 在画布上不可靠) + // 上一次点击图层名 {id,t}:图层面板重命名也走自算双击(点一下就会重绘面板, + // 浏览器不会在同一个节点上派发 dblclick) + lastNameClick: null, + altPicker: false, + // 按住 Alt 的临时吸管(画笔/橡皮下),松开 Alt 回到原工具 + pickerComposite: null, + // 吸管取样用的合成画布缓存(切工具/画布变化时失效) + // v1.8 快速效果的「可重调」状态:source 是点效果那一刻的像素备份, + // 拖强度滑杆时一律从 source 重算,绝不在上一次结果上叠加(否则来回拖会越拖越糊)。 + // layerId 用于判断源是否还对得上当前目标层:切层后滑杆自动置灰,切回即恢复。 + fx: { key: null, value: 0, layerId: null, source: null }, + // v1.15 图片调节:连续调色(曝光/对比度/白平衡…)。source 是原尺寸基准, + // previewCanvas 是它的降采样副本 —— 拖动滑杆用小的算(6.7ms),松手才用原图算(几十~上百 ms)。 + // 两者都只做「输入」,结果永远从基准重算,不在上一次结果上叠加。 + adjust: { layerId: null, source: null, previewCanvas: null, params: null }, + rectFill: false, + // 矩形/圆形是否实心填充 + penFill: true, + // 钢笔闭合路径是否实心填充(只对闭合路径有意义) + // v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细, + // 否则「调细画笔」会顺手把所有形状的描边一起改掉。 + shapeLineWidth: 3, + // 矩形/圆形/箭头/钢笔的描边粗细 + // v1.17:默认是否画描边。关掉后形状只剩填充(「无描边」), + // 对象上另存 strokeOn,老对象没有这个字段一律视为有描边。 + shapeStrokeOn: true, + shapeRadius: 0, + // 矩形圆角半径 px(v1.9,仅 rect 有意义) + // v1.10:矢量图形的填充色。null = 跟随描边色(新画的就是「同色实心」, + // 换主色时整体跟着变),一旦单独选过填充色就固定下来(每形状自己存 fillColor)。 + shapeFillColor: null, + // v1.11:工具栏色板当前在调哪个颜色。描边与填充是同一个控件上的两个槽, + // 色板(调色器 / 吸管 / 推荐色 / hex)按这个值决定写 S.color 还是 shapeFillColor, + // 否则「三个地方各调各的颜色」会一直存在。 + colorTarget: "stroke", + // stroke | fill + // v1.18:色板弹层是否「钉住」。钉住后点画布/点别处都不收起,方便连着调几处颜色。 + // 存宿主 KV(跨会话记住):钉过一次就一直钉着,下次打开仍生效。 + colorPopPinned: false, + // v1.16:右侧栏宽度(px)。0 = 按默认值走,打开编辑器时从宿主 KV 恢复。 + // 宽度统一落在 CSS 变量 --iwb-side-w 上,不再各条规则各写一个魔数。 + sideWidth: 0, + textSize: 32, + // 新建文字的字号 px + // ---- v1.9 文字样式:这套是「新建文字」的默认值,每段文字自己存一份 ---- + textWeight: "bold", + // bold | normal | 900 + textFamily: "sans", + // v1.14 字体预设 key:sans 黑体 | serif 宋体 | kai 楷体 | round 圆体 + textAlign: "left", + // left | center | right(多行时各行按块宽对齐) + textLineHeight: 1.25, + // 行高倍数(1.25 = 老版单行高度,勿随意改) + textStrokeWidth: TEXT_DEFAULTS.strokeWidth, + // 描边宽度 px,0 = 无描边 + textStrokeColor: TEXT_DEFAULTS.strokeColor, + textBgFill: TEXT_DEFAULTS.bgFill, + // 底色块 + textBgColor: TEXT_DEFAULTS.bgColor, + // 中性近黑,不再是纯黑 #000000 + textBgAlpha: TEXT_DEFAULTS.bgAlpha, + // 底色透明度(色块按这个不透明度显示,所见即所得) + // 最近使用颜色(最多 6 个,存 ctx.settings,跨会话保留) + recentColors: [], + // 图层系统 + layers: [], + // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }] + activeLayerId: null, + // 当前活跃位图图层 ID(画笔/橡皮操作目标) + // 画布引用(动态创建的 canvas 元素) + canvasWrap: null, + canvasStack: null, + textCanvas: null, + strokeCanvas: null, + overlayCanvas: null, + textCtx: null, + strokeCtx: null, + overlayCtx: null, + isDrawing: false, + panning: false, + panStart: null, + startX: 0, + startY: 0, + history: [], + redoStack: [], + cropRect: null, + cropHandle: null, + cropMoving: false, + moveStart: null, + cropConstraint: { type: "free", ratio: 0, sizeW: 0, sizeH: 0 }, + // 文字图层(独立对象,可选中/移动/缩放/再编辑) + textLayers: [], + // [{ id, x, y, text, color, fontSize, opacity, visible, z }] + selectedTextId: null, + textDrag: null, + // { mode:'move'|'scale', start:{x,y}, layer:{x,y}, fontSize, baseX } + textEditingId: null, + selectedLayerId: null, + // 选择工具当前选中的可编辑位图图层 + // 图层多选集合 [{id,type}](v1.6):只为「合并选中图层」服务, + // 不参与单选语义(selectedLayerId / selectedTextId 仍各管各的)。 + layerMulti: [], + bitmapDrag: null, + // { mode:'move'|'scale', handle, start, layer, pending } + // 形状图层(矩形/箭头,独立对象,可选中/移动/调手柄) + shapeLayers: [], + // [{ id, type:'rect'|'arrow', x1,y1,x2,y2, color, lw, fill, opacity, visible, z }] + selectedShapeId: null, + shapeDrag: null, + // { mode:'move'|'handle', handle, start:{x,y}, shape:{...}, pending } + penPath: null, + // 钢笔绘制中的点序列与预览点 + penEditId: null, + // 钢笔二次编辑中的形状 id + penDragPt: -1, + // 正在拖动的节点下标(-1=无) + penDragBase: null, + penDragPending: null, + zCounter: 0, + // 全局 z 序计数器(文字与形状统一排序) + // 图片放置中状态(导入图片时先调整大小/位置再确认) + placingImage: null, + // { img, x, y, w, h } 图片坐标 + placingHandle: null, + // 'move' | 'nw'|'ne'|'sw'|'se'|'n'|'s'|'e'|'w' + placingStart: null, + // { mx, my, x, y, w, h } + imgW: 0, + imgH: 0, + overlayPad: 0, + originalImage: null, + // 打开时的原始图片,用于「复原」 + fitW: 0, + fitH: 0, + // 适应容器时的基准显示尺寸 + zoom: 1, + // 缩放倍率(基于 fit) + viewX: null, + // 画布平移位置(wrap 内 left;null = 居中显示) + viewY: null, + callbacks: null, + spaceDown: false, + _shiftDown: false, + _canvasEventsBound: false, + // ---- v1.1 选区 / 便利性 ---- + selection: null, + // { kind, path, bbox, feather, active, fillRule, outline } + marquee: null, + // 拉框中的临时选区 { x0,y0,x1,y1,kind } + lassoPts: null, + // 套索绘制中的点序列 + selectionKind: "rect", + // 选区工具的形状:rect | ellipse + selectionFeather: 0, + // 羽化 px(0~20) + selectionCanvas: null, + // 蚂蚁线专用层(与 overlay 分离,互不擦除) + selectionCtx: null, + cursorCanvas: null, + // 笔刷环专用层 + cursorCtx: null, + _antFrame: 0, + // 蚂蚁线 rAF 句柄 + _antOffset: 0, + exportOptions: null, + // { preset, format, bg, maxKB, size },来自 ctx.settings + interaction: "idle", + // 轻量交互状态机:idle | marquee | lasso | placing | cropping + renderAll: null, + // 由 index.js 注入的统一重绘出口 + // 撤销/重做后由 history.js 调用:调节基准与参数必须跟着历史走, + // 否则「撤销把像素还原了、滑杆还显示 +80」—— 参数与画面对不上,再拖一次就叠加。 + // 用回调而不是直接 import,避免 history ↔ adjust 循环依赖。 + onHistoryRestore: null, + guides: null, + // 拖动吸附参考线(图片坐标,松手清空):[{axis:'x'|'y', at, from, to}] + lastExport: null + // 观测口:{ bytes, width, height, format, preset } + }; + var runtime = { el: null }; + + // image-annotate/plugin/editor/scale.js + function viewScale() { + return S.imgW && S.fitW ? S.fitW * S.zoom / S.imgW : 1; + } + function overlayScale() { + const base = S.imgW && S.fitW ? S.fitW / S.imgW : 1; + return Math.max(1, Math.min(4, base)); + } + function resetOverlayTransform(cx) { + const k = overlayScale(); + const pad = S.overlayPad || 0; + cx.setTransform(k, 0, 0, k, pad * k, pad * k); + } + + // image-annotate/plugin/editor/placement.js + function commitImageAsLayer(img, x, y, w, h, rotation) { + const id = "L" + Date.now() + Math.floor(Math.random() * 1e3); + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.clearRect(0, 0, S.imgW, S.imgH); + const layer = { + id, + name: "图层 " + (S.layers.length + 1), + image: img, + x, + y, + w, + h, + rotation: rotation || 0, + transformable: true, + canvas, + ctx, + opacity: 1, + visible: true, + locked: false, + // 与矢量对象 / 空白图层共用同一个 z 计数器(旧值 S.layers.length 会和 ++S.zCounter 撞车, + // 导致粘贴的截图与图形 z 相同:排序按钮交换 z 无效、命中测试选错对象) + z: ++S.zCounter + }; + redrawBitmapLayer(layer); + saveSnapshot(); + S.layers.push(layer); + reorderLayerCanvas(); + setActiveLayer(id); + updateLayerCanvasStyles(); + renderLayerPanel(); + return layer; + } + function confirmImagePlacement() { + if (!S.placingImage) return; + const { img, x, y, w, h } = S.placingImage; + const placementRotation = S.placingImage.rotation || 0; + S.placingImage = null; + S.placingHandle = null; + S.placingStart = null; + clearOverlay(); + commitImageAsLayer(img, x, y, w, h, placementRotation); + updateCursor(); + } + function placeImageDirectly(img) { + const iw = img.naturalWidth || img.width; + const ih = img.naturalHeight || img.height; + const ratio = Math.min(S.imgW * 0.5 / iw, S.imgH * 0.5 / ih, 1); + const w = Math.max(10, Math.round(iw * ratio)); + const h = Math.max(10, Math.round(ih * ratio)); + const layer = commitImageAsLayer(img, Math.round((S.imgW - w) / 2), Math.round((S.imgH - h) / 2), w, h, 0); + try { + if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); + } catch (e) { + } + if (S.renderAll) S.renderAll(); + return layer; + } + function cancelImagePlacement() { + S.placingImage = null; + S.placingHandle = null; + S.placingStart = null; + clearOverlay(); + updateCursor(); + } + function drawPlacementPreview() { + if (!S.placingImage) return; + const ctx = S.overlayCtx; + const { img, x, y, w, h } = S.placingImage; + const rot = S.placingImage.rotation || 0; + const cx = x + w / 2, cy = y + h / 2; + clearOverlay(); + ctx.save(); + ctx.fillStyle = "rgba(0,0,0,0.35)"; + ctx.fillRect(0, 0, S.imgW, S.imgH); + ctx.restore(); + ctx.save(); + ctx.translate(cx, cy); + if (rot) ctx.rotate(rot * Math.PI / 180); + ctx.translate(-cx, -cy); + ctx.drawImage(img, x, y, w, h); + ctx.restore(); + const corners = boxCorners(x, y, w, h, rot); + ctx.save(); + ctx.strokeStyle = "#4488ff"; + ctx.lineWidth = 2 / viewScale(); + ctx.setLineDash([8 / viewScale(), 4 / viewScale()]); + ctx.beginPath(); + ctx.moveTo(corners[0][0], corners[0][1]); + for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1]); + ctx.closePath(); + ctx.stroke(); + ctx.setLineDash([]); + const hs = 5.5 / viewScale(); + ctx.fillStyle = "#fff"; + ctx.strokeStyle = "#4488ff"; + ctx.lineWidth = 1.5 / viewScale(); + const localPts = { + nw: [x, y], + ne: [x + w, y], + sw: [x, y + h], + se: [x + w, y + h], + n: [x + w / 2, y], + s: [x + w / 2, y + h], + e: [x + w, y + h / 2], + w: [x, y + h / 2] + }; + for (const name in localPts) { + const ptp = rotPt(localPts[name][0], localPts[name][1], cx, cy, rot); + ctx.beginPath(); + ctx.rect(ptp[0] - hs, ptp[1] - hs, hs * 2, hs * 2); + ctx.fill(); + ctx.stroke(); + } + ctx.restore(); + drawRotationHandles(ctx, { x, y, w, h }, rot); + ctx.save(); + ctx.font = "bold " + Math.round(14 / viewScale()) + "px sans-serif"; + ctx.textAlign = "center"; + ctx.textBaseline = "top"; + const hintText = "拖拽手柄调整大小 · 圆点=旋转 · Shift=等比/15°吸附 · Enter=确认 · Esc=取消"; + const br = boxCorners(x, y, w, h, rot).reduce((acc, pt) => Math.max(acc, pt[1]), -Infinity); + const hintY = br + 10 / viewScale(); + const tw = ctx.measureText(hintText).width; + ctx.fillStyle = "rgba(0,0,0,0.6)"; + ctx.fillRect(cx - tw / 2 - 6 / viewScale(), hintY, tw + 12 / viewScale(), 22 / viewScale()); + ctx.fillStyle = "rgba(255,255,255,0.95)"; + ctx.fillText(hintText, cx, hintY + 4 / viewScale()); + ctx.restore(); + } + function hitPlacementHandle(pos) { + if (!S.placingImage) return null; + const { x, y, w, h } = S.placingImage; + const rot = S.placingImage.rotation || 0; + const cx = x + w / 2, cy = y + h / 2; + const lp = unrotPt(pos.x, pos.y, cx, cy, rot); + const R = 12 / viewScale(); + if (hitRotationHandle(lp, { x, y, w, h })) return "rotate"; + const pts = { + nw: [x, y], + ne: [x + w, y], + sw: [x, y + h], + se: [x + w, y + h], + n: [x + w / 2, y], + s: [x + w / 2, y + h], + e: [x + w, y + h / 2], + w: [x, y + h / 2] + }; + let best = null, bestDist = 1e9; + for (const name in pts) { + const dx = lp[0] - pts[name][0], dy = lp[1] - pts[name][1]; + const d = dx * dx + dy * dy; + if (d < R * R && d < bestDist) { + bestDist = d; + best = name; + } + } + return best; + } + function insidePlacementRect(pos) { + if (!S.placingImage) return false; + const { x, y, w, h } = S.placingImage; + const rot = S.placingImage.rotation || 0; + const cx = x + w / 2, cy = y + h / 2; + const lp = unrotPt(pos.x, pos.y, cx, cy, rot); + return lp[0] >= x && lp[0] <= x + w && lp[1] >= y && lp[1] <= y + h; + } + function resizePlacement(pos) { + if (!S.placingImage || !S.placingHandle || !S.placingStart) return; + const { img } = S.placingImage; + const s = S.placingStart; + const iw = img.naturalWidth || img.width; + const ih = img.naturalHeight || img.height; + const aspect = iw / ih; + const hh = S.placingHandle; + if (hh === "move") { + const dx = pos.x - s.mx; + const dy = pos.y - s.my; + S.placingImage.x = s.x + dx; + S.placingImage.y = s.y + dy; + return; + } + if (hh === "rotate") { + const rcx = s.x + s.w / 2, rcy = s.y + s.h / 2; + const a0 = Math.atan2(s.my - rcy, s.mx - rcx); + const a1 = Math.atan2(pos.y - rcy, pos.x - rcx); + let deg = (s.rotation || 0) + (a1 - a0) * 180 / Math.PI; + if (S._shiftDown) deg = Math.round(deg / 15) * 15; + S.placingImage.rotation = deg; + return; + } + const loc = unrotPt(pos.x, pos.y, s.x + s.w / 2, s.y + s.h / 2, s.rotation || 0); + pos = { x: loc[0], y: loc[1] }; + let nx = s.x, ny = s.y, nw = s.w, nh = s.h; + if (hh.includes("e")) nw = Math.max(10, pos.x - s.x); + if (hh.includes("s")) nh = Math.max(10, pos.y - s.y); + if (hh.includes("w")) { + const r = s.x + s.w; + nx = Math.min(pos.x, r - 10); + nw = r - nx; + } + if (hh.includes("n")) { + const b = s.y + s.h; + ny = Math.min(pos.y, b - 10); + nh = b - ny; + } + if (S._shiftDown) { + if (nw / nh > aspect) { + if (hh.includes("n") || hh.includes("s")) { + nw = nh * aspect; + if (hh.includes("w")) nx = s.x + s.w - nw; + } else { + nh = nw / aspect; + if (hh.includes("n")) ny = s.y + s.h - nh; + } + } else { + if (hh.includes("e") || hh.includes("w")) { + nh = nw / aspect; + if (hh.includes("n")) ny = s.y + s.h - nh; + } else { + nw = nh * aspect; + if (hh.includes("w")) nx = s.x + s.w - nw; + } + } + } + S.placingImage.x = nx; + S.placingImage.y = ny; + S.placingImage.w = nw; + S.placingImage.h = nh; + } + + // image-annotate/plugin/vendor/layer-logic.js + function isDrawableLayer(layer) { + return !!layer && layer.id !== "base" && !layer.image; + } + function restorePath(layer) { + if (!layer) return "pixels"; + const sourceCanvas = isDrawableLayer(layer) ? null : layer.sourceCanvas; + if (layer.transformable && (layer.image || sourceCanvas)) return "redraw"; + return "pixels"; + } + function needsPixelSnapshot(layer) { + return restorePath(layer) === "pixels"; + } + + // image-annotate/plugin/vendor/image-math.js + function hexToRgb(hex) { + const h = String(hex || "").replace("#", ""); + const v = h.length === 3 ? h.split("").map((c) => c + c).join("") : h; + return { + r: parseInt(v.slice(0, 2), 16) || 0, + g: parseInt(v.slice(2, 4), 16) || 0, + b: parseInt(v.slice(4, 6), 16) || 0 + }; + } + function rgbToHex(r, g, b) { + const to = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, "0"); + return `#${to(r)}${to(g)}${to(b)}`; + } + function parseRatio(str) { + if (str === "free" || !str) return 0; + const parts = String(str).split(":"); + if (parts.length === 2) { + const w = parseFloat(parts[0]); + const h = parseFloat(parts[1]); + if (w > 0 && h > 0) return w / h; + } + return 0; + } + + // image-annotate/plugin/editor/recent-colors.js + var MAX = 16; + var KEY = "recentColors"; + function valid(hex) { + return /^#[0-9a-f]{6}$/i.test(String(hex || "")); + } + function loadRecentColors() { + const st = S.callbacks && S.callbacks.settings; + let list = []; + if (st && typeof st.get === "function") { + try { + const got = st.get(KEY); + if (Array.isArray(got)) list = got; + } catch (e) { + } + } + S.recentColors = list.filter(valid).map((c) => String(c).toLowerCase()).slice(0, MAX); + renderRecentColors(); + } + function rememberColor(hex) { + if (!valid(hex)) return; + const c = String(hex).toLowerCase(); + if (S.recentColors && S.recentColors[0] === c) return; + const list = [c].concat((S.recentColors || []).filter((x) => x !== c)); + S.recentColors = list.slice(0, MAX); + const st = S.callbacks && S.callbacks.settings; + if (st && typeof st.set === "function") { + try { + st.set(KEY, S.recentColors); + } catch (e) { + } + } + renderRecentColors(); + } + function renderRecentColors() { + if (!runtime.el) return; + const wraps = runtime.el.querySelectorAll(".iwb-editor-recent-colors"); + if (!wraps.length) return; + const list = S.recentColors || []; + const html = list.map( + (c) => `` + ).join(""); + wraps.forEach((wrap) => { + wrap.innerHTML = html; + wrap.hidden = !list.length; + const group = wrap.closest(".iwb-color-group"); + if (group) group.hidden = !list.length; + }); + } + + // image-annotate/plugin/editor/tools.js + var brushStampCache = { key: "", canvas: null }; + function getBrushStamp(size, color, hardness) { + const key = size + "|" + color + "|" + hardness; + if (brushStampCache.key === key && brushStampCache.canvas) return brushStampCache.canvas; + const c = document.createElement("canvas"); + c.width = size; + c.height = size; + const cx = c.getContext("2d"); + const half = size / 2; + const { r, g, b } = hexToRgb(color); + const grad = cx.createRadialGradient(half, half, half * hardness / 100, half, half, half); + grad.addColorStop(0, `rgba(${r},${g},${b},1)`); + grad.addColorStop(1, `rgba(${r},${g},${b},0)`); + cx.fillStyle = grad; + cx.fillRect(0, 0, size, size); + brushStampCache = { key, canvas: c }; + return c; + } + function strokeSegment(x1, y1, x2, y2) { + const ctx = S.strokeCtx; + const size = Math.max(1, S.brushSize); + const color = S.tool === "eraser" ? "#ffffff" : S.color; + ctx.save(); + if (S.brushHardness >= 100) { + ctx.strokeStyle = color; + ctx.lineWidth = size; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + } else { + const stamp = getBrushStamp(size, color, S.brushHardness); + const dist = Math.hypot(x2 - x1, y2 - y1); + const step = Math.max(1, size / 6); + const n = Math.max(0, Math.ceil(dist / step)); + for (let i = 0; i <= n; i++) { + const t = n === 0 ? 0 : i / n; + ctx.drawImage(stamp, x1 + (x2 - x1) * t - size / 2, y1 + (y2 - y1) * t - size / 2); + } + } + ctx.restore(); + S.strokeCanvas.style.opacity = S.brushOpacity; + } + function eraseSegment(x1, y1, x2, y2) { + const ctx = getActiveCtx(); + if (!ctx) return; + ctx.save(); + if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule); + ctx.globalCompositeOperation = "destination-out"; + ctx.globalAlpha = S.brushOpacity; + ctx.lineWidth = Math.max(1, S.brushSize); + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + ctx.restore(); + const active = getActiveLayer(); + if (active && active.id === "draw" && active.sourceCanvas) { + const sourceCtx = active.sourceCanvas.getContext("2d", { willReadFrequently: true }); + sourceCtx.save(); + sourceCtx.globalCompositeOperation = "destination-out"; + sourceCtx.globalAlpha = S.brushOpacity; + sourceCtx.lineWidth = Math.max(1, S.brushSize) * active.w / Math.max(S.imgW, 1); + sourceCtx.lineCap = "round"; + sourceCtx.beginPath(); + sourceCtx.moveTo((x1 - active.x) * S.imgW / active.w, (y1 - active.y) * S.imgW / active.w); + sourceCtx.lineTo((x2 - active.x) * S.imgW / active.w, (y2 - active.y) * S.imgW / active.w); + sourceCtx.stroke(); + sourceCtx.restore(); + } + S.pickerComposite = null; + renderObjects(); + } + function bakeDrawableLayer(layer) { + if (!layer || !isDrawableLayer(layer) || !layer._srcBox) return; + layer._srcBox = null; + layer.sourceCanvas = null; + layer.rotation = 0; + layer.x = 0; + layer.y = 0; + layer.w = S.imgW; + layer.h = S.imgH; + layer._bounds = void 0; + } + function beginStroke() { + bakeDrawableLayer(getActiveLayer()); + S.strokeCanvas.width = S.imgW; + S.strokeCanvas.height = S.imgH; + S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH); + S.strokeCanvas.style.display = S.tool === "eraser" ? "none" : "block"; + S.strokeCanvas.style.opacity = S.brushOpacity; + } + function endStroke() { + for (const l of S.layers) l._bounds = void 0; + const ctx = getActiveCtx(); + if (!ctx) return; + ctx.save(); + if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule); + if (S.tool === "eraser") { + ctx.globalCompositeOperation = "destination-out"; + } + ctx.globalAlpha = S.brushOpacity; + ctx.drawImage(S.strokeCanvas, 0, 0); + ctx.restore(); + S.strokeCanvas.style.display = "none"; + const active = getActiveLayer(); + if (active && active.id === "draw" && active.sourceCanvas && active.w > 0 && active.h > 0) { + const sourceCtx = active.sourceCanvas.getContext("2d", { willReadFrequently: true }); + sourceCtx.save(); + sourceCtx.globalCompositeOperation = S.tool === "eraser" ? "destination-out" : "source-over"; + sourceCtx.globalAlpha = S.brushOpacity; + sourceCtx.translate(-active.x * S.imgW / active.w, -active.y * S.imgH / active.h); + sourceCtx.scale(S.imgW / active.w, S.imgH / active.h); + sourceCtx.drawImage(S.strokeCanvas, 0, 0); + sourceCtx.restore(); + } + S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH); + S.pickerComposite = null; + } + function roundedRadius(s, w, h) { + const r = Number(s && s.radius) || 0; + if (r <= 0) return 0; + return Math.min(r, Math.min(w, h) / 2); + } + function roundRectPath(ctx, x, y, w, h, r) { + const rr = Math.min(r, Math.min(w, h) / 2); + ctx.moveTo(x + rr, y); + ctx.arcTo(x + w, y, x + w, y + h, rr); + ctx.arcTo(x + w, y + h, x, y + h, rr); + ctx.arcTo(x, y + h, x, y, rr); + ctx.arcTo(x, y, x + w, y, rr); + ctx.closePath(); + } + function strokeOf(s) { + return s && s.color || S.color; + } + function fillOf(s) { + return s && s.fillColor || strokeOf(s); + } + function drawShape(ctx, s) { + ctx.save(); + ctx.globalAlpha = s.opacity != null ? s.opacity : 1; + const rot = s.rotation || 0; + if (rot) { + const b = shapeBounds(s); + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + ctx.translate(cx, cy); + ctx.rotate(rot * Math.PI / 180); + ctx.translate(-cx, -cy); + } + ctx.strokeStyle = strokeOf(s); + ctx.lineWidth = s.lw; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + const strokeOn = s.strokeOn !== false; + if (s.type === "pen") { + const pts = Array.isArray(s.pts) ? s.pts : []; + if (pts.length > 1) { + ctx.beginPath(); + ctx.moveTo(pts[0].x, pts[0].y); + for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y); + if (s.closed) ctx.closePath(); + if (s.closed && s.fill) { + ctx.fillStyle = fillOf(s); + ctx.fill(); + } + if (strokeOn) ctx.stroke(); + } + } else if (s.type === "rect") { + const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1); + const radius = roundedRadius(s, rw, rh); + if (radius > 0) { + ctx.beginPath(); + roundRectPath(ctx, rx, ry, rw, rh, radius); + if (s.fill) { + ctx.fillStyle = fillOf(s); + ctx.fill(); + } + if (strokeOn) ctx.stroke(); + } else { + if (s.fill) { + ctx.fillStyle = fillOf(s); + ctx.fillRect(rx, ry, rw, rh); + } + if (strokeOn) ctx.strokeRect(rx, ry, rw, rh); + } + } else if (s.type === "circle") { + const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2); + const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1); + ctx.beginPath(); + ctx.ellipse(rx + rw / 2, ry + rh / 2, Math.max(1, rw / 2), Math.max(1, rh / 2), 0, 0, Math.PI * 2); + if (s.fill) { + ctx.fillStyle = fillOf(s); + ctx.fill(); + } + if (strokeOn) ctx.stroke(); + } else if (strokeOn) { + ctx.fillStyle = strokeOf(s); + ctx.beginPath(); + ctx.moveTo(s.x1, s.y1); + ctx.lineTo(s.x2, s.y2); + ctx.stroke(); + const angle = Math.atan2(s.y2 - s.y1, s.x2 - s.x1); + const headLen = Math.max(12, s.lw * 4); + ctx.beginPath(); + ctx.moveTo(s.x2, s.y2); + ctx.lineTo(s.x2 - headLen * Math.cos(angle - Math.PI / 6), s.y2 - headLen * Math.sin(angle - Math.PI / 6)); + ctx.moveTo(s.x2, s.y2); + ctx.lineTo(s.x2 - headLen * Math.cos(angle + Math.PI / 6), s.y2 - headLen * Math.sin(angle + Math.PI / 6)); + ctx.stroke(); + } + ctx.restore(); + } + function getToolBrushRadius() { + return Math.max(1, S.brushSize) / 2; + } + function screenScale() { + const rect = S.canvasStack.getBoundingClientRect(); + return rect.width ? rect.width / S.imgW : S.zoom; + } + function clearToolRing() { + const ctx = S.cursorCtx; + if (!ctx) return; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + ctx.restore(); + resetOverlayTransform(ctx); + } + function drawToolRing(pos) { + clearToolRing(); + const ctx = S.cursorCtx || S.overlayCtx; + const r = getToolBrushRadius(); + const k = 1 / screenScale(); + const rMin = 2 * k; + const rr = Math.max(r, rMin); + ctx.save(); + ctx.lineWidth = k; + ctx.strokeStyle = "rgba(0,0,0,0.8)"; + ctx.beginPath(); + ctx.arc(pos.x, pos.y, rr, 0, Math.PI * 2); + ctx.stroke(); + ctx.strokeStyle = "rgba(255,255,255,0.9)"; + ctx.lineWidth = k; + ctx.beginPath(); + ctx.arc(pos.x, pos.y, Math.max(rr - k, 0), 0, Math.PI * 2); + ctx.stroke(); + ctx.restore(); + } + function getCompositeCanvas() { + const c = document.createElement("canvas"); + c.width = S.imgW; + c.height = S.imgH; + const cx = c.getContext("2d", { willReadFrequently: true }); + cx.globalAlpha = 1; + for (const u of layerUnits()) { + if (u.obj.visible === false) continue; + const el = u.kind === "bitmap" ? u.obj.canvas : u.obj._canvas; + if (!el) continue; + cx.globalAlpha = u.kind === "bitmap" ? u.obj.opacity == null ? 1 : u.obj.opacity : 1; + cx.drawImage(el, 0, 0); + } + cx.globalAlpha = 1; + return c; + } + function getPickerComposite() { + if (!S.pickerComposite) { + S.pickerComposite = getCompositeCanvas().getContext("2d", { willReadFrequently: true }); + } + return S.pickerComposite; + } + function sampleColor(pos) { + const x = clamp(Math.floor(pos.x), 0, Math.max(0, S.imgW - 1)); + const y = clamp(Math.floor(pos.y), 0, Math.max(0, S.imgH - 1)); + try { + const d = getPickerComposite().getImageData(x, y, 1, 1).data; + return { r: d[0], g: d[1], b: d[2], a: d[3] }; + } catch (e) { + return null; + } + } + function showPickerTip(e, s) { + const tip = runtime.el.querySelector(".iwb-editor-picker-tip"); + if (!tip) return; + const chip = tip.querySelector(".iwb-editor-picker-chip"); + const hex = tip.querySelector(".iwb-editor-picker-hex"); + if (s && s.a > 0) { + const h = rgbToHex(s.r, s.g, s.b); + chip.style.background = h; + chip.style.border = "1px solid rgba(255,255,255,0.3)"; + hex.textContent = h; + } else { + chip.style.background = "transparent"; + chip.style.border = "1px dashed rgba(255,255,255,0.4)"; + hex.textContent = "透明"; + } + tip.style.display = "flex"; + tip.style.left = e.clientX + 16 + "px"; + tip.style.top = e.clientY + 16 + "px"; + } + function hidePickerTip() { + const tip = runtime.el.querySelector(".iwb-editor-picker-tip"); + if (tip) tip.style.display = "none"; + } + function exitPicker() { + if (S.altPicker) { + S.pickerComposite = null; + hidePickerTip(); + return; + } + S.tool = S.prevTool && S.prevTool !== "picker" ? S.prevTool : "brush"; + S.prevTool = null; + const back = S.tool; + if (back !== "select") { + S.selectedLayerId = null; + S.selectedTextId = null; + S.selectedShapeId = null; + } + S.pickerComposite = null; + hidePickerTip(); + updateToolUI(); + updateBrushParamUI(); + if (S.tool === "crop") { + showCropBar(); + updateCropInfo(); + } else { + cancelCrop(); + hideCropBar(); + } + renderObjects(); + } + function beginAltPicker() { + if (S.altPicker) return; + if (S.tool !== "brush" && S.tool !== "eraser") return; + if (S.isDrawing) return; + S.altPicker = true; + setTool("picker"); + } + function endAltPicker() { + if (!S.altPicker) return; + S.altPicker = false; + exitPicker(); + } + function applyColorChange(color, opts) { + const skipHistory = !!(opts && opts.skipHistory); + S.color = color; + if (!skipHistory) rememberColor(color); + updateColorUI(); + const t = getSelectedText(); + if (t && !t.locked && t.color !== S.color) { + if (!skipHistory) saveSnapshot(); + t.color = S.color; + renderObjects(); + } + const sh = getSelectedShape(); + if (sh && !sh.locked && S.tool !== "text" && (sh.color !== S.color || sh.strokeOn === false)) { + const revive = sh.strokeOn === false; + if (!skipHistory) saveSnapshot(); + sh.color = S.color; + if (revive) { + sh.strokeOn = true; + S.shapeStrokeOn = true; + } + renderObjects(); + } + } + function setTool(tool) { + if (S.placingImage) cancelImagePlacement(); + commitTextInput(); + if (tool !== "picker") S.altPicker = false; + if (tool !== "select") { + S.penEditId = null; + S.penDragPt = -1; + S.penDragPending = null; + } + if (tool === "picker" && S.tool !== "picker") S.prevTool = S.tool; + if (tool !== "pen") S.penPath = null; + if (tool === "crop") { + S.selection = null; + S.marquee = null; + S.lassoPts = null; + } + if (tool !== "marquee" && tool !== "lasso") { + if (S.marquee || S.lassoPts) { + S.isDrawing = false; + S.interaction = "idle"; + } + S.marquee = null; + S.lassoPts = null; + } + S.tool = tool; + const keepSel = tool === "select" || tool === "picker"; + if (!keepSel) { + S.selectedLayerId = null; + S.selectedTextId = null; + S.selectedShapeId = null; + } + S.bitmapDrag = null; + S.textDrag = null; + S.shapeDrag = null; + S.pickerComposite = null; + S.lastClick = null; + hidePickerTip(); + updateToolUI(); + updateBrushParamUI(); + if (tool === "crop") { + showCropBar(); + updateCropInfo(); + } else { + cancelCrop(); + hideCropBar(); + } + renderObjects(); + renderLayerPanel(); + if (S.renderAll) S.renderAll(); + } + + // image-annotate/plugin/editor/commands.js + var COMMANDS = /* @__PURE__ */ Object.create(null); + function defineCommand(name, def) { + COMMANDS[name] = Object.assign({ label: name }, def || {}); + } + function execute(label, mutator) { + const before = S.history.length; + saveSnapshot(label); + let result; + try { + result = mutator(); + } catch (err) { + if (S.history.length === before + 1) S.history.pop(); + throw err; + } + if (S.renderAll) S.renderAll(); + return result; + } + function runCommand(name) { + const def = COMMANDS[name]; + if (!def) return false; + if (S.tool === "crop" && String(name).indexOf("sel.") === 0) { + toast("裁剪中不可使用选区命令,请先切换工具", "warn"); + return false; + } + if (typeof def.enabled === "function" && !def.enabled()) { + toast(def.hint || "当前状态下不可用", "warn"); + return false; + } + const args = Array.prototype.slice.call(arguments, 1); + try { + if (def.view) { + const r = def.run.apply(null, args); + if (S.renderAll) S.renderAll(); + return r; + } + return execute(def.label, () => def.run.apply(null, args)); + } catch (err) { + console.error("[IWB编辑器] 命令执行失败:" + name, err); + toast("操作失败:" + (err && err.message || name), "error"); + return false; + } + } + var toastTimer = null; + function toast(message, kind) { + const el = runtime.el && runtime.el.querySelector(".iwb-editor-toast"); + if (!el) return; + el.textContent = String(message || ""); + el.className = "iwb-editor-toast iwb-editor-toast-" + (kind || "info") + " show"; + if (toastTimer) clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + el.classList.remove("show"); + toastTimer = null; + }, 2600); + } + + // image-annotate/plugin/editor/snap.js + var SNAP_SCREEN_PX = 6; + var GUIDE_COLOR = "#ff2d95"; + function pushBox(targets, box) { + const x2 = box.x + box.w; + const y2 = box.y + box.h; + targets.x.push(box.x, box.x + box.w / 2, x2); + targets.y.push(box.y, box.y + box.h / 2, y2); + } + function nearest(targets, sources, tol, axis) { + let best = null; + for (let i = 0; i < targets.length; i++) { + for (let j = 0; j < sources.length; j++) { + const delta = targets[i] - sources[j]; + const abs = Math.abs(delta); + if (abs > tol) continue; + if (!best || abs < Math.abs(best.delta)) best = { delta, at: targets[i], axis }; + } + } + return best; + } + function snapMove(box, others) { + const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale()); + const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] }; + for (const o of others || []) { + if (!o || !isFinite(o.x) || !isFinite(o.y)) continue; + pushBox(targets, o); + } + const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w]; + const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h]; + const gx = nearest(targets.x, sourcesX, tol, "x"); + const gy = nearest(targets.y, sourcesY, tol, "y"); + const guides = []; + if (gx) guides.push(gx); + if (gy) guides.push(gy); + return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides }; + } + function drawGuides(ctx, guides) { + if (!guides || !guides.length || !ctx) return; + const scale = viewScale(); + const pad = S.overlayPad || 0; + ctx.save(); + ctx.strokeStyle = GUIDE_COLOR; + ctx.lineWidth = 1 / Math.max(0.02, scale); + ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)]); + for (const g of guides) { + ctx.beginPath(); + if (g.axis === "x") { + ctx.moveTo(g.at, -pad); + ctx.lineTo(g.at, S.imgH + pad); + } else { + ctx.moveTo(-pad, g.at); + ctx.lineTo(S.imgW + pad, g.at); + } + ctx.stroke(); + } + ctx.setLineDash([]); + ctx.restore(); + } + + // image-annotate/plugin/editor/objects.js + function textBounds(t) { + return textBox(t); + } + function getSelectedText() { + return S.textLayers.find((t) => t.id === S.selectedTextId) || null; + } + function hitTextLayer(pos) { + for (let i = S.textLayers.length - 1; i >= 0; i--) { + const t = S.textLayers[i]; + if (t.visible === false) continue; + const b = textBounds(t); + const rot = t.rotation || 0; + const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]; + if (lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 && lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2) { + return t; + } + } + return null; + } + function textHandlePoints(t) { + const b = textBounds(t); + const rot = t.rotation || 0; + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }; + const out = {}; + for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot); + return out; + } + function hitTextHandle(pos) { + const t = getSelectedText(); + if (!t) return null; + const b = textBounds(t); + const rot = t.rotation || 0; + const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]; + if (hitRotationHandle(lp, b)) return "rotate"; + const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }; + const R = 12 / viewScale(); + let best = null, bestDist = 1e9; + for (const name in local) { + const dx = lp[0] - local[name][0], dy = lp[1] - local[name][1]; + const d = dx * dx + dy * dy; + if (d < R * R && d < bestDist) { + bestDist = d; + best = name; + } + } + return best; + } + function shapeBounds(s) { + if (s.type === "pen" && s.pts && s.pts.length) { + const xs = s.pts.map((p) => p.x), ys = s.pts.map((p) => p.y), x = Math.min(...xs), y = Math.min(...ys); + return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y }; + } + return { x: Math.min(s.x1, s.x2), y: Math.min(s.y1, s.y2), w: Math.abs(s.x2 - s.x1), h: Math.abs(s.y2 - s.y1) }; + } + function getSelectedShape() { + return S.shapeLayers.find((s) => s.id === S.selectedShapeId) || null; + } + function distToSeg(px, py, x1, y1, x2, y2) { + const dx = x2 - x1, dy = y2 - y1; + const l2 = dx * dx + dy * dy; + let t = l2 ? ((px - x1) * dx + (py - y1) * dy) / l2 : 0; + t = clamp(t, 0, 1); + return Math.hypot(px - (x1 + t * dx), py - (y1 + t * dy)); + } + function hitShapeObj(pos, s, includeInterior) { + if (s.visible === false) return false; + if (s.rotation) { + const b = shapeBounds(s); + const lp = unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, s.rotation); + pos = { x: lp[0], y: lp[1] }; + } + if (s.type === "pen") { + const pts = s.pts || []; + for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i - 1].x, pts[i - 1].y, pts[i].x, pts[i].y) <= Math.max(8 / viewScale(), s.lw)) return true; + if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= Math.max(8 / viewScale(), s.lw)) return true; + if (!includeInterior) return false; + const b = shapeBounds(s); + return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h; + } + if (s.type === "circle") { + const b = shapeBounds(s); + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const rx = Math.max(0.5, b.w / 2), ry = Math.max(0.5, b.h / 2); + const nx = (pos.x - cx) / rx, ny = (pos.y - cy) / ry; + const value = nx * nx + ny * ny; + if (includeInterior || s.fill) return value <= 1; + const edgeTolerance = Math.max(4 / viewScale(), s.lw / Math.min(rx, ry)); + const outer = (1 + edgeTolerance) * (1 + edgeTolerance); + const inner = Math.max(0, 1 - edgeTolerance) * Math.max(0, 1 - edgeTolerance); + return value >= inner && value <= outer; + } + if (s.type === "rect") { + const b = shapeBounds(s); + const pad = Math.max(4, s.lw * 1.5); + const inOuter = pos.x >= b.x - pad && pos.x <= b.x + b.w + pad && pos.y >= b.y - pad && pos.y <= b.y + b.h + pad; + if (!inOuter) return false; + if (includeInterior || s.fill) return true; + const inInner = pos.x >= b.x + pad && pos.x <= b.x + b.w - pad && pos.y >= b.y + pad && pos.y <= b.y + b.h - pad; + return !inInner; + } + return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / viewScale(), s.lw); + } + function hitShapeLayer(pos, includeInterior) { + for (let i = S.shapeLayers.length - 1; i >= 0; i--) { + if (hitShapeObj(pos, S.shapeLayers[i], includeInterior)) return S.shapeLayers[i]; + } + return null; + } + function allObjects() { + const arr = S.textLayers.map((o) => ({ kind: "text", obj: o })).concat(S.shapeLayers.map((o) => ({ kind: "shape", obj: o }))); + arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0)); + return arr; + } + function sortLayersByZ() { + const cmp = (a, b) => (a.z || 0) - (b.z || 0); + S.textLayers.sort(cmp); + S.shapeLayers.sort(cmp); + } + function layerUnits() { + const arr = S.layers.map((obj) => ({ kind: "bitmap", obj })).concat(S.textLayers.map((obj) => ({ kind: "text", obj }))).concat(S.shapeLayers.map((obj) => ({ kind: "shape", obj }))); + arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0)); + return arr; + } + function layerUnitsDesc() { + return layerUnits().reverse(); + } + function assignLayerZ(units) { + units.forEach((u, i) => { + u.obj.z = i; + }); + S.zCounter = Math.max(S.zCounter, units.length - 1); + } + function selectUnit(kind, id) { + S.layerMulti.length = 0; + S.selectedLayerId = kind === "bitmap" ? id : null; + S.selectedTextId = kind === "text" ? id : null; + S.selectedShapeId = kind === "shape" ? id : null; + S.textDrag = null; + S.shapeDrag = null; + S.bitmapDrag = null; + renderOptionBar(); + } + function hitUnit(unit, pos) { + const { kind, obj } = unit; + if (!obj || obj.visible === false) return false; + if (kind === "bitmap") return obj.locked ? false : hitBitmapAt(obj, pos); + if (kind === "text") { + const b = textBounds(obj); + const rot = obj.rotation || 0; + const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]; + return lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 && lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2; + } + return hitShapeObj(pos, obj, true); + } + function hitTopmost(pos) { + for (const unit of layerUnitsDesc()) if (hitUnit(unit, pos)) return unit; + return null; + } + function otherObjectBoxes(exclude) { + const out = []; + for (const unit of layerUnits()) { + const o = unit.obj; + if (!o || o === exclude || o.id === "base" || o.visible === false) continue; + if (unit.kind === "bitmap") { + if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h }); + } else if (unit.kind === "text") { + out.push(textBox(o)); + } else { + out.push(shapeBounds(o)); + } + } + return out; + } + function hitAnyObject(pos) { + for (const unit of layerUnitsDesc()) { + if (unit.kind === "bitmap") continue; + if (hitUnit(unit, pos)) return unit; + } + return null; + } + function getSelectedObject() { + const t = getSelectedText(); + if (t) return { kind: "text", obj: t }; + const s = getSelectedShape(); + if (s) return { kind: "shape", obj: s }; + return null; + } + function moveLayer(dir) { + let sel = getSelectedObject(); + if (sel) { + if (sel.obj.locked) return; + } else { + const layer = S.layers.find((l) => l.id === S.selectedLayerId && l.id !== "base" && !l.locked); + if (layer) sel = { kind: "bitmap", obj: layer }; + } + if (!sel) { + toast("先在画布或图层面板选中要调整的元素", "info"); + return; + } + if (sel.obj.locked || sel.obj.id === "base") return; + const units = layerUnits(); + const from = units.findIndex((u) => u.obj === sel.obj); + if (from < 0) return; + const min = 0; + let to; + if (dir === "up") to = Math.min(from + 1, units.length - 1); + else if (dir === "down") to = Math.max(from - 1, min); + else if (dir === "top") to = units.length - 1; + else if (dir === "bottom") to = min; + else return; + if (to === from) return; + saveSnapshot(); + const [moved] = units.splice(from, 1); + units.splice(to, 0, moved); + assignLayerZ(units); + sortLayersByZ(); + reorderLayerCanvas(); + renderObjects(); + renderLayerPanel(); + } + function selectNeighborLayer(up) { + const units = layerUnits(); + if (!units.length) return; + const sel = getSelectedObject(); + let cur = -1; + if (sel) cur = units.findIndex((u2) => u2.obj === sel.obj); + else if (S.selectedLayerId) cur = units.findIndex((u2) => u2.kind === "bitmap" && u2.obj.id === S.selectedLayerId); + const idx = cur < 0 ? up ? units.length - 1 : 0 : up ? Math.min(cur + 1, units.length - 1) : Math.max(cur - 1, 0); + const u = units[idx]; + if (!u) return; + selectUnit(u.kind, u.obj.id); + renderLayerPanel(); + } + function shapeHandlePoints(s) { + const b = shapeBounds(s); + if (s.type === "pen") { + return Object.fromEntries((s.pts || []).map((p, i) => ["p" + i, [p.x, p.y]])); + } + if (s.type === "arrow") { + return { start: [s.x1, s.y1], end: [s.x2, s.y2] }; + } + return { + nw: [b.x, b.y], + ne: [b.x + b.w, b.y], + sw: [b.x, b.y + b.h], + se: [b.x + b.w, b.y + b.h], + n: [b.x + b.w / 2, b.y], + s: [b.x + b.w / 2, b.y + b.h], + e: [b.x + b.w, b.y + b.h / 2], + w: [b.x, b.y + b.h / 2] + }; + } + function shapeHandleWorld(s) { + const b = shapeBounds(s); + const rot = s.rotation || 0; + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const local = shapeHandlePoints(s); + const out = {}; + for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot); + return out; + } + function hitShapeHandle(pos) { + const s = getSelectedShape(); + if (!s) return null; + const b = shapeBounds(s); + const rot = s.rotation || 0; + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const lp = rot ? unrotPt(pos.x, pos.y, cx, cy, rot) : [pos.x, pos.y]; + if (hitRotationHandle(lp, b)) return "rotate"; + const pts = shapeHandlePoints(s); + const offset = 8 / viewScale(); + const R = 14 / viewScale(); + let best = null, bestDist = 1e9; + for (const name in pts) { + const px = pts[name][0] + (name.includes("w") ? -offset : name.includes("e") ? offset : 0); + const py = pts[name][1] + (name.includes("n") ? -offset : name.includes("s") ? offset : 0); + const dx = lp[0] - px, dy = lp[1] - py; + const d = dx * dx + dy * dy; + if (d < R * R && d < bestDist) { + bestDist = d; + best = name; + } + } + return best; + } + function applyShapeHandle(s, handle, pos) { + const b0 = shapeBounds(s); + const rot0 = s.rotation || 0; + const c0x = b0.x + b0.w / 2, c0y = b0.y + b0.h / 2; + if (handle === "rotate") { + const st = S.shapeDrag && S.shapeDrag.start; + const baseRot = S.shapeDrag && S.shapeDrag.shape && (S.shapeDrag.shape.rotation || 0) || 0; + if (st) { + const a0 = Math.atan2(st.y - c0y, st.x - c0x); + const a1 = Math.atan2(pos.y - c0y, pos.x - c0x); + let deg = baseRot + (a1 - a0) * 180 / Math.PI; + if (S._shiftDown) deg = Math.round(deg / 15) * 15; + s.rotation = deg; + } + return; + } + const lp = rot0 ? unrotPt(pos.x, pos.y, c0x, c0y, rot0) : [pos.x, pos.y]; + pos = { x: lp[0], y: lp[1] }; + if (s.type === "pen" && handle && handle[0] === "p") { + const i = parseInt(handle.slice(1), 10); + if (s.pts && s.pts[i]) { + s.pts[i].x = clamp(pos.x, 0, S.imgW); + s.pts[i].y = clamp(pos.y, 0, S.imgH); + } + return; + } + if (s.type === "arrow") { + if (handle === "start") { + s.x1 = clamp(pos.x, 0, S.imgW); + s.y1 = clamp(pos.y, 0, S.imgH); + } else { + s.x2 = clamp(pos.x, 0, S.imgW); + s.y2 = clamp(pos.y, 0, S.imgH); + } + return; + } + const b = shapeBounds(s); + const offset = 8 / viewScale(); + const adjusted = { x: pos.x - (handle.includes("w") ? -offset : handle.includes("e") ? offset : 0), y: pos.y - (handle.includes("n") ? -offset : handle.includes("s") ? offset : 0) }; + let x1 = b.x, y1 = b.y, x2 = b.x + b.w, y2 = b.y + b.h; + if (handle.includes("e")) x2 = Math.max(x1 + 2, adjusted.x); + if (handle.includes("s")) y2 = Math.max(y1 + 2, adjusted.y); + if (handle.includes("w")) x1 = Math.min(x2 - 2, adjusted.x); + if (handle.includes("n")) y1 = Math.min(y2 - 2, adjusted.y); + s.x1 = x1; + s.y1 = y1; + s.x2 = x2; + s.y2 = y2; + } + function drawPenPathPreview() { + const path = S.penPath; + if (!path || !path.pts || !path.pts.length) return; + const ctx = S.overlayCtx; + const pts = path.pts.slice(); + const first = pts[0]; + const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5); + if (path.preview) pts.push(nearStart ? first : path.preview); + ctx.save(); + ctx.strokeStyle = S.color; + ctx.fillStyle = nearStart ? "rgba(232, 167, 53, 0.18)" : "transparent"; + ctx.lineWidth = Math.max(1, S.shapeLineWidth); + ctx.setLineDash([8 / viewScale(), 5 / viewScale()]); + ctx.beginPath(); + ctx.moveTo(pts[0].x, pts[0].y); + for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y); + if (nearStart) { + ctx.closePath(); + ctx.fill(); + } + ctx.stroke(); + ctx.setLineDash([]); + for (let i = 0; i < path.pts.length; i++) { + const point = path.pts[i]; + ctx.beginPath(); + ctx.fillStyle = i === 0 && nearStart ? "#e8a735" : "#ffffff"; + ctx.strokeStyle = S.color; + ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2); + ctx.fill(); + ctx.stroke(); + } + ctx.restore(); + } + function drawShapeSelection(s) { + const octx = S.overlayCtx; + const b = shapeBounds(s); + const rot = s.rotation || 0; + octx.save(); + octx.strokeStyle = "#e8a735"; + octx.lineWidth = 1.5 / viewScale(); + const corners = boxCorners(b.x, b.y, b.w, b.h, rot); + octx.beginPath(); + octx.moveTo(corners[0][0], corners[0][1]); + for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1]); + octx.closePath(); + octx.stroke(); + const hs = 5.5 / viewScale(); + octx.fillStyle = "#ffffff"; + octx.strokeStyle = "#e8a735"; + const pts = shapeHandleWorld(s); + for (const name in pts) { + octx.beginPath(); + octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2); + octx.fill(); + octx.stroke(); + } + octx.restore(); + drawRotationHandles(octx, b, rot); + } + function deleteSelectedShape() { + if (!S.selectedShapeId) return; + const selected = getSelectedShape(); + if (selected && selected.locked) return; + saveSnapshot(); + removeVecCanvas(selected); + S.shapeLayers = S.shapeLayers.filter((s) => s.id !== S.selectedShapeId); + S.selectedShapeId = null; + renderObjects(); + } + function renderObjects(tempShape) { + for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj); + reorderLayerCanvas(); + clearOverlay(); + drawGuides(S.overlayCtx, S.guides); + if (tempShape) drawShape(S.overlayCtx, tempShape); + if (S.tool === "pen" && S.penPath && S.penPath.pts.length) drawPenPathPreview(); + if (S.placingImage) { + drawPlacementPreview(); + return; + } + const bitmapSelection = S.layers.find((l) => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l))); + if (bitmapSelection) drawBitmapSelection(bitmapSelection); + const sel = getSelectedText(); + if (sel) { + const b = textBounds(sel); + const rot = sel.rotation || 0; + const octx = S.overlayCtx; + octx.save(); + octx.strokeStyle = "#e8a735"; + octx.lineWidth = 1.5 / viewScale(); + const corners = boxCorners(b.x - 2 / viewScale(), b.y - 2 / viewScale(), b.w + 4 / viewScale(), b.h + 4 / viewScale(), rot); + octx.beginPath(); + octx.moveTo(corners[0][0], corners[0][1]); + for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1]); + octx.closePath(); + octx.stroke(); + const hs = 5.5 / viewScale(); + octx.fillStyle = "#ffffff"; + octx.strokeStyle = "#e8a735"; + const pts = textHandlePoints(sel); + for (const name in pts) { + octx.beginPath(); + octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2); + octx.fill(); + octx.stroke(); + } + octx.restore(); + } else { + const sh = getSelectedShape(); + if (sh) drawShapeSelection(sh); + } + const penShape = getPenEditingShape(); + if (penShape) drawPenEditOverlay(penShape); + if (S.cropRect) drawCropPreview(); + } + function getPenEditingShape() { + if (!S.penEditId) return null; + return S.shapeLayers.find((sh) => sh.id === S.penEditId && sh.type === "pen") || null; + } + function beginPenEdit(shape) { + S.penEditId = shape.id; + S.selectedShapeId = shape.id; + S.selectedTextId = null; + S.selectedLayerId = null; + S.shapeDrag = null; + S.penDragPt = -1; + S.penDragBase = null; + S.penDragPending = null; + renderObjects(); + renderLayerPanel(); + } + function exitPenEdit() { + S.penEditId = null; + S.penDragPt = -1; + S.penDragBase = null; + S.penDragPending = null; + renderObjects(); + renderLayerPanel(); + } + function hitPenPoint(pos, shape, r) { + const pts = shape.pts || []; + const b = shapeBounds(shape); + const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]; + for (let i = 0; i < pts.length; i++) { + if (Math.hypot(lp[0] - pts[i].x, lp[1] - pts[i].y) <= r) return i; + } + return -1; + } + function hitPenEdgeInsert(pos, shape) { + const pts = shape.pts || []; + const b = shapeBounds(shape); + const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]; + const r = 12 / viewScale(); + for (let i = 0; i < pts.length - 1; i++) { + if (distToSeg(lp[0], lp[1], pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y) <= r) return i; + } + if (shape.closed && pts.length >= 3) { + if (distToSeg(lp[0], lp[1], pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= r) return pts.length - 1; + } + return -1; + } + function drawPenEditOverlay(shape) { + const ctx = S.overlayCtx; + const pts = shape.pts || []; + const b = shapeBounds(shape); + const rot = shape.rotation || 0; + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const W = (p) => rotPt(p.x, p.y, cx, cy, rot); + const R = 7 / viewScale(); + ctx.save(); + ctx.lineWidth = 1.5 / viewScale(); + const segments = []; + for (let i = 0; i < pts.length - 1; i++) segments.push([pts[i], pts[i + 1]]); + if (shape.closed && pts.length >= 3) segments.push([pts[pts.length - 1], pts[0]]); + ctx.strokeStyle = "#e8a735"; + for (const [a, bb] of segments) { + const wa = W(a), wb = W(bb); + const mx = (wa[0] + wb[0]) / 2, my = (wa[1] + wb[1]) / 2; + ctx.beginPath(); + ctx.arc(mx, my, 3 / viewScale(), 0, Math.PI * 2); + ctx.stroke(); + } + for (let i = 0; i < pts.length; i++) { + const wp = W(pts[i]); + ctx.beginPath(); + ctx.rect(wp[0] - R / 2, wp[1] - R / 2, R, R); + ctx.fillStyle = "#ffffff"; + ctx.strokeStyle = i === S.penDragPt ? "#ff8c00" : "#e8a735"; + ctx.fill(); + ctx.stroke(); + } + ctx.restore(); + } + function showTextInput(x, y, layer) { + const input = runtime.el.querySelector(".iwb-editor-text-input"); + const wrapRect = S.canvasWrap.getBoundingClientRect(); + const box = (S.textCanvas || S.canvasStack).getBoundingClientRect(); + const sx = S.imgW ? box.width / S.imgW : 1; + const sy = S.imgH ? box.height / S.imgH : 1; + const INSET_X = 10; + const INSET_Y = 6; + input.style.left = box.left - wrapRect.left + x * sx - INSET_X + "px"; + input.style.top = box.top - wrapRect.top + y * sy - INSET_Y + "px"; + input.style.display = "block"; + if (layer) { + input.value = layer.text; + S.textEditingId = layer.id; + } else { + input.value = ""; + S.textEditingId = null; + } + const styleSrc = layer || { fontFamily: S.textFamily, fontWeight: S.textWeight }; + input.style.fontFamily = fontStackOf(styleSrc); + input.style.fontWeight = weightOf(styleSrc); + input.focus(); + input.select(); + input.dataset.x = x; + input.dataset.y = y; + input.style.height = "auto"; + input.style.height = Math.max(30, input.scrollHeight + 4) + "px"; + } + function hideTextInput() { + const input = runtime.el.querySelector(".iwb-editor-text-input"); + if (input) { + if (document.activeElement === input) input.blur(); + input.style.display = "none"; + input.value = ""; + } + S.textEditingId = null; + } + function commitTextInput() { + const input = runtime.el.querySelector(".iwb-editor-text-input"); + if (!input || input.style.display === "none") return false; + const text = input.value.trim(); + const x = parseFloat(input.dataset.x); + const y = parseFloat(input.dataset.y); + let committed = false; + if (S.textEditingId) { + const t = S.textLayers.find((l) => l.id === S.textEditingId); + if (t && t.locked) { + hideTextInput(); + return true; + } + if (t && text !== t.text) { + saveSnapshot(); + if (text) { + t.text = text; + } else { + removeVecCanvas(t); + S.textLayers = S.textLayers.filter((l) => l.id !== t.id); + S.selectedTextId = null; + } + renderObjects(); + } + committed = true; + } else if (text) { + saveSnapshot(); + const layer = { + id: "t" + Date.now() + Math.floor(Math.random() * 1e3), + x, + y, + text, + color: S.color, + fontSize: Math.max(8, S.textSize), + // 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值 + ...newTextStyle({ + fontWeight: S.textWeight, + fontFamily: S.textFamily, + align: S.textAlign, + lineHeight: S.textLineHeight, + strokeWidth: S.textStrokeWidth, + strokeColor: S.textStrokeColor, + bgFill: S.textBgFill, + bgColor: S.textBgColor + }), + opacity: 1, + visible: true, + locked: false, + z: ++S.zCounter + }; + S.textLayers.push(layer); + selectUnit("text", layer.id); + renderObjects(); + committed = true; + } + hideTextInput(); + if (committed) { + const id = S.selectedTextId; + queueMicrotask(() => { + if (S.tool !== "text") return; + const box = runtime.el && runtime.el.querySelector(".iwb-editor-text-input"); + if (box && box.style.display !== "none") return; + setTool("select"); + if (!id) return; + selectUnit("text", id); + renderObjects(); + renderLayerPanel(); + }); + } + return committed; + } + function deleteSelectedText() { + if (!S.selectedTextId) return; + const selected = getSelectedText(); + if (selected && selected.locked) return; + saveSnapshot(); + removeVecCanvas(selected); + S.textLayers = S.textLayers.filter((t) => t.id !== S.selectedTextId); + S.selectedTextId = null; + renderObjects(); + } + function beginTextRotate(pos) { + const t = getSelectedText(); + if (!t || t.locked) return; + const b = textBounds(t); + S.textDrag = { + mode: "rotate", + rotation: t.rotation || 0, + cx: b.x + b.w / 2, + cy: b.y + b.h / 2, + startX0: pos.x, + startY0: pos.y, + pending: snapshotState() + }; + } + function beginTextScaleDrag(handle, pos) { + const t = getSelectedText(); + if (!t || t.locked) return; + const b = textBounds(t); + const rot = t.rotation || 0; + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const anchors = { + se: [b.x, b.y], + ne: [b.x, b.y + b.h], + sw: [b.x + b.w, b.y], + nw: [b.x + b.w, b.y + b.h] + }; + const a = rotPt(anchors[handle][0], anchors[handle][1], cx, cy, rot); + const anchor = { x: a[0], y: a[1] }; + const dx = pos.x - anchor.x, dy = pos.y - anchor.y; + S.textDrag = { + mode: "scale", + anchor, + d0: Math.sqrt(dx * dx + dy * dy), + fontSize: t.fontSize, + pending: snapshotState() + }; + } + function beginShapeHandleDrag(handle, pos) { + const sh = getSelectedShape(); + if (!sh || sh.locked) return; + S.shapeDrag = { + mode: "handle", + handle, + start: pos, + shape: { ...sh }, + pending: snapshotState() + }; + } + + // image-annotate/plugin/editor/layers.js + function createLayerCanvas() { + const c = document.createElement("canvas"); + c.className = "iwb-editor-layer-canvas"; + c.width = S.imgW; + c.height = S.imgH; + c.style.position = "absolute"; + c.style.top = "0"; + c.style.left = "0"; + c.style.display = "block"; + S.canvasStack.insertBefore(c, S.strokeCanvas); + return c; + } + function reorderLayerCanvas() { + for (const u of layerUnits()) { + const el = u.kind === "bitmap" ? u.obj.canvas : u.obj._canvas; + if (!el || el.nodeType !== 1) continue; + S.canvasStack.insertBefore(el, S.strokeCanvas); + el.style.display = u.obj.visible === false ? "none" : "block"; + } + } + function getActiveLayer() { + return S.layers.find((l) => l.id === S.activeLayerId) || null; + } + function getActiveCtx() { + const layer = getActiveLayer(); + return layer && !layer.locked ? layer.ctx : null; + } + function clearSelection({ keepBitmap = false } = {}) { + if (!keepBitmap) S.selectedLayerId = null; + S.selectedTextId = null; + S.selectedShapeId = null; + S.textDrag = null; + S.shapeDrag = null; + S.bitmapDrag = null; + } + function resolveSourceBox(layer) { + if (layer._srcBox && layer.sourceCanvas) { + const b = layer._srcBox; + return { src: layer.sourceCanvas, box: b }; + } + if (layer.image && layer.w > 0 && layer.h > 0) return { src: layer.image, box: null }; + if (layer.sourceCanvas && layer.w > 0 && layer.h > 0) return { src: layer.sourceCanvas, box: null }; + return null; + } + function paintTransformed(layer, source) { + const rot = layer.rotation || 0; + const cx = layer.x + layer.w / 2, cy = layer.y + layer.h / 2; + layer.ctx.save(); + if (rot) { + layer.ctx.translate(cx, cy); + layer.ctx.rotate(rot * Math.PI / 180); + layer.ctx.translate(-cx, -cy); + } + if (source) { + if (source.box) { + const b = source.box; + layer.ctx.drawImage(source.src, b.x, b.y, b.w, b.h, layer.x, layer.y, layer.w, layer.h); + } else { + layer.ctx.drawImage(source.src, layer.x, layer.y, layer.w, layer.h); + } + } + layer.ctx.restore(); + } + function redrawBitmapLayer(layer) { + if (!layer || !layer.ctx) return; + layer.ctx.clearRect(0, 0, S.imgW, S.imgH); + paintTransformed(layer, resolveSourceBox(layer)); + } + function hitBitmapHandle(pos) { + const layer = S.layers.find((l) => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l))); + if (!layer || layer.visible === false) return null; + const box = layerFrame(layer); + if (!(box.w > 0 && box.h > 0)) return null; + const rot = layer.rotation || 0; + const cx = box.x + box.w / 2, cy = box.y + box.h / 2; + const lp = unrotPt(pos.x, pos.y, cx, cy, rot); + const R = 14 / viewScale(); + if (hitRotationHandle(lp, box)) return "rotate"; + const points = { + nw: [box.x, box.y], + ne: [box.x + box.w, box.y], + sw: [box.x, box.y + box.h], + se: [box.x + box.w, box.y + box.h], + n: [box.x + box.w / 2, box.y], + s: [box.x + box.w / 2, box.y + box.h], + e: [box.x + box.w, box.y + box.h / 2], + w: [box.x, box.y + box.h / 2] + }; + let hit = null, best = Infinity; + for (const name in points) { + const distance = Math.hypot(lp[0] - points[name][0], lp[1] - points[name][1]); + if (distance < R && distance < best) { + best = distance; + hit = name; + } + } + return hit; + } + function layerBounds(layer) { + if (!layer || !layer.ctx || !layer.canvas) return null; + if (layer._bounds !== void 0) return layer._bounds; + let b = null; + try { + const w = layer.canvas.width, h = layer.canvas.height; + const data = layer.ctx.getImageData(0, 0, w, h).data; + let minX = w, minY = h, maxX = -1, maxY = -1; + for (let y = 0; y < h; y += 2) { + for (let x = 0; x < w; x += 2) { + if (data[(y * w + x) * 4 + 3] > 8) { + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } + } + } + if (maxX >= 0) b = { x: minX, y: minY, w: maxX - minX + 2, h: maxY - minY + 2 }; + } catch (e) { + b = null; + } + layer._bounds = b; + return b; + } + function layerFrame(layer) { + if (isDrawableLayer(layer) && !layer._srcBox) { + const b = layerBounds(layer); + if (b) return b; + } + return { x: layer.x, y: layer.y, w: layer.w, h: layer.h }; + } + function hitBitmapAt(layer, pos) { + if (!layer || layer.visible === false || layer.locked) return false; + const drawable = isDrawableLayer(layer); + if (!drawable && !layer.transformable) return false; + if (!(layer.w > 0 && layer.h > 0)) return false; + const rot = layer.rotation || 0; + const lp = rot ? unrotPt(pos.x, pos.y, layer.x + layer.w / 2, layer.y + layer.h / 2, rot) : [pos.x, pos.y]; + if (lp[0] < layer.x || lp[0] > layer.x + layer.w || lp[1] < layer.y || lp[1] > layer.y + layer.h) return false; + if (!drawable) return true; + const px = Math.round(lp[0]), py = Math.round(lp[1]); + if (px < 0 || py < 0 || px >= layer.canvas.width || py >= layer.canvas.height) return false; + try { + return layer.ctx.getImageData(px, py, 1, 1).data[3] > 8; + } catch (e) { + return true; + } + } + function drawBitmapSelection(layer) { + if (!layer) return; + if (S.tool !== "select") return; + const drawable = isDrawableLayer(layer); + if (!layer.transformable && !drawable) return; + const box = layerFrame(layer); + if (!(box.w > 0 && box.h > 0)) return; + const ctx = S.overlayCtx; + const rot = layer.rotation || 0; + const hs = 5.5 / viewScale(); + ctx.save(); + ctx.strokeStyle = "#e8a735"; + ctx.lineWidth = 1.5 / viewScale(); + const corners = boxCorners(box.x, box.y, box.w, box.h, rot); + ctx.beginPath(); + ctx.moveTo(corners[0][0], corners[0][1]); + for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1]); + ctx.closePath(); + ctx.stroke(); + ctx.fillStyle = "#fff"; + ctx.strokeStyle = "#e8a735"; + const pts = frameHandlePoints(box, rot); + for (const name in pts) { + ctx.beginPath(); + ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2); + ctx.fill(); + ctx.stroke(); + } + ctx.restore(); + drawRotationHandles(ctx, box, rot); + } + function frameHandlePoints(box, rot) { + const cx = box.x + box.w / 2, cy = box.y + box.h / 2; + const local = { + nw: [box.x, box.y], + ne: [box.x + box.w, box.y], + sw: [box.x, box.y + box.h], + se: [box.x + box.w, box.y + box.h], + n: [box.x + box.w / 2, box.y], + s: [box.x + box.w / 2, box.y + box.h], + e: [box.x + box.w, box.y + box.h / 2], + w: [box.x, box.y + box.h / 2] + }; + const out = {}; + for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot || 0); + return out; + } + function beginBitmapDrag(handle, pos) { + const layer = S.layers.find((l) => l.id === S.selectedLayerId); + if (!layer || layer.locked) return; + const drawable = isDrawableLayer(layer); + if (!layer.transformable && !drawable) return; + if (drawable) { + if (!layer.sourceCanvas) { + const sc = document.createElement("canvas"); + sc.width = S.imgW; + sc.height = S.imgH; + sc.getContext("2d").drawImage(layer.canvas, 0, 0); + layer.sourceCanvas = sc; + } + if (!layer._srcBox) { + const b = layerBounds(layer) || { x: layer.x, y: layer.y, w: layer.w, h: layer.h }; + layer._srcBox = { x: b.x, y: b.y, w: b.w, h: b.h }; + layer.x = b.x; + layer.y = b.y; + layer.w = b.w; + layer.h = b.h; + layer.rotation = layer.rotation || 0; + } + } + const frame = layerFrame(layer); + S.bitmapDrag = { + mode: handle === "rotate" ? "rotate" : handle ? "scale" : "move", + handle, + start: pos, + drawable: isDrawableLayer(layer), + layer: { x: layer.x, y: layer.y, w: layer.w, h: layer.h, rotation: layer.rotation || 0 }, + frame: { x: frame.x, y: frame.y, w: frame.w, h: frame.h }, + pending: snapshotState() + }; + } + function applyBitmapDrag(pos) { + const drag = S.bitmapDrag; + const layer = S.layers.find((l) => l.id === S.selectedLayerId); + if (!drag || !layer) return; + const base = drag.layer; + if (drag.mode === "move") { + let nx = base.x + pos.x - drag.start.x; + let ny = base.y + pos.y - drag.start.y; + if (!S._altDown && base.w > 0 && base.h > 0) { + const s = snapMove({ x: nx, y: ny, w: base.w, h: base.h }, otherObjectBoxes(layer)); + nx += s.dx; + ny += s.dy; + S.guides = s.guides.length ? s.guides : null; + } else { + S.guides = null; + } + layer.x = nx; + layer.y = ny; + if (isDrawableLayer(layer)) layer._bounds = void 0; + } else if (drag.mode === "rotate") { + const rcx = base.x + base.w / 2, rcy = base.y + base.h / 2; + const a0 = Math.atan2(drag.start.y - rcy, drag.start.x - rcx); + const a1 = Math.atan2(pos.y - rcy, pos.x - rcx); + let deg = (base.rotation || 0) + (a1 - a0) * 180 / Math.PI; + if (S._shiftDown) deg = Math.round(deg / 15) * 15; + layer.rotation = deg; + } else { + const lpos = unrotPt(pos.x, pos.y, base.x + base.w / 2, base.y + base.h / 2, base.rotation || 0); + let x = base.x, y = base.y, w = base.w, h = base.h; + const min = 4; + if (drag.handle.includes("e")) w = Math.max(min, lpos[0] - base.x); + if (drag.handle.includes("s")) h = Math.max(min, lpos[1] - base.y); + if (drag.handle.includes("w")) { + x = Math.min(lpos[0], base.x + base.w - min); + w = base.x + base.w - x; + } + if (drag.handle.includes("n")) { + y = Math.min(lpos[1], base.y + base.h - min); + h = base.y + base.h - y; + } + if (S._shiftDown && layer.image) { + const iw = layer.image.naturalWidth || layer.image.width; + const ih = layer.image.naturalHeight || layer.image.height; + const aspect = iw / Math.max(1, ih); + if (w / h > aspect) h = w / aspect; + else w = h * aspect; + if (drag.handle.includes("w")) x = base.x + base.w - w; + if (drag.handle.includes("n")) y = base.y + base.h - h; + } + layer.x = x; + layer.y = y; + layer.w = w; + layer.h = h; + } + if (isDrawableLayer(layer)) layer._bounds = void 0; + redrawBitmapLayer(layer); + } + function setActiveLayer(id) { + const changed = S.activeLayerId !== id || S.selectedLayerId !== id; + S.activeLayerId = id; + selectUnit("bitmap", id); + if (!changed) return; + renderLayerPanel(); + renderObjects(); + if (S.renderFxPanel) S.renderFxPanel(); + if (S.renderAdjustPanel) S.renderAdjustPanel(); + } + function addBitmapLayer(img) { + placeImageDirectly(img); + } + function ensureWritableLayer() { + const current = getActiveLayer(); + if (current && !current.locked) return current; + const id = S.layers.some((l) => l.id === "draw") ? "L" + Date.now() + Math.floor(Math.random() * 1e3) : "draw"; + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.clearRect(0, 0, S.imgW, S.imgH); + const layer = { + id, + name: "标注 " + (S.layers.filter((l) => l.id !== "base").length + 1), + canvas, + ctx, + opacity: 1, + visible: true, + locked: false, + x: 0, + y: 0, + w: S.imgW, + h: S.imgH, + rotation: 0, + z: ++S.zCounter + }; + S.layers.push(layer); + reorderLayerCanvas(); + updateLayerCanvasStyles(); + setActiveLayer(id); + renderLayerPanel(); + return layer; + } + function addBlankLayer() { + const id = "L" + Date.now() + Math.floor(Math.random() * 1e3); + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.clearRect(0, 0, S.imgW, S.imgH); + const layer = { + id, + name: "空白图层 " + (S.layers.length + 1), + canvas, + ctx, + opacity: 1, + visible: true, + locked: false, + x: 0, + y: 0, + w: S.imgW, + h: S.imgH, + rotation: 0, + z: ++S.zCounter + }; + saveSnapshot(); + S.layers.push(layer); + reorderLayerCanvas(); + setActiveLayer(id); + updateLayerCanvasStyles(); + renderLayerPanel(); + } + function deleteLayer(id) { + const idx = S.layers.findIndex((l) => l.id === id); + if (idx < 0) return; + if (S.layers.length <= 1) return; + const layer = S.layers[idx]; + if (layer.locked) return; + saveSnapshot(); + if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas); + S.layers.splice(idx, 1); + assignLayerZ(layerUnits()); + if (S.activeLayerId === id) S.activeLayerId = S.layers[S.layers.length - 1].id; + if (S.selectedLayerId === id) S.selectedLayerId = null; + reorderLayerCanvas(); + renderLayerPanel(); + } + function vecCanvasFor(obj) { + if (!obj._canvas || obj._canvas.nodeType !== 1 || !obj._canvas.parentNode) { + const c = document.createElement("canvas"); + c.className = "iwb-editor-vec-canvas"; + c.width = S.imgW; + c.height = S.imgH; + c.style.position = "absolute"; + c.style.top = "0"; + c.style.left = "0"; + c.style.display = "block"; + S.canvasStack.insertBefore(c, S.strokeCanvas); + if (S.imgW && S.fitW) { + const vw = Math.round(S.fitW * S.zoom); + const vh = Math.round(S.fitH * S.zoom); + const vs = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + const vo = Math.round((S.overlayPad || 0) * vs); + c.style.width = vw + "px"; + c.style.height = vh + "px"; + c.style.left = vo + "px"; + c.style.top = vo + "px"; + } + obj._canvas = c; + obj._ctx = c.getContext("2d"); + } + return obj; + } + function removeVecCanvas(obj) { + if (obj && obj._canvas && obj._canvas.nodeType === 1) { + if (obj._canvas.parentNode) obj._canvas.parentNode.removeChild(obj._canvas); + obj._canvas = null; + obj._ctx = null; + } + } + function purgeVectorCanvases() { + for (const t of S.textLayers) removeVecCanvas(t); + for (const sh of S.shapeLayers) removeVecCanvas(sh); + } + function drawVectorToCanvas(kind, obj) { + vecCanvasFor(obj); + const ctx = obj._ctx; + ctx.clearRect(0, 0, S.imgW, S.imgH); + if (kind === "shape") { + drawShape(ctx, obj); + } else { + drawTextObject(ctx, obj); + } + } + function toggleLayerVisibility(id) { + const layer = S.layers.find((l) => l.id === id); + if (!layer) return; + layer.visible = !layer.visible; + reorderLayerCanvas(); + renderLayerPanel(); + S.pickerComposite = null; + } + function updateLayerCanvasStyles() { + const w = Math.round(S.fitW * S.zoom); + const h = Math.round(S.fitH * S.zoom); + const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + const offset = Math.round((S.overlayPad || 0) * scale); + for (const layer of S.layers) { + layer.canvas.style.width = w + "px"; + layer.canvas.style.height = h + "px"; + layer.canvas.style.left = offset + "px"; + layer.canvas.style.top = offset + "px"; + layer.canvas.style.opacity = String(layer.opacity == null ? 1 : layer.opacity); + } + styleVectorViewport(w, h, offset); + } + function styleVectorViewport(w, h, offset) { + for (const { obj } of allObjects()) { + if (!obj._canvas) continue; + obj._canvas.style.width = w + "px"; + obj._canvas.style.height = h + "px"; + obj._canvas.style.left = offset + "px"; + obj._canvas.style.top = offset + "px"; + } + } + function esc(v) { + return String(v == null ? "" : v).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + } + function opacityPct(v) { + const n = v == null ? 1 : v; + return Math.max(0, Math.min(100, Math.round(n * 100))); + } + function findPanelTarget(type, id) { + if (type === "bitmap") return S.layers.find((l) => l.id === id) || null; + if (type === "text") return S.textLayers.find((t) => t.id === id) || null; + if (type === "shape") return S.shapeLayers.find((s) => s.id === id) || null; + return null; + } + function applyOpacityVisual(type, obj) { + if (type === "bitmap" && obj && obj.canvas) { + obj.canvas.style.opacity = String(obj.opacity == null ? 1 : obj.opacity); + return; + } + if (type === "text" || type === "shape") renderObjects(); + } + function renderLayerPanel() { + const list = runtime.el.querySelector(".iwb-editor-layer-list"); + if (!list) return; + if (S.layerMulti.length) { + const alive = new Set(layerUnits().map((u) => u.kind + ":" + u.obj.id)); + S.layerMulti = S.layerMulti.filter((r) => alive.has(r.type + ":" + r.id)); + } + const items = []; + const multiSet = new Set(S.layerMulti.map((x) => x.type + ":" + x.id)); + for (const { kind, obj } of layerUnitsDesc()) { + if (kind === "bitmap") { + items.push({ + id: obj.id, + type: "bitmap", + name: obj.name, + opacity: obj.opacity, + visible: obj.visible, + z: obj.z, + color: obj.color || S.color, + lineWidth: obj.lineWidth || S.brushSize, + // 高亮只代表「选中」;画笔作用目标独立用 ✎ 标记,避免两个图层同时亮 + active: obj.id === S.selectedLayerId, + multi: multiSet.has("bitmap:" + obj.id), + paintTarget: obj.id === S.activeLayerId, + locked: !!obj.locked, + canDelete: S.layers.length > 1 + }); + } else { + items.push({ + id: obj.id, + type: kind, + name: kind === "text" ? '"' + (obj.text || "").slice(0, 12) + '"' : obj.type === "rect" ? "矩形" : obj.type === "circle" ? "圆形" : obj.type === "pen" ? "钢笔形状" : "箭头", + opacity: obj.opacity != null ? obj.opacity : 1, + visible: obj.visible !== false, + z: obj.z || 0, + color: obj.color || S.color, + lineWidth: obj.lw || S.brushSize, + active: kind === "text" && obj.id === S.selectedTextId || kind === "shape" && obj.id === S.selectedShapeId, + multi: multiSet.has(kind + ":" + obj.id), + paintTarget: false, + locked: !!obj.locked, + canDelete: true + }); + } + } + let html = ""; + for (const item of items) { + const activeClass = item.active ? " active" : ""; + const multiClass = item.multi ? " multi" : ""; + const visClass = item.visible ? "" : " hidden"; + let typeIconSvg = ""; + if (item.type === "bitmap") { + typeIconSvg = ''; + } else if (item.type === "text") { + typeIconSvg = ''; + } else if (item.type === "rect") { + typeIconSvg = ''; + } else { + typeIconSvg = ''; + } + const visSvg = item.visible ? '' : ''; + const lockSvg = item.locked ? '' : ''; + const delSvg = ''; + const pct = opacityPct(item.opacity); + const canRename = item.type === "bitmap"; + const sortHint = item.id === "base" ? "原图(其他图层可以拖到它下面)" : "拖动调整叠放顺序"; + html += ` + + ${visSvg} + ${typeIconSvg} + ${esc(item.name)} + ${item.paintTarget ? '✎' : ""} + ${pct < 100 && !item.active ? `${pct}%` : ""} + ${lockSvg} + ${item.canDelete ? `${delSvg}` : ""} + + ${item.active ? ` + + ${pct}% + ` : ""} + `; + } + list.innerHTML = html; + scheduleThumbs(); + const fxTarget = runtime.el.querySelector(".iwb-editor-fx-target"); + if (fxTarget) { + const active = getActiveLayer(); + fxTarget.textContent = active ? active.name : "无图层"; + fxTarget.title = active ? "效果作用于当前位图图层:" + active.name + "(切换图层可改变目标)" : "当前没有可处理的位图图层"; + } + bindLayerPanelEvents(); + } + function planPanelOrder(descKeys) { + const units = layerUnits(); + const byKey = new Map(units.map((u) => [u.kind + ":" + u.obj.id, u])); + const ordered = []; + for (const key of descKeys.slice().reverse()) { + const u = byKey.get(key); + if (!u) continue; + byKey.delete(key); + ordered.push(u); + } + if (!ordered.length || byKey.size) return null; + const before = units.map((u) => u.obj.id).join("|"); + return { ordered, changed: before !== ordered.map((u) => u.obj.id).join("|") }; + } + function applyPanelOrder(descKeys) { + const plan = planPanelOrder(descKeys); + if (!plan || !plan.changed) { + renderLayerPanel(); + return false; + } + saveSnapshot("调整图层顺序"); + assignLayerZ(plan.ordered); + reorderLayerCanvas(); + sortLayersByZ(); + renderObjects(); + renderLayerPanel(); + return true; + } + var SORT_THRESHOLD = 4; + var _sortDrag = null; + function bindLayerDragSort(list) { + if (list._iwbSortBound) return; + list._iwbSortBound = true; + list.addEventListener("pointerdown", (e) => { + if (e.button !== 0 || _sortDrag) return; + const item = e.target.closest(".iwb-layer-item"); + if (!item || !list.contains(item)) return; + if (item.dataset.layerId === "base") return; + if (e.target.closest(".iwb-layer-op-row, input, button, .iwb-layer-name-input")) return; + _sortDrag = { + list, + item, + id: item.dataset.layerId, + type: item.dataset.layerType, + startY: e.clientY, + y: e.clientY, + pointerId: e.pointerId, + active: false + }; + document.addEventListener("pointermove", onSortMove, true); + document.addEventListener("pointerup", onSortEnd, true); + document.addEventListener("pointercancel", onSortCancel, true); + window.addEventListener("blur", onWindowBlur, true); + }); + } + function onSortMove(e) { + const d = _sortDrag; + if (!d) return; + if (e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return; + d.y = e.clientY; + if (!d.active) { + if (Math.abs(e.clientY - d.startY) < SORT_THRESHOLD) return; + const rect = d.item.getBoundingClientRect(); + d.grabY = e.clientY - rect.top; + d.active = true; + d.list.classList.add("sorting"); + d.item.classList.add("dragging"); + S.lastNameClick = null; + } + updateSortTarget(d); + } + function updateSortTarget(d) { + const list = d.list; + const lr = list.getBoundingClientRect(); + if (d.y < lr.top + 18) list.scrollTop -= 8; + else if (d.y > lr.bottom - 18) list.scrollTop += 8; + const rows = Array.from(list.querySelectorAll(".iwb-layer-item")); + const movable = rows.filter((el) => el !== d.item); + let anchor = null; + for (const el of movable) { + const r2 = el.getBoundingClientRect(); + if (d.y < r2.top + r2.height / 2) { + anchor = el; + break; + } + } + if (d.item.nextElementSibling !== anchor || d.item.parentNode !== list) { + if (anchor) list.insertBefore(d.item, anchor); + else list.appendChild(d.item); + } + d.item.style.transform = ""; + const r = d.item.getBoundingClientRect(); + const dy = Math.round(d.y - d.grabY - r.top); + d.item.style.transform = dy ? "translateY(" + dy + "px)" : ""; + } + function onSortEnd(e) { + const d = _sortDrag; + if (!d) return; + if (e && e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return; + cleanupSortDrag(); + if (!d.active) return; + const rows = Array.from(d.list.querySelectorAll(".iwb-layer-item")); + const keyOf = (el) => el.dataset.layerType + ":" + el.dataset.layerId; + const desc = rows.map(keyOf); + if (d.type === "bitmap") { + if (S.layers.some((l) => l.id === d.id)) S.selectedLayerId = d.id; + } else if (d.type === "text" || d.type === "shape") { + selectUnit(d.type, d.id); + } + applyPanelOrder(desc); + } + function onSortCancel(e) { + const d = _sortDrag; + if (!d) return; + if (e && e.pointerId != null && d.pointerId != null && e.pointerId !== d.pointerId) return; + const wasActive = d.active; + cleanupSortDrag(); + if (wasActive) renderLayerPanel(); + } + function onWindowBlur(e) { + if (e.target !== window && e.target !== document) return; + onSortCancel(null); + } + function cleanupSortDrag() { + const d = _sortDrag; + if (!d) return; + document.removeEventListener("pointermove", onSortMove, true); + document.removeEventListener("pointerup", onSortEnd, true); + document.removeEventListener("pointercancel", onSortCancel, true); + window.removeEventListener("blur", onWindowBlur, true); + _sortDrag = null; + d.list.classList.remove("sorting"); + d.item.classList.remove("dragging"); + d.item.style.transform = ""; + } + function bindLayerPanelEvents() { + const list = runtime.el.querySelector(".iwb-editor-layer-list"); + if (!list) return; + bindLayerItemEvents(list); + bindLayerDragSort(list); + bindLayerNameRename(list); + bindLayerOpacityInputs(list); + bindLayerVisButtons(list); + bindLayerLockButtons(list); + bindLayerDelButtons(list); + } + function bindLayerItemEvents(list) { + list.querySelectorAll(".iwb-layer-item").forEach((item) => { + item.addEventListener("mousedown", (e) => e.stopPropagation()); + item.addEventListener("click", (e) => { + if (e.target.closest(".iwb-layer-vis") || e.target.closest(".iwb-layer-lock") || e.target.closest(".iwb-layer-del")) return; + if (e.target.closest(".iwb-layer-opacity") || e.target.closest(".iwb-layer-name-input") || e.target.closest(".iwb-layer-op-row")) return; + const id = item.dataset.layerId; + const type = item.dataset.layerType; + if (e.metaKey || e.ctrlKey) { + e.preventDefault(); + toggleLayerMulti(type, id); + renderLayerPanel(); + return; + } + if (S.layerMulti.length) S.layerMulti.length = 0; + if (type === "bitmap") { + setActiveLayer(id); + } else if (type === "text" || type === "shape") { + selectUnit(type, id); + renderObjects(); + renderLayerPanel(); + } + }); + }); + } + function bindLayerNameRename(list) { + list.querySelectorAll(".iwb-layer-name.renamable").forEach((el) => { + el.addEventListener("mousedown", (e) => { + e.stopPropagation(); + const id = el.dataset.nameId; + const now = Date.now(); + const prev = S.lastNameClick; + if (prev && prev.id === id && now - prev.t < 400) { + S.lastNameClick = null; + beginRename(id); + return; + } + S.lastNameClick = { id, t: now }; + }); + }); + } + function beginRename(id) { + const list = runtime.el.querySelector(".iwb-editor-layer-list"); + const layer = S.layers.find((l) => l.id === id); + if (!list || !layer) return; + const item = list.querySelector('.iwb-layer-item[data-layer-id="' + id + '"]'); + const span = item && item.querySelector(".iwb-layer-name"); + if (!span || !span.parentNode) return; + const input = document.createElement("input"); + input.className = "iwb-layer-name-input"; + input.type = "text"; + input.value = layer.name; + input.maxLength = 40; + span.replaceWith(input); + let done = false; + const finish = (commit) => { + if (done) return; + done = true; + const next = input.value.trim(); + if (commit && next && next !== layer.name) { + saveSnapshot("重命名图层"); + layer.name = next; + } + renderLayerPanel(); + }; + input.addEventListener("mousedown", (e) => e.stopPropagation()); + input.addEventListener("click", (e) => e.stopPropagation()); + input.addEventListener("keydown", (e) => { + e.stopPropagation(); + if (e.key === "Enter") { + e.preventDefault(); + finish(true); + } else if (e.key === "Escape") { + e.preventDefault(); + finish(false); + } + }); + input.addEventListener("blur", () => finish(true)); + input.focus(); + input.select(); + } + function bindLayerOpacityInputs(list) { + list.querySelectorAll(".iwb-layer-opacity").forEach((input) => { + input.addEventListener("mousedown", (e) => e.stopPropagation()); + input.addEventListener("click", (e) => e.stopPropagation()); + input.addEventListener("dblclick", (e) => { + e.stopPropagation(); + input._opSnapTaken = false; + input.value = "100"; + applyOpacityFromInput(input); + input._opSnapTaken = false; + }); + input.addEventListener("input", (e) => { + e.stopPropagation(); + applyOpacityFromInput(input); + }); + const resetSnap = () => { + input._opSnapTaken = false; + }; + input.addEventListener("change", resetSnap); + input.addEventListener("pointerup", resetSnap); + input.addEventListener("pointercancel", resetSnap); + input.addEventListener("blur", resetSnap); + }); + } + function applyOpacityFromInput(input) { + const type = input.dataset.opType; + const obj = findPanelTarget(type, input.dataset.opId); + if (!obj) return; + const pct = clamp(parseInt(input.value, 10) || 0, 0, 100); + if (!input._opSnapTaken) { + input._opSnapTaken = true; + saveSnapshot("调整不透明度"); + } + obj.opacity = pct / 100; + applyOpacityVisual(type, obj); + S.pickerComposite = null; + const val = input.parentNode && input.parentNode.querySelector(".iwb-layer-op-val"); + if (val) val.textContent = pct + "%"; + } + var _thumbTimer = 0; + function scheduleThumbs() { + if (_thumbTimer) return; + _thumbTimer = setTimeout(() => { + _thumbTimer = 0; + paintThumbs(); + }, 90); + } + function paintThumbs() { + if (!runtime.el) return; + const list = runtime.el.querySelector(".iwb-editor-layer-list"); + if (!list) return; + list.querySelectorAll(".iwb-layer-thumb canvas").forEach((cv) => { + const type = cv.dataset.thumbType; + const obj = findPanelTarget(type, cv.dataset.thumbId); + const src = obj ? type === "bitmap" ? obj.canvas : obj._canvas : null; + const g = cv.getContext("2d"); + if (!g) return; + g.clearRect(0, 0, cv.width, cv.height); + if (!src || !src.width || !src.height) return; + const k = Math.min(cv.width / src.width, cv.height / src.height); + const dw = Math.max(1, Math.round(src.width * k)); + const dh = Math.max(1, Math.round(src.height * k)); + try { + g.imageSmoothingQuality = "high"; + g.drawImage(src, Math.round((cv.width - dw) / 2), Math.round((cv.height - dh) / 2), dw, dh); + } catch (e) { + } + }); + } + function bindLayerVisButtons(list) { + list.querySelectorAll(".iwb-layer-vis").forEach((btn) => { + btn.addEventListener("mousedown", (e) => e.stopPropagation()); + btn.addEventListener("click", (e) => { + e.stopPropagation(); + const id = btn.dataset.visId; + const type = btn.dataset.visType; + if (type === "bitmap") { + toggleLayerVisibility(id); + } else if (type === "text") { + const obj = S.textLayers.find((t) => t.id === id); + if (obj) { + obj.visible = obj.visible === false; + renderObjects(); + renderLayerPanel(); + S.pickerComposite = null; + } + } else if (type === "shape") { + const obj = S.shapeLayers.find((s) => s.id === id); + if (obj) { + obj.visible = obj.visible === false; + renderObjects(); + renderLayerPanel(); + S.pickerComposite = null; + } + } + }); + }); + } + function bindLayerLockButtons(list) { + list.querySelectorAll(".iwb-layer-lock").forEach((btn) => { + btn.addEventListener("mousedown", (e) => e.stopPropagation()); + btn.addEventListener("click", (e) => { + e.stopPropagation(); + const id = btn.dataset.lockId; + const type = btn.dataset.lockType; + const obj = type === "bitmap" ? S.layers.find((l) => l.id === id) : type === "text" ? S.textLayers.find((t) => t.id === id) : S.shapeLayers.find((s) => s.id === id); + if (!obj) return; + saveSnapshot(); + obj.locked = !obj.locked; + renderObjects(); + renderLayerPanel(); + }); + }); + } + function bindLayerDelButtons(list) { + list.querySelectorAll(".iwb-layer-del").forEach((btn) => { + btn.addEventListener("mousedown", (e) => e.stopPropagation()); + btn.addEventListener("click", (e) => { + e.stopPropagation(); + const id = btn.dataset.delId; + const type = btn.dataset.delType; + if (type === "bitmap") { + deleteLayer(id); + } else if (type === "text") { + S.selectedTextId = id; + deleteSelectedText(); + renderLayerPanel(); + } else if (type === "shape") { + S.selectedShapeId = id; + deleteSelectedShape(); + renderLayerPanel(); + } + }); + }); + } + var multiKey = (type, id) => type + ":" + id; + function currentUnitRef() { + if (S.selectedLayerId) return { type: "bitmap", id: S.selectedLayerId }; + if (S.selectedTextId) return { type: "text", id: S.selectedTextId }; + if (S.selectedShapeId) return { type: "shape", id: S.selectedShapeId }; + return null; + } + function toggleLayerMulti(type, id) { + const key = multiKey(type, id); + const i = S.layerMulti.findIndex((x) => multiKey(x.type, x.id) === key); + if (i >= 0) { + S.layerMulti.splice(i, 1); + return; + } + if (!S.layerMulti.length) { + const cur = currentUnitRef(); + if (cur && multiKey(cur.type, cur.id) !== key) S.layerMulti.push(cur); + } + S.layerMulti.push({ type, id }); + } + function composeUnitsInto(layer, units) { + const tmp = document.createElement("canvas"); + tmp.width = S.imgW; + tmp.height = S.imgH; + const tctx = tmp.getContext("2d"); + for (const u of units) { + const el = u.kind === "bitmap" ? u.obj.canvas : u.obj._canvas; + if (!el || el.nodeType !== 1) continue; + tctx.globalAlpha = u.kind === "bitmap" ? u.obj.opacity == null ? 1 : u.obj.opacity : 1; + tctx.drawImage(el, 0, 0); + } + tctx.globalAlpha = 1; + const ctx = layer.ctx; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "copy"; + ctx.filter = "none"; + ctx.drawImage(tmp, 0, 0); + ctx.restore(); + } + function dropUnit(u) { + if (u.kind === "bitmap") { + const i = S.layers.indexOf(u.obj); + if (i >= 0) S.layers.splice(i, 1); + try { + if (u.obj.canvas && u.obj.canvas.parentNode) u.obj.canvas.parentNode.removeChild(u.obj.canvas); + } catch (e) { + } + } else if (u.kind === "text") { + S.textLayers = S.textLayers.filter((t) => t !== u.obj); + removeVecCanvas(u.obj); + } else if (u.kind === "shape") { + S.shapeLayers = S.shapeLayers.filter((s) => s !== u.obj); + removeVecCanvas(u.obj); + } + } + function mergeUnits(units) { + const sorted = units.slice().sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0)); + const lowUnit = sorted[0]; + const baseUnit = sorted.find((u) => u.kind === "bitmap" && u.obj.id === "base"); + const all = layerUnits(); + const lowIdx = all.findIndex((u) => u.obj === lowUnit.obj); + const chosenSet = new Set(sorted.map((u) => u.obj)); + const insertAt = all.slice(0, Math.max(lowIdx, 0)).filter((u) => !chosenSet.has(u.obj)).length; + let carrier; + const baseZ = baseUnit ? baseUnit.obj.z || 0 : 0; + if (baseUnit) { + carrier = baseUnit.obj; + carrier.image = null; + carrier.sourceCanvas = null; + carrier._srcBox = null; + carrier.transformable = false; + carrier.x = 0; + carrier.y = 0; + carrier.w = S.imgW; + carrier.h = S.imgH; + carrier.rotation = 0; + carrier.visible = true; + carrier.opacity = 1; + carrier._bounds = void 0; + composeUnitsInto(carrier, sorted); + for (const u of sorted) if (u.obj !== carrier) dropUnit(u); + const rest = layerUnits().filter((u) => u.obj !== carrier); + const at = rest.filter((u) => (u.obj.z || 0) < baseZ).length; + rest.splice(Math.min(at, rest.length), 0, { kind: "bitmap", obj: carrier }); + assignLayerZ(rest); + } else { + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + carrier = { + id: "m" + Date.now() + Math.floor(Math.random() * 1e3), + name: lowUnit.obj.name || "合并图层", + canvas, + ctx, + opacity: 1, + visible: true, + locked: false, + x: 0, + y: 0, + w: S.imgW, + h: S.imgH, + rotation: 0, + z: lowUnit.obj.z || 0 + }; + composeUnitsInto(carrier, sorted); + for (const u of sorted) dropUnit(u); + S.layers.push(carrier); + const rest = layerUnits().filter((u) => u.obj !== carrier); + rest.splice(Math.min(insertAt, rest.length), 0, { kind: "bitmap", obj: carrier }); + assignLayerZ(rest); + } + S.activeLayerId = carrier.id; + S.selectedLayerId = carrier.id; + S.selectedTextId = null; + S.selectedShapeId = null; + S.textDrag = null; + S.shapeDrag = null; + S.bitmapDrag = null; + S.layerMulti.length = 0; + S.pickerComposite = null; + sortLayersByZ(); + reorderLayerCanvas(); + updateLayerCanvasStyles(); + renderObjects(); + renderLayerPanel(); + if (S.renderAll) S.renderAll(); + return carrier; + } + function mergeLayers() { + const units = layerUnits(); + if (units.length < 2) return { ok: false, msg: "只有一个图层,没有可合并的对象" }; + let chosen; + if (S.layerMulti.length >= 2) { + chosen = units.filter((u) => S.layerMulti.some((r) => r.type === u.kind && r.id === u.obj.id)); + if (chosen.length < 2) return { ok: false, msg: "先选两个以上图层(⌘/Ctrl 点击图层列表)" }; + } else { + const cur = currentUnitRef(); + const idx = cur ? units.findIndex((u) => u.kind === cur.type && u.obj.id === cur.id) : -1; + if (idx < 0) return { ok: false, msg: "先在图层列表里选中一层" }; + if (idx === 0) return { ok: false, msg: "已经是最底层,没有可合并的下一层" }; + chosen = [units[idx - 1], units[idx]]; + if (chosen[1].obj.visible === false) return { ok: false, msg: "当前层已隐藏,先显示再合并" }; + if (chosen[0].obj.visible === false) return { ok: false, msg: "下一层已隐藏,先显示再合并" }; + } + const visible = chosen.filter((u) => u.obj.visible !== false); + if (visible.length < 2) return { ok: false, msg: "可见图层不足 2 个,没有可合并的内容" }; + saveSnapshot("合并图层"); + mergeUnits(visible); + return { ok: true, msg: "已合并 " + visible.length + " 个图层 · Ctrl+Z 撤销" }; + } + function mergeVisibleLayers() { + const visible = layerUnits().filter((u) => u.obj.visible !== false); + if (visible.length < 2) return { ok: false, msg: "可见图层不足 2 个,没有可合并的对象" }; + saveSnapshot("合并可见图层"); + mergeUnits(visible); + return { ok: true, msg: "已合并 " + visible.length + " 个可见图层 · Ctrl+Z 撤销" }; + } + + // image-annotate/plugin/editor/selection.js + function hasSelection() { + return !!(S.selection && S.selection.active); + } + function selectionInfo() { + if (!hasSelection()) return null; + const b = S.selection.bbox; + return { kind: S.selection.kind, x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h), feather: S.selection.feather || 0, inverted: !!S.selection.inverted }; + } + function clearSelectionCanvas() { + const ctx = S.selectionCtx; + if (!ctx) return; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + ctx.restore(); + resetOverlayTransform(ctx); + } + function clearCursorCanvas() { + const ctx = S.cursorCtx; + if (!ctx) return; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + ctx.restore(); + resetOverlayTransform(ctx); + } + function renderSelection() { + if (!S.selectionCtx) return; + clearSelectionCanvas(); + const ctx = S.selectionCtx; + const k = 1 / Math.max(viewScale(), 1e-4); + if (S.marquee || S.lassoPts && S.lassoPts.length > 1) { + ctx.save(); + ctx.lineWidth = 1.5 * k; + ctx.strokeStyle = "#ffffff"; + ctx.setLineDash([5 * k, 4 * k]); + if (S.marquee) { + const b = marqueeBox(); + if (S.selectionKind === "ellipse") { + ctx.beginPath(); + ctx.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(1, b.w / 2), Math.max(1, b.h / 2), 0, 0, Math.PI * 2); + ctx.stroke(); + } else ctx.strokeRect(b.x, b.y, b.w, b.h); + } else { + ctx.beginPath(); + ctx.moveTo(S.lassoPts[0].x, S.lassoPts[0].y); + for (let i = 1; i < S.lassoPts.length; i++) ctx.lineTo(S.lassoPts[i].x, S.lassoPts[i].y); + ctx.closePath(); + ctx.stroke(); + } + ctx.restore(); + return; + } + if (!hasSelection()) return; + const p = S.selection.outlinePath || S.selection.path; + ctx.save(); + ctx.lineWidth = 1.4 * k; + ctx.setLineDash([5 * k, 5 * k]); + ctx.lineDashOffset = (S._antOffset || 0) * k; + ctx.strokeStyle = "rgba(0,0,0,0.85)"; + ctx.stroke(p); + ctx.lineDashOffset = ((S._antOffset || 0) + 5) * k; + ctx.strokeStyle = "rgba(255,255,255,0.95)"; + ctx.stroke(p); + ctx.restore(); + } + function syncAnts() { + if (hasSelection() && S.open) { + if (!S._antFrame) { + const tick = () => { + S._antOffset = ((S._antOffset || 0) + 0.55) % 10; + renderSelection(); + if (S.positionFloating) S.positionFloating(); + S._antFrame = requestAnimationFrame(tick); + }; + S._antFrame = requestAnimationFrame(tick); + } + } else if (S._antFrame) { + cancelAnimationFrame(S._antFrame); + S._antFrame = 0; + } + } + function rectFromPoints(x0, y0, x1, y1) { + const x = Math.min(x0, x1), y = Math.min(y0, y1); + return { x, y, w: Math.abs(x1 - x0), h: Math.abs(y1 - y0) }; + } + function pathForBox(b, kind) { + const p = new Path2D(); + if (kind === "ellipse") { + p.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(0.5, b.w / 2), Math.max(0.5, b.h / 2), 0, 0, Math.PI * 2); + } else p.rect(b.x, b.y, Math.max(0.5, b.w), Math.max(0.5, b.h)); + return p; + } + function pathForLasso(pts) { + const p = new Path2D(); + if (!pts.length) return p; + p.moveTo(pts[0].x, pts[0].y); + for (let i = 1; i < pts.length; i++) p.lineTo(pts[i].x, pts[i].y); + p.closePath(); + return p; + } + function bboxOfPoints(pts) { + let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; + for (const p of pts) { + if (p.x < minX) minX = p.x; + if (p.y < minY) minY = p.y; + if (p.x > maxX) maxX = p.x; + if (p.y > maxY) maxY = p.y; + } + return { x: minX, y: minY, w: Math.max(0, maxX - minX), h: Math.max(0, maxY - minY) }; + } + function applyPath(kind, outlinePath, bbox, opts) { + const o = opts || {}; + const feather = clamp(Number(S.selectionFeather) || 0, 0, 20); + const inverted = !!o.inverted; + const path = new Path2D(); + if (inverted) { + path.rect(0, 0, S.imgW, S.imgH); + path.addPath(outlinePath); + } else { + path.addPath(outlinePath); + } + S.selectedTextId = null; + S.selectedShapeId = null; + S.selection = { + kind, + path, + outlinePath, + bbox, + fillRule: inverted ? "evenodd" : "nonzero", + feather, + inverted, + active: true + }; + S.marquee = null; + S.lassoPts = null; + S.interaction = "idle"; + if (S.renderAll) S.renderAll(); + else renderSelection(); + toast(inverted ? "已反选" : "选区 " + Math.round(bbox.w) + "×" + Math.round(bbox.h), "info"); + } + function clearMarquee() { + S.selection = null; + S.marquee = null; + S.lassoPts = null; + S.interaction = "idle"; + renderSelection(); + syncAnts(); + if (S.renderAll) S.renderAll(); + } + function selectAll() { + const b = { x: 0, y: 0, w: S.imgW, h: S.imgH }; + applyPath("rect", pathForBox(b, "rect"), b); + } + function invertSelection() { + if (!hasSelection()) { + toast("先框出一个选区"); + return; + } + applyPath(S.selection.kind, S.selection.outlinePath, S.selection.bbox, { inverted: !S.selection.inverted }); + } + function marqueeBox() { + const m = S.marquee; + return rectFromPoints(m.x0, m.y0, m.x1, m.y1); + } + function beginMarquee(pos) { + S.selection = null; + S.marquee = { x0: pos.x, y0: pos.y, x1: pos.x, y1: pos.y }; + S.interaction = "marquee"; + S.isDrawing = true; + renderSelection(); + } + function updateMarquee(pos) { + if (!S.marquee) return; + S.marquee.x1 = pos.x; + S.marquee.y1 = pos.y; + renderSelection(); + } + function endMarquee() { + const m = S.marquee; + if (!m) return; + const b = marqueeBox(); + S.marquee = null; + S.isDrawing = false; + S.interaction = "idle"; + if (b.w > 3 && b.h > 3) { + applyPath(S.selectionKind, pathForBox(b, S.selectionKind), b); + } else { + clearMarquee(); + } + } + function beginLasso(pos) { + S.selection = null; + S.lassoPts = [{ x: pos.x, y: pos.y }]; + S.interaction = "lasso"; + S.isDrawing = true; + renderSelection(); + } + function updateLasso(pos) { + if (!S.lassoPts) return; + const last = S.lassoPts[S.lassoPts.length - 1]; + if (Math.hypot(pos.x - last.x, pos.y - last.y) < 2) return; + S.lassoPts.push({ x: pos.x, y: pos.y }); + renderSelection(); + } + function endLasso() { + const pts = S.lassoPts; + if (!pts) return; + S.lassoPts = null; + S.isDrawing = false; + S.interaction = "idle"; + if (pts.length > 2) { + const b = bboxOfPoints(pts); + if (b.w > 3 && b.h > 3) { + applyPath("lasso", pathForLasso(pts), b); + return; + } + } + clearMarquee(); + } + function maskExtent() { + const sel = S.selection; + const b = sel.inverted ? { x: 0, y: 0, w: S.imgW, h: S.imgH } : sel.bbox; + const x = Math.floor(b.x); + const y = Math.floor(b.y); + return { + x, + y, + w: Math.max(1, Math.ceil(b.x + b.w) - x), + h: Math.max(1, Math.ceil(b.y + b.h) - y) + }; + } + function buildMask() { + const sel = S.selection; + const feather = sel.feather || 0; + const pad = Math.ceil(feather * 2); + const e = maskExtent(); + const w = e.w + pad * 2; + const h = e.h + pad * 2; + const c = document.createElement("canvas"); + c.width = w; + c.height = h; + const cx = c.getContext("2d"); + cx.save(); + cx.translate(-e.x + pad, -e.y + pad); + if (feather > 0) cx.filter = "blur(" + feather + "px)"; + cx.fillStyle = "#ffffff"; + cx.fill(sel.path, sel.fillRule); + cx.restore(); + return { canvas: c, x: e.x - pad, y: e.y - pad, w, h }; + } + function writableLayer() { + const layer = getActiveLayer(); + if (!layer || layer.locked) { + toast(layer && layer.locked ? "当前图层已锁定,请先解锁" : "没有可用的图层", "warn"); + return null; + } + return layer; + } + function eraseOnActiveLayer() { + const layer = writableLayer(); + if (!layer) return false; + const mask = buildMask(); + layer.ctx.save(); + layer.ctx.globalCompositeOperation = "destination-out"; + layer.ctx.drawImage(mask.canvas, mask.x, mask.y); + layer.ctx.restore(); + layer._bounds = void 0; + S.pickerComposite = null; + mask.canvas.width = 0; + mask.canvas.height = 0; + return true; + } + function copyToLayer(cut) { + const layer = writableLayer(); + if (!layer) return false; + const mask = buildMask(); + const tile = document.createElement("canvas"); + tile.width = mask.w; + tile.height = mask.h; + const tctx = tile.getContext("2d"); + tctx.drawImage(layer.canvas, -mask.x, -mask.y); + tctx.globalCompositeOperation = "destination-in"; + tctx.drawImage(mask.canvas, 0, 0); + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.drawImage(tile, mask.x, mask.y); + const id = "S" + Date.now() + Math.floor(Math.random() * 1e3); + const fresh = { + id, + name: cut ? "剪切内容" : "选区副本", + canvas, + ctx, + opacity: 1, + visible: true, + locked: false, + transformable: true, + x: 0, + y: 0, + w: S.imgW, + h: S.imgH, + rotation: 0, + z: ++S.zCounter + }; + S.layers.push(fresh); + if (cut) eraseOnActiveLayer(); + reorderLayerCanvas(); + updateLayerCanvasStyles(); + setActiveLayer(id); + for (const l of S.layers) l._bounds = void 0; + tile.width = 0; + tile.height = 0; + mask.canvas.width = 0; + mask.canvas.height = 0; + S.pickerComposite = null; + return true; + } + function fillOnActiveLayer() { + const layer = ensureWritableLayer(); + if (!layer) return false; + const sel = S.selection; + layer.ctx.save(); + if (sel.feather > 0) layer.ctx.filter = "blur(" + sel.feather + "px)"; + layer.ctx.globalAlpha = S.brushOpacity; + layer.ctx.fillStyle = S.color; + layer.ctx.fill(sel.path, sel.fillRule); + layer.ctx.restore(); + layer._bounds = void 0; + S.pickerComposite = null; + return true; + } + var registered = false; + function registerSelectionCommands() { + if (registered) return; + registered = true; + defineCommand("sel.copy", { + label: "复制为新层", + enabled: hasSelection, + hint: "先框出一个选区", + run: () => { + if (copyToLayer(false)) toast("已复制到新图层", "success"); + } + }); + defineCommand("sel.cut", { + label: "剪切到新层", + enabled: hasSelection, + hint: "先框出一个选区", + run: () => { + if (copyToLayer(true)) toast("已剪切到新图层", "success"); + } + }); + defineCommand("sel.delete", { + label: "清除选区内容(当前层)", + enabled: hasSelection, + hint: "先框出一个选区", + run: () => { + if (eraseOnActiveLayer()) toast("已清除当前层选区内容", "success"); + } + }); + defineCommand("sel.fill", { + label: "填充选区", + enabled: hasSelection, + hint: "先框出一个选区", + run: () => { + if (fillOnActiveLayer()) toast("已填充", "success"); + } + }); + defineCommand("sel.invert", { label: "反选", view: true, run: invertSelection }); + defineCommand("sel.all", { label: "全选", view: true, run: selectAll }); + defineCommand("sel.none", { label: "取消选区", view: true, run: clearMarquee }); + } + function disposeSelection() { + if (S._antFrame) cancelAnimationFrame(S._antFrame); + S._antFrame = 0; + S.selection = null; + S.marquee = null; + S.lassoPts = null; + clearSelectionCanvas(); + clearCursorCanvas(); + clearOverlay(); + } + + // image-annotate/plugin/editor/floating.js + var contextMode = false; + function bar() { + return runtime.el && runtime.el.querySelector(".iwb-editor-sel-bar"); + } + function bindFloating() { + const el = bar(); + if (!el || el.dataset.bound === "1") return; + el.dataset.bound = "1"; + el.addEventListener("mousedown", (e) => e.stopPropagation()); + el.addEventListener("click", (e) => { + const btn = e.target.closest("[data-sel-cmd]"); + if (!btn) return; + e.stopPropagation(); + runCommand(btn.dataset.selCmd); + contextMode = false; + positionFloating(); + }); + } + function imageToWrap(x, y) { + const stack = S.canvasStack.getBoundingClientRect(); + const wrap = S.canvasWrap.getBoundingClientRect(); + const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + const pad = S.overlayPad || 0; + return { + x: stack.left - wrap.left + (pad + x) * scale, + y: stack.top - wrap.top + (pad + y) * scale + }; + } + function positionFloating() { + const el = bar(); + if (!el || !S.open) return; + const active = hasSelection(); + if (!active && !contextMode) { + el.style.display = "none"; + return; + } + el.style.display = "flex"; + el.classList.toggle("as-menu", contextMode); + const wrapW = S.canvasWrap.clientWidth; + const wrapH = S.canvasWrap.clientHeight; + const bw = el.offsetWidth || 300; + const bh = el.offsetHeight || 36; + let left, top; + if (contextMode && el.dataset.cx !== void 0) { + left = Number(el.dataset.cx); + top = Number(el.dataset.cy); + } else { + const b = S.selection.bbox; + const p = imageToWrap(b.x + b.w, b.y + b.h); + left = p.x + 10; + top = p.y + 8; + if (left + bw > wrapW - 8) left = imageToWrap(b.x, b.y).x + b.w * (S.fitW * S.zoom) / S.imgW - bw; + if (top + bh > wrapH - 8) top = imageToWrap(b.x, b.y).y - bh - 8; + } + el.style.left = Math.max(8, Math.min(left, Math.max(8, wrapW - bw - 8))) + "px"; + el.style.top = Math.max(8, Math.min(top, Math.max(8, wrapH - bh - 8))) + "px"; + el.querySelectorAll("[data-sel-cmd]").forEach((btn) => { + const need = btn.dataset.needsSel === "1"; + btn.disabled = need && !active; + }); + const info = el.querySelector(".iwb-editor-sel-info"); + if (info) { + const s = selectionInfo(); + info.textContent = s ? s.w + "×" + s.h + (s.feather ? " · 羽化 " + s.feather : "") : "未框选"; + } + } + function showSelectionContext(e) { + const el = bar(); + if (!el) return; + const wrap = S.canvasWrap.getBoundingClientRect(); + contextMode = true; + el.dataset.cx = String(e.clientX - wrap.left); + el.dataset.cy = String(e.clientY - wrap.top); + positionFloating(); + if (!hasSelection()) toast("右键菜单:可先「全选」,或框选后直接操作", "info"); + } + function hideSelectionContext() { + if (!contextMode) return; + contextMode = false; + const el = bar(); + if (el) el.classList.remove("as-menu"); + positionFloating(); + } + + // image-annotate/plugin/editor/dom.js + var COMMON_COLORS = [ + "#ff4444", + "#ff8a00", + "#ffd400", + "#4cd964", + "#00bfa5", + "#4488ff", + "#ff66aa", + "#ffffff", + "#d0d0d0", + "#808080", + "#000000", + "#c0392b", + "#0f9d58", + "#1677ff", + "#6b4fbb" + ]; + function colorSurfaceHtml() { + return ` + + 描边 + 填充 + 底色 + + + + + + + + + + + + + + + + + + + 常用色 + + + + ${COMMON_COLORS.map((c) => ``).join("")} + + + + 最近 + + + + `; + } + function createEl() { + if (runtime.el) return; + runtime.el = document.createElement("div"); + runtime.el.id = "iwb-editor-overlay"; + runtime.el.className = "iwb-editor-overlay"; + runtime.el.innerHTML = ` + + + 图片编辑 — + + + 新建 + 覆盖 + 退出 + + + + + + + 输出 原尺寸 PNG ▾ + + 预设 + 原尺寸 + 电商方图 + + 格式 + PNG + JPG + WebP + + 背景 + 透明 + 白底 + + 边长 + 750 + 800 + 1000 + 1200 + + ≤KB + 不限 + 300 + 500 + 800 + + 一次只输出一个结果;设置会记住 + + + 复制 + 导出 + + + + 工具选项 + + Ctrl+J 复制 · Delete 清除 + + + + + + 图层 + + + + + + + + + + + + + + + + + + + + + + + + + #ffffff + + + 未框选 + 复制 + 剪切 + 删除 + 填充 + 反选 + 全选 + 取消 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 滚轮缩放 · 抓手/空格/中键拖拽自由移动画布 + + + + + + + 100% + — + x — y — + 无选区 + 当前层:原图 + 画笔 + + + + ${colorSurfaceHtml()} + + + + `; + document.body.appendChild(runtime.el); + S.canvasWrap = runtime.el.querySelector(".iwb-editor-canvas-wrap"); + S.canvasStack = runtime.el.querySelector(".iwb-editor-canvas-stack"); + S.transparencyGrid = runtime.el.querySelector(".iwb-editor-transparency-grid"); + S.textCanvas = runtime.el.querySelector(".iwb-editor-text"); + S.strokeCanvas = runtime.el.querySelector(".iwb-editor-stroke"); + S.overlayCanvas = runtime.el.querySelector(".iwb-editor-crop-overlay"); + S.selectionCanvas = runtime.el.querySelector(".iwb-editor-selection-overlay"); + S.cursorCanvas = runtime.el.querySelector(".iwb-editor-cursor-overlay"); + S.textCtx = S.textCanvas.getContext("2d"); + S.strokeCtx = S.strokeCanvas.getContext("2d"); + S.overlayCtx = S.overlayCanvas.getContext("2d"); + S.selectionCtx = S.selectionCanvas.getContext("2d"); + S.cursorCtx = S.cursorCanvas.getContext("2d"); + bindEvents(); + } + function dataUrlToBlob(dataUrl) { + const comma = dataUrl.indexOf(","); + if (comma < 0) return null; + const meta = dataUrl.slice(0, comma); + if (!/;base64/i.test(meta)) return null; + const mime = (/^data:([^;,]+)/.exec(meta) || [])[1] || "image/png"; + const bin = atob(dataUrl.slice(comma + 1)); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return new Blob([bytes], { type: mime }); + } + async function loadImage(src) { + let useSrc = src; + let revokeUrl = null; + if (typeof src === "string" && src.slice(0, 5) === "data:") { + try { + const blob = dataUrlToBlob(src); + if (!blob) throw new Error("dataURL 不是 base64"); + useSrc = URL.createObjectURL(blob); + revokeUrl = useSrc; + } catch (e) { + useSrc = src; + } + } + try { + return await new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = () => reject(new Error("图片加载失败")); + img.src = useSrc; + }); + } finally { + if (revokeUrl) { + try { + URL.revokeObjectURL(revokeUrl); + } catch (e) { + } + } + } + } + + // image-annotate/plugin/editor/effects.js + var SOFT_MIN = 1.2; + var SOFT_MAX = 8; + function softRadius(canvas) { + const side = Math.min(canvas.width || 0, canvas.height || 0); + return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 400 * 10) / 10)); + } + function mosaicBlock(canvas) { + const side = Math.min(canvas.width || 0, canvas.height || 0); + return Math.max(6, Math.round(side / 60)); + } + var QUICK_EFFECTS = { + invert: { + label: "反白", + hint: "反相:明暗翻转,白底变黑底", + param: "强度", + unit: "%", + min: 0, + max: 100, + step: 1, + def: () => 100, + render: (canvas, v) => { + if (v > 0) filterCanvas(canvas, "invert(" + v / 100 + ")"); + } + }, + gray: { + label: "灰度", + hint: "去色,保留明暗层次", + param: "强度", + unit: "%", + min: 0, + max: 100, + step: 1, + def: () => 100, + render: (canvas, v) => { + if (v > 0) filterCanvas(canvas, "grayscale(" + v / 100 + ")"); + } + }, + boost: { + label: "增强", + hint: "提亮并加对比,适合发灰的截图", + param: "强度", + unit: "%", + min: 0, + max: 100, + step: 1, + def: () => 100, + render: (canvas, v) => { + if (v <= 0) return; + const k = v / 100; + filterCanvas(canvas, "brightness(" + (1 + 0.4 * k).toFixed(3) + ") contrast(" + (1 + 0.25 * k).toFixed(3) + ") saturate(" + (1 + 0.2 * k).toFixed(3) + ")"); + } + }, + contrast: { + label: "高对比", + hint: "压成黑白硬调,突出主体", + param: "强度", + unit: "%", + min: 0, + max: 100, + step: 1, + def: () => 100, + render: (canvas, v) => { + if (v <= 0) return; + const k = v / 100; + filterCanvas(canvas, "grayscale(" + k.toFixed(3) + ") contrast(" + (1 + 1.6 * k).toFixed(3) + ")"); + } + }, + soft: { + label: "柔化", + hint: "模糊,弱化背景", + param: "半径", + unit: "px", + min: 0, + max: 16, + step: 0.5, + def: (canvas) => softRadius(canvas), + render: (canvas, v) => { + if (v > 0) filterCanvas(canvas, "blur(" + v + "px)"); + } + }, + mosaic: { + label: "马赛克", + hint: "像素化,用于打码手机号/地址等隐私信息", + param: "块大小", + unit: "px", + min: 2, + max: 96, + step: 1, + def: (canvas) => mosaicBlock(canvas), + render: (canvas, v) => { + if (v > 1) pixelateCanvas(canvas, v); + } + } + }; + function effectTarget() { + const active = getActiveLayer(); + if (active) return active; + return S.layers.find((l) => l.id === "base") || null; + } + function filterCanvas(canvas, css) { + const w = canvas.width, h = canvas.height; + if (!w || !h || !css) return; + const tmp = document.createElement("canvas"); + tmp.width = w; + tmp.height = h; + const tctx = tmp.getContext("2d"); + tctx.filter = css; + tctx.drawImage(canvas, 0, 0); + const ctx = canvas.getContext("2d"); + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "copy"; + ctx.filter = "none"; + ctx.drawImage(tmp, 0, 0); + ctx.restore(); + } + function pixelateCanvas(canvas, block) { + const w = canvas.width, h = canvas.height; + if (!w || !h) return; + const b = Math.max(2, block); + const sw = Math.max(1, Math.round(w / b)); + const sh = Math.max(1, Math.round(h / b)); + const tmp = document.createElement("canvas"); + tmp.width = sw; + tmp.height = sh; + const tctx = tmp.getContext("2d"); + tctx.imageSmoothingEnabled = true; + tctx.drawImage(canvas, 0, 0, sw, sh); + const ctx = canvas.getContext("2d"); + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "copy"; + ctx.imageSmoothingEnabled = false; + ctx.filter = "none"; + ctx.drawImage(tmp, 0, 0, w, h); + ctx.restore(); + } + function snapshotCanvas(canvas) { + const c = document.createElement("canvas"); + c.width = canvas.width; + c.height = canvas.height; + const ctx = c.getContext("2d"); + ctx.drawImage(canvas, 0, 0); + return c; + } + function rasterizeLayer(layer) { + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.clearRect(0, 0, S.imgW, S.imgH); + ctx.drawImage(layer.canvas, 0, 0); + const units = layerUnits(); + const i = units.findIndex((u) => u.kind === "bitmap" && u.obj === layer); + const baseZ = layer.z || 0; + const nextZ = i >= 0 && units[i + 1] ? units[i + 1].obj.z || 0 : baseZ + 1; + const z = nextZ > baseZ ? (baseZ + nextZ) / 2 : baseZ + 0.5; + const clone = { + id: "fx" + Date.now() + Math.floor(Math.random() * 1e3), + name: layer.name + " · 效果", + canvas, + ctx, + opacity: layer.opacity == null ? 1 : layer.opacity, + visible: true, + locked: false, + x: 0, + y: 0, + w: S.imgW, + h: S.imgH, + rotation: 0, + z + }; + S.layers.push(clone); + layer.visible = false; + if (S.selectedLayerId === layer.id) S.selectedLayerId = clone.id; + S.activeLayerId = clone.id; + reorderLayerCanvas(); + updateLayerCanvasStyles(); + renderLayerPanel(); + return clone; + } + function renderFromSource(target, key, value) { + const st = S.fx; + const fx = QUICK_EFFECTS[key]; + if (!st.source || !fx) return; + const ctx = target.canvas.getContext("2d"); + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "copy"; + ctx.filter = "none"; + ctx.imageSmoothingEnabled = true; + ctx.drawImage(st.source, 0, 0); + ctx.restore(); + fx.render(target.canvas, value); + target._bounds = void 0; + S.pickerComposite = null; + } + function fmtValue(fx, v) { + if (fx.unit === "px") return Math.round(v * 10) / 10 + " px"; + return Math.round(v) + "%"; + } + function renderFxPanel() { + if (!runtime.el) return; + const adv = runtime.el.querySelector(".iwb-editor-fx-adj"); + if (!adv) return; + const range = adv.querySelector(".iwb-editor-fx-range"); + const nameEl = adv.querySelector(".iwb-editor-fx-adj-name"); + const valEl = adv.querySelector(".iwb-editor-fx-adj-val"); + const targetEl = runtime.el.querySelector(".iwb-editor-fx-target"); + const layer = effectTarget(); + const activeKey = S.fx.source ? S.fx.key : null; + runtime.el.querySelectorAll("[data-fx]").forEach((btn) => { + btn.classList.toggle("is-active", Boolean(activeKey) && btn.dataset.fx === activeKey); + }); + if (targetEl) { + const name = layer ? layer.name : "无图层"; + targetEl.textContent = name; + targetEl.title = layer ? "效果作用于「" + name + "」" : "没有可处理的位图图层"; + } + const st = S.fx; + const fx = st.source ? QUICK_EFFECTS[st.key] : null; + if (!fx || !range) { + adv.classList.add("iwb-editor-fx-adj-off"); + if (nameEl) nameEl.textContent = "强度"; + if (valEl) valEl.textContent = "—"; + if (range) { + range.disabled = true; + range.value = "0"; + } + return; + } + const usable = Boolean(layer && st.layerId === layer.id); + adv.classList.toggle("iwb-editor-fx-adj-off", !usable); + if (nameEl) nameEl.textContent = fx.label + " · " + fx.param; + range.min = String(fx.min); + range.max = String(fx.max); + range.step = String(fx.step); + range.disabled = !usable; + if (usable) range.value = String(st.value); + if (valEl) { + valEl.textContent = fmtValue(fx, st.value); + valEl.title = usable ? "" : "效果作用在「" + (S.layers.find((l) => l.id === st.layerId) || {}).name + "」,切回该层可继续调整"; + } + } + function applyQuickEffect(key) { + const fx = QUICK_EFFECTS[key]; + if (!fx) return false; + const layer = effectTarget(); + if (!layer) { + toast("没有可处理的图层"); + return false; + } + if (layer.visible === false) { + toast("「" + layer.name + "」已隐藏,先显示再应用效果"); + return false; + } + let target = layer; + if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer); + if (!target) { + toast("栅格化失败,效果未应用"); + return false; + } + const st = S.fx; + if (st.source && st.layerId === target.id && st.key === key) { + st.value = fx.def(target.canvas); + renderFromSource(target, key, st.value); + if (S.renderAll) S.renderAll(); + toast("「" + fx.label + "」已重置为 " + fmtValue(fx, st.value), "success"); + return true; + } + saveSnapshot("效果:" + fx.label); + S.fx = { key, layerId: target.id, source: snapshotCanvas(target.canvas), value: fx.def(target.canvas) }; + renderFromSource(target, key, S.fx.value); + if (S.renderAll) S.renderAll(); + toast("已应用「" + fx.label + "」" + fmtValue(fx, S.fx.value) + " 到 " + target.name + " · 可拖强度微调", "success"); + return true; + } + function setEffectValue(value) { + const st = S.fx; + if (!st.source) return false; + const fx = QUICK_EFFECTS[st.key]; + if (!fx) return false; + const target = S.layers.find((l) => l.id === st.layerId); + if (!target) return false; + const layer = effectTarget(); + if (!layer || layer.id !== st.layerId) return false; + const v = Math.min(fx.max, Math.max(fx.min, Number(value) || 0)); + st.value = v; + renderFromSource(target, st.key, v); + if (runtime.el) { + const valEl = runtime.el.querySelector(".iwb-editor-fx-adj-val"); + if (valEl) valEl.textContent = fmtValue(fx, v); + } + return true; + } + + // image-annotate/plugin/editor/adjust.js + var PREVIEW_SIDE = 900; + var ADJUST_DEFS = [ + { key: "exposure", label: "曝光", min: -100, max: 100, step: 1, def: 0 }, + { key: "brightness", label: "明度", min: -100, max: 100, step: 1, def: 0 }, + { key: "contrast", label: "对比度", min: -100, max: 100, step: 1, def: 0 }, + { key: "shadows", label: "阴影", min: -100, max: 100, step: 1, def: 0 }, + { key: "highlights", label: "高光", min: -100, max: 100, step: 1, def: 0 }, + { key: "hue", label: "色相", min: -180, max: 180, step: 1, def: 0, suffix: "°" }, + { key: "saturation", label: "饱和度", min: -100, max: 100, step: 1, def: 0 }, + { key: "temp", label: "温度", title: "白平衡温度:往右偏暖(黄),往左偏冷(蓝)", min: -100, max: 100, step: 1, def: 0 }, + { key: "tint", label: "色调", title: "白平衡色调:往右偏品红,往左偏绿", min: -100, max: 100, step: 1, def: 0 }, + { key: "sharpen", label: "锐度", min: 0, max: 100, step: 1, def: 0 }, + { key: "clarity", label: "清晰度", min: -100, max: 100, step: 1, def: 0 } + ]; + var ADJUST_KEYS = ADJUST_DEFS.map((d) => d.key); + function zeroAdjust() { + const o = {}; + for (const k of ADJUST_KEYS) o[k] = 0; + return o; + } + function isNeutral(p) { + if (!p) return true; + for (const k of ADJUST_KEYS) if (p[k]) return false; + return true; + } + function adjustTarget() { + const active = getActiveLayer(); + if (active) return active; + return S.layers.find((l) => l.id === "base") || null; + } + function copyCanvas(src, maxSide) { + const w0 = src.width, h0 = src.height; + let w = w0, h = h0; + if (maxSide && Math.max(w0, h0) > maxSide) { + const k = maxSide / Math.max(w0, h0); + w = Math.max(1, Math.round(w0 * k)); + h = Math.max(1, Math.round(h0 * k)); + } + const c = document.createElement("canvas"); + c.width = w; + c.height = h; + const ctx = c.getContext("2d", { willReadFrequently: true }); + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(src, 0, 0, w, h); + return c; + } + function adjustPixels(ctx, w, h, p) { + const img = ctx.getImageData(0, 0, w, h); + const d = img.data; + const ev = p.exposure ? Math.pow(2, p.exposure / 50) : 1; + const add = p.brightness / 100 * 0.45; + const con = 1 + p.contrast / 100; + const sh = p.shadows / 100; + const hi = p.highlights / 100; + const sat = 1 + p.saturation / 100; + const wbR = 1 + p.temp / 250 + p.tint / 500; + const wbG = 1 - p.tint / 400; + const wbB = 1 - p.temp / 250 + p.tint / 500; + const wb = Boolean(p.temp || p.tint); + const needSh = Boolean(sh); + const needHi = Boolean(hi); + const needCon = Boolean(p.contrast); + const needSat = Boolean(p.saturation); + const needHue = Boolean(p.hue); + let h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, h8 = 0; + if (needHue) { + const a = p.hue * Math.PI / 180; + const c = Math.cos(a), s = Math.sin(a); + h0 = 0.213 + c * 0.787 - s * 0.213; + h1 = 0.715 - c * 0.715 - s * 0.715; + h2 = 0.072 - c * 0.072 + s * 0.928; + h3 = 0.213 - c * 0.213 + s * 0.143; + h4 = 0.715 + c * 0.285 + s * 0.14; + h5 = 0.072 - c * 0.072 - s * 0.283; + h6 = 0.213 - c * 0.213 - s * 0.787; + h7 = 0.715 - c * 0.715 + s * 0.715; + h8 = 0.072 + c * 0.928 + s * 0.072; + } + const trivial = !wb && !p.exposure && !add && !needSh && !needHi && !needCon && !needSat && !needHue; + if (trivial) return; + for (let i = 0; i < d.length; i += 4) { + let r = d[i] / 255, g = d[i + 1] / 255, b = d[i + 2] / 255; + if (wb) { + r *= wbR; + g *= wbG; + b *= wbB; + } + if (ev !== 1) { + r *= ev; + g *= ev; + b *= ev; + } + if (add) { + r += add; + g += add; + b += add; + } + if (needSh || needHi) { + const l = 0.2126 * r + 0.7152 * g + 0.0722 * b; + if (needSh) { + const m = (1 - l) * (1 - l) * sh * 0.85; + r += m; + g += m; + b += m; + } + if (needHi) { + const m = l * l * hi * 0.85; + r += m; + g += m; + b += m; + } + } + if (needCon) { + r = (r - 0.5) * con + 0.5; + g = (g - 0.5) * con + 0.5; + b = (b - 0.5) * con + 0.5; + } + if (needSat) { + const l = 0.2126 * r + 0.7152 * g + 0.0722 * b; + r = l + (r - l) * sat; + g = l + (g - l) * sat; + b = l + (b - l) * sat; + } + if (needHue) { + const nr = h0 * r + h1 * g + h2 * b; + const ng = h3 * r + h4 * g + h5 * b; + const nb = h6 * r + h7 * g + h8 * b; + r = nr; + g = ng; + b = nb; + } + d[i] = r <= 0 ? 0 : r >= 1 ? 255 : r * 255; + d[i + 1] = g <= 0 ? 0 : g >= 1 ? 255 : g * 255; + d[i + 2] = b <= 0 ? 0 : b >= 1 ? 255 : b * 255; + } + ctx.putImageData(img, 0, 0); + } + function unsharp(canvas, radius, amount) { + if (!(amount > 0)) return; + const w = canvas.width, h = canvas.height; + const blur = document.createElement("canvas"); + blur.width = w; + blur.height = h; + const bc = blur.getContext("2d", { willReadFrequently: true }); + bc.filter = "blur(" + radius.toFixed(2) + "px)"; + bc.drawImage(canvas, 0, 0); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + const src = ctx.getImageData(0, 0, w, h); + const bl = bc.getImageData(0, 0, w, h); + const a = src.data, b = bl.data; + for (let i = 0; i < a.length; i += 4) { + if (a[i + 3] === 0) continue; + for (let c = 0; c < 3; c++) { + const v = a[i + c] + (a[i + c] - b[i + c]) * amount; + a[i + c] = v <= 0 ? 0 : v >= 255 ? 255 : v; + } + } + ctx.putImageData(src, 0, 0); + } + function paint(canvas, p, refSide) { + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + adjustPixels(ctx, canvas.width, canvas.height, p); + const k = Math.max(canvas.width, canvas.height) / (refSide || Math.max(canvas.width, canvas.height)); + if (p.sharpen > 0) unsharp(canvas, Math.max(0.6, 1 * k), p.sharpen / 100 * 1.1); + if (p.clarity) { + unsharp(canvas, Math.max(1.5, 6 * k), p.clarity / 100 * 0.55); + } + } + function blit(target, src) { + const ctx = target.getContext("2d"); + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "copy"; + ctx.filter = "none"; + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(src, 0, 0, target.width, target.height); + ctx.restore(); + target._bounds = void 0; + S.pickerComposite = null; + } + function renderAdjust(preview) { + const st = S.adjust; + if (!st || !st.source) return false; + const target = S.layers.find((l) => l.id === st.layerId); + if (!target) return false; + const src = preview && st.previewCanvas ? st.previewCanvas : st.source; + const work = copyCanvas(src); + paint(work, st.params, Math.max(st.source.width, st.source.height)); + blit(target.canvas, work); + return true; + } + var sourceCache = /* @__PURE__ */ new Map(); + function captureFor(layer) { + const hit = sourceCache.get(layer.id); + if (hit) return hit; + const rec = { + source: copyCanvas(layer.canvas, 0), + previewCanvas: copyCanvas(layer.canvas, PREVIEW_SIDE) + }; + sourceCache.set(layer.id, rec); + return rec; + } + function resetAdjustCache() { + sourceCache.clear(); + S.adjust = { layerId: null, source: null, previewCanvas: null, params: zeroAdjust() }; + } + function adjustCacheSize() { + return sourceCache.size; + } + function switchTarget(layer) { + const st = S.adjust; + if (st && st.layerId && st.source) { + sourceCache.set(st.layerId, { source: st.source, previewCanvas: st.previewCanvas }); + } + const rec = captureFor(layer); + S.adjust = { + layerId: layer.id, + source: rec.source, + previewCanvas: rec.previewCanvas, + params: layer.adjustParams ? { ...layer.adjustParams } : zeroAdjust() + }; + } + function persistParams() { + const st = S.adjust; + if (!st || !st.layerId || !st.params) return; + const layer = S.layers.find((l) => l.id === st.layerId); + if (layer) layer.adjustParams = { ...st.params }; + } + function ensureAdjustTarget() { + let layer = adjustTarget(); + if (!layer) { + toast("没有可调节的图层"); + return null; + } + if (layer.visible === false) { + toast("「" + layer.name + "」已隐藏,先显示再调节"); + return null; + } + if (!needsPixelSnapshot(layer)) layer = rasterizeForAdjust(layer); + if (!layer) { + toast("栅格化失败,调节未应用"); + return null; + } + if (!S.adjust || S.adjust.layerId !== layer.id || !S.adjust.source) switchTarget(layer); + return layer; + } + function rasterizeForAdjust(layer) { + const canvas = document.createElement("canvas"); + canvas.width = S.imgW; + canvas.height = S.imgH; + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + ctx.drawImage(layer.canvas, 0, 0); + const copy = { + id: "adj" + Date.now() + Math.floor(Math.random() * 1e3), + name: layer.name + " · 调节", + canvas, + ctx, + opacity: layer.opacity == null ? 1 : layer.opacity, + visible: true, + locked: false, + x: 0, + y: 0, + w: S.imgW, + h: S.imgH, + rotation: 0, + z: (layer.z || 0) + 0.5 + }; + S.layers.push(copy); + layer.visible = false; + if (S.selectedLayerId === layer.id) S.selectedLayerId = copy.id; + S.activeLayerId = copy.id; + renderLayerPanel(); + return copy; + } + function applyAdjust(preview) { + if (!S.adjust || !S.adjust.source) return false; + const ok = renderAdjust(Boolean(preview)); + if (ok) { + persistParams(); + if (S.renderAll) S.renderAll(); + } + renderAdjustPanel(); + return ok; + } + function setAdjustValue(key, value, preview) { + const st = S.adjust; + if (!st || !st.source) return false; + const def = ADJUST_DEFS.find((d) => d.key === key); + if (!def) return false; + const v = Math.min(def.max, Math.max(def.min, Number(value) || 0)); + st.params[key] = v; + applyAdjust(preview); + return true; + } + function resetAdjust(key) { + const st = S.adjust; + if (!st || !st.source) return false; + saveSnapshot("调节复位"); + if (key) st.params[key] = 0; + else st.params = zeroAdjust(); + applyAdjust(false); + syncAdjustControls(); + return true; + } + function adjustDirty() { + return Boolean(S.adjust && S.adjust.source && !isNeutral(S.adjust.params)); + } + function mountAdjustPanel() { + if (!runtime.el) return; + const list = runtime.el.querySelector(".iwb-editor-adj-list"); + if (!list || list.childElementCount) return; + list.innerHTML = ADJUST_DEFS.map((d) => ` + + ${d.label} + + + `).join(""); + renderAdjustPanel(); + } + function renderAdjustPanel() { + if (!runtime.el) return; + const sec = runtime.el.querySelector(".iwb-editor-adj"); + if (!sec) return; + const layer = adjustTarget(); + if (layer && S.adjust && S.adjust.layerId && S.adjust.layerId !== layer.id) { + switchTarget(layer); + syncAdjustControls(); + return; + } + const nameEl = sec.querySelector(".iwb-editor-adj-target"); + if (nameEl) { + const name = layer ? layer.name : "无图层"; + nameEl.textContent = name; + nameEl.title = layer ? "调节作用于「" + name + "」" : "没有可调节的位图图层"; + } + const dirty = adjustDirty(); + sec.classList.toggle("is-dirty", dirty); + const reset = sec.querySelector('[data-adj-reset="all"]'); + if (reset) reset.disabled = !dirty; + sec.querySelectorAll(".iwb-editor-adj-row").forEach((row) => { + const k = row.dataset.adj; + const v = S.adjust && S.adjust.params ? S.adjust.params[k] || 0 : 0; + row.classList.toggle("is-set", Boolean(v)); + }); + } + function syncAdjustControls() { + if (!runtime.el) return; + const sec = runtime.el.querySelector(".iwb-editor-adj"); + if (!sec || !S.adjust || !S.adjust.params) return; + sec.querySelectorAll(".iwb-editor-adj-row").forEach((row) => { + const k = row.dataset.adj; + const v = S.adjust.params[k] || 0; + const range = row.querySelector(".iwb-editor-adj-range"); + const val = row.querySelector(".iwb-editor-adj-val"); + if (range) range.value = String(v); + if (val) val.value = String(v); + }); + renderAdjustPanel(); + } + function onHistoryRestore() { + sourceCache.clear(); + const layer = adjustTarget(); + if (!layer) { + S.adjust = { layerId: null, source: null, previewCanvas: null, params: zeroAdjust() }; + syncAdjustControls(); + return; + } + if (layer.adjustParams) delete layer.adjustParams; + S.adjust = { + layerId: layer.id, + source: copyCanvas(layer.canvas, 0), + previewCanvas: copyCanvas(layer.canvas, PREVIEW_SIDE), + params: zeroAdjust() + }; + syncAdjustControls(); + } + + // image-annotate/plugin/editor/events.js + var SIDE_DEFAULT = 280; + var SIDE_MIN = 220; + var SIDE_MAX = 520; + var MOUSE_DOWN_HANDLERS = { + select: onSelectMouseDown, + crop: onCropMouseDown, + text: onTextMouseDown, + picker: onPickerMouseDown, + brush: onBrushMouseDown, + eraser: onEraserMouseDown, + pen: onPenMouseDown, + rect: onShapeMouseDown, + arrow: onShapeMouseDown, + circle: onShapeMouseDown + }; + function onMouseDown(e) { + if (S.placingImage) { + onPlacementMouseDown(e); + return; + } + if (S.spaceDown || S.tool === "hand" || e.button === 1) { + onPanMouseDown(e); + return; + } + if (e.button !== 0) return; + e.preventDefault(); + const pos = getPos(e); + S.startX = pos.x; + S.startY = pos.y; + hideSelectionContext(); + if (S.layerMulti.length) { + S.layerMulti.length = 0; + renderLayerPanel(); + } + if (S.tool === "marquee") { + beginMarquee(pos); + return; + } + if (S.tool === "lasso") { + beginLasso(pos); + return; + } + const dbl = isDoubleClick(pos); + if (S.tool === "select") { + if (dbl && onCanvasDoubleClick(e, pos)) return; + const penShape = getPenEditingShape(); + if (penShape && onPenEditMouseDown(e, pos, penShape)) return; + } + if (S.tool === "pen" && dbl) { + commitPenPath(); + return; + } + const handler = Object.prototype.hasOwnProperty.call(MOUSE_DOWN_HANDLERS, S.tool) ? MOUSE_DOWN_HANDLERS[S.tool] : null; + if (handler) handler(pos, e); + } + var DBL_INTERVAL = 380; + function isDoubleClick(pos) { + const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now(); + const last = S.lastClick; + const hit = !!last && now - last.t < DBL_INTERVAL && Math.hypot(pos.x - last.x, pos.y - last.y) < Math.max(8 / viewScale(), 6); + S.lastClick = hit ? null : { t: now, x: pos.x, y: pos.y }; + return hit; + } + function onCanvasDoubleClick(e, pos) { + const penShape = getPenEditingShape(); + if (penShape) { + const pi = hitPenPoint(pos, penShape, Math.max(14 / viewScale(), 8)); + if (pi < 0) return false; + e.preventDefault(); + saveSnapshot(); + const pts = penShape.pts; + const minPts = penShape.closed ? 3 : 2; + if (pts.length <= minPts) { + removeVecCanvas(penShape); + S.shapeLayers = S.shapeLayers.filter((x) => x.id !== penShape.id); + S.penEditId = null; + S.selectedShapeId = null; + } else { + pts.splice(pi, 1); + if (penShape.closed && pts.length < 3) penShape.closed = false; + } + renderObjects(); + renderLayerPanel(); + return true; + } + const hitPen = hitShapeLayer(pos, true); + if (hitPen && hitPen.type === "pen") { + e.preventDefault(); + beginPenEdit(hitPen); + return true; + } + const hitText = hitTextLayer(pos); + if (hitText) { + e.preventDefault(); + selectUnit("text", hitText.id); + if (hitText.locked) return true; + renderObjects(); + showTextInput(hitText.x, hitText.y, hitText); + return true; + } + return false; + } + function onPlacementMouseDown(e) { + e.preventDefault(); + const pos = getPos(e); + const handle = hitPlacementHandle(pos); + if (handle) { + S.placingHandle = handle; + S.placingStart = { mx: pos.x, my: pos.y, x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h, rotation: S.placingImage.rotation || 0 }; + S.drawCanvasCursor(CROP_CURSORS[handle] || "move"); + return; + } + if (insidePlacementRect(pos)) { + S.placingHandle = "move"; + S.placingStart = { mx: pos.x, my: pos.y, x: S.placingImage.x, y: S.placingImage.y, rotation: S.placingImage.rotation || 0 }; + S.drawCanvasCursor("move"); + return; + } + confirmImagePlacement(); + } + function onPanMouseDown(e) { + e.preventDefault(); + commitTextInput(); + S.panning = true; + S.panStart = { x: e.clientX, y: e.clientY, vx: S.viewX || 0, vy: S.viewY || 0 }; + updateCursor(); + } + function onPenEditMouseDown(e, pos, penShape) { + const pi = hitPenPoint(pos, penShape, Math.max(16 / viewScale(), 9)); + if (pi >= 0) { + S.penDragPt = pi; + S.penDragBase = JSON.parse(JSON.stringify(penShape.pts)); + S.penDragPending = snapshotState(); + return true; + } + const ei = hitPenEdgeInsert(pos, penShape); + if (ei >= 0) { + saveSnapshot(); + penShape.pts.splice(ei + 1, 0, { x: pos.x, y: pos.y }); + renderObjects(); + renderLayerPanel(); + return true; + } + S.penEditId = null; + S.penDragPt = -1; + S.penDragPending = null; + renderObjects(); + return false; + } + function onSelectMouseDown(pos) { + if (commitTextInput()) return; + const bitmapHandle = hitBitmapHandle(pos); + if (bitmapHandle) { + beginBitmapDrag(bitmapHandle, pos); + return; + } + const th = hitTextHandle(pos); + if (th) { + if (th === "rotate") beginTextRotate(pos); + else beginTextScaleDrag(th, pos); + return; + } + const shH = hitShapeHandle(pos); + if (shH) { + beginShapeHandleDrag(shH, pos); + return; + } + const hit = hitTopmost(pos); + if (!hit) { + selectUnit(null, null); + renderObjects(); + renderLayerPanel(); + return; + } + selectUnit(hit.kind, hit.obj.id); + if (hit.obj.locked) { + renderObjects(); + renderLayerPanel(); + return; + } + if (hit.kind === "bitmap") { + S.activeLayerId = hit.obj.id; + beginBitmapDrag(null, pos); + } else if (hit.kind === "text") { + S.textDrag = { mode: "move", start: pos, layer: { x: hit.obj.x, y: hit.obj.y }, pending: snapshotState() }; + } else { + S.shapeDrag = { mode: "move", start: pos, shape: { ...hit.obj }, pending: snapshotState() }; + } + renderObjects(); + renderLayerPanel(); + } + function onCropMouseDown(pos) { + if (S.cropRect) { + const handle = hitCropHandle(pos); + if (handle) { + S.cropHandle = handle; + S.isDrawing = true; + return; + } + if (insideRect(pos, S.cropRect)) { + S.cropMoving = true; + S.moveStart = { x: pos.x, y: pos.y, rect: { ...S.cropRect } }; + S.isDrawing = true; + } + return; + } + S.isDrawing = true; + } + function onTextMouseDown(pos) { + if (commitTextInput()) return; + if (S.selectedTextId) { + S.selectedTextId = null; + renderObjects(); + renderLayerPanel(); + } + showTextInput(pos.x, pos.y); + } + function onPickerMouseDown(pos) { + const s = sampleColor(pos); + if (s && s.a > 0) { + applyPanelColor(rgbToHex(s.r, s.g, s.b)); + } + exitPicker(); + return; + } + function onBrushMouseDown(pos) { + const layer = ensureWritableLayer(); + if (!layer) return; + S.selectedLayerId = layer.id; + S.isDrawing = true; + saveSnapshot(); + beginStroke(); + strokeSegment(pos.x, pos.y, pos.x, pos.y); + } + function onEraserMouseDown(pos) { + let layer = getActiveLayer(); + if (!layer || layer.locked) layer = topWritableLayer(); + if (!layer) { + toast("没有可擦的图层:先用画笔标注,或在图层面板新建一层", "info"); + return; + } + S.activeLayerId = layer.id; + S.selectedLayerId = layer.id; + S.isDrawing = true; + saveSnapshot(); + beginStroke(); + eraseSegment(pos.x, pos.y, pos.x, pos.y); + } + function topWritableLayer() { + let hit = null; + for (const l of S.layers) { + if (l.locked || l.visible === false) continue; + if (!hit || (l.z || 0) >= (hit.z || 0)) hit = l; + } + return hit; + } + function onPenMouseDown(pos) { + if (!S.penPath) S.penPath = { pts: [], preview: null, closed: false }; + const point = { x: clamp(pos.x, 0, S.imgW), y: clamp(pos.y, 0, S.imgH) }; + const first = S.penPath.pts[0]; + if (first && S.penPath.pts.length >= 3 && Math.hypot(point.x - first.x, point.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)) { + S.penPath.closed = true; + S.penPath.nearStart = true; + S.penPath.preview = null; + commitPenPath(); + } else { + S.penPath.pts.push(point); + renderObjects({ id: "pen-preview", type: "pen", pts: S.penPath.pts.concat(S.penPath.preview ? [S.penPath.preview] : []), closed: false, color: S.color, lw: Math.max(1, S.shapeLineWidth), fill: false, opacity: 1, visible: true }); + } + return; + } + function onShapeMouseDown(pos) { + if (S.selectedShapeId) { + S.selectedShapeId = null; + renderObjects(); + renderLayerPanel(); + } + S.isDrawing = true; + } + var DRAW_MOVE_HANDLERS = { + brush: onBrushDrawMove, + eraser: onEraserDrawMove, + pen: onPenDrawMove, + rect: onShapeDrawMove, + arrow: onShapeDrawMove, + circle: onShapeDrawMove, + crop: onCropDrawMove + }; + function onMouseMove(e) { + S._altDown = !!e.altKey; + if (S.placingImage && S.placingHandle && S.placingStart) { + onPlacementDragMove(e); + return; + } + if (S.placingImage) { + onPlacementHoverMove(e); + return; + } + if (S.panning && S.panStart) { + onPanMouseMove(e); + return; + } + const pos0 = getPos(e); + if (S.marquee) { + updateMarquee(pos0); + return; + } + if (S.lassoPts) { + updateLasso(pos0); + return; + } + if (S.bitmapDrag) { + onBitmapDragMouseMove(pos0); + return; + } + if (S.textDrag) { + onTextDragMouseMove(pos0); + return; + } + if (S.penDragPt >= 0) { + onPenEditDragMove(pos0); + return; + } + if (S.shapeDrag) { + onShapeDragMouseMove(pos0); + return; + } + if (!S.isDrawing) return; + const pos = pos0; + const handler = Object.prototype.hasOwnProperty.call(DRAW_MOVE_HANDLERS, S.tool) ? DRAW_MOVE_HANDLERS[S.tool] : null; + if (handler) handler(pos); + } + function onPlacementDragMove(e) { + const pos = getPos(e); + resizePlacement(pos); + drawPlacementPreview(); + return; + } + function onPlacementHoverMove(e) { + const pos = getPos(e); + const h = hitPlacementHandle(pos); + if (h) S.drawCanvasCursor(h === "rotate" ? ROT_CURSOR : CROP_CURSORS[h] || "move"); + else S.drawCanvasCursor(insidePlacementRect(pos) ? "move" : "default"); + return; + } + function onPanMouseMove(e) { + setView( + S.panStart.vx + (e.clientX - S.panStart.x), + S.panStart.vy + (e.clientY - S.panStart.y) + ); + return; + } + function onBitmapDragMouseMove(pos0) { + applyBitmapDrag(pos0); + renderObjects(); + return; + } + function onTextDragMouseMove(pos0) { + const t = getSelectedText(); + if (t) { + if (S.textDrag.mode === "move") { + const dx = pos0.x - S.textDrag.start.x; + const dy = pos0.y - S.textDrag.start.y; + let nx = clamp(S.textDrag.layer.x + dx, 0, Math.max(0, S.imgW - 4)); + let ny = clamp(S.textDrag.layer.y + dy, 0, Math.max(0, S.imgH - 4)); + if (!S._altDown) { + const b = textBounds(t); + const offX = b.x - t.x; + const offY = b.y - t.y; + const s = snapMove({ x: nx + offX, y: ny + offY, w: b.w, h: b.h }, otherObjectBoxes(t)); + nx += s.dx; + ny += s.dy; + S.guides = s.guides.length ? s.guides : null; + } else { + S.guides = null; + } + t.x = nx; + t.y = ny; + } else if (S.textDrag.mode === "rotate") { + const st = S.textDrag; + const a1 = Math.atan2(pos0.y - st.cy, pos0.x - st.cx); + const a0 = Math.atan2(st.startY0 - st.cy, st.startX0 - st.cx); + let deg = st.rotation; + if (st.startX0 !== void 0) deg = st.rotation + (a1 - a0) * 180 / Math.PI; + if (S._shiftDown) deg = Math.round(deg / 15) * 15; + t.rotation = deg; + } else if (S.textDrag.mode === "scale") { + const dx = pos0.x - S.textDrag.anchor.x; + const dy = pos0.y - S.textDrag.anchor.y; + const d = Math.sqrt(dx * dx + dy * dy); + const f = d / Math.max(S.textDrag.d0, 1); + t.fontSize = clamp(Math.round(S.textDrag.fontSize * f), 8, 2e3); + } + renderObjects(); + } + return; + } + function onPenEditDragMove(pos0) { + const penShape = getPenEditingShape(); + if (penShape && penShape.pts[S.penDragPt]) { + penShape.pts[S.penDragPt].x = clamp(pos0.x, 0, S.imgW); + penShape.pts[S.penDragPt].y = clamp(pos0.y, 0, S.imgH); + renderObjects(); + } + return; + } + function onShapeDragMouseMove(pos0) { + const sh = getSelectedShape(); + if (sh) { + if (S.shapeDrag.mode === "move") { + const dx = pos0.x - S.shapeDrag.start.x; + const dy = pos0.y - S.shapeDrag.start.y; + const b = shapeBounds(S.shapeDrag.shape); + let cdx = clamp(dx, -b.x, Math.max(-b.x, S.imgW - (b.x + b.w))); + let cdy = clamp(dy, -b.y, Math.max(-b.y, S.imgH - (b.y + b.h))); + if (!S._altDown) { + const box = { x: b.x + cdx, y: b.y + cdy, w: b.w, h: b.h }; + const s = snapMove(box, otherObjectBoxes(sh)); + cdx += s.dx; + cdy += s.dy; + S.guides = s.guides.length ? s.guides : null; + } else { + S.guides = null; + } + if (sh.type === "pen") { + sh.pts = (S.shapeDrag.shape.pts || []).map((p) => ({ x: p.x + cdx, y: p.y + cdy })); + } else { + sh.x1 = S.shapeDrag.shape.x1 + cdx; + sh.y1 = S.shapeDrag.shape.y1 + cdy; + sh.x2 = S.shapeDrag.shape.x2 + cdx; + sh.y2 = S.shapeDrag.shape.y2 + cdy; + } + } else { + applyShapeHandle(sh, S.shapeDrag.handle, pos0); + } + renderObjects(); + } + return; + } + function onBrushDrawMove(pos) { + strokeSegment(S.startX, S.startY, pos.x, pos.y); + S.startX = pos.x; + S.startY = pos.y; + drawToolRing(pos); + } + function onEraserDrawMove(pos) { + eraseSegment(S.startX, S.startY, pos.x, pos.y); + S.startX = pos.x; + S.startY = pos.y; + drawToolRing(pos); + } + function onPenDrawMove(pos) { + if (S.penPath) { + S.penPath.preview = pos; + const first = S.penPath.pts[0]; + const nearStart = first && S.penPath.pts.length >= 3 && Math.hypot(pos.x - first.x, pos.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5); + S.penPath.nearStart = !!nearStart; + renderObjects(); + } + } + function onShapeDrawMove(pos) { + const temp = { + id: "temp", + type: S.tool, + x1: S.startX, + y1: S.startY, + x2: pos.x, + y2: pos.y, + color: S.color, + fillColor: S.shapeFillColor, + lw: Math.max(1, S.shapeLineWidth), + lineWidth: Math.max(1, S.shapeLineWidth), + fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false, + strokeOn: S.shapeStrokeOn !== false, + radius: S.tool === "rect" ? Math.max(0, S.shapeRadius) : 0, + opacity: 1, + visible: true + }; + renderObjects(temp); + } + function onCropDrawMove(pos) { + if (S.cropHandle) { + resizeCropRect(pos); + drawCropPreview(); + updateCropInfo(); + } else if (S.cropMoving && S.moveStart) { + const dx = pos.x - S.moveStart.x; + const dy = pos.y - S.moveStart.y; + const r = S.moveStart.rect; + const nx = r.x + dx; + const ny = r.y + dy; + S.cropRect = { x: nx, y: ny, w: r.w, h: r.h }; + drawCropPreview(); + updateCropInfo(); + } else { + drawCropPreview(S.startX, S.startY, pos.x, pos.y); + updateCropInfo(); + } + } + var DRAW_UP_HANDLERS = { + brush: onStrokeDrawUp, + eraser: onStrokeDrawUp, + crop: onCropDrawUp, + rect: onShapeDrawUp, + arrow: onShapeDrawUp, + circle: onShapeDrawUp + }; + function onMouseUp(e) { + if (S.marquee) { + endMarquee(); + return; + } + if (S.lassoPts) { + endLasso(); + return; + } + if (S.penDragPt >= 0) { + onPenEditMouseUp(); + return; + } + if (S.placingImage && S.placingHandle) { + onPlacementMouseUp(); + return; + } + if (S.panning) { + onPanMouseUp(); + return; + } + if (S.textDrag) { + onTextDragMouseUp(); + return; + } + if (S.bitmapDrag) { + onBitmapDragMouseUp(); + return; + } + if (S.shapeDrag) { + onShapeDragMouseUp(); + return; + } + if (!S.isDrawing) return; + S.isDrawing = false; + const pos = getPos(e); + const handler = Object.prototype.hasOwnProperty.call(DRAW_UP_HANDLERS, S.tool) ? DRAW_UP_HANDLERS[S.tool] : null; + if (handler) handler(pos); + } + function onPenEditMouseUp() { + const penShape = getPenEditingShape(); + const pending = S.penDragPending; + S.penDragPt = -1; + S.penDragPending = null; + S.penDragBase = null; + if (pending && penShape) { + const cur = snapshotState({ metaOnly: true }); + if (JSON.stringify(cur.shapes) !== JSON.stringify(pending.shapes)) { + pushHistory(S.history, pending); + S.redoStack = []; + } + } + return; + } + function onPlacementMouseUp() { + S.placingHandle = null; + S.placingStart = null; + drawPlacementPreview(); + return; + } + function onPanMouseUp() { + S.panning = false; + S.panStart = null; + updateCursor(); + return; + } + function onTextDragMouseUp() { + const pending = S.textDrag.pending; + if (pending) { + const cur = snapshotState({ metaOnly: true }); + if (JSON.stringify(cur.texts) !== JSON.stringify(pending.texts)) { + pushHistory(S.history, pending); + S.redoStack = []; + } + } + S.textDrag = null; + S.guides = null; + renderObjects(); + renderLayerPanel(); + return; + } + function onBitmapDragMouseUp() { + const pending = S.bitmapDrag.pending; + if (pending) { + const cur = snapshotState({ metaOnly: true }); + const before = pending.bitmaps.find((b) => b.id === S.selectedLayerId); + const after = cur.bitmaps.find((b) => b.id === S.selectedLayerId); + if (before && after && JSON.stringify([before.x, before.y, before.w, before.h]) !== JSON.stringify([after.x, after.y, after.w, after.h])) { + pushHistory(S.history, pending); + S.redoStack = []; + } + } + S.bitmapDrag = null; + S.guides = null; + renderObjects(); + renderLayerPanel(); + return; + } + function onShapeDragMouseUp() { + const pending = S.shapeDrag.pending; + if (pending) { + const cur = snapshotState({ metaOnly: true }); + if (JSON.stringify(cur.shapes) !== JSON.stringify(pending.shapes) || JSON.stringify(cur.texts) !== JSON.stringify(pending.texts)) { + pushHistory(S.history, pending); + S.redoStack = []; + } + } + S.shapeDrag = null; + S.guides = null; + renderObjects(); + renderLayerPanel(); + return; + } + function onStrokeDrawUp() { + endStroke(); + return; + } + function onCropDrawUp(pos) { + if (S.cropHandle) { + S.cropHandle = null; + drawCropPreview(); + updateCropInfo(); + return; + } + if (S.cropMoving) { + S.cropMoving = false; + S.moveStart = null; + drawCropPreview(); + updateCropInfo(); + return; + } + const r = applyConstraintDrag(S.startX, S.startY, pos.x, pos.y); + if (r.w > 2 && r.h > 2) { + S.cropRect = { x: r.x, y: r.y, w: r.w, h: r.h }; + showCropBar(); + drawCropPreview(); + updateCropInfo(); + } else { + clearOverlay(); + } + } + function onShapeDrawUp(pos) { + const len = Math.hypot(pos.x - S.startX, pos.y - S.startY); + const ok = S.tool === "rect" || S.tool === "circle" ? Math.abs(pos.x - S.startX) > 2 && Math.abs(pos.y - S.startY) > 2 : len > 3; + if (ok) { + saveSnapshot(); + const shape = { + id: "s" + Date.now() + Math.floor(Math.random() * 1e3), + type: S.tool, + x1: S.startX, + y1: S.startY, + x2: pos.x, + y2: pos.y, + color: S.color, + fillColor: S.shapeFillColor, + // null = 跟随描边色(改主色时整块跟着变) + lw: Math.max(1, S.shapeLineWidth), + fill: S.tool === "rect" || S.tool === "circle" ? !!S.rectFill : false, + strokeOn: S.shapeStrokeOn !== false, + radius: S.tool === "rect" ? Math.max(0, S.shapeRadius) : 0, + opacity: 1, + visible: true, + locked: false, + z: ++S.zCounter + }; + S.shapeLayers.push(shape); + renderObjects(); + renderLayerPanel(); + finishCreateTool("shape", shape.id); + return; + } + renderObjects(); + renderLayerPanel(); + } + function finishCreateTool(kind, id) { + if (["rect", "circle", "arrow", "pen"].indexOf(S.tool) < 0) return; + setTool("select"); + if (!id) return; + selectUnit(kind, id); + renderObjects(); + renderLayerPanel(); + } + function onWheel(e) { + if (!S.open) return; + if (e.target && e.target.closest && e.target.closest(".iwb-editor-tools")) return; + e.preventDefault(); + const rect = S.canvasWrap.getBoundingClientRect(); + const mx = e.clientX - rect.left; + const my = e.clientY - rect.top; + const factor = e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP; + zoomStep(factor, mx, my); + } + function updateAllUI() { + updateToolUI(); + updateColorUI(); + updateBrushUI(); + updateBrushParamUI(); + updateFillUI(); + updateZoomUI(); + hidePickerTip(); + runtime.el.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active")); + const freeBtn = runtime.el.querySelector('.iwb-editor-constraint-btn[data-ratio="free"]'); + if (freeBtn) freeBtn.classList.add("active"); + hideCropBar(); + updateCropInfo(); + hideTextInput(); + S.selectedTextId = null; + S.textDrag = null; + S.selectedShapeId = null; + S.shapeDrag = null; + renderLayerPanel(); + } + function updateZoomUI() { + const val = runtime.el.querySelector(".iwb-editor-zoom-val"); + if (val) val.textContent = Math.round(S.zoom * 100) + "%"; + updateStatusbar(); + } + function updateToolUI() { + runtime.el.querySelectorAll(".iwb-editor-tool").forEach((btn) => { + btn.classList.toggle("active", btn.dataset.tool === S.tool); + }); + updateCursor(); + renderOptionBar(); + updateStatusbar(); + } + function refreshBrushRing() { + if (!S.hoverPos) return; + if (S.tool !== "brush" && S.tool !== "eraser") return; + if (S.isDrawing) return; + drawToolRing(S.hoverPos); + } + function updateCursor() { + if (S.panning) { + S.drawCanvasCursor("grabbing"); + return; + } + if (S.spaceDown) { + S.drawCanvasCursor("grab"); + return; + } + if (S.tool === "hand") { + S.drawCanvasCursor("grab"); + return; + } + if (S.tool === "brush" || S.tool === "eraser") { + S.drawCanvasCursor("none"); + refreshBrushRing(); + return; + } + if (S.tool === "crop" && S.cropRect) { + S.drawCanvasCursor("crosshair"); + return; + } + S.drawCanvasCursor(S.tool === "text" ? "text" : S.tool === "select" ? "default" : "crosshair"); + } + S.drawCanvasCursor = function(cur) { + for (const layer of S.layers) { + layer.canvas.style.cursor = cur; + } + }; + function colorContext() { + const t = getSelectedText(); + if (t || S.tool === "text") return { kind: "text", text: t || null }; + const sh = getSelectedShape(); + if (sh) return { kind: sh.type === "arrow" ? "strokeOnly" : "shape", shape: sh }; + if (S.tool === "rect" || S.tool === "circle" || S.tool === "pen") return { kind: "shape", shape: null }; + return { kind: "strokeOnly", shape: null }; + } + function fillSlotOn() { + const ctx = colorContext(); + if (ctx.kind === "text") return true; + if (ctx.kind !== "shape") return false; + const sh = ctx.shape; + if (!sh) return true; + return sh.type === "rect" || sh.type === "circle" || sh.type === "pen" && !!sh.closed; + } + function strokeSlotCanBeNone() { + const ctx = colorContext(); + return ctx.kind === "shape" && fillSlotOn(); + } + function textColorSlots(t) { + const color = (t ? t.color : S.color) || S.color; + const strokeColor = (t ? t.strokeColor : S.textStrokeColor) || TEXT_DEFAULTS.strokeColor; + const sw = Number(t ? t.strokeWidth : S.textStrokeWidth) || 0; + const bgColor = (t ? t.bgColor : S.textBgColor) || TEXT_DEFAULTS.bgColor; + const bgFill = !!(t ? t.bgFill : S.textBgFill); + const bgAlpha = Number(t ? t.bgAlpha == null ? TEXT_DEFAULTS.bgAlpha : t.bgAlpha : S.textBgAlpha) || TEXT_DEFAULTS.bgAlpha; + return { + mode: "text", + stroke: color, + fill: strokeColor, + fillOn: sw > 0, + follow: false, + bg: bgColor, + bgOn: bgFill, + bgAlpha, + strokeName: "文字", + fillName: "描边", + bgName: "底色" + }; + } + function colorSlots() { + const ctx = colorContext(); + if (ctx.kind === "text") return textColorSlots(ctx.text); + const sh = ctx.shape; + const stroke = sh && sh.color || S.color; + const rawFill = sh ? sh.fillColor || null : S.shapeFillColor; + const fillOn = sh ? sh.type === "pen" ? !!sh.fill && !!sh.closed : !!sh.fill : S.tool === "pen" ? !!S.penFill : !!S.rectFill; + const strokeOn = ctx.kind !== "shape" ? true : sh ? sh.strokeOn !== false : S.shapeStrokeOn !== false; + return { + mode: ctx.kind === "shape" ? "shape" : "single", + stroke, + strokeOn, + fill: rawFill || stroke, + fillOn, + follow: !rawFill, + bg: null, + bgOn: false, + bgAlpha: 1, + strokeName: "描边", + fillName: "填充", + bgName: "底色" + }; + } + function activeColor() { + const sl = colorSlots(); + if (S.colorTarget === "bg") return sl.bg || sl.stroke; + if (S.colorTarget === "fill" && fillSlotOn()) return sl.fill || sl.stroke; + return sl.stroke; + } + function updateColorUI() { + const sl = colorSlots(); + const isText = sl.mode === "text"; + const second = isText ? true : fillSlotOn(); + if (S.colorTarget !== "stroke" && !second) S.colorTarget = "stroke"; + if (S.colorTarget === "bg" && !isText) S.colorTarget = "stroke"; + const pair = runtime.el.querySelector(".iwb-editor-color-pair"); + if (pair) pair.dataset.colorMode = isText ? "triple" : second ? "pair" : "single"; + const strokeBtn = runtime.el.querySelector('.iwb-editor-color-btn[data-color-slot="stroke"]'); + const fillBtn = runtime.el.querySelector('.iwb-editor-color-btn[data-color-slot="fill"]'); + const bgBtn = runtime.el.querySelector('.iwb-editor-color-btn[data-color-slot="bg"]'); + const strokeName = isText ? "文字" : S.tool === "brush" || S.tool === "eraser" ? "画笔" : "描边"; + if (strokeBtn) { + const dot = strokeBtn.querySelector("i"); + if (dot) dot.style.backgroundColor = sl.stroke; + strokeBtn.classList.toggle("active", S.colorTarget === "stroke"); + strokeBtn.classList.toggle("is-none", !isText && sl.strokeOn === false); + strokeBtn.title = isText ? `文字色 ${String(sl.stroke).toUpperCase()}:改文字本身的颜色(右边「描边」是字的外描边)` : sl.strokeOn === false ? "描边:无(只有填充)。点开选色会自动恢复描边" : second ? `描边色 ${String(sl.stroke).toUpperCase()}:形状描边也用这个值。点开色板调色,「无」= 去掉描边` : `${strokeName}色 ${String(sl.stroke).toUpperCase()}:点开色板调色`; + const popEl = runtime.el.querySelector(".iwb-editor-color-pop"); + strokeBtn.setAttribute("aria-expanded", String(!!(popEl && !popEl.hidden && S.colorTarget === "stroke"))); + } + if (fillBtn) { + const dot = fillBtn.querySelector("i"); + if (dot) dot.style.backgroundColor = sl.fill; + fillBtn.classList.toggle("is-none", !sl.fillOn); + fillBtn.classList.toggle("is-follow", sl.follow && sl.fillOn); + fillBtn.classList.toggle("active", S.colorTarget === "fill"); + const fc = String(sl.fill).toUpperCase(); + fillBtn.title = isText ? sl.fillOn ? `文字描边色 ${fc}:沿字形外沿描一圈。点开调色,「无」= 去掉描边` : "文字描边:无(描边宽度 0)。点开选色会自动给 6px 描边" : !sl.fillOn ? "填充:无(形状内部透明)。点开色板选色即可填充" : sl.follow ? "填充色:跟随描边色 " + fc + ",点开可单独指定" : "填充色 " + fc + ",点开调色"; + } + if (bgBtn) { + const dot = bgBtn.querySelector("i"); + if (dot) { + dot.style.backgroundColor = sl.bg || "transparent"; + dot.style.opacity = sl.bgOn ? String(sl.bgAlpha) : ""; + } + bgBtn.classList.toggle("is-none", !sl.bgOn); + bgBtn.classList.toggle("active", S.colorTarget === "bg"); + bgBtn.title = sl.bgOn ? `文本框底色 ${String(sl.bg || "").toUpperCase()}(${Math.round(sl.bgAlpha * 100)}% 不透明):垫在文字下面,「无」= 去掉底色` : "文本框底色:无(透明)。点开选色会自动开启底色"; + bgBtn.setAttribute("aria-expanded", String(!!(runtime.el.querySelector(".iwb-editor-color-pop:not([hidden])") && S.colorTarget === "bg"))); + } + runtime.el.querySelectorAll(".iwb-color-pop-tab").forEach((tab) => { + const slot = tab.dataset.colorSlot; + const isFill = slot === "fill"; + const isBg = slot === "bg"; + tab.classList.toggle("active", S.colorTarget === slot); + const dot = tab.querySelector("i"); + if (dot) { + dot.style.backgroundColor = isBg ? sl.bg || "transparent" : isFill ? sl.fill : sl.stroke; + if (isBg) dot.style.opacity = sl.bgOn ? String(sl.bgAlpha) : ""; + } + const label = tab.querySelector(".iwb-color-pop-tab-label"); + if (label) label.textContent = isBg ? "底色" : isFill ? isText ? "描边" : "填充" : strokeName; + tab.title = isBg ? "正在调文本框底色(垫在文字下面)" : isFill ? isText ? "正在调文字描边色(沿字形外沿)" : "正在调填充色(形状内部颜色)" : isText ? "正在调文字色(文字本身的颜色)" : "正在调描边色"; + if (isFill) { + tab.classList.toggle("is-none", !sl.fillOn); + tab.hidden = !second; + } + if (isBg) { + tab.classList.toggle("is-none", !sl.bgOn); + tab.hidden = !isText; + } + if (!isFill && !isBg) tab.classList.toggle("is-none", !isText && sl.strokeOn === false); + }); + const onBg = S.colorTarget === "bg" && isText; + const onFill = S.colorTarget === "fill" && second; + const onStroke = S.colorTarget === "stroke" && !isText && strokeSlotCanBeNone(); + const noneUsable = onBg || onFill || onStroke; + runtime.el.querySelectorAll("[data-color-none]").forEach((noneBtn) => { + noneBtn.hidden = false; + noneBtn.disabled = !noneUsable; + noneBtn.classList.toggle("is-disabled", !noneUsable); + noneBtn.classList.toggle("active", noneUsable && (onBg ? !sl.bgOn : onFill ? !sl.fillOn : !sl.strokeOn)); + noneBtn.title = noneUsable ? onBg ? "去色:文字后面完全透明(无底色)" : onStroke ? sl.strokeOn === false ? "当前已是无描边;点选颜色可恢复描边" : "去色:去掉形状外框,只留内部填充" : isText ? "去色:把描边宽度置 0,只留文字本身" : "去色:形状内部透明,只留描边" : isText && S.colorTarget === "stroke" ? "去色不可用:文字色去掉就等于把文字删了,要隐藏文字请用「清空标注」" : "去色不可用:这一格只有一种颜色,去掉就没有了"; + }); + const cur = activeColor(); + let matchPreset = false; + runtime.el.querySelectorAll(".iwb-editor-color[data-color]").forEach((s) => { + const on = (s.dataset.color || "").toLowerCase() === cur.toLowerCase(); + if (on) matchPreset = true; + s.classList.toggle("active", on); + }); + runtime.el.querySelectorAll(".iwb-editor-color-hex").forEach((el) => { + el.textContent = cur.toUpperCase(); + }); + runtime.el.querySelectorAll(".iwb-editor-color-hex-input").forEach((inp) => { + if (document.activeElement !== inp) inp.value = cur.toUpperCase(); + }); + runtime.el.querySelectorAll(".iwb-editor-color-panel-swatch").forEach((sw) => sw.classList.toggle("active", (sw.dataset.panelColor || "").toLowerCase() === cur.toLowerCase())); + const rgb = hexToRgb(cur); + const max = Math.max(rgb.r, rgb.g, rgb.b) / 255, min = Math.min(rgb.r, rgb.g, rgb.b) / 255; + const d = max - min; + let h = 0; + if (d) { + if (max === rgb.r / 255) h = 60 * ((rgb.g - rgb.b) / 255 / d % 6); + else if (max === rgb.g / 255) h = 60 * ((rgb.b - rgb.r) / 255 / d + 2); + else h = 60 * ((rgb.r - rgb.g) / 255 / d + 4); + } + if (h < 0) h += 360; + const sat = max ? d / max : 0; + runtime.el.querySelectorAll(".iwb-color-sv").forEach((sv) => { + sv.style.backgroundColor = `hsl(${h} 100% 50%)`; + const m = sv.querySelector("span"); + if (m) { + m.style.left = sat * 100 + "%"; + m.style.top = (1 - max) * 100 + "%"; + } + }); + runtime.el.querySelectorAll(".iwb-color-hue").forEach((hue) => { + hue.dataset.hue = h; + const m = hue.querySelector("span"); + if (m) m.style.top = h / 360 * 100 + "%"; + }); + runtime.el.querySelectorAll(".iwb-editor-color-custom").forEach((custom) => { + custom.classList.toggle("active", !matchPreset); + const inp = custom.querySelector("input"); + if (inp) inp.value = cur; + }); + } + function updateBrushUI() { + syncOptionBar(); + } + function updateBrushParamUI() { + syncOptionBar(); + } + function updateFillUI() { + const b = runtime.el.querySelector('[data-action="toggleFill"]'); + if (b) b.classList.toggle("active", !!S.rectFill); + } + var TOOL_NAMES = { + select: "选择 / 移动", + marquee: "框选", + lasso: "套索", + brush: "画笔", + eraser: "橡皮", + pen: "钢笔", + text: "文字", + rect: "矩形", + circle: "圆形", + arrow: "箭头", + picker: "吸管", + hand: "抓手", + crop: "裁剪" + }; + var OPT_HINTS = { + crop: "裁剪栏在画布下方;裁剪与选区互斥,确认后可 Ctrl+Z 撤销", + select: "点击选中元素,拖拽移动,手柄缩放", + picker: "点击画布取色;选中形状/文字时取色直接改它的颜色,取完自动切回上一个工具", + hand: "拖拽平移画布;任意工具下按住空格也可以", + marquee: "拖出选区 → 操作条就在选区旁边", + lasso: "按住拖动画圈,松手闭合" + }; + function rangeOpt(key, label, min, max, value, unit) { + return `${label} + + ${unit ? `${unit}` : ""}`; + } + function presetDots(key, values) { + return `${values.map((v) => ``).join("")}`; + } + function cropOptionHTML() { + const c = S.cropConstraint; + const sizeOn = c.type === "size"; + return `比例 + 自由 + 1:1 + 4:3 + 3:4 + 16:9 + 9:16 + 尺寸 + + × + + 启用尺寸 + 应用 + -- + ✓ 确认 + ✗ 取消 + 拖出裁剪框;Enter 确认 · Esc 取消;裁剪后可 Ctrl+Z`; + } + function shapeColorHTML(sh, owner) { + const sl = colorSlots(); + let html = `描边`; + if (owner) { + html += `填充`; + } + return html; + } + function fillStyleHTML(owner, sh) { + const own = !!sh && (owner === "pen" ? sh.type === "pen" : sh.type === "rect" || sh.type === "circle"); + const fill = own ? !!sh.fill : owner === "pen" ? S.penFill : S.rectFill; + return `样式 + 描边 + 实心`; + } + var SHAPE_NAMES = { rect: "矩形", circle: "圆形", arrow: "箭头", pen: "钢笔路径" }; + var TEXT_STYLE_STATE_KEY = { + fontWeight: "textWeight", + fontFamily: "textFamily", + align: "textAlign", + lineHeight: "textLineHeight", + strokeWidth: "textStrokeWidth", + strokeColor: "textStrokeColor", + bgFill: "textBgFill", + bgColor: "textBgColor" + }; + function textStyleValues(t) { + const pick = (objKey, stateKey, dflt) => { + const raw = t ? t[objKey] : S[stateKey]; + return raw == null ? dflt : raw; + }; + return { + fontWeight: String(pick("fontWeight", "textWeight", "bold")), + // 字体走 fontKeyOf 收敛:老对象没有 fontFamily,或存了不认识的 key,都落回默认黑体 + fontFamily: fontKeyOf({ fontFamily: pick("fontFamily", "textFamily", "sans") }), + align: pick("align", "textAlign", "left"), + lineHeight: Number(pick("lineHeight", "textLineHeight", TEXT_LINE_HEIGHT)) || TEXT_LINE_HEIGHT, + strokeWidth: Math.max(0, Number(pick("strokeWidth", "textStrokeWidth", TEXT_DEFAULTS.strokeWidth)) || 0), + strokeColor: pick("strokeColor", "textStrokeColor", TEXT_DEFAULTS.strokeColor), + bgFill: !!pick("bgFill", "textBgFill", TEXT_DEFAULTS.bgFill), + bgColor: pick("bgColor", "textBgColor", TEXT_DEFAULTS.bgColor), + bgAlpha: Number(pick("bgAlpha", "textBgAlpha", TEXT_DEFAULTS.bgAlpha)) || TEXT_DEFAULTS.bgAlpha + }; + } + function textStyleHTML(t) { + const v = textStyleValues(t); + const wBtn = (val, label, title) => `${label}`; + const aBtn = (val, label, title) => `${label}`; + return ` + 字体 + ${TEXT_FONT_KEYS.map((k) => `${TEXT_FONTS[k].label}`).join("")} + 字重${wBtn("normal", "常规", "常规字重")}${wBtn("bold", "粗", "粗体(默认)")}${wBtn("900", "特粗", "特粗,封面标题用")} + 对齐${aBtn("left", "左", "多行时按左缘对齐")}${aBtn("center", "中", "多行时居中")}${aBtn("right", "右", "多行时按右缘对齐")} + 行距 + % + + 描边 + px + + 底色 + `; + } + var SELCMD_SVGS = { + all: '', + invert: '', + none: '' + }; + var selCmdHTML = () => ` + ${SELCMD_SVGS.all} + ${SELCMD_SVGS.invert} + ${SELCMD_SVGS.none}`; + function selectOptionHTML() { + const sh = getSelectedShape(); + if (sh) { + const t = sh.type; + if (t === "rect" || t === "circle" || t === "pen" || t === "arrow") { + const owner = t === "pen" ? "pen" : "rect"; + const lw = Math.max(1, Math.round(sh.lw || S.shapeLineWidth)); + return `已选中:${SHAPE_NAMES[t] || t}` + rangeOpt("shapeLineWidth", "线宽", 1, 60, lw, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (t === "rect" ? rangeOpt("shapeRadius", "圆角", 0, 200, Math.round(sh.radius || 0), "px") : "") + shapeColorHTML(sh, t === "arrow" ? null : owner) + (t === "arrow" ? "" : fillStyleHTML(owner, sh)) + (t === "pen" && !sh.closed ? '这条钢笔路径未闭合,实心不生效;点回起点闭合后即可填充' : ""); + } + } + const text = getSelectedText(); + if (text) { + return `已选中:文字` + rangeOpt("textSize", "字号", 8, 400, Math.round(text.fontSize || S.textSize), "px") + textStyleHTML(text) + '双击改内容 · 拖动手柄缩放 · 左上三格 = 文字色 / 描边 / 底色'; + } + return `当前工具:选择 / 移动` + selCmdHTML() + '点中矩形/圆形/钢笔/文字后,这里出现它的描边、实心与粗细'; + } + function optionBarHTML(tool) { + if (tool === "crop") return cropOptionHTML(); + if (tool === "select") return selectOptionHTML(); + if (tool === "brush" || tool === "eraser") { + return rangeOpt("brushSize", "大小", 1, 300, S.brushSize, "") + presetDots("brushSize", [2, 4, 8, 12]) + `硬度 + + ${S.brushHardness} + 透明 + + ${Math.round(S.brushOpacity * 100)}%` + presetDots("brushHardness", [0, 25, 50, 75, 100]); + } + if (tool === "rect" || tool === "circle") { + return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + (tool === "rect" ? rangeOpt("shapeRadius", "圆角", 0, 200, S.shapeRadius, "px") : "") + shapeColorHTML(null, "rect") + fillStyleHTML("rect"); + } + if (tool === "arrow") { + return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + shapeColorHTML(null, null) + '拖出箭头,松手完成'; + } + if (tool === "pen") { + return rangeOpt("shapeLineWidth", "线宽", 1, 60, S.shapeLineWidth, "") + presetDots("shapeLineWidth", [1, 2, 3, 6, 10, 16, 24]) + shapeColorHTML(null, "pen") + fillStyleHTML("pen") + '逐点点击,点回起点闭合;闭合后可切换描边/实心'; + } + if (tool === "text") { + return rangeOpt("textSize", "字号", 8, 400, S.textSize, "px") + textStyleHTML(null) + '点画布输入文字,Enter 确认,Shift+Enter 换行'; + } + if (tool === "marquee") { + return `形状 + 矩形 + 椭圆 + 羽化 px` + selCmdHTML() + `${OPT_HINTS.marquee}`; + } + if (tool === "lasso") { + return `羽化 px` + selCmdHTML() + `${OPT_HINTS.lasso}`; + } + return `当前工具:${TOOL_NAMES[tool] || tool} + ${OPT_HINTS[tool] || "选区工具按 M / L;Ctrl+J 复制选区,Delete 清除当前层"}`; + } + function renderOptionBar(force) { + const body = runtime.el && runtime.el.querySelector(".iwb-editor-optionbar-body"); + if (!body) return; + const sig = S.tool + "|" + (S.selectedShapeId || "") + "|" + (S.selectedTextId || ""); + if (!force && body.dataset.sig === sig) { + syncOptionBar(); + return; + } + body.dataset.sig = sig; + body.dataset.tool = S.tool; + body.innerHTML = optionBarHTML(S.tool); + if (S.tool === "crop") updateCropInfo(); + syncOptionBar(); + } + function syncOptionBar() { + const body = runtime.el && runtime.el.querySelector(".iwb-editor-optionbar-body"); + if (!body) return; + const selShape = S.tool === "select" ? getSelectedShape() : null; + const selText = S.tool === "select" ? getSelectedText() : null; + const val = (key) => { + if (key === "brushSize") return S.brushSize; + if (key === "brushHardness") return S.brushHardness; + if (key === "brushOpacity") return Math.round(S.brushOpacity * 100); + if (key === "shapeLineWidth") return selShape ? Math.max(1, Math.round(selShape.lw || S.shapeLineWidth)) : S.shapeLineWidth; + if (key === "shapeRadius") return selShape && selShape.type === "rect" ? Math.round(selShape.radius || 0) : S.shapeRadius; + if (key === "textSize") return selText ? Math.round(selText.fontSize || S.textSize) : S.textSize; + if (key === "textLineHeight") return Math.round((selText ? Number(selText.lineHeight) || S.textLineHeight : S.textLineHeight) * 100); + if (key === "textStrokeWidth") return Math.round(selText ? Number(selText.strokeWidth) || 0 : S.textStrokeWidth); + if (key === "feather") return S.selectionFeather; + return ""; + }; + body.querySelectorAll("input[data-opt]").forEach((el) => { + if (document.activeElement === el) return; + const v = val(el.dataset.opt); + if (String(el.value) !== String(v)) el.value = v; + }); + body.querySelectorAll("[data-opt-val]").forEach((el) => { + const v = val(el.dataset.optVal); + el.textContent = el.dataset.optVal === "brushOpacity" ? v + "%" : v; + }); + body.querySelectorAll('[data-opt="shape"]').forEach((btn) => { + btn.classList.toggle("active", S.selectionKind === btn.dataset.value); + }); + body.querySelectorAll("[data-opt-toggle]").forEach((btn) => { + const owner = btn.dataset.fillOwner === "pen" ? "pen" : "rect"; + let cur = owner === "pen" ? S.penFill : S.rectFill; + if (selShape && (owner === "pen" ? selShape.type === "pen" : selShape.type === "rect" || selShape.type === "circle")) { + cur = !!selShape.fill; + } + btn.classList.toggle("active", !!cur === (btn.dataset.value === "fill")); + }); + const sv = textStyleValues(selText); + body.querySelectorAll("button[data-opt-text]").forEach((btn) => { + const k = btn.dataset.optText; + if (k === "bgFill") { + btn.classList.toggle("active", !!sv.bgFill); + btn.dataset.value = sv.bgFill ? "0" : "1"; + return; + } + btn.classList.toggle("active", String(sv[k]) === btn.dataset.value); + }); + body.querySelectorAll("[data-opt-color]").forEach((inp) => { + const k = inp.dataset.optColor; + if (document.activeElement !== inp) { + const v = sv[k]; + if (v && String(inp.value).toLowerCase() !== String(v).toLowerCase()) inp.value = v; + } + if (k === "strokeColor") inp.classList.toggle("is-off", !(sv.strokeWidth > 0)); + if (k === "bgColor") inp.classList.toggle("is-off", !sv.bgFill); + }); + body.querySelectorAll("[data-shape-color]").forEach((inp) => { + const kind = inp.dataset.shapeColor; + const sl = colorSlots(); + const v = kind === "fill" ? sl.fill : sl.stroke; + if (document.activeElement !== inp && v && String(inp.value).toLowerCase() !== String(v).toLowerCase()) inp.value = v; + if (kind === "fill") { + inp.classList.toggle("is-off", !sl.fillOn); + inp.title = sl.fillOn ? "填充色:与工具栏右下的填充色块是同一份" : "当前无填充(形状内部透明)。选色会自动切成实心,也可点工具栏填充色块选「无」"; + } else { + const off = sl.strokeOn === false; + inp.classList.toggle("is-off", off); + inp.title = off ? "当前无描边(只有填充)。选色会自动恢复描边,也可点工具栏描边色块选「无」" : "描边色:与工具栏左上的描边色块是同一份"; + } + }); + updateColorUI(); + } + function updateStatusbar() { + if (!runtime.el) return; + const put = (sel2, text) => { + const el = runtime.el.querySelector(sel2); + if (el && el.textContent !== text) el.textContent = text; + }; + put(".iwb-editor-status-zoom", Math.round(S.zoom * 100) + "%"); + put(".iwb-editor-status-size", S.imgW + "×" + S.imgH); + const p = S.lastPos; + put(".iwb-editor-status-pos", p ? "x " + Math.round(p.x) + " y " + Math.round(p.y) : "x — y —"); + const sel = S.selection && S.selection.active ? S.selection : null; + put(".iwb-editor-status-sel", sel ? "选区 " + Math.round(sel.bbox.w) + "×" + Math.round(sel.bbox.h) + (sel.feather ? " · 羽化 " + sel.feather : "") + (sel.inverted ? " · 反选" : "") : "无选区"); + const layer = S.layers.find((l) => l.id === S.activeLayerId); + put(".iwb-editor-status-layer", "当前层:" + (layer ? layer.name : "—")); + put(".iwb-editor-status-tool", TOOL_NAMES[S.tool] || S.tool); + } + var lwSnapDone = false; + var textSnapDone = false; + function applyShapeLineWidth(committed) { + const sh = getSelectedShape(); + if (!sh || sh.locked) { + lwSnapDone = false; + return; + } + if (committed || !lwSnapDone) { + saveSnapshot("线宽"); + lwSnapDone = true; + } + sh.lw = S.shapeLineWidth; + renderObjects(); + if (committed) lwSnapDone = false; + } + function applyTextSize(committed) { + const t = getSelectedText(); + if (!t || t.locked) { + textSnapDone = false; + return; + } + if (committed || !textSnapDone) { + saveSnapshot("字号"); + textSnapDone = true; + } + t.fontSize = S.textSize; + renderObjects(); + if (committed) textSnapDone = false; + } + var textStyleSnapDone = false; + function applyTextStyle(key, raw, committed) { + const stateKey = TEXT_STYLE_STATE_KEY[key]; + if (!stateKey) return; + let value = raw; + if (key === "bgFill") value = raw === true || raw === 1 || raw === "1" || raw === "true"; + else if (key === "fontFamily") value = fontKeyOf({ fontFamily: raw }); + else if (key === "lineHeight") value = clamp(Number(raw) || 125, 80, 300) / 100; + else if (key === "strokeWidth") value = clamp(Number(raw) || 0, 0, 40); + else if (key === "strokeColor" || key === "bgColor") value = String(raw || TEXT_DEFAULTS.bgColor).toLowerCase(); + else value = String(raw); + S[stateKey] = value; + if (key === "strokeColor" && !(Number(S.textStrokeWidth) > 0)) S.textStrokeWidth = 6; + if (key === "bgColor" && !S.textBgFill) S.textBgFill = true; + const t = getSelectedText(); + if (!t || t.locked) { + textStyleSnapDone = false; + syncOptionBar(); + return; + } + if (committed || !textStyleSnapDone) { + saveSnapshot("文字样式"); + textStyleSnapDone = true; + } + t[key] = value; + if (key === "strokeColor" && !(Number(t.strokeWidth) > 0)) t.strokeWidth = S.textStrokeWidth; + if (key === "bgColor" && !t.bgFill) t.bgFill = true; + renderObjects(); + if (key === "bgColor" || key === "strokeColor") syncOptionBar(); + if (committed) textStyleSnapDone = false; + } + var radiusSnapDone = false; + function applyShapeRadius(committed) { + const sh = getSelectedShape(); + if (!sh || sh.locked || sh.type !== "rect") { + radiusSnapDone = false; + return; + } + if (committed || !radiusSnapDone) { + saveSnapshot("圆角"); + radiusSnapDone = true; + } + sh.radius = S.shapeRadius; + renderObjects(); + if (committed) radiusSnapDone = false; + } + var textColorSnapDone = false; + function applyTextColor(key, color, opts) { + const skipHistory = !!(opts && opts.skipHistory); + const stateKey = TEXT_STYLE_STATE_KEY[key]; + if (!stateKey) return; + const hex = String(color || "").toLowerCase(); + if (!/^#[0-9a-f]{6}$/.test(hex)) return; + if (!skipHistory) rememberColor(hex); + S[stateKey] = hex; + if (key === "strokeColor" && !(Number(S.textStrokeWidth) > 0)) S.textStrokeWidth = 6; + if (key === "bgColor" && !S.textBgFill) S.textBgFill = true; + const t = getSelectedText(); + if (t && !t.locked) { + if (!skipHistory && !textColorSnapDone) { + saveSnapshot("文字颜色"); + textColorSnapDone = true; + } + t[key] = hex; + if (key === "strokeColor" && !(Number(t.strokeWidth) > 0)) t.strokeWidth = S.textStrokeWidth; + if (key === "bgColor" && !t.bgFill) t.bgFill = true; + renderObjects(); + } + updateColorUI(); + if (skipHistory) { + syncOptionBarSoon(); + return; + } + textColorSnapDone = false; + syncOptionBar(); + } + function applyColorNone() { + const sl = colorSlots(); + if (sl.mode === "text") { + if (S.colorTarget === "bg") applyTextStyle("bgFill", "0", true); + else if (S.colorTarget === "fill") applyTextStyle("strokeWidth", 0, true); + updateColorUI(); + syncOptionBar(); + return; + } + if (S.colorTarget === "stroke") { + applyStrokeNone(); + return; + } + applyShapeColor("none"); + } + function applyStrokeNone() { + if (!strokeSlotCanBeNone()) return; + S.colorTarget = "stroke"; + S.shapeStrokeOn = false; + const sh = getSelectedShape(); + if (sh && !sh.locked && sh.strokeOn !== false) { + saveSnapshot("无描边"); + sh.strokeOn = false; + if (!sh.fill && (sh.type === "rect" || sh.type === "circle" || sh.type === "pen" && sh.closed)) { + sh.fill = true; + if (sh.type === "pen") S.penFill = true; + else S.rectFill = true; + } + renderObjects(); + } + updateFillUI(); + updateColorUI(); + syncOptionBar(); + } + function applyShapeColor(kind, raw, opts) { + const skipHistory = !!(opts && opts.skipHistory); + const sh = getSelectedShape(); + const owner = sh ? sh.type === "pen" ? "pen" : "rect" : S.tool === "pen" ? "pen" : "rect"; + if (kind === "none") { + if (!fillSlotOn()) return; + S.colorTarget = "fill"; + if (owner === "pen") S.penFill = false; + else S.rectFill = false; + if (sh && !sh.locked && sh.fill) { + if (!skipHistory) saveSnapshot("无填充"); + sh.fill = false; + if (sh.strokeOn === false) { + sh.strokeOn = true; + S.shapeStrokeOn = true; + } + renderObjects(); + } + updateColorUI(); + syncOptionBar(); + return; + } + const hex = String(raw || "").toLowerCase(); + if (!/^#[0-9a-f]{6}$/.test(hex)) return; + if (kind === "stroke") { + S.colorTarget = "stroke"; + S.shapeStrokeOn = true; + applyColorChange(hex, opts); + if (skipHistory) syncOptionBarSoon(); + else syncOptionBar(); + return; + } + S.colorTarget = "fill"; + if (skipHistory) { + } else { + rememberColor(hex); + } + S.shapeFillColor = hex; + if (owner === "pen") S.penFill = true; + else S.rectFill = true; + updateFillUI(); + if (sh && !sh.locked) { + if (!skipHistory) saveSnapshot("填充颜色"); + sh.fillColor = hex; + sh.fill = owner === "pen" ? !!sh.closed : true; + renderObjects(); + } + updateColorUI(); + if (skipHistory) syncOptionBarSoon(); + else syncOptionBar(); + } + function applyPanelColor(color, opts) { + const sl = colorSlots(); + if (sl.mode === "text") { + if (S.colorTarget === "fill") { + applyTextColor("strokeColor", color, opts); + return; + } + if (S.colorTarget === "bg") { + applyTextColor("bgColor", color, opts); + return; + } + applyColorChange(color, opts); + if (opts && opts.skipHistory) syncOptionBarSoon(); + else syncOptionBar(); + return; + } + if (S.colorTarget === "fill" && fillSlotOn()) { + applyShapeColor("fill", color, opts); + return; + } + if (S.colorTarget === "fill") S.colorTarget = "stroke"; + applyColorChange(color, opts); + if (opts && opts.skipHistory) syncOptionBarSoon(); + else syncOptionBar(); + } + function setColorTarget(slot) { + S.colorTarget = slot === "fill" ? "fill" : slot === "bg" ? "bg" : "stroke"; + updateColorUI(); + } + var optionBarSyncRaf = 0; + function syncOptionBarSoon() { + if (optionBarSyncRaf) return; + optionBarSyncRaf = (typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16))(() => { + optionBarSyncRaf = 0; + syncOptionBar(); + }); + } + function setShapeFill(fill, owner) { + const isPen = owner === "pen"; + if (isPen) S.penFill = !!fill; + else S.rectFill = !!fill; + updateFillUI(); + updateColorUI(); + syncOptionBar(); + const sh = getSelectedShape(); + const types = isPen ? ["pen"] : ["rect", "circle"]; + if (sh && types.indexOf(sh.type) >= 0 && !sh.locked) { + saveSnapshot("填充"); + sh.fill = isPen ? !!S.penFill && !!sh.closed : !!S.rectFill; + if (!sh.fill && sh.strokeOn === false) { + sh.strokeOn = true; + S.shapeStrokeOn = true; + } + renderObjects(); + syncOptionBar(); + } + } + function swapShapeColors() { + const sh = getSelectedShape(); + if (!sh || sh.locked) return false; + if (sh.type === "arrow") { + toast("箭头只有描边色,没有可交换的填充色", "info"); + return true; + } + const canFill = sh.type === "rect" || sh.type === "circle" || sh.type === "pen" && !!sh.closed; + const strokeOn = sh.strokeOn !== false; + const fillOn = !!sh.fill; + const strokeColor = sh.color || S.color; + const fillColor = sh.fillColor || null; + if (!canFill && !fillOn) { + toast("这条路径没有可填内部,交换后什么都看不见", "info"); + return true; + } + if (!strokeOn && !fillOn) { + toast("描边与填充都是无色,没有可交换的颜色", "info"); + return true; + } + if (strokeOn && fillOn && !fillColor) { + toast("填充色正跟随描边色(两者同一个颜色),无需交换", "info"); + return true; + } + saveSnapshot("交换填充与描边色"); + sh.strokeOn = fillOn; + sh.fill = strokeOn && canFill; + S.shapeStrokeOn = fillOn; + if (sh.type === "pen") S.penFill = !!(sh.fill && sh.closed); + else if (sh.type === "rect" || sh.type === "circle") S.rectFill = !!sh.fill; + if (fillColor) { + sh.color = fillColor; + S.color = fillColor; + sh.fillColor = strokeColor; + S.shapeFillColor = strokeColor; + } + renderObjects(); + updateFillUI(); + updateColorUI(); + syncOptionBar(); + return true; + } + function setOptionFromControl(el, committed) { + const key = el && el.dataset ? el.dataset.opt : ""; + if (!key) return; + const n = Math.round(Number(el.value)); + const safe = Number.isFinite(n) ? n : 0; + if (key === "brushSize") { + S.brushSize = clamp(safe || 1, 1, 300); + updateBrushUI(); + updateBrushParamUI(); + refreshBrushRing(); + } else if (key === "brushHardness") { + S.brushHardness = clamp(safe, 0, 100); + updateBrushParamUI(); + } else if (key === "brushOpacity") { + S.brushOpacity = clamp(safe || 100, 5, 100) / 100; + updateBrushParamUI(); + if (S.strokeCanvas) S.strokeCanvas.style.opacity = S.brushOpacity; + } else if (key === "shapeLineWidth") { + S.shapeLineWidth = clamp(safe || 1, 1, 60); + applyShapeLineWidth(committed); + } else if (key === "textSize") { + S.textSize = clamp(safe || 32, 8, 400); + applyTextSize(committed); + } else if (key === "textLineHeight") { + applyTextStyle("lineHeight", safe || 125, committed); + } else if (key === "textStrokeWidth") { + applyTextStyle("strokeWidth", safe, committed); + } else if (key === "shapeRadius") { + S.shapeRadius = clamp(safe, 0, 400); + applyShapeRadius(committed); + } else if (key === "feather") { + S.selectionFeather = clamp(safe, 0, 20); + if (S.selection && S.selection.active) S.selection.feather = S.selectionFeather; + updateStatusbar(); + } + syncOptionBar(); + } + function togglePanelsCollapsed() { + const root = runtime.el; + if (!root) return; + const collapsed = !root.classList.contains("panels-collapsed"); + root.classList.toggle("panels-collapsed", collapsed); + const st = S.callbacks && S.callbacks.settings; + if (st && typeof st.set === "function") { + try { + st.set("panelsCollapsed", collapsed); + } catch (err) { + } + } + toast(collapsed ? "侧栏已收起" : "侧栏已展开", "info"); + } + function bindLiteUI() { + const root = runtime.el; + if (!root || root.dataset.liteBound === "1") return; + root.dataset.liteBound = "1"; + mountAdjustPanel(); + const closeMenus = () => { + const panel = root.querySelector(".iwb-editor-export-settings"); + if (panel) panel.classList.remove("open"); + const toggle = root.querySelector('[data-action="toggleExportSettings"]'); + if (toggle) toggle.setAttribute("aria-expanded", "false"); + }; + root.addEventListener("click", (e) => { + const adjReset = e.target.closest("[data-adj-reset]"); + if (adjReset) { + e.stopPropagation(); + if (!adjReset.disabled) resetAdjust(); + return; + } + const fxBtn = e.target.closest("[data-fx]"); + if (fxBtn) { + e.stopPropagation(); + applyQuickEffect(fxBtn.dataset.fx); + return; + } + const btn = e.target.closest("[data-more]"); + if (!btn) return; + e.stopPropagation(); + const key = btn.dataset.more; + if (key && key.indexOf("sel.") === 0) runCommand(key); + else if (key === "addBlankLayer") addBlankLayer(); + else if (key === "zoomFit") setZoomFit(); + else if (key === "reset") restoreAll(); + }); + root.querySelectorAll('[data-action="togglePanels"]').forEach((btn) => { + btn.addEventListener("mousedown", (e) => e.stopPropagation()); + btn.addEventListener("click", (e) => { + e.stopPropagation(); + togglePanelsCollapsed(); + closeMenus(); + }); + }); + const fxRangeOf = (e) => e.target && e.target.closest ? e.target.closest(".iwb-editor-fx-range") : null; + let adjSnapDone = false; + const adjRowOf = (el) => el && el.closest ? el.closest(".iwb-editor-adj-row") : null; + const adjBegin = () => { + if (S.adjust && S.adjust.source) return true; + return Boolean(ensureAdjustTarget()); + }; + const adjSyncTwin = (row, el) => { + const range = row.querySelector(".iwb-editor-adj-range"); + const num = row.querySelector(".iwb-editor-adj-val"); + if (!range || !num) return; + if (el === range) num.value = range.value; + else range.value = String(Number(num.value) || 0); + }; + root.addEventListener("input", (e) => { + const range = fxRangeOf(e); + if (range) { + e.stopPropagation(); + setEffectValue(parseFloat(range.value)); + return; + } + const adj = e.target.closest ? e.target.closest(".iwb-editor-adj-range") || e.target.closest(".iwb-editor-adj-val") : null; + if (!adj) return; + const row = adjRowOf(adj); + if (!row) return; + e.stopPropagation(); + if (!adjBegin()) return; + if (!adjSnapDone) { + saveSnapshot("图片调节"); + adjSnapDone = true; + } + adjSyncTwin(row, adj); + setAdjustValue(row.dataset.adj, adj.value, true); + }); + root.addEventListener("change", (e) => { + const range = fxRangeOf(e); + if (range) { + e.stopPropagation(); + if (S.renderAll) S.renderAll(); + return; + } + const adj = e.target.closest ? e.target.closest(".iwb-editor-adj-range") || e.target.closest(".iwb-editor-adj-val") : null; + if (!adj) return; + const row = adjRowOf(adj); + if (!row) return; + e.stopPropagation(); + if (!S.adjust || !S.adjust.source) return; + adjSyncTwin(row, adj); + setAdjustValue(row.dataset.adj, adj.value, false); + adjSnapDone = false; + }); + root.addEventListener("dblclick", (e) => { + const hit = e.target.closest ? e.target.closest(".iwb-editor-adj-name") || e.target.closest(".iwb-editor-adj-range") : null; + if (!hit) return; + const row = adjRowOf(hit); + if (!row) return; + e.stopPropagation(); + if (!S.adjust || !S.adjust.source) return; + saveSnapshot("调节归零"); + setAdjustValue(row.dataset.adj, 0, false); + syncAdjustControls(); + }); + const body = root.querySelector(".iwb-editor-optionbar-body"); + if (body) { + body.addEventListener("mousedown", (e) => e.stopPropagation()); + let nativeColorSnapped = false; + const nativeColorOf = (t) => t && t.closest ? t.closest("[data-shape-color]") || t.closest("[data-opt-color]") : null; + const applyNativeColor = (el, preview) => { + const isShape = el.hasAttribute("data-shape-color"); + const key = isShape ? el.dataset.shapeColor : el.dataset.optColor; + if (!nativeColorSnapped) { + const t = getSelectedText(), sh = getSelectedShape(); + if (t && !t.locked || sh && !sh.locked) { + saveSnapshot(isShape ? "填充颜色" : "文字颜色"); + nativeColorSnapped = true; + } + } + if (isShape) applyShapeColor(key, el.value, { skipHistory: true }); + else applyTextColor(key, el.value, { skipHistory: true }); + if (preview) { + syncOptionBarSoon(); + return; + } + if (nativeColorSnapped) rememberColor(String(el.value || "").toLowerCase()); + nativeColorSnapped = false; + syncOptionBar(); + }; + body.addEventListener("input", (e) => { + const colorEl = nativeColorOf(e.target); + if (colorEl) { + e.stopPropagation(); + applyNativeColor(colorEl, true); + return; + } + setOptionFromControl(e.target, false); + }); + body.addEventListener("change", (e) => { + const textSel = e.target && e.target.closest ? e.target.closest("select[data-opt-text]") : null; + if (textSel) { + e.stopPropagation(); + applyTextStyle(textSel.dataset.optText, textSel.value, true); + return; + } + const colorEl = nativeColorOf(e.target); + if (colorEl) { + e.stopPropagation(); + applyNativeColor(colorEl, false); + return; + } + setOptionFromControl(e.target, true); + }); + body.addEventListener("click", (e) => { + if (e.target && e.target.closest && e.target.closest("select[data-opt-text]")) return; + const textBtn = e.target.closest("button[data-opt-text]"); + if (textBtn) { + e.stopPropagation(); + const k = textBtn.dataset.optText; + applyTextStyle(k, textBtn.dataset.value, true); + syncOptionBar(); + return; + } + const shapeBtn = e.target.closest('[data-opt="shape"]'); + if (shapeBtn) { + e.stopPropagation(); + S.selectionKind = shapeBtn.dataset.value === "ellipse" ? "ellipse" : "rect"; + syncOptionBar(); + toast("选区形状:" + (S.selectionKind === "ellipse" ? "椭圆" : "矩形"), "info"); + return; + } + const toggle = e.target.closest("[data-opt-toggle]"); + if (toggle) { + e.stopPropagation(); + setShapeFill(toggle.dataset.value === "fill", toggle.dataset.fillOwner); + return; + } + const dot = e.target.closest("[data-opt-preset]"); + if (dot) { + e.stopPropagation(); + setOptionFromControl({ dataset: { opt: dot.dataset.optPreset }, value: dot.dataset.value }, true); + return; + } + const ratioBtn = e.target.closest("[data-ratio]"); + if (ratioBtn) { + e.stopPropagation(); + const ratio = parseRatio(ratioBtn.dataset.ratio); + body.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.toggle("active", b === ratioBtn)); + setConstraint(ratio > 0 ? "ratio" : "free", ratio > 0 ? ratio : 0, 0, 0); + return; + } + if (e.target.closest('[data-action="toggleSizeConstraint"]')) { + e.stopPropagation(); + if (S.cropConstraint.type === "size") { + setConstraint("free", 0, 0, 0); + } else { + const w = parseInt(body.querySelector(".iwb-editor-size-w").value, 10); + const h = parseInt(body.querySelector(".iwb-editor-size-h").value, 10); + if (w > 0 && h > 0) { + body.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active")); + setConstraint("size", w / h, w, h); + } + } + return; + } + if (e.target.closest('[data-action="applySize"]')) { + e.stopPropagation(); + const w = parseInt(body.querySelector(".iwb-editor-size-w").value, 10); + const h = parseInt(body.querySelector(".iwb-editor-size-h").value, 10); + if (w > 0 && h > 0) { + body.querySelectorAll(".iwb-editor-constraint-btn[data-ratio]").forEach((b) => b.classList.remove("active")); + setConstraint("size", w / h, w, h); + } + return; + } + if (e.target.closest('[data-action="confirmCrop"]')) { + e.stopPropagation(); + confirmCrop(); + return; + } + if (e.target.closest('[data-action="cancelCrop"]')) { + e.stopPropagation(); + cancelCrop(); + return; + } + }); + } + const modal = root.querySelector(".iwb-editor-modal") || root; + modal.addEventListener("mousedown", (e) => { + if (!e.target.closest(".iwb-editor-export-settings-wrap")) closeMenus(); + }, true); + } + var warnedMissing = /* @__PURE__ */ new Set(); + function bindIf(selector, type, handler, root) { + const el = (root || runtime.el).querySelector(selector); + if (!el) { + if (!warnedMissing.has(selector)) { + warnedMissing.add(selector); + console.warn("[IWB编辑器] 未找到元素,跳过绑定:" + selector); + } + return null; + } + el.addEventListener(type, handler); + return el; + } + function bindAll(selector, type, handler) { + const list = runtime.el.querySelectorAll(selector); + list.forEach((el) => el.addEventListener(type, handler)); + return list.length; + } + function bindEvents() { + bindToolButtons(); + bindColorPanel(); + bindColorPalette(); + bindFillToggle(); + bindZoomButtons(); + bindHistoryActions(); + bindLayerAddActions(); + bindExportActions(); + bindWheelZoom(); + bindTextInput(); + bindSideResize(); + bindGlobalListeners(); + } + function applySideWidth(w) { + if (!runtime.el) return S.sideWidth || SIDE_DEFAULT; + const cap = Math.min(SIDE_MAX, Math.max(SIDE_MIN, Math.floor((window.innerWidth || 1440) * 0.45))); + const v = Math.round(Math.min(cap, Math.max(SIDE_MIN, Number(w) || SIDE_DEFAULT))); + runtime.el.style.setProperty("--iwb-side-w", v + "px"); + S.sideWidth = v; + return v; + } + function loadSideWidth() { + const st = S.callbacks && S.callbacks.settings; + let w = 0; + if (st && typeof st.get === "function") { + try { + w = Number(st.get("sideWidth")) || 0; + } catch (e) { + } + } + return applySideWidth(w > 0 ? w : SIDE_DEFAULT); + } + function saveSideWidth() { + const st = S.callbacks && S.callbacks.settings; + if (st && typeof st.set === "function") { + try { + st.set("sideWidth", S.sideWidth); + } catch (e) { + } + } + } + function bindSideResize() { + const handle = runtime.el && runtime.el.querySelector("[data-side-resizer]"); + if (!handle) return; + let dragging = false; + let startX = 0; + let startW = 0; + const endDrag = () => { + if (!dragging) return; + dragging = false; + handle.classList.remove("is-dragging"); + document.body.style.cursor = ""; + document.body.style.userSelect = ""; + saveSideWidth(); + }; + handle.addEventListener("pointerdown", (e) => { + e.preventDefault(); + e.stopPropagation(); + dragging = true; + startX = e.clientX; + startW = S.sideWidth || SIDE_DEFAULT; + handle.classList.add("is-dragging"); + document.body.style.cursor = "col-resize"; + document.body.style.userSelect = "none"; + try { + handle.setPointerCapture(e.pointerId); + } catch (err) { + } + }); + handle.addEventListener("pointermove", (e) => { + if (!dragging) return; + applySideWidth(startW - (e.clientX - startX)); + }); + handle.addEventListener("pointerup", endDrag); + handle.addEventListener("pointercancel", endDrag); + handle.addEventListener("lostpointercapture", endDrag); + handle.addEventListener("dblclick", (e) => { + e.stopPropagation(); + applySideWidth(SIDE_DEFAULT); + saveSideWidth(); + }); + } + function bindToolButtons() { + runtime.el.querySelectorAll(".iwb-editor-tool").forEach((btn) => { + if (!btn.dataset.tool) return; + btn.addEventListener("mousedown", (e) => e.stopPropagation()); + btn.addEventListener("click", () => setTool(btn.dataset.tool)); + }); + } + function loadColorPopPinned() { + const st = S.callbacks && S.callbacks.settings; + let on = false; + if (st && typeof st.get === "function") { + try { + on = !!st.get("colorPopPinned"); + } catch (e) { + } + } + S.colorPopPinned = on; + syncPinUI(); + } + function setColorPopPinned(on) { + S.colorPopPinned = !!on; + const st = S.callbacks && S.callbacks.settings; + if (st && typeof st.set === "function") { + try { + st.set("colorPopPinned", S.colorPopPinned); + } catch (e) { + } + } + syncPinUI(); + } + function syncPinUI() { + if (!runtime.el) return; + runtime.el.querySelectorAll('[data-action="pinColorPop"]').forEach((btn) => { + btn.classList.toggle("active", !!S.colorPopPinned); + btn.setAttribute("aria-pressed", String(!!S.colorPopPinned)); + btn.title = S.colorPopPinned ? "已钉住:点画布不会收起色板(再点一次取消钉住)" : "钉住色板:一直开着,点画布也不收起(再点一次取消)"; + }); + } + function closeColorPop() { + const pop = runtime.el && runtime.el.querySelector(".iwb-editor-color-pop"); + if (!pop || pop.hidden) return false; + pop.hidden = true; + runtime.el.querySelectorAll('[data-action="toggleColorPop"]').forEach((btn) => { + btn.classList.remove("active"); + btn.setAttribute("aria-expanded", "false"); + }); + return true; + } + function positionColorPop() { + const pop = runtime.el && runtime.el.querySelector(".iwb-editor-color-pop"); + const btn = runtime.el && runtime.el.querySelector(`.iwb-editor-color-btn[data-color-slot="${S.colorTarget}"]`); + const modal = runtime.el && runtime.el.querySelector(".iwb-editor-modal"); + if (!pop || !btn || !modal || pop.hidden) return; + const mr = modal.getBoundingClientRect(); + const br = btn.getBoundingClientRect(); + const pr = pop.getBoundingClientRect(); + let left = br.left - mr.left - 10; + left = Math.min(Math.max(8, left), Math.max(8, mr.width - pr.width - 8)); + let top = br.top - mr.top - pr.height - 10; + if (top < 8) top = br.bottom - mr.top + 10; + pop.style.left = Math.round(left) + "px"; + pop.style.top = Math.round(top) + "px"; + } + function toggleColorPop(slot) { + const pop = runtime.el.querySelector(".iwb-editor-color-pop"); + if (!pop) return; + const want = slot === "fill" ? "fill" : slot === "bg" ? "bg" : "stroke"; + if (!pop.hidden && S.colorTarget === want) { + closeColorPop(); + return; + } + S.colorTarget = want; + if (pop.hidden) { + pop.hidden = false; + updateColorUI(); + positionColorPop(); + } else { + updateColorUI(); + positionColorPop(); + } + } + function bindColorPanel() { + const pop = runtime.el.querySelector(".iwb-editor-color-pop"); + const colorBtns = [...runtime.el.querySelectorAll('[data-action="toggleColorPop"]')]; + colorBtns.forEach((btn) => { + btn.addEventListener("mousedown", (e) => e.stopPropagation()); + btn.addEventListener("click", (e) => { + e.stopPropagation(); + toggleColorPop(btn.dataset.colorSlot); + }); + }); + if (pop) { + document.addEventListener("mousedown", (e) => { + if (S.colorPopPinned) return; + const onBtn = colorBtns.some((b) => b.contains(e.target)); + if (!pop.hidden && !pop.contains(e.target) && !onBtn) closeColorPop(); + }, true); + window.addEventListener("resize", positionColorPop); + } + runtime.el.querySelectorAll("[data-color-surface]").forEach((surface) => bindColorSurface(surface)); + } + function bindColorSurface(surface) { + const isPop = surface.classList.contains("iwb-editor-color-pop"); + surface.addEventListener("mousedown", (e) => e.stopPropagation()); + surface.addEventListener("click", (e) => { + const pin = e.target.closest('[data-action="pinColorPop"]'); + if (pin) { + e.stopPropagation(); + setColorPopPinned(!S.colorPopPinned); + return; + } + const tab = e.target.closest(".iwb-color-pop-tab[data-color-slot]"); + if (tab) { + e.stopPropagation(); + setColorTarget(tab.dataset.colorSlot); + if (isPop) positionColorPop(); + return; + } + const none = e.target.closest("[data-color-none]"); + if (none) { + e.stopPropagation(); + applyColorNone(); + return; + } + const sw = e.target.closest("[data-panel-color]"); + if (sw) { + e.stopPropagation(); + applyPanelColor(sw.dataset.panelColor); + } + }); + const hexInput = surface.querySelector(".iwb-editor-color-hex-input"); + if (hexInput) { + hexInput.addEventListener("change", () => { + if (/^#[0-9a-f]{6}$/i.test(hexInput.value)) applyPanelColor(hexInput.value); + }); + } + const palettePick = surface.querySelector('[data-action="palettePick"]'); + if (palettePick) { + palettePick.addEventListener("mousedown", (e) => e.stopPropagation()); + palettePick.addEventListener("click", () => { + closeColorPop(); + setTool("picker"); + }); + } + let dragSnapped = false; + const hasColorTarget = () => { + const t = getSelectedText(), sh = getSelectedShape(); + return !!(t && !t.locked || sh && !sh.locked); + }; + const setDragColor = (color) => { + if (!dragSnapped) { + if (hasColorTarget()) { + saveSnapshot(); + dragSnapped = true; + } + } + applyPanelColor(color, { skipHistory: true }); + }; + const sv = surface.querySelector(".iwb-color-sv"); + const hue = surface.querySelector(".iwb-color-hue"); + if (!sv || !hue) return; + const initHsv = (() => { + const { r, g, b } = hexToRgb(activeColor()); + const rr = r / 255, gg = g / 255, bb = b / 255; + const max = Math.max(rr, gg, bb), min = Math.min(rr, gg, bb), d = max - min; + let h = 0; + if (d) { + if (max === rr) h = 60 * ((gg - bb) / d % 6); + else if (max === gg) h = 60 * ((bb - rr) / d + 2); + else h = 60 * ((rr - gg) / d + 4); + } + if (h < 0) h += 360; + return { h, sat: max ? d / max : 0, val: max }; + })(); + let hueValue = initHsv.h; + let satValue = initHsv.sat; + let valValue = initHsv.val; + const hsvToHex = (h, sat, val) => { + const c = val * sat, x = c * (1 - Math.abs(h / 60 % 2 - 1)), m = val - c; + let r = 0, g = 0, b = 0; + if (h < 60) { + r = c; + g = x; + } else if (h < 120) { + r = x; + g = c; + } else if (h < 180) { + g = c; + b = x; + } else if (h < 240) { + g = x; + b = c; + } else if (h < 300) { + r = x; + b = c; + } else { + r = c; + b = x; + } + return rgbToHex(Math.round((r + m) * 255), Math.round((g + m) * 255), Math.round((b + m) * 255)); + }; + const pick = (target, e) => { + const r = target.getBoundingClientRect(); + const x = clamp((e.clientX - r.left) / r.width, 0, 1); + const y = clamp((e.clientY - r.top) / r.height, 0, 1); + if (target === hue) hueValue = y * 360; + else { + satValue = x; + valValue = 1 - y; + } + setDragColor(hsvToHex(hueValue, satValue, valValue)); + }; + const syncFromColor = () => { + const { r, g, b } = hexToRgb(activeColor()); + const rr = r / 255, gg = g / 255, bb = b / 255; + const max = Math.max(rr, gg, bb), min = Math.min(rr, gg, bb), d = max - min; + if (d > 0) { + let h = 0; + if (max === rr) h = 60 * ((gg - bb) / d % 6); + else if (max === gg) h = 60 * ((bb - rr) / d + 2); + else h = 60 * ((rr - gg) / d + 4); + if (h < 0) h += 360; + hueValue = h; + } + satValue = max ? d / max : 0; + valValue = max; + }; + const beginDrag = (target, e) => { + syncFromColor(); + dragSnapped = false; + pick(target, e); + }; + if (sv) { + sv.addEventListener("pointerdown", (e) => { + sv.setPointerCapture(e.pointerId); + beginDrag(sv, e); + }); + sv.addEventListener("pointermove", (e) => { + if (e.buttons) pick(sv, e); + }); + } + if (hue) { + hue.addEventListener("pointerdown", (e) => { + beginDrag(hue, e); + }); + hue.addEventListener("pointermove", (e) => { + if (e.buttons) pick(hue, e); + }); + } + } + function bindColorPalette() { + runtime.el.querySelectorAll(".iwb-editor-color[data-color]").forEach((s) => { + s.addEventListener("mousedown", (e) => e.stopPropagation()); + s.addEventListener("click", () => applyPanelColor(s.dataset.color)); + }); + const colorInput = runtime.el.querySelector(".iwb-editor-color-picker-input"); + if (colorInput) { + colorInput.addEventListener("mousedown", (e) => e.stopPropagation()); + colorInput.addEventListener("input", () => applyPanelColor(colorInput.value)); + } + } + function bindFillToggle() { + const fillBtn = runtime.el.querySelector('[data-action="toggleFill"]'); + if (fillBtn) fillBtn.addEventListener("mousedown", (e) => e.stopPropagation()); + fillBtn && fillBtn.addEventListener("click", () => { + S.rectFill = !S.rectFill; + updateFillUI(); + const sh = getSelectedShape(); + if (sh && (sh.type === "rect" || sh.type === "circle") && (S.tool === "rect" || S.tool === "circle" || S.tool === "select")) { + saveSnapshot(); + sh.fill = S.rectFill; + renderObjects(); + } + }); + } + function bindZoomButtons() { + bindIf('[data-action="zoomOut"]', "click", (e) => { + e.stopPropagation(); + zoomStep(1 / ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2); + }); + bindIf('[data-action="zoomIn"]', "click", (e) => { + e.stopPropagation(); + zoomStep(ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2); + }); + bindAll('[data-action="zoomFit"]', "click", (e) => { + e.stopPropagation(); + setZoomFit(); + }); + } + function bindHistoryActions() { + const undoBtn = runtime.el.querySelector('[data-action="undo"]'); + const redoBtn = runtime.el.querySelector('[data-action="redo"]'); + const resetBtn = runtime.el.querySelector('[data-action="reset"]'); + const restoreBtn = runtime.el.querySelector('[data-action="restore"]'); + undoBtn && undoBtn.addEventListener("mousedown", (e) => e.stopPropagation()); + redoBtn && redoBtn.addEventListener("mousedown", (e) => e.stopPropagation()); + resetBtn && resetBtn.addEventListener("mousedown", (e) => e.stopPropagation()); + restoreBtn && restoreBtn.addEventListener("mousedown", (e) => e.stopPropagation()); + undoBtn && undoBtn.addEventListener("click", undo); + redoBtn && redoBtn.addEventListener("click", redo); + resetBtn && resetBtn.addEventListener("click", resetDraw); + restoreBtn && restoreBtn.addEventListener("click", restoreOriginal); + } + function bindLayerAddActions() { + bindAll('[data-action="addBitmapLayer"]', "mousedown", (e) => e.stopPropagation()); + bindAll('[data-action="addBitmapLayer"]', "click", () => { + const fileInput = document.createElement("input"); + fileInput.type = "file"; + fileInput.accept = "image/*"; + fileInput.addEventListener("change", async () => { + const file = fileInput.files[0]; + if (!file) return; + const reader = new FileReader(); + reader.onload = async () => { + try { + const img = await loadImage(reader.result); + addBitmapLayer(img); + } catch (err) { + console.error("[IWB编辑器] 导入图层失败:", err); + } + }; + reader.readAsDataURL(file); + }); + fileInput.click(); + }); + bindAll('[data-action="addBlankLayer"]', "mousedown", (e) => e.stopPropagation()); + bindAll('[data-action="addBlankLayer"]', "click", () => { + addBlankLayer(); + }); + bindAll('[data-action="mergeLayers"]', "mousedown", (e) => e.stopPropagation()); + bindAll('[data-action="mergeLayers"]', "click", () => { + const r = mergeLayers(); + toast(r.msg, r.ok ? "success" : "warn"); + }); + bindAll('[data-action="mergeVisible"]', "mousedown", (e) => e.stopPropagation()); + bindAll('[data-action="mergeVisible"]', "click", () => { + const r = mergeVisibleLayers(); + toast(r.msg, r.ok ? "success" : "warn"); + }); + } + function bindExportActions() { + bindIf('[data-action="cancel"]', "click", close); + bindIf('[data-action="download"]', "click", () => exportResult("download")); + bindIf('[data-action="copyClipboard"]', "click", () => copyResult()); + bindIf('[data-action="newNode"]', "click", () => exportResult("newNode")); + bindIf('[data-action="replace"]', "click", () => exportResult("replace")); + } + function bindWheelZoom() { + S.canvasWrap.addEventListener("wheel", onWheel, { passive: false }); + } + function bindTextInput() { + const textInput = runtime.el.querySelector(".iwb-editor-text-input"); + if (!textInput) return; + textInput.addEventListener("mousedown", (e) => e.stopPropagation()); + const autosize = () => { + textInput.style.height = "auto"; + textInput.style.height = textInput.scrollHeight + 4 + "px"; + }; + textInput.addEventListener("input", autosize); + textInput.addEventListener("keydown", (e) => { + e.stopPropagation(); + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + commitTextInput(); + } else if (e.key === "Escape") { + e.preventDefault(); + hideTextInput(); + } + }); + } + function bindGlobalListeners() { + document.addEventListener("keydown", onKeydown, true); + document.addEventListener("keyup", onKeyup, true); + document.addEventListener("paste", onPaste, true); + window.addEventListener("blur", () => { + if (S.spaceDown) { + S.spaceDown = false; + updateCursor(); + } + if (S.panning) { + S.panning = false; + S.panStart = null; + updateCursor(); + } + S._shiftDown = false; + endAltPicker(); + }); + bindIf(".iwb-editor-modal", "mousedown", (e) => e.stopPropagation()); + } + function commitPenPath() { + if (!S.penPath || S.penPath.pts.length < 2) { + S.penPath = null; + renderObjects(); + return; + } + saveSnapshot(); + const shape = { id: "s" + Date.now() + Math.floor(Math.random() * 1e3), type: "pen", pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, fillColor: S.shapeFillColor, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penFill && !!S.penPath.closed, strokeOn: S.shapeStrokeOn !== false, opacity: 1, visible: true, locked: false, z: ++S.zCounter }; + S.shapeLayers.push(shape); + S.penPath = null; + renderObjects(); + renderLayerPanel(); + finishCreateTool("shape", shape.id); + } + function bindCanvasEvents() { + if (S._canvasEventsBound) return; + S._canvasEventsBound = true; + S.canvasStack.addEventListener("mousedown", onMouseDown); + S.canvasStack.addEventListener("mousemove", onMouseMove); + S.canvasStack.addEventListener("mousemove", onCanvasHover); + window.addEventListener("mouseup", onMouseUp); + S.canvasStack.addEventListener("contextmenu", (e) => { + e.preventDefault(); + if (S.open && !S.placingImage) showSelectionContext(e); + }); + S.canvasStack.addEventListener("mouseleave", () => { + if (S.placingImage) return; + S.hoverPos = null; + if ((S.tool === "brush" || S.tool === "eraser") && !S.isDrawing) clearToolRing(); + if (S.tool === "picker") hidePickerTip(); + }); + } + var CROP_CURSORS = { + nw: "nwse-resize", + se: "nwse-resize", + ne: "nesw-resize", + sw: "nesw-resize", + n: "ns-resize", + s: "ns-resize", + e: "ew-resize", + w: "ew-resize" + }; + var HOVER_HANDLERS = { + select: onHoverSelect, + marquee: onHoverCrosshair, + lasso: onHoverCrosshair, + picker: onHoverPicker, + hand: onHoverHand, + brush: onHoverBrushRing, + eraser: onHoverBrushRing, + crop: onHoverCrop, + text: onHoverText, + pen: onHoverCrosshair, + rect: onHoverShape, + arrow: onHoverShape, + circle: onHoverShape + }; + function onCanvasHover(e) { + if (S.placingImage) return; + if (S.panning || S.spaceDown) return; + if (S.isDrawing || S.textDrag || S.shapeDrag) return; + const p = getPos(e); + if (!S.lastPos || Math.abs(p.x - S.lastPos.x) > 0.5 || Math.abs(p.y - S.lastPos.y) > 0.5) { + S.lastPos = p; + updateStatusbar(); + } + S.hoverPos = p; + if (isOverRotationHandle(p)) { + S.drawCanvasCursor(ROT_CURSOR); + return; + } + const handler = Object.prototype.hasOwnProperty.call(HOVER_HANDLERS, S.tool) ? HOVER_HANDLERS[S.tool] : null; + if (handler) handler(p, e); + else S.drawCanvasCursor("crosshair"); + } + function onHoverSelect(p) { + const th = hitTextHandle(p); + if (th) { + S.drawCanvasCursor(th === "nw" || th === "se" ? "nwse-resize" : "nesw-resize"); + return; + } + const shh = hitShapeHandle(p); + if (shh) { + const sh = getSelectedShape(); + if (sh && sh.type === "rect" && CROP_CURSORS[shh]) S.drawCanvasCursor(CROP_CURSORS[shh]); + else S.drawCanvasCursor("move"); + return; + } + S.drawCanvasCursor(hitAnyObject(p) ? "move" : "default"); + } + function onHoverPicker(p, e) { + S.drawCanvasCursor("crosshair"); + showPickerTip(e, sampleColor(p)); + } + function onHoverHand() { + S.drawCanvasCursor("grab"); + } + function onHoverBrushRing(p) { + S.drawCanvasCursor("none"); + drawToolRing(p); + } + function onHoverCrop(p) { + if (S.cropRect) { + const h = hitCropHandle(p); + if (h && CROP_CURSORS[h]) { + S.drawCanvasCursor(CROP_CURSORS[h]); + return; + } + if (insideRect(p, S.cropRect)) { + S.drawCanvasCursor("move"); + return; + } + } + S.drawCanvasCursor("crosshair"); + } + function onHoverText(p) { + const h = hitTextHandle(p); + if (h) { + S.drawCanvasCursor(h === "nw" || h === "se" ? "nwse-resize" : "nesw-resize"); + return; + } + S.drawCanvasCursor(hitTextLayer(p) ? "move" : "text"); + } + function onHoverCrosshair() { + S.drawCanvasCursor("crosshair"); + } + function onHoverShape(p) { + const h = hitShapeHandle(p); + if (h) { + const sh = getSelectedShape(); + if (sh && sh.type === "rect" && CROP_CURSORS[h]) S.drawCanvasCursor(CROP_CURSORS[h]); + else S.drawCanvasCursor("move"); + return; + } + S.drawCanvasCursor("crosshair"); + } + function isTyping(e) { + const t = e.target; + if (!t) return false; + if (t.tagName === "TEXTAREA") return true; + if (t.tagName !== "INPUT") return false; + const cls = t.classList; + if (cls && (cls.contains("iwb-editor-text-input") || cls.contains("iwb-editor-color-hex-input"))) return true; + if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return false; + if (e.key === "Delete" || e.key === "Escape") return false; + return true; + } + function onKeydown(e) { + if (!S.open) return; + if (S.placingImage) { + if (e.key === "Enter") { + e.preventDefault(); + confirmImagePlacement(); + return; + } + if (e.key === "Escape") { + e.preventDefault(); + cancelImagePlacement(); + return; + } + } + if (e.key === "Shift") S._shiftDown = true; + if (e.key === "Alt" && !e.ctrlKey && !e.metaKey) { + e.preventDefault(); + beginAltPicker(); + return; + } + if (e.key === "Enter" && S.tool === "pen" && S.penPath) { + e.preventDefault(); + commitPenPath(); + return; + } + if (e.key === "Enter" && S.tool === "crop" && S.cropRect) { + e.preventDefault(); + confirmCrop(); + return; + } + if (e.key === "Escape") { + if (isTyping(e)) { + hideTextInput(); + return; + } + if (closeColorPop()) { + e.preventDefault(); + return; + } + if (S.tool === "crop" && S.cropRect) { + e.preventDefault(); + cancelCrop(); + return; + } + if (S.marquee || S.lassoPts || S.selection && S.selection.active) { + e.preventDefault(); + clearMarquee(); + return; + } + if (S.penPath) { + e.preventDefault(); + S.penPath = null; + renderObjects(); + return; + } + if (getPenEditingShape()) { + e.preventDefault(); + exitPenEdit(); + return; + } + if (S.selectedLayerId || S.selectedTextId || S.selectedShapeId || S.bitmapDrag || S.textDrag || S.shapeDrag) { + e.preventDefault(); + clearSelection(); + renderObjects(); + renderLayerPanel(); + } + return; + } + if (isTyping(e)) return; + const mod = e.ctrlKey || e.metaKey; + const key = String(e.key || "").toLowerCase(); + const letterTools = { + v: "select", + m: "marquee", + a: "lasso", + l: "arrow", + b: "brush", + e: "eraser", + p: "pen", + t: "text", + r: "rect", + o: "circle", + u: "rect", + c: "crop", + i: "picker", + h: "hand" + }; + if (!mod && !e.altKey && Object.prototype.hasOwnProperty.call(letterTools, key)) { + e.preventDefault(); + if (e.shiftKey && key === "u") { + const cycle = { rect: "circle", circle: "arrow", arrow: "rect" }; + setTool(cycle[S.tool] || "rect"); + } else if (e.shiftKey && key === "m") { + S.selectionKind = S.selectionKind === "ellipse" ? "rect" : "ellipse"; + setTool("marquee"); + toast("选区形状:" + (S.selectionKind === "ellipse" ? "椭圆" : "矩形"), "info"); + renderOptionBar(true); + } else { + setTool(letterTools[key]); + } + return; + } + if (!mod && !e.altKey && key === "tab") { + e.preventDefault(); + togglePanelsCollapsed(); + return; + } + if (!mod && !e.altKey && e.shiftKey && key === "x") { + if (swapShapeColors()) e.preventDefault(); + return; + } + const isBracket = e.key === "[" || e.key === "]" || e.code === "BracketLeft" || e.code === "BracketRight"; + if (!mod && !e.altKey && isBracket) { + e.preventDefault(); + const step = S.brushSize >= 64 ? 8 : S.brushSize >= 24 ? 4 : S.brushSize >= 8 ? 2 : 1; + S.brushSize = clamp(S.brushSize + (e.key === "]" ? step : -step), 1, 300); + syncOptionBar(); + updateCursor(); + refreshBrushRing(); + return; + } + if (mod && !e.shiftKey && e.key === "0") { + e.preventDefault(); + setZoomFit(); + return; + } + if (mod && !e.shiftKey && e.key === "1") { + e.preventDefault(); + setZoomActual(); + return; + } + if (mod && (e.key === "+" || e.key === "=")) { + e.preventDefault(); + zoomStep(ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2); + return; + } + if (mod && e.key === "-") { + e.preventDefault(); + zoomStep(1 / ZOOM_STEP, S.canvasWrap.clientWidth / 2, S.canvasWrap.clientHeight / 2); + return; + } + if (mod && key === "a") { + e.preventDefault(); + runCommand("sel.all"); + return; + } + if (mod && e.shiftKey && key === "i") { + e.preventDefault(); + runCommand("sel.invert"); + return; + } + if (mod && key === "d") { + e.preventDefault(); + runCommand("sel.none"); + return; + } + if (mod && key === "j") { + e.preventDefault(); + runCommand("sel.copy"); + return; + } + if (mod && key === "x" && S.selection && S.selection.active) { + e.preventDefault(); + runCommand("sel.cut"); + return; + } + if (mod && key === "e") { + e.preventDefault(); + const r = e.shiftKey ? mergeVisibleLayers() : mergeLayers(); + toast(r.msg, r.ok ? "success" : "warn"); + return; + } + if (mod && e.shiftKey && key === "n") { + e.preventDefault(); + addBlankLayer(); + return; + } + if (mod && !e.shiftKey && key === "o") { + e.preventDefault(); + const b = runtime.el && runtime.el.querySelector('[data-action="addBitmapLayer"]'); + if (b) b.click(); + return; + } + if (mod && key === "s") { + e.preventDefault(); + const b = runtime.el && runtime.el.querySelector('[data-action="download"]'); + if (b) b.click(); + return; + } + if (e.key === "Delete" || e.key === "Backspace") { + if (S.selection && S.selection.active && !S.selectedTextId && !S.selectedShapeId) { + e.preventDefault(); + runCommand("sel.delete"); + return; + } + if (S.selectedTextId) { + e.preventDefault(); + deleteSelectedText(); + renderLayerPanel(); + return; + } + if (S.selectedShapeId) { + e.preventDefault(); + deleteSelectedShape(); + renderLayerPanel(); + return; + } + if (S.selectedLayerId && S.selectedLayerId !== "base") { + e.preventDefault(); + deleteLayer(S.selectedLayerId); + renderLayerPanel(); + return; + } + } + if (e.code === "Space") { + e.preventDefault(); + if (!S.spaceDown) { + S.spaceDown = true; + updateCursor(); + } + return; + } + if (e.code === "BracketLeft" || e.code === "BracketRight") { + const up = e.code === "BracketRight"; + if (mod) { + e.preventDefault(); + moveLayer(e.shiftKey ? up ? "top" : "bottom" : up ? "up" : "down"); + return; + } + if (e.altKey) { + e.preventDefault(); + selectNeighborLayer(up); + return; + } + } + if (mod && key === "z") { + e.preventDefault(); + if (e.shiftKey) redo(); + else undo(); + return; + } + if (mod && key === "y") { + e.preventDefault(); + redo(); + return; + } + } + function onKeyup(e) { + if (e.key === "Shift") S._shiftDown = false; + if (e.key === "Alt") endAltPicker(); + if (e.code === "Space" && S.spaceDown) { + S.spaceDown = false; + updateCursor(); + } + } + function onPaste(e) { + if (!S.open) return; + const cd = e.clipboardData; + if (!cd) return; + const items = cd.items || []; + for (const item of items) { + if (item.kind === "file" && /^image\//.test(item.type)) { + const file = item.getAsFile(); + if (!file) continue; + e.preventDefault(); + e.stopImmediatePropagation(); + const reader = new FileReader(); + reader.onload = async () => { + try { + addBitmapLayer(await loadImage(reader.result)); + } catch (err) { + console.error("[IWB编辑器] 粘贴图层失败:", err); + } + }; + reader.readAsDataURL(file); + return; + } + } + if (isTyping(e)) return; + const html = typeof cd.getData === "function" ? cd.getData("text/html") || "" : ""; + if (html) { + const m = /]*\ssrc\s*=\s*["']([^"']+)["']/i.exec(html); + if (m) { + e.preventDefault(); + e.stopImmediatePropagation(); + pasteImageFromUrl(m[1]); + return; + } + } + const text = (typeof cd.getData === "function" ? cd.getData("text/plain") || "" : "").trim(); + if (/^(https?:\/\/\S+|data:image\/\S+)$/i.test(text)) { + e.preventDefault(); + e.stopImmediatePropagation(); + pasteImageFromUrl(text); + return; + } + } + async function pasteImageFromUrl(url) { + try { + let dataUrl = url; + if (!/^data:image\//i.test(url)) { + const resp = await fetch(url); + if (!resp.ok) throw new Error("HTTP " + resp.status); + const blob = await resp.blob(); + if (!/^image\//.test(blob.type)) throw new Error("链接不是图片(" + (blob.type || "未知类型") + ")"); + dataUrl = await new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result); + reader.onerror = () => reject(new Error("图片读取失败")); + reader.readAsDataURL(blob); + }); + } + addBitmapLayer(await loadImage(dataUrl)); + } catch (err) { + console.error("[IWB编辑器] 粘贴图片链接失败:", err); + toast("粘贴失败:" + (err && err.message || "无法读取剪贴板里的图片链接"), "error"); + } + } + + // image-annotate/plugin/editor/viewport.js + function syncOverlayCanvas() { + const pad = S.overlayPad || 0; + const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + const w = Math.round((S.imgW + pad * 2) * scale) + "px"; + const h = Math.round((S.imgH + pad * 2) * scale) + "px"; + for (const c of [S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) { + if (!c) continue; + c.style.left = "0px"; + c.style.top = "0px"; + c.style.width = w; + c.style.height = h; + } + } + function setupCanvas(img) { + purgeVectorCanvases(); + for (const layer of S.layers) { + if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas); + } + S.layers = []; + S.textCanvas.width = S.imgW; + S.textCanvas.height = S.imgH; + S.strokeCanvas.width = S.imgW; + S.strokeCanvas.height = S.imgH; + S.strokeCanvas.style.display = "none"; + S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18)); + computeFit(); + const uiK = overlayScale(); + for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) { + if (!c || !cx) continue; + c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK); + c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK); + resetOverlayTransform(cx); + } + const baseCanvas = createLayerCanvas(); + const baseCtx = baseCanvas.getContext("2d", { willReadFrequently: true }); + baseCtx.clearRect(0, 0, S.imgW, S.imgH); + baseCtx.drawImage(img, 0, 0); + S.layers.push({ + id: "base", + name: "原图", + canvas: baseCanvas, + ctx: baseCtx, + opacity: 1, + visible: true, + locked: true, + z: 0 + }); + S.activeLayerId = "base"; + S.zCounter = 1; + S.textCtx.clearRect(0, 0, S.imgW, S.imgH); + S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH); + clearOverlay(); + S.pickerComposite = null; + renderObjects(); + S.viewX = null; + applyView(); + renderLayerPanel(); + bindCanvasEvents(); + } + function resizeWorkspace(w, h) { + S.imgW = Math.max(1, Math.round(w)); + S.imgH = Math.max(1, Math.round(h)); + S.textCanvas.width = S.imgW; + S.textCanvas.height = S.imgH; + S.strokeCanvas.width = S.imgW; + S.strokeCanvas.height = S.imgH; + S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18)); + computeFit(); + const uiK = overlayScale(); + for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) { + if (!c || !cx) continue; + c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK); + c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK); + resetOverlayTransform(cx); + } + purgeVectorCanvases(); + for (const layer of S.layers) { + layer.canvas.width = S.imgW; + layer.canvas.height = S.imgH; + layer._bounds = void 0; + } + S.pickerComposite = null; + clearOverlay(); + S.viewX = null; + applyView(); + renderObjects(); + renderLayerPanel(); + } + function computeFit() { + const TOOLBAR_RESERVE = 72; + const availW = Math.max(50, S.canvasWrap.clientWidth - 48); + const availH = Math.max(50, S.canvasWrap.clientHeight - 48 - TOOLBAR_RESERVE); + const ratio = Math.min(availW / S.imgW, availH / S.imgH); + S.fitW = Math.max(1, S.imgW * ratio); + S.fitH = Math.max(1, S.imgH * ratio); + } + function applyView(anchor) { + const w = Math.round(S.fitW * S.zoom); + const h = Math.round(S.fitH * S.zoom); + for (const layer of S.layers) { + layer.canvas.style.width = w + "px"; + layer.canvas.style.height = h + "px"; + } + S.textCanvas.style.width = S.strokeCanvas.style.width = w + "px"; + S.textCanvas.style.height = S.strokeCanvas.style.height = h + "px"; + syncOverlayCanvas(); + const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + if (S.transparencyGrid) { + S.transparencyGrid.style.left = Math.round((S.overlayPad || 0) * scale) + "px"; + S.transparencyGrid.style.top = Math.round((S.overlayPad || 0) * scale) + "px"; + S.transparencyGrid.style.width = w + "px"; + S.transparencyGrid.style.height = h + "px"; + } + const pad = S.overlayPad || 0; + S.canvasStack.style.width = Math.round((S.imgW + pad * 2) * scale) + "px"; + S.canvasStack.style.height = Math.round((S.imgH + pad * 2) * scale) + "px"; + const layerOffset = Math.round(pad * scale); + for (const layer of S.layers) { + layer.canvas.style.left = layerOffset + "px"; + layer.canvas.style.top = layerOffset + "px"; + } + S.textCanvas.style.left = layerOffset + "px"; + S.textCanvas.style.top = layerOffset + "px"; + S.strokeCanvas.style.left = layerOffset + "px"; + S.strokeCanvas.style.top = layerOffset + "px"; + styleVectorViewport(w, h, layerOffset); + let left, top; + if (anchor && anchor.mx !== void 0) { + left = anchor.mx - anchor.px * S.zoom; + top = anchor.my - anchor.py * S.zoom; + } else if (S.viewX !== null) { + left = S.viewX; + top = S.viewY; + } else { + left = (S.canvasWrap.clientWidth - w) / 2; + top = (S.canvasWrap.clientHeight - h) / 2; + } + setView(left, top); + updateZoomUI(); + } + function setView(x, y) { + S.viewX = x; + S.viewY = y; + const stack = S.canvasStack; + const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + const pad = S.overlayPad || 0; + stack.style.transform = `translate3d(${Math.round(x - pad * scale)}px, ${Math.round(y - pad * scale)}px, 0)`; + } + function zoomStep(factor, mx, my) { + const nz = clamp(S.zoom * factor, ZOOM_MIN, ZOOM_MAX); + if (nz === S.zoom) return; + const px = (mx - (S.viewX || 0)) / S.zoom; + const py = (my - (S.viewY || 0)) / S.zoom; + S.zoom = nz; + applyView({ mx, my, px, py }); + } + function setZoomFit() { + computeFit(); + S.zoom = 1; + S.viewX = null; + applyView(); + } + function setZoomActual() { + computeFit(); + S.zoom = clamp(S.fitW ? S.imgW / S.fitW : 1, ZOOM_MIN, ZOOM_MAX); + S.viewX = null; + applyView(); + } + function clamp(v, min, max) { + return Math.max(min, Math.min(max, v)); + } + function rotPt(px, py, cx, cy, deg) { + if (!deg) return [px, py]; + const a = deg * Math.PI / 180, sn = Math.sin(a), cs = Math.cos(a); + const dx = px - cx, dy = py - cy; + return [cx + dx * cs - dy * sn, cy + dx * sn + dy * cs]; + } + function unrotPt(px, py, cx, cy, deg) { + return rotPt(px, py, cx, cy, -(deg || 0)); + } + function rotationHandlesLocal(b) { + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const d = 26 / Math.max(viewScale(), 1e-4); + return [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map((c) => { + const dx = c[0] - cx, dy = c[1] - cy, len = Math.hypot(dx, dy) || 1; + return [c[0] + dx / len * d, c[1] + dy / len * d]; + }); + } + function hitRotationHandle(lp, b) { + const pts = rotationHandlesLocal(b); + const R = 11 / Math.max(viewScale(), 1e-4); + for (const pt of pts) { + if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true; + } + return false; + } + function drawRotationHandles(ctx, b, rot) { + const cx = b.x + b.w / 2, cy = b.y + b.h / 2; + const pts = rotationHandlesLocal(b); + const k = Math.max(viewScale(), 1e-4); + const r = 6.5 / k; + const lw = 1.5 / k; + const ah = 3 / k; + const A0 = Math.PI * 0.2, A1 = Math.PI * 1.72; + ctx.save(); + ctx.strokeStyle = "#f0b34e"; + ctx.fillStyle = "#f0b34e"; + ctx.lineWidth = lw; + ctx.lineCap = "round"; + for (const pt of pts) { + const w = rotPt(pt[0], pt[1], cx, cy, rot || 0); + ctx.beginPath(); + ctx.arc(w[0], w[1], r, A0, A1); + ctx.stroke(); + const ex = w[0] + Math.cos(A1) * r, ey = w[1] + Math.sin(A1) * r; + const ta = A1 + Math.PI / 2; + ctx.beginPath(); + ctx.moveTo(ex + Math.cos(ta) * ah * 1.4, ey + Math.sin(ta) * ah * 1.4); + ctx.lineTo(ex + Math.cos(ta + 2.4) * ah, ey + Math.sin(ta + 2.4) * ah); + ctx.lineTo(ex + Math.cos(ta - 2.4) * ah, ey + Math.sin(ta - 2.4) * ah); + ctx.closePath(); + ctx.fill(); + } + ctx.restore(); + } + var ROT_CURSOR = `url("data:image/svg+xml;utf8,") 12 12, crosshair`; + function isOverRotationHandle(p) { + if (S.placingImage) { + const b = { x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h }; + const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, S.placingImage.rotation || 0); + return hitRotationHandle(lp, b); + } + const t = getSelectedText(); + if (t) { + const b = textBounds(t); + const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, t.rotation || 0); + return hitRotationHandle(lp, b); + } + const sh = getSelectedShape(); + if (sh) { + const b = shapeBounds(sh); + const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, sh.rotation || 0); + return hitRotationHandle(lp, b); + } + const layer = S.layers.find((l) => l.id === S.selectedLayerId && l.transformable); + if (layer) { + const lp = unrotPt(p.x, p.y, layer.x + layer.w / 2, layer.y + layer.h / 2, layer.rotation || 0); + return hitRotationHandle(lp, layer); + } + return false; + } + function boxCorners(x, y, w, h, rot) { + const cx = x + w / 2, cy = y + h / 2; + return [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map((pt) => rotPt(pt[0], pt[1], cx, cy, rot)); + } + function getPos(e) { + const rect = S.canvasStack.getBoundingClientRect(); + const pad = S.overlayPad || 0; + const scale = S.imgW ? S.fitW * S.zoom / S.imgW : 1; + return { + x: (e.clientX - rect.left) / Math.max(scale, 1e-4) - pad, + y: (e.clientY - rect.top) / Math.max(scale, 1e-4) - pad + }; + } + + // image-annotate/plugin/editor/crop.js + function setConstraint(type, ratio, sizeW, sizeH) { + S.cropConstraint = { type, ratio: ratio || 0, sizeW: sizeW || 0, sizeH: sizeH || 0 }; + const toggle = runtime.el && runtime.el.querySelector(".iwb-editor-size-toggle"); + if (toggle) { + const active = type === "size"; + toggle.classList.toggle("active", active); + toggle.setAttribute("aria-pressed", String(active)); + toggle.textContent = active ? "已启用" : "启用尺寸"; + } + if (S.cropRect) { + S.cropRect = applyConstraint(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h); + drawCropPreview(); + updateCropInfo(); + } + } + function applyConstraint(x, y, w, h) { + const c = S.cropConstraint; + if (c.type === "free" || !c.ratio || c.ratio <= 0) return { x, y, w, h }; + const ratio = c.ratio; + if (w / h > ratio) { + const nw = h * ratio; + const dx = (w - nw) / 2; + return { x: x + dx, y, w: nw, h }; + } else { + const nh = w / ratio; + const dy = (h - nh) / 2; + return { x, y: y + dy, w, h: nh }; + } + } + function applyConstraintDrag(x1, y1, x2, y2) { + const c = S.cropConstraint; + let rx = Math.min(x1, x2), ry = Math.min(y1, y2); + let rw = Math.abs(x2 - x1), rh = Math.abs(y2 - y1); + if (rw < 1) rw = 1; + if (rh < 1) rh = 1; + if (c.type === "free" || !c.ratio || c.ratio <= 0) return { x: rx, y: ry, w: rw, h: rh }; + const ratio = c.ratio; + if (rw / rh > ratio) { + rh = rw / ratio; + } else { + rw = rh * ratio; + } + return { x: rx, y: ry, w: rw, h: rh }; + } + function updateCropInfo() { + const info = runtime.el.querySelector(".iwb-editor-crop-info"); + if (!info) return; + if (S.cropRect) { + const w = Math.round(S.cropRect.w); + const h = Math.round(S.cropRect.h); + const c = S.cropConstraint; + if (c.type === "size" && c.sizeW > 0 && c.sizeH > 0) { + info.textContent = `${w}x${h} -> ${c.sizeW}x${c.sizeH}`; + } else { + info.textContent = `${w}x${h}`; + } + } else { + info.textContent = "--"; + } + } + function clearOverlay() { + const ctx = S.overlayCtx; + if (!ctx) return; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); + ctx.restore(); + resetOverlayTransform(ctx); + } + function drawCropPreview(x1, y1, x2, y2) { + const ctx = S.overlayCtx; + clearOverlay(); + let rx, ry, rw, rh; + if (x2 !== void 0) { + const r = applyConstraintDrag(x1, y1, x2, y2); + rx = r.x; + ry = r.y; + rw = r.w; + rh = r.h; + } else if (S.cropRect) { + rx = S.cropRect.x; + ry = S.cropRect.y; + rw = S.cropRect.w; + rh = S.cropRect.h; + } else { + return; + } + ctx.save(); + ctx.fillStyle = "rgba(0,0,0,0.45)"; + const cropPad = Math.max(S.imgW, S.imgH) * 2; + ctx.fillRect(-cropPad, -cropPad, S.imgW + cropPad * 2, S.imgH + cropPad * 2); + ctx.globalCompositeOperation = "destination-out"; + ctx.fillRect(rx, ry, rw, rh); + ctx.restore(); + ctx.save(); + ctx.strokeStyle = "#4488ff"; + ctx.lineWidth = 2 / viewScale(); + ctx.setLineDash([8 / viewScale(), 4 / viewScale()]); + ctx.strokeRect(rx, ry, rw, rh); + ctx.restore(); + if (S.cropRect && !S.cropHandle) drawCropHandles(rx, ry, rw, rh); + } + function cropHandlePoints(rx, ry, rw, rh) { + return { + nw: [rx, ry], + ne: [rx + rw, ry], + sw: [rx, ry + rh], + se: [rx + rw, ry + rh], + n: [rx + rw / 2, ry], + s: [rx + rw / 2, ry + rh], + e: [rx + rw, ry + rh / 2], + w: [rx, ry + rh / 2] + }; + } + function drawCropHandles(rx, ry, rw, rh) { + const ctx = S.overlayCtx; + const pts = cropHandlePoints(rx, ry, rw, rh); + const hs = 4 / viewScale(); + ctx.save(); + ctx.fillStyle = "#ffffff"; + ctx.strokeStyle = "#4488ff"; + ctx.lineWidth = 1.5 / viewScale(); + for (const name in pts) { + ctx.beginPath(); + ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2); + ctx.fill(); + ctx.stroke(); + } + ctx.restore(); + } + function insideRect(pos, rect) { + return pos.x >= rect.x && pos.x <= rect.x + rect.w && pos.y >= rect.y && pos.y <= rect.y + rect.h; + } + function hitCropHandle(pos) { + if (!S.cropRect) return null; + const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h); + const R = 12 / viewScale(); + let best = null, bestDist = 1e9; + for (const name in pts) { + const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1]; + const d = dx * dx + dy * dy; + if (d < R * R && d < bestDist) { + bestDist = d; + best = name; + } + } + return best; + } + function resizeCropRect(pos) { + if (!S.cropRect) return; + const { x, y, w, h } = S.cropRect; + const c = S.cropConstraint; + let nx = x, ny = y, nw = w, nh = h; + const hh = S.cropHandle; + if (c.type === "free" || !c.ratio || c.ratio <= 0) { + if (hh.includes("e")) nw = Math.max(4, pos.x - x); + if (hh.includes("s")) nh = Math.max(4, pos.y - y); + if (hh.includes("w")) { + const right = x + w; + nx = Math.min(pos.x, right - 4); + nw = right - nx; + } + if (hh.includes("n")) { + const bottom = y + h; + ny = Math.min(pos.y, bottom - 4); + nh = bottom - ny; + } + S.cropRect = { x: nx, y: ny, w: nw, h: nh }; + return; + } + const ratio = c.ratio; + if (hh === "e" || hh === "w") { + if (hh === "e") { + nw = Math.max(4, pos.x - x); + } else { + const right = x + w; + nx = Math.min(pos.x, right - 4); + nw = right - nx; + } + nh = nw / ratio; + } else if (hh === "n" || hh === "s") { + if (hh === "s") { + nh = Math.max(4, pos.y - y); + } else { + const bottom = y + h; + ny = Math.min(pos.y, bottom - 4); + nh = bottom - ny; + } + nw = nh * ratio; + } else { + if (hh === "se") { + nw = Math.max(4, pos.x - x); + nh = Math.max(4, pos.y - y); + } else if (hh === "ne") { + nw = Math.max(4, pos.x - x); + const bottom = y + h; + ny = Math.min(pos.y, bottom - 4); + nh = bottom - ny; + } else if (hh === "sw") { + const right = x + w; + nx = Math.min(pos.x, right - 4); + nw = right - nx; + nh = Math.max(4, pos.y - y); + } else if (hh === "nw") { + const right = x + w; + nx = Math.min(pos.x, right - 4); + nw = right - nx; + const bottom = y + h; + ny = Math.min(pos.y, bottom - 4); + nh = bottom - ny; + } + if (nw / nh > ratio) { + nh = nw / ratio; + if (hh === "ne" || hh === "nw") ny = y + h - nh; + } else { + nw = nh * ratio; + if (hh === "nw" || hh === "sw") nx = x + w - nw; + } + } + S.cropRect = { x: nx, y: ny, w: nw, h: nh }; + } + function confirmCrop() { + if (!S.cropRect) return; + const { x, y, w, h } = S.cropRect; + if (w < 2 || h < 2) { + cancelCrop(); + return; + } + const c = S.cropConstraint; + const sx = Math.round(x), sy = Math.round(y); + const sw = Math.max(1, Math.round(w)), sh = Math.max(1, Math.round(h)); + const isSize = c.type === "size" && c.sizeW > 0 && c.sizeH > 0; + const nw = isSize ? Math.max(1, Math.round(c.sizeW)) : sw; + const nh = isSize ? Math.max(1, Math.round(c.sizeH)) : sh; + if (nw === S.imgW && nh === S.imgH && sx === 0 && sy === 0) { + cancelCrop(); + return; + } + const oldW = S.imgW, oldH = S.imgH; + const scaleX = nw / sw, scaleY = nh / sh; + const srcX = Math.max(0, sx), srcY = Math.max(0, sy); + const srcW = Math.max(0, Math.min(oldW, sx + sw) - srcX); + const srcH = Math.max(0, Math.min(oldH, sy + sh) - srcY); + const dstX = (srcX - sx) * scaleX, dstY = (srcY - sy) * scaleY; + const dstW = srcW * scaleX, dstH = srcH * scaleY; + saveSnapshot("裁剪"); + disposeSelection(); + const staged = S.layers.map((layer) => { + const tmp = document.createElement("canvas"); + tmp.width = nw; + tmp.height = nh; + if (srcW > 0 && srcH > 0) { + try { + tmp.getContext("2d").drawImage(layer.canvas, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); + } catch (e) { + } + } + return tmp; + }); + resizeWorkspace(nw, nh); + S.layers.forEach((layer, i) => { + const tmp = staged[i]; + try { + layer.ctx.drawImage(tmp, 0, 0); + } catch (e) { + } + tmp.width = 0; + tmp.height = 0; + layer.x = 0; + layer.y = 0; + layer.w = nw; + layer.h = nh; + layer.rotation = 0; + layer.transformable = false; + layer.image = null; + layer.sourceCanvas = null; + layer._srcBox = null; + layer._bounds = void 0; + }); + S.textLayers = S.textLayers.map((t) => ({ + ...t, + x: (t.x - sx) * scaleX, + y: (t.y - sy) * scaleY, + fontSize: t.fontSize * scaleX + })); + S.shapeLayers = S.shapeLayers.map((s) => ({ + ...s, + ...s.type === "pen" ? { pts: (s.pts || []).map((p) => ({ x: (p.x - sx) * scaleX, y: (p.y - sy) * scaleY })) } : { + x1: (s.x1 - sx) * scaleX, + y1: (s.y1 - sy) * scaleY, + x2: (s.x2 - sx) * scaleX, + y2: (s.y2 - sy) * scaleY + }, + lw: Math.max(1, s.lw * (scaleX + scaleY) / 2) + })); + S.selectedTextId = null; + S.textDrag = null; + S.selectedShapeId = null; + S.shapeDrag = null; + S.selectedLayerId = null; + S.bitmapDrag = null; + S.zoom = 1; + S.cropRect = null; + S.cropHandle = null; + S.cropMoving = false; + S.moveStart = null; + updateCropInfo(); + if (S.renderAll) S.renderAll(); + toast("已裁剪为 " + nw + "×" + nh + "(Ctrl+Z 可撤销)", "success"); + } + function cancelCrop() { + S.cropRect = null; + S.cropHandle = null; + S.cropMoving = false; + S.moveStart = null; + clearOverlay(); + updateCropInfo(); + } + function showCropBar() { + } + function hideCropBar() { + } + + // image-annotate/plugin/editor/history.js + var snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 }; + function cloneVectors(arr) { + return JSON.parse(JSON.stringify(arr || [], (key, value) => { + if (key === "_canvas" || key === "_ctx") return void 0; + return value; + })); + } + function snapshotState(opts) { + const metaOnly = !!(opts && opts.metaOnly); + const bitmaps = S.layers.map((layer) => { + let data = null; + if (!metaOnly && needsPixelSnapshot(layer)) { + try { + data = layer.ctx.getImageData(0, 0, S.imgW, S.imgH); + } catch (e) { + } + if (data) { + snapshotStats.getImageDataCalls++; + snapshotStats.bytesWritten += data.data.byteLength; + } + } + return { + id: layer.id, + data, + // ---- 图层重建所需元数据(v1.1)---- + name: layer.name, + z: layer.z, + opacity: layer.opacity, + visible: layer.visible, + locked: !!layer.locked, + transformable: !!layer.transformable, + color: layer.color, + lineWidth: layer.lineWidth, + imageRef: layer.image || null, + sourceRef: layer.sourceCanvas || null, + sourceBox: layer._srcBox ? { ...layer._srcBox } : null, + x: layer.x, + y: layer.y, + w: layer.w, + h: layer.h, + rotation: layer.rotation || 0 + }; + }); + snapshotStats.snapshots++; + return { + imgW: S.imgW, + imgH: S.imgH, + activeLayerId: S.activeLayerId, + bitmaps, + texts: cloneVectors(S.textLayers), + shapes: cloneVectors(S.shapeLayers), + layerOrder: S.layers.map((l) => ({ id: l.id, name: l.name, z: l.z, opacity: l.opacity, visible: l.visible, locked: !!l.locked, x: l.x, y: l.y, w: l.w, h: l.h })) + }; + } + var HISTORY_MAX_ENTRIES = 50; + var HISTORY_MAX_BYTES = 128 * 1024 * 1024; + var HISTORY_MIN_BYTES = 32 * 1024 * 1024; + function historyBudgetBytes() { + const px = (S.imgW || 0) * (S.imgH || 0) * 4; + if (!px) return HISTORY_MAX_BYTES; + return Math.min(HISTORY_MAX_BYTES, Math.max(HISTORY_MIN_BYTES, px * 4)); + } + function stateBytes(state) { + let n = 0; + if (state && state.bitmaps) { + for (const b of state.bitmaps) { + if (b.data && b.data.data) n += b.data.data.byteLength; + } + } + if (state) { + n += state.texts ? JSON.stringify(state.texts).length * 2 : 0; + n += state.shapes ? JSON.stringify(state.shapes).length * 2 : 0; + } + return n; + } + function pushHistory(stack, state, label) { + state.__bytes = stateBytes(state); + if (label) state.__label = label; + stack.push(state); + const budget = historyBudgetBytes(); + let total = stack.reduce((sum, s) => sum + (s.__bytes || 0), 0); + while (stack.length > 1 && (stack.length > HISTORY_MAX_ENTRIES || total > budget)) { + total -= stack.shift().__bytes || 0; + } + return state; + } + function saveSnapshot(label) { + pushHistory(S.history, snapshotState(), label); + S.redoStack = []; + } + function recreateLayer(bm) { + const canvas = createLayerCanvas(); + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + return { + id: bm.id, + name: bm.name || "图层 " + bm.id, + canvas, + ctx, + opacity: bm.opacity == null ? 1 : bm.opacity, + visible: bm.visible !== false, + locked: !!bm.locked, + transformable: !!bm.transformable, + color: bm.color, + lineWidth: bm.lineWidth, + image: bm.imageRef || null, + sourceCanvas: bm.sourceRef || null, + _srcBox: bm.sourceBox || null, + x: bm.x, + y: bm.y, + w: bm.w, + h: bm.h, + rotation: bm.rotation || 0, + z: bm.z || 0 + }; + } + function releaseLayer(layer) { + try { + if (layer.canvas && layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas); + if (layer.canvas) { + layer.canvas.width = 0; + layer.canvas.height = 0; + } + } catch (e) { + } + } + function restoreState(state) { + if (state.imgW && state.imgH && (state.imgW !== S.imgW || state.imgH !== S.imgH)) { + purgeVectorCanvases(); + for (const l of S.layers) releaseLayer(l); + S.layers = []; + resizeWorkspace(state.imgW, state.imgH); + } + purgeVectorCanvases(); + for (const l of S.layers) l._bounds = void 0; + const snaps = state.bitmaps || []; + const want = new Set(snaps.map((b) => b.id)); + for (let i = S.layers.length - 1; i >= 0; i--) { + if (!want.has(S.layers[i].id)) { + releaseLayer(S.layers[i]); + S.layers.splice(i, 1); + } + } + const ordered = []; + for (const bm of snaps) { + let layer = S.layers.find((l) => l.id === bm.id); + if (!layer) { + layer = recreateLayer(bm); + S.layers.push(layer); + if (bm.data) { + try { + layer.ctx.putImageData(bm.data, 0, 0); + } catch (e) { + } + } else if (restorePath(layer) === "redraw") { + redrawBitmapLayer(layer); + } + } else { + layer.x = bm.x; + layer.y = bm.y; + layer.w = bm.w; + layer.h = bm.h; + layer.locked = !!bm.locked; + layer.rotation = bm.rotation || 0; + if (isDrawableLayer(layer)) { + layer._srcBox = null; + layer.sourceCanvas = null; + layer.rotation = 0; + layer.x = 0; + layer.y = 0; + layer.w = S.imgW; + layer.h = S.imgH; + layer._bounds = void 0; + } + if (restorePath(layer) === "redraw") { + redrawBitmapLayer(layer); + } else if (bm.data) { + try { + layer.ctx.clearRect(0, 0, S.imgW, S.imgH); + layer.ctx.putImageData(bm.data, 0, 0); + } catch (e) { + } + } + } + ordered.push(layer); + } + S.layers = ordered; + if (state.layerOrder) { + for (const meta of state.layerOrder) { + const layer = S.layers.find((l) => l.id === meta.id); + if (layer) { + layer.name = meta.name; + layer.z = meta.z; + layer.opacity = meta.opacity == null ? 1 : meta.opacity; + layer.visible = meta.visible !== false; + } + } + } + if (!S.layers.some((l) => l.id === S.activeLayerId)) S.activeLayerId = S.layers.length ? S.layers[S.layers.length - 1].id : null; + if (state.activeLayerId && S.layers.some((l) => l.id === state.activeLayerId)) S.activeLayerId = state.activeLayerId; + S.zCounter = Math.max(S.zCounter, ...S.layers.map((l) => l.z || 0), ...(state.texts || []).map((t) => t.z || 0), ...(state.shapes || []).map((s) => s.z || 0)); + S.textLayers = cloneVectors(state.texts); + S.shapeLayers = cloneVectors(state.shapes); + S.selectedTextId = null; + S.textDrag = null; + S.selectedShapeId = null; + S.shapeDrag = null; + S.selectedLayerId = null; + S.bitmapDrag = null; + S.penPath = null; + S.penEditId = null; + S.layerMulti.length = 0; + reorderLayerCanvas(); + updateLayerCanvasStyles(); + renderObjects(); + renderLayerPanel(); + updateCropInfo(); + } + function undo() { + if (S.placingImage) return; + if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return; + if (S.history.length === 0) { + toast("没有可撤销的操作"); + return; + } + pushHistory(S.redoStack, snapshotState()); + restoreState(S.history.pop()); + if (S.onHistoryRestore) S.onHistoryRestore(); + if (S.renderAll) S.renderAll(); + } + function redo() { + if (S.placingImage) return; + if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return; + if (S.redoStack.length === 0) { + toast("没有可重做的操作"); + return; + } + pushHistory(S.history, snapshotState()); + restoreState(S.redoStack.pop()); + if (S.onHistoryRestore) S.onHistoryRestore(); + if (S.renderAll) S.renderAll(); + } + function restoreAll() { + if (!S.originalImage) return; + const img = S.originalImage; + const ow = img.naturalWidth || img.width; + const oh = img.naturalHeight || img.height; + const sizeChanged = ow !== S.imgW || oh !== S.imgH; + if (sizeChanged) { + S.imgW = ow; + S.imgH = oh; + S.zoom = 1; + setupCanvas(img); + S.history = []; + S.redoStack = []; + clearAllEditState(); + updateAllUI(); + if (S.renderAll) S.renderAll(); + toast("已还原为原图(裁剪后的画布尺寸已复位)", "success"); + return; + } + saveSnapshot("还原原图"); + const base = S.layers.find((l) => l.id === "base"); + for (const layer of S.layers) { + if (layer !== base) releaseLayer(layer); + } + if (base) { + base.ctx.clearRect(0, 0, S.imgW, S.imgH); + base.ctx.drawImage(img, 0, 0); + base.locked = true; + base.visible = true; + base.opacity = 1; + base.z = 0; + } + S.layers = base ? [base] : []; + S.activeLayerId = base ? "base" : null; + S.zCounter = 1; + clearAllEditState(); + if (S.renderAll) S.renderAll(); + renderLayerPanel(); + hideTextInput(); + toast("已还原为原图,Ctrl+Z 可撤销", "success"); + } + function clearAllEditState() { + S.textLayers = []; + S.selectedTextId = null; + S.textDrag = null; + S.textEditingId = null; + S.shapeLayers = []; + S.selectedShapeId = null; + S.shapeDrag = null; + S.selectedLayerId = null; + S.bitmapDrag = null; + S.penPath = null; + S.penEditId = null; + S.layerMulti.length = 0; + S.cropRect = null; + S.cropHandle = null; + S.cropMoving = false; + S.moveStart = null; + S.selection = null; + S.marquee = null; + S.lassoPts = null; + S.pickerComposite = null; + clearOverlay(); + updateCropInfo(); + reorderLayerCanvas(); + updateLayerCanvasStyles(); + renderObjects(); + } + function resetDraw() { + restoreAll(); + } + function restoreOriginal() { + restoreAll(); + } + + // image-annotate/plugin/editor/export.js + var DEFAULT_EXPORT = Object.freeze({ + preset: "original", + // original | ecom800 + format: "png", + // png | jpeg | webp + bg: "transparent", + // transparent | white + maxKB: 0, + // 0 = 不限 + size: 800 + // 预设输出边长 + }); + var SETTINGS_KEY = { + preset: "exportPreset", + format: "exportFormat", + bg: "exportBg", + maxKB: "exportMaxKB", + size: "exportSize" + }; + function settings() { + return S.callbacks && S.callbacks.settings; + } + function effectiveBg(o) { + o = o || S.exportOptions || DEFAULT_EXPORT; + return o.bg === "white" || o.format === "jpeg" ? "white" : "transparent"; + } + function exportSignature(o) { + o = o || S.exportOptions || DEFAULT_EXPORT; + const ecom = o.preset === "ecom800"; + return [o.preset, o.format, ecom ? o.size : "orig", effectiveBg(o), ecom ? o.maxKB : 0].join(":"); + } + function loadExportOptions() { + const st = settings(); + const get = (k, d) => { + let v = d; + if (st && typeof st.get === "function") { + try { + const got = st.get(SETTINGS_KEY[k]); + if (got !== void 0 && got !== null) v = got; + } catch (e) { + } + } + return v; + }; + const preset = get("preset", DEFAULT_EXPORT.preset) === "ecom800" ? "ecom800" : "original"; + const format = ["png", "jpeg", "webp"].indexOf(get("format", DEFAULT_EXPORT.format)) >= 0 ? get("format", DEFAULT_EXPORT.format) : "png"; + const rawMax = get("maxKB", null); + const rawSize = get("size", null); + S.exportOptions = { + preset, + format, + // JPG 下背景直接收敛到白底,状态本身自洽,不靠 UI 撒谎 + bg: format === "jpeg" ? "white" : get("bg", DEFAULT_EXPORT.bg) === "white" ? "white" : "transparent", + maxKB: preset === "ecom800" ? rawMax === null ? 500 : Math.max(0, Number(rawMax) || 0) : 0, + size: Math.max(64, Number(rawSize === null ? 800 : rawSize) || 800) + }; + renderExportUI(); + } + function setExportOption(key, value) { + if (!S.exportOptions) loadExportOptions(); + const o = S.exportOptions; + const st = settings(); + const persist = (k, v) => { + if (st && typeof st.set === "function") { + try { + st.set(SETTINGS_KEY[k], v); + } catch (e) { + } + } + }; + if (key === "preset") { + o.preset = value === "ecom800" ? "ecom800" : "original"; + o.maxKB = o.preset === "ecom800" ? 500 : 0; + persist("preset", o.preset); + persist("maxKB", o.maxKB); + } else if (key === "format") { + o.format = ["png", "jpeg", "webp"].indexOf(value) >= 0 ? value : "png"; + persist("format", o.format); + if (o.format === "jpeg" && o.bg !== "white") { + o.bg = "white"; + persist("bg", "white"); + toast("JPG 不支持透明背景,已切换为白底", "info"); + } + } else if (key === "bg") { + if (o.format === "jpeg") { + renderExportUI(); + return; + } + o.bg = value === "white" ? "white" : "transparent"; + persist("bg", o.bg); + } else if (key === "maxKB") { + o.maxKB = Math.max(0, Number(value) || 0); + persist("maxKB", o.maxKB); + } else if (key === "size") { + o.size = Math.max(64, Number(value) || 800); + persist("size", o.size); + } + renderExportUI(); + } + function renderExportUI() { + const o = S.exportOptions || DEFAULT_EXPORT; + const root = runtime.el; + if (!root) return; + const ecom = o.preset === "ecom800"; + const jpg = o.format === "jpeg"; + root.querySelectorAll("[data-export-key]").forEach((btn) => { + const on = String(o[btn.dataset.exportKey]) === String(btn.dataset.exportValue); + btn.classList.toggle("active", on); + btn.setAttribute("aria-pressed", String(on)); + }); + root.querySelectorAll('[data-export-key="bg"]').forEach((btn) => { + const blocked = jpg && btn.dataset.exportValue === "transparent"; + btn.disabled = blocked; + if (blocked) btn.title = "JPG 不支持透明背景,已自动使用白底"; + else btn.removeAttribute("title"); + }); + root.querySelectorAll('[data-export-when="ecom800"]').forEach((row) => { + row.hidden = !ecom; + }); + const summary = root.querySelector(".iwb-editor-export-summary"); + if (summary) { + const size = ecom ? o.size + "×" + o.size : "原尺寸 " + S.imgW + "×" + S.imgH; + const limit = ecom && o.maxKB ? " · ≤" + o.maxKB + "KB" : ""; + const bg = effectiveBg(o) === "white" ? "白底" : "透明"; + const fmt = o.format === "jpeg" ? "JPG" : o.format === "webp" ? "WebP" : "PNG"; + summary.textContent = size + " · " + fmt + " · " + bg + limit; + } + const note = root.querySelector(".iwb-editor-export-note"); + if (note) { + const le = S.lastExport; + note.textContent = le && le.signature === exportSignature(o) ? "上次输出 " + le.width + "×" + le.height + " · " + Math.max(1, Math.round(le.bytes / 1024)) + "KB" : "一次只输出一个结果;设置会记住"; + } + } + function bindExportUI() { + const root = runtime.el; + if (!root) return; + const panel = root.querySelector(".iwb-editor-export-settings"); + const toggle = root.querySelector('[data-action="toggleExportSettings"]'); + if (panel && panel.dataset.bound === "1") return; + if (panel) panel.dataset.bound = "1"; + if (toggle && panel) { + toggle.addEventListener("mousedown", (e) => e.stopPropagation()); + toggle.addEventListener("click", (e) => { + e.stopPropagation(); + const open2 = panel.classList.toggle("open"); + toggle.setAttribute("aria-expanded", String(open2)); + }); + } + if (panel) { + panel.addEventListener("mousedown", (e) => e.stopPropagation()); + panel.addEventListener("click", (e) => { + const btn = e.target.closest("[data-export-key]"); + if (!btn) return; + e.stopPropagation(); + let v = btn.dataset.exportValue; + if (btn.dataset.exportKey === "maxKB" || btn.dataset.exportKey === "size") v = Number(v); + setExportOption(btn.dataset.exportKey, v); + }); + } + } + function buildOutputCanvas() { + const o = S.exportOptions || DEFAULT_EXPORT; + const white = effectiveBg(o) === "white"; + const src = getCompositeCanvas(); + let out = src; + if (o.preset === "ecom800") { + const size = o.size; + const c = document.createElement("canvas"); + c.width = size; + c.height = size; + const cx = c.getContext("2d"); + if (white) { + cx.fillStyle = "#ffffff"; + cx.fillRect(0, 0, size, size); + } + const long = Math.max(S.imgW, S.imgH) || 1; + const k = size * 0.8 / long; + const w = S.imgW * k, h = S.imgH * k; + cx.drawImage(src, (size - w) / 2, (size - h) / 2, w, h); + src.width = 0; + src.height = 0; + out = c; + } else if (white) { + const c = document.createElement("canvas"); + c.width = S.imgW; + c.height = S.imgH; + const cx = c.getContext("2d"); + cx.fillStyle = "#ffffff"; + cx.fillRect(0, 0, c.width, c.height); + cx.drawImage(src, 0, 0); + src.width = 0; + src.height = 0; + out = c; + } + return out; + } + function toBlob(canvas, mime, quality) { + return new Promise((resolve, reject) => { + try { + if (typeof canvas.toBlob !== "function") { + reject(new Error("当前环境不支持 toBlob")); + return; + } + canvas.toBlob((blob) => { + if (blob) resolve(blob); + else { + try { + resolve(dataUrlToBlob2(canvas.toDataURL(mime, quality))); + } catch (e) { + reject(e); + } + } + }, mime, quality); + } catch (e) { + reject(e); + } + }); + } + function dataUrlToBlob2(dataUrl) { + const comma = dataUrl.indexOf(","); + const meta = dataUrl.slice(0, comma); + const bin = atob(dataUrl.slice(comma + 1)); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return new Blob([bytes], { type: (/^data:([^;,]+)/.exec(meta) || [])[1] || "image/png" }); + } + async function encodeOutput(canvas) { + const o = S.exportOptions || DEFAULT_EXPORT; + const mime = o.format === "jpeg" ? "image/jpeg" : o.format === "webp" ? "image/webp" : "image/png"; + const limit = o.preset === "ecom800" && o.maxKB > 0 ? o.maxKB * 1024 : 0; + let blob = await toBlob(canvas, mime, 0.92); + if (limit && blob.size > limit) { + if (o.format === "png") { + toast("PNG 无法降质:当前 " + Math.round(blob.size / 1024) + "KB,可切换 JPG/WebP 或缩小尺寸", "warn"); + } else { + let q = 0.82; + for (let i = 0; i < 8 && blob.size > limit && q >= 0.3; i++) { + blob = await toBlob(canvas, mime, q); + q -= 0.09; + } + if (blob.size > limit) toast("已尽力压缩,仍为 " + Math.round(blob.size / 1024) + "KB(目标 ≤" + o.maxKB + "KB)", "warn"); + } + } + return blob; + } + async function prepareOutput() { + const canvas = buildOutputCanvas(); + try { + const blob = await encodeOutput(canvas); + const o = S.exportOptions || DEFAULT_EXPORT; + const info = { + bytes: blob.size, + width: canvas.width, + height: canvas.height, + format: o.format, + bg: effectiveBg(o), + preset: o.preset, + maxKB: o.preset === "ecom800" ? o.maxKB : 0, + // 记下产出时用的设置指纹,UI 才能判断「上次输出」是否还代表当前设置 + signature: exportSignature(o) + }; + S.lastExport = info; + return { blob, info }; + } finally { + canvas.width = 0; + canvas.height = 0; + } + } + function downloadBlob(blob) { + const o = S.exportOptions || DEFAULT_EXPORT; + const ext = o.format === "jpeg" ? "jpg" : o.format; + const raw = S.callbacks && S.callbacks.imageName || "image.png"; + const name = String(raw).replace(/\.[^.]+$/, "") + "_edit." + ext; + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = name; + document.body.appendChild(a); + a.click(); + if (a.parentNode) a.parentNode.removeChild(a); + setTimeout(() => { + try { + URL.revokeObjectURL(url); + } catch (e) { + } + }, 2e3); + toast("已下载 " + name + "(" + Math.round(blob.size / 1024) + "KB)", "success"); + } + async function toPngBlob(blob) { + try { + if (typeof createImageBitmap === "function") { + const bmp = await createImageBitmap(blob); + const c = document.createElement("canvas"); + c.width = bmp.width; + c.height = bmp.height; + c.getContext("2d").drawImage(bmp, 0, 0); + if (typeof bmp.close === "function") bmp.close(); + const out = await new Promise((res) => c.toBlob((b) => res(b), "image/png")); + c.width = 0; + c.height = 0; + if (out) return out; + } + } catch (e) { + } + return await new Promise((resolve) => { + const url = URL.createObjectURL(blob); + const img = new Image(); + img.onload = () => { + const c = document.createElement("canvas"); + c.width = img.naturalWidth; + c.height = img.naturalHeight; + c.getContext("2d").drawImage(img, 0, 0); + try { + URL.revokeObjectURL(url); + } catch (e) { + } + c.toBlob((b) => resolve(b || blob), "image/png"); + }; + img.onerror = () => { + try { + URL.revokeObjectURL(url); + } catch (e) { + } + resolve(blob); + }; + img.src = url; + }); + } + async function copyBlobToClipboard(blob) { + const nav = typeof navigator !== "undefined" ? navigator : null; + const CI = typeof window !== "undefined" ? window.ClipboardItem : null; + if (!nav || !nav.clipboard || typeof nav.clipboard.write !== "function" || typeof CI !== "function") { + toast("当前浏览器不支持复制图片,请用「导出」下载", "warn"); + return false; + } + let png = blob; + if (blob.type !== "image/png") { + try { + png = await toPngBlob(blob); + } catch (e) { + png = blob; + } + } + try { + await nav.clipboard.write([new CI({ "image/png": png })]); + toast("已复制到剪贴板(" + Math.round(png.size / 1024) + "KB),可直接粘贴", "success"); + return true; + } catch (e) { + toast("复制失败:" + (e && e.message || "浏览器拒绝了剪贴板写入") + ";可用「导出」下载", "error"); + return false; + } + } + + // image-annotate/plugin/editor/index.js + async function open(options) { + if (!options || !options.imageBase64) return; + createEl(); + S.callbacks = options; + S.renderAll = renderAll; + S.positionFloating = positionFloating; + S.renderFxPanel = renderFxPanel; + S.renderAdjustPanel = renderAdjustPanel; + S.onHistoryRestore = onHistoryRestore; + try { + const img = await loadImage(options.imageBase64); + S.imgW = img.naturalWidth || img.width; + S.imgH = img.naturalHeight || img.height; + S.originalImage = img; + runtime.el.style.display = "flex"; + S.open = true; + S.zoom = 1; + setupCanvas(img); + resetState(); + updateAllUI(); + registerSelectionCommands(); + loadExportOptions(); + loadRecentColors(); + loadColorPopPinned(); + bindLiteUI(); + bindFloating(); + bindExportUI(); + initPanels(); + loadSideWidth(); + renderAll(); + } catch (e) { + console.error("[IWB编辑器] 打开失败:", e); + if (runtime.el) runtime.el.style.display = "none"; + if (options.onError) options.onError(e.message); + } finally { + options.imageBase64 = null; + } + } + function resetState() { + purgeVectorCanvases(); + S.history = []; + S.redoStack = []; + S.cropRect = null; + S.cropHandle = null; + S.cropMoving = false; + S.moveStart = null; + S.isDrawing = false; + S.panning = false; + S.tool = "brush"; + S.color = "#ff4444"; + S.brushSize = 3; + S.brushHardness = 100; + S.brushOpacity = 1; + S.prevTool = null; + S.pickerComposite = null; + S.rectFill = false; + S.shapeLineWidth = 3; + S.textSize = 32; + S.cropConstraint = { type: "free", ratio: 0, sizeW: 0, sizeH: 0 }; + S.textLayers = []; + S.selectedTextId = null; + S.textDrag = null; + S.textEditingId = null; + S.shapeLayers = []; + S.selectedShapeId = null; + S.shapeDrag = null; + S.penPath = null; + S.penEditId = null; + S.penDragPt = -1; + S.penDragBase = null; + S.penDragPending = null; + S.selectedLayerId = null; + S.bitmapDrag = null; + S.layerMulti.length = 0; + S.hoverPos = null; + S.lastClick = null; + S.lastNameClick = null; + S.altPicker = false; + S.fx = { key: null, value: 0, layerId: null, source: null }; + resetAdjustCache(); + S.zCounter = Math.max(S.layers.length - 1, 0); + S.placingImage = null; + S.placingHandle = null; + S.placingStart = null; + const sizeToggle = runtime.el && runtime.el.querySelector(".iwb-editor-size-toggle"); + if (sizeToggle) { + sizeToggle.classList.remove("active"); + sizeToggle.setAttribute("aria-pressed", "false"); + sizeToggle.textContent = "启用尺寸"; + } + S.selection = null; + S.marquee = null; + S.lassoPts = null; + S.interaction = "idle"; + S.lastExport = null; + if (S._antFrame) { + cancelAnimationFrame(S._antFrame); + S._antFrame = 0; + } + hideSelectionContext(); + if (S.selectionCtx) renderSelection(); + if (S.cursorCtx) { + S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0); + S.cursorCtx.clearRect(0, 0, S.cursorCtx.canvas.width, S.cursorCtx.canvas.height); + resetOverlayTransform(S.cursorCtx); + } + } + function renderAll() { + if (!S.open || !runtime.el) return; + renderObjects(); + renderLayerPanel(); + renderFxPanel(); + renderAdjustPanel(); + renderOptionBar(); + updateStatusbar(); + renderExportUI(); + renderSelection(); + syncAnts(); + positionFloating(); + } + function initPanels() { + if (!runtime.el) return; + const st = S.callbacks && S.callbacks.settings; + let saved = false; + if (st && typeof st.get === "function") { + try { + saved = !!st.get("panelsCollapsed"); + } catch (e) { + } + } + const auto = (window.innerWidth || 1440) < 1100; + runtime.el.classList.toggle("panels-collapsed", saved || auto); + } + function close(reason) { + const callbacks = S.callbacks; + try { + if (callbacks && typeof callbacks.onClose === "function") callbacks.onClose(reason || "cancel"); + } catch (e) { + console.error("[IWB编辑器] onClose 回调异常:", e); + } + if (runtime.el) { + hideTextInput(); + runtime.el.style.display = "none"; + } + releaseEditorMemory(); + S.open = false; + S.callbacks = null; + S.placingImage = null; + S.placingHandle = null; + S.placingStart = null; + S.penPath = null; + S.textEditingId = null; + clearSelection(); + hideSelectionContext(); + disposeSelection(); + } + function releaseEditorMemory() { + S.history = []; + S.redoStack = []; + S.originalImage = null; + S.pickerComposite = null; + S.fx = { key: null, value: 0, layerId: null, source: null }; + resetAdjustCache(); + S.isDrawing = false; + S.panning = false; + S.penDragPt = -1; + S.penDragPending = null; + S.placingImage = null; + S.placingHandle = null; + S.placingStart = null; + for (const layer of S.layers) { + try { + if (layer.sourceCanvas) { + layer.sourceCanvas.width = 0; + layer.sourceCanvas.height = 0; + } + if (layer.canvas) { + if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas); + layer.canvas.width = 0; + layer.canvas.height = 0; + } + } catch (e) { + } + } + S.layers = []; + for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) { + try { + if (c) { + c.width = 0; + c.height = 0; + } + } catch (e) { + } + } + purgeVectorCanvases(); + } + async function exportResult(mode) { + if (S.placingImage) cancelImagePlacement(); + try { + const { blob } = await prepareOutput(); + if (mode === "download") { + downloadBlob(blob); + if (S.renderAll) S.renderAll(); + return; + } + if (S.callbacks && S.callbacks.onResult) S.callbacks.onResult(blob, mode); + close("done"); + } catch (e) { + console.error("[IWB编辑器] 导出失败:", e); + toast("导出失败:" + (e && e.message || "图片可能跨域"), "error"); + if (S.callbacks && S.callbacks.onError) S.callbacks.onError("导出失败:" + (e && e.message || "图片跨域")); + } + } + async function copyResult() { + if (S.placingImage) cancelImagePlacement(); + try { + const { blob } = await prepareOutput(); + await copyBlobToClipboard(blob); + if (S.renderAll) S.renderAll(); + } catch (e) { + console.error("[IWB编辑器] 复制失败:", e); + toast("复制失败:" + (e && e.message || "图片可能跨域"), "error"); + } + } + var __stats = () => ({ + history: S.history.length, + historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0), + redo: S.redoStack.length, + redoBytes: S.redoStack.reduce((n, s) => n + (s.__bytes || 0), 0), + maxEntries: HISTORY_MAX_ENTRIES, + maxBytes: HISTORY_MAX_BYTES, + historyBudget: historyBudgetBytes(), + ...snapshotStats + }); + var __debug = () => ({ + open: S.open, + tool: S.tool, + color: S.color, + altPicker: !!S.altPicker, + doc: { w: S.imgW, h: S.imgH }, + zoom: S.zoom, + fit: { w: Math.round(S.fitW || 0), h: Math.round(S.fitH || 0) }, + layers: S.layers.map((l) => ({ + id: l.id, + name: l.name, + z: l.z, + locked: !!l.locked, + visible: l.visible !== false, + // 不透明度有两个面:数据字段(导出/合并用)与 CSS(屏幕上看到的),两者必须一致 + opacity: l.opacity == null ? 1 : l.opacity, + cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || "1") : null + })), + shapes: S.shapeLayers.map((s) => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, strokeOn: s.strokeOn !== false, z: s.z, color: s.color, fillColor: s.fillColor || null, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })), + texts: S.textLayers.map((t) => ({ + id: t.id, + text: t.text, + x: t.x, + y: t.y, + fontSize: t.fontSize, + color: t.color, + fontWeight: t.fontWeight, + fontFamily: t.fontFamily, + align: t.align, + lineHeight: t.lineHeight, + strokeWidth: t.strokeWidth, + strokeColor: t.strokeColor, + bgFill: !!t.bgFill, + bgColor: t.bgColor, + // 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量 + box: (() => { + const b = textBounds(t); + return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) }; + })() + })), + // 吸附参考线(拖动中才有)与最近使用颜色:交互回归用 + guides: S.guides ? S.guides.map((g) => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [], + recentColors: (S.recentColors || []).slice(), + textDefaults: { + weight: S.textWeight, + family: S.textFamily, + align: S.textAlign, + lineHeight: S.textLineHeight, + strokeWidth: S.textStrokeWidth, + strokeColor: S.textStrokeColor, + bgFill: S.textBgFill, + bgColor: S.textBgColor, + bgAlpha: S.textBgAlpha + }, + // 矢量图形颜色:fillColor=null 表示跟随描边色(回归要能断言这条语义) + shapeColors: { stroke: S.color, fill: S.shapeFillColor || null }, + // 色板当前在调哪一格:stroke / fill / bg(文字上下文里 fill=描边、bg=底色) + colorTarget: S.colorTarget, + selectedShapeId: S.selectedShapeId, + // 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据 + lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null, + // 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点 + drag: S.shapeDrag ? "shape:" + S.shapeDrag.mode + (S.shapeDrag.handle ? ":" + S.shapeDrag.handle : "") : S.textDrag ? "text:" + S.textDrag.mode : S.bitmapDrag ? "bitmap:" + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ":" + S.bitmapDrag.handle : "") : null, + selectedTextId: S.selectedTextId, + penEditId: S.penEditId, + activeLayerId: S.activeLayerId, + selectedLayerId: S.selectedLayerId, + layerMulti: S.layerMulti.map((x) => x.type + ":" + x.id), + selection: selectionInfo(), + toolOptions: { + brushSize: S.brushSize, + brushHardness: S.brushHardness, + brushOpacity: S.brushOpacity, + shapeLineWidth: S.shapeLineWidth, + textSize: S.textSize, + rectFill: S.rectFill, + penFill: S.penFill + }, + history: S.history.length, + historyLabels: S.history.map((s) => s.__label || ""), + redo: S.redoStack.length, + exportOptions: S.exportOptions ? { ...S.exportOptions } : null, + lastExport: S.lastExport ? { ...S.lastExport } : null, + // 快速效果的可重调状态:hasSource=false 表示还没点过效果(滑杆应置灰) + fx: { key: S.fx.key, value: S.fx.value, layerId: S.fx.layerId, hasSource: Boolean(S.fx.source) }, + // v1.15 图片调节:params 是 11 项当前值,hasSource 决定面板是否可用 + adjust: { + layerId: S.adjust ? S.adjust.layerId : null, + hasSource: Boolean(S.adjust && S.adjust.source), + params: S.adjust && S.adjust.params ? { ...S.adjust.params } : null + }, + // 调节基准缓存条数:退出编辑器后必须是 0(否则下一张图会拿到上一张的像素) + adjustCacheSize: adjustCacheSize(), + interaction: S.interaction, + ants: !!S._antFrame, + view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : null, + // 图层整幅像素指纹(抽样校验和):断言「改强度后从基准重算」而不是叠加, + // 比逐点采样稳 —— 马赛克/模糊的差异散在整幅,单点可能刚好相同 + layerHash: (id) => { + const l = S.layers.find((v) => v.id === id); + if (!l || !l.ctx || !l.canvas) return 0; + try { + const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data; + let h = 2166136261; + for (let i = 0; i < d.length; i += 97) { + h ^= d[i]; + h = Math.imul(h, 16777619); + } + return h >>> 0; + } catch (e) { + return 0; + } + }, + // 非透明像素的平均色:断言效果是否落在预期值上(如反相 50% 必然趋近 128) + avgColor: (id) => { + const l = S.layers.find((v) => v.id === id); + if (!l || !l.ctx || !l.canvas) return null; + try { + const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data; + let r = 0, g = 0, b = 0, n = 0; + for (let i = 0; i < d.length; i += 4) { + if (d[i + 3] < 200) continue; + r += d[i]; + g += d[i + 1]; + b += d[i + 2]; + n++; + } + return n ? [Math.round(r / n), Math.round(g / n), Math.round(b / n), n] : null; + } catch (e) { + return null; + } + }, + pixel: (id, x, y) => { + const l = S.layers.find((v) => v.id === id); + if (!l || !l.ctx) return null; + try { + return Array.from(l.ctx.getImageData(Math.round(x), Math.round(y), 1, 1).data); + } catch (e) { + return null; + } + }, + // 区域透明像素统计:断言「合并后两半都有内容」比逐点采样快一个量级 + alphaIn: (id, x0, y0, x1, y1) => { + const l = S.layers.find((v) => v.id === id); + if (!l || !l.ctx) return 0; + try { + const w = Math.max(1, Math.round(x1 - x0)); + const h = Math.max(1, Math.round(y1 - y0)); + const d = l.ctx.getImageData(Math.round(x0), Math.round(y0), w, h).data; + let n = 0; + for (let i = 3; i < d.length; i += 4) if (d[i] > 0) n++; + return n; + } catch (e) { + return 0; + } + } + }); + window.__iwbEditor = { + open, + close, + __stats, + __debug + }; + + // image-annotate/plugin/editor.css + var editor_default = '/* IWB 鲜艺抠图节点 - 注入样式 */\n\n/* 抠图按钮 */\n.iwb-cutout-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n\n.iwb-cutout-btn:hover {\n opacity: 1;\n transform: scale(1.15);\n}\n\n.iwb-cutout-btn svg {\n width: 14px;\n height: 14px;\n display: block;\n}\n\n/* 正在处理中的按钮状态 */\n.iwb-cutout-btn.processing {\n animation: iwb-cutout-pulse 1s infinite;\n pointer-events: none;\n}\n\n@keyframes iwb-cutout-pulse {\n 0%, 100% { opacity: 0.4; }\n 50% { opacity: 1; }\n}\n\n/* 全屏遮罩 */\n.iwb-cutout-overlay {\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0, 0, 0, 0.25);\n display: none;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n gap: 12px;\n z-index: 999999;\n pointer-events: all;\n backdrop-filter: blur(2px);\n}\n\n/* 自定义按钮提示(挂在 body,最高层级,不会被图片遮挡) */\n#iwb-cutout-tip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(30, 30, 46, 0.95);\n color: #fff;\n padding: 5px 10px;\n border-radius: 6px;\n font-size: 12px;\n line-height: 1.5;\n white-space: nowrap;\n pointer-events: none;\n display: none;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);\n border: 1px solid rgba(255, 255, 255, 0.14);\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n max-width: 320px;\n white-space: normal;\n word-break: break-all;\n}\n\n/* 加载动画 */\n.iwb-cutout-spinner {\n width: 48px;\n height: 48px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #e8a735;\n border-radius: 50%;\n animation: iwb-cutout-spin 0.8s linear infinite;\n}\n\n@keyframes iwb-cutout-spin {\n to { transform: rotate(360deg); }\n}\n\n/* 遮罩文字 */\n.iwb-cutout-text {\n color: #fff;\n font-size: 14px;\n font-weight: 500;\n text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);\n background: rgba(0, 0, 0, 0.6);\n padding: 8px 16px;\n border-radius: 6px;\n}\n\n/* Toast 提示 */\n.iwb-cutout-toast {\n position: fixed;\n bottom: 24px;\n left: 50%;\n transform: translateX(-50%);\n padding: 10px 20px;\n border-radius: 8px;\n font-size: 13px;\n font-weight: 500;\n z-index: 999999;\n transition: opacity 0.3s;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n display: none;\n max-width: 400px;\n}\n\n.iwb-cutout-toast-success {\n background: #1a7f37;\n color: #fff;\n}\n\n.iwb-cutout-toast-error {\n background: #cf222e;\n color: #fff;\n}\n\n.iwb-cutout-toast-info {\n background: #1f6feb;\n color: #fff;\n}\n\n/* 白底按钮 */\n.iwb-whitebg-btn {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-whitebg-btn:hover { opacity: 1; transform: scale(1.15); }\n.iwb-whitebg-btn svg { width: 14px; height: 14px; display: block; }\n.iwb-whitebg-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n/* 编辑按钮 */\n.iwb-editor-btn-icon {\n cursor: pointer;\n opacity: 0.7;\n transition: opacity 0.15s, transform 0.15s;\n}\n.iwb-editor-btn-icon:hover { opacity: 1; transform: scale(1.15); }\n.iwb-editor-btn-icon svg { width: 14px; height: 14px; display: block; }\n\n/* ==================== 图片编辑器 ==================== */\n\n.iwb-editor-overlay {\n position: fixed;\n top: 0; left: 0;\n width: 100%; height: 100%;\n background: rgba(0, 0, 0, 0.6);\n display: none;\n align-items: center;\n justify-content: center;\n z-index: 999998;\n backdrop-filter: blur(3px);\n}\n\n.iwb-editor-modal {\n background: #1e1e2e;\n border-radius: 0;\n box-shadow: none;\n display: flex;\n flex-direction: column;\n width: 100vw;\n height: 100vh;\n max-width: none;\n max-height: none;\n overflow: visible;\n}\n\n/* 新增:主区域(画布 + 图层面板)flex 布局 */\n.iwb-editor-main {\n display: flex;\n flex: 1 1 auto;\n min-height: 0;\n overflow: visible;\n}\n\n.iwb-editor-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 10px 16px;\n background: #181825;\n border-bottom: 1px solid #313244;\n flex-wrap: nowrap;\n}\n.iwb-editor-header > .iwb-editor-tools {\n position: absolute;\n left: 12px;\n top: 68px;\n width: 44px;\n flex-direction: column;\n padding: 6px;\n background: #181825;\n border: 1px solid #313244;\n border-radius: 8px;\n z-index: 20;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action { position: static; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="redo"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"],\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] {\n position: absolute;\n top: -54px;\n left: auto;\n}\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="undo"] { right: 154px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="redo"] { right: 118px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="reset"] { right: 82px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-action[data-action="restore"] { right: 46px; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-divider {\n width: 24px;\n height: 1px;\n margin: 4px 0;\n}\n\n.iwb-editor-title {\n color: #cdd6f4;\n font-size: 14px;\n font-weight: 600;\n white-space: nowrap;\n}\n\n.iwb-editor-tools {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n/* 撤销 / 重做 / 还原(v1.18):搬进工具条末端后需要一个 flex 容器,\n 否则三个 button 之间是 inline-block 的空隙,和左边 4px gap 的工具按钮对不齐。 */\n.iwb-editor-history { display: flex; align-items: center; gap: 4px; }\n\n.iwb-editor-tool, .iwb-editor-action {\n background: #313244;\n border: none;\n border-radius: 6px;\n color: #cdd6f4;\n width: 32px; height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n font-size: 15px;\n transition: background 0.15s, transform 0.1s;\n}\n.iwb-editor-tool:hover, .iwb-editor-action:hover { background: #45475a; transform: scale(1.08); }\n.iwb-editor-tool.active { background: #e8a735; color: #1e1e2e; }\n.iwb-editor-tool svg, .iwb-editor-action svg { display: block; }\n.iwb-editor-layer-btn svg { display: block; }\n\n/* 复原按钮:绿色高亮,与撤销/重做/清空区分 */\n.iwb-editor-action-restore { background: #1a7f37; color: #fff; }\n.iwb-editor-action-restore:hover { background: #15803d !important; }\n\n.iwb-editor-divider {\n width: 1px; height: 20px;\n background: #45475a;\n margin: 0 4px;\n}\n\n.iwb-editor-params {\n display: flex;\n align-items: center;\n gap: 10px;\n margin-left: 12px;\n justify-content: flex-start;\n min-width: 0;\n flex: 1 1 auto;\n flex-wrap: wrap;\n}\n.iwb-editor-params .iwb-editor-zoom { margin-left: auto; order: 20; }\n.iwb-editor-top-colors { display: none; }\n\n.iwb-editor-color {\n width: 20px; height: 20px;\n border-radius: 50%;\n cursor: pointer;\n border: 2px solid transparent;\n transition: transform 0.1s, border-color 0.15s;\n}\n.iwb-editor-color:hover { transform: scale(1.2); }\n.iwb-editor-color.active { border-color: #fff; transform: scale(1.15); }\n\n.iwb-editor-brush-label {\n display: flex;\n align-items: center;\n gap: 6px;\n color: #a6adc8;\n font-size: 12px;\n}\n.iwb-editor-brush-size { width: 80px; cursor: pointer; }\n.iwb-editor-brush-val { color: #e8a735; font-weight: 600; min-width: 16px; }\n\n/* 笔刷/橡皮大小精确数值输入框 */\n.iwb-editor-brush-num,\n.iwb-editor-eraser-num {\n width: 44px;\n padding: 2px 3px;\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 5px;\n color: #e8a735;\n font-weight: 600;\n font-size: 11px;\n font-family: inherit;\n text-align: center;\n}\n.iwb-editor-brush-num:focus,\n.iwb-editor-eraser-num:focus {\n outline: none;\n border-color: #e8a735;\n background: #1e1e2e;\n}\n.iwb-editor-brush-num::-webkit-outer-spin-button,\n.iwb-editor-brush-num::-webkit-inner-spin-button,\n.iwb-editor-eraser-num::-webkit-outer-spin-button,\n.iwb-editor-eraser-num::-webkit-inner-spin-button {\n -webkit-appearance: none; /* 去掉上下箭头,窄输入框更干净 */\n margin: 0;\n}\n\n/* 实心矩形开关 */\n.iwb-editor-fill-btn {\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 6px;\n color: #a6adc8;\n padding: 4px 10px;\n font-size: 12px;\n cursor: pointer;\n transition: background 0.15s, color 0.15s, border-color 0.15s;\n white-space: nowrap;\n}\n.iwb-editor-fill-btn:hover { background: #45475a; }\n.iwb-editor-fill-btn.active {\n background: #e8a735;\n border-color: #e8a735;\n color: #1e1e2e;\n font-weight: 600;\n}\n\n/* 画笔参数组(硬度/透明度,画笔与橡皮工具共用) */\n.iwb-editor-brush-group {\n display: flex;\n align-items: center;\n gap: 10px;\n}\n.iwb-editor-layer-group {\n display: flex;\n align-items: center;\n gap: 3px;\n}\n.iwb-editor-layer-btn {\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 6px;\n color: #a6adc8;\n width: 26px;\n height: 26px;\n font-size: 14px;\n line-height: 1;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: background 0.15s, color 0.15s, border-color 0.15s, opacity 0.15s;\n}\n.iwb-editor-layer-btn:hover:not(:disabled) { background: #45475a; color: #cdd6f4; }\n.iwb-editor-layer-btn:disabled {\n opacity: 0.35;\n cursor: not-allowed;\n}\n\n/* 缩放控件 */\n.iwb-editor-zoom {\n display: flex;\n align-items: center;\n gap: 2px;\n background: #313244;\n border-radius: 6px;\n padding: 2px;\n}\n.iwb-editor-zoom-btn {\n background: transparent;\n border: none;\n color: #cdd6f4;\n width: 26px;\n height: 26px;\n border-radius: 4px;\n cursor: pointer;\n font-size: 14px;\n line-height: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.15s;\n}\n.iwb-editor-zoom-btn:hover { background: #45475a; }\n.iwb-editor-zoom-btn:active { transform: scale(0.94); }\n.iwb-editor-zoom-fit { font-size: 12px; width: auto; padding: 0 8px; }\n.iwb-editor-zoom-val {\n color: #e8a735;\n font-size: 12px;\n font-weight: 600;\n min-width: 46px;\n text-align: center;\n font-variant-numeric: tabular-nums;\n user-select: none;\n}\n\n/* 底部操作提示 */\n.iwb-editor-zoom-hint {\n position: absolute;\n bottom: 8px;\n right: 14px;\n color: #7f849c;\n font-size: 11px;\n background: rgba(24, 24, 37, 0.85);\n padding: 3px 10px;\n border-radius: 4px;\n pointer-events: none;\n z-index: 5;\n}\n\n.iwb-editor-canvas-wrap {\n position: relative;\n background: #11111b;\n flex: 1 1 auto;\n min-height: 0;\n max-width: 100%;\n max-height: 100%;\n overflow: hidden; /* 裁剪框允许显示在图片边界外;编辑区仍由模态层裁切 */\n overflow: clip; /* v1.2.8:hidden 仍可被编程滚动(点击底部工具栏会触发 scrollIntoView 把画布滚跑),clip 彻底禁止滚动 */\n padding: 12px;\n}\n\n.iwb-editor-canvas-stack {\n position: absolute;\n left: 0;\n top: 0;\n display: block;\n width: 0;\n height: 0;\n /* 仅图片工作区显示透明棋盘格,外围裁剪工作区保持纯色。 */\n background-color: #d6d6d6;\n background-image:\n linear-gradient(45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(-45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, #b8b8b8 75%),\n linear-gradient(-45deg, transparent 75%, #b8b8b8 75%);\n background-size: 20px 20px;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0;\n}\n\n.iwb-editor-base, .iwb-editor-draw, .iwb-editor-text, .iwb-editor-crop-overlay {\n display: block;\n}\n/* 位图图层 canvas(动态创建) */\n.iwb-editor-layer-canvas {\n display: block;\n position: absolute;\n top: 0; left: 0;\n}\n.iwb-editor-base {\n background: #fff;\n /* 棋盘格透明背景示意 */\n background-image:\n linear-gradient(45deg, #e0e0e0 25%, transparent 25%),\n linear-gradient(-45deg, #e0e0e0 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, #e0e0e0 75%),\n linear-gradient(-45deg, transparent 75%, #e0e0e0 75%);\n background-size: 20px 20px;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0px;\n}\n.iwb-editor-draw {\n position: absolute;\n top: 0; left: 0;\n cursor: crosshair;\n}\n\n/* 笔划预览层:一笔进行中显示(draw 之上、text 之下),事件穿透 */\n.iwb-editor-stroke {\n position: absolute;\n top: 0; left: 0;\n pointer-events: none;\n display: none;\n}\n\n.iwb-editor-brush-hardness { width: 70px; cursor: pointer; }\n.iwb-editor-brush-hardness-val { color: #e8a735; font-weight: 600; min-width: 20px; display: inline-block; text-align: right; }\n.iwb-editor-brush-opacity { width: 70px; cursor: pointer; }\n.iwb-editor-brush-opacity-val { color: #e8a735; font-weight: 600; min-width: 34px; display: inline-block; text-align: right; }\n\n/* 自定义颜色(原生取色器伪装成圆形色板) */\n.iwb-editor-color-custom {\n position: relative;\n overflow: hidden;\n border: 2px dashed #a6adc8;\n}\n.iwb-editor-color-custom.active { border-color: #fff; border-style: solid; transform: scale(1.15); }\n.iwb-editor-color-custom input[type="color"] {\n position: absolute;\n inset: -6px;\n width: calc(100% + 12px);\n height: calc(100% + 12px);\n padding: 0;\n border: none;\n cursor: pointer;\n background: conic-gradient(#ff4444, #ffaa00, #44dd44, #4488ff, #aa44ff, #ff4444);\n}\n.iwb-editor-color-custom input[type="color"]::-webkit-color-swatch-wrapper { padding: 0; }\n.iwb-editor-color-custom input[type="color"]::-webkit-color-swatch { border: none; }\n\n/* 吸管悬停预览浮窗 */\n.iwb-editor-picker-tip {\n position: fixed;\n z-index: 2147483000;\n display: none;\n align-items: center;\n gap: 6px;\n background: rgba(30, 30, 46, 0.95);\n border: 1px solid rgba(255, 255, 255, 0.14);\n border-radius: 6px;\n padding: 4px 8px;\n pointer-events: none;\n font-family: system-ui, -apple-system, "Segoe UI", sans-serif;\n}\n.iwb-editor-picker-chip {\n width: 16px;\n height: 16px;\n border-radius: 4px;\n background: transparent;\n}\n.iwb-editor-picker-hex {\n color: #cdd6f4;\n font-size: 12px;\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n}\n\n/* 文字图层:独立 canvas,事件穿透到下层 drawCanvas */\n.iwb-editor-text {\n position: absolute;\n top: 0; left: 0;\n pointer-events: none;\n}\n\n/* 裁剪覆盖层:遮罩/选区框/手柄画在这层,不污染标注层 */\n.iwb-editor-crop-overlay {\n position: absolute;\n top: 0; left: 0;\n pointer-events: none;\n}\n\n/* 文字输入框 */\n.iwb-editor-text-input {\n position: absolute;\n display: none;\n padding: 4px 8px;\n border: 2px solid #4488ff;\n border-radius: 4px;\n font-size: 14px;\n line-height: 1.35;\n /* textarea:默认会显示右下角拖拽柄与滚动条,画布上的就地输入框都不要 */\n resize: none;\n overflow: hidden;\n white-space: pre;\n background: rgba(255, 255, 255, 0.95);\n color: #1e1e2e;\n z-index: 10;\n min-width: 120px;\n min-height: 30px;\n font-family: inherit;\n}\n.iwb-editor-text-input:focus { outline: none; box-shadow: 0 0 0 3px rgba(68, 136, 255, 0.3); }\n\n/* 裁剪确认栏(含约束控件) */\n.iwb-editor-crop-bar {\n position: absolute;\n bottom: 16px;\n left: 50%;\n transform: translateX(-50%);\n display: none;\n gap: 8px;\n z-index: 10;\n align-items: center;\n background: rgba(24, 24, 37, 0.92);\n border: 1px solid #313244;\n border-radius: 8px;\n padding: 6px 10px;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);\n flex-wrap: wrap;\n max-width: 90%;\n justify-content: center;\n}\n\n.iwb-editor-constraint-group {\n display: flex;\n align-items: center;\n gap: 4px;\n}\n\n.iwb-editor-constraint-label {\n color: #7f849c;\n font-size: 11px;\n margin-right: 2px;\n white-space: nowrap;\n}\n\n.iwb-editor-constraint-btn {\n background: #313244;\n border: none;\n border-radius: 4px;\n color: #cdd6f4;\n padding: 3px 8px;\n font-size: 12px;\n cursor: pointer;\n transition: background 0.15s, transform 0.1s;\n white-space: nowrap;\n}\n.iwb-editor-constraint-btn:hover { background: #45475a; transform: scale(1.05); }\n.iwb-editor-constraint-btn.active { background: #4488ff; color: #fff; }\n\n.iwb-editor-constraint-sep {\n width: 1px;\n height: 20px;\n background: #45475a;\n}\n\n.iwb-editor-size-input {\n width: 50px;\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 4px;\n color: #cdd6f4;\n padding: 3px 6px;\n font-size: 12px;\n text-align: center;\n}\n.iwb-editor-size-input:focus { outline: none; border-color: #4488ff; }\n.iwb-editor-size-input::-webkit-inner-spin-button { -webkit-appearance: none; }\n\n.iwb-editor-size-x { color: #7f849c; font-size: 12px; }\n\n.iwb-editor-size-apply {\n background: #313244;\n border: 1px solid #4488ff;\n color: #4488ff;\n border-radius: 4px;\n padding: 3px 8px;\n font-size: 12px;\n cursor: pointer;\n transition: background 0.15s;\n}\n.iwb-editor-size-apply:hover { background: #4488ff; color: #fff; }\n\n.iwb-editor-crop-info {\n color: #e8a735;\n font-size: 12px;\n font-weight: 600;\n font-variant-numeric: tabular-nums;\n white-space: nowrap;\n min-width: 60px;\n text-align: center;\n}\n\n.iwb-editor-crop-confirm, .iwb-editor-crop-cancel {\n padding: 6px 16px;\n border: none;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n}\n.iwb-editor-crop-confirm { background: #1a7f37; color: #fff; }\n.iwb-editor-crop-confirm:hover { background: #15803d; }\n.iwb-editor-crop-cancel { background: #cf222e; color: #fff; }\n.iwb-editor-crop-cancel:hover { background: #b91c1c; }\n\n/* 底部 */\n.iwb-editor-footer {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n padding: 12px 16px;\n background: #181825;\n border-top: 1px solid #313244;\n}\n\n.iwb-editor-btn {\n padding: 8px 20px;\n border: none;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s, transform 0.1s;\n}\n.iwb-editor-btn:hover { transform: scale(1.03); }\n.iwb-editor-btn-cancel { background: #45475a; color: #cdd6f4; }\n.iwb-editor-btn-cancel:hover { background: #585b70; }\n.iwb-editor-btn-new { background: #4488ff; color: #fff; }\n.iwb-editor-btn-new:hover { background: #3578f0; }\n.iwb-editor-btn-replace { background: #e8a735; color: #1e1e2e; }\n.iwb-editor-btn-replace:hover { background: #d49628; }\n\n/* ==================== 图层面板 ==================== */\n\n.iwb-editor-layer-panel {\n width: 290px;\n min-width: 290px;\n background: #181825;\n border-left: 1px solid #313244;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n}\n\n.iwb-editor-layer-panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 10px 12px;\n border-bottom: 1px solid #313244;\n}\n\n.iwb-editor-layer-panel-title {\n color: #cdd6f4;\n font-size: 13px;\n font-weight: 600;\n}\n\n.iwb-editor-layer-add-group {\n display: flex;\n gap: 4px;\n}\n\n.iwb-editor-layer-add-btn {\n background: #313244;\n border: 1px solid #45475a;\n border-radius: 6px;\n color: #cdd6f4;\n width: 26px;\n height: 26px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background 0.15s;\n}\n.iwb-editor-layer-add-btn:hover { background: #45475a; color: #e8a735; }\n.iwb-editor-layer-add-btn svg { display: block; }\n\n.iwb-editor-layer-list {\n flex: 1 1 auto;\n overflow-y: auto;\n padding: 4px;\n /* 拖动排序的插入线是绝对定位的,锚点必须在列表上(随滚动一起移动) */\n position: relative;\n}\n\n/* 图层项:整项改成「行 + 可选的不透明度行」,两行都靠 .iwb-layer-row 保持原来的横向排布 */\n.iwb-layer-item {\n display: block;\n padding: 5px 8px;\n border-radius: 6px;\n cursor: grab;\n user-select: none;\n transition: background 0.12s;\n margin-bottom: 2px;\n}\n.iwb-layer-row {\n display: flex;\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n.iwb-layer-item:hover { background: #313244; }\n.iwb-layer-item.active {\n background: #313244;\n box-shadow: inset 2px 0 0 #e8a735;\n}\n.iwb-layer-item.hidden { opacity: 0.5; }\n/* 拖动中:整行跟着指针浮起,压住相邻行;其余行由 JS 实时让位(落点反馈) */\n.iwb-layer-item.dragging {\n position: relative;\n z-index: 3;\n opacity: 1;\n background: #3a3d55;\n box-shadow: 0 6px 18px rgba(0, 0, 0, 0.5), inset 0 0 0 1px #e8a735;\n transition: none;\n cursor: grabbing;\n}\n.iwb-editor-layer-list.sorting,\n.iwb-editor-layer-list.sorting .iwb-layer-item { cursor: grabbing; }\n/* 画笔/橡皮作用目标:与「选中」分离,避免出现两个图层同时高亮 */\n.iwb-layer-paint { flex: 0 0 auto; color: #a6adc8; font-size: 11px; opacity: 0.85; }\n/* 不透明度角标:只有非 100% 才出现,一眼看出哪层被调淡了 */\n.iwb-layer-op { flex: 0 0 auto; font-size: 10px; color: #a6adc8; font-variant-numeric: tabular-nums; }\n\n/* 缩略图:canvas 画内容,类型图标垫在下面当兜底(空图层的缩略图是全透明的) */\n.iwb-layer-thumb {\n position: relative;\n flex: 0 0 auto;\n width: 22px;\n height: 22px;\n border-radius: 3px;\n overflow: hidden;\n background-color: #1e1e2e;\n background-image: linear-gradient(45deg, #33334a 25%, transparent 25%), linear-gradient(-45deg, #33334a 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #33334a 75%), linear-gradient(-45deg, transparent 75%, #33334a 75%);\n background-size: 8px 8px;\n background-position: 0 0, 0 4px, 4px -4px, -4px 0;\n box-shadow: inset 0 0 0 1px #45475a;\n}\n.iwb-layer-thumb canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }\n.iwb-layer-thumb .iwb-layer-icon {\n position: absolute;\n inset: 0;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #7f849c;\n}\n\n/* 不透明度行:只出现在选中项下,拖动时不能被重绘打断 */\n.iwb-layer-op-row {\n display: flex;\n align-items: center;\n gap: 6px;\n margin: 4px 0 1px 26px;\n}\n.iwb-layer-opacity {\n flex: 1 1 auto;\n min-width: 0;\n height: 14px;\n accent-color: #e8a735;\n cursor: pointer;\n}\n.iwb-layer-op-val {\n flex: 0 0 auto;\n width: 32px;\n text-align: right;\n font-size: 10px;\n color: #a6adc8;\n font-variant-numeric: tabular-nums;\n}\n\n/* 可重命名的图层名:悬停给个提示,进入编辑时换成输入框 */\n.iwb-layer-name.renamable:hover { color: #e8a735; }\n.iwb-layer-name-input {\n flex: 1 1 auto;\n min-width: 0;\n padding: 1px 4px;\n border: 1px solid #e8a735;\n border-radius: 3px;\n background: #1e1e2e;\n color: #cdd6f4;\n font-size: 12px;\n font-family: inherit;\n outline: none;\n}\n\n.iwb-layer-vis {\n background: none;\n border: none;\n color: #a6adc8;\n cursor: pointer;\n font-size: 13px;\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: background 0.12s;\n}\n.iwb-layer-vis:hover { background: #45475a; }\n\n.iwb-layer-icon {\n font-size: 13px;\n width: 18px;\n text-align: center;\n flex-shrink: 0;\n}\n\n.iwb-layer-name {\n color: #cdd6f4;\n font-size: 12px;\n flex: 1 1 auto;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n min-width: 0;\n}\n\n.iwb-layer-lock {\n background: none;\n border: none;\n color: #7f849c;\n cursor: pointer;\n width: 20px;\n height: 20px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: background 0.12s, color 0.12s;\n flex-shrink: 0;\n}\n.iwb-layer-lock:hover, .iwb-layer-lock.active { background: #45475a; color: #e8a735; }\n\n.iwb-layer-del {\n background: none;\n border: none;\n color: #585b70;\n cursor: pointer;\n font-size: 12px;\n width: 18px;\n height: 18px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 4px;\n transition: background 0.12s, color 0.12s;\n flex-shrink: 0;\n}\n.iwb-layer-del:hover { background: #cf222e; color: #fff; }\n\n/* SVG 图标尺寸 */\n.iwb-layer-vis svg { display: block; }\n.iwb-layer-icon svg { display: block; }\n.iwb-layer-lock svg { display: block; }\n.iwb-layer-del svg { display: block; }\n\n/* 独立 PS 风格颜色面板 */\n.iwb-editor-color-panel { padding: 12px; border-bottom: 1px solid #313244; background: #202033; }\n.iwb-editor-color-panel-title { color: #cdd6f4; font-size: 12px; font-weight: 600; margin-bottom: 10px; }\n.iwb-editor-color-panel-main { display: flex; align-items: center; gap: 10px; }\n.iwb-editor-color-current { width: 52px; height: 52px; border: 2px solid #cdd6f4; border-radius: 6px; overflow: hidden; display: block; background: #ff4444; }\n.iwb-editor-color-panel-input { width: 100%; height: 100%; padding: 0; border: 0; cursor: pointer; opacity: 0; }\n.iwb-editor-color-panel-values { min-width: 0; flex: 1; }\n.iwb-editor-color-hex { color: #cdd6f4; font: 600 12px monospace; display: block; margin-bottom: 8px; }\n.iwb-editor-color-swatches { display: flex; flex-wrap: wrap; gap: 6px; }\n.iwb-editor-color-panel-swatch { width: 20px; height: 20px; border: 1px solid #585b70; border-radius: 4px; cursor: pointer; }\n.iwb-editor-color-panel-swatch:hover { transform: scale(1.12); border-color: #fff; }\n.iwb-editor-panel-width { display: flex; align-items: center; gap: 8px; margin-top: 12px; color: #a6adc8; font-size: 11px; }\n.iwb-editor-panel-width-range { flex: 1; min-width: 60px; }\n.iwb-editor-panel-width-num { width: 42px; padding: 3px; background: #313244; color: #e8a735; border: 1px solid #45475a; border-radius: 4px; text-align: center; }\n\n/* 顶部独立操作区,避免操作按钮被竖向工具栏裁切 */\n.iwb-editor-actions { display: flex; align-items: center; gap: 5px; margin-left: auto; flex: 0 0 auto; }\n.iwb-editor-actions .iwb-editor-action { position: static !important; }\n.iwb-editor-actions .iwb-editor-action-restore { width: auto; padding: 0 9px; font-size: 12px; }\n\n/* 原图 canvas 只负责绘制像素,透明处透出 stack 的棋盘格。 */\n.iwb-editor-base { background: transparent !important; background-image: none !important; }\n\n/* 透明区域使用 Photoshop 风格的灰色棋盘格,覆盖整个实际图片区域。 */\n.iwb-editor-canvas-stack {\n background-color: #d6d6d6 !important;\n background-image:\n linear-gradient(45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(-45deg, #b8b8b8 25%, transparent 25%),\n linear-gradient(45deg, transparent 75%, #b8b8b8 75%),\n linear-gradient(-45deg, transparent 75%, #b8b8b8 75%) !important;\n background-size: 20px 20px !important;\n background-position: 0 0, 0 10px, 10px -10px, -10px 0 !important;\n}\n.iwb-editor-base { background: transparent !important; background-image: none !important; }\n\n/* 顶部参数区必须保持可见且可交互,避免被侧栏定位层覆盖。 */\n.iwb-editor-header { position: relative; min-height: 56px; overflow: visible; }\n.iwb-editor-params { position: relative; z-index: 30; overflow: visible; pointer-events: auto; }\n.iwb-editor-params input, .iwb-editor-params button, .iwb-editor-params label { pointer-events: auto; }\n.iwb-editor-brush-size, .iwb-editor-brush-hardness, .iwb-editor-brush-opacity { min-width: 70px; accent-color: #e8a735; }\n.iwb-editor-brush-num, .iwb-editor-eraser-num { pointer-events: auto; }\n\n/* canvas 的透明像素必须透出 stack 棋盘格,不能被黑色工作区遮住。 */\n.iwb-editor-canvas-stack { isolation: isolate; }\n.iwb-editor-layer-canvas, .iwb-editor-text, .iwb-editor-stroke, .iwb-editor-crop-overlay { background: transparent !important; }\n\n/* 透明棋盘格只覆盖原图的显示矩形,外围裁剪扩展区保持纯色。 */\n.iwb-editor-canvas-stack { background: #11111b !important; background-image: none !important; }\n.iwb-editor-transparency-grid { position: absolute; z-index: 0; pointer-events: none; background-color: #d6d6d6; background-image: linear-gradient(45deg, #b8b8b8 25%, transparent 25%), linear-gradient(-45deg, #b8b8b8 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #b8b8b8 75%), linear-gradient(-45deg, transparent 75%, #b8b8b8 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0; }\n.iwb-editor-layer-canvas, .iwb-editor-stroke, .iwb-editor-text { z-index: 1; }\n.iwb-editor-crop-overlay { z-index: 10; }\n\n/* 画布扩展区不得盖过编辑器外围,图片区域由透明层单独标识。 */\n.iwb-editor-canvas-stack { overflow: visible; max-width: 100%; max-height: 100%; background: #11111b !important; background-image: none !important; }\n.iwb-editor-transparency-grid { z-index: 0; overflow: hidden; }\n.iwb-editor-layer-canvas { z-index: 1; }\n.iwb-editor-stroke { z-index: 4; }\n.iwb-editor-text { z-index: 5; }\n.iwb-editor-crop-overlay { z-index: 10; }\n\n/* 导出操作与缩放同处顶栏,缩放独立靠右。 */\n.iwb-editor-export-actions { display: flex; align-items: center; gap: 6px; margin-left: 10px; flex: 0 0 auto; }\n.iwb-editor-export-actions .iwb-editor-btn { padding: 6px 10px; font-size: 11px; }\n.iwb-editor-footer { display: none !important; }\n\n.iwb-editor-export-actions { display: flex; align-items: center; gap: 6px; margin-left: 10px; flex: 0 0 auto; }\n.iwb-editor-export-actions .iwb-editor-btn { padding: 6px 10px; font-size: 11px; }\n.iwb-editor-footer { display: none !important; }\n\n/* 顶部七个操作按钮统一文本按钮样式,自适应中文宽度。 */\n.iwb-editor-actions { gap: 6px; }\n.iwb-editor-actions .iwb-editor-action { width: auto; min-width: 72px; height: 32px; padding: 0 12px; gap: 5px; font-size: 12px; font-weight: 500; white-space: nowrap; }\n.iwb-editor-actions .iwb-editor-action svg { width: 14px; height: 14px; flex: 0 0 auto; }\n.iwb-editor-export-actions .iwb-editor-btn { min-width: 72px; white-space: nowrap; }\n\n/* 顶部操作按钮统一为纯文本,图标隐藏并保持一致宽度。 */\n.iwb-editor-actions .iwb-editor-action svg { display: none !important; }\n.iwb-editor-actions .iwb-editor-action { min-width: 76px; width: 76px; justify-content: center; background: #3b3d52; color: #cdd6f4; }\n.iwb-editor-actions .iwb-editor-action:hover { background: #50536b; }\n.iwb-editor-actions .iwb-editor-action-restore { background: #3b3d52; color: #cdd6f4; }\n.iwb-editor-actions .iwb-editor-action-restore:hover { background: #50536b !important; }\n\n.iwb-editor-actions .iwb-editor-action svg { display: none !important; }\n.iwb-editor-actions .iwb-editor-action { min-width: 76px; width: 76px; justify-content: center; background: #3b3d52; color: #cdd6f4; }\n.iwb-editor-actions .iwb-editor-action:hover, .iwb-editor-actions .iwb-editor-action-restore:hover { background: #50536b !important; }\n\n.iwb-editor-actions .iwb-editor-action { width: auto; min-width: 76px; padding: 0 12px; gap: 5px; }\n.iwb-editor-actions .iwb-editor-action span { display: inline-block; }\n\n.iwb-editor-actions { margin-left: 12px; }\n.iwb-editor-actions .iwb-editor-btn { width: auto; min-width: 76px; height: 32px; padding: 0 12px; font-size: 12px; white-space: nowrap; }\n.iwb-editor-actions .iwb-editor-action { width: auto; min-width: 76px; }\n\n.iwb-editor-actions .iwb-editor-action { min-width: 52px; width: auto; padding: 0 10px; font-size: 12px; }\n.iwb-editor-brush-presets { display: flex; align-items: center; gap: 7px; margin-left: 4px; }\n.iwb-editor-brush-preset { display: inline-flex; align-items: center; gap: 3px; padding: 2px 3px; border: 0; background: transparent; color: #a6adc8; cursor: pointer; font-size: 11px; }\n.iwb-editor-brush-preset i { display: block; width: 12px; height: 12px; border-radius: 50%; background: #e8a735; border: 1px solid #f6d38a; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 16px; height: 16px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 20px; height: 20px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 24px; height: 24px; }\n.iwb-editor-brush-preset:hover, .iwb-editor-brush-preset.active { color: #fff; }\n\n/* 紧凑顶栏:操作按钮与描边快捷点仅保留必要视觉信息。 */\n.iwb-editor-actions .iwb-editor-action { width: 28px; min-width: 28px; height: 28px; padding: 0; }\n.iwb-editor-actions .iwb-editor-action svg { display: block !important; width: 14px; height: 14px; }\n.iwb-editor-brush-presets { gap: 5px; margin-left: 2px; }\n.iwb-editor-brush-preset { width: 24px; height: 24px; padding: 0; justify-content: center; }\n.iwb-editor-brush-preset i { width: 5px; height: 5px; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 8px; height: 8px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 12px; height: 12px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 16px; height: 16px; }\n\n/* 图层栏内嵌调色板:颜色直接点击应用,不弹出系统取色器。 */\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-color-current { width: 42px; height: 42px; flex: 0 0 42px; cursor: default; }\n.iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(7, 20px); gap: 5px; }\n.iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; }\n\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-color-current { width: 42px; height: 42px; flex: 0 0 42px; cursor: default; }\n.iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(7, 20px); gap: 5px; }\n.iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; }\n\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-palette-current { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-palette-current .iwb-editor-color-current { width: 26px; height: 26px; flex: 0 0 26px; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-hex { margin: 0; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }\n\n.iwb-editor-color-panel { padding: 10px; }\n.iwb-editor-palette-current { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-palette-current .iwb-editor-color-current { width: 26px; height: 26px; flex: 0 0 26px; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-hex { margin: 0; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }\n\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { width: 42px; height: 28px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { width: 42px; height: 28px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 9px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { width: 42px; height: 28px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n\n.iwb-editor-color-panel { padding: 9px; }\n.iwb-editor-inline-picker { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }\n.iwb-editor-inline-picker .iwb-editor-color-panel-input { display: block; width: 44px; height: 30px; padding: 0; opacity: 1; cursor: pointer; border: 1px solid #585b70; border-radius: 4px; }\n.iwb-editor-color-panel .iwb-editor-color-swatches { display: grid; grid-template-columns: repeat(6, 20px); gap: 7px; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch { width: 20px; height: 20px; border-radius: 50%; padding: 0; }\n.iwb-editor-color-panel .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }\n\n.iwb-editor-color-picker2 { display: flex; gap: 8px; height: 118px; }\n.iwb-color-sv { position: relative; flex: 1; background: linear-gradient(to top,#000,transparent),linear-gradient(to right,#fff,rgba(255,255,255,0)); background-color: #f44; border-radius: 4px; }\n.iwb-color-hue { width: 18px; border-radius: 4px; background: linear-gradient(to bottom,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00); }\n.iwb-editor-color-fields { display: flex; gap: 6px; margin: 8px 0; }\n.iwb-editor-color-hex-input { width: 72px; background:#313244; color:#cdd6f4; border:1px solid #585b70; padding:4px; }\n.iwb-editor-color-panel-input { width: 32px; height: 26px; opacity: 1; padding: 0; }\n\n.iwb-color-sv span, .iwb-color-hue span { position: absolute; width: 10px; height: 10px; border: 2px solid #fff; border-radius: 50%; box-shadow: 0 0 0 1px #222; transform: translate(-50%, -50%); pointer-events: none; }\n.iwb-color-sv span { left: 100%; top: 0; }\n.iwb-color-hue span { left: 50%; top: 0; }\n\n.iwb-compress-btn { color: #16a34a !important; font-size: 11px; font-weight: 700; }\n\n/* 新版浮动气泡栏内的工具按钮 */\n.iwb-node-floatbar .iwb-compress-btn { font-size: 11px; font-weight: 700; }\n.iwb-node-floatbar .iwb-cutout-btn.processing,\n.iwb-node-floatbar .iwb-whitebg-btn.processing,\n.iwb-node-floatbar .iwb-compress-btn.processing { animation: iwb-cutout-pulse 1s infinite; pointer-events: none; }\n\n\n/* 调色板:吸色按钮(替代原来的弹出式取色器) */\n.iwb-editor-color-eye { width: 26px; height: 26px; border: 1px solid #585b70; border-radius: 4px; background: #313244; color: #cdd6f4; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; padding: 0; }\n.iwb-editor-color-eye:hover { border-color: #e8a735; color: #e8a735; }\n\n/* 矢量对象独立画布:与位图图层统一参与 z 排序 */\n.iwb-editor-vec-canvas { position: absolute; top: 0; left: 0; z-index: 1; background: transparent !important; }\n\n/* 空白画布创建菜单 */\n.iwb-blank-menu { position: fixed; width: 242px; background: #fff; border: 1px solid #d0d7de; border-radius: 12px; box-shadow: 0 12px 32px rgba(15,23,42,.2); padding: 10px; z-index: 2147483000; font-size: 12px; color: #1f2328; }\n.iwb-blank-menu .iwb-blank-title { font-weight: 700; font-size: 12px; margin-bottom: 8px; }\n.iwb-blank-menu .iwb-blank-bg, .iwb-blank-menu .iwb-blank-res { display: flex; align-items: center; gap: 5px; margin-bottom: 7px; }\n.iwb-blank-menu .iwb-blank-bg span, .iwb-blank-menu .iwb-blank-res span { color: #656d76; min-width: 26px; }\n.iwb-blank-menu button { border: 1px solid #d0d7de; background: #f6f8fa; color: #1f2328; border-radius: 6px; padding: 3px 8px; cursor: pointer; font-size: 11px; }\n.iwb-blank-menu button:hover { background: #eff2f4; }\n.iwb-blank-menu button.on { background: #0ea5e9; border-color: #0ea5e9; color: #fff; }\n.iwb-blank-menu .iwb-blank-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 4px; }\n.iwb-blank-menu .iwb-blank-grid button { display: flex; flex-direction: column; gap: 1px; align-items: center; padding: 5px 4px; }\n.iwb-blank-menu .iwb-blank-grid b { font-weight: 600; }\n.iwb-blank-menu .iwb-blank-grid i { font-style: normal; color: #656d76; font-size: 10px; }\n\n/* 空参考图节点:常驻“空白画布”按钮(位于节点顶部中央) */\n.iwb-blank-inline-btn { position: absolute; top: 10px; left: 50%; transform: translateX(-50%); z-index: 6; display: inline-flex; align-items: center; gap: 5px; background: #fff; border: 1px solid #d0d7de; border-radius: 14px; padding: 4px 11px; color: #0ea5e9; font-size: 11px; font-weight: 600; cursor: pointer; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }\n.iwb-blank-inline-btn:hover { background: #f0f9ff; border-color: #0ea5e9; }\n.iwb-blank-inline-btn svg { width: 13px; height: 13px; }\n\n/* ============ UI 布局重构(参照 excalidraw) ============ */\n/* 顶部:功能按钮在左,工具栏横排整行、按快捷键排序并带数字角标 */\n.iwb-editor-header { flex-wrap: wrap; }\n.iwb-editor-header > .iwb-editor-title { order: 1; }\n.iwb-editor-header > .iwb-editor-actions { order: 2; }\n.iwb-editor-header > .iwb-editor-tools {\n position: static;\n order: 3;\n flex: 1 1 100%;\n width: auto;\n left: auto;\n top: auto;\n margin-top: 8px;\n flex-direction: row;\n justify-content: center;\n padding: 6px 10px;\n border-radius: 10px;\n}\n.iwb-editor-tool { position: relative; }\n.iwb-tool-key {\n position: absolute;\n right: -3px;\n bottom: -3px;\n font-size: 8px;\n line-height: 1;\n background: #45475a;\n color: #cdd6f4;\n padding: 1px 3px;\n border-radius: 3px;\n pointer-events: none;\n font-style: normal;\n font-weight: 600;\n}\n.iwb-editor-tool.active .iwb-tool-key { background: #1e1e2e; color: #e8a735; }\n.iwb-editor-header > .iwb-editor-tools .iwb-editor-divider { width: 1px; height: 22px; margin: 0 6px; }\n\n/* 左侧:工具参数设定栏(缩放/实心/图层/描边/硬度/透明度) */\n.iwb-editor-params {\n width: 216px;\n min-width: 216px;\n flex: 0 0 216px;\n flex-direction: column;\n align-items: stretch;\n gap: 12px;\n margin-left: 0;\n padding: 14px 12px;\n background: #181825;\n border-right: 1px solid #313244;\n overflow-y: auto;\n}\n.iwb-editor-params .iwb-editor-zoom { margin-left: 0; order: 0; }\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-val { min-width: 52px; text-align: center; }\n.iwb-editor-params .iwb-editor-layer-group { flex-wrap: wrap; justify-content: flex-start; }\n.iwb-editor-params .iwb-editor-brush-label { width: 100%; }\n.iwb-editor-params .iwb-editor-brush-presets { justify-content: flex-start; }\n.iwb-editor-params .iwb-editor-fill-btn { align-self: stretch; }\n.iwb-editor-main { display: flex; flex-direction: row; }\n\n/* ======== 布局重构 v2(按用户 6 点) ======== */\n.iwb-editor-main { display: flex; flex-direction: row; align-items: stretch; }\n\n/* 顶部一行:标题 + 工具栏(含数字角标) + 撤销重做清空还原 */\n.iwb-editor-header { flex-wrap: nowrap; align-items: center; }\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n.iwb-editor-header > .iwb-editor-tools {\n position: static; order: 1; flex: 1 1 auto; flex-basis: auto;\n margin-top: 0; width: auto; left: auto; top: auto;\n flex-direction: row; justify-content: center;\n padding: 0; background: transparent; border: 0; border-radius: 0;\n}\n.iwb-editor-header > .iwb-editor-divider { order: 2; }\n.iwb-editor-header > .iwb-editor-history { order: 3; display: flex; align-items: center; gap: 4px; }\n\n/* 左栏:调色板在上,参数竖排,导出按钮底部 */\n.iwb-editor-left {\n /* v1.16:宽度唯一出处。拖拽手柄写 --iwb-side-w,下面两条历史规则也都读它,\n 不再各写一个 240/220 的魔数(以前三处硬编码,改一次要搜三次)。 */\n width: var(--iwb-side-w, 280px); min-width: var(--iwb-side-w, 280px); flex: 0 0 var(--iwb-side-w, 280px);\n display: flex; flex-direction: column; gap: 14px;\n padding: 12px; background: #181825; border-right: 1px solid #313244; overflow-y: auto;\n}\n.iwb-editor-left > .iwb-editor-color-panel { padding: 0; background: transparent; border-bottom: 0; }\n.iwb-editor-left > .iwb-editor-params {\n width: auto; min-width: 0; flex: 1 1 auto;\n flex-direction: column; align-items: stretch; gap: 12px; margin-left: 0; padding: 0;\n}\n.iwb-editor-left > .iwb-editor-export-actions {\n display: flex; flex-direction: column; gap: 8px;\n margin-top: auto; padding-top: 12px; border-top: 1px solid #313244;\n}\n.iwb-editor-left > .iwb-editor-export-actions .iwb-editor-btn { width: 100%; }\n\n/* 参数竖排:一行一个设置 */\n.iwb-editor-params .iwb-editor-brush-group { display: flex; flex-direction: column; gap: 10px; }\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-btn,\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-val { flex: 1 1 auto; }\n.iwb-editor-params .iwb-editor-layer-group { flex-wrap: wrap; }\n\n/* 颜色值后面的 实心/边线 切换 */\n.iwb-editor-fill-pair { display: inline-flex; margin-left: 6px; }\n.iwb-editor-fill-pair .iwb-editor-fill-btn { align-self: center; }\n\n/* ======== 布局优化 v3 ======== */\n/* 左栏可交互(避免被画布/层级遮挡导致“调节不起作用”) */\n.iwb-editor-left { position: relative; z-index: 40; pointer-events: auto; }\n.iwb-editor-left input, .iwb-editor-left select, .iwb-editor-left button, .iwb-editor-left label { pointer-events: auto; }\n\n/* 顶部工具栏内的 面/边(实心) 切换按钮 */\n.iwb-editor-tools .iwb-editor-fill-btn {\n width: 42px; height: 32px; padding: 0; border: 0; border-radius: 8px;\n background: transparent; color: #cdd6f4; cursor: pointer; font-size: 11px; font-weight: 600;\n}\n.iwb-editor-tools .iwb-editor-fill-btn:hover { background: #45475a; }\n.iwb-editor-tools .iwb-editor-fill-btn.active { background: #e8a735; color: #1e1e2e; }\n\n/* 右侧图层面板内的图层顺序按钮 */\n.iwb-editor-layer-panel .iwb-editor-layer-group {\n display: flex; align-items: center; gap: 6px;\n padding: 10px 12px; border-bottom: 1px solid #313244;\n}\n.iwb-editor-layer-panel .iwb-editor-layer-group .iwb-editor-constraint-label { color: #a6adc8; font-size: 12px; margin-right: 2px; }\n\n/* 缩放(画面调整)移到左栏下方 */\n.iwb-editor-params .iwb-editor-zoom {\n order: 99; margin-top: 10px; padding-top: 10px; border-top: 1px solid #313244;\n}\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-btn { flex: 0 0 auto; }\n.iwb-editor-params .iwb-editor-zoom .iwb-editor-zoom-val { flex: 0 0 auto; }\n\n/* ======== 布局优化 v4 ======== */\n/* 交换左右栏:图层在左,调色板/参数在右 */\n.iwb-editor-main { flex-direction: row; }\n.iwb-editor-main > .iwb-editor-layer-panel { order: 1; border-left: 0; border-right: 1px solid #313244; }\n.iwb-editor-main > .iwb-editor-canvas-wrap { order: 2; }\n.iwb-editor-left { order: 3; border-right: 0; border-left: 1px solid #313244; }\n\n/* 硬度/透明度 数值与滑块对齐 */\n.iwb-editor-params .iwb-editor-brush-label .iwb-editor-brush-hardness-val,\n.iwb-editor-params .iwb-editor-brush-label .iwb-editor-brush-opacity-val {\n min-width: 40px; text-align: right; color: #cdd6f4; font-size: 12px;\n}\n.iwb-editor-params .iwb-editor-brush-label input[type="range"] { flex: 1 1 auto; }\n\n/* 缩放块放在参数区最底部 */\n.iwb-editor-params .iwb-editor-zoom, .iwb-editor-left .iwb-editor-zoom {\n display: flex; align-items: center; justify-content: center; gap: 8px;\n width: 100%; padding: 8px 4px; border-top: 1px solid #313244; margin-top: 12px;\n}\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-btn {\n flex: 0 0 auto; min-width: 28px; height: 26px; background: #313244; color: #cdd6f4; border: 0; border-radius: 6px; cursor: pointer; font-size: 14px;\n}\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-btn:hover { background: #45475a; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-val { min-width: 52px; text-align: center; color: #cdd6f4; font: 600 12px sans-serif; }\n\n/* 调色板与下方参数调节之间的横线分割 */\n.iwb-editor-params { border-top: 1px solid #313244; padding-top: 12px; }\n\n/* 色相条指示器需定位父级相对 */\n.iwb-color-hue { position: relative; }\n\n/* 顶部实心按钮与工具匹配:默认背景 */\n.iwb-editor-tools .iwb-editor-fill-btn { background: #313244; color: #cdd6f4; }\n\n/* 裁剪工具条:三行展示(比例 / 尺寸 / 确认取消),避免被挤压 */\n.iwb-editor-crop-bar {\n display: flex;\n flex-direction: column;\n gap: 8px;\n align-items: center;\n padding: 10px 14px;\n}\n.iwb-editor-crop-row { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; width: 100%; gap: 6px; }\n.iwb-editor-crop-row .iwb-editor-constraint-group { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; }\n.iwb-editor-crop-actions { gap: 10px; }\n.iwb-editor-crop-actions .iwb-editor-crop-info { min-width: 88px; text-align: center; }\n.iwb-editor-constraint-sep { display: none; }\n\n/* ======== 修复:左列(图层)占满高度,三列稳定布局 ======== */\n.iwb-editor-main { display: flex; flex-direction: row; align-items: stretch; }\n.iwb-editor-main > .iwb-editor-layer-panel { flex: 0 0 290px; min-width: 290px; width: 290px; }\n.iwb-editor-main > .iwb-editor-canvas-wrap { flex: 1 1 auto; min-width: 0; }\n.iwb-editor-left { flex: 0 0 var(--iwb-side-w, 280px); min-width: var(--iwb-side-w, 280px); width: var(--iwb-side-w, 280px); }\n.iwb-editor-layer-panel .iwb-editor-layer-list { flex: 1 1 auto; min-height: 0; overflow-y: auto; }\n\n/* ======== 顶部布局 v5:左侧重置类 / 中间工具 / 右侧保存类 ======== */\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n.iwb-editor-header > .iwb-editor-history { order: 1; display: flex; align-items: center; gap: 4px; }\n.iwb-editor-header > .iwb-editor-tools { order: 2; flex: 1 1 auto; justify-content: center; }\n.iwb-editor-header > .iwb-editor-export-actions { order: 3; display: flex; align-items: center; gap: 6px; margin-left: 4px; }\n\n/* 重置类(撤销/重做/清空/复原)统一小圆角按钮 */\n.iwb-editor-header .iwb-editor-history .iwb-editor-action {\n width: 30px; height: 30px; padding: 0; border: 0; border-radius: 8px;\n background: #313244; color: #cdd6f4; display: inline-flex; align-items: center; justify-content: center; cursor: pointer;\n}\n.iwb-editor-header .iwb-editor-history .iwb-editor-action:hover { background: #45475a; }\n.iwb-editor-header .iwb-editor-history .iwb-editor-action-restore { background: #313244; color: #cdd6f4; }\n\n/* 保存类(新建/覆盖/退出)统一样式 */\n.iwb-editor-header .iwb-editor-export-actions .iwb-editor-btn {\n height: 30px; padding: 0 14px; border: 0; border-radius: 8px; font-size: 12px; font-weight: 600;\n background: #313244; color: #cdd6f4; cursor: pointer;\n}\n.iwb-editor-header .iwb-editor-export-actions .iwb-editor-btn:hover { background: #45475a; }\n\n/* 调色板与参数之间的分割线及间距 */\n.iwb-editor-left > .iwb-editor-params { border-top: 1px solid #313244; margin-top: 16px; padding-top: 16px; }\n\n/* 笔刷快捷值 7 档圆点 */\n.iwb-editor-brush-presets { display: flex; align-items: center; gap: 8px; }\n.iwb-editor-brush-preset i { width: 6px; height: 6px; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 8px; height: 8px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 10px; height: 10px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 13px; height: 13px; }\n.iwb-editor-brush-preset:nth-child(5) i { width: 16px; height: 16px; }\n.iwb-editor-brush-preset:nth-child(6) i { width: 20px; height: 20px; }\n.iwb-editor-brush-preset:nth-child(7) i { width: 24px; height: 24px; }\n\n/* 缩放:缩小比例、圆角 */\n.iwb-editor-left .iwb-editor-zoom { gap: 6px; padding: 6px 4px; margin-top: 10px; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-btn { min-width: 26px; height: 24px; border-radius: 8px; font-size: 13px; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-val { min-width: 44px; font-size: 11px; }\n.iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-fit { font-size: 11px; padding: 0 8px; }\n\n/* 笔刷快捷值:压缩横向间距,避免右栏出现横向滚动条 */\n.iwb-editor-left { overflow-x: hidden; }\n.iwb-editor-params { overflow-x: hidden; }\n.iwb-editor-brush-presets { gap: 3px; flex-wrap: wrap; max-width: 100%; justify-content: flex-start; }\n.iwb-editor-brush-preset { padding: 0 1px; min-width: 0; flex: 0 0 auto; }\n.iwb-editor-brush-preset i { width: 5px; height: 5px; }\n.iwb-editor-brush-preset:nth-child(2) i { width: 7px; height: 7px; }\n.iwb-editor-brush-preset:nth-child(3) i { width: 9px; height: 9px; }\n.iwb-editor-brush-preset:nth-child(4) i { width: 11px; height: 11px; }\n.iwb-editor-brush-preset:nth-child(5) i { width: 14px; height: 14px; }\n.iwb-editor-brush-preset:nth-child(6) i { width: 17px; height: 17px; }\n.iwb-editor-brush-preset:nth-child(7) i { width: 20px; height: 20px; }\n\n/* 去掉参数模块右侧的边线(隐藏纵向滚动条与右边框) */\n.iwb-editor-left { border-right: 0 !important; scrollbar-width: none; -ms-overflow-style: none; }\n.iwb-editor-left::-webkit-scrollbar { width: 0; height: 0; display: none; }\n.iwb-editor-left > .iwb-editor-params { border-right: 0; }\n.iwb-editor-brush-presets::-webkit-scrollbar { width: 0; height: 0; display: none; }\n\n/* 独立悬浮工具条(扩展自建,不插入应用 React DOM) */\n.iwb-cutout-toolbar {\n position: fixed; z-index: 2147483000; display: none; align-items: center; gap: 3px;\n padding: 4px 6px; border-radius: 14px; background: #fff;\n border: 1px solid #d0d7de; box-shadow: 0 8px 28px rgba(15, 23, 42, 0.14);\n pointer-events: auto;\n}\n.iwb-cutout-toolbar button {\n width: 30px; height: 28px; padding: 0; border: 0; border-radius: 8px;\n background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center;\n}\n.iwb-cutout-toolbar button:hover { background: #eef2f7; }\n.iwb-cutout-toolbar button i { font-style: normal; font-size: 11px; font-weight: 700; }\n.iwb-cutout-toolbar button svg { display: block; }\n\n/* 顶部左右两组工具交换:左=新建/覆盖/退出,右=撤销/重做/清空/复原 */\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n/* 输出设定 + 下载/新建/覆盖/退出 收在顶栏最右侧(用户裁定 2026-11-04):\n order 排最后 + margin-left:auto 兜底,中间工具区 flex:1 会把它顶到右端 */\n.iwb-editor-header > .iwb-editor-export-actions { order: 9; margin-left: auto; margin-right: 0; flex: 0 0 auto; }\n.iwb-editor-header > .iwb-editor-tools { order: 2; flex: 1 1 auto; justify-content: center; }\n.iwb-editor-header > .iwb-editor-history { order: 3; margin-left: 0; }\n\n/* 图层面板:放大锁定 / 删除按钮的点击区域与图标 */\n.iwb-editor-layer-panel .iwb-layer-lock,\n.iwb-editor-layer-panel .iwb-layer-del {\n width: 24px; height: 24px; padding: 0; display: inline-flex; align-items: center; justify-content: center;\n}\n.iwb-editor-layer-panel .iwb-layer-lock svg,\n.iwb-editor-layer-panel .iwb-layer-del svg { width: 16px; height: 16px; }\n\n\n/* 图层按钮图标统一 14px */\n.iwb-editor-layer-panel .iwb-layer-vis svg,\n.iwb-editor-layer-panel .iwb-layer-lock svg,\n.iwb-editor-layer-panel .iwb-layer-del svg { width: 14px; height: 14px; }\n.iwb-editor-layer-panel .iwb-layer-vis,\n.iwb-editor-layer-panel .iwb-layer-lock,\n.iwb-editor-layer-panel .iwb-layer-del { width: 22px; height: 22px; padding: 0; display: inline-flex; align-items: center; justify-content: center; }\n\n/* ================================================================\n v1.1 便利版 UI(单张处理)\n 只追加、不重写历史样式:旧规则里的魔数定位在这里统一覆盖。\n 分区:顶栏 / 就地选项栏 / 竖工具栏 / 画布浮层 / 状态栏 / toast\n ================================================================ */\n\n/* ---- 顶栏:精简、一步可达 ---- */\n.iwb-editor-header { min-height: 44px; padding: 6px 12px; gap: 8px; }\n.iwb-editor-title em.iwb-editor-doc-size { font-style: normal; font-weight: 400; font-size: 11px; color: #7f849c; margin-left: 6px; }\n.iwb-editor-optionbar {\n display: flex; align-items: center; gap: 10px;\n height: 36px; min-height: 36px; padding: 0 12px;\n background: #202033; border-bottom: 1px solid #313244;\n color: #a6adc8; font-size: 12px;\n}\n.iwb-editor-optionbar-label { color: #7f849c; font-weight: 600; white-space: nowrap; }\n.iwb-editor-optionbar-body { display: flex; align-items: center; gap: 8px; flex: 1 1 auto; min-width: 0; }\n/* 右端通用快捷键提示。原来只有 @media 里的 display:none,没有任何基础样式,\n 于是它作为裸 span 参与 flex 收缩,被挤成两行还贴到右边缘外。 */\n.iwb-editor-optionbar-tip {\n flex: 0 0 auto; white-space: nowrap;\n color: #6c7086; font-size: 11px; padding-left: 4px;\n}\n.iwb-opt-label { color: #a6adc8; white-space: nowrap; }\n.iwb-opt-btn {\n background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;\n padding: 3px 9px; font-size: 12px; cursor: pointer;\n}\n.iwb-opt-btn:hover { background: #45475a; }\n.iwb-opt-btn.active { background: #4488ff; color: #fff; }\n.iwb-opt-num {\n width: 46px; padding: 2px 4px; background: #313244; color: #e8a735;\n border: 1px solid #45475a; border-radius: 5px; text-align: center; font-size: 12px;\n}\n/* 字体下拉:flex:0 0 auto 不能被压 —— 选项文字是 2 个汉字宽,压窄后会被截成「黑…」,\n 用户没法确认自己选的是哪一档。 */\n.iwb-opt-select {\n flex: 0 0 auto; padding: 2px 4px; background: #313244; color: #cdd6f4;\n border: 1px solid #45475a; border-radius: 5px; font-size: 12px; cursor: pointer;\n}\n.iwb-opt-select:hover { background: #45475a; }\n.iwb-opt-select option { background: #1e1e2e; color: #cdd6f4; }\n.iwb-opt-current { color: #e8a735; font-weight: 600; white-space: nowrap; }\n/* hint 是「说明」不是「控件」:不许被压缩。\n 早先带 text-overflow:ellipsis,在 36px 高的选项栏里会被压成「双击改…」这种半截文案,\n 比不显示更误导人;现在由父级 overflow-x 决定是完整显示还是整体滚出视野。 */\n.iwb-opt-hint { color: #7f849c; font-size: 11px; margin-left: auto; white-space: nowrap; flex: 0 0 auto; }\n\n.iwb-editor-more-wrap, .iwb-editor-export-settings-wrap { position: relative; flex: 0 0 auto; z-index: 45; }\n.iwb-editor-more-btn, .iwb-editor-panel-toggle, .iwb-editor-export-settings-btn {\n background: #313244; color: #cdd6f4; border: 1px solid #45475a; border-radius: 6px;\n padding: 5px 10px; font-size: 12px; cursor: pointer; white-space: nowrap;\n}\n.iwb-editor-more-btn:hover, .iwb-editor-panel-toggle:hover, .iwb-editor-export-settings-btn:hover { background: #45475a; }\n.iwb-editor-panel-toggle { padding: 5px 8px; }\n.iwb-editor-export-summary { color: #e8a735; margin: 0 2px; }\n\n.iwb-editor-more-menu, .iwb-editor-export-settings {\n display: none; position: absolute; top: 34px; z-index: 60;\n background: #252537; border: 1px solid #45475a; border-radius: 8px;\n padding: 6px; box-shadow: 0 10px 30px rgba(0,0,0,0.45);\n}\n.iwb-editor-more-menu { left: 0; width: 206px; flex-direction: column; gap: 2px; }\n.iwb-editor-more-menu.open, .iwb-editor-export-settings.open { display: flex; flex-direction: column; gap: 4px; }\n.iwb-editor-export-settings { right: 0; width: 268px; }\n.iwb-editor-more-menu button, .iwb-editor-export-row button {\n background: transparent; color: #cdd6f4; border: 0; border-radius: 5px;\n padding: 6px 8px; font-size: 12px; text-align: left; cursor: pointer; white-space: nowrap;\n}\n.iwb-editor-more-menu button:hover, .iwb-editor-export-row button:hover { background: #3b3d52; }\n.iwb-editor-more-menu kbd { float: right; color: #7f849c; font-size: 10px; }\n.iwb-editor-more-sep { height: 1px; background: #45475a; margin: 4px 0; }\n.iwb-editor-export-row { display: flex; align-items: center; gap: 4px; }\n.iwb-editor-export-row > span { width: 34px; flex: 0 0 34px; color: #7f849c; font-size: 11px; }\n.iwb-editor-export-row button { flex: 1 1 auto; text-align: center; background: #313244; }\n.iwb-editor-export-row button.active { background: #4488ff; color: #fff; }\n.iwb-editor-export-note { color: #7f849c; font-size: 11px; border-top: 1px solid #313244; padding-top: 6px; }\n.iwb-editor-btn-download { background: #1a7f37 !important; color: #fff !important; }\n.iwb-editor-btn-download:hover { background: #15803d !important; }\n\n/* ---- v1.2.8:底部浮动工具栏(Figma 风格,横排悬浮在画布底部居中) ----\n 工具栏已从 header 移进 canvas-wrap,只占画布区域宽度,不挤压左右面板;\n bottom 距容器 14px,配合 computeFit() 预留的底部空间,图片不会被压住。 */\n.iwb-editor-canvas-wrap > .iwb-editor-tools {\n position: absolute; left: 50%; bottom: 14px; transform: translateX(-50%);\n display: flex; flex-direction: row; align-items: center; gap: 2px;\n padding: 5px 8px; border-radius: 14px;\n background: rgba(24, 24, 37, 0.94);\n border: 1px solid #313244;\n box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);\n -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);\n z-index: 40;\n max-width: calc(100% - 28px);\n overflow-x: auto; overflow-y: hidden; scrollbar-width: none;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools::-webkit-scrollbar { display: none; }\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-tool,\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-action {\n width: 32px !important; height: 32px !important; min-width: 32px; flex: 0 0 auto; border-radius: 9px;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-divider {\n width: 1px; height: 20px; margin: 0 5px; flex: 0 0 auto; background: #45475a;\n}\n.iwb-editor-main { padding-left: 0; }\n.iwb-editor-main > .iwb-editor-layer-panel { flex: 0 0 260px !important; min-width: 260px !important; width: 260px !important; }\n.iwb-editor-left { flex: 0 0 var(--iwb-side-w, 280px) !important; min-width: var(--iwb-side-w, 280px) !important; width: var(--iwb-side-w, 280px) !important; }\n.iwb-editor-overlay.panels-collapsed .iwb-editor-layer-panel,\n.iwb-editor-overlay.panels-collapsed .iwb-editor-left { display: none !important; }\n.iwb-editor-zoom-hint { display: none !important; }\n\n/* ---- 交互层:蚂蚁线 / 笔刷环各自独立,互不擦除 ---- */\n.iwb-editor-selection-overlay, .iwb-editor-cursor-overlay {\n position: absolute; top: 0; left: 0; display: block; pointer-events: none;\n background: transparent !important;\n}\n.iwb-editor-selection-overlay { z-index: 11; }\n.iwb-editor-cursor-overlay { z-index: 12; }\n\n/* ---- 选区浮动操作条(体验后再定去留;纯视图,可随时替换) ---- */\n.iwb-editor-sel-bar {\n display: none; position: absolute; z-index: 30; align-items: center; gap: 4px;\n padding: 5px 6px; background: rgba(24,24,37,0.96);\n border: 1px solid #45475a; border-radius: 8px;\n box-shadow: 0 8px 26px rgba(0,0,0,0.45); white-space: nowrap;\n}\n.iwb-editor-sel-bar.as-menu { border-color: #4488ff; }\n.iwb-editor-sel-bar .iwb-editor-sel-info {\n color: #7f849c; font-size: 11px; padding: 0 6px;\n border-right: 1px solid #45475a; margin-right: 2px; font-variant-numeric: tabular-nums;\n}\n.iwb-editor-sel-bar button {\n background: #313244; color: #cdd6f4; border: 1px solid transparent; border-radius: 5px;\n padding: 4px 8px; font-size: 12px; cursor: pointer;\n}\n.iwb-editor-sel-bar button:hover:not(:disabled) { background: #4488ff; color: #fff; }\n.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]:hover:not(:disabled) { background: #cf222e; }\n.iwb-editor-sel-bar button:disabled { opacity: 0.35; cursor: not-allowed; }\n\n/* ---- 状态栏 / toast ---- */\n.iwb-editor-statusbar {\n display: flex; align-items: center; gap: 14px;\n height: 26px; min-height: 26px; padding: 0 12px;\n background: #181825; border-top: 1px solid #313244;\n color: #a6adc8; font-size: 11px; font-variant-numeric: tabular-nums;\n}\n.iwb-editor-statusbar span + span { border-left: 1px solid #313244; padding-left: 14px; }\n.iwb-editor-status-tool { margin-left: auto; color: #e8a735; }\n.iwb-editor-toast {\n position: fixed; left: 50%; bottom: 46px; z-index: 1000000;\n transform: translate(-50%, 12px); opacity: 0; pointer-events: none;\n transition: opacity 0.2s, transform 0.2s;\n background: #313244; color: #cdd6f4; padding: 8px 14px; border-radius: 8px;\n font-size: 12px; max-width: 80vw; box-shadow: 0 8px 26px rgba(0,0,0,0.45);\n}\n.iwb-editor-toast.show { opacity: 1; transform: translate(-50%, 0); }\n.iwb-editor-toast-success { background: #1a7f37; color: #fff; }\n.iwb-editor-toast-error { background: #cf222e; color: #fff; }\n.iwb-editor-toast-warn { background: #b06a00; color: #fff; }\n.iwb-editor-toast-info { background: #2f6fed; color: #fff; }\n\n@media (max-width: 900px) {\n .iwb-opt-hint, .iwb-editor-optionbar-tip { display: none; }\n .iwb-editor-session .iwb-editor-btn-cancel,\n .iwb-editor-export-actions .iwb-editor-btn-cancel { display: none; }\n}\n\n\n/* 输出设置:按预设显示的行(尺寸/体积只属于电商方图)\n 注意 `.iwb-editor-export-row` 是 display:flex,会盖掉 UA 的 [hidden]{display:none},\n 必须显式 !important,否则 JS 设 hidden 后行还留在面板里。 */\n.iwb-editor-export-row[hidden] { display: none !important; }\n.iwb-editor-export-settings [data-export-key]:disabled {\n opacity: 0.32; cursor: not-allowed; text-decoration: line-through;\n}\n.iwb-editor-export-settings [data-export-key]:disabled:hover { background: #313244; }\n\n/* 选项栏参数控件(v1.2):滑杆 + 数字框 + 实时读数,一行放得下就该保持一行 */\n.iwb-opt-range {\n width: 84px; height: 4px; flex: 0 0 auto;\n accent-color: #4488ff; cursor: pointer;\n}\n.iwb-opt-val {\n min-width: 32px; flex: 0 0 auto; color: #e8a735; font-size: 11px;\n font-variant-numeric: tabular-nums; text-align: right;\n}\n.iwb-opt-unit { color: #7f849c; font-size: 11px; flex: 0 0 auto; }\n/* 窄屏:参数多到放不下时横向滚动,不换行(换行会把 36px 高的选项栏撑开压画布) */\n.iwb-editor-optionbar-body { overflow-x: auto; scrollbar-width: none; }\n.iwb-editor-optionbar-body::-webkit-scrollbar { display: none; }\n@media (max-width: 1100px) {\n .iwb-opt-range { width: 64px; }\n}\n\n/* ---- v1.2.2 ---- */\n/* 选项栏快捷值圆点(笔刷大小 / 矢量描边推荐值),与侧栏描边快捷点同交互 */\n.iwb-opt-dots { display: inline-flex; align-items: center; gap: 3px; flex: 0 0 auto; }\n.iwb-opt-dot {\n display: inline-flex; align-items: center; justify-content: center;\n width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%;\n background: transparent; cursor: pointer;\n}\n.iwb-opt-dot i { display: block; width: 5px; height: 5px; border-radius: 50%; background: #e8a735; border: 1px solid #f6d38a; }\n.iwb-opt-dot:nth-child(2) i { width: 7px; height: 7px; }\n.iwb-opt-dot:nth-child(3) i { width: 9px; height: 9px; }\n.iwb-opt-dot:nth-child(4) i { width: 11px; height: 11px; }\n.iwb-opt-dot:nth-child(5) i { width: 14px; height: 14px; }\n.iwb-opt-dot:nth-child(6) i { width: 17px; height: 17px; }\n.iwb-opt-dot:nth-child(7) i { width: 20px; height: 20px; }\n.iwb-opt-dot:hover { background: #313244; }\n\n/* 裁剪控件在选项栏内联布局(旧 .iwb-editor-crop-bar 的绝对定位容器已删除) */\n.iwb-editor-optionbar-body .iwb-editor-crop-info {\n min-width: 88px; text-align: center; color: #e8a735;\n font-size: 11px; font-variant-numeric: tabular-nums; flex: 0 0 auto;\n}\n.iwb-editor-optionbar-body .iwb-editor-size-input {\n width: 52px; padding: 2px 5px; font-size: 11px;\n background: #1e2030; color: #e5e9f0;\n border: 1px solid #45475a; border-radius: 4px;\n}\n.iwb-editor-optionbar-body .iwb-editor-size-input:focus { outline: none; border-color: #4488ff; }\n/* 硬度滑杆加宽:参数太密时默认 84px 拉不开,用户反馈「软度调节不明显」(2026-11-04) */\n.iwb-editor-optionbar-body .iwb-opt-range-wide { width: 140px; }\n.iwb-editor-optionbar-body .iwb-opt-dots { margin-left: 2px; }\n.iwb-editor-optionbar-body .iwb-editor-size-input::-webkit-inner-spin-button { -webkit-appearance: none; }\n.iwb-editor-optionbar-body .iwb-editor-crop-confirm,\n.iwb-editor-optionbar-body .iwb-editor-crop-cancel {\n padding: 3px 10px; border: 0; border-radius: 4px; cursor: pointer; font-size: 12px; flex: 0 0 auto;\n}\n.iwb-editor-optionbar-body .iwb-editor-crop-confirm { background: #1a7f37; color: #fff; }\n.iwb-editor-optionbar-body .iwb-editor-crop-confirm:hover { background: #15803d; }\n.iwb-editor-optionbar-body .iwb-editor-crop-cancel { background: #cf222e; color: #fff; }\n.iwb-editor-optionbar-body .iwb-editor-crop-cancel:hover { background: #b91c1c; }\n\n/* ---- v1.2.3:侧栏只留调色板 + 缩放 ---- */\n/* 笔刷粗细/快捷点从侧栏移除后,缩放条直接挂在 aside 下:贴底,与调色板拉开距离 */\n.iwb-editor-left > .iwb-editor-zoom { margin-top: auto; border-top: 1px solid #313244; padding-top: 10px; }\n\n/* ================================================================\n v1.2.4:顶栏命令带(原「更多 ▾」图标化)\n 布局:标题 | 撤销·重做·还原 | ⟨图层 新建/导入⟩ ⟨顺序 置顶/上移/下移/置底⟩ ⟨视图 适应/侧栏⟩ | …… | 输出·下载·新建·覆盖·退出\n ================================================================ */\n.iwb-editor-header > .iwb-editor-history { order: 1; }\n.iwb-editor-header > .iwb-editor-commands { order: 3; display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-divider { width: 1px; height: 20px; background: #313244; flex: 0 0 auto; }\n.iwb-editor-cmdgroup { display: flex; align-items: center; gap: 4px; }\n.iwb-editor-cmdgroup[data-group="order"] { gap: 2px; }\n/* 顶栏里的命令按钮统一 30×30 方角,和撤销/重做同款 */\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-action,\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn {\n width: 30px; height: 30px; min-width: 30px; padding: 0; border: 0; border-radius: 8px;\n background: #313244; color: #cdd6f4;\n display: inline-flex; align-items: center; justify-content: center; cursor: pointer;\n}\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-action:hover:not(:disabled),\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:hover:not(:disabled) { background: #45475a; }\n.iwb-editor-header > .iwb-editor-commands .iwb-editor-layer-btn:disabled { opacity: 0.35; cursor: not-allowed; }\n/* 选区命令(全选/反选/取消):v1.2.5 起放在「选择」工具的选项栏里,不再占竖工具条 */\n/* 分隔线只负责「分组」,不负责「推到右边」。\n 原来写的是 margin: 0 4px 0 auto —— auto 会把分隔线之后的内容整组推到最右侧,\n 在选项栏已经排满的情况下(文字样式那一行)直接把后面的选区按钮顶出可视区,\n 看起来就是「这个工具下没有那几个按钮」。留白交给末尾的 .iwb-opt-hint。 */\n.iwb-opt-sep { width: 1px; height: 18px; background: #313244; margin: 0 2px; flex: 0 0 auto; }\n.iwb-opt-selcmd {\n width: 26px; height: 26px; min-width: 26px; padding: 0; border: 0; border-radius: 7px;\n background: #26263a; color: #cdd6f4; flex: 0 0 auto;\n display: inline-flex; align-items: center; justify-content: center; cursor: pointer;\n}\n.iwb-opt-selcmd:hover { background: #45475a; }\n\n/* ================================================================\n v1.2.11:顶栏次序与配色(用户裁定 2026-11-04 晚)\n 布局:标题 | ⟨新建·覆盖·退出⟩ | 撤销·重做·还原 | 顺序·视图 | …… | 输出·导出\n 标题在前(它是标题,不能跑到按钮后面);会话组三键统一中性色,不再花\n ================================================================ */\n.iwb-editor-header > .iwb-editor-title { order: 0; }\n.iwb-editor-header > .iwb-editor-session { order: 1; display: flex; align-items: center; gap: 6px; flex: 0 0 auto; margin-left: 8px; }\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn { padding: 6px 10px; font-size: 11px; min-width: 56px; white-space: nowrap; }\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-new,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-replace,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-cancel { background: #45475a; color: #cdd6f4; }\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-new:hover,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-replace:hover,\n.iwb-editor-header > .iwb-editor-session .iwb-editor-btn-cancel:hover { background: #585b70; }\n/* 标题与会话组之间、撤销组与命令带之间的竖分隔 */\n.iwb-editor-header > .iwb-editor-session { margin-right: 4px; }\n.iwb-editor-header > .iwb-editor-divider { width: 1px; height: 20px; background: #313244; flex: 0 0 auto; margin: 0 4px; }\n\n/* ================================================================\n v1.3:色板搬进工具栏(用户裁定 2026-11-05)\n 工具栏最左一个「当前色圆点」,点开在工具栏上方弹出色板:\n [SV + 色相] | [吸管 + hex] | [6×2 推荐色]\n 弹层挂在 modal 下(不是工具栏里):工具栏 overflow-x:auto、\n canvas-wrap overflow:clip,放里面必被裁;位置由 events.js 按按钮矩形算。\n ================================================================ */\n.iwb-editor-modal { position: relative; }\n\n/* ---- v1.11:工具栏颜色双槽(描边 + 填充) ----\n 一个 30px 的按钮位上叠两颗:左上 19px 是描边,右下 19px 是填充。\n 描边压在上面(最常用),填充露出右下角,一眼能看出是两格、谁是上级。\n 只有「描边」概念的工具(画笔/文字/箭头)把填充槽藏起来,描边槽放大占满,\n 不留一个空位让人猜。 */\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-pair {\n position: relative; width: 30px; height: 30px; flex: 0 0 auto;\n}\n.iwb-editor-color-pair .iwb-editor-color-btn {\n position: absolute; width: 19px; height: 19px; min-width: 0; padding: 0;\n border: 0; border-radius: 6px; background: #181825; cursor: pointer;\n display: inline-flex; align-items: center; justify-content: center;\n box-shadow: 0 0 0 1.5px #585b70;\n}\n.iwb-editor-color-pair [data-color-slot="stroke"] { left: 0; top: 0; z-index: 2; }\n.iwb-editor-color-pair [data-color-slot="fill"] { right: 0; bottom: 0; z-index: 1; }\n.iwb-editor-color-pair .iwb-editor-color-btn:hover { box-shadow: 0 0 0 2px #89b4fa; }\n.iwb-editor-color-pair .iwb-editor-color-btn.active { box-shadow: 0 0 0 2px #e8a735; }\n.iwb-editor-color-pair .iwb-editor-color-btn i {\n width: 12px; height: 12px; border-radius: 3px; display: block;\n background-color: #ff4444; background-size: 100% 100%;\n}\n/* 无填充:不露颜色本身,画一道红斜杠 —— 留着上次的颜色会被当成「现在填的就是它」 */\n.iwb-editor-color-pair .iwb-editor-color-btn.is-none i {\n background-color: #45475a !important;\n background-image: linear-gradient(135deg, transparent calc(50% - 1px), #f38ba8 calc(50% - 1px), #f38ba8 calc(50% + 1px), transparent calc(50% + 1px));\n}\n/* 填充色还在「跟随描边色」:右下角一个小三角,表示它不是自己指定的 */\n.iwb-editor-color-pair .iwb-editor-color-btn.is-follow::after {\n content: \'\'; position: absolute; right: 0; bottom: 0;\n border-left: 4px solid transparent; border-bottom: 4px solid #89b4fa;\n}\n.iwb-editor-color-pair[data-color-mode="single"] [data-color-slot="fill"] { display: none; }\n.iwb-editor-color-pair[data-color-mode="single"] [data-color-slot="stroke"] {\n left: 1px; top: 1px; width: 28px; height: 28px; border-radius: 8px;\n}\n.iwb-editor-color-pair[data-color-mode="single"] [data-color-slot="stroke"] i { width: 20px; height: 20px; border-radius: 6px; }\n\n/* ---- v1.12:文字上下文的第三格「文本框底色」 ----\n 文字对象天生三个颜色(文字 / 描边 / 底色),两格叠放塞不下第三个。\n 文字上下文三格横排,各 18px,谁在调谁戴橙圈。\n 选择器必须带上 .iwb-editor-canvas-wrap > .iwb-editor-tools 前缀:上面那条\n 30px 宽的定位规则是三段选择器,少了前缀优先级压不过它,格子会被挤成 10px。 */\n.iwb-editor-color-pair [data-color-slot="bg"] { display: none; }\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-pair[data-color-mode="triple"] {\n width: 62px; display: flex; align-items: center; justify-content: space-between;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-pair[data-color-mode="triple"] [data-color-slot] {\n position: relative; left: auto; top: auto; right: auto; bottom: auto; z-index: 1;\n display: inline-flex; flex: 0 0 auto; width: 18px; height: 18px; border-radius: 5px;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-pair[data-color-mode="triple"] [data-color-slot="bg"] {\n display: inline-flex;\n}\n.iwb-editor-canvas-wrap > .iwb-editor-tools .iwb-editor-color-pair[data-color-mode="triple"] .iwb-editor-color-btn i {\n width: 11px; height: 11px; border-radius: 3px;\n}\n\n\n.iwb-editor-color-pop {\n position: absolute; z-index: 60; display: flex; flex-direction: column; align-items: stretch; gap: 7px;\n /* 固定宽度(不是让内容撑):绝对定位元素是 shrink-to-fit,宽度会跟着最长内容走 ——\n 文字工具多出「底色」tab 时头部变宽,弹层当场变宽 17px 再跳回来,定位也要重算。\n 440 = 内容 416(SV 176 + 8 + 色相 16 + 10 + 1 + 10 + 色块 195)+ 左右 padding 22 + 边框 2。 */\n box-sizing: border-box; width: 440px;\n padding: 9px 11px; border-radius: 12px;\n background: rgba(24, 24, 37, 0.97); border: 1px solid #313244;\n box-shadow: 0 16px 40px rgba(0, 0, 0, 0.55);\n -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);\n}\n.iwb-editor-color-pop[hidden] { display: none; }\n/* 弹层头部(v1.19 一行装完):\n 调哪个槽(描边/填充/底色)│ 吸管 + 色值 │ 去色 │ 图钉\n 原来「吸管 + 色值」在右列占一整块,现在提到头部,body 的整块高度都留给色块。 */\n.iwb-color-pop-head { display: flex; align-items: center; gap: 6px; }\n/* 竖线:分隔「调哪个槽 / 取色工具 / 去色·钉住」三组,比空白更清楚,又不加边框重量 */\n.iwb-color-pop-bar { width: 1px; height: 16px; background: #313244; flex: 0 0 auto; }\n/* 「吸管 + 色值 + 图钉」整组贴最右(margin-left:auto,v1.20.1)。\n v1.20 只推图钉、吸管与色值紧跟 tab —— tab 从 2 个变 3 个(文字工具加「底色」),\n 这组就整块左右浮一次。现在 tab 组独占左侧、空隙全给它吸收,右组从第一条竖线起整体钉住。 */\n.iwb-color-pop-tools { margin-left: auto; display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }\n\n.iwb-color-pop-tab {\n display: inline-flex; align-items: center; gap: 5px; height: 24px; padding: 0 9px;\n /* 不许被压缩、不许折行:头部一行要同时装下 tab + 吸管 + 色值 + 去色 + 图钉,\n 宽度不够时该缩的是色值框(flex:0 1),不是把「描边」压成竖排两个字 */\n flex: 0 0 auto; white-space: nowrap;\n border: 1px solid transparent; border-radius: 7px; background: #232334;\n color: #a6adc8; font: 500 11.5px/1 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;\n cursor: pointer;\n}\n.iwb-color-pop-tab i {\n width: 11px; height: 11px; border-radius: 3px; display: block;\n background-color: #ff4444; background-size: 100% 100%;\n box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.18);\n}\n.iwb-color-pop-tab:hover { background: #313244; color: #cdd6f4; }\n.iwb-color-pop-tab.active { background: #313244; color: #fff; border-color: #e8a735; }\n.iwb-color-pop-tab.is-none i {\n background-color: #45475a !important;\n background-image: linear-gradient(135deg, transparent calc(50% - 1px), #f38ba8 calc(50% - 1px), #f38ba8 calc(50% + 1px), transparent calc(50% + 1px));\n}\n.iwb-color-pop-tab[hidden] { display: none; }\n/* 去色(v1.20,用户 2026-11-10):头部那颗带文字的按钮下移到「常用色第一格」,\n 尺寸、间距跟色块完全一致(20px 圆),只是画虚线边框 + 斜圈图标 ——\n 它是开关不是色块,所以不用填充色表达状态,只换边框/图标色。\n 永远显示(不可用时不 hidden,只 disabled + 变灰),位置才记得住、头部也不重排。 */\n.iwb-color-pop-none {\n flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center;\n width: 20px; height: 20px; padding: 0; margin: 0; box-sizing: border-box;\n border: 1px dashed #585b70; border-radius: 50%; background: transparent; color: #a6adc8;\n cursor: pointer; transition: transform 0.08s ease, border-color 0.12s ease, color 0.12s ease;\n}\n.iwb-color-pop-none svg { flex: 0 0 auto; width: 12px; height: 12px; }\n/* hover 只对可用态生效:disabled 时不该有放大反馈,否则看着像能点 */\n.iwb-color-pop-none:not(:disabled):hover { border-color: #f38ba8; color: #f38ba8; transform: scale(1.14); }\n.iwb-color-pop-none.active { border-style: solid; border-color: #f38ba8; color: #f38ba8; background: rgba(243, 139, 168, 0.14); }\n/* 不可用:整颗压到 42% 不透明度 —— 灰到能看出「这里有个去色,但现在用不上」,\n 但不至于淡到看不见(32% 时在深底上几乎消失,等于又变成了「消失」,只是慢一点)。\n cursor 保持 default,不给 pointer。 */\n.iwb-color-pop-none:disabled,\n.iwb-color-pop-none.is-disabled {\n opacity: 0.42; cursor: default; color: #8b8fa8; border-color: #4a4a5e;\n background: transparent; transform: none;\n}\n.iwb-color-pop-none[hidden] { display: none; }\n.iwb-color-pop-body { display: flex; align-items: stretch; gap: 10px; }\n.iwb-color-pop-picker { display: flex; gap: 8px; flex: 0 0 auto; }\n.iwb-editor-color-pop .iwb-color-sv { width: 176px; height: 104px; flex: 0 0 176px; }\n.iwb-editor-color-pop .iwb-color-hue { width: 16px; height: 104px; flex: 0 0 16px; }\n.iwb-color-pop-sep { width: 1px; align-self: stretch; background: #313244; flex: 0 0 auto; }\n\n/* ==== 色块区(v1.19,用户 2026-11-10)====\n 常用色 8×2 在上、最近色 8×2 在下,块间 1px 细线,不写小标题。\n 8 列 20px = 195px;两排色块(45 + 11 + 45 = 101)刚好填满左侧取色器 104 的高度,\n 所以整个弹层只有头部 + 取色器两层,没有多余留白。 */\n.iwb-color-pop-side {\n display: flex; flex-direction: column; justify-content: center;\n width: 195px; flex: 0 0 195px; gap: 0;\n}\n/* 细线分隔:只加在「块与块之间」,第一块前面不加,否则顶部多一条悬空的线。\n 色号比背景亮两档(#3b3b4e):没有小标题时,这条线是唯一能看出「常用 / 最近」分界的东西,\n 按 #313244 画在深底上几乎看不见。 */\n.iwb-color-pop-side > * + * {\n border-top: 1px solid #3b3b4e; margin-top: 5px; padding-top: 5px;\n}\n.iwb-color-group { display: flex; flex-direction: column; gap: 0; min-width: 0; flex: 0 0 auto; }\n/* 标题不显示:「常用色 / 最近」各占一行是这块面板最浪费的高度,\n 色块自己的 title 已经写明是哪一个、哪一个最近用过 */\n.iwb-editor-color-pop .iwb-color-group-label { display: none; }\n/* display:flex 会盖掉 [hidden] 的默认 display:none,必须显式写一条 */\n.iwb-color-group[hidden] { display: none; }\n\n/* 色值输入定宽 96(v1.20.1 由 124 再收窄,用户「设置框可以小一些,现在长了」)。\n #RRGGBB 七个字符在 13px 等宽下约 55px,加左右 padding 10px 仍有 30px 余量;\n 它现在是右组里的一颗「读数」,不该比吸管/图钉重。仍然定宽不可缩。 */\n.iwb-editor-color-pop .iwb-editor-color-hex-input {\n flex: 0 0 96px; width: 96px; height: 26px; padding: 0 4px; text-align: center;\n font: 600 12px monospace; border-radius: 6px; box-sizing: border-box;\n}\n.iwb-editor-color-pop .iwb-editor-color-swatches {\n display: grid; grid-template-columns: repeat(8, 20px); grid-auto-rows: 20px;\n gap: 5px; flex: 0 0 auto; align-content: center;\n}\n.iwb-editor-color-pop .iwb-editor-color-panel-swatch {\n width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; cursor: pointer;\n transition: transform 0.08s ease;\n}\n.iwb-editor-color-pop .iwb-editor-color-panel-swatch:hover { transform: scale(1.14); }\n.iwb-editor-color-pop .iwb-editor-color-panel-swatch.active {\n outline: 2px solid #fff; outline-offset: 2px;\n}\n.iwb-editor-color-pop .iwb-editor-color-eye { width: 26px; height: 26px; border-radius: 6px; flex: 0 0 auto; }\n\n/* ==== 钉住(v1.18 / v1.19 改为流式)====\n v1.18 是绝对定位贴右上角(躲开「无」按钮显隐带来的位移);\n v1.19「吸管 + 色值」也进了头部,头部本来就是一排可变宽控件,\n 图钉跟着流走反而更稳 —— 竖线已经把「去色 | 图钉」和左边隔开,位置不会再被误读。 */\n.iwb-color-pop-pin {\n flex: 0 0 auto; width: 24px; height: 24px; padding: 0;\n display: inline-flex; align-items: center; justify-content: center;\n border: 1px solid transparent; border-radius: 6px; background: transparent;\n color: #9aa0b4; cursor: pointer;\n}\n.iwb-color-pop-pin:hover { background: #313244; color: #cdd6f4; }\n/* 钉住态:琥珀色描边 + 淡底。用颜色而不是旋转表达「已钉住」,\n 旋转 45° 的图钉在 13px 下看起来像歪掉的问号。 */\n.iwb-color-pop-pin.active {\n background: rgba(232, 167, 53, 0.16); border-color: #e8a735; color: #f0b752;\n}\n\n/* ================================================================\n v1.4:侧栏「快速效果」\n 3×2 网格,作用于当前位图图层。只做颜色/采样变换,不改几何。\n 图标全部用 CSS 渐变画(不引第三方库,也不加 SVG 体积)。\n ================================================================ */\n.iwb-editor-fx {\n display: flex; flex-direction: column; gap: 8px;\n flex: 0 0 auto;\n}\n.iwb-editor-fx-head {\n display: flex; align-items: center; justify-content: space-between; gap: 6px;\n}\n.iwb-editor-fx-title {\n font-size: 11px; font-weight: 600; letter-spacing: 0.4px; color: #a6adc8;\n}\n.iwb-editor-fx-target {\n max-width: 116px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n padding: 2px 6px; border-radius: 5px; background: #313244; color: #cdd6f4;\n font-size: 10px; line-height: 1.4;\n}\n.iwb-editor-fx-grid {\n display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px;\n}\n.iwb-editor-fx-btn {\n display: flex; flex-direction: column; align-items: center; gap: 5px;\n padding: 7px 2px 6px; border: 1px solid transparent; border-radius: 9px;\n background: #232334; color: #cdd6f4;\n font: 500 10.5px/1 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;\n cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease, transform 0.08s ease;\n}\n.iwb-editor-fx-btn:hover { background: #313244; border-color: #45475a; }\n.iwb-editor-fx-btn:active { transform: scale(0.96); }\n.iwb-editor-fx-btn:focus-visible { outline: 2px solid #89b4fa; outline-offset: 1px; }\n/* v1.8:当前生效的效果。必须与 hover 一眼区分 —— 拖动强度滑杆时要能看出在调哪个效果 */\n.iwb-editor-fx-btn.is-active {\n background: #2c2735; border-color: #e8a735; color: #f3dcb0;\n}\n.iwb-editor-fx-btn.is-active .iwb-editor-fx-ico {\n box-shadow: inset 0 0 0 1px rgba(232, 167, 53, 0.75);\n}\n.iwb-editor-fx-ico {\n width: 22px; height: 22px; border-radius: 5px; display: block;\n background-color: #d9d9e3;\n box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);\n}\n/* 图标统一垫浅色底:纯黑部分若直接压在深色按钮上会「消失」,看着像缺了个角 */\n.ico-invert { background-image: linear-gradient(135deg, transparent 0 50%, #14141f 50% 100%); }\n.ico-gray { background-image: linear-gradient(90deg, #12121c 0, #8a8a99 50%, #f4f4f8 100%); }\n.ico-boost {\n background-image: radial-gradient(circle at 50% 52%, #ffffff 0 24%, #cfcfdd 42%, #6e6e85 100%);\n}\n.ico-contrast { background-image: linear-gradient(90deg, #000000 0 46%, #ffffff 54% 100%); }\n.ico-soft {\n background-image: radial-gradient(circle at 50% 50%, #23233a 0 16%, rgba(35, 35, 58, 0.5) 34%, rgba(35, 35, 58, 0.16) 50%, rgba(35, 35, 58, 0) 68%);\n}\n.ico-mosaic {\n background-image: repeating-conic-gradient(#6b6b80 0% 25%, #d9d9e3 0% 50%);\n background-size: 10px 10px;\n}\n.iwb-editor-fx-tip {\n margin: 0; font-size: 10px; line-height: 1.55; color: #6c7086;\n}\n\n/* v1.8:效果参数滑杆。范围与单位随效果切换(马赛克=块大小 px、柔化=半径 px、其余=强度 %)。\n 未点效果 / 目标层被切走时加 .iwb-editor-fx-adj-off 整条置灰。 */\n.iwb-editor-fx-adj {\n display: flex; flex-direction: column; gap: 4px;\n padding: 6px 8px 5px; border-radius: 7px;\n background: #1e1e2c; border: 1px solid #2f2f42;\n transition: opacity 0.12s ease;\n}\n.iwb-editor-fx-adj-head {\n display: flex; align-items: center; justify-content: space-between; gap: 6px;\n}\n.iwb-editor-fx-adj-name {\n font-size: 10.5px; font-weight: 500; color: #b9c0d8;\n overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n}\n.iwb-editor-fx-adj-val {\n font-size: 10.5px; color: #e8a735; font-variant-numeric: tabular-nums; flex: 0 0 auto;\n}\n.iwb-editor-fx-adj-off { opacity: 0.5; }\n.iwb-editor-fx-range {\n -webkit-appearance: none; appearance: none;\n width: 100%; height: 14px; margin: 0; background: transparent; cursor: pointer;\n}\n.iwb-editor-fx-range::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: #313244; }\n.iwb-editor-fx-range::-webkit-slider-thumb {\n -webkit-appearance: none; appearance: none;\n width: 12px; height: 12px; margin-top: -4px; border-radius: 50%;\n background: #e8a735; border: 1px solid #1e1e2c;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);\n}\n.iwb-editor-fx-range::-moz-range-track { height: 4px; border-radius: 2px; background: #313244; }\n.iwb-editor-fx-range::-moz-range-thumb {\n width: 12px; height: 12px; border-radius: 50%; background: #e8a735; border: 1px solid #1e1e2c;\n}\n.iwb-editor-fx-range:disabled { cursor: default; }\n.iwb-editor-fx-range:disabled::-webkit-slider-thumb { background: #585b70; }\n.iwb-editor-fx-range:disabled::-moz-range-thumb { background: #585b70; }\n.iwb-editor-fx-range:focus-visible { outline: 2px solid #89b4fa; outline-offset: 2px; }\n\n/* ================================================================\n v1.15:图片调节面板\n 11 项挤在 240px 侧栏里,必须单行紧凑:名称 46 / 滑杆 flex / 数值 36。\n 调过的项把名称染成橙色 —— 一屏 11 项,不标出来根本看不出哪几项被动过。\n ================================================================ */\n.iwb-editor-adj {\n display: flex; flex-direction: column; gap: 7px;\n padding: 9px 10px 8px; border-radius: 10px;\n background: #1e1e2c; border: 1px solid #2f2f42;\n}\n.iwb-editor-adj-head {\n display: flex; align-items: center; gap: 6px;\n}\n.iwb-editor-adj-title {\n font-size: 11.5px; font-weight: 600; color: #cdd6f4; flex: 0 0 auto;\n}\n.iwb-editor-adj-target {\n font-size: 10px; color: #7f87a3; flex: 1 1 auto;\n overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n}\n.iwb-editor-adj-reset {\n flex: 0 0 auto; padding: 2px 7px; border-radius: 5px;\n background: #26263a; border: 1px solid #3a3a52; color: #b9c0d8;\n font: 500 10px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;\n cursor: pointer; transition: background 0.12s ease, color 0.12s ease;\n}\n.iwb-editor-adj-reset:hover:not(:disabled) { background: #33334c; color: #f3dcb0; border-color: #e8a735; }\n.iwb-editor-adj-reset:disabled { opacity: 0.4; cursor: default; }\n.iwb-editor-adj.is-dirty .iwb-editor-adj-title { color: #e8a735; }\n.iwb-editor-adj-list { display: flex; flex-direction: column; gap: 1px; }\n.iwb-editor-adj-row {\n display: grid; grid-template-columns: 46px 1fr 36px;\n align-items: center; gap: 6px; padding: 1px 0;\n}\n.iwb-editor-adj-name {\n font-size: 10px; color: #b9c0d8; white-space: nowrap;\n cursor: pointer; user-select: none; overflow: hidden; text-overflow: ellipsis;\n}\n.iwb-editor-adj-row.is-set .iwb-editor-adj-name { color: #e8a735; }\n.iwb-editor-adj-range {\n -webkit-appearance: none; appearance: none;\n width: 100%; height: 14px; margin: 0; background: transparent; cursor: pointer;\n}\n.iwb-editor-adj-range::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: #313244; }\n.iwb-editor-adj-range::-webkit-slider-thumb {\n -webkit-appearance: none; appearance: none;\n width: 11px; height: 11px; margin-top: -3.5px; border-radius: 50%;\n background: #e8a735; border: 1px solid #1e1e2c;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);\n}\n.iwb-editor-adj-range::-moz-range-track { height: 4px; border-radius: 2px; background: #313244; }\n.iwb-editor-adj-range::-moz-range-thumb {\n width: 11px; height: 11px; border-radius: 50%; background: #e8a735; border: 1px solid #1e1e2c;\n}\n.iwb-editor-adj-range:focus-visible { outline: 2px solid #89b4fa; outline-offset: 2px; }\n.iwb-editor-adj-val {\n width: 36px; padding: 1px 2px; text-align: center;\n background: #26263a; border: 1px solid #3a3a52; border-radius: 4px;\n color: #cdd6f4; font: 500 10px/1.4 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;\n font-variant-numeric: tabular-nums;\n -moz-appearance: textfield;\n}\n.iwb-editor-adj-val::-webkit-outer-spin-button,\n.iwb-editor-adj-val::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }\n.iwb-editor-adj-val:focus { outline: none; border-color: #89b4fa; }\n.iwb-editor-adj-row.is-set .iwb-editor-adj-val { color: #f3dcb0; border-color: #4a4433; }\n.iwb-editor-adj-tip {\n margin: 0; font-size: 9.5px; line-height: 1.4; color: #6c7390;\n}\n\n/* ================================================================\n v1.6:图层面板多选(⌘/Ctrl 点击)+ 合并按钮\n 多选用青色侧条与单选(橙色 #e8a735)区分:一个图层可以「被选中但不在合并集合里」,\n 两套状态不能长得一样。\n ================================================================ */\n.iwb-layer-item.multi {\n background: rgba(137, 180, 250, 0.14);\n box-shadow: inset 2px 0 0 #89b4fa;\n}\n.iwb-layer-item.multi.active {\n background: rgba(137, 180, 250, 0.2);\n box-shadow: inset 2px 0 0 #89b4fa, inset 0 0 0 1px rgba(137, 180, 250, 0.45);\n}\n.iwb-editor-layer-add-group { flex: 0 0 auto; flex-wrap: nowrap; }\n.iwb-editor-layer-add-btn[data-action="mergeLayers"]:hover,\n.iwb-editor-layer-add-btn[data-action="mergeVisible"]:hover {\n background: #45475a;\n border-color: #89b4fa;\n color: #cdd6f4;\n}\n\n/* ================================================================\n v1.9:文字样式控件 / 圆角 / 最近使用颜色 / 复制按钮\n ================================================================ */\n\n/* 选项栏里的原生颜色框(描边色 / 底色):压成和数字框同高的小方块 */\n.iwb-opt-color {\n width: 22px;\n height: 20px;\n padding: 0;\n flex: 0 0 auto;\n border: 1px solid #45475a;\n border-radius: 4px;\n background: transparent;\n cursor: pointer;\n}\n.iwb-opt-color::-webkit-color-swatch-wrapper { padding: 2px; }\n.iwb-opt-color::-webkit-color-swatch { border: 0; border-radius: 3px; }\n/* 底色是半透明的:色块按真实不透明度显示(--sw-a),看起来和画布上的效果一致,\n 不再是一块实心纯黑让人以为「又多了一个字体颜色」 */\n.iwb-opt-color { opacity: var(--sw-a, 1); }\n/* 该颜色当前没生效(描边宽度 0 / 底色未开 / 图形是描边模式):\n 不再显示那块颜色本身,而是显示为一块灰色斜纹 —— 语义是「这里还没有颜色」。\n 只做半透明灰化的话,纯黑/深色照样是一块黑方块,用户仍会以为「设了个黑色没生效」。 */\n.iwb-opt-color.is-off {\n opacity: 1;\n border-style: dashed;\n border-color: #4b4f66;\n background: repeating-linear-gradient(45deg, #353849 0 3px, #262939 3px 6px);\n}\n.iwb-opt-color.is-off::-webkit-color-swatch { opacity: 0; }\n/* 选项栏里色块旁边的分组标签,和「描边 / 底色」这类双字按钮区分开 */\n.iwb-opt-swatch-label { color: #7f849c; font-size: 11px; flex: 0 0 auto; }\n\n/* 「最近使用」:与常用色同一套 8 列 20px 网格(v1.19 起最多 16 个 = 铺满两排),\n 空的时候整块隐藏(不占位)。 */\n.iwb-editor-color-pop .iwb-editor-recent-colors {\n display: grid;\n grid-template-columns: repeat(8, 20px);\n grid-auto-rows: 20px;\n gap: 5px;\n flex: 0 0 auto;\n align-content: center;\n}\n.iwb-editor-recent-colors[hidden] { display: none; }\n.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch {\n width: 20px;\n height: 20px;\n padding: 0;\n border: 0;\n border-radius: 50%;\n cursor: pointer;\n}\n.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch:hover { transform: scale(1.12); }\n\n/* 复制到剪贴板:与「导出」同尺寸但用低饱和色,避免两个绿色按钮抢眼 */\n.iwb-editor-btn-copy { background: #313244 !important; color: #cdd6f4 !important; }\n.iwb-editor-btn-copy:hover { background: #3b3d52 !important; }\n\n/* 选项栏按钮里是中文双字标签(常规/特粗/底色),不给 nowrap 会被挤成竖排 */\n.iwb-editor-optionbar-body .iwb-opt-btn { white-space: nowrap; }\n\n/* ================================================================\n v1.16:右栏常驻调色面板 + 可拖宽度 + 整体字号提升一档\n 需求(用户 2026-11-09):① 面板文字偏小 ② 右栏要能拖宽\n ③ 把调色面板(含常用色)搬进右栏 ④ 顶部切换当前元素可调的颜色项\n ================================================================ */\n\n/* ---- 1) 右栏宽度手柄:贴在侧栏左边缘(侧栏在画布右侧) ----\n 必须放在 left:0 而不是负值:侧栏本身 overflow-x:hidden,探出去的部分会被裁掉。 */\n.iwb-editor-side-resizer {\n position: absolute; left: 0; top: 0; bottom: 0; width: 9px;\n z-index: 46; cursor: col-resize; touch-action: none;\n}\n/* 平时完全隐形,悬停/拖动时才亮一条橙线:\n 常驻一条竖线会和「画布/面板」的分隔线打架,看起来像两条边界。 */\n.iwb-editor-side-resizer::after {\n content: \'\'; position: absolute; left: 3px; top: 0; bottom: 0; width: 2px;\n border-radius: 1px; background: transparent; transition: background 0.12s ease;\n}\n.iwb-editor-side-resizer:hover::after,\n.iwb-editor-side-resizer.is-dragging::after { background: #e8a735; }\n\n/* ---- 2) 右栏调色面板:已删(v1.19,用户 2026-11-10) ----\n 颜色只剩工具栏弹层一处。弹层钉住后本来就常开,右栏那份只是重复占位。\n 原来这里的 .iwb-editor-colors / .iwb-editor-colors-head / 以及一批\n `.iwb-editor-colors .iwb-color-pop-*` 覆盖规则(弹层横排、右栏竖排)全部移除 ——\n 少一层「同一份 DOM 两套布局」的分支,改色板不会再出现「改了一处另一处没跟上」。 */\n\n\n/* ---- 3) 字号 +1 档 ----\n 旧值大量是 10–11.5px(按 1440 宽屏定的),在 2K/4K 与系统缩放 125% 下发虚。\n 集中用 #iwb-editor-overlay 前缀覆盖而不是逐条改原规则:字号以后只在这块调。\n 宿主画布外的节点浮条(.iwb-node-floatbar 等)不在遮罩内,不受影响。 */\n#iwb-editor-overlay { font-size: 13px; }\n#iwb-editor-overlay .iwb-editor-title em.iwb-editor-doc-size { font-size: 12px; }\n#iwb-editor-overlay .iwb-editor-header > .iwb-editor-session .iwb-editor-btn,\n#iwb-editor-overlay .iwb-editor-header .iwb-editor-export-actions .iwb-editor-btn { font-size: 12.5px; }\n#iwb-editor-overlay .iwb-editor-export-settings-btn { font-size: 12.5px; }\n#iwb-editor-overlay .iwb-editor-export-row > span,\n#iwb-editor-overlay .iwb-editor-export-note,\n#iwb-editor-overlay .iwb-editor-more-menu kbd { font-size: 12px; }\n\n/* 选项栏 */\n#iwb-editor-overlay .iwb-editor-optionbar { font-size: 13px; }\n#iwb-editor-overlay .iwb-opt-label,\n#iwb-editor-overlay .iwb-opt-current,\n#iwb-editor-overlay .iwb-opt-btn,\n#iwb-editor-overlay .iwb-opt-num,\n#iwb-editor-overlay .iwb-opt-select { font-size: 13px; }\n#iwb-editor-overlay .iwb-opt-num { width: 50px; }\n#iwb-editor-overlay .iwb-opt-hint,\n#iwb-editor-overlay .iwb-editor-optionbar-tip,\n#iwb-editor-overlay .iwb-opt-unit,\n#iwb-editor-overlay .iwb-opt-swatch-label { font-size: 12px; }\n\n/* 状态栏 */\n#iwb-editor-overlay .iwb-editor-statusbar { font-size: 12px; height: 28px; min-height: 28px; }\n\n/* 图层面板 */\n#iwb-editor-overlay .iwb-layer-name { font-size: 13px; }\n#iwb-editor-overlay .iwb-layer-name-input { font-size: 13px; }\n#iwb-editor-overlay .iwb-layer-paint { font-size: 12px; }\n#iwb-editor-overlay .iwb-layer-op,\n#iwb-editor-overlay .iwb-layer-op-val { font-size: 11.5px; }\n#iwb-editor-overlay .iwb-layer-op-val { width: 36px; }\n\n/* 右栏:图片调节 */\n#iwb-editor-overlay .iwb-editor-adj-title { font-size: 13px; }\n#iwb-editor-overlay .iwb-editor-adj-target { font-size: 11.5px; }\n#iwb-editor-overlay .iwb-editor-adj-reset { font: 500 12px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif; padding: 3px 8px; }\n#iwb-editor-overlay .iwb-editor-adj-row { grid-template-columns: 50px 1fr 40px; }\n#iwb-editor-overlay .iwb-editor-adj-name { font-size: 12.5px; }\n#iwb-editor-overlay .iwb-editor-adj-val { width: 40px; font: 500 12px/1.4 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif; }\n#iwb-editor-overlay .iwb-editor-adj-tip { font-size: 11.5px; }\n\n/* 右栏:快速效果 */\n#iwb-editor-overlay .iwb-editor-fx-title { font-size: 13px; }\n#iwb-editor-overlay .iwb-editor-fx-target { font-size: 11.5px; max-width: 150px; }\n#iwb-editor-overlay .iwb-editor-fx-btn { font: 500 12px/1 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif; padding: 8px 2px 7px; }\n#iwb-editor-overlay .iwb-editor-fx-tip { font-size: 11.5px; }\n#iwb-editor-overlay .iwb-editor-fx-adj-name,\n#iwb-editor-overlay .iwb-editor-fx-adj-val { font-size: 12px; }\n\n/* 右栏:缩放 */\n#iwb-editor-overlay .iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-val,\n#iwb-editor-overlay .iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-fit { font-size: 12px; }\n\n/* 调色面板本体(v1.20:去色已下移到色块网格,这里只剩 tab 需要放大字号;\n 去色是 20px 格子,高度必须跟色块一致,别被这条统一字号的规则顶成 26px) */\n#iwb-editor-overlay .iwb-color-pop-tab { font-size: 12.5px; height: 26px; }\n#iwb-editor-overlay .iwb-color-pop-none { width: 20px; height: 20px; }\n#iwb-editor-overlay .iwb-editor-color-pop .iwb-editor-color-hex-input { font-size: 13px; }\n'; + + // image-annotate/plugin/glue.js + function createGlue(ctx, css) { + let styleInjected = false; + function ensureStyle() { + if (styleInjected) return; + styleInjected = true; + try { + const style = document.createElement("style"); + style.id = "iwb-annotate-style"; + style.textContent = css; + (document.head || document.documentElement).appendChild(style); + } catch (error) { + styleInjected = false; + ctx.log("inject-style-failed", error && error.message); + } + } + function blobToDataUrl(blob) { + return new Promise(function(resolve, reject) { + const reader = new FileReader(); + reader.onload = function() { + resolve(String(reader.result || "")); + }; + reader.onerror = function() { + reject(reader.error || new Error("读取导出图片失败")); + }; + reader.readAsDataURL(blob); + }); + } + function imageToDataUrl(out) { + if (typeof out === "string") return Promise.resolve(out); + if (out && typeof out.arrayBuffer === "function") return blobToDataUrl(out); + return Promise.reject(new Error("导出结果不是可用的图片数据")); + } + function baseName(node) { + return String(node && node.name || "image").replace(/\.[^.]+$/, "") || "image"; + } + function openEditor(node) { + const id = node && node.id; + if (!id) return Promise.reject(new Error("请先选中一个带图的节点")); + const editor = typeof window !== "undefined" ? window.__iwbEditor : null; + if (!editor || typeof editor.open !== "function") { + return Promise.reject(new Error("标注编辑器未加载")); + } + return Promise.resolve(ctx.canvas.getNodeImage(id)).then(function(image) { + if (!image || !image.dataUrl) { + throw new Error(image && image.url ? "该节点是远程图片,暂不支持标注(请先转存为本地位图)" : "该节点没有可编辑的图片"); + } + ensureStyle(); + return new Promise(function(resolve, reject) { + let settled = false; + let handedOff = false; + const settle = function(fn) { + if (!settled) { + settled = true; + fn(); + } + }; + Promise.resolve(editor.open({ + imageBase64: image.dataUrl, + imageName: baseName(node) + ".png", + settings: ctx.settings, + // 记住输出预设 / 侧栏开合(宿主提供的命名空间 KV) + onError: function(message) { + settle(function() { + reject(new Error(String(message || "编辑失败"))); + }); + }, + onClose: function() { + if (handedOff) return; + settle(function() { + resolve("cancel"); + }); + }, + onResult: function(out, mode) { + handedOff = true; + imageToDataUrl(out).then(function(dataUrl) { + const replaced = mode === "replace"; + const ok = replaced ? ctx.canvas.setNodeImage(id, dataUrl) : Boolean(ctx.canvas.createImageNode({ dataUrl, name: baseName(node) + "_edit.png" })); + if (!ok) throw new Error(replaced ? "写回原节点失败" : "新建节点失败"); + settle(function() { + resolve(mode); + }); + }).catch(function(error) { + settle(function() { + reject(error); + }); + }); + } + })).catch(function(error) { + settle(function() { + reject(error); + }); + }); + }); + }); + } + function appliesTo(node) { + if (!node) return false; + return node.type === "ref"; + } + ctx.nodeActions.register({ + id: "annotate-node", + title: "标注 / 修图", + icon: "pencil-ruler", + appliesTo, + run: function(node) { + return openEditor(node); + } + }); + ctx.commands.register({ + id: "annotate-selected", + title: "标注 / 修图:选中节点", + icon: "pencil-ruler", + run: function() { + const selected = ctx.canvas.getSelectedNode(); + if (!selected) return Promise.reject(new Error("请先选中一个带图的节点")); + return openEditor(selected); + } + }); + return { + dispose: function() { + } + }; + } + + // image-annotate/plugin/entry.js + (typeof window !== "undefined" ? window : globalThis).__IWB_ANNOTATE_FACTORY__ = function(ctx) { + return createGlue(ctx, editor_default); + }; +})(); +// 手写注册尾部(build-plugin.mjs 原样追加到产物末尾,不 overlapped with esbuild 的打印器)。 +// 时序:bundle 先执行(挂好 __IWB_ANNOTATE_FACTORY__),再注册;factory 由宿主在「启用插件」时才调用。 +;(function (global) { + 'use strict' + if (!global.IWBPluginHost) return + global.IWBPluginHost.register(__IWB_ANNOTATE_MANIFEST__, function (ctx) { + return global.__IWB_ANNOTATE_FACTORY__(ctx) + }) +})(typeof window !== 'undefined' ? window : globalThis) + diff --git a/plugins/runtime/plugin-image-vectorize.03b5fc850c34.js b/plugins/runtime/plugin-image-vectorize.03b5fc850c34.js new file mode 100644 index 0000000..99e4045 --- /dev/null +++ b/plugins/runtime/plugin-image-vectorize.03b5fc850c34.js @@ -0,0 +1,3786 @@ +// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号, +// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。 +// +// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id, +// 排在 bundle 之前才能保证取到的是下面这份 manifest。 +// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。 +// +// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。 +var __IWB_VECTORIZE_MANIFEST__ = { + id: 'image-vectorize', + name: '位图转矢量', + version: '0.4.2', + apiVersion: 1, + capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'], + settings: { + preset: { type: 'string', default: 'text' }, + mode: { type: 'string', default: 'gray' }, + levels: { type: 'number', default: 3 }, + threshold: { type: 'number', default: -1 }, + turdSize: { type: 'number', default: 3 }, + alphaMax: { type: 'number', default: 1 }, + optTolerance: { type: 'number', default: 0.05 }, + invert: { type: 'boolean', default: false }, + color: { type: 'string', default: '#1a1a1a' }, + bg: { type: 'string', default: '#ffffff' }, + bgExport: { type: 'boolean', default: false }, + outScale: { type: 'number', default: 2 }, + advOpen: { type: 'boolean', default: true }, + splitIslands: { type: 'boolean', default: true } + }, +} + +"use strict"; +(() => { + var __create = Object.create; + var __defProp = Object.defineProperty; + var __getOwnPropDesc = Object.getOwnPropertyDescriptor; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __getProtoOf = Object.getPrototypeOf; + var __hasOwnProp = Object.prototype.hasOwnProperty; + var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] + }) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); + }); + var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; + }; + var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; + }; + var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod + )); + + // image-vectorize/plugin/vendor/potrace/types/Point.js + var require_Point = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Point.js"(exports, module) { + "use strict"; + function Point(x, y) { + this.x = x || 0; + this.y = y || 0; + } + Point.prototype = { + copy: function() { + return new Point(this.x, this.y); + } + }; + module.exports = Point; + } + }); + + // image-vectorize/plugin/vendor/potrace/utils.js + var require_utils = __commonJS({ + "image-vectorize/plugin/vendor/potrace/utils.js"(exports, module) { + "use strict"; + var Point = require_Point(); + var attrRegexps = {}; + function getAttrRegexp(attrName) { + if (attrRegexps[attrName]) { + return attrRegexps[attrName]; + } + attrRegexps[attrName] = new RegExp(" " + attrName + '="((?:\\\\(?=")"|[^"])+)"', "i"); + return attrRegexps[attrName]; + } + function setHtmlAttribute(html, attrName, value) { + var attr = " " + attrName + '="' + value + '"'; + if (html.indexOf(" " + attrName + '="') === -1) { + html = html.replace(/<[a-z]+/i, function(beginning) { + return beginning + attr; + }); + } else { + html = html.replace(getAttrRegexp(attrName), attr); + } + return html; + } + function fixed(number) { + return number.toFixed(3).replace(".000", ""); + } + function mod(a, n) { + return a >= n ? a % n : a >= 0 ? a : n - 1 - (-1 - a) % n; + } + function xprod(p1, p2) { + return p1.x * p2.y - p1.y * p2.x; + } + function cyclic(a, b, c) { + if (a <= c) { + return a <= b && b < c; + } else { + return a <= b || b < c; + } + } + function sign(i) { + return i > 0 ? 1 : i < 0 ? -1 : 0; + } + function quadform(Q, w) { + var v = new Array(3), i, j, sum; + v[0] = w.x; + v[1] = w.y; + v[2] = 1; + sum = 0; + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + sum += v[i] * Q.at(i, j) * v[j]; + } + } + return sum; + } + function interval(lambda, a, b) { + var res = new Point(); + res.x = a.x + lambda * (b.x - a.x); + res.y = a.y + lambda * (b.y - a.y); + return res; + } + function dorth_infty(p0, p2) { + var r = new Point(); + r.y = sign(p2.x - p0.x); + r.x = -sign(p2.y - p0.y); + return r; + } + function ddenom(p0, p2) { + var r = dorth_infty(p0, p2); + return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y); + } + function dpara(p0, p1, p2) { + var x1, y1, x2, y2; + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p2.x - p0.x; + y2 = p2.y - p0.y; + return x1 * y2 - x2 * y1; + } + function cprod(p0, p1, p2, p3) { + var x1, y1, x2, y2; + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p3.x - p2.x; + y2 = p3.y - p2.y; + return x1 * y2 - x2 * y1; + } + function iprod(p0, p1, p2) { + var x1, y1, x2, y2; + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p2.x - p0.x; + y2 = p2.y - p0.y; + return x1 * x2 + y1 * y2; + } + function iprod1(p0, p1, p2, p3) { + var x1, y1, x2, y2; + x1 = p1.x - p0.x; + y1 = p1.y - p0.y; + x2 = p3.x - p2.x; + y2 = p3.y - p2.y; + return x1 * x2 + y1 * y2; + } + function ddist(p, q) { + return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y)); + } + module.exports = { + luminance: function(r, g, b) { + return Math.round(0.2126 * r + 0.7153 * g + 0.0721 * b); + }, + between: function(val, min, max) { + return val >= min && val <= max; + }, + clamp: function(val, min, max) { + return Math.min(max, Math.max(min, val)); + }, + isNumber: function(val) { + return typeof val === "number"; + }, + setHtmlAttr: setHtmlAttribute, + /** + * Generates path instructions for given curve + * + * @param {Curve} curve + * @param {Number} [scale] + * @returns {string} + */ + renderCurve: function(curve, scale) { + scale = scale || { x: 1, y: 1 }; + var startingPoint = curve.c[(curve.n - 1) * 3 + 2]; + var path = [ + "M " + fixed(startingPoint.x * scale.x) + " " + fixed(startingPoint.y * scale.y) + ]; + curve.tag.forEach(function(tag, i) { + var i3 = i * 3; + var p0 = curve.c[i3]; + var p1 = curve.c[i3 + 1]; + var p2 = curve.c[i3 + 2]; + if (tag === "CURVE") { + path.push( + "C " + fixed(p0.x * scale.x) + " " + fixed(p0.y * scale.y) + ", " + fixed(p1.x * scale.x) + " " + fixed(p1.y * scale.y) + ", " + fixed(p2.x * scale.x) + " " + fixed(p2.y * scale.y) + ); + } else if (tag === "CORNER") { + path.push( + "L " + fixed(p1.x * scale.x) + " " + fixed(p1.y * scale.y) + " " + fixed(p2.x * scale.x) + " " + fixed(p2.y * scale.y) + ); + } + }); + return path.join(" "); + }, + bezier: function bezier(t, p0, p1, p2, p3) { + var s = 1 - t, res = new Point(); + res.x = s * s * s * p0.x + 3 * (s * s * t) * p1.x + 3 * (t * t * s) * p2.x + t * t * t * p3.x; + res.y = s * s * s * p0.y + 3 * (s * s * t) * p1.y + 3 * (t * t * s) * p2.y + t * t * t * p3.y; + return res; + }, + tangent: function tangent(p0, p1, p2, p3, q0, q1) { + var A, B, C, a, b, c, d, s, r1, r2; + A = cprod(p0, p1, q0, q1); + B = cprod(p1, p2, q0, q1); + C = cprod(p2, p3, q0, q1); + a = A - 2 * B + C; + b = -2 * A + 2 * B; + c = A; + d = b * b - 4 * a * c; + if (a === 0 || d < 0) { + return -1; + } + s = Math.sqrt(d); + r1 = (-b + s) / (2 * a); + r2 = (-b - s) / (2 * a); + if (r1 >= 0 && r1 <= 1) { + return r1; + } else if (r2 >= 0 && r2 <= 1) { + return r2; + } else { + return -1; + } + }, + mod, + xprod, + cyclic, + sign, + quadform, + interval, + dorth_infty, + ddenom, + dpara, + cprod, + iprod, + iprod1, + ddist + }; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Histogram.js + var require_Histogram = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Histogram.js"(exports, module) { + "use strict"; + var utils = require_utils(); + var Jimp = null; + try { + Jimp = __require("jimp"); + } catch (e) { + } + var Bitmap = require_Bitmap(); + var COLOR_DEPTH = 256; + var COLOR_RANGE_END = COLOR_DEPTH - 1; + function index(x, y) { + return COLOR_DEPTH * x + y; + } + function normalizeMinMax(levelMin, levelMax) { + levelMin = typeof levelMin === "number" ? utils.clamp(Math.round(levelMin), 0, COLOR_RANGE_END) : 0; + levelMax = typeof levelMax === "number" ? utils.clamp(Math.round(levelMax), 0, COLOR_RANGE_END) : COLOR_RANGE_END; + if (levelMin > levelMax) { + throw new Error('Invalid range "' + levelMin + "..." + levelMax + '"'); + } + return [levelMin, levelMax]; + } + function Histogram(imageSource, mode) { + this.data = null; + this.pixels = 0; + this._sortedIndexes = null; + this._cachedStats = {}; + this._lookupTableH = null; + if (typeof imageSource === "number") { + this._createArray(imageSource); + } else if (imageSource instanceof Bitmap) { + this._collectValuesBitmap(imageSource); + } else if (Jimp && imageSource instanceof Jimp) { + this._collectValuesJimp(imageSource, mode); + } else { + throw new Error("Unsupported image source"); + } + } + Histogram.MODE_LUMINANCE = "luminance"; + Histogram.MODE_R = "r"; + Histogram.MODE_G = "g"; + Histogram.MODE_B = "b"; + Histogram.prototype = { + /** + * Initializes data array for an image of given pixel size + * @param imageSize + * @returns {Uint8Array|Uint16Array|Uint32Array} + * @private + */ + _createArray: function(imageSize) { + var ArrayType = imageSize <= Math.pow(2, 8) ? Uint8Array : imageSize <= Math.pow(2, 16) ? Uint16Array : Uint32Array; + this.pixels = imageSize; + return this.data = new ArrayType(COLOR_DEPTH); + }, + /** + * Aggregates color data from {@link Jimp} instance + * @param {Jimp} source + * @param mode + * @private + */ + _collectValuesJimp: function(source, mode) { + var pixelData = source.bitmap.data; + var data = this._createArray(source.bitmap.width * source.bitmap.height); + source.scan(0, 0, source.bitmap.width, source.bitmap.height, function(x, y, idx) { + var val = mode === Histogram.MODE_R ? pixelData[idx] : mode === Histogram.MODE_G ? pixelData[idx + 1] : mode === Histogram.MODE_B ? pixelData[idx + 2] : utils.luminance(pixelData[idx], pixelData[idx + 1], pixelData[idx + 2]); + data[val]++; + }); + }, + /** + * Aggregates color data from {@link Bitmap} instance + * @param {Bitmap} source + * @private + */ + _collectValuesBitmap: function(source) { + var data = this._createArray(source.size); + var len = source.data.length; + var color; + for (var i = 0; i < len; i++) { + color = source.data[i]; + data[color]++; + } + }, + /** + * Returns array of color indexes in ascending order + * @param refresh + * @returns {*} + * @private + */ + _getSortedIndexes: function(refresh) { + if (!refresh && this._sortedIndexes) { + return this._sortedIndexes; + } + var data = this.data; + var indexes = new Array(COLOR_DEPTH); + var i = 0; + for (i; i < COLOR_DEPTH; i++) { + indexes[i] = i; + } + indexes.sort(function(a, b) { + return data[a] > data[b] ? 1 : data[a] < data[b] ? -1 : 0; + }); + this._sortedIndexes = indexes; + return indexes; + }, + /** + * Builds lookup table H from lookup tables P and S. + * see {@link http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf|this paper} for more details + * + * @returns {Float64Array} + * @private + */ + _thresholdingBuildLookupTable: function() { + var P = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); + var S = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); + var H = new Float64Array(COLOR_DEPTH * COLOR_DEPTH); + var pixelsTotal = this.pixels; + var i, j, idx, tmp; + for (i = 1; i < COLOR_DEPTH; ++i) { + idx = index(i, i); + tmp = this.data[i] / pixelsTotal; + P[idx] = tmp; + S[idx] = i * tmp; + } + for (i = 1; i < COLOR_DEPTH - 1; ++i) { + tmp = this.data[i + 1] / pixelsTotal; + idx = index(1, i); + P[idx + 1] = P[idx] + tmp; + S[idx + 1] = S[idx] + (i + 1) * tmp; + } + for (i = 2; i < COLOR_DEPTH; i++) { + for (j = i + 1; j < COLOR_DEPTH; j++) { + P[index(i, j)] = P[index(1, j)] - P[index(1, i - 1)]; + S[index(i, j)] = S[index(1, j)] - S[index(1, i - 1)]; + } + } + for (i = 1; i < COLOR_DEPTH; ++i) { + for (j = i + 1; j < COLOR_DEPTH; j++) { + idx = index(i, j); + H[idx] = P[idx] !== 0 ? S[idx] * S[idx] / P[idx] : 0; + } + } + return this._lookupTableH = H; + }, + /** + * Implements Algorithm For Multilevel Thresholding + * Receives desired number of color stops, returns array of said size. Could be limited to a range levelMin..levelMax + * + * Regardless of levelMin and levelMax values it still relies on between class variances for the entire histogram + * + * @param amount - how many thresholds should be calculated + * @param [levelMin=0] - histogram segment start + * @param [levelMax=255] - histogram segment end + * @returns {number[]} + */ + multilevelThresholding: function(amount, levelMin, levelMax) { + levelMin = normalizeMinMax(levelMin, levelMax); + levelMax = levelMin[1]; + levelMin = levelMin[0]; + amount = Math.min(levelMax - levelMin - 2, ~~amount); + if (amount < 1) { + return []; + } + if (!this._lookupTableH) { + this._thresholdingBuildLookupTable(); + } + var H = this._lookupTableH; + var colorStops = null; + var maxSig = 0; + if (amount > 4) { + console.log("[Warning]: Threshold computation for more than 5 levels may take a long time"); + } + function iterateRecursive(startingPoint, prevVariance, indexes, previousDepth) { + startingPoint = (startingPoint || 0) + 1; + prevVariance = prevVariance || 0; + indexes = indexes || new Array(amount); + previousDepth = previousDepth || 0; + var depth = previousDepth + 1; + var variance; + for (var i = startingPoint; i < levelMax - amount + previousDepth; i++) { + variance = prevVariance + H[index(startingPoint, i)]; + indexes[depth - 1] = i; + if (depth + 1 < amount + 1) { + iterateRecursive(i, variance, indexes, depth); + } else { + variance += H[index(i + 1, levelMax)]; + if (maxSig < variance) { + maxSig = variance; + colorStops = indexes.slice(); + } + } + } + } + iterateRecursive(levelMin || 0); + return colorStops ? colorStops : []; + }, + /** + * Automatically finds threshold value using Algorithm For Multilevel Thresholding + * + * @param {number} [levelMin] + * @param {number} [levelMax] + * @returns {null|number} + */ + autoThreshold: function(levelMin, levelMax) { + var value = this.multilevelThresholding(1, levelMin, levelMax); + return value.length ? value[0] : null; + }, + /** + * Returns dominant color in given range. Returns -1 if not a single color from the range present on the image + * + * @param [levelMin=0] + * @param [levelMax=255] + * @param [tolerance=1] + * @returns {number} + */ + getDominantColor: function(levelMin, levelMax, tolerance) { + levelMin = normalizeMinMax(levelMin, levelMax); + levelMax = levelMin[1]; + levelMin = levelMin[0]; + tolerance = tolerance || 1; + var colors = this.data, dominantIndex = -1, dominantValue = -1, i, j, tmp; + if (levelMin === levelMax) { + return colors[levelMin] ? levelMin : -1; + } + for (i = levelMin; i <= levelMax; i++) { + tmp = 0; + for (j = ~~(tolerance / -2); j < tolerance; j++) { + tmp += utils.between(i + j, 0, COLOR_RANGE_END) ? colors[i + j] : 0; + } + var summIsBigger = tmp > dominantValue; + var summEqualButMainColorIsBigger = dominantValue === tmp && (dominantIndex < 0 || colors[i] > colors[dominantIndex]); + if (summIsBigger || summEqualButMainColorIsBigger) { + dominantIndex = i; + dominantValue = tmp; + } + } + return dominantValue <= 0 ? -1 : dominantIndex; + }, + /** + * Returns stats for histogram or its segment. + * + * Returned object contains median, mean and standard deviation for pixel values; + * peak, mean and median number of pixels per level and few other values + * + * If no pixels colors from specified range present on the image - most values will be NaN + * + * @param {Number} [levelMin=0] - histogram segment start + * @param {Number} [levelMax=255] - histogram segment end + * @param {Boolean} [refresh=false] - if cached result can be returned + * @returns {{levels: {mean: (number|*), median: *, stdDev: number, unique: number}, pixelsPerLevel: {mean: (number|*), median: (number|*), peak: number}, pixels: number}} + */ + getStats: function(levelMin, levelMax, refresh) { + levelMin = normalizeMinMax(levelMin, levelMax); + levelMax = levelMin[1]; + levelMin = levelMin[0]; + if (!refresh && this._cachedStats[levelMin + "-" + levelMax]) { + return this._cachedStats[levelMin + "-" + levelMax]; + } + var data = this.data; + var sortedIndexes = this._getSortedIndexes(); + var pixelsTotal = 0; + var medianValue = null; + var meanValue; + var medianPixelIndex; + var pixelsPerLevelMean; + var pixelsPerLevelMedian; + var tmpSumOfDeviations = 0; + var tmpPixelsIterated = 0; + var allPixelValuesCombined = 0; + var i, tmpPixels, tmpPixelValue; + var uniqueValues = 0; + var mostPixelsPerLevel = 0; + for (i = levelMin; i <= levelMax; i++) { + pixelsTotal += data[i]; + allPixelValuesCombined += data[i] * i; + uniqueValues += data[i] === 0 ? 0 : 1; + if (mostPixelsPerLevel < data[i]) { + mostPixelsPerLevel = data[i]; + } + } + meanValue = allPixelValuesCombined / pixelsTotal; + pixelsPerLevelMean = pixelsTotal / (levelMax - levelMin); + pixelsPerLevelMedian = pixelsTotal / uniqueValues; + medianPixelIndex = Math.floor(pixelsTotal / 2); + for (i = 0; i < COLOR_DEPTH; i++) { + tmpPixelValue = sortedIndexes[i]; + tmpPixels = data[tmpPixelValue]; + if (tmpPixelValue < levelMin || tmpPixelValue > levelMax) { + continue; + } + tmpPixelsIterated += tmpPixels; + tmpSumOfDeviations += Math.pow(tmpPixelValue - meanValue, 2) * tmpPixels; + if (medianValue === null && tmpPixelsIterated >= medianPixelIndex) { + medianValue = tmpPixelValue; + } + } + return this._cachedStats[levelMin + "-" + levelMax] = { + // various pixel counts for levels (0..255) + levels: { + mean: meanValue, + median: medianValue, + stdDev: Math.sqrt(tmpSumOfDeviations / pixelsTotal), + unique: uniqueValues + }, + // what's visually represented as bars + pixelsPerLevel: { + mean: pixelsPerLevelMean, + median: pixelsPerLevelMedian, + peak: mostPixelsPerLevel + }, + pixels: pixelsTotal + }; + } + }; + module.exports = Histogram; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Bitmap.js + var require_Bitmap = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Bitmap.js"(exports, module) { + "use strict"; + var Point = require_Point(); + var utils = require_utils(); + var Histogram; + function Bitmap(w, h) { + this._histogram = null; + this.width = w; + this.height = h; + this.size = w * h; + this.arrayBuffer = new ArrayBuffer(this.size); + this.data = new Uint8Array(this.arrayBuffer); + } + module.exports = Bitmap; + Histogram = require_Histogram(); + Bitmap.prototype = { + /** + * Returns pixel value + * + * @param {Number|Point} x - index, point or x + * @param {Number} [y] + */ + getValueAt: function(x, y) { + var index = typeof x === "number" && typeof y !== "number" ? x : this.pointToIndex(x, y); + return this.data[index]; + }, + /** + * Converts {@link Point} to index value + * + * @param {Number} index + * @returns {Point} + */ + indexToPoint: function(index) { + var point = new Point(); + if (utils.between(index, 0, this.size)) { + point.y = Math.floor(index / this.width); + point.x = index - point.y * this.width; + } else { + point.x = -1; + point.y = -1; + } + return point; + }, + /** + * Calculates index for point or coordinate pair + * + * @param {Number|Point} pointOrX + * @param {Number} [y] + * @returns {Number} + */ + pointToIndex: function(pointOrX, y) { + var _x = pointOrX, _y = y; + if (pointOrX instanceof Point) { + _x = pointOrX.x; + _y = pointOrX.y; + } + if (!utils.between(_x, 0, this.width) || !utils.between(_y, 0, this.height)) { + return -1; + } + return this.width * _y + _x; + }, + /** + * Makes a copy of current bitmap + * + * @param {Function} [iterator] optional callback, used for processing pixel value. Accepted arguments: value, index + * @returns {Bitmap} + */ + copy: function(iterator) { + var bm = new Bitmap(this.width, this.height), iteratorPresent = typeof iterator === "function", i; + for (i = 0; i < this.size; i++) { + bm.data[i] = iteratorPresent ? iterator(this.data[i], i) : this.data[i]; + } + return bm; + }, + histogram: function() { + var Histogram2 = require_Histogram(); + if (this._histogram) { + return this._histogram; + } + this._histogram = new Histogram2(this); + return this._histogram; + } + }; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Curve.js + var require_Curve = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Curve.js"(exports, module) { + "use strict"; + function Curve(n) { + this.n = n; + this.tag = new Array(n); + this.c = new Array(n * 3); + this.alphaCurve = 0; + this.vertex = new Array(n); + this.alpha = new Array(n); + this.alpha0 = new Array(n); + this.beta = new Array(n); + } + module.exports = Curve; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Path.js + var require_Path = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Path.js"(exports, module) { + "use strict"; + function Path() { + this.area = 0; + this.len = 0; + this.curve = {}; + this.pt = []; + this.minX = 1e5; + this.minY = 1e5; + this.maxX = -1; + this.maxY = -1; + } + module.exports = Path; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Quad.js + var require_Quad = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Quad.js"(exports, module) { + "use strict"; + function Quad() { + this.data = [0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + Quad.prototype.at = function(x, y) { + return this.data[x * 3 + y]; + }; + module.exports = Quad; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Sum.js + var require_Sum = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Sum.js"(exports, module) { + "use strict"; + function Sum(x, y, xy, x2, y2) { + this.x = x; + this.y = y; + this.xy = xy; + this.x2 = x2; + this.y2 = y2; + } + module.exports = Sum; + } + }); + + // image-vectorize/plugin/vendor/potrace/types/Opti.js + var require_Opti = __commonJS({ + "image-vectorize/plugin/vendor/potrace/types/Opti.js"(exports, module) { + "use strict"; + var Point = require_Point(); + function Opti() { + this.pen = 0; + this.c = [new Point(), new Point()]; + this.t = 0; + this.s = 0; + this.alpha = 0; + } + module.exports = Opti; + } + }); + + // image-vectorize/plugin/vendor/potrace/Potrace.js + var require_Potrace = __commonJS({ + "image-vectorize/plugin/vendor/potrace/Potrace.js"(exports, module) { + "use strict"; + var Bitmap = require_Bitmap(); + var Curve = require_Curve(); + var Point = require_Point(); + var Path = require_Path(); + var Quad = require_Quad(); + var Sum = require_Sum(); + var Opti = require_Opti(); + var utils = require_utils(); + function Potrace2(options) { + this._luminanceData = null; + this._pathlist = []; + this._imageLoadingIdentifier = null; + this._imageLoaded = false; + this._processed = false; + this._params = { + turnPolicy: Potrace2.TURNPOLICY_MINORITY, + turdSize: 2, + alphaMax: 1, + optCurve: true, + optTolerance: 0.2, + threshold: Potrace2.THRESHOLD_AUTO, + blackOnWhite: true, + color: Potrace2.COLOR_AUTO, + background: Potrace2.COLOR_TRANSPARENT, + width: null, + height: null + }; + if (options) { + this.setParameters(options); + } + } + Potrace2.COLOR_AUTO = "auto"; + Potrace2.COLOR_TRANSPARENT = "transparent"; + Potrace2.THRESHOLD_AUTO = -1; + Potrace2.TURNPOLICY_BLACK = "black"; + Potrace2.TURNPOLICY_WHITE = "white"; + Potrace2.TURNPOLICY_LEFT = "left"; + Potrace2.TURNPOLICY_RIGHT = "right"; + Potrace2.TURNPOLICY_MINORITY = "minority"; + Potrace2.TURNPOLICY_MAJORITY = "majority"; + var SUPPORTED_TURNPOLICY_VALUES = [ + Potrace2.TURNPOLICY_BLACK, + Potrace2.TURNPOLICY_WHITE, + Potrace2.TURNPOLICY_LEFT, + Potrace2.TURNPOLICY_RIGHT, + Potrace2.TURNPOLICY_MINORITY, + Potrace2.TURNPOLICY_MAJORITY + ]; + Potrace2.prototype = { + /** + * Creating a new {@link Path} for every group of black pixels. + * @private + */ + _bmToPathlist: function() { + var self = this, threshold = this._params.threshold, blackOnWhite = this._params.blackOnWhite, blackMap, currentPoint = new Point(0, 0), path; + if (threshold === Potrace2.THRESHOLD_AUTO) { + threshold = this._luminanceData.histogram().autoThreshold() || 128; + } + blackMap = this._luminanceData.copy(function(lum) { + var pastTheThreshold = blackOnWhite ? lum > threshold : lum < threshold; + return pastTheThreshold ? 0 : 1; + }); + function findNext(point) { + var i = blackMap.pointToIndex(point); + while (i < blackMap.size && blackMap.data[i] !== 1) { + i++; + } + return i < blackMap.size && blackMap.indexToPoint(i); + } + function majority(x, y) { + var i, a, ct; + for (i = 2; i < 5; i++) { + ct = 0; + for (a = -i + 1; a <= i - 1; a++) { + ct += blackMap.getValueAt(x + a, y + i - 1) ? 1 : -1; + ct += blackMap.getValueAt(x + i - 1, y + a - 1) ? 1 : -1; + ct += blackMap.getValueAt(x + a - 1, y - i) ? 1 : -1; + ct += blackMap.getValueAt(x - i, y + a) ? 1 : -1; + } + if (ct > 0) { + return 1; + } else if (ct < 0) { + return 0; + } + } + return 0; + } + function findPath(point) { + var path2 = new Path(), x = point.x, y = point.y, dirx = 0, diry = 1, tmp; + path2.sign = blackMap.getValueAt(point.x, point.y) ? "+" : "-"; + while (1) { + path2.pt.push(new Point(x, y)); + if (x > path2.maxX) + path2.maxX = x; + if (x < path2.minX) + path2.minX = x; + if (y > path2.maxY) + path2.maxY = y; + if (y < path2.minY) + path2.minY = y; + path2.len++; + x += dirx; + y += diry; + path2.area -= x * diry; + if (x === point.x && y === point.y) + break; + var l = blackMap.getValueAt(x + (dirx + diry - 1) / 2, y + (diry - dirx - 1) / 2); + var r = blackMap.getValueAt(x + (dirx - diry - 1) / 2, y + (diry + dirx - 1) / 2); + if (r && !l) { + if (self._params.turnPolicy === "right" || self._params.turnPolicy === "black" && path2.sign === "+" || self._params.turnPolicy === "white" && path2.sign === "-" || self._params.turnPolicy === "majority" && majority(x, y) || self._params.turnPolicy === "minority" && !majority(x, y)) { + tmp = dirx; + dirx = -diry; + diry = tmp; + } else { + tmp = dirx; + dirx = diry; + diry = -tmp; + } + } else if (r) { + tmp = dirx; + dirx = -diry; + diry = tmp; + } else if (!l) { + tmp = dirx; + dirx = diry; + diry = -tmp; + } + } + return path2; + } + function xorPath(path2) { + var y1 = path2.pt[0].y, len = path2.len, x, y, maxX, minY, i, j, indx; + for (i = 1; i < len; i++) { + x = path2.pt[i].x; + y = path2.pt[i].y; + if (y !== y1) { + minY = y1 < y ? y1 : y; + maxX = path2.maxX; + for (j = x; j < maxX; j++) { + indx = blackMap.pointToIndex(j, minY); + blackMap.data[indx] = blackMap.data[indx] ? 0 : 1; + } + y1 = y; + } + } + } + this._pathlist = []; + while (currentPoint = findNext(currentPoint)) { + path = findPath(currentPoint); + xorPath(path); + if (path.area > self._params.turdSize) { + this._pathlist.push(path); + } + } + }, + /** + * Processes path list created by _bmToPathlist method creating and optimizing {@link Curve}'s + * @private + */ + _processPath: function() { + var self = this; + function calcSums(path2) { + var i2, x, y; + path2.x0 = path2.pt[0].x; + path2.y0 = path2.pt[0].y; + path2.sums = []; + var s = path2.sums; + s.push(new Sum(0, 0, 0, 0, 0)); + for (i2 = 0; i2 < path2.len; i2++) { + x = path2.pt[i2].x - path2.x0; + y = path2.pt[i2].y - path2.y0; + s.push(new Sum( + s[i2].x + x, + s[i2].y + y, + s[i2].xy + x * y, + s[i2].x2 + x * x, + s[i2].y2 + y * y + )); + } + } + function calcLon(path2) { + var n = path2.len, pt = path2.pt, dir, pivk = new Array(n), nc = new Array(n), ct = new Array(4); + path2.lon = new Array(n); + var constraint = [new Point(), new Point()], cur = new Point(), off = new Point(), dk = new Point(), foundk; + var i2, j, k1, a, b, c, d, k = 0; + for (i2 = n - 1; i2 >= 0; i2--) { + if (pt[i2].x != pt[k].x && pt[i2].y != pt[k].y) { + k = i2 + 1; + } + nc[i2] = k; + } + for (i2 = n - 1; i2 >= 0; i2--) { + ct[0] = ct[1] = ct[2] = ct[3] = 0; + dir = (3 + 3 * (pt[utils.mod(i2 + 1, n)].x - pt[i2].x) + (pt[utils.mod(i2 + 1, n)].y - pt[i2].y)) / 2; + ct[dir]++; + constraint[0].x = 0; + constraint[0].y = 0; + constraint[1].x = 0; + constraint[1].y = 0; + k = nc[i2]; + k1 = i2; + while (1) { + foundk = 0; + dir = (3 + 3 * utils.sign(pt[k].x - pt[k1].x) + utils.sign(pt[k].y - pt[k1].y)) / 2; + ct[dir]++; + if (ct[0] && ct[1] && ct[2] && ct[3]) { + pivk[i2] = k1; + foundk = 1; + break; + } + cur.x = pt[k].x - pt[i2].x; + cur.y = pt[k].y - pt[i2].y; + if (utils.xprod(constraint[0], cur) < 0 || utils.xprod(constraint[1], cur) > 0) { + break; + } + if (Math.abs(cur.x) <= 1 && Math.abs(cur.y) <= 1) { + } else { + off.x = cur.x + (cur.y >= 0 && (cur.y > 0 || cur.x < 0) ? 1 : -1); + off.y = cur.y + (cur.x <= 0 && (cur.x < 0 || cur.y < 0) ? 1 : -1); + if (utils.xprod(constraint[0], off) >= 0) { + constraint[0].x = off.x; + constraint[0].y = off.y; + } + off.x = cur.x + (cur.y <= 0 && (cur.y < 0 || cur.x < 0) ? 1 : -1); + off.y = cur.y + (cur.x >= 0 && (cur.x > 0 || cur.y < 0) ? 1 : -1); + if (utils.xprod(constraint[1], off) <= 0) { + constraint[1].x = off.x; + constraint[1].y = off.y; + } + } + k1 = k; + k = nc[k1]; + if (!utils.cyclic(k, i2, k1)) { + break; + } + } + if (foundk === 0) { + dk.x = utils.sign(pt[k].x - pt[k1].x); + dk.y = utils.sign(pt[k].y - pt[k1].y); + cur.x = pt[k1].x - pt[i2].x; + cur.y = pt[k1].y - pt[i2].y; + a = utils.xprod(constraint[0], cur); + b = utils.xprod(constraint[0], dk); + c = utils.xprod(constraint[1], cur); + d = utils.xprod(constraint[1], dk); + j = 1e7; + if (b < 0) { + j = Math.floor(a / -b); + } + if (d > 0) { + j = Math.min(j, Math.floor(-c / d)); + } + pivk[i2] = utils.mod(k1 + j, n); + } + } + j = pivk[n - 1]; + path2.lon[n - 1] = j; + for (i2 = n - 2; i2 >= 0; i2--) { + if (utils.cyclic(i2 + 1, pivk[i2], j)) { + j = pivk[i2]; + } + path2.lon[i2] = j; + } + for (i2 = n - 1; utils.cyclic(utils.mod(i2 + 1, n), j, path2.lon[i2]); i2--) { + path2.lon[i2] = j; + } + } + function bestPolygon(path2) { + function penalty3(path3, i3, j2) { + var n2 = path3.len, pt = path3.pt, sums = path3.sums; + var x, y, xy, x2, y2, k2, a, b, c2, s, px, py, ex, ey, r = 0; + if (j2 >= n2) { + j2 -= n2; + r = 1; + } + if (r === 0) { + x = sums[j2 + 1].x - sums[i3].x; + y = sums[j2 + 1].y - sums[i3].y; + x2 = sums[j2 + 1].x2 - sums[i3].x2; + xy = sums[j2 + 1].xy - sums[i3].xy; + y2 = sums[j2 + 1].y2 - sums[i3].y2; + k2 = j2 + 1 - i3; + } else { + x = sums[j2 + 1].x - sums[i3].x + sums[n2].x; + y = sums[j2 + 1].y - sums[i3].y + sums[n2].y; + x2 = sums[j2 + 1].x2 - sums[i3].x2 + sums[n2].x2; + xy = sums[j2 + 1].xy - sums[i3].xy + sums[n2].xy; + y2 = sums[j2 + 1].y2 - sums[i3].y2 + sums[n2].y2; + k2 = j2 + 1 - i3 + n2; + } + px = (pt[i3].x + pt[j2].x) / 2 - pt[0].x; + py = (pt[i3].y + pt[j2].y) / 2 - pt[0].y; + ey = pt[j2].x - pt[i3].x; + ex = -(pt[j2].y - pt[i3].y); + a = (x2 - 2 * x * px) / k2 + px * px; + b = (xy - x * py - y * px) / k2 + px * py; + c2 = (y2 - 2 * y * py) / k2 + py * py; + s = ex * ex * a + 2 * ex * ey * b + ey * ey * c2; + return Math.sqrt(s); + } + var i2, j, m, k, n = path2.len, pen = new Array(n + 1), prev = new Array(n + 1), clip0 = new Array(n), clip1 = new Array(n + 1), seg0 = new Array(n + 1), seg1 = new Array(n + 1), thispen, best, c; + for (i2 = 0; i2 < n; i2++) { + c = utils.mod(path2.lon[utils.mod(i2 - 1, n)] - 1, n); + if (c == i2) { + c = utils.mod(i2 + 1, n); + } + if (c < i2) { + clip0[i2] = n; + } else { + clip0[i2] = c; + } + } + j = 1; + for (i2 = 0; i2 < n; i2++) { + while (j <= clip0[i2]) { + clip1[j] = i2; + j++; + } + } + i2 = 0; + for (j = 0; i2 < n; j++) { + seg0[j] = i2; + i2 = clip0[i2]; + } + seg0[j] = n; + m = j; + i2 = n; + for (j = m; j > 0; j--) { + seg1[j] = i2; + i2 = clip1[i2]; + } + seg1[0] = 0; + pen[0] = 0; + for (j = 1; j <= m; j++) { + for (i2 = seg1[j]; i2 <= seg0[j]; i2++) { + best = -1; + for (k = seg0[j - 1]; k >= clip1[i2]; k--) { + thispen = penalty3(path2, k, i2) + pen[k]; + if (best < 0 || thispen < best) { + prev[i2] = k; + best = thispen; + } + } + pen[i2] = best; + } + } + path2.m = m; + path2.po = new Array(m); + for (i2 = n, j = m - 1; i2 > 0; j--) { + i2 = prev[i2]; + path2.po[j] = i2; + } + } + function adjustVertices(path2) { + function pointslope(path3, i3, j2, ctr2, dir2) { + var n2 = path3.len, sums = path3.sums, x, y, x2, xy, y2, k2, a, b, c, lambda2, l2, r = 0; + while (j2 >= n2) { + j2 -= n2; + r += 1; + } + while (i3 >= n2) { + i3 -= n2; + r -= 1; + } + while (j2 < 0) { + j2 += n2; + r -= 1; + } + while (i3 < 0) { + i3 += n2; + r += 1; + } + x = sums[j2 + 1].x - sums[i3].x + r * sums[n2].x; + y = sums[j2 + 1].y - sums[i3].y + r * sums[n2].y; + x2 = sums[j2 + 1].x2 - sums[i3].x2 + r * sums[n2].x2; + xy = sums[j2 + 1].xy - sums[i3].xy + r * sums[n2].xy; + y2 = sums[j2 + 1].y2 - sums[i3].y2 + r * sums[n2].y2; + k2 = j2 + 1 - i3 + r * n2; + ctr2.x = x / k2; + ctr2.y = y / k2; + a = (x2 - x * x / k2) / k2; + b = (xy - x * y / k2) / k2; + c = (y2 - y * y / k2) / k2; + lambda2 = (a + c + Math.sqrt((a - c) * (a - c) + 4 * b * b)) / 2; + a -= lambda2; + c -= lambda2; + if (Math.abs(a) >= Math.abs(c)) { + l2 = Math.sqrt(a * a + b * b); + if (l2 !== 0) { + dir2.x = -b / l2; + dir2.y = a / l2; + } + } else { + l2 = Math.sqrt(c * c + b * b); + if (l2 !== 0) { + dir2.x = -c / l2; + dir2.y = b / l2; + } + } + if (l2 === 0) { + dir2.x = dir2.y = 0; + } + } + var m = path2.m, po = path2.po, n = path2.len, pt = path2.pt, x0 = path2.x0, y0 = path2.y0, ctr = new Array(m), dir = new Array(m), q = new Array(m), v = new Array(3), d, i2, j, k, l, s = new Point(); + path2.curve = new Curve(m); + for (i2 = 0; i2 < m; i2++) { + j = po[utils.mod(i2 + 1, m)]; + j = utils.mod(j - po[i2], n) + po[i2]; + ctr[i2] = new Point(); + dir[i2] = new Point(); + pointslope(path2, po[i2], j, ctr[i2], dir[i2]); + } + for (i2 = 0; i2 < m; i2++) { + q[i2] = new Quad(); + d = dir[i2].x * dir[i2].x + dir[i2].y * dir[i2].y; + if (d === 0) { + for (j = 0; j < 3; j++) { + for (k = 0; k < 3; k++) { + q[i2].data[j * 3 + k] = 0; + } + } + } else { + v[0] = dir[i2].y; + v[1] = -dir[i2].x; + v[2] = -v[1] * ctr[i2].y - v[0] * ctr[i2].x; + for (l = 0; l < 3; l++) { + for (k = 0; k < 3; k++) { + q[i2].data[l * 3 + k] = v[l] * v[k] / d; + } + } + } + } + var Q, w, dx, dy, det, min, cand, xmin, ymin, z; + for (i2 = 0; i2 < m; i2++) { + Q = new Quad(); + w = new Point(); + s.x = pt[po[i2]].x - x0; + s.y = pt[po[i2]].y - y0; + j = utils.mod(i2 - 1, m); + for (l = 0; l < 3; l++) { + for (k = 0; k < 3; k++) { + Q.data[l * 3 + k] = q[j].at(l, k) + q[i2].at(l, k); + } + } + while (1) { + det = Q.at(0, 0) * Q.at(1, 1) - Q.at(0, 1) * Q.at(1, 0); + if (det !== 0) { + w.x = (-Q.at(0, 2) * Q.at(1, 1) + Q.at(1, 2) * Q.at(0, 1)) / det; + w.y = (Q.at(0, 2) * Q.at(1, 0) - Q.at(1, 2) * Q.at(0, 0)) / det; + break; + } + if (Q.at(0, 0) > Q.at(1, 1)) { + v[0] = -Q.at(0, 1); + v[1] = Q.at(0, 0); + } else if (Q.at(1, 1)) { + v[0] = -Q.at(1, 1); + v[1] = Q.at(1, 0); + } else { + v[0] = 1; + v[1] = 0; + } + d = v[0] * v[0] + v[1] * v[1]; + v[2] = -v[1] * s.y - v[0] * s.x; + for (l = 0; l < 3; l++) { + for (k = 0; k < 3; k++) { + Q.data[l * 3 + k] += v[l] * v[k] / d; + } + } + } + dx = Math.abs(w.x - s.x); + dy = Math.abs(w.y - s.y); + if (dx <= 0.5 && dy <= 0.5) { + path2.curve.vertex[i2] = new Point(w.x + x0, w.y + y0); + continue; + } + min = utils.quadform(Q, s); + xmin = s.x; + ymin = s.y; + if (Q.at(0, 0) !== 0) { + for (z = 0; z < 2; z++) { + w.y = s.y - 0.5 + z; + w.x = -(Q.at(0, 1) * w.y + Q.at(0, 2)) / Q.at(0, 0); + dx = Math.abs(w.x - s.x); + cand = utils.quadform(Q, w); + if (dx <= 0.5 && cand < min) { + min = cand; + xmin = w.x; + ymin = w.y; + } + } + } + if (Q.at(1, 1) !== 0) { + for (z = 0; z < 2; z++) { + w.x = s.x - 0.5 + z; + w.y = -(Q.at(1, 0) * w.x + Q.at(1, 2)) / Q.at(1, 1); + dy = Math.abs(w.y - s.y); + cand = utils.quadform(Q, w); + if (dy <= 0.5 && cand < min) { + min = cand; + xmin = w.x; + ymin = w.y; + } + } + } + for (l = 0; l < 2; l++) { + for (k = 0; k < 2; k++) { + w.x = s.x - 0.5 + l; + w.y = s.y - 0.5 + k; + cand = utils.quadform(Q, w); + if (cand < min) { + min = cand; + xmin = w.x; + ymin = w.y; + } + } + } + path2.curve.vertex[i2] = new Point(xmin + x0, ymin + y0); + } + } + function reverse(path2) { + var curve = path2.curve, m = curve.n, v = curve.vertex, i2, j, tmp; + for (i2 = 0, j = m - 1; i2 < j; i2++, j--) { + tmp = v[i2]; + v[i2] = v[j]; + v[j] = tmp; + } + } + function smooth(path2) { + var m = path2.curve.n, curve = path2.curve; + var i2, j, k, dd, denom, alpha, p2, p3, p4; + for (i2 = 0; i2 < m; i2++) { + j = utils.mod(i2 + 1, m); + k = utils.mod(i2 + 2, m); + p4 = utils.interval(1 / 2, curve.vertex[k], curve.vertex[j]); + denom = utils.ddenom(curve.vertex[i2], curve.vertex[k]); + if (denom !== 0) { + dd = utils.dpara(curve.vertex[i2], curve.vertex[j], curve.vertex[k]) / denom; + dd = Math.abs(dd); + alpha = dd > 1 ? 1 - 1 / dd : 0; + alpha = alpha / 0.75; + } else { + alpha = 4 / 3; + } + curve.alpha0[j] = alpha; + if (alpha >= self._params.alphaMax) { + curve.tag[j] = "CORNER"; + curve.c[3 * j + 1] = curve.vertex[j]; + curve.c[3 * j + 2] = p4; + } else { + if (alpha < 0.55) { + alpha = 0.55; + } else if (alpha > 1) { + alpha = 1; + } + p2 = utils.interval(0.5 + 0.5 * alpha, curve.vertex[i2], curve.vertex[j]); + p3 = utils.interval(0.5 + 0.5 * alpha, curve.vertex[k], curve.vertex[j]); + curve.tag[j] = "CURVE"; + curve.c[3 * j + 0] = p2; + curve.c[3 * j + 1] = p3; + curve.c[3 * j + 2] = p4; + } + curve.alpha[j] = alpha; + curve.beta[j] = 0.5; + } + curve.alphaCurve = 1; + } + function optiCurve(path2) { + function opti_penalty(path3, i3, j2, res, opttolerance, convc2, areac2) { + var m2 = path3.curve.n, curve2 = path3.curve, vertex = curve2.vertex, k, k1, k2, conv, i12, area2, alpha2, d, d1, d2, p02, p1, p2, p3, pt2, A, R, A1, A2, A3, A4, s2, t2; + if (i3 == j2) { + return 1; + } + k = i3; + i12 = utils.mod(i3 + 1, m2); + k1 = utils.mod(k + 1, m2); + conv = convc2[k1]; + if (conv === 0) { + return 1; + } + d = utils.ddist(vertex[i3], vertex[i12]); + for (k = k1; k != j2; k = k1) { + k1 = utils.mod(k + 1, m2); + k2 = utils.mod(k + 2, m2); + if (convc2[k1] != conv) { + return 1; + } + if (utils.sign(utils.cprod(vertex[i3], vertex[i12], vertex[k1], vertex[k2])) != conv) { + return 1; + } + if (utils.iprod1(vertex[i3], vertex[i12], vertex[k1], vertex[k2]) < d * utils.ddist(vertex[k1], vertex[k2]) * -0.999847695156) { + return 1; + } + } + p02 = curve2.c[utils.mod(i3, m2) * 3 + 2].copy(); + p1 = vertex[utils.mod(i3 + 1, m2)].copy(); + p2 = vertex[utils.mod(j2, m2)].copy(); + p3 = curve2.c[utils.mod(j2, m2) * 3 + 2].copy(); + area2 = areac2[j2] - areac2[i3]; + area2 -= utils.dpara(vertex[0], curve2.c[i3 * 3 + 2], curve2.c[j2 * 3 + 2]) / 2; + if (i3 >= j2) { + area2 += areac2[m2]; + } + A1 = utils.dpara(p02, p1, p2); + A2 = utils.dpara(p02, p1, p3); + A3 = utils.dpara(p02, p2, p3); + A4 = A1 + A3 - A2; + if (A2 == A1) { + return 1; + } + t2 = A3 / (A3 - A4); + s2 = A2 / (A2 - A1); + A = A2 * t2 / 2; + if (A === 0) { + return 1; + } + R = area2 / A; + alpha2 = 2 - Math.sqrt(4 - R / 0.3); + res.c[0] = utils.interval(t2 * alpha2, p02, p1); + res.c[1] = utils.interval(s2 * alpha2, p3, p2); + res.alpha = alpha2; + res.t = t2; + res.s = s2; + p1 = res.c[0].copy(); + p2 = res.c[1].copy(); + res.pen = 0; + for (k = utils.mod(i3 + 1, m2); k != j2; k = k1) { + k1 = utils.mod(k + 1, m2); + t2 = utils.tangent(p02, p1, p2, p3, vertex[k], vertex[k1]); + if (t2 < -0.5) { + return 1; + } + pt2 = utils.bezier(t2, p02, p1, p2, p3); + d = utils.ddist(vertex[k], vertex[k1]); + if (d === 0) { + return 1; + } + d1 = utils.dpara(vertex[k], vertex[k1], pt2) / d; + if (Math.abs(d1) > opttolerance) { + return 1; + } + if (utils.iprod(vertex[k], vertex[k1], pt2) < 0 || utils.iprod(vertex[k1], vertex[k], pt2) < 0) { + return 1; + } + res.pen += d1 * d1; + } + for (k = i3; k != j2; k = k1) { + k1 = utils.mod(k + 1, m2); + t2 = utils.tangent(p02, p1, p2, p3, curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2]); + if (t2 < -0.5) { + return 1; + } + pt2 = utils.bezier(t2, p02, p1, p2, p3); + d = utils.ddist(curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2]); + if (d === 0) { + return 1; + } + d1 = utils.dpara(curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2], pt2) / d; + d2 = utils.dpara(curve2.c[k * 3 + 2], curve2.c[k1 * 3 + 2], vertex[k1]) / d; + d2 *= 0.75 * curve2.alpha[k1]; + if (d2 < 0) { + d1 = -d1; + d2 = -d2; + } + if (d1 < d2 - opttolerance) { + return 1; + } + if (d1 < d2) { + res.pen += (d1 - d2) * (d1 - d2); + } + } + return 0; + } + var curve = path2.curve, m = curve.n, vert = curve.vertex, pt = new Array(m + 1), pen = new Array(m + 1), len = new Array(m + 1), opt = new Array(m + 1), om, i2, j, r, o = new Opti(), p0, i1, area, alpha, ocurve, s, t; + var convc = new Array(m), areac = new Array(m + 1); + for (i2 = 0; i2 < m; i2++) { + if (curve.tag[i2] == "CURVE") { + convc[i2] = utils.sign(utils.dpara(vert[utils.mod(i2 - 1, m)], vert[i2], vert[utils.mod(i2 + 1, m)])); + } else { + convc[i2] = 0; + } + } + area = 0; + areac[0] = 0; + p0 = curve.vertex[0]; + for (i2 = 0; i2 < m; i2++) { + i1 = utils.mod(i2 + 1, m); + if (curve.tag[i1] == "CURVE") { + alpha = curve.alpha[i1]; + area += 0.3 * alpha * (4 - alpha) * utils.dpara(curve.c[i2 * 3 + 2], vert[i1], curve.c[i1 * 3 + 2]) / 2; + area += utils.dpara(p0, curve.c[i2 * 3 + 2], curve.c[i1 * 3 + 2]) / 2; + } + areac[i2 + 1] = area; + } + pt[0] = -1; + pen[0] = 0; + len[0] = 0; + for (j = 1; j <= m; j++) { + pt[j] = j - 1; + pen[j] = pen[j - 1]; + len[j] = len[j - 1] + 1; + for (i2 = j - 2; i2 >= 0; i2--) { + r = opti_penalty( + path2, + i2, + utils.mod(j, m), + o, + self._params.optTolerance, + convc, + areac + ); + if (r) { + break; + } + if (len[j] > len[i2] + 1 || len[j] == len[i2] + 1 && pen[j] > pen[i2] + o.pen) { + pt[j] = i2; + pen[j] = pen[i2] + o.pen; + len[j] = len[i2] + 1; + opt[j] = o; + o = new Opti(); + } + } + } + om = len[m]; + ocurve = new Curve(om); + s = new Array(om); + t = new Array(om); + j = m; + for (i2 = om - 1; i2 >= 0; i2--) { + if (pt[j] == j - 1) { + ocurve.tag[i2] = curve.tag[utils.mod(j, m)]; + ocurve.c[i2 * 3 + 0] = curve.c[utils.mod(j, m) * 3 + 0]; + ocurve.c[i2 * 3 + 1] = curve.c[utils.mod(j, m) * 3 + 1]; + ocurve.c[i2 * 3 + 2] = curve.c[utils.mod(j, m) * 3 + 2]; + ocurve.vertex[i2] = curve.vertex[utils.mod(j, m)]; + ocurve.alpha[i2] = curve.alpha[utils.mod(j, m)]; + ocurve.alpha0[i2] = curve.alpha0[utils.mod(j, m)]; + ocurve.beta[i2] = curve.beta[utils.mod(j, m)]; + s[i2] = t[i2] = 1; + } else { + ocurve.tag[i2] = "CURVE"; + ocurve.c[i2 * 3 + 0] = opt[j].c[0]; + ocurve.c[i2 * 3 + 1] = opt[j].c[1]; + ocurve.c[i2 * 3 + 2] = curve.c[utils.mod(j, m) * 3 + 2]; + ocurve.vertex[i2] = utils.interval( + opt[j].s, + curve.c[utils.mod(j, m) * 3 + 2], + vert[utils.mod(j, m)] + ); + ocurve.alpha[i2] = opt[j].alpha; + ocurve.alpha0[i2] = opt[j].alpha; + s[i2] = opt[j].s; + t[i2] = opt[j].t; + } + j = pt[j]; + } + for (i2 = 0; i2 < om; i2++) { + i1 = utils.mod(i2 + 1, om); + ocurve.beta[i2] = s[i2] / (s[i2] + t[i1]); + } + ocurve.alphaCurve = 1; + path2.curve = ocurve; + } + for (var i = 0; i < this._pathlist.length; i++) { + var path = this._pathlist[i]; + calcSums(path); + calcLon(path); + bestPolygon(path); + adjustVertices(path); + if (path.sign === "-") { + reverse(path); + } + smooth(path); + if (self._params.optCurve) { + optiCurve(path); + } + } + }, + /** + * Validates some of parameters + * @param params + * @private + */ + _validateParameters: function(params) { + if (params && params.turnPolicy && SUPPORTED_TURNPOLICY_VALUES.indexOf(params.turnPolicy) === -1) { + var goodVals = "'" + SUPPORTED_TURNPOLICY_VALUES.join("', '") + "'"; + throw new Error("Bad turnPolicy value. Allowed values are: " + goodVals); + } + if (params && params.threshold != null && params.threshold !== Potrace2.THRESHOLD_AUTO) { + if (typeof params.threshold !== "number" || !utils.between(params.threshold, 0, 255)) { + throw new Error("Bad threshold value. Expected to be an integer in range 0..255"); + } + } + if (params && params.optCurve != null && typeof params.optCurve !== "boolean") { + throw new Error("'optCurve' must be Boolean"); + } + }, + /** + * 本项目新增:直接吃浏览器 ImageData({width,height,data:Uint8ClampedArray}), + * 不再经过 jimp。透明像素按白底合成 —— 与上游 `_processLoadedImage` 的语义一致 + * (电商素材多为透明底 PNG,若把 alpha 当黑会整片变实心)。 + */ + loadImageData: function(imageData) { + if (!imageData || !imageData.width || !imageData.height || !imageData.data) { + throw new Error("loadImageData: 需要 {width,height,data} 形式的 ImageData"); + } + this._imageLoadingIdentifier = null; + this._processLoadedImage(imageData); + }, + _processLoadedImage: function(image) { + var src = image.bitmap ? image.bitmap : image; + var width = src.width, height = src.height; + var pixels = src.data; + var bitmap = new Bitmap(width, height); + for (var i = 0, n = width * height; i < n; i++) { + var idx = i * 4; + var opacity = pixels[idx + 3] / 255, r = 255 + (pixels[idx + 0] - 255) * opacity, g = 255 + (pixels[idx + 1] - 255) * opacity, b = 255 + (pixels[idx + 2] - 255) * opacity; + bitmap.data[i] = utils.luminance(r, g, b); + } + this._luminanceData = bitmap; + this._imageLoaded = true; + }, + /** + * 上游接口:按路径/Buffer 读图(依赖 jimp)。本内联版**去掉了 jimp**, + * 因此这里只保留签名,改为提示用 `loadImageData`。保留它是为了不破坏上游类型约定, + * 也避免调用方拿到 "Jimp is not defined" 这种莫名其妙的错误。 + */ + loadImage: function(target, callback) { + var err = new Error("本内联版 potrace 不支持按路径读图,请改用 loadImageData(imageData)"); + if (typeof callback === "function") return callback.call(this, err); + throw err; + }, + /** + * Sets algorithm parameters + * @param {Potrace~Options} newParams + */ + setParameters: function(newParams) { + var key, tmpOldVal; + this._validateParameters(newParams); + for (key in this._params) { + if (this._params.hasOwnProperty(key) && newParams.hasOwnProperty(key)) { + tmpOldVal = this._params[key]; + this._params[key] = newParams[key]; + if (tmpOldVal !== this._params[key] && ["color", "background"].indexOf(key) === -1) { + this._processed = false; + } + } + } + }, + /** + * Generates just tag without rest of the SVG file + * + * @param {String} [fillColor] - overrides color from parameters + * @returns {String} + */ + getPathTag: function(fillColor, scale) { + fillColor = arguments.length === 0 ? this._params.color : fillColor; + if (fillColor === Potrace2.COLOR_AUTO) { + fillColor = this._params.blackOnWhite ? "black" : "white"; + } + if (!this._imageLoaded) { + throw new Error("Image should be loaded first"); + } + if (!this._processed) { + this._bmToPathlist(); + this._processPath(); + this._processed = true; + } + var tag = ''; + return tag; + }, + /** + * Returns tag. Always has viewBox specified and comes with no fill color, + * so it could be changed with tag + * + * @param id + * @returns {string} + */ + getSymbol: function(id) { + return '' + this.getPathTag("") + ""; + }, + /** + * Generates SVG image + * @returns {String} + */ + getSVG: function() { + var width = this._params.width || this._luminanceData.width; + var height = this._params.height || this._luminanceData.height; + var scale = { + x: this._params.width ? this._params.width / this._luminanceData.width : 1, + y: this._params.height ? this._params.height / this._luminanceData.height : 1 + }; + return '\n' + (this._params.background !== Potrace2.COLOR_TRANSPARENT ? ' \n' : "") + " " + this.getPathTag(this._params.color, scale) + "\n"; + } + }; + module.exports = Potrace2; + } + }); + + // image-vectorize/plugin/vendor/potrace/Posterizer.js + var require_Posterizer = __commonJS({ + "image-vectorize/plugin/vendor/potrace/Posterizer.js"(exports, module) { + "use strict"; + var Potrace2 = require_Potrace(); + var utils = require_utils(); + function Posterizer2(options) { + this._potrace = new Potrace2(); + this._calculatedThreshold = null; + this._params = { + threshold: Potrace2.THRESHOLD_AUTO, + blackOnWhite: true, + steps: Posterizer2.STEPS_AUTO, + background: Potrace2.COLOR_TRANSPARENT, + fillStrategy: Posterizer2.FILL_DOMINANT, + rangeDistribution: Posterizer2.RANGES_AUTO + }; + if (options) { + this.setParameters(options); + } + } + for (key in Potrace2) { + if (Object.prototype.hasOwnProperty.call(Potrace2, key) && key === key.toUpperCase()) { + Posterizer2[key] = Potrace2[key]; + } + } + var key; + Posterizer2.STEPS_AUTO = -1; + Posterizer2.FILL_SPREAD = "spread"; + Posterizer2.FILL_DOMINANT = "dominant"; + Posterizer2.FILL_MEDIAN = "median"; + Posterizer2.FILL_MEAN = "mean"; + Posterizer2.RANGES_AUTO = "auto"; + Posterizer2.RANGES_EQUAL = "equal"; + Posterizer2.prototype = { + /** + * Fine tuning to color ranges. + * + * If last range (featuring most saturated color) is larger than 10% of color space (25 units) + * then we want to add another color stop, that hopefully will include darkest pixels, improving presence of + * shadows and line art + * + * @param ranges + * @private + */ + _addExtraColorStop: function(ranges) { + var blackOnWhite = this._params.blackOnWhite; + var lastColorStop = ranges[ranges.length - 1]; + var lastRangeFrom = blackOnWhite ? 0 : lastColorStop.value; + var lastRangeTo = blackOnWhite ? lastColorStop.value : 255; + if (lastRangeTo - lastRangeFrom > 25 && lastColorStop.colorIntensity !== 1) { + var histogram = this._getImageHistogram(); + var levels = histogram.getStats(lastRangeFrom, lastRangeTo).levels; + var newColorStop = levels.mean + levels.stdDev <= 25 ? levels.mean + levels.stdDev : levels.mean - levels.stdDev <= 25 ? levels.mean - levels.stdDev : 25; + var newStats = blackOnWhite ? histogram.getStats(0, newColorStop) : histogram.getStats(newColorStop, 255); + var color = newStats.levels.mean; + ranges.push({ + value: Math.abs((blackOnWhite ? 0 : 255) - newColorStop), + colorIntensity: isNaN(color) ? 0 : (blackOnWhite ? 255 - color : color) / 255 + }); + } + return ranges; + }, + /** + * Calculates color intensity for each element of numeric array + * + * @param {number[]} colorStops + * @returns {{ levels: number, colorIntensity: number }[]} + * @private + */ + _calcColorIntensity: function(colorStops) { + var blackOnWhite = this._params.blackOnWhite; + var colorSelectionStrat = this._params.fillStrategy; + var histogram = colorSelectionStrat !== Posterizer2.FILL_SPREAD ? this._getImageHistogram() : null; + var fullRange = Math.abs(this._paramThreshold() - (blackOnWhite ? 0 : 255)); + return colorStops.map(function(threshold, index) { + var nextValue = index + 1 === colorStops.length ? blackOnWhite ? -1 : 256 : colorStops[index + 1]; + var rangeStart = Math.round(blackOnWhite ? nextValue + 1 : threshold); + var rangeEnd = Math.round(blackOnWhite ? threshold : nextValue - 1); + var factor = index / (colorStops.length - 1); + var intervalSize = rangeEnd - rangeStart; + var stats = histogram.getStats(rangeStart, rangeEnd); + var color = -1; + if (stats.pixels === 0) { + return { + value: threshold, + colorIntensity: 0 + }; + } + switch (colorSelectionStrat) { + case Posterizer2.FILL_SPREAD: + color = (blackOnWhite ? rangeStart : rangeEnd) + (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor; + break; + case Posterizer2.FILL_DOMINANT: + color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5)); + break; + case Posterizer2.FILL_MEAN: + color = stats.levels.mean; + break; + case Posterizer2.FILL_MEDIAN: + color = stats.levels.median; + break; + } + if (index !== 0) { + color = blackOnWhite ? utils.clamp(color, rangeStart, rangeEnd - Math.round(intervalSize * 0.1)) : utils.clamp(color, rangeStart + Math.round(intervalSize * 0.1), rangeEnd); + } + return { + value: threshold, + colorIntensity: color === -1 ? 0 : (blackOnWhite ? 255 - color : color) / 255 + }; + }); + }, + /** + * @returns {Histogram} + * @private + */ + _getImageHistogram: function() { + return this._potrace._luminanceData.histogram(); + }, + /** + * Processes threshold, steps and rangeDistribution parameters and returns normalized array of color stops + * @returns {*} + * @private + */ + _getRanges: function() { + var steps = this._paramSteps(); + if (!Array.isArray(steps)) { + return this._params.rangeDistribution === Posterizer2.RANGES_AUTO ? this._getRangesAuto() : this._getRangesEquallyDistributed(); + } + var colorStops = []; + var threshold = this._paramThreshold(); + var lookingForDarkPixels = this._params.blackOnWhite; + steps.forEach(function(item) { + if (colorStops.indexOf(item) === -1 && utils.between(item, 0, 255)) { + colorStops.push(item); + } + }); + if (!colorStops.length) { + colorStops.push(threshold); + } + colorStops = colorStops.sort(function(a, b) { + return a < b === lookingForDarkPixels ? 1 : -1; + }); + if (lookingForDarkPixels && colorStops[0] < threshold) { + colorStops.unshift(threshold); + } else if (!lookingForDarkPixels && colorStops[colorStops.length - 1] < threshold) { + colorStops.push(threshold); + } + return this._calcColorIntensity(colorStops); + }, + /** + * Calculates given (or lower) number of thresholds using automatic thresholding algorithm + * @returns {*} + * @private + */ + _getRangesAuto: function() { + var histogram = this._getImageHistogram(); + var steps = this._paramSteps(true); + var colorStops; + if (this._params.threshold === Potrace2.THRESHOLD_AUTO) { + colorStops = histogram.multilevelThresholding(steps); + } else { + var threshold = this._paramThreshold(); + colorStops = this._params.blackOnWhite ? histogram.multilevelThresholding(steps - 1, 0, threshold) : histogram.multilevelThresholding(steps - 1, threshold, 255); + if (this._params.blackOnWhite) { + colorStops.push(threshold); + } else { + colorStops.unshift(threshold); + } + } + if (this._params.blackOnWhite) { + colorStops = colorStops.reverse(); + } + return this._calcColorIntensity(colorStops); + }, + /** + * Calculates color stops and color representing each segment, returning them + * from least to most intense color (black or white, depending on blackOnWhite parameter) + * + * @private + */ + _getRangesEquallyDistributed: function() { + var blackOnWhite = this._params.blackOnWhite; + var colorsToThreshold = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold(); + var steps = this._paramSteps(); + var stepSize = colorsToThreshold / steps; + var colorStops = []; + var i = steps - 1, factor, threshold; + while (i >= 0) { + factor = i / (steps - 1); + threshold = Math.min(colorsToThreshold, (i + 1) * stepSize); + threshold = blackOnWhite ? threshold : 255 - threshold; + i--; + colorStops.push(threshold); + } + return this._calcColorIntensity(colorStops); + }, + /** + * Returns valid steps value + * @param {Boolean} [count=false] + * @returns {number|number[]} + * @private + */ + _paramSteps: function(count) { + var steps = this._params.steps; + if (Array.isArray(steps)) { + return count ? steps.length : steps; + } + if (steps === Posterizer2.STEPS_AUTO && this._params.threshold === Potrace2.THRESHOLD_AUTO) { + return 4; + } + var blackOnWhite = this._params.blackOnWhite; + var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold(); + return steps === Posterizer2.STEPS_AUTO ? colorsCount > 200 ? 4 : 3 : Math.min(colorsCount, Math.max(2, steps)); + }, + /** + * Returns valid threshold value + * @returns {number} + * @private + */ + _paramThreshold: function() { + if (this._calculatedThreshold !== null) { + return this._calculatedThreshold; + } + if (this._params.threshold !== Potrace2.THRESHOLD_AUTO) { + this._calculatedThreshold = this._params.threshold; + return this._calculatedThreshold; + } + var twoThresholds = this._getImageHistogram().multilevelThresholding(2); + this._calculatedThreshold = this._params.blackOnWhite ? twoThresholds[1] : twoThresholds[0]; + this._calculatedThreshold = this._calculatedThreshold || 128; + return this._calculatedThreshold; + }, + /** + * Running potrace on the image multiple times with different thresholds and returns an array + * of path tags + * + * @param {Boolean} [noFillColor] + * @returns {string[]} + * @private + */ + _pathTags: function(noFillColor) { + var ranges = this._getRanges(); + var potrace = this._potrace; + var blackOnWhite = this._params.blackOnWhite; + if (ranges.length >= 10) { + ranges = this._addExtraColorStop(ranges); + } + potrace.setParameters({ blackOnWhite }); + var actualPrevLayersOpacity = 0; + return ranges.map(function(colorStop) { + var thisLayerOpacity = colorStop.colorIntensity; + if (thisLayerOpacity === 0) { + return ""; + } + var calculatedOpacity = !actualPrevLayersOpacity || thisLayerOpacity === 1 ? thisLayerOpacity : (actualPrevLayersOpacity - thisLayerOpacity) / (actualPrevLayersOpacity - 1); + calculatedOpacity = utils.clamp(parseFloat(calculatedOpacity.toFixed(3)), 0, 1); + actualPrevLayersOpacity = actualPrevLayersOpacity + (1 - actualPrevLayersOpacity) * calculatedOpacity; + potrace.setParameters({ threshold: colorStop.value }); + var element = noFillColor ? potrace.getPathTag("") : potrace.getPathTag(); + element = utils.setHtmlAttr(element, "fill-opacity", calculatedOpacity.toFixed(3)); + var canBeIgnored = calculatedOpacity === 0 || element.indexOf(' d=""') !== -1; + return canBeIgnored ? "" : element; + }); + }, + /** + * Loads image. + * + * @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP + * @param {Function} callback + */ + loadImage: function(target, callback) { + var self = this; + this._potrace.loadImage(target, function(err) { + self._calculatedThreshold = null; + callback.call(self, err); + }); + }, + /** + * 本项目新增:直接吃浏览器 ImageData(同步),与 Potrace#loadImageData 对应。 + * 灰度分层不需要异步读图 ⇒ 调用方拿到的就是同步结果,省掉一层回调。 + */ + loadImageData: function(imageData) { + this._potrace.loadImageData(imageData); + this._calculatedThreshold = null; + }, + /** + * Sets parameters. Accepts same object as {Potrace} + * + * @param {Posterizer~Options} params + */ + setParameters: function(params) { + if (!params) { + return; + } + this._potrace.setParameters(params); + if (params.steps && !Array.isArray(params.steps) && (!utils.isNumber(params.steps) || !utils.between(params.steps, 1, 255))) { + throw new Error("Bad 'steps' value"); + } + for (var key2 in this._params) { + if (this._params.hasOwnProperty(key2) && params.hasOwnProperty(key2)) { + this._params[key2] = params[key2]; + } + } + this._calculatedThreshold = null; + }, + /** + * Returns image as tag. Always has viewBox specified + * + * @param {string} id + */ + getSymbol: function(id) { + var width = this._potrace._luminanceData.width; + var height = this._potrace._luminanceData.height; + var paths = this._pathTags(true); + return '' + paths.join("") + ""; + }, + /** + * Generates SVG image + * @returns {String} + */ + getSVG: function() { + var width = this._potrace._luminanceData.width, height = this._potrace._luminanceData.height; + var tags = this._pathTags(false); + var svg = '\n ' + (this._params.background !== Potrace2.COLOR_TRANSPARENT ? '\n ' : "") + tags.join("\n ") + "\n"; + return svg.replace(/\n(?:\t*\n)+(\t*)/g, "\n$1"); + } + }; + module.exports = Posterizer2; + } + }); + + // image-vectorize/plugin/ui.css + var ui_default = `/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。 + CSP:由宿主 style-src 'unsafe-inline' 放行,运行时注入