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

refactor: export label helpers to his own file and use both in suggestions and query #790

Merged
Merged
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
41 changes: 41 additions & 0 deletions src/__tests__/suggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -578,3 +578,44 @@ test('should suggest hidden option if element is not in the accessibilty tree',
]
`)
})

test('should find label text using the aria-labelledby', () => {
const {container} = renderIntoDocument(`
<div>
<div>
<input id="sixth-label-one" value="6th one"/>
<input id="sixth-label-two" value="6th two"/>
<label id="sixth-label-three">6th three</label>
<input aria-labelledby="sixth-label-one sixth-label-two sixth-label-three" id="sixth-id" />
</div>
</div>
`)

expect(
getSuggestedQuery(
container.querySelector('[id="sixth-id"]'),
'get',
'labelText',
),
).toMatchInlineSnapshot(
{
queryArgs: [/6th one 6th two 6th three/i],
queryMethod: 'getByLabelText',
queryName: 'LabelText',
variant: 'get',
warning: '',
},
`
Object {
"queryArgs": Array [
Object {},
],
"queryMethod": "getByLabelText",
"queryName": "LabelText",
"toString": [Function],
"variant": "get",
"warning": "",
}
`,
)
})
75 changes: 75 additions & 0 deletions src/label-helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {TEXT_NODE} from './helpers'

const labelledNodeNames = [
'button',
'meter',
'output',
'progress',
'select',
'textarea',
'input',
]

function getTextContent(node) {
if (labelledNodeNames.includes(node.nodeName.toLowerCase())) {
return ''
}

if (node.nodeType === TEXT_NODE) return node.textContent

return Array.from(node.childNodes)
.map(childNode => getTextContent(childNode))
.join('')
}

function getLabelContent(node) {
let textContent
if (node.tagName.toLowerCase() === 'label') {
textContent = getTextContent(node)
} else {
textContent = node.value || node.textContent
}
return textContent
}

// Based on https://github.com/eps1lon/dom-accessibility-api/pull/352
function getRealLabels(element) {
if (element.labels !== undefined) return element.labels

if (!isLabelable(element)) return []

const labels = element.ownerDocument.querySelectorAll('label')
return Array.from(labels).filter(label => label.control === element)
}

function isLabelable(element) {
return (
element.tagName.match(/BUTTON|METER|OUTPUT|PROGRESS|SELECT|TEXTAREA/) ||
(element.tagName === 'INPUT' && element.getAttribute('type') !== 'hidden')
)
}

function getLabels(container, element, {selector = '*'} = {}) {
const labelsId = element.getAttribute('aria-labelledby')
? element.getAttribute('aria-labelledby').split(' ')
: []
return labelsId.length
? labelsId.map(labelId => {
const labellingElement = container.querySelector(`[id="${labelId}"]`)
return labellingElement
? {content: getLabelContent(labellingElement), formControl: null}
: {content: '', formControl: null}
})
: Array.from(getRealLabels(element)).map(label => {
const textToMatch = getLabelContent(label)
const formControlSelector =
'button, input, meter, output, progress, select, textarea'
const labelledFormControl = Array.from(
label.querySelectorAll(formControlSelector),
).filter(formControlElement => formControlElement.matches(selector))[0]

return {content: textToMatch, formControl: labelledFormControl}
})
}

export {getLabels, getRealLabels, getLabelContent}
92 changes: 16 additions & 76 deletions src/queries/label-text.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {getConfig} from '../config'
import {checkContainerType, TEXT_NODE} from '../helpers'
import {checkContainerType} from '../helpers'
import {getLabels, getRealLabels, getLabelContent} from '../label-helpers'
import {
fuzzyMatches,
matches,
Expand All @@ -11,16 +12,6 @@ import {
wrapSingleQueryWithSuggestion,
} from './all-utils'

const labelledNodeNames = [
'button',
'meter',
'output',
'progress',
'select',
'textarea',
'input',
]

function queryAllLabels(container) {
return Array.from(container.querySelectorAll('label,input'))
.map(node => {
Expand All @@ -46,28 +37,6 @@ function queryAllLabelsByText(
.map(({node}) => node)
}

function getTextContent(node) {
if (labelledNodeNames.includes(node.nodeName.toLowerCase())) {
return ''
}

if (node.nodeType === TEXT_NODE) return node.textContent

return Array.from(node.childNodes)
.map(childNode => getTextContent(childNode))
.join('')
}

function getLabelContent(node) {
let textContent
if (node.tagName.toLowerCase() === 'label') {
textContent = getTextContent(node)
} else {
textContent = node.value || node.textContent
}
return textContent
}

function queryAllByLabelText(
container,
text,
Expand All @@ -79,34 +48,21 @@ function queryAllByLabelText(
const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer})
const matchingLabelledElements = Array.from(container.querySelectorAll('*'))
.filter(element => {
return getLabels(element) || element.hasAttribute('aria-labelledby')
return (
getRealLabels(element).length || element.hasAttribute('aria-labelledby')
)
})
.reduce((labelledElements, labelledElement) => {
const labelsId = labelledElement.getAttribute('aria-labelledby')
? labelledElement.getAttribute('aria-labelledby').split(' ')
: []
let labelsValue = labelsId.length
? labelsId.map(labelId => {
const labellingElement = container.querySelector(
`[id="${labelId}"]`,
)
return labellingElement ? getLabelContent(labellingElement) : ''
})
: Array.from(getLabels(labelledElement)).map(label => {
const textToMatch = getLabelContent(label)
const formControlSelector = labelledNodeNames.join(',')
const labelledFormControl = Array.from(
label.querySelectorAll(formControlSelector),
).filter(element => element.matches(selector))[0]
if (labelledFormControl) {
if (
matcher(textToMatch, labelledFormControl, text, matchNormalizer)
)
labelledElements.push(labelledFormControl)
}
return textToMatch
})
labelsValue = labelsValue.filter(Boolean)
const labelList = getLabels(container, labelledElement, {selector})
labelList
.filter(label => Boolean(label.formControl))
.forEach(label => {
if (matcher(label.content, label.formControl, text, matchNormalizer))
labelledElements.push(label.formControl)
})
const labelsValue = labelList
.filter(label => Boolean(label.content))
.map(label => label.content)
if (
matcher(labelsValue.join(' '), labelledElement, text, matchNormalizer)
)
Expand Down Expand Up @@ -232,6 +188,7 @@ const queryAllByLabelTextWithSuggestions = wrapAllByQueryWithSuggestion(
queryAllByLabelText.name,
'queryAll',
)

export {
queryAllByLabelTextWithSuggestions as queryAllByLabelText,
queryByLabelText,
Expand All @@ -240,20 +197,3 @@ export {
findAllByLabelText,
findByLabelText,
}

// Based on https://github.com/eps1lon/dom-accessibility-api/pull/352
function getLabels(element) {
if (element.labels !== undefined) return element.labels

if (!isLabelable(element)) return null

const labels = element.ownerDocument.querySelectorAll('label')
return Array.from(labels).filter(label => label.control === element)
}

function isLabelable(element) {
return (
element.tagName.match(/BUTTON|METER|OUTPUT|PROGRESS|SELECT|TEXTAREA/) ||
(element.tagName === 'INPUT' && element.getAttribute('type') !== 'hidden')
)
}
29 changes: 4 additions & 25 deletions src/suggestions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,10 @@ import {getDefaultNormalizer} from './matches'
import {getNodeText} from './get-node-text'
import {DEFAULT_IGNORE_TAGS, getConfig} from './config'
import {getImplicitAriaRoles, isInaccessible} from './role-helpers'
import {getLabels} from './label-helpers'

const normalize = getDefaultNormalizer()

function getLabelTextFor(element) {
let label =
element.labels &&
Array.from(element.labels).find(el => Boolean(normalize(el.textContent)))

// non form elements that are using aria-labelledby won't be included in `element.labels`
if (!label) {
const ariaLabelledBy = element.getAttribute('aria-labelledby')
if (ariaLabelledBy) {
// this is only a temporary fix. The problem is that at the moment @testing-library/dom
// not support label concatenation
// see https://github.com/testing-library/dom-testing-library/issues/545
const firstId = ariaLabelledBy.split(' ')[0]
// we're using this notation because with the # selector we would have to escape special characters e.g. user.name
// see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#Escaping_special_characters
label = document.querySelector(`[id="${firstId}"]`)
}
}

if (label) {
return label.textContent
}
return undefined
}
function escapeRegExp(string) {
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string
}
Expand Down Expand Up @@ -113,7 +90,9 @@ export function getSuggestedQuery(element, variant = 'get', method) {
})
}

const labelText = getLabelTextFor(element)
const labelText = getLabels(document, element)
.map(label => label.content)
.join(' ')
marcosvega91 marked this conversation as resolved.
Show resolved Hide resolved
if (canSuggest('LabelText', method, labelText)) {
return makeSuggestion('LabelText', element, labelText, {variant})
}
Expand Down