/* commands.js - 统一命令层(P0 地基) * * 浮动操作条 / 右键菜单 / 快捷键是三个「视图」,都必须走同一条 execute(): * execute(label, mutator) → 前置守卫 → 快照(label) → mutator 只改状态 → 统一重绘 → 记历史 * 这样所有新操作自动获得 Ctrl+Z / Ctrl+Shift+Z,也不会出现三套逻辑各修一遍。 * * 旧标注工具仍直接调用 history.saveSnapshot()(行为不变、仍可撤销), * 新功能(选区、还原原图、输出)一律走本模块;后续可渐进迁移旧入口。 * * 循环依赖规避:本文件顶层不 import 任何渲染模块。渲染出口由 index.js * 在 open() 时注入 S.renderAll,命令注册表由各功能模块在顶层 defineCommand()。 */ 'use strict' import { S, runtime } from './state.js' import { saveSnapshot } from './history.js' /** 命令注册表:name → { label, enabled?, run } */ export const COMMANDS = Object.create(null) export function defineCommand(name, def) { COMMANDS[name] = Object.assign({ label: name }, def || {}) } /** 统一变更入口。mutator 抛错时回滚刚压入的快照,避免留下「空撤销步」。 */ export 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 } /** 三入口共用的命令调用;enabled() 返回 false 时给 toast 而不是静默失败。 */ export function runCommand(name) { const def = COMMANDS[name] if (!def) return false // 选区与裁剪互斥:只在 setTool('crop') 清一次选区不够 —— 快捷键 / 更多菜单 / // 右键菜单都还能再建选区。三条入口都经过这里,统一在工作层拦掉 sel.*。 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 } } /** 轻量 toast:取代 window.alert / window.confirm,不打断画布操作 */ let toastTimer = null export 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) }