// fixtures/engines/first-reveal.mjs — once a document's text is on // screen, nothing about it changes, in Chromium and in WebKit, on every // path: scripts missing, the editor late, a font late, nothing wrong // (Paul: "No flashing, ever!"; branch reviews on #83). // // Run by internal/docs/fonts_engines_browser_test.go, which serves Docs // through its production middleware and passes the origin, a signed-in // cookie and the documents in DOCS_ENGINES_CONFIG. // // Each scenario captures the sheet about every 50 ms for several // seconds, without Playwright's wait for document.fonts.ready, so the // interval before a slow font is observed too. The verdict: every // capture is either "nothing painted yet" (the sheet hidden, or blank) // before the first capture with text, or exactly the final picture, with // the final page-gap count and sheet height. A capture that changes, // disappears or blanks after text has appeared fails. // // A control scenario flashes deliberately, hiding the sheet for a // second after it is shown. It must fail the same verdict, in each // engine, or this whole check fails as blind. process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY = '1' const { chromium, webkit } = await import('playwright') const { PNG } = await import('pngjs') const { createHash } = await import('node:crypto') const config = JSON.parse(process.env.DOCS_ENGINES_CONFIG) const pause = (ms) => new Promise((r) => setTimeout(r, ms)) const scenarios = [ { name: 'nothing missing', doc: 'long' }, // Review 2's case: no hold, and an editor three seconds after a sheet // already in view. { name: 'no hold, late editor', doc: 'long', block: /fontshold\./, editorDelay: 3000 }, { name: 'no gate, late editor', doc: 'long', block: /fontsgate\./, editorDelay: 3000 }, { name: 'editor later than the layout deadline', doc: 'long', editorDelay: 5000 }, // Review 3's case: a font used only by spaces, eight seconds late, and // no editor at all. { name: 'spaces in a late font, no editor', doc: 'spaces', block: /\/static\/editor\./, slowFont: /Caveat-Regular\./, fontDelay: 8000, length: 10000 }, // Review 4's case: bold Caveat throughout, Caveat Regular eight seconds // late, with the editor and without it. { name: 'bold Caveat, its regular late', doc: 'inline', slowFont: /Caveat-Regular\./, fontDelay: 8000, length: 10000 }, { name: 'bold Caveat, its regular late, no editor', doc: 'inline', block: /\/static\/editor\./, slowFont: /Caveat-Regular\./, fontDelay: 8000, length: 10000 }, // Review 5's cases: a pasted code block, and an HTML drop in a family // the page has not loaded, its font two seconds late (inside the // three-second deadline past which the action is dropped). After the // action every capture must be the picture before it or the final one, // and the wait is said at once. { name: 'paste a code block, its font late', doc: 'simple', slowFont: /LiberationMono-/, fontDelay: 2000, length: 5000, action: 'paste-pre', family: 'Docs Liberation Mono', key: 'mono', busy: true }, { name: 'drop a font, its font late', doc: 'simple', slowFont: /Caveat-/, fontDelay: 2000, length: 5000, action: 'drop-caveat', family: 'Docs Caveat', key: 'caveat', busy: true }, // Review 7's: a font the prefetch has brought in is used at once, with // no wait, and is never drawn before it has loaded (WebKit reports a // face loaded only through the font API as unloaded once its wrapper // is collected). { name: 'pick a prefetched font', doc: 'simple', length: 3000, action: 'pick-literata', setup: 'select-first', prefetched: true, family: 'Docs Literata', key: 'literata', busy: false }, // The probe's control: text in a Docs face that has not loaded (Caveat, // slowed), put on screen on purpose. The probe must see it in each // engine, whichever way it writes family names. { name: 'control: text in a face that has not loaded', doc: 'simple', slowFont: /Caveat-/, fontDelay: 8000, length: 2500, probeControl: true }, // The control: shown, then hidden for a second. Must be caught. { name: 'control: hidden for a second after it is shown', doc: 'long', control: true }, ] // DOCS_ENGINES_ONLY narrows a run to the scenarios whose name contains // it, for working on one; the control always runs. const only = process.env.DOCS_ENGINES_ONLY const chosen = only ? scenarios.filter((s) => s.control || s.probeControl || s.name.includes(only)) : scenarios // unloadedOnce puts a run in Docs Caveat on the sheet once it is shown. const unloadedOnce = `(() => { const tick = () => { const text = document.querySelector('[docs-text]') if (text && document.documentElement.getAttribute('data-docs-fonts') === 'shown') { const p = document.createElement('p'); p.style.fontFamily = '"Docs Caveat"'; p.textContent = 'Not loaded yet' text.prepend(p) return } requestAnimationFrame(tick) } requestAnimationFrame(tick) })()` // flashOnce is the control's deliberate flash. const flashOnce = `(() => { const tick = () => { const sheet = document.querySelector('[docs-page]') if (sheet && getComputedStyle(sheet).visibility === 'visible' && sheet.textContent.trim()) { setTimeout(() => { sheet.style.setProperty('visibility', 'hidden', 'important') setTimeout(() => sheet.style.removeProperty('visibility'), 1000) }, 600) return } requestAnimationFrame(tick) } requestAnimationFrame(tick) })()` const ACTIONS = { 'paste-pre': () => { const p = document.querySelector('[docs-text] p') const r = document.createRange() r.setStart(p.firstChild, 0) r.collapse(true) getSelection().removeAllRanges() getSelection().addRange(r) const el = document.querySelector('[docs-text]') el.focus() const d = new DataTransfer() d.setData('text/html', '
const answer = 42;\nsecond line of code') el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) }, // The first paragraph was selected beforehand (SETUPS), so the // editor has seen the selection before the pick. 'pick-literata': () => { const s = document.querySelector('#docs-select-font') s.value = 'literata' s.dispatchEvent(new Event('change', { bubbles: true })) // And the selection collapsed, in the same task: a highlight that // ProseMirror redraws a frame later is not the text changing. getSelection().collapseToEnd() }, 'drop-caveat': () => { const el = document.querySelector('[docs-text]') el.focus() const d = new DataTransfer() d.setData('text/html', '
Dropped text in Caveat
') const r = document.querySelector('[docs-text] p').getBoundingClientRect() el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.left + 30, clientY: r.top + 8 })) }, } const SETUPS = { 'select-first': () => { const p = document.querySelector('[docs-text] p') const r = document.createRange() r.selectNodeContents(p) document.querySelector('[docs-text]').focus() getSelection().removeAllRanges() getSelection().addRange(r) }, } // actionVerdict: after the action, every capture's text is the text // before it or the final text, never a third (text missing, or in a face // that has not loaded), and the action did take effect. function actionVerdict(frames, before, busy) { const after = frames.filter((f) => f.afterAction) const last = after[after.length - 1] if (!last) return 'nothing was captured after the action' if (last.ink === before.ink) return 'the action never took effect' // An action that waits for its font says so at once; one whose font is // in does not wait at all. if (busy && !after[0].busy) return 'the wait for the font was not said at once' if (!busy && after.some((f) => f.busy)) return 'the action waited for a font the prefetch had brought in' for (const f of after) { if (f.blank) return `the sheet was blank at ${f.ms}ms` if (f.ink !== before.ink && f.ink !== last.ink) return `at ${f.ms}ms text that was neither the text before the action nor the final text` } return null } function verdict(frames) { const text = frames.findIndex((f) => !f.blank) if (text < 0) return 'the sheet was never seen with text on it' const last = frames[frames.length - 1] if (last.blank) return `the sheet was blank at the end (${last.ms}ms)` for (const f of frames.slice(text)) { if (f.blank) return `text was on screen at ${frames[text].ms}ms, then gone at ${f.ms}ms` if (f.hash !== last.hash || f.gaps !== last.gaps || f.height !== last.height || f.left !== last.left) { return `at ${f.ms}ms ${f.gaps} page gaps, ${f.height}px at x ${f.left}, ${f.hash.slice(0, 8)}; finally ${last.gaps}, ${last.height}px at x ${last.left}, ${last.hash.slice(0, 8)}` } } return null } const failures = [] for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.DOCS_ENGINES_ENGINE || n === process.env.DOCS_ENGINES_ENGINE)) { const browser = await engine.launch({ headless: true }) for (const s of chosen) { const context = await browser.newContext({ viewport: { width: 1280, height: 1400 }, deviceScaleFactor: 1 }) await context.addCookies([ ...config.cookies.map((c) => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' })), { name: 'docs-view', value: 'paged', url: config.origin }, ]) if (s.control) await context.addInitScript(flashOnce) if (s.probeControl) await context.addInitScript(unloadedOnce) // The text-node probe too (internal/docs' probeJS): on every frame // and every DOM change, any text visible in a Docs face that has not // loaded is a violation. Screenshots alone cannot see that in every // engine. await context.addInitScript(config.probe) await context.route('**/*', async (route) => { const url = route.request().url() if (s.block && s.block.test(url)) return route.abort() const wait = s.editorDelay && url.includes('/static/editor.') ? s.editorDelay : s.slowFont && s.slowFont.test(url) ? s.fontDelay : 0 if (wait) { const response = await route.fetch() await pause(wait) try { await route.fulfill({ response }) } catch {} return } return route.continue() }) const page = await context.newPage() const sqid = config.docs[s.doc].shift() if (!sqid) throw new Error(`no fresh ${s.doc} document left for ${engineName}, ${s.name}`) await page.goto(config.origin + '/d/' + sqid, { waitUntil: 'commit' }) const label = `${engineName}, ${s.name}` const frames = [] let before = null if (s.action) { await page.waitForSelector('[docs-text][contenteditable="true"]', { timeout: 15000 }) if (s.prefetched) await page.waitForFunction(() => document.documentElement.getAttribute('data-docs-fonts-prefetch') === 'done', null, { timeout: 60000 }) if (s.setup) await page.evaluate(SETUPS[s.setup]) await pause(800) } const start = Date.now() let acted = false let clip = null while (Date.now() - start < (s.length || (s.editorDelay || 0) + 3500)) { if (s.action && !acted && before) { await page.evaluate(ACTIONS[s.action]) acted = true } const ms = Date.now() - start const state = await page.evaluate(() => { const sheet = document.querySelector('[docs-page]') return sheet ? { visible: getComputedStyle(sheet).visibility === 'visible', gaps: document.querySelectorAll('[docs-page-gap]').length, height: Math.round(sheet.getBoundingClientRect().height * 4) / 4, left: Math.round(sheet.getBoundingClientRect().left * 4) / 4, top: sheet.getBoundingClientRect().top, busy: ['loading', 'refused'].includes((document.querySelector('[docs-fonts-status]') || { getAttribute: () => '' }).getAttribute('data-state')), } : null }).catch(() => null) if (!state) continue // The sheet from just under the font status, which hangs below the // bars over the tray and the page's top margin (chrome, not text), // to the bottom of the viewport. A capture that times out is one // missed sample. Nothing is added // to the page for it: Playwright's screenshot style option inserts // and removes a stylesheet around every capture, and WebKit rebuilds // its @font-face set on each, reporting a loaded face as unloaded // until it is next used, which the probe then saw as a violation // (branch review 7's WebKit failure). // Across from 7px before the sheet's first left edge, 830px: the // sheet and a little desk either side, and never the inspector, // which floats beside the sheet from 64rem (spec I2) and whose // controls change, as chrome, when the editor mounts. Down from // half an inch into the sheet's top margin, under a two-line font // note, to the viewport's foot. The sheet is not centred at this // width while the inspector is open, and starts under the header // now the menus are in it, so the clip is taken from where the // sheet is drawn, once; a sheet that then moves sideways is caught // by its left edge (verdict), and one that moves down by the // picture. if (clip === null) { const y = Math.max(0, Math.floor(state.top) + 48) clip = { x: Math.max(0, Math.floor(state.left) - 7), y, width: 830, height: Math.min(1150, 1400 - y) } } const raw = await page.screenshot({ clip, caret: 'hide', timeout: 2000 }).catch(() => null) if (!raw) continue const shot = PNG.sync.read(raw) let ink = 0 let light = 0 // The ink mask is the text alone: which pixels are dark. An action's // pictures are compared by it, because a selection highlight that // WebKit paints a frame after the text it covers changes the // background, not the text. const mask = Buffer.alloc(shot.data.length / 4) for (let i = 0; i < shot.data.length; i += 4) { const dark = shot.data[i] < 100 && shot.data[i + 1] < 100 && shot.data[i + 2] < 100 mask[i / 4] = dark ? 1 : 0 if (dark) ink++ else light++ } // Blank: hidden, no ink at all, or nothing but ink (a capture // taken before anything was drawn). const blank = !state.visible || ink === 0 || light === 0 const frame = { ms, blank, hash: createHash('sha256').update(shot.data).digest('hex'), ink: createHash('sha256').update(mask).digest('hex'), gaps: state.gaps, height: state.height, left: state.left, busy: state.busy, afterAction: acted } if (s.action && !acted && !blank) before = frame frames.push(frame) } let v = s.action ? actionVerdict(frames, before || frames[0], s.busy) : verdict(frames) const violations = await page.evaluate(() => (window.__fontProbe ? window.__fontProbe.violations : null)).catch(() => null) if (!v && violations && violations.length) v = `text visible in a face that had not loaded: ${violations[0]}` if (s.action && !v) { // The final picture must be the text in its final face: loaded, or // committed to the fallback. A picture that never changes because // the text is still invisible is not a pass. const end = await page.evaluate(([family, key]) => ({ loaded: document.fonts.check('400 16px "' + family + '"'), committed: (document.documentElement.getAttribute('data-docs-fonts-fallback') || '').split(' ').includes(key), status: [...document.fonts].filter((f) => f.family.includes(family.slice(5))).map((f) => f.status).join(','), }), [s.family, s.key]) if (!end.loaded && !end.committed) v = `at the end the text is still waiting for ${s.family} (${end.status})` } const transitions = frames.filter((f, i) => !i || f.hash !== frames[i - 1].hash || f.blank !== frames[i - 1].blank).map((f) => `${f.ms}${f.afterAction ? '*' : ''}:${f.blank ? 'blank' : f.hash.slice(0, 6)}`) console.log(JSON.stringify({ engine: engineName, scenario: s.name, frames: frames.length, verdict: v, transitions: transitions.slice(0, 12) })) if (s.probeControl) { if (!violations || !violations.length) failures.push(`${label}: the font probe did not see text in a face that had not loaded; it is blind`) } else if (s.control && !v) failures.push(`${label}: the check did not see the control's flash; it is blind`) else if (!s.control && v) failures.push(`${label}: ${v}`) await context.close() } await browser.close() } if (failures.length) { console.error(failures.join('\n')) process.exit(1) }