//go:build browser
// The no-flash check for the chrome's typeface, in real engines. Not
// part of `make test`: it needs Node 22+ and Playwright with its
// browsers (ESTILO_PLAYWRIGHT names the playwright package directory
// when it is not resolvable from here; ESTILO_BROWSERS picks engines,
// default "chromium,webkit"). Run it with `make test-browser`. The gate
// vets this file with the tag (make test-vet), so it cannot stop
// compiling unnoticed. An engine that will not launch fails the test; it
// never skips to a pass.
//
// Paul, 2026-10-24: "There should never be a flash of unstyled text.
// Ever." A visible stretch of invisible text counts too. So this looks
// at pixels, not at what the CSS asked for or what layout reported:
// every picture of the chrome text from navigation on must be either
// "nothing painted yet" or the final picture, in that order. A fallback
// face, invisible text, or text that changes after it appears, is a
// third picture, and fails. And the final picture must be the system
// UI face (AGENTS.md row 9), visibly.
//
// The detector is checked against itself every run: two pages that do
// flash (v1's Onest with font-display: swap, and the chrome with its
// text hidden for a second) must be caught, or the run fails as blind.
package theme
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"sync/atomic"
"testing"
"time"
)
// probe is chrome text as the bar and its nav draw it, in --rst-font at
// the bar's weights, on a tinted page so "painted, text invisible" can
// never look like the blank page.
const probe = `
Chrome font probe
%s
Oficina Docs
Files · Shared · Settings · Sign out
`
// production is rastrillo's default CSP, unchanged: the system face
// needs nothing from it.
const production = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
// systemStack is --rst-font spelled out, for the reference picture.
const systemStack = `system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`
type page struct {
head, css string
cssDelay time.Duration // theme.css held back this long
fontDelay time.Duration // v1's woff2 held back this long
fetched *atomic.Int32 // v1 woff2 requests
}
func serve(t *testing.T, p page) string {
fonts := FontHandler()
if p.fetched == nil {
p.fetched = new(atomic.Int32)
}
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Security-Policy", production)
fmt.Fprintf(w, probe, p.head, p.css)
})
mux.HandleFunc("GET /theme.css", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(p.cssDelay):
case <-r.Context().Done():
return
}
w.Header().Set("Content-Type", "text/css; charset=utf-8")
_, _ = w.Write(CSS())
})
mux.Handle("GET "+FontPrefix, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, ".woff2") {
p.fetched.Add(1)
select {
case <-time.After(p.fontDelay):
case <-r.Context().Done():
return
}
}
fonts.ServeHTTP(w, r)
}))
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv.URL + "/"
}
type scenario struct {
Name string `json:"name"`
URL string `json:"url"`
WatchMs int `json:"watchMs"`
flashes bool // a control: the detector must catch it
fetched *atomic.Int32 // must stay 0 for the design: nothing is downloaded
}
type observed struct {
Engine string `json:"engine"`
Version string `json:"version"`
Error string `json:"error"`
Scenarios []struct {
Name string `json:"name"`
Blank string `json:"blank"`
Final string `json:"final"`
Samples []struct {
T int `json:"t"`
H string `json:"h"`
} `json:"samples"`
Refs map[string]string `json:"refs"`
} `json:"scenarios"`
}
func TestChromeTextNeverFlashes(t *testing.T) {
if _, err := exec.LookPath("node"); err != nil {
t.Fatal("node is required (Node 22+)")
}
engines := strings.Split(os.Getenv("ESTILO_BROWSERS"), ",")
if engines[0] == "" {
engines = []string{"chromium", "webkit"}
}
v1 := ``
hide := `#probe { animation: hide 1s step-end; } @keyframes hide { from { color: transparent; } to { color: inherit; } }`
ms := func(d time.Duration) int { return int(d / time.Millisecond) }
var scs []*scenario
add := func(name string, p page, watch time.Duration, sc scenario) {
p.fetched = new(atomic.Int32)
sc.Name, sc.URL, sc.WatchMs, sc.fetched = name, serve(t, p), ms(watch), p.fetched
scs = append(scs, &sc)
}
// The design: the page with theme.css prompt, slower than optional's
// 100 ms block period, and slower than block's 3 s.
for _, d := range []time.Duration{0, 400 * time.Millisecond, 3500 * time.Millisecond} {
add(fmt.Sprintf("system UI, theme.css +%dms", ms(d)), page{cssDelay: d}, d+1500*time.Millisecond, scenario{})
}
// An app not yet adopted: its layout still links v1's fonts.css. The
// face is declared and nothing uses it, so it is never fetched.
add("system UI, page still linking v1 fonts.css", page{head: v1, fontDelay: time.Second}, 2500*time.Millisecond, scenario{})
// Controls, which do flash.
add("control: v1 Onest (swap), font +1000ms", page{head: v1, fontDelay: time.Second, css: `#probe { font-family: "Onest", var(--rst-font); }`}, 2500*time.Millisecond, scenario{flashes: true})
add("control: text hidden 1s", page{css: hide}, 2500*time.Millisecond, scenario{flashes: true})
refs := map[string]string{
"system": serve(t, page{css: `#probe { font-family: ` + systemStack + `; }`}), // the stack, spelled out
"hidden": serve(t, page{css: `#probe { color: transparent; }`}), // painted, text invisible
}
job, _ := json.Marshal(map[string]any{
"engines": engines,
"viewport": map[string]int{"width": 480, "height": 120},
"clip": map[string]int{"x": 0, "y": 0, "width": 480, "height": 56},
"scenarios": scs,
"refs": refs,
})
cmd := exec.Command("node", "fontflash.browser.mjs", string(job))
cmd.Stderr = os.Stderr
raw, err := cmd.Output()
if err != nil {
t.Fatalf("node fontflash.browser.mjs: %v", err)
}
var results []observed
if err := json.Unmarshal(raw, &results); err != nil {
t.Fatalf("driver output: %v\n%s", err, raw)
}
for _, r := range results {
if r.Error != "" {
t.Errorf("%s did not launch: %s", r.Engine, r.Error)
continue
}
for i, s := range r.Scenarios {
sc, where := scs[i], r.Engine+" "+r.Version+", "+s.Name
// A flash is any picture that is neither "not painted yet"
// nor the final one, or "not painted" again after the final
// one has shown.
var flash []string
painted, before := false, 0
for _, p := range s.Samples {
switch p.H {
case s.Blank, "none":
before++
if painted {
flash = append(flash, fmt.Sprintf("%dms blank again", p.T))
}
case s.Final:
painted = true
default:
flash = append(flash, fmt.Sprintf("%dms %s", p.T, p.H))
}
}
if len(s.Samples) < 10 {
t.Errorf("%s: only %d pictures; the watch did not see the page", where, len(s.Samples))
continue
}
if !painted {
t.Errorf("%s: the final picture never appeared during the watch", where)
}
if s.Final == s.Refs["hidden"] || s.Final == s.Blank {
t.Errorf("%s: the final picture has no visible text", where)
}
if !sc.flashes {
if s.Final != s.Refs["system"] {
t.Errorf("%s: the final picture is not the system UI face", where)
}
if n := sc.fetched.Load(); n != 0 {
t.Errorf("%s: a font was downloaded %d times; the chrome downloads none", where, n)
}
}
switch {
case sc.flashes && len(flash) == 0:
t.Errorf("%s: a page that flashes was not caught; the detector is blind", where)
case !sc.flashes && len(flash) > 0:
t.Errorf("%s: FLASH: %d of %d pictures were neither blank nor final: %s", where, len(flash), len(s.Samples), strings.Join(first(flash, 6), ", "))
}
t.Logf("%s: timeline %s", where, timeline(s.Samples, map[string]string{s.Blank: "blank", "none": "none", s.Final: "FINAL", s.Refs["system"]: "SYSTEM", s.Refs["hidden"]: "HIDDEN"}))
t.Logf("%s: %d pictures (%d before first paint, every %dms), %d off-final", where, len(s.Samples), before, s.Samples[len(s.Samples)-1].T/len(s.Samples), len(flash))
}
}
}
// timeline is the run-length sequence of pictures: "blank 0-7ms, FINAL
// 8-1500ms".
func timeline(samples []struct {
T int `json:"t"`
H string `json:"h"`
}, names map[string]string) string {
var out []string
for i := 0; i < len(samples); {
j := i
for j+1 < len(samples) && samples[j+1].H == samples[i].H {
j++
}
name := names[samples[i].H]
if name == "" {
name = samples[i].H
}
out = append(out, fmt.Sprintf("%s %d-%dms", name, samples[i].T, samples[j].T))
i = j + 1
}
return strings.Join(first(out, 12), ", ")
}
func first(s []string, n int) []string {
if len(s) > n {
return append(s[:n:n], fmt.Sprintf("... %d more", len(s)-n))
}
return s
}