theme: the chrome's Onest never swaps in late
Paul, 2026-10-24: "There should never be a flash of unstyled text. Ever." Onest was font-display: swap, so a first visit could paint the whole chrome in the system face and then re-render it in Onest. - font-display: optional. Onest is used if it is ready when the page first renders; otherwise the page keeps the system face for its whole life and a late Onest is never swapped in, not even into a menu opened afterwards. No script, so the door and the front page get it too. block was rejected: up to 3 s of invisible text, then the same swap. - theme.FontHead and chrome's estilo-fonts partial: a woff2 preload, then fonts.css, first in <head>. With the preload Chromium holds the first frame (about 100 ms at most) instead of painting invisible text. - FontPrefix v1 -> v2: v1's fonts.css said swap and is cached for a year as immutable. - Tests: TestOnestNeverSwapsIn (plain suite, CI) pins optional; the browser check (make test-browser, -tags browser) watches the face the chrome is actually drawn in (CSS.getPlatformFontsForNode) from the first rendered frame with the font slowed to 0, 400 ms and 3.5 s, and fails for swap and for block. make test-vet vets it with the tag.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+514
−16
AGENTS.md+7 −0Makefile+12 −1README.md+4 −1chrome/chrome_test.go+10 −0chrome/templates/fonts.html+8 −0theme/fontflash.browser.mjs+111 −0theme/fonts.go+49 −12theme/fonts_browser_test.go+267 −0theme/fonts_test.go+46 −2
CI passed — run details
diff --git a/AGENTS.md b/AGENTS.md| index 28c48f9..0f92cec 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -55,6 +55,7 @@ empty repo invites the opposite.) |
| | 6 | *(Superseded by 8.)* **Estilo's theme is `day`, unchanged — not "derived from" or "based on" it. Divergence is allowed but must be driven by a named need, not a preference** — §Theme | Restyling on the strength of "day as a base"; changing a token because it "would look better" | Paul, 2026-08-31 | |
| | 7 | **Private module path is `amadan.net/oficina/estilo.git`**, using authenticated Git and `GOPRIVATE` on every builder; checked consumer `go.sum` records integrity. Preserve this path when discovery support changes. | Public visibility solely to obtain Go metadata; local filesystem replaces; a later cosmetic module rename | Overnight coordinator, 2026-09-07; Claude Fable 5.1 branch review | |
| | 8 | **Estilo's theme is Calma, the suite's own — no longer `day`.** Every app's colour sits on one ring of equal OKLCH lightness (`theme/apps.go`); each app is themed with its own accent (`theme.ForApp`). The marks are Calma's (Fanned Oficina mark, app icons with a glow of their own hue) and the suite's ambient effect is a seeded nebula (`sky`), placed at the sign-in, the team's home and the front page, **never inside an app** — §Theme | Keeping `day` "as a base"; one hue per app chosen by eye (Mail and Files would not fit); rim light, cores and motes in the sky | Paul, 2026-09-28/29, after six rounds of design directions: *"Calma is by far the best"*; *"Grain and filaments. No cores, no rim lights. Then go."* | |
| +| 9 | **Chrome text never changes face, on a first visit or ever.** Onest is `font-display: optional` and preloaded from `<head>` (`theme.FontHead`, chrome's `estilo-fonts`): it is used if it is ready when the page first renders, and otherwise the page keeps the system face for its whole life; a late Onest is never swapped in. `TestOnestNeverSwapsIn` holds the rule in CI; `make test-browser` proves it in Chromium with the font slowed — §Theme | `swap` (a fallback face, then Onest: the flash); `block` (up to 3 s of invisible text, then the same swap); a metric-matched fallback (`size-adjust`), which is still a swap; a script gate (the door and the front page run without scripts); a system UI stack (drops Calma's typeface) | Rule: Paul, 2026-10-24 (*"There should never be a flash of unstyled text. Ever."*); mechanism: branch `fix/chrome-font-no-flash`, awaiting review | |
| **Two callers at design time is the bar for *extraction*. It says nothing |
| about *destination*.** Both consuming apps were told to propose their |
| @@ -91,6 +92,12 @@ What Calma is, and where each part lives: |
| theme: estilo.css, then its accent. The ring is a closed set. |
| - **`theme/fonts.go`** — Onest, Calma's typeface, served by |
| `theme.FontHandler`; the theme falls back to the system face without it. |
| + Every page links it with `{{template "estilo-fonts"}}` (or |
| + `theme.FontHead()`), first in `<head>`: a preload, then the stylesheet. |
| + **It never swaps** (row 9): `font-display: optional`, so a slow Onest |
| + leaves that page in the system face rather than replacing it mid-read. |
| + Changing either file's bytes, or the `@font-face`, moves `FontPrefix`'s |
| + version: both are cached for a year as immutable. |
| - **`brand/`** — the marks, generated from `icons.json` (hues must equal |
| the ring; `brand_test` checks) in web, iPhone and Mac shapes. |
| - **`sky/`** — the ambient nebula: seeded per team; its colour (haze and |
diff --git a/Makefile b/Makefile| index 2818201..e70fc39 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -1,4 +1,4 @@ |
| -.PHONY: build test test-modcache test-vet test-fmt test-build test-go |
| +.PHONY: build test test-modcache test-vet test-fmt test-build test-go test-browser |
| # CGO_ENABLED=0 for the same reason sheets-core sets it: nothing here |
| # should grow a cgo dependency by accident. estilo has no cgo-driven |
| @@ -40,8 +40,11 @@ test-modcache: |
| done; \ |
| go mod download && go mod verify |
| +# Vetted twice: the second time with the browser tag, so the browser |
| +# checks (not run here) cannot stop compiling unnoticed. |
| test-vet: |
| CGO_ENABLED=0 go vet ./... |
| + CGO_ENABLED=0 go vet -tags browser ./... |
| # Fails on unformatted files rather than rewriting them. CI must never |
| # silently "fix" a diff out from under a branch — a red test-fmt tells |
| @@ -65,3 +68,11 @@ test-build: |
| # actually having run. |
| test-go: |
| CGO_ENABLED=0 go test -count=1 ./... |
| + |
| +# The browser checks: not part of `make test` (and so not CI), because |
| +# they need a Chromium (ESTILO_CHROME, on PATH, or in a Puppeteer or |
| +# Playwright cache) and Node 22+. Today that is theme's no-flash check |
| +# for Onest (theme/fonts_browser_test.go). It runs the whole suite with |
| +# the tag. A missing browser fails it; it never skips to a pass. |
| +test-browser: |
| + CGO_ENABLED=0 go test -tags browser -count=1 ./... |
diff --git a/README.md b/README.md| index faa622d..adf3f43 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -7,7 +7,10 @@ authenticated Git and `GOPRIVATE=amadan.net/oficina/estilo.git`. |
| `theme` is Calma, the suite's look (AGENTS.md, "Theme"): `theme.CSS()` is |
| the suite's theme and `theme.ForApp(slug)` an app's, with its accent from |
| the colour ring in `theme/apps.go`. `theme.FontHandler` serves Onest, the |
| -typeface; link its `fonts.css` before the theme. `brand` holds the marks, |
| +typeface; put chrome's `{{template "estilo-fonts"}}` (or `theme.FontHead()`) |
| +first in `<head>`, before the theme. It preloads the font, which is |
| +`font-display: optional`: used if it is there when the page first renders, |
| +never swapped in later. `brand` holds the marks, |
| and `sky` the seeded nebula for the sign-in, the team's home and the front |
| page — never inside an app. |
diff --git a/chrome/chrome_test.go b/chrome/chrome_test.go| index fd3a4b2..57fda3b 100644 |
| --- a/chrome/chrome_test.go |
| +++ b/chrome/chrome_test.go |
| @@ -14,6 +14,7 @@ import ( |
| "amadan.net/oficina/estilo.git/internal/tokencheck" |
| "amadan.net/oficina/estilo.git/menu" |
| "amadan.net/oficina/estilo.git/sky" |
| + "amadan.net/oficina/estilo.git/theme" |
| "github.com/carlosframework/rastrillo/ui" |
| ) |
| @@ -555,3 +556,12 @@ func TestTheAccountCanSitAtARailsFoot(t *testing.T) { |
| t.Error("the rail trigger is rounded; an in-flow highlight is square") |
| } |
| } |
| + |
| +// estilo-fonts is theme.FontHead, byte for byte: the partial an app's |
| +// layout includes and the markup estilo's own font tests load cannot |
| +// drift apart, and a FontPrefix bump cannot leave the partial behind. |
| +func TestFontsPartialIsThemeFontHead(t *testing.T) { |
| + if got, want := render(t, "estilo-fonts", nil), string(theme.FontHead()); got != want { |
| + t.Fatalf("estilo-fonts renders\n%s\nwant theme.FontHead()\n%s", got, want) |
| + } |
| +} |
diff --git a/chrome/templates/fonts.html b/chrome/templates/fonts.html| new file mode 100644 |
| index 0000000..3fa09a6 |
| --- /dev/null |
| +++ b/chrome/templates/fonts.html |
| @@ -0,0 +1,8 @@ |
| +{{/* estilo-fonts: Onest's two <head> lines, the font's preload and then |
| + its stylesheet. No data. Put it as early in <head> as possible, right |
| + after <meta charset> and the viewport, and before every stylesheet; |
| + the preload is what gets the file there by first paint. Renders |
| + exactly theme.FontHead() (chrome_test checks), so a font version bump |
| + reaches the app with its estilo pin. */}} |
| +{{define "estilo-fonts"}}<link rel="preload" href="/static/estilo/fonts/v2/onest-latin.woff2" as="font" type="font/woff2" crossorigin> |
| +<link rel="stylesheet" href="/static/estilo/fonts/v2/fonts.css">{{end}} |
diff --git a/theme/fontflash.browser.mjs b/theme/fontflash.browser.mjs| new file mode 100644 |
| index 0000000..7110605 |
| --- /dev/null |
| +++ b/theme/fontflash.browser.mjs |
| @@ -0,0 +1,111 @@ |
| +// fontflash.browser.mjs: watch which face the chrome text is drawn in, |
| +// from the first painted frame until well after a slowed Onest arrives. |
| +// Driven by fonts_browser_test.go (go test -tags browser ./theme), which |
| +// serves the page, slows the font and makes every assertion; this file |
| +// only drives Chromium over the DevTools protocol and reports what it saw. |
| +// |
| +// node fontflash.browser.mjs <browser websocket URL> <scenarios JSON> |
| +// |
| +// Scenarios: [{name, url, watchMs, visits}]. Each runs in a fresh browser |
| +// context (an empty cache), visiting url `visits` times. For each visit: |
| +// from navigation until watchMs, every sample after the page's first |
| +// rendered frame records the platform font each probe element is drawn in |
| +// (CSS.getPlatformFontsForNode: the face the renderer actually used, not |
| +// what the CSS asked for). Then a new element is added, as a menu opened |
| +// later would be, and its face recorded too. Writes JSON to stdout. |
| +// |
| +// No dependencies: Node's own WebSocket (Node 22+). estilo has no npm. |
| + |
| +const [, , wsURL, scenariosJSON] = process.argv |
| +const scenarios = JSON.parse(scenariosJSON) |
| + |
| +const ws = new WebSocket(wsURL) |
| +let nextId = 0 |
| +const pending = new Map() |
| +ws.onmessage = (e) => { |
| + const m = JSON.parse(e.data) |
| + if (m.id && pending.has(m.id)) { |
| + const { resolve, reject, method } = pending.get(m.id) |
| + pending.delete(m.id) |
| + if (m.error) reject(new Error(method + ': ' + JSON.stringify(m.error))) |
| + else resolve(m.result) |
| + } |
| +} |
| +await new Promise((resolve, reject) => { |
| + ws.onopen = resolve |
| + ws.onerror = () => reject(new Error('cannot connect to ' + wsURL)) |
| +}) |
| +const send = (method, params = {}, sessionId) => |
| + new Promise((resolve, reject) => { |
| + const id = ++nextId |
| + pending.set(id, { resolve, reject, method }) |
| + ws.send(JSON.stringify({ id, method, params, sessionId })) |
| + }) |
| + |
| +const PROBES = ['#bar', '#nav'] |
| + |
| +async function faceOf(s, selector) { |
| + const { root } = await send('DOM.getDocument', { depth: 0 }, s) |
| + const { nodeId } = await send('DOM.querySelector', { nodeId: root.nodeId, selector }, s) |
| + if (!nodeId) return null |
| + // The probe's text node carries the fonts; asking the element works in |
| + // current Chromium, and a probe holds nothing but its text. |
| + const { fonts } = await send('CSS.getPlatformFontsForNode', { nodeId }, s) |
| + if (!fonts.length) return null |
| + // One face per probe is the expectation (Latin text, one family); keep |
| + // them all so a mixed run shows up in the report rather than hiding. |
| + return fonts.map((f) => `${f.isCustomFont ? 'web' : 'system'}:${f.familyName}`).join('+') |
| +} |
| + |
| +async function evaluate(s, expression) { |
| + const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, s) |
| + if (r.exceptionDetails) throw new Error('page threw: ' + JSON.stringify(r.exceptionDetails)) |
| + return r.result.value |
| +} |
| + |
| +const results = [] |
| +for (const sc of scenarios) { |
| + const { browserContextId } = await send('Target.createBrowserContext', { disposeOnDetach: true }) |
| + const { targetId } = await send('Target.createTarget', { url: 'about:blank', browserContextId }) |
| + const { sessionId: s } = await send('Target.attachToTarget', { targetId, flatten: true }) |
| + for (const domain of ['Page', 'DOM', 'CSS', 'Runtime']) await send(domain + '.enable', {}, s) |
| + // A frame counter from the document's first moment. requestAnimationFrame |
| + // runs only when the page renders, so a count above zero means a frame |
| + // has been produced; while Chromium holds rendering (a render-blocking |
| + // stylesheet, a preloaded optional font) it stays at zero. |
| + await send('Page.addScriptToEvaluateOnNewDocument', { |
| + source: `window.__estiloFrames = 0; requestAnimationFrame(function f() { window.__estiloFrames++; requestAnimationFrame(f) })`, |
| + }, s) |
| + |
| + const visits = [] |
| + for (let v = 0; v < sc.visits; v++) { |
| + const samples = [] |
| + const started = Date.now() |
| + await send('Page.navigate', { url: sc.url }, s) |
| + while (Date.now() - started < sc.watchMs) { |
| + let painted = false |
| + try { |
| + painted = await evaluate(s, `location.href === ${JSON.stringify(sc.url)} && window.__estiloFrames > 0`) |
| + } catch { |
| + // The old document is being torn down mid-navigation: not painted yet. |
| + } |
| + if (painted) { |
| + const sample = { t: Date.now() - started } |
| + for (const p of PROBES) sample[p] = await faceOf(s, p).catch(() => null) |
| + samples.push(sample) |
| + } |
| + await new Promise((r) => setTimeout(r, 10)) |
| + } |
| + // A menu opened after the font has (or has not) arrived. |
| + await evaluate(s, `(() => { const d = document.createElement('div'); d.id = 'late'; d.textContent = 'Rename · Duplicate · Delete'; document.body.append(d); return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))) })()`) |
| + const late = await faceOf(s, '#late') |
| + const font = await evaluate(s, `(() => { const e = performance.getEntriesByType('resource').find((r) => r.name.endsWith('.woff2')); return e ? { responseEnd: Math.round(e.responseEnd), transferSize: e.transferSize } : null })()`) |
| + visits.push({ samples, late, font }) |
| + } |
| + await send('Target.closeTarget', { targetId }) |
| + await send('Target.disposeBrowserContext', { browserContextId }).catch(() => {}) |
| + results.push({ name: sc.name, visits }) |
| +} |
| +process.stdout.write(JSON.stringify(results)) |
| +ws.close() |
| +process.exit(0) |
diff --git a/theme/fonts.go b/theme/fonts.go| index c2fd6f3..e368292 100644 |
| --- a/theme/fonts.go |
| +++ b/theme/fonts.go |
| @@ -2,6 +2,7 @@ package theme |
| import ( |
| "embed" |
| + "html/template" |
| "net/http" |
| "strings" |
| ) |
| @@ -16,31 +17,67 @@ var fontFS embed.FS |
| // FontPrefix is the URL path FontHandler serves under. Its version moves |
| // whenever either file's bytes do (a new subset, a newer Onest, a changed |
| -// unicode-range): browsers hold both for a year under this path. |
| -const FontPrefix = "/static/estilo/fonts/v1/" |
| +// unicode-range, a changed font-display): browsers hold both for a year |
| +// under this path, so a change under the same version never reaches a |
| +// returning visitor. v2: font-display moved from swap to optional. |
| +const FontPrefix = "/static/estilo/fonts/v2/" |
| + |
| +// FontStylesheet and FontFile are the two URLs FontHandler answers. Link |
| +// them with FontHead (or chrome's "estilo-fonts" template), not by hand, |
| +// so the next version bump reaches every app with its estilo pin. |
| +const ( |
| + FontStylesheet = FontPrefix + "fonts.css" |
| + FontFile = FontPrefix + "onest-latin.woff2" |
| +) |
| // fontCSS declares Onest for the Latin range; a character outside it |
| -// falls through to the system face in --rst-font, glyph by glyph. |
| -const fontCSS = `/* Onest, Calma's typeface (estilo theme/fonts.go). */ |
| +// falls through to the system face in --rst-font, glyph by glyph, and |
| +// never triggers a download. |
| +// |
| +// font-display: optional is the no-flash rule (Paul, 2026-10-24: "There |
| +// should never be a flash of unstyled text. Ever."). Onest is used only |
| +// if it is ready within the browser's short block period (about 100 ms); |
| +// otherwise the page commits to the system face for its whole life, and |
| +// a late Onest is never swapped in. With FontHead's preload the file is |
| +// requested while <head> is parsed, so on a cached or normal first visit |
| +// it is there in time, and Chromium holds the first paint for a preloaded |
| +// optional font rather than painting invisible text. swap (a fallback |
| +// face, then Onest: the flash) and block (up to 3 s of invisible text, |
| +// then the same swap) both break the rule; fonts_browser_test.go shows it. |
| +const fontCSS = `/* Onest, Calma's typeface (estilo theme/fonts.go). optional: used |
| + if ready at first paint, else the system face for the page's life; |
| + never swapped in late. */ |
| @font-face { |
| font-family: "Onest"; |
| font-style: normal; |
| font-weight: 300 800; |
| - font-display: swap; |
| - src: url("` + FontPrefix + `onest-latin.woff2") format("woff2"); |
| + font-display: optional; |
| + src: url("` + FontFile + `") format("woff2"); |
| unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; |
| } |
| ` |
| // FontCSS is the @font-face stylesheet, served by FontHandler as |
| -// FontPrefix + "fonts.css". Link it before theme.css. Without it the |
| -// theme still works, in the system face. |
| +// FontStylesheet. Link it before theme.css, through FontHead. Without it |
| +// the theme still works, in the system face. |
| func FontCSS() []byte { return []byte(fontCSS) } |
| -// FontHandler serves GET and HEAD for FontPrefix + "fonts.css" and |
| -// FontPrefix + "onest-latin.woff2". Mount it at FontPrefix; anything else |
| -// under it is 404. Public, sessionless, and the bytes never change under |
| -// a name, so both are cached for a year. |
| +// fontHead is FontHead's markup. The preload comes first so the font is |
| +// requested before any stylesheet is parsed. crossorigin is required even |
| +// on the same origin: fonts are fetched in CORS mode, and the spec only |
| +// lets a preload stand in for a request made in the same mode. |
| +const fontHead = `<link rel="preload" href="` + FontFile + `" as="font" type="font/woff2" crossorigin> |
| +<link rel="stylesheet" href="` + FontStylesheet + `">` |
| + |
| +// FontHead is the two <head> lines every page with estilo chrome carries, |
| +// as early in <head> as possible and before theme.css: the font's |
| +// preload, then its stylesheet. chrome's "estilo-fonts" template renders |
| +// exactly this. |
| +func FontHead() template.HTML { return template.HTML(fontHead) } |
| + |
| +// FontHandler serves GET and HEAD for FontStylesheet and FontFile. Mount |
| +// it at FontPrefix; anything else under it is 404. Public, sessionless, |
| +// and the bytes never change under a name, so both are cached for a year. |
| func FontHandler() http.Handler { |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| name := strings.TrimPrefix(r.URL.Path, FontPrefix) |
diff --git a/theme/fonts_browser_test.go b/theme/fonts_browser_test.go| new file mode 100644 |
| index 0000000..45fd47c |
| --- /dev/null |
| +++ b/theme/fonts_browser_test.go |
| @@ -0,0 +1,267 @@ |
| +//go:build browser |
| + |
| +// The no-flash check for the chrome's typeface, in a real Chromium. Not |
| +// part of `make test`: it needs a Chromium (ESTILO_CHROME or |
| +// RASTRILLO_CHROME, on PATH, or in a Puppeteer or Playwright cache) and |
| +// Node 22+. Run it with `make test-browser`. The gate vets this file with |
| +// the tag (make test-vet), so it cannot stop compiling unnoticed. |
| +// |
| +// Paul, 2026-10-24: "There should never be a flash of unstyled text. |
| +// Ever." A visible stretch of invisible text counts too. So the |
| +// assertion is about the face the text is drawn in, sampled from the |
| +// first painted frame on: it is one face for the page's whole life, and |
| +// a menu added after a late font arrives is drawn in that same face. |
| +package theme |
| + |
| +import ( |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// probePage is a page as an app draws it: FontHead first in <head>, then |
| +// the theme, and chrome text in --rst-font (tokens.css sets body to it; |
| +// this page does the same with no tokens.css to keep the probe small). |
| +const probePage = `<!doctype html> |
| +<html lang="en"> |
| +<head> |
| +<meta charset="utf-8"> |
| +<title>Chrome font probe</title> |
| +%s |
| +<link rel="stylesheet" href="/theme.css"> |
| +<style>body { margin: 0; font-family: var(--rst-font); } #bar { font-weight: 600; }</style> |
| +</head> |
| +<body> |
| +<header id="bar">Oficina Docs</header> |
| +<nav id="nav">Files · Shared · Settings · Sign out</nav> |
| +</body> |
| +</html> |
| +` |
| + |
| +type scenario struct { |
| + Name string `json:"name"` |
| + URL string `json:"url"` |
| + WatchMs int `json:"watchMs"` |
| + Visits int `json:"visits"` |
| + |
| + delay time.Duration |
| + fetches *atomic.Int32 |
| +} |
| + |
| +type visit struct { |
| + Samples []map[string]any `json:"samples"` |
| + Late *string `json:"late"` |
| + Font *struct { |
| + ResponseEnd float64 `json:"responseEnd"` |
| + TransferSize float64 `json:"transferSize"` |
| + } `json:"font"` |
| +} |
| + |
| +type result struct { |
| + Name string `json:"name"` |
| + Visits []visit `json:"visits"` |
| +} |
| + |
| +// serve is one origin per scenario, so no two share a cache entry, with |
| +// the font's response held for delay. |
| +func serve(t *testing.T, delay time.Duration, fetches *atomic.Int32) string { |
| + fonts := FontHandler() |
| + 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") |
| + fmt.Fprintf(w, probePage, FontHead()) |
| + }) |
| + mux.HandleFunc("GET /theme.css", func(w http.ResponseWriter, r *http.Request) { |
| + 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 r.URL.Path == FontFile { |
| + fetches.Add(1) |
| + select { |
| + case <-time.After(delay): |
| + case <-r.Context().Done(): |
| + return |
| + } |
| + } |
| + fonts.ServeHTTP(w, r) |
| + })) |
| + srv := httptest.NewServer(mux) |
| + t.Cleanup(srv.Close) |
| + return srv.URL + "/" |
| +} |
| + |
| +func findChrome(t *testing.T) string { |
| + for _, env := range []string{"ESTILO_CHROME", "RASTRILLO_CHROME"} { |
| + if p := os.Getenv(env); p != "" { |
| + return p |
| + } |
| + } |
| + for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "chrome"} { |
| + if p, err := exec.LookPath(name); err == nil { |
| + return p |
| + } |
| + } |
| + home, _ := os.UserHomeDir() |
| + var globs []string |
| + switch runtime.GOOS { |
| + case "darwin": |
| + globs = []string{ |
| + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", |
| + "/Applications/Chromium.app/Contents/MacOS/Chromium", |
| + home + "/.cache/puppeteer/chrome/*/chrome-mac*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing", |
| + home + "/Library/Caches/ms-playwright/chromium-*/chrome-mac*/Chromium.app/Contents/MacOS/Chromium", |
| + } |
| + default: |
| + globs = []string{ |
| + home + "/.cache/puppeteer/chrome/*/chrome-linux*/chrome", |
| + home + "/.cache/ms-playwright/chromium-*/chrome-linux*/chrome", |
| + } |
| + } |
| + for _, g := range globs { |
| + if m, _ := filepath.Glob(g); len(m) > 0 { |
| + return m[len(m)-1] // the newest, by the caches' version-sorted names |
| + } |
| + } |
| + // Fatal, not Skip: asking for the browser tag and getting a pass |
| + // because there was no browser is the false green this repo has |
| + // already been bitten by. |
| + t.Fatal("no Chromium found: set ESTILO_CHROME to a Chrome or Chromium binary") |
| + return "" |
| +} |
| + |
| +// launch starts a headless Chromium and returns its browser websocket. |
| +func launch(t *testing.T) string { |
| + dir := t.TempDir() |
| + args := []string{ |
| + "--headless", "--remote-debugging-port=0", "--user-data-dir=" + dir, |
| + "--no-first-run", "--no-default-browser-check", "--disable-extensions", |
| + "--disable-background-networking", "--disable-component-update", "--mute-audio", |
| + "about:blank", |
| + } |
| + if os.Getuid() == 0 { |
| + args = append(args, "--no-sandbox") |
| + } |
| + cmd := exec.Command(findChrome(t), args...) |
| + if err := cmd.Start(); err != nil { |
| + t.Fatalf("start Chromium: %v", err) |
| + } |
| + t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) |
| + for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) { |
| + b, err := os.ReadFile(filepath.Join(dir, "DevToolsActivePort")) |
| + if lines := strings.Split(strings.TrimSpace(string(b)), "\n"); err == nil && len(lines) == 2 { |
| + return "ws://127.0.0.1:" + lines[0] + lines[1] |
| + } |
| + } |
| + t.Fatal("Chromium did not open its DevTools port") |
| + return "" |
| +} |
| + |
| +// faces lists the distinct faces a visit's samples saw for one probe, in |
| +// the order they first appeared. |
| +func faces(v visit, probe string) []string { |
| + var seen []string |
| + for _, s := range v.Samples { |
| + f, _ := s[probe].(string) |
| + if f == "" { |
| + continue |
| + } |
| + if len(seen) == 0 || seen[len(seen)-1] != f { |
| + seen = append(seen, f) |
| + } |
| + } |
| + return seen |
| +} |
| + |
| +func TestChromeTextNeverChangesFace(t *testing.T) { |
| + if _, err := exec.LookPath("node"); err != nil { |
| + t.Fatal("node is required (Node 22+, for its WebSocket)") |
| + } |
| + ws := launch(t) |
| + |
| + // Delays: none (a normal first visit on a fast link); 400 ms, past |
| + // optional's ~100 ms block period but well inside block's 3 s, so a |
| + // held-invisible-then-Onest page shows as a change of face; and 3.5 s, |
| + // past block's 3 s too, so block's own late swap shows up as well. |
| + var scs []*scenario |
| + for _, c := range []struct { |
| + name string |
| + delay time.Duration |
| + }{{"fast", 0}, {"slow-400ms", 400 * time.Millisecond}, {"slow-3500ms", 3500 * time.Millisecond}} { |
| + sc := &scenario{Name: c.name, delay: c.delay, fetches: new(atomic.Int32), Visits: 2, |
| + WatchMs: int((c.delay + 1500*time.Millisecond) / time.Millisecond)} |
| + sc.URL = serve(t, sc.delay, sc.fetches) |
| + scs = append(scs, sc) |
| + } |
| + arg, _ := json.Marshal(scs) |
| + cmd := exec.Command("node", "fontflash.browser.mjs", ws, string(arg)) |
| + cmd.Stderr = os.Stderr |
| + out, err := cmd.Output() |
| + if err != nil { |
| + t.Fatalf("node fontflash.browser.mjs: %v", err) |
| + } |
| + var results []result |
| + if err := json.Unmarshal(out, &results); err != nil { |
| + t.Fatalf("driver output: %v\n%s", err, out) |
| + } |
| + |
| + for i, r := range results { |
| + sc := scs[i] |
| + for vi, v := range r.Visits { |
| + where := fmt.Sprintf("%s, visit %d", r.Name, vi+1) |
| + if len(v.Samples) < 10 { |
| + t.Errorf("%s: only %d painted samples; the watch did not see the page", where, len(v.Samples)) |
| + continue |
| + } |
| + var committed string |
| + for _, probe := range []string{"#bar", "#nav"} { |
| + seen := faces(v, probe) |
| + if len(seen) != 1 { |
| + t.Errorf("%s: %s changed face after it was painted: %s", where, probe, strings.Join(seen, " -> ")) |
| + continue |
| + } |
| + if committed == "" { |
| + committed = seen[0] |
| + } |
| + } |
| + if v.Late == nil || *v.Late != committed { |
| + got := "nothing" |
| + if v.Late != nil { |
| + got = *v.Late |
| + } |
| + t.Errorf("%s: a menu added after the font settled is drawn in %s, the page in %s", where, got, committed) |
| + } |
| + if v.Font == nil || v.Font.ResponseEnd <= 0 || v.Font.ResponseEnd > float64(sc.WatchMs) { |
| + t.Errorf("%s: the font did not arrive inside the watch (%+v), so a late swap could not have been seen", where, v.Font) |
| + } |
| + // What each visit must look like, not only that it held still: |
| + // a test where Onest never renders would otherwise pass. |
| + isOnest := strings.HasPrefix(committed, "web:Onest") |
| + switch { |
| + case vi == 1 && !isOnest: |
| + t.Errorf("%s: a return visit (font cached) is drawn in %s, not Onest", where, committed) |
| + case r.Name == "fast" && !isOnest: |
| + t.Errorf("%s: a first visit with a prompt font is drawn in %s, not Onest", where, committed) |
| + case r.Name == "slow-3500ms" && vi == 0 && isOnest: |
| + t.Errorf("%s: drawn in Onest though the font took 3.5 s; the watch cannot have started at first paint", where) |
| + } |
| + t.Logf("%s: %s, %d samples from %vms, font at %vms", where, committed, len(v.Samples), v.Samples[0]["t"], v.Font.ResponseEnd) |
| + } |
| + // One download in all: the preload is the request the @font-face |
| + // uses, and the return visit is from cache (FontHandler's |
| + // one-year immutable). |
| + if n := sc.fetches.Load(); n != 1 { |
| + t.Errorf("%s: the font was requested %d times, want 1", r.Name, n) |
| + } |
| + } |
| +} |
diff --git a/theme/fonts_test.go b/theme/fonts_test.go| index 5ed6360..e336b0e 100644 |
| --- a/theme/fonts_test.go |
| +++ b/theme/fonts_test.go |
| @@ -5,14 +5,16 @@ import ( |
| "encoding/hex" |
| "net/http" |
| "net/http/httptest" |
| + "regexp" |
| + "strings" |
| "testing" |
| ) |
| func TestFontHandlerServesOnlyItsTwoFiles(t *testing.T) { |
| h := FontHandler() |
| for path, want := range map[string]int{ |
| - FontPrefix + "fonts.css": 200, |
| - FontPrefix + "onest-latin.woff2": 200, |
| + FontStylesheet: 200, |
| + FontFile: 200, |
| FontPrefix + "onest.woff2": 404, |
| FontPrefix + "../theme/estilo.css": 404, |
| FontPrefix: 404, |
| @@ -42,3 +44,45 @@ func TestOnestIsTheRecordedFile(t *testing.T) { |
| t.Fatalf("onest-latin.woff2 is not the file credits/notices/onest-provenance.json records (sha256 %s)", got) |
| } |
| } |
| + |
| +// The no-flash rule, in the plain suite so CI holds it without a browser |
| +// (fonts_browser_test.go is the proof in one): the face is optional, |
| +// never swap, block, fallback or auto, each of which swaps Onest in late. |
| +func TestOnestNeverSwapsIn(t *testing.T) { |
| + got := regexp.MustCompile(`font-display:\s*([a-z]+)`).FindAllStringSubmatch(fontCSS, -1) |
| + if len(got) != 1 || got[0][1] != "optional" { |
| + t.Fatalf("fonts.css font-display = %v, want exactly one, optional", got) |
| + } |
| + if strings.Count(fontCSS, "@font-face") != 1 { |
| + t.Fatal("fonts.css declares more than one face; each needs the same rule and its own preload") |
| + } |
| +} |
| + |
| +// FontHead preloads the very file the @font-face names, as a CORS font |
| +// fetch (crossorigin) so the preload is the request the face uses, and |
| +// before the stylesheet. |
| +func TestFontHeadPreloadsTheFace(t *testing.T) { |
| + head := string(FontHead()) |
| + preload := `<link rel="preload" href="` + FontFile + `" as="font" type="font/woff2" crossorigin>` |
| + sheet := `<link rel="stylesheet" href="` + FontStylesheet + `">` |
| + if head != preload+"\n"+sheet { |
| + t.Fatalf("FontHead = %q, want the preload then the stylesheet", head) |
| + } |
| + if !strings.Contains(fontCSS, `url("`+FontFile+`")`) { |
| + t.Fatal("the @font-face does not use the file FontHead preloads") |
| + } |
| +} |
| + |
| +// v1's fonts.css said swap and is cached for a year as immutable; serving |
| +// the new rule under the old name would never reach a returning visitor. |
| +// The prefix moved, and the old one is not served. |
| +func TestOldFontPrefixIsGone(t *testing.T) { |
| + if FontPrefix == "/static/estilo/fonts/v1/" { |
| + t.Fatal("font-display changed without a FontPrefix bump") |
| + } |
| + rec := httptest.NewRecorder() |
| + FontHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/static/estilo/fonts/v1/fonts.css", nil)) |
| + if rec.Code != http.StatusNotFound { |
| + t.Fatalf("GET v1 fonts.css = %d, want 404", rec.Code) |
| + } |
| +} |