Skip to content

撤销与重做

vkedit 的所有元素操作都通过命令对象执行,每个命令自动进入撤销栈。

基本用法

typescript
// 撤销
host.undo()

// 重做
host.redo()

检查撤销/重做状态

EditorHost 没有内置 canUndo() / canRedo() 方法。可通过监听 command:executedcommand:undonecommand:redone 事件感知命令栈变化:

typescript
host.on('command:executed', (data) => {
  console.log('执行了:', data.command.constructor.name)
})
host.on('command:undone', (data) => {
  console.log('撤销了:', data.command.constructor.name)
})

内置命令列表

所有命令的构造函数第一个参数都是 host: EditorHost

命令构造函数签名说明
AddElementCommand(host, element)添加元素
RemoveElementCommand(host, element)删除元素
TransformElementCommand(host, element, oldState, newState)变换元素(位置/尺寸/旋转)
UpdatePropertyCommand(host, element, propertyPath, oldValue, newValue)更新元素属性
BatchCommand(host, commands?, description?)批量命令
AlignElementsCommand(host, alignment, elementIds)对齐元素
DistributeElementsCommand(host, direction, elementIds)分布元素
ChangeLayerOrderCommand(host, elementId, direction)改变图层顺序
ClearSelectionCommand(host)清除选择

执行命令

typescript
import { AddElementCommand, UpdatePropertyCommand } from 'vkedit'

// 添加元素(element 须为 IGraphicElement 实例,通常通过 ElementManagerPlugin.createElement 创建)
const elementManager = host.getPlugin('element-manager-plugin')
const element = elementManager.createElement('rect')
element.xmm = 10
element.ymm = 10
element.wmm = 50
element.hmm = 30

host.executeCommand(new AddElementCommand(host, element))

// 更新元素属性
host.executeCommand(new UpdatePropertyCommand(host, element, 'fill', '', '#6366f1'))

元素创建模式

命令操作的是 IGraphicElement 实例对象,而非普通数据对象。通过 ElementManagerPlugin.createElement(type) 创建元素实例。详见 元素创建

批量命令

typescript
import { BatchCommand, AddElementCommand } from 'vkedit'

// 方式一:构造时传入命令数组
const commands = [
  new AddElementCommand(host, rectElement1),
  new AddElementCommand(host, rectElement2),
  new AddElementCommand(host, rectElement3),
]
host.executeCommand(new BatchCommand(host, commands, '批量添加元素'))

// 方式二:逐步添加
const batch = new BatchCommand(host)
batch.addCommand(new AddElementCommand(host, rectElement1))
batch.addCommand(new AddElementCommand(host, rectElement2))
host.executeCommand(batch)

批量命令的撤销

BatchCommand 撤销时会按添加顺序的逆序回滚每个子命令。确保子命令之间无依赖冲突。

监听命令事件

typescript
import type { CommandEventData } from 'vkedit'

host.on('command:executed', (data: CommandEventData) => {
  console.log('执行了:', data.command.constructor.name)
})

host.on('command:undone', (data: CommandEventData) => {
  console.log('撤销了:', data.command.constructor.name)
})

下一步

基于 MIT 许可发布