//go:build browser
// The font checks in a real Chromium, through the production serving
// stack (rastrillo.Handler with Slides' own ServeOptions, CSP included),
// with the font files slowed or refused on the way out:
//
// RASTRILLO_CHROME=… go test -tags browser -run Font ./internal/slidestest/
//
// Paul, 2026-10-26: "No flashing, ever!" Text in one face and then
// another, a visible gap of invisible text, and a layout that moves
// after the page is shown all count. Every check here samples the page
// on every animation frame and every DOM change, from before the first
// byte of HTML is parsed, and fails on any sample where slide text is
// visible in a face that has not loaded, any run of text seen in two
// faces, and any slide whose layout differs from the one it was first
// shown with.
//
// The probe reads only what any page has: the computed font-family of
// each run and the faces in document.fonts. So it judges the code on
// main (faces declared in slides.css with font-display: swap) by the
// same rule as the gate, and fails it.
package slidestest
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html"
"image/png"
"io"
"log/slog"
"math"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/blobs"
"amadan.net/rastrillo/rastrillo/db"
"amadan.net/rastrillo/rastrillo/harness"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/input"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
slides "amadan.net/oficina/slides/internal/slides"
"amadan.net/oficina/slides/internal/slides/fonts"
)
// fontRig is Slides behind its production serving stack, with every
// font file (/static/fonts/*.woff2, and a deck's own under
// {base}/fonts/{ref}) held for slow before it is served
// when its path contains match, any path containing blocked answered
// 404, and the editor bundle held for editorDelay. It is signed in, in
// the browser and as an agent for the API.
type fontRig struct {
rig *harness.Rig
app *testApp
cookies []*http.Cookie
token string
slow atomic.Int64
match atomic.Value
blocked atomic.Value
editorDelay atomic.Int64
// wrap, when set, answers every request in place of the rig's own
// handling, which it is handed as next: a check can hold a request,
// or cut a stream, on the way out.
wrap atomic.Pointer[func(w http.ResponseWriter, r *http.Request, next http.Handler)]
mu sync.Mutex
fontHits map[string]int
}
func newFontRig(t *testing.T) *fontRig {
t.Helper()
return newFontRigWith(t, nil)
}
// newFontRigWith is newFontRig with an object store, so a deck can hold
// pictures.
func newFontRigWith(t *testing.T, store blobs.Store) *fontRig {
t.Helper()
fr := &fontRig{fontHits: map[string]int{}}
fr.match.Store("")
fr.blocked.Store("")
mailer := &fakeMailer{}
fr.rig = harness.New(t, func(origin string) http.Handler {
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
if err != nil {
t.Fatalf("db.Open: %v", err)
}
t.Cleanup(func() { d.Close() })
mux, a, err := slides.New(d, slides.Config{
KeymailServers: testKeymailServers,
Origin: origin,
InstanceKey: testInstanceKey,
Mailer: mailer,
AllowedAddresses: []string{allowedAddress},
Blobs: store,
Logger: logger,
})
if err != nil {
t.Fatalf("slides.New: %v", err)
}
t.Cleanup(func() { a.Close() })
mailer.flush = a.FlushMail
served, closeFn, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: logger}, mux))
if err != nil {
t.Fatalf("rastrillo.Handler: %v", err)
}
t.Cleanup(func() { _ = closeFn() })
fr.app = &testApp{Handler: served, mailer: mailer, db: d, mux: mux, app: a}
var rest http.Handler
outer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if wrap := fr.wrap.Load(); wrap != nil {
(*wrap)(w, r, rest)
return
}
rest.ServeHTTP(w, r)
})
rest = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if b := fr.blocked.Load().(string); b != "" && strings.Contains(r.URL.Path, b) {
http.NotFound(w, r)
return
}
// The bundle, not editor.css: holding the stylesheet would hold
// the first paint, which is not what a late editor is.
if strings.HasPrefix(r.URL.Path, "/static/editor.") && strings.HasSuffix(r.URL.Path, ".js") {
time.Sleep(time.Duration(fr.editorDelay.Load()))
}
if strings.HasPrefix(r.URL.Path, "/static/fonts/") || uploadedFaceURL.MatchString(r.URL.Path) {
fr.mu.Lock()
fr.fontHits[r.URL.Path]++
fr.mu.Unlock()
if strings.Contains(r.URL.Path, fr.match.Load().(string)) {
time.Sleep(time.Duration(fr.slow.Load()))
}
}
served.ServeHTTP(w, r)
})
return outer
})
fr.cookies = signedIn(t, fr.app, allowedAddress)
fr.token = mintAgent(t, fr.app, fr.cookies, "fonts")
var set []chromedp.Action[chromedp.Void]
for _, c := range fr.cookies {
set = append(set, cdpStep(network.SetCookie, network.SetCookieParams{
Name: c.Name, Value: c.Value, URL: fr.rig.Origin + "/",
HTTPOnly: new(c.HttpOnly), Secure: new(c.Secure), SameSite: network.CookieSameSiteLax,
}))
}
set = append(set, cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 900, DeviceScaleFactor: 1, Mobile: false}),
// No HTTP cache between checks: each one is a first visit, which
// is when the fonts have to come over the network.
cdpStep(network.SetCacheDisabled, network.SetCacheDisabledParams{CacheDisabled: true}),
cdpStep(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: probeJS}))
fr.rig.Run(set...)
return fr
}
// deck makes a deck over the API holding exactly what ops says: the
// first slide every new deck is given is removed in the same batch.
func (fr *fontRig) deck(t *testing.T, title, ops string) string {
t.Helper()
sqid := apiDeck(t, fr.app, fr.token, title)
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
var remove []string
if s, ok := view["slides"].([]any); ok {
for _, x := range s {
if id, _ := x.(map[string]any)["id"].(string); id != "" {
remove = append(remove, `{"op":"remove_slide","id":"`+id+`"}`)
}
}
}
body := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(ops), "["), "]"))
if body != "" {
remove = append(remove, body)
}
fr.ops(t, sqid, "["+strings.Join(remove, ",")+"]")
return sqid
}
// ops applies a batch over the API, as a collaborator's agent would.
func (fr *fontRig) ops(t *testing.T, sqid, batch string) {
t.Helper()
apiJSON(t, fr.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", fr.token, `{"ops":`+batch+`}`, http.StatusOK)
}
func (fr *fontRig) hits(path string) int {
fr.mu.Lock()
defer fr.mu.Unlock()
n := 0
for p, c := range fr.fontHits {
if strings.Contains(p, path) {
n += c
}
}
return n
}
// navigate goes to path without waiting for the load event, which waits
// for every font the page has started fetching: a check of what happens
// while a font is slow must be able to act while it is.
func (fr *fontRig) navigate(path string) chromedp.Action[chromedp.Void] {
return cdpStep(page.Navigate, page.NavigateParams{URL: fr.rig.Origin + path})
}
// shown waits until a slide is on screen: the hold is off (or there was
// none) and a slide is visible.
func (fr *fontRig) shown(t *testing.T) {
t.Helper()
fr.rig.Run(chromedp.Poll[chromedp.Void](`(() => { const s = document.querySelector('[slides-slide]');
return !!s && getComputedStyle(s).visibility === 'visible' && document.documentElement.getAttribute('data-slides-fonts') !== 'pending' })()`, chromedp.WithPollingTimeout(15*time.Second)))
}
func (fr *fontRig) eval(t *testing.T, js string, out any) {
t.Helper()
fr.rig.Run(evalValue(out, js, func(p *cdpruntime.EvaluateParams) { p.AwaitPromise = new(true) }))
}
// probeJS runs before the page's own HTML. On every frame and every DOM
// change it looks at every run of slide text that is visible, works out
// for each Liberation family its stack names (and each family named, in
// lower case, in window.__fontProbeExtra: a deck's uploaded families)
// whether that family has a face in document.fonts in the run's weight
// and slope and whether it has loaded, and records a violation if a
// face the run can be drawn in
// is in the set but not loaded (drawn in a fallback while it loads, or
// invisible). It records every distinct face a run has been seen in, so
// a check can say a run never changed face; the slides' layout, every
// time it changes after text is first visible; and any frame on which
// slide text that had been visible was gone.
const probeJS = `(() => {
const LIB = new Set(['liberation sans', 'liberation serif', 'liberation mono']);
const log = { violations: [], seen: {}, firstVisible: null, samples: 0, layouts: [], gaps: [], families: {}, errors: [] };
window.__fontProbe = log;
// A rejection nobody handled, or an uncaught error, is a failure too:
// a refusal that threw stalled every collaborator's change after it
// while the page looked fine (Astra, #27).
addEventListener('unhandledrejection', (e) => log.errors.push('unhandled rejection: ' + String((e.reason && (e.reason.stack || e.reason.message)) || e.reason)));
addEventListener('error', (e) => log.errors.push('uncaught: ' + e.message));
const names = (stack) => stack.split(',').map((p) => p.trim().replace(/^["']+|["']+$/g, '')).filter(Boolean);
const bucket = (w) => (Number(w) >= 600 ? 700 : 400);
const stateOf = (family, weight, style) => {
const faces = [...document.fonts].filter((f) => f.family.replace(/["']/g, '').toLowerCase() === family);
if (!faces.length) return 'system';
const exact = faces.filter((f) => f.style === style && bucket(f.weight) === bucket(weight));
const pick = exact.length ? exact : faces;
return pick.some((f) => f.status === 'loaded') ? 'web' : 'pending';
};
window.__fontState = stateOf;
let lastLayout = null;
let wasVisible = false;
// Nothing is painted before the first frame (a page's stylesheets
// block rendering), so a DOM change before it is a state nobody saw.
let rendering = false;
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; };
const sample = (why) => {
if (why === 'frame') rendering = true;
if (!rendering) return;
const slides = [...document.querySelectorAll('[slides-slide]')];
if (!slides.length) return;
log.samples++;
let visible = 0;
const parts = [];
for (const s of slides) {
const sr = s.getBoundingClientRect();
const w = document.createTreeWalker(s, NodeFilter.SHOW_TEXT);
for (let n = w.nextNode(); n; n = w.nextNode()) {
if (!n.data.trim()) continue;
const el = n.parentElement;
const cs = getComputedStyle(el);
if (cs.visibility !== 'visible') continue;
const range = document.createRange();
range.selectNodeContents(n);
const r = range.getBoundingClientRect();
if (!r.width && !r.height) continue;
visible++;
if (log.firstVisible === null) log.firstVisible = performance.now();
const fams = names(cs.fontFamily).map((x) => x.toLowerCase()).filter((x) => LIB.has(x) || (window.__fontProbeExtra || []).includes(x));
const states = fams.map((f) => f + ':' + stateOf(f, cs.fontWeight, cs.fontStyle));
for (const f of fams) log.families[f] = true;
const block = el.closest('[data-id]');
const key = n.data.trim().slice(0, 32) + '@' + (block ? block.getAttribute('data-id') : '');
const desc = (states.join(',') || 'system:' + (names(cs.fontFamily)[0] || '')) + ' ' + bucket(cs.fontWeight) + ' ' + cs.fontStyle;
(log.seen[key] = log.seen[key] || {})[desc] = true;
for (const st of states) {
if (st.endsWith(':pending')) {
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') + ']');
}
}
}
// The layout: each block's box and the box of all its text (the
// union of its text's own boxes), relative to its slide. Per
// block rather than per text node, and the text's boxes rather
// than its elements', so the editor drawing a block's text in
// elements of its own (a
per line) is no change while the
// picture is the same; a face that changes moves the text.
const round = (b) => [b.left - sr.left, b.top - sr.top, b.width, b.height].map((v) => Math.round(v * 2) / 2).join(',');
for (const b of s.querySelectorAll('[slides-block]')) {
if (getComputedStyle(b).visibility !== 'visible') continue;
let box = null;
const tw = document.createTreeWalker(b, NodeFilter.SHOW_TEXT);
for (let t = tw.nextNode(); t; t = tw.nextNode()) {
if (!t.data.trim()) continue;
const range = document.createRange();
range.selectNodeContents(t);
for (const r of range.getClientRects()) {
if (!r.width && !r.height) continue;
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) }
: { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
}
}
const text = box ? round({ left: box.left, top: box.top, width: box.right - box.left, height: box.bottom - box.top }) : '-';
parts.push((b.getAttribute('data-id') || b.getAttribute('data-block')) + '=' + round(b.getBoundingClientRect()) + ';' + text);
}
}
if (why !== 'frame') return;
if (visible) {
wasVisible = true;
const sig = hash(parts.join('|'));
if (sig !== lastLayout) {
log.layouts.push({ ms: Math.round(performance.now()), sig });
lastLayout = sig;
}
} else if (wasVisible) {
log.gaps.push(Math.round(performance.now()));
}
};
const frame = () => { sample('frame'); requestAnimationFrame(frame); };
requestAnimationFrame(frame);
new MutationObserver(() => sample('mutation')).observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
})()`
type probe struct {
Violations []string `json:"violations"`
Seen map[string]map[string]bool `json:"seen"`
FirstVisible *float64 `json:"firstVisible"`
Samples int `json:"samples"`
Layouts []struct {
Ms int `json:"ms"`
Sig string `json:"sig"`
} `json:"layouts"`
Gaps []int `json:"gaps"`
Families map[string]bool `json:"families"`
Errors []string `json:"errors"`
}
func (fr *fontRig) probe(t *testing.T) probe {
t.Helper()
var raw string
fr.rig.Run(evalInto(&raw, `JSON.stringify(window.__fontProbe)`))
var p probe
if err := json.Unmarshal([]byte(raw), &p); err != nil {
t.Fatalf("probe: %v (%s)", err, raw)
}
if p.Samples < 10 {
t.Fatalf("the probe sampled the page %d times; it cannot see what it is checking", p.Samples)
}
return p
}
// clean fails on any violation, any run seen in two faces, and any
// frame on which visible slide text went missing. It returns the probe.
func (fr *fontRig) clean(t *testing.T) probe {
t.Helper()
return fr.cleanWith(t, false)
}
// cleanAcross is clean for a check whose subject is a change of family —
// a theme, a font, a code mark: a run may be seen in more than one face
// so long as every one of them is a web face that had loaded, which is
// the change, and not the fallback on the way to it.
func (fr *fontRig) cleanAcross(t *testing.T) probe {
t.Helper()
return fr.cleanWith(t, true)
}
func (fr *fontRig) cleanWith(t *testing.T, across bool) probe {
t.Helper()
p := fr.probe(t)
for i, v := range p.Violations {
if i == 3 {
t.Errorf("…and %d more", len(p.Violations)-3)
break
}
t.Error(v)
}
for run, faces := range p.Seen {
if len(faces) == 1 {
continue
}
// A web face that had loaded, or a system face the deck itself
// chose (its stack names no Liberation family): either is a face
// somebody asked for. A Liberation family in its fallback, or in
// a face still loading, is not.
allWeb := true
for f := range faces {
chosen := strings.HasPrefix(f, "system:")
allWeb = allWeb && (chosen || strings.Contains(f, ":web")) && !inFallback.MatchString(f) && !strings.Contains(f, ":pending")
}
if !across || !allWeb {
t.Errorf("%q was shown in more than one face: %v", run, sortedKeys(faces))
}
}
if len(p.Gaps) > 0 {
t.Errorf("slide text was on screen, then gone, at %v ms", p.Gaps)
}
for _, e := range p.Errors {
t.Errorf("the page: %s", e)
}
if p.FirstVisible == nil {
t.Error("no slide text was ever visible")
}
return p
}
// sameLayout fails unless the slides kept the layout they were first
// shown with.
func sameLayout(t *testing.T, p probe) {
t.Helper()
if len(p.Layouts) > 1 {
t.Errorf("the slide was shown, then its layout changed %d times (at %v)", len(p.Layouts)-1, p.Layouts)
}
}
func sortedKeys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
// webEverywhere fails unless every face every run was seen in is a web
// face: nothing committed, nothing in a system face.
func webEverywhere(t *testing.T, p probe) {
t.Helper()
for run, faces := range p.Seen {
for f := range faces {
if inFallback.MatchString(f) {
t.Errorf("%q was shown in %s, though its fonts arrived in time", run, f)
}
}
}
}
// decks the checks use. paper sets headings in Liberation Serif and
// everything else in Liberation Sans; a code block or a code mark brings
// in Liberation Mono.
const (
paperDeck = `[{"op":"set_meta","theme":"paper","title":"Paper"},
{"op":"add_slide","id":"slideone0001","layout":"flow","template":"title-body"},
{"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"A heading in serif"},
{"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."},
{"op":"add_slide","id":"slidetwo0002","layout":"flow","template":"title-body"},
{"op":"add_block","slide":"slidetwo0002","id":"head00000002","type":"heading","region":"heading","props":{"level":2},"markdown":"Second"},
{"op":"add_block","slide":"slidetwo0002","id":"code00000002","type":"code","region":"body","markdown":"func main() {\n\tprintln(1)\n}"}]`
inkDeck = `[{"op":"set_meta","theme":"ink","title":"Ink"},
{"op":"add_slide","id":"slideone0001","layout":"flow","template":"title-body"},
{"op":"add_block","slide":"slideone0001","id":"head00000001","type":"heading","region":"heading","props":{"level":1},"markdown":"Ink heading"},
{"op":"add_block","slide":"slideone0001","id":"text00000001","type":"text","region":"body","markdown":"Plain body text, nothing in code, **bold** and *italic*."},
{"op":"add_slide","id":"slidetwo0002","layout":"flow","template":"title-body"},
{"op":"add_block","slide":"slidetwo0002","id":"head00000002","type":"heading","region":"heading","props":{"level":2},"markdown":"Second slide"}]`
)
// Slide text is not painted before its fonts are ready. Every font file
// is held for 700 ms, well under the gate's deadline, so the right
// answer is: nothing visible until every face of every family the deck
// uses has loaded, then the text, once, in those faces.
func TestFontSlideTextIsNotPaintedBeforeItsFontsAreReady(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Faces", paperDeck)
fr.slow.Store(int64(700 * time.Millisecond))
start := time.Now()
fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
fr.shown(t)
if waited := time.Since(start); waited < 650*time.Millisecond {
t.Fatalf("the slide was shown %v after navigating, before the fonts could have arrived: the slowdown did not apply", waited)
}
fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
p := fr.clean(t)
webEverywhere(t, p)
sameLayout(t, p)
for _, f := range []string{"liberation sans", "liberation serif", "liberation mono"} {
if !p.Families[f] {
t.Errorf("no run was seen in %s; the deck is meant to use all three", f)
}
}
}
// Past the deadline the gate commits: the slide appears with that
// family in its system fallback and stays in it when the files finally
// arrive. Shown once, never swapped, and the layout it was shown with
// is the one it keeps.
func TestFontALateFamilyCommitsToItsFallbackAndNeverSwaps(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Late", paperDeck)
// Serif alone is late: slowing every file would hold all six of this
// HTTP/1.1 server's connections and keep the gate's own script from
// arriving before the deadline.
fr.match.Store("LiberationSerif-")
fr.slow.Store(int64(4 * time.Second))
fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
fr.shown(t)
// Let the late files land, and keep sampling while they do.
fr.rig.Run(chromedp.Sleep(4 * time.Second))
if n := fr.hits("LiberationSerif-"); n == 0 {
t.Fatal("Liberation Serif was never requested, so this cannot show it was not swapped in")
}
p := fr.clean(t)
sameLayout(t, p)
serif := false
for run, faces := range p.Seen {
for f := range faces {
if strings.Contains(f, "liberation serif:web") {
t.Errorf("%q is in the web serif, which arrived after the page was shown", run)
}
serif = serif || strings.Contains(f, "liberation serif")
}
}
if !serif {
t.Error("no run was seen in the heading's stack; the check saw nothing")
}
}
// The first reveal is the final layout, on every surface that draws a
// slide in the deck's faces: the viewer at a desktop and at a phone
// width, its scriptless presenting mode, the projector, the audience's
// follow view, and the editor — with the editor in time, and with it
// so late that the slide is shown before it mounts.
func TestFontTheFirstRevealIsTheFinalLayout(t *testing.T) {
for _, c := range []struct {
name string
path func(fr *fontRig, sqid string) string
width int64
editorDelay time.Duration
after time.Duration
}{
{name: "viewer", path: func(_ *fontRig, s string) string { return "/d/" + s + "?slide=1" }},
{name: "viewer at a phone width", path: func(_ *fontRig, s string) string { return "/d/" + s + "?vp=phone" }, width: 390},
{name: "viewer presenting", path: func(_ *fontRig, s string) string { return "/d/" + s + "?present=1&slide=2" }},
{name: "projector", path: func(fr *fontRig, s string) string {
session, _ := startPresenting(t, fr.app, "/d/"+s, fr.cookies)
return "/p/" + session
}},
{name: "follow view", path: func(fr *fontRig, s string) string {
share := "/s/" + mintShareLink(t, fr.app, "/d/"+s, fr.cookies)
startPresenting(t, fr.app, "/d/"+s, fr.cookies)
return share + "?follow=1"
}, after: 6 * time.Second},
{name: "editor in time", path: func(_ *fontRig, s string) string { return "/d/" + s + "/edit" }},
{name: "editor late", path: func(_ *fontRig, s string) string { return "/d/" + s + "/edit" }, editorDelay: 5 * time.Second, after: 6 * time.Second},
} {
t.Run(c.name, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Reveal", paperDeck)
if c.width > 0 {
fr.rig.Run(cdpStep(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: c.width, Height: 800, DeviceScaleFactor: 1, Mobile: true}))
}
path := c.path(fr, sqid)
fr.slow.Store(int64(500 * time.Millisecond))
fr.editorDelay.Store(int64(c.editorDelay))
fr.rig.Run(fr.navigate(path))
fr.shown(t)
after := c.after
if after == 0 {
after = 2 * time.Second
}
fr.rig.Run(chromedp.Sleep(after))
if c.editorDelay > 0 {
var bound bool
fr.eval(t, `!!document.querySelector('[slides-stage] [contenteditable="true"]')`, &bound)
if !bound {
t.Fatal("the late editor never mounted, so this cannot show its mount moved nothing")
}
}
p := fr.clean(t)
sameLayout(t, p)
})
}
}
// If the font gate's script never arrives, the slides are still shown,
// in their system faces, and never change face. If the hold itself never
// arrives, nothing is held at all.
func TestFontAMissingScriptNeverHidesTheSlides(t *testing.T) {
for _, c := range []struct {
blocked string
path string
wait time.Duration
}{
{"/static/fontsgate.", "", 7 * time.Second},
{"/static/fontsgate.", "/edit", 3 * time.Second},
{"/static/fontshold.", "", 2 * time.Second},
{"/static/fontshold.", "/edit", 3 * time.Second},
} {
t.Run(c.blocked+c.path, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Missing", paperDeck)
fr.blocked.Store(c.blocked)
fr.rig.Allow(http.MethodGet, c.blocked, http.StatusNotFound)
fr.rig.Run(fr.navigate("/d/"+sqid+c.path), chromedp.Sleep(c.wait))
var visible string
fr.eval(t, `getComputedStyle(document.querySelector('[slides-slide]')).visibility`, &visible)
if visible != "visible" {
t.Fatalf("the slide is %s with %s missing", visible, c.blocked)
}
p := fr.clean(t)
sameLayout(t, p)
})
}
}
// Without JavaScript nothing is held and no web face is used: the slide
// is in its system faces from the first paint and stays in them, so
// there is nothing to wait for and nothing to swap.
func TestFontWithoutJavaScriptTheSystemFacesAreFinal(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "No script", paperDeck)
fr.rig.Run(cdpStep(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}))
fr.slow.Store(int64(1500 * time.Millisecond))
// Until the stylesheets are in nothing is painted at all (they block
// rendering), so the first look is once slides.css has arrived.
// (A loop of plain evaluations, not chromedp.Poll: its polling is a
// promise in the page, and the page runs no script.)
fr.rig.Run(fr.navigate("/d/"+sqid+"?slide=1"), chromedp.WaitReady(chromedp.CSS(`[slides-slide]`)))
for deadline := time.Now().Add(10 * time.Second); ; {
var in bool
fr.rig.Run(evalInto(&in, `[...document.styleSheets].some((s) => s.href && s.href.includes('/static/slides.') && s.cssRules.length > 0)`))
if in {
break
}
if time.Now().After(deadline) {
t.Fatal("slides.css never arrived")
}
time.Sleep(20 * time.Millisecond)
}
read := func() (vis string, families []string, web int) {
var out struct {
Vis string
Families []string
Web int
}
fr.rig.Run(evalInto(&out, `(() => {
const runs = [...document.querySelectorAll('[slides-slide] h1, [slides-slide] h2, [slides-slide] p, [slides-slide] code, [slides-slide] strong, [slides-slide] em')];
return { Vis: getComputedStyle(document.querySelector('[slides-slide]')).visibility,
Families: runs.map((e) => getComputedStyle(e).fontFamily + ' ' + getComputedStyle(e).fontWeight + ' ' + getComputedStyle(e).fontStyle),
Web: [...document.fonts].filter((f) => f.family.includes('Liberation') && f.status !== 'unloaded').length };
})()`))
return out.Vis, out.Families, out.Web
}
vis, early, _ := read()
fr.rig.Run(chromedp.Sleep(3 * time.Second))
_, late, web := read()
if vis != "visible" {
t.Errorf("without JavaScript the slide is %s", vis)
}
if strings.Join(early, "|") != strings.Join(late, "|") || len(early) == 0 {
t.Errorf("without JavaScript the text is set in\n %v\nthen\n %v", early, late)
}
if web != 0 {
t.Errorf("%d web faces were put to use without JavaScript", web)
}
}
// The preloads are the gate's: each file the slides need is fetched once
// (the preload, which the gate's own load then uses), none twice, and no
// file of a family the deck does not use is fetched before the slide is
// shown.
func TestFontThePreloadsAreTheFacesTheGateLoads(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Preloads", inkDeck)
fr.slow.Store(int64(300 * time.Millisecond))
fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
fr.shown(t)
fr.rig.Run(chromedp.Sleep(1 * time.Second))
fr.mu.Lock()
hits := map[string]int{}
for p, n := range fr.fontHits {
hits[p] = n
}
fr.mu.Unlock()
sans := 0
for p, n := range hits {
switch {
case strings.Contains(p, "LiberationSans-"):
sans++
if n != 1 {
t.Errorf("%s was fetched %d times; a preload the gate does not use is a second download", p, n)
}
default:
t.Errorf("%s was fetched, but the ink deck draws only in Liberation Sans", p)
}
}
if sans != 4 {
t.Errorf("%d of Liberation Sans's four files were fetched: %v", sans, hits)
}
p := fr.clean(t)
webEverywhere(t, p)
}
// The remote draws its slides as pictures and its notes in the chrome's
// face: no web face is ever in its document, and no font file is
// fetched for it, so nothing on it could change face mid-talk. The
// presenter window draws its slides live (Task 9), so it takes the
// gate: its slides are in the deck's faces once shown, and its own
// words, the notes among them, stay in the chrome's.
func TestFontThePresenterAndRemoteDrawInNoWebFace(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Talk", paperDeck)
fr.ops(t, sqid, `[{"op":"set_notes","id":"slideone0001","markdown":"Notes with **bold** and `+"`code`"+`."}]`)
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
remote := "/p/" + session + "/remote?t=" + token
before := fr.hits("/static/fonts/")
fr.rig.Run(fr.navigate(remote), chromedp.WaitReady(chromedp.CSS(`main`)), chromedp.Sleep(1500*time.Millisecond))
var out struct {
Web int
Liberty []string
}
fr.eval(t, `(() => ({ Web: [...document.fonts].filter((f) => /liberation/i.test(f.family)).length,
Liberty: [...document.querySelectorAll('main *')].filter((e) => e.childNodes.length && [...e.childNodes].some((n) => n.nodeType === 3 && n.data.trim()))
.map((e) => getComputedStyle(e).fontFamily).filter((f) => /liberation/i.test(f)) }))()`, &out)
if out.Web != 0 {
t.Errorf("%s: %d web faces in the document", remote, out.Web)
}
if len(out.Liberty) != 0 {
t.Errorf("%s: text set in a deck face: %v", remote, out.Liberty)
}
if after := fr.hits("/static/fonts/"); after != before {
t.Errorf("%s fetched %d font files", remote, after-before)
}
window := "/p/" + session + "/notes?t=" + token
before = fr.hits("/static/fonts/")
fr.goTo(t, window)
var got struct {
Gate bool
Loaded int
Slide []string
Chrome []string
Visible bool
}
fr.eval(t, `document.fonts.ready.then(() => {
const texts = (root, inside) => [...root.querySelectorAll('*')].filter((e) => (e.closest('[slides-slide]') !== null) === inside &&
[...e.childNodes].some((n) => n.nodeType === 3 && n.data.trim())).map((e) => getComputedStyle(e).fontFamily);
const main = document.querySelector('main');
return { Gate: !!document.querySelector('meta[name="slides-fonts"]'),
Loaded: [...document.fonts].filter((f) => /liberation/i.test(f.family) && f.status === 'loaded').length,
Slide: texts(document.querySelector('[presenter-panel="now"]'), true),
Chrome: texts(main, false).filter((f) => /liberation/i.test(f)),
Visible: getComputedStyle(document.querySelector('[presenter-panel="now"] [slides-slide]')).visibility === 'visible' };
})`, &got)
if !got.Gate {
t.Errorf("%s: the presenter window does not take the font gate", window)
}
if got.Loaded == 0 || fr.hits("/static/fonts/") == before {
t.Errorf("%s: no deck face was loaded for the live slides (%d loaded)", window, got.Loaded)
}
if !got.Visible || len(got.Slide) == 0 {
t.Fatalf("%s: the current slide is not shown (visible %v, %d runs of text)", window, got.Visible, len(got.Slide))
}
for _, f := range got.Slide {
if !strings.Contains(strings.ToLower(f), "liberation") {
t.Errorf("%s: slide text in %q, not the deck's face", window, f)
}
}
if len(got.Chrome) != 0 {
t.Errorf("%s: the window's own words are set in a deck face: %v", window, got.Chrome)
}
}
// inFallback matches a face description of a Liberation family drawn in
// its system fallback ("liberation serif:system 700 normal").
var inFallback = regexp.MustCompile(`liberation [a-z]+:system`)
// editable waits until the editor accepts input: its text is bound and
// the slide is shown.
func (fr *fontRig) editable(t *testing.T) {
t.Helper()
fr.shown(t)
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)))
}
// waitLogJS records, on every change, whether the editor's parts are
// inert, what the font status says and is it visible, and the stage's
// text, so a check can see a wait from start to end.
const waitLogJS = `(() => {
window.__waitLog = [];
const status = document.querySelector('[slides-fonts-status]');
const rec = () => window.__waitLog.push({
ms: Math.round(performance.now()),
inert: !!document.querySelector('[slides-stage-pane]').inert && !!document.querySelector('aside[slides-inspector][estilo-card]').inert &&
!!document.querySelector('[slides-strip-nav]').inert && !!document.querySelector('[slides-menubar]').inert &&
!!document.querySelector('[slides-deck-dialog]').inert,
state: (status && status.getAttribute('data-state')) || '',
said: (status && status.querySelector('[role="status"]').textContent.trim()) || '',
text: (document.querySelector('[slides-stage]') || { innerText: '' }).innerText.replace(/\n+/g, '|'),
});
rec();
new MutationObserver(rec).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['inert', 'data-state'] });
return true;
})()`
type waitEntry struct {
Ms int `json:"ms"`
Inert bool `json:"inert"`
State string `json:"state"`
Said string `json:"said"`
Text string `json:"text"`
}
func (fr *fontRig) waitLog(t *testing.T) []waitEntry {
t.Helper()
var raw string
fr.rig.Run(evalInto(&raw, `JSON.stringify(window.__waitLog || [])`))
var log []waitEntry
if err := json.Unmarshal([]byte(raw), &log); err != nil {
t.Fatalf("wait log: %v", err)
}
return log
}
// waited reports whether the log shows a wait: the editor inert and the
// status saying a font is loading, in words.
func waited(log []waitEntry) bool {
for _, e := range log {
if e.Inert && e.State == "loading" && e.Said != "" {
return true
}
}
return false
}
// settled waits until no font wait is in progress.
func (fr *fontRig) settled(t *testing.T) {
t.Helper()
fr.rig.Run(chromedp.Poll[chromedp.Void](`(() => { const s = document.querySelector('[slides-fonts-status]');
return !document.querySelector('[slides-stage-pane]').inert && !['loading'].includes((s && s.getAttribute('data-state')) || '') })()`,
chromedp.WithPollingTimeout(15*time.Second)))
}
// faceOf is the state of the face a stage element's text is drawn in,
// read the way the probe reads it: "liberation mono:web 400 normal".
func (fr *fontRig) faceOf(t *testing.T, selector string) string {
t.Helper()
var out string
fr.eval(t, `(() => { const el = document.querySelector(`+jsString(selector)+`); if (!el) return 'missing';
const cs = getComputedStyle(el); const fam = cs.fontFamily.split(',').map((p) => p.trim().replace(/^["']+|["']+$/g, '').toLowerCase()).find((n) => n.startsWith('liberation'));
return fam ? fam + ':' + window.__fontState(fam, cs.fontWeight, cs.fontStyle) : 'system' })()`, &out)
return out
}
func jsString(s string) string {
b, _ := json.Marshal(s)
return string(b)
}
// selectTextJS puts the selection over the first word of the stage's
// first text block and focuses it.
const selectTextJS = `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
const p = el.querySelector('p'); const n = document.createTreeWalker(p, NodeFilter.SHOW_TEXT).nextNode();
const r = document.createRange(); r.setStart(n, 0); r.setEnd(n, 5); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`
func pasteJS(html string) string {
return `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
const p = el.querySelector('p'); const n = document.createTreeWalker(p, NodeFilter.SHOW_TEXT).nextNode();
const r = document.createRange(); r.setStart(n, n.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r);
const d = new DataTransfer(); d.setData('text/html', ` + jsString(html) + `); d.setData('text/plain', 'x');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`
}
func dropJS(html string) string {
return `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
const d = new DataTransfer(); d.setData('text/html', ` + jsString(html) + `); d.setData('text/plain', 'x');
const r = el.querySelector('p').getBoundingClientRect();
el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.right - 4, clientY: r.top + 8 })); return true })()`
}
func changeJS(selector, value string) string {
return `(() => { const s = document.querySelector(` + jsString(selector) + `); s.value = ` + jsString(value) + `;
s.dispatchEvent(new Event('change', { bubbles: true })); return true })()`
}
func clickJS(selector string) string {
return `(() => { document.querySelector(` + jsString(selector) + `).click(); return true })()`
}
// Every way a change reaches a slide goes through the one font gate:
// each row brings in a family nobody on the page has loaded, held slow,
// and no frame may show slide text in a face that has not loaded, no run
// may change face, and the change must land, in its own family. One
// table, so a path without a row is easy to see missing.
func TestFontEveryInputPathWaitsForItsFamily(t *testing.T) {
rows := []struct {
name string
// deck is the batch the deck is made from; slow the font files
// held back (a family the deck does not use).
deck, slow string
// act does the change; done is a JS expression true once it has
// landed; face, a selector whose text must end in face want.
act func(t *testing.T, fr *fontRig, sqid string)
done string
face, want string
// local rows are this person's own and must wait visibly.
local bool
// then is done once the change has landed (typing into what it made).
then func(t *testing.T, fr *fontRig)
}{
{name: "change the theme", deck: inkDeck, slow: "LiberationSerif-", local: true,
act: func(t *testing.T, fr *fontRig, _ string) { fr.eval(t, changeJS("#rst-deck-theme", "paper"), nil) },
done: `document.querySelector('[slides-stage] [slides-slide]').getAttribute('data-theme') === 'paper'`,
face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
{name: "go back to the theme's heading font", slow: "LiberationSerif-", local: true,
deck: strings.Replace(paperDeck, `"theme":"paper"`, `"theme":"paper","fonts":{"heading":"system-ui, sans-serif","body":""}`, 1),
act: func(t *testing.T, fr *fontRig, _ string) { fr.eval(t, changeJS("#rst-deck-font-heading", ""), nil) },
done: `!document.querySelector('[slides-stage] [slides-slide]').getAttribute('style').includes('system-ui, sans-serif;')`,
face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
{name: "add a code block", deck: inkDeck, slow: "LiberationMono-", local: true,
act: func(t *testing.T, fr *fontRig, _ string) {
fr.eval(t, insertBlockJS("code"), nil)
},
done: `!!document.querySelector('[slides-stage] [data-block="code"]')`,
face: `[slides-stage] [data-block="code"]`, want: "liberation mono:web"},
{name: "toggle code and type", deck: inkDeck, slow: "LiberationMono-", local: true,
act: func(t *testing.T, fr *fontRig, _ string) {
fr.eval(t, selectTextJS, nil)
fr.rig.Run(chromedp.KeyEvent("e", chromedp.KeyModifiers(inputModifierMeta)))
},
done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
{name: "paste code", deck: inkDeck, slow: "LiberationMono-", local: true,
act: func(t *testing.T, fr *fontRig, _ string) {
fr.eval(t, pasteJS(`
pasted in code
`), nil)
},
done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
{name: "drop code", deck: inkDeck, slow: "LiberationMono-", local: true,
act: func(t *testing.T, fr *fontRig, _ string) {
fr.eval(t, dropJS(`
dropped in code
`), nil)
},
done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
{name: "the first slide of an empty deck", deck: `[{"op":"set_meta","theme":"paper","title":"Empty"}]`, slow: "Liberation", local: true,
act: func(t *testing.T, fr *fontRig, _ string) {
fr.eval(t, clickJS(`[slides-menu] [data-command="new-slide"]`), nil)
},
done: `!!document.querySelector('[slides-stage] [data-block="heading"][contenteditable="true"]')`,
then: func(t *testing.T, fr *fontRig) {
fr.eval(t, `(() => { document.querySelector('[slides-stage] [data-block="heading"]').focus(); return true })()`, nil)
fr.rig.Run(chromedp.KeyEvent("First slide"))
},
face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
{name: "a collaborator's code block", deck: inkDeck, slow: "LiberationMono-",
act: func(t *testing.T, fr *fontRig, sqid string) {
fr.ops(t, sqid, `[{"op":"add_block","slide":"slideone0001","type":"code","region":"body","markdown":"from(a, collaborator)"}]`)
},
done: `!!document.querySelector('[slides-stage] [data-block="code"]')`,
face: `[slides-stage] [data-block="code"]`, want: "liberation mono:web"},
{name: "a collaborator's theme", deck: inkDeck, slow: "LiberationSerif-",
act: func(t *testing.T, fr *fontRig, sqid string) { fr.ops(t, sqid, `[{"op":"set_meta","theme":"paper"}]`) },
done: `document.querySelector('[slides-stage] [slides-slide]').getAttribute('data-theme') === 'paper'`,
face: `[slides-stage] [data-block="heading"]`, want: "liberation serif:web"},
{name: "a collaborator's code mark", deck: inkDeck, slow: "LiberationMono-",
act: func(t *testing.T, fr *fontRig, sqid string) {
fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"text00000001","markdown":"now with `+"`code`"+` in it"}]`)
},
done: `!!document.querySelector('[slides-stage] [data-block="text"] code')`,
face: `[slides-stage] [data-block="text"] code`, want: "liberation mono:web"},
}
for _, row := range rows {
t.Run(row.name, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Paths", row.deck)
fr.match.Store(row.slow)
// Held long enough to be waited for, and short enough that all
// of a row's files arrive inside the four seconds a change
// waits over this test server's six HTTP/1.1 connections: the
// empty deck's row holds two families, eight files.
slow := 1500 * time.Millisecond
if row.slow == "Liberation" {
slow = 900 * time.Millisecond
}
fr.slow.Store(int64(slow))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
if strings.Contains(row.deck, `"add_slide"`) {
fr.editable(t)
} else {
fr.rig.Run(chromedp.Poll[chromedp.Void](`document.documentElement.getAttribute('data-slides-fonts') === 'shown' && !!document.querySelector('[slides-menu]')`, chromedp.WithPollingTimeout(15*time.Second)),
chromedp.Sleep(300*time.Millisecond))
}
fr.eval(t, waitLogJS, nil)
row.act(t, fr, sqid)
if err := chromedp.Do(fr.rig.Context(), chromedp.Poll[chromedp.Void](row.done, chromedp.WithPollingTimeout(15*time.Second))); err != nil {
log := fr.waitLog(t)
if len(log) > 12 {
log = log[len(log)-12:]
}
var where string
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)
t.Fatalf("the change never landed: %v\nwait log tail: %+v\nstage: %s", err, log, where)
}
fr.settled(t)
if row.then != nil {
row.then(t, fr)
}
// Long enough for anything still on its way to have landed.
fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
if got := fr.faceOf(t, row.face); !strings.HasPrefix(got, row.want) {
t.Errorf("%s is in %s, want %s", row.face, got, row.want)
}
if row.local && !waited(fr.waitLog(t)) {
t.Error("the change needed a font that was not in and did not wait for it, visibly")
}
p := fr.cleanAcross(t)
webEverywhere(t, p)
})
}
}
const inputModifierMeta = chromedp.ModifierMeta
// inWait reports whether the editor's parts are inert and the status
// says, visibly and in words, that a font is loading, right now.
func (fr *fontRig) inWait(t *testing.T) bool {
t.Helper()
var on bool
fr.eval(t, `(() => { const s = document.querySelector('[slides-fonts-status]');
return ['[slides-stage-pane]', 'aside[slides-inspector][estilo-card]', '[slides-strip-nav]', '[slides-menubar]', '[slides-deck-dialog]'].every((q) => document.querySelector(q).inert) &&
['loading', 'refused'].includes(s.getAttribute('data-state')) && s.querySelector('[role="status"]').textContent.trim() !== '' &&
getComputedStyle(s.querySelector('[role="status"]')).visibility === 'visible' })()`, &on)
return on
}
func (fr *fontRig) stageText(t *testing.T) string {
t.Helper()
var s string
fr.eval(t, `document.querySelector('[slides-stage]').innerText.replace(/\n+/g, '|')`, &s)
return s
}
// addCodeBlockJS adds a code box from the Insert menu.
var addCodeBlockJS = insertBlockJS("code")
// A wait for a font is a short modal (Docs' review 7, adopted). The
// change that needs the font is held before it changes anything; the
// stage, the strip, the inspector and the Slide menu go inert at once
// and the status under the bar says a font is loading; what is typed
// meanwhile goes nowhere, and a second change is refused and said, not
// queued; a collaborator's change that arrives meanwhile is applied
// after it, in order, and not lost; once the font is in, the change is
// made once.
func TestFontAWaitIsAShortModal(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Modal", inkDeck)
fr.match.Store("LiberationMono-")
// Under the four seconds a change waits, counting the prefetch that
// started the files at the reveal.
fr.slow.Store(int64(3200 * time.Millisecond))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
before := fr.stageText(t)
fr.eval(t, waitLogJS, nil)
fr.eval(t, addCodeBlockJS, nil)
if !fr.inWait(t) {
t.Fatal("adding a code block whose font is not in did not start a visible wait")
}
// Typing into the slide, which is inert: nothing reaches it.
fr.rig.Run(chromedp.KeyEvent("qzqz"))
// A second change, which only a script can make while the inspector
// is inert: refused, and said.
fr.eval(t, changeJS("#rst-deck-theme", "paper"), nil)
// A collaborator's change, during the wait.
fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"Retitled by a collaborator"}]`)
if !fr.inWait(t) {
t.Fatalf("the wait ended before the collaborator's change was made, so this cannot show it waited behind it: %+v", fr.waitLog(t))
}
fr.settled(t)
fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage]').innerText.includes('Retitled by a collaborator')`, chromedp.WithPollingTimeout(10*time.Second)),
chromedp.Sleep(800*time.Millisecond))
var codes int
var theme string
fr.eval(t, `document.querySelectorAll('[slides-stage] [data-block="code"]').length`, &codes)
fr.eval(t, `document.querySelector('[slides-stage] [slides-slide]').getAttribute('data-theme')`, &theme)
if codes != 1 {
t.Errorf("%d code blocks on the slide; the change waits and then runs once", codes)
}
if theme != "ink" {
t.Errorf("the theme is %q: the second change, made during the wait, must be refused", theme)
}
if text := fr.stageText(t); strings.Contains(text, "qzqz") && !strings.Contains(before, "qzqz") {
t.Errorf("what was typed during the wait reached the slide: %q", text)
}
if got := fr.faceOf(t, `[slides-stage] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
t.Errorf("the code block is in %s", got)
}
log := fr.waitLog(t)
refused, early := false, false
for _, e := range log {
refused = refused || e.State == "refused"
early = early || (e.Inert && strings.Contains(e.Text, "Retitled by a collaborator"))
}
if !refused {
t.Error("the second change was not said to be refused")
}
if early {
t.Error("the collaborator's change reached the slide during the wait, under the change being made")
}
fr.clean(t)
}
// The notes card and the icon that opens it are inside the stage pane,
// so a font wait makes them inert with it: the card, its ×, its top
// edge and the notes with the card open; the icon with it closed.
// Neither is inert once the wait is over.
func TestFontAWaitMakesTheNotesInert(t *testing.T) {
const parts = `['[slides-notes-pane]', '[slides-notes-close]', '[slides-notes-resize]', '[slides-notes]', '[slides-notes-open]']`
const free = parts + `.filter((q) => !document.querySelector(q).closest('[inert]'))`
for _, closed := range []bool{false, true} {
t.Run(map[bool]string{false: "open", true: "closed"}[closed], func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Notes", inkDeck)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(3200 * time.Millisecond))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
if closed {
fr.eval(t, `(document.querySelector('[slides-notes-close]').click(), true)`, nil)
}
var state string
fr.eval(t, `document.querySelector('[slides-notes-pane]').dataset.state`, &state)
if want := map[bool]string{false: "open", true: "closed"}[closed]; state != want {
t.Fatalf("the notes card is %q, want %q", state, want)
}
fr.eval(t, addCodeBlockJS, nil)
if !fr.inWait(t) {
t.Fatal("adding a code block whose font is not in did not start a visible wait")
}
var during []string
fr.eval(t, free, &during)
if len(during) != 0 {
t.Errorf("during the font wait these are not inert: %v", during)
}
fr.settled(t)
var after []string
fr.eval(t, free, &after)
if len(after) != 5 {
t.Errorf("after the font wait only %v are free of inert", after)
}
})
}
}
// A change whose font cannot be had changes nothing and says so: the
// font files are refused, the code block is never added (on the slide
// or in the deck), and the status says the font could not be loaded.
func TestFontAChangeWhoseFamilyCannotLoadChangesNothing(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Refused", inkDeck)
fr.blocked.Store("LiberationMono-")
fr.rig.Allow(http.MethodGet, "LiberationMono-", http.StatusNotFound)
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, waitLogJS, nil)
fr.eval(t, addCodeBlockJS, nil)
fr.settled(t)
fr.rig.Run(chromedp.Sleep(800 * time.Millisecond))
var state, said string
var codes int
fr.eval(t, `document.querySelector('[slides-fonts-status]').getAttribute('data-state') || ''`, &state)
fr.eval(t, `document.querySelector('[slides-fonts-status] [role="status"]').textContent`, &said)
fr.eval(t, `document.querySelectorAll('[slides-stage] [data-block="code"]').length`, &codes)
if state != "unavailable" || said == "" {
t.Errorf("the status is %q %q; it must say the font could not be loaded", state, said)
}
if codes != 0 {
t.Errorf("%d code blocks on the slide; a change whose font cannot load is not made", codes)
}
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
if b, _ := json.Marshal(view); strings.Contains(string(b), `"type":"code"`) {
t.Error("the deck holds a code block; the refused change reached the server")
}
if !waited(fr.waitLog(t)) {
t.Error("the change did not wait, visibly, before it was refused")
}
fr.clean(t)
}
// Undo and redo bring back what was on screen in this visit, in a family
// that stayed in: neither waits, and neither paints a face that has not
// loaded.
func TestFontUndoAndRedoOfACodeBlockNeverFlash(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Undo", inkDeck)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(1500 * time.Millisecond))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, addCodeBlockJS, nil)
fr.settled(t)
fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)))
fr.eval(t, waitLogJS, nil)
fr.eval(t, `(() => { document.activeElement && document.activeElement.blur(); return true })()`, nil)
fr.eval(t, clickJS(`[slides-menu] [data-command="undo"]`), nil)
fr.rig.Run(chromedp.Poll[chromedp.Void](`!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)))
fr.eval(t, clickJS(`[slides-menu] [data-command="redo"]`), nil)
fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)),
chromedp.Sleep(800*time.Millisecond))
if waited(fr.waitLog(t)) {
t.Error("undo or redo waited for a font that was already in")
}
if got := fr.faceOf(t, `[slides-stage] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
t.Errorf("the code block is back in %s", got)
}
fr.clean(t)
}
// The projector never swaps faces mid-presentation: a slide that needs a
// family the projector has not loaded — the deck was changed during the
// talk — waits for it before it goes up, and goes up once, in it.
func TestFontTheProjectorsNextSlideWaitsForItsFamily(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Talk", inkDeck)
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
fr.rig.Run(fr.navigate("/p/" + session))
fr.shown(t)
fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(1500 * time.Millisecond))
fr.ops(t, sqid, `[{"op":"add_block","slide":"slidetwo0002","type":"code","region":"body","markdown":"added(mid, talk)"}]`)
if rec := command(t, fr.app, session, "next", token, "", nil); rec.Code >= 400 {
t.Fatalf("next: %d", rec.Code)
}
fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [data-block="code"]')`, chromedp.WithPollingTimeout(10*time.Second)),
chromedp.Sleep(800*time.Millisecond))
if got := fr.faceOf(t, `[slides-stage] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
t.Errorf("the projector's code is in %s", got)
}
p := fr.clean(t)
webEverywhere(t, p)
}
// Random decks from Slides' own model (fixtures/generate-random-decks.mjs
// walks the op vocabulary, the text schema's marks and the server's
// themes and stacks, and fails unless every block type, template,
// layout, theme and mark appeared, marks in table cells included), each
// opened on every slide in the viewer at a desktop and at a phone width,
// and in the editor. On every page every element of the slide that is
// drawn names, in its computed font stack, only families the gate
// waited for (the manifest's need); and the gate waited for nothing the
// deck does not reference: its heading and body stacks, and the code
// stack if any slide draws code. The probe watches every one of those
// pages for a face drawn before it loaded.
func TestFontTheGateCoversEveryFaceADeckUses(t *testing.T) {
fr := newFontRig(t)
seed := fontSeed()
const decks = 16
sqids := fr.randomDecks(t, decks, seed)
// Generated images name no picture; their frames fetch nothing.
const checkJS = `(() => {
const m = JSON.parse(document.querySelector('meta[name="slides-fonts"]').getAttribute('content'));
const section = document.querySelector('[slides-stage] [slides-slide]') || document.querySelector('[slides-slide]');
if (!section) return { need: m.need, drawn: [], referenced: [], code: false, where: [], none: true };
const names = (s) => s.split(',').map((p) => p.trim().replace(/^["']+|["']+$/g, '').toLowerCase());
const keyOf = { 'liberation sans': 'sans', 'liberation serif': 'serif', 'liberation mono': 'mono' };
const drawn = new Set(); const where = [];
for (const el of [section, ...section.querySelectorAll('*')]) {
const cs = getComputedStyle(el);
if (cs.visibility !== 'visible' || !el.getClientRects().length) continue;
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) + '"'); }
}
const style = section.getAttribute('style') || '';
const decl = (k) => { const d = style.split(';').find((x) => x.trim().startsWith(k + ':')); return d ? d.slice(d.indexOf(':') + 1) : ''; };
const referenced = [...new Set([...names(decl('--slides-font-heading')), ...names(decl('--slides-font-body'))].map((n) => keyOf[n]).filter(Boolean))];
const code = [...section.querySelectorAll('pre, code')].some((el) => el.getClientRects().length > 0);
return { need: m.need, drawn: [...drawn], referenced, code, where };
})()`
type check struct {
Need, Drawn, Referenced, Where []string
Code, None bool
}
checked := 0
for i, sqid := range sqids {
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
slides, _ := view["slides"].([]any)
if len(slides) == 0 {
t.Fatalf("deck %d has no slides", i)
}
referenced := map[string]bool{}
code := false
var need []string
var paths []string
for n := 1; n <= len(slides); n++ {
paths = append(paths, fmt.Sprintf("/d/%s?slide=%d", sqid, n), fmt.Sprintf("/d/%s?slide=%d&vp=phone", sqid, n))
}
paths = append(paths, "/d/"+sqid+"/edit")
for _, path := range paths {
// Navigate and wait for the load: nothing here is slowed, and
// a check that starts before the navigation has committed reads
// the page before.
fr.rig.Run(chromedp.Navigate(fr.rig.Origin + path))
fr.shown(t)
if strings.HasSuffix(path, "/edit") {
fr.rig.Run(chromedp.Poll[chromedp.Void](`!document.querySelector('[slides-stage] [slides-block][data-block="text"], [slides-stage] [slides-block][data-block="heading"]') ||
!!document.querySelector('[slides-stage] [contenteditable="true"]')`, chromedp.WithPollingTimeout(15*time.Second)))
}
var c check
fr.eval(t, checkJS, &c)
if c.None {
t.Fatalf("%s shows no slide", path)
}
for _, w := range c.Where {
t.Errorf("deck %d %s: drawn in a family the gate did not wait for: %s (need %v)", i, path, w, c.Need)
}
for _, k := range c.Referenced {
referenced[k] = true
}
code = code || c.Code
need = c.Need
var violations []string
fr.eval(t, `(window.__fontProbe || { violations: [] }).violations`, &violations)
for _, v := range violations {
t.Errorf("deck %d %s: %s", i, path, v)
}
checked++
}
if code {
referenced["mono"] = true
}
for _, k := range need {
if !referenced[k] {
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))
}
}
}
if checked < decks*3 {
t.Fatalf("checked %d pages; the generated decks are too small to mean anything", checked)
}
}
// A wait never begins in an IME composition: interrupting one loses the
// word being composed. Composing in a slide's text while a family is
// still on its way neither waits nor paints anything in a face that has
// not loaded, and the composed text lands.
func TestFontACompositionNeverStartsAWait(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Compose", inkDeck)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(3 * time.Second))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
const n = document.createTreeWalker(el.querySelector('p'), NodeFilter.SHOW_TEXT).nextNode();
const r = document.createRange(); r.setStart(n, n.length); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, nil)
fr.eval(t, waitLogJS, nil)
fr.rig.Run(
cdpStep(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほ", SelectionStart: 2, SelectionEnd: 2}),
chromedp.Sleep(100*time.Millisecond),
cdpStep(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "日本", SelectionStart: 2, SelectionEnd: 2}),
chromedp.Sleep(100*time.Millisecond),
cdpStep(input.InsertText, input.InsertTextParams{Text: "日本"}),
chromedp.Sleep(800*time.Millisecond),
)
if waited(fr.waitLog(t)) {
t.Error("a composition started a wait for a font")
}
if text := fr.stageText(t); !strings.Contains(text, "日本") {
t.Errorf("the composed text did not land: %q", text)
}
fr.clean(t)
}
// A refused change lets go of everything queued behind it. The code face
// is refused (its files 404); a collaborator's change arrives during the
// wait and queues behind it; after the refusal the collaborator's change
// lands, and a second one after it, in order, and nothing on the page
// throws (Astra's finding 1 on #27: the refusal threw before it released
// the queue, and every collaborator's change after it was stuck).
func TestFontARefusalReleasesTheCollaboratorsChangesInOrder(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Refused", inkDeck)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(7 * time.Second))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, addCodeBlockJS, nil)
if !fr.inWait(t) {
t.Fatal("adding a code block whose font is not in did not start a wait")
}
fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"First from a collaborator"}]`)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"head00000001","markdown":"Second from a collaborator"}]`)
// The four seconds a change waits, then the refusal.
fr.settled(t)
fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage]').innerText.includes('Second from a collaborator')`,
chromedp.WithPollingTimeout(10*time.Second)))
var state string
var codes int
fr.eval(t, `document.querySelector('[slides-fonts-status]').getAttribute('data-state') || ''`, &state)
fr.eval(t, `document.querySelectorAll('[slides-stage] [data-block="code"]').length`, &codes)
if state != "unavailable" || codes != 0 {
t.Errorf("status %q and %d code blocks: the change was meant to be refused", state, codes)
}
// And the queue still moves after it.
fr.ops(t, sqid, `[{"op":"set_text","slide":"slideone0001","id":"text00000001","markdown":"Third, after the refusal"}]`)
fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage]').innerText.includes('Third, after the refusal')`,
chromedp.WithPollingTimeout(10*time.Second)))
fr.clean(t)
}
// A change waiting for its font is never lost to a refresh of the stage
// that was already on its way (Astra's finding 2 on #27). The accent is
// changed — its save brings a refresh of the slide — and at once text
// with code in it is pasted, the code face three seconds away. The
// refresh waits for the paste, not the other way round: the pasted words
// land, once, in the code face, the refreshed slide wears the new accent,
// and the deck on the server holds both.
func TestFontAPendingRefreshNeverLosesAWaitingPaste(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Refresh", inkDeck)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(3 * time.Second))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, waitLogJS, nil)
fr.eval(t, changeJS("#rst-deck-accent", "#3366cc")+` && `+pasteJS(`
pasted kept code words
`), nil)
fr.settled(t)
fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[slides-stage] [slides-slide]').getAttribute('style').includes('#3366cc')`,
chromedp.WithPollingTimeout(10*time.Second)), chromedp.Sleep(1500*time.Millisecond))
text := fr.stageText(t)
if strings.Count(text, "kept code") != 1 {
t.Errorf("the pasted words are on the slide %d times: %q", strings.Count(text, "kept code"), text)
}
if got := fr.faceOf(t, `[slides-stage] [data-block="text"] code`); !strings.HasPrefix(got, "liberation mono:web") {
t.Errorf("the pasted code is in %s", got)
}
for _, e := range fr.waitLog(t) {
if e.State == "unavailable" || e.State == "interrupted" {
t.Errorf("the paste was refused (%s): %q", e.State, e.Said)
}
}
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
b, _ := json.Marshal(view)
if !strings.Contains(string(b), "kept code") || !strings.Contains(string(b), "#3366cc") {
t.Errorf("the deck does not hold both the accent and the paste: %s", b)
}
fr.cleanAcross(t)
}
// randomDecks makes n decks over the API and fills them with
// fixtures/generate-random-decks.mjs's decks, through the ordinary write
// path, and returns their sqids.
func (fr *fontRig) randomDecks(t *testing.T, n int, seed string) []string {
t.Helper()
dir := t.TempDir()
sqids := make([]string, n)
for i := range n {
sqids[i] = apiDeck(t, fr.app, fr.token, fmt.Sprintf("Random %d", i))
rec := get(t, fr.app, "/d/"+sqids[i]+"/updates?since=0", fr.cookies...)
if rec.Code != http.StatusOK {
t.Fatalf("GET updates: %d", rec.Code)
}
if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%d.base", i)), rec.Body.Bytes(), 0o600); err != nil {
t.Fatal(err)
}
}
page := get(t, fr.app, "/d/"+sqids[0]+"?slide=1", fr.cookies...).Body.String()
m := manifestMeta.FindStringSubmatch(page)
if m == nil {
t.Fatal("no font manifest on the viewer")
}
manifest := filepath.Join(dir, "manifest.json")
if err := os.WriteFile(manifest, []byte(html.UnescapeString(m[1])), 0o600); err != nil {
t.Fatal(err)
}
gen := exec.Command("node", "generate-random-decks.mjs", seed, dir, manifest)
gen.Dir = filepath.Join("..", "..", "fixtures")
if out, err := gen.CombinedOutput(); err != nil {
t.Fatalf("generate: %v\n%s", err, out)
}
for i, sqid := range sqids {
update, err := os.ReadFile(filepath.Join(dir, fmt.Sprintf("%d.bin", i)))
if err != nil {
t.Fatal(err)
}
if rec := postBody(t, fr.app, "/d/"+sqid+"/updates", "application/octet-stream", update, fr.cookies); rec.Code != http.StatusNoContent {
t.Fatalf("deck %d: POST updates: %d %s", i, rec.Code, rec.Body)
}
}
return sqids
}
// fontSeed is the generator's seed: SLIDES_FONT_SEED, or a fixed one.
func fontSeed() string {
if seed := os.Getenv("SLIDES_FONT_SEED"); seed != "" {
return seed
}
return "20261026"
}
// An editor that mounts after its slide is shown moves nothing (Astra's
// finding 3 on #27). The editor's bundle is held five seconds — past the
// gate's 3.5 s, so the slide is shown in the server's markup first — on
// generated decks whose first slide has a block of every type the
// editor binds, and a table, each text in a shape the renderer and
// ProseMirror could draw differently: no paragraphs, one empty one, and
// empties before, between and after words. Before and after the mount
// each bound element holds the same markup, the slide the same layout,
// and the same pixels.
func TestFontALateEditorMovesNothing(t *testing.T) {
fr := newFontRig(t)
sqids := fr.randomDecks(t, 12, fontSeed())
fr.editorDelay.Store(int64(6 * time.Second))
const snapJS = `(() => {
const s = document.querySelector('[slides-stage] [slides-slide]');
const sr = s.getBoundingClientRect();
const round = (b) => [b.left - sr.left, b.top - sr.top, b.width, b.height].map((v) => Math.round(v * 4) / 4).join(',');
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')];
const boxes = [...s.querySelectorAll('[slides-block], [slides-block] *')].map((e) => e.tagName + '@' + round(e.getBoundingClientRect()));
return { Mounted: !!s.querySelector('[contenteditable="true"]'), Markup: bound.map((e) => e.innerHTML),
Blocks: [...s.querySelectorAll('[slides-block]')].map((e) => (e.getAttribute('data-block') || '') + '@' + round(e.getBoundingClientRect())),
Lines: bound.map((e) => { const r = document.createRange(); r.selectNodeContents(e); return [...r.getClientRects()].length + ':' + round(r.getBoundingClientRect()) }),
Shown: document.documentElement.getAttribute('data-slides-fonts') === 'shown',
Slide: [sr.left, sr.top, sr.width, sr.height, document.documentElement.clientWidth, scrollY].join(',') };
})()`
type snap struct {
Mounted, Shown bool
Markup, Blocks, Lines []string
Slide string
}
for i, sqid := range sqids {
// The page before is marked, so the wait below is for the new
// one: navigate does not wait, and the load event waits for the
// held bundle.
fr.rig.Run(chromedp.Evaluate[chromedp.Void](`window.__leaving = true`), fr.navigate("/d/"+sqid+"/edit"))
fr.until(t, `!window.__leaving && !!document.querySelector('[slides-stage] [slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`)
var before, after snap
var a, b []byte
fr.rig.Run(chromedp.Sleep(200*time.Millisecond), evalInto(&before, snapJS),
inViewShot(`[slides-stage] [slides-slide]`, &a))
if before.Mounted || !before.Shown {
t.Fatalf("deck %d: shown %v, mounted %v before the late editor arrived; the delay did not apply", i, before.Shown, before.Mounted)
}
fr.rig.Run(chromedp.Poll[chromedp.Void](`!!document.querySelector('[slides-stage] [contenteditable="true"]')`, chromedp.WithPollingTimeout(15*time.Second)),
chromedp.Sleep(500*time.Millisecond), evalInto(&after, snapJS),
inViewShot(`[slides-stage] [slides-slide]`, &b))
for k := range before.Markup {
if k < len(after.Markup) && before.Markup[k] != after.Markup[k] {
t.Errorf("deck %d: text %d was\n %s\nand the editor drew\n %s", i, k, before.Markup[k], after.Markup[k])
}
}
if before.Slide != after.Slide {
t.Errorf("deck %d: the slide itself moved when the editor mounted: %s -> %s", i, before.Slide, after.Slide)
}
if fmt.Sprint(before.Blocks) != fmt.Sprint(after.Blocks) || fmt.Sprint(before.Lines) != fmt.Sprint(after.Lines) {
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)
}
if diff := pixelDiff(t, a, b); diff != "" {
t.Errorf("deck %d: the slide's pixels changed when the editor mounted: %s", i, diff)
if dir := os.Getenv("SLIDES_FONT_SHOTS"); dir != "" {
_ = os.WriteFile(filepath.Join(dir, fmt.Sprintf("late-%d-before.png", i)), a, 0o644)
_ = os.WriteFile(filepath.Join(dir, fmt.Sprintf("late-%d-after.png", i)), b, 0o644)
}
}
p := fr.clean(t)
sameLayout(t, p)
}
}
// inViewShot captures the first element sel matches, which must be on
// screen, as a PNG. chromedp.Screenshot captures with
// captureBeyondViewport, and for that capture Chromium lays the page
// out at another size for a frame (1×1 CSS px, seen by the font probe's
// frame sampler as the slide jumping to 80px wide and back); a capture
// of what is already in the viewport needs no relayout, so the page the
// probe watches is the page as shown. The clip is rounded as chromedp
// rounds it.
func inViewShot(sel string, buf *[]byte) chromedp.Action[chromedp.Void] {
return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
var r struct{ X, Y, Width, Height float64 }
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 {
return err
}
x, y := math.Round(r.X), math.Round(r.Y)
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}
pic, err := cdp.Call(ctx, t, page.CaptureScreenshot, page.CaptureScreenshotParams{
Format: page.CaptureScreenshotFormatPng, Clip: clip,
CaptureBeyondViewport: new(false), FromSurface: new(true),
})
if err != nil {
return err
}
*buf = pic.Data
return nil
})
}
// pixelDiff is "" when two PNG captures are the same picture, and the
// changed box otherwise.
func pixelDiff(t *testing.T, a, b []byte) string {
t.Helper()
ia, err := png.Decode(bytes.NewReader(a))
if err != nil {
t.Fatal(err)
}
ib, err := png.Decode(bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
if ia.Bounds() != ib.Bounds() {
return fmt.Sprintf("size %v, then %v", ia.Bounds(), ib.Bounds())
}
r := ia.Bounds()
minx, miny, maxx, maxy, n := r.Max.X, r.Max.Y, -1, -1, 0
for y := r.Min.Y; y < r.Max.Y; y++ {
for x := r.Min.X; x < r.Max.X; x++ {
if ia.At(x, y) != ib.At(x, y) {
n++
minx, miny, maxx, maxy = min(minx, x), min(miny, y), max(maxx, x), max(maxy, y)
}
}
}
if n == 0 {
return ""
}
return fmt.Sprintf("%d pixels in %d,%d–%d,%d", n, minx, miny, maxx, maxy)
}
// until polls a JS expression from Go until it is true, riding over a
// navigation in progress (chromedp.Poll gives up when the page it was
// polling goes away).
func (fr *fontRig) until(t *testing.T, expr string) {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for {
var ok bool
if err := chromedp.Do(fr.rig.Context(), evalInto(&ok, `!!(`+expr+`)`)); err == nil && ok {
return
}
if time.Now().After(deadline) {
t.Fatalf("never true within 15s: %s", expr)
}
time.Sleep(25 * time.Millisecond)
}
}
// markPage puts a marker on the page's window, which only a page load
// takes away.
const markPageJS = `window.__samePage = true; true`
// The viewer changes slides in place (Astra's finding 4 on #27): Next,
// Next, then Previous by link, then the browser's Back, on the viewer and
// in its scriptless presenting mode. The page is never reloaded, the
// address follows each slide, and no frame between two slides is
// without one: slide text is never on screen, then gone.
func TestFontTheViewerChangesSlidesInPlace(t *testing.T) {
three := strings.TrimSuffix(paperDeck, "]") + `,
{"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},
{"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]`
for _, mode := range []string{"", "&present=1"} {
t.Run("mode"+mode, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Pages", three)
fr.slow.Store(int64(600 * time.Millisecond))
fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1" + mode))
fr.shown(t)
fr.eval(t, markPageJS, nil)
step := func(sel, want, path string) {
t.Helper()
fr.eval(t, clickJS(sel), nil)
fr.until(t, `document.querySelector('[slides-slide]').textContent.includes(`+jsString(want)+`)`)
var same bool
var loc string
fr.eval(t, `!!window.__samePage`, &same)
fr.eval(t, `location.search`, &loc)
if !same {
t.Fatalf("going to %q loaded a page", want)
}
if !strings.Contains(loc, path) {
t.Errorf("at %q the address is %q, want it to name %s", want, loc, path)
}
}
step(`[slides-pager] a[rel="next"]`, "Second", "slide=2")
step(`[slides-pager] a[rel="next"]`, "Third", "slide=3")
step(`[slides-pager] a[rel="prev"]`, "Second", "slide=2")
fr.rig.Run(chromedp.NavigateBack())
fr.until(t, `document.querySelector('[slides-slide]').textContent.includes('Third')`)
fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
var same bool
fr.eval(t, `!!window.__samePage`, &same)
if !same {
t.Error("Back loaded a page")
}
fr.cleanAcross(t)
})
}
}
// When the next slide needs a family the page has not loaded — the deck
// changed after the page was opened — the current slide stays on screen
// until the family is in, then the next one replaces it, once, in it.
// Never a frame without a slide, never a face that has not loaded.
func TestFontTheNextSlideWaitsForItsFamilyBehindTheCurrentOne(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Waits", inkDeck)
fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
fr.shown(t)
fr.eval(t, markPageJS, nil)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(1500 * time.Millisecond))
fr.ops(t, sqid, `[{"op":"add_block","slide":"slidetwo0002","type":"code","region":"body","markdown":"new(code)"}]`)
start := time.Now()
fr.eval(t, clickJS(`[slides-pager] a[rel="next"]`), nil)
fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
var still bool
fr.eval(t, `document.querySelector('[slides-slide]').textContent.includes('Ink heading')`, &still)
if !still {
t.Error("the current slide was taken down before the next one's family was in")
}
fr.until(t, `!!document.querySelector('[slides-slide] [data-block="code"]')`)
if waited := time.Since(start); waited < time.Second {
t.Errorf("the next slide went up after %v, before its family could have loaded", waited)
}
if got := fr.faceOf(t, `[slides-slide] [data-block="code"]`); !strings.HasPrefix(got, "liberation mono:web") {
t.Errorf("the code is in %s", got)
}
var same bool
fr.eval(t, `!!window.__samePage`, &same)
if !same {
t.Error("the page was reloaded")
}
fr.cleanAcross(t)
}
// The projector pages in place too: the presenter's own Next and
// Previous on the projector (command forms) and a watcher's links on the
// follow-free projector page. Never a reload, never a frame without a
// slide. A watcher is somebody who may not drive: no token, and not the
// presenter signed in, who drives from their own slide window.
func TestFontTheProjectorPagesInPlace(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "Talk", paperDeck)
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
for _, c := range []struct {
name, path, next, prev string
watcher bool
}{
{"the presenter's buttons", "/p/" + session + "?t=" + token, `[slides-bar] form input[value="next"]`, `[slides-bar] form input[value="prev"]`, false},
{"a watcher's links", "/p/" + session, `[slides-bar] a[rel="next"]`, `[slides-bar] a[rel="prev"]`, true},
} {
t.Run(c.name, func(t *testing.T) {
if c.watcher {
fr.rig.Run(cdpStep(network.ClearBrowserCookies, cdp.Empty{}))
}
fr.rig.Run(chromedp.Evaluate[chromedp.Void](`window.__leaving = true`), fr.navigate(c.path))
fr.until(t, `!window.__leaving && !!document.querySelector('[slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, markPageJS, nil)
press := func(sel string) {
if strings.Contains(sel, "form") {
fr.eval(t, `(() => { document.querySelector(`+jsString(sel)+`).form.requestSubmit(); return true })()`, nil)
} else {
fr.eval(t, clickJS(sel), nil)
}
}
press(c.next)
fr.until(t, `document.querySelector('[slides-slide]').textContent.includes('Second')`)
press(c.prev)
fr.until(t, `document.querySelector('[slides-slide]').textContent.includes('A heading in serif')`)
fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
var same bool
fr.eval(t, `!!window.__samePage`, &same)
if !same {
t.Error("paging reloaded the projector")
}
fr.cleanAcross(t)
})
}
}
// goTo navigates to path and waits for the new page's slide to be shown,
// not the old page's: the page being left is marked first.
func (fr *fontRig) goTo(t *testing.T, path string) {
t.Helper()
fr.rig.Run(chromedp.Evaluate[chromedp.Void](`window.__leaving = true`), fr.navigate(path))
fr.until(t, `!window.__leaving && !!document.querySelector('[slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`)
}
// uploadFamily puts file, renamed to name, in fr's library and answers
// the css name it was given and its ref.
func uploadFamily(t *testing.T, fr *fontRig, file, name string) (css, ref string) {
t.Helper()
f, err := fonts.Parse(libFont(t, file))
if err != nil {
t.Fatal(err)
}
data, err := f.Renamed(name, 400, false)
if err != nil {
t.Fatal(err)
}
if rec := uploadFonts(t, fr.app, fr.cookies, upFile{"f.ttf", data}); rec.Code != http.StatusOK {
t.Fatalf("upload: %d\n%s", rec.Code, rec.Body)
}
var row slides.LibraryFont
if err := fr.app.db.G.Where("ref = ?", sha(data)).First(&row).Error; err != nil {
t.Fatal(err)
}
return row.CSSName, sha(data)
}
// recordFamily is the editor's pick of css for sqid without its
// set_meta (POST /d/{sqid}/fonts), answering the family as
// meta.fontFiles carries it.
func recordFamily(t *testing.T, fr *fontRig, sqid, css string) string {
t.Helper()
rec := pickFont(t, fr.app, sqid, css, fr.cookies)
if rec.Code != http.StatusOK {
t.Fatalf("pick: %d\n%s", rec.Code, rec.Body)
}
return rec.Body.String()
}
// probeAlso has the probe track the given uploaded families too.
func (fr *fontRig) probeAlso(names ...string) {
b, _ := json.Marshal(names)
fr.rig.Run(cdpStep(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `window.__fontProbeExtra = ` + strings.ToLower(string(b))}))
}
// uploadedFontRig is a font rig with an object store and a paper deck
// whose headings lead with an uploaded family: Liberation Mono's regular
// renamed "Oddity Sans 2", a name a stack must quote (FontFace must
// not: it takes the name literally), with a monospace font's wide
// glyphs, so a heading drawn first in the stack's next family
// (Liberation Serif) and then in this one would visibly move. It
// returns the deck and the face's ref.
func uploadedFontRig(t *testing.T) (fr *fontRig, sqid, ref string) {
t.Helper()
fr = newFontRigWith(t, dirStore(t))
css, ref := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Oddity Sans 2")
sqid = fr.deck(t, "Uploaded", paperDeck)
fam := recordFamily(t, fr, sqid, css)
fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'Oddity Sans 2', Liberation Serif, Georgia, serif","body":""}}]`)
fr.probeAlso("Oddity Sans 2")
return fr, sqid, ref
}
// An uploaded font is held to the catalog's rule on every surface: its
// file held for a second, well inside the deadline, the slides are not
// shown until it is in, and then the headings are in it from their
// first frame and never in anything else. The preload is the file the
// gate loads: one fetch per page.
func TestAnUploadedFontIsNotPaintedBeforeItLoads(t *testing.T) {
fr, sqid, ref := uploadedFontRig(t)
share := "/s/" + mintShareLink(t, fr.app, "/d/"+sqid, fr.cookies)
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
fr.match.Store(ref)
fr.slow.Store(int64(time.Second))
for _, c := range []struct{ name, path string }{
{"viewer", "/d/" + sqid + "?slide=1"},
{"share link", share + "?slide=1"},
{"projector", "/p/" + session},
{"presenter window", "/p/" + session + "/notes?t=" + token},
{"editor", "/d/" + sqid + "/edit"},
} {
t.Run(c.name, func(t *testing.T) {
before := fr.hits(ref)
start := time.Now()
fr.goTo(t, c.path)
if waited := time.Since(start); waited < 950*time.Millisecond {
t.Fatalf("the slide was shown %v after navigating, before the uploaded face could have arrived", waited)
}
fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
p := fr.clean(t)
webEverywhere(t, p)
sameLayout(t, p)
odd := false
for run, faces := range p.Seen {
for f := range faces {
if strings.Contains(f, "oddity sans 2:") && !strings.Contains(f, "oddity sans 2:web") {
t.Errorf("%q was shown in %s", run, f)
}
odd = odd || strings.Contains(f, "oddity sans 2:web")
}
}
if !odd {
t.Error("no run was seen in the uploaded family")
}
if n := fr.hits(ref) - before; n != 1 {
t.Errorf("the uploaded face was fetched %d times; the preload is the gate's one fetch", n)
}
})
}
}
// Past the deadline an uploaded family commits to its stack's next
// family, as a catalog one does: the headings are shown in Liberation
// Serif and stay in it when the late file lands; the uploaded faces
// never join the page.
func TestALateUploadedFontCommitsToItsFallback(t *testing.T) {
fr, sqid, ref := uploadedFontRig(t)
fr.match.Store(ref)
fr.slow.Store(int64(4 * time.Second))
fr.rig.Run(fr.navigate("/d/" + sqid + "?slide=1"))
fr.shown(t)
fr.rig.Run(chromedp.Sleep(4 * time.Second))
if fr.hits(ref) == 0 {
t.Fatal("the uploaded face was never requested, so this cannot show it was not swapped in")
}
p := fr.clean(t)
sameLayout(t, p)
next := false
for run, faces := range p.Seen {
for f := range faces {
if strings.Contains(f, "oddity sans 2:web") {
t.Errorf("%q is in the uploaded face, which arrived after the page was shown", run)
}
next = next || strings.HasPrefix(f, "oddity sans 2:system,liberation serif:web")
}
}
if !next {
t.Errorf("no heading was seen in the stack's next family, Liberation Serif: %v", p.Seen)
}
var st struct {
Committed bool
Faces int
}
fr.eval(t, `({ Committed: !!(window.slidesFonts && window.slidesFonts.committed('u:Oddity Sans 2')),
Faces: [...document.fonts].filter((f) => /oddity/i.test(f.family)).length })`, &st)
if !st.Committed || st.Faces != 0 {
t.Errorf("the late family: committed %v, %d of its faces in the page", st.Committed, st.Faces)
}
}
// A collaborator's pick reaches an editor open on the deck: the family,
// which this tab has never heard of, is learned from the changed deck,
// and the change waits for it like any change that brings in a family —
// applied once its face is in, or past the timeout with the family
// committed to its stack's next one, which it then never leaves.
func TestAnUploadedFontFromACollaboratorLoads(t *testing.T) {
for _, c := range []struct {
name string
slow time.Duration
late bool
}{{"in time", time.Second, false}, {"late", 5 * time.Second, true}} {
t.Run(c.name, func(t *testing.T) {
fr := newFontRigWith(t, dirStore(t))
css, ref := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Oddity Sans 2")
sqid := fr.deck(t, "Collaborator", paperDeck)
fam := recordFamily(t, fr, sqid, css)
fr.probeAlso(css)
fr.goTo(t, "/d/"+sqid+"/edit")
fr.editable(t)
fr.until(t, `document.documentElement.getAttribute('data-slides-fonts-prefetch') === 'done'`)
fr.match.Store(ref)
fr.slow.Store(int64(c.slow))
fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"'`+css+`', Liberation Serif, Georgia, serif","body":""}}]`)
// The change reaches the heading on the stage.
fr.until(t, `(() => { const h = document.querySelector('[slides-stage] [data-id="head00000001"]');
return !!h && /oddity/i.test(getComputedStyle(h).fontFamily) })()`)
fr.rig.Run(chromedp.Sleep(c.slow + time.Second))
p := fr.cleanAcross(t)
web, system := false, false
for run, faces := range p.Seen {
for f := range faces {
if strings.Contains(f, "oddity sans 2:web") {
web = true
if c.late {
t.Errorf("%q is in the uploaded face, which arrived after its change was shown", run)
}
}
if strings.Contains(f, "oddity sans 2:system") {
system = true
if !c.late {
t.Errorf("%q was shown in %s, though the face came in time", run, f)
}
}
}
}
var st struct{ Loaded, Committed bool }
fr.eval(t, `({ Loaded: window.slidesFonts.loaded('u:Oddity Sans 2'), Committed: window.slidesFonts.committed('u:Oddity Sans 2') })`, &st)
if c.late {
if !system || !st.Committed {
t.Errorf("late: committed %v, a run seen in its fallback %v", st.Committed, system)
}
} else if !web || !st.Loaded {
t.Errorf("in time: loaded %v, a run seen in it %v", st.Loaded, web)
}
if n := fr.hits(ref); n != 1 {
t.Errorf("the uploaded face was fetched %d times", n)
}
})
}
}
// An upload whose own name is a catalog family's ("Liberation Serif")
// gets a css name of its own (library.go's cssFamilyName), loads under
// it, and the deck's catalog Serif headings never change face: the
// browser has only the catalog's four faces under that name.
func TestAnUploadedFontNamedLikeACatalogFamilyKeepsItsOwnName(t *testing.T) {
fr := newFontRigWith(t, dirStore(t))
css, _ := uploadFamily(t, fr, "LiberationMono-Regular.ttf", "Liberation Serif")
if strings.EqualFold(css, "Liberation Serif") {
t.Errorf("the upload took the catalog's name %q", css)
}
sqid := fr.deck(t, "Named", paperDeck)
fam := recordFamily(t, fr, sqid, css)
fr.ops(t, sqid, `[{"op":"set_meta","fontFiles":[`+fam+`],"fonts":{"heading":"","body":"'`+css+`', Liberation Sans, sans-serif"}}]`)
fr.probeAlso(css)
fr.goTo(t, "/d/"+sqid+"?slide=1")
fr.rig.Run(chromedp.Sleep(1500 * time.Millisecond))
p := fr.clean(t)
webEverywhere(t, p)
sameLayout(t, p)
if faces := p.Seen["A heading in serif@head00000001"]; len(faces) != 1 || !faces["liberation serif:web 700 normal"] {
t.Errorf("the heading was seen in %v, want only the catalog Serif", sortedKeys(faces))
}
body := false
for f := range p.Seen["Body@text00000001"] {
body = body || strings.HasPrefix(f, strings.ToLower(css)+":web")
}
if !body {
t.Errorf("the body was seen in %v, want the upload under %q", sortedKeys(p.Seen["Body@text00000001"]), css)
}
var serif int
fr.eval(t, `[...document.fonts].filter((f) => f.family.replace(/["']/g, '').toLowerCase() === 'liberation serif').length`, &serif)
if serif != 4 {
t.Errorf("%d faces in the page are called Liberation Serif, want the catalog's four", serif)
}
}