Keyboard
onKeyPress exists on a <TextInput> and a <View> had nothing, so an app
could not bind a shortcut to anything it draws. On a phone that is no loss; on a
desktop it is most of the interface.
import {KeyHandler} from 'basalt-core';
<KeyHandler
keys={[
{key: 'k', metaKey: true},
{key: 'ArrowDown'},
{key: 'Escape'},
]}
onKeyDown={pressed => act(pressed.key)}
focusOnMount
>
<List />
</KeyHandler><KeyHandler> is a <View> with two extra props, and takes every other
<View> prop.
| prop | |
|---|---|
keys | the combinations this view handles. Required |
onKeyDown | called with the one that was pressed |
focusOnMount | take keyboard focus when mounted |
A HandledKey is {key, altKey?, ctrlKey?, metaKey?, shiftKey?}, and a
PressedKey is the same shape, so the thing you are handed matches an entry in
the list you declared.
The names are a browser's
key is what KeyboardEvent.key reports: 'a', 'A', ' ', 'ArrowLeft',
'Escape'. react-native-macos and react-native-windows both use these, so a
binding means the same thing on every platform an app might run on. Case follows
the character, as in a browser: Shift+A is 'A' and has shiftKey.
Why the keys are declared rather than just listened for
Because a key nothing handled has to go on, to the menu, to a focused text field, to a scroll view that scrolls on arrows, and a key that was handled must not. The host decides that synchronously, inside the toolkit's key handler, and cannot ask JavaScript at that moment.
So the list is what answers, and a combination absent from it is one this view
will never be told about. Which also means changing keys changes what the view
handles from that render on, which is what an editor adding bindings as panes
mount needs.
Focus
A view only hears keys when it has keyboard focus. focusOnMount is the common
case: a panel that should be ready for its shortcuts as soon as it appears.
Tab moves focus the way the desktop expects, and what is in the ring is one
answer shared by all three hosts: a view is reachable by Tab if it is a control
or sets accessible, unless accessibilityElementsHidden is set, and never if
accessibilityRespondsToUserInteraction is false. See
Platform support for those props.