oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package slidestest
4
5import (
6 "strconv"
7 "strings"
8 "testing"
9 "time"
10
11 "github.com/chromedp/chromedp"
12)
13
14// Claude Fable's review of #28 at c49ed4e, in the real editor: the edges
15// of carry.mjs where the page and the server came apart, or a replayed
16// paste landed in the wrong place. Each test ends with the page and the
17// server holding the same text.
18
19const carryDeck = `[{"op":"set_meta","theme":"paper","title":"Carry"},
20 {"op":"add_slide","id":"slideone0001","layout":"flow","template":"title-body"},
21 {"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"Carry"},
22 {"op":"add_block","slide":"slideone0001","id":"text00000001","type":"text","region":"body","markdown":"hello world\n\nSecond paragraph."}]`
23
24// caretJS puts the caret in paragraph i of the text block at offset off
25// (a number, or -1 for the end).
26func caretJS(i, off int) string {
27 return `(() => { const p = document.querySelectorAll('[slides-stage] [data-block="text"] p')[` + strconv.Itoa(i) + `];
28 p.closest('[contenteditable]').focus();
29 const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT); let n, last = null, left = ` + strconv.Itoa(off) + `;
30 if (left < 0) left = Infinity;
31 const r = document.createRange();
32 while ((n = w.nextNode())) { last = n; if (left <= n.data.length) { r.setStart(n, left); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true } left -= n.data.length }
33 r.setStart(last, last.data.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`
34}
35
36func selectWordsJS(words string) string {
37 return `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
38 const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); let n;
39 while ((n = w.nextNode())) { const i = n.data.indexOf(` + strconv.Quote(words) + `); if (i >= 0) { const r = document.createRange(); r.setStart(n, i); r.setEnd(n, i + ` + strconv.Itoa(len(words)) + `);
40 getSelection().removeAllRanges(); getSelection().addRange(r); return true } }
41 return false })()`
42}
43
44// pasteHereJS pastes html at the selection ProseMirror already has.
45func pasteHereJS(html string) string {
46 return `(() => { const el = document.activeElement; const d = new DataTransfer(); d.setData('text/html', ` + strconv.Quote(html) + `); d.setData('text/plain', 'x');
47 el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`
48}
49
50const pageParagraphsJS = `[...document.querySelectorAll('[slides-stage] [data-block="text"] p')].map((p) => p.textContent)`
51
52// samePageAndServer fails unless the page's text block and the server's
53// hold the same paragraphs, and returns the page's.
54func samePageAndServer(t *testing.T, fr *fontRig, sqid string) []string {
55 t.Helper()
56 var page []string
57 fr.eval(t, pageParagraphsJS, &page)
58 server := serverParagraphs(t, fr, sqid)
59 if strings.Join(page, "\n") != strings.Join(server, "\n") {
60 t.Errorf("the page and the server differ after the resync: page %q, server %q", page, server)
61 }
62 return page
63}
64
65// The tab typed "abc", saved, then "x", refused, and Backspaced over "cx":
66// one delete range of one client, which Yjs applied up to what the rebuilt
67// document holds — the "c" — and held pending past it. It read as not
68// taken, nothing was posted, and the page said "ab" while the server kept
69// "abc" (Fable's finding 1 on #28).
70func TestABackspaceAcrossSavedAndRefusedWordsReachesTheServer(t *testing.T) {
71 fr := newFontRig(t)
72 sqid := fr.deck(t, "boundary", carryDeck)
73 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
74 fr.editable(t)
75 fr.eval(t, `(() => { const f = window.fetch; window.posts = []; window.refuseNext = false; window.refused = false;
76 window.fetch = async function (u, o) {
77 const post = String(u).endsWith('/updates') && o && o.method === 'POST';
78 if (post && window.refuseNext && !window.refused) { window.refused = true; window.refuseNext = false; await new Promise((r) => setTimeout(r, 150)); window.posts.push(413); return new Response('', { status: 413 }) }
79 if (window.refused && String(u).includes('since=0')) await new Promise((r) => setTimeout(r, 1500));
80 const r = await f.call(this, u, o); if (post) window.posts.push(r.status); return r };
81 return true })()`, nil)
82 fr.eval(t, caretJS(0, -1), nil)
83 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("abc"))
84 fr.until(t, `window.posts.length >= 1`)
85 fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
86 fr.eval(t, `window.refuseNext = true`, nil)
87 fr.rig.Run(chromedp.KeyEvent("x"))
88 fr.until(t, `window.refused === true`)
89 fr.rig.Run(chromedp.Sleep(50 * time.Millisecond))
90 var ok bool
91 fr.eval(t, selectWordsJS("cx"), &ok)
92 if !ok {
93 t.Fatalf("no \"cx\" on the stage: %q", fr.stageText(t))
94 }
95 fr.rig.Run(chromedp.Sleep(50*time.Millisecond), chromedp.KeyEvent("\b"))
96 fr.rig.Run(chromedp.Sleep(5 * time.Second))
97 var posts []int
98 fr.eval(t, `window.posts`, &posts)
99 t.Logf("posts %v", posts)
100 if page := samePageAndServer(t, fr, sqid); len(page) == 0 || page[0] != "hello worldab" {
101 t.Errorf("the page says %q, want \"hello worldab\"", page)
102 }
103}
104
105// A refused change that repeats a letter beside it makes the two ends of
106// the rebuilt text's diff overlap; the one-span map clamped that to an
107// empty span, and the replayed paste landed a letter off (Fable's finding
108// 2 on #28). Both shapes: an "l" typed into "hell|o" with the paste right
109// after it, anchored to the refused l; an "l" of "hello" deleted, with the
110// paste at the paragraph's end.
111func TestAReplayedPasteLandsWhereItWasMadeBesideARepeatedLetter(t *testing.T) {
112 for _, c := range []struct {
113 name string
114 caret int
115 key string
116 pasteAt int
117 want string
118 }{
119 {"an l typed into hell|o, the paste right after it", 4, "l", -2, "hellREVIEW_RESYNC_PASTE codewordo world"},
120 // The deletion was refused, so the server keeps hello whole.
121 {"an l of hello deleted, the paste at the end", 4, "\b", -1, "hello worldREVIEW_RESYNC_PASTE codeword"},
122 } {
123 t.Run(c.name, func(t *testing.T) {
124 fr := newFontRig(t)
125 sqid := fr.deck(t, "overlap", carryDeck)
126 fr.match.Store("LiberationMono-")
127 fr.slow.Store(int64(3 * time.Second))
128 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
129 fr.editable(t)
130 fr.eval(t, refuseFirstSaveJS(1500), nil)
131 fr.eval(t, caretJS(0, c.caret), nil)
132 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent(c.key))
133 if c.pasteAt == -1 {
134 fr.eval(t, caretJS(0, -1), nil)
135 fr.rig.Run(chromedp.Sleep(40 * time.Millisecond))
136 }
137 fr.eval(t, pasteHereJS(`<p>REVIEW_RESYNC_PASTE <code>codeword</code></p>`), nil)
138 var waiting string
139 fr.eval(t, `document.querySelector('[slides-fonts-status]').getAttribute('data-state')`, &waiting)
140 if waiting != "loading" {
141 t.Fatalf("the paste did not wait for its font (%q), so this proves nothing", waiting)
142 }
143 fr.until(t, `window.refused === true`)
144 fr.rig.Run(chromedp.Sleep(6 * time.Second))
145 want := c.want
146 if page := samePageAndServer(t, fr, sqid); len(page) == 0 || page[0] != want {
147 t.Errorf("the replayed paste is not where it was made: page %q, want %q first", page, want)
148 }
149 })
150 }
151}
152
153// Once one change is held back — written on the refused text, with no
154// transaction to replay — every change after it under the same client id
155// was held back too, wherever it was made: Yjs integrates a client's
156// structs in clock order (Fable's finding 3 on #28). The keeper gives the
157// document a fresh id after every change while diverged. In both orders
158// the paste made in a clean spot is kept, on the page and the server; the
159// keystroke on the refused text is the one change lost.
160func TestAChangeInACleanSpotIsNotLostWithOneOnTheRefusedText(t *testing.T) {
161 for _, order := range []string{"on the refused text, then elsewhere", "elsewhere, then on the refused text"} {
162 t.Run(order, func(t *testing.T) {
163 fr := newFontRig(t)
164 sqid := fr.deck(t, "contiguity", carryDeck)
165 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
166 fr.editable(t)
167 fr.eval(t, refuseFirstSaveJS(2500), nil)
168 fr.eval(t, caretJS(0, -1), nil)
169 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("x"))
170 fr.until(t, `window.refused === true`)
171 fr.rig.Run(chromedp.Sleep(50 * time.Millisecond))
172 onRefused := func() {
173 fr.eval(t, caretJS(0, -1), nil)
174 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(60*time.Millisecond))
175 }
176 elsewhere := func() {
177 fr.eval(t, caretJS(1, 0), nil)
178 fr.rig.Run(chromedp.Sleep(40 * time.Millisecond))
179 fr.eval(t, pasteHereJS(`CLEANPASTE`), nil)
180 fr.rig.Run(chromedp.Sleep(60 * time.Millisecond))
181 }
182 if strings.HasPrefix(order, "on") {
183 onRefused()
184 elsewhere()
185 } else {
186 elsewhere()
187 onRefused()
188 }
189 fr.rig.Run(chromedp.Sleep(5 * time.Second))
190 page := samePageAndServer(t, fr, sqid)
191 if len(page) < 2 || page[1] != "CLEANPASTESecond paragraph." {
192 t.Errorf("the paste made in a clean spot was lost: page %q", page)
193 }
194 })
195 }
196}
197
198// An undo made while diverged stays undone (Claude Fable's P1 on #29). The
199// undo is the undo manager's Yjs change; the "a" it took back, typed on the
200// refused text, is a change the resync replays under new ids, which the
201// undo's delete cannot reach, so the "a" came back on the page and was
202// posted — with a "b" typed after, "ab" where the person wrote "b". The
203// keeper now marks what the undo took back and leaves it out; a redo
204// brings back the change it was undoing, which the resync replays.
205func TestAnUndoWhileARefusalIsPendingStaysUndone(t *testing.T) {
206 for _, c := range []struct {
207 name, then, want string
208 redo bool
209 }{
210 {name: "Cmd-Z alone", want: "hello world"},
211 {name: "Cmd-Z, then b typed on the x", then: "b", want: "hello worldb"},
212 {name: "Cmd-Z, then Cmd-Shift-Z", redo: true, want: "hello worlda"},
213 } {
214 t.Run(c.name, func(t *testing.T) {
215 fr := newFontRig(t)
216 sqid := fr.deck(t, "undo", carryDeck)
217 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
218 fr.editable(t)
219 fr.eval(t, refuseFirstSaveJS(3000), nil)
220 fr.eval(t, caretJS(0, -1), nil)
221 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("x"))
222 fr.until(t, `window.refused === true`)
223 // Past the undo manager's 500 ms capture window, so Cmd-Z takes
224 // back the "a" alone, not the x with it.
225 fr.rig.Run(chromedp.Sleep(700 * time.Millisecond))
226 fr.eval(t, caretJS(0, -1), nil)
227 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(120*time.Millisecond))
228 fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(200*time.Millisecond))
229 if c.redo {
230 fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(200*time.Millisecond))
231 }
232 if c.then != "" {
233 fr.eval(t, caretJS(0, -1), nil)
234 fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent(c.then), chromedp.Sleep(120*time.Millisecond))
235 }
236 fr.rig.Run(chromedp.Sleep(6 * time.Second))
237 if page := samePageAndServer(t, fr, sqid); len(page) == 0 || page[0] != c.want {
238 t.Errorf("after the resync the page reads %q, want %q first", page, c.want)
239 }
240 })
241 }
242}
243