@shopify/react-shortcuts3.0.2 • Public • Published
Declarative and performant library for matching shortcut combinations in React applications.
$ yarn add @shopify/react-shortcuts
The library exposes three main parts,
<Shortcut /> and
Wrapping your application in a
<ShortcutProvider /> allows you to use
<Shortcut /> components anywhere in your application, internally sharing a single
ShortcutManager instance to minimize listeners and collisions.
Shortcut is used to register a new keyboard shortcut to
ShortcutManager. It can be triggered globally or only when a node is focused.
<Shortcut /> must have a
<ShortcutProvider /> somewhere above it in the tree.
With modifier keys
You may also want to provide alternate groupings of
held modifier keys. For example, “undo/redo” key combos are slightly different on Windows vs Mac OS. The below example will register
onMatch if either
Control + z or
Meta + z is pressed simultaneously.
Metarefers to the “Command” key on Mac keyboards.
FnLockkeys are not supported because they don't produce events, as mentioned in the spec
On a focused node
Provide a node in the form of a
<Shortcut /> will automatically subscribe to the
ShortcutManager once the node is available.
<Shortcut /> invokes a hook,
useShortcut(), under the hood. This hook is also available for use from this package. It will also register a new keyboard shortcut to the
ShortcutManager and the API is very similar.
The below example illustrates the same basic functionality as the
<Shortcut /> example above. However, it uses the
useShortcut() hook and the component has been removed.
ShortcutManager is created by
ShortcutProvider and handles the logic for calling the appropriate shortcut callbacks and avoiding conflicts. You should never need to use it directly in application code, though you may want access to it in tests.
Example jest test
Given a component implementing a
you might want to add a
ShortcutManager to it's context in an enzyme test to prevent errors