//go:build browser package mapatest import ( "context" "encoding/json" "fmt" "runtime" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/cdproto/page" "github.com/chromedp/chromedp" "amadan.net/oficina/mapa/internal/mapa" ) // The page editor in a real Chromium (level-up spec §6, §7): L5's // mount, and L9's saving end to end, through the real server. The // saver's own logic, case by case, is editor/saver.test.mjs. // mod is ProseMirror's Mod key in this browser: ⌘ on a Mac, else Ctrl. func mod() chromedp.KeyOption { if runtime.GOOS == "darwin" { return chromedp.KeyModifiers(chromedp.ModifierMeta) } return chromedp.KeyModifiers(chromedp.ModifierCtrl) } // mounted waits for the editor on the page. const mounted = `article[mapa-body].ProseMirror[contenteditable="true"]` // caretAt puts the caret at the end of the page's nth top-level block. func caretAt(block int) chromedp.Action[chromedp.Void] { return chromedp.Evaluate[chromedp.Void](`(function (n) { var view = mapaEditor.view, state = view.state, pos = 0; view.focus(); for (var i = 0; i < n; i++) pos += state.doc.child(i).nodeSize; pos += state.doc.child(n).nodeSize - 1; var Selection = state.selection.constructor; var near = Selection.near(state.doc.resolve(pos), -1); view.dispatch(state.tr.setSelection(near)); })(` + string(rune('0'+block)) + `)`) } // typed is the page's Markdown as the editor would save it now. func typed(t *testing.T, rig *harness.Rig) string { t.Helper() return read(t, rig, chromedp.Evaluate[string]( `mapaEditor.saver.deps.editor.current()`)) } // eventually polls ok for up to ten seconds. func eventually(t *testing.T, what string, ok func() bool) { t.Helper() for deadline := time.Now().Add(10 * time.Second); ; { if ok() { return } if time.Now().After(deadline) { t.Fatalf("never: %s", what) } time.Sleep(100 * time.Millisecond) } } // arrive waits for the browser to be at path. func arrive(t *testing.T, rig *harness.Rig, path string) { t.Helper() eventually(t, "at "+path, func() bool { return read(t, rig, chromedp.Location()) == rig.Origin+path }) drive(t, rig, chromedp.WaitReady("body")) } // current is a page's current revision and body, as Ana reads it. func current(t *testing.T, store *mapa.Store, pageID int64) (int64, string) { t.Helper() ctx := context.Background() viewer, _ := store.Viewer(ctx, Ana, nil) history, err := store.History(ctx, viewer, pageID, 0) if err != nil || len(history.Versions) == 0 { t.Fatalf("history: %v", err) } revision := history.Versions[0].Revision chosen, err := store.ChooseVersion(ctx, viewer, pageID, revision) if err != nil { t.Fatal(err) } return revision, chosen.Record.Body } // draftOf is Ana's draft on a page, if she has one. func draftOf(t *testing.T, store *mapa.Store, pageID int64) (mapa.DraftView, bool) { t.Helper() ctx := context.Background() viewer, _ := store.Viewer(ctx, Ana, nil) draft, found, err := store.OwnDraft(ctx, viewer, mapa.DraftKey{PageID: pageID}) if err != nil { t.Fatal(err) } return draft, found } // teamPage is a page Bo wrote, opened in Ana's editor. func teamPage(t *testing.T, rig *harness.Rig, store *mapa.Store, body string) mapa.Page { t.Helper() page, err := store.CreateTeamPage(context.Background(), Bo, "Plan "+strings.ReplaceAll(t.Name(), "/", " "), body) if err != nil { t.Fatal(err) } drive(t, rig, scripts(true), chromedp.EmulateViewport(1440, 900), chromedp.Navigate(rig.Origin+mapa.PagePath(page)), chromedp.WaitVisible(mounted)) return page } func TestL9AutosaveWritesTheDraftAndSaveCommits(t *testing.T) { rig, store := browserRig(t, 0) page := teamPage(t, rig, store, "One.\n\nTwo.") drive(t, rig, caretAt(0), chromedp.KeyEvent(" Ana.")) eventually(t, "a draft", func() bool { _, found := draftOf(t, store, page.ID) return found }) if revision, _ := current(t, store, page.ID); revision != page.Revision { t.Fatal("autosave wrote the page") } drive(t, rig, chromedp.KeyEvent("s", mod())) eventually(t, "the commit", func() bool { _, body := current(t, store, page.ID) _, found := draftOf(t, store, page.ID) return body == "One. Ana.\n\nTwo." && !found }) } func TestL9LeavingInsideMapaCommitsFirst(t *testing.T) { rig, store := browserRig(t, 0) page := teamPage(t, rig, store, "One.") drive(t, rig, caretAt(0), chromedp.KeyEvent(" Left."), chromedp.Click(`[mapa-side] a[href="/pages"]`)) arrive(t, rig, "/pages") if _, body := current(t, store, page.ID); body != "One. Left." { t.Fatalf("leaving did not commit: %q", body) } } func TestL9ClosingTheTabCommitsWhatThisTabTyped(t *testing.T) { rig, store := browserRig(t, 0) page := teamPage(t, rig, store, "One.") drive(t, rig, caretAt(0), chromedp.KeyEvent(" Saved.")) eventually(t, "a draft", func() bool { _, found := draftOf(t, store, page.ID) return found }) // A reload is a close as far as the page can tell: it commits. The // page it loads settles which draft is this tab's, and closing that // one commits what is not sent yet. drive(t, rig, chromedp.Reload(), chromedp.WaitVisible(mounted)) // The reload's own commit and the page it loads race; the page asks // again until the draft it shows is settled (build note 38). read(t, rig, chromedp.Poll[bool](`mapaEditor.saver.closed === false`)) drive(t, rig, caretAt(0), chromedp.KeyEvent(" Unsent."), chromedp.Navigate(rig.Origin+"/pages")) eventually(t, "the closing commit", func() bool { _, body := current(t, store, page.ID) return body == "One. Saved. Unsent." }) } func TestL9AnOfferedDraftIsNeverCommittedByLeaving(t *testing.T) { rig, store := browserRig(t, 0) ctx := context.Background() page, err := store.CreateTeamPage(ctx, Bo, "Offered", "One.") if err != nil { t.Fatal(err) } viewer, _ := store.Viewer(ctx, Ana, nil) saved, err := store.Autosave(ctx, viewer, mapa.DraftKey{PageID: page.ID}, mapa.DraftWrite{Base: page.Revision, Body: "From yesterday."}) if err != nil { t.Fatal(err) } drive(t, rig, scripts(true), chromedp.EmulateViewport(1440, 900), chromedp.Navigate(rig.Origin+mapa.PagePath(page)), chromedp.WaitVisible(mounted), chromedp.Click(`[mapa-side] a[href="/pages"]`)) arrive(t, rig, "/pages") drive(t, rig, chromedp.Navigate(rig.Origin+mapa.PagePath(page)), chromedp.WaitVisible(mounted), chromedp.Navigate(rig.Origin+"/pages"), chromedp.Sleep(500*time.Millisecond)) draft, found := draftOf(t, store, page.ID) revision, _ := current(t, store, page.ID) if !found || draft.Version != saved.Version || revision != page.Revision { t.Fatal("an offered draft was written or committed") } } // L7: mounting the editor and leaving it without typing writes nothing, // and neither does opening New scratch page and leaving it. func TestL7MountingAndLeavingWritesNothing(t *testing.T) { rig, store := browserRig(t, 0) page := teamPage(t, rig, store, "One.") drive(t, rig, chromedp.Click(`[mapa-side] a[href="/pages"]`)) arrive(t, rig, "/pages") drive(t, rig, chromedp.Navigate(rig.Origin+mapa.PagePath(page)), chromedp.WaitVisible(mounted), chromedp.Navigate(rig.Origin+"/scratch/new"), chromedp.WaitVisible(mounted), chromedp.Navigate(rig.Origin+"/scratch"), chromedp.WaitVisible("main"), chromedp.Sleep(300*time.Millisecond)) revision, _ := current(t, store, page.ID) if _, found := draftOf(t, store, page.ID); found || revision != page.Revision { t.Fatal("mounting and leaving wrote the page or a draft") } scratch := read(t, rig, chromedp.Evaluate[int]( `document.querySelectorAll('main a[href^="/p/"]').length`)) if scratch != 0 { t.Fatalf("opening New scratch page made %d pages", scratch) } } func TestL9ACleanRebaseAppliesTheTeammatesBlockAndKeepsTheCaret( t *testing.T) { rig, store := browserRig(t, 0) page := teamPage(t, rig, store, "One.\n\nTwo.") if _, err := store.Commit(context.Background(), Bo, page.ID, page.Revision, "One.\n\nTwo, as Bo has it."); err != nil { t.Fatal(err) } theirs, _ := current(t, store, page.ID) drive(t, rig, caretAt(0), chromedp.KeyEvent(" Ana."), caretAt(1)) merged := "One. Ana.\n\nTwo, as Bo has it." eventually(t, "the merge applied and the base moved", func() bool { draft, found := draftOf(t, store, page.ID) return found && draft.BaseRevision == theirs && draft.Body == merged }) if got := typed(t, rig); got != merged { t.Fatalf("the editor holds %q", got) } // The caret is still at the end of the teammate's block. drive(t, rig, chromedp.KeyEvent(" Ana again."), chromedp.KeyEvent("s", mod())) eventually(t, "a plain commit with M's bytes", func() bool { _, body := current(t, store, page.ID) return body == merged+" Ana again." }) } func TestL9TheInlineChoiceCommitsYours(t *testing.T) { rig, store := browserRig(t, 0) page := teamPage(t, rig, store, "One.\n\nTwo.") if _, err := store.Commit(context.Background(), Bo, page.ID, page.Revision, "One, as Bo has it.\n\nTwo."); err != nil { t.Fatal(err) } drive(t, rig, caretAt(0), chromedp.KeyEvent(" Ana."), chromedp.WaitVisible(`[mapa-hunk-choice]`)) // The block is locked until chosen; the rest stays editable. drive(t, rig, caretAt(0), chromedp.KeyEvent("X"), caretAt(1), chromedp.KeyEvent(" Free.")) if got := typed(t, rig); got != "One. Ana.\n\nTwo. Free." { t.Fatalf("the editor holds %q", got) } drive(t, rig, chromedp.Sleep(1500*time.Millisecond), chromedp.Click(`[mapa-hunk-choice] button[data-choice="mine"]`)) eventually(t, "Resolve's commit", func() bool { _, body := current(t, store, page.ID) return body == "One. Ana.\n\nTwo. Free." }) } func TestL9TheFirstScratchCommitMakesOnePage(t *testing.T) { rig, store := browserRig(t, 0) drive(t, rig, scripts(true), chromedp.Navigate(rig.Origin+"/scratch/new"), chromedp.WaitVisible(mounted), caretAt(0), chromedp.KeyEvent("Hello")) var path string eventually(t, "the page's address", func() bool { path = strings.TrimPrefix(read(t, rig, chromedp.Location()), rig.Origin) return strings.HasPrefix(path, "/p/") }) pageID, _, err := store.RowID(context.Background(), strings.TrimPrefix(path, "/p/")) if err != nil { t.Fatal(err) } drive(t, rig, chromedp.KeyEvent(" again")) eventually(t, "a draft on the new page", func() bool { draft, found := draftOf(t, store, pageID) return found && draft.Body == "Hello again" }) drive(t, rig, chromedp.Navigate(rig.Origin+"/scratch"), chromedp.WaitVisible("main")) links := read(t, rig, chromedp.Evaluate[int]( `document.querySelectorAll('main a[href^="/p/"]').length`)) if links != 1 { t.Fatalf("%d scratch pages", links) } } // L5 (spec §7): mounting moves no block, from first paint through // mount, light and dark, at three widths, with and without a draft. // The boxes the server drew are read from the same page with scripts // off; with them on, the boxes after the mount must be the same, and no // layout-shift entry may be recorded from the start of the load. The // time from parsing's end to the mount is logged; past 1s fails. // Chromium only here; WebKit is checked by hand (build note 37). func TestL5TheEditorMountsWithoutAShift(t *testing.T) { rig, store := browserRig(t, 0) ctx := context.Background() page, err := store.CreateTeamPage(ctx, Bo, "Pilot", shiftBody) if err != nil { t.Fatal(err) } viewer, _ := store.Viewer(ctx, Ana, nil) drive(t, rig, onNewDocument(shiftRecorder)) for _, draft := range []bool{false, true} { if draft { write := mapa.DraftWrite{Base: page.Revision, Body: shiftBody + "\n\nMine."} if _, err := store.Autosave(ctx, viewer, mapa.DraftKey{PageID: page.ID}, write); err != nil { t.Fatal(err) } } for _, dark := range []bool{false, true} { for _, width := range []int64{1440, 1000, 390} { noShift(t, rig, mapa.PagePath(page), width, dark, draft) } } } // An unwritten day: one empty paragraph, the body below it empty. for _, width := range []int64{1440, 1000, 390} { noShift(t, rig, "/d/2026-11-02", width, false, false) } } const shiftBody = "# Pilot\n\nMet [[Pilot]] and [[Not yet]] on " + "[[2026-11-12]], with *em*, **strong** and `code`. ^intro\n\n" + "- one\n - nested [[Pilot]]\n- [ ] a task\n- [x] done\n\n" + "1. first\n2. second\n\n> quoted\n> twice\n\n```go\ncode()\n```" + "\n\n---\n\nEnds on a chip [[Pilot]]" func onNewDocument(source string) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: source}) return err }) } func colorScheme(dark bool) chromedp.Action[chromedp.Void] { scheme := "light" if dark { scheme = "dark" } return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { features := []*emulation.MediaFeature{ {Name: "prefers-color-scheme", Value: scheme}} _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: features}) return err }) } // shiftRecorder keeps every layout shift from the start of the load. const shiftRecorder = `(function () { window.__shifts = []; try { new PerformanceObserver(function (list) { list.getEntries().forEach(function (entry) { __shifts.push(entry.value); }); }).observe({ type: "layout-shift", buffered: true }); } catch (error) {} })()` // boxes is every block of the page's body, with its box; and the body // and the foot themselves, which fill the column to take a click below // the text (build note 84). const boxes = `JSON.stringify(Array.prototype.map.call( document.querySelectorAll("article[mapa-body], footer[mapa-foot-refs], " + "article[mapa-body] :is(p, h2, h3, h4, h5, h6, li, pre, hr, " + "blockquote, ul, ol)"), function (block) { var box = block.getBoundingClientRect(); return [block.nodeName, box.left, box.top, box.width, box.height].join(" "); }))` // mountReading is the time from parsing's end to the mount, and the // shifts recorded. const mountReading = `JSON.stringify({ mount: performance.getEntriesByName("mapa-mounted")[0].startTime - performance.getEntriesByType("navigation")[0].domInteractive, shifts: window.__shifts || [] })` func noShift(t *testing.T, rig *harness.Rig, path string, width int64, dark, draft bool) { t.Helper() load := func(live bool) string { drive(t, rig, scripts(live), chromedp.EmulateViewport(width, 900), colorScheme(dark), chromedp.Navigate(rig.Origin+path), chromedp.WaitVisible("article[mapa-body] p")) if live { drive(t, rig, chromedp.WaitVisible(mounted)) } return read(t, rig, chromedp.Evaluate[string](boxes)) } before, after := load(false), load(true) var report struct { Mount float64 Shifts []float64 } raw := read(t, rig, chromedp.Evaluate[string](mountReading)) if err := json.Unmarshal([]byte(raw), &report); err != nil { t.Fatal(err) } name := fmt.Sprintf("%dpx %s", width, map[bool]string{false: "light", true: "dark"}[dark]) + map[bool]string{false: "", true: ", draft"}[draft] t.Logf("%s: parsed to mounted %.1fms", name, report.Mount) if report.Mount > 1000 { t.Errorf("%s: mounting took %.1fms", name, report.Mount) } if before != after { t.Errorf("%s: blocks moved:\nbefore %s\nafter %s", name, before, after) } if len(report.Shifts) > 0 { t.Errorf("%s: layout shifts %v", name, report.Shifts) } }