From 38ed922b3813cc83fac93c7421e2e9449e62428d Mon Sep 17 00:00:00 2001 From: Donovan Hutchence Date: Mon, 30 Dec 2024 14:10:34 +0000 Subject: [PATCH] fixes --- src/main.ts | 4 ++-- src/shortcuts.ts | 22 ++++++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/main.ts b/src/main.ts index cb87fcba..4cc4cf90 100644 --- a/src/main.ts +++ b/src/main.ts @@ -83,8 +83,8 @@ const initShortcuts = (events: Events) => { shortcuts.register(['U', 'u'], { event: 'select.unhide' }); shortcuts.register(['['], { event: 'tool.brushSelection.smaller' }); shortcuts.register([']'], { event: 'tool.brushSelection.bigger' }); - shortcuts.register(['Z', 'z'], { event: 'edit.undo', ctrl: true }); - shortcuts.register(['Z', 'z'], { event: 'edit.redo', ctrl: true, shift: true }); + shortcuts.register(['Z', 'z'], { event: 'edit.undo', ctrl: true, capture: true }); + shortcuts.register(['Z', 'z'], { event: 'edit.redo', ctrl: true, shift: true, capture: true }); shortcuts.register(['M', 'm'], { event: 'camera.toggleMode' }); shortcuts.register(['D', 'd'], { event: 'dataPanel.toggle' }); shortcuts.register([' '], { event: 'camera.toggleOverlay' }); diff --git a/src/shortcuts.ts b/src/shortcuts.ts index decfbab0..92bc8899 100644 --- a/src/shortcuts.ts +++ b/src/shortcuts.ts @@ -4,6 +4,7 @@ interface ShortcutOptions { ctrl?: boolean; shift?: boolean; sticky?: boolean; + capture?: boolean; // use capture phase - i.e. handle the events before anyone else func?: () => void; event?: string; } @@ -14,18 +15,22 @@ class Shortcuts { constructor(events: Events) { const shortcuts = this.shortcuts; - const handleEvent = (e: KeyboardEvent, down: boolean) => { + const handleEvent = (e: KeyboardEvent, down: boolean, capture: boolean) => { // skip keys in input fields - if (e.target !== document.body) return; + if (!capture && e.target !== document.body) return; for (let i = 0; i < shortcuts.length; i++) { const shortcut = shortcuts[i]; const options = shortcut.options; if (shortcut.keys.includes(e.key) && + ((options.capture ?? false) === capture) && !!options.ctrl === !!(e.ctrlKey || e.metaKey) && !!options.shift === !!e.shiftKey) { + e.stopPropagation(); + e.preventDefault(); + // handle sticky shortcuts if (options.sticky) { if (down) { @@ -53,12 +58,21 @@ class Shortcuts { // register keyboard handler document.addEventListener('keydown', (e) => { - handleEvent(e, true); + handleEvent(e, true, false); }); document.addEventListener('keyup', (e) => { - handleEvent(e, false); + handleEvent(e, false, false); }); + + // also handle capture phase + document.addEventListener('keydown', (e) => { + handleEvent(e, true, true); + }, true); + + document.addEventListener('keyup', (e) => { + handleEvent(e, false, true); + }, true); } register(keys: string[], options: ShortcutOptions) {