oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/engines/replay.mjs — a paste that waited for its font is kept
2// across a resync, in Chromium and in WebKit, through the real editor
3// (Claude Fable's eleven replay cases on #27/#88, pm-replay-probe.mjs, made
4// into the editor's own keys and clipboard).
5//
6// Run by internal/slidestest/replay_engines_browser_test.go with the same
7// SLIDES_ENGINES_CONFIG as first-reveal.mjs; decks.replay holds a fresh
8// deck per engine and case, its text block "First paragraph." / "Second
9// paragraph.".
10//
11// Each case: the editor's first save is answered 413 (the refused change,
12// made with real keys); at once a paste with code in it is made, which
13// waits for the code face (held 1.5 s); a colleague's words reach the
14// server meanwhile in (j) and (k), through a second editor, while the
15// rebuild's fetch is held. Afterwards the page must hold the paste once, in
16// the shape the case wants, and the pasted words must never have left the
17// page once there — no DOM change and no frame without them. A line
18// RESULT {...} per case carries what the Go test checks on the server.
19
20const { chromium, webkit } = await import('playwright')
21
22const config = JSON.parse(process.env.SLIDES_ENGINES_CONFIG)
23const pause = (ms) => new Promise((r) => setTimeout(r, ms))
24const PASTE = '<p>REVIEW_RESYNC_PASTE <code>codeword</code></p>'
25const TWO = '<p>ONE <code>c1</code></p><p>TWO</p>'
26const KEPT = ['First paragraph.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword']
27
28// Each step is [what, ...args] run in the page (see act below).
29const cases = [
30 { name: '(a) the paste right after the refused x (Fable\'s probe)', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], want: KEPT },
31 { name: '(b) the refused x elsewhere, before the paste', refuse: [['type', 0, 'end', 'x']], paste: [['caret', 1, 'end']], want: KEPT },
32 { name: '(g) the refused x after the paste point', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 0, 'end']], want: ['First paragraph.REVIEW_RESYNC_PASTE codeword', 'Second paragraph.'] },
33 { name: '(c) two refused x, the paste after the second', refuse: [['type', 0, 'end', 'x'], ['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], want: KEPT },
34 { name: '(i) the refused x mid-paragraph, the paste at its end', refuse: [['type', 1, 7, 'x']], paste: [['caret', 1, 'end']], want: KEPT },
35 { name: '(d) the paste inside a paragraph the refused Enter made', refuse: [['press', 1, 'end', 'Enter']], paste: [['caret', 2, 0]], want: ['First paragraph.', 'Second paragraph.'], lost: true },
36 { name: '(e) the paste over "paragraph.x"', refuse: [['type', 1, 'end', 'x']], paste: [['select', 1, 7, 'end']], want: ['First paragraph.', 'Second REVIEW_RESYNC_PASTE codeword'] },
37 { name: '(f) a refused deletion elsewhere', refuse: [['select', 0, 6, 15], ['key', 'Backspace']], paste: [['caret', 1, 'end']], want: KEPT },
38 { name: '(h) two paragraphs pasted after the refused x', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], html: TWO, words: 'ONE', want: ['First paragraph.', 'Second paragraph.ONE c1', 'TWO'] },
39 { name: '(j) a colleague\'s words before, the refused x after', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], colleague: [0, ' More from a colleague.'], want: ['First paragraph. More from a colleague.', 'Second paragraph.REVIEW_RESYNC_PASTE codeword'] },
40 { name: '(k) a colleague appended where the x was refused', refuse: [['type', 1, 'end', 'x']], paste: [['caret', 1, 'end']], colleague: [1, ' Colleague.'], want: ['First paragraph.', 'Second paragraph. Colleague.REVIEW_RESYNC_PASTE codeword'] },
41]
42
43// In the page: the first save refused, the rebuild's fetch held while
44// window.__hold is set, and a log of whether the pasted words are on the
45// stage at every DOM change and every frame.
46const instrument = (words) => {
47 const f = window.fetch
48 window.__posts = []
49 window.__errors = []
50 addEventListener('error', (e) => window.__errors.push(String(e.message)))
51 addEventListener('unhandledrejection', (e) => window.__errors.push(String(e.reason)))
52 window.__release = () => { window.__hold = false; if (window.__go) window.__go() }
53 window.fetch = async function (u, o) {
54 const post = String(u).endsWith('/updates') && o && o.method === 'POST'
55 if (post && !window.refused) {
56 await new Promise((r) => setTimeout(r, 150))
57 window.refused = true
58 window.__posts.push(413)
59 return new Response('', { status: 413 })
60 }
61 if (window.refused && String(u).includes('since=0') && window.__hold) await new Promise((r) => { window.__go = r })
62 const r = await f.call(this, u, o)
63 if (post) window.__posts.push(r.status)
64 return r
65 }
66 window.__log = []
67 const stage = document.querySelector('[slides-stage]')
68 const rec = (how) => {
69 const has = stage.textContent.includes(words)
70 const last = window.__log[window.__log.length - 1]
71 if (!last || last.has !== has) window.__log.push({ ms: Math.round(performance.now()), has, how })
72 }
73 new MutationObserver(() => rec('dom')).observe(stage, { subtree: true, childList: true, characterData: true })
74 const frame = () => { rec('frame'); requestAnimationFrame(frame) }
75 requestAnimationFrame(frame)
76}
77
78// place puts the DOM selection in paragraph i of the text block: a caret at
79// offset (a number or 'end'), or a range from a to b.
80const place = ([i, a, b]) => {
81 const ps = document.querySelectorAll('[slides-stage] [data-block="text"] p')
82 const p = ps[i]
83 const el = p.closest('[contenteditable]')
84 el.focus()
85 const at = (off) => {
86 const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT)
87 let n
88 let last = null
89 let left = off === 'end' ? Infinity : off
90 while ((n = w.nextNode())) {
91 last = n
92 if (left <= n.data.length) return [n, left]
93 left -= n.data.length
94 }
95 return last ? [last, last.data.length] : [p, 0]
96 }
97 const r = document.createRange()
98 const [sn, so] = at(a)
99 r.setStart(sn, so)
100 if (b !== undefined) {
101 const [en, eo] = at(b)
102 r.setEnd(en, eo)
103 } else r.collapse(true)
104 getSelection().removeAllRanges()
105 getSelection().addRange(r)
106}
107
108const paste = (html) => {
109 const el = document.activeElement
110 const d = new DataTransfer()
111 d.setData('text/html', html)
112 d.setData('text/plain', 'x')
113 el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true }))
114}
115
116// act runs one step. ProseMirror reads a moved caret on the next
117// selectionchange, so every move is followed by a moment before the key.
118async function act (page, [what, ...args]) {
119 if (what === 'caret') await page.evaluate(place, [args[0], args[1]])
120 else if (what === 'select') await page.evaluate(place, [args[0], args[1], args[2]])
121 else if (what === 'type' || what === 'press') {
122 await page.evaluate(place, [args[0], args[1]])
123 await pause(40)
124 if (what === 'type') await page.keyboard.type(args[2])
125 else await page.keyboard.press(args[2])
126 return
127 } else if (what === 'key') {
128 await page.keyboard.press(args[0])
129 return
130 }
131 await pause(40)
132}
133
134const paragraphs = () => [...document.querySelectorAll('[slides-stage] [data-block="text"] p')].map((p) => p.textContent)
135
136async function editor (context, deck) {
137 const page = await context.newPage()
138 await page.goto(config.origin + '/d/' + deck + '/edit')
139 await page.waitForSelector('[slides-stage] [data-block="text"] [contenteditable="true"], [slides-stage] [data-block="text"][contenteditable="true"]', { timeout: 15000 })
140 await page.waitForFunction(() => document.documentElement.getAttribute('data-slides-fonts') === 'shown')
141 await pause(300)
142 return page
143}
144
145const failures = []
146for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.SLIDES_ENGINES_ENGINE || n === process.env.SLIDES_ENGINES_ENGINE)) {
147 const browser = await engine.launch(engineName === 'chromium' ? { headless: true, channel: 'chromium' } : { headless: true })
148 for (const c of cases) {
149 if (process.env.SLIDES_REPLAY_CASE && !c.name.startsWith(process.env.SLIDES_REPLAY_CASE)) continue
150 const label = `${engineName}, ${c.name}`
151 const deck = config.decks.replay.shift()
152 const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1 })
153 await context.addCookies(config.cookies.map((k) => ({ name: k.Name, value: k.Value, url: config.origin, httpOnly: k.HttpOnly, sameSite: 'Lax' })))
154 await context.route('**/*', async (route) => {
155 if (/LiberationMono-/.test(route.request().url())) {
156 const response = await route.fetch()
157 await pause(1500)
158 try { await route.fulfill({ response }) } catch {}
159 return
160 }
161 return route.continue()
162 })
163 try {
164 const page = await editor(context, deck)
165 const words = c.words || 'REVIEW_RESYNC_PASTE'
166 await page.evaluate(instrument, words)
167 if (c.colleague) await page.evaluate(() => { window.__hold = true })
168 // The refused change, and at once the paste: it is waiting for its
169 // font when the refusal arrives (the save goes 250 ms after the
170 // first key and is answered 150 ms later), and runs after it.
171 for (const step of c.refuse) await act(page, step)
172 for (const step of c.paste) await act(page, step)
173 const early = await page.evaluate(() => !!window.refused)
174 await page.evaluate(paste, c.html || PASTE)
175 const waited = await page.evaluate(() => document.querySelector('[slides-fonts-status]').getAttribute('data-state') === 'loading')
176 if (early || !waited) failures.push(`${label}: the paste did not wait for its font across the refusal (${early ? 'refused first' : 'no wait'}), so this proves nothing`)
177 await page.waitForFunction(() => window.refused === true, null, { timeout: 5000 })
178 if (c.colleague) {
179 const other = await editor(context, deck)
180 await act(other, ['caret', c.colleague[0], 'end'])
181 await other.keyboard.type(c.colleague[1])
182 await pause(1500)
183 await other.close()
184 await page.evaluate(() => window.__release())
185 }
186 await pause(4500)
187 const got = await page.evaluate(paragraphs)
188 const state = await page.evaluate(() => ({ log: window.__log, posts: window.__posts, errors: window.__errors, status: document.querySelector('[estilo-save-status]') && document.querySelector('[estilo-save-status]').getAttribute('data-state') }))
189 if (JSON.stringify(got) !== JSON.stringify(c.want)) failures.push(`${label}: the page holds ${JSON.stringify(got)}, want ${JSON.stringify(c.want)}`)
190 if (state.errors.length) failures.push(`${label}: errors ${JSON.stringify(state.errors)}`)
191 if (!c.lost) {
192 const appeared = state.log.filter((e) => e.has).length
193 const stayed = state.log.length && state.log[state.log.length - 1].has
194 if (appeared !== 1 || !stayed) failures.push(`${label}: the pasted words appeared ${appeared} times and ${stayed ? 'stayed' : 'went'}, want once and to stay: ${JSON.stringify(state.log)}`)
195 } else {
196 if (state.posts.length !== 1) failures.push(`${label}: a paste that could not be kept was posted: ${JSON.stringify(state.posts)}`)
197 if (state.status !== 'failed') failures.push(`${label}: the save line says ${state.status}, want failed`)
198 }
199 console.log('RESULT ' + JSON.stringify({ label, deck, want: c.want }))
200 } catch (err) {
201 failures.push(`${label}: ${err.message}`)
202 }
203 await context.close()
204 }
205 await browser.close()
206}
207
208if (failures.length) {
209 console.error(failures.join('\n'))
210 process.exit(1)
211}
212console.log('every case kept its paste, or refused it cleanly, in both engines')
213