-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathmenu.ts
More file actions
449 lines (401 loc) · 15.1 KB
/
menu.ts
File metadata and controls
449 lines (401 loc) · 15.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
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
/*
* 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} from './act';
import {MenuTesterOpts, UserOpts} from './types';
import {triggerLongPress} from './events';
import {waitFor, within} from '@testing-library/dom';
interface MenuOpenOpts {
/**
* Whether the menu needs to be long pressed to open.
*/
needsLongPress?: boolean,
/**
* What interaction type to use when opening the menu. Defaults to the interaction type set on the tester.
*/
interactionType?: UserOpts['interactionType'],
/**
* Whether to open the menu via ArrowUp or ArrowDown if in keyboard modality.
*/
direction?: 'up' | 'down'
}
interface MenuSelectOpts extends MenuOpenOpts {
/**
* The index, text, or node of the option to select. Option nodes can be sourced via `options()`.
*/
option: number | string | HTMLElement,
/**
* The menu's selection mode. Will affect whether or not the menu is expected to be closed upon option selection.
* @default 'single'
*/
menuSelectionMode?: 'single' | 'multiple',
/**
* Whether or not the menu closes on select. Depends on menu implementation and configuration.
* @default true
*/
closesOnSelect?: boolean,
/**
* Whether the option should be triggered by Space or Enter in keyboard modality.
* @default 'Enter'
*/
keyboardActivation?: 'Space' | 'Enter'
}
interface MenuOpenSubmenuOpts extends MenuOpenOpts {
/**
* The text or node of the submenu trigger to open. Available submenu trigger nodes can be sourced via `submenuTriggers`.
*/
submenuTrigger: string | HTMLElement
}
export class MenuTester {
private user;
private _interactionType: UserOpts['interactionType'];
private _advanceTimer: UserOpts['advanceTimer'];
private _trigger: HTMLElement | undefined;
private _isSubmenu: boolean = false;
private _rootMenu: HTMLElement | undefined;
constructor(opts: MenuTesterOpts) {
let {root, user, interactionType, advanceTimer, isSubmenu, rootMenu} = opts;
this.user = user;
this._interactionType = interactionType || 'mouse';
this._advanceTimer = advanceTimer;
// Handle case where a submenu trigger is provided to the tester
if (root.getAttribute('role') === 'menuitem') {
this._trigger = root;
} else {
// Handle case where element provided is a wrapper of the trigger button
let trigger = within(root).queryByRole('button');
if (trigger) {
this._trigger = trigger;
} else {
this._trigger = root;
}
}
this._isSubmenu = isSubmenu || false;
this._rootMenu = rootMenu;
}
/**
* Set the interaction type used by the menu tester.
*/
setInteractionType(type: UserOpts['interactionType']): void {
this._interactionType = type;
}
// TODO: this has been common to select as well, maybe make select use it? Or make a generic method. Will need to make error messages generic
// One difference will be that it supports long press as well
/**
* Opens the menu. Defaults to using the interaction type set on the menu tester.
*/
async open(opts: MenuOpenOpts = {}): Promise<void> {
let {
needsLongPress,
interactionType = this._interactionType,
direction
} = opts;
let trigger = this.trigger;
let isDisabled = trigger.hasAttribute('disabled');
if (interactionType === 'mouse' || interactionType === 'touch') {
if (needsLongPress) {
if (this._advanceTimer == null) {
throw new Error('No advanceTimers provided for long press.');
}
let pointerType = interactionType === 'mouse' ? 'mouse' : 'touch';
await triggerLongPress({element: trigger, advanceTimer: this._advanceTimer, pointerOpts: {pointerType}});
} else if (interactionType === 'mouse') {
await this.user.click(trigger);
} else {
await this.user.pointer({target: trigger, keys: '[TouchA]'});
}
} else if (interactionType === 'keyboard' && !isDisabled) {
if (direction === 'up') {
act(() => trigger.focus());
await this.user.keyboard('[ArrowUp]');
} else if (direction === 'down') {
act(() => trigger.focus());
await this.user.keyboard('[ArrowDown]');
} else {
act(() => trigger.focus());
await this.user.keyboard('[Enter]');
}
}
await waitFor(() => {
if (trigger.getAttribute('aria-controls') == null && !isDisabled) {
throw new Error('No aria-controls found on menu trigger element.');
} else {
return true;
}
});
if (!isDisabled) {
let menuId = trigger.getAttribute('aria-controls');
await waitFor(() => {
if (!menuId || document.getElementById(menuId) == null) {
throw new Error(`Menu with id of ${menuId} not found in document.`);
} else {
return true;
}
});
}
}
/**
* Returns a option matching the specified index or text content.
*/
findOption(opts: {optionIndexOrText: number | string}): HTMLElement {
let {
optionIndexOrText
} = opts;
let option;
let options = this.options();
let menu = this.menu;
if (typeof optionIndexOrText === 'number') {
option = options[optionIndexOrText];
} else if (typeof optionIndexOrText === 'string' && menu != null) {
option = (within(menu!).getByText(optionIndexOrText).closest('[role=menuitem], [role=menuitemradio], [role=menuitemcheckbox]'))! as HTMLElement;
}
return option;
}
// TODO: also very similar to select, barring potential long press support
// Close on select is also kinda specific?
/**
* Selects the desired menu option. Defaults to using the interaction type set on the menu tester. If necessary, will open the menu dropdown beforehand.
* The desired option can be targeted via the option's node, the option's text, or the option's index.
*/
async selectOption(opts: MenuSelectOpts): Promise<void> {
let {
menuSelectionMode = 'single',
needsLongPress,
closesOnSelect = true,
option,
interactionType = this._interactionType,
keyboardActivation = 'Enter'
} = opts;
let trigger = this.trigger;
if (!trigger.getAttribute('aria-controls') && !trigger.hasAttribute('aria-expanded')) {
await this.open({needsLongPress});
}
let menu = this.menu;
if (!menu) {
throw new Error('Menu not found.');
}
if (menu) {
if (typeof option === 'string' || typeof option === 'number') {
option = this.findOption({optionIndexOrText: option});
}
if (!option) {
throw new Error('Target option not found in the menu.');
}
if (interactionType === 'keyboard') {
if (option?.getAttribute('aria-disabled') === 'true') {
return;
}
if (document.activeElement !== menu && !menu.contains(document.activeElement)) {
act(() => menu.focus());
}
await this.keyboardNavigateToOption({option});
await this.user.keyboard(`[${keyboardActivation}]`);
} else {
if (interactionType === 'mouse') {
await this.user.click(option);
} else {
await this.user.pointer({target: option, keys: '[TouchA]'});
}
}
// This chain of waitFors is needed in place of running all timers since we don't know how long transitions may take, or what action
// the menu option select may trigger.
if (
!(menuSelectionMode === 'single' && !closesOnSelect) &&
!(menuSelectionMode === 'multiple' && (keyboardActivation === 'Space' || interactionType === 'mouse'))
) {
// For RSP, clicking on a submenu option seems to briefly lose focus to the body before moving to the clicked option in the test so we need to wait
// for focus to be coerced to somewhere else in place of running all timers.
if (this._isSubmenu) {
await waitFor(() => {
if (document.activeElement === document.body) {
throw new Error('Expected focus to move to somewhere other than the body after selecting a submenu option.');
} else {
return true;
}
});
}
// If user isn't trying to select multiple menu options or closeOnSelect is true then we can assume that
// the menu will close or some action is triggered. In cases like that focus should move somewhere after the menu closes
// but we can't really know where so just make sure it doesn't get lost to the body.
await waitFor(() => {
if (document.activeElement === option) {
throw new Error('Expected focus after selecting an option to move away from the option.');
} else {
return true;
}
});
// We'll also want to wait for focus to move away from the original submenu trigger since the entire submenu tree should
// close. In React 16, focus actually makes it all the way to the root menu's submenu trigger so we need check the root menu
if (this._isSubmenu) {
await waitFor(() => {
if (document.activeElement === this.trigger || this._rootMenu?.contains(document.activeElement)) {
throw new Error('Expected focus after selecting an submenu option to move away from the original submenu trigger.');
} else {
return true;
}
});
}
// Finally wait for focus to be coerced somewhere final when the menu tree is removed from the DOM
await waitFor(() => {
if (document.activeElement === document.body) {
throw new Error('Expected focus to move to somewhere other than the body after selecting a menu option.');
} else {
return true;
}
});
}
} else {
throw new Error("Attempted to select a option in the menu, but menu wasn't found.");
}
}
// TODO: update this to remove needsLongPress if we wanna make the user call open first always
/**
* Opens the submenu. Defaults to using the interaction type set on the menu tester. The submenu trigger can be targeted via the trigger's node or the trigger's text.
*/
async openSubmenu(opts: MenuOpenSubmenuOpts): Promise<MenuTester | null> {
let {
submenuTrigger,
needsLongPress,
interactionType = this._interactionType
} = opts;
let trigger = this.trigger;
let isDisabled = trigger.hasAttribute('disabled');
if (!trigger.getAttribute('aria-controls') && !isDisabled) {
await this.open({needsLongPress});
}
if (!isDisabled) {
let menu = this.menu;
if (menu) {
if (typeof submenuTrigger === 'string') {
submenuTrigger = (within(menu!).getByText(submenuTrigger).closest('[role=menuitem]'))! as HTMLElement;
}
let submenuTriggerTester = new MenuTester({
user: this.user,
interactionType: this._interactionType,
root: submenuTrigger,
isSubmenu: true,
advanceTimer: this._advanceTimer,
rootMenu: (this._isSubmenu ? this._rootMenu : this.menu) || undefined
});
if (interactionType === 'mouse') {
await this.user.pointer({target: submenuTrigger});
} else if (interactionType === 'keyboard') {
await this.keyboardNavigateToOption({option: submenuTrigger});
await this.user.keyboard('[ArrowRight]');
} else {
await submenuTriggerTester.open();
}
await waitFor(() => {
if (submenuTriggerTester._trigger?.getAttribute('aria-expanded') !== 'true') {
throw new Error('aria-expanded for the submenu trigger wasn\'t changed to "true", unable to confirm the existance of the submenu');
} else {
return true;
}
});
return submenuTriggerTester;
}
}
return null;
}
private async keyboardNavigateToOption(opts: {option: HTMLElement}) {
let {option} = opts;
let options = this.options();
let targetIndex = options.findIndex(opt => (opt === option) || opt.contains(option));
if (targetIndex === -1) {
throw new Error('Option provided is not in the menu');
}
if (document.activeElement === this.menu) {
await this.user.keyboard('[ArrowDown]');
}
let currIndex = options.indexOf(document.activeElement as HTMLElement);
if (currIndex === -1) {
throw new Error('ActiveElement is not in the menu');
}
let direction = targetIndex > currIndex ? 'down' : 'up';
for (let i = 0; i < Math.abs(targetIndex - currIndex); i++) {
await this.user.keyboard(`[${direction === 'down' ? 'ArrowDown' : 'ArrowUp'}]`);
}
};
/**
* Closes the menu.
*/
async close(): Promise<void> {
let menu = this.menu;
if (menu) {
act(() => menu.focus());
await this.user.keyboard('[Escape]');
await waitFor(() => {
if (document.activeElement !== this.trigger) {
throw new Error(`Expected the document.activeElement after closing the menu to be the menu trigger but got ${document.activeElement}`);
} else {
return true;
}
});
if (document.contains(menu)) {
throw new Error('Expected the menu to not be in the document after closing it.');
}
}
}
/**
* Returns the menu's trigger.
*/
get trigger(): HTMLElement {
if (!this._trigger) {
throw new Error('No trigger element found for menu.');
}
return this._trigger;
}
/**
* Returns the menu if present.
*/
get menu(): HTMLElement | null {
let menuId = this.trigger.getAttribute('aria-controls');
return menuId ? document.getElementById(menuId) : null;
}
/**
* Returns the menu's sections if any.
*/
get sections(): HTMLElement[] {
let menu = this.menu;
if (menu) {
return within(menu).queryAllByRole('group');
} else {
return [];
}
}
/**
* Returns the menu's options if present. Can be filtered to a subsection of the menu if provided via `element`.
*/
options(opts: {element?: HTMLElement} = {}): HTMLElement[] {
let {element = this.menu} = opts;
let options: HTMLElement[] = [];
if (element) {
options = within(element).queryAllByRole('menuitem');
if (options.length === 0) {
options = within(element).queryAllByRole('menuitemradio');
if (options.length === 0) {
options = within(element).queryAllByRole('menuitemcheckbox');
}
}
}
return options;
}
/**
* Returns the menu's submenu triggers if any.
*/
get submenuTriggers(): HTMLElement[] {
let options = this.options();
if (options.length > 0) {
return options.filter(item => item.getAttribute('aria-haspopup') != null);
}
return [];
}
}