//go:build browser
// The door's rhythm, measured: Fiesta's rhythm audit (its check/rhythm,
// v1.7.0, copied into testdata/rhythm.js because estilo does not require
// Fiesta; see the Makefile's test-spacing) over the card of every door
// page, the Colophon and the Google Drive chooser, in real engines, on a
// desktop and a phone. It reports two blocks whose gap is not a step of
// the spacing scale, text and a control less than --rst-sp-2 apart, a
// heading no closer to its content than to what comes before it, and a
// stack (rst-stack) bent out of its column or holding a fixed or
// absolute child it does not pass over; none of these pages is an
// rst-stack, so the last two have nothing to find here. It does not read
// past a closed ' summary, nor into a list (a text block), so
// an open Colophon entry is audited from its own root.
//
// Not part of `make test`: it needs Node 22+ and Playwright
// (ESTILO_PLAYWRIGHT, ESTILO_BROWSERS as for the title check).
// ESTILO_SHOTS= saves each page there to look at.
package chrome
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"amadan.net/oficina/estilo.git/base"
"amadan.net/oficina/estilo.git/credits"
"amadan.net/oficina/estilo.git/googleimport"
"amadan.net/oficina/estilo.git/theme"
"github.com/carlosframework/rastrillo/ui"
)
const doorPage = `
%s
`
type doorRhythm struct {
Engine string `json:"engine"`
Version string `json:"version"`
Error string `json:"error"`
Pages []struct {
Page string `json:"page"`
Viewport int `json:"viewport"`
Sizes map[string][]float64 `json:"sizes"`
Gaps map[string]*float64 `json:"gaps"`
Findings []struct {
Kind string `json:"kind"`
Gap float64 `json:"gap"`
Before string `json:"before"`
After string `json:"after"`
Message string `json:"message"`
} `json:"findings"`
} `json:"pages"`
}
func openCard(t *testing.T) string {
t.Helper()
open := render(t, "estilo-door-open", SignIn{Icon: "/i.svg", App: "Calendar"})
body := `
Join your team
Calendar keeps your team's schedule in one place.
Your details
Shown to your team.
Your work address.
We never show it to anyone outside the team.
Notifications
Hidden.
After a hidden block, still close to its heading.
We'll email you when someone invites you.
A section of the card's own.
`
return open + body + render(t, "estilo-door-close", nil)
}
// openGaps is the table, in the open card: the space above each block,
// in CSS pixels at a 16px root.
var openGaps = map[string]float64{
"#g-h1": 24, // after the brand
"#g-lede": 8, // after a heading
"#g-h2": 24, // before an h2
"#g-label": 8, // after a heading
"#g-input": 8, // an input after its label
"#g-hint": 12, // anything else
"#g-field-hint": 12, // anything else
"#g-hinted": 8, // an input after its hint
"#g-after-hint": 8, // a hint after its input
"#g-h3": 16, // before an h3
"#g-past-hidden": 8, // after a heading, past a hidden block: the gap
"#g-section": 24, // a section
"#door-img": 12, // anything else
"#g-after-img": 12, // anything else
"#door-button": 16, // before a button
}
// colophon renders estilo's Colophon (credits) with two entries, one
// with its source and notices; open, every entry is open, as a reader
// who opened them sees it. Closed, the page also carries an app's own
// margin on the heading, which must not reach it.
func colophon(t *testing.T, open bool) string {
t.Helper()
tpl := template.Must(template.ParseFS(credits.Templates(), "templates/*.html"))
var out bytes.Buffer
data := credits.PageData{Title: "Open source", MissingNoticeLabel: "No notice was found.", Components: []credits.Component{
{Name: "example.org/first", Version: "v1.2.3", SourceURL: "https://example.org/first", Notices: []credits.Notice{{Name: "LICENSE", Text: "Copyright the authors.\nPermission is granted."}, {Name: "NOTICE", Text: "Built with care."}}},
{Name: "example.org/second"},
}}
if err := tpl.ExecuteTemplate(&out, "estilo/credits", data); err != nil {
t.Fatal(err)
}
html := out.String()
if !open {
// An app's own rule on the heading, as Mapa's frame.css wrote
// one before estilo spaced the Colophon: the stack outweighs it.
html = `` + html
}
if open {
html = strings.ReplaceAll(html, "", "")
}
return html
}
// colophonGaps is the space above each of the Colophon's blocks: the
// list --rst-sp-2 under its heading, and in an open entry its source
// --rst-sp-3 under the summary, a notice's name --rst-sp-3 under what
// is above it, and the notice's text --rst-sp-2 under its name.
var colophonGaps = map[string]float64{
"[estilo-credits] > ul": 8,
"[estilo-credits] li:first-child details > p": 12,
"[estilo-credits] li:first-child details > pre": 8,
"[estilo-credits] li:first-child details > p + pre + p": 12,
}
// chooser renders the Google Drive chooser as its script leaves it:
// ready, the Choose button shown and the status empty; idle, the status
// saying something under Choose (a refusal, or what was imported);
// busy, Cancel under Choose and the status saying what is happening.
func chooser(t *testing.T, state string) string {
t.Helper()
tpl := template.Must(template.New("root").Parse(googleimport.Template()))
var out bytes.Buffer
view := googleimport.View{Config: googleimport.Config{ClientID: "123456789-client.apps.googleusercontent.com", APIKey: "AIzaPublicBrowserKey123456789", AppID: "123456789"}, Kind: googleimport.Docs, FormID: "upload", InputID: "file", Labels: googleimport.Text("en")}
if err := tpl.ExecuteTemplate(&out, "estilo-google-import", view); err != nil {
t.Fatal(err)
}
html := strings.Replace(out.String(), "", "", 1)
switch state {
case "busy":
html = strings.Replace(html, "", "", 1)
html = strings.Replace(html, `aria-live="polite">
`, `aria-live="polite">Connecting to Google…`, 1)
case "idle":
html = strings.Replace(html, `aria-live="polite">`, `aria-live="polite">That file is too large to import.`, 1)
}
return html
}
// chooserGaps is the space above each of the chooser's blocks: Choose
// --rst-sp-4 under the disclosure, Cancel --rst-sp-2 under Choose, the
// status --rst-sp-3 under the buttons.
var chooserGaps = map[string]float64{
"[data-google-choose-wrap]": 16,
"[data-google-cancel-wrap]": 8,
"[data-google-status]": 12,
}
// chooserIdleGaps is the resting chooser: the status --rst-sp-3 under
// Choose, past the hidden Cancel.
var chooserIdleGaps = map[string]float64{
"[data-google-choose-wrap]": 16,
"[data-google-status]": 12,
}
func openGapNames() []string {
var names []string
for _, gaps := range []map[string]float64{openGaps, colophonGaps, chooserGaps} {
for id := range gaps {
names = append(names, id)
}
}
return names
}
// pageGaps is the table each page is held to, by page.
var pageGaps = map[string]map[string]float64{
"open": openGaps,
"colophon": {"[estilo-credits] > ul": 8},
"colophon-open": colophonGaps,
"chooser-busy": chooserGaps,
"chooser-idle": chooserIdleGaps,
}
// doorPages is every page the door draws, with the states that change
// what the card holds (a lede, an error, the notices), and an app's own
// card drawn through estilo-door-open, holding every relation of the
// table, a picture and a lone button. The smart door is not here: its
// card holds rastrillo's partial, whose rhythm is rastrillo's, and
// estilo pins a rastrillo that has none (testdata/signin-stand-in.html
// stands in for its shape only); an app drawing it audits the real one.
func doorPages(t *testing.T) map[string]string {
t.Helper()
notice := SignInNotice{Icon: "/i.svg", App: "Calendar", Heading: "Check your email", Body: "We sent a link to ada@example.com. It works once and expires soon."}
sent := notice
sent.Link = &Link{Href: "/signin", Label: "Use a different email"}
out := notice
out.Heading, out.Body = "You're signed out", "You signed out of Calendar on this device."
out.Link = &Link{Href: "/signin", Label: "Sign in"}
out.Forget = &ForgetForm{Action: "/signin/forget", Label: "Forget me on this device"}
return map[string]string{
"form": render(t, "estilo-signin", SignIn{Icon: "/i.svg", App: "Calendar", Action: "/signin"}),
"lede": render(t, "estilo-signin", SignIn{Icon: "/i.svg", App: "Calendar", Action: "/signin", Lede: "Use the address your team invited."}),
"error": render(t, "estilo-signin", SignIn{Icon: "/i.svg", App: "Calendar", Action: "/signin", Lede: "Use the address your team invited.", Error: "That link has expired.", Address: "ada@", AddressError: "That doesn't look like an email address."}),
"sent": render(t, "estilo-signin-sent", sent),
"signed-out": render(t, "estilo-signed-out", out),
"open": openCard(t),
// Not door pages, but chrome every app draws: the Colophon under
// Help and the Google Drive chooser, each audited from its own
// root (pageRoots).
"colophon": colophon(t, false),
"colophon-open": colophon(t, true),
"chooser-ready": chooser(t, "ready"),
"chooser-idle": chooser(t, "idle"),
"chooser-busy": chooser(t, "busy"),
}
}
// pageRoots is the root each page that is not a door card is audited
// from; a door card is audited from [estilo-signin].
var pageRoots = map[string]string{
"colophon": "[estilo-credits]",
"colophon-open": "[estilo-credits] li:first-child details",
"chooser-idle": "[estilo-google-import]",
"chooser-ready": "[estilo-google-import]",
"chooser-busy": "[estilo-google-import]",
}
func TestTheDoorKeepsTheRhythm(t *testing.T) {
if _, err := exec.LookPath("node"); err != nil {
t.Fatal("node is required (Node 22+)")
}
pages := doorPages(t)
mux := http.NewServeMux()
var names []string
for name, card := range pages {
names = append(names, name)
mux.HandleFunc("GET /"+name, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, doorPage, card)
})
}
brandCSS, err := os.ReadFile("../brand/brand.css")
if err != nil {
t.Fatal(err)
}
assets := map[string][]byte{"/tokens.css": ui.TokensCSS(), "/theme.css": theme.CSS(), "/base.css": base.CSS(), "/brand.css": brandCSS, "/chrome.css": CSS(), "/credits.css": credits.CSS(), "/google-import.css": googleimport.CSS()}
for path, body := range assets {
mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css; charset=utf-8")
_, _ = w.Write(body)
})
}
mux.HandleFunc("GET /dot.svg", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/svg+xml")
fmt.Fprint(w, ``)
})
mux.HandleFunc("GET /i.svg", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/svg+xml")
fmt.Fprint(w, ``)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
script, err := os.ReadFile("testdata/rhythm.js")
if err != nil {
t.Fatal(err)
}
engines := strings.Split(os.Getenv("ESTILO_BROWSERS"), ",")
if engines[0] == "" {
engines = []string{"chromium", "webkit"}
}
job, _ := json.Marshal(map[string]any{
"origin": srv.URL, "engines": engines, "viewports": []int{1440, 390},
"pages": names, "root": "[estilo-signin]", "roots": pageRoots, "script": string(script),
"sizes": []string{"#door-img", "#door-button"},
"gaps": openGapNames(),
"shots": os.Getenv("ESTILO_SHOTS"),
})
cmd := exec.Command("node", "rhythm.browser.mjs", string(job))
cmd.Stderr = os.Stderr
raw, err := cmd.Output()
if err != nil {
t.Fatalf("node rhythm.browser.mjs: %v", err)
}
var results []doorRhythm
if err := json.Unmarshal(raw, &results); err != nil {
t.Fatalf("driver output: %v\n%s", err, raw)
}
if len(results) != len(engines) {
t.Fatalf("%d engines asked for, %d reported", len(engines), len(results))
}
for _, r := range results {
if r.Error != "" {
t.Errorf("%s did not run: %s", r.Engine, r.Error)
continue
}
if len(r.Pages) != 2*len(names) {
t.Errorf("%s audited %d pages, want %d", r.Engine, len(r.Pages), 2*len(names))
}
for _, p := range r.Pages {
var report bytes.Buffer
for _, f := range p.Findings {
fmt.Fprintf(&report, "\n\t%s: %s\n\t\tabove: %s\n\t\tbelow: %s", f.Kind, f.Message, f.Before, f.After)
}
if report.Len() > 0 {
t.Errorf("%s %s, %s at %dpx:%s", r.Engine, r.Version, p.Page, p.Viewport, report.String())
}
for id, want := range pageGaps[p.Page] {
got := p.Gaps[id]
switch {
case got == nil:
t.Errorf("%s, %s's %s at %dpx: not measured", r.Engine, p.Page, id, p.Viewport)
case *got < want-0.5 || *got > want+0.5:
t.Errorf("%s, %s's %s at %dpx: %.1fpx above it, want %vpx", r.Engine, p.Page, id, p.Viewport, *got, want)
}
}
if p.Page != "open" {
continue
}
// A column stretches its children; a picture and a lone
// button keep their own width.
if img := p.Sizes["#door-img"]; len(img) != 2 || img[0] != 20 || img[1] != 20 {
t.Errorf("%s, the card's 20x20 picture at %dpx is %v", r.Engine, p.Viewport, img)
}
if b := p.Sizes["#door-button"]; len(b) != 2 || b[0] > 200 {
t.Errorf("%s, the card's lone button at %dpx is %v wide: stretched across the card", r.Engine, p.Viewport, b)
}
}
}
}