-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathtable.ts
More file actions
487 lines (431 loc) · 16.7 KB
/
table.ts
File metadata and controls
487 lines (431 loc) · 16.7 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {act, waitFor, within} from '@testing-library/react';
import {getAltKey, getMetaKey, pressElement, triggerLongPress} from './events';
import {GridRowActionOpts, TableTesterOpts, ToggleGridRowOpts, UserOpts} from './types';
interface TableToggleRowOpts extends ToggleGridRowOpts {}
interface TableToggleSortOpts {
/**
* The index, text, or node of the column to toggle selection for.
*/
column: number | string | HTMLElement,
/**
* What interaction type to use when sorting the column. Defaults to the interaction type set on the tester.
*/
interactionType?: UserOpts['interactionType']
}
interface TableColumnHeaderActionOpts extends TableToggleSortOpts {
/**
* The index of the column header action to trigger.
*/
action: number
}
interface TableRowActionOpts extends GridRowActionOpts {}
export class TableTester {
private user;
private _interactionType: UserOpts['interactionType'];
private _advanceTimer: UserOpts['advanceTimer'];
private _table: HTMLElement;
constructor(opts: TableTesterOpts) {
let {root, user, interactionType, advanceTimer} = opts;
this.user = user;
this._interactionType = interactionType || 'mouse';
this._advanceTimer = advanceTimer;
this._table = root;
}
/**
* Set the interaction type used by the table tester.
*/
setInteractionType(type: UserOpts['interactionType']): void {
this._interactionType = type;
}
// TODO: RTL
private async keyboardNavigateToRow(opts: {row: HTMLElement, selectionOnNav?: 'default' | 'none'}) {
let {row, selectionOnNav = 'default'} = opts;
let altKey = getAltKey();
let rows = this.rows;
let targetIndex = rows.indexOf(row);
if (targetIndex === -1) {
throw new Error('Row provided is not in the table');
}
// Move focus into the table
if (document.activeElement !== this._table && !this._table.contains(document.activeElement)) {
act(() => this._table.focus());
}
if (document.activeElement === this._table) {
await this.user.keyboard('[ArrowDown]');
}
// If focus is currently somewhere in the first row group (aka on a column), we want to keyboard navigate downwards till we reach the rows
if (this.rowGroups[0].contains(document.activeElement)) {
do {
await this.user.keyboard('[ArrowDown]');
} while (!this.rowGroups[1].contains(document.activeElement));
}
// Move focus onto the row itself
if (this.rowGroups[1].contains(document.activeElement) && document.activeElement!.getAttribute('role') !== 'row') {
do {
await this.user.keyboard('[ArrowLeft]');
} while (document.activeElement!.getAttribute('role') !== 'row');
}
let currIndex = rows.indexOf(document.activeElement as HTMLElement);
if (currIndex === -1) {
throw new Error('Current active element is not on any of the table rows');
}
let direction = targetIndex > currIndex ? 'down' : 'up';
if (selectionOnNav === 'none') {
await this.user.keyboard(`[${altKey}>]`);
}
for (let i = 0; i < Math.abs(targetIndex - currIndex); i++) {
await this.user.keyboard(`[${direction === 'down' ? 'ArrowDown' : 'ArrowUp'}]`);
}
if (selectionOnNav === 'none') {
await this.user.keyboard(`[/${altKey}]`);
}
};
/**
* Toggles the selection for the specified table row. Defaults to using the interaction type set on the table tester.
*/
async toggleRowSelection(opts: TableToggleRowOpts): Promise<void> {
let {
row,
needsLongPress,
checkboxSelection = true,
interactionType = this._interactionType,
selectionBehavior = 'toggle'
} = opts;
let altKey = getMetaKey();
let metaKey = getMetaKey();
if (typeof row === 'string' || typeof row === 'number') {
row = this.findRow({rowIndexOrText: row});
}
if (!row) {
throw new Error('Target row not found in the table.');
}
let rowCheckbox = within(row).queryByRole('checkbox');
if (interactionType === 'keyboard' && (!checkboxSelection || !rowCheckbox)) {
await this.keyboardNavigateToRow({row, selectionOnNav: selectionBehavior === 'replace' ? 'none' : 'default'});
if (selectionBehavior === 'replace') {
await this.user.keyboard(`[${altKey}>]`);
}
await this.user.keyboard('[Space]');
if (selectionBehavior === 'replace') {
await this.user.keyboard(`[/${altKey}]`);
}
return;
}
if (rowCheckbox && checkboxSelection) {
await pressElement(this.user, rowCheckbox, interactionType);
} else {
let cell = within(row).getAllByRole('gridcell')[0];
if (needsLongPress && interactionType === 'touch') {
if (this._advanceTimer == null) {
throw new Error('No advanceTimers provided for long press.');
}
// Note that long press interactions with rows is strictly touch only for grid rows
await triggerLongPress({element: cell, advanceTimer: this._advanceTimer, pointerOpts: {pointerType: 'touch'}});
} else {
if (selectionBehavior === 'replace' && interactionType !== 'touch') {
await this.user.keyboard(`[${metaKey}>]`);
}
await pressElement(this.user, cell, interactionType);
if (selectionBehavior === 'replace' && interactionType !== 'touch') {
await this.user.keyboard(`[/${metaKey}]`);
}
}
}
};
/**
* Toggles the sort order for the specified table column. Defaults to using the interaction type set on the table tester.
*/
async toggleSort(opts: TableToggleSortOpts): Promise<void> {
let {
column,
interactionType = this._interactionType
} = opts;
let columnheader;
if (typeof column === 'number') {
columnheader = this.columns[column];
} else if (typeof column === 'string') {
columnheader = within(this.rowGroups[0]).getByText(column);
while (columnheader && !/columnheader/.test(columnheader.getAttribute('role'))) {
columnheader = columnheader.parentElement;
}
} else {
columnheader = column;
}
let menuButton = within(columnheader).queryByRole('button');
if (menuButton) {
let currentSort = columnheader.getAttribute('aria-sort');
// TODO: Focus management is all kinda of messed up if I just use .focus and Space to open the sort menu. Seems like
// the focused key doesn't get properly set to the desired column header. Have to do this strange flow where I focus the
// column header except if the active element is already the menu button within the column header
if (interactionType === 'keyboard' && document.activeElement !== menuButton) {
await pressElement(this.user, columnheader, interactionType);
} else {
await pressElement(this.user, menuButton, interactionType);
}
await waitFor(() => {
if (menuButton.getAttribute('aria-controls') == null) {
throw new Error('No aria-controls found on table column dropdown menu trigger element.');
} else {
return true;
}
});
let menuId = menuButton.getAttribute('aria-controls');
await waitFor(() => {
if (!menuId || document.getElementById(menuId) == null) {
throw new Error(`Table column header menu with id of ${menuId} not found in document.`);
} else {
return true;
}
});
if (menuId) {
let menu = document.getElementById(menuId);
if (menu) {
if (currentSort === 'ascending') {
await pressElement(this.user, within(menu).getAllByRole('menuitem')[1], interactionType);
} else {
await pressElement(this.user, within(menu).getAllByRole('menuitem')[0], interactionType);
}
await waitFor(() => {
if (document.contains(menu)) {
throw new Error('Expected table column menu listbox to not be in the document after selecting an option');
} else {
return true;
}
});
}
}
// Handle cases where the table may transition in response to the row selection/deselection
if (!this._advanceTimer) {
throw new Error('No advanceTimers provided for table transition.');
}
await act(async () => {
await this._advanceTimer?.(200);
});
await waitFor(() => {
if (document.activeElement !== menuButton) {
throw new Error(`Expected the document.activeElement to be the table column menu button but got ${document.activeElement}`);
} else {
return true;
}
});
} else {
await pressElement(this.user, columnheader, interactionType);
}
}
/**
* Triggers an action for the specified table column menu. Defaults to using the interaction type set on the table tester.
*/
async triggerColumnHeaderAction(opts: TableColumnHeaderActionOpts): Promise<void> {
let {
column,
interactionType = this._interactionType,
action
} = opts;
let columnheader;
if (typeof column === 'number') {
columnheader = this.columns[column];
} else if (typeof column === 'string') {
columnheader = within(this.rowGroups[0]).getByText(column);
while (columnheader && !/columnheader/.test(columnheader.getAttribute('role'))) {
columnheader = columnheader.parentElement;
}
} else {
columnheader = column;
}
let menuButton = within(columnheader).queryByRole('button');
if (menuButton) {
// TODO: Focus management is all kinda of messed up if I just use .focus and Space to open the sort menu. Seems like
// the focused key doesn't get properly set to the desired column header. Have to do this strange flow where I focus the
// column header except if the active element is already the menu button within the column header
if (interactionType === 'keyboard' && document.activeElement !== menuButton) {
await pressElement(this.user, columnheader, interactionType);
} else {
await pressElement(this.user, menuButton, interactionType);
}
await waitFor(() => {
if (menuButton.getAttribute('aria-controls') == null) {
throw new Error('No aria-controls found on table column dropdown menu trigger element.');
} else {
return true;
}
});
let menuId = menuButton.getAttribute('aria-controls');
await waitFor(() => {
if (!menuId || document.getElementById(menuId) == null) {
throw new Error(`Table column header menu with id of ${menuId} not found in document.`);
} else {
return true;
}
});
if (menuId) {
let menu = document.getElementById(menuId);
if (menu) {
await pressElement(this.user, within(menu).getAllByRole('menuitem')[action], interactionType);
await waitFor(() => {
if (document.contains(menu)) {
throw new Error('Expected table column menu listbox to not be in the document after selecting an option');
} else {
return true;
}
});
}
}
// Handle cases where the table may transition in response to the row selection/deselection
if (!this._advanceTimer) {
throw new Error('No advanceTimers provided for table transition.');
}
await act(async () => {
await this._advanceTimer?.(200);
});
await waitFor(() => {
if (document.activeElement !== menuButton) {
throw new Error(`Expected the document.activeElement to be the table column menu button but got ${document.activeElement}`);
} else {
return true;
}
});
} else {
throw new Error('No menu button found on table column header.');
}
}
/**
* Triggers the action for the specified table row. Defaults to using the interaction type set on the table tester.
*/
async triggerRowAction(opts: TableRowActionOpts): Promise<void> {
let {
row,
needsDoubleClick,
interactionType = this._interactionType
} = opts;
if (typeof row === 'string' || typeof row === 'number') {
row = this.findRow({rowIndexOrText: row});
}
if (!row) {
throw new Error('Target row not found in the table.');
}
if (needsDoubleClick) {
await this.user.dblClick(row);
} else if (interactionType === 'keyboard') {
await this.keyboardNavigateToRow({row, selectionOnNav: 'none'});
await this.user.keyboard('[Enter]');
} else {
await pressElement(this.user, row, interactionType);
}
}
// TODO: should there be utils for drag and drop and column resizing? For column resizing, I'm not entirely convinced that users will be doing that in their tests.
// For DnD, it might be tricky to do for keyboard DnD since we wouldn't know what valid drop zones there are... Similarly, for simulating mouse drag and drop the coordinates depend
// on the mocks the user sets up for their row height/etc.
// Additionally, should we also support keyboard navigation/typeahead? Those felt like they could be very easily replicated by the user via user.keyboard already and don't really
// add much value if we provide that to them
/**
* Toggle selection for all rows in the table. Defaults to using the interaction type set on the table tester.
*/
async toggleSelectAll(opts: {interactionType?: UserOpts['interactionType']} = {}): Promise<void> {
let {
interactionType = this._interactionType
} = opts;
let checkbox = within(this.table).getByLabelText('Select All');
if (interactionType === 'keyboard') {
// TODO: using the .focus -> trigger keyboard Enter approach doesn't work for some reason, for now just trigger select all with click.
await this.user.click(checkbox);
} else {
await pressElement(this.user, checkbox, interactionType);
}
}
/**
* Returns a row matching the specified index or text content.
*/
findRow(opts: {rowIndexOrText: number | string}): HTMLElement {
let {
rowIndexOrText
} = opts;
let row;
let rows = this.rows;
let bodyRowGroup = this.rowGroups[1];
if (typeof rowIndexOrText === 'number') {
row = rows[rowIndexOrText];
} else if (typeof rowIndexOrText === 'string') {
row = within(bodyRowGroup).getByText(rowIndexOrText);
while (row && row.getAttribute('role') !== 'row') {
row = row.parentElement;
}
}
return row;
}
/**
* Returns a cell matching the specified text content.
*/
findCell(opts: {text: string}): HTMLElement {
let {
text
} = opts;
let cell = within(this.table).getByText(text);
if (cell) {
while (cell && !/gridcell|rowheader|columnheader/.test(cell.getAttribute('role') || '')) {
if (cell.parentElement) {
cell = cell.parentElement;
} else {
break;
}
}
}
return cell;
}
/**
* Returns the table.
*/
get table(): HTMLElement {
return this._table;
}
/**
* Returns the row groups within the table.
*/
get rowGroups(): HTMLElement[] {
let table = this._table;
return table ? within(table).queryAllByRole('rowgroup') : [];
}
/**
* Returns the columns within the table.
*/
get columns(): HTMLElement[] {
let headerRowGroup = this.rowGroups[0];
return headerRowGroup ? within(headerRowGroup).queryAllByRole('columnheader') : [];
}
/**
* Returns the rows within the table if any.
*/
get rows(): HTMLElement[] {
let bodyRowGroup = this.rowGroups[1];
return bodyRowGroup ? within(bodyRowGroup).queryAllByRole('row') : [];
}
/**
* Returns the currently selected rows within the table if any.
*/
get selectedRows(): HTMLElement[] {
return this.rows.filter(row => row.getAttribute('aria-selected') === 'true');
}
/**
* Returns the row headers within the table if any.
*/
get rowHeaders(): HTMLElement[] {
return within(this.table).queryAllByRole('rowheader');
}
/**
* Returns the cells within the table if any. Can be filtered against a specific row if provided via `element`.
*/
cells(opts: {element?: HTMLElement} = {}): HTMLElement[] {
let {element = this.table} = opts;
return within(element).queryAllByRole('gridcell');
}
}