Skip to content

Commit 62785b8

Browse files
committed
feat(ByRole): improved byRole query performance (#698)
1 parent 1fc17be commit 62785b8

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

src/role-helpers.js

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -102,27 +102,40 @@ function buildElementRoleList(elementRolesMap) {
102102
}
103103

104104
function match(element) {
105+
let {attributes = []} = element
106+
const {name} = element
107+
const upperCasedTagName = name && name.toUpperCase()
108+
109+
// https://github.com/testing-library/dom-testing-library/issues/814
110+
const typeTextIndex = attributes.findIndex(
111+
attribute =>
112+
attribute.value &&
113+
attribute.name === 'type' &&
114+
attribute.value === 'text',
115+
)
116+
117+
if (typeTextIndex >= 0) {
118+
// not using splice to not mutate the attributes array
119+
attributes = [
120+
...attributes.slice(0, typeTextIndex),
121+
...attributes.slice(typeTextIndex + 1),
122+
]
123+
}
124+
125+
const selector = makeElementSelector({...element, attributes})
126+
105127
return node => {
106-
let {attributes = []} = element
107-
// https://github.com/testing-library/dom-testing-library/issues/814
108-
const typeTextIndex = attributes.findIndex(
109-
attribute =>
110-
attribute.value &&
111-
attribute.name === 'type' &&
112-
attribute.value === 'text',
113-
)
114-
if (typeTextIndex >= 0) {
115-
// not using splice to not mutate the attributes array
116-
attributes = [
117-
...attributes.slice(0, typeTextIndex),
118-
...attributes.slice(typeTextIndex + 1),
119-
]
120-
if (node.type !== 'text') {
121-
return false
122-
}
128+
if (upperCasedTagName && node.tagName !== upperCasedTagName) {
129+
// Short-circuit if tag name does not match,
130+
// because this code runs in a tight loop over many nodes and many roles.
131+
return false
132+
}
133+
134+
if (typeTextIndex >= 0 && node.type !== 'text') {
135+
return false
123136
}
124137

125-
return node.matches(makeElementSelector({...element, attributes}))
138+
return node.matches(selector)
126139
}
127140
}
128141

0 commit comments

Comments
 (0)