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/diverged.mjs — every change a person makes while a
2// resync is pending is kept, in Chromium and in WebKit, through the real
3// editor (feat/replay-while-diverged; Claude Fable's rv-general-probe.mjs
4// made into keys and clipboard events). Paul ranks a lost edit worse than
5// a flash.
6//
7// Run by internal/slidestest/diverged_engines_browser_test.go with the
8// same SLIDES_ENGINES_CONFIG as first-reveal.mjs; decks.diverged holds a
9// fresh deck per engine and case, its text block "First paragraph." /
10// "Second paragraph.". Docs has the same script.
11//
12// Each case: the editor's first save (the refused change, made with real
13// keys) is answered 413, and the rebuild's fetch of the log is held while
14// the person goes on editing. Then it is let go. The page must hold what
15// the case wants, a line RESULT {...} carries it for the Go test to hold
16// the server to, and one Cmd/Ctrl-Z must take back the last change only —
17// the carried changes undo in the steps they were made in — the server
18// following.
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 TEXT = '[slides-stage] [data-block="text"]'
25
26const cases = [
27 {
28 name: 'mixed edits: on the refused text, a paste elsewhere, a delete across server, refused and new text, typing elsewhere',
29 refuse: [['type', 1, 'end', 'x']],
30 edits: [
31 ['type', 1, 'end', 'a'],
32 ['paste', 0, 0, 'ELSEWHERE-'],
33 ['type', 1, 'end', 'b'],
34 ['select', 1, 7, 'end'], ['key', 'Backspace'],
35 // A second later, so it is its own undo step, as it was when made.
36 ['wait', 900],
37 ['type', 0, 'end', 'c'],
38 ],
39 want: ['ELSEWHERE-First paragraph.c', 'Second '],
40 undone: ['ELSEWHERE-First paragraph.', 'Second '],
41 },
42 {
43 name: 'typing on the refused text, a paste elsewhere, more typing after it: all kept',
44 refuse: [['type', 1, 'end', 'x']],
45 edits: [
46 ['type', 1, 'end', 'KEPT'],
47 ['paste', 0, 0, 'ELSEWHERE-'],
48 ['wait', 900],
49 ['type', 1, 'end', ' more'],
50 ],
51 want: ['ELSEWHERE-First paragraph.', 'Second paragraph.KEPT more'],
52 undone: ['ELSEWHERE-First paragraph.', 'Second paragraph.KEPT'],
53 },
54 {
55 name: 'an undo in the middle: typing on the refused text, Cmd-Z, then typing elsewhere',
56 refuse: [['type', 1, 'end', 'x']],
57 edits: [
58 ['wait', 700],
59 ['type', 1, 'end', 'a'],
60 ['undo'],
61 ['wait', 700],
62 ['type', 0, 'end', 'b'],
63 ],
64 want: ['First paragraph.b', 'Second paragraph.'],
65 undone: ['First paragraph.', 'Second paragraph.'],
66 },
67 {
68 name: 'a change that cannot be kept in the middle: typing in the paragraph a refused Enter made, then elsewhere, then in it again',
69 refuse: [['press', 1, 'end', 'Enter']],
70 edits: [
71 ['type', 2, 0, 'INSIDE'],
72 ['type', 0, 'end', ' after'],
73 ['type', 2, 'end', '!'],
74 ],
75 want: ['First paragraph. after', 'Second paragraph.'],
76 undone: ['First paragraph.', 'Second paragraph.'],
77 },
78]
79
80const instrument = () => {
81 const f = window.fetch
82 window.__posts = []
83 window.__errors = []
84 addEventListener('error', (e) => window.__errors.push(String(e.message)))
85 addEventListener('unhandledrejection', (e) => window.__errors.push(String(e.reason)))
86 window.__hold = true
87 window.__release = () => { window.__hold = false; if (window.__go) window.__go() }
88 window.fetch = async function (u, o) {
89 const post = String(u).endsWith('/updates') && o && o.method === 'POST'
90 if (post && !window.refused) {
91 await new Promise((r) => setTimeout(r, 150))
92 window.refused = true
93 window.__posts.push(413)
94 return new Response('', { status: 413 })
95 }
96 if (window.refused && String(u).includes('since=0') && window.__hold) await new Promise((r) => { window.__go = r })
97 const r = await f.call(this, u, o)
98 if (post) window.__posts.push(r.status)
99 return r
100 }
101}
102
103const place = ([i, a, b]) => {
104 const p = document.querySelectorAll('[slides-stage] [data-block="text"] p')[i]
105 p.closest('[contenteditable]').focus()
106 const at = (off) => {
107 const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT)
108 let n
109 let last = null
110 let left = off === 'end' ? Infinity : off
111 while ((n = w.nextNode())) {
112 last = n
113 if (left <= n.data.length) return [n, left]
114 left -= n.data.length
115 }
116 return last ? [last, last.data.length] : [p, 0]
117 }
118 const r = document.createRange()
119 const [sn, so] = at(a)
120 r.setStart(sn, so)
121 if (b !== undefined) {
122 const [en, eo] = at(b)
123 r.setEnd(en, eo)
124 } else r.collapse(true)
125 getSelection().removeAllRanges()
126 getSelection().addRange(r)
127}
128
129const paste = (html) => {
130 const d = new DataTransfer()
131 d.setData('text/html', html)
132 d.setData('text/plain', html)
133 document.activeElement.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true }))
134}
135
136// act runs one step. ProseMirror reads a moved caret on the next
137// selectionchange, so every move is followed by a moment before the key.
138async function act (page, [what, ...args]) {
139 if (what === 'wait') {
140 await pause(args[0])
141 return
142 }
143 if (what === 'undo') {
144 await page.keyboard.press('ControlOrMeta+z')
145 await pause(200)
146 return
147 }
148 if (what === 'select') {
149 await page.evaluate(place, [args[0], args[1], args[2]])
150 await pause(40)
151 } else if (what === 'key') {
152 await page.keyboard.press(args[0])
153 } else {
154 await page.evaluate(place, [args[0], args[1]])
155 await pause(40)
156 if (what === 'type') await page.keyboard.type(args[2])
157 else if (what === 'press') await page.keyboard.press(args[2])
158 else if (what === 'paste') await page.evaluate(paste, args[2])
159 }
160 await pause(80)
161}
162
163const paragraphs = () => [...document.querySelectorAll('[slides-stage] [data-block="text"] p')].map((p) => p.textContent)
164const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
165
166const failures = []
167for (const [engineName, engine] of Object.entries({ chromium, webkit }).filter(([n]) => !process.env.SLIDES_ENGINES_ENGINE || n === process.env.SLIDES_ENGINES_ENGINE)) {
168 const browser = await engine.launch(engineName === 'chromium' ? { headless: true, channel: 'chromium' } : { headless: true })
169 for (const c of cases) {
170 const label = `${engineName}, ${c.name}`
171 const deck = config.decks.diverged.shift()
172 const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1 })
173 await context.addCookies(config.cookies.map((k) => ({ name: k.Name, value: k.Value, url: config.origin, httpOnly: k.HttpOnly, sameSite: 'Lax' })))
174 try {
175 const page = await context.newPage()
176 await page.goto(config.origin + '/d/' + deck + '/edit')
177 await page.waitForSelector(`${TEXT} [contenteditable="true"], ${TEXT}[contenteditable="true"]`, { timeout: 15000 })
178 await page.waitForFunction(() => document.documentElement.getAttribute('data-slides-fonts') === 'shown')
179 await pause(300)
180 await page.evaluate(instrument)
181 for (const step of c.refuse) await act(page, step)
182 await page.waitForFunction(() => window.refused === true, null, { timeout: 5000 })
183 await pause(50)
184 for (const step of c.edits) await act(page, step)
185 const diverged = await page.evaluate(() => !!window.__go || window.__hold)
186 if (!diverged) failures.push(`${label}: the rebuild was not still pending during the edits, so this proves nothing`)
187 await page.evaluate(() => window.__release())
188 await pause(3500)
189 const got = await page.evaluate(paragraphs)
190 if (!same(got, c.want)) failures.push(`${label}: the page holds ${JSON.stringify(got)}, want ${JSON.stringify(c.want)}`)
191 // One undo takes back the last change, and only it.
192 await act(page, ['type', 0, 'end', ''])
193 await page.keyboard.press('ControlOrMeta+z')
194 await pause(2000)
195 const undone = await page.evaluate(paragraphs)
196 if (!same(undone, c.undone)) failures.push(`${label}: after one undo the page holds ${JSON.stringify(undone)}, want ${JSON.stringify(c.undone)}`)
197 const errors = await page.evaluate(() => window.__errors)
198 if (errors.length) failures.push(`${label}: errors ${JSON.stringify(errors)}`)
199 console.log('RESULT ' + JSON.stringify({ label, deck, want: undone }))
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 change made while the resync was pending was kept, in both engines')
213