Skip to content

Instantly share code, notes, and snippets.

@asgvard
Created March 17, 2022 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asgvard/6bf1a9c5bb91650c36b380d26dc66864 to your computer and use it in GitHub Desktop.
Save asgvard/6bf1a9c5bb91650c36b380d26dc66864 to your computer and use it in GitHub Desktop.
function GalleryRow({items, focused}) {
const [focusedItemIndex, setFocusedItemIndex] = useState(0);
const onSetFocus = useCallback(({newFocusedIndex}) => {
if (!focused) {
return;
}
setFocusedItemIndex(Math.clamp(newFocusedIndex, 0, items.length - 1));
}, [focused]);
return (<div>
{items.map((item, index) => <GalleryItem
key={item.id}
focused={index === focusedItemIndex}
{...item}
onSetFocus={onSetFocus}
focusMap={{
left: index - 1,
right: index + 1
}}
/>)}
</div>);
}
function GalleryItem({items, focused, onSetFocus, focusMap}) {
const onKeyPress = useCallback(({keyCode}) => {
if (!focused) {
return;
}
if (keyCode === KEY_RIGHT) {
onSetFocus(focusMap.right);
} else if (keyCode === KEY_LEFT) {
onSetFocus(focusMap.left);
}
}, [onSetFocus, focusMap]);
useEffect(() => {
window.addEventListener('keydown', onKeyPress);
return () => {
window.removeEventListener('keydown', onKeyPress);
};
}, [onKeyPress]);
return (<div>
...
</div>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment