Skip to content

feat(ByRole): Check only elements that could be a match #1046

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions src/queries/role.js
Original file line number Diff line number Diff line change
@@ -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