oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/engines/first-reveal.mjs — once a document's text is on
2// screen, nothing about it changes, in Chromium and in WebKit, on every
3// path: scripts missing, the editor late, a font late, nothing wrong
4// (Paul: "No flashing, ever!"; branch reviews on #83).
5//
6// Run by internal/docs/fonts_engines_browser_test.go, which serves Docs
7// through its production middleware and passes the origin, a signed-in
8// cookie and the documents in DOCS_ENGINES_CONFIG.
9//
10// Each scenario captures the sheet about every 50 ms for several
11// seconds, without Playwright's wait for document.fonts.ready, so the
12// interval before a slow font is observed too. The verdict: every
13// capture is either "nothing painted yet" (the sheet hidden, or blank)
14// before the first capture with text, or exactly the final picture, with
15// the final page-gap count and sheet height. A capture that changes,
16// disappears or blanks after text has appeared fails.
17//
18// A control scenario flashes deliberately, hiding the sheet for a
19// second after it is shown. It must fail the same verdict, in each
20// engine, or this whole check fails as blind.
21
22process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY = '1'
23const { chromium, webkit } = await import('playwright')
24const { PNG } = await import('pngjs')
25const { createHash } = await import('node:crypto')
26
27const config = JSON.parse(process.env.DOCS_ENGINES_CONFIG)
28const pause = (ms) => new Promise((r) => setTimeout(r, ms))
29
30const scenarios = [
31 { name: 'nothing missing', doc: 'long' },
32 // Review 2's case: no hold, and an editor three seconds after a sheet
33 // already in view.
34 { name: 'no hold, late editor', doc: 'long', block: /fontshold\./, editorDelay: 3000 },
35 { name: 'no gate, late editor', doc: 'long', block: /fontsgate\./, editorDelay: 3000 },
36 { name: 'editor later than the layout deadline', doc: 'long', editorDelay: 5000 },
37 // Review 3's case: a font used only by spaces, eight seconds late, and
38 // no editor at all.
39 { name: 'spaces in a late font, no editor', doc: 'spaces', block: /\/static\/editor\./, slowFont: /Caveat-Regular\./, fontDelay: 8000, length: 10000 },
40 // Review 4's case: bold Caveat throughout, Caveat Regular eight seconds
41 // late, with the editor and without it.
42 { name: 'bold Caveat, its regular late', doc: 'inline', slowFont: /Caveat-Regular\./, fontDelay: 8000, length: 10000 },
43 { name: 'bold Caveat, its regular late, no editor', doc: 'inline', block: /\/static\/editor\./, slowFont: /Caveat-Regular\./, fontDelay: 8000, length: 10000 },
44 // Review 5's cases: a pasted code block, and an HTML drop in a family
45 // the page has not loaded, its font two seconds late (inside the
46 // three-second deadline past which the action is dropped). After the
47 // action every capture must be the picture before it or the final one,
48 // and the wait is said at once.
49 { 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 },
50 { 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 },
51 // Review 7's: a font the prefetch has brought in is used at once, with
52 // no wait, and is never drawn before it has loaded (WebKit reports a
53 // face loaded only through the font API as unloaded once its wrapper
54 // is collected).
55 { name: 'pick a prefetched font', doc: 'simple', length: 3000, action: 'pick-literata', setup: 'select-first', prefetched: true, family: 'Docs Literata', key: 'literata', busy: false },
56 // The probe's control: text in a Docs face that has not loaded (Caveat,
57 // slowed), put on screen on purpose. The probe must see it in each
58 // engine, whichever way it writes family names.
59 { name: 'control: text in a face that has not loaded', doc: 'simple', slowFont: /Caveat-/, fontDelay: 8000, length: 2500, probeControl: true },
60 // The control: shown, then hidden for a second. Must be caught.
61 { name: 'control: hidden for a second after it is shown', doc: 'long', control: true },
62]
63
64// DOCS_ENGINES_ONLY narrows a run to the scenarios whose name contains
65// it, for working on one; the control always runs.
66const only = process.env.DOCS_ENGINES_ONLY
67const chosen = only ? scenarios.filter((s) => s.control || s.probeControl || s.name.includes(only)) : scenarios
68
69// unloadedOnce puts a run in Docs Caveat on the sheet once it is shown.
70const unloadedOnce = `(() => {
71 const tick = () => {
72 const text = document.querySelector('[docs-text]')
73 if (text && document.documentElement.getAttribute('data-docs-fonts') === 'shown') {
74 const p = document.createElement('p'); p.style.fontFamily = '"Docs Caveat"'; p.textContent = 'Not loaded yet'
75 text.prepend(p)
76 return
77 }
78 requestAnimationFrame(tick)
79 }
80 requestAnimationFrame(tick)
81})()`
82
83// flashOnce is the control's deliberate flash.
84const flashOnce = `(() => {
85 const tick = () => {
86 const sheet = document.querySelector('[docs-page]')
87 if (sheet && getComputedStyle(sheet).visibility === 'visible' && sheet.textContent.trim()) {
88 setTimeout(() => {
89 sheet.style.setProperty('visibility', 'hidden', 'important')
90 setTimeout(() => sheet.style.removeProperty('visibility'), 1000)
91 }, 600)
92 return
93 }
94 requestAnimationFrame(tick)
95 }
96 requestAnimationFrame(tick)
97})()`
98
99const ACTIONS = {
100 'paste-pre': () => {
101 const p = document.querySelector('[docs-text] p')
102 const r = document.createRange()
103 r.setStart(p.firstChild, 0)
104 r.collapse(true)
105 getSelection().removeAllRanges()
106 getSelection().addRange(r)
107 const el = document.querySelector('[docs-text]')
108 el.focus()
109 const d = new DataTransfer()
110 d.setData('text/html', '<pre>const answer = 42;\nsecond line of code</pre>')
111 el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true }))
112 },
113 // The first paragraph was selected beforehand (SETUPS), so the
114 // editor has seen the selection before the pick.
115 'pick-literata': () => {
116 const s = document.querySelector('#docs-select-font')
117 s.value = 'literata'
118 s.dispatchEvent(new Event('change', { bubbles: true }))
119 // And the selection collapsed, in the same task: a highlight that
120 // ProseMirror redraws a frame later is not the text changing.
121 getSelection().collapseToEnd()
122 },
123 'drop-caveat': () => {
124 const el = document.querySelector('[docs-text]')
125 el.focus()
126 const d = new DataTransfer()
127 d.setData('text/html', '<p style="font-family: Caveat">Dropped text in Caveat</p>')
128 const r = document.querySelector('[docs-text] p').getBoundingClientRect()
129 el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.left + 30, clientY: r.top + 8 }))
130 },
131}
132
133const SETUPS = {
134 'select-first': () => {
135 const p = document.querySelector('[docs-text] p')
136 const r = document.createRange()
137 r.selectNodeContents(p)
138 document.querySelector('[docs-text]').focus()
139 getSelection().removeAllRanges()
140 getSelection().addRange(r)
141 },
142}
143
144// actionVerdict: after the action, every capture's text is the text
145// before it or the final text, never a third (text missing, or in a face
146// that has not loaded), and the action did take effect.
147function actionVerdict(frames, before, busy) {
148 const after = frames.filter((f) => f.afterAction)
149 const last = after[after.length - 1]
150 if (!last) return 'nothing was captured after the action'
151 if (last.ink === before.ink) return 'the action never took effect'
152 // An action that waits for its font says so at once; one whose font is
153 // in does not wait at all.
154 if (busy && !after[0].busy) return 'the wait for the font was not said at once'
155 if (!busy && after.some((f) => f.busy)) return 'the action waited for a font the prefetch had brought in'
156 for (const f of after) {
157 if (f.blank) return `the sheet was blank at ${f.ms}ms`
158 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`
159 }
160 return null
161}
162
163function verdict(frames) {
164 const text = frames.findIndex((f) => !f.blank)
165 if (text < 0) return 'the sheet was never seen with text on it'
166 const last = frames[frames.length - 1]
167 if (last.blank) return `the sheet was blank at the end (${last.ms}ms)`
168 for (const f of frames.slice(text)) {
169 if (f.blank) return `text was on screen at ${frames[text].ms}ms, then gone at ${f.ms}ms`
170 if (f.hash !== last.hash || f.gaps !== last.gaps || f.height !== last.height || f.left !== last.left) {
171 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)}`
172 }
173 }
174 return null
175}
176
177const failures = []
178for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.DOCS_ENGINES_ENGINE || n === process.env.DOCS_ENGINES_ENGINE)) {
179 const browser = await engine.launch({ headless: true })
180 for (const s of chosen) {
181 const context = await browser.newContext({ viewport: { width: 1280, height: 1400 }, deviceScaleFactor: 1 })
182 await context.addCookies([
183 ...config.cookies.map((c) => ({ name: c.Name, value: c.Value, url: config.origin, httpOnly: c.HttpOnly, sameSite: 'Lax' })),
184 { name: 'docs-view', value: 'paged', url: config.origin },
185 ])
186 if (s.control) await context.addInitScript(flashOnce)
187 if (s.probeControl) await context.addInitScript(unloadedOnce)
188 // The text-node probe too (internal/docs' probeJS): on every frame
189 // and every DOM change, any text visible in a Docs face that has not
190 // loaded is a violation. Screenshots alone cannot see that in every
191 // engine.
192 await context.addInitScript(config.probe)
193 await context.route('**/*', async (route) => {
194 const url = route.request().url()
195 if (s.block && s.block.test(url)) return route.abort()
196 const wait = s.editorDelay && url.includes('/static/editor.') ? s.editorDelay : s.slowFont && s.slowFont.test(url) ? s.fontDelay : 0
197 if (wait) {
198 const response = await route.fetch()
199 await pause(wait)
200 try { await route.fulfill({ response }) } catch {}
201 return
202 }
203 return route.continue()
204 })
205 const page = await context.newPage()
206 const sqid = config.docs[s.doc].shift()
207 if (!sqid) throw new Error(`no fresh ${s.doc} document left for ${engineName}, ${s.name}`)
208 await page.goto(config.origin + '/d/' + sqid, { waitUntil: 'commit' })
209 const label = `${engineName}, ${s.name}`
210 const frames = []
211 let before = null
212 if (s.action) {
213 await page.waitForSelector('[docs-text][contenteditable="true"]', { timeout: 15000 })
214 if (s.prefetched) await page.waitForFunction(() => document.documentElement.getAttribute('data-docs-fonts-prefetch') === 'done', null, { timeout: 60000 })
215 if (s.setup) await page.evaluate(SETUPS[s.setup])
216 await pause(800)
217 }
218 const start = Date.now()
219 let acted = false
220 let clip = null
221 while (Date.now() - start < (s.length || (s.editorDelay || 0) + 3500)) {
222 if (s.action && !acted && before) {
223 await page.evaluate(ACTIONS[s.action])
224 acted = true
225 }
226 const ms = Date.now() - start
227 const state = await page.evaluate(() => {
228 const sheet = document.querySelector('[docs-page]')
229 return sheet ? {
230 visible: getComputedStyle(sheet).visibility === 'visible',
231 gaps: document.querySelectorAll('[docs-page-gap]').length,
232 height: Math.round(sheet.getBoundingClientRect().height * 4) / 4,
233 left: Math.round(sheet.getBoundingClientRect().left * 4) / 4,
234 top: sheet.getBoundingClientRect().top,
235 busy: ['loading', 'refused'].includes((document.querySelector('[docs-fonts-status]') || { getAttribute: () => '' }).getAttribute('data-state')),
236 } : null
237 }).catch(() => null)
238 if (!state) continue
239 // The sheet from just under the font status, which hangs below the
240 // bars over the tray and the page's top margin (chrome, not text),
241 // to the bottom of the viewport. A capture that times out is one
242 // missed sample. Nothing is added
243 // to the page for it: Playwright's screenshot style option inserts
244 // and removes a stylesheet around every capture, and WebKit rebuilds
245 // its @font-face set on each, reporting a loaded face as unloaded
246 // until it is next used, which the probe then saw as a violation
247 // (branch review 7's WebKit failure).
248 // Across from 7px before the sheet's first left edge, 830px: the
249 // sheet and a little desk either side, and never the inspector,
250 // which floats beside the sheet from 64rem (spec I2) and whose
251 // controls change, as chrome, when the editor mounts. Down from
252 // half an inch into the sheet's top margin, under a two-line font
253 // note, to the viewport's foot. The sheet is not centred at this
254 // width while the inspector is open, and starts under the header
255 // now the menus are in it, so the clip is taken from where the
256 // sheet is drawn, once; a sheet that then moves sideways is caught
257 // by its left edge (verdict), and one that moves down by the
258 // picture.
259 if (clip === null) {
260 const y = Math.max(0, Math.floor(state.top) + 48)
261 clip = { x: Math.max(0, Math.floor(state.left) - 7), y, width: 830, height: Math.min(1150, 1400 - y) }
262 }
263 const raw = await page.screenshot({ clip, caret: 'hide', timeout: 2000 }).catch(() => null)
264 if (!raw) continue
265 const shot = PNG.sync.read(raw)
266 let ink = 0
267 let light = 0
268 // The ink mask is the text alone: which pixels are dark. An action's
269 // pictures are compared by it, because a selection highlight that
270 // WebKit paints a frame after the text it covers changes the
271 // background, not the text.
272 const mask = Buffer.alloc(shot.data.length / 4)
273 for (let i = 0; i < shot.data.length; i += 4) {
274 const dark = shot.data[i] < 100 && shot.data[i + 1] < 100 && shot.data[i + 2] < 100
275 mask[i / 4] = dark ? 1 : 0
276 if (dark) ink++
277 else light++
278 }
279 // Blank: hidden, no ink at all, or nothing but ink (a capture
280 // taken before anything was drawn).
281 const blank = !state.visible || ink === 0 || light === 0
282 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 }
283 if (s.action && !acted && !blank) before = frame
284 frames.push(frame)
285 }
286 let v = s.action ? actionVerdict(frames, before || frames[0], s.busy) : verdict(frames)
287 const violations = await page.evaluate(() => (window.__fontProbe ? window.__fontProbe.violations : null)).catch(() => null)
288 if (!v && violations && violations.length) v = `text visible in a face that had not loaded: ${violations[0]}`
289 if (s.action && !v) {
290 // The final picture must be the text in its final face: loaded, or
291 // committed to the fallback. A picture that never changes because
292 // the text is still invisible is not a pass.
293 const end = await page.evaluate(([family, key]) => ({
294 loaded: document.fonts.check('400 16px "' + family + '"'),
295 committed: (document.documentElement.getAttribute('data-docs-fonts-fallback') || '').split(' ').includes(key),
296 status: [...document.fonts].filter((f) => f.family.includes(family.slice(5))).map((f) => f.status).join(','),
297 }), [s.family, s.key])
298 if (!end.loaded && !end.committed) v = `at the end the text is still waiting for ${s.family} (${end.status})`
299 }
300 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)}`)
301 console.log(JSON.stringify({ engine: engineName, scenario: s.name, frames: frames.length, verdict: v, transitions: transitions.slice(0, 12) }))
302 if (s.probeControl) {
303 if (!violations || !violations.length) failures.push(`${label}: the font probe did not see text in a face that had not loaded; it is blind`)
304 } else if (s.control && !v) failures.push(`${label}: the check did not see the control's flash; it is blind`)
305 else if (!s.control && v) failures.push(`${label}: ${v}`)
306 await context.close()
307 }
308 await browser.close()
309}
310if (failures.length) {
311 console.error(failures.join('\n'))
312 process.exit(1)
313}
314