feat: 全局撤销/重做(ADR-010)

This commit is contained in:
chenshoulin
2026-10-24 21:21:36 +08:00
parent 29100b6d7d
commit 648b1ddca4
8 changed files with 533 additions and 17 deletions
+62 -1
View File
@@ -1,6 +1,12 @@
import { describe, expect, it, vi } from 'vitest'
import { isEditableTarget, matchShortcut, type ShortcutEventLike } from './useKeyboardShortcuts'
import {
isEditableTarget,
matchShortcut,
matchUndoShortcut,
type ShortcutEventLike,
type UndoEventLike,
} from './useKeyboardShortcuts'
function makeEvent(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLike {
return {
@@ -14,6 +20,19 @@ function makeEvent(overrides: Partial<ShortcutEventLike> = {}): ShortcutEventLik
}
}
function makeUndoEvent(overrides: Partial<UndoEventLike> = {}): UndoEventLike {
return {
key: 'z',
target: document.body,
defaultPrevented: false,
ctrlKey: true,
metaKey: false,
altKey: false,
shiftKey: false,
...overrides,
}
}
function makeElement(tag: string, contentEditable = false): HTMLElement {
const element = document.createElement(tag)
// 用 setAttribute 而非 property:jsdom 不会把 contentEditable 属性反射到 attribute
@@ -83,3 +102,45 @@ describe('matchShortcut', () => {
expect(matchShortcut(makeEvent({ key: 'z' }), { n: vi.fn() })).toBeNull()
})
})
describe('matchUndoShortcut', () => {
it('Ctrl+Z 与 Cmd+Z 都是撤销', () => {
expect(matchUndoShortcut(makeUndoEvent())).toBe('undo')
expect(matchUndoShortcut(makeUndoEvent({ ctrlKey: false, metaKey: true }))).toBe('undo')
})
it('Shift+Z 是重做', () => {
expect(matchUndoShortcut(makeUndoEvent({ shiftKey: true }))).toBe('redo')
expect(
matchUndoShortcut(makeUndoEvent({ ctrlKey: false, metaKey: true, shiftKey: true })),
).toBe('redo')
})
it('Ctrl+Y 也认作重做,但 Cmd+Y 不认', () => {
expect(matchUndoShortcut(makeUndoEvent({ key: 'y' }))).toBe('redo')
expect(matchUndoShortcut(makeUndoEvent({ key: 'y', ctrlKey: false, metaKey: true }))).toBeNull()
})
it('没有修饰键时不是撤销快捷键', () => {
expect(matchUndoShortcut(makeUndoEvent({ ctrlKey: false }))).toBeNull()
})
it('其它键不触发', () => {
expect(matchUndoShortcut(makeUndoEvent({ key: 'a' }))).toBeNull()
expect(matchUndoShortcut(makeUndoEvent({ key: 'f' }))).toBeNull()
})
it('带 Alt 的组合不劫持', () => {
expect(matchUndoShortcut(makeUndoEvent({ altKey: true }))).toBeNull()
})
it('输入框内交还浏览器,撤销的是文字输入', () => {
expect(matchUndoShortcut(makeUndoEvent({ target: makeElement('input') }))).toBeNull()
expect(matchUndoShortcut(makeUndoEvent({ target: makeElement('textarea') }))).toBeNull()
expect(matchUndoShortcut(makeUndoEvent({ target: makeElement('div', true) }))).toBeNull()
})
it('已被处理的事件不重复触发', () => {
expect(matchUndoShortcut(makeUndoEvent({ defaultPrevented: true }))).toBeNull()
})
})