Skip to content

Commit

Permalink
feat(ByRole): Check only elements that could be a match (#1046)
Browse files Browse the repository at this point in the history
Co-authored-by: eps1lon <silbermann.sebastian@gmail.com>
  • Loading branch information
ph-fritsche and eps1lon committed Oct 13, 2021
1 parent fb6f2d5 commit 8edfad0
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/queries/role.js
@@ -1,5 +1,5 @@
import {computeAccessibleName} from 'dom-accessibility-api'
import {roles as allRoles} from 'aria-query'
import {roles as allRoles, roleElements} from 'aria-query'
import {
computeAriaSelected,
computeAriaChecked,
Expand Down Expand Up @@ -99,7 +99,12 @@ function queryAllByRole(
return subtreeIsInaccessibleCache.get(element)
}

return Array.from(container.querySelectorAll('*'))
return Array.from(
container.querySelectorAll(
// Only query elements that can be matched by the following filters
makeRoleSelector(role, exact, normalizer ? matchNormalizer : undefined),
),
)
.filter(node => {
const isRoleSpecifiedExplicitly = node.hasAttribute('role')

Expand Down Expand Up @@ -173,6 +178,22 @@ function queryAllByRole(
})
}

function makeRoleSelector(role, exact, customNormalizer) {
if (typeof role !== 'string') {
// For non-string role parameters we can not determine the implicitRoleSelectors.
return '*'
}

const explicitRoleSelector =
exact && !customNormalizer ? `*[role~="${role}"]` : '*[role]'

const roleRelations = roleElements.get(role)
const implicitRoleSelectors =
roleRelations && new Set(Array.from(roleRelations).map(({name}) => name))

return [explicitRoleSelector, ...(implicitRoleSelectors ?? [])].join(',')
}

const getMultipleError = (c, role, {name} = {}) => {
let nameHint = ''
if (name === undefined) {
Expand Down

0 comments on commit 8edfad0

Please sign in to comment.