@dloizides/game-e2e 0.0.0-stage → 1.1.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.mjs ADDED
@@ -0,0 +1,657 @@
1
+ import { devices, expect } from '@playwright/test';
2
+ import { STANDARD_BUTTON, DIALOG_SELECTOR, MENU_FOCUSABLE_SELECTOR } from '@dloizides/game-input';
3
+
4
+ // src/boxes.ts
5
+ var CONTROL_TEXT_CHARS = 12;
6
+ var OPEN_BAND = [-Infinity, Infinity];
7
+ function overlaps(a, b) {
8
+ return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom;
9
+ }
10
+ function findOverlaps(a, b) {
11
+ const hits = [];
12
+ for (const x of a) {
13
+ for (const y of b) {
14
+ if (x !== y && overlaps(x, y)) {
15
+ hits.push([x, y]);
16
+ }
17
+ }
18
+ }
19
+ return hits;
20
+ }
21
+ function findOverlapsWithin(boxes) {
22
+ const hits = [];
23
+ boxes.forEach((x, i) => {
24
+ for (const y of boxes.slice(i + 1)) {
25
+ if (overlaps(x, y)) {
26
+ hits.push([x, y]);
27
+ }
28
+ }
29
+ });
30
+ return hits;
31
+ }
32
+ function canvasBoxToPage(frame, bounds, name, band = OPEN_BAND) {
33
+ const scale = frame.width / frame.logicalWidth;
34
+ const top = Math.max(bounds.y, band[0]);
35
+ const bottom = Math.min(bounds.y + bounds.height, band[1]);
36
+ if (bottom <= top) {
37
+ return null;
38
+ }
39
+ return {
40
+ name,
41
+ left: frame.left + bounds.x * scale,
42
+ top: frame.top + top * scale,
43
+ right: frame.left + (bounds.x + bounds.width) * scale,
44
+ bottom: frame.top + bottom * scale
45
+ };
46
+ }
47
+ function controlName(c) {
48
+ const firstClass = c.className.trim().split(/\s+/)[0] ?? "";
49
+ const id = c.id !== "" ? `#${c.id}` : `.${firstClass}`;
50
+ return `${c.tag.toLowerCase()}${id}:${c.text.trim().slice(0, CONTROL_TEXT_CHARS)}`;
51
+ }
52
+ var PHONE_DEVICE = "Galaxy S5";
53
+ var DESKTOP_DEVICE = "Desktop Chrome";
54
+ var PHONE_SIZE = { width: 360, height: 640 };
55
+ var DESKTOP_SIZE = { width: 1280, height: 720 };
56
+ function deviceDescriptor(name) {
57
+ const found = devices[name];
58
+ if (found === void 0) {
59
+ throw new Error(`Playwright has no device descriptor named "${name}"`);
60
+ }
61
+ const { defaultBrowserType: _browser, ...rest } = found;
62
+ return rest;
63
+ }
64
+ function phone(width = PHONE_SIZE.width, height = PHONE_SIZE.height, deviceScaleFactor) {
65
+ const base = deviceDescriptor(PHONE_DEVICE);
66
+ return { ...base, viewport: { width, height }, screen: { width, height }, deviceScaleFactor: deviceScaleFactor ?? base.deviceScaleFactor };
67
+ }
68
+ function desktop(width = DESKTOP_SIZE.width, height = DESKTOP_SIZE.height, deviceScaleFactor = 1) {
69
+ const base = deviceDescriptor(DESKTOP_DEVICE);
70
+ return { ...base, viewport: { width, height }, screen: { width, height }, deviceScaleFactor };
71
+ }
72
+ function gameProjects(options = {}) {
73
+ const p = options.phone ?? PHONE_SIZE;
74
+ const d = options.desktop ?? DESKTOP_SIZE;
75
+ return [
76
+ { name: options.phoneName ?? "phone", use: phone(p.width, p.height) },
77
+ { name: options.desktopName ?? "desktop", use: desktop(d.width, d.height) }
78
+ ];
79
+ }
80
+ var RELAYOUT_TIMEOUT_MS = 15e3;
81
+ async function armVisibleHeight(page) {
82
+ await page.addInitScript(() => {
83
+ if (!window.visualViewport) {
84
+ return;
85
+ }
86
+ const proto = Object.getPrototypeOf(window.visualViewport);
87
+ Object.defineProperty(proto, "height", {
88
+ configurable: true,
89
+ get: () => window.__gfVisibleHeight ?? window.innerHeight
90
+ });
91
+ });
92
+ }
93
+ async function shrinkVisibleHeight(page, height, options = {}) {
94
+ const key = options.relayoutGlobal ?? null;
95
+ const found = await page.evaluate(({ h, gameKey }) => {
96
+ const w = window;
97
+ let present = true;
98
+ if (gameKey !== null) {
99
+ const game = w[gameKey];
100
+ present = game !== void 0;
101
+ const relaid = {};
102
+ w.__gfRelaid = relaid;
103
+ for (const s of game?.scene.getScenes(true) ?? []) {
104
+ const sceneKey = s.sys.settings.key;
105
+ relaid[sceneKey] = false;
106
+ s.events.once("create", () => {
107
+ relaid[sceneKey] = true;
108
+ });
109
+ }
110
+ }
111
+ w.__gfVisibleHeight = h;
112
+ window.visualViewport?.dispatchEvent(new Event("resize"));
113
+ return present;
114
+ }, { h: height, gameKey: key });
115
+ if (key === null) {
116
+ return;
117
+ }
118
+ if (!found) {
119
+ throw new Error(`shrinkVisibleHeight: window.${key} is not defined, so no scene re-layout can be awaited`);
120
+ }
121
+ await expect.poll(() => page.evaluate(() => {
122
+ const relaid = window.__gfRelaid ?? {};
123
+ return Object.keys(relaid).filter((k) => !relaid[k]);
124
+ }), { message: "scenes still showing the layout of the old height", timeout: options.timeout ?? RELAYOUT_TIMEOUT_MS }).toEqual([]);
125
+ }
126
+ var GAME_SHELL_HEIGHT_VAR = "--gs-vh";
127
+ var DEFAULT_CANVAS_SELECTOR = "canvas";
128
+ var FIT_TIMEOUT_MS = 1e4;
129
+ var CANVAS_TIMEOUT_MS = 15e3;
130
+ var MISSING_BOTTOM = 1e9;
131
+ async function expectFitTo(page, height, options = {}) {
132
+ const cssVar = options.cssVar ?? GAME_SHELL_HEIGHT_VAR;
133
+ await expect.poll(
134
+ () => page.evaluate((v) => getComputedStyle(document.documentElement).getPropertyValue(v).trim(), cssVar),
135
+ { message: `${cssVar} never became ${String(height)}px (game-shell fit not running)`, timeout: options.timeout ?? FIT_TIMEOUT_MS }
136
+ ).toBe(`${String(height)}px`);
137
+ }
138
+ async function expectCanvasHeight(page, height, options = {}) {
139
+ const selector = options.canvasSelector ?? DEFAULT_CANVAS_SELECTOR;
140
+ await expect.poll(
141
+ () => page.evaluate((s) => Math.round(document.querySelector(s)?.getBoundingClientRect().height ?? -1), selector),
142
+ { message: `canvas ${selector} never re-fit to the ${String(height)}px visible height`, timeout: options.timeout ?? CANVAS_TIMEOUT_MS }
143
+ ).toBe(height);
144
+ }
145
+ async function expectCanvasInside(page, height, options = {}) {
146
+ const selector = options.canvasSelector ?? DEFAULT_CANVAS_SELECTOR;
147
+ await expect.poll(
148
+ () => page.evaluate(({ s, missing }) => Math.round(document.querySelector(s)?.getBoundingClientRect().bottom ?? missing), { s: selector, missing: MISSING_BOTTOM }),
149
+ { message: `canvas ${selector} never re-fit inside the ${String(height)}px visible height`, timeout: options.timeout ?? CANVAS_TIMEOUT_MS }
150
+ ).toBeLessThanOrEqual(height);
151
+ }
152
+
153
+ // src/dom-controls.ts
154
+ var CONTROL_SELECTOR = 'button, a[href], [role="button"]';
155
+ async function domControls(page, selector = CONTROL_SELECTOR) {
156
+ const records = await page.evaluate((sel) => Array.from(document.querySelectorAll(sel)).filter((el) => {
157
+ const s = getComputedStyle(el);
158
+ const b = el.getBoundingClientRect();
159
+ return s.display !== "none" && s.visibility !== "hidden" && b.width > 0 && b.height > 0;
160
+ }).map((el) => {
161
+ const b = el.getBoundingClientRect();
162
+ return { tag: el.tagName, id: el.id, className: el.getAttribute("class") ?? "", text: el.textContent ?? "", left: b.left, top: b.top, right: b.right, bottom: b.bottom };
163
+ }), selector);
164
+ return records.map((r) => ({ name: controlName(r), left: r.left, top: r.top, right: r.right, bottom: r.bottom }));
165
+ }
166
+
167
+ // src/pixel-diff-math.ts
168
+ var EXACT = 0;
169
+ var ANTI_ALIAS_TOLERANCE = 48;
170
+ var CHANNELS = 4;
171
+ function at(data, i) {
172
+ return data[i] ?? 0;
173
+ }
174
+ function channelDelta(a, b, i) {
175
+ return Math.max(Math.abs(at(a, i) - at(b, i)), Math.abs(at(a, i + 1) - at(b, i + 1)), Math.abs(at(a, i + 2) - at(b, i + 2)));
176
+ }
177
+ function countDiff(a, b, width, tolerance = EXACT) {
178
+ if (a.length !== b.length) {
179
+ throw new Error(`pixel buffers differ in length: ${String(a.length)} vs ${String(b.length)}`);
180
+ }
181
+ if (width <= 0 || a.length % (width * CHANNELS) !== 0) {
182
+ throw new Error(`pixel buffer of ${String(a.length)} bytes is not whole RGBA rows of width ${String(width)}`);
183
+ }
184
+ const total = a.length / CHANNELS;
185
+ let differing = 0;
186
+ let x0 = width;
187
+ let y0 = total / width;
188
+ let x1 = -1;
189
+ let y1 = -1;
190
+ for (let i = 0; i < a.length; i += CHANNELS) {
191
+ if (channelDelta(a, b, i) <= tolerance) {
192
+ continue;
193
+ }
194
+ differing += 1;
195
+ const p = i / CHANNELS;
196
+ const px = p % width;
197
+ const py = Math.floor(p / width);
198
+ x0 = Math.min(x0, px);
199
+ y0 = Math.min(y0, py);
200
+ x1 = Math.max(x1, px);
201
+ y1 = Math.max(y1, py);
202
+ }
203
+ const bbox = differing > 0 ? `${String(x0)},${String(y0)}-${String(x1)},${String(y1)}` : "none";
204
+ return { differing, total, ratio: total === 0 ? 0 : differing / total, bbox };
205
+ }
206
+
207
+ // src/pixel-diff.ts
208
+ async function diffPngs(factory, a, b, options = {}) {
209
+ const scratch = await factory.newPage();
210
+ try {
211
+ const decoded = await scratch.evaluate(async ({ pa, pb, ra, rb, w, h }) => {
212
+ const load = (src) => new Promise((resolve, reject) => {
213
+ const img = new Image();
214
+ img.onload = () => resolve(img);
215
+ img.onerror = () => reject(new Error("image did not decode"));
216
+ img.src = `data:image/png;base64,${src}`;
217
+ });
218
+ const [ia, ib] = await Promise.all([load(pa), load(pb)]);
219
+ const unscaled = w === null && h === null && ra === null && rb === null;
220
+ if (unscaled && (ia.naturalWidth !== ib.naturalWidth || ia.naturalHeight !== ib.naturalHeight)) {
221
+ throw new Error(`image sizes differ: ${String(ia.naturalWidth)}x${String(ia.naturalHeight)} vs ${String(ib.naturalWidth)}x${String(ib.naturalHeight)}`);
222
+ }
223
+ const width = Math.max(1, Math.round(w ?? ra?.w ?? ia.naturalWidth));
224
+ const height = Math.max(1, Math.round(h ?? ra?.h ?? ia.naturalHeight));
225
+ const chunk = 32768;
226
+ const toBase64 = (img, r) => {
227
+ const c = document.createElement("canvas");
228
+ c.width = width;
229
+ c.height = height;
230
+ const g = c.getContext("2d");
231
+ if (!g) {
232
+ throw new Error("no 2d context");
233
+ }
234
+ if (r) {
235
+ g.drawImage(img, r.x, r.y, r.w, r.h, 0, 0, width, height);
236
+ } else {
237
+ g.drawImage(img, 0, 0, width, height);
238
+ }
239
+ const data = g.getImageData(0, 0, width, height).data;
240
+ let s = "";
241
+ for (let i = 0; i < data.length; i += chunk) {
242
+ s += String.fromCharCode(...data.subarray(i, i + chunk));
243
+ }
244
+ return btoa(s);
245
+ };
246
+ return { width, a: toBase64(ia, ra), b: toBase64(ib, rb) };
247
+ }, {
248
+ pa: a.toString("base64"),
249
+ pb: b.toString("base64"),
250
+ ra: options.regionA ?? null,
251
+ rb: options.regionB ?? null,
252
+ w: options.width ?? null,
253
+ h: options.height ?? null
254
+ });
255
+ return countDiff(Buffer.from(decoded.a, "base64"), Buffer.from(decoded.b, "base64"), decoded.width, options.tolerance ?? EXACT);
256
+ } finally {
257
+ await scratch.close();
258
+ }
259
+ }
260
+ async function regionDiff(factory, a, b, options = {}) {
261
+ return diffPngs(factory, a.png, b.png, { ...options, regionA: a.region, regionB: b.region });
262
+ }
263
+
264
+ // src/touch-report.ts
265
+ var MIN_TARGET_PX = 44;
266
+ var MAX_REPORTED = 12;
267
+ function renderFindings(findings, alsoIn, alsoLabel) {
268
+ if (findings.length === 0) {
269
+ return "none";
270
+ }
271
+ const shown = findings.slice(0, MAX_REPORTED).map((f) => `${f.selector} ${String(f.width)}x${String(f.height)} via=${f.reason} name="${f.name}"` + (alsoIn.has(f.idx) ? ` [ALSO ${alsoLabel}]` : ""));
272
+ const rest = findings.length - shown.length;
273
+ return shown.join("; ") + (rest > 0 ? ` (+${String(rest)} more)` : "");
274
+ }
275
+ function renderRouteAudit({ route, audit }, minPx) {
276
+ if (audit.total === 0) {
277
+ return `
278
+ ${route}: PROBE FOUND NO INTERACTIVE TARGETS - the probe is broken, or the route loaded blank. NOT a clean route. [funnel: raw=${String(audit.probe.raw)} -> afterWrapper=${String(audit.probe.afterWrapper)} -> outermost=${String(audit.probe.kept)}]`;
279
+ }
280
+ const undersizedIdx = new Set(audit.undersized.map((f) => f.idx));
281
+ const unlabelledIdx = new Set(audit.unlabelled.map((f) => f.idx));
282
+ const both = audit.unlabelled.filter((f) => undersizedIdx.has(f.idx)).length;
283
+ return `
284
+ ${route}: ${String(audit.undersized.length)} of ${String(audit.total)} under ${String(minPx)}px; ${String(audit.unlabelled.length)} of ${String(audit.total)} with NO role and NO accessible name; ${String(both)} BOTH
285
+ UNDERSIZED (<${String(minPx)}px): ${renderFindings(audit.undersized, unlabelledIdx, "unlabelled")}
286
+ UNLABELLED (no role, no name): ${renderFindings(audit.unlabelled, undersizedIdx, "undersized")}`;
287
+ }
288
+ function routeProblems({ audit }) {
289
+ if (audit.total === 0) {
290
+ return 1;
291
+ }
292
+ return audit.undersized.length + audit.unlabelled.length;
293
+ }
294
+ function summariseTouchTargets(readings, portal, minPx = MIN_TARGET_PX) {
295
+ if (readings.length === 0) {
296
+ return { problems: 1, message: `${portal}: no routes were measured at all` };
297
+ }
298
+ const sum = (pick) => readings.reduce((n, r) => n + pick(r), 0);
299
+ const blank = readings.filter((r) => r.audit.total === 0).length;
300
+ const message = `${portal}: ${String(readings.length)} route(s), ${String(sum((r) => r.audit.total))} targets; ${String(sum((r) => r.audit.undersized.length))} under ${String(minPx)}px; ${String(sum((r) => r.audit.unlabelled.length))} with NO role and NO accessible name; ${String(blank)} route(s) read ZERO targets` + readings.map((r) => renderRouteAudit(r, minPx)).join("");
301
+ return { problems: sum(routeProblems), message };
302
+ }
303
+ async function auditTouchTargets(page, minPx = MIN_TARGET_PX) {
304
+ return page.evaluate((min) => {
305
+ const ROLE_SEL = 'a[href], button, input:not([type="hidden"]), select, textarea, summary, [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"], [role="menuitem"], [role="menuitemcheckbox"], [role="option"], [role="slider"]';
306
+ const unreachable = (el, cs) => {
307
+ if (el.closest('[aria-hidden="true"]')) {
308
+ return true;
309
+ }
310
+ if (el.closest("[inert]")) {
311
+ return true;
312
+ }
313
+ if (cs.pointerEvents === "none") {
314
+ return true;
315
+ }
316
+ if (el.getAttribute("aria-disabled") === "true") {
317
+ return true;
318
+ }
319
+ return el.disabled === true;
320
+ };
321
+ const why = (el, cs) => {
322
+ if (el instanceof SVGElement && !el.hasAttribute("role")) {
323
+ return null;
324
+ }
325
+ if (el.matches(ROLE_SEL)) {
326
+ return "role";
327
+ }
328
+ if (typeof el.onclick === "function") {
329
+ return "handler";
330
+ }
331
+ if (el.getAttribute("data-focusable") === "true") {
332
+ return "rnw-focusable";
333
+ }
334
+ const ti = el.getAttribute("tabindex");
335
+ if (ti !== null && Number(ti) >= 0) {
336
+ return "tabindex";
337
+ }
338
+ if (cs.cursor === "pointer") {
339
+ const parent = el.parentElement;
340
+ if (!parent || getComputedStyle(parent).cursor !== "pointer") {
341
+ return "cursor-origin";
342
+ }
343
+ }
344
+ return null;
345
+ };
346
+ const raw = [];
347
+ for (const el of Array.from(document.querySelectorAll("*"))) {
348
+ const cs = getComputedStyle(el);
349
+ if (unreachable(el, cs)) {
350
+ continue;
351
+ }
352
+ const reason = why(el, cs);
353
+ if (reason !== null) {
354
+ raw.push({ el, reason });
355
+ }
356
+ }
357
+ const members = new Set(raw.map((c) => c.el));
358
+ const afterWrapper = raw.filter(({ el, reason }) => reason === "role" || !Array.from(el.querySelectorAll(ROLE_SEL)).some((d) => members.has(d)));
359
+ const survivors = new Set(afterWrapper.map((c) => c.el));
360
+ const kept = afterWrapper.filter(({ el }) => {
361
+ for (let p = el.parentElement; p; p = p.parentElement) {
362
+ if (survivors.has(p)) {
363
+ return false;
364
+ }
365
+ }
366
+ return true;
367
+ });
368
+ const describe = (el) => {
369
+ const id = el.getAttribute("data-testid") ?? el.getAttribute("id") ?? "";
370
+ return `${el.tagName.toLowerCase()}${id ? `[${id}]` : ""}`.slice(0, 60);
371
+ };
372
+ const accName = (el) => {
373
+ const aria = el.getAttribute("aria-label");
374
+ if (aria && aria.trim()) {
375
+ return aria.trim();
376
+ }
377
+ const by = el.getAttribute("aria-labelledby");
378
+ if (by) {
379
+ const t = by.split(/\s+/).map((i) => document.getElementById(i)?.textContent ?? "").join(" ").trim();
380
+ if (t) {
381
+ return t;
382
+ }
383
+ }
384
+ const attr = el.getAttribute("title") ?? el.getAttribute("alt") ?? el.value ?? "";
385
+ if (attr && attr.trim()) {
386
+ return attr.trim();
387
+ }
388
+ return (el.textContent ?? "").trim();
389
+ };
390
+ const undersized = [];
391
+ const unlabelled = [];
392
+ let total = 0;
393
+ for (const { el, reason } of kept) {
394
+ const r = el.getBoundingClientRect();
395
+ if (r.width <= 0 || r.height <= 0 || getComputedStyle(el).visibility === "hidden") {
396
+ continue;
397
+ }
398
+ const f = { idx: total, selector: describe(el), width: Math.round(r.width), height: Math.round(r.height), reason, name: accName(el).slice(0, 40) };
399
+ total += 1;
400
+ if (r.width < min || r.height < min) {
401
+ undersized.push(f);
402
+ }
403
+ const hasRole = el.matches(ROLE_SEL) || (el.getAttribute("role") ?? "") !== "";
404
+ if (!hasRole && !f.name) {
405
+ unlabelled.push(f);
406
+ }
407
+ }
408
+ return { total, undersized, unlabelled, probe: { raw: raw.length, afterWrapper: afterWrapper.length, kept: kept.length } };
409
+ }, minPx);
410
+ }
411
+ async function auditRoute(page, route, minPx = MIN_TARGET_PX) {
412
+ return { route, audit: await auditTouchTargets(page, minPx) };
413
+ }
414
+ function expectTouchTargetsAcrossRoutes(readings, portal, minPx = MIN_TARGET_PX) {
415
+ const summary = summariseTouchTargets(readings, portal, minPx);
416
+ expect(summary.problems, summary.message).toBe(0);
417
+ }
418
+ async function expectTouchTargets(page, where, minPx = MIN_TARGET_PX) {
419
+ const reading = await auditRoute(page, where, minPx);
420
+ expectTouchTargetsAcrossRoutes([reading], where, minPx);
421
+ return reading.audit;
422
+ }
423
+
424
+ // src/overflow-report.ts
425
+ function toOverflowReading(m) {
426
+ const visual = Math.ceil(m.visualViewportWidth);
427
+ return { ...m, overflowPx: m.scrollWidth - Math.min(visual, m.clientWidth), layoutViewportDrift: m.innerWidth - visual };
428
+ }
429
+ function renderOverflow({ route, reading: r }) {
430
+ const head = r.overflowPx > 0 ? `OVERFLOWS by ${String(r.overflowPx)}px` : "ok";
431
+ return `
432
+ ${route}: ${head} - scrollWidth=${String(r.scrollWidth)} vs visualViewport=${String(Math.ceil(r.visualViewportWidth))} (innerWidth=${String(r.innerWidth)}, clientWidth=${String(r.clientWidth)}, layout-viewport drift=${String(r.layoutViewportDrift)}px)`;
433
+ }
434
+ function summariseOverflow(readings, portal) {
435
+ if (readings.length === 0) {
436
+ return { problems: 1, message: `${portal}: no routes were measured at all` };
437
+ }
438
+ const bad = readings.filter((r) => r.reading.overflowPx > 0);
439
+ const worst = readings.reduce((n, r) => Math.max(n, r.reading.overflowPx), 0);
440
+ const message = `${portal}: ${String(readings.length)} reading(s), ${String(bad.length)} scroll horizontally; worst overflow ${String(worst)}px` + readings.map(renderOverflow).join("");
441
+ return { problems: bad.length, message };
442
+ }
443
+ async function readHorizontalOverflow(page) {
444
+ const metrics = await page.evaluate(() => ({
445
+ scrollWidth: document.documentElement.scrollWidth,
446
+ visualViewportWidth: window.visualViewport ? window.visualViewport.width : window.innerWidth,
447
+ innerWidth: window.innerWidth,
448
+ clientWidth: document.documentElement.clientWidth
449
+ }));
450
+ return toOverflowReading(metrics);
451
+ }
452
+ async function measureHorizontalOverflow(page, route) {
453
+ return { route, reading: await readHorizontalOverflow(page) };
454
+ }
455
+ async function horizontalOverflowPx(page) {
456
+ return (await readHorizontalOverflow(page)).overflowPx;
457
+ }
458
+ function expectNoHorizontalOverflowAcrossRoutes(readings, portal) {
459
+ const summary = summariseOverflow(readings, portal);
460
+ expect(summary.problems, summary.message).toBe(0);
461
+ }
462
+ async function expectNoHorizontalOverflow(page, where) {
463
+ const r = await measureHorizontalOverflow(page, where);
464
+ expectNoHorizontalOverflowAcrossRoutes([r], where);
465
+ return r.reading;
466
+ }
467
+
468
+ // src/gamepad-stub.ts
469
+ var STUB_FRAMES = 3;
470
+ var STANDARD_BUTTON_COUNT = 17;
471
+ var AXIS_COUNT = 4;
472
+ async function stubGamepad(page) {
473
+ await page.addInitScript(([buttons, axes]) => {
474
+ const pad = { id: "nav-walk-stub", index: 0, connected: true, mapping: "standard", timestamp: 0, axes: new Array(axes).fill(0), buttons: Array.from({ length: buttons }, () => ({ pressed: false, touched: false, value: 0 })) };
475
+ Object.assign(window, { __navPad: pad });
476
+ Object.defineProperty(navigator, "getGamepads", { configurable: true, value: () => [pad, null, null, null] });
477
+ window.addEventListener("load", () => window.dispatchEvent(Object.assign(new Event("gamepadconnected"), { gamepad: pad })));
478
+ }, [STANDARD_BUTTON_COUNT, AXIS_COUNT]);
479
+ return {
480
+ press: (button) => page.evaluate(async ([b, n]) => {
481
+ const pad = window.__navPad;
482
+ const frames = (k) => new Promise((resolve) => {
483
+ const step = (left) => {
484
+ if (left === 0) {
485
+ resolve();
486
+ return;
487
+ }
488
+ requestAnimationFrame(() => step(left - 1));
489
+ };
490
+ step(k);
491
+ });
492
+ const target = pad.buttons[b] ?? { pressed: false, value: 0 };
493
+ target.pressed = true;
494
+ target.value = 1;
495
+ await frames(n);
496
+ target.pressed = false;
497
+ target.value = 0;
498
+ await frames(n);
499
+ }, [button, STUB_FRAMES]),
500
+ hold: (axis, value) => page.evaluate(([a, v]) => {
501
+ window.__navPad.axes[a] = v;
502
+ }, [axis, value])
503
+ };
504
+ }
505
+
506
+ // src/menu-walk-page.ts
507
+ function scanScreen(a) {
508
+ const shown = (el) => el.getClientRects().length > 0 && el.closest('[hidden], [inert], [aria-hidden="true"]') === null && getComputedStyle(el).visibility !== "hidden";
509
+ const dialogs = Array.from(document.querySelectorAll(a.dialogSel)).filter(shown);
510
+ const modal = dialogs.filter((d) => d.getAttribute("aria-modal") === "true");
511
+ const root = (modal.length > 0 ? modal : dialogs).pop() ?? document.body;
512
+ document.querySelectorAll(`[${a.attr}], [${a.rootAttr}]`).forEach((el) => {
513
+ el.removeAttribute(a.attr);
514
+ el.removeAttribute(a.rootAttr);
515
+ });
516
+ root.setAttribute(a.rootAttr, "");
517
+ const list = Array.from(root.querySelectorAll(`${a.focusSel}, [onclick]`)).filter((el) => shown(el) && el.disabled !== true && !a.exempt.some((s) => el.matches(s)));
518
+ list.forEach((el, i) => el.setAttribute(a.attr, String(i)));
519
+ const nonText = ["range", "checkbox", "radio", "button", "submit", "reset", "color", "file", "image"];
520
+ const isText = (el) => el.tagName === "TEXTAREA" || el instanceof HTMLInputElement && !nonText.includes(el.type);
521
+ const isSlider = (el) => el instanceof HTMLInputElement && el.type === "range" || el.getAttribute("role") === "slider";
522
+ const active2 = document.activeElement;
523
+ return {
524
+ identities: list.map((el) => ({ tag: el.tagName, id: el.id, className: el.getAttribute("class") ?? "", text: el.textContent ?? "" })),
525
+ isDialog: root !== document.body,
526
+ focusedInRoot: active2 instanceof HTMLElement && active2 !== root && root.contains(active2),
527
+ sliders: list.flatMap((el, i) => isSlider(el) ? [i] : []),
528
+ textFields: list.flatMap((el, i) => isText(el) ? [i] : [])
529
+ };
530
+ }
531
+ function activeWalkId(attr) {
532
+ const v = document.activeElement?.getAttribute(attr) ?? null;
533
+ return v === null ? null : Number(v);
534
+ }
535
+ function focusWalkId([attr, id]) {
536
+ document.querySelector(`[${attr}="${id}"]`)?.focus();
537
+ }
538
+ function controlValue([attr, id]) {
539
+ const el = document.querySelector(`[${attr}="${id}"]`);
540
+ return el instanceof HTMLInputElement ? el.value : el?.getAttribute("aria-valuenow") ?? "";
541
+ }
542
+ function rootOpen(rootAttr) {
543
+ const r = document.querySelector(`[${rootAttr}]`);
544
+ return r !== null && r.getClientRects().length > 0 && r.closest("[hidden]") === null;
545
+ }
546
+
547
+ // src/menu-walk-report.ts
548
+ var WALK_INPUTS = { keys: "keys", pad: "pad" };
549
+ var walkFailed = (r) => r.unreached.length > 0 || r.problems.length > 0;
550
+ function renderWalk(results) {
551
+ return results.map((r) => [
552
+ `${r.screen} [${r.via}] reached ${r.reached}/${r.total}`,
553
+ ...r.unreached.map((n) => ` unreached: ${n}`),
554
+ ...r.problems.map((p) => ` problem: ${p}`),
555
+ ...r.exempt.map((e) => ` exempt: ${e}`)
556
+ ].join("\n")).join("\n");
557
+ }
558
+
559
+ // src/menu-walk.ts
560
+ var WALK_ATTR = "data-walk-id";
561
+ var ROOT_ATTR = "data-walk-root";
562
+ var PRESSES_PER_CONTROL = 4;
563
+ var DIRS = ["up", "down", "left", "right"];
564
+ var KEYS = { up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight" };
565
+ var PAD_BUTTONS = { up: STANDARD_BUTTON.dpadUp, down: STANDARD_BUTTON.dpadDown, left: STANDARD_BUTTON.dpadLeft, right: STANDARD_BUTTON.dpadRight };
566
+ function driverFor(page, via, pad) {
567
+ if (via === WALK_INPUTS.pad && pad !== null) {
568
+ return { dir: (d) => pad.press(PAD_BUTTONS[d]), back: () => pad.press(STANDARD_BUTTON.east) };
569
+ }
570
+ return { dir: (d) => page.keyboard.press(KEYS[d]), back: () => page.keyboard.press("Escape") };
571
+ }
572
+ var active = (page) => page.evaluate(activeWalkId, WALK_ATTR);
573
+ var focusId = (page, id) => page.evaluate(focusWalkId, [WALK_ATTR, id]);
574
+ async function bfs(page, driver, total) {
575
+ const reached = /* @__PURE__ */ new Set();
576
+ let start = await active(page);
577
+ if (start === null) {
578
+ await driver.dir("down");
579
+ start = await active(page);
580
+ }
581
+ if (start === null) {
582
+ return reached;
583
+ }
584
+ reached.add(start);
585
+ const queue = [start];
586
+ let presses = 0;
587
+ while (queue.length > 0 && presses < PRESSES_PER_CONTROL * total) {
588
+ const from = queue.shift();
589
+ for (const d of DIRS) {
590
+ await focusId(page, from);
591
+ await driver.dir(d);
592
+ presses += 1;
593
+ const at2 = await active(page);
594
+ if (at2 !== null && !reached.has(at2)) {
595
+ reached.add(at2);
596
+ queue.push(at2);
597
+ }
598
+ }
599
+ }
600
+ return reached;
601
+ }
602
+ async function sliderProblems(page, driver, scan, reached, names) {
603
+ const problems = [];
604
+ for (const i of scan.sliders.filter((s) => reached.has(s))) {
605
+ await focusId(page, i);
606
+ const before = await page.evaluate(controlValue, [WALK_ATTR, i]);
607
+ await driver.dir("right");
608
+ const right = await page.evaluate(controlValue, [WALK_ATTR, i]);
609
+ await driver.dir("left");
610
+ const left = await page.evaluate(controlValue, [WALK_ATTR, i]);
611
+ if (right === before && left === before) {
612
+ problems.push(`slider ${names[i]} does not move on Left/Right`);
613
+ }
614
+ }
615
+ return problems;
616
+ }
617
+ async function walkScreen(page, screen, via, pad) {
618
+ const driver = driverFor(page, via, pad);
619
+ const exempt = screen.exempt ?? [];
620
+ await screen.open(page);
621
+ const scan = await page.evaluate(scanScreen, { focusSel: MENU_FOCUSABLE_SELECTOR, dialogSel: DIALOG_SELECTOR, exempt: exempt.map((e) => e.selector), attr: WALK_ATTR, rootAttr: ROOT_ATTR });
622
+ const names = scan.identities.map(controlName);
623
+ const reached = await bfs(page, driver, names.length);
624
+ const problems = scan.isDialog && !scan.focusedInRoot ? ["focus is not inside the dialog when it opens"] : [];
625
+ problems.push(...await sliderProblems(page, driver, scan, reached, names));
626
+ const closer = [...reached].find((i) => !scan.textFields.includes(i) && !scan.sliders.includes(i));
627
+ if (scan.isDialog && closer !== void 0) {
628
+ await focusId(page, closer);
629
+ await driver.back();
630
+ if (await page.evaluate(rootOpen, ROOT_ATTR)) {
631
+ problems.push(`${via === WALK_INPUTS.pad ? "B" : "Escape"} does not close the dialog`);
632
+ }
633
+ }
634
+ return { screen: screen.name, via, reached: reached.size, total: names.length, unreached: names.filter((_, i) => !reached.has(i)), problems, exempt: exempt.map((e) => `${e.selector}: ${e.reason}`) };
635
+ }
636
+ async function walkMenus(page, screens, options = {}) {
637
+ const via = options.via ?? [WALK_INPUTS.keys, WALK_INPUTS.pad];
638
+ const pad = via.includes(WALK_INPUTS.pad) ? await stubGamepad(page) : null;
639
+ const results = [];
640
+ for (const screen of screens) {
641
+ for (const v of via) {
642
+ results.push(await walkScreen(page, screen, v, pad));
643
+ }
644
+ }
645
+ return results;
646
+ }
647
+ async function expectMenuWalkable(page, screens, options = {}) {
648
+ const results = await walkMenus(page, screens, options);
649
+ if (results.some(walkFailed)) {
650
+ throw new Error(`Menus not walkable by arrow keys / pad:
651
+ ${renderWalk(results)}`);
652
+ }
653
+ }
654
+
655
+ export { ANTI_ALIAS_TOLERANCE, CANVAS_TIMEOUT_MS, CONTROL_SELECTOR, DEFAULT_CANVAS_SELECTOR, DESKTOP_DEVICE, DESKTOP_SIZE, EXACT, FIT_TIMEOUT_MS, GAME_SHELL_HEIGHT_VAR, MAX_REPORTED, MIN_TARGET_PX, PHONE_DEVICE, PHONE_SIZE, RELAYOUT_TIMEOUT_MS, STUB_FRAMES, WALK_INPUTS, armVisibleHeight, auditRoute, auditTouchTargets, canvasBoxToPage, controlName, countDiff, desktop, deviceDescriptor, diffPngs, domControls, expectCanvasHeight, expectCanvasInside, expectFitTo, expectMenuWalkable, expectNoHorizontalOverflow, expectNoHorizontalOverflowAcrossRoutes, expectTouchTargets, expectTouchTargetsAcrossRoutes, findOverlaps, findOverlapsWithin, gameProjects, horizontalOverflowPx, measureHorizontalOverflow, overlaps, phone, readHorizontalOverflow, regionDiff, renderFindings, renderOverflow, renderRouteAudit, renderWalk, routeProblems, shrinkVisibleHeight, stubGamepad, summariseOverflow, summariseTouchTargets, toOverflowReading, walkFailed, walkMenus };
656
+ //# sourceMappingURL=index.mjs.map
657
+ //# sourceMappingURL=index.mjs.map