From 79feb7df6d9772808c6629ea9e17daf9ecd97721 Mon Sep 17 00:00:00 2001 From: tglide <26071571+TGlide@users.noreply.github.com> Date: Tue, 11 Jul 2023 18:54:58 +0100 Subject: [PATCH] refactor: improve command ranking algorithm --- src/lib/commandCenter/commands.ts | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/lib/commandCenter/commands.ts b/src/lib/commandCenter/commands.ts index 2e50916b2..bb2f5cde4 100644 --- a/src/lib/commandCenter/commands.ts +++ b/src/lib/commandCenter/commands.ts @@ -71,6 +71,20 @@ function isInputEvent(event: KeyboardEvent) { return ['INPUT', 'TEXTAREA', 'SELECT'].includes((event.target as HTMLElement).tagName); } +function hasDisputing(command: KeyedCommand, allCommands: Command[]) { + return allCommands.some((otherCommand) => { + if (command === otherCommand) { + return false; + } + if (!isKeyedCommand(otherCommand)) { + return false; + } + const keysString = command.keys.join('+'); + const otherKeysString = otherCommand.keys.join('+'); + return keysString.includes(otherKeysString) || otherKeysString.includes(keysString); + }); +} + export const commandCenterKeyDownHandler = derived( [commandMap, commandsEnabled], ([$commandMap, enabled]) => { @@ -121,15 +135,23 @@ export const commandCenterKeyDownHandler = derived( return mostModifiersCommands[0].command; }; - const execute = debounce(() => { - console.log('Executing command center command', { validCommands, recentKeyCodes }); - + const rankAndExecute = debounce(() => { const command = getHighestPriorityCommand(); command.callback(); reset.immediate(); }, 200); + const execute = (command: KeyedCommand) => { + if (hasDisputing(command, commandsArr)) { + validCommands.push(command); + rankAndExecute(); + } else { + command.callback(); + reset.immediate(); + } + }; + return (event: KeyboardEvent) => { recentKeyCodes.push(event.keyCode); reset(); @@ -153,8 +175,7 @@ export const commandCenterKeyDownHandler = derived( if (allKeysPressed && isMetaPressed && isShiftPressed && isAltPressed) { event.preventDefault(); - validCommands.push(command); - execute(); + execute(command); } } };