Merge pull request #251 from jhd3197/feat/ux-layout-snapshots
test(ui): add screenshot regression checks for phone, tablet and desktop
No files matched your search
@@ -89,6 +89,9 @@ jobs:
|
||||
- name: Assistant deployment browser regressions
|
||||
working-directory: frontend
|
||||
run: npm run test:ai-operations
|
||||
- name: Layout screenshot regressions
|
||||
working-directory: frontend
|
||||
run: npm run test:layout
|
||||
- name: Upload Settings screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
|
||||
@@ -132,6 +132,10 @@ SECURITY_AND_CODE_AUDIT.md
|
||||
!/docs/screenshots/
|
||||
!/docs/screenshots/*.png
|
||||
|
||||
# Layout screenshot baselines compared by `npm run test:layout`.
|
||||
!/frontend/tests/layout-baselines/
|
||||
!/frontend/tests/layout-baselines/*.png
|
||||
|
||||
# Video walkthrough thumbnails linked from the README.
|
||||
!/docs/videos/*.png
|
||||
|
||||
|
||||
@@ -86,6 +86,14 @@ VITE_API_URL=https://api.example.com
|
||||
|
||||
Access them in code via `import.meta.env.VITE_API_URL`.
|
||||
|
||||
## Layout screenshot regressions
|
||||
|
||||
`npm run test:layout` renders the main pages at 390, 768 and 1440 px from synthetic
|
||||
fixtures and compares them with `tests/layout-baselines/`. After an intended UI
|
||||
change run `LAYOUT_UPDATE=1 npm run test:layout` and commit the new PNGs; failures
|
||||
leave actual/diff images in `test-results/layout/`. See the header of
|
||||
`scripts/layout-screenshots-browser.mjs` for the options.
|
||||
|
||||
## Contributing
|
||||
|
||||
See the documentation files for AI agent permissions and guidelines.
|
||||
@@ -11,6 +11,7 @@
|
||||
"test:settings-ui": "node scripts/settings-ui-browser.mjs",
|
||||
"lint": "node scripts/lint.mjs && node scripts/check-font-integrity.mjs && node scripts/check-settings-index.mjs && node scripts/check-theme-tokens.mjs && node scripts/check-frontend-boundaries.mjs && node scripts/check-style-ownership.mjs && node scripts/check-status-one-door.mjs && node scripts/check-shared-fields.mjs && node scripts/check-tables.mjs && node scripts/check-type-scale.mjs && node scripts/check-geometry.mjs && node scripts/check-status-scss.mjs && node scripts/check-i18n-literals.mjs && node scripts/check-intl-door.mjs && node scripts/extract-i18n.mjs --check && node scripts/check-i18n.mjs && node scripts/check-logical-properties.mjs && node scripts/generate-vendor-shims.mjs --check && node ../scripts/check-html-sinks.mjs && node scripts/check-orphan-files.mjs && node scripts/check-label-association.mjs",
|
||||
"lint:baseline": "node scripts/lint.mjs --update",
|
||||
"test:layout": "node scripts/layout-screenshots-browser.mjs",
|
||||
"test:controls": "node scripts/controls-browser.mjs",
|
||||
"test:metrics": "node scripts/metrics-browser.mjs",
|
||||
"measure:build": "node scripts/measure-build.mjs",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Synthetic API responses for layout-screenshots-browser.mjs. example.test data only.
|
||||
const T = '2026-01-14T09:30:00Z';
|
||||
const user = { id: 1, username: 'operator', email: 'operator@example.test', role: 'admin', is_active: true, auth_provider: 'local', permissions: {}, created_at: T, totp_enabled: false };
|
||||
const servers = [
|
||||
{ id: 'srv-1', name: 'web-01.example.test', hostname: 'web-01.example.test', ip_address: '192.0.2.10', status: 'online', is_local: true, os_type: 'linux', os_version: 'Ubuntu 24.04', agent_version: '1.0.0', permission_level_effective: 'standard', created_at: T, last_seen: T },
|
||||
{ id: 'srv-2', name: 'db-01.example.test', hostname: 'db-01.example.test', ip_address: '192.0.2.11', status: 'offline', os_type: 'linux', os_version: 'Debian 12', agent_version: '1.0.0', permission_level_effective: 'standard', created_at: T, last_seen: T },
|
||||
];
|
||||
const apps = [
|
||||
{ id: 1, name: 'blog', domains: ['blog.example.test'], status: 'running', app_type: 'docker', stack: 'node', created_at: T, updated_at: T },
|
||||
{ id: 2, name: 'shop', domains: ['shop.example.test'], status: 'stopped', app_type: 'php', stack: 'php', created_at: T, updated_at: T },
|
||||
];
|
||||
const notifications = [
|
||||
{ delivery_id: 1, title: 'Backup completed', body: 'Nightly backup finished for blog.example.test', severity: 'info', category: 'backup', read: false, is_read: false, created_at: T },
|
||||
{ delivery_id: 2, title: 'Certificate expiring', body: 'shop.example.test expires in 12 days', severity: 'warning', category: 'ssl', read: true, is_read: true, created_at: T },
|
||||
];
|
||||
const certificates = [
|
||||
{ domain: 'blog.example.test', issuer: "Let's Encrypt", status: 'valid', days_remaining: 62, expires_at: '2026-03-18T00:00:00Z', auto_renew: true },
|
||||
{ domain: 'shop.example.test', issuer: "Let's Encrypt", status: 'expiring', days_remaining: 12, expires_at: '2026-01-27T00:00:00Z', auto_renew: false },
|
||||
];
|
||||
|
||||
// Longest-prefix-free rules, first match wins. Anything else answers `{}`.
|
||||
const RULES = [
|
||||
[/^\/auth\/setup-status/, { needs_setup: false, registration_enabled: false }],
|
||||
[/^\/auth\/me/, { user }],
|
||||
[/^\/plugins\/contributions/, { contributions: [], routes: [], items: [] }],
|
||||
[/^\/servers\/groups/, []],
|
||||
[/^\/servers\/?$/, servers],
|
||||
[/^\/servers\/available/, { servers }],
|
||||
[/^\/(apps|services)/, { apps, services: apps, total: apps.length }],
|
||||
[/^\/notifications/, { notifications, items: notifications, unread_count: 1, total: 2 }],
|
||||
[/^\/ssl/, { certificates, items: certificates }],
|
||||
[/^\/queues?/, { groups: [], queues: [] }],
|
||||
];
|
||||
|
||||
export function fixtureFor(path) {
|
||||
return RULES.find(([re]) => re.test(path))?.[1];
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* Layout screenshot regressions: main pages at phone (390x844), tablet
|
||||
* (768x1024) and desktop (1440x900), rendered from synthetic API fixtures
|
||||
* (no backend, no network), compared with committed baselines.
|
||||
*
|
||||
* Per snapshot it asserts: no page-level horizontal scroll, no visible control
|
||||
* clipped by the viewport edge (outside intentional overflow-x scrollers), the
|
||||
* page header is present and there is no uncaught page error. Then it diffs the
|
||||
* viewport screenshot against tests/layout-baselines/<page>-<width>[-light].png
|
||||
* (per-channel tolerance, fails above LAYOUT_DIFF_RATIO of pixels differing).
|
||||
* A pixel only counts as different if it mismatches the baseline at the same
|
||||
* position AND no pixel within 1px in the other image matches it, checked in
|
||||
* both directions (like pixelmatch's AA detection): text anti-aliasing/hinting
|
||||
* differences between machines pass, moved or resized boxes still fail.
|
||||
* Chromium is launched with fixed font-rendering flags to keep text stable.
|
||||
*
|
||||
* npm run test:layout # check
|
||||
* LAYOUT_UPDATE=1 npm run test:layout # rewrite baselines
|
||||
* LAYOUT_ONLY=dashboard,ssl npm run test:layout
|
||||
* LAYOUT_DIFF_RATIO=0.01 npm run test:layout
|
||||
*
|
||||
* A missing baseline is created locally and fails under CI. On a diff, the
|
||||
* actual and diff (magenta) images land in test-results/layout/. Diffs appear
|
||||
* when layout/CSS changes (update the baselines in the same commit if intended)
|
||||
* or when fonts/rendering differ from the machine that made the baselines;
|
||||
* regenerate with the Playwright chromium that CI installs.
|
||||
*/
|
||||
import { createServer } from 'vite';
|
||||
import { chromium } from 'playwright';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { fixtureFor } from './layout-fixtures.mjs';
|
||||
|
||||
const DIFF_RATIO = Number(process.env.LAYOUT_DIFF_RATIO ?? 0.002);
|
||||
const TOLERANCE = 24;
|
||||
const LAUNCH_ARGS = ['--font-render-hinting=none', '--disable-font-subpixel-positioning', '--disable-lcd-text', '--force-color-profile=srgb'];
|
||||
const OUT = 'test-results/layout';
|
||||
const BASE_DIR = 'tests/layout-baselines';
|
||||
const NOW = '2026-01-15T12:00:00Z';
|
||||
const WIDTHS = { 390: 844, 768: 1024, 1440: 900 };
|
||||
const PAGES = [
|
||||
{ key: 'dashboard', path: '/' },
|
||||
{ key: 'servers', path: '/servers' },
|
||||
{ key: 'services', path: '/services' },
|
||||
{ key: 'monitoring', path: '/monitoring' },
|
||||
{ key: 'notifications', path: '/notifications' },
|
||||
{ key: 'settings', path: '/settings/general' },
|
||||
{ key: 'ssl', path: '/ssl' },
|
||||
{ key: 'queue', path: '/queue' },
|
||||
];
|
||||
const only = (process.env.LAYOUT_ONLY || '').split(',').filter(Boolean);
|
||||
const jobs = [];
|
||||
for (const p of PAGES) {
|
||||
if (only.length && !only.includes(p.key)) continue;
|
||||
for (const w of Object.keys(WIDTHS)) jobs.push({ ...p, width: Number(w), theme: 'dark' });
|
||||
}
|
||||
if (!only.length || only.includes('dashboard')) jobs.push({ ...PAGES[0], width: 1440, theme: 'light' });
|
||||
|
||||
const FREEZE_CSS = `*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}`;
|
||||
|
||||
// Runs inside the page: loads both PNGs into canvases and counts differing pixels.
|
||||
const diffInPage = async ({ a, b, tol }) => {
|
||||
const load = (src) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = src; });
|
||||
const [ia, ib] = await Promise.all([load(a), load(b)]);
|
||||
if (ia.width !== ib.width || ia.height !== ib.height) return { size: false };
|
||||
const read = (img) => { const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; const x = c.getContext('2d'); x.drawImage(img, 0, 0); return x.getImageData(0, 0, c.width, c.height); };
|
||||
const da = read(ia); const db = read(ib);
|
||||
const out = new ImageData(ia.width, ia.height);
|
||||
const { width: W, height: H } = ia;
|
||||
const near = (x, y, i, o) => Math.abs(x[i] - y[o]) <= tol && Math.abs(x[i + 1] - y[o + 1]) <= tol && Math.abs(x[i + 2] - y[o + 2]) <= tol;
|
||||
// true if any pixel of `d` within 1px of (px,py) matches pixel i of `s` (AA shifts glyph edges by <=1px)
|
||||
const matchesAround = (s, d, i, px, py) => {
|
||||
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
|
||||
const x = px + dx; const y = py + dy;
|
||||
if (x >= 0 && y >= 0 && x < W && y < H && near(s, d, i, (y * W + x) * 4)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
let count = 0;
|
||||
for (let i = 0; i < da.data.length; i += 4) {
|
||||
const px = (i / 4) % W; const py = Math.floor(i / 4 / W);
|
||||
const bad = !near(da.data, db.data, i, i) && !matchesAround(da.data, db.data, i, px, py) && !matchesAround(db.data, da.data, i, px, py);
|
||||
if (bad) { count++; out.data.set([255, 0, 255, 255], i); } else out.data.set([db.data[i], db.data[i + 1], db.data[i + 2], 80], i);
|
||||
}
|
||||
const c = document.createElement('canvas'); c.width = ia.width; c.height = ia.height; c.getContext('2d').putImageData(out, 0, 0);
|
||||
return { size: true, count, total: ia.width * ia.height, diff: c.toDataURL('image/png') };
|
||||
};
|
||||
|
||||
// Runs inside the page: layout invariants; returns a list of problems.
|
||||
const invariants = () => {
|
||||
const problems = [];
|
||||
const root = document.documentElement;
|
||||
if (root.scrollWidth > root.clientWidth + 1) problems.push(`page scrolls horizontally (${root.scrollWidth} > ${root.clientWidth})`);
|
||||
if (!document.querySelector('header, [role=banner], .page-header, .topbar, .header')) problems.push('page header/topbar missing');
|
||||
const inScroller = (el) => { for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) { if (/(auto|scroll)/.test(getComputedStyle(p).overflowX) && p.scrollWidth > p.clientWidth) return true; } return false; };
|
||||
for (const el of document.querySelectorAll('button, a, input, select, [role=button]')) {
|
||||
const r = el.getBoundingClientRect(); const s = getComputedStyle(el);
|
||||
if (!r.width || !r.height || s.visibility === 'hidden' || s.display === 'none' || el.closest('[hidden],[aria-hidden=true],[inert]')) continue;
|
||||
if ((r.left < -1 || r.right > root.clientWidth + 1) && !inScroller(el)) {
|
||||
problems.push(`control clipped horizontally: <${el.tagName.toLowerCase()}> "${(el.getAttribute('aria-label') || el.textContent || '').trim().slice(0, 40)}" [${Math.round(r.left)}..${Math.round(r.right)}]`);
|
||||
if (problems.length > 8) break;
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
};
|
||||
|
||||
const server = await createServer({ server: { host: '127.0.0.1', port: 0, strictPort: false, open: false } });
|
||||
let browser;
|
||||
const failures = [];
|
||||
const started = Date.now();
|
||||
try {
|
||||
await server.listen();
|
||||
const base = server.resolvedUrls.local[0];
|
||||
const origin = new URL(base).origin;
|
||||
browser = await chromium.launch({ headless: true, args: LAUNCH_ARGS });
|
||||
await mkdir(OUT, { recursive: true });
|
||||
await mkdir(BASE_DIR, { recursive: true });
|
||||
const diffPage = await browser.newPage();
|
||||
for (const job of jobs) {
|
||||
const name = `${job.key}-${job.width}${job.theme === 'light' ? '-light' : ''}`;
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: job.width, height: WIDTHS[job.width] }, locale: 'en-US', timezoneId: 'UTC',
|
||||
reducedMotion: 'reduce', colorScheme: job.theme, deviceScaleFactor: 1,
|
||||
});
|
||||
await context.addInitScript((theme) => {
|
||||
localStorage.setItem('access_token', 'synthetic-browser-fixture');
|
||||
localStorage.setItem('theme', theme);
|
||||
document.addEventListener('DOMContentLoaded', () => document.documentElement.setAttribute('data-theme', theme), { once: true });
|
||||
}, job.theme);
|
||||
const page = await context.newPage();
|
||||
await page.clock.install({ time: new Date(NOW) });
|
||||
const errors = [];
|
||||
page.on('pageerror', (e) => errors.push(e.message));
|
||||
await page.routeWebSocket(/socket\.io/, (ws) => ws.close());
|
||||
await page.route('**/*', (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
// .env may point the API at a local backend port; serve that from fixtures too
|
||||
const local = ['localhost', '127.0.0.1'].includes(url.hostname);
|
||||
if (!local || (url.origin !== origin && !url.pathname.startsWith('/api/v1/'))) { if (process.env.LAYOUT_DEBUG) console.log(' abort', url.href); return route.abort(); }
|
||||
if (url.pathname.startsWith('/socket.io/')) return route.abort(); // no live socket: keeps data static
|
||||
if (!url.pathname.startsWith('/api/v1/')) return route.continue();
|
||||
const body = fixtureFor(url.pathname.slice('/api/v1'.length), route.request().method());
|
||||
if (process.env.LAYOUT_DEBUG) console.log(` api ${name} ${url.pathname}${body === undefined ? ' (unhandled)' : ''}`);
|
||||
return route.fulfill({ json: body ?? {} });
|
||||
});
|
||||
await page.goto(`${base.replace(/\/$/, '')}${job.path}`, { waitUntil: 'networkidle' });
|
||||
await page.addStyleTag({ content: FREEZE_CSS });
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
await page.clock.runFor(1000);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.waitForFunction(() => !document.querySelector('[class*=skeleton], [aria-busy=true], [role=progressbar], .spinner, .loading'), null, { timeout: 10000 }).catch(async () => { if (process.env.LAYOUT_DEBUG) console.log(' busy:', await page.evaluate(() => [...document.querySelectorAll('[class*=skeleton], [aria-busy=true], [role=progressbar], .spinner, .loading')].map((e) => e.className).join(' | '))); });
|
||||
const problems = await page.evaluate(invariants);
|
||||
errors.forEach((e) => problems.push(`uncaught page error: ${e}`));
|
||||
const shot = await page.screenshot({ animations: 'disabled', caret: 'hide' });
|
||||
await context.close();
|
||||
|
||||
const file = `${BASE_DIR}/${name}.png`;
|
||||
if (process.env.LAYOUT_UPDATE || !existsSync(file)) {
|
||||
if (!process.env.LAYOUT_UPDATE && process.env.CI) problems.push(`baseline ${file} is missing (run LAYOUT_UPDATE=1 npm run test:layout and commit it)`);
|
||||
else await writeFile(file, shot);
|
||||
} else {
|
||||
const res = await diffPage.evaluate(diffInPage, { a: `data:image/png;base64,${shot.toString('base64')}`, b: `data:image/png;base64,${(await readFile(file)).toString('base64')}`, tol: TOLERANCE });
|
||||
if (!res.size || res.count / res.total > DIFF_RATIO) {
|
||||
await writeFile(`${OUT}/${name}.actual.png`, shot);
|
||||
if (res.size) await writeFile(`${OUT}/${name}.diff.png`, Buffer.from(res.diff.split(',')[1], 'base64'));
|
||||
problems.push(res.size ? `pixel diff ${(100 * res.count / res.total).toFixed(2)}% > ${(100 * DIFF_RATIO).toFixed(2)}% (see ${OUT}/${name}.diff.png)` : 'screenshot size differs from baseline');
|
||||
}
|
||||
}
|
||||
for (const p of problems) failures.push(`${job.key}@${job.width}${job.theme === 'light' ? ' (light)' : ''}: ${p}`);
|
||||
console.log(`${problems.length ? 'FAIL' : 'ok '} ${name}`);
|
||||
}
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await server.close();
|
||||
}
|
||||
console.log(`${jobs.length} snapshots in ${((Date.now() - started) / 1000).toFixed(1)}s`);
|
||||
if (failures.length) {
|
||||
console.error(`\nLayout regressions:\n - ${failures.join('\n - ')}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 110 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 42 KiB |