From 0226aea74e873ba96dae414edc533c33b1e51867 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tarnay=20K=C3=A1lm=C3=A1n?= Date: Tue, 9 Aug 2022 15:56:11 +0200 Subject: [PATCH] feat(ByRole): improved byRole query performance (#1086) Co-authored-by: Sebastian Silbermann --- src/role-helpers.js | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/role-helpers.js b/src/role-helpers.js index 0b494da5..500bcdd2 100644 --- a/src/role-helpers.js +++ b/src/role-helpers.js @@ -105,27 +105,32 @@ function buildElementRoleList(elementRolesMap) { } function match(element) { + 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), + ] + } + + 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 (typeTextIndex >= 0 && node.type !== 'text') { + return false } - return node.matches(makeElementSelector({...element, attributes})) + return node.matches(selector) } }