Skip to content

Commit 25eeb36

Browse files
committed
feat: ignore element that is children of aria-hidden="true"
1 parent ffc8f26 commit 25eeb36

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/__tests__/element-queries.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,26 @@ test('query can return null', () => {
2222
expect(queryByAltText('LucyRicardo')).toBeNull()
2323
})
2424

25+
test('query by text outside `aria-hidden` tags', () => {
26+
const {queryByText} = render('<div><div>LucyRicardo</div></div>')
27+
expect(queryByText('LucyRicardo')).not.toBeNull()
28+
const {queryByText: queryByTextRoot} = render(
29+
'<div aria-hidden="false">LucyRicardo</div>',
30+
)
31+
expect(queryByTextRoot('LucyRicardo')).not.toBeNull()
32+
})
33+
34+
test('query by text inside `aria-hidden` tags', () => {
35+
const {queryByText} = render(
36+
'<div aria-hidden="true"><div>LucyRicardo</div></div>',
37+
)
38+
expect(queryByText('LucyRicardo')).toBeNull()
39+
const {queryByText: queryByTextRoot} = render(
40+
'<div aria-hidden="true">LucyRicardo</div>',
41+
)
42+
expect(queryByTextRoot('LucyRicardo')).toBeNull()
43+
})
44+
2545
test('get throws a useful error message', () => {
2646
const {
2747
getByLabelText,

src/queries/text.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,31 @@ import {
99
buildQueries,
1010
} from './all-utils'
1111

12+
function ignoreHiddenElements(container, selector, baseArray) {
13+
const hiddenElements = [
14+
...Array.from(container.querySelectorAll("[aria-hidden='true']")),
15+
]
16+
baseArray.forEach(base => {
17+
if (base.getAttribute('aria-hidden') === 'true') {
18+
hiddenElements.push(base)
19+
}
20+
})
21+
let foundHiddenChildren = [...hiddenElements]
22+
hiddenElements.forEach(hiddenElement => {
23+
foundHiddenChildren = [
24+
...foundHiddenChildren,
25+
...Array.from(hiddenElement.querySelectorAll(selector)),
26+
]
27+
})
28+
const findSameNode = foundElement =>
29+
!foundHiddenChildren.find(foundHiddenElement =>
30+
foundElement.isSameNode(foundHiddenElement),
31+
)
32+
return [...baseArray, ...container.querySelectorAll(selector)].filter(
33+
findSameNode,
34+
)
35+
}
36+
1237
function queryAllByText(
1338
container,
1439
text,
@@ -28,7 +53,10 @@ function queryAllByText(
2853
if (typeof container.matches === 'function' && container.matches(selector)) {
2954
baseArray = [container]
3055
}
31-
return [...baseArray, ...Array.from(container.querySelectorAll(selector))]
56+
57+
const foundElements = ignoreHiddenElements(container, selector, baseArray)
58+
59+
return foundElements
3260
.filter(node => !ignore || !node.matches(ignore))
3361
.filter(node => matcher(getNodeText(node), node, text, matchNormalizer))
3462
}

0 commit comments

Comments
 (0)