responsivelint 0.1.0 → 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/llms.txt CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  ## Run a check
14
14
 
15
- - Use Node.js 20 or newer. Install Chromium with `npx playwright install chromium` if the command cannot find it. For ResponsiveLint 0.1.0 run via `npx` alone, use `npx --yes --package=playwright@1.59.1 playwright install chromium` to match its browser version.
15
+ - Use Node.js 20 or newer. Install Chromium with `npx playwright install chromium` if the command cannot find it. For ResponsiveLint 0.2.0 run via `npx` alone, use `npx --yes --package=playwright@1.59.1 playwright install chromium` to match its browser version.
16
16
  - Start the site's dev server and run `npx responsivelint http://localhost:5173 --json report.json`.
17
17
  - A built site folder also works, for example `npx responsivelint ./dist --html report.html`.
18
18
  - Normal mode checks 320 to 1920 px in 48 px steps and up to eight extra states. Aggressive mode uses 24 px steps and up to 20 extra states. Quick mode checks four widths and the starting state only. Set `--step 1` to check every whole-pixel width in the selected range.
@@ -20,12 +20,19 @@
20
20
  - Exit code `0` means no findings met the failure threshold. Code `1` means the run found errors, or warnings under `--strict`. Code `2` means the command failed or received an unknown option.
21
21
  - For an in-page check, load `dist/responsivelint.js` from the npm package. The README has the script tag, `data-ui`, `data-sweep`, `data-anywhere` and `window.ResponsiveLint` examples.
22
22
  - From Node, use `import {check} from 'responsivelint'; const report = await check(url)`.
23
+ - For slow apps, `--click-wait 2000` waits longer after each click and `--pace 1000` keeps page loads and clicks at least a second apart. `--wait` pauses after load and `--click-timeout` sets how long to wait for a control. The script tag takes `data-wait`, `data-click-wait`, `data-click-timeout` and `data-pace`.
24
+
25
+ ## Replay a finding
26
+
27
+ - `npx responsivelint <url> --replay` checks, then steps through the findings in a visible browser. `npx responsivelint replay report.json [base-url]` replays a saved report.
28
+ - In the page, `data-ui="replay"` (with `data-report="report.json"` for a command-line report) or `await ResponsiveLint.replay(findings)` shows each finding in a frame at its width.
29
+ - Each step loads the page fresh at `replay.startWidth`, sets `replay.storage`, repeats the clicks in `replay.actions`, sets `replay.width` and outlines the element with a label.
23
30
 
24
31
  ## Read and fix findings
25
32
 
26
- The report includes `widths`, `states` and `findings`. Each finding gives `rule`, `severity`, `confidence`, `elements` (selector in `key` and visible `text`), `bands` in pixels, `states`, `measured`, `why`, `tries` (the usual causes and fixes, most likely first), `skill` (the fix skill to load: `name`, `file`, `url`) and `guide`. Sweep findings may include nearby measurements in `expected`.
33
+ The report includes `widths`, `states` (each with the clicks that reach it in `actions`), `timing` and `findings`. Each finding gives `rule`, `severity`, `confidence`, `elements` (selector in `key` and visible `text`), `bands` in pixels, `states`, `measured`, `why`, `tries` (the usual causes and fixes, most likely first), `skill` (the fix skill to load: `name`, `file`, `url`), `guide` and `replay` (`url`, `route`, `storage`, `startWidth`, `width`, `height`, `state`, `actions`). Sweep findings may include nearby measurements in `expected`.
27
34
 
28
- Open the page at a width inside the finding's band. Repeat the click named in the state and inspect the named element. Load the skill named in `skill`, check the causes in `tries` in order, fix the layout and run the check again. For an intentional layout, use `data-rl-ignore="rule-name"`.
35
+ Reproduce it from `replay`: load `url` at `startWidth`, apply `storage`, click each selector in `actions`, set the width to `width` and inspect the named element. Load the skill named in `skill`, check the causes in `tries` in order, fix the layout and run the check again. For an intentional layout, use `data-rl-ignore="rule-name"`.
29
36
 
30
37
  - [text-overlap](https://github.com/prajwalsouza/ResponsiveLint/blob/main/docs/rules/text-overlap.md) finds visible text drawn over other text.
31
38
  - [squashed-text](https://github.com/prajwalsouza/ResponsiveLint/blob/main/docs/rules/squashed-text.md) finds text with about one word per line.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "responsivelint",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Layout linter that checks every width and every state of a web UI against itself: overlapping text, overflow, squashed labels, hidden controls.",
5
5
  "author": "Prajwal DSouza",
6
6
  "license": "MIT",
@@ -2,8 +2,14 @@
2
2
  // <script src="responsivelint.js"></script> console findings, re-checked as the page changes
3
3
  // <script src="responsivelint.js" data-ui></script> also outline problems on the page
4
4
  // <script src="responsivelint.js" data-sweep></script> also sweep widths in a hidden copy of the page
5
+ // <script src="responsivelint.js" data-ui="replay"></script> step through the findings, each from a fresh load
6
+ // data-report="report.json" replay a command-line report instead of the live findings
7
+ // data-wait, data-click-wait, data-click-timeout, data-pace timing in milliseconds, as on the command line
5
8
  import {checkNow, detectEnvironment} from '../core/measure.js';
6
9
  import {analyze, RULES} from '../core/analyze.js';
10
+ import {highlight} from '../core/highlight.js';
11
+ import {createBar} from '../core/bar.js';
12
+ import {recipe, START_WIDTH} from '../core/recipe.js';
7
13
 
8
14
  const FRAME = 'responsivelint-frame';
9
15
  const script = document.currentScript;
@@ -16,15 +22,88 @@ if (window.name === FRAME) {
16
22
  const local = /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost|.+\.test)$/.test(location.hostname) || location.protocol === 'file:';
17
23
  const api = window.ResponsiveLint = createApi();
18
24
  if (local || 'anywhere' in opts) {
19
- const start = () => {
25
+ const start = async () => {
20
26
  api.check();
21
- if ('ui' in opts) api.ui(true);
22
- if ('sweep' in opts) api.sweep();
27
+ const replaying = opts.ui === 'replay';
28
+ if ('ui' in opts && !replaying) api.ui(true);
29
+ if ('sweep' in opts && (!replaying || !opts.report)) await api.sweep();
30
+ if (replaying) api.replay();
23
31
  };
24
32
  if (document.readyState === 'complete') setTimeout(start, 50); else addEventListener('load', () => setTimeout(start, 50));
25
33
  }
26
34
  }
27
35
 
36
+ const TIMING = {wait: 300, clickWait: 300, clickTimeout: 3000, pace: 0};
37
+ const NETWORK_CAP = 5000, NETWORK_IDLE = 250;
38
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
39
+ const frames = (win, n = 2) => new Promise((r) => { const step = (k) => (k ? win.requestAnimationFrame(() => step(k - 1)) : r()); step(n); });
40
+
41
+ /** Timing from the script tag's data-wait, data-click-wait, data-click-timeout and data-pace, then from o. */
42
+ function timing(o = {}) {
43
+ const t = {...TIMING};
44
+ for (const k of Object.keys(TIMING)) {
45
+ const v = o[k] ?? opts[k];
46
+ if (v != null && v !== '' && Number.isFinite(+v) && +v >= 0) t[k] = +v;
47
+ }
48
+ return t;
49
+ }
50
+
51
+ /** Waits for fonts, two frames and finite animations, as the command line does, then extra ms. */
52
+ async function settle(win, extra = 0) {
53
+ try {
54
+ await win.document.fonts?.ready;
55
+ await frames(win);
56
+ const anims = (win.document.getAnimations?.() || []).filter((a) => a.playState === 'running' && a.effect?.getTiming?.().iterations !== Infinity);
57
+ await Promise.race([Promise.all(anims.map((a) => a.finished.catch(() => {}))), sleep(600)]);
58
+ } catch {}
59
+ if (extra) await sleep(extra);
60
+ }
61
+
62
+ /**
63
+ * Counts the frame's fetch and XMLHttpRequest calls, so a step can wait until the network is quiet after a click,
64
+ * and refuses writes (POST, PUT, PATCH, DELETE), as the command line does.
65
+ */
66
+ function trackRequests(win) {
67
+ let open = 0, last = 0;
68
+ const bump = (d) => { open = Math.max(0, open + d); last = Date.now(); };
69
+ const read = (m) => String(m || 'GET').toUpperCase();
70
+ const safe = (m) => ['GET', 'HEAD', 'OPTIONS'].includes(read(m));
71
+ try {
72
+ const f = win.fetch;
73
+ if (f) win.fetch = function (input, init) {
74
+ const method = init?.method || (input && typeof input === 'object' && input.method);
75
+ if (!safe(method)) return Promise.reject(new TypeError('ResponsiveLint replay blocks ' + read(method) + ' requests'));
76
+ bump(1);
77
+ return f.call(this, input, init).finally(() => bump(-1));
78
+ };
79
+ const X = win.XMLHttpRequest?.prototype;
80
+ if (X) {
81
+ const xopen = X.open, send = X.send;
82
+ X.open = function (method, ...rest) { this.__rlMethod = method; return xopen.call(this, method, ...rest); };
83
+ X.send = function (...a) {
84
+ if (!safe(this.__rlMethod)) { this.abort(); return; }
85
+ bump(1); this.addEventListener('loadend', () => bump(-1), {once: true});
86
+ return send.apply(this, a);
87
+ };
88
+ }
89
+ } catch {}
90
+ return async () => {
91
+ const end = Date.now() + NETWORK_CAP;
92
+ while (Date.now() < end) { if (!open && Date.now() - last >= NETWORK_IDLE) return; await sleep(40); }
93
+ };
94
+ }
95
+
96
+ /** Waits up to timeout ms for a visible element that matches the selector. */
97
+ async function waitFor(doc, selector, timeout) {
98
+ const end = Date.now() + timeout;
99
+ for (;;) {
100
+ const el = doc.querySelector(selector);
101
+ if (el) { const r = el.getBoundingClientRect(); if (r.width && r.height && doc.defaultView.getComputedStyle(el).visibility !== 'hidden') return el; }
102
+ if (Date.now() > end) throw new Error(`no visible ${selector} after ${timeout} ms`);
103
+ await sleep(50);
104
+ }
105
+ }
106
+
28
107
  function createApi() {
29
108
  const logged = new Set();
30
109
  const listeners = new Set();
@@ -76,6 +155,7 @@ function createApi() {
76
155
  await new Promise((r, x) => { frame.onload = r; setTimeout(() => x(new Error('timeout')), 20000); });
77
156
  const win = frame.contentWindow;
78
157
  if (!win.__ResponsiveLintFrame) throw new Error('the page does not load this script in a frame');
158
+ await settle(win, timing().wait);
79
159
  const snaps = [];
80
160
  for (let w = from; w <= to; w += step) {
81
161
  frame.style.width = w + 'px';
@@ -113,8 +193,10 @@ function createApi() {
113
193
  }
114
194
  const panel = document.createElement('div');
115
195
  panel.style.cssText = 'position:fixed;right:12px;bottom:12px;max-width:360px;max-height:50vh;overflow:auto;pointer-events:auto;background:hsla(0,0%,100%,.97);color:#1d1f24;border-radius:10px;box-shadow:0 6px 24px hsla(0,0%,0%,.18);font:12px/1.45 system-ui,sans-serif;padding:10px 12px';
116
- panel.innerHTML = `<div style="display:flex;justify-content:space-between;gap:8px;margin-bottom:6px"><b>ResponsiveLint · ${all.length} finding${all.length === 1 ? '' : 's'}</b><button type="button" style="border:0;background:none;cursor:pointer;font:inherit">×</button></div>`;
117
- panel.querySelector('button').onclick = () => api.ui(false);
196
+ panel.innerHTML = `<div style="display:flex;align-items:center;gap:8px;margin-bottom:6px"><b style="margin-right:auto">ResponsiveLint · ${all.length} finding${all.length === 1 ? '' : 's'}</b>${all.length ? '<button type="button" data-act="replay" style="border:1px solid hsla(220,15%,85%,1);border-radius:6px;background:none;cursor:pointer;font:inherit;padding:1px 8px">Replay</button>' : ''}<button type="button" data-act="close" style="border:0;background:none;cursor:pointer;font:inherit">×</button></div>`;
197
+ panel.querySelector('[data-act=close]').onclick = () => api.ui(false);
198
+ const rb = panel.querySelector('[data-act=replay]');
199
+ if (rb) rb.onclick = () => api.replay(all);
118
200
  for (const f of all) {
119
201
  const row = document.createElement('div');
120
202
  row.style.cssText = 'padding:5px 0;border-top:1px solid hsla(220,15%,90%,1);cursor:pointer';
@@ -125,11 +207,128 @@ function createApi() {
125
207
  panel.append(row);
126
208
  }
127
209
  layer.append(panel);
210
+ if (session) layer.style.display = 'none'; // the replay is open
128
211
  document.body.append(layer);
129
212
  }
130
213
 
214
+ // ---- guided replay ----
215
+ let session = null;
216
+
217
+ async function loadReport(url) {
218
+ const res = await fetch(url, {cache: 'no-store'});
219
+ if (!res.ok) throw new Error(`${url}: ${res.status}`);
220
+ const r = await res.json();
221
+ return r.findings || [];
222
+ }
223
+
224
+ /**
225
+ * Steps through findings one at a time. Each step loads the page fresh in a visible same-origin frame at the
226
+ * start width, applies the recipe's storage, waits, repeats the clicks, sets the finding's width and points at
227
+ * the element. Findings come from the argument, data-report, or this page's own check and sweep.
228
+ */
229
+ async function replay(list, o = {}) {
230
+ if (!list) {
231
+ try { list = opts.report ? await loadReport(opts.report) : [...current, ...sweepFindings.filter((f) => !current.some((c) => c.id === f.id))]; }
232
+ catch (e) { console.info('ResponsiveLint: could not load the report (' + e.message + ').'); return null; }
233
+ }
234
+ if (!list.length) { console.info('ResponsiveLint: nothing to replay.'); return null; }
235
+ session?.close();
236
+ if (layer) layer.style.display = 'none';
237
+ const t = timing(o);
238
+ const steps = list.map((f) => ({finding: f, recipe: f.replay || recipe(f, [{id: f.instances?.[0]?.state || 'live', label: 'live page', actions: []}], {url: location.href, route: null, storage: {}, height: innerHeight})}));
239
+ const saved = new Map();
240
+ const store = (k, v) => { try { if (!saved.has(k)) saved.set(k, localStorage.getItem(k)); localStorage.setItem(k, v); } catch {} };
241
+ let index = -1, frame = null, token = 0, last = 0, closed = false;
242
+ const paced = async () => { const gap = last + t.pace - Date.now(); if (gap > 0) await sleep(gap); last = Date.now(); };
243
+
244
+ const shade = document.createElement('div');
245
+ shade.setAttribute('data-rl-overlay', 'replay');
246
+ shade.style.cssText = 'position:fixed;inset:0;z-index:2147483645;background:hsla(222,18%,10%,0.55)';
247
+ const stage = document.createElement('div');
248
+ stage.style.cssText = 'position:absolute;left:0;top:0;transform-origin:0 0;box-shadow:0 8px 32px hsla(0,0%,0%,0.35);background:hsla(0,0%,100%,1)';
249
+ shade.append(stage);
250
+ document.body.append(shade);
251
+ const bar = createBar(document, {onPrev: () => go(index - 1), onNext: () => go(index + 1), onClose: () => close()});
252
+ const BAR_SPACE = 204, GAP = 12;
253
+
254
+ // Shows the frame at its real size, scaled down with a transform when it is larger than the window.
255
+ const fit = (w, h) => {
256
+ const s = Math.min(1, (innerWidth - 2 * GAP) / w, (innerHeight - BAR_SPACE - GAP) / h);
257
+ frame.style.width = w + 'px'; frame.style.height = h + 'px';
258
+ stage.style.width = w + 'px'; stage.style.height = h + 'px';
259
+ stage.style.transform = `translate(${Math.round((innerWidth - w * s) / 2)}px, ${GAP}px) scale(${s})`;
260
+ stage.dataset.scale = s.toFixed(3);
261
+ };
262
+
263
+ function url(r) {
264
+ const u = new URL(r.url, location.href);
265
+ return u.origin === location.origin ? u.href : location.origin + u.pathname + u.search + u.hash;
266
+ }
267
+
268
+ async function go(i) {
269
+ if (closed || i < 0 || i >= steps.length) return null;
270
+ const my = ++token; index = i;
271
+ const {finding: f, recipe: r} = steps[i];
272
+ const h = r.height || innerHeight;
273
+ bar.update({finding: f, index: i, total: steps.length, width: r.width, busy: true});
274
+ frame?.remove();
275
+ for (const [k, v] of Object.entries(r.storage || {})) store(k, v);
276
+ await paced();
277
+ if (my !== token) return null;
278
+ // A new frame each time, so every step starts from a fresh load.
279
+ frame = document.createElement('iframe');
280
+ frame.name = FRAME; frame.setAttribute('data-rl-overlay', 'replay-frame'); frame.title = 'ResponsiveLint replay';
281
+ frame.style.cssText = 'display:block;border:0;background:hsla(0,0%,100%,1)';
282
+ stage.append(frame);
283
+ fit(r.startWidth || START_WIDTH, h);
284
+ let note = '';
285
+ try {
286
+ await new Promise((ok, fail) => { frame.onload = ok; setTimeout(() => fail(new Error('the page took over 20 s to load')), 20000); frame.src = url(r); });
287
+ if (my !== token) return null;
288
+ const win = frame.contentWindow, doc = frame.contentDocument;
289
+ if (!doc) throw new Error('the frame is not on the same site');
290
+ const quiet = trackRequests(win);
291
+ await settle(win, t.wait);
292
+ for (const a of r.actions || []) {
293
+ const el = await waitFor(doc, a.click, t.clickTimeout);
294
+ if (my !== token) return null;
295
+ await paced();
296
+ el.click();
297
+ await quiet();
298
+ await settle(win, 150);
299
+ if (t.clickWait) await sleep(t.clickWait);
300
+ }
301
+ fit(r.width, h);
302
+ await settle(win);
303
+ if (my !== token) return null;
304
+ const inst = (f.instances || []).find((x) => x.width === r.width && x.state === r.state && x.rect);
305
+ const shown = highlight(doc, f, {width: r.width, rect: inst?.rect});
306
+ if (!shown.found) note = 'The element is not on the page at this width.';
307
+ if (!(r.actions || []).length && !f.replay) note = note || 'Shown in the starting state: clicks made on the live page are not recorded.';
308
+ } catch (e) {
309
+ note = 'Could not repeat the steps: ' + e.message;
310
+ }
311
+ if (my !== token) return null;
312
+ bar.update({finding: f, index: i, total: steps.length, width: r.width, note});
313
+ shade.dataset.step = String(i);
314
+ return {index: i, note, frame};
315
+ }
316
+
317
+ function close() {
318
+ if (closed) return; closed = true; token++;
319
+ bar.remove(); shade.remove();
320
+ for (const [k, v] of saved) try { v == null ? localStorage.removeItem(k) : localStorage.setItem(k, v); } catch {}
321
+ if (session === api_) { session = null; draw(); }
322
+ }
323
+ const api_ = {go, close, get index() { return index; }, get frame() { return frame; }, steps: steps.map((s) => s.recipe), done: null};
324
+ session = api_;
325
+ api_.done = go(o.start || 0);
326
+ await api_.done;
327
+ return api_;
328
+ }
329
+
131
330
  return {
132
- check, sweep,
331
+ check, sweep, replay,
133
332
  ui(on = true) { uiOn = !!on; draw(); return uiOn; },
134
333
  on(event, fn) { if (event === 'finding') listeners.add(fn); return () => listeners.delete(fn); },
135
334
  get findings() { return [...current, ...sweepFindings]; },
@@ -0,0 +1,86 @@
1
+ // Guided replay from the command line: a visible browser goes through a report's findings one at a time. Each
2
+ // step starts from zero: a fresh load at the start width with the report's storage, the clicks that led to the
3
+ // state, then the finding's width. The bar's Previous and Next call back here through page.exposeFunction.
4
+ import {stat} from 'node:fs/promises';
5
+ import {openBrowser, LOCAL, START_WIDTH} from './run.js';
6
+ import {serveFolder} from './server.js';
7
+
8
+ /**
9
+ * replay(report, {headless, allowRemote, base, wait, clickWait, clickTimeout, pace, onStep}) opens the first
10
+ * finding and returns {page, findings, go(i), current(), close(), done}. done resolves when the bar or the
11
+ * browser is closed.
12
+ */
13
+ export async function replay(report, options = {}) {
14
+ const findings = (report.findings || []).filter((f) => f.replay);
15
+ if (!report.findings?.length) throw new Error('The report has no findings to replay.');
16
+ if (!findings.length) throw new Error('The findings in this report have no replay recipe. Run the check again with ResponsiveLint 0.2.0 or newer.');
17
+
18
+ // A folder report was served on a port that is gone: serve the folder again. --base moves every finding to
19
+ // another origin, for a dev server that now runs on a different port.
20
+ let server = null, base = options.base || null;
21
+ if (!base && report.target && !/^https?:\/\//.test(report.target)) {
22
+ if (!(await stat(report.target).catch(() => null))) throw new Error(`The report's folder ${report.target} is missing. Pass a base URL to replay it against a running server.`);
23
+ server = await serveFolder(report.target); base = server.url;
24
+ }
25
+ const move = (u) => { if (!base) return u; const from = new URL(u), to = new URL(base); return to.origin + from.pathname + from.search + from.hash; };
26
+ for (const f of findings) f.replay = {...f.replay, url: move(f.replay.url)};
27
+ const origin = new URL(findings[0].replay.url).origin;
28
+ for (const f of findings) {
29
+ const host = new URL(f.replay.url).hostname;
30
+ if (!LOCAL.test(host) && !options.allowRemote) throw new Error(`ResponsiveLint replays clicks, so it only runs against local or test hosts. Pass --allow-remote to replay on ${host} anyway.`);
31
+ if (new URL(f.replay.url).origin !== origin) throw new Error('Every finding in a replay must come from the same site.');
32
+ }
33
+
34
+ const timing = {...report.timing};
35
+ for (const k of ['wait', 'clickWait', 'clickTimeout', 'pace']) if (options[k] != null) timing[k] = options[k];
36
+ const r0 = findings[0].replay;
37
+ const {browser, page, open, resize} = await openBrowser({url: r0.url, origin, height: r0.height || 900, storage: r0.storage, timing, headless: options.headless ?? false});
38
+
39
+ let index = -1, busy = false, closed = false, finish;
40
+ const done = new Promise((r) => { finish = r; });
41
+ const close = async () => {
42
+ if (closed) return; closed = true;
43
+ await browser.close().catch(() => {});
44
+ if (server) await server.close();
45
+ finish();
46
+ };
47
+ browser.on('disconnected', () => { if (!closed) close(); });
48
+ page.on('close', () => { if (!closed) close(); });
49
+
50
+ const go = async (i) => {
51
+ if (busy || closed || i < 0 || i >= findings.length) return null;
52
+ busy = true; index = i;
53
+ const f = findings[i], r = f.replay;
54
+ let note = '';
55
+ try {
56
+ await open({actions: r.actions}, r.startWidth || START_WIDTH, r.url);
57
+ if (await resize({actions: r.actions}, r.width, r.url)) note = `The page reloaded itself at ${r.width} px, so it was opened again at that width.`;
58
+ } catch (e) {
59
+ note = `Could not repeat the steps: ${String(e.message).split('\n')[0]}`;
60
+ }
61
+ if (!r.actions.length && r.state === 'live') note = note || 'Shown in the starting state: clicks made on the live page are not recorded.';
62
+ let result = {found: false, rect: null};
63
+ if (!closed) {
64
+ result = await page.evaluate(([f, i, n, note]) => {
65
+ const R = window.__ResponsiveLint, w = f.replay.width;
66
+ const inst = (f.instances || []).find((x) => x.width === w && x.state === f.replay.state && x.rect);
67
+ const h = R.highlight(document, f, {width: w, rect: inst?.rect});
68
+ window.__rlBar?.remove();
69
+ const args = {finding: f, index: i, total: n, width: w, note: note || (h.found ? '' : 'The element is not on the page at this width.')};
70
+ const step = (j) => { bar.update({...args, busy: true}); window.__rlGo(j); };
71
+ const bar = window.__rlBar = R.createBar(document, {onPrev: () => step(i - 1), onNext: () => step(i + 1), onClose: () => window.__rlClose()});
72
+ bar.update(args);
73
+ return {found: h.found, rect: h.rect};
74
+ }, [f, i, findings.length, note]).catch(() => ({found: false, rect: null}));
75
+ }
76
+ busy = false;
77
+ const out = {index: i, finding: f, note, ...result};
78
+ options.onStep?.(out);
79
+ return out;
80
+ };
81
+ // Called from the bar. Not awaited inside the binding, because the step navigates the page that called it.
82
+ await page.exposeFunction('__rlGo', (i) => { setTimeout(() => go(i)); });
83
+ await page.exposeFunction('__rlClose', () => { setTimeout(close); });
84
+ await go(options.start || 0);
85
+ return {page, findings, go, current: () => index, close, done};
86
+ }
package/src/cli/run.js CHANGED
@@ -5,6 +5,9 @@ import {dirname, join} from 'node:path';
5
5
  import {chromium} from 'playwright';
6
6
  import {analyze} from '../core/analyze.js';
7
7
  import {serveFolder} from './server.js';
8
+ import {recipe, START_WIDTH} from '../core/recipe.js';
9
+
10
+ export {START_WIDTH};
8
11
 
9
12
  const here = dirname(fileURLToPath(import.meta.url));
10
13
  const MODES = {
@@ -13,7 +16,10 @@ const MODES = {
13
16
  aggressive: {from: 320, to: 1920, step: 24, states: 20},
14
17
  };
15
18
 
16
- const LOCAL = /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost|.+\.test)$/;
19
+ export const LOCAL = /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost|.+\.test)$/;
20
+ /** Timing defaults, in milliseconds. The same names work on the command line and in the script tag. */
21
+ export const TIMING = {wait: 300, clickWait: 300, clickTimeout: 3000, pace: 0};
22
+ const NETWORK_CAP = 5000, NETWORK_IDLE = 250;
17
23
 
18
24
  // Runs before any page script: records WebGL/WebGPU contexts and WebXR sessions for 3D detection.
19
25
  const INIT = `(() => {
@@ -43,43 +49,7 @@ export async function check(target, options = {}) {
43
49
  throw new Error(`ResponsiveLint clicks through pages to find states, so it only runs against local or test hosts. Pass --allow-remote to check ${new URL(url).hostname} anyway.`);
44
50
  }
45
51
 
46
- const bundle = await readFile(join(here, '../../dist/core.iife.js'), 'utf8').catch(() => { throw new Error('dist/core.iife.js is missing. Run npm run build first.'); });
47
- const browser = await chromium.launch({headless: true});
48
- const context = await browser.newContext({viewport: {width: 1280, height}, deviceScaleFactor: 1, acceptDownloads: false});
49
- await context.addInitScript(INIT);
50
- await context.addInitScript(bundle);
51
- if (options.storage) await context.addInitScript(([s]) => { for (const [k, v] of Object.entries(s)) try { localStorage.setItem(k, v); } catch {} }, [options.storage]);
52
- // Safety: no writes, no other sites' pages.
53
- await context.route('**/*', (route) => {
54
- const req = route.request();
55
- if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method())) return route.abort();
56
- if (req.isNavigationRequest() && new URL(req.url()).origin !== origin) return route.abort();
57
- return route.continue();
58
- });
59
- const page = await context.newPage();
60
- page.on('dialog', (d) => d.dismiss().catch(() => {}));
61
- const errors = [];
62
- page.on('pageerror', (e) => errors.push(String(e.message || e)));
63
-
64
- const settle = async (extra = 0) => {
65
- await page.evaluate(async (extra) => {
66
- await document.fonts?.ready;
67
- await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
68
- const anims = (document.getAnimations?.() || []).filter((a) => a.playState === 'running' && a.effect?.getTiming?.().iterations !== Infinity);
69
- await Promise.race([Promise.all(anims.map((a) => a.finished.catch(() => {}))), new Promise((r) => setTimeout(r, 600))]);
70
- if (extra) await new Promise((r) => setTimeout(r, extra));
71
- }, extra).catch(() => {});
72
- };
73
- const open = async (state, width) => {
74
- await page.setViewportSize({width: width || 1280, height});
75
- await page.goto(url, {waitUntil: 'load'});
76
- await settle(options.wait || 300);
77
- for (const a of state.actions) {
78
- await page.click(a.click, {timeout: 3000});
79
- await settle(150);
80
- }
81
- };
82
-
52
+ const {browser, page, open, resize, settle, errors, timing} = await openBrowser({url, origin, height, storage: options.storage, timing: options});
83
53
  const started = Date.now();
84
54
  const states = [{id: 'default', label: 'Default', actions: []}];
85
55
  let env = null;
@@ -112,17 +82,18 @@ export async function check(target, options = {}) {
112
82
  // ---- width sweep in each state ----
113
83
  const snapshots = [];
114
84
  for (const state of states) {
115
- try { await open(state, 1280); } catch (e) { log(`Could not reach state "${state.label}": ${e.message}`); continue; }
85
+ try { await open(state, START_WIDTH); } catch (e) { log(`Could not reach state "${state.label}": ${e.message}`); continue; }
86
+ const reloads = [];
116
87
  for (const w of widths) {
117
- await page.setViewportSize({width: w, height});
118
- await page.evaluate(() => scrollTo(0, 0));
119
- await settle();
88
+ try { if (await resize(state, w)) reloads.push(w); } catch (e) { log(` ${state.label}: skipped ${w} px (${e.message.split('\n')[0]})`); continue; }
89
+ await page.evaluate(() => scrollTo(0, 0)).catch(() => {});
120
90
  const snap = await page.evaluate(() => __ResponsiveLint.checkNow({revealSkipped: true}));
121
91
  snapshots.push({state: {id: state.id, label: state.label}, width: w, findings: snap.findings, measures: snap.measures});
122
92
  }
123
- log(` ${state.label}: ${widths.length} widths`);
93
+ log(` ${state.label}: ${widths.length} widths${reloads.length ? ` (the page reloaded itself at ${reloads.join(', ')} px; each time it was opened again at that width; if findings appear just after those widths, raise --wait)` : ''}`);
124
94
  }
125
95
  const result = analyze(snapshots, {only: options.only, skip: options.skip, minConfidence: options.minConfidence});
96
+ for (const f of result.findings) f.replay = recipe(f, states, {url, route: options.route || null, storage: options.storage || {}, height});
126
97
  // ---- evidence screenshots ----
127
98
  if (options.evidence) {
128
99
  for (const f of result.findings.slice(0, options.evidence)) {
@@ -147,14 +118,107 @@ export async function check(target, options = {}) {
147
118
  }
148
119
  }
149
120
  }
150
- return {target, url, startedAt: new Date(started).toISOString(), seconds: Math.round((Date.now() - started) / 1000), mode: options.mode || 'normal',
151
- widths, states: states.map(({id, label, change}) => ({id, label, change})), env, pageErrors: [...new Set(errors)].slice(0, 10), ...result};
121
+ return {target, url, startedAt: new Date(started).toISOString(), seconds: Math.round((Date.now() - started) / 1000), mode: options.mode || 'normal', timing,
122
+ widths, states: states.map(({id, label, change, actions}) => ({id, label, change, actions})), env, pageErrors: [...new Set(errors)].slice(0, 10), ...result};
152
123
  } finally {
153
124
  await browser.close();
154
125
  if (server) await server.close();
155
126
  }
156
127
  }
157
128
 
129
+ /**
130
+ * Launches Chromium with the safety rules and returns open(state, width): a fresh load, then the clicks, each
131
+ * paced and followed by network quiet, the settle and clickWait.
132
+ */
133
+ export async function openBrowser({url, origin, height = 900, storage, timing = {}, headless = true, bundles = []}) {
134
+ const t = {...TIMING};
135
+ for (const k of Object.keys(TIMING)) if (timing[k] != null && !Number.isNaN(+timing[k])) t[k] = +timing[k];
136
+ const bundle = await readFile(join(here, '../../dist/core.iife.js'), 'utf8').catch(() => { throw new Error('dist/core.iife.js is missing. Run npm run build first.'); });
137
+ const browser = await chromium.launch({headless});
138
+ const context = await browser.newContext({viewport: {width: START_WIDTH, height}, deviceScaleFactor: 1, acceptDownloads: false});
139
+ await context.addInitScript(INIT);
140
+ await context.addInitScript(bundle);
141
+ for (const b of bundles) await context.addInitScript(b);
142
+ if (storage && Object.keys(storage).length) await context.addInitScript(([s]) => { for (const [k, v] of Object.entries(s)) try { localStorage.setItem(k, v); } catch {} }, [storage]);
143
+ // Safety: no writes, no other sites' pages.
144
+ await context.route('**/*', (route) => {
145
+ const req = route.request();
146
+ if (!['GET', 'HEAD', 'OPTIONS'].includes(req.method())) return route.abort();
147
+ if (req.isNavigationRequest() && new URL(req.url()).origin !== origin) return route.abort();
148
+ return route.continue();
149
+ });
150
+ const page = await context.newPage();
151
+ page.on('dialog', (d) => d.dismiss().catch(() => {}));
152
+ const errors = [];
153
+ page.on('pageerror', (e) => errors.push(String(e.message || e)));
154
+
155
+ // Requests in flight, for waiting until the network is quiet after a click.
156
+ let inflight = new Set(), lastNet = 0;
157
+ page.on('request', (r) => { inflight.add(r); lastNet = Date.now(); });
158
+ const done = (r) => { inflight.delete(r); lastNet = Date.now(); };
159
+ page.on('requestfinished', done);
160
+ page.on('requestfailed', done);
161
+ const quiet = async () => {
162
+ const end = Date.now() + NETWORK_CAP;
163
+ while (Date.now() < end) {
164
+ if (!inflight.size && Date.now() - lastNet >= NETWORK_IDLE) return;
165
+ await sleep(40);
166
+ }
167
+ };
168
+ // pace: the least time between two page loads or clicks.
169
+ let last = 0;
170
+ const paced = async () => { const gap = last + t.pace - Date.now(); if (gap > 0) await sleep(gap); last = Date.now(); };
171
+
172
+ const settle = async (extra = 0) => {
173
+ await page.evaluate(async (extra) => {
174
+ await document.fonts?.ready;
175
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
176
+ const anims = (document.getAnimations?.() || []).filter((a) => a.playState === 'running' && a.effect?.getTiming?.().iterations !== Infinity);
177
+ await Promise.race([Promise.all(anims.map((a) => a.finished.catch(() => {}))), new Promise((r) => setTimeout(r, 600))]);
178
+ if (extra) await new Promise((r) => setTimeout(r, extra));
179
+ }, extra).catch(() => {});
180
+ };
181
+ const open = async (state, width, target = url) => {
182
+ await page.setViewportSize({width: width || START_WIDTH, height});
183
+ // Back to zero: storage left by an earlier click is cleared, then the init script sets --storage again.
184
+ await page.evaluate((o) => { if (location.origin === o) { try { localStorage.clear(); sessionStorage.clear(); } catch {} } }, origin).catch(() => {});
185
+ await paced();
186
+ inflight = new Set();
187
+ // A page that is reloading itself aborts our navigation: let its load finish, then go again.
188
+ await page.goto(target, {waitUntil: 'load'}).catch(async (e) => {
189
+ if (!/ERR_ABORTED|interrupted by another navigation/.test(e.message)) throw e;
190
+ await page.waitForLoadState('load').catch(() => {});
191
+ await page.goto(target, {waitUntil: 'load'});
192
+ });
193
+ await settle(t.wait);
194
+ for (const a of state.actions || []) {
195
+ await page.waitForSelector(a.click, {state: 'visible', timeout: t.clickTimeout});
196
+ await paced();
197
+ await page.click(a.click, {timeout: t.clickTimeout});
198
+ await quiet();
199
+ await settle(150);
200
+ if (t.clickWait) await sleep(t.clickWait);
201
+ }
202
+ };
203
+ // Some pages reload themselves when the width crosses a breakpoint (location.reload() in a resize handler).
204
+ // resize() notices the new load, waits for it, and opens the state again at that width. Returns true then.
205
+ let loads = 0;
206
+ page.on('load', () => { loads++; });
207
+ const resize = async (state, width, target = url) => {
208
+ const before = loads;
209
+ await page.setViewportSize({width, height});
210
+ await settle();
211
+ await sleep(50);
212
+ if (loads === before && !(await page.evaluate(() => !document.body).catch(() => true))) return false;
213
+ await page.waitForLoadState('load').catch(() => {});
214
+ await open(state, width, target);
215
+ return true;
216
+ };
217
+ return {browser, context, page, open, resize, settle, errors, timing: t};
218
+ }
219
+
220
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
221
+
158
222
  export function range(from, to, step) { const out = []; for (let w = from; w <= to; w += step) out.push(w); if (out[out.length - 1] !== to) out.push(to); return out; }
159
223
 
160
224
  function describe(c) {