Skip to content

Commit

Permalink
Fix undo/redo keyboard shortcut (#361)
Browse files Browse the repository at this point in the history
  • Loading branch information
slimbuck authored Jan 2, 2025
1 parent 9b3284a commit d1cab3e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
Expand Down
22 changes: 18 additions & 4 deletions src/shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit d1cab3e

Please sign in to comment.