NoriginMedia / react-spatial-navigation

DEPRECATED. HOC-based Spatial Navigation. NEW Hooks version is available here: https://github.com/NoriginMedia/norigin-spatial-navigation
MIT License
226 stars 64 forks source link

feat: Add event emitter and support a `focusKeyUpdate` event #57

Closed shirakaba closed 1 year ago

shirakaba commented 4 years ago

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}`);
  }
);