| 1 | //go:build browser |
| 2 | |
| 3 | package docs_test |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/chromedp/chromedp" |
| 12 | ) |
| 13 | |
| 14 | // A resync never discards a paste that was waiting for its font (Claude |
| 15 | // Fable's P1 on Docs #87; Slides #27 had the same). A typed character's |
| 16 | // save is answered 413, which sends the editor into a resync; 100 ms |
| 17 | // later text with a code mark is pasted, Mono 1.5 s away. The paste runs |
| 18 | // once its font is in, on the view and document it was made in — the font |
| 19 | // strip does not say the font was unavailable — and is carried onto the |
| 20 | // rebuilt document. |
| 21 | // |
| 22 | // - elsewhere: the refused character is in the first paragraph, the |
| 23 | // paste at the end of the last. The paste is on the sheet once and on |
| 24 | // the server once, and once its words are on the sheet no DOM change |
| 25 | // and no frame is without them. |
| 26 | // - on the refused text: Fable's probe as written, the paste straight |
| 27 | // after the refused character. Yjs anchors it to that character, |
| 28 | // which the server never took, so its own updates cannot integrate; |
| 29 | // its ProseMirror transaction is replayed onto the rebuilt document |
| 30 | // instead (carry.mjs, this branch). The paste is on the sheet once and |
| 31 | // on the server once and never leaves the sheet, as elsewhere; the |
| 32 | // refused character alone is lost, and the save line says so. |
| 33 | // - control: the same steps as Fable's probe with the save accepted. |
| 34 | func TestFontAResyncNeverDiscardsAWaitingPaste(t *testing.T) { |
| 35 | for _, c := range []struct { |
| 36 | name string |
| 37 | refuse, elsewhere bool |
| 38 | }{ |
| 39 | {"elsewhere", true, true}, |
| 40 | {"on the refused text", true, false}, |
| 41 | {"control", false, false}, |
| 42 | } { |
| 43 | t.Run(c.name, func(t *testing.T) { resyncPaste(t, c.refuse, c.elsewhere) }) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func resyncPaste(t *testing.T, refuse, elsewhere bool) { |
| 48 | fr := newFontRig(t) |
| 49 | sqid := fr.document(t, "resync pending paste", "simple.bin") |
| 50 | fr.match.Store("LiberationMono-") |
| 51 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 52 | fr.open(t, sqid) |
| 53 | fr.editable(t) |
| 54 | var ok bool |
| 55 | fr.eval(t, `(() => { const f = window.fetch; let first = `+map[bool]string{true: "true", false: "false"}[refuse]+`; window.__posts = []; window.__errors = []; |
| 56 | addEventListener('unhandledrejection', (e) => window.__errors.push(String(e.reason))); |
| 57 | addEventListener('error', (e) => window.__errors.push(String(e.message))); |
| 58 | window.fetch = async function (u, o) { |
| 59 | if (String(u).endsWith('/updates') && o && o.method === 'POST') { |
| 60 | if (first) { first = false; await new Promise((r) => setTimeout(r, 150)); window.__posts.push(413); return new Response('', { status: 413 }) } |
| 61 | const r = await f.call(this, u, o); window.__posts.push(r.status); return r } |
| 62 | return f.call(this, u, o) }; |
| 63 | window.__log = []; const sheet = document.querySelector('[docs-text]'); |
| 64 | const rec = () => { const has = sheet.textContent.includes('REVIEW_RESYNC_PASTE'); const last = window.__log[window.__log.length - 1]; |
| 65 | if (!last || last.has !== has) window.__log.push({ ms: Math.round(performance.now()), has }) }; |
| 66 | new MutationObserver(rec).observe(sheet, { subtree: true, childList: true, characterData: true }); |
| 67 | const frame = () => { rec(); requestAnimationFrame(frame) }; requestAnimationFrame(frame); |
| 68 | return true })()`, &ok) |
| 69 | // The edit whose save is refused. |
| 70 | fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p:`+map[bool]string{true: "first-child", false: "last-child"}[elsewhere]+`'); const r = document.createRange(); |
| 71 | r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r); |
| 72 | document.querySelector('[docs-text]').focus(); return true })()`, &ok) |
| 73 | fr.rig.Run(chromedp.KeyEvent("x"), chromedp.Sleep(100*time.Millisecond)) |
| 74 | // At once, a paste with a code mark at the end of the last paragraph: |
| 75 | // Mono is cold, so it waits. ProseMirror reads a moved caret on the |
| 76 | // next selectionchange, so the paste goes a moment after the move. |
| 77 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 78 | const p = el.querySelector('p:last-child'); const r = document.createRange(); r.selectNodeContents(p); r.collapse(false); |
| 79 | getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, &ok) |
| 80 | fr.rig.Run(chromedp.Sleep(30 * time.Millisecond)) |
| 81 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); |
| 82 | const d = new DataTransfer(); d.setData('text/html', '<p>REVIEW_RESYNC_PASTE <code>codeword</code></p>'); d.setData('text/plain', 'x'); |
| 83 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`, &ok) |
| 84 | var waiting bool |
| 85 | fr.eval(t, `!!document.querySelector('[docs-text]').inert`, &waiting) |
| 86 | if !waiting { |
| 87 | t.Fatal("the paste did not start a font wait; the check is not testing what it means to") |
| 88 | } |
| 89 | fr.rig.Run(chromedp.Sleep(4 * time.Second)) |
| 90 | var state struct { |
| 91 | Text, Status string |
| 92 | Posts []int |
| 93 | Errors []string |
| 94 | Log []struct { |
| 95 | Ms int `json:"ms"` |
| 96 | Has bool `json:"has"` |
| 97 | } |
| 98 | } |
| 99 | fr.eval(t, `(() => { const s = document.querySelector('[docs-fonts-status]'); return { Text: document.querySelector('[docs-text]').textContent, |
| 100 | Status: s ? (s.getAttribute('data-state') || '') : '', Posts: window.__posts, Errors: window.__errors, Log: window.__log } })()`, &state) |
| 101 | want := 1 |
| 102 | if refuse { |
| 103 | var said string |
| 104 | fr.eval(t, `document.querySelector('[estilo-save-status~="floating"]').getAttribute('data-state') || ''`, &said) |
| 105 | if said != "failed" { |
| 106 | t.Errorf("the save line says %q, want failed", said) |
| 107 | } |
| 108 | } |
| 109 | if n := strings.Count(state.Text, "REVIEW_RESYNC_PASTE"); n != want { |
| 110 | t.Errorf("after the resync the paste is on the sheet %d times, want %d: %q", n, want, state.Text) |
| 111 | } |
| 112 | if state.Status == "unavailable" { |
| 113 | t.Errorf("the font strip says the font was unavailable; it loaded, and the resync took the paste's view away (posts %v)", state.Posts) |
| 114 | } |
| 115 | if len(state.Errors) != 0 { |
| 116 | t.Errorf("errors: %v", state.Errors) |
| 117 | } |
| 118 | seen := 0 |
| 119 | for _, e := range state.Log { |
| 120 | if e.Has { |
| 121 | seen++ |
| 122 | } |
| 123 | } |
| 124 | if want == 1 && (seen != 1 || !state.Log[len(state.Log)-1].Has) { |
| 125 | t.Errorf("the pasted words appeared %d times on the sheet, want once and to stay: %+v", seen, state.Log) |
| 126 | } |
| 127 | structureJSON, err := fr.app.Store().JSON(context.Background(), fr.storeDoc(t, sqid)) |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | if n := strings.Count(structureJSON, "REVIEW_RESYNC_PASTE"); n != want { |
| 132 | t.Errorf("the server holds the paste %d times, want %d", n, want) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // Changes written on top of text the server refused are kept without it |
| 137 | // (feat/replay-while-diverged). Two pastes after the refused words and a |
| 138 | // Backspace over them, none of which waited for a font: their own Yjs |
| 139 | // updates are anchored to the refused words and cannot be carried, so |
| 140 | // they are replayed from their ProseMirror transactions. The pastes land |
| 141 | // where the refused words were, once, on the sheet and on the server; the |
| 142 | // Backspace had nothing left to delete; the refused words are on neither. |
| 143 | // (On fix/carry-replay they were held back and lost; before it they were |
| 144 | // posted and sat pending in the server's log, Claude Fable on #88.) |
| 145 | func TestChangesOnRefusedTextAreKeptWithoutIt(t *testing.T) { |
| 146 | fr := newFontRig(t) |
| 147 | sqid := fr.document(t, "uncarriable", "simple.bin") |
| 148 | fr.open(t, sqid) |
| 149 | fr.editable(t) |
| 150 | var ok bool |
| 151 | // The first save answered 413; the rebuild's fetch of the log held |
| 152 | // 2.5 s, so the changes below are made while diverged; every later |
| 153 | // save counted. |
| 154 | fr.eval(t, `(() => { const f = window.fetch; window.__later = []; |
| 155 | window.fetch = async function (u, o) { |
| 156 | const post = String(u).endsWith('/updates') && o && o.method === 'POST'; |
| 157 | if (post && !window.refused) { await new Promise((r) => setTimeout(r, 150)); window.refused = true; return new Response('', { status: 413 }) } |
| 158 | if (window.refused && !post && String(u).includes('/updates') && !String(u).includes('since=')) await new Promise((r) => setTimeout(r, 2500)); |
| 159 | const r = await f.call(this, u, o); if (post) window.__later.push(r.status); return r }; |
| 160 | return true })()`, &ok) |
| 161 | caretAtEnd := `(() => { const p = document.querySelector('[docs-text] p:last-child'); const r = document.createRange(); |
| 162 | r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r); |
| 163 | document.querySelector('[docs-text]').focus(); return true })()` |
| 164 | pasteText := func(words string) string { |
| 165 | return `(() => { const el = document.querySelector('[docs-text]'); |
| 166 | const d = new DataTransfer(); d.setData('text/html', '` + words + `'); d.setData('text/plain', '` + words + `'); |
| 167 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()` |
| 168 | } |
| 169 | fr.eval(t, caretAtEnd, &ok) |
| 170 | fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("REFUSEDWORDS")) |
| 171 | untilTrue(t, fr, `window.refused === true`) |
| 172 | fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) |
| 173 | fr.eval(t, pasteText("ONTOPOFIT"), &ok) |
| 174 | fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) |
| 175 | fr.eval(t, pasteText("ANDAGAIN"), &ok) |
| 176 | fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) |
| 177 | // Select the refused words and press Backspace. |
| 178 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); |
| 179 | const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); let n; |
| 180 | while ((n = w.nextNode())) { const i = n.data.indexOf('REFUSEDWORDS'); if (i >= 0) { const r = document.createRange(); r.setStart(n, i); r.setEnd(n, i + 12); |
| 181 | getSelection().removeAllRanges(); getSelection().addRange(r); return true } } |
| 182 | return false })()`, &ok) |
| 183 | if !ok { |
| 184 | t.Fatal("the refused words were not on the sheet to select") |
| 185 | } |
| 186 | fr.rig.Run(chromedp.Sleep(50*time.Millisecond), chromedp.KeyEvent("\b")) |
| 187 | fr.rig.Run(chromedp.Sleep(4 * time.Second)) |
| 188 | var text string |
| 189 | fr.eval(t, `document.querySelector('[docs-text]').textContent`, &text) |
| 190 | structureJSON, err := fr.app.Store().JSON(context.Background(), fr.storeDoc(t, sqid)) |
| 191 | if err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | for _, c := range []struct { |
| 195 | words string |
| 196 | n int |
| 197 | }{{"REFUSEDWORDS", 0}, {"ONTOPOFIT", 1}, {"ANDAGAIN", 1}} { |
| 198 | if got := strings.Count(text, c.words); got != c.n { |
| 199 | t.Errorf("the sheet holds %s %d times, want %d: %q", c.words, got, c.n, text) |
| 200 | } |
| 201 | if got := strings.Count(structureJSON, c.words); got != c.n { |
| 202 | t.Errorf("the server holds %s %d times, want %d", c.words, got, c.n) |
| 203 | } |
| 204 | } |
| 205 | sameSheetAndServer(t, fr, sqid) |
| 206 | } |
| 207 | |
| 208 | // untilTrue polls expr in the page until it is true, for up to 10 s. |
| 209 | func untilTrue(t *testing.T, fr *fontRig, expr string) { |
| 210 | t.Helper() |
| 211 | deadline := time.Now().Add(10 * time.Second) |
| 212 | for { |
| 213 | var ok bool |
| 214 | fr.eval(t, "!!("+expr+")", &ok) |
| 215 | if ok { |
| 216 | return |
| 217 | } |
| 218 | if time.Now().After(deadline) { |
| 219 | t.Fatalf("never true within 10s: %s", expr) |
| 220 | } |
| 221 | time.Sleep(20 * time.Millisecond) |
| 222 | } |
| 223 | } |
| 224 | |