//go:build browser package slidestest import ( "strconv" "strings" "testing" "time" "github.com/chromedp/chromedp" ) // Claude Fable's review of #28 at c49ed4e, in the real editor: the edges // of carry.mjs where the page and the server came apart, or a replayed // paste landed in the wrong place. Each test ends with the page and the // server holding the same text. const carryDeck = `[{"op":"set_meta","theme":"paper","title":"Carry"}, {"op":"add_slide","id":"slideone0001","layout":"flow","template":"title-body"}, {"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"Carry"}, {"op":"add_block","slide":"slideone0001","id":"text00000001","type":"text","region":"body","markdown":"hello world\n\nSecond paragraph."}]` // caretJS puts the caret in paragraph i of the text block at offset off // (a number, or -1 for the end). func caretJS(i, off int) string { return `(() => { const p = document.querySelectorAll('[slides-stage] [data-block="text"] p')[` + strconv.Itoa(i) + `]; p.closest('[contenteditable]').focus(); const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT); let n, last = null, left = ` + strconv.Itoa(off) + `; if (left < 0) left = Infinity; const r = document.createRange(); 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 } r.setStart(last, last.data.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()` } func selectWordsJS(words string) string { return `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus(); const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); let n; 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)) + `); getSelection().removeAllRanges(); getSelection().addRange(r); return true } } return false })()` } // pasteHereJS pastes html at the selection ProseMirror already has. func pasteHereJS(html string) string { return `(() => { const el = document.activeElement; const d = new DataTransfer(); d.setData('text/html', ` + strconv.Quote(html) + `); d.setData('text/plain', 'x'); el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()` } const pageParagraphsJS = `[...document.querySelectorAll('[slides-stage] [data-block="text"] p')].map((p) => p.textContent)` // samePageAndServer fails unless the page's text block and the server's // hold the same paragraphs, and returns the page's. func samePageAndServer(t *testing.T, fr *fontRig, sqid string) []string { t.Helper() var page []string fr.eval(t, pageParagraphsJS, &page) server := serverParagraphs(t, fr, sqid) if strings.Join(page, "\n") != strings.Join(server, "\n") { t.Errorf("the page and the server differ after the resync: page %q, server %q", page, server) } return page } // The tab typed "abc", saved, then "x", refused, and Backspaced over "cx": // one delete range of one client, which Yjs applied up to what the rebuilt // document holds — the "c" — and held pending past it. It read as not // taken, nothing was posted, and the page said "ab" while the server kept // "abc" (Fable's finding 1 on #28). func TestABackspaceAcrossSavedAndRefusedWordsReachesTheServer(t *testing.T) { fr := newFontRig(t) sqid := fr.deck(t, "boundary", carryDeck) fr.rig.Run(fr.navigate("/d/" + sqid + "/edit")) fr.editable(t) fr.eval(t, `(() => { const f = window.fetch; window.posts = []; window.refuseNext = false; window.refused = false; window.fetch = async function (u, o) { const post = String(u).endsWith('/updates') && o && o.method === 'POST'; 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 }) } if (window.refused && String(u).includes('since=0')) await new Promise((r) => setTimeout(r, 1500)); const r = await f.call(this, u, o); if (post) window.posts.push(r.status); return r }; return true })()`, nil) fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("abc")) fr.until(t, `window.posts.length >= 1`) fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) fr.eval(t, `window.refuseNext = true`, nil) fr.rig.Run(chromedp.KeyEvent("x")) fr.until(t, `window.refused === true`) fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) var ok bool fr.eval(t, selectWordsJS("cx"), &ok) if !ok { t.Fatalf("no \"cx\" on the stage: %q", fr.stageText(t)) } fr.rig.Run(chromedp.Sleep(50*time.Millisecond), chromedp.KeyEvent("\b")) fr.rig.Run(chromedp.Sleep(5 * time.Second)) var posts []int fr.eval(t, `window.posts`, &posts) t.Logf("posts %v", posts) if page := samePageAndServer(t, fr, sqid); len(page) == 0 || page[0] != "hello worldab" { t.Errorf("the page says %q, want \"hello worldab\"", page) } } // A refused change that repeats a letter beside it makes the two ends of // the rebuilt text's diff overlap; the one-span map clamped that to an // empty span, and the replayed paste landed a letter off (Fable's finding // 2 on #28). Both shapes: an "l" typed into "hell|o" with the paste right // after it, anchored to the refused l; an "l" of "hello" deleted, with the // paste at the paragraph's end. func TestAReplayedPasteLandsWhereItWasMadeBesideARepeatedLetter(t *testing.T) { for _, c := range []struct { name string caret int key string pasteAt int want string }{ {"an l typed into hell|o, the paste right after it", 4, "l", -2, "hellREVIEW_RESYNC_PASTE codewordo world"}, // The deletion was refused, so the server keeps hello whole. {"an l of hello deleted, the paste at the end", 4, "\b", -1, "hello worldREVIEW_RESYNC_PASTE codeword"}, } { t.Run(c.name, func(t *testing.T) { fr := newFontRig(t) sqid := fr.deck(t, "overlap", carryDeck) fr.match.Store("LiberationMono-") fr.slow.Store(int64(3 * time.Second)) fr.rig.Run(fr.navigate("/d/" + sqid + "/edit")) fr.editable(t) fr.eval(t, refuseFirstSaveJS(1500), nil) fr.eval(t, caretJS(0, c.caret), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent(c.key)) if c.pasteAt == -1 { fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40 * time.Millisecond)) } fr.eval(t, pasteHereJS(`

REVIEW_RESYNC_PASTE codeword

`), nil) var waiting string fr.eval(t, `document.querySelector('[slides-fonts-status]').getAttribute('data-state')`, &waiting) if waiting != "loading" { t.Fatalf("the paste did not wait for its font (%q), so this proves nothing", waiting) } fr.until(t, `window.refused === true`) fr.rig.Run(chromedp.Sleep(6 * time.Second)) want := c.want if page := samePageAndServer(t, fr, sqid); len(page) == 0 || page[0] != want { t.Errorf("the replayed paste is not where it was made: page %q, want %q first", page, want) } }) } } // Once one change is held back — written on the refused text, with no // transaction to replay — every change after it under the same client id // was held back too, wherever it was made: Yjs integrates a client's // structs in clock order (Fable's finding 3 on #28). The keeper gives the // document a fresh id after every change while diverged. In both orders // the paste made in a clean spot is kept, on the page and the server; the // keystroke on the refused text is the one change lost. func TestAChangeInACleanSpotIsNotLostWithOneOnTheRefusedText(t *testing.T) { for _, order := range []string{"on the refused text, then elsewhere", "elsewhere, then on the refused text"} { t.Run(order, func(t *testing.T) { fr := newFontRig(t) sqid := fr.deck(t, "contiguity", carryDeck) fr.rig.Run(fr.navigate("/d/" + sqid + "/edit")) fr.editable(t) fr.eval(t, refuseFirstSaveJS(2500), nil) fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("x")) fr.until(t, `window.refused === true`) fr.rig.Run(chromedp.Sleep(50 * time.Millisecond)) onRefused := func() { fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(60*time.Millisecond)) } elsewhere := func() { fr.eval(t, caretJS(1, 0), nil) fr.rig.Run(chromedp.Sleep(40 * time.Millisecond)) fr.eval(t, pasteHereJS(`CLEANPASTE`), nil) fr.rig.Run(chromedp.Sleep(60 * time.Millisecond)) } if strings.HasPrefix(order, "on") { onRefused() elsewhere() } else { elsewhere() onRefused() } fr.rig.Run(chromedp.Sleep(5 * time.Second)) page := samePageAndServer(t, fr, sqid) if len(page) < 2 || page[1] != "CLEANPASTESecond paragraph." { t.Errorf("the paste made in a clean spot was lost: page %q", page) } }) } } // An undo made while diverged stays undone (Claude Fable's P1 on #29). The // undo is the undo manager's Yjs change; the "a" it took back, typed on the // refused text, is a change the resync replays under new ids, which the // undo's delete cannot reach, so the "a" came back on the page and was // posted — with a "b" typed after, "ab" where the person wrote "b". The // keeper now marks what the undo took back and leaves it out; a redo // brings back the change it was undoing, which the resync replays. func TestAnUndoWhileARefusalIsPendingStaysUndone(t *testing.T) { for _, c := range []struct { name, then, want string redo bool }{ {name: "Cmd-Z alone", want: "hello world"}, {name: "Cmd-Z, then b typed on the x", then: "b", want: "hello worldb"}, {name: "Cmd-Z, then Cmd-Shift-Z", redo: true, want: "hello worlda"}, } { t.Run(c.name, func(t *testing.T) { fr := newFontRig(t) sqid := fr.deck(t, "undo", carryDeck) fr.rig.Run(fr.navigate("/d/" + sqid + "/edit")) fr.editable(t) fr.eval(t, refuseFirstSaveJS(3000), nil) fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("x")) fr.until(t, `window.refused === true`) // Past the undo manager's 500 ms capture window, so Cmd-Z takes // back the "a" alone, not the x with it. fr.rig.Run(chromedp.Sleep(700 * time.Millisecond)) fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent("a"), chromedp.Sleep(120*time.Millisecond)) fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(200*time.Millisecond)) if c.redo { fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(200*time.Millisecond)) } if c.then != "" { fr.eval(t, caretJS(0, -1), nil) fr.rig.Run(chromedp.Sleep(40*time.Millisecond), chromedp.KeyEvent(c.then), chromedp.Sleep(120*time.Millisecond)) } fr.rig.Run(chromedp.Sleep(6 * time.Second)) if page := samePageAndServer(t, fr, sqid); len(page) == 0 || page[0] != c.want { t.Errorf("after the resync the page reads %q, want %q first", page, c.want) } }) } }