|
1 |
| -import {queryAllByAttribute, buildQueries} from './all-utils' |
| 1 | +import {buildQueries, fuzzyMatches, makeNormalizer, matches} from './all-utils' |
| 2 | +import {elementRoles} from 'aria-query' |
2 | 3 |
|
3 |
| -const queryAllByRole = queryAllByAttribute.bind(null, 'role') |
| 4 | +function buildElementRoleList(elementRolesMap) { |
| 5 | + function makeElementSelector({name, attributes = []}) { |
| 6 | + return `${name}${attributes |
| 7 | + .map(({name: attributeName, value}) => `[${attributeName}=${value}]`) |
| 8 | + .join('')}` |
| 9 | + } |
| 10 | + |
| 11 | + function getSelectorSpecificity({attributes = []}) { |
| 12 | + return attributes.length |
| 13 | + } |
| 14 | + |
| 15 | + function bySelectorSpecificity( |
| 16 | + {specificity: leftSpecificity}, |
| 17 | + {specificity: rightSpecificity}, |
| 18 | + ) { |
| 19 | + return rightSpecificity - leftSpecificity |
| 20 | + } |
| 21 | + |
| 22 | + let result = [] |
| 23 | + |
| 24 | + for (const [element, roles] of elementRolesMap.entries()) { |
| 25 | + result = [ |
| 26 | + ...result, |
| 27 | + { |
| 28 | + selector: makeElementSelector(element), |
| 29 | + roles: Array.from(roles), |
| 30 | + specificity: getSelectorSpecificity(element), |
| 31 | + }, |
| 32 | + ] |
| 33 | + } |
| 34 | + |
| 35 | + return result.sort(bySelectorSpecificity) |
| 36 | +} |
| 37 | + |
| 38 | +const elementRoleList = buildElementRoleList(elementRoles) |
| 39 | + |
| 40 | +function queryAllByRole( |
| 41 | + container, |
| 42 | + role, |
| 43 | + {exact = true, collapseWhitespace, trim, normalizer} = {}, |
| 44 | +) { |
| 45 | + const matcher = exact ? matches : fuzzyMatches |
| 46 | + const matchNormalizer = makeNormalizer({collapseWhitespace, trim, normalizer}) |
| 47 | + |
| 48 | + function getImplicitAriaRole(currentNode) { |
| 49 | + for (const {selector, roles} of elementRoleList) { |
| 50 | + if (currentNode.matches(selector)) { |
| 51 | + return [...roles] |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return [] |
| 56 | + } |
| 57 | + |
| 58 | + return Array.from(container.querySelectorAll('*')).filter(node => { |
| 59 | + const isRoleSpecifiedExplicitly = node.hasAttribute('role') |
| 60 | + |
| 61 | + if (isRoleSpecifiedExplicitly) { |
| 62 | + return matcher(node.getAttribute('role'), node, role, matchNormalizer) |
| 63 | + } |
| 64 | + |
| 65 | + const implicitRoles = getImplicitAriaRole(node) |
| 66 | + |
| 67 | + return implicitRoles.some(implicitRole => |
| 68 | + matcher(implicitRole, node, role, matchNormalizer), |
| 69 | + ) |
| 70 | + }) |
| 71 | +} |
4 | 72 |
|
5 | 73 | const getMultipleError = (c, id) => `Found multiple elements by [role=${id}]`
|
6 | 74 | const getMissingError = (c, id) => `Unable to find an element by [role=${id}]`
|
|
0 commit comments