responsivelint 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 +214 -2
- package/agents/skills/responsivelint/SKILL.md +57 -0
- package/agents/skills/responsivelint-fix/SKILL.md +38 -0
- package/agents/skills/responsivelint-fix-controls/SKILL.md +35 -0
- package/agents/skills/responsivelint-fix-cramped-text/SKILL.md +47 -0
- package/agents/skills/responsivelint-fix-overflow/SKILL.md +33 -0
- package/agents/skills/responsivelint-fix-overlap/SKILL.md +33 -0
- package/bin/responsivelint.mjs +111 -0
- package/dist/core.iife.js +944 -0
- package/dist/responsivelint.js +1232 -0
- package/dist/responsivelint.min.js +25 -0
- package/docs/rules/clipped-text.md +21 -0
- package/docs/rules/disappears-in-band.md +21 -0
- package/docs/rules/hidden-control.md +21 -0
- package/docs/rules/page-overflow.md +21 -0
- package/docs/rules/squashed-text.md +21 -0
- package/docs/rules/text-overlap.md +21 -0
- package/docs/rules/width-outlier.md +21 -0
- package/llms.txt +49 -0
- package/package.json +43 -4
- package/src/browser/entry.js +337 -0
- package/src/cli/replay.js +86 -0
- package/src/cli/report.js +90 -0
- package/src/cli/run.js +241 -0
- package/src/cli/server.js +24 -0
- package/src/core/analyze.js +265 -0
- package/src/core/bar.js +78 -0
- package/src/core/dom.js +122 -0
- package/src/core/highlight.js +73 -0
- package/src/core/index.js +5 -0
- package/src/core/inject.js +5 -0
- package/src/core/measure.js +241 -0
- package/src/core/recipe.js +19 -0
- package/src/explore/page.js +63 -0
- package/src/icons/measure.js +106 -0
- package/src/index.js +5 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
// The script-tag version.
|
|
2
|
+
// <script src="responsivelint.js"></script> console findings, re-checked as the page changes
|
|
3
|
+
// <script src="responsivelint.js" data-ui></script> also outline problems on the page
|
|
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
|
|
8
|
+
import {checkNow, detectEnvironment} from '../core/measure.js';
|
|
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';
|
|
13
|
+
|
|
14
|
+
const FRAME = 'responsivelint-frame';
|
|
15
|
+
const script = document.currentScript;
|
|
16
|
+
const opts = script ? script.dataset : {};
|
|
17
|
+
|
|
18
|
+
if (window.name === FRAME) {
|
|
19
|
+
// Inside our own sweep frame: only measure when asked.
|
|
20
|
+
window.__ResponsiveLintFrame = {checkNow};
|
|
21
|
+
} else {
|
|
22
|
+
const local = /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost|.+\.test)$/.test(location.hostname) || location.protocol === 'file:';
|
|
23
|
+
const api = window.ResponsiveLint = createApi();
|
|
24
|
+
if (local || 'anywhere' in opts) {
|
|
25
|
+
const start = async () => {
|
|
26
|
+
api.check();
|
|
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();
|
|
31
|
+
};
|
|
32
|
+
if (document.readyState === 'complete') setTimeout(start, 50); else addEventListener('load', () => setTimeout(start, 50));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
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
|
+
|
|
107
|
+
function createApi() {
|
|
108
|
+
const logged = new Set();
|
|
109
|
+
const listeners = new Set();
|
|
110
|
+
let current = [], sweepFindings = [], uiOn = false, timer = 0;
|
|
111
|
+
|
|
112
|
+
const emit = (f) => listeners.forEach((fn) => { try { fn(f); } catch {} });
|
|
113
|
+
|
|
114
|
+
function report(findings) {
|
|
115
|
+
for (const f of findings) {
|
|
116
|
+
if (logged.has(f.id)) continue;
|
|
117
|
+
logged.add(f.id);
|
|
118
|
+
emit(f);
|
|
119
|
+
const color = f.severity === 'error' ? '#e5484d' : f.severity === 'warning' ? '#d08a12' : '#888';
|
|
120
|
+
console.groupCollapsed(`%cResponsiveLint%c ${f.severity === 'error' ? '✖' : '▲'} ${f.rule}: ${f.title}`, 'font-weight:700', `color:${color}`);
|
|
121
|
+
for (const e of f.elements) console.log(e.text ? `“${e.text}”` : e.key, document.querySelector(e.key) || e.key);
|
|
122
|
+
console.log('where:', f.bands.map(([a, b]) => (a === b ? a : `${a}–${b}`)).join(', ') + ' px', f.states.join(' · '));
|
|
123
|
+
if (f.measured) console.log('measured:', f.measured, f.expected ? ['neighbours:', f.expected] : '');
|
|
124
|
+
console.log('why:', f.why);
|
|
125
|
+
console.log('try:\n' + f.tries.map((t, i) => `${i + 1}. ${t}`).join('\n'));
|
|
126
|
+
console.log('skill:', f.skill.name, f.skill.url);
|
|
127
|
+
console.log('silence:', f.suppress);
|
|
128
|
+
console.groupEnd();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function check() {
|
|
133
|
+
const snap = checkNow();
|
|
134
|
+
const env = detectEnvironment();
|
|
135
|
+
current = analyze([{state: {id: 'live', label: 'live page'}, width: snap.width, findings: snap.findings, measures: []}]).findings;
|
|
136
|
+
report(current);
|
|
137
|
+
if (env.is3D && !logged.has('3d')) { logged.add('3d'); console.info('ResponsiveLint: 3D detected (' + (env.frameworks.join(', ') || 'WebGL') + '). The 3D rule pack is not implemented yet.'); }
|
|
138
|
+
if (uiOn) draw();
|
|
139
|
+
return current;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const recheck = () => { clearTimeout(timer); timer = setTimeout(check, 500); };
|
|
143
|
+
addEventListener('resize', recheck);
|
|
144
|
+
addEventListener('click', recheck, true);
|
|
145
|
+
new MutationObserver((m) => { if (m.some((r) => !(r.target instanceof Element && r.target.closest('[data-rl-overlay]')))) recheck(); })
|
|
146
|
+
.observe(document.documentElement, {subtree: true, childList: true, attributes: true, attributeFilter: ['class', 'style', 'hidden', 'aria-expanded', 'open']});
|
|
147
|
+
|
|
148
|
+
/** Sweep widths in a hidden same-origin copy of this page. */
|
|
149
|
+
async function sweep({from = 320, to = 1920, step = 48} = {}) {
|
|
150
|
+
const frame = document.createElement('iframe');
|
|
151
|
+
frame.name = FRAME; frame.src = location.href; frame.setAttribute('data-rl-overlay', '');
|
|
152
|
+
frame.style.cssText = `position:fixed;left:-20000px;top:0;height:${innerHeight}px;width:1280px;border:0;visibility:hidden`;
|
|
153
|
+
document.body.append(frame);
|
|
154
|
+
try {
|
|
155
|
+
await new Promise((r, x) => { frame.onload = r; setTimeout(() => x(new Error('timeout')), 20000); });
|
|
156
|
+
const win = frame.contentWindow;
|
|
157
|
+
if (!win.__ResponsiveLintFrame) throw new Error('the page does not load this script in a frame');
|
|
158
|
+
await settle(win, timing().wait);
|
|
159
|
+
const snaps = [];
|
|
160
|
+
for (let w = from; w <= to; w += step) {
|
|
161
|
+
frame.style.width = w + 'px';
|
|
162
|
+
await new Promise((r) => win.requestAnimationFrame(() => win.requestAnimationFrame(() => setTimeout(r, 120))));
|
|
163
|
+
const s = win.__ResponsiveLintFrame.checkNow();
|
|
164
|
+
snaps.push({state: {id: 'sweep', label: 'width sweep'}, width: w, findings: s.findings, measures: s.measures});
|
|
165
|
+
}
|
|
166
|
+
sweepFindings = analyze(snaps).findings;
|
|
167
|
+
report(sweepFindings);
|
|
168
|
+
if (uiOn) draw();
|
|
169
|
+
return sweepFindings;
|
|
170
|
+
} catch (e) {
|
|
171
|
+
console.info('ResponsiveLint: the width sweep could not run (' + e.message + '). Use the command line, npx responsivelint, for a full sweep.');
|
|
172
|
+
return [];
|
|
173
|
+
} finally { frame.remove(); }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ---- overlay ----
|
|
177
|
+
let layer = null;
|
|
178
|
+
function draw() {
|
|
179
|
+
layer?.remove();
|
|
180
|
+
if (!uiOn) return;
|
|
181
|
+
layer = document.createElement('div');
|
|
182
|
+
layer.setAttribute('data-rl-overlay', '');
|
|
183
|
+
layer.style.cssText = 'position:absolute;left:0;top:0;width:0;height:0;z-index:2147483646;pointer-events:none';
|
|
184
|
+
const all = [...current, ...sweepFindings.filter((f) => !current.some((c) => c.id === f.id))];
|
|
185
|
+
for (const f of current) {
|
|
186
|
+
for (const inst of f.instances) {
|
|
187
|
+
const r = inst.rect; if (!r) continue;
|
|
188
|
+
const box = document.createElement('div');
|
|
189
|
+
box.style.cssText = `position:absolute;left:${r.left}px;top:${r.top}px;width:${r.right - r.left}px;height:${r.bottom - r.top}px;outline:2px solid ${f.severity === 'error' ? '#e5484d' : '#d08a12'};outline-offset:1px;border-radius:2px`;
|
|
190
|
+
box.title = f.title;
|
|
191
|
+
layer.append(box);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const panel = document.createElement('div');
|
|
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';
|
|
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);
|
|
200
|
+
for (const f of all) {
|
|
201
|
+
const row = document.createElement('div');
|
|
202
|
+
row.style.cssText = 'padding:5px 0;border-top:1px solid hsla(220,15%,90%,1);cursor:pointer';
|
|
203
|
+
const where = f.bands.map(([a, b]) => (a === b ? a : `${a}–${b}`)).join(', ') + ' px';
|
|
204
|
+
const esc = (t) => String(t).replace(/[&<>"]/g, (ch) => ({'&': '&', '<': '<', '>': '>', '"': '"'}[ch]));
|
|
205
|
+
row.innerHTML = `<span style="color:${f.severity === 'error' ? '#e5484d' : '#b37400'}">${f.severity === 'error' ? '✖' : '▲'}</span> ${esc(f.title)}<br><span style="color:#6b7280">${esc((f.elements[0]?.text || f.elements[0]?.key || '').slice(0, 50))} · ${where}</span><br><span style="color:#374151">Try: ${esc(f.tries[0])}</span> <a href="${esc(f.skill.url)}" target="_blank" rel="noopener" style="color:hsla(220,70%,45%,1);text-decoration:none">${esc(f.skill.name)}</a>`;
|
|
206
|
+
row.onclick = () => document.querySelector(f.elements[0]?.key)?.scrollIntoView({block: 'center', behavior: 'smooth'});
|
|
207
|
+
panel.append(row);
|
|
208
|
+
}
|
|
209
|
+
layer.append(panel);
|
|
210
|
+
if (session) layer.style.display = 'none'; // the replay is open
|
|
211
|
+
document.body.append(layer);
|
|
212
|
+
}
|
|
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
|
+
|
|
330
|
+
return {
|
|
331
|
+
check, sweep, replay,
|
|
332
|
+
ui(on = true) { uiOn = !!on; draw(); return uiOn; },
|
|
333
|
+
on(event, fn) { if (event === 'finding') listeners.add(fn); return () => listeners.delete(fn); },
|
|
334
|
+
get findings() { return [...current, ...sweepFindings]; },
|
|
335
|
+
rules: RULES,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Reporters. Every finding answers: what is wrong, where, why we think so, how sure we are, how to fix or silence it.
|
|
2
|
+
|
|
3
|
+
const tty = process.stdout.isTTY;
|
|
4
|
+
const c = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
5
|
+
const red = c(31), yellow = c(33), dim = c(2), bold = c(1), cyan = c(36);
|
|
6
|
+
|
|
7
|
+
export const fmtBands = (bands) => bands.map(([a, b]) => (a === b ? `${a}` : `${a}–${b}`)).join(', ') + ' px';
|
|
8
|
+
|
|
9
|
+
export function terminalReport(r) {
|
|
10
|
+
const out = [];
|
|
11
|
+
const head = `ResponsiveLint · ${r.url} · ${r.widths.length} widths (${r.widths[0]}–${r.widths[r.widths.length - 1]} px) · ${r.states.length} state${r.states.length === 1 ? '' : 's'} · ${r.seconds}s`;
|
|
12
|
+
out.push(bold(head));
|
|
13
|
+
if (r.env?.is3D) out.push(cyan(`3D detected: ${r.env.frameworks.join(', ') || 'WebGL canvas'}${r.env.xr ? ' with WebXR' : ''}. The 3D rule pack is planned and not yet implemented, so the scene itself was not checked.`));
|
|
14
|
+
if (r.states.length > 1) out.push(dim('States: ' + r.states.map((s) => s.label).join(' · ')));
|
|
15
|
+
out.push('');
|
|
16
|
+
for (const f of r.findings) {
|
|
17
|
+
const mark = f.severity === 'error' ? red('✖') : f.severity === 'warning' ? yellow('▲') : dim('·');
|
|
18
|
+
const el = f.elements[0];
|
|
19
|
+
out.push(`${mark} ${bold(f.rule)} ${f.title}${f.everyWidth ? dim(' (at every width)') : ''} ${dim(f.confidence + ' confidence')}`);
|
|
20
|
+
out.push(` ${dim('element')} ${el.text ? `"${el.text}" ` : ''}${dim(el.key)}`);
|
|
21
|
+
if (f.elements[1]) out.push(` ${dim('and')} ${f.elements[1].text ? `"${f.elements[1].text}" ` : ''}${dim(f.elements[1].key)}`);
|
|
22
|
+
out.push(` ${dim('where')} ${fmtBands(f.bands)}${f.states.length ? ` · ${f.states.join(' · ')}` : ''}`);
|
|
23
|
+
if (f.measured) out.push(` ${dim('measured')} ${fmt(f.measured)}${f.expected ? ` ${dim('neighbours')} ${fmt(f.expected)}` : ''}`);
|
|
24
|
+
out.push(` ${dim('why')} ${f.why}`);
|
|
25
|
+
f.tries.forEach((t, i) => out.push(`${i ? ' ' : ' ' + dim('try') + ' '}${i + 1}. ${t}`));
|
|
26
|
+
out.push(` ${dim('skill')} ${f.skill.name} ${dim(f.skill.file)}`);
|
|
27
|
+
out.push(` ${dim('guide')} ${dim(f.guide)}`);
|
|
28
|
+
out.push(` ${dim('silence')} ${f.suppress}`);
|
|
29
|
+
out.push('');
|
|
30
|
+
}
|
|
31
|
+
const n = (s) => r.findings.filter((f) => f.severity === s).length;
|
|
32
|
+
const skills = new Map();
|
|
33
|
+
for (const f of r.findings) skills.set(f.skill.name, [f.skill, (skills.get(f.skill.name)?.[1] || 0) + 1]);
|
|
34
|
+
if (skills.size) {
|
|
35
|
+
out.push(bold('To fix with an AI agent, load these skills (in the package and the repository):'));
|
|
36
|
+
for (const [name, [sk, k]] of skills) out.push(` ${name} ${dim(`${k} finding${k === 1 ? '' : 's'} · ${sk.file}`)}`);
|
|
37
|
+
out.push('');
|
|
38
|
+
}
|
|
39
|
+
out.push(bold(`${n('error')} errors, ${n('warning')} warnings, ${n('info')} notes`) + (r.pageErrors?.length ? dim(` · the page logged ${r.pageErrors.length} error(s)`) : ''));
|
|
40
|
+
return out.join('\n');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const fmt = (o) => Object.entries(o).map(([k, v]) => `${k} ${v}`).join(', ');
|
|
44
|
+
|
|
45
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (ch) => ({'&': '&', '<': '<', '>': '>', '"': '"'}[ch]));
|
|
46
|
+
|
|
47
|
+
export function htmlReport(r) {
|
|
48
|
+
const min = r.widths[0], max = r.widths[r.widths.length - 1];
|
|
49
|
+
const pos = (w) => ((w - min) / Math.max(1, max - min)) * 100;
|
|
50
|
+
const ruler = (f) => f.bands.map(([a, b]) => `<i class="band ${f.severity}" style="left:${pos(a)}%;width:max(3px,${pos(b) - pos(a)}%)" title="${a}–${b} px"></i>`).join('');
|
|
51
|
+
const cards = r.findings.map((f) => `
|
|
52
|
+
<article class="card ${f.severity}">
|
|
53
|
+
<header><span class="sev">${f.severity}</span><b>${esc(f.title)}</b><code>${f.rule}</code><span class="conf">${f.confidence} confidence</span></header>
|
|
54
|
+
<div class="ruler">${ruler(f)}</div>
|
|
55
|
+
<dl>
|
|
56
|
+
<dt>Element</dt><dd>${f.elements.map((e) => `${e.text ? `“${esc(e.text)}” ` : ''}<code>${esc(e.key)}</code>`).join('<br>')}</dd>
|
|
57
|
+
<dt>Where</dt><dd>${esc(fmtBands(f.bands))}${f.states.length ? ' · ' + f.states.map(esc).join(' · ') : ''}</dd>
|
|
58
|
+
${f.measured ? `<dt>Measured</dt><dd>${esc(fmt(f.measured))}${f.expected ? ` <span class="muted">· neighbours ${esc(fmt(f.expected))}</span>` : ''}</dd>` : ''}
|
|
59
|
+
<dt>Why</dt><dd>${esc(f.why)}</dd>
|
|
60
|
+
<dt>Try</dt><dd><ol>${f.tries.map((t) => `<li>${esc(t)}</li>`).join('')}</ol></dd>
|
|
61
|
+
<dt>Skill</dt><dd><a href="${esc(f.skill.url)}">${esc(f.skill.name)}</a> · <a href="${esc(f.guide)}">rule guide</a></dd>
|
|
62
|
+
<dt>Silence</dt><dd><code>${esc(f.suppress)}</code></dd>
|
|
63
|
+
</dl>
|
|
64
|
+
${f.evidence?.length ? `<div class="shots">${f.evidence.map((e) => `<figure><img src="data:image/png;base64,${e.png}" alt=""><figcaption>${e.kind === 'bad' ? 'Problem' : 'Healthy'} at ${e.width} px</figcaption></figure>`).join('')}</div>` : ''}
|
|
65
|
+
</article>`).join('');
|
|
66
|
+
return `<!doctype html><meta charset="utf-8"><title>ResponsiveLint report</title>
|
|
67
|
+
<style>a{color:hsla(220,70%,45%,1);text-decoration:none}dd ol{margin:0;padding-left:1.2em}
|
|
68
|
+
:root{--bg:hsla(60,20%,98%,1);--ink:hsla(220,15%,15%,1);--muted:hsla(220,8%,45%,1);--line:hsla(220,15%,88%,1);--err:hsla(358,75%,59%,1);--warn:hsla(36,90%,50%,1);--info:hsla(220,10%,60%,1);--card:hsla(0,0%,100%,1)}
|
|
69
|
+
body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.55 system-ui,-apple-system,sans-serif}
|
|
70
|
+
main{max-width:980px;margin:0 auto;padding:32px 20px}
|
|
71
|
+
h1{font-size:22px;margin:0 0 4px}.muted{color:var(--muted)}a{color:inherit;text-decoration:none}
|
|
72
|
+
.axis{display:flex;justify-content:space-between;color:var(--muted);font-size:11px;margin:18px 0 6px}
|
|
73
|
+
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px 18px;margin:14px 0}
|
|
74
|
+
.card header{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap}.card header code{color:var(--muted)}
|
|
75
|
+
.sev{font-size:11px;text-transform:uppercase;letter-spacing:.08em;font-weight:700}.error .sev{color:var(--err)}.warning .sev{color:var(--warn)}.info .sev{color:var(--info)}
|
|
76
|
+
.conf{margin-left:auto;color:var(--muted);font-size:12px}
|
|
77
|
+
.ruler{position:relative;height:8px;background:hsla(150,40%,45%,.18);border-radius:4px;margin:12px 0}
|
|
78
|
+
.band{position:absolute;top:0;bottom:0;border-radius:4px}.band.error{background:var(--err)}.band.warning{background:var(--warn)}.band.info{background:var(--info)}
|
|
79
|
+
dl{display:grid;grid-template-columns:90px 1fr;gap:4px 14px;margin:0}dt{color:var(--muted)}dd{margin:0;overflow-wrap:anywhere}
|
|
80
|
+
.shots{display:flex;gap:12px;flex-wrap:wrap;margin-top:12px}figure{margin:0;max-width:100%}img{max-width:100%;border:1px solid var(--line);border-radius:6px;display:block}figcaption{color:var(--muted);font-size:12px}
|
|
81
|
+
</style>
|
|
82
|
+
<main>
|
|
83
|
+
<h1>ResponsiveLint report</h1>
|
|
84
|
+
<div class="muted">${esc(r.url)} · ${r.widths.length} widths · ${r.states.length} states · ${r.seconds}s · ${esc(r.startedAt)}</div>
|
|
85
|
+
${r.env?.is3D ? `<p class="muted">3D detected: ${esc(r.env.frameworks.join(', ') || 'WebGL canvas')}. The 3D rule pack is not implemented yet.</p>` : ''}
|
|
86
|
+
<p class="muted">States checked: ${r.states.map((s) => esc(s.label)).join(' · ')}</p>
|
|
87
|
+
<div class="axis"><span>${min} px</span><span>each bar: green where it is fine, coloured where the problem is</span><span>${max} px</span></div>
|
|
88
|
+
${cards || '<p>No problems found.</p>'}
|
|
89
|
+
</main>`;
|
|
90
|
+
}
|