oficina / estilo Public

Clone
git clone https://amadan.net/oficina/estilo

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// The door's rhythm, measured: Fiesta's rhythm audit (its check/rhythm,
4// v1.7.0, copied into testdata/rhythm.js because estilo does not require
5// Fiesta; see the Makefile's test-spacing) over the card of every door
6// page, the Colophon and the Google Drive chooser, in real engines, on a
7// desktop and a phone. It reports two blocks whose gap is not a step of
8// the spacing scale, text and a control less than --rst-sp-2 apart, a
9// heading no closer to its content than to what comes before it, and a
10// stack (rst-stack) bent out of its column or holding a fixed or
11// absolute child it does not pass over; none of these pages is an
12// rst-stack, so the last two have nothing to find here. It does not read
13// past a closed <details>' summary, nor into a list (a text block), so
14// an open Colophon entry is audited from its own root.
15//
16// Not part of `make test`: it needs Node 22+ and Playwright
17// (ESTILO_PLAYWRIGHT, ESTILO_BROWSERS as for the title check).
18// ESTILO_SHOTS=<dir> saves each page there to look at.
19package chrome
20
21import (
22 "bytes"
23 "encoding/json"
24 "fmt"
25 "html/template"
26 "net/http"
27 "net/http/httptest"
28 "os"
29 "os/exec"
30 "strings"
31 "testing"
32
33 "amadan.net/oficina/estilo.git/base"
34 "amadan.net/oficina/estilo.git/credits"
35 "amadan.net/oficina/estilo.git/googleimport"
36 "amadan.net/oficina/estilo.git/theme"
37 "github.com/carlosframework/rastrillo/ui"
38)
39
40const doorPage = `<!doctype html>
41<html lang="en">
42<head>
43<meta charset="utf-8">
44<meta name="viewport" content="width=device-width, initial-scale=1">
45<link rel="stylesheet" href="/tokens.css">
46<link rel="stylesheet" href="/theme.css">
47<link rel="stylesheet" href="/base.css">
48<link rel="stylesheet" href="/brand.css">
49<link rel="stylesheet" href="/chrome.css">
50<link rel="stylesheet" href="/credits.css">
51<link rel="stylesheet" href="/google-import.css">
52</head>
53<body>
54<main id="main" rst-page>
55%s
56</main>
57</body>
58</html>
59`
60
61type doorRhythm struct {
62 Engine string `json:"engine"`
63 Version string `json:"version"`
64 Error string `json:"error"`
65 Pages []struct {
66 Page string `json:"page"`
67 Viewport int `json:"viewport"`
68 Sizes map[string][]float64 `json:"sizes"`
69 Gaps map[string]*float64 `json:"gaps"`
70 Findings []struct {
71 Kind string `json:"kind"`
72 Gap float64 `json:"gap"`
73 Before string `json:"before"`
74 After string `json:"after"`
75 Message string `json:"message"`
76 } `json:"findings"`
77 } `json:"pages"`
78}
79
80func openCard(t *testing.T) string {
81 t.Helper()
82 open := render(t, "estilo-door-open", SignIn{Icon: "/i.svg", App: "Calendar"})
83 body := `
84 <h1 id="g-h1">Join your team</h1>
85 <p id="g-lede">Calendar keeps your team's schedule in one place.</p>
86 <h2 id="g-h2">Your details</h2>
87 <label id="g-label" for="door-name">Your name</label>
88 <input id="g-input" type="text">
89 <p id="g-hint">Shown to your team.</p>
90 <p id="g-field-hint" estilo-signin-hint>Your work address.</p>
91 <input id="g-hinted" type="email" aria-label="Email">
92 <p id="g-after-hint" estilo-signin-hint>We never show it to anyone outside the team.</p>
93 <h3 id="g-h3">Notifications</h3>
94 <p id="g-hidden" hidden>Hidden.</p>
95 <p id="g-past-hidden">After a hidden block, still close to its heading.</p>
96 <img id="door-img" src="/dot.svg" alt="">
97 <p id="g-after-img">We'll email you when someone invites you.</p>
98 <button id="door-button" type="button">Join</button>
99 <section id="g-section" estilo-signin-section><p>A section of the card's own.</p></section>`
100 return open + body + render(t, "estilo-door-close", nil)
101}
102
103// openGaps is the table, in the open card: the space above each block,
104// in CSS pixels at a 16px root.
105var openGaps = map[string]float64{
106 "#g-h1": 24, // after the brand
107 "#g-lede": 8, // after a heading
108 "#g-h2": 24, // before an h2
109 "#g-label": 8, // after a heading
110 "#g-input": 8, // an input after its label
111 "#g-hint": 12, // anything else
112 "#g-field-hint": 12, // anything else
113 "#g-hinted": 8, // an input after its hint
114 "#g-after-hint": 8, // a hint after its input
115 "#g-h3": 16, // before an h3
116 "#g-past-hidden": 8, // after a heading, past a hidden block: the gap
117 "#g-section": 24, // a section
118 "#door-img": 12, // anything else
119 "#g-after-img": 12, // anything else
120 "#door-button": 16, // before a button
121}
122
123// colophon renders estilo's Colophon (credits) with two entries, one
124// with its source and notices; open, every entry is open, as a reader
125// who opened them sees it. Closed, the page also carries an app's own
126// margin on the heading, which must not reach it.
127func colophon(t *testing.T, open bool) string {
128 t.Helper()
129 tpl := template.Must(template.ParseFS(credits.Templates(), "templates/*.html"))
130 var out bytes.Buffer
131 data := credits.PageData{Title: "Open source", MissingNoticeLabel: "No notice was found.", Components: []credits.Component{
132 {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."}}},
133 {Name: "example.org/second"},
134 }}
135 if err := tpl.ExecuteTemplate(&out, "estilo/credits", data); err != nil {
136 t.Fatal(err)
137 }
138 html := out.String()
139 if !open {
140 // An app's own rule on the heading, as Mapa's frame.css wrote
141 // one before estilo spaced the Colophon: the stack outweighs it.
142 html = `<style>[estilo-credits] > h1 { margin: 0 0 var(--rst-sp-2); } [estilo-credits] > ul { margin: 0; }</style>` + html
143 }
144 if open {
145 html = strings.ReplaceAll(html, "<details>", "<details open>")
146 }
147 return html
148}
149
150// colophonGaps is the space above each of the Colophon's blocks: the
151// list --rst-sp-2 under its heading, and in an open entry its source
152// --rst-sp-3 under the summary, a notice's name --rst-sp-3 under what
153// is above it, and the notice's text --rst-sp-2 under its name.
154var colophonGaps = map[string]float64{
155 "[estilo-credits] > ul": 8,
156 "[estilo-credits] li:first-child details > p": 12,
157 "[estilo-credits] li:first-child details > pre": 8,
158 "[estilo-credits] li:first-child details > p + pre + p": 12,
159}
160
161// chooser renders the Google Drive chooser as its script leaves it:
162// ready, the Choose button shown and the status empty; idle, the status
163// saying something under Choose (a refusal, or what was imported);
164// busy, Cancel under Choose and the status saying what is happening.
165func chooser(t *testing.T, state string) string {
166 t.Helper()
167 tpl := template.Must(template.New("root").Parse(googleimport.Template()))
168 var out bytes.Buffer
169 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")}
170 if err := tpl.ExecuteTemplate(&out, "estilo-google-import", view); err != nil {
171 t.Fatal(err)
172 }
173 html := strings.Replace(out.String(), "<span data-google-choose-wrap hidden>", "<span data-google-choose-wrap>", 1)
174 switch state {
175 case "busy":
176 html = strings.Replace(html, "<span data-google-cancel-wrap hidden>", "<span data-google-cancel-wrap>", 1)
177 html = strings.Replace(html, `aria-live="polite"></p>`, `aria-live="polite">Connecting to Google…</p>`, 1)
178 case "idle":
179 html = strings.Replace(html, `aria-live="polite"></p>`, `aria-live="polite">That file is too large to import.</p>`, 1)
180 }
181 return html
182}
183
184// chooserGaps is the space above each of the chooser's blocks: Choose
185// --rst-sp-4 under the disclosure, Cancel --rst-sp-2 under Choose, the
186// status --rst-sp-3 under the buttons.
187var chooserGaps = map[string]float64{
188 "[data-google-choose-wrap]": 16,
189 "[data-google-cancel-wrap]": 8,
190 "[data-google-status]": 12,
191}
192
193// chooserIdleGaps is the resting chooser: the status --rst-sp-3 under
194// Choose, past the hidden Cancel.
195var chooserIdleGaps = map[string]float64{
196 "[data-google-choose-wrap]": 16,
197 "[data-google-status]": 12,
198}
199
200func openGapNames() []string {
201 var names []string
202 for _, gaps := range []map[string]float64{openGaps, colophonGaps, chooserGaps} {
203 for id := range gaps {
204 names = append(names, id)
205 }
206 }
207 return names
208}
209
210// pageGaps is the table each page is held to, by page.
211var pageGaps = map[string]map[string]float64{
212 "open": openGaps,
213 "colophon": {"[estilo-credits] > ul": 8},
214 "colophon-open": colophonGaps,
215 "chooser-busy": chooserGaps,
216 "chooser-idle": chooserIdleGaps,
217}
218
219// doorPages is every page the door draws, with the states that change
220// what the card holds (a lede, an error, the notices), and an app's own
221// card drawn through estilo-door-open, holding every relation of the
222// table, a picture and a lone button. The smart door is not here: its
223// card holds rastrillo's partial, whose rhythm is rastrillo's, and
224// estilo pins a rastrillo that has none (testdata/signin-stand-in.html
225// stands in for its shape only); an app drawing it audits the real one.
226func doorPages(t *testing.T) map[string]string {
227 t.Helper()
228 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."}
229 sent := notice
230 sent.Link = &Link{Href: "/signin", Label: "Use a different email"}
231 out := notice
232 out.Heading, out.Body = "You're signed out", "You signed out of Calendar on this device."
233 out.Link = &Link{Href: "/signin", Label: "Sign in"}
234 out.Forget = &ForgetForm{Action: "/signin/forget", Label: "Forget me on this device"}
235 return map[string]string{
236 "form": render(t, "estilo-signin", SignIn{Icon: "/i.svg", App: "Calendar", Action: "/signin"}),
237 "lede": render(t, "estilo-signin", SignIn{Icon: "/i.svg", App: "Calendar", Action: "/signin", Lede: "Use the address your team invited."}),
238 "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."}),
239 "sent": render(t, "estilo-signin-sent", sent),
240 "signed-out": render(t, "estilo-signed-out", out),
241 "open": openCard(t),
242 // Not door pages, but chrome every app draws: the Colophon under
243 // Help and the Google Drive chooser, each audited from its own
244 // root (pageRoots).
245 "colophon": colophon(t, false),
246 "colophon-open": colophon(t, true),
247 "chooser-ready": chooser(t, "ready"),
248 "chooser-idle": chooser(t, "idle"),
249 "chooser-busy": chooser(t, "busy"),
250 }
251}
252
253// pageRoots is the root each page that is not a door card is audited
254// from; a door card is audited from [estilo-signin].
255var pageRoots = map[string]string{
256 "colophon": "[estilo-credits]",
257 "colophon-open": "[estilo-credits] li:first-child details",
258 "chooser-idle": "[estilo-google-import]",
259 "chooser-ready": "[estilo-google-import]",
260 "chooser-busy": "[estilo-google-import]",
261}
262
263func TestTheDoorKeepsTheRhythm(t *testing.T) {
264 if _, err := exec.LookPath("node"); err != nil {
265 t.Fatal("node is required (Node 22+)")
266 }
267 pages := doorPages(t)
268 mux := http.NewServeMux()
269 var names []string
270 for name, card := range pages {
271 names = append(names, name)
272 mux.HandleFunc("GET /"+name, func(w http.ResponseWriter, r *http.Request) {
273 w.Header().Set("Content-Type", "text/html; charset=utf-8")
274 fmt.Fprintf(w, doorPage, card)
275 })
276 }
277 brandCSS, err := os.ReadFile("../brand/brand.css")
278 if err != nil {
279 t.Fatal(err)
280 }
281 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()}
282 for path, body := range assets {
283 mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
284 w.Header().Set("Content-Type", "text/css; charset=utf-8")
285 _, _ = w.Write(body)
286 })
287 }
288 mux.HandleFunc("GET /dot.svg", func(w http.ResponseWriter, r *http.Request) {
289 w.Header().Set("Content-Type", "image/svg+xml")
290 fmt.Fprint(w, `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20"><circle cx="10" cy="10" r="10" fill="#888"/></svg>`)
291 })
292 mux.HandleFunc("GET /i.svg", func(w http.ResponseWriter, r *http.Request) {
293 w.Header().Set("Content-Type", "image/svg+xml")
294 fmt.Fprint(w, `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36"><rect width="36" height="36" rx="8" fill="#888"/></svg>`)
295 })
296 srv := httptest.NewServer(mux)
297 t.Cleanup(srv.Close)
298
299 script, err := os.ReadFile("testdata/rhythm.js")
300 if err != nil {
301 t.Fatal(err)
302 }
303 engines := strings.Split(os.Getenv("ESTILO_BROWSERS"), ",")
304 if engines[0] == "" {
305 engines = []string{"chromium", "webkit"}
306 }
307 job, _ := json.Marshal(map[string]any{
308 "origin": srv.URL, "engines": engines, "viewports": []int{1440, 390},
309 "pages": names, "root": "[estilo-signin]", "roots": pageRoots, "script": string(script),
310 "sizes": []string{"#door-img", "#door-button"},
311 "gaps": openGapNames(),
312 "shots": os.Getenv("ESTILO_SHOTS"),
313 })
314 cmd := exec.Command("node", "rhythm.browser.mjs", string(job))
315 cmd.Stderr = os.Stderr
316 raw, err := cmd.Output()
317 if err != nil {
318 t.Fatalf("node rhythm.browser.mjs: %v", err)
319 }
320 var results []doorRhythm
321 if err := json.Unmarshal(raw, &results); err != nil {
322 t.Fatalf("driver output: %v\n%s", err, raw)
323 }
324 if len(results) != len(engines) {
325 t.Fatalf("%d engines asked for, %d reported", len(engines), len(results))
326 }
327 for _, r := range results {
328 if r.Error != "" {
329 t.Errorf("%s did not run: %s", r.Engine, r.Error)
330 continue
331 }
332 if len(r.Pages) != 2*len(names) {
333 t.Errorf("%s audited %d pages, want %d", r.Engine, len(r.Pages), 2*len(names))
334 }
335 for _, p := range r.Pages {
336 var report bytes.Buffer
337 for _, f := range p.Findings {
338 fmt.Fprintf(&report, "\n\t%s: %s\n\t\tabove: %s\n\t\tbelow: %s", f.Kind, f.Message, f.Before, f.After)
339 }
340 if report.Len() > 0 {
341 t.Errorf("%s %s, %s at %dpx:%s", r.Engine, r.Version, p.Page, p.Viewport, report.String())
342 }
343 for id, want := range pageGaps[p.Page] {
344 got := p.Gaps[id]
345 switch {
346 case got == nil:
347 t.Errorf("%s, %s's %s at %dpx: not measured", r.Engine, p.Page, id, p.Viewport)
348 case *got < want-0.5 || *got > want+0.5:
349 t.Errorf("%s, %s's %s at %dpx: %.1fpx above it, want %vpx", r.Engine, p.Page, id, p.Viewport, *got, want)
350 }
351 }
352 if p.Page != "open" {
353 continue
354 }
355 // A column stretches its children; a picture and a lone
356 // button keep their own width.
357 if img := p.Sizes["#door-img"]; len(img) != 2 || img[0] != 20 || img[1] != 20 {
358 t.Errorf("%s, the card's 20x20 picture at %dpx is %v", r.Engine, p.Viewport, img)
359 }
360 if b := p.Sizes["#door-button"]; len(b) != 2 || b[0] > 200 {
361 t.Errorf("%s, the card's lone button at %dpx is %v wide: stretched across the card", r.Engine, p.Viewport, b)
362 }
363 }
364 }
365}
366