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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The phone pass: at 390px, is the page still one screen wide, and can a
3
+ * person still reach every place the desktop navigation goes? Links hidden at
4
+ * phone width need a menu button that shows them, and the menu it opens
5
+ * should close on Escape.
6
+ */
7
+ import { add } from "../browse/findings.mjs";
8
+ import { shotKey } from "../browse/capture.mjs";
9
+ import { PAGE } from "./page.mjs";
10
+ import { describe, open, openStep, pathOf, sleep } from "./util.mjs";
11
+
12
+ const MENU_WORDS = /\b(menu|nav|navigation|open menu|toggle|more)\b|☰|≡/i;
13
+
14
+ function toggleScore(c) {
15
+ let s = 0;
16
+ if (c.expanded != null) s += 4;
17
+ if (c.controls) s += 3;
18
+ if (c.haspopup) s += 2;
19
+ if (MENU_WORDS.test(c.text)) s += 3;
20
+ if (c.inNav) s += 1;
21
+ if (c.box.y < 140) s += 1;
22
+ return s;
23
+ }
24
+
25
+ export async function checkPhone({ run, context, base, route, desktop, phone, find, log }) {
26
+ const at = { page: route, viewport: "phone", theme: "light", shot: shotKey("phone", "light") };
27
+ if (phone?.overflow) {
28
+ const o = phone.overflow;
29
+ add(run, {
30
+ ...at,
31
+ box: o.culprit?.box,
32
+ selector: o.culprit?.sel,
33
+ ...(o.culprit ? (find?.(o.culprit) ?? {}) : {}),
34
+ rule: "flow/phone-overflow",
35
+ severity: "warning",
36
+ title: "The page is wider than a phone screen",
37
+ evidence: `${o.scrollWidth}px of content in a ${o.width}px screen${o.culprit ? `; ${o.culprit.offscreen ? `${o.culprit.pastName ? `“${o.culprit.pastName}”` : o.culprit.past} is entirely past the edge, inside ${o.culprit.sel}` : `widest: ${o.culprit.sel}`}` : ""}`,
38
+ detail: "Everything can be dragged sideways, and whatever sits past the edge is easy to miss. Let the wide element wrap, shrink or scroll inside its own box.",
39
+ fix: "/keyline layout",
40
+ steps: [openStep(route, "phone"), "Swipe sideways", `The page scrolls ${o.scrollWidth - o.width}px to the side`],
41
+ });
42
+ }
43
+
44
+ const desktopNav = [...new Set((desktop?.links ?? []).filter((l) => l.sameOrigin && l.visible && l.inNav).map((l) => l.key))];
45
+ const shown = new Set((phone?.links ?? []).filter((l) => l.visible).map((l) => l.key));
46
+ const missing = desktopNav.filter((k) => !shown.has(k));
47
+ if (!missing.length) return;
48
+ const label = (k) => {
49
+ const l = desktop.links.find((x) => x.key === k);
50
+ return l?.text ? `“${l.text}”` : pathOf(l?.href ?? k, base);
51
+ };
52
+ const names = missing.slice(0, 6).map(label).join(", ") + (missing.length > 6 ? ", …" : "");
53
+
54
+ const toggles = (phone?.clickables ?? []).filter((c) => (c.kind !== "link" || c.placeholder) && toggleScore(c) >= 3).sort((a, b) => toggleScore(b) - toggleScore(a));
55
+ if (!toggles.length) {
56
+ add(run, {
57
+ ...at,
58
+ rule: "flow/phone-nav-missing",
59
+ severity: "error",
60
+ title: `On a phone, ${missing.length === 1 ? "a place in the navigation is" : `${missing.length} places in the navigation are`} out of reach`,
61
+ evidence: `hidden at 390px with no menu button: ${names}`,
62
+ detail: "The desktop navigation hides on a phone and nothing replaces it. Add a menu button that opens it, or let it wrap.",
63
+ fix: "/keyline layout",
64
+ steps: [openStep(route, "phone"), `Look for ${label(missing[0])}`, "It's hidden, and there's no menu button to show it"],
65
+ });
66
+ return;
67
+ }
68
+
69
+ const toggle = toggles[0];
70
+ log(` phone ${route} ${missing.length} nav links hidden; trying ${describe(toggle)}`);
71
+ const { page, error } = await open(context, { base, route });
72
+ try {
73
+ if (error) return;
74
+ const marked = await page.evaluate(PAGE.mark, { match: { sel: toggle.sel, text: toggle.text, tag: toggle.tag } });
75
+ if (!marked) return;
76
+ await page.evaluate(PAGE.watch);
77
+ await sleep(250);
78
+ await page.evaluate(PAGE.arm);
79
+ const steps = [openStep(route, "phone"), `Tap ${describe(toggle)}`];
80
+ try {
81
+ await page.locator("[data-keyline-target]").first().click({ timeout: 2500 });
82
+ } catch {
83
+ return; // the click pass reports what blocks a control
84
+ }
85
+ await sleep(700);
86
+ const read = await page.evaluate(PAGE.read).catch(() => null);
87
+ const revealed = await page.evaluate(PAGE.visibleHrefs, { keys: missing }).catch(() => []);
88
+ if (!revealed.length) {
89
+ add(run, {
90
+ ...at,
91
+ box: toggle.box,
92
+ selector: toggle.sel,
93
+ ...(find?.(toggle) ?? {}),
94
+ rule: "flow/phone-menu-dead",
95
+ severity: "error",
96
+ title: `On a phone, ${describe(toggle)} doesn't show the navigation`,
97
+ evidence: `after the tap, still hidden: ${names}`,
98
+ detail: "The menu button is there but what it should reveal stays hidden, so these pages can't be reached on a phone.",
99
+ steps: [...steps, `${label(missing[0])} is still nowhere to be seen`],
100
+ });
101
+ return;
102
+ }
103
+ if (read?.opened) {
104
+ await page.keyboard.press("Escape");
105
+ await sleep(400);
106
+ const still = await page.evaluate(PAGE.visibleHrefs, { keys: revealed }).catch(() => []);
107
+ const after = await page.evaluate(PAGE.afterEscape).catch(() => null);
108
+ if (still.length && after && (after.expanded === "true" || after.overlays.length > read.overlaysBefore)) {
109
+ add(run, {
110
+ ...at,
111
+ box: toggle.box,
112
+ selector: toggle.sel,
113
+ rule: "flow/escape-ignored",
114
+ severity: "warning",
115
+ title: "On a phone, Escape doesn't close the menu",
116
+ evidence: `${still.length} menu links still showing after Escape`,
117
+ detail: "A keyboard (or switch, or screen reader) user closes an open menu with Escape.",
118
+ fix: "/keyline patterns",
119
+ steps: [...steps, "The menu opens", "Press Escape", "It stays open"],
120
+ });
121
+ }
122
+ }
123
+ } finally {
124
+ await page.close().catch(() => {});
125
+ }
126
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Load each page on a slow connection and record what moves while it loads:
3
+ * the browser's own layout-shift entries, scored as Cumulative Layout Shift
4
+ * (the worst burst of shifts, each burst under 5 s with gaps under 1 s).
5
+ * A fast local server hides most shifts; throttling brings back what a reader
6
+ * on a train sees — text that jumps when an image or a font arrives.
7
+ */
8
+ import { add } from "../browse/findings.mjs";
9
+ import { shotKey } from "../browse/capture.mjs";
10
+ import { sleep } from "./util.mjs";
11
+
12
+ export const SLOW = { latency: 150, downloadKbps: 1600, uploadKbps: 750, cpu: 2 };
13
+
14
+ function recordShifts() {
15
+ window.__klShifts = [];
16
+ try {
17
+ new PerformanceObserver((list) => {
18
+ for (const e of list.getEntries()) {
19
+ if (e.hadRecentInput) continue;
20
+ window.__klShifts.push({ value: e.value, t: e.startTime, sources: (e.sources || []).map((s) => ({ node: s.node, now: s.currentRect, was: s.previousRect })) });
21
+ }
22
+ }).observe({ type: "layout-shift", buffered: true });
23
+ } catch {
24
+ window.__klShifts = null;
25
+ }
26
+ }
27
+
28
+ function readShifts() {
29
+ const list = window.__klShifts;
30
+ if (!list) return null;
31
+ const sel = window.__keylineSelector || ((n) => n?.localName ?? null);
32
+ return list.map((e) => ({
33
+ value: e.value,
34
+ t: Math.round(e.t),
35
+ sources: e.sources.map((s) => ({
36
+ sel: s.node && s.node.nodeType === 1 && s.node.isConnected ? sel(s.node) : s.node?.parentElement?.isConnected ? sel(s.node.parentElement) : null,
37
+ now: { x: Math.round(s.now.x), y: Math.round(s.now.y + window.scrollY), w: Math.round(s.now.width), h: Math.round(s.now.height) },
38
+ dy: Math.round(s.now.y - s.was.y),
39
+ dx: Math.round(s.now.x - s.was.x),
40
+ })),
41
+ }));
42
+ }
43
+
44
+ /** CLS as Chrome scores it: the largest session window. */
45
+ export function cls(entries) {
46
+ let best = { value: 0, entries: [] };
47
+ let cur = { value: 0, entries: [] };
48
+ for (const e of entries) {
49
+ const last = cur.entries.at(-1);
50
+ if (last && (e.t - last.t > 1000 || e.t - cur.entries[0].t > 5000)) cur = { value: 0, entries: [] };
51
+ cur.value += e.value;
52
+ cur.entries.push(e);
53
+ if (cur.value > best.value) best = { value: cur.value, entries: [...cur.entries] };
54
+ }
55
+ return best;
56
+ }
57
+
58
+ export async function checkShift({ run, context, base, route, log, find }) {
59
+ const page = await context.newPage();
60
+ try {
61
+ await page.addInitScript(recordShifts);
62
+ const cdp = await context.newCDPSession(page);
63
+ await cdp.send("Network.enable");
64
+ await cdp.send("Network.emulateNetworkConditions", { offline: false, latency: SLOW.latency, downloadThroughput: (SLOW.downloadKbps * 1024) / 8, uploadThroughput: (SLOW.uploadKbps * 1024) / 8 });
65
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: SLOW.cpu }).catch(() => {});
66
+ try {
67
+ await page.goto(new URL(route, base).href, { waitUntil: "load", timeout: 60000 });
68
+ } catch {
69
+ return;
70
+ }
71
+ await page.waitForLoadState("networkidle", { timeout: 10000 }).catch(() => {});
72
+ await sleep(1500);
73
+ const entries = await page.evaluate(readShifts).catch(() => null);
74
+ if (!entries) return;
75
+ const score = cls(entries);
76
+ log(` shift ${route} CLS ${score.value.toFixed(3)}`);
77
+ run.stats.shiftChecked++;
78
+ if (score.value < 0.1) return;
79
+ const sources = score.entries.flatMap((e) => e.sources).filter((s) => s.sel);
80
+ const worst = sources.sort((a, b) => Math.abs(b.dy) + Math.abs(b.dx) - (Math.abs(a.dy) + Math.abs(a.dx)))[0];
81
+ const moved = worst ? `${worst.sel} moved ${Math.abs(worst.dy) >= Math.abs(worst.dx) ? `${Math.abs(worst.dy)}px ${worst.dy > 0 ? "down" : "up"}` : `${Math.abs(worst.dx)}px sideways`}` : "";
82
+ add(run, {
83
+ page: route,
84
+ viewport: "desktop",
85
+ theme: "light",
86
+ shot: shotKey("desktop", "light"),
87
+ box: worst?.now,
88
+ selector: worst?.sel,
89
+ ...(worst ? (find?.({ sel: worst.sel }) ?? {}) : {}),
90
+ rule: "flow/layout-shift",
91
+ severity: score.value >= 0.25 ? "error" : "warning",
92
+ title: "The page jumps while it loads",
93
+ evidence: `layout shift ${score.value.toFixed(2)} (good is under 0.1) on a slow connection${moved ? `; ${moved}` : ""}`,
94
+ detail: "Content moves after it first appears, so a reader loses their place or taps the wrong thing. Reserve space for images, embeds and late content (width and height, aspect-ratio, min-height), and use metric-matched fallback fonts.",
95
+ fix: "/keyline layout",
96
+ steps: [`Open ${route} at desktop width on a slow connection (${SLOW.latency} ms, ${SLOW.downloadKbps / 1000} Mbps, CPU ×${SLOW.cpu})`, "Watch the page while it loads", moved ? `${cap(moved)} after it first appeared` : "Content moves after it first appeared"],
97
+ });
98
+ } finally {
99
+ await page.close().catch(() => {});
100
+ }
101
+ }
102
+
103
+ const cap = (s) => s[0].toUpperCase() + s.slice(1);
package/smoke/util.mjs ADDED
@@ -0,0 +1,113 @@
1
+ /** Small things every smoke pass shares: a worker pool, a fresh page, steps in words, and finding the source. */
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { walk } from "trykeyline/check/files";
4
+ import { VIEWPORTS, listen } from "../browse/capture.mjs";
5
+
6
+ export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
7
+
8
+ /** Run `fn` over `items`, `n` at a time. */
9
+ export async function pool(items, n, fn) {
10
+ const out = new Array(items.length);
11
+ let next = 0;
12
+ const worker = async () => {
13
+ while (next < items.length) {
14
+ const i = next++;
15
+ out[i] = await fn(items[i], i);
16
+ }
17
+ };
18
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
19
+ return out;
20
+ }
21
+
22
+ /** Open a route in a fresh page and let it settle. Returns the page, its log and the response status. */
23
+ export async function open(context, { base, route, timeout = 30000, idle = 2500 }) {
24
+ const page = await context.newPage();
25
+ const log = listen(page, new URL(base).origin);
26
+ page.on("dialog", (d) => d.dismiss().catch(() => {}));
27
+ let status = null;
28
+ let error = null;
29
+ try {
30
+ const res = await page.goto(new URL(route, base).href, { waitUntil: "load", timeout });
31
+ status = res?.status() ?? null;
32
+ await page.waitForLoadState("networkidle", { timeout: idle }).catch(() => {});
33
+ } catch (err) {
34
+ error = String(err?.message ?? err).split("\n")[0];
35
+ }
36
+ return { page, log, status, error };
37
+ }
38
+
39
+ /** The first step of every reproduction. */
40
+ export function openStep(route, viewport = "desktop") {
41
+ const vp = VIEWPORTS[viewport];
42
+ return `Open ${route} at ${viewport} width (${vp.width}×${vp.height})`;
43
+ }
44
+
45
+ /** How a person would name a control in a step: its words, then what it is. */
46
+ export function describe(c) {
47
+ const what = c.kind === "link" ? "link" : c.role ? c.role : c.tag === "summary" ? "disclosure" : c.kind === "pointer" ? `clickable ${c.tag}` : "button";
48
+ const words = c.text ? `“${c.text}”` : "with no name";
49
+ return `the ${what} ${words}`;
50
+ }
51
+
52
+ /** URL without a bare trailing "#", so `href="#"` doesn't count as moving. */
53
+ export function normalUrl(u) {
54
+ return String(u ?? "").replace(/#$/, "");
55
+ }
56
+
57
+ export function pathOf(url, base) {
58
+ try {
59
+ const u = new URL(url, base);
60
+ return u.origin === new URL(base).origin ? u.pathname + u.search + u.hash : u.href;
61
+ } catch {
62
+ return url;
63
+ }
64
+ }
65
+
66
+ /* ── Pointing at the source ──────────────────────────────────────────────── */
67
+
68
+ const SOURCE = new Set([".html", ".htm", ".js", ".jsx", ".ts", ".tsx", ".vue", ".svelte", ".astro", ".md", ".mdx"]);
69
+
70
+ /**
71
+ * Find where an element is written, by its id, its text or a class from its
72
+ * selector. Cheap and best-effort: the first file and line that mentions it.
73
+ * Files are walked as the detector walks them, the first time one is asked for.
74
+ */
75
+ export function sourceFinder(root) {
76
+ if (!root || !existsSync(root)) return () => null;
77
+ let files = null;
78
+ const load = () => {
79
+ files = [];
80
+ for (const f of walk(root, { accept: SOURCE }).slice(0, 3000)) {
81
+ try {
82
+ files.push({ path: f.rel, lines: readFileSync(f.abs, "utf8").split("\n") });
83
+ } catch {
84
+ // Unreadable: not a source to point at.
85
+ }
86
+ }
87
+ };
88
+ const find = (needle) => {
89
+ for (const f of files) {
90
+ const i = f.lines.findIndex((l) => l.includes(needle));
91
+ if (i >= 0) return { file: f.path, line: i + 1 };
92
+ }
93
+ return null;
94
+ };
95
+ return ({ sel, text } = {}) => {
96
+ if (!files) load();
97
+ const id = sel?.match(/#([A-Za-z][\w-]*)/)?.[1];
98
+ if (id) {
99
+ const hit = find(`id="${id}"`) ?? find(`id='${id}'`) ?? find(`id={"${id}"}`);
100
+ if (hit) return hit;
101
+ }
102
+ if (text && text.length >= 4 && text.length <= 60) {
103
+ const hit = find(`>${text}<`) ?? find(`"${text}"`) ?? find(text);
104
+ if (hit) return hit;
105
+ }
106
+ const cls = sel?.match(/\.([A-Za-z][\w-]{2,})/g)?.map((c) => c.slice(1)).filter((c) => !/^(is|has)-/.test(c));
107
+ for (const c of cls ?? []) {
108
+ const hit = find(`"${c}"`) ?? find(` ${c}"`) ?? find(`"${c} `) ?? find(` ${c} `);
109
+ if (hit) return hit;
110
+ }
111
+ return null;
112
+ };
113
+ }