//go:build browser package browsertest import ( "bytes" "context" "encoding/json" "fmt" "image/png" "math" "os" "path/filepath" "regexp" "strconv" "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" ) // prefersScheme emulates the device's light or dark setting. func prefersScheme(scheme string) chromedp.Action[chromedp.Void] { 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}}}) return err }) } // lightShot saves what is on screen to BASE_LIGHT_ARTIFACTS, when set. func lightShot(t *testing.T, rig *harness.Rig, name string) { t.Helper() dir := os.Getenv("BASE_LIGHT_ARTIFACTS") if dir == "" { return } t.Setenv("BASE_BROWSER_ARTIFACTS", dir) viewportShot(t, rig, name) } type textBox struct { Label string X, Y, W, H, Size float64 Color string } var rgbRE = regexp.MustCompile(`rgba?\(([\d.]+),? ([\d.]+),? ([\d.]+)`) func luminance(r, g, b float64) float64 { ch := func(v float64) float64 { v /= 255 if v <= 0.03928 { return v / 12.92 } return math.Pow((v+0.055)/1.055, 2.4) } return 0.2126*ch(r) + 0.7152*ch(g) + 0.0722*ch(b) } // textContrast measures, for each visible element matching sel, the // contrast of its computed text colour against the pixels right behind its // glyphs, as the page is drawn at that moment (fog, glass and all). With // animations paused it takes one screenshot with the text and one without // (descendants with their own colour, such as a step's tick, stay drawn in // both): the pixels that differ are the glyphs, and the second shot has // what lies behind them. It returns the worst element's ratio and the ratio // that element needs (3 for large text). func textContrast(t *testing.T, rig *harness.Rig, sel string) (worst, need float64, where string) { t.Helper() return contrastOf(t, rig, sel, "color", 0) } // pauseJS stops the page's animations and transitions (a constructed // stylesheet, which the page's CSP allows), so two screenshots differ only // in what a check changes. const pauseJS = `(() => { const s = new CSSStyleSheet(); s.replaceSync("*, *::before, *::after { animation-play-state: paused !important; transition: none !important; caret-color: transparent !important; }"); document.adoptedStyleSheets = [...document.adoptedStyleSheets, s]; window.__pause = s; })()` const unpauseJS = `document.adoptedStyleSheets = document.adoptedStyleSheets.filter(s => s !== window.__pause)` // contrastOf is textContrast for any colour an element draws: prop is the // CSS property (color, stroke, outline-color) it hides to find the pixels // that colour paints. need 0 means text: 4.5, or 3 when large; anything // else (an icon, a focus ring) needs what it is given. func contrastOf(t *testing.T, rig *harness.Rig, sel, prop string, minimum float64) (worst, need float64, where string) { t.Helper() drive(t, rig, chromedp.Evaluate[chromedp.Void](pauseJS), chromedp.Sleep(100*time.Millisecond)) with := harness.Read(rig, chromedp.CaptureScreenshot()) var boxes []textBox if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `((sel, prop) => { const out = []; for (const e of document.querySelectorAll(sel)) { let r = e.getBoundingClientRect(); if (!e.checkVisibility() || (prop === "color" && !e.textContent.trim()) || r.bottom <= 0 || r.top >= innerHeight || r.width === 0) continue; const s = getComputedStyle(e); if (prop === "outline-color") { // the ring lies outside the box const o = parseFloat(s.outlineOffset) + parseFloat(s.outlineWidth) + 2; r = {left: r.left - o, top: r.top - o, width: r.width + 2 * o, height: r.height + 2 * o}; } 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, Size: parseFloat(s.fontSize) * (parseInt(s.fontWeight) >= 700 ? 1.33 : 1), Color: s.getPropertyValue(prop)}); e.dataset.contrast = "1"; e.style.setProperty(prop, "transparent", "important"); } return JSON.stringify(out); })(`+strconv.Quote(sel)+`, `+strconv.Quote(prop)+`)`)), &boxes); 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("[data-contrast]").forEach(e => { e.style.removeProperty(`+strconv.Quote(prop)+`); delete e.dataset.contrast; }), `+unpauseJS)) if len(boxes) == 0 { t.Fatalf("nothing on screen matches %s", sel) } 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) } worst, need = math.Inf(1), 4.5 measured := 0 for _, box := range boxes { m := rgbRE.FindStringSubmatch(box.Color) if m == nil { t.Fatalf("%s: colour %q", box.Label, box.Color) } r, _ := strconv.ParseFloat(m[1], 64) g, _ := strconv.ParseFloat(m[2], 64) bl, _ := strconv.ParseFloat(m[3], 64) fg := luminance(r, g, bl) lo, glyphs := math.Inf(1), 0 for y := max(0, int(box.Y*dpr)); y < int((box.Y+box.H)*dpr); y++ { for x := max(0, int(box.X*dpr)); x < int((box.X+box.W)*dpr); 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) < 48 { continue // not a glyph } glyphs++ l := luminance(float64(br>>8), float64(bg>>8), float64(bb>>8)) lo = math.Min(lo, (math.Max(fg, l)+0.05)/(math.Min(fg, l)+0.05)) } } if glyphs == 0 { continue // below the fold, or drawn the same either way } measured++ n := minimum if n == 0 { n = 4.5 if box.Size >= 24 { n = 3 } } if lo/n < worst/need { worst, need, where = lo, n, box.Label } } if measured == 0 { t.Fatalf("%s: nothing drawn in %s", sel, prop) } return worst, need, where } // diff is how far apart two 16-bit channels are, in 8-bit steps. func diff(a, b uint32) int { d := int(a>>8) - int(b>>8) if d < 0 { return -d } return d } // checkContrast holds each selector's text to AA at this moment and again // a few seconds on, when the fog has moved. func checkContrast(t *testing.T, rig *harness.Rig, when string, sels ...string) { t.Helper() for moment := range 2 { if moment > 0 { drive(t, rig, chromedp.Sleep(4*time.Second)) } for _, sel := range sels { worst, need, where := textContrast(t, rig, sel) t.Logf("%s, moment %d: %s worst %.2f (%q, needs %.1f)", when, moment+1, sel, worst, where, need) if worst < need { t.Errorf("%s, moment %d: %s %q has contrast %.2f, needs %.1f", when, moment+1, sel, where, worst, need) } } } } // focusRing tabs until focus is on the first element matching sel and holds // its focus ring to 3:1 against what lies behind it. func focusRing(t *testing.T, rig *harness.Rig, when, sel string) { t.Helper() drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`)) for range 40 { drive(t, rig, chromedp.KeyEvent("\t")) if harness.Evaluate[bool](rig, `document.activeElement.matches(`+strconv.Quote(sel)+`)`) { break } } if !harness.Evaluate[bool](rig, `document.activeElement.matches(`+strconv.Quote(sel)+`) && document.activeElement.matches(":focus-visible")`) { t.Fatalf("%s: the keyboard never reached %s", when, sel) } worst, need, where := contrastOf(t, rig, ":focus-visible", "outline-color", 3) t.Logf("%s: focus ring on %s %.2f (%q)", when, sel, worst, where) if worst < need { t.Errorf("%s: the focus ring on %s %q has contrast %.2f, needs %.1f", when, sel, where, worst, need) } } // iconContrast holds the tiles' line icons to 3:1 against their tint. func iconContrast(t *testing.T, rig *harness.Rig, when, sel string) { t.Helper() worst, need, where := contrastOf(t, rig, sel, "stroke", 3) t.Logf("%s: icons %s worst %.2f (%q)", when, sel, worst, where) if worst < need { t.Errorf("%s: the icon in %q has contrast %.2f, needs %.1f", when, where, worst, need) } } // textColour is el's computed colour. func textColour(rig *harness.Rig, sel string) string { return harness.Evaluate[string](rig, `getComputedStyle(document.querySelector(`+strconv.Quote(sel)+`)).color`) } const ( lightInk = "rgb(30, 36, 64)" // #1E2440 darkInk = "rgb(238, 242, 248)" // #EEF2F8 ) // Base follows the device's light or dark setting until the member picks // one in Settings; light mode's text passes AA over the moving fog. func TestLightMode(t *testing.T) { apps := teamApps(t) rig, _, b := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps }) installAll(t, b) // every tile tint on Home home := func() { t.Helper() drive(t, rig, chromedp.Navigate(rig.Origin+"/"), chromedp.WaitVisible(chromedp.CSS(".hello"))) } // System: the device decides. drive(t, rig, chromedp.EmulateViewport(1280, 800), prefersScheme("light")) home() if got := textColour(rig, ".hello"); got != lightInk || harness.Evaluate[bool](rig, `document.documentElement.hasAttribute("data-theme")`) { t.Fatalf("System on a light device: Home's text is %s (want %s), data-theme %v", got, lightInk, harness.Evaluate[bool](rig, `document.documentElement.hasAttribute("data-theme")`)) } drive(t, rig, prefersScheme("dark")) if got := textColour(rig, ".hello"); got != darkInk { t.Errorf("System on a dark device: Home's text is %s, want %s", got, darkInk) } drive(t, rig, prefersScheme("light")) // Light Home with the chat closed: the greeting, the lede, the steps, // the Ask field and the apps' labels. 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, light", ".hello", ".lede", ".team", ".steps li", ".ask-field span", ".app-grid .label") lightShot(t, rig, "home-desktop") for _, tint := range []string{"teal", "violet", "mist", "amber", "rose"} { iconContrast(t, rig, "Home, light", "nav.apps .tile.t-"+tint+" svg") } for _, sel := range []string{".base-btn", "a.me", ".ask-field", ".app-grid a.app", `.app-grid a.app[href="/store"]`} { focusRing(t, rig, "Home, light", sel) } // The docked chat mid-conversation: both bubbles, the header and status. drive(t, rig, chromedp.Click(chromedp.CSS(`.base-btn`)), chromedp.Poll[chromedp.Void](settledJS, chromedp.WithPollingTimeout(3*time.Second)), 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)), chromedp.Poll[chromedp.Void](`getComputedStyle(document.querySelector("#ask-panel")).transform === "none"`, chromedp.WithPollingTimeout(3*time.Second))) checkContrast(t, rig, "the panel, light", "#ask-panel .msg.person", "#ask-panel .msg.coordinator", "#ask-panel .ask-head h2") lightShot(t, rig, "home-panel-open") // Settings. drive(t, rig, chromedp.EmulateViewport(1280, 800), chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form.segmented`))) checkContrast(t, rig, "Settings, light", ".sheet h2", ".settings .group h3", ".rows .who", ".rows .who small", ".signout .note", "form.segmented button") lightShot(t, rig, "settings") for _, sel := range []string{"a.wordmark", ".crumb a.close", "form.segmented button", ".rows .btn.ghost"} { focusRing(t, rig, "Settings, light", sel) } // A phone. drive(t, rig, chromedp.EmulateViewport(390, 844, chromedp.EmulateMobile, chromedp.EmulateScale(3))) home() checkContrast(t, rig, "Home on a phone, light", ".lede", ".app-grid .label") lightShot(t, rig, "home-phone") layoutShot(t, rig, "phone-home-light") noOverflow(t, rig, "Home on a phone, light") drive(t, rig, chromedp.EmulateViewport(1280, 800)) // /ask with scripts off: the same conversation as a page. drive(t, rig, scriptsDisabled(true), chromedp.Navigate(rig.Origin+"/ask"), chromedp.WaitVisible(chromedp.CSS(".ask-page .composer"))) checkContrast(t, rig, "/ask with scripts off, light", ".ask-page .msg.person", ".ask-page .msg.coordinator", ".ask-page .ask-head h2", ".crumb span") lightShot(t, rig, "ask-scripts-off") drive(t, rig, scriptsDisabled(false)) // The member's choice holds whatever the device says, and System gives // it back. Scripts off too: it is a plain form. for _, off := range []bool{false, true} { drive(t, rig, scriptsDisabled(off)) for _, c := range []struct{ choice, device, want string }{ {"light", "dark", lightInk}, {"dark", "light", darkInk}, {"system", "light", lightInk}, {"system", "dark", darkInk}, } { pressed := fmt.Sprintf(`form.segmented button[value=%q][aria-pressed="true"]`, c.choice) drive(t, rig, prefersScheme(c.device), chromedp.Navigate(rig.Origin+"/settings"), chromedp.WaitVisible(chromedp.CSS(`form.segmented`))) // Already chosen (System twice running), there is nothing to submit. if !harness.Evaluate[bool](rig, `!!document.querySelector(`+strconv.Quote(pressed)+`)`) { drive(t, rig, chromedp.Click(chromedp.CSS(fmt.Sprintf(`form.segmented button[value=%q]`, c.choice))), chromedp.WaitVisible(chromedp.CSS(pressed))) } home() if got := textColour(rig, ".hello"); got != c.want { 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) } } } drive(t, rig, scriptsDisabled(false), prefersScheme("dark")) if dir := os.Getenv("BASE_LIGHT_ARTIFACTS"); dir != "" { t.Logf("light screenshots in %s", filepath.Clean(dir)) } } // snapshotJS records every colour each element (and the wordmark's mark) // is drawn in, with transitions off so none is caught midway. const snapshotJS = `(() => { const props = ["color", "background-color", "background-image", "border-top-color", "box-shadow", "outline-color", "stroke", "color-scheme"]; const out = []; for (const e of [document.documentElement, ...document.querySelectorAll("body, body *")]) { const s = getComputedStyle(e); out.push(e.tagName + "." + e.className + " " + props.map(p => s.getPropertyValue(p)).join(" | ")); } const w = document.querySelector(".wordmark"); if (w) out.push("wordmark::before " + getComputedStyle(w, "::before").backgroundImage); return JSON.stringify(out); })()` // oldBrowserJS swaps the stylesheet for what a browser without // light-dark() makes of it (Safari before 17.5): the @supports block is // dropped, and so is any token whose value uses light-dark(). const oldBrowserJS = `(async () => { const link = document.querySelector('link[rel="stylesheet"]'); let css = await (await fetch(link.href)).text(); const head = "@supports (color: light-dark(white, black)) {"; for (let i; (i = css.indexOf(head)) >= 0;) { let d = 0, j = i + head.length - 1; for (; j < css.length; j++) { if (css[j] === "{") d++; else if (css[j] === "}" && --d === 0) break; } css = css.slice(0, i) + css.slice(j + 1); } css = css.replace(/--[\w-]+:\s*light-dark\([^;]*;/g, ""); const s = new CSSStyleSheet(); s.replaceSync(css); document.adoptedStyleSheets = [...document.adoptedStyleSheets, s]; link.disabled = true; return true; })()` // A browser without light-dark() draws Base in its dark theme, every colour // intact, even on a light device; a member who chose Light gets it there // too. Each is held to what a current browser draws for that theme. func TestThemesWithoutLightDark(t *testing.T) { apps := teamApps(t) rig, _, _ := askBaseWith(t, func(c *config.Config) { c.OficinaApps = apps }) drive(t, rig, prefersScheme("light")) for _, page := range []struct{ path, wait string }{{"/", ".hello"}, {"/settings", "form.segmented"}} { snap := func(theme string, old bool) []string { t.Helper() // Focus out of the composer first: its glow breathes, and two // loads would catch it at different breaths. drive(t, rig, chromedp.Navigate(rig.Origin+page.path), chromedp.WaitVisible(chromedp.CSS(page.wait)), chromedp.Evaluate[chromedp.Void](`document.activeElement.blur()`), chromedp.Evaluate[chromedp.Void](pauseJS)) if theme != "" { drive(t, rig, chromedp.Evaluate[chromedp.Void](`document.documentElement.dataset.theme = `+strconv.Quote(theme))) } if old { drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := chromedp.Evaluate[bool](oldBrowserJS, chromedp.EvalAwaitPromise)(ctx, target) return err })) } var out []string if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, snapshotJS)), &out); err != nil { t.Fatal(err) } return out } for _, c := range []struct{ name, want, old string }{ {"System on a light device", "dark", ""}, {"Light chosen", "light", "light"}, {"Dark chosen", "dark", "dark"}, } { want, got := snap(c.want, false), snap(c.old, true) if len(want) != len(got) { t.Fatalf("%s %s: %d elements, want %d", page.path, c.name, len(got), len(want)) } bad := 0 for i := range want { if want[i] != got[i] { if bad++; bad <= 5 { t.Errorf("%s, %s, without light-dark():\n got %s\n want %s", page.path, c.name, got[i], want[i]) } } } if bad > 5 { t.Errorf("%s, %s: %d elements differ in all", page.path, c.name, bad) } } } }