useKeyboardShortcut
The useKeyboardShortcut hook registers a keydown listener for a key combination in aria-keyshortcuts format and runs onTrigger when the user presses it. On top of that, the hook accepts mod, which resolves to Meta on macOS and to Control on every other platform.
Import
import { useKeyboardShortcut } from '@dynatrace/strato-components/core';
Demo
The keys prop uses the aria-keyshortcuts format: any combination of modifier keys—Alt, Control, Shift, Meta, AltGraph—followed by exactly one non-modifier key, all joined with + (for example, Control+Shift+K). You can include zero or more modifiers, but only one key that isn't a modifier. Matching is case-insensitive.
Define a per-platform combination
The keys prop also accepts an object: macos applies on macOS when it is set, and default applies everywhere else. Reach for it when a combination differs by more than the mod modifier.
Scope listener to an element
The keydown listener is attached to document.body by default. Alternatively, eventTarget can be set to an element or a ref.
Trigger shortcut while user types
The shouldIgnoreTarget callback runs against event.target before the combination is matched and skips the shortcut when it returns true. It defaults to isValueEntryTarget, which covers <input>, <textarea>, <select>, role="textbox", and contenteditable elements. Pass () => false to match on any target.
Each check behind isValueEntryTarget is exported on its own, as follows: isInputTarget, isTextareaTarget, isSelectTarget, isTextboxTarget, and isEditableTarget.
Run ahead of descendant
The listener is registered in the bubble phase, so a descendant calling stopPropagation on the event stops it from ever running. capture: true registers it in the capture phase instead, ahead of every descendant.
Caveats
Use Alt and AltGr sparingly, and only with a letter or a digit. Both compose a character on some layouts, which replaces the key name in event.key. The hook only recovers it from event.code for letters and digits.