-
Notifications
You must be signed in to change notification settings - Fork 470
/
role.ts
419 lines (382 loc) · 11.4 KB
/
role.ts
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
/* eslint-disable complexity */
import {
computeAccessibleDescription,
computeAccessibleName,
} from 'dom-accessibility-api'
import {
roles as allRoles,
roleElements,
ARIARoleDefinitionKey,
} from 'aria-query'
import {
computeAriaSelected,
computeAriaBusy,
computeAriaChecked,
computeAriaPressed,
computeAriaCurrent,
computeAriaExpanded,
computeAriaValueNow,
computeAriaValueMax,
computeAriaValueMin,
computeAriaValueText,
computeHeadingLevel,
getImplicitAriaRoles,
prettyRoles,
isInaccessible,
isSubtreeInaccessible,
} from '../role-helpers'
import {wrapAllByQueryWithSuggestion} from '../query-helpers'
import {checkContainerType} from '../helpers'
import {
AllByRole,
ByRoleMatcher,
ByRoleOptions,
GetErrorFunction,
Matcher,
MatcherFunction,
MatcherOptions,
} from '../../types'
import {buildQueries, getConfig, matches} from './all-utils'
const queryAllByRole: AllByRole = (
container,
role,
{
hidden = getConfig().defaultHidden,
name,
description,
queryFallbacks = false,
selected,
busy,
checked,
pressed,
current,
level,
expanded,
value: {
now: valueNow,
min: valueMin,
max: valueMax,
text: valueText,
} = {} as NonNullable<ByRoleOptions['value']>,
} = {},
) => {
checkContainerType(container)
if (selected !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-selected'] ===
undefined
) {
throw new Error(`"aria-selected" is not supported on role "${role}".`)
}
}
if (busy !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-busy'] ===
undefined
) {
throw new Error(`"aria-busy" is not supported on role "${role}".`)
}
}
if (checked !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-checked'] ===
undefined
) {
throw new Error(`"aria-checked" is not supported on role "${role}".`)
}
}
if (pressed !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-pressed'] ===
undefined
) {
throw new Error(`"aria-pressed" is not supported on role "${role}".`)
}
}
if (current !== undefined) {
/* istanbul ignore next */
// guard against unknown roles
// All currently released ARIA versions support `aria-current` on all roles.
// Leaving this for symmetry and forward compatibility
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-current'] ===
undefined
) {
throw new Error(`"aria-current" is not supported on role "${role}".`)
}
}
if (level !== undefined) {
// guard against using `level` option with any role other than `heading`
if (role !== 'heading') {
throw new Error(`Role "${role}" cannot have "level" property.`)
}
}
if (valueNow !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-valuenow'] ===
undefined
) {
throw new Error(`"aria-valuenow" is not supported on role "${role}".`)
}
}
if (valueMax !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-valuemax'] ===
undefined
) {
throw new Error(`"aria-valuemax" is not supported on role "${role}".`)
}
}
if (valueMin !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-valuemin'] ===
undefined
) {
throw new Error(`"aria-valuemin" is not supported on role "${role}".`)
}
}
if (valueText !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-valuetext'] ===
undefined
) {
throw new Error(`"aria-valuetext" is not supported on role "${role}".`)
}
}
if (expanded !== undefined) {
// guard against unknown roles
if (
allRoles.get(role as ARIARoleDefinitionKey)?.props['aria-expanded'] ===
undefined
) {
throw new Error(`"aria-expanded" is not supported on role "${role}".`)
}
}
const subtreeIsInaccessibleCache = new WeakMap<Element, Boolean>()
function cachedIsSubtreeInaccessible(element: Element) {
if (!subtreeIsInaccessibleCache.has(element)) {
subtreeIsInaccessibleCache.set(element, isSubtreeInaccessible(element))
}
return subtreeIsInaccessibleCache.get(element) as boolean
}
return Array.from(
container.querySelectorAll<HTMLElement>(
// Only query elements that can be matched by the following filters
makeRoleSelector(role),
),
)
.filter(node => {
const isRoleSpecifiedExplicitly = node.hasAttribute('role')
if (isRoleSpecifiedExplicitly) {
const roleValue = node.getAttribute('role') as string
if (queryFallbacks) {
return roleValue
.split(' ')
.filter(Boolean)
.some(roleAttributeToken => roleAttributeToken === role)
}
// other wise only send the first token to match
const [firstRoleAttributeToken] = roleValue.split(' ')
return firstRoleAttributeToken === role
}
const implicitRoles = getImplicitAriaRoles(node) as string[]
return implicitRoles.some(implicitRole => {
return implicitRole === role
})
})
.filter(element => {
if (selected !== undefined) {
return selected === computeAriaSelected(element)
}
if (busy !== undefined) {
return busy === computeAriaBusy(element)
}
if (checked !== undefined) {
return checked === computeAriaChecked(element)
}
if (pressed !== undefined) {
return pressed === computeAriaPressed(element)
}
if (current !== undefined) {
return current === computeAriaCurrent(element)
}
if (expanded !== undefined) {
return expanded === computeAriaExpanded(element)
}
if (level !== undefined) {
return level === computeHeadingLevel(element)
}
if (
valueNow !== undefined ||
valueMax !== undefined ||
valueMin !== undefined ||
valueText !== undefined
) {
let valueMatches = true
if (valueNow !== undefined) {
valueMatches &&= valueNow === computeAriaValueNow(element)
}
if (valueMax !== undefined) {
valueMatches &&= valueMax === computeAriaValueMax(element)
}
if (valueMin !== undefined) {
valueMatches &&= valueMin === computeAriaValueMin(element)
}
if (valueText !== undefined) {
valueMatches &&= matches(
computeAriaValueText(element) ?? null,
element,
valueText,
text => text,
)
}
return valueMatches
}
// don't care if aria attributes are unspecified
return true
})
.filter(element => {
if (name === undefined) {
// Don't care
return true
}
return matches(
computeAccessibleName(element, {
computedStyleSupportsPseudoElements:
getConfig().computedStyleSupportsPseudoElements,
}),
element,
name as MatcherFunction,
text => text,
)
})
.filter(element => {
if (description === undefined) {
// Don't care
return true
}
return matches(
computeAccessibleDescription(element, {
computedStyleSupportsPseudoElements:
getConfig().computedStyleSupportsPseudoElements,
}),
element,
description as Matcher,
text => text,
)
})
.filter(element => {
return hidden === false
? isInaccessible(element, {
isSubtreeInaccessible: cachedIsSubtreeInaccessible,
}) === false
: true
})
}
function makeRoleSelector(role: ByRoleMatcher) {
const explicitRoleSelector = `*[role~="${role}"]`
const roleRelations =
roleElements.get(role as ARIARoleDefinitionKey) ?? new Set()
const implicitRoleSelectors = new Set(
Array.from(roleRelations).map(({name}) => name),
)
// Current transpilation config sometimes assumes `...` is always applied to arrays.
// `...` is equivalent to `Array.prototype.concat` for arrays.
// If you replace this code with `[explicitRoleSelector, ...implicitRoleSelectors]`, make sure every transpilation target retains the `...` in favor of `Array.prototype.concat`.
return [explicitRoleSelector]
.concat(Array.from(implicitRoleSelectors))
.join(',')
}
const getNameHint = (name: ByRoleOptions['name']): string => {
let nameHint = ''
if (name === undefined) {
nameHint = ''
} else if (typeof name === 'string') {
nameHint = ` and name "${name}"`
} else {
nameHint = ` and name \`${name}\``
}
return nameHint
}
const getMultipleError: GetErrorFunction<
[matcher: ByRoleMatcher, options: ByRoleOptions]
> = (c, role, {name} = {}) => {
return `Found multiple elements with the role "${role}"${getNameHint(name)}`
}
const getMissingError: GetErrorFunction<
[matcher: ByRoleMatcher, options: ByRoleOptions]
> = (
container,
role,
{hidden = getConfig().defaultHidden, name, description} = {},
) => {
if (getConfig()._disableExpensiveErrorDiagnostics) {
return `Unable to find role="${role}"${getNameHint(name)}`
}
let roles = ''
Array.from((container as Element).children).forEach(childElement => {
roles += prettyRoles(childElement, {
hidden,
includeDescription: description !== undefined,
})
})
let roleMessage
if (roles.length === 0) {
if (hidden === false) {
roleMessage =
'There are no accessible roles. But there might be some inaccessible roles. ' +
'If you wish to access them, then set the `hidden` option to `true`. ' +
'Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole'
} else {
roleMessage = 'There are no available roles.'
}
} else {
roleMessage = `
Here are the ${hidden === false ? 'accessible' : 'available'} roles:
${roles.replace(/\n/g, '\n ').replace(/\n\s\s\n/g, '\n\n')}
`.trim()
}
let nameHint = ''
if (name === undefined) {
nameHint = ''
} else if (typeof name === 'string') {
nameHint = ` and name "${name}"`
} else {
nameHint = ` and name \`${name}\``
}
let descriptionHint = ''
if (description === undefined) {
descriptionHint = ''
} else if (typeof description === 'string') {
descriptionHint = ` and description "${description}"`
} else {
descriptionHint = ` and description \`${description}\``
}
return `
Unable to find an ${
hidden === false ? 'accessible ' : ''
}element with the role "${role}"${nameHint}${descriptionHint}
${roleMessage}`.trim()
}
const queryAllByRoleWithSuggestions = wrapAllByQueryWithSuggestion<
// @ts-expect-error -- See `wrapAllByQueryWithSuggestion` Argument constraint comment
[labelText: Matcher, options?: MatcherOptions]
>(queryAllByRole, queryAllByRole.name, 'queryAll')
const [queryByRole, getAllByRole, getByRole, findAllByRole, findByRole] =
buildQueries(queryAllByRole, getMultipleError, getMissingError)
export {
queryByRole,
queryAllByRoleWithSuggestions as queryAllByRole,
getAllByRole,
getByRole,
findAllByRole,
findByRole,
}