-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathuseKeyboardNavigation.ts
More file actions
413 lines (392 loc) · 16.1 KB
/
useKeyboardNavigation.ts
File metadata and controls
413 lines (392 loc) · 16.1 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import type { FocusEventHandler, KeyboardEvent, KeyboardEventHandler, MutableRefObject } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { actions } from 'react-table';
import type { ColumnType, ReactTableHooks, TableInstance } from '../types/index.js';
import { getLeafHeaders, NAVIGATION_KEYS } from '../util/index.js';
const CELL_DATA_ATTRIBUTES = ['visibleColumnIndex', 'columnIndex', 'rowIndex', 'visibleRowIndex'];
const getFirstVisibleCell = (target, currentlyFocusedCell, noData) => {
if (
target.dataset.componentName === 'AnalyticalTableContainer' &&
target.querySelector('[data-component-name="AnalyticalTableBodyScrollableContainer"]')
) {
const rowElements = target.querySelector('[data-component-name="AnalyticalTableBodyScrollableContainer"]').children;
const middleRowCell = target.querySelector(
`div[data-visible-column-index="0"][data-visible-row-index="${Math.round(rowElements.length / 2)}"]`,
);
middleRowCell?.focus({ preventScroll: true });
} else {
const firstVisibleCell = noData
? target.querySelector(`div[data-visible-column-index="0"][data-visible-row-index="0"]`)
: target.querySelector(`div[data-visible-column-index="0"][data-visible-row-index="1"]`);
if (firstVisibleCell) {
firstVisibleCell.tabIndex = 0;
firstVisibleCell.focus();
currentlyFocusedCell.current = firstVisibleCell;
}
}
};
function recursiveSubComponentElementSearch(element: HTMLElement): HTMLElement | null {
if (!element.parentElement) {
return null;
}
if (element?.parentElement.dataset.subcomponent) {
return element.parentElement;
}
return recursiveSubComponentElementSearch(element.parentElement);
}
const findParentCell = (target: HTMLElement | undefined | null): HTMLElement | null | undefined => {
if (target === undefined || target === null) return;
if (
(target.dataset.rowIndex !== undefined && target.dataset.columnIndex !== undefined) ||
(target.dataset.rowIndexSub !== undefined && target.dataset.columnIndexSub !== undefined)
) {
return target;
} else {
return findParentCell(target.parentElement);
}
};
const setFocus = (currentlyFocusedCell: MutableRefObject<HTMLElement>, nextElement: HTMLElement | null) => {
currentlyFocusedCell.current.tabIndex = -1;
if (nextElement) {
nextElement.tabIndex = 0;
nextElement.focus();
currentlyFocusedCell.current = nextElement;
}
};
const navigateFromActiveSubCompItem = (currentlyFocusedCell: MutableRefObject<HTMLElement>, e: KeyboardEvent) => {
setFocus(currentlyFocusedCell, recursiveSubComponentElementSearch(e.target as HTMLElement));
};
const scrollToHorizontalEdgeAndFocus = (
tableRef: MutableRefObject<HTMLElement>,
scrollLeft: number,
targetSelector: string,
currentlyFocusedCell: MutableRefObject<HTMLElement>,
) => {
tableRef.current.scrollLeft = scrollLeft;
requestAnimationFrame(() => {
const el: HTMLElement | null = tableRef.current.querySelector(targetSelector);
if (el) {
setFocus(currentlyFocusedCell, el);
}
});
};
const useGetTableProps = (
tableProps,
{ instance: { webComponentsReactProperties, data, columns, state, visibleColumns } }: { instance: TableInstance },
) => {
const { showOverlay, tableRef } = webComponentsReactProperties;
const { isRtl } = state;
const currentlyFocusedCell = useRef<HTMLElement>(null);
const noData = data.length === 0;
useEffect(() => {
if (showOverlay && currentlyFocusedCell.current) {
currentlyFocusedCell.current.tabIndex = -1;
currentlyFocusedCell.current = null;
}
}, [showOverlay]);
const onTableBlur: FocusEventHandler<HTMLElement> = (e) => {
if (e.target.tagName === 'UI5-LI' || e.target.tagName === 'UI5-LI-CUSTOM') {
currentlyFocusedCell.current = null;
}
};
useEffect(() => {
if (
!showOverlay &&
data &&
columns &&
currentlyFocusedCell.current &&
tableRef.current &&
tableRef.current.tabIndex !== 0 &&
!tableRef.current.contains(currentlyFocusedCell.current)
) {
currentlyFocusedCell.current = null;
tableRef.current.tabIndex = 0;
}
}, [data, columns, showOverlay, tableRef]);
const onTableFocus = useCallback(
(e) => {
const { dataset } = e.target;
if (
dataset.emptyRowCell === 'true' ||
Object.prototype.hasOwnProperty.call(dataset, 'subcomponentActiveElement') ||
dataset.componentName === 'ATHeaderPopoverList' ||
dataset.componentName === 'ATHeaderPopover' ||
dataset.componentName === 'AnalyticalTableNoDataContainer'
) {
return;
}
if (e.target.dataset.subcomponent) {
e.target.tabIndex = 0;
e.target.focus();
currentlyFocusedCell.current = e.target;
return;
}
const isFirstCellAvailable = e.target.querySelector('div[data-column-index="0"][data-row-index="1"]');
if (e.target.dataset.componentName === 'AnalyticalTableContainer') {
e.target.tabIndex = -1;
if (currentlyFocusedCell.current) {
const { dataset } = currentlyFocusedCell.current;
const rowIndex = parseInt(dataset.rowIndex ?? dataset.rowIndexSub, 10);
const columnIndex = parseInt(dataset.columnIndex ?? dataset.columnIndexSub, 10);
if (
e.target.querySelector(`div[data-column-index="${columnIndex}"][data-row-index="${rowIndex}"]`) ||
e.target.querySelector(`div[data-column-index-sub="${columnIndex}"][data-row-index-sub="${rowIndex}"]`)
) {
currentlyFocusedCell.current.tabIndex = 0;
currentlyFocusedCell.current.focus({ preventScroll: true });
} else {
getFirstVisibleCell(e.target, currentlyFocusedCell, noData);
}
} else if (isFirstCellAvailable) {
const firstCell = e.target.querySelector(
'div[data-column-index]:not([data-column-id^="__ui5wcr__internal"][data-row-index="0"])',
);
firstCell.tabIndex = 0;
firstCell.focus({ preventScroll: true });
currentlyFocusedCell.current = firstCell;
} else {
getFirstVisibleCell(e.target, currentlyFocusedCell, noData);
}
} else {
const tableCell = findParentCell(e.target);
if (tableCell) {
currentlyFocusedCell.current = tableCell;
} else {
getFirstVisibleCell(tableRef.current, currentlyFocusedCell, noData);
}
}
},
[noData, tableRef],
);
const onKeyboardNavigation = useCallback(
(e) => {
const isActiveItemInSubComponent = Object.prototype.hasOwnProperty.call(
e.target.dataset,
'subcomponentActiveElement',
);
// check if target is cell and if so proceed from there
if (
!currentlyFocusedCell.current &&
CELL_DATA_ATTRIBUTES.every((item) => Object.keys(e.target.dataset).includes(item))
) {
currentlyFocusedCell.current = e.target;
}
if (currentlyFocusedCell.current) {
const columnIndex = parseInt(currentlyFocusedCell.current.dataset.columnIndex ?? '0', 10);
const rowIndex = parseInt(
currentlyFocusedCell.current.dataset.rowIndex ?? currentlyFocusedCell.current.dataset.subcomponentRowIndex,
10,
);
if (NAVIGATION_KEYS.has(e.key)) {
e.preventDefault();
}
switch (e.key) {
case 'End': {
const lastColumnIndex = visibleColumns.length - 1;
const targetSelector = `div[data-column-index="${lastColumnIndex}"][data-row-index="${rowIndex}"]`;
const newElement: HTMLElement | null = tableRef.current.querySelector(targetSelector);
if (newElement) {
setFocus(currentlyFocusedCell, newElement);
} else {
scrollToHorizontalEdgeAndFocus(
tableRef,
isRtl ? 0 : tableRef.current.scrollWidth,
targetSelector,
currentlyFocusedCell,
);
}
break;
}
case 'Home': {
const targetSelector = `div[data-column-index="0"][data-row-index="${rowIndex}"]`;
const newElement: HTMLElement | null = tableRef.current.querySelector(targetSelector);
if (newElement) {
setFocus(currentlyFocusedCell, newElement);
} else {
scrollToHorizontalEdgeAndFocus(
tableRef,
isRtl ? tableRef.current.scrollWidth : 0,
targetSelector,
currentlyFocusedCell,
);
}
break;
}
case 'PageDown': {
if (currentlyFocusedCell.current.dataset.rowIndex === '0') {
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex}"][data-row-index="${rowIndex + 1}"]`,
);
setFocus(currentlyFocusedCell, newElement);
} else {
const lastVisibleRow = tableRef.current.querySelector(`div[data-component-name="AnalyticalTableBody"]`)
?.children?.[0].children.length;
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex}"][data-visible-row-index="${lastVisibleRow}"]`,
);
setFocus(currentlyFocusedCell, newElement);
}
break;
}
case 'PageUp': {
if (currentlyFocusedCell.current.dataset.rowIndex <= '1') {
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex}"][data-row-index="0"]`,
);
setFocus(currentlyFocusedCell, newElement);
} else {
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex}"][data-visible-row-index="1"]`,
);
setFocus(currentlyFocusedCell, newElement);
}
break;
}
case 'ArrowRight': {
if (isActiveItemInSubComponent) {
navigateFromActiveSubCompItem(currentlyFocusedCell, e);
return;
}
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex + (isRtl ? -1 : 1)}"][data-row-index="${rowIndex}"]`,
);
if (newElement) {
setFocus(currentlyFocusedCell, newElement);
// scroll to show full cell if it's only partial visible
newElement.scrollIntoView({ block: 'nearest' });
}
break;
}
case 'ArrowLeft': {
if (isActiveItemInSubComponent) {
navigateFromActiveSubCompItem(currentlyFocusedCell, e);
return;
}
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex - (isRtl ? -1 : 1)}"][data-row-index="${rowIndex}"]`,
);
if (newElement) {
setFocus(currentlyFocusedCell, newElement);
// scroll to show full cell if it's only partial visible
newElement.scrollIntoView({ block: 'nearest' });
}
break;
}
case 'ArrowDown': {
if (isActiveItemInSubComponent) {
navigateFromActiveSubCompItem(currentlyFocusedCell, e);
return;
}
const parent = currentlyFocusedCell.current.parentElement as HTMLDivElement;
const firstChildOfParent = parent?.children?.[0] as HTMLDivElement;
const hasSubcomponent = firstChildOfParent?.dataset?.subcomponent;
const newElement: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex}"][data-row-index="${rowIndex + 1}"]`,
);
if (hasSubcomponent && !currentlyFocusedCell.current?.dataset?.subcomponent) {
currentlyFocusedCell.current.tabIndex = -1;
// Happens outside of React's scope
// eslint-disable-next-line react-hooks/immutability
firstChildOfParent.tabIndex = 0;
firstChildOfParent.dataset.rowIndexSub = `${rowIndex}`;
firstChildOfParent.dataset.columnIndexSub = `${columnIndex}`;
firstChildOfParent.focus();
currentlyFocusedCell.current = firstChildOfParent;
} else if (newElement) {
setFocus(currentlyFocusedCell, newElement);
}
break;
}
case 'ArrowUp': {
if (isActiveItemInSubComponent) {
navigateFromActiveSubCompItem(currentlyFocusedCell, e);
return;
}
let prevRowIndex = rowIndex - 1;
const isSubComponent = e.target.dataset.subcomponent;
if (isSubComponent) {
prevRowIndex++;
}
const previousRowCell: HTMLElement | null = tableRef.current.querySelector(
`div[data-column-index="${columnIndex}"][data-row-index="${prevRowIndex}"]`,
);
const firstChildPrevRow = previousRowCell?.parentElement.children[0] as HTMLDivElement;
const hasSubcomponent = firstChildPrevRow?.dataset?.subcomponent;
if (hasSubcomponent && !isSubComponent) {
currentlyFocusedCell.current.tabIndex = -1;
firstChildPrevRow.dataset.rowIndexSub = `${rowIndex - 1}`;
firstChildPrevRow.dataset.columnIndexSub = `${columnIndex}`;
firstChildPrevRow.tabIndex = 0;
firstChildPrevRow.focus();
currentlyFocusedCell.current = firstChildPrevRow;
} else if (previousRowCell) {
setFocus(currentlyFocusedCell, previousRowCell);
}
break;
}
}
}
},
[isRtl, tableRef, visibleColumns],
);
if (showOverlay) {
return tableProps;
}
// keyboard nav is only enabled if the table is not in edit mode
const handleEditModeKeyDown: KeyboardEventHandler<HTMLDivElement> = (e) => {
if (typeof tableProps.onKeyDown === 'function') {
tableProps.onKeyDown(e);
}
};
return [
tableProps,
{
onFocus: onTableFocus,
onKeyDown: state.cellContentTabIndex === 0 ? handleEditModeKeyDown : onKeyboardNavigation,
onBlur: onTableBlur,
},
];
};
function getPayload(e: KeyboardEvent, column: ColumnType) {
e.preventDefault();
e.stopPropagation();
const target = e.target as HTMLElement;
const clientX = target.getBoundingClientRect().x + target.getBoundingClientRect().width;
const columnId = column.id;
const columnWidth = column.totalWidth;
const headersToResize = getLeafHeaders(column);
const headerIdWidths = headersToResize.map((d) => [d.id, d.totalWidth, d.minWidth, d.maxWidth]);
return { clientX, columnId, columnWidth, headerIdWidths };
}
const setHeaderProps = (
headerProps,
{ instance: { dispatch }, column }: { instance: TableInstance; column: ColumnType },
) => {
// resize col with keyboard
const handleKeyDown: KeyboardEventHandler<HTMLElement> = (e) => {
if (typeof headerProps.onKeyDown === 'function') {
headerProps.onKeyDown(e);
}
if (e.nativeEvent.shiftKey) {
if (e.key === 'ArrowRight') {
const payload = getPayload(e, column);
dispatch({ type: actions.columnStartResizing, ...payload });
dispatch({ type: actions.columnResizing, clientX: payload.clientX + 16 });
dispatch({ type: actions.columnDoneResizing });
return;
}
if (e.key === 'ArrowLeft') {
const payload = getPayload(e, column);
dispatch({ type: actions.columnStartResizing, ...payload });
dispatch({ type: actions.columnResizing, clientX: payload.clientX - 16 });
dispatch({ type: actions.columnDoneResizing });
return;
}
}
};
return [headerProps, { onKeyDown: handleKeyDown }];
};
export const useKeyboardNavigation = (hooks: ReactTableHooks) => {
hooks.getTableProps.push(useGetTableProps);
hooks.getHeaderProps.push(setHeaderProps);
};