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
3// The font checks in a real Chromium, through the production serving
4// stack (rastrillo.Handler with Slides' own ServeOptions, CSP included),
5// with the font files slowed or refused on the way out:
6//
7// RASTRILLO_CHROME=… go test -tags browser -run Font ./internal/slidestest/
8//
9// Paul, 2026-10-26: "No flashing, ever!" Text in one face and then
10// another, a visible gap of invisible text, and a layout that moves
11// after the page is shown all count. Every check here samples the page
12// on every animation frame and every DOM change, from before the first
13// byte of HTML is parsed, and fails on any sample where slide text is
14// visible in a face that has not loaded, any run of text seen in two
15// faces, and any slide whose layout differs from the one it was first
16// shown with.
17//
18// The probe reads only what any page has: the computed font-family of
19// each run and the faces in document.fonts. So it judges the code on
20// main (faces declared in slides.css with font-display: swap) by the
21// same rule as the gate, and fails it.
22package slidestest
23
24import (
25 "bytes"
26 "context"
27 "encoding/json"
28 "fmt"
29 "html"
30 "image/png"
31 "io"
32 "log/slog"
33 "math"
34 "net/http"
35 "os"
36 "os/exec"
37 "path/filepath"
38 "regexp"
39 "sort"
40 "strings"
41 "sync"
42 "sync/atomic"
43 "testing"
44 "time"
45
46 "amadan.net/rastrillo/rastrillo"
47 "amadan.net/rastrillo/rastrillo/blobs"
48 "amadan.net/rastrillo/rastrillo/db"
49 "amadan.net/rastrillo/rastrillo/harness"
50 "github.com/chromedp/cdproto/cdp"
51 "github.com/chromedp/cdproto/emulation"
52 "github.com/chromedp/cdproto/input"
53 "github.com/chromedp/cdproto/network"
54 "github.com/chromedp/cdproto/page"
55 cdpruntime "github.com/chromedp/cdproto/runtime"
56 "github.com/chromedp/chromedp"
57
58 slides "amadan.net/oficina/slides/internal/slides"
59 "amadan.net/oficina/slides/internal/slides/fonts"
60)
61
62// fontRig is Slides behind its production serving stack, with every
63// font file (/static/fonts/*.woff2, and a deck's own under
64// {base}/fonts/{ref}) held for slow before it is served
65// when its path contains match, any path containing blocked answered
66// 404, and the editor bundle held for editorDelay. It is signed in, in
67// the browser and as an agent for the API.
68type fontRig struct {
69 rig *harness.Rig
70 app *testApp
71 cookies []*http.Cookie
72 token string
73
74 slow atomic.Int64
75 match atomic.Value
76 blocked atomic.Value
77 editorDelay atomic.Int64
78 // wrap, when set, answers every request in place of the rig's own
79 // handling, which it is handed as next: a check can hold a request,
80 // or cut a stream, on the way out.
81 wrap atomic.Pointer[func(w http.ResponseWriter, r *http.Request, next http.Handler)]
82
83 mu sync.Mutex
84 fontHits map[string]int
85}
86
87func newFontRig(t *testing.T) *fontRig {
88 t.Helper()
89 return newFontRigWith(t, nil)
90}
91
92// newFontRigWith is newFontRig with an object store, so a deck can hold
93// pictures.
94func newFontRigWith(t *testing.T, store blobs.Store) *fontRig {
95 t.Helper()
96 fr := &fontRig{fontHits: map[string]int{}}
97 fr.match.Store("")
98 fr.blocked.Store("")
99 mailer := &fakeMailer{}
100 fr.rig = harness.New(t, func(origin string) http.Handler {
101 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
102 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
103 if err != nil {
104 t.Fatalf("db.Open: %v", err)
105 }
106 t.Cleanup(func() { d.Close() })
107 mux, a, err := slides.New(d, slides.Config{
108 KeymailServers: testKeymailServers,
109 Origin: origin,
110 InstanceKey: testInstanceKey,
111 Mailer: mailer,
112 AllowedAddresses: []string{allowedAddress},
113 Blobs: store,
114 Logger: logger,
115 })
116 if err != nil {
117 t.Fatalf("slides.New: %v", err)
118 }
119 t.Cleanup(func() { a.Close() })
120 mailer.flush = a.FlushMail
121 served, closeFn, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux))
122 if err != nil {
123 t.Fatalf("rastrillo.Handler: %v", err)
124 }
125 t.Cleanup(func() { _ = closeFn() })
126 fr.app = &testApp{Handler: served, mailer: mailer, db: d, mux: mux, app: a}
127 var rest http.Handler
128 outer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
129 if wrap := fr.wrap.Load(); wrap != nil {
130 (*wrap)(w, r, rest)
131 return
132 }
133 rest.ServeHTTP(w, r)
134 })
135 rest = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
136 if b := fr.blocked.Load().(string); b != "" && strings.Contains(r.URL.Path, b) {
137 http.NotFound(w, r)
138 return
139 }
140 // The bundle, not editor.css: holding the stylesheet would hold
141 // the first paint, which is not what a late editor is.
142 if strings.HasPrefix(r.URL.Path, "/static/editor.") && strings.HasSuffix(r.URL.Path, ".js") {
143 time.Sleep(time.Duration(fr.editorDelay.Load()))
144 }
145 if strings.HasPrefix(r.URL.Path, "/static/fonts/") || uploadedFaceURL.MatchString(r.URL.Path) {
146 fr.mu.Lock()
147 fr.fontHits[r.URL.Path]++
148 fr.mu.Unlock()
149 if strings.Contains(r.URL.Path, fr.match.Load().(string)) {
150 time.Sleep(time.Duration(fr.slow.Load()))
151 }
152 }
153 served.ServeHTTP(w, r)
154 })
155 return outer
156 })
157 fr.cookies = signedIn(t, fr.app, allowedAddress)
158 fr.token = mintAgent(t, fr.app, fr.cookies, "fonts")
159 var set []chromedp.Action[chromedp.Void]
160 for _, c := range fr.cookies {
161 set = append(set, cdpStep(network.SetCookie, network.SetCookieParams{
162 Name: c.Name, Value: c.Value, URL: fr.rig.Origin + "/",
163 HTTPOnly: new(c.HttpOnly), Secure: new(c.Secure), SameSite: network.CookieSameSiteLax,
164 }))
165 }
166 set = append(set, cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 900, DeviceScaleFactor: 1, Mobile: false}),
167 // No HTTP cache between checks: each one is a first visit, which
168 // is when the fonts have to come over the network.
169 cdpStep(network.SetCacheDisabled, network.SetCacheDisabledParams{CacheDisabled: true}),
170 cdpStep(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: probeJS}))
171 fr.rig.Run(set...)
172 return fr
173}
174
175// deck makes a deck over the API holding exactly what ops says: the
176// first slide every new deck is given is removed in the same batch.
177func (fr *fontRig) deck(t *testing.T, title, ops string) string {
178 t.Helper()
179 sqid := apiDeck(t, fr.app, fr.token, title)
180 view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
181 var remove []string
182 if s, ok := view["slides"].([]any); ok {
183 for _, x := range s {
184 if id, _ := x.(map[string]any)["id"].(string); id != "" {
185 remove = append(remove, `{"op":"remove_slide","id":"`+id+`"}`)
186 }
187 }
188 }
189 body := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(ops), "["), "]"))
190 if body != "" {
191 remove = append(remove, body)
192 }
193 fr.ops(t, sqid, "["+strings.Join(remove, ",")+"]")
194 return sqid
195}
196
197// ops applies a batch over the API, as a collaborator's agent would.
198func (fr *fontRig) ops(t *testing.T, sqid, batch string) {
199 t.Helper()
200 apiJSON(t, fr.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", fr.token, `{"ops":`+batch+`}`, http.StatusOK)
201}
202
203func (fr *fontRig) hits(path string) int {
204 fr.mu.Lock()
205 defer fr.mu.Unlock()
206 n := 0
207 for p, c := range fr.fontHits {
208 if strings.Contains(p, path) {
209 n += c
210 }
211 }
212 return n
213}
214
215// navigate goes to path without waiting for the load event, which waits
216// for every font the page has started fetching: a check of what happens
217// while a font is slow must be able to act while it is.
218func (fr *fontRig) navigate(path string) chromedp.Action[chromedp.Void] {
219 return cdpStep(page.Navigate, page.NavigateParams{URL: fr.rig.Origin + path})
220}
221
222// shown waits until a slide is on screen: the hold is off (or there was
223// none) and a slide is visible.
224func (fr *fontRig) shown(t *testing.T) {
225 t.Helper()
226 fr.rig.Run(chromedp.Poll[chromedp.Void](`(() => { const s = document.querySelector('[slides-slide]');
227 return !!s && getComputedStyle(s).visibility === 'visible' && document.documentElement.getAttribute('data-slides-fonts') !== 'pending' })()`, chromedp.WithPollingTimeout(15*time.Second)))
228}
229
230func (fr *fontRig) eval(t *testing.T, js string, out any) {
231 t.Helper()
232 fr.rig.Run(evalValue(out, js, func(p *cdpruntime.EvaluateParams) { p.AwaitPromise = new(true) }))
233}
234
235// probeJS runs before the page's own HTML. On every frame and every DOM
236// change it looks at every run of slide text that is visible, works out
237// for each Liberation family its stack names (and each family named, in
238// lower case, in window.__fontProbeExtra: a deck's uploaded families)
239// whether that family has a face in document.fonts in the run's weight
240// and slope and whether it has loaded, and records a violation if a
241// face the run can be drawn in
242// is in the set but not loaded (drawn in a fallback while it loads, or
243// invisible). It records every distinct face a run has been seen in, so
244// a check can say a run never changed face; the slides' layout, every
245// time it changes after text is first visible; and any frame on which
246// slide text that had been visible was gone.
247const probeJS = `(() => {
248 const LIB = new Set(['liberation sans', 'liberation serif', 'liberation mono']);
249 const log = { violations: [], seen: {}, firstVisible: null, samples: 0, layouts: [], gaps: [], families: {}, errors: [] };
250 window.__fontProbe = log;
251 // A rejection nobody handled, or an uncaught error, is a failure too:
252 // a refusal that threw stalled every collaborator's change after it
253 // while the page looked fine (Astra, #27).
254 addEventListener('unhandledrejection', (e) => log.errors.push('unhandled rejection: ' + String((e.reason && (e.reason.stack || e.reason.message)) || e.reason)));
255 addEventListener('error', (e) => log.errors.push('uncaught: ' + e.message));
256 const names = (stack) => stack.split(',').map((p) => p.trim().replace(/^["']+|["']+$/g, '')).filter(Boolean);
257 const bucket = (w) => (Number(w) >= 600 ? 700 : 400);
258 const stateOf = (family, weight, style) => {
259 const faces = [...document.fonts].filter((f) => f.family.replace(/["']/g, '').toLowerCase() === family);
260 if (!faces.length) return 'system';
261 const exact = faces.filter((f) => f.style === style && bucket(f.weight) === bucket(weight));
262 const pick = exact.length ? exact : faces;
263 return pick.some((f) => f.status === 'loaded') ? 'web' : 'pending';
264 };
265 window.__fontState = stateOf;
266 let lastLayout = null;
267 let wasVisible = false;
268 // Nothing is painted before the first frame (a page's stylesheets
269 // block rendering), so a DOM change before it is a state nobody saw.
270 let rendering = false;
271 const hash = (s) => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h * 33) ^ s.charCodeAt(i)) >>> 0; return h.toString(16) + ':' + s.length; };
272 const sample = (why) => {
273 if (why === 'frame') rendering = true;
274 if (!rendering) return;
275 const slides = [...document.querySelectorAll('[slides-slide]')];
276 if (!slides.length) return;
277 log.samples++;
278 let visible = 0;
279 const parts = [];
280 for (const s of slides) {
281 const sr = s.getBoundingClientRect();
282 const w = document.createTreeWalker(s, NodeFilter.SHOW_TEXT);
283 for (let n = w.nextNode(); n; n = w.nextNode()) {
284 if (!n.data.trim()) continue;
285 const el = n.parentElement;
286 const cs = getComputedStyle(el);
287 if (cs.visibility !== 'visible') continue;
288 const range = document.createRange();
289 range.selectNodeContents(n);
290 const r = range.getBoundingClientRect();
291 if (!r.width && !r.height) continue;
292 visible++;
293 if (log.firstVisible === null) log.firstVisible = performance.now();
294 const fams = names(cs.fontFamily).map((x) => x.toLowerCase()).filter((x) => LIB.has(x) || (window.__fontProbeExtra || []).includes(x));
295 const states = fams.map((f) => f + ':' + stateOf(f, cs.fontWeight, cs.fontStyle));
296 for (const f of fams) log.families[f] = true;
297 const block = el.closest('[data-id]');
298 const key = n.data.trim().slice(0, 32) + '@' + (block ? block.getAttribute('data-id') : '');
299 const desc = (states.join(',') || 'system:' + (names(cs.fontFamily)[0] || '')) + ' ' + bucket(cs.fontWeight) + ' ' + cs.fontStyle;
300 (log.seen[key] = log.seen[key] || {})[desc] = true;
301 for (const st of states) {
302 if (st.endsWith(':pending')) {
303 log.violations.push(Math.round(performance.now()) + 'ms ' + why + ': "' + key + '" visible in ' + st + ' ' + cs.fontWeight + ' ' + cs.fontStyle + ' before it loaded [fonts=' + document.documentElement.getAttribute('data-slides-fonts') + ']');
304 }
305 }
306 }
307 // The layout: each block's box and the box of all its text (the
308 // union of its text's own boxes), relative to its slide. Per
309 // block rather than per text node, and the text's boxes rather
310 // than its elements', so the editor drawing a block's text in
311 // elements of its own (a <div> per line) is no change while the
312 // picture is the same; a face that changes moves the text.
313 const round = (b) => [b.left - sr.left, b.top - sr.top, b.width, b.height].map((v) => Math.round(v * 2) / 2).join(',');
314 for (const b of s.querySelectorAll('[slides-block]')) {
315 if (getComputedStyle(b).visibility !== 'visible') continue;
316 let box = null;
317 const tw = document.createTreeWalker(b, NodeFilter.SHOW_TEXT);
318 for (let t = tw.nextNode(); t; t = tw.nextNode()) {
319 if (!t.data.trim()) continue;
320 const range = document.createRange();
321 range.selectNodeContents(t);
322 for (const r of range.getClientRects()) {
323 if (!r.width && !r.height) continue;
324 box = box ? { left: Math.min(box.left, r.left), top: Math.min(box.top, r.top), right: Math.max(box.right, r.right), bottom: Math.max(box.bottom, r.bottom) }
325 : { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
326 }
327 }
328 const text = box ? round({ left: box.left, top: box.top, width: box.right - box.left, height: box.bottom - box.top }) : '-';
329 parts.push((b.getAttribute('data-id') || b.getAttribute('data-block')) + '=' + round(b.getBoundingClientRect()) + ';' + text);
330 }
331 }
332 if (why !== 'frame') return;
333 if (visible) {
334 wasVisible = true;
335 const sig = hash(parts.join('|'));
336 if (sig !== lastLayout) {
337 log.layouts.push({ ms: Math.round(performance.now()), sig });
338 lastLayout = sig;
339 }
340 } else if (wasVisible) {
341 log.gaps.push(Math.round(performance.now()));
342 }
343 };
344 const frame = () => { sample('frame'); requestAnimationFrame(frame); };
345 requestAnimationFrame(frame);
346 new MutationObserver(() => sample('mutation')).observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
347})()`
348
349type probe struct {
350 Violations []string `json:"violations"`
351 Seen map[string]map[string]bool `json:"seen"`
352 FirstVisible *float64 `json:"firstVisible"`
353 Samples int `json:"samples"`
354 Layouts []struct {
355 Ms int `json:"ms"`
356 Sig string `json:"sig"`
357 } `json:"layouts"`
358 Gaps []int `json:"gaps"`
359 Families map[string]bool `json:"families"`
360 Errors []string `json:"errors"`
361}
362
363func (fr *fontRig) probe(t *testing.T) probe {
364 t.Helper()
365 var raw string
366 fr.rig.Run(evalInto(&raw, `JSON.stringify(window.__fontProbe)`))
367 var p probe
368 if err := json.Unmarshal([]byte(raw), &p); err != nil {
369 t.Fatalf("probe: %v (%s)", err, raw)
370 }
371 if p.Samples < 10 {
372 t.Fatalf("the probe sampled the page %d times; it cannot see what it is checking", p.Samples)
373 }
374 return p
375}
376
377// clean fails on any violation, any run seen in two faces, and any
378// frame on which visible slide text went missing. It returns the probe.
379func (fr *fontRig) clean(t *testing.T) probe {
380 t.Helper()
381 return fr.cleanWith(t, false)
382}
383
384// cleanAcross is clean for a check whose subject is a change of family —
385// a theme, a font, a code mark: a run may be seen in more than one face
386// so long as every one of them is a web face that had loaded, which is
387// the change, and not the fallback on the way to it.
388func (fr *fontRig) cleanAcross(t *testing.T) probe {
389 t.Helper()
390 return fr.cleanWith(t, true)
391}
392
393func (fr *fontRig) cleanWith(t *testing.T, across bool) probe {
394 t.Helper()
395 p := fr.probe(t)
396 for i, v := range p.Violations {
397 if i == 3 {
398 t.Errorf("…and %d more", len(p.Violations)-3)
399 break
400 }
401 t.Error(v)
402 }
403 for run, faces := range p.Seen {
404 if len(faces) == 1 {
405 continue
406 }
407 // A web face that had loaded, or a system face the deck itself
408 // chose (its stack names no Liberation family): either is a face
409 // somebody asked for. A Liberation family in its fallback, or in
410 // a face still loading, is not.
411 allWeb := true
412 for f := range faces {
413 chosen := strings.HasPrefix(f, "system:")
414 allWeb = allWeb && (chosen || strings.Contains(f, ":web")) && !inFallback.MatchString(f) && !strings.Contains(f, ":pending")
415 }
416 if !across || !allWeb {
417 t.Errorf("%q was shown in more than one face: %v", run, sortedKeys(faces))
418 }
419 }
420 if len(p.Gaps) > 0 {
421 t.Errorf("slide text was on screen, then gone, at %v ms", p.Gaps)
422 }
423 for _, e := range p.Errors {
424 t.Errorf("the page: %s", e)
425 }
426 if p.FirstVisible == nil {
427 t.Error("no slide text was ever visible")
428 }
429 return p
430}
431
432// sameLayout fails unless the slides kept the layout they were first
433// shown with.
434func sameLayout(t *testing.T, p probe) {
435 t.Helper()
436 if len(p.Layouts) > 1 {
437 t.Errorf("the slide was shown, then its layout changed %d times (at %v)", len(p.Layouts)-1, p.Layouts)
438 }
439}
440
441func sortedKeys(m map[string]bool) []string {
442 out := make([]string, 0, len(m))
443 for k := range m {
444 out = append(out, k)
445 }
446 sort.Strings(out)
447 return out
448}
449
450// webEverywhere fails unless every face every run was seen in is a web
451// face: nothing committed, nothing in a system face.
452func webEverywhere(t *testing.T, p probe) {
453 t.Helper()
454 for run, faces := range p.Seen {
455 for f := range faces {
456 if inFallback.MatchString(f) {
457 t.Errorf("%q was shown in %s, though its fonts arrived in time", run, f)
458 }
459 }
460 }
461}
462
463// decks the checks use. paper sets headings in Liberation Serif and
464// everything else in Liberation Sans; a code block or a code mark brings
465// in Liberation Mono.
466const (
467 paperDeck = `[{"op":"set_meta","theme":"paper","title":"Paper"},
468 {"op":"add_slide","id":"slideone0001","layout":"flow","template":"title-body"},
469 {"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"A heading in serif"},
470 {"op":"add_block","slide":"slideone0001","id":"text00000001","type":"text","region":"body","markdown":"Body **bold** and *italic* text, with ` + "`code`" + ` in it, long enough to wrap across the slide at least once or twice."},
471 {"op":"add_slide","id":"slidetwo0002","layout":"flow","template":"title-body"},
472 {"op":"add_block","slide":"slidetwo0002","id":"head00000002","type":"heading","region":"heading","props":{"level":2},"markdown":"Second"},
473 {"op":"add_block","slide":"slidetwo0002","id":"code00000002","type":"code","region":"body","markdown":"func main() {\n\tprintln(1)\n}"}]`
474 inkDeck = `[{"op":"set_meta","theme":"ink","title":"Ink"},
475 {"op":"add_slide","id":"slideone0001","layout":"flow","template":"title-body"},
476 {"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"Ink heading"},
477 {"op":"add_block","slide":"slideone0001","id":"text00000001","type":"text","region":"body","markdown":"Plain body text, nothing in code, **bold** and *italic*."},
478 {"op":"add_slide","id":"slidetwo0002","layout":"flow","template":"title-body"},
479 {"op":"add_block","slide":"slidetwo0002","id":"head00000002","type":"heading","region":"heading","props":{"level":2},"markdown":"Second slide"}]`
480)
481
482// Slide text is not painted before its fonts are ready. Every font file
483// is held for 700 ms, well under the gate's deadline, so the right
484// answer is: nothing visible until every face of every family the deck
485// uses has loaded, then the text, once, in those faces.
486func TestFontSlideTextIsNotPaintedBeforeItsFontsAreReady(t *testing.T) {
487 fr := newFontRig(t)
488 sqid := fr.deck(t, "Faces", paperDeck)
489 fr.slow.Store(int64(700 * time.Millisecond))
490 start := time.Now()
491 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
492 fr.shown(t)
493 if waited := time.Since(start); waited < 650*time.Millisecond {
494 t.Fatalf("the slide was shown %v after navigating, before the fonts could have arrived: the slowdown did not apply", waited)
495 }
496 fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
497 p := fr.clean(t)
498 webEverywhere(t, p)
499 sameLayout(t, p)
500 for _, f := range []string{"liberation sans", "liberation serif", "liberation mono"} {
501 if !p.Families[f] {
502 t.Errorf("no run was seen in %s; the deck is meant to use all three", f)
503 }
504 }
505}
506
507// Past the deadline the gate commits: the slide appears with that
508// family in its system fallback and stays in it when the files finally
509// arrive. Shown once, never swapped, and the layout it was shown with
510// is the one it keeps.
511func TestFontALateFamilyCommitsToItsFallbackAndNeverSwaps(t *testing.T) {
512 fr := newFontRig(t)
513 sqid := fr.deck(t, "Late", paperDeck)
514 // Serif alone is late: slowing every file would hold all six of this
515 // HTTP/1.1 server's connections and keep the gate's own script from
516 // arriving before the deadline.
517 fr.match.Store("LiberationSerif-")
518 fr.slow.Store(int64(4 * time.Second))
519 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
520 fr.shown(t)
521 // Let the late files land, and keep sampling while they do.
522 fr.rig.Run(chromedp.Sleep(4 * time.Second))
523 if n := fr.hits("LiberationSerif-"); n == 0 {
524 t.Fatal("Liberation Serif was never requested, so this cannot show it was not swapped in")
525 }
526 p := fr.clean(t)
527 sameLayout(t, p)
528 serif := false
529 for run, faces := range p.Seen {
530 for f := range faces {
531 if strings.Contains(f, "liberation serif:web") {
532 t.Errorf("%q is in the web serif, which arrived after the page was shown", run)
533 }
534 serif = serif || strings.Contains(f, "liberation serif")
535 }
536 }
537 if !serif {
538 t.Error("no run was seen in the heading's stack; the check saw nothing")
539 }
540}
541
542// The first reveal is the final layout, on every surface that draws a
543// slide in the deck's faces: the viewer at a desktop and at a phone
544// width, its scriptless presenting mode, the projector, the audience's
545// follow view, and the editor — with the editor in time, and with it
546// so late that the slide is shown before it mounts.
547func TestFontTheFirstRevealIsTheFinalLayout(t *testing.T) {
548 for _, c := range []struct {
549 name string
550 path func(fr *fontRig, sqid string) string
551 width int64
552 editorDelay time.Duration
553 after time.Duration
554 }{
555 {name: "viewer", path: func(_ *fontRig, s string) string { return "/d/" + s + "?slide=1" }},
556 {name: "viewer at a phone width", path: func(_ *fontRig, s string) string { return "/d/" + s + "?vp=phone" }, width: 390},
557 {name: "viewer presenting", path: func(_ *fontRig, s string) string { return "/d/" + s + "?present=1&slide=2" }},
558 {name: "projector", path: func(fr *fontRig, s string) string {
559 session, _ := startPresenting(t, fr.app, "/d/"+s, fr.cookies)
560 return "/p/" + session
561 }},
562 {name: "follow view", path: func(fr *fontRig, s string) string {
563 share := "/s/" + mintShareLink(t, fr.app, "/d/"+s, fr.cookies)
564 startPresenting(t, fr.app, "/d/"+s, fr.cookies)
565 return share + "?follow=1"
566 }, after: 6 * time.Second},
567 {name: "editor in time", path: func(_ *fontRig, s string) string { return "/d/" + s + "/edit" }},
568 {name: "editor late", path: func(_ *fontRig, s string) string { return "/d/" + s + "/edit" }, editorDelay: 5 * time.Second, after: 6 * time.Second},
569 } {
570 t.Run(c.name, func(t *testing.T) {
571 fr := newFontRig(t)
572 sqid := fr.deck(t, "Reveal", paperDeck)
573 if c.width > 0 {
574 fr.rig.Run(cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: c.width, Height: 800, DeviceScaleFactor: 1, Mobile: true}))
575 }
576 path := c.path(fr, sqid)
577 fr.slow.Store(int64(500 * time.Millisecond))
578 fr.editorDelay.Store(int64(c.editorDelay))
579 fr.rig.Run(fr.navigate(path))
580 fr.shown(t)
581 after := c.after
582 if after == 0 {
583 after = 2 * time.Second
584 }
585 fr.rig.Run(chromedp.Sleep(after))
586 if c.editorDelay > 0 {
587 var bound bool
588 fr.eval(t, `!!document.querySelector('[slides-stage] [contenteditable="true"]')`, &bound)
589 if !bound {
590 t.Fatal("the late editor never mounted, so this cannot show its mount moved nothing")
591 }
592 }
593 p := fr.clean(t)
594 sameLayout(t, p)
595 })
596 }
597}
598
599// If the font gate's script never arrives, the slides are still shown,
600// in their system faces, and never change face. If the hold itself never
601// arrives, nothing is held at all.
602func TestFontAMissingScriptNeverHidesTheSlides(t *testing.T) {
603 for _, c := range []struct {
604 blocked string
605 path string
606 wait time.Duration
607 }{
608 {"/static/fontsgate.", "", 7 * time.Second},
609 {"/static/fontsgate.", "/edit", 3 * time.Second},
610 {"/static/fontshold.", "", 2 * time.Second},
611 {"/static/fontshold.", "/edit", 3 * time.Second},
612 } {
613 t.Run(c.blocked+c.path, func(t *testing.T) {
614 fr := newFontRig(t)
615 sqid := fr.deck(t, "Missing", paperDeck)
616 fr.blocked.Store(c.blocked)
617 fr.rig.Allow(http.MethodGet, c.blocked, http.StatusNotFound)
618 fr.rig.Run(fr.navigate("/d/"+sqid+c.path), chromedp.Sleep(c.wait))
619 var visible string
620 fr.eval(t, `getComputedStyle(document.querySelector('[slides-slide]')).visibility`, &visible)
621 if visible != "visible" {
622 t.Fatalf("the slide is %s with %s missing", visible, c.blocked)
623 }
624 p := fr.clean(t)
625 sameLayout(t, p)
626 })
627 }
628}
629
630// Without JavaScript nothing is held and no web face is used: the slide
631// is in its system faces from the first paint and stays in them, so
632// there is nothing to wait for and nothing to swap.
633func TestFontWithoutJavaScriptTheSystemFacesAreFinal(t *testing.T) {
634 fr := newFontRig(t)
635 sqid := fr.deck(t, "No script", paperDeck)
636 fr.rig.Run(cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}))
637 fr.slow.Store(int64(1500 * time.Millisecond))
638 // Until the stylesheets are in nothing is painted at all (they block
639 // rendering), so the first look is once slides.css has arrived.
640 // (A loop of plain evaluations, not chromedp.Poll: its polling is a
641 // promise in the page, and the page runs no script.)
642 fr.rig.Run(fr.navigate("/d/"+sqid+"?slide=1"), chromedp.WaitReady(chromedp.CSS(`[slides-slide]`)))
643 for deadline := time.Now().Add(10 * time.Second); ; {
644 var in bool
645 fr.rig.Run(evalInto(&in, `[...document.styleSheets].some((s) => s.href && s.href.includes('/static/slides.') && s.cssRules.length > 0)`))
646 if in {
647 break
648 }
649 if time.Now().After(deadline) {
650 t.Fatal("slides.css never arrived")
651 }
652 time.Sleep(20 * time.Millisecond)
653 }
654 read := func() (vis string, families []string, web int) {
655 var out struct {
656 Vis string
657 Families []string
658 Web int
659 }
660 fr.rig.Run(evalInto(&out, `(() => {
661 const runs = [...document.querySelectorAll('[slides-slide] h1, [slides-slide] h2, [slides-slide] p, [slides-slide] code, [slides-slide] strong, [slides-slide] em')];
662 return { Vis: getComputedStyle(document.querySelector('[slides-slide]')).visibility,
663 Families: runs.map((e) => getComputedStyle(e).fontFamily + ' ' + getComputedStyle(e).fontWeight + ' ' + getComputedStyle(e).fontStyle),
664 Web: [...document.fonts].filter((f) => f.family.includes('Liberation') && f.status !== 'unloaded').length };
665 })()`))
666 return out.Vis, out.Families, out.Web
667 }
668 vis, early, _ := read()
669 fr.rig.Run(chromedp.Sleep(3 * time.Second))
670 _, late, web := read()
671 if vis != "visible" {
672 t.Errorf("without JavaScript the slide is %s", vis)
673 }
674 if strings.Join(early, "|") != strings.Join(late, "|") || len(early) == 0 {
675 t.Errorf("without JavaScript the text is set in\n %v\nthen\n %v", early, late)
676 }
677 if web != 0 {
678 t.Errorf("%d web faces were put to use without JavaScript", web)
679 }
680}
681
682// The preloads are the gate's: each file the slides need is fetched once
683// (the preload, which the gate's own load then uses), none twice, and no
684// file of a family the deck does not use is fetched before the slide is
685// shown.
686func TestFontThePreloadsAreTheFacesTheGateLoads(t *testing.T) {
687 fr := newFontRig(t)
688 sqid := fr.deck(t, "Preloads", inkDeck)
689 fr.slow.Store(int64(300 * time.Millisecond))
690 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
691 fr.shown(t)
692 fr.rig.Run(chromedp.Sleep(1 * time.Second))
693 fr.mu.Lock()
694 hits := map[string]int{}
695 for p, n := range fr.fontHits {
696 hits[p] = n
697 }
698 fr.mu.Unlock()
699 sans := 0
700 for p, n := range hits {
701 switch {
702 case strings.Contains(p, "LiberationSans-"):
703 sans++
704 if n != 1 {
705 t.Errorf("%s was fetched %d times; a preload the gate does not use is a second download", p, n)
706 }
707 default:
708 t.Errorf("%s was fetched, but the ink deck draws only in Liberation Sans", p)
709 }
710 }
711 if sans != 4 {
712 t.Errorf("%d of Liberation Sans's four files were fetched: %v", sans, hits)
713 }
714 p := fr.clean(t)
715 webEverywhere(t, p)
716}
717
718// The remote draws its slides as pictures and its notes in the chrome's
719// face: no web face is ever in its document, and no font file is
720// fetched for it, so nothing on it could change face mid-talk. The
721// presenter window draws its slides live (Task 9), so it takes the
722// gate: its slides are in the deck's faces once shown, and its own
723// words, the notes among them, stay in the chrome's.
724func TestFontThePresenterAndRemoteDrawInNoWebFace(t *testing.T) {
725 fr := newFontRig(t)
726 sqid := fr.deck(t, "Talk", paperDeck)
727 fr.ops(t, sqid, `[{"op":"set_notes","id":"slideone0001","markdown":"Notes with **bold** and `+"`code`"+`."}]`)
728 session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
729
730 remote := "/p/" + session + "/remote?t=" + token
731 before := fr.hits("/static/fonts/")
732 fr.rig.Run(fr.navigate(remote), chromedp.WaitReady(chromedp.CSS(`main`)), chromedp.Sleep(1500*time.Millisecond))
733 var out struct {
734 Web int
735 Liberty []string
736 }
737 fr.eval(t, `(() => ({ Web: [...document.fonts].filter((f) => /liberation/i.test(f.family)).length,
738 Liberty: [...document.querySelectorAll('main *')].filter((e) => e.childNodes.length && [...e.childNodes].some((n) => n.nodeType === 3 && n.data.trim()))
739 .map((e) => getComputedStyle(e).fontFamily).filter((f) => /liberation/i.test(f)) }))()`, &out)
740 if out.Web != 0 {
741 t.Errorf("%s: %d web faces in the document", remote, out.Web)
742 }
743 if len(out.Liberty) != 0 {
744 t.Errorf("%s: text set in a deck face: %v", remote, out.Liberty)
745 }
746 if after := fr.hits("/static/fonts/"); after != before {
747 t.Errorf("%s fetched %d font files", remote, after-before)
748 }
749
750 window := "/p/" + session + "/notes?t=" + token
751 before = fr.hits("/static/fonts/")
752 fr.goTo(t, window)
753 var got struct {
754 Gate bool
755 Loaded int
756 Slide []string
757 Chrome []string
758 Visible bool
759 }
760 fr.eval(t, `document.fonts.ready.then(() => {
761 const texts = (root, inside) => [...root.querySelectorAll('*')].filter((e) => (e.closest('[slides-slide]') !== null) === inside &&
762 [...e.childNodes].some((n) => n.nodeType === 3 && n.data.trim())).map((e) => getComputedStyle(e).fontFamily);
763 const main = document.querySelector('main');
764 return { Gate: !!document.querySelector('meta[name="slides-fonts"]'),
765 Loaded: [...document.fonts].filter((f) => /liberation/i.test(f.family) && f.status === 'loaded').length,
766 Slide: texts(document.querySelector('[presenter-panel="now"]'), true),
767 Chrome: texts(main, false).filter((f) => /liberation/i.test(f)),
768 Visible: getComputedStyle(document.querySelector('[presenter-panel="now"] [slides-slide]')).visibility === 'visible' };
769 })`, &got)
770 if !got.Gate {
771 t.Errorf("%s: the presenter window does not take the font gate", window)
772 }
773 if got.Loaded == 0 || fr.hits("/static/fonts/") == before {
774 t.Errorf("%s: no deck face was loaded for the live slides (%d loaded)", window, got.Loaded)
775 }
776 if !got.Visible || len(got.Slide) == 0 {
777 t.Fatalf("%s: the current slide is not shown (visible %v, %d runs of text)", window, got.Visible, len(got.Slide))
778 }
779 for _, f := range got.Slide {
780 if !strings.Contains(strings.ToLower(f), "liberation") {
781 t.Errorf("%s: slide text in %q, not the deck's face", window, f)
782 }
783 }
784 if len(got.Chrome) != 0 {
785 t.Errorf("%s: the window's own words are set in a deck face: %v", window, got.Chrome)
786 }
787}
788
789// inFallback matches a face description of a Liberation family drawn in
790// its system fallback ("liberation serif:system 700 normal").
791var inFallback = regexp.MustCompile(`liberation [a-z]+:system`)
792
793// editable waits until the editor accepts input: its text is bound and
794// the slide is shown.
795func (fr *fontRig) editable(t *testing.T) {
796 t.Helper()
797 fr.shown(t)
798 fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="text"][contenteditable="true"]') && !document.querySelector('[slides-stage-pane]').inert`, chromedp.WithPollingTimeout(15*time.Second)))
799}
800
801// waitLogJS records, on every change, whether the editor's parts are
802// inert, what the font status says and is it visible, and the stage's
803// text, so a check can see a wait from start to end.
804const waitLogJS = `(() => {
805 window.__waitLog = [];
806 const status = document.querySelector('[slides-fonts-status]');
807 const rec = () => window.__waitLog.push({
808 ms: Math.round(performance.now()),
809 inert: !!document.querySelector('[slides-stage-pane]').inert && !!document.querySelector('aside[slides-inspector][estilo-card]').inert &&
810 !!document.querySelector('[slides-strip-nav]').inert && !!document.querySelector('[slides-menubar]').inert &&
811 !!document.querySelector('[slides-deck-dialog]').inert,
812 state: (status && status.getAttribute('data-state')) || '',
813 said: (status && status.querySelector('[role="status"]').textContent.trim()) || '',
814 text: (document.querySelector('[slides-stage]') || { innerText: '' }).innerText.replace(/\n+/g, '|'),
815 });
816 rec();
817 new MutationObserver(rec).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['inert', 'data-state'] });
818 return true;
819})()`
820
821type waitEntry struct {
822 Ms int `json:"ms"`
823 Inert bool `json:"inert"`
824 State string `json:"state"`
825 Said string `json:"said"`
826 Text string `json:"text"`
827}
828
829func (fr *fontRig) waitLog(t *testing.T) []waitEntry {
830 t.Helper()
831 var raw string
832 fr.rig.Run(evalInto(&raw, `JSON.stringify(window.__waitLog || [])`))
833 var log []waitEntry
834 if err := json.Unmarshal([]byte(raw), &log); err != nil {
835 t.Fatalf("wait log: %v", err)
836 }
837 return log
838}
839
840// waited reports whether the log shows a wait: the editor inert and the
841// status saying a font is loading, in words.
842func waited(log []waitEntry) bool {
843 for _, e := range log {
844 if e.Inert && e.State == "loading" && e.Said != "" {
845 return true
846 }
847 }
848 return false
849}
850
851// settled waits until no font wait is in progress.
852func (fr *fontRig) settled(t *testing.T) {
853 t.Helper()
854 fr.rig.Run(chromedp.Poll[chromedp.Void](`(() => { const s = document.querySelector('[slides-fonts-status]');
855 return !document.querySelector('[slides-stage-pane]').inert && !['loading'].includes((s && s.getAttribute('data-state')) || '') })()`,
856 chromedp.WithPollingTimeout(15*time.Second)))
857}
858
859// faceOf is the state of the face a stage element's text is drawn in,
860// read the way the probe reads it: "liberation mono:web 400 normal".
861func (fr *fontRig) faceOf(t *testing.T, selector string) string {
862 t.Helper()
863 var out string
864 fr.eval(t, `(() => { const el = document.querySelector(`+jsString(selector)+`); if (!el) return 'missing';
865 const cs = getComputedStyle(el); const fam = cs.fontFamily.split(',').map((p) => p.trim().replace(/^["']+|["']+$/g, '').toLowerCase()).find((n) => n.startsWith('liberation'));
866 return fam ? fam + ':' + window.__fontState(fam, cs.fontWeight, cs.fontStyle) : 'system' })()`, &out)
867 return out
868}
869
870func jsString(s string) string {
871 b, _ := json.Marshal(s)
872 return string(b)
873}
874
875// selectTextJS puts the selection over the first word of the stage's
876// first text block and focuses it.
877const selectTextJS = `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
878 const p = el.querySelector('p'); const n = document.createTreeWalker(p, NodeFilter.SHOW_TEXT).nextNode();
879 const r = document.createRange(); r.setStart(n, 0); r.setEnd(n, 5); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`
880
881func pasteJS(html string) string {
882 return `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
883 const p = el.querySelector('p'); const n = document.createTreeWalker(p, NodeFilter.SHOW_TEXT).nextNode();
884 const r = document.createRange(); r.setStart(n, n.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r);
885 const d = new DataTransfer(); d.setData('text/html', ` + jsString(html) + `); d.setData('text/plain', 'x');
886 el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`
887}
888
889func dropJS(html string) string {
890 return `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
891 const d = new DataTransfer(); d.setData('text/html', ` + jsString(html) + `); d.setData('text/plain', 'x');
892 const r = el.querySelector('p').getBoundingClientRect();
893 el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.right - 4, clientY: r.top + 8 })); return true })()`
894}
895
896func changeJS(selector, value string) string {
897 return `(() => { const s = document.querySelector(` + jsString(selector) + `); s.value = ` + jsString(value) + `;
898 s.dispatchEvent(new Event('change', { bubbles: true })); return true })()`
899}
900
901func clickJS(selector string) string {
902 return `(() => { document.querySelector(` + jsString(selector) + `).click(); return true })()`
903}
904
905// Every way a change reaches a slide goes through the one font gate:
906// each row brings in a family nobody on the page has loaded, held slow,
907// and no frame may show slide text in a face that has not loaded, no run
908// may change face, and the change must land, in its own family. One
909// table, so a path without a row is easy to see missing.
910func TestFontEveryInputPathWaitsForItsFamily(t *testing.T) {
911 rows := []struct {
912 name string
913 // deck is the batch the deck is made from; slow the font files
914 // held back (a family the deck does not use).
915 deck, slow string
916 // act does the change; done is a JS expression true once it has
917 // landed; face, a selector whose text must end in face want.
918 act func(t *testing.T, fr *fontRig, sqid string)
919 done string
920 face, want string
921 // local rows are this person's own and must wait visibly.
922 local bool
923 // then is done once the change has landed (typing into what it made).
924 then func(t *testing.T, fr *fontRig)
925 }{
926 {name: "change the theme", deck: inkDeck, slow: "LiberationSerif-", local: true,
927 act: func(t *testing.T, fr *fontRig, _ string) { fr.eval(t, changeJS("#rst-deck-theme", "paper"), nil) },
928 done: `document.querySelector('[slides-stage] [slides-slide]').getAttribute('data-theme') === 'paper'`,
929 face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
930 {name: "go back to the theme's heading font", slow: "LiberationSerif-", local: true,
931 deck: strings.Replace(paperDeck, `"theme":"paper"`, `"theme":"paper","fonts":{"heading":"system-ui, sans-serif","body":""}`, 1),
932 act: func(t *testing.T, fr *fontRig, _ string) { fr.eval(t, changeJS("#rst-deck-font-heading", ""), nil) },
933 done: `!document.querySelector('[slides-stage] [slides-slide]').getAttribute('style').includes('system-ui, sans-serif;')`,
934 face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
935 {name: "add a code block", deck: inkDeck, slow: "LiberationMono-", local: true,
936 act: func(t *testing.T, fr *fontRig, _ string) {
937 fr.eval(t, insertBlockJS("code"), nil)
938 },
939 done: `!!document.querySelector('[slides-stage] [data-block="code"]')`,
940 face: `[slides-stage] [data-block="code"]`, want: "liberation mono:web"},
941 {name: "toggle code and type", deck: inkDeck, slow: "LiberationMono-", local: true,
942 act: func(t *testing.T, fr *fontRig, _ string) {
943 fr.eval(t, selectTextJS, nil)
944 fr.rig.Run(chromedp.KeyEvent("e", chromedp.KeyModifiers(inputModifierMeta)))
945 },
946 done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
947 face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
948 {name: "paste code", deck: inkDeck, slow: "LiberationMono-", local: true,
949 act: func(t *testing.T, fr *fontRig, _ string) {
950 fr.eval(t, pasteJS(`<p>pasted <code>in code</code></p>`), nil)
951 },
952 done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
953 face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
954 {name: "drop code", deck: inkDeck, slow: "LiberationMono-", local: true,
955 act: func(t *testing.T, fr *fontRig, _ string) {
956 fr.eval(t, dropJS(`<p>dropped <code>in code</code></p>`), nil)
957 },
958 done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
959 face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
960 {name: "the first slide of an empty deck", deck: `[{"op":"set_meta","theme":"paper","title":"Empty"}]`, slow: "Liberation", local: true,
961 act: func(t *testing.T, fr *fontRig, _ string) {
962 fr.eval(t, clickJS(`[slides-menu] [data-command="new-slide"]`), nil)
963 },
964 done: `!!document.querySelector('[slides-stage] [data-block="heading"][contenteditable="true"]')`,
965 then: func(t *testing.T, fr *fontRig) {
966 fr.eval(t, `(() => { document.querySelector('[slides-stage] [data-block="heading"]').focus(); return true })()`, nil)
967 fr.rig.Run(chromedp.KeyEvent("First slide"))
968 },
969 face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
970 {name: "a collaborator's code block", deck: inkDeck, slow: "LiberationMono-",
971 act: func(t *testing.T, fr *fontRig, sqid string) {
972 fr.ops(t, sqid, `[{"op":"add_block","slide":"slideone0001","type":"code","region":"body","markdown":"from(a, collaborator)"}]`)
973 },
974 done: `!!document.querySelector('[slides-stage] [data-block="code"]')`,
975 face: `[slides-stage] [data-block="code"]`, want: "liberation mono:web"},
976 {name: "a collaborator's theme", deck: inkDeck, slow: "LiberationSerif-",
977 act: func(t *testing.T, fr *fontRig, sqid string) { fr.ops(t, sqid, `[{"op":"set_meta","theme":"paper"}]`) },
978 done: `document.querySelector('[slides-stage] [slides-slide]').getAttribute('data-theme') === 'paper'`,
979 face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
980 {name: "a collaborator's code mark", deck: inkDeck, slow: "LiberationMono-",
981 act: func(t *testing.T, fr *fontRig, sqid string) {
982 fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"text00000001","markdown":"now with `+"`code`"+` in it"}]`)
983 },
984 done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
985 face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
986 }
987 for _, row := range rows {
988 t.Run(row.name, func(t *testing.T) {
989 fr := newFontRig(t)
990 sqid := fr.deck(t, "Paths", row.deck)
991 fr.match.Store(row.slow)
992 // Held long enough to be waited for, and short enough that all
993 // of a row's files arrive inside the four seconds a change
994 // waits over this test server's six HTTP/1.1 connections: the
995 // empty deck's row holds two families, eight files.
996 slow := 1500 * time.Millisecond
997 if row.slow == "Liberation" {
998 slow = 900 * time.Millisecond
999 }
1000 fr.slow.Store(int64(slow))
1001 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1002 if strings.Contains(row.deck, `"add_slide"`) {
1003 fr.editable(t)
1004 } else {
1005 fr.rig.Run(chromedp.Poll[chromedp.Void](`document.documentElement.getAttribute('data-slides-fonts') === 'shown' && !!document.querySelector('[slides-menu]')`, chromedp.WithPollingTimeout(15*time.Second)),
1006 chromedp.Sleep(300*time.Millisecond))
1007 }
1008 fr.eval(t, waitLogJS, nil)
1009 row.act(t, fr, sqid)
1010 if err := chromedp.Do(fr.rig.Context(), chromedp.Poll[chromedp.Void](row.done, chromedp.WithPollingTimeout(15*time.Second))); err != nil {
1011 log := fr.waitLog(t)
1012 if len(log) > 12 {
1013 log = log[len(log)-12:]
1014 }
1015 var where string
1016 fr.eval(t, `(async () => location.hash + ' ' + document.querySelector('[slides-stage]').innerHTML.slice(0, 300) + ' errors: ' + JSON.stringify((window.__fontProbe || {}).errors) + ' load-error: ' + (document.querySelector('[slides-load-error]') || {}).textContent + ' now: ' + await fetch(location.pathname.replace('/edit', '') + '/slides/' + location.hash.slice(1) + '.html?vp=desktop').then(r => r.status + ' ' + r.statusText) + ' save: ' + (document.querySelector('[estilo-save-status]') || {}).textContent)()`, &where)
1017 t.Fatalf("the change never landed: %v\nwait log tail: %+v\nstage: %s", err, log, where)
1018 }
1019 fr.settled(t)
1020 if row.then != nil {
1021 row.then(t, fr)
1022 }
1023 // Long enough for anything still on its way to have landed.
1024 fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
1025 if got := fr.faceOf(t, row.face); !strings.HasPrefix(got, row.want) {
1026 t.Errorf("%s is in %s, want %s", row.face, got, row.want)
1027 }
1028 if row.local && !waited(fr.waitLog(t)) {
1029 t.Error("the change needed a font that was not in and did not wait for it, visibly")
1030 }
1031 p := fr.cleanAcross(t)
1032 webEverywhere(t, p)
1033 })
1034 }
1035}
1036
1037const inputModifierMeta = chromedp.ModifierMeta
1038
1039// inWait reports whether the editor's parts are inert and the status
1040// says, visibly and in words, that a font is loading, right now.
1041func (fr *fontRig) inWait(t *testing.T) bool {
1042 t.Helper()
1043 var on bool
1044 fr.eval(t, `(() => { const s = document.querySelector('[slides-fonts-status]');
1045 return ['[slides-stage-pane]', 'aside[slides-inspector][estilo-card]', '[slides-strip-nav]', '[slides-menubar]', '[slides-deck-dialog]'].every((q) => document.querySelector(q).inert) &&
1046 ['loading', 'refused'].includes(s.getAttribute('data-state')) && s.querySelector('[role="status"]').textContent.trim() !== '' &&
1047 getComputedStyle(s.querySelector('[role="status"]')).visibility === 'visible' })()`, &on)
1048 return on
1049}
1050
1051func (fr *fontRig) stageText(t *testing.T) string {
1052 t.Helper()
1053 var s string
1054 fr.eval(t, `document.querySelector('[slides-stage]').innerText.replace(/\n+/g, '|')`, &s)
1055 return s
1056}
1057
1058// addCodeBlockJS adds a code box from the Insert menu.
1059var addCodeBlockJS = insertBlockJS("code")
1060
1061// A wait for a font is a short modal (Docs' review 7, adopted). The
1062// change that needs the font is held before it changes anything; the
1063// stage, the strip, the inspector and the Slide menu go inert at once
1064// and the status under the bar says a font is loading; what is typed
1065// meanwhile goes nowhere, and a second change is refused and said, not
1066// queued; a collaborator's change that arrives meanwhile is applied
1067// after it, in order, and not lost; once the font is in, the change is
1068// made once.
1069func TestFontAWaitIsAShortModal(t *testing.T) {
1070 fr := newFontRig(t)
1071 sqid := fr.deck(t, "Modal", inkDeck)
1072 fr.match.Store("LiberationMono-")
1073 // Under the four seconds a change waits, counting the prefetch that
1074 // started the files at the reveal.
1075 fr.slow.Store(int64(3200 * time.Millisecond))
1076 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1077 fr.editable(t)
1078 before := fr.stageText(t)
1079 fr.eval(t, waitLogJS, nil)
1080 fr.eval(t, addCodeBlockJS, nil)
1081 if !fr.inWait(t) {
1082 t.Fatal("adding a code block whose font is not in did not start a visible wait")
1083 }
1084 // Typing into the slide, which is inert: nothing reaches it.
1085 fr.rig.Run(chromedp.KeyEvent("qzqz"))
1086 // A second change, which only a script can make while the inspector
1087 // is inert: refused, and said.
1088 fr.eval(t, changeJS("#rst-deck-theme", "paper"), nil)
1089 // A collaborator's change, during the wait.
1090 fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"Retitled by a collaborator"}]`)
1091 if !fr.inWait(t) {
1092 t.Fatalf("the wait ended before the collaborator's change was made, so this cannot show it waited behind it: %+v", fr.waitLog(t))
1093 }
1094 fr.settled(t)
1095 fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage]').innerText.includes('Retitled by a collaborator')`, chromedp.WithPollingTimeout(10*time.Second)),
1096 chromedp.Sleep(800*time.Millisecond))
1097
1098 var codes int
1099 var theme string
1100 fr.eval(t, `document.querySelectorAll('[slides-stage] [data-block="code"]').length`, &codes)
1101 fr.eval(t, `document.querySelector('[slides-stage] [slides-slide]').getAttribute('data-theme')`, &theme)
1102 if codes != 1 {
1103 t.Errorf("%d code blocks on the slide; the change waits and then runs once", codes)
1104 }
1105 if theme != "ink" {
1106 t.Errorf("the theme is %q: the second change, made during the wait, must be refused", theme)
1107 }
1108 if text := fr.stageText(t); strings.Contains(text, "qzqz") && !strings.Contains(before, "qzqz") {
1109 t.Errorf("what was typed during the wait reached the slide: %q", text)
1110 }
1111 if got := fr.faceOf(t, `[slides-stage] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
1112 t.Errorf("the code block is in %s", got)
1113 }
1114 log := fr.waitLog(t)
1115 refused, early := false, false
1116 for _, e := range log {
1117 refused = refused || e.State == "refused"
1118 early = early || (e.Inert && strings.Contains(e.Text, "Retitled by a collaborator"))
1119 }
1120 if !refused {
1121 t.Error("the second change was not said to be refused")
1122 }
1123 if early {
1124 t.Error("the collaborator's change reached the slide during the wait, under the change being made")
1125 }
1126 fr.clean(t)
1127}
1128
1129// The notes card and the icon that opens it are inside the stage pane,
1130// so a font wait makes them inert with it: the card, its ×, its top
1131// edge and the notes with the card open; the icon with it closed.
1132// Neither is inert once the wait is over.
1133func TestFontAWaitMakesTheNotesInert(t *testing.T) {
1134 const parts = `['[slides-notes-pane]', '[slides-notes-close]', '[slides-notes-resize]', '[slides-notes]', '[slides-notes-open]']`
1135 const free = parts + `.filter((q) => !document.querySelector(q).closest('[inert]'))`
1136 for _, closed := range []bool{false, true} {
1137 t.Run(map[bool]string{false: "open", true: "closed"}[closed], func(t *testing.T) {
1138 fr := newFontRig(t)
1139 sqid := fr.deck(t, "Notes", inkDeck)
1140 fr.match.Store("LiberationMono-")
1141 fr.slow.Store(int64(3200 * time.Millisecond))
1142 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1143 fr.editable(t)
1144 if closed {
1145 fr.eval(t, `(document.querySelector('[slides-notes-close]').click(), true)`, nil)
1146 }
1147 var state string
1148 fr.eval(t, `document.querySelector('[slides-notes-pane]').dataset.state`, &state)
1149 if want := map[bool]string{false: "open", true: "closed"}[closed]; state != want {
1150 t.Fatalf("the notes card is %q, want %q", state, want)
1151 }
1152 fr.eval(t, addCodeBlockJS, nil)
1153 if !fr.inWait(t) {
1154 t.Fatal("adding a code block whose font is not in did not start a visible wait")
1155 }
1156 var during []string
1157 fr.eval(t, free, &during)
1158 if len(during) != 0 {
1159 t.Errorf("during the font wait these are not inert: %v", during)
1160 }
1161 fr.settled(t)
1162 var after []string
1163 fr.eval(t, free, &after)
1164 if len(after) != 5 {
1165 t.Errorf("after the font wait only %v are free of inert", after)
1166 }
1167 })
1168 }
1169}
1170
1171// A change whose font cannot be had changes nothing and says so: the
1172// font files are refused, the code block is never added (on the slide
1173// or in the deck), and the status says the font could not be loaded.
1174func TestFontAChangeWhoseFamilyCannotLoadChangesNothing(t *testing.T) {
1175 fr := newFontRig(t)
1176 sqid := fr.deck(t, "Refused", inkDeck)
1177 fr.blocked.Store("LiberationMono-")
1178 fr.rig.Allow(http.MethodGet, "LiberationMono-", http.StatusNotFound)
1179 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1180 fr.editable(t)
1181 fr.eval(t, waitLogJS, nil)
1182 fr.eval(t, addCodeBlockJS, nil)
1183 fr.settled(t)
1184 fr.rig.Run(chromedp.Sleep(800 * time.Millisecond))
1185 var state, said string
1186 var codes int
1187 fr.eval(t, `document.querySelector('[slides-fonts-status]').getAttribute('data-state') || ''`, &state)
1188 fr.eval(t, `document.querySelector('[slides-fonts-status] [role="status"]').textContent`, &said)
1189 fr.eval(t, `document.querySelectorAll('[slides-stage] [data-block="code"]').length`, &codes)
1190 if state != "unavailable" || said == "" {
1191 t.Errorf("the status is %q %q; it must say the font could not be loaded", state, said)
1192 }
1193 if codes != 0 {
1194 t.Errorf("%d code blocks on the slide; a change whose font cannot load is not made", codes)
1195 }
1196 view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
1197 if b, _ := json.Marshal(view); strings.Contains(string(b), `"type":"code"`) {
1198 t.Error("the deck holds a code block; the refused change reached the server")
1199 }
1200 if !waited(fr.waitLog(t)) {
1201 t.Error("the change did not wait, visibly, before it was refused")
1202 }
1203 fr.clean(t)
1204}
1205
1206// Undo and redo bring back what was on screen in this visit, in a family
1207// that stayed in: neither waits, and neither paints a face that has not
1208// loaded.
1209func TestFontUndoAndRedoOfACodeBlockNeverFlash(t *testing.T) {
1210 fr := newFontRig(t)
1211 sqid := fr.deck(t, "Undo", inkDeck)
1212 fr.match.Store("LiberationMono-")
1213 fr.slow.Store(int64(1500 * time.Millisecond))
1214 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1215 fr.editable(t)
1216 fr.eval(t, addCodeBlockJS, nil)
1217 fr.settled(t)
1218 fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)))
1219 fr.eval(t, waitLogJS, nil)
1220 fr.eval(t, `(() => { document.activeElement && document.activeElement.blur(); return true })()`, nil)
1221 fr.eval(t, clickJS(`[slides-menu] [data-command="undo"]`), nil)
1222 fr.rig.Run(chromedp.Poll[chromedp.Void](`!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)))
1223 fr.eval(t, clickJS(`[slides-menu] [data-command="redo"]`), nil)
1224 fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)),
1225 chromedp.Sleep(800*time.Millisecond))
1226 if waited(fr.waitLog(t)) {
1227 t.Error("undo or redo waited for a font that was already in")
1228 }
1229 if got := fr.faceOf(t, `[slides-stage] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
1230 t.Errorf("the code block is back in %s", got)
1231 }
1232 fr.clean(t)
1233}
1234
1235// The projector never swaps faces mid-presentation: a slide that needs a
1236// family the projector has not loaded — the deck was changed during the
1237// talk — waits for it before it goes up, and goes up once, in it.
1238func TestFontTheProjectorsNextSlideWaitsForItsFamily(t *testing.T) {
1239 fr := newFontRig(t)
1240 sqid := fr.deck(t, "Talk", inkDeck)
1241 session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
1242 fr.rig.Run(fr.navigate("/p/" + session))
1243 fr.shown(t)
1244 fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
1245 fr.match.Store("LiberationMono-")
1246 fr.slow.Store(int64(1500 * time.Millisecond))
1247 fr.ops(t, sqid, `[{"op":"add_block","slide":"slidetwo0002","type":"code","region":"body","markdown":"added(mid, talk)"}]`)
1248 if rec := command(t, fr.app, session, "next", token, "", nil); rec.Code >= 400 {
1249 t.Fatalf("next: %d", rec.Code)
1250 }
1251 fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)),
1252 chromedp.Sleep(800*time.Millisecond))
1253 if got := fr.faceOf(t, `[slides-stage] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
1254 t.Errorf("the projector's code is in %s", got)
1255 }
1256 p := fr.clean(t)
1257 webEverywhere(t, p)
1258}
1259
1260// Random decks from Slides' own model (fixtures/generate-random-decks.mjs
1261// walks the op vocabulary, the text schema's marks and the server's
1262// themes and stacks, and fails unless every block type, template,
1263// layout, theme and mark appeared, marks in table cells included), each
1264// opened on every slide in the viewer at a desktop and at a phone width,
1265// and in the editor. On every page every element of the slide that is
1266// drawn names, in its computed font stack, only families the gate
1267// waited for (the manifest's need); and the gate waited for nothing the
1268// deck does not reference: its heading and body stacks, and the code
1269// stack if any slide draws code. The probe watches every one of those
1270// pages for a face drawn before it loaded.
1271func TestFontTheGateCoversEveryFaceADeckUses(t *testing.T) {
1272 fr := newFontRig(t)
1273 seed := fontSeed()
1274 const decks = 16
1275 sqids := fr.randomDecks(t, decks, seed)
1276 // Generated images name no picture; their frames fetch nothing.
1277 const checkJS = `(() => {
1278 const m = JSON.parse(document.querySelector('meta[name="slides-fonts"]').getAttribute('content'));
1279 const section = document.querySelector('[slides-stage] [slides-slide]') || document.querySelector('[slides-slide]');
1280 if (!section) return { need: m.need, drawn: [], referenced: [], code: false, where: [], none: true };
1281 const names = (s) => s.split(',').map((p) => p.trim().replace(/^["']+|["']+$/g, '').toLowerCase());
1282 const keyOf = { 'liberation sans': 'sans', 'liberation serif': 'serif', 'liberation mono': 'mono' };
1283 const drawn = new Set(); const where = [];
1284 for (const el of [section, ...section.querySelectorAll('*')]) {
1285 const cs = getComputedStyle(el);
1286 if (cs.visibility !== 'visible' || !el.getClientRects().length) continue;
1287 for (const n of names(cs.fontFamily)) if (keyOf[n]) { drawn.add(keyOf[n]); if (!m.need.includes(keyOf[n])) where.push(keyOf[n] + ' on ' + el.tagName + ' ' + (el.getAttribute('data-block') || '') + ' "' + (el.textContent || '').slice(0, 20) + '"'); }
1288 }
1289 const style = section.getAttribute('style') || '';
1290 const decl = (k) => { const d = style.split(';').find((x) => x.trim().startsWith(k + ':')); return d ? d.slice(d.indexOf(':') + 1) : ''; };
1291 const referenced = [...new Set([...names(decl('--slides-font-heading')), ...names(decl('--slides-font-body'))].map((n) => keyOf[n]).filter(Boolean))];
1292 const code = [...section.querySelectorAll('pre, code')].some((el) => el.getClientRects().length > 0);
1293 return { need: m.need, drawn: [...drawn], referenced, code, where };
1294 })()`
1295 type check struct {
1296 Need, Drawn, Referenced, Where []string
1297 Code, None bool
1298 }
1299 checked := 0
1300 for i, sqid := range sqids {
1301 view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
1302 slides, _ := view["slides"].([]any)
1303 if len(slides) == 0 {
1304 t.Fatalf("deck %d has no slides", i)
1305 }
1306 referenced := map[string]bool{}
1307 code := false
1308 var need []string
1309 var paths []string
1310 for n := 1; n <= len(slides); n++ {
1311 paths = append(paths, fmt.Sprintf("/d/%s?slide=%d", sqid, n), fmt.Sprintf("/d/%s?slide=%d&vp=phone", sqid, n))
1312 }
1313 paths = append(paths, "/d/"+sqid+"/edit")
1314 for _, path := range paths {
1315 // Navigate and wait for the load: nothing here is slowed, and
1316 // a check that starts before the navigation has committed reads
1317 // the page before.
1318 fr.rig.Run(chromedp.Navigate(fr.rig.Origin + path))
1319 fr.shown(t)
1320 if strings.HasSuffix(path, "/edit") {
1321 fr.rig.Run(chromedp.Poll[chromedp.Void](`!document.querySelector('[slides-stage] [slides-block][data-block="text"], [slides-stage] [slides-block][data-block="heading"]') ||
1322 !!document.querySelector('[slides-stage] [contenteditable="true"]')`, chromedp.WithPollingTimeout(15*time.Second)))
1323 }
1324 var c check
1325 fr.eval(t, checkJS, &c)
1326 if c.None {
1327 t.Fatalf("%s shows no slide", path)
1328 }
1329 for _, w := range c.Where {
1330 t.Errorf("deck %d %s: drawn in a family the gate did not wait for: %s (need %v)", i, path, w, c.Need)
1331 }
1332 for _, k := range c.Referenced {
1333 referenced[k] = true
1334 }
1335 code = code || c.Code
1336 need = c.Need
1337 var violations []string
1338 fr.eval(t, `(window.__fontProbe || { violations: [] }).violations`, &violations)
1339 for _, v := range violations {
1340 t.Errorf("deck %d %s: %s", i, path, v)
1341 }
1342 checked++
1343 }
1344 if code {
1345 referenced["mono"] = true
1346 }
1347 for _, k := range need {
1348 if !referenced[k] {
1349 t.Errorf("deck %d: the gate waited for %s, which no slide's stacks name and no slide's code draws in (need %v, referenced %v)", i, k, need, sortedKeys(referenced))
1350 }
1351 }
1352 }
1353 if checked < decks*3 {
1354 t.Fatalf("checked %d pages; the generated decks are too small to mean anything", checked)
1355 }
1356}
1357
1358// A wait never begins in an IME composition: interrupting one loses the
1359// word being composed. Composing in a slide's text while a family is
1360// still on its way neither waits nor paints anything in a face that has
1361// not loaded, and the composed text lands.
1362func TestFontACompositionNeverStartsAWait(t *testing.T) {
1363 fr := newFontRig(t)
1364 sqid := fr.deck(t, "Compose", inkDeck)
1365 fr.match.Store("LiberationMono-")
1366 fr.slow.Store(int64(3 * time.Second))
1367 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1368 fr.editable(t)
1369 fr.eval(t, `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
1370 const n = document.createTreeWalker(el.querySelector('p'), NodeFilter.SHOW_TEXT).nextNode();
1371 const r = document.createRange(); r.setStart(n, n.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, nil)
1372 fr.eval(t, waitLogJS, nil)
1373 fr.rig.Run(
1374 cdpStep(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほ", SelectionStart: 2, SelectionEnd: 2}),
1375 chromedp.Sleep(100*time.Millisecond),
1376 cdpStep(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "日本", SelectionStart: 2, SelectionEnd: 2}),
1377 chromedp.Sleep(100*time.Millisecond),
1378 cdpStep(input.InsertText, input.InsertTextParams{Text: "日本"}),
1379 chromedp.Sleep(800*time.Millisecond),
1380 )
1381 if waited(fr.waitLog(t)) {
1382 t.Error("a composition started a wait for a font")
1383 }
1384 if text := fr.stageText(t); !strings.Contains(text, "日本") {
1385 t.Errorf("the composed text did not land: %q", text)
1386 }
1387 fr.clean(t)
1388}
1389
1390// A refused change lets go of everything queued behind it. The code face
1391// is refused (its files 404); a collaborator's change arrives during the
1392// wait and queues behind it; after the refusal the collaborator's change
1393// lands, and a second one after it, in order, and nothing on the page
1394// throws (Astra's finding 1 on #27: the refusal threw before it released
1395// the queue, and every collaborator's change after it was stuck).
1396func TestFontARefusalReleasesTheCollaboratorsChangesInOrder(t *testing.T) {
1397 fr := newFontRig(t)
1398 sqid := fr.deck(t, "Refused", inkDeck)
1399 fr.match.Store("LiberationMono-")
1400 fr.slow.Store(int64(7 * time.Second))
1401 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1402 fr.editable(t)
1403 fr.eval(t, addCodeBlockJS, nil)
1404 if !fr.inWait(t) {
1405 t.Fatal("adding a code block whose font is not in did not start a wait")
1406 }
1407 fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"First from a collaborator"}]`)
1408 fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
1409 fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"Second from a collaborator"}]`)
1410 // The four seconds a change waits, then the refusal.
1411 fr.settled(t)
1412 fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage]').innerText.includes('Second from a collaborator')`,
1413 chromedp.WithPollingTimeout(10*time.Second)))
1414 var state string
1415 var codes int
1416 fr.eval(t, `document.querySelector('[slides-fonts-status]').getAttribute('data-state') || ''`, &state)
1417 fr.eval(t, `document.querySelectorAll('[slides-stage] [data-block="code"]').length`, &codes)
1418 if state != "unavailable" || codes != 0 {
1419 t.Errorf("status %q and %d code blocks: the change was meant to be refused", state, codes)
1420 }
1421 // And the queue still moves after it.
1422 fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"text00000001","markdown":"Third, after the refusal"}]`)
1423 fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage]').innerText.includes('Third, after the refusal')`,
1424 chromedp.WithPollingTimeout(10*time.Second)))
1425 fr.clean(t)
1426}
1427
1428// A change waiting for its font is never lost to a refresh of the stage
1429// that was already on its way (Astra's finding 2 on #27). The accent is
1430// changed — its save brings a refresh of the slide — and at once text
1431// with code in it is pasted, the code face three seconds away. The
1432// refresh waits for the paste, not the other way round: the pasted words
1433// land, once, in the code face, the refreshed slide wears the new accent,
1434// and the deck on the server holds both.
1435func TestFontAPendingRefreshNeverLosesAWaitingPaste(t *testing.T) {
1436 fr := newFontRig(t)
1437 sqid := fr.deck(t, "Refresh", inkDeck)
1438 fr.match.Store("LiberationMono-")
1439 fr.slow.Store(int64(3 * time.Second))
1440 fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
1441 fr.editable(t)
1442 fr.eval(t, waitLogJS, nil)
1443 fr.eval(t, changeJS("#rst-deck-accent", "#3366cc")+` && `+pasteJS(`<p>pasted <code>kept code</code> words</p>`), nil)
1444 fr.settled(t)
1445 fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage] [slides-slide]').getAttribute('style').includes('#3366cc')`,
1446 chromedp.WithPollingTimeout(10*time.Second)), chromedp.Sleep(1500*time.Millisecond))
1447 text := fr.stageText(t)
1448 if strings.Count(text, "kept code") != 1 {
1449 t.Errorf("the pasted words are on the slide %d times: %q", strings.Count(text, "kept code"), text)
1450 }
1451 if got := fr.faceOf(t, `[slides-stage] [data-block="text"] code`); !strings.HasPrefix(got, "liberation mono:web") {
1452 t.Errorf("the pasted code is in %s", got)
1453 }
1454 for _, e := range fr.waitLog(t) {
1455 if e.State == "unavailable" || e.State == "interrupted" {
1456 t.Errorf("the paste was refused (%s): %q", e.State, e.Said)
1457 }
1458 }
1459 view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
1460 b, _ := json.Marshal(view)
1461 if !strings.Contains(string(b), "kept code") || !strings.Contains(string(b), "#3366cc") {
1462 t.Errorf("the deck does not hold both the accent and the paste: %s", b)
1463 }
1464 fr.cleanAcross(t)
1465}
1466
1467// randomDecks makes n decks over the API and fills them with
1468// fixtures/generate-random-decks.mjs's decks, through the ordinary write
1469// path, and returns their sqids.
1470func (fr *fontRig) randomDecks(t *testing.T, n int, seed string) []string {
1471 t.Helper()
1472 dir := t.TempDir()
1473 sqids := make([]string, n)
1474 for i := range n {
1475 sqids[i] = apiDeck(t, fr.app, fr.token, fmt.Sprintf("Random %d", i))
1476 rec := get(t, fr.app, "/d/"+sqids[i]+"/updates?since=0", fr.cookies...)
1477 if rec.Code != http.StatusOK {
1478 t.Fatalf("GET updates: %d", rec.Code)
1479 }
1480 if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%d.base", i)), rec.Body.Bytes(), 0o600); err != nil {
1481 t.Fatal(err)
1482 }
1483 }
1484 page := get(t, fr.app, "/d/"+sqids[0]+"?slide=1", fr.cookies...).Body.String()
1485 m := manifestMeta.FindStringSubmatch(page)
1486 if m == nil {
1487 t.Fatal("no font manifest on the viewer")
1488 }
1489 manifest := filepath.Join(dir, "manifest.json")
1490 if err := os.WriteFile(manifest, []byte(html.UnescapeString(m[1])), 0o600); err != nil {
1491 t.Fatal(err)
1492 }
1493 gen := exec.Command("node", "generate-random-decks.mjs", seed, dir, manifest)
1494 gen.Dir = filepath.Join("..", "..", "fixtures")
1495 if out, err := gen.CombinedOutput(); err != nil {
1496 t.Fatalf("generate: %v\n%s", err, out)
1497 }
1498 for i, sqid := range sqids {
1499 update, err := os.ReadFile(filepath.Join(dir, fmt.Sprintf("%d.bin", i)))
1500 if err != nil {
1501 t.Fatal(err)
1502 }
1503 if rec := postBody(t, fr.app, "/d/"+sqid+"/updates", "application/octet-stream", update, fr.cookies); rec.Code != http.StatusNoContent {
1504 t.Fatalf("deck %d: POST updates: %d %s", i, rec.Code, rec.Body)
1505 }
1506 }
1507 return sqids
1508}
1509
1510// fontSeed is the generator's seed: SLIDES_FONT_SEED, or a fixed one.
1511func fontSeed() string {
1512 if seed := os.Getenv("SLIDES_FONT_SEED"); seed != "" {
1513 return seed
1514 }
1515 return "20261026"
1516}
1517
1518// An editor that mounts after its slide is shown moves nothing (Astra's
1519// finding 3 on #27). The editor's bundle is held five seconds — past the
1520// gate's 3.5 s, so the slide is shown in the server's markup first — on
1521// generated decks whose first slide has a block of every type the
1522// editor binds, and a table, each text in a shape the renderer and
1523// ProseMirror could draw differently: no paragraphs, one empty one, and
1524// empties before, between and after words. Before and after the mount
1525// each bound element holds the same markup, the slide the same layout,
1526// and the same pixels.
1527func TestFontALateEditorMovesNothing(t *testing.T) {
1528 fr := newFontRig(t)
1529 sqids := fr.randomDecks(t, 12, fontSeed())
1530 fr.editorDelay.Store(int64(6 * time.Second))
1531 const snapJS = `(() => {
1532 const s = document.querySelector('[slides-stage] [slides-slide]');
1533 const sr = s.getBoundingClientRect();
1534 const round = (b) => [b.left - sr.left, b.top - sr.top, b.width, b.height].map((v) => Math.round(v * 4) / 4).join(',');
1535 const bound = [...s.querySelectorAll('[data-block="heading"], [data-block="text"], [data-block="list"], [data-block="quote"] blockquote, [data-block="code"] > code, [data-block="table"] th, [data-block="table"] td')];
1536 const boxes = [...s.querySelectorAll('[slides-block], [slides-block] *')].map((e) => e.tagName + '@' + round(e.getBoundingClientRect()));
1537 return { Mounted: !!s.querySelector('[contenteditable="true"]'), Markup: bound.map((e) => e.innerHTML),
1538 Blocks: [...s.querySelectorAll('[slides-block]')].map((e) => (e.getAttribute('data-block') || '') + '@' + round(e.getBoundingClientRect())),
1539 Lines: bound.map((e) => { const r = document.createRange(); r.selectNodeContents(e); return [...r.getClientRects()].length + ':' + round(r.getBoundingClientRect()) }),
1540 Shown: document.documentElement.getAttribute('data-slides-fonts') === 'shown',
1541 Slide: [sr.left, sr.top, sr.width, sr.height, document.documentElement.clientWidth, scrollY].join(',') };
1542 })()`
1543 type snap struct {
1544 Mounted, Shown bool
1545 Markup, Blocks, Lines []string
1546 Slide string
1547 }
1548 for i, sqid := range sqids {
1549 // The page before is marked, so the wait below is for the new
1550 // one: navigate does not wait, and the load event waits for the
1551 // held bundle.
1552 fr.rig.Run(chromedp.Evaluate[chromedp.Void](`window.__leaving = true`), fr.navigate("/d/"+sqid+"/edit"))
1553 fr.until(t, `!window.__leaving && !!document.querySelector('[slides-stage] [slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`)
1554 var before, after snap
1555 var a, b []byte
1556 fr.rig.Run(chromedp.Sleep(200*time.Millisecond), evalInto(&before, snapJS),
1557 inViewShot(`[slides-stage] [slides-slide]`, &a))
1558 if before.Mounted || !before.Shown {
1559 t.Fatalf("deck %d: shown %v, mounted %v before the late editor arrived; the delay did not apply", i, before.Shown, before.Mounted)
1560 }
1561 fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [contenteditable="true"]')`, chromedp.WithPollingTimeout(15*time.Second)),
1562 chromedp.Sleep(500*time.Millisecond), evalInto(&after, snapJS),
1563 inViewShot(`[slides-stage] [slides-slide]`, &b))
1564 for k := range before.Markup {
1565 if k < len(after.Markup) && before.Markup[k] != after.Markup[k] {
1566 t.Errorf("deck %d: text %d was\n %s\nand the editor drew\n %s", i, k, before.Markup[k], after.Markup[k])
1567 }
1568 }
1569 if before.Slide != after.Slide {
1570 t.Errorf("deck %d: the slide itself moved when the editor mounted: %s -> %s", i, before.Slide, after.Slide)
1571 }
1572 if fmt.Sprint(before.Blocks) != fmt.Sprint(after.Blocks) || fmt.Sprint(before.Lines) != fmt.Sprint(after.Lines) {
1573 t.Errorf("deck %d: the layout moved when the editor mounted:\n blocks %v\n -> %v\n lines %v\n -> %v", i, before.Blocks, after.Blocks, before.Lines, after.Lines)
1574 }
1575 if diff := pixelDiff(t, a, b); diff != "" {
1576 t.Errorf("deck %d: the slide's pixels changed when the editor mounted: %s", i, diff)
1577 if dir := os.Getenv("SLIDES_FONT_SHOTS"); dir != "" {
1578 _ = os.WriteFile(filepath.Join(dir, fmt.Sprintf("late-%d-before.png", i)), a, 0o644)
1579 _ = os.WriteFile(filepath.Join(dir, fmt.Sprintf("late-%d-after.png", i)), b, 0o644)
1580 }
1581 }
1582 p := fr.clean(t)
1583 sameLayout(t, p)
1584 }
1585}
1586
1587// inViewShot captures the first element sel matches, which must be on
1588// screen, as a PNG. chromedp.Screenshot captures with
1589// captureBeyondViewport, and for that capture Chromium lays the page
1590// out at another size for a frame (1×1 CSS px, seen by the font probe's
1591// frame sampler as the slide jumping to 80px wide and back); a capture
1592// of what is already in the viewport needs no relayout, so the page the
1593// probe watches is the page as shown. The clip is rounded as chromedp
1594// rounds it.
1595func inViewShot(sel string, buf *[]byte) chromedp.Action[chromedp.Void] {
1596 return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
1597 var r struct{ X, Y, Width, Height float64 }
1598 if _, err := evalInto(&r, `(r => ({ X: r.left, Y: r.top, Width: r.width, Height: r.height }))(document.querySelector(`+"`"+sel+"`"+`).getBoundingClientRect())`)(ctx, t); err != nil {
1599 return err
1600 }
1601 x, y := math.Round(r.X), math.Round(r.Y)
1602 clip := &page.Viewport{X: x, Y: y, Width: math.Round(r.Width + r.X - x), Height: math.Round(r.Height + r.Y - y), Scale: 1}
1603 pic, err := cdp.Call(ctx, t, page.CaptureScreenshot, page.CaptureScreenshotParams{
1604 Format: page.CaptureScreenshotFormatPng, Clip: clip,
1605 CaptureBeyondViewport: new(false), FromSurface: new(true),
1606 })
1607 if err != nil {
1608 return err
1609 }
1610 *buf = pic.Data
1611 return nil
1612 })
1613}
1614
1615// pixelDiff is "" when two PNG captures are the same picture, and the
1616// changed box otherwise.
1617func pixelDiff(t *testing.T, a, b []byte) string {
1618 t.Helper()
1619 ia, err := png.Decode(bytes.NewReader(a))
1620 if err != nil {
1621 t.Fatal(err)
1622 }
1623 ib, err := png.Decode(bytes.NewReader(b))
1624 if err != nil {
1625 t.Fatal(err)
1626 }
1627 if ia.Bounds() != ib.Bounds() {
1628 return fmt.Sprintf("size %v, then %v", ia.Bounds(), ib.Bounds())
1629 }
1630 r := ia.Bounds()
1631 minx, miny, maxx, maxy, n := r.Max.X, r.Max.Y, -1, -1, 0
1632 for y := r.Min.Y; y < r.Max.Y; y++ {
1633 for x := r.Min.X; x < r.Max.X; x++ {
1634 if ia.At(x, y) != ib.At(x, y) {
1635 n++
1636 minx, miny, maxx, maxy = min(minx, x), min(miny, y), max(maxx, x), max(maxy, y)
1637 }
1638 }
1639 }
1640 if n == 0 {
1641 return ""
1642 }
1643 return fmt.Sprintf("%d pixels in %d,%d–%d,%d", n, minx, miny, maxx, maxy)
1644}
1645
1646// until polls a JS expression from Go until it is true, riding over a
1647// navigation in progress (chromedp.Poll gives up when the page it was
1648// polling goes away).
1649func (fr *fontRig) until(t *testing.T, expr string) {
1650 t.Helper()
1651 deadline := time.Now().Add(15 * time.Second)
1652 for {
1653 var ok bool
1654 if err := chromedp.Do(fr.rig.Context(), evalInto(&ok, `!!(`+expr+`)`)); err == nil && ok {
1655 return
1656 }
1657 if time.Now().After(deadline) {
1658 t.Fatalf("never true within 15s: %s", expr)
1659 }
1660 time.Sleep(25 * time.Millisecond)
1661 }
1662}
1663
1664// markPage puts a marker on the page's window, which only a page load
1665// takes away.
1666const markPageJS = `window.__samePage = true; true`
1667
1668// The viewer changes slides in place (Astra's finding 4 on #27): Next,
1669// Next, then Previous by link, then the browser's Back, on the viewer and
1670// in its scriptless presenting mode. The page is never reloaded, the
1671// address follows each slide, and no frame between two slides is
1672// without one: slide text is never on screen, then gone.
1673func TestFontTheViewerChangesSlidesInPlace(t *testing.T) {
1674 three := strings.TrimSuffix(paperDeck, "]") + `,
1675 {"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},
1676 {"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]`
1677 for _, mode := range []string{"", "&present=1"} {
1678 t.Run("mode"+mode, func(t *testing.T) {
1679 fr := newFontRig(t)
1680 sqid := fr.deck(t, "Pages", three)
1681 fr.slow.Store(int64(600 * time.Millisecond))
1682 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1" + mode))
1683 fr.shown(t)
1684 fr.eval(t, markPageJS, nil)
1685 step := func(sel, want, path string) {
1686 t.Helper()
1687 fr.eval(t, clickJS(sel), nil)
1688 fr.until(t, `document.querySelector('[slides-slide]').textContent.includes(`+jsString(want)+`)`)
1689 var same bool
1690 var loc string
1691 fr.eval(t, `!!window.__samePage`, &same)
1692 fr.eval(t, `location.search`, &loc)
1693 if !same {
1694 t.Fatalf("going to %q loaded a page", want)
1695 }
1696 if !strings.Contains(loc, path) {
1697 t.Errorf("at %q the address is %q, want it to name %s", want, loc, path)
1698 }
1699 }
1700 step(`[slides-pager] a[rel="next"]`, "Second", "slide=2")
1701 step(`[slides-pager] a[rel="next"]`, "Third", "slide=3")
1702 step(`[slides-pager] a[rel="prev"]`, "Second", "slide=2")
1703 fr.rig.Run(chromedp.NavigateBack())
1704 fr.until(t, `document.querySelector('[slides-slide]').textContent.includes('Third')`)
1705 fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
1706 var same bool
1707 fr.eval(t, `!!window.__samePage`, &same)
1708 if !same {
1709 t.Error("Back loaded a page")
1710 }
1711 fr.cleanAcross(t)
1712 })
1713 }
1714}
1715
1716// When the next slide needs a family the page has not loaded — the deck
1717// changed after the page was opened — the current slide stays on screen
1718// until the family is in, then the next one replaces it, once, in it.
1719// Never a frame without a slide, never a face that has not loaded.
1720func TestFontTheNextSlideWaitsForItsFamilyBehindTheCurrentOne(t *testing.T) {
1721 fr := newFontRig(t)
1722 sqid := fr.deck(t, "Waits", inkDeck)
1723 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
1724 fr.shown(t)
1725 fr.eval(t, markPageJS, nil)
1726 fr.match.Store("LiberationMono-")
1727 fr.slow.Store(int64(1500 * time.Millisecond))
1728 fr.ops(t, sqid, `[{"op":"add_block","slide":"slidetwo0002","type":"code","region":"body","markdown":"new(code)"}]`)
1729 start := time.Now()
1730 fr.eval(t, clickJS(`[slides-pager] a[rel="next"]`), nil)
1731 fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
1732 var still bool
1733 fr.eval(t, `document.querySelector('[slides-slide]').textContent.includes('Ink heading')`, &still)
1734 if !still {
1735 t.Error("the current slide was taken down before the next one's family was in")
1736 }
1737 fr.until(t, `!!document.querySelector('[slides-slide] [data-block="code"]')`)
1738 if waited := time.Since(start); waited < time.Second {
1739 t.Errorf("the next slide went up after %v, before its family could have loaded", waited)
1740 }
1741 if got := fr.faceOf(t, `[slides-slide] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
1742 t.Errorf("the code is in %s", got)
1743 }
1744 var same bool
1745 fr.eval(t, `!!window.__samePage`, &same)
1746 if !same {
1747 t.Error("the page was reloaded")
1748 }
1749 fr.cleanAcross(t)
1750}
1751
1752// The projector pages in place too: the presenter's own Next and
1753// Previous on the projector (command forms) and a watcher's links on the
1754// follow-free projector page. Never a reload, never a frame without a
1755// slide. A watcher is somebody who may not drive: no token, and not the
1756// presenter signed in, who drives from their own slide window.
1757func TestFontTheProjectorPagesInPlace(t *testing.T) {
1758 fr := newFontRig(t)
1759 sqid := fr.deck(t, "Talk", paperDeck)
1760 session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
1761 for _, c := range []struct {
1762 name, path, next, prev string
1763 watcher bool
1764 }{
1765 {"the presenter's buttons", "/p/" + session + "?t=" + token, `[slides-bar] form input[value="next"]`, `[slides-bar] form input[value="prev"]`, false},
1766 {"a watcher's links", "/p/" + session, `[slides-bar] a[rel="next"]`, `[slides-bar] a[rel="prev"]`, true},
1767 } {
1768 t.Run(c.name, func(t *testing.T) {
1769 if c.watcher {
1770 fr.rig.Run(cdpStep(network.ClearBrowserCookies, cdp.Empty{}))
1771 }
1772 fr.rig.Run(chromedp.Evaluate[chromedp.Void](`window.__leaving = true`), fr.navigate(c.path))
1773 fr.until(t, `!window.__leaving && !!document.querySelector('[slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`)
1774 fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
1775 fr.eval(t, markPageJS, nil)
1776 press := func(sel string) {
1777 if strings.Contains(sel, "form") {
1778 fr.eval(t, `(() => { document.querySelector(`+jsString(sel)+`).form.requestSubmit(); return true })()`, nil)
1779 } else {
1780 fr.eval(t, clickJS(sel), nil)
1781 }
1782 }
1783 press(c.next)
1784 fr.until(t, `document.querySelector('[slides-slide]').textContent.includes('Second')`)
1785 press(c.prev)
1786 fr.until(t, `document.querySelector('[slides-slide]').textContent.includes('A heading in serif')`)
1787 fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
1788 var same bool
1789 fr.eval(t, `!!window.__samePage`, &same)
1790 if !same {
1791 t.Error("paging reloaded the projector")
1792 }
1793 fr.cleanAcross(t)
1794 })
1795 }
1796}
1797
1798// goTo navigates to path and waits for the new page's slide to be shown,
1799// not the old page's: the page being left is marked first.
1800func (fr *fontRig) goTo(t *testing.T, path string) {
1801 t.Helper()
1802 fr.rig.Run(chromedp.Evaluate[chromedp.Void](`window.__leaving = true`), fr.navigate(path))
1803 fr.until(t, `!window.__leaving && !!document.querySelector('[slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`)
1804}
1805
1806// uploadFamily puts file, renamed to name, in fr's library and answers
1807// the css name it was given and its ref.
1808func uploadFamily(t *testing.T, fr *fontRig, file, name string) (css, ref string) {
1809 t.Helper()
1810 f, err := fonts.Parse(libFont(t, file))
1811 if err != nil {
1812 t.Fatal(err)
1813 }
1814 data, err := f.Renamed(name, 400, false)
1815 if err != nil {
1816 t.Fatal(err)
1817 }
1818 if rec := uploadFonts(t, fr.app, fr.cookies, upFile{"f.ttf", data}); rec.Code != http.StatusOK {
1819 t.Fatalf("upload: %d\n%s", rec.Code, rec.Body)
1820 }
1821 var row slides.LibraryFont
1822 if err := fr.app.db.G.Where("ref = ?", sha(data)).First(&row).Error; err != nil {
1823 t.Fatal(err)
1824 }
1825 return row.CSSName, sha(data)
1826}
1827
1828// recordFamily is the editor's pick of css for sqid without its
1829// set_meta (POST /d/{sqid}/fonts), answering the family as
1830// meta.fontFiles carries it.
1831func recordFamily(t *testing.T, fr *fontRig, sqid, css string) string {
1832 t.Helper()
1833 rec := pickFont(t, fr.app, sqid, css, fr.cookies)
1834 if rec.Code != http.StatusOK {
1835 t.Fatalf("pick: %d\n%s", rec.Code, rec.Body)
1836 }
1837 return rec.Body.String()
1838}
1839
1840// probeAlso has the probe track the given uploaded families too.
1841func (fr *fontRig) probeAlso(names ...string) {
1842 b, _ := json.Marshal(names)
1843 fr.rig.Run(cdpStep(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `window.__fontProbeExtra = ` + strings.ToLower(string(b))}))
1844}
1845
1846// uploadedFontRig is a font rig with an object store and a paper deck
1847// whose headings lead with an uploaded family: Liberation Mono's regular
1848// renamed "Oddity Sans 2", a name a stack must quote (FontFace must
1849// not: it takes the name literally), with a monospace font's wide
1850// glyphs, so a heading drawn first in the stack's next family
1851// (Liberation Serif) and then in this one would visibly move. It
1852// returns the deck and the face's ref.
1853func uploadedFontRig(t *testing.T) (fr *fontRig, sqid, ref string) {
1854 t.Helper()
1855 fr = newFontRigWith(t, dirStore(t))
1856 css, ref := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Oddity Sans 2")
1857 sqid = fr.deck(t, "Uploaded", paperDeck)
1858 fam := recordFamily(t, fr, sqid, css)
1859 fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'Oddity Sans 2', Liberation Serif, Georgia, serif","body":""}}]`)
1860 fr.probeAlso("Oddity Sans 2")
1861 return fr, sqid, ref
1862}
1863
1864// An uploaded font is held to the catalog's rule on every surface: its
1865// file held for a second, well inside the deadline, the slides are not
1866// shown until it is in, and then the headings are in it from their
1867// first frame and never in anything else. The preload is the file the
1868// gate loads: one fetch per page.
1869func TestAnUploadedFontIsNotPaintedBeforeItLoads(t *testing.T) {
1870 fr, sqid, ref := uploadedFontRig(t)
1871 share := "/s/" + mintShareLink(t, fr.app, "/d/"+sqid, fr.cookies)
1872 session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
1873 fr.match.Store(ref)
1874 fr.slow.Store(int64(time.Second))
1875 for _, c := range []struct{ name, path string }{
1876 {"viewer", "/d/" + sqid + "?slide=1"},
1877 {"share link", share + "?slide=1"},
1878 {"projector", "/p/" + session},
1879 {"presenter window", "/p/" + session + "/notes?t=" + token},
1880 {"editor", "/d/" + sqid + "/edit"},
1881 } {
1882 t.Run(c.name, func(t *testing.T) {
1883 before := fr.hits(ref)
1884 start := time.Now()
1885 fr.goTo(t, c.path)
1886 if waited := time.Since(start); waited < 950*time.Millisecond {
1887 t.Fatalf("the slide was shown %v after navigating, before the uploaded face could have arrived", waited)
1888 }
1889 fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
1890 p := fr.clean(t)
1891 webEverywhere(t, p)
1892 sameLayout(t, p)
1893 odd := false
1894 for run, faces := range p.Seen {
1895 for f := range faces {
1896 if strings.Contains(f, "oddity sans 2:") && !strings.Contains(f, "oddity sans 2:web") {
1897 t.Errorf("%q was shown in %s", run, f)
1898 }
1899 odd = odd || strings.Contains(f, "oddity sans 2:web")
1900 }
1901 }
1902 if !odd {
1903 t.Error("no run was seen in the uploaded family")
1904 }
1905 if n := fr.hits(ref) - before; n != 1 {
1906 t.Errorf("the uploaded face was fetched %d times; the preload is the gate's one fetch", n)
1907 }
1908 })
1909 }
1910}
1911
1912// Past the deadline an uploaded family commits to its stack's next
1913// family, as a catalog one does: the headings are shown in Liberation
1914// Serif and stay in it when the late file lands; the uploaded faces
1915// never join the page.
1916func TestALateUploadedFontCommitsToItsFallback(t *testing.T) {
1917 fr, sqid, ref := uploadedFontRig(t)
1918 fr.match.Store(ref)
1919 fr.slow.Store(int64(4 * time.Second))
1920 fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
1921 fr.shown(t)
1922 fr.rig.Run(chromedp.Sleep(4 * time.Second))
1923 if fr.hits(ref) == 0 {
1924 t.Fatal("the uploaded face was never requested, so this cannot show it was not swapped in")
1925 }
1926 p := fr.clean(t)
1927 sameLayout(t, p)
1928 next := false
1929 for run, faces := range p.Seen {
1930 for f := range faces {
1931 if strings.Contains(f, "oddity sans 2:web") {
1932 t.Errorf("%q is in the uploaded face, which arrived after the page was shown", run)
1933 }
1934 next = next || strings.HasPrefix(f, "oddity sans 2:system,liberation serif:web")
1935 }
1936 }
1937 if !next {
1938 t.Errorf("no heading was seen in the stack's next family, Liberation Serif: %v", p.Seen)
1939 }
1940 var st struct {
1941 Committed bool
1942 Faces int
1943 }
1944 fr.eval(t, `({ Committed: !!(window.slidesFonts && window.slidesFonts.committed('u:Oddity Sans 2')),
1945 Faces: [...document.fonts].filter((f) => /oddity/i.test(f.family)).length })`, &st)
1946 if !st.Committed || st.Faces != 0 {
1947 t.Errorf("the late family: committed %v, %d of its faces in the page", st.Committed, st.Faces)
1948 }
1949}
1950
1951// A collaborator's pick reaches an editor open on the deck: the family,
1952// which this tab has never heard of, is learned from the changed deck,
1953// and the change waits for it like any change that brings in a family —
1954// applied once its face is in, or past the timeout with the family
1955// committed to its stack's next one, which it then never leaves.
1956func TestAnUploadedFontFromACollaboratorLoads(t *testing.T) {
1957 for _, c := range []struct {
1958 name string
1959 slow time.Duration
1960 late bool
1961 }{{"in time", time.Second, false}, {"late", 5 * time.Second, true}} {
1962 t.Run(c.name, func(t *testing.T) {
1963 fr := newFontRigWith(t, dirStore(t))
1964 css, ref := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Oddity Sans 2")
1965 sqid := fr.deck(t, "Collaborator", paperDeck)
1966 fam := recordFamily(t, fr, sqid, css)
1967 fr.probeAlso(css)
1968 fr.goTo(t, "/d/"+sqid+"/edit")
1969 fr.editable(t)
1970 fr.until(t, `document.documentElement.getAttribute('data-slides-fonts-prefetch') === 'done'`)
1971 fr.match.Store(ref)
1972 fr.slow.Store(int64(c.slow))
1973 fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'`+css+`', Liberation Serif, Georgia, serif","body":""}}]`)
1974 // The change reaches the heading on the stage.
1975 fr.until(t, `(() => { const h = document.querySelector('[slides-stage] [data-id="head00000001"]');
1976 return !!h && /oddity/i.test(getComputedStyle(h).fontFamily) })()`)
1977 fr.rig.Run(chromedp.Sleep(c.slow + time.Second))
1978 p := fr.cleanAcross(t)
1979 web, system := false, false
1980 for run, faces := range p.Seen {
1981 for f := range faces {
1982 if strings.Contains(f, "oddity sans 2:web") {
1983 web = true
1984 if c.late {
1985 t.Errorf("%q is in the uploaded face, which arrived after its change was shown", run)
1986 }
1987 }
1988 if strings.Contains(f, "oddity sans 2:system") {
1989 system = true
1990 if !c.late {
1991 t.Errorf("%q was shown in %s, though the face came in time", run, f)
1992 }
1993 }
1994 }
1995 }
1996 var st struct{ Loaded, Committed bool }
1997 fr.eval(t, `({ Loaded: window.slidesFonts.loaded('u:Oddity Sans 2'), Committed: window.slidesFonts.committed('u:Oddity Sans 2') })`, &st)
1998 if c.late {
1999 if !system || !st.Committed {
2000 t.Errorf("late: committed %v, a run seen in its fallback %v", st.Committed, system)
2001 }
2002 } else if !web || !st.Loaded {
2003 t.Errorf("in time: loaded %v, a run seen in it %v", st.Loaded, web)
2004 }
2005 if n := fr.hits(ref); n != 1 {
2006 t.Errorf("the uploaded face was fetched %d times", n)
2007 }
2008 })
2009 }
2010}
2011
2012// An upload whose own name is a catalog family's ("Liberation Serif")
2013// gets a css name of its own (library.go's cssFamilyName), loads under
2014// it, and the deck's catalog Serif headings never change face: the
2015// browser has only the catalog's four faces under that name.
2016func TestAnUploadedFontNamedLikeACatalogFamilyKeepsItsOwnName(t *testing.T) {
2017 fr := newFontRigWith(t, dirStore(t))
2018 css, _ := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Liberation Serif")
2019 if strings.EqualFold(css, "Liberation Serif") {
2020 t.Errorf("the upload took the catalog's name %q", css)
2021 }
2022 sqid := fr.deck(t, "Named", paperDeck)
2023 fam := recordFamily(t, fr, sqid, css)
2024 fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"","body":"'`+css+`', Liberation Sans, sans-serif"}}]`)
2025 fr.probeAlso(css)
2026 fr.goTo(t, "/d/"+sqid+"?slide=1")
2027 fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
2028 p := fr.clean(t)
2029 webEverywhere(t, p)
2030 sameLayout(t, p)
2031 if faces := p.Seen["A heading in serif@head00000001"]; len(faces) != 1 || !faces["liberation serif:web 700 normal"] {
2032 t.Errorf("the heading was seen in %v, want only the catalog Serif", sortedKeys(faces))
2033 }
2034 body := false
2035 for f := range p.Seen["Body@text00000001"] {
2036 body = body || strings.HasPrefix(f, strings.ToLower(css)+":web")
2037 }
2038 if !body {
2039 t.Errorf("the body was seen in %v, want the upload under %q", sortedKeys(p.Seen["Body@text00000001"]), css)
2040 }
2041 var serif int
2042 fr.eval(t, `[...document.fonts].filter((f) => f.family.replace(/["']/g, '').toLowerCase() === 'liberation serif').length`, &serif)
2043 if serif != 4 {
2044 t.Errorf("%d faces in the page are called Liberation Serif, want the catalog's four", serif)
2045 }
2046}
2047