11import useDropdownContext from '../../dropdown-context' ;
22import { isMobileDisplay } from '~/helpers/device' ;
33
4- function findNext ( dropdownRef : React . MutableRefObject < HTMLDivElement > ) {
4+ function findNext ( dropdownRef : React . MutableRefObject < HTMLDivElement | null > ) {
55 const nextSib = document . activeElement ?. nextElementSibling ;
66
77 if ( nextSib ?. matches ( 'a' ) ) {
88 return nextSib as HTMLAnchorElement ;
99 }
10- const targets = Array . from ( dropdownRef . current . querySelectorAll ( 'a' ) ) ;
10+ const targets = Array . from ( dropdownRef . current ? .querySelectorAll ( 'a' ) ?? [ ] ) ;
1111 const idx = targets . indexOf ( document . activeElement as HTMLAnchorElement ) ;
1212 const nextIdx = ( idx + 1 ) % targets . length ;
1313
1414 return targets [ nextIdx ] ;
1515}
1616
17+ // eslint-disable-next-line complexity
1718function findPrev (
18- topRef : React . MutableRefObject < HTMLAnchorElement > ,
19- dropdownRef : React . MutableRefObject < HTMLDivElement >
19+ topRef : React . MutableRefObject < HTMLAnchorElement | null > ,
20+ dropdownRef : React . MutableRefObject < HTMLDivElement | null >
2021) {
2122 const prevSib = document . activeElement ?. previousElementSibling ;
2223
2324 if ( prevSib ?. matches ( 'a' ) ) {
2425 return prevSib as HTMLAnchorElement ;
2526 }
26- const targets = Array . from ( dropdownRef . current . querySelectorAll ( 'a' ) ) ;
27+ const targets = Array . from ( dropdownRef . current ? .querySelectorAll ( 'a' ) ?? [ ] ) ;
2728 const idx = targets . indexOf ( document . activeElement as HTMLAnchorElement ) ;
2829
2930 if ( idx === 0 ) {
@@ -40,8 +41,8 @@ export default function useNavigateByKey({
4041 closeMenu,
4142 closeDesktopMenu
4243} : {
43- topRef : React . MutableRefObject < HTMLAnchorElement > ;
44- dropdownRef : React . MutableRefObject < HTMLDivElement > ;
44+ topRef : React . MutableRefObject < HTMLAnchorElement | null > ;
45+ dropdownRef : React . MutableRefObject < HTMLDivElement | null > ;
4546 closeMenu : ( ) => void ;
4647 closeDesktopMenu : ( ) => void ;
4748} ) {
@@ -69,15 +70,15 @@ export default function useNavigateByKey({
6970 case 'ArrowDown' :
7071 event . preventDefault ( ) ;
7172 if ( document . activeElement === topRef . current ) {
72- ( dropdownRef . current . firstChild as HTMLAnchorElement ) ?. focus ( ) ;
73+ ( dropdownRef . current ? .firstChild as HTMLAnchorElement ) ?. focus ( ) ;
7374 } else {
7475 findNext ( dropdownRef ) . focus ( ) ;
7576 }
7677 break ;
7778 case 'ArrowUp' :
7879 event . preventDefault ( ) ;
7980 if ( document . activeElement !== topRef . current ) {
80- findPrev ( topRef , dropdownRef ) . focus ( ) ;
81+ findPrev ( topRef , dropdownRef ) ? .focus ( ) ;
8182 }
8283 break ;
8384 case 'Escape' :
0 commit comments