@a11y-pulse/skip-link-audit 0.1.2 → 0.3.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.
package/dist/index.js CHANGED
@@ -1,43 +1,223 @@
1
1
  // src/audit.ts
2
+ import { captureElementScreenshot } from "@a11y-pulse/browser-adaptor";
2
3
  import { getSelector, truncateHtml } from "@a11y-pulse/browser-adaptor/dom";
3
4
 
4
5
  // src/browser-scripts.ts
5
- function probeActiveElementScript() {
6
- let el = document.activeElement;
7
- while (el?.shadowRoot?.activeElement) {
8
- el = el.shadowRoot.activeElement;
6
+ function inspectSkipLinkScript(el, mode, limit = 3) {
7
+ const WORD = "\\p{L}\\p{N}_";
8
+ const START = `(?:^|[^${WORD}])`;
9
+ const END = `(?![${WORD}])`;
10
+ const GO = "skip|jump|go|zum|zur|springe|aller|passer|acc\xE9der|ir|saltar|salta|vai|passa|pular|avan\xE7ar|ga|naar|spring|hoppa|hopp|g\xE5|till|siirry|hypp\xE4\xE4|przejd\u017A|przeskocz|pomi\u0144|p\u0159esko\u010Dit|p\u0159ej\xEDt|\u043F\u0435\u0440\u0435\u0439\u0442\u0438|\u043F\u0440\u043E\u043F\u0443\u0441\u0442\u0438\u0442\u044C";
11
+ const FILLER = "to|the|main|primary|zu|zum|zur|dem|der|direkt|au|aux|\xE0|la|le|du|directement|al|a|el|alla|allo|ai|il|para|o|ao|naar|de|het|direct|till|til|det|do|na|k|ke|g\u0142\xF3wnej|hlavn\xED|hlavn\xEDmu|\u043A|\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u043C\u0443";
12
+ const NOUN = "content|main|navigation|nav|menu|search|footer|\\p{L}*inhalt|\\p{L}*navigation|men\xFC|suche|contenu|recherche|contenido|navegaci\xF3n|men\xFA|b\xFAsqueda|contenuto|navigazione|ricerca|conte\xFAdo|navega\xE7\xE3o|pesquisa|\\p{L}*inhoud|navigatie|zoeken|\\p{L}*inneh\xE5ll\\p{L}*|navigering\\p{L}*|meny\\p{L}*|\\p{L}*innhold\\p{L}*|\\p{L}*indhold\\p{L}*|navigasjon\\p{L}*|\\p{L}*sis\xE4lt\\p{L}*|navigaatio\\p{L}*|valikko\\p{L}*|tre\u015Bci|zawarto\u015Bci|nawigacj\\p{L}*|obsah\\p{L}*|navigac\\p{L}*|\u0441\u043E\u0434\u0435\u0440\u0436\u0430\u043D\u0438\\p{L}*|\u043A\u043E\u043D\u0442\u0435\u043D\u0442\\p{L}*|\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\\p{L}*|\u043C\u0435\u043D\u044E";
13
+ const SKIP_WORDS = new RegExp(
14
+ [
15
+ // "Skip to content", "Aller au contenu", "Ga direct naar de inhoud", "Перейти к содержанию".
16
+ `${START}(?:${GO})(?:\\s+(?:${FILLER})){0,3}\\s+(?:${NOUN})${END}`,
17
+ // Verbs that only ever mean "skip".
18
+ `${START}(?:skip|\xFCberspringen)${END}`,
19
+ // Scripts written without spaces between words.
20
+ "\u30B9\u30AD\u30C3\u30D7|\u672C\u6587\u3078|\u30E1\u30A4\u30F3\u30B3\u30F3\u30C6\u30F3\u30C4\u3078|\u8DF3[\u8FC7\u904E]|\u8DF3(?:\u5230|\u81F3|\u8F6C\u5230|\u8F49\u5230)\\s*(?:\u4E3B\u8981|\u4E3B|\u6B63\u6587|\u5185\u5BB9|\u5167\u5BB9|\u5BFC\u822A|\u5C0E\u822A)|\uAC74\uB108\uB6F0\uAE30|\uBCF8\uBB38\\s*(?:\uC73C\uB85C|\uBC14\uB85C\\s*\uAC00\uAE30)"
21
+ ].join("|"),
22
+ "iu"
23
+ );
24
+ const SKIP_TOKEN = /^skip(?:[-_]?(?:link|nav|navigation|main|content|to[-_]?[a-z]+))?$/i;
25
+ const CONTENT_ID = /^(?:(?:main|page|site|primary|skip)[-_]?)?(?:content|main)(?:[-_]?(?:area|wrapper|container|start))?$|^primary$/i;
26
+ const UNREACHABLE_ATTR = "data-a11y-pulse-unreachable-skip-link";
27
+ function openingTag(node) {
28
+ return node.cloneNode(false).outerHTML;
9
29
  }
10
- if (!el || el === document.body) {
11
- return {
12
- isBody: true,
13
- html: "",
14
- fragment: null,
15
- targetResolves: false
16
- };
30
+ function isRendered(node) {
31
+ if (typeof node.checkVisibility === "function") {
32
+ return node.checkVisibility();
33
+ }
34
+ for (let current = node; current; current = current.parentElement) {
35
+ if (getComputedStyle(current).display === "none") {
36
+ return false;
37
+ }
38
+ }
39
+ return true;
17
40
  }
18
- const openingTag = el.cloneNode(false).outerHTML;
19
- const href = el.tagName === "A" ? el.getAttribute("href") : null;
20
- let fragment = null;
21
- if (href?.startsWith("#") && href !== "#" && href !== "#top" && !href.startsWith("#/") && !href.startsWith("#!/")) {
22
- fragment = href;
41
+ function textOf(node) {
42
+ const text = (node.textContent ?? "").replace(/\s+/g, " ").trim();
43
+ return (text || (node.getAttribute("aria-label") ?? "").trim()).slice(0, 200);
44
+ }
45
+ function fragmentOf(node) {
46
+ if (node.tagName !== "A" || !node.hasAttribute("href")) {
47
+ return null;
48
+ }
49
+ let url;
50
+ let here;
51
+ try {
52
+ url = new URL(node.href);
53
+ here = new URL(location.href);
54
+ } catch {
55
+ return null;
56
+ }
57
+ if (url.origin !== here.origin || url.pathname !== here.pathname || url.search !== here.search) {
58
+ return null;
59
+ }
60
+ const hash = url.hash;
61
+ if (hash === "" || hash === "#" || hash.toLowerCase() === "#top") {
62
+ return null;
63
+ }
64
+ if (hash.startsWith("#/") || hash.startsWith("#!/")) {
65
+ return null;
66
+ }
67
+ return hash;
23
68
  }
24
- let targetResolves = false;
25
- if (fragment) {
26
- const raw = fragment.slice(1);
69
+ function targetOf(fragment2) {
70
+ const raw = fragment2.slice(1);
27
71
  let decoded = raw;
28
72
  try {
29
73
  decoded = decodeURIComponent(raw);
30
74
  } catch {
31
75
  }
32
- targetResolves = Boolean(
33
- document.getElementById(decoded) ?? document.getElementsByName(decoded)[0]
34
- );
76
+ for (const id of raw === decoded ? [raw] : [raw, decoded]) {
77
+ const byId = document.getElementById(id);
78
+ if (byId) {
79
+ return byId;
80
+ }
81
+ for (const named of Array.from(document.getElementsByName(id))) {
82
+ if (named.tagName === "A") {
83
+ return named;
84
+ }
85
+ }
86
+ }
87
+ return null;
88
+ }
89
+ function follows(node, reference) {
90
+ return Boolean(reference.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING);
91
+ }
92
+ function hasSkipWords(node) {
93
+ return SKIP_WORDS.test(`${textOf(node)} ${node.getAttribute("aria-label") ?? ""}`);
94
+ }
95
+ function hasSkipToken(node) {
96
+ if (SKIP_TOKEN.test(node.id)) {
97
+ return true;
98
+ }
99
+ return (node.getAttribute("class") ?? "").split(/\s+/).some((token) => SKIP_TOKEN.test(token));
100
+ }
101
+ function isContentTarget(target2) {
102
+ if (target2.matches('h1, h2, h3, h4, h5, h6, [role="heading"]')) {
103
+ return true;
104
+ }
105
+ const main = document.querySelector('main, [role="main"]');
106
+ if (main) {
107
+ return target2 === main || target2.contains(main) || main.contains(target2);
108
+ }
109
+ return CONTENT_ID.test(target2.id || (target2.getAttribute("name") ?? ""));
110
+ }
111
+ function isSkipLike(link, target2) {
112
+ const role = link.getAttribute("role");
113
+ if (link.hasAttribute("aria-expanded") || role === "tab" || role === "button") {
114
+ return false;
115
+ }
116
+ if (hasSkipWords(link) || hasSkipToken(link)) {
117
+ return true;
118
+ }
119
+ if (!target2 || !follows(target2, link)) {
120
+ return false;
121
+ }
122
+ if (!isRendered(target2) || target2.closest('nav, [role="navigation"]')) {
123
+ return false;
124
+ }
125
+ return isContentTarget(target2);
126
+ }
127
+ function targetSelector(target2) {
128
+ if (target2.id) {
129
+ return `#${CSS.escape(target2.id)}`;
130
+ }
131
+ return `a[name="${CSS.escape(target2.getAttribute("name") ?? "")}"]`;
132
+ }
133
+ function unreachableReason(link) {
134
+ if (!isRendered(link)) {
135
+ return "not-rendered";
136
+ }
137
+ const visibility = getComputedStyle(link).visibility;
138
+ if (visibility === "hidden" || visibility === "collapse") {
139
+ return "visibility-hidden";
140
+ }
141
+ if (link.closest("[inert]")) {
142
+ return "inert";
143
+ }
144
+ const tabindex = link.getAttribute("tabindex");
145
+ if (tabindex !== null && Number.parseInt(tabindex, 10) < 0) {
146
+ return "negative-tabindex";
147
+ }
148
+ return null;
149
+ }
150
+ if (mode === "unreachable") {
151
+ const unreachable = [];
152
+ for (const marked of Array.from(document.querySelectorAll(`[${UNREACHABLE_ATTR}]`))) {
153
+ marked.removeAttribute(UNREACHABLE_ATTR);
154
+ }
155
+ for (const link of Array.from(document.querySelectorAll("a[href]")).slice(0, 50)) {
156
+ if (unreachable.length >= limit) {
157
+ break;
158
+ }
159
+ const fragment2 = fragmentOf(link);
160
+ if (!fragment2 || !hasSkipWords(link) || !isSkipLike(link, targetOf(fragment2))) {
161
+ continue;
162
+ }
163
+ const reason = unreachableReason(link);
164
+ if (!reason) {
165
+ continue;
166
+ }
167
+ const html = openingTag(link);
168
+ link.setAttribute(UNREACHABLE_ATTR, String(unreachable.length));
169
+ unreachable.push({ html, linkText: textOf(link), fragment: fragment2, reason });
170
+ }
171
+ return { link: null, unreachable };
172
+ }
173
+ if (!el || el === document.body || el === document.documentElement) {
174
+ return {
175
+ link: {
176
+ isBody: true,
177
+ html: "",
178
+ linkText: "",
179
+ fragment: null,
180
+ skipLike: false,
181
+ target: null,
182
+ focus: { position: "body", navigated: false }
183
+ },
184
+ unreachable: []
185
+ };
186
+ }
187
+ const fragment = fragmentOf(el);
188
+ const target = fragment ? targetOf(fragment) : null;
189
+ const host = document.activeElement;
190
+ let active = host;
191
+ while (active?.shadowRoot?.activeElement) {
192
+ active = active.shadowRoot.activeElement;
193
+ }
194
+ let position = "elsewhere";
195
+ if (!host || !active || host === document.body || host === document.documentElement) {
196
+ position = "body";
197
+ } else if (active === el) {
198
+ position = "skip-link";
199
+ } else if (target && (active === target || target.contains(active) || target.contains(host))) {
200
+ position = "inside-target";
201
+ } else if (target && follows(host, target)) {
202
+ position = "after-target";
203
+ } else if (!target && follows(host, el)) {
204
+ position = "after-link";
35
205
  }
36
206
  return {
37
- isBody: false,
38
- html: openingTag,
39
- fragment,
40
- targetResolves
207
+ link: {
208
+ isBody: false,
209
+ html: openingTag(el),
210
+ linkText: textOf(el),
211
+ fragment,
212
+ skipLike: mode === "classify" && fragment !== null ? isSkipLike(el, target) : false,
213
+ target: target ? {
214
+ selector: targetSelector(target),
215
+ html: openingTag(target),
216
+ rendered: isRendered(target)
217
+ } : null,
218
+ focus: { position, navigated: fragment !== null && location.hash === fragment }
219
+ },
220
+ unreachable: []
41
221
  };
42
222
  }
43
223
  function activeElementHandleScript() {
@@ -47,33 +227,158 @@ function activeElementHandleScript() {
47
227
  }
48
228
  return el;
49
229
  }
50
- function isFocusInsideTargetScript(fragment) {
51
- const raw = fragment.startsWith("#") ? fragment.slice(1) : fragment;
52
- let decoded = raw;
53
- try {
54
- decoded = decodeURIComponent(raw);
55
- } catch {
56
- }
57
- const target = document.getElementById(decoded) ?? document.getElementsByName(decoded)[0] ?? null;
58
- if (!target) {
59
- return false;
60
- }
61
- let el = document.activeElement;
62
- while (el?.shadowRoot?.activeElement) {
63
- el = el.shadowRoot.activeElement;
64
- }
65
- if (!el) {
66
- return false;
230
+ function takeUnreachableSkipLinkScript() {
231
+ const marked = document.querySelector("[data-a11y-pulse-unreachable-skip-link]");
232
+ marked?.removeAttribute("data-a11y-pulse-unreachable-skip-link");
233
+ return marked;
234
+ }
235
+ function readPageStateScript() {
236
+ return {
237
+ href: location.href,
238
+ scrollX: window.scrollX,
239
+ scrollY: window.scrollY,
240
+ historyLength: history.length
241
+ };
242
+ }
243
+ function restorePageStateScript(state) {
244
+ const withoutFragment = (href) => href.split("#")[0] ?? href;
245
+ const rewrite = () => {
246
+ if (location.href === state.href) {
247
+ return;
248
+ }
249
+ try {
250
+ history.replaceState(history.state, "", state.href);
251
+ } catch {
252
+ }
253
+ };
254
+ const scroll = () => {
255
+ window.scrollTo(state.scrollX, state.scrollY);
256
+ };
257
+ if (location.href === state.href || withoutFragment(location.href) !== withoutFragment(state.href) || history.length !== state.historyLength + 1) {
258
+ rewrite();
259
+ scroll();
260
+ return Promise.resolve();
67
261
  }
68
- return el === target || target.contains(el);
262
+ return new Promise((resolve) => {
263
+ let settled = false;
264
+ const settle = () => {
265
+ if (settled) {
266
+ return;
267
+ }
268
+ settled = true;
269
+ window.removeEventListener("popstate", onPopState);
270
+ rewrite();
271
+ scroll();
272
+ resolve();
273
+ };
274
+ const onPopState = () => {
275
+ requestAnimationFrame(() => requestAnimationFrame(settle));
276
+ setTimeout(settle, 100);
277
+ };
278
+ window.addEventListener("popstate", onPopState);
279
+ setTimeout(settle, 1e3);
280
+ history.back();
281
+ });
69
282
  }
70
283
  function focusScript(el) {
71
284
  el?.focus();
72
285
  }
286
+ function resetFocusScript() {
287
+ const anchorAttr = "data-a11y-pulse-skip-link-focus-start";
288
+ return new Promise((resolve) => {
289
+ let done = false;
290
+ const run = () => {
291
+ if (done) {
292
+ return;
293
+ }
294
+ done = true;
295
+ try {
296
+ reset();
297
+ } finally {
298
+ resolve();
299
+ }
300
+ };
301
+ requestAnimationFrame(() => requestAnimationFrame(run));
302
+ setTimeout(run, 100);
303
+ });
304
+ function reset() {
305
+ let active = document.activeElement;
306
+ while (active?.shadowRoot?.activeElement) {
307
+ active = active.shadowRoot.activeElement;
308
+ }
309
+ active?.blur?.();
310
+ for (const leftover of Array.from(document.querySelectorAll(`[${anchorAttr}]`))) {
311
+ leftover.remove();
312
+ }
313
+ const root = document.documentElement;
314
+ const body = document.body;
315
+ if (!root || !body) {
316
+ return;
317
+ }
318
+ const place = (parent, before) => {
319
+ const anchor = document.createElement("span");
320
+ anchor.tabIndex = -1;
321
+ anchor.setAttribute(anchorAttr, "");
322
+ anchor.setAttribute("aria-hidden", "true");
323
+ anchor.style.cssText = "position:fixed;top:0;left:0;width:1px;height:1px;outline:none";
324
+ try {
325
+ parent.insertBefore(anchor, before);
326
+ anchor.focus({ preventScroll: true });
327
+ } catch {
328
+ }
329
+ if (document.activeElement === anchor) {
330
+ return anchor;
331
+ }
332
+ anchor.remove();
333
+ return null;
334
+ };
335
+ let first = null;
336
+ let lowest = Number.POSITIVE_INFINITY;
337
+ for (const candidate of Array.from(document.querySelectorAll("[tabindex]"))) {
338
+ const tabIndex = candidate.tabIndex;
339
+ if (tabIndex <= 0 || tabIndex >= lowest) {
340
+ continue;
341
+ }
342
+ if (candidate.matches(":disabled") || candidate.closest("[inert]") || typeof candidate.checkVisibility === "function" && !candidate.checkVisibility({ checkVisibilityCSS: true })) {
343
+ continue;
344
+ }
345
+ first = candidate;
346
+ lowest = tabIndex;
347
+ }
348
+ if (first?.parentNode) {
349
+ const anchor = place(first.parentNode, first);
350
+ if (anchor) {
351
+ anchor.blur();
352
+ const cleanUp = (event) => {
353
+ if (event.target !== anchor) {
354
+ anchor.remove();
355
+ window.removeEventListener("focus", cleanUp, true);
356
+ }
357
+ };
358
+ window.addEventListener("focus", cleanUp, true);
359
+ return;
360
+ }
361
+ }
362
+ const places = [
363
+ [root, body],
364
+ [body, body.firstChild]
365
+ ];
366
+ for (const [parent, before] of places) {
367
+ const anchor = place(parent, before);
368
+ if (anchor) {
369
+ anchor.remove();
370
+ return;
371
+ }
372
+ }
373
+ }
374
+ }
73
375
 
74
376
  // src/audit.ts
75
377
  var DEFAULT_CANDIDATE_LIMIT = 3;
76
378
  var DEFAULT_ACTIVATION_POLL_MS = 250;
379
+ var UNREACHABLE_LIMIT = 3;
380
+ var SCREENSHOT_CLIP_BUFFER = 10;
381
+ var SCREENSHOT_SETTLE_MS = 33;
77
382
  function resolveOptions(options) {
78
383
  return {
79
384
  candidateLimit: options.candidateLimit ?? DEFAULT_CANDIDATE_LIMIT,
@@ -84,78 +389,103 @@ async function runSkipLinkAudit(adaptor, options = {}) {
84
389
  await adaptor.ensureFocusReporting();
85
390
  return runSkipLinkLoop(createAdaptorProbe(adaptor), resolveOptions(options));
86
391
  }
392
+ function movedByEnter(focus) {
393
+ if (focus.position === "inside-target" || focus.position === "after-target") {
394
+ return true;
395
+ }
396
+ return !focus.targetExists && focus.position === "after-link";
397
+ }
398
+ async function landing(probe, focus) {
399
+ const focused = focus.position === "body" ? null : await probe.describeFocused();
400
+ return {
401
+ position: focus.position,
402
+ selector: focused?.selector ?? null,
403
+ html: focused?.html ?? null
404
+ };
405
+ }
87
406
  async function runSkipLinkLoop(probe, options) {
88
407
  const collected = [];
89
408
  const seen = /* @__PURE__ */ new Set();
90
- for (let i = 0; i < options.candidateLimit; i++) {
91
- await probe.pressTab();
92
- const tabStop = await probe.probeTabStop();
93
- if (tabStop.isBody || seen.has(tabStop.identity)) {
94
- break;
95
- }
96
- seen.add(tabStop.identity);
97
- if (tabStop.candidate) {
98
- collected.push({ ...tabStop.candidate, tabIndex: i + 1 });
99
- }
100
- }
101
409
  const skipLinks = [];
102
- for (const found of collected) {
103
- try {
104
- if (!found.targetResolves) {
105
- skipLinks.push({
106
- selector: found.selector,
107
- html: found.html,
108
- fragment: found.fragment,
109
- tabIndex: found.tabIndex,
110
- passed: false,
111
- failureReason: "target-missing"
112
- });
113
- continue;
410
+ try {
411
+ for (let i = 0; i < options.candidateLimit; i++) {
412
+ await probe.pressTab();
413
+ const tabStop = await probe.probeTabStop();
414
+ if (tabStop.isBody || seen.has(tabStop.identity)) {
415
+ break;
416
+ }
417
+ seen.add(tabStop.identity);
418
+ if (tabStop.candidate) {
419
+ collected.push({ ...tabStop.candidate, tabIndex: i + 1 });
420
+ }
421
+ }
422
+ for (const found of collected) {
423
+ try {
424
+ const state = await probe.saveState();
425
+ try {
426
+ await probe.focusHandle(found.handle);
427
+ await probe.pressEnter();
428
+ const afterEnter = await pollFocus(probe, found.handle, options.activationPollMs);
429
+ const focusAfterEnter = await landing(probe, afterEnter);
430
+ let passed2 = movedByEnter(afterEnter);
431
+ let failureReason = null;
432
+ let focusAfterTab = null;
433
+ if (!passed2 && !afterEnter.targetExists) {
434
+ failureReason = "target-missing";
435
+ } else if (!passed2 && !afterEnter.targetRendered) {
436
+ failureReason = "target-hidden";
437
+ } else if (!passed2) {
438
+ await probe.pressTab();
439
+ const afterTab = await probe.readFocus(found.handle);
440
+ const activated = afterEnter.navigated || afterEnter.position !== "skip-link";
441
+ focusAfterTab = await landing(probe, afterTab);
442
+ passed2 = afterTab.position === "inside-target" || activated && afterTab.position === "after-target" || afterEnter.navigated && afterTab.position === "body";
443
+ failureReason = passed2 ? null : "activation-no-effect";
444
+ }
445
+ skipLinks.push({
446
+ selector: found.selector,
447
+ html: found.html,
448
+ fragment: found.fragment,
449
+ tabIndex: found.tabIndex,
450
+ passed: passed2,
451
+ failureReason,
452
+ linkText: found.linkText,
453
+ target: found.target,
454
+ focusAfterEnter,
455
+ focusAfterTab,
456
+ screenshot: passed2 ? void 0 : await probe.screenshotFocused(found.handle)
457
+ });
458
+ } finally {
459
+ await probe.restoreState(state);
460
+ }
461
+ } finally {
462
+ await probe.disposeRef(found.handle);
114
463
  }
115
- await probe.focusHandle(found.handle);
116
- await probe.pressEnter();
117
- let passed2 = await pollFocusInsideTarget(probe, found.fragment, options.activationPollMs);
118
- if (!passed2) {
119
- await probe.pressTab();
120
- passed2 = await probe.isFocusInsideTarget(found.fragment);
121
- }
122
- skipLinks.push({
123
- selector: found.selector,
124
- html: found.html,
125
- fragment: found.fragment,
126
- tabIndex: found.tabIndex,
127
- passed: passed2,
128
- failureReason: passed2 ? null : "activation-no-effect"
129
- });
130
- } finally {
131
- await probe.disposeRef(found.handle);
132
464
  }
465
+ } finally {
466
+ await probe.clearFocus();
133
467
  }
468
+ const unreachable = collected.length === 0 ? await probe.findUnreachable() : [];
134
469
  const passed = skipLinks.filter((link) => link.passed).length;
135
470
  return {
136
471
  skipLinks,
472
+ unreachable,
137
473
  summary: {
138
474
  found: skipLinks.length,
139
475
  passed,
140
- failed: skipLinks.length - passed
476
+ failed: skipLinks.length - passed,
477
+ unreachable: unreachable.length
141
478
  }
142
479
  };
143
480
  }
144
- async function pollFocusInsideTarget(probe, fragment, pollMs) {
145
- if (await probe.isFocusInsideTarget(fragment)) {
146
- return true;
147
- }
148
- if (pollMs <= 0) {
149
- return false;
150
- }
481
+ async function pollFocus(probe, ref, pollMs) {
482
+ let focus = await probe.readFocus(ref);
151
483
  const deadline = Date.now() + pollMs;
152
- while (Date.now() < deadline) {
484
+ while (!movedByEnter(focus) && Date.now() < deadline) {
153
485
  await new Promise((resolve) => setTimeout(resolve, 16));
154
- if (await probe.isFocusInsideTarget(fragment)) {
155
- return true;
156
- }
486
+ focus = await probe.readFocus(ref);
157
487
  }
158
- return false;
488
+ return focus;
159
489
  }
160
490
  function createAdaptorProbe(adaptor) {
161
491
  return {
@@ -166,22 +496,23 @@ function createAdaptorProbe(adaptor) {
166
496
  return adaptor.pressEnter();
167
497
  },
168
498
  async probeTabStop() {
169
- const base = await adaptor.evaluate(probeActiveElementScript);
170
- if (base.isBody) {
499
+ const handle = await adaptor.evaluateHandle(activeElementHandleScript);
500
+ const { link } = await adaptor.evaluate(inspectSkipLinkScript, handle, "classify");
501
+ if (!link || link.isBody) {
502
+ await adaptor.disposeRef(handle);
171
503
  return { isBody: true, identity: "body", candidate: null };
172
504
  }
173
- const handle = await adaptor.evaluateHandle(activeElementHandleScript);
174
505
  const selector = await adaptor.evaluate(getSelector, handle);
175
- const html = truncateHtml(base.html);
176
- if (base.fragment) {
506
+ if (link.fragment && link.skipLike) {
177
507
  return {
178
508
  isBody: false,
179
509
  identity: selector,
180
510
  candidate: {
181
511
  selector,
182
- html,
183
- fragment: base.fragment,
184
- targetResolves: base.targetResolves,
512
+ html: truncateHtml(link.html),
513
+ fragment: link.fragment,
514
+ linkText: link.linkText,
515
+ target: link.target && { ...link.target, html: truncateHtml(link.target.html) },
185
516
  handle
186
517
  }
187
518
  };
@@ -192,8 +523,70 @@ function createAdaptorProbe(adaptor) {
192
523
  focusHandle(ref) {
193
524
  return adaptor.evaluate(focusScript, ref);
194
525
  },
195
- isFocusInsideTarget(fragment) {
196
- return adaptor.evaluate(isFocusInsideTargetScript, fragment);
526
+ async readFocus(ref) {
527
+ const { link } = await adaptor.evaluate(inspectSkipLinkScript, ref, "focus");
528
+ return {
529
+ position: link?.focus.position ?? "body",
530
+ navigated: link?.focus.navigated ?? false,
531
+ targetExists: Boolean(link?.target),
532
+ targetRendered: link?.target?.rendered ?? false
533
+ };
534
+ },
535
+ async describeFocused() {
536
+ const handle = await adaptor.evaluateHandle(activeElementHandleScript);
537
+ try {
538
+ const { link } = await adaptor.evaluate(inspectSkipLinkScript, handle, "focus");
539
+ if (!link || link.isBody) {
540
+ return null;
541
+ }
542
+ return {
543
+ selector: await adaptor.evaluate(getSelector, handle),
544
+ html: truncateHtml(link.html)
545
+ };
546
+ } finally {
547
+ await adaptor.disposeRef(handle);
548
+ }
549
+ },
550
+ async findUnreachable() {
551
+ const { unreachable } = await adaptor.evaluate(
552
+ inspectSkipLinkScript,
553
+ null,
554
+ "unreachable",
555
+ UNREACHABLE_LIMIT
556
+ );
557
+ const results = [];
558
+ for (const link of unreachable) {
559
+ const handle = await adaptor.evaluateHandle(takeUnreachableSkipLinkScript);
560
+ try {
561
+ results.push({
562
+ selector: await adaptor.evaluate(getSelector, handle),
563
+ html: truncateHtml(link.html),
564
+ fragment: link.fragment,
565
+ linkText: link.linkText,
566
+ reason: link.reason
567
+ });
568
+ } finally {
569
+ await adaptor.disposeRef(handle);
570
+ }
571
+ }
572
+ return results;
573
+ },
574
+ saveState() {
575
+ return adaptor.evaluate(readPageStateScript);
576
+ },
577
+ restoreState(state) {
578
+ return adaptor.evaluate(restorePageStateScript, state);
579
+ },
580
+ clearFocus() {
581
+ return adaptor.evaluate(resetFocusScript);
582
+ },
583
+ async screenshotFocused(ref) {
584
+ await adaptor.evaluate(focusScript, ref);
585
+ await new Promise((resolve) => setTimeout(resolve, SCREENSHOT_SETTLE_MS));
586
+ return captureElementScreenshot(adaptor, ref, {
587
+ clipBuffer: SCREENSHOT_CLIP_BUFFER,
588
+ settleDelay: SCREENSHOT_SETTLE_MS
589
+ });
197
590
  },
198
591
  disposeRef(ref) {
199
592
  return adaptor.disposeRef(ref);