oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package browsertest
4
5import (
6 "bytes"
7 "context"
8 "encoding/json"
9 "fmt"
10 "image"
11 "image/png"
12 "math"
13 "os"
14 "path/filepath"
15 "testing"
16 "time"
17
18 "github.com/chromedp/cdproto/cdp"
19 "github.com/chromedp/cdproto/emulation"
20 "github.com/chromedp/chromedp"
21
22 "amadan.net/rastrillo/rastrillo/harness"
23
24 "amadan.net/oficina/base/internal/config"
25 "amadan.net/oficina/base/internal/store"
26)
27
28// layoutShot saves what is on screen to BASE_LAYOUT_ARTIFACTS, when set.
29func layoutShot(t *testing.T, rig *harness.Rig, name string) {
30 t.Helper()
31 dir := os.Getenv("BASE_LAYOUT_ARTIFACTS")
32 if dir == "" {
33 return
34 }
35 t.Setenv("BASE_BROWSER_ARTIFACTS", dir)
36 viewportShot(t, rig, name)
37}
38
39// reducedMotion emulates the device's reduced-motion setting, with the
40// colour scheme given.
41func reducedMotion(scheme string, on bool) chromedp.Action[chromedp.Void] {
42 v := "no-preference"
43 if on {
44 v = "reduce"
45 }
46 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
47 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{
48 Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: scheme}, {Name: "prefers-reduced-motion", Value: v}}})
49 return err
50 })
51}
52
53// installAll installs Welcome and Scratchpad, so Home's grid has Store apps.
54func installAll(t *testing.T, b *baseApp) {
55 t.Helper()
56 for _, app := range []string{"welcome", "scratchpad"} {
57 if _, err := store.ClaimInstall(context.Background(), b.db, app, "acme-"+app+".test"); err != nil {
58 t.Fatal(err)
59 }
60 if err := store.SetInstallState(context.Background(), b.db, app, "installed", ""); err != nil {
61 t.Fatal(err)
62 }
63 }
64}
65
66// gridNames is every app Home's grid should hold, in order.
67func gridNames(apps []config.OficinaApp) string {
68 b, _ := json.Marshal(append(names(apps), "Scratchpad", "Welcome", "Store", "People", "Settings"))
69 return string(b)
70}
71
72func names(apps []config.OficinaApp) []string {
73 var out []string
74 for _, a := range apps {
75 out = append(out, a.Name)
76 }
77 return out
78}
79
80// sameColumnsJS checks a grid of apps: every item the same size, with
81// the same size icon, each on one of the first row's columns.
82const sameColumnsJS = `function sameColumns(grid, icon, problems) {
83 const first = grid[0].getBoundingClientRect(), cols = [];
84 for (const a of grid) { const r = a.getBoundingClientRect(); if (Math.abs(r.top - first.top) < 1) cols.push(Math.round(r.left)); }
85 for (const a of grid) {
86 const r = a.getBoundingClientRect(), i = a.querySelector(".icon").getBoundingClientRect(), name = a.textContent.trim();
87 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);
88 if (Math.abs(i.width - icon) > 2 || Math.abs(i.height - icon) > 2) problems.push(name + "'s icon is " + i.width + "x" + i.height);
89 if (!cols.some(c => Math.abs(c - r.left) <= 1)) problems.push(name + " at " + r.left + " is off the columns " + cols.join(","));
90 if (r.width < 44 || r.height < 44) problems.push(name + " is " + r.width + "x" + r.height);
91 }
92 // Base's own pages start a row of their own: Store in the first column,
93 // People and Settings beside it.
94 const own = grid.slice(-3).map(a => a.getBoundingClientRect());
95 const before = grid.length > 3 ? grid[grid.length - 4].getBoundingClientRect() : null;
96 if (Math.abs(own[0].left - cols[0]) > 1) problems.push("Store is not in the first column");
97 if (before && own[0].top <= before.top) problems.push("Store does not start a new row");
98 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");
99 return cols;
100}`
101
102// appsPanelJS checks Home's apps panel on a wide screen: glass, at most
103// 960px and under the steps; every app, Base's own pages last, in one
104// wrapping grid of alike items with 64px icons, inside the panel.
105const appsPanelJS = `((want) => {
106 ` + sameColumnsJS + `
107 const problems = [], vw = document.documentElement.clientWidth;
108 const panel = document.querySelector("nav.apps");
109 if (!panel || !panel.checkVisibility()) return "no apps panel";
110 const p = panel.getBoundingClientRect(), ps = getComputedStyle(panel);
111 if (panel.getAttribute("aria-label") !== "Apps") problems.push("panel labelled " + panel.getAttribute("aria-label"));
112 if (ps.backdropFilter === "none") problems.push("the panel is not glass");
113 if (p.width > 960.5) problems.push("panel is " + p.width + " wide");
114 if (p.top < document.querySelector(".steps").getBoundingClientRect().bottom) problems.push("panel is not under the steps");
115 if (p.left < 0 || p.right > vw) problems.push("panel at " + p.left + "-" + p.right + " of " + vw);
116 if (document.querySelector(".dock")) problems.push("there is still a dock");
117 const grid = [...panel.querySelectorAll(".app-grid a.app")];
118 const got = grid.map(a => a.textContent.trim());
119 if (JSON.stringify(got) !== JSON.stringify(want)) problems.push("grid " + JSON.stringify(got));
120 const cols = sameColumns(grid, 64, problems);
121 if (cols.length > 5) problems.push(cols.length + " columns, want at most 5");
122 if (vw >= 1024 && cols.length !== 5) problems.push(cols.length + " columns, want 5");
123 // The panel fits its columns, left-aligned under the greeting.
124 const lastCol = Math.max(...grid.map(a => a.getBoundingClientRect().right));
125 if (p.right - lastCol > 32) problems.push("the panel runs " + (p.right - lastCol) + "px past its last column");
126 if (Math.abs(p.left - document.querySelector(".hello").getBoundingClientRect().left) > 1) problems.push("the panel is not left-aligned under the greeting");
127 for (const a of grid) {
128 const r = a.getBoundingClientRect();
129 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");
130 const img = a.querySelector("img");
131 if (img && (!img.complete || img.naturalWidth === 0)) problems.push(a.textContent.trim() + "'s icon did not load");
132 }
133 for (const a of grid.slice(0, 8)) if (a.target !== "_blank" || a.rel !== "noopener") problems.push(a.textContent.trim() + " target/rel");
134 if (grid.slice(-3).map(a => a.getAttribute("href")).join(" ") !== "/store /people /settings") problems.push("Base's own pages are not last");
135 if (document.documentElement.scrollWidth > vw) problems.push("page is " + document.documentElement.scrollWidth + " wide");
136 return problems.join("; ");
137})`
138
139// springboardJS checks Home on a phone: the same glass panel, four columns
140// of alike items with 60px icons, Base's own pages among them; nothing
141// fixed to the screen, so the grid scrolls with Home.
142const springboardJS = `((want) => {
143 ` + sameColumnsJS + `
144 const problems = [], vw = document.documentElement.clientWidth;
145 const panel = document.querySelector("nav.apps"), p = panel.getBoundingClientRect();
146 if (getComputedStyle(panel).backdropFilter === "none") problems.push("the panel is not glass");
147 const grid = [...document.querySelectorAll(".app-grid a.app")];
148 const got = grid.map(a => a.textContent.trim());
149 if (JSON.stringify(got) !== JSON.stringify(want)) problems.push("grid " + JSON.stringify(got));
150 const cols = sameColumns(grid, 60, problems);
151 if (cols.length !== 4) problems.push(cols.length + " columns, want 4");
152 for (const a of grid) {
153 const r = a.getBoundingClientRect();
154 if (r.left < p.left || r.right > p.right) problems.push(a.textContent.trim() + " is outside the panel");
155 }
156 if (document.querySelector(".dock")) problems.push("there is still a dock");
157 const fixed = [...document.querySelectorAll("main *")].filter(e => getComputedStyle(e).position === "fixed" && e.checkVisibility() && !e.closest(".chat-col"));
158 if (fixed.length) problems.push("fixed: " + fixed.map(e => e.className).join(", "));
159 window.scrollTo(0, document.documentElement.scrollHeight);
160 const last = grid[grid.length - 1].getBoundingClientRect();
161 if (last.bottom > innerHeight) problems.push("the last app is off the foot of the screen at " + last.bottom);
162 window.scrollTo(0, 0);
163 if (document.documentElement.scrollWidth > vw) problems.push("page is " + document.documentElement.scrollWidth + " wide");
164 return problems.join("; ");
165})`
166
167// On a wide screen Home is the greeting, the steps and one glass panel
168// of every app, Base's own pages last among them. Nothing runs
169// off the screen at any width, and the keyboard reaches every app in order.
170func TestHomeApps(t *testing.T) {
171 apps := teamApps(t)
172 rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
173 installAll(t, b)
174 for _, scheme := range []string{"dark", "light"} {
175 for _, w := range []int64{1280, 1024, 800, 700} {
176 drive(t, rig, reducedMotion(scheme, false), chromedp.EmulateViewport(w, 800),
177 chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("nav.apps")))
178 if got := harness.Evaluate[string](rig, appsPanelJS+`(`+gridNames(apps)+`)`); got != "" {
179 t.Errorf("%s at %dx800: %s", scheme, w, got)
180 }
181 if w == 1280 {
182 checkContrast(t, rig, "Home, "+scheme, ".lede", ".app-grid .label", "a.me")
183 for _, tint := range []string{"teal", "violet", "mist", "amber", "rose"} {
184 iconContrast(t, rig, "Home, "+scheme, "nav.apps .tile.t-"+tint+" svg")
185 }
186 if got := harness.Evaluate[string](rig, `(() => { const r = document.querySelector("a.me").getBoundingClientRect(), bar = document.querySelector(".topbar").getBoundingClientRect();
187 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 != "" {
188 t.Errorf("%s: the avatar (Settings) target is %s, want 44px inside the top bar", scheme, got)
189 }
190 layoutShot(t, rig, "desktop-home-"+scheme)
191 }
192 }
193 }
194 // The keyboard: the top bar, then every app, Base's own pages last.
195 // With the chat docked open the Base button and the greeting's field
196 // are out of reach.
197 drive(t, rig, chromedp.EmulateViewport(1280, 800), chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("nav.apps")))
198 var seen []string
199 for range 3 + len(apps) + 2 + 3 {
200 drive(t, rig, chromedp.KeyEvent("\t"))
201 seen = append(seen, harness.Evaluate[string](rig, `document.activeElement.matches(":focus-visible") ? document.activeElement.textContent.trim() : "(no visible focus)"`))
202 }
203 want := append(append([]string{"PC"}, append(names(apps), "Scratchpad", "Welcome")...), "Store", "People", "Settings")
204 if fmt.Sprint(seen[:len(want)]) != fmt.Sprint(want) && fmt.Sprint(seen[1:len(want)+1]) != fmt.Sprint(want) {
205 t.Errorf("Tab visits %v, want %v", seen, want)
206 }
207}
208
209// dockedJS checks the chat on a wide screen: docked on the right under the
210// header and down to the foot of the screen, clamp(360px, 30vw, 440px)
211// wide, beside Home and its apps, inside the screen.
212const dockedJS = `(() => {
213 const problems = [], vw = document.documentElement.clientWidth, vh = innerHeight;
214 const r = document.querySelector("#ask-panel").getBoundingClientRect(), bar = document.querySelector(".topbar").getBoundingClientRect();
215 const home = document.querySelector("main.home").getBoundingClientRect(), apps = document.querySelector("nav.apps").getBoundingClientRect();
216 const w = Math.min(440, Math.max(360, vw * 0.3));
217 if (Math.abs(r.width - w) > 1) problems.push("width " + r.width + ", want " + w);
218 if (Math.abs(r.top - (bar.bottom + 16)) > 1) problems.push("top " + r.top + ", the header ends at " + bar.bottom);
219 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);
220 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);
221 if (document.documentElement.scrollWidth > vw) problems.push("page overflows");
222 return problems.join("; ");
223})()`
224
225// On a wide screen the chat is docked beside Home, at every size; its
226// conversation passes AA in both themes.
227func TestAskDockLayout(t *testing.T) {
228 apps := teamApps(t)
229 rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
230 installAll(t, b)
231 for _, size := range [][2]int64{{1280, 800}, {1024, 800}, {800, 800}, {700, 800}, {1280, 600}} {
232 when := fmt.Sprintf("%dx%d", size[0], size[1])
233 drive(t, rig, reducedMotion("dark", false), chromedp.EmulateViewport(size[0], size[1]))
234 openPanel(t, rig)
235 if got := harness.Evaluate[string](rig, dockedJS); got != "" {
236 t.Errorf("%s: %s", when, got)
237 }
238 }
239 // Mid-conversation, in both themes; then closed.
240 for _, scheme := range []string{"dark", "light"} {
241 drive(t, rig, reducedMotion(scheme, false), chromedp.EmulateViewport(1280, 800))
242 openPanel(t, rig)
243 if harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .msg.coordinator").length`) == 0 {
244 drive(t, rig, chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"),
245 chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
246 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)`,
247 chromedp.WithPollingTimeout(10*time.Second)))
248 }
249 if got := harness.Evaluate[string](rig, dockedJS); got != "" {
250 t.Errorf("%s, mid-conversation: %s", scheme, got)
251 }
252 checkContrast(t, rig, "the docked chat, "+scheme, "#ask-panel .msg.person", "#ask-panel .msg.coordinator", "#ask-panel .ask-head h2")
253 layoutShot(t, rig, "desktop-chat-"+scheme)
254 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)),
255 chromedp.Poll[chromedp.Void](`!document.querySelector("#ask-panel").checkVisibility({ visibilityProperty: true })`, chromedp.WithPollingTimeout(3*time.Second)))
256 askClosed(t, b, true)
257 checkContrast(t, rig, "Home with the chat closed, "+scheme, ".ask-field span")
258 layoutShot(t, rig, "desktop-home-closed-"+scheme)
259 drive(t, rig, chromedp.Click(chromedp.CSS(".base-btn")), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)))
260 askClosed(t, b, false)
261 }
262 drive(t, rig, reducedMotion("dark", false))
263}
264
265// drawnIcon is what one app icon paints, measured in pixels, relative to
266// its 64px (or 60px) box.
267type drawnIcon struct {
268 Name string
269 Image bool // an Oficina icon (Estilo's artwork) rather than one of Base's tiles
270 L, T, W, H float64
271}
272
273// drawnIcons measures every icon in Home's grid from the screen: with the
274// page paused, one screenshot with the icons and one without; the pixels
275// that differ are each icon's drawing.
276func drawnIcons(t *testing.T, rig *harness.Rig) []drawnIcon {
277 t.Helper()
278 drive(t, rig, chromedp.Evaluate[chromedp.Void](pauseJS), chromedp.Sleep(150*time.Millisecond))
279 with := harness.Read(rig, chromedp.CaptureScreenshot())
280 var icons []struct {
281 Name string
282 Image bool
283 X, Y, W, H float64
284 }
285 if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `JSON.stringify([...document.querySelectorAll(".app-grid .icon")].map(i => {
286 const r = i.getBoundingClientRect(); i.style.visibility = "hidden";
287 return {Name: i.closest("a").textContent.trim(), Image: !!i.querySelector("img"), X: r.left, Y: r.top, W: r.width, H: r.height};
288 }))`)), &icons); err != nil {
289 t.Fatal(err)
290 }
291 without := harness.Read(rig, chromedp.CaptureScreenshot())
292 dpr := harness.Evaluate[float64](rig, `window.devicePixelRatio`)
293 drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelectorAll(".app-grid .icon").forEach(i => i.style.removeProperty("visibility")), `+unpauseJS))
294 a, err := png.Decode(bytes.NewReader(with))
295 if err != nil {
296 t.Fatal(err)
297 }
298 b, err := png.Decode(bytes.NewReader(without))
299 if err != nil {
300 t.Fatal(err)
301 }
302 var out []drawnIcon
303 for _, ic := range icons {
304 x0, y0 := int((ic.X-3)*dpr), int((ic.Y-3)*dpr)
305 x1, y1 := int((ic.X+ic.W+3)*dpr), int((ic.Y+ic.H+3)*dpr)
306 minX, minY, maxX, maxY := x1, y1, x0, y0
307 for y := max(0, y0); y < y1; y++ {
308 for x := max(0, x0); x < x1; x++ {
309 ar, ag, ab, _ := a.At(x, y).RGBA()
310 br, bg, bb, _ := b.At(x, y).RGBA()
311 if diff(ar, br)+diff(ag, bg)+diff(ab, bb) < 30 {
312 continue
313 }
314 minX, minY, maxX, maxY = min(minX, x), min(minY, y), max(maxX, x), max(maxY, y)
315 }
316 }
317 out = append(out, drawnIcon{Name: ic.Name, Image: ic.Image,
318 L: float64(minX)/dpr - ic.X, T: float64(minY)/dpr - ic.Y,
319 W: float64(maxX-minX+1) / dpr, H: float64(maxY-minY+1) / dpr})
320 }
321 return out
322}
323
324// Base's own tiles (Store, People, Settings and the installed apps) are
325// drawn the size and shape of Estilo's Oficina icons, whose squircle sits
326// inside the box with a margin: on screen each matches within a pixel, on
327// a wide screen and a phone.
328func TestTilesMatchOficinaIcons(t *testing.T) {
329 apps := teamApps(t)
330 rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
331 installAll(t, b)
332 for _, c := range []struct {
333 name string
334 size chromedp.Action[chromedp.Void]
335 }{
336 {"wide", chromedp.EmulateViewport(1280, 800, chromedp.EmulateScale(2))},
337 {"phone", chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3))},
338 } {
339 drive(t, rig, reducedMotion("dark", true), c.size, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS("nav.apps")),
340 chromedp.Poll[chromedp.Void](`[...document.images].every(i => i.complete)`, chromedp.WithPollingTimeout(5*time.Second)))
341 icons := drawnIcons(t, rig)
342 var ref *drawnIcon
343 for i := range icons {
344 if icons[i].Image && icons[i].Name == "Calendar" {
345 ref = &icons[i]
346 }
347 }
348 if ref == nil {
349 t.Fatalf("%s: no Calendar icon", c.name)
350 }
351 t.Logf("%s: Calendar's squircle %+v", c.name, *ref)
352 for _, ic := range icons {
353 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 {
354 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)
355 }
356 }
357 if c.name == "wide" {
358 saveTilesZoom(t, rig)
359 }
360 }
361 drive(t, rig, reducedMotion("dark", false))
362}
363
364// saveTilesZoom saves the rows where Oficina icons and Base's tiles meet,
365// at twice size, to BASE_LAYOUT_ARTIFACTS/tiles-zoom.png.
366func saveTilesZoom(t *testing.T, rig *harness.Rig) {
367 t.Helper()
368 dir := os.Getenv("BASE_LAYOUT_ARTIFACTS")
369 if dir == "" {
370 return
371 }
372 var r struct{ X, Y, W, H float64 }
373 if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `(() => {
374 const items = [...document.querySelectorAll(".app-grid > li")], a = items[5].getBoundingClientRect(), z = items[items.length - 1].getBoundingClientRect();
375 const p = document.querySelector("nav.apps").getBoundingClientRect();
376 return JSON.stringify({X: p.left, Y: a.top - 8, W: p.width, H: z.bottom - a.top + 16});
377 })()`)), &r); err != nil {
378 t.Fatal(err)
379 }
380 img, err := png.Decode(bytes.NewReader(harness.Read(rig, chromedp.CaptureScreenshot())))
381 if err != nil {
382 t.Fatal(err)
383 }
384 dpr := harness.Evaluate[float64](rig, `window.devicePixelRatio`)
385 crop := img.(interface {
386 SubImage(image.Rectangle) image.Image
387 }).SubImage(image.Rect(int(r.X*dpr), int(r.Y*dpr), int((r.X+r.W)*dpr), int((r.Y+r.H)*dpr)))
388 var buf bytes.Buffer
389 if err := png.Encode(&buf, crop); err != nil {
390 t.Fatal(err)
391 }
392 if err := os.WriteFile(filepath.Join(dir, "tiles-zoom.png"), buf.Bytes(), 0o644); err != nil {
393 t.Fatal(err)
394 }
395}
396