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.
@@ -0,0 +1,241 @@
1
+ // One check of the page as it is now, at the current width and state. Runs inside the page.
2
+ // Returns point findings (wrong at this width on their own) and measurements that the sweep compares
3
+ // across widths and states.
4
+ import {SKIP_TAGS, INTERACTIVE_SELECTOR, elementKey, ignoredRules, createContext, ownTextRects, countLines, intersect, area, label} from './dom.js';
5
+
6
+ const MAX_TEXT = 4000, MAX_MEASURES = 2500;
7
+
8
+ /** Which 3D and XR frameworks the page uses. */
9
+ export function detectEnvironment() {
10
+ const w = globalThis;
11
+ const frameworks = [];
12
+ if (w.__THREE__) frameworks.push('three.js r' + w.__THREE__);
13
+ if (w.AFRAME) frameworks.push('A-Frame ' + (w.AFRAME.version || ''));
14
+ if (w.BABYLON) frameworks.push('Babylon.js ' + (w.BABYLON.Engine?.Version || ''));
15
+ if (w.pc && w.pc.version) frameworks.push('PlayCanvas ' + w.pc.version);
16
+ if ([...document.querySelectorAll('canvas')].some((c) => c.__r3f || c.parentElement?.__r3f)) frameworks.push('React Three Fiber');
17
+ const contexts = w.__rlContexts || {};
18
+ const canvases = document.querySelectorAll('canvas').length;
19
+ return {
20
+ frameworks: frameworks.map((f) => f.trim()),
21
+ webgl: (contexts.webgl || 0) + (contexts.webgl2 || 0), webgpu: contexts.webgpu || 0, canvases,
22
+ xr: !!(w.__rlXR) || (!!navigator.xr && frameworks.length > 0),
23
+ is3D: frameworks.length > 0 || (contexts.webgl || 0) + (contexts.webgl2 || 0) + (contexts.webgpu || 0) > 0,
24
+ };
25
+ }
26
+
27
+ export function checkNow(options = {}) {
28
+ // Sections skipped by content-visibility: auto report estimated positions for text that is not laid out
29
+ // there yet. The command line renders them for the measurement (the layout a reader sees on scrolling);
30
+ // the live script, which must not change the page, skips them instead.
31
+ let reveal = null;
32
+ if (options.revealSkipped) {
33
+ reveal = document.createElement('style');
34
+ reveal.textContent = '*{content-visibility:visible!important}';
35
+ document.head.append(reveal);
36
+ }
37
+ try { return measureAll(options); } finally { reveal?.remove(); }
38
+ }
39
+
40
+ function measureAll(options) {
41
+ const ctx = createContext();
42
+ const viewport = {width: innerWidth, height: innerHeight};
43
+ const findings = [];
44
+ const add = (f) => findings.push(f);
45
+ const texts = [];
46
+ const measures = [];
47
+
48
+ // ---- collect text blocks ----
49
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
50
+ for (let el = walker.currentNode; el; el = walker.nextNode()) {
51
+ if (texts.length >= MAX_TEXT) break;
52
+ if (!(el instanceof HTMLElement) || SKIP_TAGS.has(el.tagName)) continue;
53
+ if (el.closest('[data-rl-overlay]')) continue;
54
+ const {text, rects} = ownTextRects(el, ctx);
55
+ if (!text || !rects.length || ctx.hidden(el) || ctx.effectiveOpacity(el) < 0.05) continue;
56
+ if (!options.revealSkipped && el.checkVisibility && !el.checkVisibility({contentVisibilityAuto: true})) continue;
57
+ // Text clipped to a sliver (visually-hidden helpers such as screen-reader-only labels) is not visible text.
58
+ const box = el.getBoundingClientRect();
59
+ if (box.width <= 2 || box.height <= 2) continue;
60
+ const ignore = ignoredRules(el);
61
+ texts.push({el, key: elementKey(el), text, rects, ignore, pinned: ctx.isPinned(el)});
62
+ }
63
+
64
+ // ---- text-overlap: line boxes of different elements that cover each other ----
65
+ const boxes = [];
66
+ texts.forEach((t, i) => t.rects.forEach((r) => boxes.push({i, r})));
67
+ boxes.sort((a, b) => a.r.top - b.r.top);
68
+ const reported = new Set();
69
+ const overlaps = [];
70
+ let start = 0;
71
+ for (let a = 0; a < boxes.length; a++) {
72
+ const A = boxes[a];
73
+ while (start < a && boxes[start].r.bottom <= A.r.top) start++;
74
+ for (let b = start; b < a; b++) {
75
+ const B = boxes[b];
76
+ if (A.i === B.i || B.r.bottom <= A.r.top) continue;
77
+ const ta = texts[A.i], tb = texts[B.i];
78
+ if (ta.pinned !== tb.pinned) continue; // a pinned header over scrolling text is a scroll position, not a layout
79
+ if (ta.el.contains(tb.el) || tb.el.contains(ta.el)) continue;
80
+ if (ta.ignore.has('all') || ta.ignore.has('text-overlap') || tb.ignore.has('all') || tb.ignore.has('text-overlap')) continue;
81
+ const cut = intersect(A.r, B.r);
82
+ const smaller = Math.min(area(A.r), area(B.r));
83
+ const minH = Math.min(A.r.bottom - A.r.top, B.r.bottom - B.r.top);
84
+ if (area(cut) < 0.25 * smaller || cut.bottom - cut.top < 0.4 * minH) continue;
85
+ const pair = A.i < B.i ? A.i + ':' + B.i : B.i + ':' + A.i;
86
+ if (reported.has(pair)) continue;
87
+ reported.add(pair);
88
+ overlaps.push({ta, tb, cut, share: Math.round((100 * area(cut)) / smaller)});
89
+ }
90
+ }
91
+
92
+ // ---- confirm each overlap with the browser's own paint order ----
93
+ for (const o of confirmOverlaps(overlaps)) {
94
+ const {ta, tb, cut, share, top} = o;
95
+ add({rule: 'text-overlap', keys: [ta.key, tb.key].sort(),
96
+ elements: [{key: ta.key, text: ta.text.slice(0, 60)}, {key: tb.key, text: tb.text.slice(0, 60)}],
97
+ rect: cut, onTop: top, measured: {overlap: share + '% of the smaller line', ...(top ? {onTop: top.summary} : {})}});
98
+ }
99
+
100
+ // ---- squashed-text: about one word per line ----
101
+ for (const t of texts) {
102
+ const words = t.text.split(/\s+/).filter(Boolean).length;
103
+ const lines = countLines(t.rects);
104
+ if (measures.length < MAX_MEASURES && t.text.length >= 6) {
105
+ const left = Math.min(...t.rects.map((r) => r.left)), right = Math.max(...t.rects.map((r) => r.right));
106
+ const top = Math.min(...t.rects.map((r) => r.top)), bottom = Math.max(...t.rects.map((r) => r.bottom));
107
+ measures.push({key: t.key, kind: 'text', text: t.text.slice(0, 60), words, lines, w: Math.round(right - left), rect: {left, top, right, bottom}});
108
+ }
109
+ if (t.ignore.has('all') || t.ignore.has('squashed-text')) continue;
110
+ if (words >= 3 && lines >= 3 && words / lines <= 1.25 && t.text.length >= 15) {
111
+ const left = Math.min(...t.rects.map((r) => r.left)), right = Math.max(...t.rects.map((r) => r.right));
112
+ const top = Math.min(...t.rects.map((r) => r.top)), bottom = Math.max(...t.rects.map((r) => r.bottom));
113
+ add({rule: 'squashed-text', keys: [t.key], elements: [{key: t.key, text: t.text.slice(0, 60)}],
114
+ rect: {left, top, right, bottom}, measured: {width: Math.round(right - left), lines, words}});
115
+ }
116
+ }
117
+
118
+ // ---- clipped-text: a box that hides part of its own text ----
119
+ const seenClip = new Set();
120
+ for (const t of texts) {
121
+ for (let el = t.el; el && el !== document.body; el = el.parentElement) {
122
+ const s = ctx.cs(el);
123
+ const clipsX = s.overflowX === 'hidden' || s.overflowX === 'clip';
124
+ const clipsY = s.overflowY === 'hidden' || s.overflowY === 'clip';
125
+ if (!clipsX && !clipsY) continue;
126
+ if (seenClip.has(el)) break;
127
+ seenClip.add(el);
128
+ if (el.clientWidth < 2 || el.clientHeight < 2 || ctx.hidden(el)) break;
129
+ if (s.webkitLineClamp && s.webkitLineClamp !== 'none') break; // line clamping is a deliberate cut
130
+ const over = (clipsX && el.scrollWidth > el.clientWidth + 2) || (clipsY && el.scrollHeight > el.clientHeight + 2);
131
+ if (!over) break;
132
+ // The box hides content and holds text: part of that text cannot be read.
133
+ const r = el.getBoundingClientRect();
134
+ const edge = {left: r.left + scrollX, top: r.top + scrollY, right: r.left + scrollX + el.clientWidth, bottom: r.top + scrollY + el.clientHeight};
135
+ const ig = ignoredRules(el);
136
+ if (!ig.has('all') && !ig.has('clipped-text')) {
137
+ add({rule: 'clipped-text', keys: [elementKey(el)], elements: [{key: elementKey(el), text: label(el, t.text)}],
138
+ rect: edge, ellipsis: s.textOverflow === 'ellipsis',
139
+ measured: {contentWidth: el.scrollWidth, boxWidth: el.clientWidth, contentHeight: el.scrollHeight, boxHeight: el.clientHeight}});
140
+ }
141
+ break;
142
+ }
143
+ }
144
+
145
+ // ---- page-overflow: the page scrolls sideways ----
146
+ const docWidth = document.documentElement.scrollWidth;
147
+ if (docWidth > viewport.width + 1 && !ignoredRules(document.body).has('page-overflow')) {
148
+ const culprits = [];
149
+ const all = document.body.querySelectorAll('*');
150
+ for (const el of all) {
151
+ if (culprits.length >= 5) break;
152
+ if (!(el instanceof HTMLElement) || SKIP_TAGS.has(el.tagName) || ctx.hidden(el)) continue;
153
+ const r = el.getBoundingClientRect();
154
+ if (r.right + scrollX <= viewport.width + 1 || r.width === 0) continue;
155
+ const c = ctx.clipRect(el.parentElement);
156
+ if (c.right <= viewport.width + 1) continue; // an ancestor clips or scrolls it
157
+ const parent = el.parentElement.getBoundingClientRect();
158
+ if (parent.right + scrollX > viewport.width + 1 && el.parentElement !== document.body) continue; // report the outermost
159
+ culprits.push({key: elementKey(el), text: label(el, (el.textContent || '').trim()) || el.tagName.toLowerCase(), right: Math.round(r.right + scrollX)});
160
+ }
161
+ add({rule: 'page-overflow', keys: culprits.map((c) => c.key).sort().slice(0, 1), elements: culprits,
162
+ rect: null, measured: {pageWidth: docWidth, viewport: viewport.width, by: docWidth - viewport.width}});
163
+ }
164
+
165
+ // ---- hidden-control: a control that takes space but cannot be seen ----
166
+ for (const el of document.body.querySelectorAll(INTERACTIVE_SELECTOR)) {
167
+ if (!(el instanceof HTMLElement) || el.closest('[data-rl-overlay]')) continue;
168
+ const s = ctx.cs(el);
169
+ if (s.display === 'none' || el.disabled) continue;
170
+ if (el.closest('[aria-hidden=true],[inert],[hidden]')) continue;
171
+ const r = el.getBoundingClientRect();
172
+ if (r.width < 4 || r.height < 4) continue;
173
+ const box = {left: r.left + scrollX, top: r.top + scrollY, right: r.right + scrollX, bottom: r.bottom + scrollY};
174
+ if (area(intersect(box, ctx.clipRect(el.parentElement))) < 4) continue; // clipped away on purpose
175
+ const op = ctx.effectiveOpacity(el);
176
+ // visibility: hidden and pointer-events: none also make a control unclickable, so it is properly hidden.
177
+ // The trap is a control that can still be clicked or focused while nobody can see it.
178
+ const invisible = op < 0.1 && s.visibility === 'visible' && s.pointerEvents !== 'none';
179
+ if (measures.length < MAX_MEASURES + 500) measures.push({key: elementKey(el), kind: 'control', text: label(el, (el.textContent || '').trim()), visible: !invisible, rect: box});
180
+ if (!invisible) continue;
181
+ // A native checkbox or radio hidden behind a styled label is a common, deliberate pattern.
182
+ if (el.matches('input[type=checkbox],input[type=radio],input[type=file],input[type=range]') && (el.labels?.length || el.closest('label'))) continue;
183
+ const ig = ignoredRules(el);
184
+ if (ig.has('all') || ig.has('hidden-control')) continue;
185
+ add({rule: 'hidden-control', keys: [elementKey(el)], elements: [{key: elementKey(el), text: label(el, (el.textContent || '').trim()) || el.tagName.toLowerCase()}],
186
+ rect: box, measured: {opacity: +op.toFixed(2)}});
187
+ }
188
+
189
+ return {width: viewport.width, height: viewport.height, env: detectEnvironment(), findings, measures};
190
+ }
191
+
192
+ /**
193
+ * Ask the browser what is painted at the centre of each overlap, after z-index, positioning and stacking
194
+ * contexts. An overlap where neither text is painted (something opaque covers both, or the text is not
195
+ * really laid out there) is not visible and is dropped. For the rest, record which element is on top and
196
+ * why, which is usually the fix.
197
+ */
198
+ function confirmOverlaps(list) {
199
+ if (!list.length) return [];
200
+ // Hit testing skips pointer-events: none (common on toasts and overlays), so allow it for the check.
201
+ const allow = document.createElement('style');
202
+ allow.textContent = '*{pointer-events:auto!important}';
203
+ document.head.append(allow);
204
+ const sx = scrollX, sy = scrollY;
205
+ const out = [];
206
+ try {
207
+ for (const o of list) {
208
+ const cx = (o.cut.left + o.cut.right) / 2, cy = (o.cut.top + o.cut.bottom) / 2;
209
+ const pinned = o.ta.pinned && o.tb.pinned;
210
+ let vx = cx - scrollX, vy = cy - scrollY;
211
+ if (!pinned && (vx < 0 || vy < 0 || vx >= innerWidth || vy >= innerHeight)) {
212
+ window.scrollTo({left: Math.max(0, cx - innerWidth / 2), top: Math.max(0, cy - innerHeight / 2), behavior: 'instant'});
213
+ vx = cx - scrollX; vy = cy - scrollY;
214
+ }
215
+ if (pinned) { vx = cx - sx; vy = cy - sy; }
216
+ const stack = document.elementsFromPoint(vx, vy);
217
+ const at = (el) => stack.findIndex((s) => s === el || el.contains(s));
218
+ const ia = at(o.ta.el), ib = at(o.tb.el);
219
+ if (ia < 0 && ib < 0) continue; // not painted here: not a visible overlap
220
+ const topEl = ia < 0 ? o.tb.el : ib < 0 ? o.ta.el : ia <= ib ? o.ta.el : o.tb.el;
221
+ out.push({...o, top: describeLayer(topEl)});
222
+ }
223
+ } finally {
224
+ allow.remove();
225
+ if (scrollX !== sx || scrollY !== sy) window.scrollTo({left: sx, top: sy, behavior: 'instant'});
226
+ }
227
+ return out;
228
+ }
229
+
230
+ /** Which element is painted on top, and the positioning that puts it there. */
231
+ function describeLayer(el) {
232
+ let layer = el;
233
+ for (let n = el; n && n !== document.body; n = n.parentElement) {
234
+ const s = getComputedStyle(n);
235
+ if (s.position !== 'static' || s.zIndex !== 'auto' || s.transform !== 'none') { layer = n; break; }
236
+ }
237
+ const s = getComputedStyle(layer);
238
+ const parts = [s.position !== 'static' ? 'position: ' + s.position : '', s.zIndex !== 'auto' ? 'z-index: ' + s.zIndex : '', s.transform !== 'none' ? 'transformed' : ''].filter(Boolean);
239
+ const text = (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 40);
240
+ return {key: elementKey(layer), text, position: s.position, zIndex: s.zIndex, summary: `"${text}"` + (parts.length ? ' (' + parts.join(', ') + ')' : ' (normal flow)')};
241
+ }
@@ -0,0 +1,63 @@
1
+ // In-page helpers for state discovery. They find what a reader can click, using standard signals only,
2
+ // and describe the layout so that the command line can tell whether a click changed it.
3
+ import {INTERACTIVE_SELECTOR, elementKey, createContext, label} from '../core/dom.js';
4
+
5
+ const DANGEROUS = /\b(delete|remove|destroy|erase|log ?out|sign ?out|unsubscribe|pay|purchase|buy|checkout|submit|send|publish|reset)\b/i;
6
+
7
+ /** Candidates for interaction, one representative per group of structurally identical siblings. */
8
+ export function discoverCandidates({limit = 60} = {}) {
9
+ const ctx = createContext();
10
+ const found = new Set();
11
+ const nodes = [...document.querySelectorAll(INTERACTIVE_SELECTOR)];
12
+ // Elements that look clickable without saying so: a pointer cursor and no interactive ancestor.
13
+ for (const el of document.body.querySelectorAll('div,span,li,img,svg,label,h1,h2,h3,h4,p')) {
14
+ if (nodes.length > 4000) break;
15
+ if (el.closest(INTERACTIVE_SELECTOR)) continue;
16
+ if (getComputedStyle(el).cursor === 'pointer' && !(el.parentElement && getComputedStyle(el.parentElement).cursor === 'pointer')) nodes.push(el);
17
+ }
18
+ const groups = new Map();
19
+ for (const el of nodes) {
20
+ if (!(el instanceof Element) || found.has(el) || el.closest('[data-rl-overlay]')) continue;
21
+ found.add(el);
22
+ if (el.closest('[data-rl-never]') || el.matches('[disabled],[aria-disabled=true]')) continue;
23
+ if (el.matches('input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]),textarea,select')) continue; // never type
24
+ if (el.matches('[type=submit],button:not([type])') && el.closest('form')) continue; // never submit
25
+ const r = el.getBoundingClientRect();
26
+ if (r.width < 4 || r.height < 4 || ctx.hidden(el)) continue;
27
+ const name = label(el, (el.textContent || '').trim());
28
+ if (DANGEROUS.test(name)) continue;
29
+ let href = null;
30
+ if (el.matches('a[href]')) {
31
+ const url = new URL(el.getAttribute('href'), location.href);
32
+ if (url.origin !== location.origin || el.hasAttribute('download') || el.target === '_blank') continue;
33
+ if (url.pathname !== location.pathname) continue; // other pages are listed as pages, not states
34
+ href = url.hash;
35
+ }
36
+ // Structural signature: tag, role, and the parent's tag and child count. Siblings that share it are
37
+ // usually the same control repeated (list items, sentences), so one of them stands for the group.
38
+ const sig = [el.tagName, el.getAttribute('role') || '', el.parentElement?.tagName || '', el.className && typeof el.className === 'string' ? el.className.split(/\s+/).sort().join('.') : ''].join('|');
39
+ if (!groups.has(sig)) groups.set(sig, []);
40
+ groups.get(sig).push({key: elementKey(el), label: name || el.tagName.toLowerCase(), role: el.getAttribute('role') || el.tagName.toLowerCase(),
41
+ expanded: el.getAttribute('aria-expanded'), href, area: Math.round(r.width * r.height), top: Math.round(r.top + scrollY)});
42
+ }
43
+ const out = [];
44
+ for (const list of groups.values()) out.push({...list[0], repeats: list.length});
45
+ // Native and ARIA toggles first, then the rest by how high on the page they sit.
46
+ out.sort((a, b) => (b.expanded != null) - (a.expanded != null) || a.top - b.top);
47
+ return out.slice(0, limit);
48
+ }
49
+
50
+ /** A compact description of the visible layout, used to measure how much an action changed. */
51
+ export function layoutSignature({max = 2500} = {}) {
52
+ const out = [];
53
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
54
+ for (let el = walker.currentNode; el && out.length < max; el = walker.nextNode()) {
55
+ if (!(el instanceof HTMLElement) || el.closest('[data-rl-overlay]')) continue;
56
+ const r = el.getBoundingClientRect();
57
+ if (r.width * r.height < 400) continue;
58
+ const s = getComputedStyle(el);
59
+ if (s.visibility !== 'visible' || +s.opacity < 0.05) continue;
60
+ out.push([elementKey(el), Math.round(r.left + scrollX), Math.round(r.top + scrollY), Math.round(r.width), Math.round(r.height)]);
61
+ }
62
+ return {url: location.href, hash: location.hash, boxes: out};
63
+ }
@@ -0,0 +1,106 @@
1
+ // Icon style measures for monochrome SVG icons, computed from the rendered shape (not the file).
2
+ // Each icon is drawn at the same scale it uses on screen (its viewBox fitted into a square), then measured:
3
+ // ink share of the square covered by the icon (visual weight)
4
+ // stroke typical line thickness from a distance transform, as a share of the square
5
+ // evenness how much local line thickness varies (low for icons drawn with one even stroke)
6
+ // holes share of the icon's silhouette that is enclosed empty space (outline icons have more)
7
+ // size share of the square taken by the icon's bounding box (optical size and padding)
8
+ // detail outline length squared ÷ area (more parts and corners give a higher number)
9
+ export function measureIcon(svg, N = 160) {
10
+ const vb = (svg.getAttribute('viewBox') || '0 0 24 24').split(/[\s,]+/).map(Number);
11
+ const [x0, y0, w, h] = vb;
12
+ const c = document.createElement('canvas'); c.width = c.height = N;
13
+ const g = c.getContext('2d');
14
+ const s = N / Math.max(w, h);
15
+ g.translate((N - w * s) / 2, (N - h * s) / 2); g.scale(s, s); g.translate(-x0, -y0);
16
+ for (const el of svg.querySelectorAll('path,circle,rect,polygon,polyline,ellipse,line')) {
17
+ const d = el.tagName === 'path' ? el.getAttribute('d') : null;
18
+ const cs = getComputedStyle(el);
19
+ const p = d ? new Path2D(d) : null;
20
+ if (!p) continue;
21
+ if (cs.fill !== 'none') { g.fillStyle = '#000'; g.fill(p, el.getAttribute('fill-rule') || cs.fillRule || 'nonzero'); }
22
+ if (cs.stroke && cs.stroke !== 'none') { g.lineWidth = parseFloat(cs.strokeWidth) || 1; g.strokeStyle = '#000'; g.stroke(p); }
23
+ }
24
+ return maskMetrics(g.getImageData(0, 0, N, N).data, N);
25
+ }
26
+
27
+ /** Draw one character in a font at a fixed size, so strokes are comparable across letters. */
28
+ export function measureGlyph(char, font, N = 400) {
29
+ const c = document.createElement('canvas'); c.width = c.height = N;
30
+ const g = c.getContext('2d');
31
+ g.font = font; g.textAlign = 'center'; g.textBaseline = 'alphabetic'; g.fillStyle = '#000';
32
+ g.fillText(char, N / 2, N * 0.78);
33
+ return maskMetrics(g.getImageData(0, 0, N, N).data, N);
34
+ }
35
+
36
+ /** Measures of a black shape on a square canvas. */
37
+ export function maskMetrics(px, N) {
38
+ const ink = new Uint8Array(N * N);
39
+ let area = 0, minx = N, miny = N, maxx = -1, maxy = -1;
40
+ for (let i = 0; i < N * N; i++) if (px[i * 4 + 3] > 127) { ink[i] = 1; area++; const x = i % N, y = (i / N) | 0; if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; }
41
+ if (!area) return null;
42
+ let edge = 0;
43
+ for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
44
+ const i = y * N + x; if (!ink[i]) continue;
45
+ if (x === 0 || !ink[i - 1]) edge++; if (x === N - 1 || !ink[i + 1]) edge++;
46
+ if (y === 0 || !ink[i - N]) edge++; if (y === N - 1 || !ink[i + N]) edge++;
47
+ }
48
+ const seen = new Uint8Array(N * N); const q = [];
49
+ for (let k = 0; k < N; k++) for (const i of [k, (N - 1) * N + k, k * N, k * N + N - 1]) if (!ink[i] && !seen[i]) { seen[i] = 1; q.push(i); }
50
+ while (q.length) { const i = q.pop(); const x = i % N; for (const j of [i - 1, i + 1, i - N, i + N]) { if (j < 0 || j >= N * N || seen[j] || ink[j]) continue; if ((j === i - 1 && x === 0) || (j === i + 1 && x === N - 1)) continue; seen[j] = 1; q.push(j); } }
51
+ let holes = 0; for (let i = 0; i < N * N; i++) if (!ink[i] && !seen[i]) holes++;
52
+ const {width, spread} = strokeProfile(ink, N);
53
+ return {
54
+ ink: +(area / (N * N)).toFixed(3),
55
+ stroke: +(width / N).toFixed(4), // typical line thickness (distance transform), share of the square
56
+ evenness: +spread.toFixed(2), // spread of local thickness ÷ typical thickness: low = even lines
57
+ holes: +(holes / (holes + area)).toFixed(3),
58
+ size: +(((maxx - minx + 1) * (maxy - miny + 1)) / (N * N)).toFixed(3),
59
+ detail: +((edge * edge) / area / 100).toFixed(2),
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Local line thickness. A chamfer distance transform gives each ink pixel its distance to the background;
65
+ * pixels on the centre line of a stroke are local maxima, and twice their distance is the stroke's width
66
+ * there. The median is the typical width; the interquartile range divided by it says how even the lines are.
67
+ */
68
+ export function strokeProfile(ink, N) {
69
+ const INF = 1e9, d = new Float32Array(N * N);
70
+ for (let i = 0; i < N * N; i++) d[i] = ink[i] ? INF : 0;
71
+ const a = 1, b = Math.SQRT2;
72
+ for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) { const i = y * N + x; if (!d[i]) continue;
73
+ let v = d[i]; if (x > 0) v = Math.min(v, d[i - 1] + a); else v = Math.min(v, a); if (y > 0) { v = Math.min(v, d[i - N] + a); if (x > 0) v = Math.min(v, d[i - N - 1] + b); if (x < N - 1) v = Math.min(v, d[i - N + 1] + b); } else v = Math.min(v, a); d[i] = v; }
74
+ for (let y = N - 1; y >= 0; y--) for (let x = N - 1; x >= 0; x--) { const i = y * N + x; if (!d[i]) continue;
75
+ let v = d[i]; if (x < N - 1) v = Math.min(v, d[i + 1] + a); if (y < N - 1) { v = Math.min(v, d[i + N] + a); if (x < N - 1) v = Math.min(v, d[i + N + 1] + b); if (x > 0) v = Math.min(v, d[i + N - 1] + b); } d[i] = v; }
76
+ const ridge = [];
77
+ for (let y = 1; y < N - 1; y++) for (let x = 1; x < N - 1; x++) { const i = y * N + x; const v = d[i]; if (v < 1) continue;
78
+ if (v >= d[i - 1] && v >= d[i + 1] && v >= d[i - N] && v >= d[i + N] && v >= d[i - N - 1] && v >= d[i - N + 1] && v >= d[i + N - 1] && v >= d[i + N + 1]) ridge.push(2 * v); }
79
+ if (!ridge.length) return {width: 0, spread: 0};
80
+ ridge.sort((x, y) => x - y);
81
+ const at = (p) => ridge[Math.min(ridge.length - 1, Math.floor(p * ridge.length))];
82
+ const width = at(0.5);
83
+ return {width, spread: (at(0.75) - at(0.25)) / width};
84
+ }
85
+
86
+ /**
87
+ * The odd ones out in a set. Small sets make statistics fragile, so an icon is flagged on a measure when it is
88
+ * far from the set's median in robust units (with a minimum spread per measure) and also differs from the
89
+ * median by a clear ratio, which is what a designer notices.
90
+ */
91
+ // Style measures say how a shape is drawn; shape measures say what it depicts (a magnifier has a hole, an "l"
92
+ // is narrow). Only style measures decide whether an icon or letter belongs to a set.
93
+ export const STYLE = ['stroke'];
94
+ export const SHAPE = ['ink', 'evenness', 'holes', 'size', 'detail'];
95
+
96
+ export function iconOutliers(items, {limit = 3, ratio = 0.88, keys = STYLE} = {}) {
97
+ const floor = {ink: 0.03, stroke: 0.002, evenness: 0.1, holes: 0.08, size: 0.06, detail: 0.2};
98
+ const med = (a) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };
99
+ const stats = Object.fromEntries(keys.map((k) => { const v = items.map((i) => i.m[k]); const m = med(v); const mad = Math.max(med(v.map((x) => Math.abs(x - m))) * 1.4826, floor[k]); return [k, {m, mad}]; }));
100
+ return items.map((i) => {
101
+ const z = Object.fromEntries(keys.map((k) => [k, +((i.m[k] - stats[k].m) / stats[k].mad).toFixed(1)]));
102
+ const rel = Object.fromEntries(keys.map((k) => [k, stats[k].m ? +(i.m[k] / stats[k].m).toFixed(2) : 1]));
103
+ const off = keys.filter((k) => Math.abs(z[k]) > limit && (k === 'holes' ? Math.abs(i.m[k] - stats[k].m) > 0.2 : rel[k] < ratio || rel[k] > 1 / ratio));
104
+ return {...i, z, rel, off};
105
+ });
106
+ }
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // Node entry: import {check} from 'responsivelint'
2
+ export {check} from './cli/run.js';
3
+ export {analyze, RULES, PACKS, FIX_SKILLS, skillFor} from './core/analyze.js';
4
+ export {terminalReport, htmlReport} from './cli/report.js';