176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
fix: make the browser check tool clean up after itself and fail pages that did not load properly
matinb38d20321bf3
diff --git a/tools/check-pages.mjs b/tools/check-pages.mjsindex cfd126e0..7a3a2dea 100644--- a/tools/check-pages.mjs+++ b/tools/check-pages.mjs@@ -3,14 +3,15 @@// Needs the local Chrome and a static server for the repo (python -m http.server 8731 --bind 127.0.0.1).// Usage: node tools/check-pages.mjs [--base http://127.0.0.1:8731] [--out <folder>] <page folder>...// e.g. node tools/check-pages.mjs animations/02-entrance-and-exit/fade-in-out-// Each page is loaded at five screen setups; problems are printed and screenshots saved. Exit code 1 on any problem.+// Each page is loaded at five screen setups; problems are printed and screenshots saved. Console warnings count as+// problems too (the page script warns about settings that have no label or value). Exit code 1 on any problem.import { spawn } from 'node:child_process';-import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';const CHROME = process.env.CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe';-const PORT = Number(process.env.CDP_PORT || 9333);+const LOAD_TIMEOUT = 20000;const args = process.argv.slice(2);function option(name, fallback) {const i = args.indexOf(name);@@ -41,6 +42,7 @@ const CHECK = `(() => {const r = el => el.getBoundingClientRect();const phone = innerWidth <= 600;const problems = [];+ if (!document.querySelector('.hb-page')) problems.push('not a guided-steps page');if (document.documentElement.scrollWidth > innerWidth + 1) problems.push('horizontal overflow');if (phone) {const small = [...document.querySelectorAll('.hb-bar a, .hb-page button, .hb-page summary, .hb-page select, .hb-page input[type=range], .hb-page .hb-text, label.hb-toggle, label.hb-switch-row, .hb-foot a, .hb-rel')]@@ -49,95 +51,145 @@ const CHECK = `(() => {.map(el => el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).split(' ')[0] : '') + ' ' + Math.round(r(el).width) + 'x' + Math.round(r(el).height));if (small.length) problems.push('small targets: ' + small.join(', '));}- const player = document.querySelector('.hb-player');- if (innerWidth >= 1025 && player && r(player).bottom > innerHeight) problems.push('player bar below the first screen');+ const firstScreen = document.querySelector('.hb-player') || document.querySelector('.hb-page .stage');+ if (innerWidth >= 1025 && firstScreen && r(firstScreen).bottom > innerHeight) problems.push('stage or player bar below the first screen');const tryIt = document.querySelector('.hb-try');const shown = el => { for (let n = el; n && n !== tryIt; n = n.parentElement) { if (n.hidden || n.hasAttribute('data-hb-skip') || getComputedStyle(n).display === 'none') return false; } return true; };const controls = tryIt ? [...tryIt.querySelectorAll('input[type=range], input[type=checkbox], input[type=text], textarea, select, .seg, .swatches')].filter(shown).length : 0;const chips = document.querySelectorAll('.hb-chips li').length;if (chips !== controls) problems.push('chips ' + chips + ' vs settings ' + controls);- if (!document.querySelector('.hb-what-text p')) problems.push('What it is is empty');+ const what = document.querySelector('.hb-what-text');+ if (!what || !what.querySelector('p')) problems.push('What it is is missing');+ else if (what.querySelector('a[href="README.md"]')) problems.push('What it is did not load from the README');const loop = document.querySelector('[data-hb-loop]');return { kind: document.body.dataset.hbKind || '', loop: loop ? loop.checked : null, problems };})()`;const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));-const chrome = spawn(CHROME, ['--headless=new', '--disable-gpu', '--hide-scrollbars', `--remote-debugging-port=${PORT}`,- `--user-data-dir=${mkdtempSync(join(tmpdir(), 'hb-chrome-'))}`, 'about:blank'], { stdio: 'ignore' });+const withTimeout = (promise, ms) => Promise.race([promise, sleep(ms).then(() => { throw new Error('timeout'); })]);++const profile = mkdtempSync(join(tmpdir(), 'hb-chrome-'));+function removeProfile() {+ try { rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); }+ catch { console.error(`Could not remove the temporary Chrome profile: ${profile}`); }+}+// Port 0: Chrome picks a free port and writes it into DevToolsActivePort in its profile folder,+// so a Chrome left over from an earlier run can never be picked up by mistake.+const chrome = spawn(CHROME, ['--headless=new', '--disable-gpu', '--hide-scrollbars', '--remote-debugging-port=0',+ `--user-data-dir=${profile}`, 'about:blank'], { stdio: 'ignore' });+const chromeExited = new Promise(resolve => chrome.once('exit', resolve));+chrome.once('error', err => {+ console.error(`Could not start Chrome at ${CHROME} (${err.message}). Set CHROME to its path.`);+ removeProfile();+ process.exit(2);+});async function pageSocket() {- for (let i = 0; i < 50; i++) {- try {- const list = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();- const page = list.find(t => t.type === 'page');- if (page) return page.webSocketDebuggerUrl;- } catch {}- await sleep(200);+ const portFile = join(profile, 'DevToolsActivePort');+ for (let i = 0; i < 100; i++) {+ if (existsSync(portFile)) {+ const port = readFileSync(portFile, 'utf8').split('\n')[0].trim();+ try {+ const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();+ const page = list.find(t => t.type === 'page');+ if (page) return page.webSocketDebuggerUrl;+ } catch {}+ }+ await sleep(100);}- throw new Error('Chrome did not start (set CHROME to its path if it is not in the default place)');+ throw new Error('Chrome started but its DevTools port did not answer');}-const ws = new WebSocket(await pageSocket());-await new Promise(resolve => ws.addEventListener('open', resolve, { once: true }));+let ws = null;let nextId = 0;const pending = new Map();const listeners = new Set();-ws.addEventListener('message', event => {- const msg = JSON.parse(event.data);- if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } else listeners.forEach(fn => fn(msg));-});-const send = (method, params = {}) => new Promise((resolve, reject) => {- const id = ++nextId;- pending.set(id, msg => (msg.error ? reject(new Error(`${method}: ${msg.error.message}`)) : resolve(msg.result)));- ws.send(JSON.stringify({ id, method, params }));-});+function send(method, params = {}) {+ return new Promise((resolve, reject) => {+ const id = ++nextId;+ pending.set(id, msg => (msg.error ? reject(new Error(`${method}: ${msg.error.message}`)) : resolve(msg.result)));+ ws.send(JSON.stringify({ id, method, params }));+ });+}+function failPending(reason) {+ for (const done of pending.values()) done({ error: { message: reason } });+ pending.clear();+}const evaluate = async expression => (await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })).result.value;-const errors = [];-listeners.add(msg => {- if (msg.method === 'Runtime.exceptionThrown') errors.push(msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text);- if (msg.method === 'Runtime.consoleAPICalled' && (msg.params.type === 'error' || msg.params.type === 'warning')) {- errors.push(msg.params.args.map(a => a.value ?? a.description).join(' '));- }- if (msg.method === 'Log.entryAdded' && msg.params.entry.level === 'error') errors.push(msg.params.entry.text + ' ' + (msg.params.entry.url || ''));-});-await send('Page.enable');-await send('Runtime.enable');-await send('Log.enable');-let failures = 0;-for (const page of pages) {- for (const setup of SETUPS) {- errors.length = 0;- await send('Emulation.setDeviceMetricsOverride', { width: setup.width, height: setup.height, deviceScaleFactor: setup.scale || 1, mobile: !!setup.mobile });- await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: setup.reduce ? 'reduce' : 'no-preference' }] });- const loaded = new Promise(resolve => {- const onLoad = msg => { if (msg.method === 'Page.loadEventFired') { listeners.delete(onLoad); resolve(); } };- listeners.add(onLoad);- });- await send('Page.navigate', { url: `${BASE}/${page}` });- await loaded;- await sleep(2000);- const result = await evaluate(CHECK);- const problems = [...result.problems, ...errors.map(e => 'console: ' + e)];- if (result.kind === 'once' && result.loop !== null) {- if (setup.reduce && result.loop) problems.push('Loop switched on under reduced motion');- if (!setup.reduce && !result.loop) problems.push('did not start playing on arrival (Loop is off)');+try {+ ws = new WebSocket(await pageSocket());+ await new Promise((resolve, reject) => {+ ws.addEventListener('open', resolve, { once: true });+ ws.addEventListener('error', () => reject(new Error('Could not connect to Chrome')), { once: true });+ });+ ws.addEventListener('message', event => {+ const msg = JSON.parse(event.data);+ if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } else listeners.forEach(fn => fn(msg));+ });+ ws.addEventListener('close', () => failPending('Chrome closed the connection'));++ const errors = [];+ listeners.add(msg => {+ if (msg.method === 'Runtime.exceptionThrown') errors.push(msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text);+ if (msg.method === 'Runtime.consoleAPICalled' && (msg.params.type === 'error' || msg.params.type === 'warning')) {+ errors.push(msg.params.args.map(a => a.value ?? a.description).join(' '));}- const name = page.replace(/\/$/, '').split('/').pop();- const shot = await send('Page.captureScreenshot', { format: 'png' });- writeFileSync(join(OUT, `${name}-${setup.name}.png`), Buffer.from(shot.data, 'base64'));- if (setup.full) {- const { cssContentSize } = await send('Page.getLayoutMetrics');- const full = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true,- clip: { x: 0, y: 0, width: setup.width, height: Math.ceil(cssContentSize.height), scale: 1 } });- writeFileSync(join(OUT, `${name}-${setup.name}-full.png`), Buffer.from(full.data, 'base64'));+ if (msg.method === 'Log.entryAdded' && msg.params.entry.level === 'error') errors.push(msg.params.entry.text + ' ' + (msg.params.entry.url || ''));+ });+ await send('Page.enable');+ await send('Runtime.enable');+ await send('Log.enable');++ for (const page of pages) {+ const parts = page.replace(/\/$/, '').split('/');+ const name = `${parts[parts.length - 2].slice(0, 2)}-${parts[parts.length - 1]}`;+ for (const setup of SETUPS) {+ errors.length = 0;+ const problems = [];+ try {+ await send('Emulation.setDeviceMetricsOverride', { width: setup.width, height: setup.height, deviceScaleFactor: setup.scale || 1, mobile: !!setup.mobile });+ await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: setup.reduce ? 'reduce' : 'no-preference' }] });+ let onLoad;+ const loaded = new Promise(resolve => {+ onLoad = msg => { if (msg.method === 'Page.loadEventFired') resolve(); };+ listeners.add(onLoad);+ });+ await send('Page.navigate', { url: `${BASE}/${page}` });+ try { await withTimeout(loaded, LOAD_TIMEOUT); } catch { problems.push(`page did not finish loading within ${LOAD_TIMEOUT / 1000} s`); }+ listeners.delete(onLoad);+ await sleep(2000);+ const result = await evaluate(CHECK);+ problems.push(...result.problems);+ if (result.kind === 'once' && result.loop !== null) {+ if (setup.reduce && result.loop) problems.push('Loop switched on under reduced motion');+ if (!setup.reduce && !result.loop) problems.push('did not start playing on arrival (Loop is off)');+ }+ const shot = await send('Page.captureScreenshot', { format: 'png' });+ writeFileSync(join(OUT, `${name}-${setup.name}.png`), Buffer.from(shot.data, 'base64'));+ if (setup.full) {+ const { cssContentSize } = await send('Page.getLayoutMetrics');+ const full = await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true,+ clip: { x: 0, y: 0, width: setup.width, height: Math.ceil(cssContentSize.height), scale: 1 } });+ writeFileSync(join(OUT, `${name}-${setup.name}-full.png`), Buffer.from(full.data, 'base64'));+ }+ } catch (err) {+ problems.push(`check failed: ${err.message}`);+ }+ problems.push(...errors.map(e => 'console: ' + e));+ if (problems.length) failures++;+ console.log(`${problems.length ? 'FAIL' : 'ok '} ${name} ${setup.name}${problems.length ? ' — ' + problems.join('; ') : ''}`);}- if (problems.length) failures++;- console.log(`${problems.length ? 'FAIL' : 'ok '} ${name} ${setup.name}${problems.length ? ' — ' + problems.join('; ') : ''}`);}+ console.log(`Screenshots: ${OUT}`);+} catch (err) {+ console.error(err.message);+ failures++;+} finally {+ if (ws) ws.close();+ chrome.kill();+ await Promise.race([chromeExited, sleep(5000)]);+ removeProfile();}-console.log(`Screenshots: ${OUT}`);-ws.close();-chrome.kill();process.exit(failures ? 1 : 0);