-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathselect.ts
More file actions
268 lines (237 loc) · 8.67 KB
/
select.ts
File metadata and controls
268 lines (237 loc) · 8.67 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
/*
* 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 {SelectTesterOpts, UserOpts} from './types';
import {waitFor, within} from '@testing-library/dom';
interface SelectOpenOpts {
/**
* What interaction type to use when opening the select. Defaults to the interaction type set on the tester.
*/
interactionType?: UserOpts['interactionType']
}
interface SelectTriggerOptionOpts extends SelectOpenOpts {
/**
* The index, text, or node of the option to select. Option nodes can be sourced via `options()`.
*/
option: number | string | HTMLElement,
/**
* Whether or not the select closes on selection. Depends on select implementation and configuration.
* @default true
*/
closesOnSelect?: boolean
}
export class SelectTester {
private user;
private _interactionType: UserOpts['interactionType'];
private _trigger: HTMLElement;
constructor(opts: SelectTesterOpts) {
let {root, user, interactionType} = opts;
this.user = user;
this._interactionType = interactionType || 'mouse';
// Handle case where the wrapper element is provided rather than the Select's button (aka RAC)
let buttons = within(root).queryAllByRole('button');
let triggerButton;
if (buttons.length === 0) {
triggerButton = root;
} else if (buttons.length === 1) {
triggerButton = buttons[0];
} else {
triggerButton = buttons.find(button => button.hasAttribute('aria-haspopup'));
}
this._trigger = triggerButton ?? root;
}
/**
* Set the interaction type used by the select tester.
*/
setInteractionType(type: UserOpts['interactionType']): void {
this._interactionType = type;
}
/**
* Opens the select. Defaults to using the interaction type set on the select tester.
*/
async open(opts: SelectOpenOpts = {}): Promise<void> {
let {
interactionType = this._interactionType
} = opts;
let trigger = this.trigger;
let isDisabled = trigger.hasAttribute('disabled');
if (interactionType === 'mouse') {
await this.user.click(this._trigger);
} else if (interactionType === 'keyboard') {
act(() => trigger.focus());
await this.user.keyboard('[Enter]');
} else if (interactionType === 'touch') {
await this.user.pointer({target: this._trigger, keys: '[TouchA]'});
}
await waitFor(() => {
if (!isDisabled && trigger.getAttribute('aria-controls') == null) {
throw new Error('No aria-controls found on select element trigger.');
} else {
return true;
}
});
let listBoxId = trigger.getAttribute('aria-controls');
await waitFor(() => {
if (!isDisabled && (!listBoxId || document.getElementById(listBoxId) == null)) {
throw new Error(`ListBox with id of ${listBoxId} not found in document.`);
} else {
return true;
}
});
}
/**
* Closes the select.
*/
async close(): Promise<void> {
let listbox = this.listbox;
if (listbox) {
act(() => listbox.focus());
await this.user.keyboard('[Escape]');
}
await waitFor(() => {
if (document.activeElement !== this._trigger) {
throw new Error(`Expected the document.activeElement after closing the select dropdown to be the select component trigger but got ${document.activeElement}`);
} else {
return true;
}
});
if (listbox && document.contains(listbox)) {
throw new Error('Expected the select element listbox to not be in the document after closing the dropdown.');
}
}
/**
* 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 listbox = this.listbox;
if (typeof optionIndexOrText === 'number') {
option = options[optionIndexOrText];
} else if (typeof optionIndexOrText === 'string' && listbox != null) {
option = (within(listbox!).getByText(optionIndexOrText).closest('[role=option]'))! as HTMLElement;
}
return option;
}
private async keyboardNavigateToOption(opts: {option: HTMLElement}) {
let {option} = opts;
let options = this.options();
let targetIndex = options.indexOf(option);
if (targetIndex === -1) {
throw new Error('Option provided is not in the listbox');
}
if (document.activeElement === this.listbox) {
await this.user.keyboard('[ArrowDown]');
}
let currIndex = options.indexOf(document.activeElement as HTMLElement);
if (currIndex === -1) {
throw new Error('ActiveElement is not in the listbox');
}
let direction = targetIndex > currIndex ? 'down' : 'up';
for (let i = 0; i < Math.abs(targetIndex - currIndex); i++) {
await this.user.keyboard(`[${direction === 'down' ? 'ArrowDown' : 'ArrowUp'}]`);
}
};
/**
* Selects the desired select option. Defaults to using the interaction type set on the select tester. If necessary, will open the select 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: SelectTriggerOptionOpts): Promise<void> {
let {
option,
closesOnSelect,
interactionType = this._interactionType
} = opts || {};
let trigger = this.trigger;
if (!trigger.getAttribute('aria-controls')) {
await this.open();
}
let listbox = this.listbox;
if (!listbox) {
throw new Error('Select\'s listbox not found.');
}
if (listbox) {
if (typeof option === 'string' || typeof option === 'number') {
option = this.findOption({optionIndexOrText: option});
}
if (!option) {
throw new Error('Target option not found in the listbox.');
}
let isMultiSelect = listbox.getAttribute('aria-multiselectable') === 'true';
let isSingleSelect = !isMultiSelect;
closesOnSelect = closesOnSelect ?? isSingleSelect;
if (interactionType === 'keyboard') {
if (option?.getAttribute('aria-disabled') === 'true') {
return;
}
if (document.activeElement !== listbox && !listbox.contains(document.activeElement)) {
act(() => listbox.focus());
}
await this.keyboardNavigateToOption({option});
await this.user.keyboard('[Enter]');
} else {
// TODO: what if the user needs to scroll the list to find the option? What if there are multiple matches for text (hopefully the picker options are pretty unique)
if (interactionType === 'mouse') {
await this.user.click(option);
} else {
await this.user.pointer({target: option, keys: '[TouchA]'});
}
}
if (closesOnSelect && option?.getAttribute('href') == null) {
await waitFor(() => {
if (document.activeElement !== this._trigger) {
throw new Error(`Expected the document.activeElement after selecting an option to be the select component trigger but got ${document.activeElement}`);
} else {
return true;
}
});
if (document.contains(listbox)) {
throw new Error('Expected select element listbox to not be in the document after selecting an option');
}
}
}
}
/**
* Returns the select's options if present. Can be filtered to a subsection of the listbox if provided via `element`.
*/
options(opts: {element?: HTMLElement} = {}): HTMLElement[] {
let {element = this.listbox} = opts;
let options = [];
if (element) {
options = within(element).queryAllByRole('option');
}
return options;
}
/**
* Returns the select's trigger.
*/
get trigger(): HTMLElement {
return this._trigger;
}
/**
* Returns the select's listbox if present.
*/
get listbox(): HTMLElement | null {
let listBoxId = this.trigger.getAttribute('aria-controls');
return listBoxId ? document.getElementById(listBoxId) : null;
}
/**
* Returns the select's sections if present.
*/
get sections(): HTMLElement[] {
let listbox = this.listbox;
return listbox ? within(listbox).queryAllByRole('group') : [];
}
}