Installation
npm install react-sunbeam
or
yarn add react-sunbeam
Usage
// app.js { const setFocus moveFocusLeft moveFocusRight moveFocusUp moveFocusDown = const onKeyDown = return <div> <FocusableCard focusKey="card-1" /> <Focusable focusKey="item1"> <div>focused ? "I am focused" : "I am not focused"</div> </Focusable> <Focusable focusKey="menuContainer"> <div> <Focusable focusKey="menuItem1"> <div style= backgroundColor: focused ? "salmon" : "deepskyblue" > You can nest Focusables </div> </Focusable> <Focusable focusKey="menuItem2"> <div style= backgroundColor: focused ? "salmon" : "deepskyblue" > In this case Sunbeam will try to find the best candidate for the focus within the common Focusable parent first </div> </Focusable> </div> </Focusable> <Focusable focusKey="item2"> <div style= textDecoration: focused ? "underline" : "none" onClick= > You can also programmatically change focus by using `setFocus` API </div> </Focusable> </div> } const focusManager = initialFocusPath: "menuContainer" "menuItem2" // FocusableCard.js { const elementRef = const focused = return <div ref=elementRef style= border: focused ? "1px solid salmon" : "1px solid transparent" > Card </div> }
API
FocusManager
FocusManager
is responsible for maintaining the tree of focusable nodes and updating the currently focused node.
Usually, your app will only have a single instance of it which you pass to a <SunbeamProvider>
component
moveLeft()
/ moveRight()
/ moveUp()
/ moveDown()
These are the most important methods of FocusManager
.
They move focus to the nearest focusable node in the corresponding direction.
You can call these methods in response to any events you want: key presses, game controller button presses, scroll events, etc.
setFocus(path: string[]): void
Immediately makes focused the focusable node with the given path
.
Example
const focusManager = initialFocusPath: "menuContainer" "menuItem1" // Use arrow key presses to control focus.document
SunbeamProvider
Focusable
useSunbeam(): { setFocus(focusPath: readonly string[]): void; moveFocusRight(): void; moveFocusLeft(): void; moveFocusUp(): void; moveFocusDown(): void; }
This hook provides access to some public methods of FocusManager
inside the React components.
It expects <SunbeamProvider>
to be present in the tree, otherwise it returns no-op versions of the methods
useFocusable(options: Options): { focused: boolean; path: string[] }
This hook makes the enclosing component focusable. It can only be used for the "leaf" focusables so the component
that uses it cannot have other focusable children. If you need the latter behaviour use <Focusable>
instead.
Options
Example
KeyPressManager
TODO