import React, { createContext, FC, ReactNode, useCallback, useContext, useEffect } from 'react' import { createUseStyles } from 'react-jss' type OptionButtonProps = { children: ReactNode className?: string selectionIndex?: number onSelect: () => void } export const OptionButton: FC = ({ children, className, selectionIndex, onSelect, }) => { // styles const styles = useStyles() // memoized values and constants const { activeIndex, focusIndex } = useContext(OptionButtonContext) const isActive = activeIndex === selectionIndex const classNames = [styles.optionButton] if (className) classNames.push(className) if (isActive) classNames.push(styles.active) // event handlers const handleMouseMove = useCallback(() => { if (selectionIndex === undefined) return focusIndex(selectionIndex) }, [focusIndex, selectionIndex]) const handleClick = useCallback(() => { onSelect() }, [onSelect]) // side effects useEffect(() => { if (!isActive) return const handleDocumentKeyDown = (event: KeyboardEvent) => { if (event.key === 'Enter') { onSelect() } } document.addEventListener('keydown', handleDocumentKeyDown) return () => { document.removeEventListener('keydown', handleDocumentKeyDown) } }, [isActive, onSelect]) return (
{children}
) } const useStyles = createUseStyles({ optionButton: { cursor: 'pointer', paddingTop: 6, paddingBottom: 6, paddingLeft: 8, paddingRight: 8, borderRadius: 4, fontSize: 14, }, active: { backgroundColor: 'rgb(240, 240, 240)', }, }) export type OptionButtonContextType = { activeIndex: number | undefined focusPreviousOption: () => void focusNextOption: () => void clearSelection: () => void focusIndex: (index: number) => void } export const OptionButtonContext = createContext({ activeIndex: undefined, focusNextOption: () => {}, focusPreviousOption: () => {}, clearSelection: () => {}, focusIndex: () => {}, })