trykeyline-browser 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +14 -2
- package/audit/probe.mjs +390 -0
- package/audit.mjs +209 -0
- package/bin/trykeyline-browser.mjs +79 -0
- package/browse/args.mjs +44 -0
- package/browse/capture.mjs +181 -0
- package/browse/compare.mjs +260 -0
- package/browse/findings.mjs +125 -0
- package/browse/playwright.mjs +78 -0
- package/browse/report.mjs +265 -0
- package/browse/routes.mjs +252 -0
- package/browse/serve.mjs +61 -0
- package/browse/walk.mjs +117 -0
- package/browse.mjs +175 -0
- package/package.json +53 -4
- package/probe.mjs +26 -0
- package/smoke/clicks.mjs +320 -0
- package/smoke/config.mjs +184 -0
- package/smoke/forms.mjs +329 -0
- package/smoke/keyboard.mjs +100 -0
- package/smoke/links.mjs +120 -0
- package/smoke/page.mjs +575 -0
- package/smoke/phone.mjs +126 -0
- package/smoke/shift.mjs +103 -0
- package/smoke/util.mjs +113 -0
- package/smoke.mjs +412 -0
package/smoke/page.mjs
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the smoke test runs inside a page. Each export is a function Playwright
|
|
3
|
+
* serialises into the page (`page.evaluate(fn, arg)`), so none of them may
|
|
4
|
+
* close over anything here: they share helpers through `window.__kl`, which
|
|
5
|
+
* `HELPERS` installs and every exported function installs first.
|
|
6
|
+
*
|
|
7
|
+
* The same source works in an agent's own browser: `keyline probe <name>`
|
|
8
|
+
* prints any of them as one expression to paste into its JavaScript tool.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Installs window.__kl: visibility, accessible-ish names, selectors and boxes. Runs in the page. */
|
|
12
|
+
function installHelpers() {
|
|
13
|
+
if (window.__kl) return;
|
|
14
|
+
const sel =
|
|
15
|
+
window.__keylineSelector ||
|
|
16
|
+
function (el) {
|
|
17
|
+
const parts = [];
|
|
18
|
+
while (el && el.nodeType === 1 && parts.length < 4) {
|
|
19
|
+
if (el.id) {
|
|
20
|
+
parts.unshift("#" + CSS.escape(el.id));
|
|
21
|
+
break;
|
|
22
|
+
}
|
|
23
|
+
parts.unshift(el.localName);
|
|
24
|
+
el = el.parentElement;
|
|
25
|
+
}
|
|
26
|
+
return parts.join(" > ");
|
|
27
|
+
};
|
|
28
|
+
const box = (el) => {
|
|
29
|
+
const r = el.getBoundingClientRect();
|
|
30
|
+
return { x: Math.round(r.left + window.scrollX), y: Math.round(r.top + window.scrollY), w: Math.round(r.width), h: Math.round(r.height) };
|
|
31
|
+
};
|
|
32
|
+
const visible = (el) => {
|
|
33
|
+
if (!el || !el.isConnected || el.nodeType !== 1) return false;
|
|
34
|
+
const r = el.getBoundingClientRect();
|
|
35
|
+
if (r.width < 2 || r.height < 2) return false;
|
|
36
|
+
if (el.checkVisibility && !el.checkVisibility({ opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true })) return false;
|
|
37
|
+
const cs = getComputedStyle(el);
|
|
38
|
+
if (cs.visibility === "hidden" || cs.display === "none" || Number(cs.opacity) === 0) return false;
|
|
39
|
+
const vw = document.documentElement.clientWidth;
|
|
40
|
+
if (r.right <= 0 || r.left >= vw || r.bottom + window.scrollY <= 0) return false;
|
|
41
|
+
// Clipped to nothing (the "visually hidden" pattern).
|
|
42
|
+
if (cs.clip === "rect(0px, 0px, 0px, 0px)" || cs.clipPath === "inset(50%)") return false;
|
|
43
|
+
return true;
|
|
44
|
+
};
|
|
45
|
+
const clean = (s) => String(s || "").replace(/\s+/g, " ").trim().slice(0, 80);
|
|
46
|
+
const name = (el) => {
|
|
47
|
+
const labelled = el.getAttribute("aria-labelledby");
|
|
48
|
+
if (labelled) {
|
|
49
|
+
const t = labelled.split(/\s+/).map((id) => document.getElementById(id)?.innerText || "").join(" ");
|
|
50
|
+
if (clean(t)) return clean(t);
|
|
51
|
+
}
|
|
52
|
+
return clean(
|
|
53
|
+
el.getAttribute("aria-label") ||
|
|
54
|
+
el.innerText ||
|
|
55
|
+
(el.localName === "input" ? el.value : "") ||
|
|
56
|
+
el.getAttribute("title") ||
|
|
57
|
+
el.getAttribute("alt") ||
|
|
58
|
+
el.querySelector?.("img[alt]")?.getAttribute("alt") ||
|
|
59
|
+
el.querySelector?.("svg title")?.textContent ||
|
|
60
|
+
"",
|
|
61
|
+
);
|
|
62
|
+
};
|
|
63
|
+
const abs = (href) => {
|
|
64
|
+
try {
|
|
65
|
+
return new URL(href, location.href).href;
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const noHash = (u) => (u ? u.replace(/#.*$/, "") : u);
|
|
71
|
+
/** Text a reader can see on the page, as a set of words: what "the same content" is compared by. */
|
|
72
|
+
const words = () => {
|
|
73
|
+
const root = document.querySelector("main, [role=main]") || document.body;
|
|
74
|
+
const text = (root?.innerText || "").toLowerCase();
|
|
75
|
+
return [...new Set(text.match(/[\p{L}\p{N}]{2,}/gu) || [])].slice(0, 1500);
|
|
76
|
+
};
|
|
77
|
+
const OVERLAY = 'dialog[open], [role="dialog"], [role="alertdialog"], [aria-modal="true"], [role="menu"], [role="listbox"], [popover]:popover-open';
|
|
78
|
+
const overlays = () => {
|
|
79
|
+
let list = [];
|
|
80
|
+
try {
|
|
81
|
+
list = [...document.querySelectorAll(OVERLAY)];
|
|
82
|
+
} catch {
|
|
83
|
+
list = [...document.querySelectorAll(OVERLAY.replace(", [popover]:popover-open", ""))];
|
|
84
|
+
}
|
|
85
|
+
return list.filter(visible);
|
|
86
|
+
};
|
|
87
|
+
window.__kl = { sel, box, visible, name, clean, abs, noHash, words, overlays };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const HELPERS = `(${installHelpers.toString()})();`;
|
|
91
|
+
|
|
92
|
+
/** Make a function that installs the helpers, then runs `fn(arg)`. */
|
|
93
|
+
function withKl(fn) {
|
|
94
|
+
// eslint-disable-next-line no-new-func
|
|
95
|
+
return new Function("arg", `${HELPERS}\nreturn (${fn.toString()})(arg);`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/* ── Inventory: everything a tester would try ────────────────────────────── */
|
|
99
|
+
|
|
100
|
+
function inventoryFn(arg = {}) {
|
|
101
|
+
const kl = window.__kl;
|
|
102
|
+
const origin = location.origin;
|
|
103
|
+
const doc = document.documentElement;
|
|
104
|
+
const CONTROL = [
|
|
105
|
+
"a[href]",
|
|
106
|
+
"a[onclick]",
|
|
107
|
+
"button",
|
|
108
|
+
"input[type=button]",
|
|
109
|
+
"input[type=submit]",
|
|
110
|
+
"input[type=reset]",
|
|
111
|
+
"input[type=image]",
|
|
112
|
+
"summary",
|
|
113
|
+
"[role=button]",
|
|
114
|
+
"[role=link]",
|
|
115
|
+
"[role=tab]",
|
|
116
|
+
"[role=menuitem]",
|
|
117
|
+
"[role=option]",
|
|
118
|
+
"[role=switch]",
|
|
119
|
+
"[role=checkbox]",
|
|
120
|
+
"[onclick]",
|
|
121
|
+
].join(",");
|
|
122
|
+
|
|
123
|
+
const disabled = (el) => el.matches(":disabled") || el.closest('[aria-disabled="true"], [inert], fieldset:disabled');
|
|
124
|
+
const forms = [...document.forms];
|
|
125
|
+
const all = [];
|
|
126
|
+
const seen = new Set();
|
|
127
|
+
for (const el of document.querySelectorAll(CONTROL)) {
|
|
128
|
+
if (seen.has(el)) continue;
|
|
129
|
+
// A control inside another control is the same click.
|
|
130
|
+
if (el.parentElement?.closest(CONTROL) && !el.matches("a[href], button")) continue;
|
|
131
|
+
seen.add(el);
|
|
132
|
+
all.push(el);
|
|
133
|
+
}
|
|
134
|
+
// Elements that only say "click me" through the cursor: the div with an onClick handler.
|
|
135
|
+
for (const el of document.body ? document.body.querySelectorAll("*") : []) {
|
|
136
|
+
if (seen.has(el) || el.closest(CONTROL) || el.closest("label")) continue;
|
|
137
|
+
if (/^(html|body|input|select|textarea|option|label|svg|path|use|img|video|audio|iframe|canvas)$/.test(el.localName)) continue;
|
|
138
|
+
const cs = getComputedStyle(el);
|
|
139
|
+
if (cs.cursor !== "pointer") continue;
|
|
140
|
+
const parent = el.parentElement;
|
|
141
|
+
if (parent && getComputedStyle(parent).cursor === "pointer") continue;
|
|
142
|
+
if (el.querySelector(CONTROL + ", input, select, textarea, label")) continue;
|
|
143
|
+
seen.add(el);
|
|
144
|
+
all.push(el);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const clickables = [];
|
|
148
|
+
for (const el of all) {
|
|
149
|
+
if (disabled(el)) continue;
|
|
150
|
+
const visible = kl.visible(el);
|
|
151
|
+
if (!visible) continue;
|
|
152
|
+
const hrefRaw = el.localName === "a" ? el.getAttribute("href") : null;
|
|
153
|
+
const href = hrefRaw != null ? kl.abs(hrefRaw) : null;
|
|
154
|
+
const form = el.form || el.closest("form");
|
|
155
|
+
const type = (el.getAttribute("type") || "").toLowerCase();
|
|
156
|
+
const isSubmit = Boolean(form) && ((el.localName === "button" && (type === "" || type === "submit")) || (el.localName === "input" && (type === "submit" || type === "image")));
|
|
157
|
+
let kind = "pointer";
|
|
158
|
+
if (el.localName === "a" && hrefRaw != null) kind = "link";
|
|
159
|
+
else if (el.localName === "button" || el.localName === "input") kind = "button";
|
|
160
|
+
else if (el.getAttribute("role") || el.localName === "summary") kind = "control";
|
|
161
|
+
else if (el.hasAttribute("onclick")) kind = "button";
|
|
162
|
+
clickables.push({
|
|
163
|
+
i: clickables.length,
|
|
164
|
+
kind,
|
|
165
|
+
tag: el.localName,
|
|
166
|
+
role: el.getAttribute("role"),
|
|
167
|
+
text: kl.name(el),
|
|
168
|
+
sel: kl.sel(el),
|
|
169
|
+
box: kl.box(el),
|
|
170
|
+
href,
|
|
171
|
+
hrefRaw,
|
|
172
|
+
target: el.getAttribute("target"),
|
|
173
|
+
download: el.hasAttribute("download"),
|
|
174
|
+
sameOrigin: href ? href.startsWith(origin + "/") || href === origin : null,
|
|
175
|
+
placeholder: hrefRaw != null && /^\s*(#\s*|javascript:.*)?$/i.test(hrefRaw),
|
|
176
|
+
hashOnly: hrefRaw != null && /^#./.test(hrefRaw.trim()),
|
|
177
|
+
isSubmit,
|
|
178
|
+
form: form ? forms.indexOf(form) : -1,
|
|
179
|
+
haspopup: el.getAttribute("aria-haspopup"),
|
|
180
|
+
expanded: el.getAttribute("aria-expanded"),
|
|
181
|
+
controls: el.getAttribute("aria-controls"),
|
|
182
|
+
inNav: Boolean(el.closest("nav, header, [role=navigation], [role=banner]")),
|
|
183
|
+
// Already where it would take you: the selected tab, the current page's link. Clicking it should do nothing.
|
|
184
|
+
current: (el.getAttribute("aria-selected") === "true" && /^(tab|option)$/.test(el.getAttribute("role") || "")) || (el.hasAttribute("aria-current") && el.getAttribute("aria-current") !== "false"),
|
|
185
|
+
context: kl.clean(el.closest("form, section, [role=dialog], nav, header, footer, li, tr")?.getAttribute("aria-label") || ""),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const formList = forms.map((form, i) => {
|
|
190
|
+
const fields = [...form.elements]
|
|
191
|
+
.filter((f) => /^(input|select|textarea)$/.test(f.localName) && !/^(hidden|submit|button|reset|image)$/i.test(f.type) && !f.disabled)
|
|
192
|
+
.map((f) => {
|
|
193
|
+
const label = kl.clean((f.labels && f.labels[0]?.innerText) || f.getAttribute("aria-label") || f.getAttribute("placeholder") || f.name || "");
|
|
194
|
+
return {
|
|
195
|
+
sel: kl.sel(f),
|
|
196
|
+
tag: f.localName,
|
|
197
|
+
type: (f.type || "text").toLowerCase(),
|
|
198
|
+
name: f.name || null,
|
|
199
|
+
label,
|
|
200
|
+
required: f.required || f.getAttribute("aria-required") === "true" || /\*\s*$/.test(label),
|
|
201
|
+
pattern: f.getAttribute("pattern"),
|
|
202
|
+
minLength: f.minLength > 0 ? f.minLength : null,
|
|
203
|
+
min: f.getAttribute("min"),
|
|
204
|
+
max: f.getAttribute("max"),
|
|
205
|
+
visible: kl.visible(f),
|
|
206
|
+
};
|
|
207
|
+
});
|
|
208
|
+
const submit = [...form.querySelectorAll('button:not([type]), button[type=submit], input[type=submit], input[type=image]')].find(kl.visible) ||
|
|
209
|
+
(form.id ? [...document.querySelectorAll(`[form="${CSS.escape(form.id)}"]`)].find((b) => b.type === "submit" && kl.visible(b)) : null);
|
|
210
|
+
return {
|
|
211
|
+
i,
|
|
212
|
+
sel: kl.sel(form),
|
|
213
|
+
box: kl.box(form),
|
|
214
|
+
visible: kl.visible(form),
|
|
215
|
+
method: (form.getAttribute("method") || "get").toLowerCase(),
|
|
216
|
+
action: form.getAttribute("action") ? kl.abs(form.getAttribute("action")) : location.href,
|
|
217
|
+
novalidate: form.noValidate,
|
|
218
|
+
role: form.getAttribute("role"),
|
|
219
|
+
name: kl.clean(form.getAttribute("aria-label") || form.querySelector("h1,h2,h3,legend")?.innerText || ""),
|
|
220
|
+
text: kl.clean(form.innerText).slice(0, 200),
|
|
221
|
+
fields,
|
|
222
|
+
submit: submit ? { sel: kl.sel(submit), text: kl.name(submit), box: kl.box(submit) } : null,
|
|
223
|
+
};
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
// Every same-origin link, visible or not, once per target: the link check reads these.
|
|
227
|
+
// Keyed by URL and words, so placeholder links (all "#") stay apart for the phone pass.
|
|
228
|
+
const links = [];
|
|
229
|
+
const byKey = new Set();
|
|
230
|
+
for (const a of document.querySelectorAll("a[href]")) {
|
|
231
|
+
const href = kl.noHash(kl.abs(a.getAttribute("href")));
|
|
232
|
+
if (!href || !/^https?:/.test(href)) continue;
|
|
233
|
+
const key = href + "|" + kl.name(a);
|
|
234
|
+
if (byKey.has(key)) continue;
|
|
235
|
+
byKey.add(key);
|
|
236
|
+
const vis = kl.visible(a);
|
|
237
|
+
links.push({ key, href, sameOrigin: href.startsWith(origin + "/") || href === origin, text: kl.name(a), sel: kl.sel(a), box: vis ? kl.box(a) : null, visible: vis, inNav: Boolean(a.closest("nav, header, [role=navigation], [role=banner]")) });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Wider than the screen: the widest element that pokes out, outside any scroller.
|
|
241
|
+
let overflow = null;
|
|
242
|
+
const vw = doc.clientWidth;
|
|
243
|
+
if (doc.scrollWidth > vw + 1) {
|
|
244
|
+
let worst = null;
|
|
245
|
+
for (const el of document.body.querySelectorAll("*")) {
|
|
246
|
+
const r = el.getBoundingClientRect();
|
|
247
|
+
if (r.right <= vw + 1 || r.width === 0) continue;
|
|
248
|
+
let clipped = false;
|
|
249
|
+
for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
|
|
250
|
+
const ox = getComputedStyle(p).overflowX;
|
|
251
|
+
if (ox !== "visible") {
|
|
252
|
+
clipped = true;
|
|
253
|
+
break;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (clipped) continue;
|
|
257
|
+
const pr = el.parentElement?.getBoundingClientRect();
|
|
258
|
+
if (pr && pr.right > vw + 1 && el.parentElement !== document.body) continue; // report the outermost
|
|
259
|
+
if (!worst || r.right > worst.r.right) worst = { el, r };
|
|
260
|
+
}
|
|
261
|
+
// Outline something that's at least partly on screen: the off-screen element's nearest visible ancestor.
|
|
262
|
+
let shown = worst?.el;
|
|
263
|
+
while (shown && shown.parentElement && shown.parentElement !== document.body && shown.getBoundingClientRect().left >= vw) shown = shown.parentElement;
|
|
264
|
+
overflow = {
|
|
265
|
+
scrollWidth: doc.scrollWidth,
|
|
266
|
+
width: vw,
|
|
267
|
+
culprit: worst ? { sel: kl.sel(shown), box: kl.box(shown), text: kl.name(shown), past: kl.sel(worst.el), pastName: kl.name(worst.el), offscreen: worst.r.left >= vw } : null,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
return { url: location.href, clickables, forms: formList, links, overflow };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Find one clickable again in a fresh page and mark it for Playwright: `[data-keyline-target]`. */
|
|
275
|
+
function markFn({ match, attr = "data-keyline-target" }) {
|
|
276
|
+
const kl = window.__kl;
|
|
277
|
+
for (const old of document.querySelectorAll(`[${attr}]`)) old.removeAttribute(attr);
|
|
278
|
+
let el = null;
|
|
279
|
+
try {
|
|
280
|
+
const candidates = [...document.querySelectorAll(match.sel)];
|
|
281
|
+
el = candidates.find((c) => kl.name(c) === match.text) || (candidates.length === 1 ? candidates[0] : null);
|
|
282
|
+
} catch {
|
|
283
|
+
// An unparseable selector: fall through to text.
|
|
284
|
+
}
|
|
285
|
+
if (!el && match.text) {
|
|
286
|
+
const tags = document.querySelectorAll(match.tag || "*");
|
|
287
|
+
el = [...tags].find((c) => kl.name(c) === match.text && kl.visible(c)) || null;
|
|
288
|
+
}
|
|
289
|
+
if (!el) return null;
|
|
290
|
+
el.setAttribute(attr, "");
|
|
291
|
+
return { box: kl.box(el), sel: kl.sel(el) };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/* ── Stuck loading ───────────────────────────────────────────────────────── */
|
|
295
|
+
|
|
296
|
+
async function stuckFn({ after = 8000 } = {}) {
|
|
297
|
+
const kl = window.__kl;
|
|
298
|
+
const LOADER = /(^|[-_\s])(spinner|loader|loading|skeleton|shimmer|placeholder-glow|placeholder-wave)([-_\s]|$)/i;
|
|
299
|
+
const isLoader = (el) =>
|
|
300
|
+
el.getAttribute("aria-busy") === "true" ||
|
|
301
|
+
(el.getAttribute("role") === "progressbar" && !el.hasAttribute("aria-valuenow")) ||
|
|
302
|
+
(el.localName === "progress" && !el.hasAttribute("value")) ||
|
|
303
|
+
(typeof el.className === "string" && LOADER.test(el.className));
|
|
304
|
+
const find = () => {
|
|
305
|
+
const hits = [...document.body.querySelectorAll("*")].filter((el) => isLoader(el) && kl.visible(el));
|
|
306
|
+
return hits.filter((el) => !hits.some((o) => o !== el && o.contains(el)));
|
|
307
|
+
};
|
|
308
|
+
if (!find().length) return [];
|
|
309
|
+
const wait = after - performance.now();
|
|
310
|
+
if (wait > 0) await new Promise((r) => setTimeout(r, wait));
|
|
311
|
+
return find().map((el) => ({
|
|
312
|
+
sel: kl.sel(el),
|
|
313
|
+
box: kl.box(el),
|
|
314
|
+
text: kl.name(el),
|
|
315
|
+
why: el.getAttribute("aria-busy") === "true" ? 'aria-busy="true"' : el.getAttribute("role") === "progressbar" ? "an indeterminate progressbar" : el.localName === "progress" ? "an indeterminate <progress>" : `class "${String(el.className).trim().slice(0, 60)}"`,
|
|
316
|
+
seconds: Math.round(performance.now() / 100) / 10,
|
|
317
|
+
}));
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/* ── Watching a click ────────────────────────────────────────────────────── */
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Start watching the page. Mutations during the baseline (before `armFn`) mark
|
|
324
|
+
* their nodes as background noise — a clock, a carousel — and are ignored after.
|
|
325
|
+
*/
|
|
326
|
+
function watchFn() {
|
|
327
|
+
const kl = window.__kl;
|
|
328
|
+
const target = document.querySelector("[data-keyline-target]");
|
|
329
|
+
// Press, hover and focus markers that libraries set on the control itself are not an effect.
|
|
330
|
+
const PRESS = /^data-(?:rac-)?(?:pressed|focus|focused|focus-visible|focus-within|hovered|hover|active)$/;
|
|
331
|
+
const w = {
|
|
332
|
+
armed: false,
|
|
333
|
+
bg: new WeakSet(),
|
|
334
|
+
count: 0,
|
|
335
|
+
samples: [],
|
|
336
|
+
own: new Map(), // attribute changes on the target or its ancestors: count only if they stuck
|
|
337
|
+
focus: null,
|
|
338
|
+
scroll: [0, 0],
|
|
339
|
+
overlays: 0,
|
|
340
|
+
expanded: null,
|
|
341
|
+
words: null,
|
|
342
|
+
target,
|
|
343
|
+
};
|
|
344
|
+
const describe = (m) => (m.type === "childList" ? `${m.addedNodes.length ? "added" : "removed"} in ${kl.sel(m.target.nodeType === 1 ? m.target : m.target.parentElement)}` : m.type === "attributes" ? `${m.attributeName} on ${kl.sel(m.target)}` : `text in ${kl.sel(m.target.parentElement)}`);
|
|
345
|
+
const obs = new MutationObserver((list) => {
|
|
346
|
+
for (const m of list) {
|
|
347
|
+
if (m.type === "attributes" && /^data-keyline/.test(m.attributeName)) continue;
|
|
348
|
+
if (!w.armed) {
|
|
349
|
+
w.bg.add(m.target);
|
|
350
|
+
continue;
|
|
351
|
+
}
|
|
352
|
+
if (w.bg.has(m.target)) continue;
|
|
353
|
+
if (m.type === "attributes" && m.target.nodeType === 1 && target && m.target.contains(target)) {
|
|
354
|
+
if (PRESS.test(m.attributeName)) continue;
|
|
355
|
+
const key = m.attributeName;
|
|
356
|
+
if (!w.own.has(m.target)) w.own.set(m.target, new Map());
|
|
357
|
+
const byAttr = w.own.get(m.target);
|
|
358
|
+
if (!byAttr.has(key)) byAttr.set(key, m.oldValue);
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
w.count++;
|
|
362
|
+
if (w.samples.length < 3) w.samples.push(describe(m));
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
obs.observe(document, { subtree: true, childList: true, attributes: true, attributeOldValue: true, characterData: true });
|
|
366
|
+
w.obs = obs;
|
|
367
|
+
window.__klWatch = w;
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function armFn() {
|
|
372
|
+
const kl = window.__kl;
|
|
373
|
+
const w = window.__klWatch;
|
|
374
|
+
if (!w) return false;
|
|
375
|
+
w.armed = true;
|
|
376
|
+
w.focus = document.activeElement;
|
|
377
|
+
w.scroll = [window.scrollX, window.scrollY];
|
|
378
|
+
w.overlays = kl.overlays().length;
|
|
379
|
+
w.expanded = w.target?.getAttribute("aria-expanded") ?? null;
|
|
380
|
+
w.words = kl.words();
|
|
381
|
+
return { words: w.words };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function readFn() {
|
|
385
|
+
const kl = window.__kl;
|
|
386
|
+
const w = window.__klWatch;
|
|
387
|
+
if (!w || !kl) return { gone: true };
|
|
388
|
+
let own = 0;
|
|
389
|
+
for (const [node, attrs] of w.own) for (const [attr, old] of attrs) if (node.getAttribute(attr) !== old) own++;
|
|
390
|
+
const active = document.activeElement;
|
|
391
|
+
const focusMoved = active !== w.focus && active && active !== document.body && !(w.target && w.target.contains(active)) && !(active === w.target);
|
|
392
|
+
const overlays = kl.overlays();
|
|
393
|
+
const expanded = w.target?.isConnected ? w.target.getAttribute("aria-expanded") : null;
|
|
394
|
+
return {
|
|
395
|
+
gone: false,
|
|
396
|
+
mutations: w.count + own,
|
|
397
|
+
samples: w.samples,
|
|
398
|
+
focusMoved: Boolean(focusMoved),
|
|
399
|
+
focusTo: focusMoved ? kl.sel(active) : null,
|
|
400
|
+
scrolled: Math.abs(window.scrollX - w.scroll[0]) + Math.abs(window.scrollY - w.scroll[1]) > 4,
|
|
401
|
+
opened: overlays.length > w.overlays || (w.expanded === "false" && expanded === "true"),
|
|
402
|
+
overlays: overlays.map((o) => kl.sel(o)),
|
|
403
|
+
overlaysBefore: w.overlays,
|
|
404
|
+
expanded,
|
|
405
|
+
expandedBefore: w.expanded,
|
|
406
|
+
targetConnected: Boolean(w.target?.isConnected),
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** After Escape: is what opened still open, and where did focus go? */
|
|
411
|
+
function afterEscapeFn() {
|
|
412
|
+
const kl = window.__kl;
|
|
413
|
+
const w = window.__klWatch;
|
|
414
|
+
const target = w?.target ?? document.querySelector("[data-keyline-target]");
|
|
415
|
+
return {
|
|
416
|
+
overlays: kl.overlays().map((o) => kl.sel(o)),
|
|
417
|
+
expanded: target?.isConnected ? target.getAttribute("aria-expanded") : null,
|
|
418
|
+
focusOnTarget: Boolean(target && (document.activeElement === target || target.contains(document.activeElement))),
|
|
419
|
+
focus: document.activeElement ? kl.sel(document.activeElement) : null,
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function wordsFn() {
|
|
424
|
+
return window.__kl.words();
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/* ── Keyboard ────────────────────────────────────────────────────────────── */
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* Record how every focusable element looks before it has focus, so a Tab can
|
|
431
|
+
* tell whether focus changed anything a reader can see. Transitions are
|
|
432
|
+
* switched off so the focused style is read at its end state.
|
|
433
|
+
*/
|
|
434
|
+
function keyboardPrepFn() {
|
|
435
|
+
const kl = window.__kl;
|
|
436
|
+
const style = document.createElement("style");
|
|
437
|
+
style.textContent = "*,*::before,*::after{transition-duration:0s!important;transition-delay:0s!important}";
|
|
438
|
+
document.head.appendChild(style);
|
|
439
|
+
const FOCUSABLE = 'a[href], button, input:not([type=hidden]), select, textarea, summary, iframe, [tabindex], [contenteditable=""], [contenteditable=true], audio[controls], video[controls]';
|
|
440
|
+
const sig = (el) => {
|
|
441
|
+
const parts = [];
|
|
442
|
+
for (const pseudo of [null, "::before", "::after"]) {
|
|
443
|
+
const cs = getComputedStyle(el, pseudo);
|
|
444
|
+
if (pseudo && cs.content === "none") {
|
|
445
|
+
parts.push("-");
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
parts.push([cs.outlineStyle, cs.outlineWidth, cs.outlineColor, cs.outlineOffset, cs.boxShadow, cs.borderTopColor, cs.borderBottomColor, cs.borderBottomWidth, cs.backgroundColor, cs.backgroundImage, cs.color, cs.textDecorationLine, cs.transform, cs.opacity].join("|"));
|
|
449
|
+
}
|
|
450
|
+
return parts.join("¦");
|
|
451
|
+
};
|
|
452
|
+
const all = [...document.querySelectorAll(FOCUSABLE)].filter((el) => el.tabIndex >= 0 && !el.matches(":disabled") && !el.closest("[inert]"));
|
|
453
|
+
const before = new Map();
|
|
454
|
+
for (const el of all) {
|
|
455
|
+
before.set(el, sig(el));
|
|
456
|
+
if (el.parentElement) before.set(el.parentElement, sig(el.parentElement));
|
|
457
|
+
}
|
|
458
|
+
window.__klKb = { before, sig, ids: new WeakMap(), next: 1 };
|
|
459
|
+
return { tabbable: all.filter((el) => kl.visible(el) || el.getBoundingClientRect().width > 0).length, total: all.length };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function keyboardReadFn() {
|
|
463
|
+
const kl = window.__kl;
|
|
464
|
+
const kb = window.__klKb;
|
|
465
|
+
let el = document.activeElement;
|
|
466
|
+
if (!el || el === document.body || el === document.documentElement) return { body: true };
|
|
467
|
+
// Framework dev overlays sit after the page in the Tab order; reaching one is the end of the page.
|
|
468
|
+
if (el.closest("nextjs-portal, vite-error-overlay, astro-dev-toolbar, [data-nextjs-dev-tools-button], #__next-build-watcher")) return { body: true, devtool: true };
|
|
469
|
+
// Inside a shadow root the document only sees the host: follow focus in.
|
|
470
|
+
while (el.shadowRoot && el.shadowRoot.activeElement) el = el.shadowRoot.activeElement;
|
|
471
|
+
if (!kb.ids.has(el)) kb.ids.set(el, kb.next++);
|
|
472
|
+
const id = kb.ids.get(el);
|
|
473
|
+
const iframe = el.localName === "iframe";
|
|
474
|
+
const before = kb.before.get(el);
|
|
475
|
+
const parent = el.parentElement;
|
|
476
|
+
const changed = before === undefined ? null : kb.sig(el) !== before || (parent && kb.before.has(parent) && kb.sig(parent) !== kb.before.get(parent));
|
|
477
|
+
const modal = el.closest('dialog[open], [aria-modal="true"]');
|
|
478
|
+
const r = el.getBoundingClientRect();
|
|
479
|
+
const onScreen = r.width >= 1 && r.height >= 1 && r.bottom > 0 && r.right > 0 && r.left < document.documentElement.clientWidth && kl.visible(el);
|
|
480
|
+
return {
|
|
481
|
+
body: false,
|
|
482
|
+
id,
|
|
483
|
+
sel: kl.sel(el),
|
|
484
|
+
text: kl.name(el),
|
|
485
|
+
box: kl.box(el),
|
|
486
|
+
iframe,
|
|
487
|
+
ring: changed,
|
|
488
|
+
onScreen,
|
|
489
|
+
inModal: Boolean(modal && kl.visible(modal)),
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/* ── Forms ───────────────────────────────────────────────────────────────── */
|
|
494
|
+
|
|
495
|
+
/** The visible text near a form, so a submit can tell whether anything new appeared, and where. */
|
|
496
|
+
function textSnapshotFn({ formSel }) {
|
|
497
|
+
const kl = window.__kl;
|
|
498
|
+
const form = formSel ? document.querySelector(formSel) : null;
|
|
499
|
+
const fields = form ? [...form.elements].filter((f) => /^(input|select|textarea)$/.test(f.localName) && f.type !== "hidden") : [];
|
|
500
|
+
const fieldBoxes = fields.filter(kl.visible).map((f) => kl.box(f));
|
|
501
|
+
const items = [];
|
|
502
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
503
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
504
|
+
const t = n.textContent.replace(/\s+/g, " ").trim();
|
|
505
|
+
if (!t || !n.parentElement || /^(script|style|noscript|template)$/i.test(n.parentElement.localName)) continue;
|
|
506
|
+
if (!kl.visible(n.parentElement)) continue;
|
|
507
|
+
items.push({ text: t.slice(0, 120), box: kl.box(n.parentElement), sel: kl.sel(n.parentElement) });
|
|
508
|
+
}
|
|
509
|
+
const invalid = fields.filter((f) => f.getAttribute("aria-invalid") === "true" && kl.visible(f)).map((f) => kl.sel(f));
|
|
510
|
+
const values = fields.map((f) => (f.type === "checkbox" || f.type === "radio" ? String(f.checked) : f.value)).join("\u0001");
|
|
511
|
+
return { items, fieldBoxes, invalid, values, url: location.href, formConnected: Boolean(form?.isConnected) };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/** Listen for the browser's own validation (the `invalid` event) on a form's fields. */
|
|
515
|
+
function listenInvalidFn({ formSel }) {
|
|
516
|
+
window.__klInvalid = [];
|
|
517
|
+
const form = document.querySelector(formSel);
|
|
518
|
+
if (!form) return false;
|
|
519
|
+
for (const f of form.elements) f.addEventListener("invalid", () => window.__klInvalid.push(window.__kl.sel(f)), { once: true });
|
|
520
|
+
return true;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function readInvalidFn() {
|
|
524
|
+
return window.__klInvalid || [];
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** Submit a form the way a person does: its button, or Enter when it has none. */
|
|
528
|
+
function requestSubmitFn({ formSel }) {
|
|
529
|
+
const form = document.querySelector(formSel);
|
|
530
|
+
if (!form) return false;
|
|
531
|
+
form.requestSubmit ? form.requestSubmit() : form.submit();
|
|
532
|
+
return true;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Which of these links (keyed "url|words", as the inventory keys them) are on screen right now. */
|
|
536
|
+
function visibleHrefsFn({ keys }) {
|
|
537
|
+
const kl = window.__kl;
|
|
538
|
+
const shown = new Set([...document.querySelectorAll("a[href]")].filter(kl.visible).map((a) => kl.noHash(a.href) + "|" + kl.name(a)));
|
|
539
|
+
return keys.filter((k) => shown.has(k));
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export const PAGE = {
|
|
543
|
+
visibleHrefs: withKl(visibleHrefsFn),
|
|
544
|
+
inventory: withKl(inventoryFn),
|
|
545
|
+
mark: withKl(markFn),
|
|
546
|
+
stuck: withKl(stuckFn),
|
|
547
|
+
watch: withKl(watchFn),
|
|
548
|
+
arm: withKl(armFn),
|
|
549
|
+
read: withKl(readFn),
|
|
550
|
+
afterEscape: withKl(afterEscapeFn),
|
|
551
|
+
words: withKl(wordsFn),
|
|
552
|
+
keyboardPrep: withKl(keyboardPrepFn),
|
|
553
|
+
keyboardRead: withKl(keyboardReadFn),
|
|
554
|
+
textSnapshot: withKl(textSnapshotFn),
|
|
555
|
+
listenInvalid: withKl(listenInvalidFn),
|
|
556
|
+
readInvalid: withKl(readInvalidFn),
|
|
557
|
+
requestSubmit: withKl(requestSubmitFn),
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
/** One expression an agent can paste into its browser's JavaScript tool. */
|
|
561
|
+
export function expression(name, arg = {}) {
|
|
562
|
+
const fn = PAGE[name];
|
|
563
|
+
if (!fn) throw new Error(`no page function '${name}' — one of ${Object.keys(PAGE).join(", ")}`);
|
|
564
|
+
return `(${fn.toString()})(${JSON.stringify(arg)})`;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Jaccard similarity of two word lists: 1 is the same content, 0 nothing shared. */
|
|
568
|
+
export function similarity(a = [], b = []) {
|
|
569
|
+
if (!a.length && !b.length) return 1;
|
|
570
|
+
const A = new Set(a);
|
|
571
|
+
const B = new Set(b);
|
|
572
|
+
let both = 0;
|
|
573
|
+
for (const w of A) if (B.has(w)) both++;
|
|
574
|
+
return both / (A.size + B.size - both);
|
|
575
|
+
}
|