oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package mapatest
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "runtime"
10 "strings"
11 "testing"
12 "time"
13
14 "amadan.net/rastrillo/rastrillo/harness"
15 "github.com/chromedp/cdproto/cdp"
16 "github.com/chromedp/cdproto/emulation"
17 "github.com/chromedp/cdproto/page"
18 "github.com/chromedp/chromedp"
19
20 "amadan.net/oficina/mapa/internal/mapa"
21)
22
23// The page editor in a real Chromium (level-up spec §6, §7): L5's
24// mount, and L9's saving end to end, through the real server. The
25// saver's own logic, case by case, is editor/saver.test.mjs.
26
27// mod is ProseMirror's Mod key in this browser: ⌘ on a Mac, else Ctrl.
28func mod() chromedp.KeyOption {
29 if runtime.GOOS == "darwin" {
30 return chromedp.KeyModifiers(chromedp.ModifierMeta)
31 }
32 return chromedp.KeyModifiers(chromedp.ModifierCtrl)
33}
34
35// mounted waits for the editor on the page.
36const mounted = `article[mapa-body].ProseMirror[contenteditable="true"]`
37
38// caretAt puts the caret at the end of the page's nth top-level block.
39func caretAt(block int) chromedp.Action[chromedp.Void] {
40 return chromedp.Evaluate[chromedp.Void](`(function (n) {
41 var view = mapaEditor.view, state = view.state, pos = 0;
42 view.focus();
43 for (var i = 0; i < n; i++) pos += state.doc.child(i).nodeSize;
44 pos += state.doc.child(n).nodeSize - 1;
45 var Selection = state.selection.constructor;
46 var near = Selection.near(state.doc.resolve(pos), -1);
47 view.dispatch(state.tr.setSelection(near));
48})(` + string(rune('0'+block)) + `)`)
49}
50
51// typed is the page's Markdown as the editor would save it now.
52func typed(t *testing.T, rig *harness.Rig) string {
53 t.Helper()
54 return read(t, rig, chromedp.Evaluate[string](
55 `mapaEditor.saver.deps.editor.current()`))
56}
57
58// eventually polls ok for up to ten seconds.
59func eventually(t *testing.T, what string, ok func() bool) {
60 t.Helper()
61 for deadline := time.Now().Add(10 * time.Second); ; {
62 if ok() {
63 return
64 }
65 if time.Now().After(deadline) {
66 t.Fatalf("never: %s", what)
67 }
68 time.Sleep(100 * time.Millisecond)
69 }
70}
71
72// arrive waits for the browser to be at path.
73func arrive(t *testing.T, rig *harness.Rig, path string) {
74 t.Helper()
75 eventually(t, "at "+path, func() bool {
76 return read(t, rig, chromedp.Location()) == rig.Origin+path
77 })
78 drive(t, rig, chromedp.WaitReady("body"))
79}
80
81// current is a page's current revision and body, as Ana reads it.
82func current(t *testing.T, store *mapa.Store, pageID int64) (int64,
83 string) {
84 t.Helper()
85 ctx := context.Background()
86 viewer, _ := store.Viewer(ctx, Ana, nil)
87 history, err := store.History(ctx, viewer, pageID, 0)
88 if err != nil || len(history.Versions) == 0 {
89 t.Fatalf("history: %v", err)
90 }
91 revision := history.Versions[0].Revision
92 chosen, err := store.ChooseVersion(ctx, viewer, pageID, revision)
93 if err != nil {
94 t.Fatal(err)
95 }
96 return revision, chosen.Record.Body
97}
98
99// draftOf is Ana's draft on a page, if she has one.
100func draftOf(t *testing.T, store *mapa.Store, pageID int64) (mapa.DraftView,
101 bool) {
102 t.Helper()
103 ctx := context.Background()
104 viewer, _ := store.Viewer(ctx, Ana, nil)
105 draft, found, err := store.OwnDraft(ctx, viewer,
106 mapa.DraftKey{PageID: pageID})
107 if err != nil {
108 t.Fatal(err)
109 }
110 return draft, found
111}
112
113// teamPage is a page Bo wrote, opened in Ana's editor.
114func teamPage(t *testing.T, rig *harness.Rig, store *mapa.Store,
115 body string) mapa.Page {
116 t.Helper()
117 page, err := store.CreateTeamPage(context.Background(), Bo,
118 "Plan "+strings.ReplaceAll(t.Name(), "/", " "), body)
119 if err != nil {
120 t.Fatal(err)
121 }
122 drive(t, rig, scripts(true), chromedp.EmulateViewport(1440, 900),
123 chromedp.Navigate(rig.Origin+mapa.PagePath(page)),
124 chromedp.WaitVisible(mounted))
125 return page
126}
127
128func TestL9AutosaveWritesTheDraftAndSaveCommits(t *testing.T) {
129 rig, store := browserRig(t, 0)
130 page := teamPage(t, rig, store, "One.\n\nTwo.")
131 drive(t, rig, caretAt(0), chromedp.KeyEvent(" Ana."))
132 eventually(t, "a draft", func() bool {
133 _, found := draftOf(t, store, page.ID)
134 return found
135 })
136 if revision, _ := current(t, store, page.ID); revision != page.Revision {
137 t.Fatal("autosave wrote the page")
138 }
139 drive(t, rig, chromedp.KeyEvent("s", mod()))
140 eventually(t, "the commit", func() bool {
141 _, body := current(t, store, page.ID)
142 _, found := draftOf(t, store, page.ID)
143 return body == "One. Ana.\n\nTwo." && !found
144 })
145}
146
147func TestL9LeavingInsideMapaCommitsFirst(t *testing.T) {
148 rig, store := browserRig(t, 0)
149 page := teamPage(t, rig, store, "One.")
150 drive(t, rig, caretAt(0), chromedp.KeyEvent(" Left."),
151 chromedp.Click(`[mapa-side] a[href="/pages"]`))
152 arrive(t, rig, "/pages")
153 if _, body := current(t, store, page.ID); body != "One. Left." {
154 t.Fatalf("leaving did not commit: %q", body)
155 }
156}
157
158func TestL9ClosingTheTabCommitsWhatThisTabTyped(t *testing.T) {
159 rig, store := browserRig(t, 0)
160 page := teamPage(t, rig, store, "One.")
161 drive(t, rig, caretAt(0), chromedp.KeyEvent(" Saved."))
162 eventually(t, "a draft", func() bool {
163 _, found := draftOf(t, store, page.ID)
164 return found
165 })
166 // A reload is a close as far as the page can tell: it commits. The
167 // page it loads settles which draft is this tab's, and closing that
168 // one commits what is not sent yet.
169 drive(t, rig, chromedp.Reload(), chromedp.WaitVisible(mounted))
170 // The reload's own commit and the page it loads race; the page asks
171 // again until the draft it shows is settled (build note 38).
172 read(t, rig, chromedp.Poll[bool](`mapaEditor.saver.closed === false`))
173 drive(t, rig, caretAt(0), chromedp.KeyEvent(" Unsent."),
174 chromedp.Navigate(rig.Origin+"/pages"))
175 eventually(t, "the closing commit", func() bool {
176 _, body := current(t, store, page.ID)
177 return body == "One. Saved. Unsent."
178 })
179}
180
181func TestL9AnOfferedDraftIsNeverCommittedByLeaving(t *testing.T) {
182 rig, store := browserRig(t, 0)
183 ctx := context.Background()
184 page, err := store.CreateTeamPage(ctx, Bo, "Offered", "One.")
185 if err != nil {
186 t.Fatal(err)
187 }
188 viewer, _ := store.Viewer(ctx, Ana, nil)
189 saved, err := store.Autosave(ctx, viewer, mapa.DraftKey{PageID: page.ID},
190 mapa.DraftWrite{Base: page.Revision, Body: "From yesterday."})
191 if err != nil {
192 t.Fatal(err)
193 }
194 drive(t, rig, scripts(true), chromedp.EmulateViewport(1440, 900),
195 chromedp.Navigate(rig.Origin+mapa.PagePath(page)),
196 chromedp.WaitVisible(mounted),
197 chromedp.Click(`[mapa-side] a[href="/pages"]`))
198 arrive(t, rig, "/pages")
199 drive(t, rig, chromedp.Navigate(rig.Origin+mapa.PagePath(page)),
200 chromedp.WaitVisible(mounted),
201 chromedp.Navigate(rig.Origin+"/pages"),
202 chromedp.Sleep(500*time.Millisecond))
203 draft, found := draftOf(t, store, page.ID)
204 revision, _ := current(t, store, page.ID)
205 if !found || draft.Version != saved.Version ||
206 revision != page.Revision {
207 t.Fatal("an offered draft was written or committed")
208 }
209}
210
211// L7: mounting the editor and leaving it without typing writes nothing,
212// and neither does opening New scratch page and leaving it.
213func TestL7MountingAndLeavingWritesNothing(t *testing.T) {
214 rig, store := browserRig(t, 0)
215 page := teamPage(t, rig, store, "One.")
216 drive(t, rig, chromedp.Click(`[mapa-side] a[href="/pages"]`))
217 arrive(t, rig, "/pages")
218 drive(t, rig, chromedp.Navigate(rig.Origin+mapa.PagePath(page)),
219 chromedp.WaitVisible(mounted),
220 chromedp.Navigate(rig.Origin+"/scratch/new"),
221 chromedp.WaitVisible(mounted),
222 chromedp.Navigate(rig.Origin+"/scratch"),
223 chromedp.WaitVisible("main"), chromedp.Sleep(300*time.Millisecond))
224 revision, _ := current(t, store, page.ID)
225 if _, found := draftOf(t, store, page.ID); found ||
226 revision != page.Revision {
227 t.Fatal("mounting and leaving wrote the page or a draft")
228 }
229 scratch := read(t, rig, chromedp.Evaluate[int](
230 `document.querySelectorAll('main a[href^="/p/"]').length`))
231 if scratch != 0 {
232 t.Fatalf("opening New scratch page made %d pages", scratch)
233 }
234}
235
236func TestL9ACleanRebaseAppliesTheTeammatesBlockAndKeepsTheCaret(
237 t *testing.T) {
238 rig, store := browserRig(t, 0)
239 page := teamPage(t, rig, store, "One.\n\nTwo.")
240 if _, err := store.Commit(context.Background(), Bo, page.ID,
241 page.Revision, "One.\n\nTwo, as Bo has it."); err != nil {
242 t.Fatal(err)
243 }
244 theirs, _ := current(t, store, page.ID)
245 drive(t, rig, caretAt(0), chromedp.KeyEvent(" Ana."), caretAt(1))
246 merged := "One. Ana.\n\nTwo, as Bo has it."
247 eventually(t, "the merge applied and the base moved", func() bool {
248 draft, found := draftOf(t, store, page.ID)
249 return found && draft.BaseRevision == theirs && draft.Body == merged
250 })
251 if got := typed(t, rig); got != merged {
252 t.Fatalf("the editor holds %q", got)
253 }
254 // The caret is still at the end of the teammate's block.
255 drive(t, rig, chromedp.KeyEvent(" Ana again."),
256 chromedp.KeyEvent("s", mod()))
257 eventually(t, "a plain commit with M's bytes", func() bool {
258 _, body := current(t, store, page.ID)
259 return body == merged+" Ana again."
260 })
261}
262
263func TestL9TheInlineChoiceCommitsYours(t *testing.T) {
264 rig, store := browserRig(t, 0)
265 page := teamPage(t, rig, store, "One.\n\nTwo.")
266 if _, err := store.Commit(context.Background(), Bo, page.ID,
267 page.Revision, "One, as Bo has it.\n\nTwo."); err != nil {
268 t.Fatal(err)
269 }
270 drive(t, rig, caretAt(0), chromedp.KeyEvent(" Ana."),
271 chromedp.WaitVisible(`[mapa-hunk-choice]`))
272 // The block is locked until chosen; the rest stays editable.
273 drive(t, rig, caretAt(0), chromedp.KeyEvent("X"), caretAt(1),
274 chromedp.KeyEvent(" Free."))
275 if got := typed(t, rig); got != "One. Ana.\n\nTwo. Free." {
276 t.Fatalf("the editor holds %q", got)
277 }
278 drive(t, rig, chromedp.Sleep(1500*time.Millisecond),
279 chromedp.Click(`[mapa-hunk-choice] button[data-choice="mine"]`))
280 eventually(t, "Resolve's commit", func() bool {
281 _, body := current(t, store, page.ID)
282 return body == "One. Ana.\n\nTwo. Free."
283 })
284}
285
286func TestL9TheFirstScratchCommitMakesOnePage(t *testing.T) {
287 rig, store := browserRig(t, 0)
288 drive(t, rig, scripts(true),
289 chromedp.Navigate(rig.Origin+"/scratch/new"),
290 chromedp.WaitVisible(mounted), caretAt(0),
291 chromedp.KeyEvent("Hello"))
292 var path string
293 eventually(t, "the page's address", func() bool {
294 path = strings.TrimPrefix(read(t, rig, chromedp.Location()),
295 rig.Origin)
296 return strings.HasPrefix(path, "/p/")
297 })
298 pageID, _, err := store.RowID(context.Background(),
299 strings.TrimPrefix(path, "/p/"))
300 if err != nil {
301 t.Fatal(err)
302 }
303 drive(t, rig, chromedp.KeyEvent(" again"))
304 eventually(t, "a draft on the new page", func() bool {
305 draft, found := draftOf(t, store, pageID)
306 return found && draft.Body == "Hello again"
307 })
308 drive(t, rig, chromedp.Navigate(rig.Origin+"/scratch"),
309 chromedp.WaitVisible("main"))
310 links := read(t, rig, chromedp.Evaluate[int](
311 `document.querySelectorAll('main a[href^="/p/"]').length`))
312 if links != 1 {
313 t.Fatalf("%d scratch pages", links)
314 }
315}
316
317// L5 (spec §7): mounting moves no block, from first paint through
318// mount, light and dark, at three widths, with and without a draft.
319// The boxes the server drew are read from the same page with scripts
320// off; with them on, the boxes after the mount must be the same, and no
321// layout-shift entry may be recorded from the start of the load. The
322// time from parsing's end to the mount is logged; past 1s fails.
323// Chromium only here; WebKit is checked by hand (build note 37).
324func TestL5TheEditorMountsWithoutAShift(t *testing.T) {
325 rig, store := browserRig(t, 0)
326 ctx := context.Background()
327 page, err := store.CreateTeamPage(ctx, Bo, "Pilot", shiftBody)
328 if err != nil {
329 t.Fatal(err)
330 }
331 viewer, _ := store.Viewer(ctx, Ana, nil)
332 drive(t, rig, onNewDocument(shiftRecorder))
333 for _, draft := range []bool{false, true} {
334 if draft {
335 write := mapa.DraftWrite{Base: page.Revision,
336 Body: shiftBody + "\n\nMine."}
337 if _, err := store.Autosave(ctx, viewer,
338 mapa.DraftKey{PageID: page.ID}, write); err != nil {
339 t.Fatal(err)
340 }
341 }
342 for _, dark := range []bool{false, true} {
343 for _, width := range []int64{1440, 1000, 390} {
344 noShift(t, rig, mapa.PagePath(page), width, dark, draft)
345 }
346 }
347 }
348 // An unwritten day: one empty paragraph, the body below it empty.
349 for _, width := range []int64{1440, 1000, 390} {
350 noShift(t, rig, "/d/2026-11-02", width, false, false)
351 }
352}
353
354const shiftBody = "# Pilot\n\nMet [[Pilot]] and [[Not yet]] on " +
355 "[[2026-11-12]], with *em*, **strong** and `code`. ^intro\n\n" +
356 "- one\n - nested [[Pilot]]\n- [ ] a task\n- [x] done\n\n" +
357 "1. first\n2. second\n\n> quoted\n> twice\n\n```go\ncode()\n```" +
358 "\n\n---\n\nEnds on a chip [[Pilot]]"
359
360func onNewDocument(source string) chromedp.Action[chromedp.Void] {
361 return chromedp.Func(func(ctx context.Context,
362 target *chromedp.Target) error {
363 _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument,
364 page.AddScriptToEvaluateOnNewDocumentParams{Source: source})
365 return err
366 })
367}
368
369func colorScheme(dark bool) chromedp.Action[chromedp.Void] {
370 scheme := "light"
371 if dark {
372 scheme = "dark"
373 }
374 return chromedp.Func(func(ctx context.Context,
375 target *chromedp.Target) error {
376 features := []*emulation.MediaFeature{
377 {Name: "prefers-color-scheme", Value: scheme}}
378 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia,
379 emulation.SetEmulatedMediaParams{Features: features})
380 return err
381 })
382}
383
384// shiftRecorder keeps every layout shift from the start of the load.
385const shiftRecorder = `(function () {
386 window.__shifts = [];
387 try {
388 new PerformanceObserver(function (list) {
389 list.getEntries().forEach(function (entry) {
390 __shifts.push(entry.value);
391 });
392 }).observe({ type: "layout-shift", buffered: true });
393 } catch (error) {}
394})()`
395
396// boxes is every block of the page's body, with its box; and the body
397// and the foot themselves, which fill the column to take a click below
398// the text (build note 84).
399const boxes = `JSON.stringify(Array.prototype.map.call(
400 document.querySelectorAll("article[mapa-body], footer[mapa-foot-refs], " +
401 "article[mapa-body] :is(p, h2, h3, h4, h5, h6, li, pre, hr, " +
402 "blockquote, ul, ol)"),
403 function (block) {
404 var box = block.getBoundingClientRect();
405 return [block.nodeName, box.left, box.top, box.width, box.height].join(" ");
406 }))`
407
408// mountReading is the time from parsing's end to the mount, and the
409// shifts recorded.
410const mountReading = `JSON.stringify({
411 mount: performance.getEntriesByName("mapa-mounted")[0].startTime -
412 performance.getEntriesByType("navigation")[0].domInteractive,
413 shifts: window.__shifts || [] })`
414
415func noShift(t *testing.T, rig *harness.Rig, path string, width int64,
416 dark, draft bool) {
417 t.Helper()
418 load := func(live bool) string {
419 drive(t, rig, scripts(live), chromedp.EmulateViewport(width, 900),
420 colorScheme(dark), chromedp.Navigate(rig.Origin+path),
421 chromedp.WaitVisible("article[mapa-body] p"))
422 if live {
423 drive(t, rig, chromedp.WaitVisible(mounted))
424 }
425 return read(t, rig, chromedp.Evaluate[string](boxes))
426 }
427 before, after := load(false), load(true)
428 var report struct {
429 Mount float64
430 Shifts []float64
431 }
432 raw := read(t, rig, chromedp.Evaluate[string](mountReading))
433 if err := json.Unmarshal([]byte(raw), &report); err != nil {
434 t.Fatal(err)
435 }
436 name := fmt.Sprintf("%dpx %s", width,
437 map[bool]string{false: "light", true: "dark"}[dark]) +
438 map[bool]string{false: "", true: ", draft"}[draft]
439 t.Logf("%s: parsed to mounted %.1fms", name, report.Mount)
440 if report.Mount > 1000 {
441 t.Errorf("%s: mounting took %.1fms", name, report.Mount)
442 }
443 if before != after {
444 t.Errorf("%s: blocks moved:\nbefore %s\nafter %s", name, before,
445 after)
446 }
447 if len(report.Shifts) > 0 {
448 t.Errorf("%s: layout shifts %v", name, report.Shifts)
449 }
450}
451