Mmohebifar

prefer-keyboardevent-key-over-keycode-javascript

Replace deprecated KeyboardEvent.keyCode checks with standards-based event.key string comparisons in JavaScript and TypeScript keyboard handlers.

transformationmigrationkeyboardeventkeycodeaccessibility
Public
0 executions

Run locally

npx codemod prefer-keyboardevent-key-over-keycode-javascript

prefer-keyboardevent-key-over-keycode-javascript

Replace deprecated KeyboardEvent.keyCode checks with standards-based event.key string comparisons in JavaScript and TypeScript keyboard handlers.

What It Rewrites

  • Equality and inequality checks against mapped numeric key codes: ===, !==, ==, !=
  • Comparisons against file-local const aliases that resolve to mapped numeric key codes
  • Reversed comparisons such as 13 === e.keyCode
  • Bracket access such as e['keyCode'] === 9
  • Boolean compositions that contain safe keyCode comparisons
  • switch (event.keyCode) when every non-default case label is a mapped numeric literal

Default key mapping:

  • 8 -> 'Backspace'
  • 9 -> 'Tab'
  • 13 -> 'Enter'
  • 27 -> 'Escape'
  • 32 -> ' '
  • 37 -> 'ArrowLeft'
  • 38 -> 'ArrowUp'
  • 39 -> 'ArrowRight'
  • 40 -> 'ArrowDown'
  • 46 -> 'Delete'

Handler Heuristics

By default, the codemod only rewrites keyCode usage when it appears in keyboard-oriented contexts:

  • DOM listeners passed to addEventListener('keydown' | 'keyup' | 'keypress', ...)
  • JSX handlers such as onKeyDown, onKeyUp, and onKeyPress
  • Functions whose matching event parameter is explicitly typed as KeyboardEvent or React.KeyboardEvent
  • Keyboard-named handlers such as handleKeyDown

This keeps the transform conservative for user-defined .keyCode properties outside browser keyboard handling.

Exclusions

  • Assignments and updates such as e.keyCode = 13 or e.keyCode++
  • Unmapped numeric key codes
  • Comparisons against non-literal values that cannot be folded to a mapped numeric key code
  • Branches that already mix the same object's keyCode and key checks
  • TypeScript handlers whose event parameter is explicitly typed as a non-keyboard event, unless unsafe=true
  • switch statements with any non-default case label that cannot be mapped deterministically

Parameters

  • force=true: bypass keyboard-context heuristics and rewrite any safe keyCode comparison or switch
  • unsafe=true: allow rewrites even when the matching TypeScript event parameter is explicitly typed as a non-keyboard event

Before And After

js
js

Usage

bash

Development

bash

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.