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 theKeyCodeclassshiftKey- Require Shift keyctrlKey- Require Ctrl keyaltKey- Require Alt key
KeyCode
import { KeyCode } from 'cx/util'; Copied Common key codes:
| Key | Code |
|---|---|
| Enter | KeyCode.enter |
| Escape | KeyCode.esc |
| Space | KeyCode.space |
| Tab | KeyCode.tab |
| Backspace | KeyCode.backspace |
| Delete | KeyCode.delete |
| Arrow keys | KeyCode.up, KeyCode.down, KeyCode.left, KeyCode.right |
| Page Up/Down | KeyCode.pageUp, KeyCode.pageDown |
| Home/End | KeyCode.home, KeyCode.end |
| Letter A | KeyCode.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.