react-spatial-navigation
react-spatial-navigation copied to clipboard
feat: Add event emitter and support a `focusKeyUpdate` event
Added dependency
This adds the EventEmitter3 package, which implements the Node.js EventEmitter API, with some minor differences noted in the repository's readme. It is chosen for supporting Node, browser, and React Native environments.
Use case
It allows you to listen for a focusKeyUpdate event, fired any time setFocus() is called. This is very useful for debugging what actions in your app lead to focusKey changes, particularly in cases such as the currently focused element becoming unmounted (e.g. because a modal appeared or because a focused menu faded out whilst a video was playing).
It is also ideal for keeping a history of focus key changes, either for analytics purposes or for restoring focus to the last-focused item on a screen when a modal is dismissed.
focusKeyUpdate event
The event object has the interface:
interface FocusKeyUpdateEvent {
lastFocusedKey: string;
newFocusKey: string;
}
Example usage
As focusKeyUpdate is fired in response to any setFocus() call, it is not guaranteed that the new focus key will be different from the previous one. So if the user specifically wants to detect focus key changes, they are advised to check whether the newFocusKey property differs from the lastFocusedKey property on the event.
spatialNavigation.eventEmitter.addListener(
'focusKeyUpdate',
(event) => {
const { lastFocusedKey, newFocusKey } = event;
if(lastFocusedKey === newFocusKey){
console.log(`setFocus() was called on the same focus key as before; no focus change.`);
return;
}
console.log(`Focus changed from ${lastFocusedKey} -> ${newFocusKey}`);
}
);