Skip to content

Conversation

Veenoway
Copy link

@Veenoway Veenoway commented Jul 30, 2025

Bug Fix

Problem

The keyboard handlers stack gets permanently mutated during iteration, causing unpredictable behavior on subsequent key presses.

Root Cause

for (let handler of handlersStack.reverse()) {
 //                              ^^^^^^^^^ Mutates original array

The .reverse() method modifies the array in-place, so after the first keydown event, all handlers are permanently stored in reverse order, breaking the expected execution sequence.

Solution

Use array spread to create a copy before reversing:

javascript
for (let handler of [...handlersStack].reverse()) {
  //                  ^^^ Creates copy, preserves original order

Additionally, fix handler cleanup to prevent removing wrong handlers:

javascript 
const index = allHandlersStacks[lowerKey].indexOf(handler);
if (index > -1) {  // Check handler exists before removal
  allHandlersStacks[lowerKey].splice(index, 1);
}

Impact

  • Fixes inconsistent keyboard shortcut behavior after first use
  • Ensures handlers execute in correct LIFO order on every key press
  • Prevents accidental removal of wrong handlers during cleanup
  • Maintains backwards compatibility with existing functionality

Files Changed

hooks/useGlobalKey.ts - Fixed array mutation and cleanup logic

@Veenoway Veenoway requested a review from a team as a code owner July 30, 2025 19:54
@Veenoway Veenoway force-pushed the fix/keyboard-handlers-stack-mutation branch from b136525 to 71af0a2 Compare September 4, 2025 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant