Skip to content
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

feat(ByRole): improved byRole query performance #1086

Merged
merged 3 commits into from Aug 9, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
49 changes: 31 additions & 18 deletions src/role-helpers.js
Expand Up @@ -102,27 +102,40 @@ function buildElementRoleList(elementRolesMap) {
}

function match(element) {
let {attributes = []} = element
const {name} = element
const upperCasedTagName = name && name.toUpperCase()

// https://github.com/testing-library/dom-testing-library/issues/814
const typeTextIndex = attributes.findIndex(
attribute =>
attribute.value &&
attribute.name === 'type' &&
attribute.value === 'text',
)

if (typeTextIndex >= 0) {
// not using splice to not mutate the attributes array
attributes = [
...attributes.slice(0, typeTextIndex),
...attributes.slice(typeTextIndex + 1),
]
}

const selector = makeElementSelector({...element, attributes})

return node => {
let {attributes = []} = element
// https://github.com/testing-library/dom-testing-library/issues/814
const typeTextIndex = attributes.findIndex(
attribute =>
attribute.value &&
attribute.name === 'type' &&
attribute.value === 'text',
)
if (typeTextIndex >= 0) {
// not using splice to not mutate the attributes array
attributes = [
...attributes.slice(0, typeTextIndex),
...attributes.slice(typeTextIndex + 1),
]
if (node.type !== 'text') {
return false
}
if (upperCasedTagName && node.tagName !== upperCasedTagName) {
// Short-circuit if tag name does not match,
eps1lon marked this conversation as resolved.
Show resolved Hide resolved
// because this code runs in a tight loop over many nodes and many roles.
return false
}

if (typeTextIndex >= 0 && node.type !== 'text') {
return false
}

return node.matches(makeElementSelector({...element, attributes}))
return node.matches(selector)
}
}

Expand Down