-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser.ts
More file actions
755 lines (659 loc) · 25.2 KB
/
Copy pathbrowser.ts
File metadata and controls
755 lines (659 loc) · 25.2 KB
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
import type {
SemanticNode,
SemanticNodeState,
SemanticTreeChange,
SemanticTreeObserverOptions,
SemanticTreeOptions,
} from "./types";
type WalkContext = {
options: Required<SemanticTreeOptions>;
nextId: number;
rootDocument: Document;
};
const defaultOptions: Required<SemanticTreeOptions> = {
mode: "compact",
includeBounds: true,
includeAttributes: true,
includeTextNodes: true,
includeHidden: false,
includeSelectOptions: true,
excludeLikelyAds: false,
excludeLikelyBoilerplate: false,
pruneCustomElementWrappers: true,
pruneCollapsedSubtrees: true,
pruneLikelyClosedOverlays: false,
summarizeLargeSubtrees: false,
summarizeLikelyLinkFarms: false,
summarizeRepeatedSubtrees: false,
maxChildrenPerNode: 80,
maxLinkFarmChildren: 24,
maxRepeatedSubtreeInstances: 3,
maxTextLength: 240,
};
const defaultObserverOptions: Required<Pick<SemanticTreeObserverOptions, "debounceMs">> = {
debounceMs: 50,
};
const interactiveRoles = new Set([
"button",
"checkbox",
"combobox",
"link",
"listbox",
"menuitem",
"menuitemcheckbox",
"menuitemradio",
"option",
"radio",
"searchbox",
"slider",
"spinbutton",
"switch",
"tab",
"textbox",
"treeitem",
]);
const landmarkTags: Record<string, string> = {
article: "article",
aside: "complementary",
footer: "contentinfo",
form: "form",
header: "banner",
main: "main",
nav: "navigation",
section: "region",
};
const rolesNamedFromContents = new Set([
"button",
"cell",
"checkbox",
"columnheader",
"heading",
"link",
"menuitem",
"menuitemcheckbox",
"menuitemradio",
"option",
"radio",
"rowheader",
"switch",
"tab",
"treeitem",
]);
export function extractSemanticTree(options: SemanticTreeOptions = {}): SemanticNode {
const rootDocument = document;
const context: WalkContext = {
options: { ...defaultOptions, ...options },
nextId: 1,
rootDocument,
};
return (
walkElement(rootDocument.body ?? rootDocument.documentElement, context) ??
unavailableNode(context, "document", "Document has no inspectable body")
);
}
export { extractSemanticTree as extract };
export function formatSemanticTreeText(node: SemanticNode): string {
const lines: string[] = [];
function visit(current: SemanticNode, depth: number): void {
const prefix = " ".repeat(depth);
const role = current.role ?? current.tag;
const marker = current.interactive ? "[i] " : "";
const name = current.name ? ` '${current.name}'` : "";
const state = formatState(current.state);
const unavailable = current.unavailableReason ? ` (${current.unavailableReason})` : "";
lines.push(`${prefix}${marker}${role}${name}${state}${unavailable}`);
for (const child of current.children) visit(child, depth + 1);
}
visit(node, 0);
return lines.join("\n");
}
export function observeSemanticTree(
onChange: (change: SemanticTreeChange) => void,
options: SemanticTreeObserverOptions = {},
): { disconnect: () => void; snapshot: () => SemanticNode } {
const root = document.documentElement;
const observerOptions = { ...defaultObserverOptions, ...options };
let mutationCount = 0;
let timeoutId: number | undefined;
function snapshot(): SemanticNode {
return extractSemanticTree(options);
}
function emit(): void {
timeoutId = undefined;
onChange({
tree: snapshot(),
changedAt: Date.now(),
mutationCount,
});
mutationCount = 0;
}
const observer = new MutationObserver((mutations) => {
mutationCount += mutations.length;
if (timeoutId !== undefined) window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(emit, observerOptions.debounceMs);
});
observer.observe(root, {
attributes: true,
characterData: true,
childList: true,
subtree: true,
});
return {
disconnect() {
if (timeoutId !== undefined) window.clearTimeout(timeoutId);
observer.disconnect();
},
snapshot,
};
}
function walkElement(element: Element, context: WalkContext): SemanticNode | null {
if (!context.options.includeHidden && isHidden(element)) return null;
if (context.options.excludeLikelyAds && isLikelyAd(element)) return null;
const role = getRole(element);
const state = getState(element, context);
const focusable = isFocusable(element);
const interactive = isInteractive(element, role, focusable);
const name = role ? computeName(element, role, context) : "";
const description = computeDescription(element, context);
const tag = element.tagName.toLowerCase();
const children = collectChildren(element, context);
if (context.options.mode === "interactive" && !interactive) {
return children.length > 0
? containerNode(context, tag, children)
: null;
}
if (shouldPrune(element, role, name, interactive, children, context)) {
return children.length === 1 ? children[0] ?? null : containerNode(context, tag, children);
}
const node: SemanticNode = {
id: nextId(context),
tag,
role,
name,
interactive,
focusable,
children,
};
if (description) node.description = description;
const text = getDirectText(element, context.options.maxTextLength);
if (text) node.text = text;
const value = getValue(element);
if (value) node.value = value;
if (Object.keys(state).length > 0) node.state = state;
node.selector = getCssPath(element);
node.xpath = getXPath(element);
if (context.options.includeBounds) node.bounds = getBounds(element);
if (context.options.includeAttributes) node.attributes = getAttributes(element);
appendSpecialChildren(element, node, context);
appendShadowChildren(element, node, context);
appendFrameChildren(element, node, context);
return node;
}
function collectChildren(element: Element, context: WalkContext): SemanticNode[] {
const children: SemanticNode[] = [];
for (const child of Array.from(element.childNodes)) {
if (child.nodeType === Node.ELEMENT_NODE) {
if (!context.options.includeSelectOptions && element instanceof HTMLSelectElement) continue;
const semanticChild = walkElement(child as Element, context);
if (semanticChild) children.push(semanticChild);
continue;
}
if (context.options.includeTextNodes && child.nodeType === Node.TEXT_NODE) {
const text = normalizeText(child.textContent ?? "", context.options.maxTextLength);
if (text) {
children.push({
id: nextId(context),
tag: "#text",
role: "text",
name: text,
text,
interactive: false,
focusable: false,
children: [],
});
}
}
}
return children;
}
function shouldPrune(
element: Element,
role: string | null,
name: string,
interactive: boolean,
children: SemanticNode[],
context: WalkContext,
): boolean {
if (context.options.mode === "full") return false;
if (role === "none" || role === "presentation") return true;
if (interactive) return false;
if (context.options.pruneCustomElementWrappers && isCustomElement(element)) return children.length > 0;
if (role && role !== "generic") return false;
if (name) return false;
if (element.id || element.getAttribute("aria-label") || element.getAttribute("aria-labelledby")) return false;
return children.length > 0;
}
function getRole(element: Element): string | null {
const explicit = firstToken(element.getAttribute("role"));
if (explicit) return explicit;
const tag = element.tagName.toLowerCase();
if (tag === "section" && !hasExplicitNameSource(element)) return null;
if (tag === "form" && !hasExplicitNameSource(element)) return null;
if (tag in landmarkTags) return landmarkTags[tag] ?? null;
if (/^h[1-6]$/.test(tag)) return "heading";
if (tag === "a" || tag === "area") return element.hasAttribute("href") ? "link" : null;
if (tag === "button") return "button";
if (tag === "details") return "group";
if (tag === "dialog") return "dialog";
if (tag === "fieldset") return "group";
if (tag === "figure") return "figure";
if (tag === "iframe") return "iframe";
if (tag === "img") return hasEmptyAlt(element) ? "presentation" : "img";
if (tag === "li") return "listitem";
if (tag === "ol" || tag === "ul") return "list";
if (tag === "optgroup") return "group";
if (tag === "option") return "option";
if (tag === "output") return "status";
if (tag === "progress") return "progressbar";
if (tag === "select") return element.hasAttribute("multiple") ? "listbox" : "combobox";
if (tag === "summary") return "button";
if (tag === "table") return "table";
if (tag === "caption") return "caption";
if (tag === "tbody" || tag === "tfoot" || tag === "thead") return "rowgroup";
if (tag === "td") return "cell";
if (tag === "textarea") return "textbox";
if (tag === "th") return element.getAttribute("scope") === "row" ? "rowheader" : "columnheader";
if (tag === "tr") return "row";
if (tag === "input") return inputRole(element as HTMLInputElement);
return null;
}
function inputRole(input: HTMLInputElement): string | null {
const type = (input.getAttribute("type") || "text").toLowerCase();
if (type === "button" || type === "image" || type === "reset" || type === "submit") return "button";
if (type === "checkbox") return "checkbox";
if (type === "email" || type === "tel" || type === "text" || type === "url") return "textbox";
if (type === "number") return "spinbutton";
if (type === "radio") return "radio";
if (type === "range") return "slider";
if (type === "search") return "searchbox";
if (type === "hidden") return null;
return "textbox";
}
function computeName(element: Element, role: string, context: WalkContext): string {
if (element.getAttribute("aria-labelledby")) {
const labelled = textFromIds(element.getAttribute("aria-labelledby") ?? "", context.rootDocument);
if (labelled) return labelled;
}
const ariaLabel = element.getAttribute("aria-label");
if (ariaLabel) return normalizeText(ariaLabel, context.options.maxTextLength);
if (element instanceof HTMLInputElement && isButtonLikeInput(element)) {
return normalizeText(element.value || element.getAttribute("value") || inputFallbackName(element), context.options.maxTextLength);
}
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
const label = labelText(element, context);
if (label) return label;
const placeholder = element.getAttribute("placeholder");
if (placeholder) return normalizeText(placeholder, context.options.maxTextLength);
}
if (element instanceof HTMLImageElement) {
return normalizeText(element.alt || element.getAttribute("title") || "", context.options.maxTextLength);
}
if (element instanceof HTMLFieldSetElement) {
const legend = element.querySelector(":scope > legend");
if (legend) return getVisibleText(legend, context.options.maxTextLength);
}
if (rolesNamedFromContents.has(role)) {
const ownText = getVisibleText(element, context.options.maxTextLength);
if (ownText) return ownText;
}
return normalizeText(element.getAttribute("title") ?? "", context.options.maxTextLength);
}
function computeDescription(element: Element, context: WalkContext): string {
const describedBy = element.getAttribute("aria-describedby");
if (describedBy) return textFromIds(describedBy, context.rootDocument);
return normalizeText(element.getAttribute("title") ?? "", context.options.maxTextLength);
}
function labelText(
element: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement,
context: WalkContext,
): string {
if (element.labels && element.labels.length > 0) {
return normalizeText(Array.from(element.labels).map((label) => getVisibleText(label, context.options.maxTextLength)).join(" "), context.options.maxTextLength);
}
return "";
}
function getState(element: Element, context: WalkContext): SemanticNodeState {
const state: SemanticNodeState = {};
if (isHidden(element)) state.hidden = true;
if (isDisabled(element)) state.disabled = true;
const busy = ariaBoolean(element.getAttribute("aria-busy"));
if (busy !== undefined) state.busy = busy;
const multiselectable = ariaBoolean(element.getAttribute("aria-multiselectable"));
if (multiselectable !== undefined) state.multiselectable = multiselectable;
const sort = element.getAttribute("aria-sort");
if (sort) state.sort = normalizeText(sort, 40);
const grabbed = ariaBoolean(element.getAttribute("aria-grabbed"));
if (grabbed !== undefined) state.grabbed = grabbed;
const dropEffect = element.getAttribute("aria-dropeffect");
if (dropEffect) state.dropEffect = normalizeText(dropEffect, 80);
if (element === document.activeElement) state.focused = true;
const checked = ariaBooleanOrMixed(element.getAttribute("aria-checked"));
if (checked !== undefined) state.checked = checked;
else if (element instanceof HTMLInputElement && (element.type === "checkbox" || element.type === "radio")) {
state.checked = element.checked;
}
const selected = ariaBoolean(element.getAttribute("aria-selected"));
if (selected !== undefined) state.selected = selected;
else if (element instanceof HTMLOptionElement) state.selected = element.selected;
const expanded = ariaBoolean(element.getAttribute("aria-expanded"));
if (expanded !== undefined) state.expanded = expanded;
const pressed = ariaBooleanOrMixed(element.getAttribute("aria-pressed"));
if (pressed !== undefined) state.pressed = pressed;
const required = ariaBoolean(element.getAttribute("aria-required"));
if (required !== undefined) state.required = required;
else if ("required" in element && Boolean((element as HTMLInputElement).required)) state.required = true;
const invalid = element.getAttribute("aria-invalid");
if (invalid && invalid !== "false") state.invalid = invalid === "true" ? true : invalid;
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
if (element.readOnly) state.readonly = true;
}
const current = element.getAttribute("aria-current");
if (current && current !== "false") state.current = current === "true" ? true : current;
const haspopup = element.getAttribute("aria-haspopup");
if (haspopup && haspopup !== "false") state.haspopup = haspopup === "true" ? true : haspopup;
const controls = element.getAttribute("aria-controls");
if (controls) state.controls = normalizeText(controls, context.options.maxTextLength);
const live = element.getAttribute("aria-live");
if (live) state.live = normalizeText(live, context.options.maxTextLength);
if (element.getAttribute("aria-modal") === "true") state.modal = true;
const orientation = element.getAttribute("aria-orientation");
if (orientation) state.orientation = normalizeText(orientation, 40);
const valueMin = ariaNumber(element.getAttribute("aria-valuemin"));
if (typeof valueMin === "number") state.valueMin = valueMin;
const valueMax = ariaNumber(element.getAttribute("aria-valuemax"));
if (typeof valueMax === "number") state.valueMax = valueMax;
const valueNow = ariaNumber(element.getAttribute("aria-valuenow"));
if (typeof valueNow === "number") state.valueNow = valueNow;
const valueText = element.getAttribute("aria-valuetext");
if (valueText) state.valueText = normalizeText(valueText, context.options.maxTextLength);
return state;
}
function isHidden(element: Element): boolean {
if (element.hasAttribute("hidden")) return true;
if (element.getAttribute("aria-hidden") === "true") return true;
const style = getComputedStyle(element);
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.contentVisibility === "hidden"
) return true;
if (Number(style.opacity) === 0) return true;
return false;
}
function isLikelyAd(element: Element): boolean {
const haystack = [
element.id,
element.getAttribute("class"),
element.getAttribute("aria-label"),
element.getAttribute("data-testid"),
element.getAttribute("data-test-id"),
element.getAttribute("data-name"),
].filter(Boolean).join(" ").toLowerCase();
if (/\b(ad|ads|advert|advertisement|sponsor|sponsored|placement)\b/.test(haystack)) return true;
if (element instanceof HTMLAnchorElement && normalizeText(element.textContent ?? "", 80).toLowerCase() === "ad") return true;
return false;
}
function isDisabled(element: Element): boolean {
if (element.getAttribute("aria-disabled") === "true") return true;
return "disabled" in element && Boolean((element as HTMLButtonElement).disabled);
}
function isFocusable(element: Element): boolean {
if (isDisabled(element) || isHidden(element)) return false;
const tabindex = element.getAttribute("tabindex");
if (tabindex !== null) return Number(tabindex) >= 0;
return element.matches("a[href],area[href],button,input,select,textarea,summary,iframe,[contenteditable=''],[contenteditable='true']");
}
function isInteractive(element: Element, role: string | null, focusable: boolean): boolean {
if (role && interactiveRoles.has(role)) return true;
if (element.matches("a[href],button,input,select,textarea,summary,option")) return true;
if (element.hasAttribute("onclick")) return true;
return focusable && Boolean(role);
}
function appendSpecialChildren(element: Element, node: SemanticNode, context: WalkContext): void {
if (!context.options.includeSelectOptions) return;
if (element instanceof HTMLSelectElement) {
for (const option of Array.from(element.options)) {
node.children.push({
id: nextId(context),
tag: "option",
role: "option",
name: normalizeText(option.textContent ?? "", context.options.maxTextLength),
value: option.value,
state: { selected: option.selected, disabled: option.disabled },
interactive: false,
focusable: false,
selector: getCssPath(option),
xpath: getXPath(option),
children: [],
});
}
}
}
function isCustomElement(element: Element): boolean {
return element.tagName.includes("-");
}
function appendShadowChildren(element: Element, node: SemanticNode, context: WalkContext): void {
const shadowRoot = element.shadowRoot;
if (!shadowRoot) return;
for (const child of Array.from(shadowRoot.children)) {
const semanticChild = walkElement(child, context);
if (semanticChild) node.children.push(semanticChild);
}
}
function appendFrameChildren(element: Element, node: SemanticNode, context: WalkContext): void {
if (!(element instanceof HTMLIFrameElement)) return;
try {
const frameDocument = element.contentDocument;
if (!frameDocument?.body) {
node.children.push(unavailableNode(context, "iframe", "iframe document unavailable"));
return;
}
const previousDocument = context.rootDocument;
context.rootDocument = frameDocument;
const child = walkElement(frameDocument.body, context);
context.rootDocument = previousDocument;
if (child) node.children.push(child);
} catch {
node.children.push(unavailableNode(context, "iframe", "cross-origin iframe"));
}
}
function unavailableNode(context: WalkContext, tag: string, reason: string): SemanticNode {
return {
id: nextId(context),
tag,
role: null,
name: "",
interactive: false,
focusable: false,
unavailableReason: reason,
children: [],
};
}
function containerNode(context: WalkContext, tag: string, children: SemanticNode[]): SemanticNode {
return {
id: nextId(context),
tag,
role: null,
name: "",
interactive: false,
focusable: false,
children,
};
}
function getValue(element: Element): string {
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
return element.value;
}
return normalizeText(element.getAttribute("aria-valuetext") ?? element.getAttribute("aria-valuenow") ?? "", 80);
}
function getDirectText(element: Element, maxLength: number): string {
return normalizeText(
Array.from(element.childNodes)
.filter((node) => node.nodeType === Node.TEXT_NODE)
.map((node) => node.textContent ?? "")
.join(" "),
maxLength,
);
}
function getVisibleText(element: Element, maxLength: number): string {
const parts: string[] = [];
function visit(node: Node): void {
if (node.nodeType === Node.TEXT_NODE) {
parts.push(node.textContent ?? "");
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const childElement = node as Element;
if (isHidden(childElement)) return;
for (const child of Array.from(childElement.childNodes)) visit(child);
}
visit(element);
return normalizeText(parts.join(" "), maxLength);
}
function getAttributes(element: Element): Record<string, string> {
const attributes: Record<string, string> = {};
for (const attribute of Array.from(element.attributes)) {
if (
attribute.name === "id" ||
attribute.name === "href" ||
attribute.name === "type" ||
attribute.name === "role" ||
attribute.name === "alt" ||
attribute.name === "title" ||
attribute.name.startsWith("aria-") ||
attribute.name.startsWith("data-")
) {
attributes[attribute.name] = attribute.value;
}
}
return attributes;
}
function getBounds(element: Element) {
const rect = element.getBoundingClientRect();
return {
x: round(rect.x),
y: round(rect.y),
width: round(rect.width),
height: round(rect.height),
};
}
function getCssPath(element: Element): string {
if (element.id) return `#${cssEscape(element.id)}`;
const segments: string[] = [];
let current: Element | null = element;
while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.documentElement) {
const elementAtLevel: Element = current;
const tag = elementAtLevel.tagName.toLowerCase();
const parent: Element | null = elementAtLevel.parentElement;
if (!parent) {
segments.unshift(tag);
break;
}
const siblings = Array.from(parent.children).filter((child) => child.tagName === elementAtLevel.tagName);
const index = siblings.indexOf(elementAtLevel) + 1;
segments.unshift(siblings.length > 1 ? `${tag}:nth-of-type(${index})` : tag);
current = parent;
}
return segments.join(" > ");
}
function getXPath(element: Element): string {
const segments: string[] = [];
let current: Element | null = element;
while (current && current.nodeType === Node.ELEMENT_NODE) {
const elementAtLevel: Element = current;
const tag = elementAtLevel.tagName.toLowerCase();
const parent: Element | null = elementAtLevel.parentElement;
if (!parent) {
segments.unshift(`/${tag}[1]`);
break;
}
const sameTag = Array.from(parent.children).filter((child) => child.tagName === elementAtLevel.tagName);
segments.unshift(`/${tag}[${sameTag.indexOf(elementAtLevel) + 1}]`);
current = parent;
}
return segments.join("");
}
function textFromIds(ids: string, rootDocument: Document): string {
return normalizeText(
ids
.split(/\s+/)
.map((id) => {
const element = rootDocument.getElementById(id);
return element ? getVisibleText(element, 240) : "";
})
.filter(Boolean)
.join(" "),
240,
);
}
function normalizeText(value: string, maxLength: number): string {
const normalized = value.replace(/\s+/g, " ").trim();
return normalized.length > maxLength ? `${normalized.slice(0, maxLength - 1)}…` : normalized;
}
function firstToken(value: string | null): string | null {
return value?.trim().split(/\s+/)[0] || null;
}
function hasExplicitNameSource(element: Element): boolean {
return Boolean(
element.getAttribute("aria-label") ||
element.getAttribute("aria-labelledby") ||
element.getAttribute("title"),
);
}
function hasEmptyAlt(element: Element): boolean {
return element.hasAttribute("alt") && element.getAttribute("alt") === "";
}
function isButtonLikeInput(input: HTMLInputElement): boolean {
return ["button", "image", "reset", "submit"].includes((input.getAttribute("type") || "").toLowerCase());
}
function inputFallbackName(input: HTMLInputElement): string {
const type = (input.getAttribute("type") || "").toLowerCase();
if (type === "submit") return "Submit";
if (type === "reset") return "Reset";
return "";
}
function ariaBoolean(value: string | null): boolean | undefined {
if (value === "true") return true;
if (value === "false") return false;
return undefined;
}
function ariaBooleanOrMixed(value: string | null): boolean | "mixed" | undefined {
if (value === "mixed") return "mixed";
return ariaBoolean(value);
}
function ariaNumber(value: string | null): number | undefined {
if (value === null || value.trim() === "") return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
function formatState(state: SemanticNodeState | undefined): string {
if (!state) return "";
const entries = Object.entries(state).filter(([, value]) => value !== undefined);
return entries.length > 0
? ` [${entries.map(([key, value]) => `${key}=${String(value)}`).join(" ")}]`
: "";
}
function nextId(context: WalkContext): string {
const id = `n${context.nextId}`;
context.nextId += 1;
return id;
}
function round(value: number): number {
return Math.round(value * 100) / 100;
}
function cssEscape(value: string): string {
if (typeof CSS !== "undefined" && typeof CSS.escape === "function") {
return CSS.escape(value);
}
return value.replace(/[^a-zA-Z0-9_-]/g, (char) => `\\${char}`);
}