-
Notifications
You must be signed in to change notification settings - Fork 467
/
role-helpers.js
306 lines (271 loc) · 8.4 KB
/
role-helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import {elementRoles} from 'aria-query'
import {computeAccessibleName} from 'dom-accessibility-api'
import {prettyDOM} from './pretty-dom'
import {getConfig} from './config'
const elementRoleList = buildElementRoleList(elementRoles)
/**
* @param {Element} element -
* @returns {boolean} - `true` if `element` and its subtree are inaccessible
*/
function isSubtreeInaccessible(element) {
if (element.hidden === true) {
return true
}
if (element.getAttribute('aria-hidden') === 'true') {
return true
}
const window = element.ownerDocument.defaultView
if (window.getComputedStyle(element).display === 'none') {
return true
}
return false
}
/**
* Partial implementation https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion
* which should only be used for elements with a non-presentational role i.e.
* `role="none"` and `role="presentation"` will not be excluded.
*
* Implements aria-hidden semantics (i.e. parent overrides child)
* Ignores "Child Presentational: True" characteristics
*
* @param {Element} element -
* @param {object} [options] -
* @param {function (element: Element): boolean} options.isSubtreeInaccessible -
* can be used to return cached results from previous isSubtreeInaccessible calls
* @returns {boolean} true if excluded, otherwise false
*/
function isInaccessible(element, options = {}) {
const {
isSubtreeInaccessible: isSubtreeInaccessibleImpl = isSubtreeInaccessible,
} = options
const window = element.ownerDocument.defaultView
// since visibility is inherited we can exit early
if (window.getComputedStyle(element).visibility === 'hidden') {
return true
}
let currentElement = element
while (currentElement) {
if (isSubtreeInaccessibleImpl(currentElement)) {
return true
}
currentElement = currentElement.parentElement
}
return false
}
function getImplicitAriaRoles(currentNode) {
// eslint bug here:
// eslint-disable-next-line no-unused-vars
for (const {match, roles} of elementRoleList) {
if (match(currentNode)) {
return [...roles]
}
}
return []
}
function buildElementRoleList(elementRolesMap) {
function makeElementSelector({name, attributes}) {
return `${name}${attributes
.map(({name: attributeName, value, constraints = []}) => {
const shouldNotExist = constraints.indexOf('undefined') !== -1
if (shouldNotExist) {
return `:not([${attributeName}])`
} else if (value) {
return `[${attributeName}="${value}"]`
} else {
return `[${attributeName}]`
}
})
.join('')}`
}
function getSelectorSpecificity({attributes = []}) {
return attributes.length
}
function bySelectorSpecificity(
{specificity: leftSpecificity},
{specificity: rightSpecificity},
) {
return rightSpecificity - leftSpecificity
}
function match(element) {
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
}
}
return node.matches(makeElementSelector({...element, attributes}))
}
}
let result = []
// eslint bug here:
// eslint-disable-next-line no-unused-vars
for (const [element, roles] of elementRolesMap.entries()) {
result = [
...result,
{
match: match(element),
roles: Array.from(roles),
specificity: getSelectorSpecificity(element),
},
]
}
return result.sort(bySelectorSpecificity)
}
function getRoles(container, {hidden = false} = {}) {
function flattenDOM(node) {
return [
node,
...Array.from(node.children).reduce(
(acc, child) => [...acc, ...flattenDOM(child)],
[],
),
]
}
return flattenDOM(container)
.filter(element => {
return hidden === false ? isInaccessible(element) === false : true
})
.reduce((acc, node) => {
let roles = []
// TODO: This violates html-aria which does not allow any role on every element
if (node.hasAttribute('role')) {
roles = node.getAttribute('role').split(' ').slice(0, 1)
} else {
roles = getImplicitAriaRoles(node)
}
return roles.reduce(
(rolesAcc, role) =>
Array.isArray(rolesAcc[role])
? {...rolesAcc, [role]: [...rolesAcc[role], node]}
: {...rolesAcc, [role]: [node]},
acc,
)
}, {})
}
function prettyRoles(dom, {hidden}) {
const roles = getRoles(dom, {hidden})
// We prefer to skip generic role, we don't recommend it
return Object.entries(roles)
.filter(([role]) => role !== 'generic')
.map(([role, elements]) => {
const delimiterBar = '-'.repeat(50)
const elementsString = elements
.map(el => {
const nameString = `Name "${computeAccessibleName(el, {
computedStyleSupportsPseudoElements: getConfig()
.computedStyleSupportsPseudoElements,
})}":\n`
const domString = prettyDOM(el.cloneNode(false))
return `${nameString}${domString}`
})
.join('\n\n')
return `${role}:\n\n${elementsString}\n\n${delimiterBar}`
})
.join('\n')
}
const logRoles = (dom, {hidden = false} = {}) =>
console.log(prettyRoles(dom, {hidden}))
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)selected, undefined if not selectable
*/
function computeAriaSelected(element) {
// implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// https://www.w3.org/TR/html-aam-1.0/#details-id-97
if (element.tagName === 'OPTION') {
return element.selected
}
// explicit value
return checkBooleanAttribute(element, 'aria-selected')
}
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)checked, undefined if not checked-able
*/
function computeAriaChecked(element) {
// implicit value from html-aam mappings: https://www.w3.org/TR/html-aam-1.0/#html-attribute-state-and-property-mappings
// https://www.w3.org/TR/html-aam-1.0/#details-id-56
// https://www.w3.org/TR/html-aam-1.0/#details-id-67
if ('indeterminate' in element && element.indeterminate) {
return undefined
}
if ('checked' in element) {
return element.checked
}
// explicit value
return checkBooleanAttribute(element, 'aria-checked')
}
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)pressed, undefined if not press-able
*/
function computeAriaPressed(element) {
// https://www.w3.org/TR/wai-aria-1.1/#aria-pressed
return checkBooleanAttribute(element, 'aria-pressed')
}
/**
* @param {Element} element -
* @returns {boolean | undefined} - false/true if (not)expanded, undefined if not expand-able
*/
function computeAriaExpanded(element) {
// https://www.w3.org/TR/wai-aria-1.1/#aria-expanded
return checkBooleanAttribute(element, 'aria-expanded')
}
function checkBooleanAttribute(element, attribute) {
const attributeValue = element.getAttribute(attribute)
if (attributeValue === 'true') {
return true
}
if (attributeValue === 'false') {
return false
}
return undefined
}
/**
* @param {Element} element -
* @returns {number | undefined} - number if implicit heading or aria-level present, otherwise undefined
*/
function computeHeadingLevel(element) {
// https://w3c.github.io/html-aam/#el-h1-h6
// https://w3c.github.io/html-aam/#el-h1-h6
const implicitHeadingLevels = {
H1: 1,
H2: 2,
H3: 3,
H4: 4,
H5: 5,
H6: 6,
}
// explicit aria-level value
// https://www.w3.org/TR/wai-aria-1.2/#aria-level
const ariaLevelAttribute =
element.getAttribute('aria-level') &&
Number(element.getAttribute('aria-level'))
return ariaLevelAttribute || implicitHeadingLevels[element.tagName]
}
export {
getRoles,
logRoles,
getImplicitAriaRoles,
isSubtreeInaccessible,
prettyRoles,
isInaccessible,
computeAriaSelected,
computeAriaChecked,
computeAriaPressed,
computeAriaExpanded,
computeHeadingLevel,
}