Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | import { useEffect, useRef, useState, useCallback } from 'react'; interface UseKeyboardNavigationOptions { /** Total number of items to navigate */ itemCount: number; /** Callback when an item is selected (Enter/Space) */ onSelect?: (index: number) => void; /** Navigation orientation */ orientation?: 'horizontal' | 'vertical'; /** Whether to loop when reaching the end */ loop?: boolean; /** Initially active index */ initialIndex?: number; } interface UseKeyboardNavigationReturn { /** Currently active index */ activeIndex: number; /** Set the active index manually */ setActiveIndex: React.Dispatch<React.SetStateAction<number>>; /** Ref setter for each item */ setItemRef: (index: number) => (el: HTMLElement | null) => void; /** Keyboard event handler for the container */ handleKeyDown: (e: React.KeyboardEvent) => void; /** Props getter for each item */ getItemProps: (index: number) => { ref: (el: HTMLElement | null) => void; tabIndex: number; 'aria-selected': boolean; }; } /** * Hook for keyboard navigation in lists, tabs, and other navigable components. * Implements WAI-ARIA keyboard navigation patterns including roving tabindex. * * @example * ```tsx * function TabList({ tabs, onTabChange }) { * const { activeIndex, handleKeyDown, getItemProps } = useKeyboardNavigation({ * itemCount: tabs.length, * onSelect: onTabChange, * orientation: 'horizontal', * }); * * return ( * <div role="tablist" onKeyDown={handleKeyDown}> * {tabs.map((tab, index) => ( * <button * key={tab.id} * role="tab" * {...getItemProps(index)} * onClick={() => onTabChange(index)} * > * {tab.label} * </button> * ))} * </div> * ); * } * ``` */ export function useKeyboardNavigation({ itemCount, onSelect, orientation = 'vertical', loop = true, initialIndex = 0}: UseKeyboardNavigationOptions): UseKeyboardNavigationReturn { const [activeIndex, setActiveIndex] = useState(initialIndex); const itemRefs = useRef<(HTMLElement | null)[]>([]); // Reset refs array when item count changes useEffect(() => { itemRefs.current = itemRefs.current.slice(0, itemCount); }, [itemCount]); const setItemRef = useCallback( (index: number) => (el: HTMLElement | null) => { itemRefs.current[index] = el; }, [] ); const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { const nextKey = orientation === 'vertical' ? 'ArrowDown' : 'ArrowRight'; const prevKey = orientation === 'vertical' ? 'ArrowUp' : 'ArrowLeft'; switch (e.key) { case nextKey: e.preventDefault(); setActiveIndex((prev) => { const next = prev + 1; if (next >= itemCount) return loop ? 0 : prev; return next; }); break; case prevKey: e.preventDefault(); setActiveIndex((prev) => { const next = prev - 1; if (next < 0) return loop ? itemCount - 1 : prev; return next; }); break; case 'Home': e.preventDefault(); setActiveIndex(0); break; case 'End': e.preventDefault(); setActiveIndex(itemCount - 1); break; case 'Enter': case ' ': e.preventDefault(); onSelect?.(activeIndex); break; } }, [activeIndex, itemCount, loop, onSelect, orientation] ); // Focus the active item when it changes useEffect(() => { const activeElement = itemRefs.current[activeIndex]; if (activeElement && document.activeElement !== activeElement) { activeElement.focus(); } }, [activeIndex]); const getItemProps = useCallback( (index: number) => ({ ref: setItemRef(index), tabIndex: index === activeIndex ? 0 : -1, 'aria-selected': index === activeIndex}), [activeIndex, setItemRef] ); return { activeIndex, setActiveIndex, setItemRef, handleKeyDown, getItemProps}; } export default useKeyboardNavigation; |