@selenium/atoms 4.52.0 → 4.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +56 -0
  2. package/dist/index.d.ts +4 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +2 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/typescript/accessibility-snapshot-wire.d.ts +4 -0
  7. package/dist/typescript/accessibility-snapshot-wire.d.ts.map +1 -0
  8. package/dist/typescript/accessibility-snapshot-wire.js +18 -0
  9. package/dist/typescript/accessibility-snapshot-wire.js.map +1 -0
  10. package/dist/typescript/accessibility-snapshot.d.ts +3 -0
  11. package/dist/typescript/accessibility-snapshot.d.ts.map +1 -0
  12. package/dist/typescript/accessibility-snapshot.js +18 -0
  13. package/dist/typescript/accessibility-snapshot.js.map +1 -0
  14. package/dist/typescript/core/accessibility/accname.d.ts +6 -0
  15. package/dist/typescript/core/accessibility/accname.d.ts.map +1 -0
  16. package/dist/typescript/core/accessibility/accname.js +537 -0
  17. package/dist/typescript/core/accessibility/accname.js.map +1 -0
  18. package/dist/typescript/core/accessibility/context.d.ts +43 -0
  19. package/dist/typescript/core/accessibility/context.d.ts.map +1 -0
  20. package/dist/typescript/core/accessibility/context.js +49 -0
  21. package/dist/typescript/core/accessibility/context.js.map +1 -0
  22. package/dist/typescript/core/accessibility/hidden.d.ts +39 -0
  23. package/dist/typescript/core/accessibility/hidden.d.ts.map +1 -0
  24. package/dist/typescript/core/accessibility/hidden.js +216 -0
  25. package/dist/typescript/core/accessibility/hidden.js.map +1 -0
  26. package/dist/typescript/core/accessibility/roles.d.ts +28 -0
  27. package/dist/typescript/core/accessibility/roles.d.ts.map +1 -0
  28. package/dist/typescript/core/accessibility/roles.js +381 -0
  29. package/dist/typescript/core/accessibility/roles.js.map +1 -0
  30. package/dist/typescript/core/accessibility/snapshot.d.ts +13 -0
  31. package/dist/typescript/core/accessibility/snapshot.d.ts.map +1 -0
  32. package/dist/typescript/core/accessibility/snapshot.js +55 -0
  33. package/dist/typescript/core/accessibility/snapshot.js.map +1 -0
  34. package/dist/typescript/core/accessibility/states.d.ts +18 -0
  35. package/dist/typescript/core/accessibility/states.d.ts.map +1 -0
  36. package/dist/typescript/core/accessibility/states.js +215 -0
  37. package/dist/typescript/core/accessibility/states.js.map +1 -0
  38. package/dist/typescript/core/accessibility/tree.d.ts +10 -0
  39. package/dist/typescript/core/accessibility/tree.d.ts.map +1 -0
  40. package/dist/typescript/core/accessibility/tree.js +261 -0
  41. package/dist/typescript/core/accessibility/tree.js.map +1 -0
  42. package/dist/typescript/core/accessibility/types.d.ts +30 -0
  43. package/dist/typescript/core/accessibility/types.d.ts.map +1 -0
  44. package/dist/typescript/core/accessibility/types.js +18 -0
  45. package/dist/typescript/core/accessibility/types.js.map +1 -0
  46. package/dist/typescript/core/accessibility/value.d.ts +4 -0
  47. package/dist/typescript/core/accessibility/value.d.ts.map +1 -0
  48. package/dist/typescript/core/accessibility/value.js +83 -0
  49. package/dist/typescript/core/accessibility/value.js.map +1 -0
  50. package/dist/typescript/core/accessibility/wire.d.ts +57 -0
  51. package/dist/typescript/core/accessibility/wire.d.ts.map +1 -0
  52. package/dist/typescript/core/accessibility/wire.js +72 -0
  53. package/dist/typescript/core/accessibility/wire.js.map +1 -0
  54. package/index.ts +4 -0
  55. package/package.json +15 -1
  56. package/typescript/accessibility-snapshot-wire.ts +20 -0
  57. package/typescript/accessibility-snapshot.ts +21 -0
  58. package/typescript/core/accessibility/accname.ts +587 -0
  59. package/typescript/core/accessibility/context.ts +116 -0
  60. package/typescript/core/accessibility/hidden.ts +242 -0
  61. package/typescript/core/accessibility/roles.ts +410 -0
  62. package/typescript/core/accessibility/snapshot.ts +61 -0
  63. package/typescript/core/accessibility/states.ts +233 -0
  64. package/typescript/core/accessibility/tree.ts +306 -0
  65. package/typescript/core/accessibility/types.ts +52 -0
  66. package/typescript/core/accessibility/value.ts +89 -0
  67. package/typescript/core/accessibility/wire.ts +123 -0
@@ -0,0 +1,587 @@
1
+ // Licensed to the Software Freedom Conservancy (SFC) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The SFC licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ import { NameResult, roleOf, SnapshotContext, styleOf } from './context.js'
19
+ import { flatTreeChildren, hiddenState, isClosedDetails, isCollapsedDetailsContent, isHidden } from './hidden.js'
20
+ import { embeddedValue, isEmbeddedControl } from './value.js'
21
+
22
+ // Accessible name and description, following the accname 1.2 text
23
+ // alternative computation (https://w3c.github.io/accname/#computation-steps)
24
+ // with the html-aam rules for native elements. Step numbers in comments refer
25
+ // to that algorithm.
26
+
27
+ const TEXT_NODE = 3
28
+ const ELEMENT_NODE = 1
29
+
30
+ // WAI-ARIA 1.2 roles with "Name From: contents".
31
+ const NAME_FROM_CONTENT: ReadonlySet<string> = new Set([
32
+ 'button', 'cell', 'checkbox', 'columnheader', 'gridcell', 'heading', 'link', 'menuitem',
33
+ 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'row', 'rowheader', 'switch', 'tab',
34
+ 'tooltip', 'treeitem',
35
+ ])
36
+
37
+ // The input types that take a placeholder.
38
+ const TEXT_INPUT_TYPES: ReadonlySet<string> = new Set(['email', 'number', 'password', 'search', 'tel', 'text', 'url'])
39
+
40
+ // Display values whose boxes sit inline with text; everything else is treated
41
+ // as block-level when children are joined (2F.iii).
42
+ const INLINE_DISPLAYS: ReadonlySet<string> = new Set([
43
+ 'inline', 'inline-block', 'inline-flex', 'inline-grid', 'inline-table', 'contents', 'ruby',
44
+ 'ruby-base', 'ruby-text', '',
45
+ ])
46
+
47
+ interface Traversal {
48
+ readonly context: SnapshotContext
49
+ /** True while computing a description rather than a name. */
50
+ readonly describing: boolean
51
+ /** True inside an aria-labelledby / aria-describedby reference (2B is not applied again). */
52
+ readonly inReference: boolean
53
+ /** True for descendants of the element being named (2F.iii recursion) and for native label traversals. */
54
+ readonly recursive: boolean
55
+ /** True when the traversal root was hidden, so hidden descendants count too (2A). */
56
+ readonly includeHidden: boolean
57
+ /** The labelled control while its own label is traversed; it does not name itself. */
58
+ readonly skip: Element | null
59
+ }
60
+
61
+ function normalize(text: string): string {
62
+ return text.replace(/\s+/g, ' ').trim()
63
+ }
64
+
65
+ function attribute(element: Element, name: string): string | null {
66
+ const value = element.getAttribute(name)
67
+ return value !== null && value.trim() !== '' ? value : null
68
+ }
69
+
70
+ function rootNodeOf(element: Element): Document | ShadowRoot {
71
+ return element.getRootNode() as Document | ShadowRoot
72
+ }
73
+
74
+ function referencedElements(element: Element, attributeName: string): Element[] {
75
+ const ids = element.getAttribute(attributeName)
76
+ if (!ids) {
77
+ return []
78
+ }
79
+ const root = rootNodeOf(element)
80
+ const found: Element[] = []
81
+ for (const id of ids.trim().split(/\s+/)) {
82
+ const target = root.getElementById(id)
83
+ if (target) {
84
+ found.push(target)
85
+ }
86
+ }
87
+ return found
88
+ }
89
+
90
+ // 2B: the text alternatives of the referenced elements, space-joined, an id
91
+ // listed twice counting once (as Chromium reads it). A target's text
92
+ // alternative is the same whoever references it and whether for a name or a
93
+ // description (2B is not applied inside a reference and 2C is), so it is
94
+ // computed once per snapshot: a header that labels every cell of a column is
95
+ // read once, not once per cell. No cycle check is needed beyond
96
+ // `inReference`: nothing below a reference follows references again.
97
+ function fromReferences(element: Element, attributeName: string, t: Traversal): string {
98
+ const parts: string[] = []
99
+ const listed = new Set<Element>()
100
+ for (const target of referencedElements(element, attributeName)) {
101
+ if (listed.has(target)) {
102
+ continue
103
+ }
104
+ listed.add(target)
105
+ let text = t.context.referenceTexts.get(target)
106
+ if (text === undefined) {
107
+ text = textAlternative(target, {
108
+ ...t,
109
+ inReference: true,
110
+ recursive: false,
111
+ includeHidden: isHidden(target, t.context),
112
+ skip: null,
113
+ })
114
+ t.context.referenceTexts.set(target, text)
115
+ }
116
+ parts.push(text)
117
+ }
118
+ return normalize(parts.join(' '))
119
+ }
120
+
121
+ const GENERATED_CONTENT_SELECTOR = /::?(before|after)\b/i
122
+
123
+ // Whether one stylesheet has a rule that can set ::before or ::after content,
124
+ // looking into grouping rules (@media, @supports, @layer, @container, nested
125
+ // rules) and imports. A sheet whose rules cannot be read (cross-origin)
126
+ // counts as defining them: a wrong "no" would drop real text, a wrong "yes"
127
+ // only costs the reads.
128
+ function sheetDefinesGeneratedContent(sheet: CSSStyleSheet): boolean {
129
+ let rules: CSSRuleList
130
+ try {
131
+ rules = sheet.cssRules
132
+ } catch (e) {
133
+ return true
134
+ }
135
+ return rulesDefineGeneratedContent(rules)
136
+ }
137
+
138
+ function rulesDefineGeneratedContent(rules: CSSRuleList): boolean {
139
+ for (let i = 0; i < rules.length; i++) {
140
+ const rule = rules[i] as CSSRule & { selectorText?: string; cssRules?: CSSRuleList; styleSheet?: CSSStyleSheet | null }
141
+ if (typeof rule.selectorText === 'string' && GENERATED_CONTENT_SELECTOR.test(rule.selectorText)) {
142
+ return true
143
+ }
144
+ if (rule.styleSheet && sheetDefinesGeneratedContent(rule.styleSheet)) {
145
+ return true
146
+ }
147
+ if (rule.cssRules && rulesDefineGeneratedContent(rule.cssRules)) {
148
+ return true
149
+ }
150
+ }
151
+ return false
152
+ }
153
+
154
+ // Whether the sheets of one tree scope (the document or a shadow root) can
155
+ // define generated content; cached per scope for the call.
156
+ function scopeDefinesGeneratedContent(scope: Document | ShadowRoot, t: Traversal): boolean {
157
+ let defines = t.context.generatedScopes.get(scope)
158
+ if (defines === undefined) {
159
+ defines = false
160
+ const sheets = scope.styleSheets
161
+ for (let i = 0; i < sheets.length && !defines; i++) {
162
+ defines = sheetDefinesGeneratedContent(sheets[i])
163
+ }
164
+ const adopted = (scope as { adoptedStyleSheets?: CSSStyleSheet[] }).adoptedStyleSheets
165
+ if (adopted) {
166
+ for (let i = 0; i < adopted.length && !defines; i++) {
167
+ defines = sheetDefinesGeneratedContent(adopted[i])
168
+ }
169
+ }
170
+ t.context.generatedScopes.set(scope, defines)
171
+ }
172
+ return defines
173
+ }
174
+
175
+ // The scopes whose sheets can style an element's pseudo-elements: its own
176
+ // tree, its shadow root (through :host::before), the tree of the slot it is
177
+ // assigned to (through ::slotted()::before), and, for an element with a part
178
+ // name, every enclosing tree (through ::part()::before). The UA stylesheet is
179
+ // not consulted: its only generated content is the open-quote and
180
+ // close-quote keywords on q, which are not strings and are not text the atom
181
+ // can read (the names page pins that).
182
+ function mayHaveGeneratedContent(element: Element, t: Traversal): boolean {
183
+ if (scopeDefinesGeneratedContent(rootNodeOf(element), t)) {
184
+ return true
185
+ }
186
+ if (element.shadowRoot && scopeDefinesGeneratedContent(element.shadowRoot, t)) {
187
+ return true
188
+ }
189
+ const slot = element.assignedSlot
190
+ if (slot && scopeDefinesGeneratedContent(rootNodeOf(slot), t)) {
191
+ return true
192
+ }
193
+ if (element.hasAttribute('part')) {
194
+ for (let host = (rootNodeOf(element) as ShadowRoot).host; host; host = (rootNodeOf(host) as ShadowRoot).host) {
195
+ if (scopeDefinesGeneratedContent(rootNodeOf(host), t)) {
196
+ return true
197
+ }
198
+ }
199
+ }
200
+ return false
201
+ }
202
+
203
+ // Generated content of ::before and ::after, read once per element and only
204
+ // when some sheet in scope can define it: pseudo-element style reads are the
205
+ // most expensive kind, and every element in a name-from-content traversal
206
+ // would otherwise pay two.
207
+ function pseudoContent(element: Element, pseudo: '::before' | '::after', t: Traversal): string {
208
+ let texts = t.context.generated.get(element)
209
+ if (texts === undefined) {
210
+ texts = mayHaveGeneratedContent(element, t)
211
+ ? [readPseudoContent(element, '::before', t), readPseudoContent(element, '::after', t)]
212
+ : ['', '']
213
+ t.context.generated.set(element, texts)
214
+ }
215
+ return pseudo === '::before' ? texts[0] : texts[1]
216
+ }
217
+
218
+ // The index just past the quoted string that opens at `start`.
219
+ function endOfString(content: string, start: number): number {
220
+ const quote = content[start]
221
+ let i = start + 1
222
+ while (i < content.length && content[i] !== quote) {
223
+ if (content[i] === '\\' && i + 1 < content.length) {
224
+ i++
225
+ }
226
+ i++
227
+ }
228
+ return i + 1
229
+ }
230
+
231
+ // The index just past the function whose opening parenthesis is at `start`,
232
+ // so url("...") and the like, whose quoted arguments are not text, are read
233
+ // as one token.
234
+ function endOfFunction(content: string, start: number): number {
235
+ let depth = 0
236
+ let i = start
237
+ while (i < content.length) {
238
+ const char = content[i]
239
+ if (char === '"' || char === "'") {
240
+ i = endOfString(content, i)
241
+ continue
242
+ }
243
+ if (char === '(') {
244
+ depth++
245
+ } else if (char === ')' && --depth === 0) {
246
+ return i + 1
247
+ }
248
+ i++
249
+ }
250
+ return i
251
+ }
252
+
253
+ // An attr() token in computed `content`: Chromium resolves it to a string
254
+ // before serialising, Firefox keeps the function, so the attribute is read
255
+ // from the originating element here. Only the attribute name is read; a
256
+ // fallback or type argument is ignored, as the attribute's string value is
257
+ // what both engines render.
258
+ function readAttrToken(element: Element, token: string): string {
259
+ const match = /^attr\(\s*([^\s,)]+)/.exec(token)
260
+ return match ? element.getAttribute(match[1]) || '' : ''
261
+ }
262
+
263
+ // The computed `content` is a list of strings and other tokens; only the
264
+ // strings and attr() references are text, and a bare slash introduces
265
+ // alternative text that replaces everything before it. A slash inside a
266
+ // quoted string is just a character, and a quoted string inside a function
267
+ // (the URL of an image) is not text. A pseudo-element that is not rendered
268
+ // has no text at all.
269
+ function readPseudoContent(element: Element, pseudo: string, t: Traversal): string {
270
+ const style = styleOf(element, t.context, pseudo)
271
+ if (!style || style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') {
272
+ return ''
273
+ }
274
+ const content = style.content
275
+ if (!content || content === 'none' || content === 'normal') {
276
+ return ''
277
+ }
278
+ let text = ''
279
+ let i = 0
280
+ while (i < content.length) {
281
+ const char = content[i]
282
+ if (char === '"' || char === "'") {
283
+ const end = endOfString(content, i)
284
+ text += content.slice(i + 1, end - 1).replace(/\\(.)/g, '$1')
285
+ i = end
286
+ } else if (char === '(') {
287
+ const end = endOfFunction(content, i)
288
+ const start = content.lastIndexOf(' ', i) + 1
289
+ text += readAttrToken(element, content.slice(start, end))
290
+ i = end
291
+ } else if (char === '/') {
292
+ text = ''
293
+ i++
294
+ } else {
295
+ i++
296
+ }
297
+ }
298
+ return text
299
+ }
300
+
301
+ function isInline(element: Element, t: Traversal): boolean {
302
+ const style = styleOf(element, t.context)
303
+ return !style || INLINE_DISPLAYS.has(style.display)
304
+ }
305
+
306
+ // 2F: the concatenated text alternatives of the children, with generated
307
+ // content around them and block-level children set off by spaces.
308
+ //
309
+ // Cached per element for the traversal every enclosing content-named
310
+ // ancestor repeats (a cell's text is wanted by the row, then by the cell, then
311
+ // by a link inside it): no reference being followed, no hidden content
312
+ // included, no control skipped, a name rather than a description. The
313
+ // `recursive` flag does not change the result, since children are always
314
+ // traversed as recursive. Other traversals compute afresh.
315
+ function fromContent(element: Element, t: Traversal): string {
316
+ const cacheable = !t.inReference && !t.includeHidden && t.skip === null && !t.describing
317
+ if (!cacheable) {
318
+ return computeContentText(element, t)
319
+ }
320
+ let text = t.context.contentTexts.get(element)
321
+ if (text === undefined) {
322
+ text = computeContentText(element, t)
323
+ t.context.contentTexts.set(element, text)
324
+ }
325
+ return text
326
+ }
327
+
328
+ function computeContentText(element: Element, t: Traversal): string {
329
+ // An invisible element's own text and generated content are not rendered;
330
+ // visibility is inherited, so only descendants that set themselves visible
331
+ // again contribute, through the recursion below.
332
+ const ownTextHidden = !t.includeHidden && hiddenState(element, t.context) === 'self'
333
+ let text = ownTextHidden ? '' : pseudoContent(element, '::before', t)
334
+ const textCollapsed = isClosedDetails(element)
335
+ const children = flatTreeChildren(element)
336
+ for (let i = 0; i < children.length; i++) {
337
+ const child = children[i]
338
+ if (child.nodeType === TEXT_NODE) {
339
+ if (!ownTextHidden && !textCollapsed) {
340
+ text += child.nodeValue || ''
341
+ }
342
+ continue
343
+ }
344
+ if (child.nodeType !== ELEMENT_NODE) {
345
+ continue
346
+ }
347
+ const childElement = child as Element
348
+ if (childElement === t.skip || isCollapsedDetailsContent(childElement, childElement.parentElement || element)) {
349
+ continue
350
+ }
351
+ if (childElement.localName === 'br') {
352
+ text += ' '
353
+ continue
354
+ }
355
+ const childState = t.includeHidden ? 'rendered' : hiddenState(childElement, t.context)
356
+ if (childState === 'subtree' || childState === 'contents') {
357
+ continue
358
+ }
359
+ // An invisible child has no text alternative of its own (2A); only what
360
+ // is visible below it counts.
361
+ const childText =
362
+ childState === 'self'
363
+ ? fromContent(childElement, { ...t, recursive: true })
364
+ : textAlternative(childElement, { ...t, recursive: true })
365
+ text += isInline(childElement, t) ? childText : ` ${childText} `
366
+ }
367
+ return text + (ownTextHidden ? '' : pseudoContent(element, '::after', t))
368
+ }
369
+
370
+ function firstChildNamed(element: Element, localName: string): Element | null {
371
+ for (let child = element.firstElementChild; child; child = child.nextElementSibling) {
372
+ if (child.localName === localName) {
373
+ return child
374
+ }
375
+ }
376
+ return null
377
+ }
378
+
379
+ // html-aam: the labels of a labelable element, each traversed with the
380
+ // control itself left out so a wrapping label does not include its value.
381
+ function fromLabels(element: Element, t: Traversal): string | null {
382
+ const labels = (element as HTMLInputElement).labels
383
+ if (!labels || labels.length === 0) {
384
+ return null
385
+ }
386
+ const parts: string[] = []
387
+ for (let i = 0; i < labels.length; i++) {
388
+ const label = labels[i]
389
+ parts.push(fromContent(label, { ...t, recursive: true, includeHidden: isHidden(label, t.context), skip: element }))
390
+ }
391
+ const text = normalize(parts.join(' '))
392
+ return text !== '' ? text : null
393
+ }
394
+
395
+ function inputNativeName(input: HTMLInputElement, t: Traversal): string | null {
396
+ switch (input.type) {
397
+ case 'button':
398
+ case 'reset':
399
+ case 'submit': {
400
+ // html-aam: label elements, then the value, then the user agent's
401
+ // default button labels.
402
+ const label = fromLabels(input, t)
403
+ if (label !== null) {
404
+ return label
405
+ }
406
+ const value = attribute(input, 'value')
407
+ if (value !== null) {
408
+ return value
409
+ }
410
+ return input.type === 'submit' ? 'Submit' : input.type === 'reset' ? 'Reset' : null
411
+ }
412
+ case 'image':
413
+ return attribute(input, 'alt') || fromLabels(input, t) || attribute(input, 'value')
414
+ default:
415
+ return fromLabels(input, t)
416
+ }
417
+ }
418
+
419
+ // 2D: text alternatives the host language defines.
420
+ function nativeName(element: Element, t: Traversal): string | null {
421
+ switch (element.localName) {
422
+ case 'html':
423
+ return (element.ownerDocument.title || '').trim() || null
424
+ case 'input':
425
+ return inputNativeName(element as HTMLInputElement, t)
426
+ case 'button':
427
+ case 'meter':
428
+ case 'output':
429
+ case 'progress':
430
+ case 'select':
431
+ case 'textarea':
432
+ return fromLabels(element, t)
433
+ case 'fieldset': {
434
+ const legend = firstChildNamed(element, 'legend')
435
+ return legend ? normalize(fromContent(legend, { ...t, recursive: true })) || null : null
436
+ }
437
+ case 'figure': {
438
+ const caption = firstChildNamed(element, 'figcaption')
439
+ return caption ? normalize(fromContent(caption, { ...t, recursive: true })) || null : null
440
+ }
441
+ case 'table': {
442
+ const caption = firstChildNamed(element, 'caption')
443
+ return caption ? normalize(fromContent(caption, { ...t, recursive: true })) || null : null
444
+ }
445
+ case 'img':
446
+ case 'area':
447
+ return attribute(element, 'alt')
448
+ case 'optgroup':
449
+ return attribute(element, 'label')
450
+ case 'option':
451
+ return attribute(element, 'label')
452
+ case 'svg': {
453
+ const title = firstChildNamed(element, 'title')
454
+ return title ? normalize(title.textContent || '') || null : null
455
+ }
456
+ default:
457
+ return null
458
+ }
459
+ }
460
+
461
+ function placeholder(element: Element): string | null {
462
+ if (element.localName === 'textarea') {
463
+ return attribute(element, 'placeholder')
464
+ }
465
+ if (element.localName === 'input' && TEXT_INPUT_TYPES.has((element as HTMLInputElement).type)) {
466
+ return attribute(element, 'placeholder')
467
+ }
468
+ return null
469
+ }
470
+
471
+ // The traversal every content-named ancestor repeats for the same descendant:
472
+ // a cell is a descendant of its row, a link of its cell. Its result depends
473
+ // on nothing but the element, so it is cached per element; the top-level
474
+ // result (computeName) differs in steps 2C, 2E and 2F and has its own cache.
475
+ function isStandardDescendantTraversal(t: Traversal): boolean {
476
+ return t.recursive && !t.inReference && !t.includeHidden && t.skip === null && !t.describing
477
+ }
478
+
479
+ function textAlternative(node: Node, t: Traversal): string {
480
+ if (node.nodeType === TEXT_NODE) {
481
+ return node.nodeValue || ''
482
+ }
483
+ if (node.nodeType !== ELEMENT_NODE) {
484
+ return ''
485
+ }
486
+ const element = node as Element
487
+ if (!isStandardDescendantTraversal(t)) {
488
+ return computeTextAlternative(element, t).text
489
+ }
490
+ let text = t.context.descendantTexts.get(element)
491
+ if (text === undefined) {
492
+ text = computeTextAlternative(element, t).text
493
+ t.context.descendantTexts.set(element, text)
494
+ }
495
+ return text
496
+ }
497
+
498
+ // The computation for one element, also used for the element being named.
499
+ function computeTextAlternative(element: Element, t: Traversal): NameResult {
500
+ const role = roleOf(element, t.context)
501
+ const embedded = (t.recursive || t.inReference) && isEmbeddedControl(role)
502
+
503
+ // 2B
504
+ if (!t.inReference) {
505
+ const referenced = fromReferences(element, t.describing ? 'aria-describedby' : 'aria-labelledby', t)
506
+ if (referenced !== '') {
507
+ return { text: referenced, source: 'reference' }
508
+ }
509
+ }
510
+ // 2C. The element being described does not take aria-label; a referenced
511
+ // element does, because its text alternative is what is being read.
512
+ if (!t.describing || t.inReference) {
513
+ const label = attribute(element, 'aria-label')
514
+ if (label !== null && !embedded) {
515
+ return { text: normalize(label), source: 'label' }
516
+ }
517
+ }
518
+ // 2E, ahead of 2D: a control reached while naming something else
519
+ // contributes its value, not its own label. That is what the user sees in
520
+ // the enclosing label, and it is also what stops two labels that wrap each
521
+ // other's control from recursing without end.
522
+ if (embedded) {
523
+ const value = embeddedValue(element, role)
524
+ if (value !== null) {
525
+ return { text: normalize(value), source: 'native' }
526
+ }
527
+ }
528
+ // 2D. A present alt attribute is the final answer for an image, even when
529
+ // empty (html-aam): a decorative image does not pick up its title.
530
+ if ((element.localName === 'img' || element.localName === 'area') && element.hasAttribute('alt')) {
531
+ return { text: normalize(element.getAttribute('alt') || ''), source: 'native' }
532
+ }
533
+ const native = nativeName(element, t)
534
+ if (native !== null && normalize(native) !== '') {
535
+ return { text: normalize(native), source: 'native' }
536
+ }
537
+ // 2F, 2H
538
+ if (NAME_FROM_CONTENT.has(role) || t.recursive || t.inReference) {
539
+ const content = normalize(fromContent(element, t))
540
+ if (content !== '') {
541
+ return { text: content, source: 'content' }
542
+ }
543
+ }
544
+ // 2I
545
+ const title = attribute(element, 'title')
546
+ if (title !== null) {
547
+ return { text: normalize(title), source: 'title' }
548
+ }
549
+ const hint = placeholder(element)
550
+ if (hint !== null) {
551
+ return { text: normalize(hint), source: 'placeholder' }
552
+ }
553
+ return { text: '', source: 'none' }
554
+ }
555
+
556
+ function traversal(context: SnapshotContext, describing: boolean): Traversal {
557
+ return { context, describing, inReference: false, recursive: false, includeHidden: false, skip: null }
558
+ }
559
+
560
+ /** The accessible name of an element and where it came from. */
561
+ export function computeName(element: Element, context: SnapshotContext): NameResult {
562
+ let result = context.names.get(element)
563
+ if (result === undefined) {
564
+ result = computeTextAlternative(element, traversal(context, false))
565
+ context.names.set(element, result)
566
+ }
567
+ return result
568
+ }
569
+
570
+ /** The accessible description: aria-describedby, aria-description, then title when the name did not use it. */
571
+ export function computeDescription(element: Element, context: SnapshotContext): string {
572
+ let description = context.descriptions.get(element)
573
+ if (description === undefined) {
574
+ description = fromReferences(element, 'aria-describedby', traversal(context, true))
575
+ if (description === '') {
576
+ const inline = attribute(element, 'aria-description')
577
+ if (inline !== null) {
578
+ description = normalize(inline)
579
+ } else {
580
+ const title = attribute(element, 'title')
581
+ description = title !== null && computeName(element, context).source !== 'title' ? normalize(title) : ''
582
+ }
583
+ }
584
+ context.descriptions.set(element, description)
585
+ }
586
+ return description
587
+ }