// 手写 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.6',
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 += `
${typeIconSvg}
${esc(item.name)}
${item.paintTarget ? '✎' : ""}
${pct < 100 && !item.active ? `${pct}%` : ""}
${item.canDelete ? `` : ""}
${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 = `
工具选项
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) return;
const k = v / 100;
if (FILTER_SUPPORTED) {
filterCanvas(canvas, "invert(" + k + ")");
return;
}
const ok = mapPixels(canvas, (r, g, b) => [
clamp255(r + (255 - 2 * r) * k),
clamp255(g + (255 - 2 * g) * k),
clamp255(b + (255 - 2 * b) * k)
]);
if (!ok) blendFallback(canvas, "invert", k);
}
},
gray: {
label: "灰度",
hint: "去色,保留明暗层次",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v <= 0) return;
const k = v / 100;
if (FILTER_SUPPORTED) {
filterCanvas(canvas, "grayscale(" + k + ")");
return;
}
const okGray = mapPixels(canvas, (r, g, b) => {
const y = luma(r, g, b);
return [clamp255(r + (y - r) * k), clamp255(g + (y - g) * k), clamp255(b + (y - b) * k)];
});
if (!okGray) blendFallback(canvas, "gray", k);
}
},
boost: {
label: "增强",
hint: "提亮并加对比,适合发灰的截图",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v <= 0) return;
const k = v / 100;
if (FILTER_SUPPORTED) {
filterCanvas(canvas, "brightness(" + (1 + 0.4 * k).toFixed(3) + ") contrast(" + (1 + 0.25 * k).toFixed(3) + ") saturate(" + (1 + 0.2 * k).toFixed(3) + ")");
return;
}
const bright = 1 + 0.4 * k, contrast = 1 + 0.25 * k, sat = 1 + 0.2 * k;
mapPixels(canvas, (r, g, b) => {
const y = luma(r, g, b);
const out = [r, g, b].map((c) => {
let v2 = y + (c - y) * sat;
v2 = (v2 - 128) * contrast + 128;
return clamp255(v2 * bright);
});
return out;
});
}
},
contrast: {
label: "高对比",
hint: "压成黑白硬调,突出主体",
param: "强度",
unit: "%",
min: 0,
max: 100,
step: 1,
def: () => 100,
render: (canvas, v) => {
if (v <= 0) return;
const k = v / 100;
if (FILTER_SUPPORTED) {
filterCanvas(canvas, "grayscale(" + k.toFixed(3) + ") contrast(" + (1 + 1.6 * k).toFixed(3) + ")");
return;
}
const c = 1 + 1.6 * k;
mapPixels(canvas, (r, g, b) => {
const y = luma(r, g, b);
const gray = y * k + (r + g + b) / 3 * (1 - k);
const v2 = (gray - 128) * c + 128;
return [clamp255(v2), clamp255(v2), clamp255(v2)];
});
}
},
soft: {
label: "柔化",
hint: "模糊,弱化背景",
param: "半径",
unit: "px",
min: 0,
max: 16,
step: 0.5,
def: (canvas) => softRadius(canvas),
render: (canvas, v) => {
if (v <= 0) return;
if (FILTER_SUPPORTED) filterCanvas(canvas, "blur(" + v + "px)");
else blurCanvas(canvas, v);
}
},
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();
}
var FILTER_SUPPORTED = function() {
try {
const src = document.createElement("canvas");
src.width = 2;
src.height = 2;
const sctx = src.getContext("2d");
sctx.fillStyle = "#ff0000";
sctx.fillRect(0, 0, 2, 2);
const dst = document.createElement("canvas");
dst.width = 2;
dst.height = 2;
const dctx = dst.getContext("2d");
dctx.filter = "invert(1)";
dctx.drawImage(src, 0, 0);
const d = dctx.getImageData(0, 0, 1, 1).data;
return d[0] < 60 && d[1] > 180 && d[2] > 180;
} catch (e) {
return false;
}
}();
function mapPixels(canvas, fn) {
const w = canvas.width, h = canvas.height;
if (!w || !h) return false;
const ctx = canvas.getContext("2d", { willReadFrequently: true });
let img;
try {
img = ctx.getImageData(0, 0, w, h);
} catch (e) {
return false;
}
const d = img.data;
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] === 0) continue;
const out = fn(d[i], d[i + 1], d[i + 2]);
d[i] = out[0];
d[i + 1] = out[1];
d[i + 2] = out[2];
}
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.putImageData(img, 0, 0);
return true;
}
function blendFallback(canvas, mode, strength) {
const k = typeof strength === "number" ? Math.max(0, Math.min(1, strength)) : 1;
const ctx = canvas.getContext("2d");
const copy = document.createElement("canvas");
copy.width = canvas.width;
copy.height = canvas.height;
copy.getContext("2d").drawImage(canvas, 0, 0);
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalAlpha = 1;
if (mode === "invert") {
ctx.globalCompositeOperation = "difference";
ctx.fillStyle = "#ffffff";
} else {
ctx.globalCompositeOperation = "saturation";
ctx.fillStyle = "#808080";
}
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (k < 1) {
ctx.globalCompositeOperation = "source-over";
ctx.globalAlpha = 1 - k;
ctx.drawImage(copy, 0, 0);
}
ctx.restore();
}
function luma(r, g, b) {
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
function clamp255(v) {
return v < 0 ? 0 : v > 255 ? 255 : v;
}
function blurCanvas(canvas, radius) {
const w = canvas.width, h = canvas.height;
if (!w || !h || radius <= 0) return;
const n = Math.max(2, Math.min(16, Math.round(radius * 1.6)));
const sw = Math.max(1, Math.round(w / n));
const sh = Math.max(1, Math.round(h / n));
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 = true;
ctx.drawImage(tmp, 0, 0, w, h);
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();
try {
fx.render(target.canvas, value);
} catch (e) {
toast("效果失败:" + (e && e.message || e), "error");
throw e;
}
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.isDrawing && e.buttons === 0) {
S.isDrawing = false;
const up = Object.prototype.hasOwnProperty.call(DRAW_UP_HANDLERS, S.tool) ? DRAW_UP_HANDLERS[S.tool] : null;
try {
if (up) up(getPos(e));
} catch (err) {
}
}
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 `比例
尺寸
×
--
拖出裁剪框;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) => ``;
const aBtn = (val, label, title) => ``;
return `
字体
字重${wBtn("normal", "常规", "常规字重")}${wBtn("bold", "粗", "粗体(默认)")}${wBtn("900", "特粗", "特粗,封面标题用")}
对齐${aBtn("left", "左", "多行时按左缘对齐")}${aBtn("center", "中", "多行时居中")}${aBtn("right", "右", "多行时按右缘对齐")}
行距
%
描边
px
`;
}
var SELCMD_SVGS = {
all: '',
invert: '',
none: ''
};
var selCmdHTML = () => `
`;
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 `形状
` + 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 resetPointerState() {
S.isDrawing = false;
S.marquee = null;
S.lassoPts = null;
S.textDrag = null;
S.bitmapDrag = null;
S.shapeDrag = null;
S.penDragPt = -1;
S.penDragPending = null;
S.placingHandle = null;
S.panning = false;
S.interaction = "idle";
if (S.strokeCanvas) S.strokeCanvas.style.display = "none";
document.body.style.cursor = "";
document.body.style.userSelect = "";
try {
renderObjects();
} catch (e) {
}
}
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);
window.addEventListener("blur", resetPointerState);
document.addEventListener("pointercancel", resetPointerState);
document.addEventListener("visibilitychange", () => {
if (document.hidden) resetPointerState();
});
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)
// build-rev: 2026-11-17T17 (pointer-self-heal)