@@ -48,3 +48,50 @@ export const openEditingCell = <TData extends MRT_RowData>({
48
48
} ) ;
49
49
}
50
50
} ;
51
+
52
+ export const navigateToNextCell = (
53
+ e : React . KeyboardEvent < HTMLTableCellElement > ,
54
+ ) => {
55
+ if ( [ 'ArrowRight' , 'ArrowLeft' , 'ArrowUp' , 'ArrowDown' ] . includes ( e . key ) ) {
56
+ e . preventDefault ( ) ;
57
+ const currentCell = e . currentTarget ;
58
+ const tableElement = currentCell . closest ( 'table' ) ;
59
+ if ( ! tableElement ) return ;
60
+
61
+ const currentIndex = parseInt (
62
+ currentCell . getAttribute ( 'data-index' ) || '0' ,
63
+ ) ;
64
+ let nextCell : HTMLElement | undefined = undefined ;
65
+
66
+ const findNextCell = ( index : number , searchDirection : 'f' | 'b' ) => {
67
+ const allCells = Array . from ( tableElement . querySelectorAll ( 'th, td' ) ) ;
68
+ const currentCellIndex = allCells . indexOf ( currentCell ) ;
69
+ const searchArray =
70
+ searchDirection === 'f'
71
+ ? allCells . slice ( currentCellIndex + 1 )
72
+ : allCells . slice ( 0 , currentCellIndex ) . reverse ( ) ;
73
+ return searchArray . find ( ( cell ) =>
74
+ cell . matches ( `[data-index="${ index } "]` ) ,
75
+ ) as HTMLElement | undefined ;
76
+ } ;
77
+
78
+ switch ( e . key ) {
79
+ case 'ArrowRight' :
80
+ nextCell = findNextCell ( currentIndex + 1 , 'f' ) ;
81
+ break ;
82
+ case 'ArrowLeft' :
83
+ nextCell = findNextCell ( currentIndex - 1 , 'b' ) ;
84
+ break ;
85
+ case 'ArrowUp' :
86
+ nextCell = findNextCell ( currentIndex , 'b' ) ;
87
+ break ;
88
+ case 'ArrowDown' :
89
+ nextCell = findNextCell ( currentIndex , 'f' ) ;
90
+ break ;
91
+ }
92
+
93
+ if ( nextCell ) {
94
+ nextCell . focus ( ) ;
95
+ }
96
+ }
97
+ } ;
0 commit comments