| 1 | //go:build browser |
| 2 | |
| 3 | package docs_test |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/chromedp/chromedp" |
| 14 | ) |
| 15 | |
| 16 | // Claude Fable's review of #89 at b48dad3, in the real editor: the edges |
| 17 | // of carry.mjs where the sheet and the server came apart, or a replayed |
| 18 | // paste landed in the wrong place. Each test ends with the sheet and the |
| 19 | // server holding the same text. The document is "First paragraph." / |
| 20 | // "Second paragraph.". |
| 21 | |
| 22 | // refuseJS answers the next save 413 once window.refuseNext is set (or |
| 23 | // the first, with first), holds the rebuild's fetch of the log for ms, |
| 24 | // and counts every save. |
| 25 | func refuseJS(first bool, ms int) string { |
| 26 | return `(() => { const f = window.fetch; window.posts = []; window.refuseNext = ` + strconv.FormatBool(first) + `; window.refused = false; |
| 27 | window.fetch = async function (u, o) { |
| 28 | const post = String(u).endsWith('/updates') && o && o.method === 'POST'; |
| 29 | if (post && window.refuseNext && !window.refused) { window.refuseNext = false; await new Promise((r) => setTimeout(r, 150)); window.refused = true; window.posts.push(413); return new Response('', { status: 413 }) } |
| 30 | if (window.refused && !post && String(u).includes('/updates') && !String(u).includes('since=')) await new Promise((r) => setTimeout(r, ` + strconv.Itoa(ms) + `)); |
| 31 | const r = await f.call(this, u, o); if (post) window.posts.push(r.status); return r }; |
| 32 | return true })()` |
| 33 | } |
| 34 | |
| 35 | // docCaretJS puts the caret in paragraph i at offset off (-1: the end). |
| 36 | func docCaretJS(i, off int) string { |
| 37 | return `(() => { const el = document.querySelector('[docs-text]'); el.focus(); const p = el.querySelectorAll('p')[` + strconv.Itoa(i) + `]; |
| 38 | const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT); let n, last = null, left = ` + strconv.Itoa(off) + `; |
| 39 | if (left < 0) left = Infinity; |
| 40 | const r = document.createRange(); |
| 41 | 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 } |
| 42 | r.setStart(last, last.data.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()` |
| 43 | } |
| 44 | |
| 45 | func docSelectJS(words string) string { |
| 46 | return `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 47 | const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); let n; |
| 48 | 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)) + `); |
| 49 | getSelection().removeAllRanges(); getSelection().addRange(r); return true } } |
| 50 | return false })()` |
| 51 | } |
| 52 | |
| 53 | func docPasteJS(html string) string { |
| 54 | return `(() => { const el = document.querySelector('[docs-text]'); const d = new DataTransfer(); d.setData('text/html', ` + strconv.Quote(html) + `); d.setData('text/plain', 'x'); |
| 55 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()` |
| 56 | } |
| 57 | |
| 58 | // sameSheetAndServer fails unless the sheet's paragraphs and the server's |
| 59 | // are the same, and returns the sheet's. |
| 60 | func sameSheetAndServer(t *testing.T, fr *fontRig, sqid string) []string { |
| 61 | t.Helper() |
| 62 | var sheet []string |
| 63 | fr.eval(t, `[...document.querySelectorAll('[docs-text] p')].map((p) => p.textContent)`, &sheet) |
| 64 | structure, err := fr.app.Store().JSON(context.Background(), fr.storeDoc(t, sqid)) |
| 65 | if err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | type node struct { |
| 69 | Text string `json:"text"` |
| 70 | Content []node `json:"content"` |
| 71 | } |
| 72 | var root node |
| 73 | if err := json.Unmarshal([]byte(structure), &root); err != nil { |
| 74 | t.Fatal(err) |
| 75 | } |
| 76 | var words func(n node) string |
| 77 | words = func(n node) string { |
| 78 | s := n.Text |
| 79 | for _, c := range n.Content { |
| 80 | s += words(c) |
| 81 | } |
| 82 | return s |
| 83 | } |
| 84 | var server []string |
| 85 | for _, c := range root.Content { |
| 86 | server = append(server, words(c)) |
| 87 | } |
| 88 | if strings.Join(sheet, "\n") != strings.Join(server, "\n") { |
| 89 | t.Errorf("the sheet and the server differ after the resync: sheet %q, server %q", sheet, server) |
| 90 | } |
| 91 | return sheet |
| 92 | } |
| 93 | |
| 94 | // The tab typed "abc", saved, then "x", refused, and Backspaced over "cx": |
| 95 | // one delete range of one client, which Yjs applied up to what the rebuilt |
| 96 | // document holds and held pending past it (Fable's finding 1). |
| 97 | func TestABackspaceAcrossSavedAndRefusedWordsReachesTheServer(t *testing.T) { |
| 98 | fr := newFontRig(t) |
| 99 | sqid := fr.document(t, "boundary", "simple.bin") |
| 100 | fr.open(t, sqid) |
| 101 | fr.editable(t) |
| 102 | var ok bool |
| 103 | fr.eval(t, refuseJS(false, 1500), &ok) |
| 104 | fr.eval(t, docCaretJS(0, -1), &ok) |
| 105 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("abc")) |
| 106 | untilTrue(t, fr, `window.posts.length >= 1`) |
| 107 | fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
| 108 | fr.eval(t, `window.refuseNext = true`, &ok) |
| 109 | fr.rig.Run(chromedp.KeyEvent("x")) |
| 110 | untilTrue(t, fr, `window.refused === true`) |
| 111 | fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) |
| 112 | fr.eval(t, docSelectJS("cx"), &ok) |
| 113 | if !ok { |
| 114 | t.Fatal("no \"cx\" on the sheet") |
| 115 | } |
| 116 | fr.rig.Run(chromedp.Sleep(50*time.Millisecond), chromedp.KeyEvent("\b")) |
| 117 | fr.rig.Run(chromedp.Sleep(5 * time.Second)) |
| 118 | var posts []int |
| 119 | fr.eval(t, `window.posts`, &posts) |
| 120 | t.Logf("posts %v", posts) |
| 121 | if sheet := sameSheetAndServer(t, fr, sqid); len(sheet) == 0 || sheet[0] != "First paragraph.ab" { |
| 122 | t.Errorf("the sheet says %q, want \"First paragraph.ab\" first", sheet) |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | // A refused "r" typed into "par|agraph" repeats the letter beside it, so |
| 127 | // the two ends of the rebuilt document's diff overlap; the one-span map |
| 128 | // clamped that to an empty span and the replayed paste, made right after |
| 129 | // the r, landed a letter off (Fable's finding 2). |
| 130 | func TestAReplayedPasteLandsWhereItWasMadeBesideARepeatedLetter(t *testing.T) { |
| 131 | fr := newFontRig(t) |
| 132 | sqid := fr.document(t, "overlap", "simple.bin") |
| 133 | fr.match.Store("LiberationMono-") |
| 134 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 135 | fr.open(t, sqid) |
| 136 | fr.editable(t) |
| 137 | var ok bool |
| 138 | fr.eval(t, refuseJS(true, 0), &ok) |
| 139 | fr.eval(t, docCaretJS(1, len("Second par")), &ok) |
| 140 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("r"), chromedp.Sleep(30*time.Millisecond)) |
| 141 | fr.eval(t, docPasteJS(`<p>REVIEW_RESYNC_PASTE <code>codeword</code></p>`), &ok) |
| 142 | var waiting bool |
| 143 | fr.eval(t, `!!document.querySelector('[docs-text]').inert`, &waiting) |
| 144 | if !waiting { |
| 145 | t.Fatal("the paste did not wait for its font, so this proves nothing") |
| 146 | } |
| 147 | untilTrue(t, fr, `window.refused === true`) |
| 148 | fr.rig.Run(chromedp.Sleep(5 * time.Second)) |
| 149 | want := "Second parREVIEW_RESYNC_PASTE codewordagraph." |
| 150 | if sheet := sameSheetAndServer(t, fr, sqid); len(sheet) < 2 || sheet[1] != want { |
| 151 | t.Errorf("the replayed paste is not where it was made: sheet %q, want %q second", sheet, want) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // Once one change is held back — written on the refused text, with no |
| 156 | // transaction to replay — every change after it under the same client id |
| 157 | // was held back too, wherever it was made (Fable's finding 3). In both |
| 158 | // orders the paste made in a clean spot is kept, on the sheet and the |
| 159 | // server. |
| 160 | func 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.document(t, "contiguity", "simple.bin") |
| 165 | fr.open(t, sqid) |
| 166 | fr.editable(t) |
| 167 | var ok bool |
| 168 | fr.eval(t, refuseJS(true, 2500), &ok) |
| 169 | fr.eval(t, docCaretJS(0, -1), &ok) |
| 170 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("x")) |
| 171 | untilTrue(t, fr, `window.refused === true`) |
| 172 | fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) |
| 173 | onRefused := func() { |
| 174 | fr.eval(t, docCaretJS(0, -1), &ok) |
| 175 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(60*time.Millisecond)) |
| 176 | } |
| 177 | elsewhere := func() { |
| 178 | fr.eval(t, docCaretJS(1, 0), &ok) |
| 179 | fr.rig.Run(chromedp.Sleep(40 * time.Millisecond)) |
| 180 | fr.eval(t, docPasteJS(`CLEANPASTE`), &ok) |
| 181 | fr.rig.Run(chromedp.Sleep(60 * time.Millisecond)) |
| 182 | } |
| 183 | if strings.HasPrefix(order, "on") { |
| 184 | onRefused() |
| 185 | elsewhere() |
| 186 | } else { |
| 187 | elsewhere() |
| 188 | onRefused() |
| 189 | } |
| 190 | fr.rig.Run(chromedp.Sleep(5 * time.Second)) |
| 191 | sheet := sameSheetAndServer(t, fr, sqid) |
| 192 | if len(sheet) < 2 || sheet[1] != "CLEANPASTESecond paragraph." { |
| 193 | t.Errorf("the paste made in a clean spot was lost: sheet %q", sheet) |
| 194 | } |
| 195 | }) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // An undo made while diverged stays undone (Claude Fable's P1 on #90). The |
| 200 | // undo is the undo manager's Yjs change; the "a" it took back, typed on the |
| 201 | // refused text, is a change the resync replays under new ids, which the |
| 202 | // undo's delete cannot reach, so the "a" came back on the sheet and was |
| 203 | // posted — with a "b" typed after, "ab" where the person wrote "b". The |
| 204 | // keeper now marks what the undo took back and leaves it out; a redo |
| 205 | // brings back the change it was undoing, which the resync replays. |
| 206 | func TestAnUndoWhileARefusalIsPendingStaysUndone(t *testing.T) { |
| 207 | for _, c := range []struct { |
| 208 | name, then, want string |
| 209 | redo bool |
| 210 | }{ |
| 211 | {name: "Cmd-Z alone", want: "First paragraph."}, |
| 212 | {name: "Cmd-Z, then b typed on the x", then: "b", want: "First paragraph.b"}, |
| 213 | {name: "Cmd-Z, then Cmd-Shift-Z", redo: true, want: "First paragraph.a"}, |
| 214 | } { |
| 215 | t.Run(c.name, func(t *testing.T) { |
| 216 | fr := newFontRig(t) |
| 217 | sqid := fr.document(t, "undo", "simple.bin") |
| 218 | fr.open(t, sqid) |
| 219 | fr.editable(t) |
| 220 | var ok bool |
| 221 | fr.eval(t, refuseJS(true, 3000), &ok) |
| 222 | fr.eval(t, docCaretJS(0, -1), &ok) |
| 223 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("x")) |
| 224 | untilTrue(t, fr, `window.refused === true`) |
| 225 | // Past the undo manager's 500 ms capture window, so Cmd-Z takes |
| 226 | // back the "a" alone, not the x with it. |
| 227 | fr.rig.Run(chromedp.Sleep(700 * time.Millisecond)) |
| 228 | fr.eval(t, docCaretJS(0, -1), &ok) |
| 229 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(120*time.Millisecond)) |
| 230 | fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(200*time.Millisecond)) |
| 231 | if c.redo { |
| 232 | fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(200*time.Millisecond)) |
| 233 | } |
| 234 | if c.then != "" { |
| 235 | fr.eval(t, docCaretJS(0, -1), &ok) |
| 236 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent(c.then), chromedp.Sleep(120*time.Millisecond)) |
| 237 | } |
| 238 | fr.rig.Run(chromedp.Sleep(6 * time.Second)) |
| 239 | if sheet := sameSheetAndServer(t, fr, sqid); len(sheet) == 0 || sheet[0] != c.want { |
| 240 | t.Errorf("after the resync the sheet reads %q, want %q first", sheet, c.want) |
| 241 | } |
| 242 | }) |
| 243 | } |
| 244 | } |
| 245 | |