oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package slidestest
4
5import (
6 "context"
7 "encoding/json"
8 "fmt"
9 "net/http"
10 "net/url"
11 "strings"
12 "testing"
13 "time"
14
15 "amadan.net/rastrillo/fiesta/check/rhythm"
16 "amadan.net/rastrillo/rastrillo/harness"
17 "github.com/chromedp/cdproto/emulation"
18 "github.com/chromedp/cdproto/network"
19 "github.com/chromedp/chromedp"
20)
21
22// rhythmCanvas is what the audit reads around on every screen: the
23// slide itself and the pictures of it. A slide is the deck's geometry,
24// sized in cqw against its own 16:9 frame (slides.css), not the page's,
25// so its insides are not on the page's scale and are not meant to be.
26// The editor's stage and its phone preview, the viewer's slide, the
27// presenter's slides and the strip's pictures are all that. Nothing
28// else is skipped: the editor's chrome around the stage (the bar, the
29// strip, the stage bar, the inspector card, the notes) is read.
30var rhythmCanvas = []string{
31 "[slides-slide]",
32 "[slides-thumb]",
33 "[slides-film-thumb]",
34 "[presenter-frame]",
35}
36
37// rhythmScreen is one state of one screen: where it is, what only that
38// screen draws (ready), the least number of blocks it must draw for the
39// audit to have read anything, whether page scripts run, and an
40// optional step in the page (submit a form) with what to wait for after.
41type rhythmScreen struct {
42 name, path, ready string
43 blocks int
44 noScript bool
45 act, then string
46 // at is where the browser must be when the audit reads, when it is
47 // not path (a form's POST answers at the form's action).
48 at string
49}
50
51// rhythmDrawn is how many blocks main draws outside the skipped
52// regions: an element with a box, not inline, not inside a region the
53// audit reads around. A page that drew nothing would pass the audit by
54// having nothing to measure.
55const rhythmDrawn = `((skip) => {
56 const main = document.querySelector('main');
57 if (!main) return 0;
58 let n = 0;
59 for (const el of main.querySelectorAll('*')) {
60 if (skip.some((s) => el.closest(s))) continue;
61 const cs = getComputedStyle(el);
62 if (cs.display === 'none' || cs.display === 'contents' || cs.display.startsWith('inline')) continue;
63 const r = el.getBoundingClientRect();
64 if (r.width > 0 && r.height > 0) n++;
65 }
66 return n;
67})`
68
69// stackHygiene is what the audit cannot see in a stack under main: a
70// child taken out of the flow (position: absolute or fixed, such as a
71// visually hidden live region) that the stack's sibling rule still gave
72// a margin, which moves it; and the first child in the flow carrying a
73// margin, which a stack's first block never has. That one comes from
74// the stack's rule seeing an out-of-flow or visually hidden sibling
75// before it: the audit measures nothing above a stack's first block.
76const stackHygiene = `(() => {
77 const out = [];
78 const name = (el) => el.tagName.toLowerCase() + [...el.attributes].filter((a) => a.name !== 'class' && a.name !== 'id' && !a.name.startsWith('aria-')).slice(0, 2).map((a) => '[' + a.name + ']').join('');
79 for (const stack of document.querySelectorAll('main [rst-stack], main[rst-stack]')) {
80 let first = true;
81 for (const el of stack.children) {
82 const cs = getComputedStyle(el);
83 if (cs.display === 'none' || el.matches('[type="hidden"], template, script')) continue;
84 const margin = parseFloat(cs.marginBlockStart) + parseFloat(cs.marginBlockEnd);
85 if (cs.position === 'absolute' || cs.position === 'fixed') {
86 if (margin !== 0) out.push(name(el) + ' is out of the flow of ' + name(stack) + ' with a ' + margin + 'px margin');
87 continue;
88 }
89 if (first && parseFloat(cs.marginBlockStart) !== 0) out.push(name(el) + ' opens ' + name(stack) + ' with a ' + cs.marginBlockStart + ' margin');
90 first = false;
91 }
92 }
93 return out;
94})()`
95
96// scriptsAreOn reads the parser's scripting flag the way the page sees
97// it: with scripting off, a <noscript>'s contents are parsed as markup,
98// so it has an element child; with scripting on they are text.
99const scriptsAreOn = `(() => {
100 const d = document.createElement('div');
101 d.innerHTML = '<noscript><p></p></noscript>';
102 return d.firstElementChild.childElementCount === 0;
103})()`
104
105// TestEveryScreenKeepsTheRhythm: Fiesta's rhythm audit (Paul,
106// 2026-11-22: "Can we somehow put something in place to avoid weird
107// spacing issues like this in future?") over Slides' own screens, at a
108// desktop width and a phone's: every gap between two of a page's
109// blocks is a step of the spacing scale, no text rests on a control,
110// and every heading sits closer to its own content than to what comes
111// before it. The slide is read around (rhythmCanvas); its chrome is
112// read.
113//
114// Each screen is checked to be the one asked for: the browser is still
115// at its address (a lost session lands on the sign-in door, whose
116// rhythm is not this page's) and the screen's own marker is drawn.
117// The without-script states run with scripting really off.
118//
119// Not drawn here, because nothing in this rig reaches them: the projector
120// surface (/p/{session}, the slide and nothing else); the Home member
121// choice (home_link.html, Home and team mode); the deck list's notice
122// under team mode's Unknown standing; an export refused at its start
123// (the slide cap, four running), still running, failed, or past its
124// hour. Each is markup the screens above already use: a box, a callout,
125// rastrillo's job status.
126//
127// CGO_ENABLED=0 go test -tags browser -run KeepsTheRhythm ./internal/slidestest/
128func TestEveryScreenKeepsTheRhythm(t *testing.T) {
129 rig, app := newRigApp(t, nil)
130
131 // Signed out first, on a browser with no session.
132 signedOut := []rhythmScreen{
133 {name: "the sign-in door", path: "/signin", ready: `form[action="/signin"] input[name="address"]`, blocks: 4},
134 {name: "the sign-in door, without script", path: "/signin", ready: `form[action="/signin"] input[name="address"]`, blocks: 4, noScript: true},
135 {name: "the sign-in door, refused", path: "/signin", ready: `form[action="/signin"] input[name="address"]`, blocks: 4,
136 act: `HTMLFormElement.prototype.submit.call(document.querySelector('form[action="/signin"]'))`, then: `[rst-callout], [rst-field-error]`, at: "/signin?err=address"},
137 {name: "signed out", path: "/signed-out", ready: `main a[href="/signin"], main [estilo-signed-out]`, blocks: 3},
138 }
139 for _, width := range []int64{1440, 390} {
140 for _, s := range signedOut {
141 auditRhythm(t, rig, width, s)
142 }
143 }
144
145 // Signed in, with decks enough for the list to show its shelf and
146 // its rows (the newest five are covers, the rest rows), a share
147 // link, an agent, a finished export and a talk in progress.
148 cookies := signedIn(t, app, allowedAddress)
149 edit := deckWithSlides(t, app, cookies, 3)
150 deck := strings.TrimSuffix(edit, "/edit")
151 for i := range 6 {
152 createDeck(t, app, cookies, fmt.Sprintf("Quarterly review %d", i+1))
153 }
154 empty := emptyDeck(t, app, cookies)
155 shared := mintShareLink(t, app, deck, cookies)
156 mintAgent(t, app, cookies, "rhythm")
157 status := startExport(t, app, deck, cookies, nil)
158 waitForExport(t, app, status, cookies)
159 session, token := startPresenting(t, app, deck, cookies)
160 code := sessionCode(t, app, session)
161 // An export whose layout warns: a word wider than its column.
162 warned := createDeck(t, app, cookies, "Too wide")
163 {
164 agent := mintAgent(t, app, cookies, "too-wide")
165 sqid := strings.TrimPrefix(warned, "/d/")
166 view := apiJSON(t, app, http.MethodGet, "/api/v1/decks/"+sqid, agent, "", http.StatusOK)
167 first, _ := view["slides"].([]any)[0].(map[string]any)["id"].(string)
168 apiJSON(t, app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", agent,
169 `{"ops":[{"op":"add_block","slide":`+quote(first)+`,"type":"text","region":"body","markdown":"`+strings.Repeat("Unbreakable", 12)+`"}]}`, http.StatusOK)
170 }
171 warnedStatus := startExport(t, app, warned, cookies, nil)
172 waitForExport(t, app, warnedStatus, cookies)
173 // A talk begun before positions keeps the old presenter view; its
174 // own deck, since Present on a deck already being presented resumes
175 // that talk.
176 old, oldToken := startPresenting(t, app, warned, cookies)
177 preDeploy(t, app, old)
178
179 var set []chromedp.Action[chromedp.Void]
180 for _, c := range cookies {
181 set = append(set, cdpStep(network.SetCookie, network.SetCookieParams{
182 Name: c.Name, Value: c.Value, URL: rig.Origin + "/",
183 HTTPOnly: new(c.HttpOnly), Secure: new(c.Secure), SameSite: network.CookieSameSiteLax,
184 }))
185 }
186 rig.Run(set...)
187 rig.Allow(http.MethodGet, "/no-such-page", http.StatusNotFound)
188
189 submit := func(form string) string {
190 return `HTMLFormElement.prototype.submit.call(document.querySelector(` + "`" + form + "`" + `))`
191 }
192 q := url.QueryEscape
193 signedInScreens := []rhythmScreen{
194 {name: "the deck list", path: "/", ready: `[slides-decks] [slides-shelf]`, blocks: 8},
195 {name: "the deck list, without script", path: "/", ready: `[slides-decks] [slides-shelf]`, blocks: 8, noScript: true},
196 {name: "a search", path: "/?q=" + q("Quarterly"), ready: `[slides-decks] [slides-search-clear]`, blocks: 6},
197 {name: "a search with no results", path: "/?q=" + q("nothing matches this"), ready: `[slides-decks] [rst-empty]`, blocks: 4},
198 {name: "new deck", path: "/decks/new", ready: `form[action="/decks"]`, blocks: 3},
199 // The one refusal POST /decks makes of a browser: a theme that is
200 // not one of the six, which only a hand-made request can send.
201 {name: "new deck, refused", path: "/decks/new", ready: `form[action="/decks"]`, blocks: 3,
202 act: `(f => { const i = document.createElement('input'); i.type = 'hidden'; i.name = 'theme'; i.value = 'no-such-theme'; f.prepend(i); HTMLFormElement.prototype.submit.call(f) })(document.querySelector('main form[action="/decks"]'))`,
203 then: `main [rst-callout]`, at: "/decks"},
204 {name: "the viewer", path: deck + "?slide=1", ready: `[slides-viewer] [slides-stage] [slides-slide]`, blocks: 3},
205 {name: "the viewer, without script", path: deck + "?slide=1", ready: `[slides-viewer] [slides-stage] [slides-slide]`, blocks: 3, noScript: true},
206 {name: "the shared viewer", path: "/s/" + shared, ready: `[slides-viewer] [slides-stage] [slides-slide]`, blocks: 3},
207 {name: "the notes", path: deck + "/notes", ready: `[rst-box-head] h2 a[href*="slide="]`, blocks: 6},
208 {name: "the editor", path: edit, ready: `[slides-editor] [slides-strip-item]`, blocks: 8, then: editorBound},
209 {name: "the editor, without script", path: edit, ready: `[slides-editor] noscript [rst-callout]`, blocks: 6, noScript: true},
210 {name: "the editor of an empty deck", path: empty, ready: `[slides-editor] [slides-stage-empty]`, blocks: 6},
211 {name: "export", path: deck + "/export", ready: `form[action$="/export"] input[name="notes"]`, blocks: 4},
212 {name: "an export, done", path: status, ready: `[slides-export] a[href$=".pdf"]`, blocks: 4},
213 {name: "an export, done with warnings", path: warnedStatus, ready: `[slides-export] [slides-export-warnings] li`, blocks: 6},
214 {name: "share", path: deck + "/share", ready: `[slides-share-links] [rst-list]`, blocks: 8},
215 {name: "share, a new link", path: deck + "/share?new=" + q(shared), ready: `#share-url`, blocks: 8},
216 {name: "settings", path: deck + "/settings", ready: `form input[name="title"]`, blocks: 6},
217 {name: "settings, without script", path: deck + "/settings", ready: `form input[name="title"]`, blocks: 6, noScript: true},
218 {name: "settings, refused", path: deck + "/settings", ready: `form input[name="title"]`, blocks: 6,
219 act: `document.querySelector('form input[name="title"]').value = ''; ` + submit(`main form[rst-form]`), then: `[rst-field-error]`},
220 {name: "delete", path: deck + "/delete", ready: `main form[action$="/delete"]`, blocks: 3},
221 {name: "agents", path: "/agents", ready: `form[action="/agents"] input[name="name"]`, blocks: 6},
222 {name: "agents, a new token", path: "/agents", ready: `form[action="/agents"] input[name="name"]`, blocks: 6,
223 act: `document.querySelector('form[action="/agents"] input[name="name"]').value = 'another-' + Math.floor(Math.random() * 1e6); ` + submit(`form[action="/agents"]`), then: `#agent-token`},
224 {name: "agents, refused", path: "/agents", ready: `form[action="/agents"] input[name="name"]`, blocks: 6,
225 act: submit(`form[action="/agents"]`), then: `[rst-field-error]`},
226 {name: "the Colophon", path: "/help/open-source", ready: `main [estilo-credits] h1`, blocks: 6},
227 {name: "not found", path: "/no-such-page", ready: `main [rst-error], main [estilo-error]`, blocks: 2},
228 {name: "the presenter", path: "/p/" + session + "/notes?t=" + q(token), ready: `[presenter-panel="notes"]`, blocks: 4},
229 {name: "the presenter of a talk begun before positions", path: "/p/" + old + "/notes?t=" + q(oldToken), ready: `[slides-clock] [slides-counter]`, blocks: 6},
230 {name: "the remote", path: "/p/" + session + "/remote?t=" + q(token), ready: `main form[action*="/command"], main button`, blocks: 3},
231 {name: "the remote's pairing page", path: "/r/" + code, ready: `main form`, blocks: 3},
232 {name: "the presenter's slide picker, without script", path: "/p/" + session + "/notes?pick=1&t=" + q(token), ready: `[presenter-pick-list]`, blocks: 4, noScript: true},
233 {name: "presenting in the viewer", path: deck + "?slide=1&present=1", ready: `[slides-present] [slides-pager]`, blocks: 2},
234 }
235 for _, width := range []int64{1440, 390} {
236 for _, s := range signedInScreens {
237 auditRhythm(t, rig, width, s)
238 }
239 }
240
241 // Last, because pairing retires the remote's token the screens above
242 // open: the ⋯ menu's Pair a phone, which posts into a window of its
243 // own, answered here in this one.
244 for _, width := range []int64{1440, 390} {
245 auditRhythm(t, rig, width, rhythmScreen{name: "pairing a phone", path: "/p/" + session + "/notes", ready: `form[action$="/pair"]`, blocks: 4,
246 act: `(f => { f.removeAttribute('target'); HTMLFormElement.prototype.submit.call(f) })(document.querySelector('form[action$="/pair"]'))`,
247 then: `[slides-pair] [slides-code]`, at: "/p/" + session + "/pair"})
248 }
249}
250
251// auditRhythm draws one screen state and reads the audit over main.
252// Scripts are switched back on afterwards, whatever happened.
253func auditRhythm(t *testing.T, rig *harness.Rig, width int64, s rhythmScreen) {
254 t.Helper()
255 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
256 defer cancel()
257 defer rig.Run(cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: false}))
258 steps := []chromedp.Action[chromedp.Void]{
259 cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: s.noScript}),
260 chromedp.EmulateViewport(width, 900),
261 chromedp.Navigate(rig.Origin + s.path),
262 }
263 // The server's markup, through the DOM domain, which needs no page
264 // script; a marker below the fold is still drawn.
265 steps = append(steps, chromedp.WaitReady(chromedp.CSS(s.ready)))
266 if s.act != "" {
267 // The step leaves the page (a form's POST), so what follows is
268 // polled for rather than waited on through the old document.
269 steps = append(steps, chromedp.Evaluate[chromedp.Void](s.act))
270 }
271 if s.then != "" {
272 then := s.then
273 if !strings.Contains(then, "===") {
274 then = `document.querySelector(` + "`" + then + "`" + `)`
275 }
276 steps = append(steps, waitFor(then))
277 }
278 skip, _ := json.Marshal(rhythmCanvas)
279 var at string
280 var drawn int
281 var scripts bool
282 var found []rhythm.Finding
283 var hygiene []string
284 steps = append(steps,
285 evalInto(&hygiene, stackHygiene),
286 evalInto(&at, `location.pathname + location.search`),
287 evalInto(&scripts, scriptsAreOn),
288 evalInto(&drawn, rhythmDrawn+`(`+string(skip)+`)`),
289 harness.Into(&found, chromedp.Evaluate[[]rhythm.Finding](
290 rhythm.Expression("main", rhythm.Options{Skip: rhythmCanvas}))))
291 if err := chromedp.Do(ctx, steps...); err != nil {
292 var page string
293 rig.Run(evalInto(&page, `location.pathname + location.search + ' ' + document.title + '\n' + (document.querySelector('main')?.outerHTML ?? '').slice(0, 3000)`))
294 t.Errorf("%s at %dpx: %v (at %s)", s.name, width, err, page)
295 return
296 }
297 want := s.path
298 if s.at != "" {
299 want = s.at
300 }
301 // Not the screen asked for, or not as asked: its findings would be
302 // some other page's.
303 switch {
304 case want != "*" && at != want:
305 t.Errorf("%s at %dpx: the browser is at %s, not %s", s.name, width, at, want)
306 case scripts == s.noScript:
307 t.Errorf("%s at %dpx: scripts on is %v, want %v", s.name, width, scripts, !s.noScript)
308 case drawn < s.blocks:
309 t.Errorf("%s at %dpx: main draws %d blocks outside the slide, want at least %d", s.name, width, drawn, s.blocks)
310 case len(hygiene) > 0:
311 t.Errorf("%s at %dpx: %s", s.name, width, strings.Join(hygiene, "; "))
312 case len(found) > 0:
313 t.Errorf("%s at %dpx: %d findings\n%s", s.name, width, len(found), rhythm.Report(found))
314 }
315}
316