Skip to content

Commit 8edfad0

Browse files
ph-fritscheeps1lon
andauthored
feat(ByRole): Check only elements that could be a match (#1046)
Co-authored-by: eps1lon <[email protected]>
1 parent fb6f2d5 commit 8edfad0

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/queries/role.js

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {computeAccessibleName} from 'dom-accessibility-api'
2-
import {roles as allRoles} from 'aria-query'
2+
import {roles as allRoles, roleElements} from 'aria-query'
33
import {
44
computeAriaSelected,
55
computeAriaChecked,
@@ -99,7 +99,12 @@ function queryAllByRole(
9999
return subtreeIsInaccessibleCache.get(element)
100100
}
101101

102-
return Array.from(container.querySelectorAll('*'))
102+
return Array.from(
103+
container.querySelectorAll(
104+
// Only query elements that can be matched by the following filters
105+
makeRoleSelector(role, exact, normalizer ? matchNormalizer : undefined),
106+
),
107+
)
103108
.filter(node => {
104109
const isRoleSpecifiedExplicitly = node.hasAttribute('role')
105110

@@ -173,6 +178,22 @@ function queryAllByRole(
173178
})
174179
}
175180

181+
function makeRoleSelector(role, exact, customNormalizer) {
182+
if (typeof role !== 'string') {
183+
// For non-string role parameters we can not determine the implicitRoleSelectors.
184+
return '*'
185+
}
186+
187+
const explicitRoleSelector =
188+
exact && !customNormalizer ? `*[role~="${role}"]` : '*[role]'
189+
190+
const roleRelations = roleElements.get(role)
191+
const implicitRoleSelectors =
192+
roleRelations && new Set(Array.from(roleRelations).map(({name}) => name))
193+
194+
return [explicitRoleSelector, ...(implicitRoleSelectors ?? [])].join(',')
195+
}
196+
176197
const getMultipleError = (c, role, {name} = {}) => {
177198
let nameHint = ''
178199
if (name === undefined) {

0 commit comments

Comments
 (0)