responsivelint 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +171 -2
- package/agents/skills/responsivelint/SKILL.md +44 -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 +74 -0
- package/dist/core.iife.js +773 -0
- package/dist/responsivelint.js +838 -0
- package/dist/responsivelint.min.js +3 -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 +42 -0
- package/package.json +43 -4
- package/src/browser/entry.js +138 -0
- package/src/cli/report.js +90 -0
- package/src/cli/run.js +177 -0
- package/src/cli/server.js +24 -0
- package/src/core/analyze.js +265 -0
- package/src/core/dom.js +122 -0
- package/src/core/index.js +3 -0
- package/src/core/inject.js +4 -0
- package/src/core/measure.js +241 -0
- package/src/explore/page.js +63 -0
- package/src/icons/measure.js +106 -0
- package/src/index.js +4 -0
package/src/cli/run.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// Drives a real browser: discovers states, sweeps widths in each state, and analyses the snapshots.
|
|
2
|
+
import {readFile, stat} from 'node:fs/promises';
|
|
3
|
+
import {fileURLToPath} from 'node:url';
|
|
4
|
+
import {dirname, join} from 'node:path';
|
|
5
|
+
import {chromium} from 'playwright';
|
|
6
|
+
import {analyze} from '../core/analyze.js';
|
|
7
|
+
import {serveFolder} from './server.js';
|
|
8
|
+
|
|
9
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const MODES = {
|
|
11
|
+
quick: {from: 360, to: 1440, step: 360, states: 0},
|
|
12
|
+
normal: {from: 320, to: 1920, step: 48, states: 8},
|
|
13
|
+
aggressive: {from: 320, to: 1920, step: 24, states: 20},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const LOCAL = /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost|.+\.test)$/;
|
|
17
|
+
|
|
18
|
+
// Runs before any page script: records WebGL/WebGPU contexts and WebXR sessions for 3D detection.
|
|
19
|
+
const INIT = `(() => {
|
|
20
|
+
const c = window.__rlContexts = {};
|
|
21
|
+
const orig = HTMLCanvasElement.prototype.getContext;
|
|
22
|
+
HTMLCanvasElement.prototype.getContext = function (type, ...rest) { const ctx = orig.call(this, type, ...rest); if (ctx && /webgl|webgpu/.test(type)) c[type.replace('experimental-', '')] = (c[type] || 0) + 1; return ctx; };
|
|
23
|
+
if (navigator.xr && navigator.xr.requestSession) { const r = navigator.xr.requestSession.bind(navigator.xr); navigator.xr.requestSession = (...a) => { window.__rlXR = true; return r(...a); }; }
|
|
24
|
+
window.alert = window.confirm = window.prompt = () => undefined;
|
|
25
|
+
})();`;
|
|
26
|
+
|
|
27
|
+
export async function check(target, options = {}) {
|
|
28
|
+
const mode = MODES[options.mode || 'normal'];
|
|
29
|
+
const from = options.from ?? mode.from, to = options.to ?? mode.to, step = options.step ?? mode.step;
|
|
30
|
+
const maxStates = options.states ?? mode.states;
|
|
31
|
+
const widths = options.widths || range(from, to, step);
|
|
32
|
+
const log = options.log || (() => {});
|
|
33
|
+
const height = options.height || 900;
|
|
34
|
+
|
|
35
|
+
let server = null, url = target;
|
|
36
|
+
if (!/^https?:\/\//.test(target)) {
|
|
37
|
+
if (!(await stat(target).catch(() => null))) throw new Error(`No such URL or folder: ${target}`);
|
|
38
|
+
server = await serveFolder(target); url = server.url;
|
|
39
|
+
}
|
|
40
|
+
if (options.route) url = new URL(options.route, url).href;
|
|
41
|
+
const origin = new URL(url).origin;
|
|
42
|
+
if (!LOCAL.test(new URL(url).hostname) && !options.allowRemote) {
|
|
43
|
+
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
|
+
}
|
|
45
|
+
|
|
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
|
+
|
|
83
|
+
const started = Date.now();
|
|
84
|
+
const states = [{id: 'default', label: 'Default', actions: []}];
|
|
85
|
+
let env = null;
|
|
86
|
+
try {
|
|
87
|
+
await open(states[0]);
|
|
88
|
+
env = await page.evaluate(() => __ResponsiveLint.detectEnvironment());
|
|
89
|
+
// ---- state discovery ----
|
|
90
|
+
if (maxStates > 0) {
|
|
91
|
+
const base = await page.evaluate(() => __ResponsiveLint.layoutSignature());
|
|
92
|
+
const candidates = await page.evaluate((limit) => __ResponsiveLint.discoverCandidates({limit}), options.candidates || 40);
|
|
93
|
+
log(`Exploring ${candidates.length} kinds of control for states…`);
|
|
94
|
+
const found = [];
|
|
95
|
+
const seen = new Set([stateFingerprint(base)]);
|
|
96
|
+
for (const c of candidates) {
|
|
97
|
+
const state = {id: 's' + (found.length + 1), label: describe(c), actions: [{click: c.key}]};
|
|
98
|
+
try { await open(state); } catch { continue; }
|
|
99
|
+
if (new URL(page.url()).origin !== origin) continue;
|
|
100
|
+
const sig = await page.evaluate(() => __ResponsiveLint.layoutSignature());
|
|
101
|
+
const change = layoutChange(base, sig);
|
|
102
|
+
if (change < 0.02) continue; // a click that moves nothing (or only changes the URL hash) is not a new state
|
|
103
|
+
const fp = stateFingerprint(sig);
|
|
104
|
+
if (seen.has(fp)) continue;
|
|
105
|
+
seen.add(fp);
|
|
106
|
+
found.push({...state, change: +change.toFixed(3), hash: sig.hash});
|
|
107
|
+
}
|
|
108
|
+
found.sort((a, b) => b.change - a.change);
|
|
109
|
+
states.push(...found.slice(0, maxStates).map((s, i) => ({...s, id: 's' + (i + 1)})));
|
|
110
|
+
log(`Found ${found.length} states; checking ${states.length - 1} plus the default.`);
|
|
111
|
+
}
|
|
112
|
+
// ---- width sweep in each state ----
|
|
113
|
+
const snapshots = [];
|
|
114
|
+
for (const state of states) {
|
|
115
|
+
try { await open(state, 1280); } catch (e) { log(`Could not reach state "${state.label}": ${e.message}`); continue; }
|
|
116
|
+
for (const w of widths) {
|
|
117
|
+
await page.setViewportSize({width: w, height});
|
|
118
|
+
await page.evaluate(() => scrollTo(0, 0));
|
|
119
|
+
await settle();
|
|
120
|
+
const snap = await page.evaluate(() => __ResponsiveLint.checkNow({revealSkipped: true}));
|
|
121
|
+
snapshots.push({state: {id: state.id, label: state.label}, width: w, findings: snap.findings, measures: snap.measures});
|
|
122
|
+
}
|
|
123
|
+
log(` ${state.label}: ${widths.length} widths`);
|
|
124
|
+
}
|
|
125
|
+
const result = analyze(snapshots, {only: options.only, skip: options.skip, minConfidence: options.minConfidence});
|
|
126
|
+
// ---- evidence screenshots ----
|
|
127
|
+
if (options.evidence) {
|
|
128
|
+
for (const f of result.findings.slice(0, options.evidence)) {
|
|
129
|
+
const inst = f.instances.find((i) => i.rect) || f.instances[0];
|
|
130
|
+
const state = states.find((s) => s.id === inst.state);
|
|
131
|
+
if (!state || !inst.rect) continue;
|
|
132
|
+
f.evidence = [];
|
|
133
|
+
const goodWidth = f.goodWidth || widths.find((w) => !f.widths.includes(w));
|
|
134
|
+
for (const [w, kind] of [[inst.width, 'bad'], [goodWidth, 'good']]) {
|
|
135
|
+
if (!w) continue;
|
|
136
|
+
try {
|
|
137
|
+
await open(state, w);
|
|
138
|
+
const r = kind === 'bad' ? inst.rect : await page.evaluate((key) => { const el = document.querySelector(key); if (!el) return null; const b = el.getBoundingClientRect(); return {left: b.left + scrollX, top: b.top + scrollY, right: b.right + scrollX, bottom: b.bottom + scrollY}; }, f.elements[0].key).catch(() => null);
|
|
139
|
+
if (!r) continue;
|
|
140
|
+
await page.evaluate(([key]) => { const el = document.querySelector(key); if (el) el.style.outline = '2px solid #e5484d'; }, [f.elements[0].key]).catch(() => {});
|
|
141
|
+
const pad = 40;
|
|
142
|
+
const clip = {x: Math.max(0, r.left - pad), y: Math.max(0, r.top - pad), width: Math.min(w, r.right - r.left + 2 * pad), height: Math.min(700, r.bottom - r.top + 2 * pad)};
|
|
143
|
+
if (clip.width < 4 || clip.height < 4) continue;
|
|
144
|
+
const png = await page.screenshot({clip, fullPage: true});
|
|
145
|
+
f.evidence.push({kind, width: w, png: png.toString('base64')});
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
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};
|
|
152
|
+
} finally {
|
|
153
|
+
await browser.close();
|
|
154
|
+
if (server) await server.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
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
|
+
|
|
160
|
+
function describe(c) {
|
|
161
|
+
const role = c.role === 'a' ? 'link' : c.role;
|
|
162
|
+
return `after clicking ${role} "${c.label}"`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The share of the default layout's boxes that moved, resized, appeared or disappeared. */
|
|
166
|
+
function layoutChange(a, b) {
|
|
167
|
+
const A = new Map(a.boxes.map((x) => [x[0], x])), B = new Map(b.boxes.map((x) => [x[0], x]));
|
|
168
|
+
let changed = 0;
|
|
169
|
+
for (const [k, x] of A) { const y = B.get(k); if (!y || Math.abs(x[1] - y[1]) > 4 || Math.abs(x[2] - y[2]) > 4 || Math.abs(x[3] - y[3]) > 4 || Math.abs(x[4] - y[4]) > 4) changed++; }
|
|
170
|
+
for (const k of B.keys()) if (!A.has(k)) changed++;
|
|
171
|
+
return changed / Math.max(1, A.size + B.size) * 2;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function stateFingerprint(sig) {
|
|
175
|
+
const big = sig.boxes.filter((x) => x[3] * x[4] > 20000).map((x) => [x[0], x[1] >> 4, x[2] >> 4, x[3] >> 4, x[4] >> 4].join(',')).sort().join(';');
|
|
176
|
+
return sig.hash + '|' + big;
|
|
177
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// A small static file server for checking a built folder.
|
|
2
|
+
import {createServer} from 'node:http';
|
|
3
|
+
import {readFile, stat} from 'node:fs/promises';
|
|
4
|
+
import {join, normalize, extname, resolve} from 'node:path';
|
|
5
|
+
|
|
6
|
+
const TYPES = {'.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json',
|
|
7
|
+
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp',
|
|
8
|
+
'.woff': 'font/woff', '.woff2': 'font/woff2', '.ttf': 'font/ttf', '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.wasm': 'application/wasm', '.zip': 'application/zip'};
|
|
9
|
+
|
|
10
|
+
export async function serveFolder(folder) {
|
|
11
|
+
const root = resolve(folder);
|
|
12
|
+
const server = createServer(async (req, res) => {
|
|
13
|
+
try {
|
|
14
|
+
let path = decodeURIComponent(new URL(req.url, 'http://x').pathname);
|
|
15
|
+
let file = normalize(join(root, path));
|
|
16
|
+
if (!file.startsWith(root)) { res.writeHead(403).end(); return; }
|
|
17
|
+
if ((await stat(file)).isDirectory()) file = join(file, 'index.html');
|
|
18
|
+
const body = await readFile(file);
|
|
19
|
+
res.writeHead(200, {'content-type': TYPES[extname(file).toLowerCase()] || 'application/octet-stream'}).end(body);
|
|
20
|
+
} catch { res.writeHead(404).end('not found'); }
|
|
21
|
+
});
|
|
22
|
+
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
|
23
|
+
return {url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise((r) => server.close(r))};
|
|
24
|
+
}
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// Turns many snapshots (one per state and width) into findings. Pure functions: no DOM, no Node APIs,
|
|
2
|
+
// so the command line and the script tag share them.
|
|
3
|
+
|
|
4
|
+
const REPO = 'https://github.com/prajwalsouza/ResponsiveLint/blob/main/';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Fix skills: one Agent Skill per group of related problems, so an agent loads only the guide it needs.
|
|
8
|
+
* Each finding names its skill by name, by path inside the package and by URL.
|
|
9
|
+
*/
|
|
10
|
+
export const FIX_SKILLS = {
|
|
11
|
+
'responsivelint-fix-overlap': {title: 'Fix text drawn over other text', rules: ['text-overlap']},
|
|
12
|
+
'responsivelint-fix-cramped-text': {title: 'Fix text that is squeezed or cut off', rules: ['squashed-text', 'clipped-text', 'width-outlier']},
|
|
13
|
+
'responsivelint-fix-overflow': {title: 'Fix a page that scrolls sideways', rules: ['page-overflow']},
|
|
14
|
+
'responsivelint-fix-controls': {title: 'Fix controls that are invisible or go missing', rules: ['hidden-control', 'disappears-in-band']},
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const skillFor = (rule) => {
|
|
18
|
+
const name = Object.keys(FIX_SKILLS).find((k) => FIX_SKILLS[k].rules.includes(rule)) || 'responsivelint-fix';
|
|
19
|
+
const file = `agents/skills/${name}/SKILL.md`;
|
|
20
|
+
return {name, file, url: REPO + file};
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// `tries` lists the usual causes, most likely first, each with the change that usually fixes it.
|
|
24
|
+
export const RULES = {
|
|
25
|
+
'text-overlap': {pack: 'text', severity: 'error', confidence: 'high', title: 'Text covers other text',
|
|
26
|
+
why: 'Two pieces of visible text are drawn in the same place, so neither can be read.',
|
|
27
|
+
tries: [
|
|
28
|
+
'An element with position: absolute or fixed sits on text that wraps at this width: place it with flex or grid instead, or move it off the text. Changing z-index only swaps which text is hidden.',
|
|
29
|
+
'A box has a fixed height, so its text spills out when it wraps: remove height, or use min-height.',
|
|
30
|
+
'A negative margin or a transform pulls one element onto another: remove it at these widths.',
|
|
31
|
+
'A toast, tooltip or badge is placed on a toolbar: place it above or beside the toolbar.',
|
|
32
|
+
]},
|
|
33
|
+
'squashed-text': {pack: 'text', severity: 'warning', confidence: 'high', title: 'Text squeezed to about one word per line',
|
|
34
|
+
why: 'The text has become so narrow that almost every word sits on its own line.',
|
|
35
|
+
tries: [
|
|
36
|
+
'A neighbour in the same row does not wrap (white-space: nowrap, flex-shrink: 0, an auto grid column full of buttons): let it wrap with flex-wrap: wrap, or put it on its own line with grid-template-columns: 1fr.',
|
|
37
|
+
'The row keeps two columns at a width where one fits better: stack them below this width with a media or container query.',
|
|
38
|
+
'Nothing stops the text from shrinking: give it min-width: 12em (or similar).',
|
|
39
|
+
]},
|
|
40
|
+
'clipped-text': {pack: 'text', severity: 'warning', confidence: 'medium', title: 'Text cut off by its box',
|
|
41
|
+
why: 'A box with overflow hidden is smaller than the text inside it, so part of the text is not shown.',
|
|
42
|
+
tries: [
|
|
43
|
+
'The box has a fixed width or height: remove it, or use min-width or min-height, so the box grows with its text.',
|
|
44
|
+
'The text is not allowed to wrap (white-space: nowrap): allow wrapping.',
|
|
45
|
+
'The cut is intended: add text-overflow: ellipsis and a title with the full text, so the finding becomes a note.',
|
|
46
|
+
]},
|
|
47
|
+
'page-overflow': {pack: 'overflow', severity: 'error', confidence: 'high', title: 'The page scrolls sideways',
|
|
48
|
+
why: 'Something is wider than the screen, so the whole page can be dragged sideways.',
|
|
49
|
+
tries: [
|
|
50
|
+
'The named element has a fixed width in pixels: use max-width: 100%, or a width in % or fr.',
|
|
51
|
+
'A row of controls or a long word or URL does not wrap: add flex-wrap: wrap, or overflow-wrap: anywhere for long words.',
|
|
52
|
+
'A wide table, code block or image: wrap it in a box with overflow-x: auto, or give images max-width: 100%.',
|
|
53
|
+
'Do not hide the problem with overflow-x: hidden on body or html; it cuts content off instead.',
|
|
54
|
+
]},
|
|
55
|
+
'hidden-control': {pack: 'visibility', severity: 'warning', confidence: 'medium', title: 'A control takes space but cannot be seen',
|
|
56
|
+
why: 'A button, link or tab is laid out, clickable and focusable, but fully transparent in its resting state, so people do not know it is there.',
|
|
57
|
+
tries: [
|
|
58
|
+
'It appears only on hover (opacity: 0 until :hover): show it at rest, perhaps quieter, because touch screens have no hover.',
|
|
59
|
+
'It should stay hidden until something happens: hide it properly with display: none, visibility: hidden or the hidden attribute until then, so it leaves the tab order too.',
|
|
60
|
+
'Keyboard users cannot find it: also show it on :focus-visible and :focus-within.',
|
|
61
|
+
]},
|
|
62
|
+
'width-outlier': {pack: 'sweep', severity: 'warning', confidence: 'high', title: 'Breaks only in a narrow band of widths',
|
|
63
|
+
why: 'This element looks normal at the widths on both sides, but changes sharply inside this band, which is how layout bugs between breakpoints show up.',
|
|
64
|
+
tries: [
|
|
65
|
+
'One part of the layout switches at a breakpoint before another does (a sidebar appears before the content stacks): line the two media queries up, or switch the content to a container query.',
|
|
66
|
+
'A neighbour stops wrapping inside the band and takes the width: let it wrap, or stack it below this width.',
|
|
67
|
+
'A fixed size takes over inside the band: replace it with min(), max() or clamp().',
|
|
68
|
+
]},
|
|
69
|
+
'disappears-in-band': {pack: 'sweep', severity: 'warning', confidence: 'medium', title: 'A control disappears in a narrow band of widths',
|
|
70
|
+
why: 'The control is visible at the widths on both sides but not inside this band.',
|
|
71
|
+
tries: [
|
|
72
|
+
'Two media queries hand over at different widths (one hides the desktop control, the other shows the mobile one a few pixels later): use the same width for both, or one query.',
|
|
73
|
+
'max-width and min-width both use the same number, so one pixel shows neither: use max-width: 767px with min-width: 768px, or a range query.',
|
|
74
|
+
'The control is pushed out of its row and clipped: let the row wrap.',
|
|
75
|
+
]},
|
|
76
|
+
};
|
|
77
|
+
for (const r of Object.values(RULES)) r.fix = r.tries[0];
|
|
78
|
+
|
|
79
|
+
export const PACKS = ['text', 'overlap', 'visibility', 'overflow', 'sweep'];
|
|
80
|
+
|
|
81
|
+
/** Merge sorted numbers into bands: [[from, to], ...] using the sweep step to decide adjacency. */
|
|
82
|
+
export function bands(widths, allWidths) {
|
|
83
|
+
const sorted = [...new Set(widths)].sort((a, b) => a - b);
|
|
84
|
+
const index = new Map(allWidths.map((w, i) => [w, i]));
|
|
85
|
+
const out = [];
|
|
86
|
+
for (const w of sorted) {
|
|
87
|
+
const last = out[out.length - 1];
|
|
88
|
+
if (last && index.get(w) === index.get(last[1]) + 1) last[1] = w; else out.push([w, w]);
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; };
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The self-comparison. For each element, compare its measurement at each width with the same element at
|
|
97
|
+
* neighbouring widths. A width is an outlier when the element departs sharply from its neighbours on both
|
|
98
|
+
* sides and the departure covers only a narrow band.
|
|
99
|
+
*/
|
|
100
|
+
export function sweepOutliers(series, allWidths, state) {
|
|
101
|
+
const findings = [];
|
|
102
|
+
for (const [key, byWidth] of series) {
|
|
103
|
+
const pts = allWidths.map((w) => byWidth.get(w));
|
|
104
|
+
if (pts.filter(Boolean).length < 5) continue;
|
|
105
|
+
const kind = pts.find(Boolean).kind;
|
|
106
|
+
const odd = new Array(pts.length).fill(false);
|
|
107
|
+
for (let i = 0; i < pts.length; i++) {
|
|
108
|
+
const p = pts[i];
|
|
109
|
+
const near = [];
|
|
110
|
+
for (let d = 1; d <= 3; d++) { if (pts[i - d]) near.push(pts[i - d]); if (pts[i + d]) near.push(pts[i + d]); }
|
|
111
|
+
if (near.length < 3) continue;
|
|
112
|
+
if (kind === 'text') {
|
|
113
|
+
if (!p) continue;
|
|
114
|
+
const ml = median(near.map((n) => n.lines)), mw = median(near.map((n) => n.words / Math.max(1, n.lines)));
|
|
115
|
+
const wpl = p.words / Math.max(1, p.lines);
|
|
116
|
+
// Sharply worse than its neighbours and also squashed in absolute terms: a column that is merely
|
|
117
|
+
// narrower (four readable words per line) is a design choice, not a break.
|
|
118
|
+
odd[i] = p.words >= 3 && p.lines >= Math.max(3, 2 * ml, ml + 2) && wpl <= 0.5 * mw && wpl <= 2.5;
|
|
119
|
+
} else if (kind === 'control') {
|
|
120
|
+
const visibleNear = near.filter((n) => n.visible).length;
|
|
121
|
+
odd[i] = (!p || !p.visible) && visibleNear >= near.length - 1;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
// Group odd widths into bands; keep only narrow bands with normal widths on both sides.
|
|
125
|
+
let i = 0;
|
|
126
|
+
while (i < pts.length) {
|
|
127
|
+
if (!odd[i]) { i++; continue; }
|
|
128
|
+
let j = i; while (j + 1 < pts.length && odd[j + 1]) j++;
|
|
129
|
+
const before = pts.slice(0, i).some((p, k) => p && !odd[k]);
|
|
130
|
+
const after = pts.slice(j + 1).some((p, k) => p && !odd[j + 1 + k]);
|
|
131
|
+
const narrow = j - i + 1 <= Math.max(1, Math.floor(0.35 * pts.length));
|
|
132
|
+
if (before && after && narrow) {
|
|
133
|
+
const bad = pts[i] || pts.slice(i, j + 1).find(Boolean);
|
|
134
|
+
const good = pts.slice(0, i).reverse().find(Boolean);
|
|
135
|
+
const rule = kind === 'text' ? 'width-outlier' : 'disappears-in-band';
|
|
136
|
+
findings.push({rule, keys: [key], state, widths: allWidths.slice(i, j + 1),
|
|
137
|
+
elements: [{key, text: (bad || good)?.text || ''}],
|
|
138
|
+
rect: bad?.rect || good?.rect, goodWidth: allWidths[allWidths.indexOf(allWidths[i]) - 1],
|
|
139
|
+
measured: kind === 'text' && bad ? {lines: bad.lines, wordsPerLine: +(bad.words / bad.lines).toFixed(1)} : {visible: false},
|
|
140
|
+
expected: kind === 'text' && good ? {lines: good.lines, wordsPerLine: +(good.words / Math.max(1, good.lines)).toFixed(1)} : {visible: true}});
|
|
141
|
+
}
|
|
142
|
+
i = j + 1;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return findings;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* snapshots: [{state: {id, label}, width, findings, measures}]
|
|
150
|
+
* options: {only, skip, minConfidence}
|
|
151
|
+
*/
|
|
152
|
+
export function analyze(snapshots, options = {}) {
|
|
153
|
+
const allWidths = [...new Set(snapshots.map((s) => s.width))].sort((a, b) => a - b);
|
|
154
|
+
const raw = [];
|
|
155
|
+
for (const s of snapshots) for (const f of s.findings) raw.push({...f, state: s.state, widths: [s.width]});
|
|
156
|
+
// Sweep comparison, state by state.
|
|
157
|
+
const states = new Map();
|
|
158
|
+
for (const s of snapshots) { if (!states.has(s.state.id)) states.set(s.state.id, {state: s.state, snaps: []}); states.get(s.state.id).snaps.push(s); }
|
|
159
|
+
for (const {state, snaps} of states.values()) {
|
|
160
|
+
if (snaps.length < 5) continue;
|
|
161
|
+
const series = new Map();
|
|
162
|
+
for (const s of snaps) for (const m of s.measures) {
|
|
163
|
+
if (!series.has(m.key + '|' + m.kind)) series.set(m.key + '|' + m.kind, new Map());
|
|
164
|
+
series.get(m.key + '|' + m.kind).set(s.width, m);
|
|
165
|
+
}
|
|
166
|
+
const keyed = new Map([...series].map(([k, v]) => [k.split('|')[0], v]));
|
|
167
|
+
raw.push(...sweepOutliers(keyed, snaps.map((s) => s.width).sort((a, b) => a - b), state));
|
|
168
|
+
}
|
|
169
|
+
// Group by rule and elements: one finding per root cause, listing every width and state.
|
|
170
|
+
const groups = new Map();
|
|
171
|
+
for (const f of raw) {
|
|
172
|
+
const id = f.rule + '|' + f.keys.join('+');
|
|
173
|
+
if (!groups.has(id)) groups.set(id, {...f, widths: [], states: [], instances: []});
|
|
174
|
+
const g = groups.get(id);
|
|
175
|
+
g.widths.push(...f.widths);
|
|
176
|
+
if (!g.states.some((s) => s.id === f.state.id)) g.states.push(f.state);
|
|
177
|
+
g.instances.push({state: f.state.id, width: f.widths[0], rect: f.rect, measured: f.measured});
|
|
178
|
+
}
|
|
179
|
+
mergeOverlaps(groups);
|
|
180
|
+
const order = {error: 0, warning: 1, info: 2};
|
|
181
|
+
const conf = {high: 0, medium: 1, low: 2};
|
|
182
|
+
const out = [];
|
|
183
|
+
for (const [id, g] of groups) {
|
|
184
|
+
const meta = RULES[g.rule];
|
|
185
|
+
if (options.only && !options.only.includes(meta.pack) && !options.only.includes(g.rule)) continue;
|
|
186
|
+
if (options.skip && (options.skip.includes(meta.pack) || options.skip.includes(g.rule))) continue;
|
|
187
|
+
let severity = meta.severity, confidence = meta.confidence;
|
|
188
|
+
if (g.rule === 'clipped-text' && g.ellipsis) { severity = 'info'; }
|
|
189
|
+
// A point finding at every width is usually by design; one that comes and goes is the bug.
|
|
190
|
+
const ws = [...new Set(g.widths)].sort((a, b) => a - b);
|
|
191
|
+
const tries = likelyTries(g, meta);
|
|
192
|
+
out.push({
|
|
193
|
+
id: fingerprint(id), rule: g.rule, pack: meta.pack, severity, confidence, title: meta.title,
|
|
194
|
+
elements: g.elements, widths: ws, bands: bands(ws, allWidths), everyWidth: ws.length === allWidths.length,
|
|
195
|
+
states: g.states.map((s) => s.label), measured: g.measured, expected: g.expected,
|
|
196
|
+
why: meta.why, fix: tries[0], tries, guide: REPO + 'docs/rules/' + g.rule + '.md',
|
|
197
|
+
skill: skillFor(g.rule),
|
|
198
|
+
suppress: `data-rl-ignore="${g.rule}"`, instances: g.instances.slice(0, 50), goodWidth: g.goodWidth,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
if (options.minConfidence) out.splice(0, out.length, ...out.filter((f) => conf[f.confidence] <= conf[options.minConfidence]));
|
|
202
|
+
out.sort((a, b) => order[a.severity] - order[b.severity] || conf[a.confidence] - conf[b.confidence] || b.widths.length - a.widths.length);
|
|
203
|
+
return {widths: allWidths, findings: out};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The usual causes, reordered by what was measured, so the first one is the most likely here. */
|
|
207
|
+
function likelyTries(g, meta) {
|
|
208
|
+
const t = [...meta.tries];
|
|
209
|
+
const first = (i, text) => { const [x] = t.splice(i, 1); t.unshift(text || x); };
|
|
210
|
+
const m = g.measured || {};
|
|
211
|
+
if (g.rule === 'text-overlap') {
|
|
212
|
+
const top = g.onTop;
|
|
213
|
+
if (top && ['absolute', 'fixed', 'sticky'].includes(top.position)) {
|
|
214
|
+
first(0, `The text on top, ${top.summary}, is taken out of the normal layout: place it with flex or grid instead, or move it so it does not sit on the text. Changing z-index only swaps which text is hidden. (${top.key})`);
|
|
215
|
+
} else if (top && top.position === 'static') first(1);
|
|
216
|
+
} else if (g.rule === 'clipped-text') {
|
|
217
|
+
if (g.ellipsis) first(2, 'The cut is marked with an ellipsis, so it looks intended: make sure a title or tooltip gives the full text.');
|
|
218
|
+
else if (m.contentWidth > m.boxWidth && !(m.contentHeight > m.boxHeight)) first(1);
|
|
219
|
+
}
|
|
220
|
+
return t;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One root cause, one finding: when the same element overlaps several siblings (each link in a nav over a
|
|
225
|
+
* title), report the element and the siblings' parent once, with every width and state.
|
|
226
|
+
*/
|
|
227
|
+
function mergeOverlaps(groups) {
|
|
228
|
+
const parent = (k) => k.includes('>') ? k.slice(0, k.lastIndexOf('>')) : k;
|
|
229
|
+
const byRoot = new Map();
|
|
230
|
+
for (const [id, g] of groups) {
|
|
231
|
+
if (g.rule !== 'text-overlap') continue;
|
|
232
|
+
const [a, b] = g.keys;
|
|
233
|
+
// Two candidate roots: element a with b's parent, or b with a's parent. Prefer the pairing shared by others.
|
|
234
|
+
for (const [shared, other] of [[a, b], [b, a]]) {
|
|
235
|
+
const root = shared + '~' + parent(other);
|
|
236
|
+
if (!byRoot.has(root)) byRoot.set(root, []);
|
|
237
|
+
byRoot.get(root).push({id, shared, other});
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const done = new Set();
|
|
241
|
+
for (const [root, list] of [...byRoot].sort((x, y) => y[1].length - x[1].length)) {
|
|
242
|
+
const live = list.filter((x) => !done.has(x.id) && groups.has(x.id));
|
|
243
|
+
if (live.length < 2) continue;
|
|
244
|
+
const first = groups.get(live[0].id);
|
|
245
|
+
const shared = live[0].shared, container = parent(live[0].other);
|
|
246
|
+
const sharedEl = first.elements.find((e) => e.key === shared);
|
|
247
|
+
const others = live.map((x) => groups.get(x.id).elements.find((e) => e.key === x.other)?.text).filter(Boolean);
|
|
248
|
+
const merged = {...first, keys: [shared, container], widths: [], states: [], instances: [],
|
|
249
|
+
elements: [sharedEl, {key: container, text: others.join(' · ').slice(0, 60)}]};
|
|
250
|
+
for (const x of live) {
|
|
251
|
+
const g = groups.get(x.id);
|
|
252
|
+
merged.widths.push(...g.widths);
|
|
253
|
+
for (const st of g.states) if (!merged.states.some((s) => s.id === st.id)) merged.states.push(st);
|
|
254
|
+
merged.instances.push(...g.instances);
|
|
255
|
+
groups.delete(x.id); done.add(x.id);
|
|
256
|
+
}
|
|
257
|
+
groups.set('text-overlap|' + shared + '+' + container, merged);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function fingerprint(s) {
|
|
262
|
+
let h = 2166136261;
|
|
263
|
+
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
|
|
264
|
+
return (h >>> 0).toString(36);
|
|
265
|
+
}
|
package/src/core/dom.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// DOM helpers that run inside the page. They read only standard signals (HTML elements, ARIA, computed
|
|
2
|
+
// style, boxes) and never interpret class names, so they work on any codebase in any language.
|
|
3
|
+
|
|
4
|
+
export const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'TITLE', 'OPTION', 'HEAD', 'META', 'LINK']);
|
|
5
|
+
|
|
6
|
+
export const INTERACTIVE_SELECTOR = [
|
|
7
|
+
'button', 'a[href]', 'summary', 'select', 'textarea',
|
|
8
|
+
'input:not([type=hidden])',
|
|
9
|
+
'[role=button]', '[role=tab]', '[role=link]', '[role=menuitem]', '[role=switch]', '[role=checkbox]', '[role=option]',
|
|
10
|
+
'[tabindex]:not([tabindex="-1"])',
|
|
11
|
+
].join(',');
|
|
12
|
+
|
|
13
|
+
/** A key that identifies an element by its position in the tree, anchored on the nearest id. */
|
|
14
|
+
export function elementKey(el) {
|
|
15
|
+
const parts = [];
|
|
16
|
+
for (let node = el; node && node.nodeType === 1 && node !== document.body && node !== document.documentElement; node = node.parentElement) {
|
|
17
|
+
if (node.id && /^[A-Za-z][\w-]*$/.test(node.id)) { parts.unshift('#' + node.id); return parts.join('>'); }
|
|
18
|
+
const parent = node.parentElement;
|
|
19
|
+
const index = parent ? Array.prototype.indexOf.call(parent.children, node) + 1 : 1;
|
|
20
|
+
parts.unshift(node.tagName.toLowerCase() + ':nth-child(' + index + ')');
|
|
21
|
+
}
|
|
22
|
+
parts.unshift('body');
|
|
23
|
+
return parts.join('>');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A CSS selector for an element key (keys are written so that they are valid selectors). */
|
|
27
|
+
export const keySelector = (key) => key;
|
|
28
|
+
|
|
29
|
+
export function ignoredRules(el) {
|
|
30
|
+
const out = new Set();
|
|
31
|
+
for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
|
|
32
|
+
const v = node.getAttribute && node.getAttribute('data-rl-ignore');
|
|
33
|
+
if (v != null) { if (v === '' || v === 'all') out.add('all'); else v.split(/[\s,]+/).forEach((r) => out.add(r)); }
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createContext() {
|
|
39
|
+
const style = new Map(), opacity = new Map(), clip = new Map(), fixed = new Map();
|
|
40
|
+
const cs = (el) => { let s = style.get(el); if (!s) { s = getComputedStyle(el); style.set(el, s); } return s; };
|
|
41
|
+
|
|
42
|
+
/** Opacity after multiplying every ancestor's opacity. */
|
|
43
|
+
function effectiveOpacity(el) {
|
|
44
|
+
if (!el || el.nodeType !== 1) return 1;
|
|
45
|
+
if (opacity.has(el)) return opacity.get(el);
|
|
46
|
+
const v = parseFloat(cs(el).opacity || '1') * effectiveOpacity(el.parentElement);
|
|
47
|
+
opacity.set(el, v); return v;
|
|
48
|
+
}
|
|
49
|
+
/** Whether the element or an ancestor is fixed or sticky (it moves with the viewport, by design). */
|
|
50
|
+
function isPinned(el) {
|
|
51
|
+
if (!el || el.nodeType !== 1) return false;
|
|
52
|
+
if (fixed.has(el)) return fixed.get(el);
|
|
53
|
+
const p = cs(el).position;
|
|
54
|
+
const v = p === 'fixed' || p === 'sticky' || isPinned(el.parentElement);
|
|
55
|
+
fixed.set(el, v); return v;
|
|
56
|
+
}
|
|
57
|
+
/** The part of the document an element's content can show in, after ancestors that clip overflow. */
|
|
58
|
+
function clipRect(el) {
|
|
59
|
+
if (!el || el.nodeType !== 1 || el === document.documentElement) return {left: -1e9, top: -1e9, right: 1e9, bottom: 1e9};
|
|
60
|
+
if (clip.has(el)) return clip.get(el);
|
|
61
|
+
const parent = clipRect(el.parentElement);
|
|
62
|
+
const s = cs(el);
|
|
63
|
+
let out = parent;
|
|
64
|
+
if (el !== document.body && (s.overflowX !== 'visible' || s.overflowY !== 'visible')) {
|
|
65
|
+
const r = el.getBoundingClientRect();
|
|
66
|
+
const box = {left: r.left + scrollX + el.clientLeft, top: r.top + scrollY + el.clientTop};
|
|
67
|
+
box.right = box.left + el.clientWidth; box.bottom = box.top + el.clientHeight;
|
|
68
|
+
out = {
|
|
69
|
+
left: s.overflowX === 'visible' ? parent.left : Math.max(parent.left, box.left),
|
|
70
|
+
right: s.overflowX === 'visible' ? parent.right : Math.min(parent.right, box.right),
|
|
71
|
+
top: s.overflowY === 'visible' ? parent.top : Math.max(parent.top, box.top),
|
|
72
|
+
bottom: s.overflowY === 'visible' ? parent.bottom : Math.min(parent.bottom, box.bottom),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
if (s.position === 'fixed') out = {left: -1e9, top: -1e9, right: 1e9, bottom: 1e9};
|
|
76
|
+
clip.set(el, out); return out;
|
|
77
|
+
}
|
|
78
|
+
function hidden(el) {
|
|
79
|
+
for (let node = el; node && node.nodeType === 1; node = node.parentElement) {
|
|
80
|
+
if (node.getAttribute('aria-hidden') === 'true' || node.hasAttribute('inert') || node.hidden) return true;
|
|
81
|
+
}
|
|
82
|
+
const s = cs(el);
|
|
83
|
+
return s.visibility !== 'visible' || s.display === 'none' || s.contentVisibility === 'hidden';
|
|
84
|
+
}
|
|
85
|
+
return {cs, effectiveOpacity, isPinned, clipRect, hidden};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export const intersect = (a, b) => ({left: Math.max(a.left, b.left), top: Math.max(a.top, b.top), right: Math.min(a.right, b.right), bottom: Math.min(a.bottom, b.bottom)});
|
|
89
|
+
export const area = (r) => Math.max(0, r.right - r.left) * Math.max(0, r.bottom - r.top);
|
|
90
|
+
|
|
91
|
+
/** Line boxes of an element's own text (not its children's), in document coordinates, cut to what can show. */
|
|
92
|
+
export function ownTextRects(el, ctx) {
|
|
93
|
+
const rects = [];
|
|
94
|
+
let text = '';
|
|
95
|
+
const clipTo = ctx.clipRect(el);
|
|
96
|
+
for (const node of el.childNodes) {
|
|
97
|
+
if (node.nodeType !== 3 || !node.textContent.trim()) continue;
|
|
98
|
+
text += node.textContent;
|
|
99
|
+
const range = document.createRange();
|
|
100
|
+
range.selectNodeContents(node);
|
|
101
|
+
for (const r of range.getClientRects()) {
|
|
102
|
+
if (r.width < 1 || r.height < 1) continue;
|
|
103
|
+
const doc = {left: r.left + scrollX, top: r.top + scrollY, right: r.right + scrollX, bottom: r.bottom + scrollY};
|
|
104
|
+
const cut = intersect(doc, clipTo);
|
|
105
|
+
if (area(cut) > 0) rects.push(cut);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return {text: text.replace(/\s+/g, ' ').trim(), rects};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Count lines from line boxes: boxes whose vertical centres are close belong to one line. */
|
|
112
|
+
export function countLines(rects) {
|
|
113
|
+
const centres = rects.map((r) => (r.top + r.bottom) / 2).sort((a, b) => a - b);
|
|
114
|
+
let lines = 0, last = -1e9;
|
|
115
|
+
for (const c of centres) { if (c - last > 3) { lines++; last = c; } }
|
|
116
|
+
return lines;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function label(el, text) {
|
|
120
|
+
const name = el.getAttribute('aria-label') || text || el.getAttribute('title') || el.getAttribute('alt') || '';
|
|
121
|
+
return name.replace(/\s+/g, ' ').trim().slice(0, 60);
|
|
122
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Entry for the injected build: the command line adds this to each page it checks.
|
|
2
|
+
import * as core from './index.js';
|
|
3
|
+
import {discoverCandidates, layoutSignature} from '../explore/page.js';
|
|
4
|
+
globalThis.__ResponsiveLint = {...core, discoverCandidates, layoutSignature};
|