@@ -37,47 +37,46 @@ const AccessibleList: React.FunctionComponent<AccessibleListProps> = (
3737 } , [ refArray , current , props . focusFirstItem ] ) ;
3838
3939 const handleKeyDown = ( e : KeyboardEvent ) => {
40- if (
41- e . key === KeyboardKeys . DownArrow &&
42- current === refArray . length - 1
43- ) {
44- e . preventDefault ( ) ;
45- setCurrent ( 0 ) ;
46- return ;
47- }
48-
49- if ( e . key === KeyboardKeys . UpArrow && current === 0 ) {
50- e . preventDefault ( ) ;
51- setCurrent ( refArray . length - 1 ) ;
52- return ;
40+ switch ( e . key ) {
41+ case KeyboardKeys . UpArrow : {
42+ handleUpArrowPress ( e ) ;
43+ break ;
44+ }
45+ case KeyboardKeys . DownArrow : {
46+ handleDownArrowPress ( e ) ;
47+ break ;
48+ }
49+ case KeyboardKeys . Escape : {
50+ handleEscapePress ( e ) ;
51+ break ;
52+ }
53+ default : {
54+ return ;
55+ }
5356 }
57+ } ;
5458
55- if (
56- e . key === KeyboardKeys . DownArrow &&
57- current !== refArray . length - 1
58- ) {
59- e . preventDefault ( ) ;
60-
61- setCurrent ( current + 1 ) ;
62- return ;
63- }
59+ const handleDownArrowPress = ( e : KeyboardEvent ) => {
60+ const isLastElementFocused = current === refArray . length - 1 ;
61+ const indexToFocus = isLastElementFocused ? 0 : current + 1 ;
6462
65- if ( e . key === KeyboardKeys . UpArrow && current !== 0 ) {
66- e . preventDefault ( ) ;
63+ setCurrentAndPreventDefault ( e , indexToFocus ) ;
64+ } ;
6765
68- setCurrent ( current - 1 ) ;
69- return ;
66+ const handleEscapePress = ( e : KeyboardEvent ) => {
67+ setCurrentAndPreventDefault ( e , 0 ) ;
68+ if ( props . onEsc != null ) {
69+ props . onEsc ( ) ;
7070 }
71+ } ;
7172
72- if ( e . key === KeyboardKeys . Escape ) {
73- e . preventDefault ( ) ;
74- setCurrent ( 0 ) ;
73+ const handleUpArrowPress = ( e : KeyboardEvent ) => {
74+ const isFirstElementFocused = current === 0 ;
75+ const indexToFocus = isFirstElementFocused
76+ ? refArray . length - 1
77+ : current - 1 ;
7578
76- if ( props . onEsc != null ) {
77- props . onEsc ( ) ;
78- }
79- return ;
80- }
79+ setCurrentAndPreventDefault ( e , indexToFocus ) ;
8180 } ;
8281
8382 const renderChildren = ( ) => {
@@ -100,6 +99,17 @@ const AccessibleList: React.FunctionComponent<AccessibleListProps> = (
10099 } ) ;
101100 } ;
102101
102+ const setCurrentAndPreventDefault = (
103+ e : KeyboardEvent ,
104+ indexToFocus : number
105+ ) => {
106+ if ( indexToFocus < 0 ) {
107+ return ;
108+ }
109+ e . preventDefault ( ) ;
110+ setCurrent ( indexToFocus ) ;
111+ } ;
112+
103113 return < React . Fragment > { renderChildren ( ) } </ React . Fragment > ;
104114} ;
105115
0 commit comments