-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDomTreeScript.swift
More file actions
2136 lines (2026 loc) · 88.5 KB
/
Copy pathDomTreeScript.swift
File metadata and controls
2136 lines (2026 loc) · 88.5 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
/// Produces the page-side document walker injected via the tab layer. It walks
/// the live document, decides which nodes are interactive / visible / topmost,
/// assigns each kept node a stable hashed `aloha-id` (also written back onto the
/// element as an attribute so it can be relocated by `[aloha-id="..."]`), and
/// returns a flat `metadata` array grouped into element / positioning /
/// interactivity / content. The returned id is derived in one place
/// (`alohaIdFor`) by hashing either an authored name (`#id`, `[data-testid]`) or
/// the node's frame-scoped xpath, so it stays stable across walks of the same page.
///
/// `focusInteractive` maps to the in-page `collectAllInteractive` flag: when
/// `true` every interactive node is kept/highlighted; when `false` only
/// interactive nodes lacking their own comprehensive text are highlighted.
/// `highlight` is accepted for call-site symmetry; the overlay it controls is
/// torn down separately by the caller.
nonisolated public func buildAgentDomTreeScript(highlight: Bool, focusInteractive: Bool) -> String {
let collectAllInteractive = focusInteractive
let debug = false
_ = highlight
return #"""
(() => {
const DEBUG = \#(debug);
\#(sensitiveFieldPredicateJS)
const collectDomTree = (collectAllInteractive = true, debug = false) => {
const DEBUG = debug;
const SEMANTIC_STRUCTURE_TAGS = new Set(["header", "footer", "aside", "main", "article", "fieldset", "section", "nav"]);
const comprehensiveTextCache = new WeakMap();
const descendantTextCache = new WeakMap();
const interactiveCache = new WeakMap();
const caches = {
boundingRects: new WeakMap(),
computedStyles: new WeakMap(),
scrollProperties: new WeakMap(),
elementVisibility: new WeakMap(),
elementData: new WeakMap(),
clearCache: () => {
caches.boundingRects = new WeakMap();
caches.computedStyles = new WeakMap();
caches.scrollProperties = new WeakMap();
caches.elementVisibility = new WeakMap();
caches.elementData = new WeakMap();
}
};
const INTERACTIVE_TAGS = new Set(["a", "button", "input", "select", "textarea", "details", "summary", "label", "option", "optgroup", "fieldset", "legend"]);
const INTERACTIVE_CURSORS = new Set([
"pointer", "context-menu", "help", "crosshair", "cell", "alias", "copy",
"text", "vertical-text",
"move", "grab", "grabbing", "all-scroll",
"col-resize", "row-resize", "n-resize", "e-resize", "s-resize", "w-resize",
"ne-resize", "nw-resize", "se-resize", "sw-resize", "ew-resize", "ns-resize", "nesw-resize", "nwse-resize",
"zoom-in", "zoom-out"
]);
const DISABLED_CURSORS = new Set(["not-allowed", "no-drop", "wait", "progress"]);
const HIGHLIGHT_LABEL_TAGS = new Set(["a", "button", "input", "select", "textarea", "textarea-shape", "details", "summary"]);
const LEAF_NODE_TAGS = new Set(["a", "button", "input", "select", "textarea", "summary", "details", "label", "option"]);
const INTERACTIVE_ROLES = new Set(["button", "link", "menuitem", "menuitemradio", "menuitemcheckbox", "radio", "checkbox", "tab", "switch", "slider", "spinbutton", "combobox", "searchbox", "textbox", "listbox", "option", "scrollbar"]);
const DISABLED_ATTRIBUTES = new Set(["disabled", "readonly", "aria-disabled", "aria-readonly", "hidden", "inert"]);
const ALWAYS_ACCEPTED_TAGS = new Set(["body", "div", "main", "article", "section", "nav", "header", "footer"]);
const NEVER_ACCEPTED_TAGS = new Set(["script", "style", "link", "meta", "noscript", "template"]);
const TEXT_CONTAINER_TAGS = new Set(["a", "button", "label", "option", "li", "p", "summary", "dt", "dd", "th", "td", "h1", "h2", "h3", "h4", "h5", "h6"]);
const EVENT_HANDLER_ATTRS = ["onclick", "onmousedown", "onmouseup", "ondblclick", "oncontextmenu", "onmouseenter", "onmouseleave", "onmouseover", "onmouseout", "onkeydown", "onkeyup", "onchange", "oninput", "onfocus", "onblur", "onpointerdown", "onpointerup", "onpointermove", "onpointerenter", "onpointerleave", "onpointerover", "onpointerout", "onpointercancel", "ontouchstart", "ontouchend", "ontouchmove", "ontouchcancel"];
const DROPZONE_CLASS_HINTS = ["dropzone", "drop-zone", "file-drop", "file-upload", "upload-area", "drag-drop", "file-dropzone", "upload-zone", "drop-area"];
const DRAG_EVENT_ATTRS = ["ondragover", "ondragenter", "ondragleave", "ondrop"];
function truncateText(text, maxLength = 3000) {
const length = text?.length || 0;
if (length <= maxLength) return text || "";
{
const hidden = length - maxLength;
if (hidden > 100) {
const marker = `... [content truncated, ${hidden} chars hidden] ...`;
const budget = maxLength - marker.length;
const headLength = Math.floor(budget / 2);
const tailLength = budget - headLength;
const head = text?.substring(0, headLength) || "";
const tail = text?.substring(length - tailLength) || "";
return `${head}${marker}${tail}`;
} else return text || "";
}
}
function findDescendantAriaLabel(element) {
if (!element || !element.children || element.children.length === 0 || element.children.length > 30) return null;
const queue = Array.from(element.children);
for (let i = 0; i < queue.length; i++) {
const child = queue[i];
const label = child.getAttribute("aria-label");
if (label && label.trim()) return label.trim();
const grandChildren = child.children;
if (grandChildren && grandChildren.length)
for (let j = 0; j < grandChildren.length; j++) queue.push(grandChildren[j]);
}
return null;
}
function getElementData(element) {
if (!element) return null;
if (caches.elementData.has(element)) return caches.elementData.get(element) || null;
const rect = element.getBoundingClientRect();
const style = window.getComputedStyle(element);
const el = element;
const data = {
rect,
style,
offsetWidth: el.offsetWidth || 0,
offsetHeight: el.offsetHeight || 0,
isVisible:
(el.offsetWidth || 0) > 0 &&
(el.offsetHeight || 0) > 0 &&
style.visibility !== "hidden" &&
style.display !== "none" &&
element.getAttribute("aria-hidden") !== "true",
tagName: element.tagName ? element.tagName.toLowerCase() : null
};
caches.elementData.set(element, data);
return data;
}
function getBoundingRect(element) {
const data = getElementData(element);
return data ? data.rect : null;
}
function getComputedStyleCached(element) {
const data = getElementData(element);
return data ? data.style : null;
}
const nodeMap = {};
// Document order, kept apart from nodeMap because `for...in` does not preserve it: an
// aloha-id whose hex happens to be all digits ("38397819") is a canonical array index,
// and JS enumerates those first and numerically ascending, ahead of every other key.
// The read's element order IS the page's structure, so hoisting ~2% of refs to the top
// of every read silently mis-describes the page.
const orderedIds = [];
const takenAlohaIds = new Set();
// THE ONLY PLACE AN ALOHA-ID COMES FROM. Read `identity` top to bottom; the first rung
// that answers is what gets hashed:
// 1. a name the page's authors declared (#id, [data-testid]) — survives a re-render
// that moves the element among its siblings;
// 2. the element's position — frame/shadow scope + xpath. Survives a walk of an
// unchanged page, and changes when the element moves.
// Same input, same id, on every walk. That is what lets an id from an earlier read still
// address the same element, and what lets the stuck-loop guard see a repeated click as a
// repeat instead of as a new action. It is not free: these hashed ids measure 2534 tokens
// on a /f/books read against 2316 for the base36 walk counter they replaced, so every step
// costs +218 tokens (+9.4%). A loop that ends at round three pays that back.
// The body's id is the constant hashString("|/body") on every page and every tab — an id
// need only be unique within its walk and resolvable within its page, and an iframe's body
// is never walked as a body.
// Memoised on the descriptor because the highlight labels a node sixty lines before the
// walk registers it; one memo is what lets both read one id without reordering the walk.
function alohaIdFor(descriptor, element) {
if (descriptor.alohaId) return descriptor.alohaId;
const identity = scopeKey(descriptor.contextPath) + (authoredIdentity(element) || descriptor.xpath);
return (descriptor.alohaId = uniqueAlohaId(hashString(identity)));
}
// What the page says this element IS, when it says anything durable. getAttribute("id"),
// not element.id: HTMLFormElement's named getter shadows the property, so
// <form><input name="id"></form> makes form.id return the input, not a string.
function authoredIdentity(element) {
if (!element || !element.getAttribute) return null;
const authored = element.getAttribute("id");
if (authored && !looksGenerated(authored)) return `#${authored}`;
const testId = element.getAttribute("data-testid") || element.getAttribute("data-test");
return testId && !looksGenerated(testId) ? `@${testId}` : null;
}
// Refuse a name the framework minted this render. #ember1234, #mui-5 and #radix-:r1: are
// renumbered on remount, so hashing one would make the id LESS stable than the position it
// replaced — on exactly the pages this change exists for.
// KNOWN CEILING: two regexes, not a framework list. Widen if real ids start churning between walks.
function looksGenerated(value) {
return !/^[A-Za-z][\w-]*$/.test(value) || /\d{3,}$/.test(value) || /[-_]\d+$/.test(value);
}
// Which document the identity is relative to. Without it these are exact-string duplicates,
// not unlucky hash collisions: iframe children are walked with parentXPath "/body" — the
// same literal the top document uses — with the iframe's own <body> skipped, and a shadow
// child is walked with its host's own xpath, the same path its light siblings get. A
// duplicate does not merely leave two elements matching [aloha-id="…"]; nodeMap[id] hands
// the map to the later node and re-parents the earlier one's children onto it.
function scopeKey(contextPath) {
return (contextPath || []).map((s) => s.selector || `shadow${s.index}`).join(">") + "|";
}
// hashString is 32 bits, Math.abs-folded, over inputs that share long prefixes, and duplicate
// #id attributes are legal in practice. An undetected collision hands nodeMap to the later
// node while querySelector hands the click to the earlier one. "-", never "." (aloha.click
// splits an id on its last dot for a select-option index) and never "," (get_text splits a
// batch of ids on commas).
function uniqueAlohaId(base) {
let id = base;
for (let n = 2; takenAlohaIds.has(id); n++) id = `${base}-${n}`;
takenAlohaIds.add(id);
return id;
}
function clearStaleAlohaIds(root) {
if (!root || !root.querySelectorAll) return;
for (const stale of root.querySelectorAll("[aloha-id]")) stale.removeAttribute("aloha-id");
for (const host of root.querySelectorAll("*")) {
if (host.shadowRoot) clearStaleAlohaIds(host.shadowRoot);
}
for (const frame of root.querySelectorAll("iframe")) {
try { if (frame.contentDocument) clearStaleAlohaIds(frame.contentDocument); } catch (e) {}
}
}
function hashString(input) {
let hash = 0;
for (let i = 0; i < input.length; i++) hash = ((hash << 5) - hash + input.charCodeAt(i)) | 0;
return `${Math.abs(hash).toString(16).slice(0, 10)}`;
}
const OVERLAY_ROOT_ID = "alohajet-highlight-container";
const highlightedElements = new Set();
let scrollListenersAttached = false;
let updateScheduled = false;
function attachScrollListeners() {
if (scrollListenersAttached) return;
scrollListenersAttached = true;
const onChange = () => scheduleHighlightUpdate();
window.addEventListener("scroll", onChange, true);
window.addEventListener("resize", onChange);
}
function scheduleHighlightUpdate() {
if (!updateScheduled) {
updateScheduled = true;
requestAnimationFrame(() => {
updateScheduled = false;
updateAllHighlights();
});
}
}
function updateAllHighlights() {
if (highlightedElements.size !== 0)
for (const entry of highlightedElements) updateHighlightPosition(entry);
}
function updateHighlightPosition(entry) {
const element = entry.element;
if (!element || !element.isConnected) return;
const rects = element.getClientRects();
const offset = { x: 0, y: 0 };
if (entry.parentIframe) {
const iframeRect = entry.parentIframe.getBoundingClientRect();
offset.x = iframeRect.left;
offset.y = iframeRect.top;
}
for (let i = 0; i < entry.overlays.length; i++) {
const overlay = entry.overlays[i];
if (i < rects.length) {
const rect = rects[i];
const top = rect.top + offset.y;
const left = rect.left + offset.x;
overlay.element.style.top = `${top}px`;
overlay.element.style.left = `${left}px`;
overlay.element.style.width = `${rect.width}px`;
overlay.element.style.height = `${rect.height}px`;
overlay.element.style.display = rect.width === 0 || rect.height === 0 ? "none" : "block";
} else overlay.element.style.display = "none";
}
const label = entry.label;
if (label && rects.length > 0) {
const rect = rects[0];
const top = rect.top + offset.y;
const left = rect.left + offset.x;
let labelTop = top - entry.labelHeight - 2;
let labelLeft = left + rect.width - entry.labelWidth - 2;
if (labelTop < offset.y) {
labelTop = top + 2;
if (labelLeft < offset.x) labelLeft = left + 2;
else if (labelLeft + entry.labelWidth > window.innerWidth) {
labelLeft = window.innerWidth - entry.labelWidth - 2;
labelLeft = Math.max(left + 2, labelLeft);
}
} else if (labelLeft < offset.x) labelLeft = offset.x;
else if (labelLeft + entry.labelWidth > window.innerWidth) labelLeft = window.innerWidth - entry.labelWidth - 2;
labelTop = Math.max(offset.y, labelTop);
label.style.top = `${labelTop}px`;
label.style.left = `${labelLeft}px`;
label.style.display = "block";
} else if (label) label.style.display = "none";
}
function isVisibleAndTop(element) {
if (!element) return false;
const inViewport = isInViewport(element, 0);
const top = isTopElement(element);
return inViewport && top;
}
function highlightElement(element, label, parentIframe = null) {
if (!element) return false;
const overlays = [];
let labelEl = null;
let labelWidth = 20;
let labelHeight = 16;
try {
let container = document.getElementById(OVERLAY_ROOT_ID);
if (!container) {
container = document.createElement("div");
container.id = OVERLAY_ROOT_ID;
container.style.cssText =
"position:fixed;pointer-events:none;top:0;left:0;width:100%;height:100%;z-index:2147483647;background-color:transparent";
document.body.appendChild(container);
}
if (isVisibleAndTop(element) === false) return false;
const rects = element.getClientRects();
if (!rects || rects.length === 0) return false;
const palette = ["#8B0000", "#4B0082", "#00008B"];
const colorIndex = Math.floor(Math.random() * palette.length);
const color = palette[colorIndex];
const borderColor = color + "B1";
const offset = { x: 0, y: 0 };
if (parentIframe) {
const iframeRect = parentIframe.getBoundingClientRect();
offset.x = iframeRect.left;
offset.y = iframeRect.top;
}
for (const rect of rects) {
if (rect.width === 0 || rect.height === 0) continue;
const overlay = document.createElement("div");
overlay.style.position = "fixed";
overlay.style.border = `1px solid ${borderColor}`;
overlay.style.pointerEvents = "none";
overlay.style.boxSizing = "border-box";
const top = rect.top + offset.y;
const left = rect.left + offset.x;
overlay.style.top = `${top}px`;
overlay.style.left = `${left}px`;
overlay.style.width = `${rect.width}px`;
overlay.style.height = `${rect.height}px`;
container.appendChild(overlay);
overlays.push({ element: overlay, initialRect: rect });
}
const firstRect = rects[0];
labelEl = document.createElement("div");
labelEl.className = "alohajet-highlight-label";
labelEl.style.position = "fixed";
labelEl.style.background = color;
labelEl.style.color = "white";
labelEl.style.fontWeight = "bold";
labelEl.style.padding = "2px 3px";
labelEl.style.borderRadius = "4px";
labelEl.style.fontSize = "13px";
labelEl.textContent = `${label}`;
labelWidth = labelEl.offsetWidth > 0 ? labelEl.offsetWidth : labelWidth;
labelHeight = labelEl.offsetHeight > 0 ? labelEl.offsetHeight : labelHeight;
const firstTop = firstRect.top + offset.y;
const firstLeft = firstRect.left + offset.x;
let labelTop = firstTop - labelHeight - 2;
let labelLeft = firstLeft + firstRect.width - labelWidth - 2;
if (labelTop < offset.y) {
labelTop = firstTop + 2;
if (labelLeft < offset.x) labelLeft = firstLeft + 2;
else if (labelLeft + labelWidth > window.innerWidth) {
labelLeft = window.innerWidth - labelWidth + 4;
labelLeft = Math.max(firstLeft + 2, labelLeft);
}
} else if (labelLeft < offset.x) labelLeft = offset.x;
else if (labelLeft + labelWidth > window.innerWidth) labelLeft = window.innerWidth - labelWidth - 2;
labelTop = Math.max(offset.y, labelTop);
labelEl.style.top = `${labelTop}px`;
labelEl.style.left = `${labelLeft}px`;
container.appendChild(labelEl);
const entry = {
element,
parentIframe,
overlays,
label: labelEl,
labelWidth,
labelHeight
};
highlightedElements.add(entry);
attachScrollListeners();
scheduleHighlightUpdate();
return true;
} finally {
}
}
function getSiblingIndex(element) {
const parent = element.parentElement;
if (!parent) return 0;
const tagName = element.tagName;
let count = 0;
let indexOfElement = 0;
let sibling = parent.firstElementChild;
for (; sibling; ) {
if (sibling.tagName === tagName && sibling.id !== OVERLAY_ROOT_ID) {
count++;
if (sibling === element) indexOfElement = count;
}
sibling = sibling.nextElementSibling;
}
return count <= 1 ? 0 : indexOfElement;
}
function hasVisibleTextRect(textNode) {
try {
const range = document.createRange();
range.selectNodeContents(textNode);
const rects = range.getClientRects();
if (!rects || rects.length === 0) return false;
let hasVisibleRect = false;
for (let i = 0; i < rects.length; i++) {
const rect = rects[i];
if (rect.width > 0 && rect.height > 0) {
hasVisibleRect = true;
break;
}
}
if (!hasVisibleRect) return false;
const parent = textNode.parentElement;
if (!parent) return false;
const style = getComputedStyleCached(parent);
return style ? style.display !== "none" && style.visibility !== "hidden" && parseFloat(style.opacity) > 0 : false;
} catch {
return false;
}
}
function isElementAccepted(element) {
if (!element || !element.tagName) return false;
const tag = element.tagName.toLowerCase();
return ALWAYS_ACCEPTED_TAGS.has(tag) ? true : !NEVER_ACCEPTED_TAGS.has(tag);
}
function isElementVisible(element) {
if (!element) return false;
if (caches.elementVisibility.has(element)) return caches.elementVisibility.get(element);
const data = getElementData(element);
const visible = data ? data.isVisible : false;
caches.elementVisibility.set(element, visible);
return visible;
}
function isInteractive(element) {
if (!element || element.nodeType !== Node.ELEMENT_NODE) return false;
if (interactiveCache.has(element)) return !!interactiveCache.get(element);
const disabledCursors = DISABLED_CURSORS;
function hasInteractiveCursor(el) {
if (el.tagName.toLowerCase() === "html") return false;
const style = getComputedStyleCached(el);
return style ? INTERACTIVE_CURSORS.has(style.cursor) : false;
}
const cursorIsInteractive = hasInteractiveCursor(element);
const tag = element.tagName.toLowerCase();
const interactiveTags = INTERACTIVE_TAGS;
function hasInteractiveAncestor(el) {
try {
let ancestor = el.parentElement;
let depth = 0;
for (; ancestor && depth < 8; ) {
const ancestorTag = ancestor.tagName ? ancestor.tagName.toLowerCase() : "";
if (INTERACTIVE_TAGS.has(ancestorTag)) return true;
const role = ancestor.getAttribute && ancestor.getAttribute("role");
if (
(role && INTERACTIVE_ROLES.has(role)) ||
(ancestor.hasAttribute && ancestor.hasAttribute("onclick")) ||
typeof ancestor.onclick == "function"
)
return true;
ancestor = ancestor.parentElement;
depth++;
}
} catch {}
return false;
}
const style = getComputedStyleCached(element);
if (interactiveTags.has(tag)) {
for (const attr of DISABLED_ATTRIBUTES) {
const value = element.getAttribute(attr);
if (attr === "aria-disabled" || attr === "aria-readonly") {
if (value === "true") return false;
} else if (element.hasAttribute(attr)) return false;
}
const el = element;
let disabled = false;
let readOnly = false;
if (tag === "input") {
const input = element;
disabled = input.disabled;
readOnly = input.readOnly;
} else if (tag === "textarea") {
const textarea = element;
disabled = textarea.disabled;
readOnly = textarea.readOnly;
} else if (tag === "button" || tag === "select") disabled = element.disabled;
if (disabled || readOnly || el.inert) return false;
if (tag === "a") {
const role = element.getAttribute("role");
const href = element.getAttribute("href");
const tabindex = element.getAttribute("tabindex");
const hasValidTabindex = tabindex !== null && !Number.isNaN(parseInt(tabindex, 10));
if (href !== null || (role && (INTERACTIVE_ROLES.has(role) || role === "link" || role === "option")) || hasValidTabindex) {
interactiveCache.set(element, true);
return true;
}
}
if (tag === "label") {
const label = element;
const control = label.control || (label.getAttribute("for") ? document.getElementById(label.getAttribute("for")) : null);
if (control && control.tagName?.toLowerCase() === "input") {
const inputType = (control.type || "").toLowerCase();
if (inputType === "checkbox" || inputType === "radio") {
const rects = element.getClientRects();
if (rects && rects.length > 0) {
for (const rect of rects)
if (rect.width > 0 && rect.height > 0) {
interactiveCache.set(element, true);
return true;
}
}
}
}
}
return cursorIsInteractive ? true : tag === "input" || tag === "select" || tag === "textarea" || tag === "button";
}
const role = element.getAttribute("role");
if (role === "switch" || role === "checkbox" || role === "radio")
return !(
element.getAttribute("aria-disabled") === "true" ||
element.hasAttribute("disabled") ||
(style && style.cursor === "not-allowed")
);
const ariaChecked = element.getAttribute("aria-checked");
const ariaPressed = element.getAttribute("aria-pressed");
if (ariaChecked !== null || ariaPressed !== null)
return !(
element.getAttribute("aria-disabled") === "true" ||
element.hasAttribute("disabled") ||
(style && style.cursor === "not-allowed")
);
if (style && (disabledCursors.has(style.cursor) || style.pointerEvents === "none" || parseFloat(style.opacity) < 0.3)) return false;
if (
element.classList &&
(element.classList.contains("button") ||
element.classList.contains("dropdown-toggle") ||
element.classList.contains("toggle") ||
element.classList.contains("switch") ||
element.getAttribute("data-toggle") === "dropdown" ||
element.getAttribute("aria-haspopup") === "true")
) {
if (element.getAttribute("aria-disabled") === "true" || element.hasAttribute("disabled") || (style && style.cursor === "not-allowed"))
return false;
const tabindex = element.getAttribute("tabindex");
const hasValidTabindex = tabindex !== null && !Number.isNaN(parseInt(tabindex, 10));
return !!(cursorIsInteractive || hasValidTabindex);
}
if (interactiveTags.has(tag) || (role && INTERACTIVE_ROLES.has(role)) || isContentEditableHost(element))
return !(element.getAttribute("aria-disabled") === "true" || (style && style.cursor === "not-allowed"));
if (
element.getAttribute("draggable") === "true" ||
isFileInputLike(element) ||
EVENT_HANDLER_ATTRS.some((attr) => (element.hasAttribute(attr) ? true : typeof element[attr] == "function"))
)
return true;
if (hasInteractiveAncestor(element)) {
const tabindex = element.getAttribute("tabindex");
return !(tabindex !== null && !Number.isNaN(parseInt(tabindex, 10))) && !cursorIsInteractive ? false : cursorIsInteractive;
}
interactiveCache.set(element, false);
return false;
}
function getFirstDescendantText(element) {
if (!element || element.nodeType !== Node.ELEMENT_NODE) return "";
const skipTags = new Set(["script", "style", "template", "noscript", "code"]);
const cached = descendantTextCache.get(element);
if (cached !== void 0) return cached;
const parts = [];
let collectedLength = 0;
const maxLength = 3000;
const maxNodes = 2000;
let visited = 0;
function visit(node) {
if (!node || collectedLength >= maxLength || visited++ >= maxNodes) return;
if (node.nodeType === Node.TEXT_NODE) {
const textNode = node;
const text = (textNode.textContent || "").trim();
if (text && hasVisibleTextRect(textNode)) {
parts.push(text);
collectedLength += text.length;
}
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const el = node;
const tag = el.tagName ? el.tagName.toLowerCase() : "";
if (skipTags.has(tag)) return;
if (tag === "img") {
const alt = el.getAttribute("alt");
if (alt && alt.trim()) {
parts.push(alt.trim());
collectedLength += alt.length;
}
return;
}
if (tag === "svg") {
const titleEl = el.querySelector("title");
if (titleEl && titleEl.textContent) {
const title = titleEl.textContent.trim();
if (title) {
parts.push(title);
collectedLength += title.length;
}
}
const ariaLabel = el.getAttribute("aria-label");
if (ariaLabel && ariaLabel.trim()) {
parts.push(ariaLabel.trim());
collectedLength += ariaLabel.length;
}
return;
}
if (el !== element && isInteractive(el)) return;
const children = el.childNodes;
for (let i = 0; i < children.length && collectedLength < maxLength; i++) visit(children[i]);
}
visit(element);
const result = parts.join(" ").replace(/\s+/g, " ").trim();
descendantTextCache.set(element, result);
return result;
}
function getAriaLabelledByText(element) {
try {
const labelledBy = element.getAttribute && element.getAttribute("aria-labelledby");
if (!labelledBy) return "";
const ids = labelledBy.split(/\s+/).filter((id) => id.trim());
const parts = [];
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const referenced = document.getElementById(id);
if (referenced) {
const text = referenced.textContent ? referenced.textContent.trim() : "";
if (text) parts.push(text);
}
}
return parts.join(" ");
} catch {
return "";
}
}
function getNestedAriaLabels(element) {
try {
if ((element.childElementCount || 0) > 120) return "";
const labelled = element.querySelectorAll("[aria-label], [aria-labelledby]");
const parts = [];
const seen = new Set();
const maxLabels = 50;
for (let i = 0; i < labelled.length && i < maxLabels; i++) {
const el = labelled[i];
if (el.getAttribute && el.getAttribute("aria-hidden") === "true") continue;
let text = "";
const ariaLabel = el.getAttribute && el.getAttribute("aria-label");
if (ariaLabel && ariaLabel.trim()) text = ariaLabel.trim();
else {
const labelledByText = getAriaLabelledByText(el);
if (labelledByText && labelledByText.trim()) text = labelledByText.trim();
}
if (text) {
const lower = text.toLowerCase();
if (!seen.has(lower)) {
seen.add(lower);
parts.push(text);
}
}
}
return parts.join(" ");
} catch {
return "";
}
}
function getFormValue(element) {
try {
const tag = element.tagName ? element.tagName.toLowerCase() : "";
if (tag === "input" || tag === "textarea") {
return __alohaIsSensitiveField(element) ? \#(sensitiveFieldMaskJS) : (element.value || "");
}
if (tag === "select") {
const select = element;
if (select.selectedIndex >= 0) {
const option = select.options[select.selectedIndex];
return (option && (option.text || option.textContent || "")) || "";
}
return "";
}
} catch {}
return "";
}
function getComprehensiveText(element) {
if (!element) return "";
const cached = comprehensiveTextCache.get(element);
if (cached !== void 0) return cached;
try {
const tag = element.tagName ? element.tagName.toLowerCase() : "";
if (tag === "style" || tag === "script" || tag === "code") return "";
} catch {}
const parts = [];
const seen = new Set();
function add(text) {
if (!text || typeof text != "string") return;
const trimmed = text.trim();
if (!trimmed) return;
const lower = trimmed.toLowerCase();
if (!seen.has(lower)) {
seen.add(lower);
parts.push(trimmed);
}
}
try {
const labelledBy = element.getAttribute && element.getAttribute("aria-labelledby");
if (labelledBy) {
const ids = labelledBy.split(/\s+/).filter((id) => id.trim());
const maxIds = 5;
for (let i = 0; i < ids.length && i < maxIds; i++) {
const referenced = document.getElementById(ids[i]);
if (referenced) add(getComprehensiveText(referenced));
}
}
} catch {}
try {
const ariaLabel = element.getAttribute && element.getAttribute("aria-label");
if (ariaLabel) add(ariaLabel);
} catch {}
try {
const describedBy = element.getAttribute && element.getAttribute("aria-describedby");
if (describedBy) {
const ids = describedBy.split(/\s+/).filter((id) => id.trim());
const maxIds = 5;
for (let i = 0; i < ids.length && i < maxIds; i++) {
const referenced = document.getElementById(ids[i]);
if (referenced) add(getComprehensiveText(referenced));
}
}
} catch {}
try {
const tag = element.tagName ? element.tagName.toLowerCase() : "";
if (tag === "input") {
const input = element;
// A credential field's VALUE never joins the text the model reads. Everything
// else about the field — its label, placeholder, type — still does.
if (input.value && !__alohaIsSensitiveField(input)) add(input.value);
if (input.placeholder) add(input.placeholder);
if ((input.type === "checkbox" || input.type === "radio") && input.labels)
for (let i = 0; i < input.labels.length; i++) add(input.labels[i].textContent || "");
} else if (tag === "textarea") {
const textarea = element;
if (textarea.value && !__alohaIsSensitiveField(textarea)) add(textarea.value);
if (textarea.placeholder) add(textarea.placeholder);
} else if (tag === "select") {
const select = element;
if (select.selectedIndex >= 0) {
const selected = select.options[select.selectedIndex];
if (selected) add(selected.text || selected.textContent || "");
}
const maxOptions = 50;
for (let i = 0; i < select.options.length && i < maxOptions; i++) {
const option = select.options[i];
add(option.text || option.textContent || "");
}
} else if (tag === "option") {
const option = element;
add(option.text || option.textContent || "");
if (option.value && option.value !== option.text) add(option.value);
}
} catch {}
try {
const attrs = ["alt", "title", "aria-placeholder", "data-label", "data-text", "data-tooltip"];
for (let i = 0; i < attrs.length; i++) {
const value = element.getAttribute && element.getAttribute(attrs[i]);
if (value) add(value);
}
} catch {}
try {
const directText = Array.from(element.childNodes)
.filter((node) => node.nodeType === Node.TEXT_NODE)
.map((node) => (node.textContent || "").trim())
.filter((text) => !!text)
.join(" ");
if (directText) add(directText);
} catch {}
try {
const descendantText = getFirstDescendantText(element);
if (descendantText) add(descendantText);
} catch {}
try {
const nestedLabels = getNestedAriaLabels(element);
if (nestedLabels) add(nestedLabels);
} catch {}
try {
const el = element;
if (el.shadowRoot) {
const shadowParts = [];
const shadowChildren = Array.from(el.shadowRoot.childNodes);
const maxShadowChildren = 100;
for (let i = 0; i < shadowChildren.length && i < maxShadowChildren; i++) {
const node = shadowChildren[i];
if (node.nodeType === Node.ELEMENT_NODE) {
const childEl = node;
const childTag = childEl.tagName ? childEl.tagName.toLowerCase() : "";
if (childTag === "style" || childTag === "script" || childTag === "code") continue;
shadowParts.push(getComprehensiveText(childEl));
} else if (node.nodeType === Node.TEXT_NODE) {
const text = (node.textContent || "").trim();
if (text) shadowParts.push(text);
}
}
const shadowText = shadowParts.join(" ").replace(/\s+/g, " ").trim();
if (shadowText) add(shadowText);
}
} catch {}
if (parts.length === 0)
try {
const fallbackParts = [];
const collect = (node) => {
if (node.nodeType === Node.TEXT_NODE) {
const text = (node.textContent || "").trim();
if (text) fallbackParts.push(text);
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const el = node;
const tag = el.tagName ? el.tagName.toLowerCase() : "";
if (tag === "script" || tag === "style" || tag === "template" || tag === "noscript") return;
if (tag === "img") {
const alt = el.getAttribute("alt");
if (alt && alt.trim()) fallbackParts.push(alt.trim());
return;
}
if (tag === "svg") {
const titleEl = el.querySelector("title");
if (titleEl && titleEl.textContent) {
const title = titleEl.textContent.trim();
if (title) fallbackParts.push(title);
}
const ariaLabel = el.getAttribute("aria-label");
if (ariaLabel && ariaLabel.trim()) fallbackParts.push(ariaLabel.trim());
return;
}
const children = el.childNodes;
for (let i = 0; i < children.length; i++) collect(children[i]);
};
collect(element);
const fallbackText = fallbackParts.join(" ").replace(/\s+/g, " ").trim();
if (fallbackText) add(fallbackText);
} catch {}
// Different collectors above (direct text nodes, getFirstDescendantText, aria) can each
// add a text where one is a SUBSTRING of another — e.g. the direct text "Submitted by"
// plus the first-descendant text "Submitted by t3_… 3 years ago". The exact-match `seen`
// set misses that overlap, so the join reads "Submitted by Submitted by t3_…". Drop any
// part fully contained in a longer part; the longer one already carries it.
const kept = parts.filter(function (p) {
const pl = p.toLowerCase();
return !parts.some(function (q) { return q.length > p.length && q.toLowerCase().indexOf(pl) !== -1; });
});
const result = kept.join(" ").replace(/\s+/g, " ").trim();
comprehensiveTextCache.set(element, result);
return result;
}
function attachComprehensiveText(node, element) {
try {
const comprehensiveText = getComprehensiveText(element);
node.comprehensiveText = comprehensiveText;
node.textSources = {
ariaLabel: (element.getAttribute && (element.getAttribute("aria-label") || "")) || "",
ariaLabelledby: getAriaLabelledByText(element),
formValue: getFormValue(element),
placeholder: (element.getAttribute && (element.getAttribute("placeholder") || "")) || "",
ariaPlaceholder: (element.getAttribute && (element.getAttribute("aria-placeholder") || "")) || "",
alt: (element.getAttribute && (element.getAttribute("alt") || "")) || "",
title: (element.getAttribute && (element.getAttribute("title") || "")) || "",
textContent: (element.textContent || "").trim(),
descendantText: getFirstDescendantText(element)
};
} catch {}
}
let cachedModalContainers;
const VIEWPORT_EDGE_SLACK = 1;
function isRectOnScreen(rect) {
if (rect.width <= 0 || rect.height <= 0) return false;
return !(
rect.bottom < VIEWPORT_EDGE_SLACK ||
rect.top > window.innerHeight - VIEWPORT_EDGE_SLACK ||
rect.right < VIEWPORT_EDGE_SLACK ||
rect.left > window.innerWidth - VIEWPORT_EDGE_SLACK
);
}
function rectsIncludeOnScreen(rects) {
for (const rect of rects) if (isRectOnScreen(rect)) return true;
return false;
}
function getVisibleModalContainers() {
if (cachedModalContainers) return cachedModalContainers;
let containers = [];
try {
const candidates = Array.from(
document.querySelectorAll(
'[data-baseweb="modal"], [data-baseweb="drawer"], [role="dialog"], [aria-modal="true"], [aria-label="dialog"], [data-animated-popover-backdrop]'
)
);
for (const candidate of candidates) {
const rects = candidate.getClientRects();
if (!rects || rects.length === 0) continue;
if (rectsIncludeOnScreen(rects)) containers.push(candidate);
}
} catch {
containers = [];
}
cachedModalContainers = containers;
return cachedModalContainers;
}
function isTopElement(element) {
const rects = element.getClientRects();
if (!rects || rects.length === 0) return false;
const hasVisibleRect = rectsIncludeOnScreen(rects);
if (element.ownerDocument !== window.document) return true;
if (element.getRootNode() instanceof ShadowRoot) return true;
if (!hasVisibleRect) return true;
const centerX = rects[Math.floor(rects.length / 2)].left + rects[Math.floor(rects.length / 2)].width / 2;
const centerY = rects[Math.floor(rects.length / 2)].top + rects[Math.floor(rects.length / 2)].height / 2;
try {
const topElementAtPoint = document.elementFromPoint(centerX, centerY);
if (!topElementAtPoint) return false;
let current = topElementAtPoint;
for (; current && current !== document.documentElement; ) {
if (current === element) return true;
current = current.parentElement;
}
const tag = element.tagName.toLowerCase();
if (
tag === "input" ||
tag === "button" ||
tag === "select" ||
tag === "textarea" ||
element.getAttribute("role") === "switch" ||
element.getAttribute("role") === "checkbox" ||
element.getAttribute("role") === "radio" ||
element.hasAttribute("aria-checked") ||
element.hasAttribute("aria-pressed")
) {
if (topElementAtPoint.contains(element)) return true;
const elementParent = element.parentElement;
const topParent = topElementAtPoint.parentElement;
if ((elementParent && elementParent === topParent) || (elementParent?.parentElement && elementParent.parentElement === topParent?.parentElement))
return true;
if (tag === "input") {
const id = element.getAttribute("id");
if (id) {
let current2 = topElementAtPoint;
for (; current2 && current2 !== document.documentElement; ) {
if (current2.tagName.toLowerCase() === "label" && current2.getAttribute("for") === id) return true;
current2 = current2.parentElement;
}
}
let ancestor = element.parentElement;
for (; ancestor && ancestor !== document.documentElement; ) {
if (ancestor.tagName.toLowerCase() === "label") {
if (ancestor.contains(topElementAtPoint)) return true;
break;
}
ancestor = ancestor.parentElement;
}
}
}
return false;
} catch {
return true;
}
}
// Hit-test probe: returns the element visually covering `element`, or null if `element` is