Skip to content
Open
Show file tree
Hide file tree
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
17 changes: 17 additions & 0 deletions src/__tests__/element-queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,23 @@ test('query/get title element of SVG', () => {
expect(queryByTitle('Close').id).toEqual('svg-title')
})

test('query/get nested title element of SVG graphics element', () => {
const {getByTitle, queryByTitle} = render(`
<div>
<svg>
<g>
<path id="svg-path">
<title>Close</title>
</path>
</g>
</svg>
</div>
`)

expect(getByTitle('Close').id).toEqual('svg-path')
expect(queryByTitle('Close').id).toEqual('svg-path')
})

test('queryByTitle matches case with non-string matcher', () => {
const {queryByTitle} = render(`<span title="1" />`)
expect(queryByTitle(1)).toBeTruthy()
Expand Down
45 changes: 34 additions & 11 deletions src/queries/title.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,21 @@ import {
buildQueries,
} from './all-utils'

const isSvgTitle = (node: HTMLElement) =>
node.tagName.toLowerCase() === 'title' &&
node.parentElement?.tagName.toLowerCase() === 'svg'
const getSvgTitleOwner = (node: HTMLElement) => {
if (
node.tagName.toLowerCase() !== 'title' ||
node.namespaceURI !== 'http://www.w3.org/2000/svg'
) {
return null
}

const parent = node.parentElement
if (!parent || parent.tagName.toLowerCase() === 'svg') {
return node
}

return parent
}

const queryAllByTitle: AllByBoundAttribute = (
container,
Expand All @@ -26,14 +38,25 @@ const queryAllByTitle: AllByBoundAttribute = (
checkContainerType(container)
const matcher = exact ? matches : fuzzyMatches
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
return Array.from(
container.querySelectorAll<HTMLElement>('[title], svg > title'),
).filter(
node =>
matcher(node.getAttribute('title'), node, text, matchNormalizer) ||
(isSvgTitle(node) &&
matcher(getNodeText(node), node, text, matchNormalizer)),
)
const results = new Set<HTMLElement>()

Array.from(
container.querySelectorAll<HTMLElement>('[title], svg title'),
).forEach(node => {
if (matcher(node.getAttribute('title'), node, text, matchNormalizer)) {
results.add(node)
}

const svgTitleOwner = getSvgTitleOwner(node)
if (
svgTitleOwner &&
matcher(getNodeText(node), svgTitleOwner, text, matchNormalizer)
) {
results.add(svgTitleOwner)
}
})

return Array.from(results)
}

const getMultipleError: GetErrorFunction<[unknown]> = (c, title) =>
Expand Down
Loading