/* history.js - 历史快照与撤销/重做 * * v1.1:快照升级为「完整图层集合」——除了像素,还记录图层的类型、名称、z、 * image/sourceCanvas 引用等元数据。恢复时能删掉后来新增的层、重建被删掉的层, * 于是「复制/剪切到新层」「还原原图」这类会改变图层数量的操作也能 Ctrl+Z。 * 快照只存在于会话内存里(ImageData / Image 引用都可以直接持有,不需要序列化)。 * * 约定:快照端 needsPixelSnapshot() 与恢复端 restorePath() 共用 vendor/layer-logic.js, * 两边判定必须一致,否则会出现「没拍却要读」的像素丢失。 */ 'use strict' import { S } from './state.js' import { clearOverlay, updateCropInfo } from './crop.js' import { hideTextInput, renderObjects } from './objects.js' import { createLayerCanvas, purgeVectorCanvases, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles } from './layers.js' import { resizeWorkspace, setupCanvas } from './viewport.js' import { updateAllUI } from './events.js' import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js' import { toast } from './commands.js' // ============ 历史快照(所有位图图层 + 矢量对象) ============ export const snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 } /** * 矢量对象上挂着运行时 DOM 画布(_canvas / _ctx)。JSON 深拷贝会把 canvas * 序列化成 {},撤销恢复后 reorderLayerCanvas() 就会拿 {} 去 insertBefore → * "parameter 1 is not of type 'Node'"。快照必须把这些运行时字段剔干净。 */ function cloneVectors(arr) { return JSON.parse(JSON.stringify(arr || [], (key, value) => { if (key === '_canvas' || key === '_ctx') return undefined return value })) } /** * 捕获当前状态 * @param {{metaOnly?: boolean}} [opts] * metaOnly=true:只取几何/矢量/图层元数据,用于拖拽结束时「有没有变化」的比对。 */ export 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) { /* ignore */ } 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 })) } } export const HISTORY_MAX_ENTRIES = 50 export const HISTORY_MAX_BYTES = 128 * 1024 * 1024 const HISTORY_MIN_BYTES = 32 * 1024 * 1024 export 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 } export 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 } /** 操作前调用:压入历史,清空重做栈 */ export 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) { // v1.2:裁剪也进历史链,所以快照的画布尺寸可能与当前不同,必须先把尺寸复位。 // 尺寸一变,现有图层对象的像素缓冲已被 resizeWorkspace 清空、几何元数据也失效, // 直接「复用现有图层再 putImageData」会让走过 redraw 路径的图片层彻底丢内容; // 因此全部释放、让下面的「按快照重建」分支统一重建(它会按 bm 的 imageRef/sourceRef // 选择 redraw 还是 pixels)。 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 = undefined 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) { /* ignore */ } } 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 = undefined } 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) { /* ignore */ } } } 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 // 撤销不动选区:选区是「视图状态」,不是像素状态,避免 Ctrl+Z 后框消失还要重画 reorderLayerCanvas() updateLayerCanvasStyles() renderObjects() renderLayerPanel() updateCropInfo() } export 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.renderAll) S.renderAll() } export 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.renderAll) S.renderAll() } /** * 还原原图(用户 2026-11-04 裁定):清空标注 = 全部还原到刚打开时的状态 —— * 删掉所有非原图图层、清掉所有绘制/矢量、复位变换与选区,只留「原图」。 * 整步记一个快照,Ctrl+Z 可完整恢复(包括被删的粘贴层与图形)。 * 旧版 resetDraw() 只清像素、留下空白层且清空撤销栈,已废弃。 */ export 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 // 裁剪会改变画布尺寸且(P2 之前)会清空历史,此路径无法用像素快照回退; // 明确 toast 告知,不做「假的可撤销」。 if (sizeChanged) { S.imgW = ow S.imgH = oh S.zoom = 1 setupCanvas(img) S.history = [] S.redoStack = [] clearAllEditState() updateAllUI() // 尺寸变了就必须走统一重绘出口:输出摘要/状态栏读 S.imgW/imgH, // clearAllEditState 只清选区不停止蚂蚁线 rAF(唯一停止点是 renderAll/clearMarquee) 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] : [] // 默认无画笔层(用户裁定),活动层回到原图;再画时 ensureWritableLayer 兜底建层 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.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() } /** 兼容旧入口:清空标注按钮 / 更多菜单都指向 restoreAll */ export function resetDraw() { restoreAll() } export function restoreOriginal() { restoreAll() }