Files
image-workbench-desktop/src/canvas-history-store.js
T

147 lines
7.3 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.
/* 撤销/重做历史仓库(状态模型 epic · Pilot 1)
*
* 从 app.js Workbench() 收编"撤销栈机器":栈状态 {stack, idx}、入栈裁剪、跨 session 字节预算淘汰、
* 空闲清扫器(把快照里的大图引用化)、undo/redo 的游标移动。
*
* 与画布/组件状态的边界(§11.3):**取快照**与**写回画布**必须碰组件状态,故作为**注入的适配器**留在 app.js:
* - snapshot() → 变更前同步捕获快照(含大图引用化)
* - restore(snap) → 把快照写回画布(+ 异步 hydrate 图片)
* - unhydrate(snap) → 清扫器用(把快照里的大图引用化)
* - otherStacks() → 其余 session 的历史栈(跨 session 预算淘汰用)
* - bytesOf(snap) → 快照字节数(淘汰预算用)
* - onSwept(n) → 清扫计数回调(e2e 探针)
* 本模块纯逻辑、无 React / 无 DOM 直接依赖;宿主只经 window.IWBHistoryStore 使用。
*/
;(function (global) {
'use strict'
const HISTORY_MAX = 20
const HISTORY_BYTES_BUDGET = 60 * 1048576
const HISTORY_MIN_KEEP = 3
const createHistoryStore = (options) => {
const opt = options || {}
const snapshotFn = opt.snapshot
const restoreFn = opt.restore
const unhydrateFn = opt.unhydrate
const otherStacksFn = opt.otherStacks
const bytesOfFn = opt.bytesOf
const hasBigImageFn = opt.hasBigImage
const onSweptFn = opt.onSwept
const now = typeof opt.now === 'function' ? opt.now : (() => Date.now())
const setT = typeof global.setTimeout === 'function' ? global.setTimeout : (typeof setTimeout === 'function' ? setTimeout : (() => 0))
const clearT = typeof global.clearTimeout === 'function' ? global.clearTimeout : (typeof clearTimeout === 'function' ? clearTimeout : (() => {}))
let active = { stack: [], idx: -1 } // 当前激活栈(由 setActive 随 session 切换注入)
// 清扫器取栈的来源:优先注入的 getStack()(方案2:栈仍留 app.js);否则用 setActive 注入的激活栈。
const getStackFn = typeof opt.getStack === 'function' ? opt.getStack : (() => (active && active.stack) || [])
let histWindow = null
let histTimer = null
let sweeping = false
let swept = 0
let typingUntil = 0
const tried = new WeakSet() // 试过就不再试(失败也不重试,避免无限 churn)
const listeners = new Set()
const emit = () => { for (const l of Array.from(listeners)) { try { l() } catch (e) { /* 订阅者异常隔离 */ } } }
const subscribe = (l) => { if (typeof l !== 'function') return () => {}; listeners.add(l); return () => listeners.delete(l) }
const setActive = (rec) => { active = rec && typeof rec === 'object' ? rec : { stack: [], idx: -1 }; if (!Array.isArray(active.stack)) active.stack = [] }
const getActive = () => active
const canUndo = () => !!active && active.idx > 0
const canRedo = () => !!active && active.idx < active.stack.length - 1
const snapshotVersion = () => (active.idx + 1) * 100000 + active.stack.length // 供订阅者判"是否需要重渲染"
const noteTyping = () => { typingUntil = now() + 1600 }
const clearTyping = () => { typingUntil = 0 }
const isTyping = () => now() < typingUntil
const sweepState = () => ({ sweeping, swept })
// 跨 session 全局字节预算淘汰(激活栈优先、再按 LRU 顺序淘汰最旧 session 的栈)
const evictGlobal = () => {
const order = []
if (active && active.stack) order.push(active)
const others = typeof otherStacksFn === 'function' ? otherStacksFn() : []
for (const h of (Array.isArray(others) ? others : [])) if (h && Array.isArray(h.stack) && h.stack !== active.stack) order.push(h)
const collect = (stack) => { let t = 0; for (const x of stack) { try { t += bytesOfFn ? bytesOfFn(x) : 0 } catch (e) { /* ignore */ } } return t }
let total = 0
for (const h of order) total += collect(h.stack)
if (total <= HISTORY_BYTES_BUDGET) return
for (const h of order) {
while (h.stack.length > HISTORY_MIN_KEEP && total > HISTORY_BYTES_BUDGET) {
const dropped = h.stack.shift()
if (!dropped) break
try { total -= bytesOfFn ? bytesOfFn(dropped) : 0 } catch (e) { /* ignore */ }
if (h.idx > 0) h.idx--
}
if (total <= HISTORY_BYTES_BUDGET) break
}
}
// 空闲清扫器:单 worker,扫描栈里"还带着大图"的快照逐个引用化(打字期跳过、每轮上限 8、8s 预算、120ms 步进)
const schedule = () => {
if (now() < typingUntil) return
if (sweeping) return
if (typeof unhydrateFn !== 'function') return
sweeping = true
const started = now()
const step = async () => {
let done = 0
try {
const stack = getStackFn()
const snap = stack.find((x) => x && !tried.has(x) && (typeof hasBigImageFn === 'function' ? hasBigImageFn(x) : false))
if (!snap || done >= 8 || now() - started > 8000) { sweeping = false; return }
tried.add(snap)
await unhydrateFn(snap)
swept += 1
if (typeof onSweptFn === 'function') { try { onSweptFn(swept) } catch (e) { /* ignore */ } }
done += 1
} catch (e) { /* 引用化失败:退化为原快照(多占内存但不丢撤销) */ }
setT(step, 120)
}
setT(step, 0)
}
const pushStack = (snap, baseline) => {
const h = active
if (!h || !snap) return
h.stack = h.stack.slice(0, h.idx + 1)
if (h.idx < 0 && baseline) h.stack.push(baseline)
h.stack.push(snap)
while (h.stack.length > HISTORY_MAX) h.stack.shift()
h.idx = h.stack.length - 1
try { evictGlobal() } catch (e) { /* 预算失败不影响历史 */ }
schedule()
emit()
}
const push = () => {
const h = active
if (!h || typeof snapshotFn !== 'function') return
const snap = snapshotFn()
const baseline = (h.idx < 0) ? snapshotFn() : null
pushStack(snap, baseline)
}
const pushDebounced = () => {
if (!histWindow) {
const h0 = active
histWindow = { snap: typeof snapshotFn === 'function' ? snapshotFn() : null, baseline: (h0 && h0.idx < 0 && typeof snapshotFn === 'function') ? snapshotFn() : null }
}
if (histTimer) { try { clearT(histTimer) } catch (e) { /* ignore */ } }
histTimer = setT(() => { const w = histWindow; histWindow = null; if (w) pushStack(w.snap, w.baseline) }, 800)
}
const discardPending = () => { if (histTimer) { clearT(histTimer); histTimer = null } histWindow = null }
const undo = () => { if (!canUndo()) return false; active.idx -= 1; if (typeof restoreFn === 'function') restoreFn(active.stack[active.idx]); emit(); return true }
const redo = () => { if (!canRedo()) return false; active.idx += 1; if (typeof restoreFn === 'function') restoreFn(active.stack[active.idx]); emit(); return true }
return {
setActive, getActive, push, pushDebounced, undo, redo, canUndo, canRedo,
evictGlobal, schedule, noteTyping, clearTyping, isTyping, sweepState, discardPending, subscribe, snapshotVersion,
HISTORY_MAX, HISTORY_BYTES_BUDGET, HISTORY_MIN_KEEP,
}
}
global.IWBHistoryStore = Object.freeze({ create: createHistoryStore, HISTORY_MAX, HISTORY_BYTES_BUDGET, HISTORY_MIN_KEEP })
})(typeof window !== 'undefined' ? window : globalThis)