Files
iwb-plugins-desktop/image-annotate/plugin/editor/layers.js
T
qiqi 9d923aed26 feat(image-annotate): v1.2.9 图层 PS 快捷键 + 顶栏会话组左移
- 图层快捷键(PS 同款,e.code 匹配防中文输入法吞键):
  Ctrl+]/[ 上/下移一层、Ctrl+Shift+]/[ 置顶/置底、Alt+]/[ 向上/向下选层
- Delete 删除选中的位图图层(原图锁定除外)
- moveLayer 无选中时 toast 提示,不再无声失败
- 顶栏「新建/覆盖/退出」移到最左会话组;右侧只留 输出+导出,下载改文案「导出」
- [ / ] 笔刷大小同时匹配 e.code,中文输入法下不再失灵
- __debug().shapes 补 z 字段;harness 新增 6 项断言(113 项全绿)
2026-11-04 22:48:12 +08:00

719 lines
32 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* layers.js - 位图图层管理、矢量对象画布与图层面板
* 节:图层管理、矢量对象独立画布(位图/矢量统一排序)、图层面板 UI,
* 外加原属「图片放置」节末尾的 deleteLayer。
* 约定:位图图层一个 canvas,矢量对象(文字/形状)各自独立 canvas,
* reorderLayerCanvas 按 z 统一排序插入 S.canvasStack。
*/
'use strict'
import { S, runtime } from './state.js'
import { TEXT_FONT, allObjects, assignLayerZ, deleteSelectedShape, deleteSelectedText, layerUnits, layerUnitsDesc, renderObjects, selectUnit, sortLayersByZ, textBounds } from './objects.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { drawShape } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { placeImageDirectly } from './placement.js'
import { updateBrushParamUI, updateColorUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 图层管理 ============
/** 创建位图图层 canvas 元素并插入 DOM 栈 */
export 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'
// 插入到 strokeCanvas 之前(位图图层在矢量层之下)
S.canvasStack.insertBefore(c, S.strokeCanvas)
return c
}
/** 按图层 z 序重排 DOM 中的 canvas 元素。
* 所有 canvas 必须共享 canvas-stack 的坐标系;隐藏图层只用 CSS 隐藏,
* 不从 DOM 移除,避免 canvas-stack 在 flex/inline 布局下重新计算位置。 */
export function reorderLayerCanvas() {
// 与合成/导出/面板/命中测试共用同一份 z 序,杜绝「面板顺序 ≠ 实际叠放」
for (const u of layerUnits()) {
const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas
// 快照恢复后的矢量对象可能带着被 JSON 序列化过的伪画布({}),必须挡住
if (!el || el.nodeType !== 1) continue
S.canvasStack.insertBefore(el, S.strokeCanvas)
el.style.display = u.obj.visible === false ? 'none' : 'block'
}
}
/** 获取活跃位图图层 */
export function getActiveLayer() {
return S.layers.find(l => l.id === S.activeLayerId) || null
}
/** 获取活跃位图图层的 2d context(画笔/橡皮操作目标) */
export function getActiveCtx() {
const layer = getActiveLayer()
return layer && !layer.locked ? layer.ctx : null
}
/** 清理所有画布/图层选择态,保证不同工具和图层之间互斥 */
export function clearSelection({ keepBitmap = false } = {}) {
if (!keepBitmap) S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = null
S.textDrag = null
S.shapeDrag = null
S.bitmapDrag = null
}
/** 确定源图/源画布的取样框:内容盒 _srcBox 优先,其次整图 image,再其次整张 sourceCanvas;无可用源返回 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()
}
/** 按图层当前的源(原图 / 源画布 / 内容盒)与旋转角重绘该图层 */
export function redrawBitmapLayer(layer) {
if (!layer || !layer.ctx) return
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
paintTransformed(layer, resolveSourceBox(layer))
}
export 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 / S.zoom
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
}
// isDrawableLayer / restorePath / needsPixelSnapshot 统一由 shared/layer-logic.js 提供
// (快照端与恢复端必须共用同一判定,可单测守护)
/** 内容包围盒(非透明像素范围),带缓存;step=2 降低扫描开销 */
function layerBounds(layer) {
if (!layer || !layer.ctx || !layer.canvas) return null
if (layer._bounds !== undefined) 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 }
}
/** 单个位图图层是否命中该点:绘制类按像素(透明处不算),图片类按矩形 */
export 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 }
}
/** 兼容入口:按统一 z 降序找最上面的位图图层 */
export function hitBitmapLayer(pos) {
for (const u of layerUnitsDesc()) {
if (u.kind !== 'bitmap') continue
if (hitBitmapAt(u.obj, pos)) return u.obj
}
return null
}
export function drawBitmapSelection(layer) {
if (!layer) return
// 变换框/手柄只在「选择」工具下出现(用户裁定 2026-11-04):
// 画笔/橡皮等绘制工具下不显示调节杆,避免误抓手柄也减少视觉噪音。
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 = 7 / S.zoom
ctx.save()
ctx.strokeStyle = '#e8a735'
ctx.lineWidth = 1.5 / S.zoom
ctx.setLineDash([6 / S.zoom, 3 / S.zoom])
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.setLineDash([])
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)
}
/** 任意矩形的 8 个控制点(含旋转)*/
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
}
export 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()
}
}
export 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') {
layer.x = base.x + pos.x - drag.start.x
layer.y = base.y + pos.y - drag.start.y
if (isDrawableLayer(layer)) layer._bounds = undefined
} 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 = undefined
redrawBitmapLayer(layer)
}
/** 切换画笔/橡皮作用的活动图层 */
export function setActiveLayer(id) {
S.activeLayerId = id
selectUnit('bitmap', id)
renderLayerPanel()
renderObjects()
}
/** 添加位图图层(导入图片)— 便利版:一步落层,不再需要 Enter 二次确认
* 需要调大小/位置时切换到「选择」工具拖动 8 个手柄;Ctrl+Z 可撤销这一步。 */
export function addBitmapLayer(img) {
placeImageDirectly(img)
}
/** 确保有可绘制的活动图层:没有(或被锁定)就自动落一个「标注 N」空层并激活。
* 默认不再预建画笔层(用户裁定:需要时自己加),所以画笔起笔前必须兜底建层。
* 注意:本函数不进历史 —— 调用方(onBrushMouseDown)随后 saveSnapshot(),
* 这样首笔 Ctrl+Z 会连「自动建的层 + 笔迹」一起撤掉,不留空层。 */
export 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() * 1000) : '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()
// 新 canvas 必须立刻套上当前视图的显示尺寸/偏移,否则它会以原始像素尺寸
// 贴在 stack 原点 —— 表现就是「第一笔画在错误的位置,滚轮缩放后才正常」
// (addBlankLayer 一直有这步,这里漏了。2026-11-04 用户反馈)
updateLayerCanvasStyles()
setActiveLayer(id)
renderLayerPanel()
return layer
}
/** 新建空白图层 */
export function addBlankLayer() { // 创建可独立编辑的位图图层
const id = 'L' + Date.now() + Math.floor(Math.random() * 1000)
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()
}
/** 删除图层(图层面板按钮与 Delete 快捷键共用) */
export 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)
// 旧实现把位图 z 重设为 0..n-1,会与矢量对象的 z 再次撞车;统一重新分配
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
}
export 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
}
}
export function purgeVectorCanvases() {
for (const t of S.textLayers) removeVecCanvas(t)
for (const sh of S.shapeLayers) removeVecCanvas(sh)
}
export 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 {
ctx.save()
ctx.textBaseline = 'top'
ctx.globalAlpha = obj.opacity != null ? obj.opacity : 1
const rot = obj.rotation || 0
if (rot) {
const b = textBounds(obj)
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.font = TEXT_FONT(obj.fontSize)
ctx.fillStyle = obj.color
ctx.fillText(obj.text, obj.x, obj.y)
ctx.restore()
}
}
/** 切换图层可见性 */
function toggleLayerVisibility(id) {
const layer = S.layers.find(l => l.id === id)
if (!layer) return
layer.visible = !layer.visible
reorderLayerCanvas()
renderLayerPanel()
S.pickerComposite = null
}
/** 更新位图图层尺寸;位置始终由 canvas-stack 统一管理。 */
export 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'
}
styleVectorViewport(w, h, offset)
}
export 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'
}
}
// ============ 图层面板 UI ============
export function renderLayerPanel() {
const list = runtime.el.querySelector('.iwb-editor-layer-list')
if (!list) return
// 面板顺序直接取统一 z 序的倒序(与画布叠放完全一致)。
// 旧实现位图用 S.layers 数组序、矢量用 allObjects() 再 sort,z 相同时两者次序相反。
const items = []
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,
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),
paintTarget: false, locked: !!obj.locked, canDelete: true
})
}
}
let html = ''
for (const item of items) {
const activeClass = item.active ? ' active' : ''
const visClass = item.visible ? '' : ' hidden'
// SVG 图标
let typeIconSvg = ''
if (item.type === 'bitmap') {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>'
} else if (item.type === 'text') {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 3 20 3 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="3" x2="12" y2="20"/></svg>'
} else if (item.type === 'rect') {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>'
} else {
typeIconSvg = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>'
}
const visSvg = item.visible
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>'
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61"/><line x1="2" y1="2" x2="22" y2="22"/></svg>'
const lockSvg = item.locked
? '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>'
: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 7-2"/></svg>'
const delSvg = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
html += `<div class="iwb-layer-item${activeClass}${visClass}" draggable="${item.id !== 'base'}" data-layer-id="${item.id}" data-layer-type="${item.type}">
<button class="iwb-layer-vis" data-vis-id="${item.id}" data-vis-type="${item.type}" title="${item.visible ? '隐藏' : '显示'}">${visSvg}</button>
<span class="iwb-layer-icon">${typeIconSvg}</span>
<span class="iwb-layer-name">${item.name}</span>${item.paintTarget ? '<span class="iwb-layer-paint" title="当前画笔 / 橡皮作用图层">✎</span>' : ''}
${(item.type === 'bitmap' || item.type === 'shape') ? `<input class="iwb-layer-color" type="color" value="${item.color}" data-color-id="${item.id}" data-color-type="${item.type}" title="调整颜色">` : ''}
${(item.type === 'bitmap' || item.type === 'shape') ? `<input class="iwb-layer-width" type="number" min="1" max="300" value="${Math.round(item.lineWidth)}" data-width-id="${item.id}" data-width-type="${item.type}" title="调整边框粗细">` : ''}
<button class="iwb-layer-lock${item.locked ? ' active' : ''}" data-lock-id="${item.id}" data-lock-type="${item.type}" title="${item.locked ? '解锁图层' : '锁定图层'}">${lockSvg}</button>
${item.canDelete ? `<button class="iwb-layer-del" data-del-id="${item.id}" data-del-type="${item.type}" title="删除图层">${delSvg}</button>` : ''}
</div>`
}
list.innerHTML = html
// 绑定图层面板事件
bindLayerPanelEvents()
}
function reorderPanelItem(dragId, targetId) {
if (!dragId || !targetId || dragId === targetId || dragId === 'base' || targetId === 'base') return
const all = layerUnits()
const baseIdx = all.findIndex(u => u.obj.id === 'base')
if (baseIdx > 0) { const [b] = all.splice(baseIdx, 1); all.unshift(b) }
const from = all.findIndex(item => item.obj.id === dragId)
const to0 = all.findIndex(item => item.obj.id === targetId)
if (from < 0 || to0 < 0) return
const before = all.map(u => u.obj.id).join('|')
const [moved] = all.splice(from, 1)
const to = Math.max(all.findIndex(item => item.obj.id === targetId), baseIdx >= 0 ? 1 : 0)
all.splice(to, 0, moved)
if (all.map(u => u.obj.id).join('|') === before) return
saveSnapshot()
assignLayerZ(all)
reorderLayerCanvas()
sortLayersByZ()
renderObjects()
renderLayerPanel()
}
function bindLayerPanelEvents() {
const list = runtime.el.querySelector('.iwb-editor-layer-list')
if (!list) return
bindLayerItemEvents(list)
bindLayerStyleInputs(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('dragstart', (e) => { if (item.draggable) { e.dataTransfer.setData('text/plain', item.dataset.layerId); item.classList.add('dragging') } })
item.addEventListener('dragend', () => item.classList.remove('dragging'))
item.addEventListener('dragover', (e) => { if (item.draggable) e.preventDefault() })
item.addEventListener('drop', (e) => { e.preventDefault(); reorderPanelItem(e.dataTransfer.getData('text/plain'), item.dataset.layerId) })
item.addEventListener('click', (e) => {
if (e.target.closest('.iwb-layer-vis') || e.target.closest('.iwb-layer-lock') || e.target.closest('.iwb-layer-del')) return
const id = item.dataset.layerId
const type = item.dataset.layerType
if (type === 'bitmap') {
setActiveLayer(id)
} else if (type === 'text' || type === 'shape') {
selectUnit(type, id)
renderObjects()
renderLayerPanel()
}
})
})
}
/** 图层颜色与边框粗细输入:修改后立即刷新画布和面板 */
function bindLayerStyleInputs(list) {
// 图层颜色与边框粗细:修改后立即刷新画布和面板。
list.querySelectorAll('.iwb-layer-color').forEach(input => {
input.addEventListener('mousedown', (e) => e.stopPropagation())
input.addEventListener('input', (e) => {
e.stopPropagation()
const id = input.dataset.colorId
const type = input.dataset.colorType
const obj = type === 'bitmap' ? S.layers.find(l => l.id === id) : S.shapeLayers.find(s => s.id === id)
if (obj) { obj.color = input.value; S.color = input.value; updateColorUI(); renderObjects(); renderLayerPanel(); S.pickerComposite = null }
})
})
list.querySelectorAll('.iwb-layer-width').forEach(input => {
input.addEventListener('mousedown', (e) => e.stopPropagation())
input.addEventListener('input', (e) => {
e.stopPropagation()
const id = input.dataset.widthId
const type = input.dataset.widthType
const value = clamp(parseInt(input.value, 10) || 1, 1, 300)
const obj = type === 'bitmap' ? S.layers.find(l => l.id === id) : S.shapeLayers.find(s => s.id === id)
if (obj) { obj.lineWidth = value; if (type === 'shape') obj.lw = value; else S.brushSize = value; renderObjects(); updateBrushParamUI(); renderLayerPanel() }
})
})
}
/** 显隐切换按钮:位图直接切 visible,文字/形状切对象 visible 并重绘 */
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 }
}
})
})
}
/** 锁定/解锁按钮:切换对象 locked 并存快照 */
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()
}
})
})
}