//go:build browser package browsertest import ( "bytes" "context" "encoding/json" "fmt" "image" "image/png" "math" "os" "path/filepath" "testing" "time" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp" "amadan.net/rastrillo/rastrillo/harness" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/store" ) // layoutShot saves what is on screen to BASE_LAYOUT_ARTIFACTS, when set. func layoutShot(t *testing.T, rig *harness.Rig, name string) { t.Helper() dir := os.Getenv("BASE_LAYOUT_ARTIFACTS") if dir == "" { return } t.Setenv("BASE_BROWSER_ARTIFACTS", dir) viewportShot(t, rig, name) } // reducedMotion emulates the device's reduced-motion setting, with the // colour scheme given. func reducedMotion(scheme string, on bool) chromedp.Action[chromedp.Void] { v := "no-preference" if on { v = "reduce" } return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{ Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: scheme}, {Name: "prefers-reduced-motion", Value: v}}}) return err }) } // installAll installs Welcome and Scratchpad, so Home's grid has Store apps. func installAll(t *testing.T, b *baseApp) { t.Helper() for _, app := range []string{"welcome", "scratchpad"} { if _, err := store.ClaimInstall(context.Background(), b.db, app, "acme-"+app+".test"); err != nil { t.Fatal(err) } if err := store.SetInstallState(context.Background(), b.db, app, "installed", ""); err != nil { t.Fatal(err) } } } // gridNames is every app Home's grid should hold, in order. func gridNames(apps []config.OficinaApp) string { b, _ := json.Marshal(append(names(apps), "Scratchpad", "Welcome", "Store", "People", "Settings")) return string(b) } func names(apps []config.OficinaApp) []string { var out []string for _, a := range apps { out = append(out, a.Name) } return out } // sameColumnsJS checks a grid of apps: every item the same size, with // the same size icon, each on one of the first row's columns. const sameColumnsJS = `function sameColumns(grid, icon, problems) { const first = grid[0].getBoundingClientRect(), cols = []; for (const a of grid) { const r = a.getBoundingClientRect(); if (Math.abs(r.top - first.top) < 1) cols.push(Math.round(r.left)); } for (const a of grid) { const r = a.getBoundingClientRect(), i = a.querySelector(".icon").getBoundingClientRect(), name = a.textContent.trim(); if (Math.abs(r.width - first.width) > 0.5 || Math.abs(r.height - first.height) > 0.5) problems.push(name + " is " + r.width + "x" + r.height + ", not " + first.width + "x" + first.height); if (Math.abs(i.width - icon) > 2 || Math.abs(i.height - icon) > 2) problems.push(name + "'s icon is " + i.width + "x" + i.height); if (!cols.some(c => Math.abs(c - r.left) <= 1)) problems.push(name + " at " + r.left + " is off the columns " + cols.join(",")); if (r.width < 44 || r.height < 44) problems.push(name + " is " + r.width + "x" + r.height); } // Base's own pages start a row of their own: Store in the first column, // People and Settings beside it. const own = grid.slice(-3).map(a => a.getBoundingClientRect()); const before = grid.length > 3 ? grid[grid.length - 4].getBoundingClientRect() : null; if (Math.abs(own[0].left - cols[0]) > 1) problems.push("Store is not in the first column"); if (before && own[0].top <= before.top) problems.push("Store does not start a new row"); if (Math.abs(own[1].top - own[0].top) > 0.5 || Math.abs(own[2].top - own[0].top) > 0.5 || Math.abs(own[1].left - cols[1]) > 1 || Math.abs(own[2].left - cols[2]) > 1) problems.push("People and Settings are not beside Store"); return cols; }` // appsPanelJS checks Home's apps panel on a wide screen: glass, at most // 960px and under the steps; every app, Base's own pages last, in one // wrapping grid of alike items with 64px icons, inside the panel. const appsPanelJS = `((want) => { ` + sameColumnsJS + ` const problems = [], vw = document.documentElement.clientWidth; const panel = document.querySelector("nav.apps"); if (!panel || !panel.checkVisibility()) return "no apps panel"; const p = panel.getBoundingClientRect(), ps = getComputedStyle(panel); if (panel.getAttribute("aria-label") !== "Apps") problems.push("panel labelled " + panel.getAttribute("aria-label")); if (ps.backdropFilter === "none") problems.push("the panel is not glass"); if (p.width > 960.5) problems.push("panel is " + p.width + " wide"); if (p.top < document.querySelector(".steps").getBoundingClientRect().bottom) problems.push("panel is not under the steps"); if (p.left < 0 || p.right > vw) problems.push("panel at " + p.left + "-" + p.right + " of " + vw); if (document.querySelector(".dock")) problems.push("there is still a dock"); const grid = [...panel.querySelectorAll(".app-grid a.app")]; const got = grid.map(a => a.textContent.trim()); if (JSON.stringify(got) !== JSON.stringify(want)) problems.push("grid " + JSON.stringify(got)); const cols = sameColumns(grid, 64, problems); if (cols.length > 5) problems.push(cols.length + " columns, want at most 5"); if (vw >= 1024 && cols.length !== 5) problems.push(cols.length + " columns, want 5"); // The panel fits its columns, left-aligned under the greeting. const lastCol = Math.max(...grid.map(a => a.getBoundingClientRect().right)); if (p.right - lastCol > 32) problems.push("the panel runs " + (p.right - lastCol) + "px past its last column"); if (Math.abs(p.left - document.querySelector(".hello").getBoundingClientRect().left) > 1) problems.push("the panel is not left-aligned under the greeting"); for (const a of grid) { const r = a.getBoundingClientRect(); if (r.left < p.left || r.right > p.right || r.top < p.top || r.bottom > p.bottom) problems.push(a.textContent.trim() + " is outside the panel"); const img = a.querySelector("img"); if (img && (!img.complete || img.naturalWidth === 0)) problems.push(a.textContent.trim() + "'s icon did not load"); } for (const a of grid.slice(0, 8)) if (a.target !== "_blank" || a.rel !== "noopener") problems.push(a.textContent.trim() + " target/rel"); if (grid.slice(-3).map(a => a.getAttribute("href")).join(" ") !== "/store /people /settings") problems.push("Base's own pages are not last"); if (document.documentElement.scrollWidth > vw) problems.push("page is " + document.documentElement.scrollWidth + " wide"); return problems.join("; "); })` // springboardJS checks Home on a phone: the same glass panel, four columns // of alike items with 60px icons, Base's own pages among them; nothing // fixed to the screen, so the grid scrolls with Home. const springboardJS = `((want) => { ` + sameColumnsJS + ` const problems = [], vw = document.documentElement.clientWidth; const panel = document.querySelector("nav.apps"), p = panel.getBoundingClientRect(); if (getComputedStyle(panel).backdropFilter === "none") problems.push("the panel is not glass"); const grid = [...document.querySelectorAll(".app-grid a.app")]; const got = grid.map(a => a.textContent.trim()); if (JSON.stringify(got) !== JSON.stringify(want)) problems.push("grid " + JSON.stringify(got)); const cols = sameColumns(grid, 60, problems); if (cols.length !== 4) problems.push(cols.length + " columns, want 4"); for (const a of grid) { const r = a.getBoundingClientRect(); if (r.left < p.left || r.right > p.right) problems.push(a.textContent.trim() + " is outside the panel"); } if (document.querySelector(".dock")) problems.push("there is still a dock"); const fixed = [...document.querySelectorAll("main *")].filter(e => getComputedStyle(e).position === "fixed" && e.checkVisibility() && !e.closest(".chat-col")); if (fixed.length) problems.push("fixed: " + fixed.map(e => e.className).join(", ")); window.scrollTo(0, document.documentElement.scrollHeight); const last = grid[grid.length - 1].getBoundingClientRect(); if (last.bottom > innerHeight) problems.push("the last app is off the foot of the screen at " + last.bottom); window.scrollTo(0, 0); if (document.documentElement.scrollWidth > vw) problems.push("page is " + document.documentElement.scrollWidth + " wide"); return problems.join("; "); })` // On a wide screen Home is the greeting, the steps and one glass panel // of every app, Base's own pages last among them. Nothing runs // off the screen at any width, and the keyboard reaches every app in order. func TestHomeApps(t *testing.T) { apps := teamApps(t) rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps }) installAll(t, b) for _, scheme := range []string{"dark", "light"} { for _, w := range []int64{1280, 1024, 800, 700} { drive(t, rig, reducedMotion(scheme, false), chromedp.EmulateViewport(w, 800), chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("nav.apps"))) if got := harness.Evaluate[string](rig, appsPanelJS+`(`+gridNames(apps)+`)`); got != "" { t.Errorf("%s at %dx800: %s", scheme, w, got) } if w == 1280 { checkContrast(t, rig, "Home, "+scheme, ".lede", ".app-grid .label", "a.me") for _, tint := range []string{"teal", "violet", "mist", "amber", "rose"} { iconContrast(t, rig, "Home, "+scheme, "nav.apps .tile.t-"+tint+" svg") } if got := harness.Evaluate[string](rig, `(() => { const r = document.querySelector("a.me").getBoundingClientRect(), bar = document.querySelector(".topbar").getBoundingClientRect(); return r.width >= 44 && r.height >= 44 && r.top >= bar.top - 0.5 && r.bottom <= bar.bottom + 0.5 ? "" : r.width + "x" + r.height + " at " + r.top + "-" + r.bottom; })()`); got != "" { t.Errorf("%s: the avatar (Settings) target is %s, want 44px inside the top bar", scheme, got) } layoutShot(t, rig, "desktop-home-"+scheme) } } } // The keyboard: the top bar, then every app, Base's own pages last. // With the chat docked open the Base button and the greeting's field // are out of reach. drive(t, rig, chromedp.EmulateViewport(1280, 800), chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("nav.apps"))) var seen []string for range 3 + len(apps) + 2 + 3 { drive(t, rig, chromedp.KeyEvent("\t")) seen = append(seen, harness.Evaluate[string](rig, `document.activeElement.matches(":focus-visible") ? document.activeElement.textContent.trim() : "(no visible focus)"`)) } want := append(append([]string{"PC"}, append(names(apps), "Scratchpad", "Welcome")...), "Store", "People", "Settings") if fmt.Sprint(seen[:len(want)]) != fmt.Sprint(want) && fmt.Sprint(seen[1:len(want)+1]) != fmt.Sprint(want) { t.Errorf("Tab visits %v, want %v", seen, want) } } // dockedJS checks the chat on a wide screen: docked on the right under the // header and down to the foot of the screen, clamp(360px, 30vw, 440px) // wide, beside Home and its apps, inside the screen. const dockedJS = `(() => { const problems = [], vw = document.documentElement.clientWidth, vh = innerHeight; const r = document.querySelector("#ask-panel").getBoundingClientRect(), bar = document.querySelector(".topbar").getBoundingClientRect(); const home = document.querySelector("main.home").getBoundingClientRect(), apps = document.querySelector("nav.apps").getBoundingClientRect(); const w = Math.min(440, Math.max(360, vw * 0.3)); if (Math.abs(r.width - w) > 1) problems.push("width " + r.width + ", want " + w); if (Math.abs(r.top - (bar.bottom + 16)) > 1) problems.push("top " + r.top + ", the header ends at " + bar.bottom); if (Math.abs(r.bottom - (vh - 16)) > 1 || Math.abs(r.right - (vw - 16)) > 1) problems.push("ends at " + r.right + "," + r.bottom + " of " + vw + "," + vh); if (r.left < home.right - 0.5 || r.left < apps.right) problems.push("left " + r.left + ", Home ends at " + home.right + ", the apps at " + apps.right); if (document.documentElement.scrollWidth > vw) problems.push("page overflows"); return problems.join("; "); })()` // On a wide screen the chat is docked beside Home, at every size; its // conversation passes AA in both themes. func TestAskDockLayout(t *testing.T) { apps := teamApps(t) rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps }) installAll(t, b) for _, size := range [][2]int64{{1280, 800}, {1024, 800}, {800, 800}, {700, 800}, {1280, 600}} { when := fmt.Sprintf("%dx%d", size[0], size[1]) drive(t, rig, reducedMotion("dark", false), chromedp.EmulateViewport(size[0], size[1])) openPanel(t, rig) if got := harness.Evaluate[string](rig, dockedJS); got != "" { t.Errorf("%s: %s", when, got) } } // Mid-conversation, in both themes; then closed. for _, scheme := range []string{"dark", "light"} { drive(t, rig, reducedMotion(scheme, false), chromedp.EmulateViewport(1280, 800)) openPanel(t, rig) if harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.coordinator").length`) == 0 { drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"), chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)), chromedp.Poll[chromedp.Void](`!document.querySelector("#ask-panel .thinking, #ask-panel .draft, #ask-panel .think-line") && [...document.querySelectorAll("#ask-panel .msg.coordinator")].some(m => m.dataset.id)`, chromedp.WithPollingTimeout(10*time.Second))) } if got := harness.Evaluate[string](rig, dockedJS); got != "" { t.Errorf("%s, mid-conversation: %s", scheme, got) } checkContrast(t, rig, "the docked chat, "+scheme, "#ask-panel .msg.person", "#ask-panel .msg.coordinator", "#ask-panel .ask-head h2") layoutShot(t, rig, "desktop-chat-"+scheme) drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)), chromedp.Poll[chromedp.Void](`!document.querySelector("#ask-panel").checkVisibility({ visibilityProperty: true })`, chromedp.WithPollingTimeout(3*time.Second))) askClosed(t, b, true) checkContrast(t, rig, "Home with the chat closed, "+scheme, ".ask-field span") layoutShot(t, rig, "desktop-home-closed-"+scheme) drive(t, rig, chromedp.Click(chromedp.CSS(".base-btn")), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second))) askClosed(t, b, false) } drive(t, rig, reducedMotion("dark", false)) } // drawnIcon is what one app icon paints, measured in pixels, relative to // its 64px (or 60px) box. type drawnIcon struct { Name string Image bool // an Oficina icon (Estilo's artwork) rather than one of Base's tiles L, T, W, H float64 } // drawnIcons measures every icon in Home's grid from the screen: with the // page paused, one screenshot with the icons and one without; the pixels // that differ are each icon's drawing. func drawnIcons(t *testing.T, rig *harness.Rig) []drawnIcon { t.Helper() drive(t, rig, chromedp.Evaluate[chromedp.Void](pauseJS), chromedp.Sleep(150*time.Millisecond)) with := harness.Read(rig, chromedp.CaptureScreenshot()) var icons []struct { Name string Image bool X, Y, W, H float64 } if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `JSON.stringify([...document.querySelectorAll(".app-grid .icon")].map(i => { const r = i.getBoundingClientRect(); i.style.visibility = "hidden"; return {Name: i.closest("a").textContent.trim(), Image: !!i.querySelector("img"), X: r.left, Y: r.top, W: r.width, H: r.height}; }))`)), &icons); err != nil { t.Fatal(err) } without := harness.Read(rig, chromedp.CaptureScreenshot()) dpr := harness.Evaluate[float64](rig, `window.devicePixelRatio`) drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelectorAll(".app-grid .icon").forEach(i => i.style.removeProperty("visibility")), `+unpauseJS)) a, err := png.Decode(bytes.NewReader(with)) if err != nil { t.Fatal(err) } b, err := png.Decode(bytes.NewReader(without)) if err != nil { t.Fatal(err) } var out []drawnIcon for _, ic := range icons { x0, y0 := int((ic.X-3)*dpr), int((ic.Y-3)*dpr) x1, y1 := int((ic.X+ic.W+3)*dpr), int((ic.Y+ic.H+3)*dpr) minX, minY, maxX, maxY := x1, y1, x0, y0 for y := max(0, y0); y < y1; y++ { for x := max(0, x0); x < x1; x++ { ar, ag, ab, _ := a.At(x, y).RGBA() br, bg, bb, _ := b.At(x, y).RGBA() if diff(ar, br)+diff(ag, bg)+diff(ab, bb) < 30 { continue } minX, minY, maxX, maxY = min(minX, x), min(minY, y), max(maxX, x), max(maxY, y) } } out = append(out, drawnIcon{Name: ic.Name, Image: ic.Image, L: float64(minX)/dpr - ic.X, T: float64(minY)/dpr - ic.Y, W: float64(maxX-minX+1) / dpr, H: float64(maxY-minY+1) / dpr}) } return out } // Base's own tiles (Store, People, Settings and the installed apps) are // drawn the size and shape of Estilo's Oficina icons, whose squircle sits // inside the box with a margin: on screen each matches within a pixel, on // a wide screen and a phone. func TestTilesMatchOficinaIcons(t *testing.T) { apps := teamApps(t) rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps }) installAll(t, b) for _, c := range []struct { name string size chromedp.Action[chromedp.Void] }{ {"wide", chromedp.EmulateViewport(1280, 800, chromedp.EmulateScale(2))}, {"phone", chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3))}, } { drive(t, rig, reducedMotion("dark", true), c.size, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("nav.apps")), chromedp.Poll[chromedp.Void](`[...document.images].every(i => i.complete)`, chromedp.WithPollingTimeout(5*time.Second))) icons := drawnIcons(t, rig) var ref *drawnIcon for i := range icons { if icons[i].Image && icons[i].Name == "Calendar" { ref = &icons[i] } } if ref == nil { t.Fatalf("%s: no Calendar icon", c.name) } t.Logf("%s: Calendar's squircle %+v", c.name, *ref) for _, ic := range icons { if math.Abs(ic.L-ref.L) > 1 || math.Abs(ic.T-ref.T) > 1 || math.Abs(ic.W-ref.W) > 1 || math.Abs(ic.H-ref.H) > 1 { t.Errorf("%s: %s is drawn at %.1f,%.1f %.1fx%.1f; Calendar at %.1f,%.1f %.1fx%.1f", c.name, ic.Name, ic.L, ic.T, ic.W, ic.H, ref.L, ref.T, ref.W, ref.H) } } if c.name == "wide" { saveTilesZoom(t, rig) } } drive(t, rig, reducedMotion("dark", false)) } // saveTilesZoom saves the rows where Oficina icons and Base's tiles meet, // at twice size, to BASE_LAYOUT_ARTIFACTS/tiles-zoom.png. func saveTilesZoom(t *testing.T, rig *harness.Rig) { t.Helper() dir := os.Getenv("BASE_LAYOUT_ARTIFACTS") if dir == "" { return } var r struct{ X, Y, W, H float64 } if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `(() => { const items = [...document.querySelectorAll(".app-grid > li")], a = items[5].getBoundingClientRect(), z = items[items.length - 1].getBoundingClientRect(); const p = document.querySelector("nav.apps").getBoundingClientRect(); return JSON.stringify({X: p.left, Y: a.top - 8, W: p.width, H: z.bottom - a.top + 16}); })()`)), &r); err != nil { t.Fatal(err) } img, err := png.Decode(bytes.NewReader(harness.Read(rig, chromedp.CaptureScreenshot()))) if err != nil { t.Fatal(err) } dpr := harness.Evaluate[float64](rig, `window.devicePixelRatio`) crop := img.(interface { SubImage(image.Rectangle) image.Image }).SubImage(image.Rect(int(r.X*dpr), int(r.Y*dpr), int((r.X+r.W)*dpr), int((r.Y+r.H)*dpr))) var buf bytes.Buffer if err := png.Encode(&buf, crop); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, "tiles-zoom.png"), buf.Bytes(), 0o644); err != nil { t.Fatal(err) } }