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/png"
11 "math"
12 "os"
13 "path/filepath"
14 "regexp"
15 "strconv"
16 "testing"
17 "time"
18
19 "github.com/chromedp/cdproto/cdp"
20 "github.com/chromedp/cdproto/emulation"
21 "github.com/chromedp/chromedp"
22
23 "amadan.net/rastrillo/rastrillo/harness"
24
25 "amadan.net/oficina/base/internal/config"
26)
27
28// prefersScheme emulates the device's light or dark setting.
29func prefersScheme(scheme string) chromedp.Action[chromedp.Void] {
30 return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
31 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{
32 Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: scheme}}})
33 return err
34 })
35}
36
37// lightShot saves what is on screen to BASE_LIGHT_ARTIFACTS, when set.
38func lightShot(t *testing.T, rig *harness.Rig, name string) {
39 t.Helper()
40 dir := os.Getenv("BASE_LIGHT_ARTIFACTS")
41 if dir == "" {
42 return
43 }
44 t.Setenv("BASE_BROWSER_ARTIFACTS", dir)
45 viewportShot(t, rig, name)
46}
47
48type textBox struct {
49 Label string
50 X, Y, W, H, Size float64
51 Color string
52}
53
54var rgbRE = regexp.MustCompile(`rgba?\(([\d.]+),? ([\d.]+),? ([\d.]+)`)
55
56func luminance(r, g, b float64) float64 {
57 ch := func(v float64) float64 {
58 v /= 255
59 if v <= 0.03928 {
60 return v / 12.92
61 }
62 return math.Pow((v+0.055)/1.055, 2.4)
63 }
64 return 0.2126*ch(r) + 0.7152*ch(g) + 0.0722*ch(b)
65}
66
67// textContrast measures, for each visible element matching sel, the
68// contrast of its computed text colour against the pixels right behind its
69// glyphs, as the page is drawn at that moment (fog, glass and all). With
70// animations paused it takes one screenshot with the text and one without
71// (descendants with their own colour, such as a step's tick, stay drawn in
72// both): the pixels that differ are the glyphs, and the second shot has
73// what lies behind them. It returns the worst element's ratio and the ratio
74// that element needs (3 for large text).
75func textContrast(t *testing.T, rig *harness.Rig, sel string) (worst, need float64, where string) {
76 t.Helper()
77 return contrastOf(t, rig, sel, "color", 0)
78}
79
80// pauseJS stops the page's animations and transitions (a constructed
81// stylesheet, which the page's CSP allows), so two screenshots differ only
82// in what a check changes.
83const pauseJS = `(() => { const s = new CSSStyleSheet();
84 s.replaceSync("*, *::before, *::after { animation-play-state: paused !important; transition: none !important; caret-color: transparent !important; }");
85 document.adoptedStyleSheets = [...document.adoptedStyleSheets, s]; window.__pause = s; })()`
86
87const unpauseJS = `document.adoptedStyleSheets = document.adoptedStyleSheets.filter(s => s !== window.__pause)`
88
89// contrastOf is textContrast for any colour an element draws: prop is the
90// CSS property (color, stroke, outline-color) it hides to find the pixels
91// that colour paints. need 0 means text: 4.5, or 3 when large; anything
92// else (an icon, a focus ring) needs what it is given.
93func contrastOf(t *testing.T, rig *harness.Rig, sel, prop string, minimum float64) (worst, need float64, where string) {
94 t.Helper()
95 drive(t, rig, chromedp.Evaluate[chromedp.Void](pauseJS), chromedp.Sleep(100*time.Millisecond))
96 with := harness.Read(rig, chromedp.CaptureScreenshot())
97 var boxes []textBox
98 if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `((sel, prop) => {
99 const out = [];
100 for (const e of document.querySelectorAll(sel)) {
101 let r = e.getBoundingClientRect();
102 if (!e.checkVisibility() || (prop === "color" && !e.textContent.trim()) || r.bottom <= 0 || r.top >= innerHeight || r.width === 0) continue;
103 const s = getComputedStyle(e);
104 if (prop === "outline-color") { // the ring lies outside the box
105 const o = parseFloat(s.outlineOffset) + parseFloat(s.outlineWidth) + 2;
106 r = {left: r.left - o, top: r.top - o, width: r.width + 2 * o, height: r.height + 2 * o};
107 }
108 out.push({Label: (e.textContent.trim() || e.closest("a,button")?.textContent.trim() || sel).slice(0, 30), X: r.left, Y: r.top, W: r.width, H: r.height,
109 Size: parseFloat(s.fontSize) * (parseInt(s.fontWeight) >= 700 ? 1.33 : 1), Color: s.getPropertyValue(prop)});
110 e.dataset.contrast = "1";
111 e.style.setProperty(prop, "transparent", "important");
112 }
113 return JSON.stringify(out);
114 })(`+strconv.Quote(sel)+`, `+strconv.Quote(prop)+`)`)), &boxes); err != nil {
115 t.Fatal(err)
116 }
117 without := harness.Read(rig, chromedp.CaptureScreenshot())
118 dpr := harness.Evaluate[float64](rig, `window.devicePixelRatio`)
119 drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.querySelectorAll("[data-contrast]").forEach(e => { e.style.removeProperty(`+strconv.Quote(prop)+`); delete e.dataset.contrast; }), `+unpauseJS))
120 if len(boxes) == 0 {
121 t.Fatalf("nothing on screen matches %s", sel)
122 }
123 a, err := png.Decode(bytes.NewReader(with))
124 if err != nil {
125 t.Fatal(err)
126 }
127 b, err := png.Decode(bytes.NewReader(without))
128 if err != nil {
129 t.Fatal(err)
130 }
131 worst, need = math.Inf(1), 4.5
132 measured := 0
133 for _, box := range boxes {
134 m := rgbRE.FindStringSubmatch(box.Color)
135 if m == nil {
136 t.Fatalf("%s: colour %q", box.Label, box.Color)
137 }
138 r, _ := strconv.ParseFloat(m[1], 64)
139 g, _ := strconv.ParseFloat(m[2], 64)
140 bl, _ := strconv.ParseFloat(m[3], 64)
141 fg := luminance(r, g, bl)
142 lo, glyphs := math.Inf(1), 0
143 for y := max(0, int(box.Y*dpr)); y < int((box.Y+box.H)*dpr); y++ {
144 for x := max(0, int(box.X*dpr)); x < int((box.X+box.W)*dpr); x++ {
145 ar, ag, ab, _ := a.At(x, y).RGBA()
146 br, bg, bb, _ := b.At(x, y).RGBA()
147 if diff(ar, br)+diff(ag, bg)+diff(ab, bb) < 48 {
148 continue // not a glyph
149 }
150 glyphs++
151 l := luminance(float64(br>>8), float64(bg>>8), float64(bb>>8))
152 lo = math.Min(lo, (math.Max(fg, l)+0.05)/(math.Min(fg, l)+0.05))
153 }
154 }
155 if glyphs == 0 {
156 continue // below the fold, or drawn the same either way
157 }
158 measured++
159 n := minimum
160 if n == 0 {
161 n = 4.5
162 if box.Size >= 24 {
163 n = 3
164 }
165 }
166 if lo/n < worst/need {
167 worst, need, where = lo, n, box.Label
168 }
169 }
170 if measured == 0 {
171 t.Fatalf("%s: nothing drawn in %s", sel, prop)
172 }
173 return worst, need, where
174}
175
176// diff is how far apart two 16-bit channels are, in 8-bit steps.
177func diff(a, b uint32) int {
178 d := int(a>>8) - int(b>>8)
179 if d < 0 {
180 return -d
181 }
182 return d
183}
184
185// checkContrast holds each selector's text to AA at this moment and again
186// a few seconds on, when the fog has moved.
187func checkContrast(t *testing.T, rig *harness.Rig, when string, sels ...string) {
188 t.Helper()
189 for moment := range 2 {
190 if moment > 0 {
191 drive(t, rig, chromedp.Sleep(4*time.Second))
192 }
193 for _, sel := range sels {
194 worst, need, where := textContrast(t, rig, sel)
195 t.Logf("%s, moment %d: %s worst %.2f (%q, needs %.1f)", when, moment+1, sel, worst, where, need)
196 if worst < need {
197 t.Errorf("%s, moment %d: %s %q has contrast %.2f, needs %.1f", when, moment+1, sel, where, worst, need)
198 }
199 }
200 }
201}
202
203// focusRing tabs until focus is on the first element matching sel and holds
204// its focus ring to 3:1 against what lies behind it.
205func focusRing(t *testing.T, rig *harness.Rig, when, sel string) {
206 t.Helper()
207 drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`))
208 for range 40 {
209 drive(t, rig, chromedp.KeyEvent("\t"))
210 if harness.Evaluate[bool](rig, `document.activeElement.matches(`+strconv.Quote(sel)+`)`) {
211 break
212 }
213 }
214 if !harness.Evaluate[bool](rig, `document.activeElement.matches(`+strconv.Quote(sel)+`) && document.activeElement.matches(":focus-visible")`) {
215 t.Fatalf("%s: the keyboard never reached %s", when, sel)
216 }
217 worst, need, where := contrastOf(t, rig, ":focus-visible", "outline-color", 3)
218 t.Logf("%s: focus ring on %s %.2f (%q)", when, sel, worst, where)
219 if worst < need {
220 t.Errorf("%s: the focus ring on %s %q has contrast %.2f, needs %.1f", when, sel, where, worst, need)
221 }
222}
223
224// iconContrast holds the tiles' line icons to 3:1 against their tint.
225func iconContrast(t *testing.T, rig *harness.Rig, when, sel string) {
226 t.Helper()
227 worst, need, where := contrastOf(t, rig, sel, "stroke", 3)
228 t.Logf("%s: icons %s worst %.2f (%q)", when, sel, worst, where)
229 if worst < need {
230 t.Errorf("%s: the icon in %q has contrast %.2f, needs %.1f", when, where, worst, need)
231 }
232}
233
234// textColour is el's computed colour.
235func textColour(rig *harness.Rig, sel string) string {
236 return harness.Evaluate[string](rig, `getComputedStyle(document.querySelector(`+strconv.Quote(sel)+`)).color`)
237}
238
239const (
240 lightInk = "rgb(30, 36, 64)" // #1E2440
241 darkInk = "rgb(238, 242, 248)" // #EEF2F8
242)
243
244// Base follows the device's light or dark setting until the member picks
245// one in Settings; light mode's text passes AA over the moving fog.
246func TestLightMode(t *testing.T) {
247 apps := teamApps(t)
248 rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
249 installAll(t, b) // every tile tint on Home
250 home := func() {
251 t.Helper()
252 drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(".hello")))
253 }
254
255 // System: the device decides.
256 drive(t, rig, chromedp.EmulateViewport(1280, 800), prefersScheme("light"))
257 home()
258 if got := textColour(rig, ".hello"); got != lightInk || harness.Evaluate[bool](rig, `document.documentElement.hasAttribute("data-theme")`) {
259 t.Fatalf("System on a light device: Home's text is %s (want %s), data-theme %v", got, lightInk,
260 harness.Evaluate[bool](rig, `document.documentElement.hasAttribute("data-theme")`))
261 }
262 drive(t, rig, prefersScheme("dark"))
263 if got := textColour(rig, ".hello"); got != darkInk {
264 t.Errorf("System on a dark device: Home's text is %s, want %s", got, darkInk)
265 }
266 drive(t, rig, prefersScheme("light"))
267
268 // Light Home with the chat closed: the greeting, the lede, the steps,
269 // the Ask field and the apps' labels.
270 drive(t, rig, chromedp.Click(chromedp.CSS(`#ask-panel .ask-head button.close`)),
271 chromedp.Poll[chromedp.Void](`!document.querySelector("#ask-panel").checkVisibility({ visibilityProperty: true })`, chromedp.WithPollingTimeout(3*time.Second)))
272 askClosed(t, b, true)
273 checkContrast(t, rig, "Home, light", ".hello", ".lede", ".team", ".steps li", ".ask-field span", ".app-grid .label")
274 lightShot(t, rig, "home-desktop")
275 for _, tint := range []string{"teal", "violet", "mist", "amber", "rose"} {
276 iconContrast(t, rig, "Home, light", "nav.apps .tile.t-"+tint+" svg")
277 }
278 for _, sel := range []string{".base-btn", "a.me", ".ask-field", ".app-grid a.app", `.app-grid a.app[href="/store"]`} {
279 focusRing(t, rig, "Home, light", sel)
280 }
281
282 // The docked chat mid-conversation: both bubbles, the header and status.
283 drive(t, rig, chromedp.Click(chromedp.CSS(`.base-btn`)), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)),
284 chromedp.SendKeys(chromedp.CSS(`#ask-text`), "What can I do"),
285 chromedp.Click(chromedp.CSS(`#ask-panel form.composer button.send`)),
286 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)`,
287 chromedp.WithPollingTimeout(10*time.Second)),
288 chromedp.Poll[chromedp.Void](`getComputedStyle(document.querySelector("#ask-panel")).transform === "none"`, chromedp.WithPollingTimeout(3*time.Second)))
289 checkContrast(t, rig, "the panel, light", "#ask-panel .msg.person", "#ask-panel .msg.coordinator", "#ask-panel .ask-head h2")
290 lightShot(t, rig, "home-panel-open")
291
292 // Settings.
293 drive(t, rig, chromedp.EmulateViewport(1280, 800), chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form.segmented`)))
294 checkContrast(t, rig, "Settings, light", ".sheet h2", ".settings .group h3", ".rows .who", ".rows .who small", ".signout .note", "form.segmented button")
295 lightShot(t, rig, "settings")
296 for _, sel := range []string{"a.wordmark", ".crumb a.close", "form.segmented button", ".rows .btn.ghost"} {
297 focusRing(t, rig, "Settings, light", sel)
298 }
299
300 // A phone.
301 drive(t, rig, chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3)))
302 home()
303 checkContrast(t, rig, "Home on a phone, light", ".lede", ".app-grid .label")
304 lightShot(t, rig, "home-phone")
305 layoutShot(t, rig, "phone-home-light")
306 noOverflow(t, rig, "Home on a phone, light")
307 drive(t, rig, chromedp.EmulateViewport(1280, 800))
308
309 // /ask with scripts off: the same conversation as a page.
310 drive(t, rig, scriptsDisabled(true), chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(".ask-page .composer")))
311 checkContrast(t, rig, "/ask with scripts off, light", ".ask-page .msg.person", ".ask-page .msg.coordinator", ".ask-page .ask-head h2", ".crumb span")
312 lightShot(t, rig, "ask-scripts-off")
313 drive(t, rig, scriptsDisabled(false))
314
315 // The member's choice holds whatever the device says, and System gives
316 // it back. Scripts off too: it is a plain form.
317 for _, off := range []bool{false, true} {
318 drive(t, rig, scriptsDisabled(off))
319 for _, c := range []struct{ choice, device, want string }{
320 {"light", "dark", lightInk}, {"dark", "light", darkInk}, {"system", "light", lightInk}, {"system", "dark", darkInk},
321 } {
322 pressed := fmt.Sprintf(`form.segmented button[value=%q][aria-pressed="true"]`, c.choice)
323 drive(t, rig, prefersScheme(c.device), chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form.segmented`)))
324 // Already chosen (System twice running), there is nothing to submit.
325 if !harness.Evaluate[bool](rig, `!!document.querySelector(`+strconv.Quote(pressed)+`)`) {
326 drive(t, rig, chromedp.Click(chromedp.CSS(fmt.Sprintf(`form.segmented button[value=%q]`, c.choice))),
327 chromedp.WaitVisible(chromedp.CSS(pressed)))
328 }
329 home()
330 if got := textColour(rig, ".hello"); got != c.want {
331 t.Errorf("scripts off %v: %s on a %s device draws Home's text %s, want %s", off, c.choice, c.device, got, c.want)
332 }
333 }
334 }
335 drive(t, rig, scriptsDisabled(false), prefersScheme("dark"))
336 if dir := os.Getenv("BASE_LIGHT_ARTIFACTS"); dir != "" {
337 t.Logf("light screenshots in %s", filepath.Clean(dir))
338 }
339}
340
341// snapshotJS records every colour each element (and the wordmark's mark)
342// is drawn in, with transitions off so none is caught midway.
343const snapshotJS = `(() => {
344 const props = ["color", "background-color", "background-image", "border-top-color", "box-shadow", "outline-color", "stroke", "color-scheme"];
345 const out = [];
346 for (const e of [document.documentElement, ...document.querySelectorAll("body, body *")]) {
347 const s = getComputedStyle(e);
348 out.push(e.tagName + "." + e.className + " " + props.map(p => s.getPropertyValue(p)).join(" | "));
349 }
350 const w = document.querySelector(".wordmark");
351 if (w) out.push("wordmark::before " + getComputedStyle(w, "::before").backgroundImage);
352 return JSON.stringify(out);
353})()`
354
355// oldBrowserJS swaps the stylesheet for what a browser without
356// light-dark() makes of it (Safari before 17.5): the @supports block is
357// dropped, and so is any token whose value uses light-dark().
358const oldBrowserJS = `(async () => {
359 const link = document.querySelector('link[rel="stylesheet"]');
360 let css = await (await fetch(link.href)).text();
361 const head = "@supports (color: light-dark(white, black)) {";
362 for (let i; (i = css.indexOf(head)) >= 0;) {
363 let d = 0, j = i + head.length - 1;
364 for (; j < css.length; j++) { if (css[j] === "{") d++; else if (css[j] === "}" && --d === 0) break; }
365 css = css.slice(0, i) + css.slice(j + 1);
366 }
367 css = css.replace(/--[\w-]+:\s*light-dark\([^;]*;/g, "");
368 const s = new CSSStyleSheet();
369 s.replaceSync(css);
370 document.adoptedStyleSheets = [...document.adoptedStyleSheets, s];
371 link.disabled = true;
372 return true;
373})()`
374
375// A browser without light-dark() draws Base in its dark theme, every colour
376// intact, even on a light device; a member who chose Light gets it there
377// too. Each is held to what a current browser draws for that theme.
378func TestThemesWithoutLightDark(t *testing.T) {
379 apps := teamApps(t)
380 rig, _, _ := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps })
381 drive(t, rig, prefersScheme("light"))
382 for _, page := range []struct{ path, wait string }{{"/", ".hello"}, {"/settings", "form.segmented"}} {
383 snap := func(theme string, old bool) []string {
384 t.Helper()
385 // Focus out of the composer first: its glow breathes, and two
386 // loads would catch it at different breaths.
387 drive(t, rig, chromedp.Navigate(rig.Origin+page.path), chromedp.WaitVisible(chromedp.CSS(page.wait)),
388 chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`), chromedp.Evaluate[chromedp.Void](pauseJS))
389 if theme != "" {
390 drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.documentElement.dataset.theme = `+strconv.Quote(theme)))
391 }
392 if old {
393 drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
394 _, err := chromedp.Evaluate[bool](oldBrowserJS, chromedp.EvalAwaitPromise)(ctx, target)
395 return err
396 }))
397 }
398 var out []string
399 if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, snapshotJS)), &out); err != nil {
400 t.Fatal(err)
401 }
402 return out
403 }
404 for _, c := range []struct{ name, want, old string }{
405 {"System on a light device", "dark", ""},
406 {"Light chosen", "light", "light"},
407 {"Dark chosen", "dark", "dark"},
408 } {
409 want, got := snap(c.want, false), snap(c.old, true)
410 if len(want) != len(got) {
411 t.Fatalf("%s %s: %d elements, want %d", page.path, c.name, len(got), len(want))
412 }
413 bad := 0
414 for i := range want {
415 if want[i] != got[i] {
416 if bad++; bad <= 5 {
417 t.Errorf("%s, %s, without light-dark():\n got %s\n want %s", page.path, c.name, got[i], want[i])
418 }
419 }
420 }
421 if bad > 5 {
422 t.Errorf("%s, %s: %d elements differ in all", page.path, c.name, bad)
423 }
424 }
425 }
426}
427