Mobile guard: real-browser overflow suite, card-grid + HtmlBlock mobile hooks, wide custom HTML publish warning
- scripts/e2e-mobile-guard.mjs (npm run test:browser:mobile-guard): Chromium + Firefox at 360/390/768/1280 over
exporter-built pages (navbar, columns, FeaturesGrid/Testimonials/NumberCounter/Gallery/Pricing/Reviews, big
image, long word/URL, wide customer HtmlBlocks). Asserts body.scrollWidth and every visible box/text right edge
(html,body{overflow-x:clip} hides overflow from documentElement.scrollWidth), stacking on phones, columns kept
on tablet, navbar wrap, intentional overflow-x:auto still scrolls, and 1280 box + pixel identity with the hooks
removed (optional cross-commit baseline).
- OLS home overflow was FeaturesGrid (inline repeat(3,1fr)), not an HtmlBlock. FeaturesGrid, Testimonials and
NumberCounter grids carry data-wsb-grid; the <=767px head block makes them one column.
- HtmlBlock output is exported inside <div data-wsb-html style="display:contents"> (applied after attr
injection, toHtml().html unchanged); on phones it becomes a max-width:100% sideways-scrolling box, media
shrink, long words break. body{overflow-wrap:break-word} on phones. Navbar link wrap now up to 991px
(8 links + long logo overflowed at 768).
- Head parity pins updated (mirror in WHP generateCompiledHTML); editor.css mirrors for the mobile frame.
- publish-checks: warn when an HtmlBlock's inline/<style> CSS sets widths, flex sizes or grids over 390px or a
3+ column grid with no phone @media rule; says what is not checked.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f9be5f41a
commit
bb4fb7548b
15 files changed
+647
-27
No files matched your search
@@ -0,0 +1,110 @@
|
||||
// Bundled (browser IIFE) by scripts/e2e-mobile-guard.mjs. Builds representative published documents
|
||||
// with the REAL exporter (exportBodyHtml + exportComposedPreviewHtml, the Preview/publish path) so the
|
||||
// real-browser suite measures exactly what customers get. HtmlBlock sanitising needs a DOM, which is
|
||||
// why this runs inside the browser rather than in node.
|
||||
// Uses only exports that exist before and after the mobile-guard change, so the SAME harness can record
|
||||
// a desktop baseline on the base commit (MOBILE_GUARD_RECORD).
|
||||
import { exportBodyHtml, exportComposedPreviewHtml } from '../src/utils/html-export';
|
||||
import { componentResolver } from '../src/components/resolver';
|
||||
|
||||
type N = Record<string, any>;
|
||||
const defaults = (type: string): Record<string, unknown> => {
|
||||
const c = (componentResolver as any)[type];
|
||||
return c?.craft?.props ? JSON.parse(JSON.stringify(c.craft.props)) : {};
|
||||
};
|
||||
const node = (type: string, props: Record<string, unknown>, nodes: string[] = [], extra: N = {}) => ({
|
||||
type: { resolvedName: type }, isCanvas: type === 'Container', props: { ...defaults(type), ...props }, displayName: type,
|
||||
custom: {}, hidden: false, nodes, linkedNodes: {}, ...extra,
|
||||
});
|
||||
const LONG = 'Honest prices, straight answers and work that is finished when we say it will be, every time.';
|
||||
|
||||
function columns(nodes: N, id: string, split: string, n: number) {
|
||||
const linked: Record<string, string> = {};
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = `${id}-c${i}`; const t = `${id}-t${i}`;
|
||||
nodes[c] = node('Container', { tag: 'div', style: { padding: '8px' } }, [t], { parent: id });
|
||||
nodes[t] = node('TextBlock', { text: `${LONG} (${id} col ${i + 1})`, style: { fontSize: '16px' } }, [], { parent: c });
|
||||
linked[`col-${i}`] = c;
|
||||
}
|
||||
nodes[id] = node('ColumnLayout', { columns: n, gap: '16px', split }, [], { parent: 'ROOT', linkedNodes: linked });
|
||||
}
|
||||
|
||||
const NAV_LINKS = ['Home', 'About us', 'Services', 'Our work', 'Pricing', 'Testimonials', 'Blog', 'Contact us'].map((text, i, a) => ({
|
||||
text, href: '#' + text.toLowerCase().replace(/\s/g, '-'), ...(i === a.length - 1 ? { isCta: true } : {}),
|
||||
}));
|
||||
|
||||
/** showMobileMenu false = every Navbar saved before the hamburger existed (links must wrap);
|
||||
* true = the default for a newly dropped Navbar (hamburger). */
|
||||
function header(showMobileMenu: boolean): string {
|
||||
const nodes: N = { nav: node('Navbar', { logoText: 'Acme Plumbing & Heating Ltd', links: NAV_LINKS, padding: '16px 24px', showMobileMenu }, [], { parent: 'ROOT' }) };
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: {} }, ['nav']);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
/** First-party components only: every one of them must fit every width. */
|
||||
export function componentsState(): string {
|
||||
const nodes: N = {};
|
||||
const kids: string[] = [];
|
||||
const add = (id: string, type: string, props: Record<string, unknown> = {}) => { nodes[id] = node(type, props, [], { parent: 'ROOT' }); kids.push(id); };
|
||||
add('hero', 'HeroSimple', { title: 'Plumbing and heating you can actually rely on', subtitle: LONG });
|
||||
for (const [id, split, n] of [['c2', '50-50', 2], ['c3', '33-33-33', 3], ['c4', '25-25-25-25', 4], ['side', '30-70', 2]] as const) { columns(nodes, id, split, n); kids.push(id); }
|
||||
add('features', 'FeaturesGrid');
|
||||
add('testimonials', 'Testimonials');
|
||||
add('counter', 'NumberCounter');
|
||||
add('gallery', 'Gallery');
|
||||
add('pricing', 'PricingTable');
|
||||
add('reviews', 'ReviewsStrip');
|
||||
add('img', 'ImageBlock', { src: 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="600"><rect width="1600" height="600" fill="#888"/></svg>') });
|
||||
add('longword', 'TextBlock', { text: 'Supercalifragilisticexpialidociouslyunbreakablewordthatgoesonandonandonforeverandever and https://example.com/a/really/long/path/that/never/breaks/because/it/has/no/spaces/at/all?query=string&more=yes' });
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: {} }, kids);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
/** Customer raw HTML that is wider than a phone. Keyed by node id so the runner can name offenders. */
|
||||
export const HTML_BLOCKS: Record<string, string> = {
|
||||
hbFixed: '<div style="width:1100px;background:#eee;padding:20px">A fixed 1100px banner</div>',
|
||||
hbGridPx: '<div style="display:grid;grid-template-columns:repeat(3,300px);gap:20px"><div style="padding:16px;border:1px solid #ccc">One</div><div style="padding:16px;border:1px solid #ccc">Two</div><div style="padding:16px;border:1px solid #ccc">Three</div></div>',
|
||||
hbGridFr: '<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:32px"><div style="padding:24px"><h3>Multi-Brand Portfolio</h3></div><div style="padding:24px"><h3>Hosting</h3></div><div style="padding:24px"><h3>StreamerTools</h3></div><div style="padding:24px"><h3>Consultancy</h3></div></div>',
|
||||
hbStyleFlex: '<style>.cards{display:flex;gap:16px}.card{flex:0 0 360px;padding:16px;border:1px solid #ccc}</style><div class="cards"><div class="card">A</div><div class="card">B</div><div class="card">C</div></div>',
|
||||
hbMinWidth: '<div style="min-width:900px">min-width 900px content</div>',
|
||||
hbIframe: '<iframe width="800" height="450" src="about:blank" title="video"></iframe>',
|
||||
hbImg: '<img src="data:image/gif;base64,R0lGODlhAQABAAAAACw=" width="1200" height="400" alt="">',
|
||||
hbTableBare: '<table><tr>' + Array.from({ length: 10 }, (_, i) => `<td>Column_heading_${i}</td>`).join('') + '</tr></table>',
|
||||
hbPre: '<pre>const reallyLongLine = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";</pre>',
|
||||
hbUrl: '<p>See https://example.com/a/really/long/path/that/never/breaks/because/it/has/no/spaces/at/all/ok</p>',
|
||||
// Deliberate horizontal scroller: must STILL scroll (the net must not flatten or clip it).
|
||||
hbScrollTable: '<div id="intentional-scroll" style="overflow-x:auto"><table style="width:1000px"><tr><td>a</td><td>b</td><td>c</td></tr></table></div>',
|
||||
};
|
||||
|
||||
export function htmlBlocksState(): string {
|
||||
const nodes: N = {};
|
||||
const kids: string[] = [];
|
||||
nodes.intro = node('TextBlock', { text: 'Before the custom HTML' }, [], { parent: 'ROOT' }); kids.push('intro');
|
||||
for (const [id, code] of Object.entries(HTML_BLOCKS)) { nodes[id] = node('HtmlBlock', { code }, [], { parent: 'ROOT' }); kids.push(id); }
|
||||
// Desktop-identity probes: a boxed wrapper would merge these roots into ONE flex item, stop the root
|
||||
// margins collapsing with their neighbours', and break the inline run. display:contents must not.
|
||||
nodes.flexRow = node('Container', { tag: 'div', style: { display: 'flex', flexDirection: 'row', gap: '12px' } }, ['hbRoots', 'rowText'], { parent: 'ROOT' });
|
||||
nodes.hbRoots = node('HtmlBlock', { code: '<div style="flex:1;background:#eef">root one</div><div style="flex:2;background:#fee">root two</div>' }, [], { parent: 'flexRow' });
|
||||
nodes.rowText = node('TextBlock', { text: 'flex sibling' }, [], { parent: 'flexRow' });
|
||||
kids.push('flexRow');
|
||||
nodes.marginText = node('TextBlock', { text: 'margin neighbour', style: { marginBottom: '30px' } }, [], { parent: 'ROOT' }); kids.push('marginText');
|
||||
nodes.hbMargins = node('HtmlBlock', { code: '<h2 style="margin:40px 0">Collapsing margins</h2>' }, [], { parent: 'ROOT' }); kids.push('hbMargins');
|
||||
nodes.inlineRun = node('Container', { tag: 'div', style: {} }, ['hbInline', 'inlineBtn'], { parent: 'ROOT' });
|
||||
nodes.hbInline = node('HtmlBlock', { code: '<span>inline custom</span>' }, [], { parent: 'inlineRun' });
|
||||
nodes.inlineBtn = node('ButtonLink', { text: 'inline button' }, [], { parent: 'inlineRun' });
|
||||
kids.push('inlineRun');
|
||||
nodes.outro = node('TextBlock', { text: 'After the custom HTML' }, [], { parent: 'ROOT' }); kids.push('outro');
|
||||
nodes.ROOT = node('Container', { tag: 'div', style: { padding: '20px' } }, kids);
|
||||
return JSON.stringify(nodes);
|
||||
}
|
||||
|
||||
function compose(state: string, title: string, showMobileMenu: boolean): string {
|
||||
const hdr = exportBodyHtml(header(showMobileMenu), 'header').html;
|
||||
const body = exportBodyHtml(state).html;
|
||||
return exportComposedPreviewHtml(state, hdr + body, { title, includeFonts: false });
|
||||
}
|
||||
|
||||
(window as any).wsbMobileGuardDocs = (): Record<string, string> => ({
|
||||
components: compose(componentsState(), 'Components', false),
|
||||
htmlblocks: compose(htmlBlocksState(), 'Custom HTML', true),
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Mobile guard: real-browser (Chromium AND Firefox, headless) regression suite for published pages.
|
||||
* jsdom has no layout engine, so none of this can be asserted in vitest.
|
||||
*
|
||||
* npm run test:browser:mobile-guard
|
||||
*
|
||||
* Builds two representative documents with the REAL exporter (scripts/e2e-mobile-guard-entry.ts):
|
||||
* components - Navbar with 8 links, hero, ColumnLayout 2/3/4/30-70, FeaturesGrid, Testimonials,
|
||||
* NumberCounter, Gallery, PricingTable, ReviewsStrip, a 1600px image, long word + URL
|
||||
* htmlblocks - customer HtmlBlocks wider than a phone (fixed width, px grid, 1fr grid, <style> flex
|
||||
* cards, min-width, iframe, img, bare table, pre, URL) + one intentional overflow-x:auto table
|
||||
* and measures them at 360 / 390 / 768 / 1280.
|
||||
*
|
||||
* Asserted:
|
||||
* - documentElement.scrollWidth AND body.scrollWidth <= viewport (the head sets html,body{overflow-x:clip},
|
||||
* so these alone stay green while content is CLIPPED -- hence also:)
|
||||
* - the right edge of every visible element box and text line <= viewport, unless it sits inside a
|
||||
* scroll/clip container that itself fits (that content is reachable / intentionally clipped).
|
||||
* components: at every width. htmlblocks: at <=767px (the HtmlBlock net is mobile-only).
|
||||
* - ColumnLayout rows stack (one column per row) at <=767px; component card grids are one column at
|
||||
* <=767px and keep more than one column at 768 (tablet).
|
||||
* - the Navbar fits the viewport and wraps its links onto more than one row at 360/390.
|
||||
* - the intentional overflow-x:auto table still scrolls at every width.
|
||||
* - desktop (1280) is unchanged by the mobile hooks: every element box AND the full-page screenshot are
|
||||
* identical after removing them in the page (unwrap [data-wsb-html], drop data-wsb-grid). The htmlblocks
|
||||
* page carries probes a boxed wrapper would move (multi-root flex item, collapsing margins, inline run).
|
||||
* Optional cross-commit proof of the same thing:
|
||||
* MOBILE_GUARD_RECORD=<file> write the 1280 boxes (run this on the base commit)
|
||||
* MOBILE_GUARD_BASELINE=<file> assert 1280 boxes equal that recording
|
||||
*
|
||||
* Env: CHROMIUM_PATH / FIREFOX_PATH (when the Playwright-pinned builds are not installed),
|
||||
* MOBILE_ONLY=chromium|firefox.
|
||||
*/
|
||||
import { chromium, firefox } from '@playwright/test';
|
||||
import { build as esbuild } from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = await esbuild({
|
||||
entryPoints: [path.join(root, 'scripts/e2e-mobile-guard-entry.ts')],
|
||||
bundle: true, write: false, format: 'iife', platform: 'browser', jsx: 'automatic', logLevel: 'error',
|
||||
define: { 'process.env.NODE_ENV': '"production"', __EDITOR_BUILD__: '"test"' },
|
||||
});
|
||||
const js = out.outputFiles[0].text;
|
||||
const WIDTHS = [360, 390, 768, 1280];
|
||||
const MOBILE_MAX = 767;
|
||||
|
||||
/** Runs in the page. */
|
||||
function measure() {
|
||||
const vw = window.innerWidth;
|
||||
const skip = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE']);
|
||||
// An ancestor (below body) that scrolls or clips horizontally and itself fits the viewport keeps its
|
||||
// content reachable (auto/scroll) or deliberately hidden (hidden/clip): not page overflow.
|
||||
const contained = (el) => {
|
||||
for (let a = el.parentElement; a && a !== document.body && a !== document.documentElement; a = a.parentElement) {
|
||||
if (getComputedStyle(a).overflowX !== 'visible' && a.getBoundingClientRect().right <= vw + 0.5) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const label = (el) => {
|
||||
const host = el.closest('[id]');
|
||||
return `${el.tagName.toLowerCase()}${host ? ' in #' + host.id : ''} "${(el.textContent || '').trim().slice(0, 24)}"`;
|
||||
};
|
||||
let maxRight = 0; let worst = '';
|
||||
const bump = (right, el) => { if (right > maxRight) { maxRight = right; worst = label(el); } };
|
||||
for (const el of document.body.querySelectorAll('*')) {
|
||||
if (skip.has(el.tagName)) continue;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!(r.width || r.height) || getComputedStyle(el).visibility === 'hidden' || contained(el)) continue;
|
||||
bump(r.right, el);
|
||||
}
|
||||
const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||
for (let n = tw.nextNode(); n; n = tw.nextNode()) {
|
||||
const el = n.parentElement;
|
||||
if (!el || skip.has(el.tagName) || !n.textContent.trim() || contained(n)) continue;
|
||||
const range = document.createRange(); range.selectNodeContents(n);
|
||||
for (const r of range.getClientRects()) if (r.width) bump(r.right, el);
|
||||
}
|
||||
// Distinct rows among boxes: a box starts a new row when its top is below the previous row's bottom.
|
||||
const rowsOf = (kids) => {
|
||||
const rs = kids.map((k) => k.getBoundingClientRect()).filter((r) => r.height > 0).sort((a, b) => a.top - b.top);
|
||||
let rows = 0; let bottom = -Infinity;
|
||||
for (const r of rs) { if (r.top >= bottom - 1) { rows++; bottom = r.bottom; } else bottom = Math.max(bottom, r.bottom); }
|
||||
return rows;
|
||||
};
|
||||
const realKids = (w) => [...w.children].filter((c) => !skip.has(c.tagName));
|
||||
const cols = [...document.querySelectorAll('[class^="cols_"]')].map((w) => ({ n: realKids(w).length, rows: rowsOf(realKids(w)) }));
|
||||
// Every CSS grid the first-party components emit (inline display:grid), keyed by its section.
|
||||
const grids = [...document.querySelectorAll('div')].filter((d) => getComputedStyle(d).display === 'grid' && !d.closest('[data-wsb-html]') && !d.closest('[id^="hb"]')).map((g) => {
|
||||
const kids = realKids(g).filter((k) => k.getBoundingClientRect().height > 0);
|
||||
const firstTop = kids.length ? Math.round(kids[0].getBoundingClientRect().top) : 0;
|
||||
return {
|
||||
where: (g.closest('section')?.textContent || '').trim().slice(0, 30),
|
||||
hook: g.hasAttribute('data-wsb-grid'),
|
||||
// A grid of images (Gallery) shrinks its thumbnails instead of overflowing; it may keep its columns.
|
||||
imagesOnly: kids.length > 0 && kids.every((k) => k.tagName === 'IMG' || k.querySelector('img')),
|
||||
n: kids.length, perRow: kids.filter((k) => Math.round(k.getBoundingClientRect().top) === firstTop).length,
|
||||
};
|
||||
});
|
||||
const nav = document.querySelector('nav');
|
||||
let navRight = 0; let linkRows = null;
|
||||
if (nav) {
|
||||
for (const el of [nav, ...nav.querySelectorAll('*')]) { const r = el.getBoundingClientRect(); if (r.width || r.height) navRight = Math.max(navRight, r.right); }
|
||||
const links = [...nav.querySelectorAll('.navbar-link, .navbar-cta')].filter((a) => a.getBoundingClientRect().height > 0);
|
||||
linkRows = links.length ? rowsOf(links) : null; // null: links collapsed behind the hamburger
|
||||
}
|
||||
const sc = document.getElementById('intentional-scroll');
|
||||
let scrolls = null;
|
||||
if (sc) { sc.scrollLeft = 50; scrolls = sc.scrollWidth > sc.clientWidth && sc.scrollLeft > 0; sc.scrollLeft = 0; }
|
||||
return {
|
||||
vw, docSW: document.documentElement.scrollWidth, bodySW: document.body.scrollWidth,
|
||||
maxRight: Math.round(maxRight * 10) / 10, worst, cols, grids, navRight: Math.round(navRight * 10) / 10, linkRows, scrolls,
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs in the page. Element boxes, ignoring display:contents hook wrappers (they have no box). */
|
||||
function boxes() {
|
||||
return [...document.body.querySelectorAll('*')]
|
||||
.filter((e) => !['SCRIPT', 'STYLE', 'NOSCRIPT'].includes(e.tagName) && !e.hasAttribute('data-wsb-html'))
|
||||
.map((e) => { const r = e.getBoundingClientRect(); return [e.tagName, ...[r.x, r.y, r.width, r.height].map((v) => Math.round(v * 10) / 10)].join(','); });
|
||||
}
|
||||
|
||||
/** Runs in the page: remove the mobile hooks (unwrap the HtmlBlock wrapper, drop the grid hook). */
|
||||
function stripHooks() {
|
||||
for (const w of [...document.querySelectorAll('[data-wsb-html]')]) w.replaceWith(...w.childNodes);
|
||||
for (const g of document.querySelectorAll('[data-wsb-grid]')) g.removeAttribute('data-wsb-grid');
|
||||
}
|
||||
|
||||
let fail = 0;
|
||||
const ok = (c, m) => { if (!c) { fail++; console.log(' FAIL', m); } };
|
||||
const baseline = process.env.MOBILE_GUARD_BASELINE ? JSON.parse(fs.readFileSync(process.env.MOBILE_GUARD_BASELINE, 'utf8')) : null;
|
||||
const record = {};
|
||||
const summary = [];
|
||||
|
||||
async function run(name, launcher, exe) {
|
||||
const browser = await launcher.launch({ executablePath: exe || undefined, ...(name === 'chromium' ? { args: ['--no-sandbox'] } : {}) });
|
||||
const gen = await browser.newPage();
|
||||
await gen.setContent('<!doctype html><html><body></body></html>');
|
||||
await gen.addScriptTag({ content: js });
|
||||
const docs = await gen.evaluate(() => window.wsbMobileGuardDocs());
|
||||
await gen.close();
|
||||
record[name] = {};
|
||||
for (const [docName, html] of Object.entries(docs)) {
|
||||
for (const w of WIDTHS) {
|
||||
const page = await browser.newPage({ viewport: { width: w, height: 900 } });
|
||||
await page.route(/^https?:/, (r) => r.abort()); // deterministic: no fonts/CDN racing the layout
|
||||
await page.setContent(html, { waitUntil: 'load' });
|
||||
await page.waitForTimeout(50);
|
||||
const m = await page.evaluate(measure);
|
||||
const tag = `[${name} ${w}] ${docName}`;
|
||||
const mobile = w <= MOBILE_MAX;
|
||||
summary.push(`${name.padEnd(8)} ${String(w).padEnd(4)} ${docName.padEnd(10)} docSW=${m.docSW} bodySW=${m.bodySW} maxRight=${m.maxRight}${m.maxRight > w + 0.5 ? ' (' + m.worst + ')' : ''} cols=${m.cols.map((c) => c.rows + '/' + c.n).join(',') || '-'} grids/row=${m.grids.map((g) => g.perRow + '/' + g.n + (g.hook ? 'h' : '')).join(',') || '-'} nav=${m.navRight}/${m.linkRows}rows${m.scrolls === null ? '' : ' scroller=' + m.scrolls}`);
|
||||
|
||||
ok(m.docSW <= w, `${tag}: documentElement.scrollWidth ${m.docSW} > ${w}`);
|
||||
// Customer HTML is held to the viewport only where the HtmlBlock net applies (<=767px): wider than
|
||||
// that, a block the author made wider than the screen renders exactly as it always has.
|
||||
if (docName === 'components' || mobile) {
|
||||
ok(m.bodySW <= w, `${tag}: body.scrollWidth ${m.bodySW} > ${w}`);
|
||||
ok(m.maxRight <= w + 0.5, `${tag}: content reaches x=${m.maxRight} (clipped on a real device): ${m.worst}`);
|
||||
}
|
||||
ok(m.navRight <= w + 0.5, `${tag}: navbar reaches x=${m.navRight}`);
|
||||
if (docName === 'components' && w <= 390) ok(m.linkRows > 1, `${tag}: navbar links did not wrap (${m.linkRows} row)`);
|
||||
if (docName === 'htmlblocks' && mobile) ok(m.linkRows === null, `${tag}: hamburger navbar shows its links on a phone`);
|
||||
// The 1000px table only needs to scroll where it is wider than its box.
|
||||
if (m.scrolls !== null && w <= 768) ok(m.scrolls, `${tag}: the intentional overflow-x:auto table no longer scrolls`);
|
||||
if (docName === 'components') {
|
||||
for (const c of m.cols) ok(mobile ? c.rows === c.n : c.rows === 1, `${tag}: ColumnLayout ${mobile ? 'not stacked' : 'stacked'} (${c.rows} rows / ${c.n} cols)`);
|
||||
for (const g of m.grids) {
|
||||
if (g.n < 2) continue;
|
||||
if (mobile && !g.imagesOnly) ok(g.perRow === 1, `${tag}: grid "${g.where}" keeps ${g.perRow} columns on a phone`);
|
||||
if (!mobile && g.hook) ok(g.perRow > 1, `${tag}: grid "${g.where}" lost its columns (${g.perRow} per row)`);
|
||||
}
|
||||
}
|
||||
if (w === 1280) {
|
||||
const before = await page.evaluate(boxes);
|
||||
const shotBefore = await page.screenshot({ fullPage: true });
|
||||
await page.evaluate(stripHooks);
|
||||
await page.waitForTimeout(20);
|
||||
const after = await page.evaluate(boxes);
|
||||
const shotAfter = await page.screenshot({ fullPage: true });
|
||||
ok(shotBefore.equals(shotAfter), `${tag}: full-page pixels differ with vs without the mobile hooks`);
|
||||
const diffs = before.length !== after.length ? Infinity : before.filter((b, i) => b !== after[i]).length;
|
||||
ok(diffs === 0, `${tag}: ${diffs} element boxes differ with vs without the mobile hooks (${before.length}/${after.length} elements)`);
|
||||
record[name][docName] = after;
|
||||
const b = baseline?.[name]?.[docName];
|
||||
if (b) {
|
||||
const d = b.length !== before.length ? Infinity : b.filter((x, i) => x !== before[i]).length;
|
||||
if (d) for (let i = 0, shown = 0; i < Math.min(b.length, before.length) && shown < 3; i++) if (b[i] !== before[i]) { shown++; console.log(' diff', b[i], '->', before[i]); }
|
||||
ok(d === 0, `${tag}: ${d} element boxes differ from the recorded baseline (${b.length} -> ${before.length} elements)`);
|
||||
}
|
||||
}
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
const only = process.env.MOBILE_ONLY;
|
||||
if (!only || only === 'chromium') await run('chromium', chromium, process.env.CHROMIUM_PATH);
|
||||
if (!only || only === 'firefox') await run('firefox', firefox, process.env.FIREFOX_PATH);
|
||||
if (process.env.MOBILE_GUARD_RECORD) fs.writeFileSync(process.env.MOBILE_GUARD_RECORD, JSON.stringify(record));
|
||||
console.log('\n' + summary.join('\n'));
|
||||
console.log(fail ? `\n${fail} FAILED` : '\nall passed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -87,10 +87,10 @@ async function run(name, launcher, exe) {
|
||||
results[name][docName][w] = m;
|
||||
const tag = `[${name} ${w}] ${docName}`;
|
||||
if (w === 390) {
|
||||
// ols/index carries a customer HtmlBlock card grid that overflows on its own (out of scope here): for it,
|
||||
// only the navbar is held to the phone width.
|
||||
// ols/index's FeaturesGrid stacks via its data-wsb-grid hook, which a body stored before the hook
|
||||
// existed does not carry: only that stored body is exempt (it is fixed by republishing).
|
||||
ok(m.navRight <= 390.5, `${tag}: navbar overflows, reaches x=${m.navRight}`);
|
||||
if (!docName.startsWith('ols/index')) ok(m.maxRight <= 390.5, `${tag}: horizontal overflow, content reaches x=${m.maxRight} (${m.worst})`);
|
||||
if (docName !== 'ols/index (stored body, current head)') ok(m.maxRight <= 390.5, `${tag}: horizontal overflow, content reaches x=${m.maxRight} (${m.worst})`);
|
||||
for (const c of m.cols) {
|
||||
const optOut = c.id === 'optout';
|
||||
if (optOut) ok(c.rows === 1 || c.n === 1, `${tag}: opt-out columns should stay side by side (${JSON.stringify(c)})`);
|
||||
|
||||
Reference in new issue
Block a user