//go:build browser package mapatest import ( "bytes" "context" "encoding/base64" "image" "image/color" "image/png" "io" "os" "path/filepath" "strings" "sync" "testing" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/chromedp" "amadan.net/oficina/mapa/internal/mapa" ) // The images' page gates in a real Chromium (images spec ยง6): L5 with // images, L9 with an upload in flight, L10's walk, and the JPEG that is // scaled down upright before it is sent. // filePicker holds the file inputs the editor opens, so the test can give // them files: the system's picker is not part of the page. const filePicker = `(function () { var click = HTMLInputElement.prototype.click; HTMLInputElement.prototype.click = function () { if (this.hasAttribute("mapa-image-input")) return; return click.call(this); }; })()` // pictureFile writes a PNG of width by height to a file. func pictureFile(t *testing.T, width, height int) string { t.Helper() canvas := image.NewRGBA(image.Rect(0, 0, width, height)) for column := range width { for line := range height { canvas.Set(column, line, color.RGBA{uint8(column), 90, uint8(line), 255}) } } var out bytes.Buffer if err := png.Encode(&out, canvas); err != nil { t.Fatal(err) } path := filepath.Join(t.TempDir(), "picture.png") if err := os.WriteFile(path, out.Bytes(), 0o600); err != nil { t.Fatal(err) } return path } // addImage stores a picture as who's pending image. func addImage(t *testing.T, store *mapa.Store, who string, width, height int) mapa.Image { t.Helper() raw, err := os.ReadFile(pictureFile(t, width, height)) if err != nil { t.Fatal(err) } ctx := context.Background() viewer, _ := store.Viewer(ctx, who, nil) member := viewer.MemberID if member == 0 { if err := store.SetTimeZone(ctx, who, "Europe/Dublin"); err != nil { t.Fatal(err) } viewer, _ = store.Viewer(ctx, who, nil) member = viewer.MemberID } added, err := store.AddImage(ctx, member, bytes.NewReader(raw)) if err != nil { t.Fatal(err) } return added } // choose gives the file input the editor opened a file. func choose(path string) chromedp.Action[chromedp.Void] { return chromedp.Steps(chromedp.WaitReady(`input[mapa-image-input]`), chromedp.SetUploadFiles(`input[mapa-image-input]`, []string{path})) } // heldGets holds every image's bytes until let() is called, so L5 // measures the boxes before a single picture has arrived (Fable M7: on // loopback the pictures arrived before the first measurement, and the // gate passed with width and height removed). type heldGets struct { blobs.Store mutex sync.Mutex gate chan struct{} } func (store *heldGets) hold() { store.mutex.Lock() store.gate = make(chan struct{}) store.mutex.Unlock() } func (store *heldGets) let() { store.mutex.Lock() if store.gate != nil { close(store.gate) store.gate = nil } store.mutex.Unlock() } func (store *heldGets) Get(ctx context.Context, key string) (io.ReadCloser, error) { store.mutex.Lock() gate := store.gate store.mutex.Unlock() if gate != nil { select { case <-gate: case <-ctx.Done(): return nil, ctx.Err() } } return store.Store.Get(ctx, key) } func TestL5ImagesReserveTheirBoxes(t *testing.T) { held := &heldGets{} rig, store := browserRigWith(t, 0, func(inner blobs.Store) blobs.Store { held.Store = inner return held }) t.Cleanup(held.let) ctx := context.Background() top, below := addImage(t, store, Bo, 900, 500), addImage(t, store, Bo, 300, 700) body := "# Pictures\n\n" + top.Markdown("Above the fold") + "\n\n" + strings.Repeat("A paragraph that fills the page. ", 120) + "\n\nBetween " + below.Markdown("below") + " words.\n\n" + "![gone](/i/zz9) and the end." page, err := store.CreateTeamPage(ctx, Bo, "Pictures", body) if err != nil { t.Fatal(err) } drafted := addImage(t, store, Ana, 400, 400) 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: body + "\n\n" + drafted.Markdown("in my draft")} if _, err := store.Autosave(ctx, viewer, mapa.DraftKey{PageID: page.ID}, write); err != nil { t.Fatal(err) } } for _, width := range []int64{1440, 390} { for _, live := range []bool{false, true} { beforeTheBytes(t, rig, held, mapa.PagePath(page), width, live) } } } } // beforeTheBytes loads path with every picture held, measures the // blocks, lets the pictures come, and finds every block where it was // and no layout shift. func beforeTheBytes(t *testing.T, rig *harness.Rig, held *heldGets, path string, width int64, live bool) { t.Helper() held.hold() drive(t, rig, scripts(live), chromedp.EmulateViewport(width, 900), chromedp.Evaluate[chromedp.Void](`location.href = `+ "`"+rig.Origin+path+"`"), chromedp.WaitVisible("article[mapa-body] p")) if live { drive(t, rig, chromedp.WaitVisible(mounted)) } before := read(t, rig, chromedp.Evaluate[string](boxes)) held.let() loaded(t, rig, before) if t.Failed() { t.Fatalf("%dpx, scripts on: %v", width, live) } } // loaded scrolls to every image, waits for each to load, and finds no // layout shift and every box as before was. func loaded(t *testing.T, rig *harness.Rig, before string) { t.Helper() eventually(t, "every image loaded", func() bool { return read(t, rig, chromedp.Evaluate[bool](`Array.prototype.every.call( document.querySelectorAll('article[mapa-body] img[src^="/i/"]'), function (img) { img.scrollIntoView(); return img.complete && img.naturalWidth > 0; })`)) }) drive(t, rig, chromedp.Evaluate[chromedp.Void](`window.scrollTo(0, 0)`)) after := read(t, rig, chromedp.Evaluate[string](boxes)) if after != before { t.Errorf("blocks moved when the images loaded:\n%s\n%s", before, after) } shifts := read(t, rig, chromedp.Evaluate[string]( `JSON.stringify(window.__shifts || [])`)) if shifts != "[]" { t.Errorf("layout shifts while the images loaded: %s", shifts) } } // heldStore holds every Put until let() is called. type heldStore struct { blobs.Store mutex sync.Mutex gate chan struct{} } func (store *heldStore) hold() { store.mutex.Lock() store.gate = make(chan struct{}) store.mutex.Unlock() } func (store *heldStore) let() { store.mutex.Lock() if store.gate != nil { close(store.gate) store.gate = nil } store.mutex.Unlock() } func (store *heldStore) Put(ctx context.Context, data io.Reader, kind string) (blobs.Ref, error) { store.mutex.Lock() gate := store.gate store.mutex.Unlock() if gate != nil { <-gate } return store.Store.Put(ctx, data, kind) } // pasteFile pastes a PNG file the page draws itself, as a screenshot // on the clipboard would arrive. func pasteFile(path string) chromedp.Action[chromedp.Void] { raw, _ := os.ReadFile(path) encoded := base64.StdEncoding.EncodeToString(raw) return chromedp.Evaluate[chromedp.Void](`(function () { var bytes = Uint8Array.from(atob("` + encoded + `"), function (c) { return c.charCodeAt(0); }); var data = new DataTransfer(); data.items.add(new File([bytes], "shot.png", { type: "image/png" })); mapaEditor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true })); })()`) }