CxJS

Keyboard Shortcuts

import { registerKeyboardShortcut } from 'cx/ui'; Copied

CxJS provides registerKeyboardShortcut for listening to keyboard shortcuts. Shortcuts only trigger when the document body has focus (not when focused on input fields).

Example

<div class="flex flex-col gap-4" controller={PageController}>
  <div class="text-sm text-gray-600">
    Click outside the checkboxes and press the shortcuts:
  </div>
  <div class="flex flex-col gap-2">
    <Checkbox value={m.enterPressed} text="Enter" readOnly />
    <Checkbox value={m.shiftAPressed} text="Shift + A" readOnly />
  </div>
</div>
Click outside the checkboxes and press the shortcuts:

Key Argument

The first argument can be a simple key code or an object for key combinations:

// Simple key
registerKeyboardShortcut(KeyCode.enter, callback);

// Key combination
registerKeyboardShortcut({ keyCode: KeyCode.a, shiftKey: true }, callback);

The object form accepts:

  • keyCode (required) - A value from the KeyCode class
  • shiftKey - Require Shift key
  • ctrlKey - Require Ctrl key
  • altKey - Require Alt key

KeyCode

import { KeyCode } from 'cx/util'; Copied

Common key codes:

KeyCode
EnterKeyCode.enter
EscapeKeyCode.esc
SpaceKeyCode.space
TabKeyCode.tab
BackspaceKeyCode.backspace
DeleteKeyCode.delete
Arrow keysKeyCode.up, KeyCode.down, KeyCode.left, KeyCode.right
Page Up/DownKeyCode.pageUp, KeyCode.pageDown
Home/EndKeyCode.home, KeyCode.end
Letter AKeyCode.a
Warning

Always unregister keyboard shortcuts when they’re no longer needed to prevent memory leaks. Call the unregister function returned by registerKeyboardShortcut in the controller’s onDestroy method.