Instantly share code, notes, and snippets.
Created
March 17, 2022 14:09
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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