@realadvisor-sites/kit-core 0.4.1 → 0.5.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/AGENTS.md +158 -148
- package/CHANGELOG.md +91 -0
- package/DESIGN.md +70 -9
- package/README.md +3 -3
- package/bin/sites-kit.mjs +5 -1
- package/lib/render-error.ts +6 -0
- package/package.json +3 -2
- package/tools/critic-calibrate.mjs +95 -0
- package/tools/critic.mjs +397 -0
- package/tools/screenshot.mjs +198 -1
- package/tools/search-map-test.mjs +8 -3
- package/tools/use-fixture.mjs +13 -8
package/tools/critic.mjs
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Collect what the taste critic needs to judge one page (TASTE.md section 4,
|
|
4
|
+
* critic/CRITIC.md), so a separate model can review it from files alone.
|
|
5
|
+
*
|
|
6
|
+
* pnpm kit critic # the home page, starts `pnpm dev` if needed
|
|
7
|
+
* pnpm kit critic -- /listings --url http://localhost:4321
|
|
8
|
+
* pnpm kit critic -- / --anchor http://localhost:4799 # the chosen example, running
|
|
9
|
+
* pnpm kit critic -- / --anchor-shots a@1440.png,a@390.png # or its screenshots
|
|
10
|
+
* pnpm kit critic -- / --anchor ... --previous critic-round1.md # round 2: the critic checks its fixes
|
|
11
|
+
*
|
|
12
|
+
* Output (default critic-input/):
|
|
13
|
+
* INDEX.md what each file is, in reading order (the critic starts here)
|
|
14
|
+
* summary.json measured facts: taste lines, fonts by role, colours, logo, images, sections
|
|
15
|
+
* page@1440.png, page@390.png full page
|
|
16
|
+
* page-first@1440.png, page-first@390.png first screen only
|
|
17
|
+
* anchor@1440.png, anchor@390.png, anchor-first@*.png the anchor (when given)
|
|
18
|
+
* logo.<ext>, type-vs-logo.png the logo file, and the logo beside every font family in use
|
|
19
|
+
* BRIEF.md, DESIGN-NOTES.md copied from the site root when present
|
|
20
|
+
* CRITIC.md the critic's instructions (from the kit)
|
|
21
|
+
*/
|
|
22
|
+
import { chromium } from 'playwright';
|
|
23
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
24
|
+
import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
25
|
+
import { existsSync } from 'node:fs';
|
|
26
|
+
import { basename, extname, join, resolve } from 'node:path';
|
|
27
|
+
import { fileURLToPath } from 'node:url';
|
|
28
|
+
|
|
29
|
+
const args = process.argv.slice(2).filter((a) => a !== '--');
|
|
30
|
+
const opt = (name, def) => {
|
|
31
|
+
const i = args.indexOf(`--${name}`);
|
|
32
|
+
if (i === -1) return def;
|
|
33
|
+
const v = args[i + 1];
|
|
34
|
+
args.splice(i, 2);
|
|
35
|
+
return v;
|
|
36
|
+
};
|
|
37
|
+
const BASE = opt('url', `http://localhost:${process.env.PORT ?? 4321}`).replace(/\/$/, '');
|
|
38
|
+
const OUT = resolve(opt('out', 'critic-input'));
|
|
39
|
+
const ANCHOR = opt('anchor', '')?.replace(/\/$/, '');
|
|
40
|
+
const ANCHOR_PATH = opt('anchor-path', '/');
|
|
41
|
+
const ANCHOR_SHOTS = opt('anchor-shots', '');
|
|
42
|
+
const PREVIOUS = opt('previous', '');
|
|
43
|
+
const INJECT = opt('inject', '');
|
|
44
|
+
const injectCss = INJECT ? await readFile(INJECT, 'utf8') : '';
|
|
45
|
+
const PATH = args.find((a) => a.startsWith('/')) ?? '/';
|
|
46
|
+
const WIDTHS = [
|
|
47
|
+
{ name: '1440', width: 1440, height: 900 },
|
|
48
|
+
{ name: '390', width: 390, height: 844, isMobile: true, hasTouch: true, deviceScaleFactor: 2 },
|
|
49
|
+
];
|
|
50
|
+
const here = (p) => fileURLToPath(new URL(p, import.meta.url));
|
|
51
|
+
|
|
52
|
+
async function up(url) {
|
|
53
|
+
try {
|
|
54
|
+
return (await fetch(url, { signal: AbortSignal.timeout(2000) })).status < 500;
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let server;
|
|
61
|
+
if (!(await up(BASE))) {
|
|
62
|
+
console.log(`Nothing on ${BASE}, starting pnpm dev…`);
|
|
63
|
+
server = spawn('pnpm', ['dev'], { stdio: 'ignore', detached: true });
|
|
64
|
+
for (let i = 0; i < 60 && !(await up(BASE)); i++) await new Promise((r) => setTimeout(r, 1000));
|
|
65
|
+
if (!(await up(BASE))) {
|
|
66
|
+
console.error('Dev server did not start. Run `pnpm dev` and read its errors.');
|
|
67
|
+
process.exit(2);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const stop = () => {
|
|
71
|
+
try {
|
|
72
|
+
if (server) process.kill(-server.pid);
|
|
73
|
+
} catch {}
|
|
74
|
+
};
|
|
75
|
+
process.on('exit', stop);
|
|
76
|
+
|
|
77
|
+
await rm(OUT, { recursive: true, force: true });
|
|
78
|
+
await mkdir(OUT, { recursive: true });
|
|
79
|
+
|
|
80
|
+
// 1. The measured checks: the screenshot tool on this one path (its taste: lines and problems).
|
|
81
|
+
const shotDir = join(OUT, '.screenshot');
|
|
82
|
+
spawnSync(process.execPath, [here('./screenshot.mjs'), '--url', BASE, '--out', shotDir, ...(INJECT ? ['--inject', INJECT] : []), PATH], { stdio: 'ignore' });
|
|
83
|
+
let problems = [];
|
|
84
|
+
try {
|
|
85
|
+
problems = JSON.parse(await readFile(join(shotDir, 'report.json'), 'utf8'))[0]?.problems ?? [];
|
|
86
|
+
} catch {
|
|
87
|
+
problems = ['(the screenshot tool did not write a report: run `pnpm screenshot` and read its errors)'];
|
|
88
|
+
}
|
|
89
|
+
await rm(shotDir, { recursive: true, force: true });
|
|
90
|
+
|
|
91
|
+
const browser = await chromium.launch().catch(() => chromium.launch({ channel: 'chrome' }));
|
|
92
|
+
|
|
93
|
+
/** Load a page fully: lazy images scrolled in, fonts ready. */
|
|
94
|
+
async function open(ctx, url, css = '') {
|
|
95
|
+
const page = await ctx.newPage();
|
|
96
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
|
|
97
|
+
await page.waitForLoadState('load', { timeout: 10000 }).catch(() => {});
|
|
98
|
+
if (css) await page.addStyleTag({ content: css }).catch(() => {});
|
|
99
|
+
await page.evaluate(async () => {
|
|
100
|
+
for (let y = 0; y < document.body.scrollHeight; y += 600) {
|
|
101
|
+
window.scrollTo(0, y);
|
|
102
|
+
await new Promise((r) => setTimeout(r, 60));
|
|
103
|
+
}
|
|
104
|
+
window.scrollTo(0, 0);
|
|
105
|
+
await document.fonts.ready;
|
|
106
|
+
// Real file pixels (srcset descriptors lie when the image CDN never enlarges).
|
|
107
|
+
await Promise.all([...document.images].map((img) => new Promise((done) => {
|
|
108
|
+
const src = img.currentSrc || img.src;
|
|
109
|
+
if (!src) return done();
|
|
110
|
+
const probe = new Image();
|
|
111
|
+
probe.onload = () => { img.dataset.realW = String(probe.naturalWidth); img.dataset.realH = String(probe.naturalHeight); done(); };
|
|
112
|
+
probe.onerror = () => done();
|
|
113
|
+
probe.src = src;
|
|
114
|
+
setTimeout(done, 5000);
|
|
115
|
+
})));
|
|
116
|
+
});
|
|
117
|
+
await page.waitForTimeout(300);
|
|
118
|
+
return page;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function shots(url, prefix, css = '') {
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const vp of WIDTHS) {
|
|
124
|
+
const ctx = await browser.newContext({ viewport: { width: vp.width, height: vp.height }, isMobile: vp.isMobile, hasTouch: vp.hasTouch, deviceScaleFactor: vp.deviceScaleFactor ?? 1 });
|
|
125
|
+
try {
|
|
126
|
+
const page = await open(ctx, url, css);
|
|
127
|
+
const full = `${prefix}@${vp.name}.png`;
|
|
128
|
+
const first = `${prefix}-first@${vp.name}.png`;
|
|
129
|
+
const h = await page.evaluate(() => document.documentElement.scrollHeight);
|
|
130
|
+
await page.screenshot({ path: join(OUT, full), fullPage: true, clip: { x: 0, y: 0, width: vp.width, height: Math.min(h, vp.height * 12) } });
|
|
131
|
+
await page.screenshot({ path: join(OUT, first) });
|
|
132
|
+
out[vp.name] = { page, ctx, full, first };
|
|
133
|
+
} catch (e) {
|
|
134
|
+
await ctx.close();
|
|
135
|
+
throw e;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Everything measurable about taste on one loaded page. Runs in the browser. */
|
|
142
|
+
function measure() {
|
|
143
|
+
const vw = innerWidth, vh = innerHeight;
|
|
144
|
+
const rgb = (c) => (c.match(/[\d.]+/g) || []).map(Number);
|
|
145
|
+
const hex = (c) => { const v = rgb(c); return v.length >= 3 ? '#' + v.slice(0, 3).map((n) => Math.round(n).toString(16).padStart(2, '0')).join('') : c; };
|
|
146
|
+
// The ground an element sits on: its own background or the first opaque one above it.
|
|
147
|
+
const groundOf = (el) => {
|
|
148
|
+
for (let e = el; e; e = e.parentElement) {
|
|
149
|
+
const v = rgb(getComputedStyle(e).backgroundColor);
|
|
150
|
+
if (v.length >= 3 && (v.length < 4 || v[3] > 0.5)) return hex(getComputedStyle(e).backgroundColor);
|
|
151
|
+
}
|
|
152
|
+
return '#ffffff';
|
|
153
|
+
};
|
|
154
|
+
// An image CDN URL hides the file name in base64: show the original's name.
|
|
155
|
+
const fileName = (src) => {
|
|
156
|
+
const seg = (src || '').split('/').pop()?.split('?')[0] ?? '';
|
|
157
|
+
try {
|
|
158
|
+
const orig = atob(seg.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'));
|
|
159
|
+
if (/^https?:\/\//.test(orig)) return orig.split('/').pop().slice(0, 80);
|
|
160
|
+
} catch {}
|
|
161
|
+
return seg.slice(0, 80);
|
|
162
|
+
};
|
|
163
|
+
const family = (f) => f.split(',')[0].trim().replace(/^["']|["']$/g, '');
|
|
164
|
+
const visible = (el) => { const r = el.getBoundingClientRect(); const cs = getComputedStyle(el); return r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none' && !el.closest('[hidden], .sr-only'); };
|
|
165
|
+
const ownText = (el) => [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent).join('').trim();
|
|
166
|
+
const style = (el) => {
|
|
167
|
+
const cs = getComputedStyle(el);
|
|
168
|
+
return {
|
|
169
|
+
family: family(cs.fontFamily), size: Math.round(parseFloat(cs.fontSize) * 10) / 10, weight: cs.fontWeight, style: cs.fontStyle,
|
|
170
|
+
tracking: cs.letterSpacing === 'normal' ? 0 : Math.round((parseFloat(cs.letterSpacing) / parseFloat(cs.fontSize)) * 1000) / 1000,
|
|
171
|
+
transform: cs.textTransform, lineHeight: cs.lineHeight, color: hex(cs.color), stretch: cs.fontStretch,
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
// Text roles: what each kind of text is set in. The critic compares them with the logo.
|
|
175
|
+
const textEls = [...document.querySelectorAll('body *')].filter((el) => ownText(el) && visible(el) && !el.closest('script, style, noscript'));
|
|
176
|
+
const caps = (el) => { const cs = getComputedStyle(el); return cs.textTransform === 'uppercase' || (ownText(el) === ownText(el).toUpperCase() && /[A-Z]{3}/.test(ownText(el))); };
|
|
177
|
+
const roleOf = (el) => {
|
|
178
|
+
const cs = getComputedStyle(el), fs = parseFloat(cs.fontSize), t = ownText(el);
|
|
179
|
+
if (el.closest('[role="banner"]') || (el.closest('header') && !el.closest('main, article, section'))) return 'header / nav';
|
|
180
|
+
if (el.closest('footer')) return 'footer';
|
|
181
|
+
if (el.closest('button, .btn, [class*="button"]') || (el.closest('a') && rgb(getComputedStyle(el.closest('a')).backgroundColor)[3] !== 0 && getComputedStyle(el.closest('a')).backgroundColor !== 'rgba(0, 0, 0, 0)')) return 'button';
|
|
182
|
+
if (/^h1$/i.test(el.tagName)) return 'h1';
|
|
183
|
+
if (/^h[23]$/i.test(el.tagName) && fs >= 20) return 'section heading (h2/h3)';
|
|
184
|
+
if (/\d/.test(t) && fs >= 40) return 'big number';
|
|
185
|
+
if (/(CHF|EUR|€|Fr\.)\s?[\d'’.,]+|[\d'’.,]{5,}\s?(CHF|€)/.test(t)) return 'price';
|
|
186
|
+
if (fs <= 14 && caps(el)) return 'eyebrow / caps label';
|
|
187
|
+
if (fs <= 15) return 'small text / meta';
|
|
188
|
+
if (el.closest('form')) return 'form';
|
|
189
|
+
return 'body / lede';
|
|
190
|
+
};
|
|
191
|
+
const roles = new Map();
|
|
192
|
+
for (const el of textEls) {
|
|
193
|
+
const role = roleOf(el);
|
|
194
|
+
const s = style(el);
|
|
195
|
+
const key = `${role}|${s.family}|${s.size}|${s.weight}|${s.style}|${s.transform}`;
|
|
196
|
+
const cur = roles.get(key) ?? { role, ...s, count: 0, sample: ownText(el).slice(0, 50) };
|
|
197
|
+
cur.count++;
|
|
198
|
+
roles.set(key, cur);
|
|
199
|
+
}
|
|
200
|
+
const byRole = {};
|
|
201
|
+
for (const r of [...roles.values()].sort((a, b) => b.count - a.count)) (byRole[r.role] ??= []).length < 3 && byRole[r.role].push(r);
|
|
202
|
+
// Families by characters drawn.
|
|
203
|
+
const chars = new Map();
|
|
204
|
+
let total = 0;
|
|
205
|
+
for (const el of textEls) { const n = ownText(el).length; const f = family(getComputedStyle(el).fontFamily); chars.set(f, (chars.get(f) || 0) + n); total += n; }
|
|
206
|
+
const families = [...chars].sort((a, b) => b[1] - a[1]).map(([f, n]) => ({ family: f, share: Math.round((n / total) * 100) / 100, loaded: [...document.fonts].some((ff) => ff.family.replace(/["']/g, '') === f && ff.status === 'loaded') }));
|
|
207
|
+
// Colours: grounds by area (top-level boxes only once), text colours by characters.
|
|
208
|
+
const grounds = new Map();
|
|
209
|
+
for (const el of document.querySelectorAll('body, body *')) {
|
|
210
|
+
if (!visible(el)) continue;
|
|
211
|
+
const c = rgb(getComputedStyle(el).backgroundColor);
|
|
212
|
+
if (c.length < 3 || (c.length > 3 && c[3] < 0.5)) continue;
|
|
213
|
+
const r = el.getBoundingClientRect();
|
|
214
|
+
const h = hex(getComputedStyle(el).backgroundColor);
|
|
215
|
+
grounds.set(h, (grounds.get(h) || 0) + r.width * r.height);
|
|
216
|
+
}
|
|
217
|
+
const page = document.documentElement.scrollWidth * document.documentElement.scrollHeight;
|
|
218
|
+
const inks = new Map();
|
|
219
|
+
for (const el of textEls) { const h = hex(getComputedStyle(el).color); inks.set(h, (inks.get(h) || 0) + ownText(el).length); }
|
|
220
|
+
// Logo.
|
|
221
|
+
const logoEl = document.querySelector('img[data-logo]') || document.querySelector('header img, [role="banner"] img') || document.querySelector('header svg');
|
|
222
|
+
// No logo file: the text wordmark (the home link in the header) stands for it.
|
|
223
|
+
const wordmark = !logoEl && document.querySelector('header a[href="/"], [role="banner"] a[href="/"]');
|
|
224
|
+
let logo = null;
|
|
225
|
+
if (logoEl) {
|
|
226
|
+
const r = logoEl.getBoundingClientRect();
|
|
227
|
+
logo = { tag: logoEl.tagName.toLowerCase(), src: logoEl.currentSrc || logoEl.src || null, original: fileName(logoEl.currentSrc || logoEl.src), alt: logoEl.getAttribute('alt'), drawn: [Math.round(r.width), Math.round(r.height)], file: logoEl.naturalWidth ? [logoEl.naturalWidth, logoEl.naturalHeight] : null, shareOfHeader: null };
|
|
228
|
+
const header = logoEl.closest('header, [role="banner"]');
|
|
229
|
+
if (header) logo.shareOfHeader = Math.round((r.height / header.getBoundingClientRect().height) * 100) / 100;
|
|
230
|
+
}
|
|
231
|
+
if (wordmark) {
|
|
232
|
+
const r = wordmark.getBoundingClientRect(), s = style(wordmark.querySelector('span') || wordmark);
|
|
233
|
+
logo = { tag: 'text wordmark', text: wordmark.innerText.trim().replace(/\s+/g, ' '), drawn: [Math.round(r.width), Math.round(r.height)], font: s };
|
|
234
|
+
}
|
|
235
|
+
const header = document.querySelector('header, [role="banner"]');
|
|
236
|
+
// Images: file pixels against the box x devicePixelRatio (the photo-sharpness line).
|
|
237
|
+
const images = [...document.images].filter(visible).map((i) => {
|
|
238
|
+
const r = i.getBoundingClientRect();
|
|
239
|
+
const cs = getComputedStyle(i);
|
|
240
|
+
const realW = Number(i.dataset.realW) || i.naturalWidth, realH = Number(i.dataset.realH) || i.naturalHeight;
|
|
241
|
+
const cover = cs.objectFit !== 'contain' && cs.objectFit !== 'scale-down';
|
|
242
|
+
const fillW = realW && realH && cover ? Math.max(r.width, r.height * (realW / realH)) : r.width;
|
|
243
|
+
return {
|
|
244
|
+
file: fileName(i.currentSrc || i.src), alt: i.alt, hero: !!(i.getAttribute('fetchpriority') === 'high' || i.closest('[data-hero]')),
|
|
245
|
+
box: [Math.round(r.width), Math.round(r.height)], top: Math.round(r.top + scrollY), filePx: [realW, realH],
|
|
246
|
+
density: realW ? Math.round((realW / fillW) * 100) / 100 : null, // file pixels per CSS pixel: under devicePixelRatio is upscaled on that screen
|
|
247
|
+
};
|
|
248
|
+
}).filter((i) => i.box[0] >= 80);
|
|
249
|
+
// Section rhythm: the page's top-level bands, their grounds and inner spacing.
|
|
250
|
+
const main = document.querySelector('main') || document.body;
|
|
251
|
+
const sections = [...main.children].filter(visible).map((s) => {
|
|
252
|
+
const r = s.getBoundingClientRect(), cs = getComputedStyle(s);
|
|
253
|
+
const heading = s.querySelector('h1, h2, h3');
|
|
254
|
+
return {
|
|
255
|
+
el: `${s.tagName.toLowerCase()}${typeof s.className === 'string' && s.className ? '.' + s.className.trim().split(/\s+/).join('.') : ''}`,
|
|
256
|
+
top: Math.round(r.top + scrollY), height: Math.round(r.height), ground: groundOf(s),
|
|
257
|
+
padding: [Math.round(parseFloat(cs.paddingTop)), Math.round(parseFloat(cs.paddingBottom))],
|
|
258
|
+
heading: heading ? heading.textContent.trim().slice(0, 50) : null,
|
|
259
|
+
};
|
|
260
|
+
});
|
|
261
|
+
// Type scale: every size with text, how often, in which family (the critic judges near-duplicates).
|
|
262
|
+
const steps = new Map();
|
|
263
|
+
for (const el of textEls) { const cs = getComputedStyle(el); const k = `${Math.round(parseFloat(cs.fontSize) * 2) / 2}px ${family(cs.fontFamily)} ${cs.fontWeight}`; steps.set(k, (steps.get(k) || 0) + 1); }
|
|
264
|
+
const typeScale = [...steps].sort((x, y) => parseFloat(x[0]) - parseFloat(y[0])).map(([k, n]) => `${k} x${n}`);
|
|
265
|
+
return {
|
|
266
|
+
viewport: [vw, vh], typeScale, dpr: devicePixelRatio, pageHeight: document.documentElement.scrollHeight, title: document.title,
|
|
267
|
+
header: header ? { height: Math.round(header.getBoundingClientRect().height), share: Math.round((header.getBoundingClientRect().height / vh) * 100) / 100, position: getComputedStyle(header).position } : null,
|
|
268
|
+
logo, families, fontsByRole: byRole,
|
|
269
|
+
grounds: [...grounds].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([c, a]) => ({ color: c, share: Math.round((a / page) * 100) / 100 })),
|
|
270
|
+
textColors: [...inks].sort((a, b) => b[1] - a[1]).slice(0, 6).map(([c, n]) => ({ color: c, chars: n })),
|
|
271
|
+
images, sections,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The logo beside each family in use, drawn on the live page (its fonts are loaded there). */
|
|
276
|
+
async function typeVsLogo(page, families, logoSrc, name, file) {
|
|
277
|
+
const height = await page.evaluate(({ families, logoSrc, name }) => {
|
|
278
|
+
const box = document.createElement('div');
|
|
279
|
+
box.id = 'ra-specimen';
|
|
280
|
+
box.style.cssText = 'position:absolute;left:0;top:0;width:100%;z-index:2147483647;background:#fff;color:#111;padding:40px;display:grid;grid-template-columns:auto 1fr;gap:40px;align-items:start;overflow:hidden';
|
|
281
|
+
const l = document.createElement('div');
|
|
282
|
+
const mark = !logoSrc && document.querySelector('header a[href="/"], [role="banner"] a[href="/"]');
|
|
283
|
+
if (logoSrc) l.innerHTML = `<img src="${logoSrc}" style="height:220px;width:auto;display:block"><div style="font:12px system-ui;margin-top:8px;color:#666">logo at 220px tall</div>`;
|
|
284
|
+
else if (mark) {
|
|
285
|
+
// The text wordmark, cloned on the live page (its CSS applies), drawn three times larger.
|
|
286
|
+
const c = mark.cloneNode(true);
|
|
287
|
+
c.removeAttribute('href');
|
|
288
|
+
c.style.cssText = 'zoom:3;display:inline-flex;position:static;transform:none';
|
|
289
|
+
l.append(c);
|
|
290
|
+
l.insertAdjacentHTML('beforeend', '<div style="font:12px system-ui;margin-top:8px;color:#666">text wordmark at 3x</div>');
|
|
291
|
+
}
|
|
292
|
+
const r = document.createElement('div');
|
|
293
|
+
r.style.cssText = 'display:grid;gap:22px';
|
|
294
|
+
for (const f of families) {
|
|
295
|
+
const row = document.createElement('div');
|
|
296
|
+
row.innerHTML = `<div style="font:12px system-ui;color:#666;margin-bottom:4px">${f.family} (${Math.round(f.share * 100)}% of the text${f.loaded ? '' : ', NOT LOADED'})</div>` +
|
|
297
|
+
`<div style="font-family:'${f.family}';font-size:56px;line-height:1.05;font-weight:400">${name} 1'250'000</div>` +
|
|
298
|
+
`<div style="font-family:'${f.family}';font-size:56px;line-height:1.05;font-weight:700;text-transform:uppercase">${name.split(/\s+/)[0]} 4.5 · 96</div>`;
|
|
299
|
+
r.append(row);
|
|
300
|
+
}
|
|
301
|
+
box.append(l, r);
|
|
302
|
+
window.scrollTo(0, 0);
|
|
303
|
+
document.body.append(box);
|
|
304
|
+
return Promise.all([...box.querySelectorAll('img')].map((i) => i.decode().catch(() => {}))).then(() => box.getBoundingClientRect().height);
|
|
305
|
+
}, { families, logoSrc, name });
|
|
306
|
+
await page.waitForTimeout(200);
|
|
307
|
+
await page.screenshot({ path: file, clip: { x: 0, y: 0, width: page.viewportSize().width, height: Math.ceil(height) } });
|
|
308
|
+
await page.evaluate(() => document.getElementById('ra-specimen')?.remove());
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
const summary = { page: BASE + PATH, measuredProblems: problems, taste: problems.filter((p) => p.includes('taste:')), widths: {} };
|
|
312
|
+
const files = [];
|
|
313
|
+
try {
|
|
314
|
+
const site = await shots(BASE + PATH, 'page', injectCss);
|
|
315
|
+
for (const [w, s] of Object.entries(site)) {
|
|
316
|
+
summary.widths[w] = await s.page.evaluate(measure);
|
|
317
|
+
files.push([s.first, `the page, first screen at ${w}`], [s.full, `the page, full at ${w}`]);
|
|
318
|
+
}
|
|
319
|
+
const d = summary.widths['1440'];
|
|
320
|
+
if (d.logo?.src) {
|
|
321
|
+
// An image CDN serves the logo as a raster derivative: fetch the original too (an SVG tells more).
|
|
322
|
+
const seg = new URL(d.logo.src).pathname.split('/').pop()?.split('.')[0] ?? '';
|
|
323
|
+
let original = null;
|
|
324
|
+
try {
|
|
325
|
+
const u = Buffer.from(seg.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
|
|
326
|
+
if (/^https?:\/\/[^\s]+$/.test(u)) original = u;
|
|
327
|
+
} catch {}
|
|
328
|
+
if (original) d.logo.originalUrl = original;
|
|
329
|
+
try {
|
|
330
|
+
const res = await site['1440'].page.request.get(original && /\.svg$/i.test(original) ? original : d.logo.src);
|
|
331
|
+
const ext = (extname(new URL(res.url()).pathname) || '.img').slice(0, 6);
|
|
332
|
+
await writeFile(join(OUT, `logo${ext}`), await res.body());
|
|
333
|
+
files.push([`logo${ext}`, 'the logo file as served']);
|
|
334
|
+
if (ext === '.svg') {
|
|
335
|
+
const svg = (await res.text()).slice(0, 200000);
|
|
336
|
+
d.logo.svg = { textElements: (svg.match(/<text\b/g) || []).length, fontFamilies: [...new Set((svg.match(/font-family\s*[:=]\s*["']?([^;"'>]+)/g) || []).map((m) => m.replace(/font-family\s*[:=]\s*["']?/, '').trim()))], fills: [...new Set((svg.match(/#[0-9a-f]{6}\b|#[0-9a-f]{3}\b/gi) || []).map((c) => c.toLowerCase()))] };
|
|
337
|
+
}
|
|
338
|
+
} catch {}
|
|
339
|
+
}
|
|
340
|
+
await typeVsLogo(site['1440'].page, d.families.filter((f) => f.share >= 0.02), d.logo?.src, (d.logo?.alt || d.logo?.text || 'Agency').replace(/\s+(AG|SA|GmbH|Sàrl|SARL|SRL|SL|SAS|Srl)$/i, ''), join(OUT, 'type-vs-logo.png'));
|
|
341
|
+
files.push(['type-vs-logo.png', "the logo beside every font family in use: does the type echo the logo's character, or contrast with it on purpose?"]);
|
|
342
|
+
for (const s of Object.values(site)) await s.ctx.close();
|
|
343
|
+
|
|
344
|
+
if (ANCHOR) {
|
|
345
|
+
const a = await shots(ANCHOR + ANCHOR_PATH, 'anchor');
|
|
346
|
+
summary.anchor = { url: ANCHOR + ANCHOR_PATH, widths: {} };
|
|
347
|
+
for (const [w, s] of Object.entries(a)) {
|
|
348
|
+
summary.anchor.widths[w] = await s.page.evaluate(measure);
|
|
349
|
+
files.unshift([s.first, `the anchor, first screen at ${w}`], [s.full, `the anchor, full at ${w}`]);
|
|
350
|
+
await s.ctx.close();
|
|
351
|
+
}
|
|
352
|
+
} else if (ANCHOR_SHOTS) {
|
|
353
|
+
summary.anchor = { shots: [] };
|
|
354
|
+
for (const f of ANCHOR_SHOTS.split(',').map((s) => s.trim()).filter(Boolean)) {
|
|
355
|
+
const name = `anchor-${basename(f)}`;
|
|
356
|
+
await copyFile(f, join(OUT, name));
|
|
357
|
+
summary.anchor.shots.push(name);
|
|
358
|
+
files.unshift([name, `the anchor (given): ${basename(f)}`]);
|
|
359
|
+
}
|
|
360
|
+
} else {
|
|
361
|
+
summary.anchor = null;
|
|
362
|
+
}
|
|
363
|
+
} finally {
|
|
364
|
+
await browser.close();
|
|
365
|
+
stop();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
for (const f of ['BRIEF.md', 'DESIGN-NOTES.md']) {
|
|
369
|
+
if (existsSync(f)) {
|
|
370
|
+
await copyFile(f, join(OUT, f));
|
|
371
|
+
files.unshift([f, f === 'BRIEF.md' ? 'what the agency asked for (facts and tone: never contradict it)' : 'what the builder decided and why (anything kept on purpose is named here)']);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (PREVIOUS) {
|
|
375
|
+
await copyFile(PREVIOUS, join(OUT, 'PREVIOUS-CRITIC.md'));
|
|
376
|
+
files.unshift(['PREVIOUS-CRITIC.md', 'the previous round\'s critique: this is round 2, check each of its fixes first']);
|
|
377
|
+
}
|
|
378
|
+
await copyFile(here('../critic/CRITIC.md'), join(OUT, 'CRITIC.md'));
|
|
379
|
+
await copyFile(here('../TASTE.md'), join(OUT, 'TASTE.md'));
|
|
380
|
+
await writeFile(join(OUT, 'summary.json'), JSON.stringify(summary, null, 2));
|
|
381
|
+
const index = `# Critic input: ${BASE + PATH}
|
|
382
|
+
|
|
383
|
+
Read CRITIC.md first (your instructions; the rubric is TASTE.md), then the files below in this order.
|
|
384
|
+
summary.json holds the measured facts: \`taste\` (problems the screenshot tool measured), and per width
|
|
385
|
+
the fonts by role, families in use, grounds and text colours, the logo (drawn size, file, SVG facts),
|
|
386
|
+
images (file pixels per CSS pixel: \`density\` under the width's dpr means upscaled), and the sections
|
|
387
|
+
(top, height, ground, padding) for the rhythm line.
|
|
388
|
+
${summary.anchor ? '' : '\nNo anchor was given: judge against the style named in BRIEF.md and DESIGN-NOTES.md, and say so.\n'}
|
|
389
|
+
${files.map(([f, what]) => `- ${f}: ${what}`).join('\n')}
|
|
390
|
+
- summary.json: the measured facts
|
|
391
|
+
- TASTE.md: the rubric
|
|
392
|
+
|
|
393
|
+
Measured taste lines: ${summary.taste.length ? '\n' + summary.taste.map((t) => `- ${t}`).join('\n') : 'none.'}
|
|
394
|
+
`;
|
|
395
|
+
await writeFile(join(OUT, 'INDEX.md'), index);
|
|
396
|
+
console.log(`Critic input in ${OUT}/ (${files.length + 3} files). Give the critic ${join(OUT, 'INDEX.md')} and nothing else.`);
|
|
397
|
+
if (summary.taste.length) console.log(`${summary.taste.length} measured taste line(s):\n ${summary.taste.join('\n ')}`);
|
package/tools/screenshot.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* pnpm screenshot -- --url http://localhost:4321 --max 40
|
|
8
8
|
* pnpm screenshot -- /listings /contact # only these paths
|
|
9
9
|
* pnpm screenshot -- --jobs 1 # one page at a time (default 4)
|
|
10
|
+
* pnpm screenshot -- --inject fault.css # add a CSS file to every page (critic calibration)
|
|
10
11
|
*
|
|
11
12
|
* Output: screenshots/<route>@1440.png, screenshots/<route>@390.png and
|
|
12
13
|
* screenshots/report.json. Exit code 1 if any page has console errors, failed
|
|
@@ -16,6 +17,7 @@
|
|
|
16
17
|
import { chromium } from 'playwright';
|
|
17
18
|
import { spawn, spawnSync } from 'node:child_process';
|
|
18
19
|
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
|
20
|
+
import { readFileSync } from 'node:fs';
|
|
19
21
|
import { resolve } from 'node:path';
|
|
20
22
|
import { pathToFileURL } from 'node:url';
|
|
21
23
|
|
|
@@ -34,6 +36,9 @@ const MAX = Number(opt('max', '30'));
|
|
|
34
36
|
// timers), so 4 at a time is about 3x faster than one after the other, even on 4 vCPUs.
|
|
35
37
|
const JOBS = Math.max(1, Number(opt('jobs', process.env.SCREENSHOT_JOBS ?? '4')));
|
|
36
38
|
const OUT = opt('out', 'screenshots');
|
|
39
|
+
// A CSS file added to every page after load (the critic's calibration cases put a fault back with it).
|
|
40
|
+
const INJECT = opt('inject', '');
|
|
41
|
+
const injectCss = INJECT ? readFileSync(INJECT, 'utf8') : '';
|
|
37
42
|
const explicit = args.filter((a) => a.startsWith('/'));
|
|
38
43
|
const WIDTHS = [
|
|
39
44
|
{ name: '1440', width: 1440, height: 900 },
|
|
@@ -243,6 +248,7 @@ async function shoot({ path, vp, i }) {
|
|
|
243
248
|
return null;
|
|
244
249
|
});
|
|
245
250
|
await page.waitForLoadState('load', { timeout: 10000 }).catch(() => {});
|
|
251
|
+
if (injectCss) await page.addStyleTag({ content: injectCss }).catch(() => {});
|
|
246
252
|
const status = res?.status() ?? 0;
|
|
247
253
|
entry.status = Math.max(entry.status, status);
|
|
248
254
|
if (status >= 400) entry.problems.push(`[${vp.name}] page HTTP ${status}`);
|
|
@@ -375,15 +381,206 @@ async function shoot({ path, vp, i }) {
|
|
|
375
381
|
const drawnH = contain ? Math.min(r.height, r.width / nat) : r.height;
|
|
376
382
|
return { name: (i.alt || i.currentSrc.split('/').pop() || '').slice(0, 40), fit, dev: (r.width / r.height) / nat, contain, drawnW, drawnH };
|
|
377
383
|
})(),
|
|
384
|
+
// Taste (TASTE.md): proportions, colour restraint, reading comfort. Measured, never judged.
|
|
385
|
+
taste: (() => {
|
|
386
|
+
const vw = innerWidth, vh = innerHeight;
|
|
387
|
+
const rgb = (c) => (c.match(/[\d.]+/g) || []).map(Number);
|
|
388
|
+
const hsl = ([r, g, b]) => {
|
|
389
|
+
r /= 255; g /= 255; b /= 255;
|
|
390
|
+
const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2, d = mx - mn;
|
|
391
|
+
const sat = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
|
|
392
|
+
let h = 0;
|
|
393
|
+
if (d) h = mx === r ? ((g - b) / d) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
|
394
|
+
return { h: (h * 60 + 360) % 360, s: sat, l };
|
|
395
|
+
};
|
|
396
|
+
const vivid = (c) => { const v = rgb(c); if (v.length < 3 || (v.length > 3 && v[3] < 0.9)) return null; const x = hsl(v); return x.s >= 0.6 && x.l >= 0.3 && x.l <= 0.72 ? x : null; };
|
|
397
|
+
const header = document.querySelector('header, [role="banner"]');
|
|
398
|
+
const headerH = header ? header.getBoundingClientRect().height : 0;
|
|
399
|
+
// Large vivid fields: a full-bleed band or block in a saturated colour.
|
|
400
|
+
const fields = [];
|
|
401
|
+
const hues = new Map();
|
|
402
|
+
for (const n of document.querySelectorAll('body *')) {
|
|
403
|
+
const cs = getComputedStyle(n);
|
|
404
|
+
if (cs.display === 'none' || cs.visibility === 'hidden') continue;
|
|
405
|
+
const r = n.getBoundingClientRect();
|
|
406
|
+
if (!r.width || !r.height) continue;
|
|
407
|
+
const bg = vivid(cs.backgroundColor);
|
|
408
|
+
if (bg) {
|
|
409
|
+
const area = r.width * Math.min(r.height, vh);
|
|
410
|
+
const bucket = Math.round(bg.h / 30) * 30;
|
|
411
|
+
hues.set(bucket, (hues.get(bucket) || 0) + area);
|
|
412
|
+
if (area >= vw * vh * 0.2) fields.push(`${n.tagName.toLowerCase()}${n.className && typeof n.className === 'string' ? '.' + n.className.trim().split(/\s+/)[0] : ''} ${cs.backgroundColor} ${Math.round(r.width)}x${Math.round(r.height)}`);
|
|
413
|
+
}
|
|
414
|
+
const fg = vivid(cs.color);
|
|
415
|
+
if (fg && n.childNodes.length && [...n.childNodes].some((c) => c.nodeType === 3 && c.textContent.trim())) {
|
|
416
|
+
const bucket = Math.round(fg.h / 30) * 30;
|
|
417
|
+
hues.set(bucket, (hues.get(bucket) || 0) + r.width * r.height);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const accentHues = [...hues].filter(([, a]) => a >= 400).map(([h]) => h % 360);
|
|
421
|
+
// Reading comfort: body paragraphs.
|
|
422
|
+
let longLines = 0, smallBody = 0, paras = 0;
|
|
423
|
+
for (const p of document.querySelectorAll('main p, article p')) {
|
|
424
|
+
const cs = getComputedStyle(p), fs = parseFloat(cs.fontSize), lh = parseFloat(cs.lineHeight) || fs * 1.4;
|
|
425
|
+
const r = p.getBoundingClientRect(), text = p.textContent.trim();
|
|
426
|
+
if (!r.width || text.length < 120 || fs > 22) continue;
|
|
427
|
+
paras++;
|
|
428
|
+
const lines = Math.max(1, Math.round(r.height / lh));
|
|
429
|
+
if (lines >= 3 && text.length / lines > 90) longLines++;
|
|
430
|
+
if (fs < 15) smallBody++;
|
|
431
|
+
}
|
|
432
|
+
// Soft photos: the file actually loaded (its real pixels, not the srcset's claim; an
|
|
433
|
+
// image CDN never enlarges) against the box it fills x devicePixelRatio (capped at 1.5:
|
|
434
|
+
// a 1.5x file already looks sharp on a 2x phone). Decorative images are exempt unless
|
|
435
|
+
// they are the hero or a big photo (an aria-hidden hero link still counts).
|
|
436
|
+
const dpr = Math.min(devicePixelRatio || 1, 1.5);
|
|
437
|
+
const soft = [];
|
|
438
|
+
for (const i of document.images) {
|
|
439
|
+
const r = i.getBoundingClientRect();
|
|
440
|
+
const src = i.currentSrc || i.src;
|
|
441
|
+
const realW = Number(i.dataset.realW) || i.naturalWidth;
|
|
442
|
+
const realH = Number(i.dataset.realH) || i.naturalHeight;
|
|
443
|
+
if (r.width < 160 || r.height < 120 || !realW || !realH || /\.svg(\?|$)/i.test(src) || i.closest('header, [role="banner"]')) continue;
|
|
444
|
+
const cs = getComputedStyle(i);
|
|
445
|
+
if (cs.filter.includes('blur')) continue; // a blurred placeholder or backdrop
|
|
446
|
+
const big = r.width >= vw * 0.4;
|
|
447
|
+
const hero = i.getAttribute('fetchpriority') === 'high' || i.closest('[data-hero]');
|
|
448
|
+
if (i.getAttribute('alt') === '' && !hero && !big) continue;
|
|
449
|
+
const nat = realW / realH;
|
|
450
|
+
const cover = cs.objectFit !== 'contain' && cs.objectFit !== 'scale-down';
|
|
451
|
+
const fillW = cover ? Math.max(r.width, r.height * nat) : r.width;
|
|
452
|
+
const up = (fillW * dpr) / realW;
|
|
453
|
+
// An image CDN hides the file name in base64: name the original file.
|
|
454
|
+
let file = src.split('/').pop()?.split('?')[0] ?? '';
|
|
455
|
+
try { const o = atob(file.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')); if (/^https?:\/\//.test(o)) file = o.split('/').pop(); } catch {}
|
|
456
|
+
if (up > 1.15) soft.push(`"${(i.alt || file || '').slice(0, 40)}" file ${realW}x${realH} fills ${Math.round(fillW)}px x ${dpr} dpr (upscaled ${Math.round(up * 100)}%)${hero ? ', the hero' : ''}`);
|
|
457
|
+
}
|
|
458
|
+
// Ledes: the first paragraph after a section heading (h1/h2, an eyebrow may sit
|
|
459
|
+
// between). One style for every lede: family, size, weight, italic, full or muted
|
|
460
|
+
// colour (contrast with the ground under it). Colour is relative, so white on ink
|
|
461
|
+
// and near-black on paper are the same style.
|
|
462
|
+
const ground = (n) => {
|
|
463
|
+
for (let e = n; e; e = e.parentElement) {
|
|
464
|
+
const c = rgb(getComputedStyle(e).backgroundColor);
|
|
465
|
+
if (c.length >= 3 && (c.length < 4 || c[3] > 0.5)) return c.slice(0, 3);
|
|
466
|
+
}
|
|
467
|
+
return [255, 255, 255];
|
|
468
|
+
};
|
|
469
|
+
const lin = (v) => ((v /= 255) <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
|
|
470
|
+
const lum = ([r, g, b]) => 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
|
471
|
+
const contrast = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
|
|
472
|
+
const blend = (c, under) => (c.length > 3 && c[3] < 1 ? c.slice(0, 3).map((v, k) => v * c[3] + under[k] * (1 - c[3])) : c.slice(0, 3));
|
|
473
|
+
const family = (f) => f.split(',')[0].trim().replace(/^["']|["']$/g, '');
|
|
474
|
+
const ledes = new Map();
|
|
475
|
+
for (const h of document.querySelectorAll('main h1, main h2')) {
|
|
476
|
+
let p = h.nextElementSibling;
|
|
477
|
+
if (p && p.tagName !== 'P' && (p.textContent || '').trim().length < 40) p = p.nextElementSibling; // an eyebrow or rule after the heading
|
|
478
|
+
if (!p || p.tagName !== 'P') continue;
|
|
479
|
+
const cs = getComputedStyle(p), r = p.getBoundingClientRect(), text = p.textContent.trim();
|
|
480
|
+
if (!r.width || text.length < 40 || parseFloat(cs.fontSize) < 15 || p.closest('form, [data-enquiry]')) continue;
|
|
481
|
+
// A heading styled as an eyebrow (a small h2 over a statement or a big number) has no lede.
|
|
482
|
+
if (parseFloat(getComputedStyle(h).fontSize) < parseFloat(cs.fontSize) * 1.25) continue;
|
|
483
|
+
const g = ground(p);
|
|
484
|
+
const tone = contrast(blend(rgb(cs.color), g), g) >= 9 ? 'full' : 'muted';
|
|
485
|
+
const sig = `${family(cs.fontFamily)} ${Math.round(parseFloat(cs.fontSize))}px ${cs.fontWeight}${cs.fontStyle === 'italic' ? ' italic' : ''} ${tone}`;
|
|
486
|
+
if (!ledes.has(sig)) ledes.set(sig, []);
|
|
487
|
+
ledes.get(sig).push(`"${text.slice(0, 24)}…"`);
|
|
488
|
+
}
|
|
489
|
+
// Families in use, by characters drawn (a family under 3% of the text is a detail),
|
|
490
|
+
// and webfonts the CSS asks for that never loaded (a silent fallback to Georgia/Arial).
|
|
491
|
+
const chars = new Map();
|
|
492
|
+
let total = 0;
|
|
493
|
+
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
|
494
|
+
for (let t = walker.nextNode(); t; t = walker.nextNode()) {
|
|
495
|
+
const el = t.parentElement, n = t.textContent.trim().length;
|
|
496
|
+
if (!n || !el || el.closest('script, style, noscript, [hidden], .sr-only')) continue;
|
|
497
|
+
const r = el.getBoundingClientRect();
|
|
498
|
+
if (!r.width || !r.height) continue;
|
|
499
|
+
const f = family(getComputedStyle(el).fontFamily);
|
|
500
|
+
chars.set(f, (chars.get(f) || 0) + n);
|
|
501
|
+
total += n;
|
|
502
|
+
}
|
|
503
|
+
const families = [...chars].filter(([, n]) => n / total >= 0.03).sort((a, b) => b[1] - a[1]).map(([f, n]) => `${f} ${Math.round((n / total) * 100)}%`);
|
|
504
|
+
const faces = [...document.fonts];
|
|
505
|
+
const declared = (f) => faces.filter((ff) => ff.family.replace(/["']/g, '') === f);
|
|
506
|
+
// Only families the page itself declares (@font-face): a missing local font is not a bug here.
|
|
507
|
+
const notLoaded = [...chars.keys()].filter((f) => chars.get(f) / total >= 0.03 && declared(f).length && !declared(f).some((ff) => ff.status === 'loaded'));
|
|
508
|
+
// Craft defaults (DESIGN.md section 10). Elements with their own text, shown.
|
|
509
|
+
const own = (el) => [...el.childNodes].filter((c) => c.nodeType === 3).map((c) => c.textContent).join('').trim();
|
|
510
|
+
const label = (el) => `${el.tagName.toLowerCase()}${typeof el.className === 'string' && el.className.trim() ? '.' + el.className.trim().split(/\s+/)[0] : ''} "${(el.innerText || '').trim().replace(/\s+/g, ' ').slice(0, 28)}"`;
|
|
511
|
+
const shown = [...document.querySelectorAll('body *')].filter((el) => {
|
|
512
|
+
if (el.closest('script, style, noscript, [hidden], .sr-only, [aria-hidden="true"]')) return false;
|
|
513
|
+
const r = el.getBoundingClientRect();
|
|
514
|
+
return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== 'hidden';
|
|
515
|
+
});
|
|
516
|
+
const texts = shown.filter((el) => own(el));
|
|
517
|
+
// Justified body text, caps on sentences, straight double quotes in text.
|
|
518
|
+
const justified = [...document.querySelectorAll('main p, article p')].filter((p) => shown.includes(p) && getComputedStyle(p).textAlign === 'justify' && p.textContent.trim().length >= 120).map(label);
|
|
519
|
+
const longCaps = texts.filter((el) => {
|
|
520
|
+
const t = own(el);
|
|
521
|
+
return t.length > 40 && (getComputedStyle(el).textTransform === 'uppercase' || (/[A-ZÄÖÜÉÈÀ]{2}/.test(t) && t === t.toUpperCase() && /[A-Z]/.test(t) && t.replace(/[^A-Za-zÀ-ÿ]/g, '').length >= 20));
|
|
522
|
+
}).map(label);
|
|
523
|
+
const quotes = texts.filter((el) => !el.closest('code, pre, kbd, samp, input, textarea') && /"/.test(own(el))).map(label);
|
|
524
|
+
// Off-grid: a block whose left and right edges match no edge the layout gives it:
|
|
525
|
+
// another block's edge, its parent's content edges, its parent's grid tracks or the
|
|
526
|
+
// page edge (±3px). Catches ad-hoc margins and nudges, not a deliberate second
|
|
527
|
+
// column. Centred blocks and blocks inside another block are skipped.
|
|
528
|
+
const BLOCK = 'h1, h2, h3, p, ul, ol, dl, figure, form, picture, img, blockquote, address, table, a.more, .button, .btn';
|
|
529
|
+
const blocks = [...document.querySelectorAll(`main :is(${BLOCK})`)].filter((el) => shown.includes(el) && !el.parentElement.closest(BLOCK) && el.getBoundingClientRect().width >= 24);
|
|
530
|
+
const box = blocks.map((el) => ({ el, r: el.getBoundingClientRect() }));
|
|
531
|
+
const near = (x, xs) => xs.some((v) => Math.abs(v - x) <= 3);
|
|
532
|
+
const offGrid = box.filter(({ el, r }) => {
|
|
533
|
+
const cs = getComputedStyle(el);
|
|
534
|
+
const parent = el.parentElement.getBoundingClientRect();
|
|
535
|
+
if (cs.textAlign === 'center' && Math.abs((r.left - parent.left) - (parent.right - r.right)) < 6) return false;
|
|
536
|
+
// Second item in a row (a link after a button): it follows its sibling.
|
|
537
|
+
const prev = el.previousElementSibling?.getBoundingClientRect();
|
|
538
|
+
if (prev && prev.width && prev.top < r.bottom && prev.bottom > r.top && r.left - prev.right >= 0 && r.left - prev.right <= 64) return false;
|
|
539
|
+
const others = box.filter((o) => o.el !== el).flatMap((o) => [o.r.left, o.r.right]);
|
|
540
|
+
others.push(0, vw);
|
|
541
|
+
const pcs = getComputedStyle(el.parentElement);
|
|
542
|
+
const cl = parent.left + parseFloat(pcs.borderLeftWidth) + parseFloat(pcs.paddingLeft);
|
|
543
|
+
const cr = parent.right - parseFloat(pcs.borderRightWidth) - parseFloat(pcs.paddingRight);
|
|
544
|
+
others.push(cl, cr);
|
|
545
|
+
if (pcs.display.includes('grid')) {
|
|
546
|
+
const gap = parseFloat(pcs.columnGap) || 0;
|
|
547
|
+
let x = cl;
|
|
548
|
+
for (const t of pcs.gridTemplateColumns.split(/\s+/).map(parseFloat).filter((n) => !Number.isNaN(n))) { others.push(x, x + t); x += t + gap; }
|
|
549
|
+
}
|
|
550
|
+
return !near(r.left, others) && !near(r.right, others);
|
|
551
|
+
}).map(({ el }) => label(el));
|
|
552
|
+
return { vw, vh, headerH, fields: [...new Set(fields)].slice(0, 3), accentHues: [...new Set(accentHues)], longLines, smallBody, paras, soft: soft.slice(0, 4), ledes: [...ledes].map(([s, l]) => `${s} (${l.slice(0, 3).join(', ')})`), families, notLoaded, justified, longCaps, quotes, offGrid };
|
|
553
|
+
})(),
|
|
378
554
|
}));
|
|
379
555
|
// Hero text legibility: text over the hero photo, contrast against the pixels behind it.
|
|
380
556
|
for (const t of await heroContrast(page)) entry.problems.push(`[${vp.name}] hero text "${t.text}" contrast ${t.ratio.toFixed(1)}:1 on the photo (need ${t.need}:1): add a scrim (gradient >= 0.55 black at the text's top edge) or a panel`);
|
|
381
557
|
const lg = checks.logo;
|
|
382
558
|
if (lg) {
|
|
383
559
|
if (!lg.contain && (lg.dev > 1.05 || lg.dev < 0.95)) entry.problems.push(`[${vp.name}] logo "${lg.name}" ${lg.fit === 'fill' ? 'stretched' : 'cropped'} (box ratio ${(lg.dev * 100 - 100).toFixed(0)}% off the file): set only height (width: auto), no fixed box, no object-fit: cover`);
|
|
384
|
-
|
|
560
|
+
// A wide wordmark is sized by width, a tall or square mark (3³, a monogram) by height.
|
|
561
|
+
const wide = lg.drawnW / lg.drawnH >= 1.3;
|
|
562
|
+
if (vp.name === '1440' && wide && (lg.drawnW < 100 || lg.drawnH < 32)) entry.problems.push(`[1440] logo "${lg.name}" drawn ${Math.round(lg.drawnW)}x${Math.round(lg.drawnH)}px: at least 100px wide and 32px tall (140–180px wide for a detailed logo)`);
|
|
563
|
+
if (vp.name === '1440' && !wide && (lg.drawnH < 40 || lg.drawnH > 72)) entry.problems.push(`[1440] logo "${lg.name}" (a tall or square mark) drawn ${Math.round(lg.drawnH)}px tall: 40–72px tall`);
|
|
564
|
+
if (vp.name === '1440' && wide && lg.drawnH > 72) entry.problems.push(`[1440] taste: logo "${lg.name}" drawn ${Math.round(lg.drawnH)}px tall: at most 72px, the header stays slim`);
|
|
385
565
|
if (vp.name === '390' && lg.drawnH < 28) entry.problems.push(`[390] logo "${lg.name}" drawn ${Math.round(lg.drawnH)}px tall: at least 28px`);
|
|
386
566
|
}
|
|
567
|
+
const ts = checks.taste;
|
|
568
|
+
if (ts) {
|
|
569
|
+
const maxHeader = Math.round(ts.vh * 0.12);
|
|
570
|
+
if (ts.headerH > maxHeader) entry.problems.push(`[${vp.name}] taste: header ${Math.round(ts.headerH)}px tall, more than 12% of the screen (${maxHeader}px): slim it (logo 40–72px, one row)`);
|
|
571
|
+
for (const f of ts.fields) entry.problems.push(`[${vp.name}] taste: large field in a saturated colour (${f}): keep vivid brand colours for small accents; use a deep or muted shade, the ink colour or a neutral surface for bands`);
|
|
572
|
+
if (vp.name === '1440' && ts.accentHues.length > 2) entry.problems.push(`[1440] taste: ${ts.accentHues.length} saturated accent hues (${ts.accentHues.join(', ')}°): one accent, two at most`);
|
|
573
|
+
if (vp.name === '1440' && ts.longLines) entry.problems.push(`[1440] taste: ${ts.longLines} paragraph(s) over 90 characters a line: limit the measure (max-width about 65ch)`);
|
|
574
|
+
if (vp.name === '1440' && ts.smallBody) entry.problems.push(`[1440] taste: ${ts.smallBody} body paragraph(s) under 15px: body text 16–20px on desktop`);
|
|
575
|
+
for (const s of ts.soft) entry.problems.push(`[${vp.name}] taste: soft photo, ${s}: use a larger source or a smaller box (the file must cover the box x devicePixelRatio, up to 1.5x)`);
|
|
576
|
+
if (vp.name === '1440' && ts.ledes.length > 1) entry.problems.push(`[1440] taste: section ledes in ${ts.ledes.length} styles: ${ts.ledes.join(' | ')}: one lede style (one class) for every section`);
|
|
577
|
+
if (vp.name === '1440' && ts.families.length > 2) entry.problems.push(`[1440] taste: ${ts.families.length} font families in use (${ts.families.join(', ')}): two at most`);
|
|
578
|
+
if (vp.name === '1440' && ts.offGrid.length) entry.problems.push(`[1440] taste: off-grid, ${ts.offGrid.length} block(s) on no edge the layout gives them (other blocks, the parent's content box or grid tracks): ${ts.offGrid.slice(0, 3).join(', ')}: put them on the section's column edges`);
|
|
579
|
+
if (vp.name === '1440' && ts.justified.length) entry.problems.push(`[1440] taste: justified body text (${ts.justified.slice(0, 2).join(', ')}): left-align it, ragged right`);
|
|
580
|
+
if (vp.name === '1440' && ts.longCaps.length) entry.problems.push(`[1440] taste: caps on text over 40 characters (${ts.longCaps.slice(0, 2).join(', ')}): caps only for short labels`);
|
|
581
|
+
if (vp.name === '1440' && ts.quotes.length) entry.problems.push(`[1440] taste: straight " quotes in text (${ts.quotes.slice(0, 2).join(', ')}): use the language's marks („…“ de, « … » fr, «…» it/es, “…” en)`);
|
|
582
|
+
for (const f of ts.notLoaded) entry.problems.push(`[${vp.name}] taste: font "${f}" is declared but never loaded: the text falls back to another font (check the @fontsource import and the family name)`);
|
|
583
|
+
}
|
|
387
584
|
for (const b of new Set(checks.blockers)) entry.problems.push(`[${vp.name}] invisible element blocks clicks: ${b} (closed overlays need visibility:hidden + pointer-events:none)`);
|
|
388
585
|
// Click-through: a link below the fold must be the element under its own centre.
|
|
389
586
|
const click = await page.evaluate(async () => {
|