Security News
New Python Packaging Proposal Aims to Solve Phantom Dependency Problem with SBOMs
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
@noriginmedia/react-spatial-navigation
Advanced tools
HOC-based Spatial Navigation (key navigation) solution for React
The main motivation to create this package was to bring the best Developer Experience and Performance when working with Key Navigation and React. Ideally you wouldn't want to have any logic to define the navigation in your app. It should be as easy as just to tell which components should be navigable. With this package all you have to do is to initialize it, wrap your components with the HOC and set initial focus. The spatial navigation system will automatically figure out which components to focus next when you navigate with the directional keys.
Smart TV Navigation with React
npm i @noriginmedia/react-spatial-navigation --save
// Somewhere at the root of the app
import {initNavigation, setKeyMap} from '@noriginmedia/react-spatial-navigation';
initNavigation();
// Optional
setKeyMap({
'left': 9001,
'up': 9002,
'right': 9003,
'down': 9004,
'enter': 9005
});
import {withFocusable} from '@noriginmedia/react-spatial-navigation';
...
const FocusableComponent = withFocusable()(Component);
import {withFocusable} from '@noriginmedia/react-spatial-navigation';
...
const FocusableComponent = withFocusable({
trackChildren: true,
forgetLastFocusedChild: true
})(Component);
import {withFocusable} from '@noriginmedia/react-spatial-navigation';
...
const FocusableComponent = withFocusable()(Component);
const ParentComponent = (props) => (<View>
...
<FocusableComponent
trackChildren
forgetLastFocusedChild
focusKey={'FOCUSABLE_COMPONENT'}
onEnterPress={props.onItemPress}
onArrowPress={props.onArrowPress}
onBecameFocused={props.onItemFocused}
onBecameBlurred={props.onItemBlurred}
/>
...
</View>);
import {withFocusable} from '@noriginmedia/react-spatial-navigation';
const Component = ({focused, setFocus}) => (<View>
<View style={focused ? styles.focusedStyle : styles.defaultStyle} />
<TouchableOpacity
onPress={() => {
setFocus('SOME_ANOTHER_COMPONENT');
}}
/>
</View>);
const FocusableComponent = withFocusable()(Component);
import React, {PureComponent} from 'react';
import {withFocusable} from '@noriginmedia/react-spatial-navigation';
...
class Menu extends PureComponent {
componentDidMount() {
// this.props.setFocus(); // If you need to focus first child automatically
this.props.setFocus('MENU-6'); // If you need to focus specific item that you know focus key of
}
render() {
return (<View style={hasFocusedChild ? styles.menuExpanded : styles.defaultStyle}>
<MenuItemFocusable />
<MenuItemFocusable />
<MenuItemFocusable />
<MenuItemFocusable />
<MenuItemFocusable />
<MenuItemFocusable focusKey={'MENU-6'} />
</View>);
}
}
const MenuFocusable = withFocusable({
trackChildren: true
})(Menu);
Since in native environment the focus is controlled by the native engine, we can only "sync" with it by setting focus on the component itself when it gets focused.
Native navigation system automatically converts all Touchable
component to focusable components and enhances them with the callbacks such as onFocus
and onBlur
.
Read more here: React Native on TVs.
import {withFocusable} from '@noriginmedia/react-spatial-navigation';
const Component = ({focused, stealFocus}) => (<View>
<View style={focused ? styles.focusedStyle : styles.defaultStyle} />
<TouchableOpacity
onFocus={stealFocus}
/>
</View>);
const FocusableComponent = withFocusable()(Component);
initNavigation
: functionFunction that needs to be called to enable Spatial Navigation system and bind key event listeners. Accepts Initialization Config as a param.
initNavigation({
debug: true,
visualDebug: true
})
debug
: booleanEnable console debugging
visualDebug
: booleanEnable visual debugging (all layouts, reference points and siblings refernce points are printed on canvases)
nativeMode
: booleanEnable Native mode. It will block certain web-only functionality such as:
onBecameFocused
and onBecameBlurred
callbacks doesn't return coordinates, but still has node ref to lazy measure layoutNative mode should be only used to keep the tree of focusable components and to sync the focused
flag to enable styling for focused components.
In Native mode you can only stealFocus
to some component to flag it as focused
, normal setFocus
method is blocked because it will not propagate to native layer.
throttle
: integerEnable to throttle the function fired by the event listener.
setKeyMap
: functionFunction to set custom key codes.
setKeyMap({
'left': 9001,
'up': 9002,
'right': 9003,
'down': 9004,
'enter': 9005
});
withFocusable
: functionMain HOC wrapper function. Accepts config as a param.
const FocusableComponent = withFocusable({...})(Component);
trackChildren
: booleanDetermine whether to track when any child component is focused. Wrapped component can rely on hasFocusedChild
prop when this mode is enabled. Otherwise hasFocusedChild
will be always false
.
hasFocusedChild
changesforgetLastFocusedChild
: booleanDetermine whether this component should not remember the last focused child components. By default when focus goes away from the component and then it gets focused again, it will focus the last focused child. This functionality is enabled by default.
All these props are optional.
trackChildren
: booleanSame as in config.
forgetLastFocusedChild
: booleanSame as in config.
focusable
: booleanDetermine whether this component should be focusable (in other words, whether it's currently participating in the spatial navigation tree). This allows a focusable component to be ignored as a navigation target despite being mounted (e.g. due to being off-screen, hidden, or temporarily disabled).
Note that behaviour is undefined for trees of components in which an focusable={false}
component has any focusable={true}
components as descendants; it is recommended to ensure that all components in a given branch of the spatial navigation tree have a common focusable
state.
Also focusable={false}
does not prevent component from being directly focused with setFocus
. It only blocks "automatic" focus logic such as directional navigation, or focusing component as lastFocusedChild or preferredFocusChild.
focusKey
: stringString that is used as a component focus key. Should be unique, otherwise it will override previously stored component with the same focus key in the Spatial Navigation service storage of focusable components. If this is not specified, the focus key will be generated automatically.
onEnterPress
: functionCallback function that is called when the item is currently focused and Enter (OK) key is pressed.
Payload:
const onPress = ({prop1, prop2}, details) => {...};
...
<FocusableItem
prop1={111}
prop2={222}
onEnterPress={onPress}
/>
...
onArrowPress
: functionCallback function that is called when the item is currently focused and an arrow (LEFT, RIGHT, UP, DOWN) key is pressed.
Payload:
Prevent default navigation:
By returning false
the default navigation behavior is prevented.
const onPress = (direction, {prop1, prop2}) => {
...
return false;
};
...
<FocusableItem
prop1={111}
prop2={222}
onArrowPress={onPress}
/>
...
onBecameFocused
: functionCallback function that is called when the item becomes focused directly or when any of the children components become focused. For example when you have nested tree of 5 focusable components, this callback will be called on every level of down-tree focus change.
Payload:
The first parameter is the component layout object. The second paramter is an object containing all the component props. The third parameter is a details object that was used when triggering the focus change, for example it contains the key event in case of arrow navigation. Useful to avoid creating callback functions during render. x
and y
are relative coordinates to parent DOM (not the Focusable parent) element. left
and top
are absolute coordinates on the screen.
const onFocused = ({width, height, x, y, top, left, node}, {prop1, prop2}, {event, other}) => {...};
...
<FocusableItem
prop1={111}
prop2={222}
onBecameFocused={onFocused}
/>
...
onBecameBlurred
: functionCallback function that is called when the item loses focus or when all the children components lose focus. For example when you have nested tree of 5 focusable components, this callback will be called on every level of down-tree focus change.
Payload:
The first parameter is the component layout object. The second paramter is an object containing all the component props. The third parameter is a details object that was used when triggering the focus change, for example it contains the key event in case of arrow navigation. Useful to avoid creating callback functions during render. x
and y
are relative coordinates to parent DOM (not the Focusable parent) element. left
and top
are absolute coordinates on the screen.
const onBlur = ({width, height, x, y, top, left, node}, {prop1, prop2}, {event, other}) => {...};
...
<FocusableItem
prop1={111}
prop2={222}
onBecameBlurred={onBlur}
/>
...
focusKey
: stringFocus key that represents the focus key that was applied to HOC component. Might be null
when not set. It is recommended to not rely on this prop ¯\_(ツ)_/¯
realFocusKey
: stringFocus key that is either the focusKey
prop of the HOC, or automatically generated focus key like sn:focusable-item-23
.
parentFocusKey
: stringFocus key of the parent component. If it is a top level focusable component, this prop will be SN:ROOT
preferredChildFocusKey
: stringFocus key of the child component focused during the focus propagation when the parent component is focused the first time or has forgetLastFocusedChild
set
focused
: booleanWhether component is currently focused. It is only true
if this exact component is focused, e.g. when this component propagates focus to child component, this value will be false
.
hasFocusedChild
: booleanThis prop indicates that the component currently has some focused child on any depth of the focusable tree.
setFocus
: functionThis method sets the focus to another component (when focus key is passed as param) or steals the focus to itself (when used w/o params). It is also possible to set focus to a non-existent component, and it will be automatically picked up when component with that focus key will get mounted.
This preemptive setting of the focus might be useful when rendering lists of data.
You can assign focus key with the item index and set it to e.g. first item, then as soon as it will be rendered, that item will get focused.
In Native mode this method is ignored (noop
).
This method accepts a second parameter as a details object that will be passed back to the onBecameFocused
and onBecameBlurred
callbacks.
setFocus(); // set focus to self
setFocus('SOME_COMPONENT', {event: keyEvent}); // set focus to another component if you know its focus key
navigateByDirection
: functionMove the focus by direction, if you can't use buttons or focusing by key.
This method accepts a second parameter as a details object that will be passed back to the onBecameFocused
and onBecameBlurred
callbacks.
navigateByDirection('left'); // The focus is moved to left
navigateByDirection('right'); // The focus is moved to right
navigateByDirection('up'); // The focus is moved to up
navigateByDirection('down', {event: keyEvent}); // The focus is moved to down
stealFocus
: functionThis method works exactly like setFocus
, but it always sets focus to current component no matter which params you pass in.
This is the only way to set focus in Native mode.
<TouchableOpacity
onFocus={stealFocus}
/>
pauseSpatialNavigation
: functionThis function pauses key listeners. Useful when you need to temporary disable navigation. (e.g. when player controls are hidden during video playback and you want to bind the keys to show controls again).
resumeSpatialNavigation
: functionThis function resumes key listeners if it was paused with pauseSpatialNavigation
KeyDetails
: objectThis object contains informations about keys.
{
pressedKeys: {
[KEY]: number
}
}
pressedKeys
contains a property for each pressed key in a given moment, the value is the number of keydown events fired before the keyup event.
This library is using Parcel to serve the web build.
To run the testbed app locally:
npm start
This will start local server on localhost:1234
Source code is in src/App.js
parentFocusKey
.withFocusable
HOCrealFocusKey
is created once at component mount in withStateHandlers
. It either takes the focusKey
prop value or is automatically generated.setFocus
method is bound with the current component realFocusKey
so you can call it w/o params to focus component itself. Also the behaviour of this method can be described as an attempt to set the focus, because even if the target component doesn't exist yet, the target focus key will be stored and the focus will be picked up by the component with that focus key when it will get mounted.parentFocusKey
is propagated to children components through context. This is done because the focusable components tree is not necessary the same as the DOM tree.spatialNavigation
service storage of all focusable components.spatialNavigation
ServiceaddFocusable
and removed in removeFocusable
setFocus
. First it decides next focus key (getNextFocusKey
), then set focus to the new component (setCurrentFocusedKey
), then the service updates all components that has focused child and finally updates layout (coordinates and dimensions) for all focusable component.getNextFocusKey
is used to determine the good candidate to focus when you call setFocus
. This method will either return the target focus key for the component you are trying to focus, or go down by the focusable tree and select the best child component to focus. This function is recoursive and going down by the focusable tree.smartNavigate
is similar to the previous one, but is called in response to a key press event. It tries to focus the best sibling candidate in the direction of key press, or delegates this task to a focusable parent, that will do the same attempt for its sibling and so on.stealFocus
. This service mostly works as a "sync" between native navigation system and JS to apply focused
state and keep the tree structure of focusable components. All the layout and coordinates measurement features are disabled because native engine takes care of it.Please follow the Contribution Guide
MIT Licensed
[2.11.0]
onBecameBlurred
and onBecameFocused
are always invoked synchonously with focus change and not on componentDidUpdatesetFocus
and navigateByDirection
accept an details object, this object is passed back on onBecameBlurred
and onBecameFocused
callbacksFAQs
HOC-based Spatial Navigation (key navigation) solution for React
The npm package @noriginmedia/react-spatial-navigation receives a total of 4,183 weekly downloads. As such, @noriginmedia/react-spatial-navigation popularity was classified as popular.
We found that @noriginmedia/react-spatial-navigation demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
Security News
Socket CEO Feross Aboukhadijeh discusses open source security challenges, including zero-day attacks and supply chain risks, on the Cyber Security Council podcast.
Security News
Research
Socket researchers uncover how threat actors weaponize Out-of-Band Application Security Testing (OAST) techniques across the npm, PyPI, and RubyGems ecosystems to exfiltrate sensitive data.