oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/browser-drive.mjs — drive the real editor in a real
2// browser, and assert what a person would actually see.
3//
4// Spec §12 asks for "a browser drive of the editor itself, because a JS
5// syntax error takes the whole client down". This is the first one, and
6// its first run earned its place: the toolbar branch had made the
7// editor silently discard every edit — typing did nothing, bold did
8// nothing, no error anywhere — and the Go suite was green throughout,
9// because nothing in it runs the bundle. A screenshot did not show it
10// either: the bar renders correctly and the document looks untouched
11// because it IS untouched.
12//
13// Run it through scripts/browser-drive.sh, which brings up a scratch
14// server and a headless Chrome around it. This file only speaks the
15// DevTools protocol, over Node's own WebSocket — no puppeteer, no
16// playwright, nothing to install (the same "no build step, no new
17// dependency" constraint the editor bundle itself lives under).
18//
19// One limitation to know before extending this to two pages (a
20// cross-tab check wants one): headless Chromium refuses more than one
21// startup target — "Multiple targets are not supported in headless
22// mode" — so a second tab has to be opened through CDP
23// (Target.createTarget) or the /json/new endpoint, not by passing a
24// second URL on the command line. Found by the live-sync session.
25//
26// It uses REAL input events, not element.click() and not a synthetic
27// DOM Range. Both of those skip what the editor actually listens to: a
28// Range set by script is not the selection ProseMirror reads, and a
29// click() with no mousedown skips the preventDefault the toolbar
30// depends on to keep the selection alive while the button is pressed.
31// A drive that fakes its input tests the fake.
32
33const [, , wsUrl, base, signinLink] = process.argv
34if (!wsUrl || !base) {
35 console.error('usage: node browser-drive.mjs <devtools-ws-url> <base-url> [sign-in-link]')
36 process.exit(2)
37}
38
39const ws = new WebSocket(wsUrl)
40let nextId = 0
41const pending = new Map()
42const pageProblems = []
43
44function send(method, params = {}) {
45 const id = ++nextId
46 return new Promise((resolve, reject) => {
47 pending.set(id, { resolve, reject })
48 ws.send(JSON.stringify({ id, method, params }))
49 })
50}
51
52ws.onmessage = (e) => {
53 const msg = JSON.parse(e.data)
54 if (msg.id && pending.has(msg.id)) {
55 const { resolve, reject } = pending.get(msg.id)
56 pending.delete(msg.id)
57 if (msg.error) reject(new Error(JSON.stringify(msg.error)))
58 else resolve(msg.result)
59 return
60 }
61 // A JS error in the bundle is the failure §12 names first, so it is
62 // collected here rather than left to show up as "nothing happened".
63 if (msg.method === 'Runtime.exceptionThrown') {
64 const d = msg.params.exceptionDetails
65 pageProblems.push('uncaught: ' + (d.exception?.description || d.text || '').split('\n')[0])
66 }
67 if (msg.method === 'Runtime.consoleAPICalled' && msg.params.type === 'error') {
68 pageProblems.push('console.error: ' + msg.params.args.map((a) => a.description || a.value).join(' '))
69 }
70}
71
72const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
73
74async function evaluate(expression) {
75 const res = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })
76 if (res.exceptionDetails) {
77 throw new Error('page threw: ' + (res.exceptionDetails.exception?.description || '').split('\n')[0])
78 }
79 return res.result.value
80}
81
82async function click(x, y, clickCount = 1) {
83 await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount, buttons: 1 })
84 await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount, buttons: 0 })
85}
86
87// clickSelector clicks the centre of the first element matching a
88// selector — and refuses two things that used to fail much later and
89// much less clearly.
90//
91// A ZERO-SIZE TARGET IS AN ERROR, not a click at (0,0). This cost five
92// checks and an hour. The menu bar gave a second home to every
93// data-docs-command name, and menu items come before the toolbar in
94// document order, so `[data-docs-command="strong"]` started matching a
95// menu item inside a closed <details> — display: none, rect all zeros.
96// Every click went to the top-left corner of the page, and the checks
97// failed thirty seconds later saying "timed out waiting for bold to
98// apply", which is true and points nowhere near the cause. Refusing the
99// click names it instead.
100//
101// MORE THAN ONE MATCH IS ALSO AN ERROR, because that is the same bug
102// one step earlier: the selector stopped identifying one control and
103// nothing said so. A caller that genuinely wants the first of several
104// scopes its selector, which is what the toolbar's three now do.
105async function clickSelector(selector) {
106 const at = await evaluate(
107 `(()=>{const all=document.querySelectorAll(${JSON.stringify(selector)});` +
108 `if(!all.length)return {none:true};` +
109 `const e=all[0];const r=e.getBoundingClientRect();` +
110 `return {count:all.length,w:r.width,h:r.height,x:r.left+r.width/2,y:r.top+r.height/2}})()`,
111 )
112 if (at.none) throw new Error(`no element matching ${selector}`)
113 if (at.count > 1) {
114 throw new Error(
115 `${at.count} elements match ${selector} — the selector no longer identifies one control, so this would click whichever comes first in the document`,
116 )
117 }
118 if (at.w === 0 || at.h === 0) {
119 throw new Error(
120 `${selector} matched an element with no size (${at.w}x${at.h}) — it is hidden, so clicking its centre would click the page corner`,
121 )
122 }
123 await click(at.x, at.y)
124}
125
126async function editorHTML() {
127 return evaluate(`document.querySelector('[docs-editor]').innerHTML`)
128}
129
130// pressKey dispatches one key the way a keyboard does.
131//
132// rawKeyDown rather than keyDown for the non-printing keys: a keyDown
133// carrying no text is what CDP turns into a char event, and a stray
134// char is how an Escape ends up inserting nothing visible while the
135// handler that should have run never did. Printing keys pass `text`
136// and get the char event they need.
137//
138// modifiers is CDP's bitfield — 2 is Control, which is the one the
139// palette is bound to.
140async function pressKey(key, { code, vk = 0, modifiers = 0, text } = {}) {
141 const base = { key, code: code || key, windowsVirtualKeyCode: vk, modifiers }
142 await send('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', ...base, ...(text ? { text } : {}) })
143 await send('Input.dispatchKeyEvent', { type: 'keyUp', ...base })
144}
145
146// typeText types a string one character at a time, with a real gap
147// between them. The palette debounces its query, so a burst delivered
148// instantly is not the input it was written for.
149async function typeText(text) {
150 for (const ch of text) {
151 await send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, key: ch })
152 await send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch })
153 await sleep(20)
154 }
155}
156
157const CONTROL = 2
158
159// The editor writes through the CRDT and re-renders from it, so a
160// change is not in the DOM the instant a command returns. settle waits
161// for a condition rather than for a fixed delay, which is what keeps
162// this from being flaky in one direction and slow in the other.
163async function settle(describe, predicate, timeoutMs = 5000) {
164 const deadline = Date.now() + timeoutMs
165 let last = ''
166 for (;;) {
167 last = await editorHTML()
168 if (predicate(last)) return last
169 if (Date.now() > deadline) {
170 throw new Error(`timed out waiting for ${describe}\n document is: ${last.slice(0, 200)}`)
171 }
172 await sleep(150)
173 }
174}
175
176// settleOn polls one probe until it satisfies a predicate. settle
177// above watches the whole document; this watches one value, which is
178// what an assertion about a single block needs.
179async function settleOn(describe, probe, predicate, timeoutMs = 5000) {
180 const deadline = Date.now() + timeoutMs
181 let last
182 for (;;) {
183 last = await probe()
184 if (predicate(last)) return last
185 if (Date.now() > deadline) {
186 throw new Error(`timed out waiting for ${describe}\n it is: ${JSON.stringify(last)}`)
187 }
188 await sleep(150)
189 }
190}
191
192// settleScrollToTop blurs the editor, scrolls to the top, and waits
193// until the position actually holds still.
194//
195// The page scrolls the window itself — verified, not assumed: nothing
196// between [docs-page] and the document element is a scroll container,
197// document.scrollingElement is the document element, and
198// window.scrollTo moves window.scrollY. That matters because the
199// no-yank check below asserts on window.scrollY, and on a layout where
200// some inner element did the scrolling that check would pass while
201// measuring nothing at all.
202async function settleScrollToTop() {
203 await evaluate(`document.querySelector('[docs-editor]').blur();window.scrollTo(0,0)`)
204 for (let i = 0; i < 20; i++) {
205 await sleep(100)
206 if ((await evaluate(`window.scrollY`)) === 0) {
207 // Two consecutive readings, because a scroll still in flight
208 // reads zero once on its way past.
209 await sleep(100)
210 if ((await evaluate(`window.scrollY`)) === 0) return
211 }
212 await evaluate(`window.scrollTo(0,0)`)
213 }
214 throw new Error('the page would not stay scrolled to the top')
215}
216
217// blockTag is the tag name of one top-level block of the document.
218async function blockTag(index) {
219 return evaluate(
220 `(()=>{const b=document.querySelectorAll('[docs-editor] > *')[${index}];return b?b.tagName:null})()`,
221 )
222}
223
224const checks = []
225function check(name, ok, detail) {
226 checks.push({ name, ok, detail })
227 console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${ok || !detail ? '' : ' — ' + detail}`)
228}
229
230// group runs a set of checks so that one throwing does not delete the
231// ones that come after it.
232//
233// Without this, a group that dies partway through simply stops, the
234// later groups never run, and the summary line reports a smaller total
235// that looks like a smaller suite rather than like missing coverage.
236// The abort becomes its own named failure instead.
237async function group(name, fn) {
238 try {
239 await fn()
240 } catch (err) {
241 check(`${name} ran to completion`, false, err.message)
242 }
243}
244
245// caretInfo reports where the caret is, read from the DOM selection
246// rather than from ProseMirror's own state.
247//
248// The DOM is the honest probe: it is what a person actually sees, and
249// it catches the case where the selection is set correctly in the
250// editor's state but the DOM never followed. (Credited to the
251// caret-placement session, which learned it the hard way.)
252const CARET_INFO = `(()=>{
253 const sel = document.getSelection()
254 const ed = document.querySelector('[docs-editor]')
255 if (!sel || sel.rangeCount === 0 || !ed) return null
256 const r = sel.getRangeAt(0)
257 const blocks = Array.from(ed.children)
258 const rect = r.getBoundingClientRect()
259 // The caret can sit ON the editor element itself, between two
260 // blocks, in which case startOffset is a child index rather than a
261 // text offset. Walking up from there runs straight past the editor
262 // and reports -1, which reads as "the caret went somewhere else
263 // entirely" when it did not.
264 if (r.startContainer === ed) {
265 return { blockIndex: r.startOffset, blockCount: blocks.length, offset: 0,
266 onBoundary: true, collapsed: r.collapsed, top: rect.top, bottom: rect.bottom }
267 }
268 let node = r.startContainer
269 while (node && node.parentElement && node.parentElement !== ed) node = node.parentElement
270 return {
271 blockIndex: blocks.indexOf(node),
272 blockCount: blocks.length,
273 offset: r.startOffset,
274 onBoundary: false,
275 inEditor: ed.contains(r.startContainer),
276 collapsed: r.collapsed,
277 top: rect.top,
278 bottom: rect.bottom,
279 }
280})()`
281
282// pickLongestDocument opens the longest of the seeded documents.
283//
284// On a short one, the scroll-related checks below pass trivially
285// because the whole document is already on screen — which is exactly
286// how the caret session nearly convinced itself an unconditional focus
287// handler was fine. Measured by fetching each document's own
288// server-rendered page rather than by mounting the editor six times.
289async function pickLongestDocument() {
290 return evaluate(`(async () => {
291 const hrefs = Array.from(document.querySelectorAll('a[href^="/d/"]')).map(a => a.getAttribute('href'))
292 let best = null, bestLen = -1
293 for (const href of hrefs) {
294 const res = await fetch(href, { credentials: 'same-origin' })
295 const html = await res.text()
296 if (html.length > bestLen) { bestLen = html.length; best = href }
297 }
298 return best
299 })()`)
300}
301
302async function run() {
303 await send('Page.enable')
304 await send('Runtime.enable')
305
306 // Sign in the way a person does: the emailed link opens the confirm
307 // door, which spends nothing, and its one Sign in button posts it.
308 if (signinLink) {
309 await send('Page.navigate', { url: signinLink })
310 await sleep(1500)
311 await clickSelector('form[action="/auth/verify"] button[type="submit"]')
312 await sleep(1500)
313 }
314 await send('Page.navigate', { url: base + '/' })
315 await sleep(1500)
316 const href = await pickLongestDocument()
317 if (!href) throw new Error('the document list has no documents to open')
318 await send('Page.navigate', { url: base + href })
319 await sleep(2500)
320
321// editorChecks is the toolbar and editing section: it mounted, you
322// can type, the buttons and selects act on a real selection, and undo
323// undoes.
324//
325// EXTRACTED INTO A GROUP, which is the follow-up the comment at the
326// call site used to describe and defer. It throws deliberately in two
327// places — there is no point continuing without a selection — and
328// while it was inline in run() those aborts took every group after it
329// down with them. That cost was paid for real: a selector that had
330// stopped being unique threw here, and the run reported 5/6 rather
331// than one failure plus 38 other checks. The output read like a
332// smaller suite instead of like missing coverage, which is the exact
333// shape this file exists to refuse.
334async function editorChecks() {
335 check('the editor mounted', await evaluate(`!!document.querySelector('[docs-editor] p')`))
336 check('the formatting bar rendered', await evaluate(`!!document.querySelector('[docs-toolbar]')`))
337 check(
338 'the editor did not fall back to the read view',
339 !(await evaluate(`document.querySelector('[docs-editor]').hasAttribute('data-editor-failed')`)),
340 )
341
342 // Work on a paragraph chosen by its own type rather than on
343 // whatever happens to be first: these documents open with a heading,
344 // and a "make this a heading" check aimed at one is a no-op that
345 // passes.
346 const paragraphIndex = await evaluate(
347 `Array.from(document.querySelectorAll('[docs-editor] > *')).findIndex(e => e.tagName === 'P')`,
348 )
349 if (paragraphIndex < 0) throw new Error('the document has no paragraph to edit')
350
351 // Double-click a word: the ordinary way a person selects one.
352 //
353 // Tried at a few offsets along the line rather than at one fixed
354 // point. A double click that lands between words, on an indent, or
355 // past the end of a short line selects nothing — which is a fact
356 // about where the pointer went, not about the editor, and a check
357 // that cannot tell those apart is worse than no check.
358 let wordAt = null
359 let word = ''
360 for (const dx of [60, 120, 200, 300]) {
361 const at = await evaluate(
362 `(()=>{const e=document.querySelectorAll('[docs-editor] > *')[${paragraphIndex}];` +
363 `const r=e.getBoundingClientRect();const t=document.querySelector('[docs-toolbar]');` +
364 `const floor=t?t.getBoundingClientRect().bottom:0;const y=r.top+8;` +
365 `if(y<floor+4||y>window.innerHeight-4||${dx}>r.width-20) return null;` +
366 `return {x:r.left+${dx},y}})()`,
367 )
368 if (!at) continue
369 await click(at.x, at.y, 1)
370 await click(at.x, at.y, 2)
371 await sleep(400)
372 word = await evaluate(`window.getSelection().toString()`)
373 if (word.trim().length > 0) {
374 wordAt = at
375 break
376 }
377 }
378 check('a double click selects a word', !!wordAt, `selected ${JSON.stringify(word)}`)
379 if (!wordAt) throw new Error('could not select a word to format')
380
381 // Typing. This is the one that was broken, and it is not a toolbar
382 // feature at all — which is exactly why it is asserted here.
383 await send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'Z', key: 'Z', code: 'KeyZ', windowsVirtualKeyCode: 90 })
384 await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Z', code: 'KeyZ', windowsVirtualKeyCode: 90 })
385 try {
386 await settle('the typed character to appear', (html) => html.includes('Z'))
387 check('typing changes the document', true)
388 } catch (err) {
389 check('typing changes the document', false, err.message)
390 }
391
392 // Bold, through the toolbar, over a real selection.
393 await click(wordAt.x, wordAt.y, 1)
394 await click(wordAt.x, wordAt.y, 2)
395 await sleep(300)
396 await clickSelector('[docs-toolbar] [data-docs-command="strong"]')
397 try {
398 await settle('bold to apply', (html) => html.includes('<strong>'))
399 check('the bold button bolds the selection', true)
400 } catch (err) {
401 check('the bold button bolds the selection', false, err.message)
402 }
403 check(
404 'the selection survives pressing a toolbar button',
405 (await evaluate(`window.getSelection().toString()`)).length > 0,
406 )
407
408 // A font mark, through the select, and the class it must produce —
409 // the same class core/src/fragment.rs renders server-side.
410 //
411 // Serif, not Carlito, and that is not interchangeable. Carlito is the
412 // default (fixtures/fonts.mjs's DEFAULT_FONT), and choosing the
413 // default CLEARS the group rather than setting a mark — so a drive
414 // that picked it would wait for a class the control is correct never
415 // to write, and report the font control broken. Any non-default face
416 // makes the check honest. The font loads before it applies, so the
417 // settle below waits for that too.
418 await evaluate(
419 `(()=>{const s=document.querySelector('[data-docs-select="font"]');s.value='serif';` +
420 `s.dispatchEvent(new Event('change',{bubbles:true}));return true})()`,
421 )
422 try {
423 await settle('the serif face to apply', (html) => html.includes('docs-font-serif'))
424 check('the font control applies the serif mark', true)
425 } catch (err) {
426 check('the font control applies the serif mark', false, err.message)
427 }
428
429 // A heading, through the block select — asserted on the ONE block
430 // being changed, not on the document's markup as a whole. A seeded
431 // document that already contains an <h2> makes a
432 // "does the HTML contain <h2>" check pass without the control having
433 // done anything, and makes its undo impossible to observe. Both of
434 // those happened here, on the second document this drive was pointed
435 // at, which is a good argument for the longest fixture.
436 await evaluate(
437 `(()=>{const s=document.querySelector('[data-docs-select="block"]');s.value='heading-2';` +
438 `s.dispatchEvent(new Event('change',{bubbles:true}));return true})()`,
439 )
440 try {
441 await settleOn(`the block to become a heading`, () => blockTag(paragraphIndex), (tag) => tag === 'H2')
442 check('the style control makes a heading', true)
443 } catch (err) {
444 check('the style control makes a heading', false, err.message)
445 }
446
447 // Undo has to be available now, and has to walk the heading back.
448 check('undo becomes available after an edit', !(await evaluate(
449 `document.querySelector('[estilo-bar-lead] [data-docs-command="undo"]').disabled`,
450 )))
451 // The bar's lead pair: from 800px it is the one drawn (spec I2).
452 await clickSelector('[estilo-bar-lead] [data-docs-command="undo"]')
453 try {
454 await settleOn(`the heading to be undone`, () => blockTag(paragraphIndex), (tag) => tag === 'P')
455 check('undo reverses the last change', true)
456 } catch (err) {
457 check('undo reverses the last change', false, err.message)
458 }
459}
460
461
462 await group('the editor and toolbar checks', editorChecks)
463
464 // Each of these is wrapped so that a failure inside one cannot take
465 // the checks after it down with it. Proven necessary rather than
466 // assumed: breaking the palette's Control-K binding threw on the
467 // first null it produced, and the run ended at 31 checks instead of
468 // 44 — with the 320px reflow checks never reached and simply absent
469 // from the output rather than reported as anything. A check that
470 // silently removes other checks when it fails is the same "cannot
471 // tell no from I can't see it" shape this file exists to avoid, so
472 // an aborted group is now itself a failed check that names the group.
473 //
474 // The toolbar section is a group too now. It used to be inline here
475 // and this comment said extracting it was a follow-up, on the
476 // reasoning that moving a hundred working checks while fixing them is
477 // how a harness stops being trustworthy. That was right, and the
478 // follow-up then demonstrated itself: an ambiguous selector threw
479 // inside that section and the run reported 5/6 — one failure, and 38
480 // checks simply absent rather than failed or skipped. Moved on its
481 // own, with no change to the checks themselves.
482 await group('the caret-placement checks', caretChecks)
483 await group('the jump-to palette checks', paletteChecks)
484 await group('the 320px reflow checks', reflowChecks)
485
486 check('the page reported no JavaScript errors', pageProblems.length === 0, pageProblems.join(' | '))
487}
488
489// The jump-to palette (Control-K), and the plain search URL under it.
490//
491// These are the seventeen checks discussion #14 ran and could not
492// commit: the harness they belonged in was on another branch at the
493// time, and shipping a second harness to avoid waiting would have been
494// worse than waiting. Both branches have landed, so this is that fold —
495// branch task 22. What protected the palette's keyboard contract until
496// now was one person having run a scratch script once, which is exactly
497// what this repo does not count as a gate.
498//
499// Two things are different from the scratch version, both because a
500// check that depends on the fixture data is a check that fails for
501// reasons that have nothing to do with the code:
502//
503// - The queries are DERIVED from the titles actually on the list,
504// not typed in as "s" and "waterworks". Those worked against the
505// six seeded documents and would go red the day somebody edits
506// seeddata — reporting "the palette is broken" when it is not,
507// which is the failure this file's own header warns about.
508// - The single-result case queries a whole title, so the exact-match
509// rank guarantees which row lands first. Asserting on "the first
510// result" after a query that merely matches something is asserting
511// on the ranker's tie-break by accident.
512//
513// It runs before reflowChecks because that one leaves a phone-sized
514// viewport behind, and a 320px palette is a different check from this
515// one.
516async function paletteChecks() {
517 // Where the palette matters most: inside a document, which is where
518 // the run() above has already left us. A shortcut that works on the
519 // list and not in the editor is the case worth catching, because the
520 // editor is the page with a keymap of its own to collide with.
521 await pressKey('k', { code: 'KeyK', vk: 75, modifiers: CONTROL })
522 await sleep(400)
523 check('Control-K opens the palette inside a document', await evaluate(`!document.querySelector('[docs-jumpto]').hidden`))
524 await pressKey('Escape', { vk: 27 })
525 await sleep(300)
526
527 // Everything else from the list.
528 await send('Page.navigate', { url: base + '/' })
529 await sleep(1500)
530
531 // The titles this instance actually has, with the hrefs, so every
532 // query below is derived rather than assumed.
533 const docs = await evaluate(`(() => {
534 return Array.from(document.querySelectorAll('a[href^="/d/"]')).map(a => ({
535 href: a.getAttribute('href'),
536 title: a.textContent.trim(),
537 })).filter(d => d.title.length > 0)
538 })()`)
539 if (!docs || docs.length === 0) throw new Error('the document list has no titles to search for')
540
541 // A query that matches more than one, found rather than guessed: the
542 // shortest single letter contained in at least two titles. The arrow
543 // keys need two options to move between, and "there are two" is a
544 // property of the data that this asks about instead of assuming.
545 const multi = await evaluate(`(() => {
546 const titles = ${JSON.stringify(docs.map((d) => d.title.toLowerCase()))}
547 for (const ch of 'etaoinsrhldcumfpgwybvkxjqz') {
548 if (titles.filter(t => t.includes(ch)).length >= 2) return ch
549 }
550 return null
551 })()`)
552
553 // --- The no-JS path. Search is a plain page at a plain URL, and
554 // that is what lets the palette be an addition rather than the only
555 // way in. Asserted with the palette's own bundle irrelevant.
556 const one = docs[0]
557 const others = docs.slice(1).map((d) => d.title)
558 await send('Page.navigate', { url: base + '/?q=' + encodeURIComponent(one.title) })
559 await sleep(1200)
560 const searched = await evaluate(`document.body.innerText`)
561 check('a search URL renders the matching document', searched.includes(one.title), searched.slice(0, 160))
562 // Only meaningful if some other title would have shown on an
563 // unfiltered list — with one document there is nothing to hide, and
564 // a check that cannot fail is not a check.
565 const hidden = others.filter((t) => !searched.includes(t))
566 check(
567 'and hides the ones that do not match',
568 others.length === 0 || hidden.length > 0,
569 `none of the other ${others.length} titles were filtered out`,
570 )
571
572 await send('Page.navigate', { url: base + '/' })
573 await sleep(1500)
574
575 check(
576 'the palette is on the page but hidden',
577 await evaluate(`(()=>{const e=document.querySelector('[docs-jumpto]');return !!e && e.hidden})()`),
578 )
579
580 await pressKey('k', { code: 'KeyK', vk: 75, modifiers: CONTROL })
581 await sleep(400)
582 check('Control-K opens the palette from the list', await evaluate(`!document.querySelector('[docs-jumpto]').hidden`))
583 check(
584 'and focus lands in the field',
585 await evaluate(`document.activeElement === document.querySelector('[docs-jumpto-input]')`),
586 )
587 check(
588 'aria-expanded says it is open',
589 (await evaluate(`document.querySelector('[docs-jumpto-input]').getAttribute('aria-expanded')`)) === 'true',
590 )
591
592 let options = 0
593 if (multi) {
594 await typeText(multi)
595 try {
596 options = await settleOn(
597 'results',
598 () => evaluate(`document.querySelectorAll('[docs-jumpto-list] li').length`),
599 (n) => n > 0,
600 )
601 check('typing produces results', true)
602 } catch (err) {
603 check('typing produces results', false, err.message)
604 }
605 } else {
606 check('typing produces results', false, 'no letter is shared by two titles — cannot form a query')
607 }
608
609 // Read through a null-safe probe rather than dereferencing the first
610 // <li> directly. With no results that dereference throws, and a throw
611 // here used to end the whole run — so the failure of one check
612 // deleted every check after it instead of reporting itself.
613 const firstOption = await evaluate(`(() => {
614 const li = document.querySelector('[docs-jumpto-list] li')
615 const input = document.querySelector('[docs-jumpto-input]')
616 return {
617 exists: !!li,
618 selected: li ? li.getAttribute('aria-selected') : null,
619 id: li ? li.id : null,
620 activeDescendant: input ? input.getAttribute('aria-activedescendant') : null,
621 }
622 })()`)
623 check(
624 'the first result is the active option',
625 firstOption.selected === 'true',
626 firstOption.exists ? `aria-selected is ${firstOption.selected}` : 'there are no results at all',
627 )
628 check(
629 'aria-activedescendant names the active option',
630 firstOption.exists && firstOption.activeDescendant === firstOption.id,
631 `aria-activedescendant is ${firstOption.activeDescendant}, the first option's id is ${firstOption.id}`,
632 )
633
634 // Which option is selected, as an index — one probe, so a movement
635 // is asserted as "it moved from here to there" rather than as two
636 // separate facts about two separate elements.
637 const selectedIndex = () =>
638 evaluate(
639 `Array.from(document.querySelectorAll('[docs-jumpto-list] li')).findIndex(l => l.getAttribute('aria-selected') === 'true')`,
640 )
641
642 if (options > 1) {
643 await pressKey('ArrowDown', { vk: 40 })
644 await sleep(250)
645 const afterDown = await selectedIndex()
646 check('Down moves to the second result', afterDown === 1, `the selected option is ${afterDown}`)
647
648 await pressKey('ArrowUp', { vk: 38 })
649 await sleep(250)
650 const afterUp = await selectedIndex()
651 // Guarded on Down having actually moved. "The first option is
652 // selected" is true both when Up walked back to it and when
653 // nothing moved at all, so on its own this check passes against an
654 // arrow-key handler that does nothing — verified: breaking move()
655 // turned Down red and left this one green. It is only evidence
656 // when there was somewhere to come back FROM.
657 check(
658 'Up moves back to the first',
659 afterDown === 1 && afterUp === 0,
660 afterDown !== 1
661 ? `Down never moved (selected ${afterDown}), so returning to 0 proves nothing`
662 : `the selected option is ${afterUp}`,
663 )
664 } else {
665 check('Down moves to the second result', false, `only ${options} result(s) to move through`)
666 check('Up moves back to the first', false, `only ${options} result(s) to move through`)
667 }
668
669 // Escape closes and hands focus back. Tab is deliberately NOT a
670 // cycle here — the panel holds two focusable things, and a general
671 // focus trap is where a palette usually strands somebody.
672 await pressKey('Escape', { vk: 27 })
673 await sleep(400)
674 check('Escape closes the palette', await evaluate(`document.querySelector('[docs-jumpto]').hidden`))
675
676 // Focus returns to WHERE IT CAME FROM, asserted by naming that
677 // element rather than by observing that it is no longer in the
678 // field.
679 //
680 // "activeElement is not the palette input" was the obvious way to
681 // write this and it is worthless: closing the palette hides the
682 // input, so focus leaves it whether or not anything put focus back,
683 // and the check passes either way. Verified — deleting the
684 // returnFocusTo.focus() call left it green at 44/44, which is a
685 // check that cannot tell "no" from "I can't see it", and this file
686 // exists to not do that.
687 //
688 // So focus a known element first, open from there, and assert that
689 // Escape brings focus back to that exact element. A keyboard user
690 // who opens the palette from the search field and dismisses it
691 // should be back in the search field, not at the top of the page.
692 const returned = await evaluate(`(() => {
693 const f = document.querySelector('[docs-search-input]')
694 if (!f) return null
695 f.focus()
696 return document.activeElement === f
697 })()`)
698 if (returned) {
699 await pressKey('k', { code: 'KeyK', vk: 75, modifiers: CONTROL })
700 await sleep(400)
701 await pressKey('Escape', { vk: 27 })
702 await sleep(400)
703 check(
704 'and focus goes back to whatever opened it',
705 await evaluate(`document.activeElement === document.querySelector('[docs-search-input]')`),
706 `focus is on ${await evaluate(`document.activeElement ? document.activeElement.tagName + (document.activeElement.className || '') : 'nothing'`)}`,
707 )
708 } else {
709 check('and focus goes back to whatever opened it', false, 'no [docs-search-input] to open the palette from')
710 }
711
712 // A query matching nothing says so rather than showing an empty box.
713 //
714 // Compared against the status element's own data-empty, NOT merely
715 // "some text appeared". The palette writes two different strings
716 // into that element — data-empty when nothing matched, data-failed
717 // when the fetch threw — so "text is non-empty" passes just as well
718 // when the search is BROKEN and the person is being told so. That is
719 // the wrong answer under a check whose name claims to be about the
720 // empty case.
721 await pressKey('k', { code: 'KeyK', vk: 75, modifiers: CONTROL })
722 await sleep(300)
723 await typeText('zzzznothingmatchesthis')
724 try {
725 const said = await settleOn(
726 'the empty-result message',
727 () => evaluate(`(()=>{const s=document.querySelector('[docs-jumpto-status]');return s.hidden?'':s.textContent})()`),
728 (t) => t.length > 0,
729 )
730 const expected = await evaluate(
731 `document.querySelector('[docs-jumpto-status]').getAttribute('data-empty')`,
732 )
733 check(
734 'a query matching nothing says so',
735 said.trim() === (expected || '').trim(),
736 `it says ${JSON.stringify(said)}; the empty-result copy is ${JSON.stringify(expected)}`,
737 )
738 } catch (err) {
739 check('a query matching nothing says so', false, err.message)
740 }
741
742 // Closing on that message and reopening must not still be saying it.
743 //
744 // This one is a regression check rather than a contract check: the
745 // Fable review of #14 found the palette reopening over an EMPTY query
746 // still showing "No documents match", and because the status is a
747 // live region it announced the stale answer again to a screen reader
748 // — an answer to a question nobody had asked yet.
749 await pressKey('Escape', { vk: 27 })
750 await sleep(300)
751 await pressKey('k', { code: 'KeyK', vk: 75, modifiers: CONTROL })
752 await sleep(400)
753 const stale = await evaluate(
754 `(()=>{const s=document.querySelector('[docs-jumpto-status]');return s.hidden?'':s.textContent.trim()})()`,
755 )
756 check('reopening it does not repeat the last empty-result message', stale === '', `it still says ${JSON.stringify(stale)}`)
757 check(
758 'and it reopens with an empty field',
759 (await evaluate(`document.querySelector('[docs-jumpto-input]').value`)) === '',
760 )
761
762 // Enter opens the chosen document. Queried by a whole title, so the
763 // exact-match rank decides which row is first rather than the
764 // tie-break happening to.
765 await typeText(one.title)
766 try {
767 await settleOn(
768 'a result for a whole title',
769 () => evaluate(`document.querySelectorAll('[docs-jumpto-list] li').length`),
770 (n) => n > 0,
771 )
772 const target = await evaluate(
773 `(()=>{const l=document.querySelector('[docs-jumpto-list] li');return l?l.dataset.href:null})()`,
774 )
775 check('the exact title ranks first', target === one.href, `first result was ${target}, wanted ${one.href}`)
776 await pressKey('Enter', { vk: 13 })
777 await sleep(2000)
778 const url = await evaluate(`location.pathname`)
779 check('Enter opens the chosen document', url === target, `went to ${url}, wanted ${target}`)
780 } catch (err) {
781 check('the exact title ranks first', false, err.message)
782 check('Enter opens the chosen document', false, err.message)
783 }
784}
785
786// 320px reflow — WCAG 2.2 SC 1.4.10, which AGENTS.md takes with no
787// exemptions.
788//
789// Last, and it changes the viewport, so nothing above it may depend on
790// the window size afterwards. The criterion is binary: six pixels of
791// horizontal scroll fails it exactly as a hundred would, and six is
792// what the formatting bar shipped with — three selects in a group that
793// could not break inside itself, ending at x=326 in a 320px viewport.
794// It reached main, because nothing here was looking.
795//
796// The check names the offending element rather than reporting a
797// number, because "something overflows" sends the next person hunting
798// through a stylesheet and "input[docs-search-input] ends at 356" does
799// not.
800//
801// Both pages, not just the document. The list page's own overflow —
802// 36px, from a search form that claimed a fixed field width inside a
803// row it had told not to wrap — was found only because this walks
804// every page rather than the one that was being worked on.
805async function reflowChecks() {
806 await send('Emulation.setDeviceMetricsOverride', {
807 width: 320, height: 720, deviceScaleFactor: 1, mobile: true,
808 })
809 try {
810 for (const [name, path] of [['the document list', '/'], ['a document', null]]) {
811 if (path) {
812 await send('Page.navigate', { url: base + path })
813 await sleep(1500)
814 } else {
815 const href = await evaluate(
816 `(()=>{const a=document.querySelector('a[href^="/d/"]');return a?a.getAttribute('href'):null})()`,
817 )
818 await send('Page.navigate', { url: base + href })
819 await sleep(2500)
820 }
821 const found = await evaluate(`(() => {
822 const vw = document.documentElement.clientWidth
823 const over = []
824 for (const el of document.querySelectorAll('*')) {
825 const r = el.getBoundingClientRect()
826 if (r.width === 0 && r.height === 0) continue
827 if (r.right > vw + 0.5 || r.left < -0.5) {
828 let depth = 0
829 for (let n = el; n.parentElement; n = n.parentElement) depth++
830 over.push({
831 d: depth,
832 what: el.tagName.toLowerCase() +
833 (el.getAttributeNames().filter(a => a.startsWith('docs-')).map(a => '[' + a + ']').join('') || ''),
834 right: Math.round(r.right),
835 })
836 }
837 }
838 over.sort((a, b) => b.d - a.d)
839 return { scrollWidth: document.documentElement.scrollWidth, viewport: vw, worst: over.slice(0, 3) }
840 })()`)
841 // The viewport is asserted to BE 320, not merely used as the
842 // yardstick. Everything here measures against
843 // documentElement.clientWidth, and that reads 320 only because
844 // rastrillo's vendored topbar layout emits
845 // <meta name="viewport" content="width=device-width"> — nothing
846 // in this app does. Lose that meta on a module upgrade and
847 // Chrome's mobile emulation lays out at 980px, clientWidth reads
848 // 980, and both of these checks pass while measuring a
849 // desktop-width page: a green result that has stopped looking at
850 // the thing it is named for.
851 check(
852 `${name} does not scroll sideways at 320px`,
853 found.viewport === 320 && found.scrollWidth <= found.viewport && found.worst.length === 0,
854 found.viewport !== 320
855 ? `the page laid out at ${found.viewport}px, not 320 — check the viewport meta tag; this check measured nothing`
856 : `scrollWidth ${found.scrollWidth} vs viewport ${found.viewport}; ` +
857 found.worst.map((o) => `${o.what} ends at ${o.right}`).join(', '),
858 )
859 }
860 } finally {
861 // Always put the viewport back, even if a check threw — a later
862 // reader running this by hand should not inherit a phone.
863 await send('Emulation.clearDeviceMetricsOverride')
864 }
865}
866
867// The caret-placement checks.
868//
869// These cover fd1d21a (clicking the page margins places the caret, and
870// the focus ring is gone from the editable surface), which shipped with
871// no regression coverage because it was verified with throwaway
872// scripts. The assertions are the ones that branch's author actually
873// ran, contributed to this harness afterwards; the reasoning in each
874// comment is theirs.
875async function caretChecks() {
876 const page = '[docs-page]'
877 const ed = '[docs-editor]'
878
879 // 1. A click in the left margin, level with a block, puts the caret
880 // at the START of that block. "Is the editor focused" is not the
881 // assertion — that passes even when the caret went to the end of
882 // the document, which is the bug.
883 // Settle the scroll position BEFORE measuring. Every toolbar command
884 // ends in view.focus(), and a focus the editor did not attribute to a
885 // pointer scrolls the caret into view — so a coordinate measured
886 // immediately after one can be stale by the time it is clicked, and
887 // the click then lands on the sticky formatting bar instead of the
888 // paper. That produced a failure that looked exactly like broken
889 // caret placement and was not.
890 await settleScrollToTop()
891 // Aim at a block that is actually on screen and clear of the sticky
892 // formatting bar, rather than at a fixed index. A point below the
893 // viewport receives the click and does nothing at all — which looks
894 // identical to the caret being placed wrongly, and is the trap this
895 // check exists to avoid rather than to fall into. Which block it
896 // lands on is not the point; that it lands at the START of the one
897 // beside the pointer is.
898 const target = await evaluate(
899 `(()=>{const p=document.querySelector('${page}');const t=document.querySelector('[docs-toolbar]');` +
900 `const floor=t?t.getBoundingClientRect().bottom:0;` +
901 `const blocks=Array.from(document.querySelectorAll('${ed} > *'));` +
902 `for(let i=0;i<blocks.length;i++){const br=blocks[i].getBoundingClientRect();` +
903 `if(br.top>floor+12 && br.bottom<window.innerHeight-12 && blocks[i].textContent.trim().length>0){` +
904 `const pr=p.getBoundingClientRect();return {index:i,x:pr.left+20,y:br.top+8}}}return null})()`,
905 )
906 if (!target) throw new Error('no block is both on screen and clear of the formatting bar')
907 await click(target.x, target.y)
908 await sleep(400)
909 const fromMargin = await evaluate(CARET_INFO)
910 check(
911 'a click in the left margin puts the caret at the start of that line',
912 !!fromMargin && fromMargin.blockIndex === target.index && fromMargin.offset === 0,
913 `aimed at block ${target.index}, got ${JSON.stringify(fromMargin)}`,
914 )
915
916 // 2. A click in the empty space below the last paragraph but still
917 // inside the editable node. Only meaningful once scrolled to the
918 // bottom — a click below the viewport lands on nothing at all,
919 // which reads exactly like the bug it is supposed to catch.
920 await evaluate(`window.scrollTo(0, document.body.scrollHeight)`)
921 await sleep(400)
922 const belowText = await evaluate(
923 `(()=>{const e=document.querySelector('${ed}');const r=e.getBoundingClientRect();` +
924 `const y=r.bottom-12;if(y<0||y>window.innerHeight) return null;return {x:r.left+40,y}})()`,
925 )
926 if (belowText) {
927 await click(belowText.x, belowText.y)
928 await sleep(400)
929 const c = await evaluate(CARET_INFO)
930 check(
931 'a click below the last paragraph puts the caret in the last block',
932 !!c && c.blockIndex === c.blockCount - 1,
933 JSON.stringify(c),
934 )
935 } else {
936 check('a click below the last paragraph puts the caret in the last block', false, 'the point was off screen')
937 }
938
939 // 3. A click in the page's bottom margin, outside the editable node
940 // entirely. This is the path that goes through placeCaretFromPage
941 // rather than through ProseMirror's own hit testing.
942 const bottomMargin = await evaluate(
943 `(()=>{const p=document.querySelector('${page}');const e=document.querySelector('${ed}');` +
944 `const pr=p.getBoundingClientRect();const er=e.getBoundingClientRect();` +
945 `const y=(er.bottom+pr.bottom)/2;if(y<0||y>window.innerHeight) return null;return {x:pr.left+80,y}})()`,
946 )
947 if (bottomMargin) {
948 await click(bottomMargin.x, bottomMargin.y)
949 await sleep(400)
950 const c = await evaluate(CARET_INFO)
951 check(
952 'a click in the bottom margin puts the caret in the last block',
953 !!c && c.blockIndex === c.blockCount - 1,
954 JSON.stringify(c),
955 )
956 } else {
957 check('a click in the bottom margin puts the caret in the last block', false, 'the point was off screen')
958 }
959
960 // 4. And typing then lands THERE, not merely somewhere. The last
961 // element's own text, not the whole editor's, or a character that
962 // went to the top of the document would still pass.
963 await send('Input.dispatchKeyEvent', { type: 'keyDown', text: 'Q', key: 'Q', code: 'KeyQ', windowsVirtualKeyCode: 81 })
964 await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Q', code: 'KeyQ', windowsVirtualKeyCode: 81 })
965 await sleep(1200)
966 const lastBlockText = await evaluate(`document.querySelector('${ed}').lastElementChild.textContent`)
967 check('typing after that click lands in the last block', lastBlockText.includes('Q'))
968
969 // 5. The no-yank regression, and the one most worth keeping. A focus
970 // event fires BEFORE ProseMirror sets the selection a click asked
971 // for, so a focus handler that scrolls unconditionally yanks the
972 // view to wherever the selection was last left. With the selection
973 // at the end of a long document, clicking in the first block must
974 // leave the page where it is.
975 await settleScrollToTop()
976 const firstBlock = await evaluate(
977 `(()=>{const b=document.querySelector('${ed} > *');const r=b.getBoundingClientRect();return {x:r.left+40,y:r.top+8}})()`,
978 )
979 await click(firstBlock.x, firstBlock.y)
980 await sleep(600)
981 const scrolledTo = await evaluate(`window.scrollY`)
982 check(
983 'clicking near the top does not yank the view to the old selection',
984 scrolledTo < 40,
985 `scrollY became ${scrolledTo}`,
986 )
987
988 // 6. The other half of that trade: the editable surface has no focus
989 // ring (views/show.html removes it, on the argument that a caret
990 // says more), so a focus that did NOT come from a pointer has to
991 // scroll the caret into view — otherwise focus lands with no
992 // visible indicator anywhere on screen, which is a WCAG 2.2 AA
993 // regression and AGENTS.md allows no exemptions.
994 //
995 // The caret session ran this as Tab from the sign-out button. That
996 // no longer reaches the editor: the formatting bar sits between
997 // the header and the paper, so Tab from sign-out now lands on the
998 // toolbar. The guarantee being checked is not about the tab order
999 // though — it is "a non-pointer focus scrolls the caret into
1000 // view" — so it is exercised directly here, and stays true however
1001 // the tab order changes next.
1002 await settleScrollToTop()
1003 await evaluate(`document.querySelector('${ed}').focus()`)
1004 await sleep(700)
1005 const caret = await evaluate(CARET_INFO)
1006 check(
1007 'a keyboard focus scrolls the caret into view',
1008 !!caret && caret.top >= 0 && caret.bottom <= (await evaluate(`window.innerHeight`)),
1009 JSON.stringify(caret),
1010 )
1011
1012 check(
1013 'the editable surface draws no focus ring (the caret is the indicator)',
1014 (await evaluate(`getComputedStyle(document.querySelector('${ed}')).outlineStyle`)) === 'none',
1015 )
1016
1017 // 7. And the document has to be REACHABLE by keyboard from outside
1018 // it. The check above focuses the editor programmatically, which
1019 // succeeds whether or not a person could ever have got there with
1020 // Tab — so if the formatting bar ever traps focus, every other
1021 // check here still passes while the document has become
1022 // unreachable to anyone not using a mouse. (The gap was spotted
1023 // by the caret-placement session; it is exactly the shape
1024 // AGENTS.md names, a check that cannot tell "no" from "I cannot
1025 // see it".)
1026 //
1027 // Bounded rather than exact: the bar is one tab stop today
1028 // (toolbar.mjs's roving tabindex), but asserting an exact number
1029 // would break the week someone adds a control outside the bar for
1030 // a reason that has nothing to do with this. Twelve is generous
1031 // and still fails loudly the day focus cannot get out of the
1032 // toolbar at all.
1033 //
1034 // Starts from the shell bar's brand link, and that is not a free
1035 // choice. It used to start from the sign-out button, which was in
1036 // this page's own header; sign-out is now inside the shell's
1037 // account dropdown, a CLOSED <details>, whose content is in the
1038 // DOM but is not rendered — so querySelector still finds the
1039 // button, .focus() is a silent no-op, and the loop below counted
1040 // Tab presses from wherever focus happened to be already (the
1041 // editor, from check 6 above). It reported 8, which was a true
1042 // measurement of nothing. That is the failure shape AGENTS.md
1043 // names twice, so: the anchor must be something always rendered.
1044 // [estilo-bar-brand] is — the estilo bar's brand link, the first
1045 // focusable thing in the bar at every width (it was rastrillo's
1046 // [rst-shell-brand] until round 2 replaced the shell) — and the
1047 // assertion below fails if it ever stops being focusable, rather
1048 // than quietly measuring from somewhere else.
1049 const anchored = await evaluate(
1050 `(()=>{const b=document.querySelector('[estilo-bar-brand]');if(!b)return false;b.focus();` +
1051 `return document.activeElement===b})()`,
1052 )
1053 check(
1054 'the tab-order check starts where it thinks it does',
1055 anchored === true,
1056 'could not focus [estilo-bar-brand] — the count below would measure from somewhere else',
1057 )
1058 // How many tab stops the bar itself has after the brand, counted from
1059 // the live page rather than pinned: the title field and its Rename
1060 // button, Share…, the switcher when configured, the account trigger —
1061 // not the rows inside a closed panel, which Chrome still lays out.
1062 // Pinning a total is what made the old bound go stale when the bar
1063 // changed; what check 8 below holds is the claim that matters — the menu
1064 // bar and the formatting bar are ONE stop each.
1065 const barStops = await evaluate(
1066 `(()=>{const bar=document.querySelector('[estilo-bar]');const brand=bar.querySelector('[estilo-bar-brand]');` +
1067 `return [...bar.querySelectorAll('a[href],button,input,summary')].filter(e=>{const shut=e.closest('details:not([open])');return e!==brand&&e.tabIndex>=0&&!e.disabled&&(!shut||e.matches('summary')&&e.parentElement===shut)&&e.getClientRects().length>0&&getComputedStyle(e).visibility!=='hidden'}).length})()`,
1068 )
1069 await sleep(200)
1070 let reachedAfter = -1
1071 for (let i = 1; i <= 12; i++) {
1072 await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 })
1073 await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Tab', code: 'Tab', windowsVirtualKeyCode: 9 })
1074 await sleep(120)
1075 if (await evaluate(`document.activeElement === document.querySelector('${ed}')`)) {
1076 reachedAfter = i
1077 break
1078 }
1079 }
1080 check(
1081 'the document is reachable by Tab from the shell bar',
1082 reachedAfter > 0,
1083 reachedAfter > 0 ? '' : 'twelve presses of Tab never reached the editor',
1084 )
1085
1086 // 8. And the bar is ONE stop on the way, not one per control.
1087 // role="toolbar" is a promise that the arrow keys move within it;
1088 // a bar that spends fourteen tab presses has made that promise
1089 // and broken it.
1090 //
1091 // Four, derived rather than chosen, at this drive's 1280px (above
1092 // the shell's own 800px breakpoint, so the bar is laid out wide:
1093 // the hamburger is hidden and the tail is display: contents).
1094 // (History: the paragraphs below derived a fixed four for the
1095 // rastrillo shell. Round 2 counts the bar's own stops from the page
1096 // instead; see barStops above and the check at the end.)
1097 // From [rst-shell-brand], in DOM order: the account summary (1),
1098 // the menu bar, entire, as one roving-tabindex stop (2), the
1099 // formatting bar, entire, as one roving-tabindex stop (3), the
1100 // editor (4).
1101 //
1102 // It was three when the path was sign-out -> bar -> editor and
1103 // this page drew its own header, then five when the two exports
1104 // moved into the bar's trailing end and the account control moved
1105 // into the shell.
1106 //
1107 // It is four now, and it went DOWN while the page gained a whole
1108 // menu bar, which is the reason to re-derive rather than nudge. A
1109 // menu bar adds one stop; the same change took the two export
1110 // links out of the tab order entirely, because they are File menu
1111 // items inside a closed <details> and a closed disclosure's
1112 // contents are not focusable. Nudging 5 upward to admit the new
1113 // control would have left a bound that passes whether the order is
1114 // right or wrong by two.
1115 //
1116 // ONE STOP FOR THE MENU BAR IS THE ENHANCED NUMBER. With no
1117 // JavaScript the bar is six <details> summaries and six stops, so
1118 // the count would be nine. This drive runs with scripts, so four
1119 // is what it should see — but the difference is real, this app
1120 // renders without JavaScript on purpose, and a reader of this
1121 // check is entitled to know which of the two numbers it pins.
1122 //
1123 // DERIVED, NOT MEASURED. Chromium cannot start in the sandbox this
1124 // was written in (scripts/browser-drive.sh's own note: "socket()
1125 // failed: Operation not permitted"), so the four above comes from
1126 // reading the DOM order in views/show.html rather than from a run.
1127 // The first real run of this check is therefore a check on this
1128 // derivation as much as on the page; if it reports five, the extra
1129 // stop is the thing to find, not the bound to raise.
1130 // Round 2 (estilo bar): the stops are the bar's own (barStops,
1131 // counted above from the page), then the menu bar as one stop, the
1132 // formatting bar as one stop, then the editor. So the editor is
1133 // exactly barStops + 3 presses away, and a menu bar or toolbar that
1134 // leaks a second stop makes it barStops + 4 or more.
1135 // I2 (spec 2026-11-11): the menu bar is inside the estilo bar now,
1136 // so barStops counts it, as one stop, with the undo/redo pair and
1137 // Format; after the bar comes only the formatting bar, as one stop
1138 // (the inspector at this drive's 1280px), then the editor. So the
1139 // editor is exactly barStops + 2 presses away, and a menu bar or
1140 // toolbar that leaks a second stop makes it more.
1141 check(
1142 'the menu bar and the formatting bar are one tab stop each',
1143 reachedAfter > 0 && reachedAfter === barStops + 2,
1144 `the editor was ${reachedAfter} tab presses from the brand; the bar has ${barStops} stops of its own, so ${barStops + 2} was expected`,
1145 )
1146
1147 // 9. ...and the arrow keys are what move inside it.
1148 await evaluate(
1149 `(()=>{const c=document.querySelector('[docs-toolbar] [data-docs-command],[docs-toolbar] [data-docs-select]');` +
1150 `const list=Array.from(document.querySelectorAll('[docs-toolbar] [data-docs-command],[docs-toolbar] [data-docs-select]'))` +
1151 `.filter(e=>!e.disabled);if(list[0])list[0].focus();return true})()`,
1152 )
1153 await sleep(150)
1154 const before = await evaluate(`document.activeElement.getAttribute('data-docs-command')||document.activeElement.getAttribute('data-docs-select')`)
1155 await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 })
1156 await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 })
1157 await sleep(200)
1158 const after = await evaluate(`document.activeElement.getAttribute('data-docs-command')||document.activeElement.getAttribute('data-docs-select')`)
1159 check(
1160 'the arrow keys move between the toolbar controls',
1161 !!before && !!after && before !== after,
1162 `focus went from ${before} to ${after}`,
1163 )
1164}
1165
1166ws.onopen = async () => {
1167 try {
1168 await run()
1169 } catch (err) {
1170 check('the drive ran to completion', false, err.message)
1171 }
1172 const failed = checks.filter((c) => !c.ok)
1173 console.log(`\n${checks.length - failed.length}/${checks.length} checks passed`)
1174 ws.close()
1175 process.exit(failed.length === 0 ? 0 : 1)
1176}
1177
1178ws.onerror = () => {
1179 console.error('browser-drive: could not connect to the browser at ' + wsUrl)
1180 process.exit(2)
1181}
1182