| 1 | //go:build browser |
| 2 | |
| 3 | // The font checks in a real Chromium, through the production middleware |
| 4 | // (rastrillo.Handler with Docs' own ServeOptions, CSP included), with the |
| 5 | // font files slowed down on the way out: |
| 6 | // |
| 7 | // RASTRILLO_CHROME=… CGO_ENABLED=0 go test -tags browser -run Font ./internal/docs/ |
| 8 | // |
| 9 | // Paul, 2026-10-24: "never a flash of unstyled text, ever", and the font |
| 10 | // menu shows each font in its own face. Every check here samples the page |
| 11 | // on every animation frame and on every DOM change, from before the first |
| 12 | // byte of HTML is parsed, and fails on any sample where text is visible in |
| 13 | // a face that has not loaded. |
| 14 | package docs_test |
| 15 | |
| 16 | import ( |
| 17 | "bytes" |
| 18 | "context" |
| 19 | "encoding/json" |
| 20 | "fmt" |
| 21 | "math" |
| 22 | "net/http" |
| 23 | "net/http/httptest" |
| 24 | "os" |
| 25 | "os/exec" |
| 26 | "path/filepath" |
| 27 | "sort" |
| 28 | "strconv" |
| 29 | "strings" |
| 30 | "sync" |
| 31 | "sync/atomic" |
| 32 | "testing" |
| 33 | "time" |
| 34 | |
| 35 | "amadan.net/rastrillo/rastrillo" |
| 36 | "amadan.net/rastrillo/rastrillo/harness" |
| 37 | "github.com/chromedp/cdproto/cdp" |
| 38 | "github.com/chromedp/cdproto/emulation" |
| 39 | "github.com/chromedp/cdproto/input" |
| 40 | "github.com/chromedp/cdproto/network" |
| 41 | "github.com/chromedp/cdproto/page" |
| 42 | "github.com/chromedp/chromedp" |
| 43 | "github.com/chromedp/chromedp/kb" |
| 44 | |
| 45 | "github.com/carlosframework/docs/internal/docs" |
| 46 | "github.com/carlosframework/docs/internal/export" |
| 47 | "github.com/carlosframework/docs/internal/fonts" |
| 48 | ) |
| 49 | |
| 50 | // fontRig is Docs behind its production middleware, with every font |
| 51 | // file (/static/fonts/*.woff2) held for slow before it is served, and a |
| 52 | // signed-in browser. |
| 53 | type fontRig struct { |
| 54 | rig *harness.Rig |
| 55 | app *docs.App |
| 56 | served http.Handler |
| 57 | cookies []*http.Cookie |
| 58 | // slow is how long a matching font waits, and match picks which |
| 59 | // font files wait ("" for all of them). |
| 60 | slow atomic.Int64 |
| 61 | match atomic.Value |
| 62 | // editorDelay holds the editor bundle; blocked answers 404 for any |
| 63 | // path containing it. |
| 64 | editorDelay atomic.Int64 |
| 65 | blocked atomic.Value |
| 66 | // sqid is the document a test is on, for the steps that post to it. |
| 67 | sqid string |
| 68 | // streams is how many live-update streams the server is serving now. |
| 69 | streams atomic.Int64 |
| 70 | } |
| 71 | |
| 72 | func newFontRig(t *testing.T) *fontRig { |
| 73 | t.Helper() |
| 74 | fr := &fontRig{} |
| 75 | fr.match.Store("") |
| 76 | fr.blocked.Store("") |
| 77 | fr.rig = harness.New(t, func(origin string) http.Handler { |
| 78 | var err error |
| 79 | fr.app, err = docs.NewForTestWith(t, docs.Config{Origin: origin}) |
| 80 | if err != nil { |
| 81 | t.Fatalf("NewForTestWith: %v", err) |
| 82 | } |
| 83 | served, done, err := rastrillo.Handler(docs.ServeOptions(rastrillo.Options{}, fr.app)) |
| 84 | if err != nil { |
| 85 | t.Fatalf("rastrillo.Handler: %v", err) |
| 86 | } |
| 87 | if done != nil { |
| 88 | t.Cleanup(func() { _ = done() }) |
| 89 | } |
| 90 | fr.served = served |
| 91 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 92 | if b := fr.blocked.Load().(string); b != "" && strings.Contains(r.URL.Path, b) { |
| 93 | http.NotFound(w, r) |
| 94 | return |
| 95 | } |
| 96 | if strings.HasSuffix(r.URL.Path, "/stream") { |
| 97 | fr.streams.Add(1) |
| 98 | defer fr.streams.Add(-1) |
| 99 | } |
| 100 | if strings.HasPrefix(r.URL.Path, "/static/editor.") { |
| 101 | time.Sleep(time.Duration(fr.editorDelay.Load())) |
| 102 | } |
| 103 | // The document's faces, not the picker's previews: this server |
| 104 | // is HTTP/1.1, whose six connections would queue sixteen |
| 105 | // held previews behind each other where a deployed instance's |
| 106 | // HTTP/2 fetches them at once. |
| 107 | if strings.HasPrefix(r.URL.Path, fonts.PathPrefix) && strings.HasSuffix(r.URL.Path, ".woff2") && |
| 108 | !strings.Contains(r.URL.Path, "/preview-") && strings.Contains(r.URL.Path, fr.match.Load().(string)) { |
| 109 | time.Sleep(time.Duration(fr.slow.Load())) |
| 110 | } |
| 111 | served.ServeHTTP(w, r) |
| 112 | }) |
| 113 | }) |
| 114 | fr.cookies = signInCookies(t, fr.app, "fonts@example.com") |
| 115 | var set []chromedp.Action[chromedp.Void] |
| 116 | for _, c := range fr.cookies { |
| 117 | set = append(set, setCookie(fr.rig.Origin, c)) |
| 118 | } |
| 119 | // Wide enough for the whole sheet, so the line-break check measures |
| 120 | // the 6.5in column the PDF sets. |
| 121 | set = append(set, command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: 1280, Height: 1000, DeviceScaleFactor: 1}), |
| 122 | // No HTTP cache between checks: each one is a first visit, which |
| 123 | // is when the fonts have to come over the network. |
| 124 | command(network.SetCacheDisabled, network.SetCacheDisabledParams{CacheDisabled: true}), |
| 125 | command(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: probeJS})) |
| 126 | fr.rig.Run(set...) |
| 127 | return fr |
| 128 | } |
| 129 | |
| 130 | // document creates a document holding a fragment vector. |
| 131 | func (fr *fontRig) document(t *testing.T, title, vector string) string { |
| 132 | t.Helper() |
| 133 | ctx := context.Background() |
| 134 | doc, err := fr.app.Store().Create(ctx, fr.app.TestPerson(t, "fonts@example.com"), title) |
| 135 | if err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | if vector != "" { |
| 139 | update, err := os.ReadFile("../../fixtures/vectors/fragment/" + vector) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | if _, err := fr.app.Store().ApplyUpdate(ctx, doc, fr.app.TestActorFor(t, doc), update); err != nil { |
| 144 | t.Fatal(err) |
| 145 | } |
| 146 | } |
| 147 | return doc.Sqid |
| 148 | } |
| 149 | |
| 150 | // probeJS runs before the page's own HTML. On every frame and every DOM |
| 151 | // change it looks at every run of document text that is visible, works |
| 152 | // out which private face it is drawn in, and records a violation if |
| 153 | // that face has not loaded. A run in a committed fallback names no |
| 154 | // private face, which is allowed: wrong but stable is not a flash. What |
| 155 | // is recorded too is every distinct face a run has been seen in, so a |
| 156 | // test can say a run never changed face. |
| 157 | const probeJS = `(() => { |
| 158 | const log = { violations: [], seen: {}, firstVisible: null, samples: 0, revealGaps: null, revealHeight: null }; |
| 159 | window.__fontProbe = log; |
| 160 | // The first Docs family in a computed stack. Chromium quotes the names |
| 161 | // and WebKit does not (Docs Caveat, Segoe Print, cursive), so the stack |
| 162 | // is split, not matched for quotes (branch review 6). |
| 163 | const docsFamily = (stack) => { |
| 164 | for (const part of stack.split(',')) { |
| 165 | const name = part.trim().replace(/^["']|["']$/g, ''); |
| 166 | if (name.startsWith('Docs ')) return name; |
| 167 | } |
| 168 | return null; |
| 169 | }; |
| 170 | window.__docsFamily = docsFamily; |
| 171 | const faceOf = (el) => { |
| 172 | const cs = getComputedStyle(el); |
| 173 | return { family: docsFamily(cs.fontFamily), stack: cs.fontFamily, weight: cs.fontWeight, style: cs.fontStyle, visible: cs.visibility === 'visible' }; |
| 174 | }; |
| 175 | const sample = (why) => { |
| 176 | const root = document.querySelector('[docs-text]'); |
| 177 | if (!root) return; |
| 178 | log.samples++; |
| 179 | const sheet = document.querySelector('[docs-page]'); |
| 180 | if (sheet && log.revealGaps === null && getComputedStyle(sheet).visibility === 'visible') { |
| 181 | log.revealGaps = document.querySelectorAll('[docs-page-gap]').length; |
| 182 | log.revealHeight = Math.round(sheet.getBoundingClientRect().height); |
| 183 | } |
| 184 | const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); |
| 185 | for (let n = walker.nextNode(); n; n = walker.nextNode()) { |
| 186 | if (!n.data.trim()) continue; |
| 187 | const el = n.parentElement; |
| 188 | const f = faceOf(el); |
| 189 | if (!f.visible) continue; |
| 190 | if (log.firstVisible === null) log.firstVisible = performance.now(); |
| 191 | const key = n.data.slice(0, 24); |
| 192 | const desc = (f.family || f.stack) + ' ' + f.weight + ' ' + f.style; |
| 193 | (log.seen[key] = log.seen[key] || {})[desc] = true; |
| 194 | if (!f.family) continue; |
| 195 | const css = (f.style === 'italic' ? 'italic ' : '') + f.weight + ' 16px "' + f.family + '"'; |
| 196 | if (!document.fonts.check(css)) { |
| 197 | const faces = [...document.fonts].filter((x) => x.family.replace(/["']/g, '') === f.family).map((x) => x.weight + '/' + x.style + '=' + x.status).join(' '); |
| 198 | log.violations.push(Math.round(performance.now()) + 'ms ' + why + ': "' + key + '" visible in ' + css + ' before it loaded [' + faces + '; faces=' + document.documentElement.getAttribute('data-docs-faces') + ' fonts=' + document.documentElement.getAttribute('data-docs-fonts') + ']'); |
| 199 | } |
| 200 | } |
| 201 | }; |
| 202 | const frame = () => { sample('frame'); requestAnimationFrame(frame); }; |
| 203 | requestAnimationFrame(frame); |
| 204 | new MutationObserver(() => sample('mutation')).observe(document, { subtree: true, childList: true, attributes: true, characterData: true }); |
| 205 | })()` |
| 206 | |
| 207 | type probe struct { |
| 208 | Violations []string `json:"violations"` |
| 209 | Seen map[string]map[string]bool `json:"seen"` |
| 210 | FirstVisible *float64 `json:"firstVisible"` |
| 211 | Samples int `json:"samples"` |
| 212 | RevealGaps *int `json:"revealGaps"` |
| 213 | RevealHeight *int `json:"revealHeight"` |
| 214 | } |
| 215 | |
| 216 | func (fr *fontRig) probe(t *testing.T) probe { |
| 217 | t.Helper() |
| 218 | var raw string |
| 219 | fr.rig.Run(evalInto(&raw, `JSON.stringify(window.__fontProbe)`)) |
| 220 | var p probe |
| 221 | if err := json.Unmarshal([]byte(raw), &p); err != nil { |
| 222 | t.Fatalf("probe: %v (%s)", err, raw) |
| 223 | } |
| 224 | if p.Samples < 10 { |
| 225 | t.Fatalf("the probe sampled the page %d times; it cannot see what it is checking", p.Samples) |
| 226 | } |
| 227 | return p |
| 228 | } |
| 229 | |
| 230 | func (fr *fontRig) open(t *testing.T, sqid string) { |
| 231 | t.Helper() |
| 232 | fr.rig.Run(fr.navigate("/d/"+sqid), |
| 233 | chromedp.WaitVisible(chromedp.CSS(`html[data-docs-fonts="shown"] [docs-text]`))) |
| 234 | } |
| 235 | |
| 236 | // navigate goes to path without waiting for the load event, which waits |
| 237 | // for every font the page has started fetching: a check of what happens |
| 238 | // while a font is slow must be able to act while it is. |
| 239 | func (fr *fontRig) navigate(path string) chromedp.Action[chromedp.Void] { |
| 240 | return command(page.Navigate, page.NavigateParams{URL: fr.rig.Origin + path}) |
| 241 | } |
| 242 | |
| 243 | // editable waits until the editor accepts input, which is once every |
| 244 | // face of every family in use has settled. |
| 245 | func (fr *fontRig) editable(t *testing.T) { |
| 246 | t.Helper() |
| 247 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text][contenteditable="true"]`))) |
| 248 | } |
| 249 | |
| 250 | func (fr *fontRig) eval(t *testing.T, js string, out any, await ...bool) { |
| 251 | t.Helper() |
| 252 | var opts []chromedp.EvaluateOption |
| 253 | if len(await) > 0 && await[0] { |
| 254 | opts = append(opts, chromedp.EvalAwaitPromise) |
| 255 | } |
| 256 | var raw json.RawMessage |
| 257 | fr.rig.Run(evalInto(&raw, js, opts...)) |
| 258 | if len(raw) == 0 || string(raw) == "null" { |
| 259 | return |
| 260 | } |
| 261 | if err := json.Unmarshal(raw, out); err != nil { |
| 262 | t.Fatalf("eval: decoding %s: %v", raw, err) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // evalInto is a step that evaluates js and decodes the result into out. |
| 267 | // A script that returns null or undefined leaves out as it was, as |
| 268 | // chromedp v0.14's Evaluate did; v0.21's fails on null for a type that |
| 269 | // cannot be nil, so the result is read through a pointer. |
| 270 | func evalInto[T any](out *T, js string, opts ...chromedp.EvaluateOption) chromedp.Action[chromedp.Void] { |
| 271 | return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { |
| 272 | v, err := chromedp.Evaluate[*T](js, opts...)(ctx, t) |
| 273 | if err != nil { |
| 274 | return err |
| 275 | } |
| 276 | if v != nil { |
| 277 | *out = *v |
| 278 | } |
| 279 | return nil |
| 280 | }) |
| 281 | } |
| 282 | |
| 283 | // command is a step that sends one protocol command and drops its result. |
| 284 | func command[P, R any](c cdp.Command[P, R], params P) chromedp.Action[chromedp.Void] { |
| 285 | return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { |
| 286 | _, err := cdp.Call(ctx, t, c, params) |
| 287 | return err |
| 288 | }) |
| 289 | } |
| 290 | |
| 291 | // setCookie is a step that sets a sign-in cookie for the rig's origin. |
| 292 | func setCookie(origin string, c *http.Cookie) chromedp.Action[chromedp.Void] { |
| 293 | return command(network.SetCookie, network.SetCookieParams{ |
| 294 | Name: c.Name, Value: c.Value, URL: origin + "/", |
| 295 | HTTPOnly: &c.HttpOnly, Secure: &c.Secure, SameSite: network.CookieSameSiteLax, |
| 296 | }) |
| 297 | } |
| 298 | |
| 299 | // Text is not painted before its fonts are ready. Every font file is |
| 300 | // held for a second and a half, well under the gate's deadline, so the |
| 301 | // right answer is: nothing visible until every face the document uses |
| 302 | // has loaded, then the text, once, in those faces. |
| 303 | func TestFontTextIsNotPaintedBeforeItsFontsAreReady(t *testing.T) { |
| 304 | fr := newFontRig(t) |
| 305 | sqid := fr.document(t, "Faces", "faces.bin") |
| 306 | // 700 ms, not more: the gate now waits for every style of three |
| 307 | // families, twelve files, and this test server is HTTP/1.1, whose six |
| 308 | // connections fetch them in two rounds. |
| 309 | fr.slow.Store(int64(700 * time.Millisecond)) |
| 310 | start := time.Now() |
| 311 | fr.open(t, sqid) |
| 312 | if waited := time.Since(start); waited < 650*time.Millisecond { |
| 313 | t.Fatalf("the sheet was shown %v after navigating, before the fonts could have arrived: the slowdown did not apply", waited) |
| 314 | } |
| 315 | p := fr.probe(t) |
| 316 | for _, v := range p.Violations { |
| 317 | t.Error(v) |
| 318 | } |
| 319 | var fallback string |
| 320 | fr.eval(t, `document.documentElement.getAttribute('data-docs-fonts-fallback') || ''`, &fallback) |
| 321 | if fallback != "" { |
| 322 | t.Errorf("fonts that arrived in time were committed to their fallback: %q", fallback) |
| 323 | } |
| 324 | for run, faces := range p.Seen { |
| 325 | if len(faces) != 1 { |
| 326 | t.Errorf("%q was shown in more than one face: %v", run, faces) |
| 327 | } |
| 328 | } |
| 329 | if p.FirstVisible == nil { |
| 330 | t.Fatal("no text was ever visible") |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // Past the deadline the gate commits: the text appears in its fallback |
| 335 | // and stays in it when the font finally arrives, so it is shown once and |
| 336 | // never swaps. Nothing is visible in a face that has not loaded. |
| 337 | func TestFontALateFontCommitsToItsFallbackAndNeverSwaps(t *testing.T) { |
| 338 | fr := newFontRig(t) |
| 339 | sqid := fr.document(t, "Late", "faces.bin") |
| 340 | // Carlito alone is late: slowing every file would hold all six of |
| 341 | // this HTTP/1.1 server's connections and keep the gate's own script |
| 342 | // from arriving before the deadline. |
| 343 | fr.match.Store("Carlito-") |
| 344 | fr.slow.Store(int64(4 * time.Second)) |
| 345 | fr.open(t, sqid) |
| 346 | var fallback string |
| 347 | fr.eval(t, `document.documentElement.getAttribute('data-docs-fonts-fallback') || ''`, &fallback) |
| 348 | if !strings.Contains(fallback, "carlito") { |
| 349 | t.Fatalf("Carlito missed the deadline and was not committed: fallback %q", fallback) |
| 350 | } |
| 351 | // Let the late fonts land, and keep sampling while they do. |
| 352 | fr.rig.Run(chromedp.Sleep(3 * time.Second)) |
| 353 | var loaded bool |
| 354 | fr.eval(t, `document.fonts.check('16px "Docs Carlito"')`, &loaded) |
| 355 | if !loaded { |
| 356 | t.Fatal("Carlito never arrived, so this cannot show it was not swapped in") |
| 357 | } |
| 358 | p := fr.probe(t) |
| 359 | for _, v := range p.Violations { |
| 360 | t.Error(v) |
| 361 | } |
| 362 | for run, faces := range p.Seen { |
| 363 | if len(faces) != 1 { |
| 364 | t.Errorf("%q changed face after it was shown: %v", run, faces) |
| 365 | } |
| 366 | for f := range faces { |
| 367 | if strings.Contains(f, "Docs Carlito") { |
| 368 | t.Errorf("%q swapped into Carlito after the page committed to its fallback", run) |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | var note bool |
| 373 | fr.eval(t, `(document.querySelector('[docs-fonts-status]') || { getAttribute: () => '' }).getAttribute('data-state') === 'substitute'`, ¬e) |
| 374 | if !note { |
| 375 | t.Error("the page shows substitutes and does not say so") |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | // Each entry of the font menu is drawn in its own face, and the menu |
| 380 | // does not open until those faces are in. A row is the family's name and |
| 381 | // nothing else (no compatibility description, Paul 2026-10-26), and every |
| 382 | // row is the same height, twin or not. |
| 383 | func TestFontEachPickerEntryRendersInItsOwnFace(t *testing.T) { |
| 384 | fr := newFontRig(t) |
| 385 | sqid := fr.document(t, "Picker", "") |
| 386 | fr.open(t, sqid) |
| 387 | fr.rig.Run( |
| 388 | chromedp.WaitEnabled(chromedp.CSS(`#docs-select-font-combo`)), |
| 389 | chromedp.Click(chromedp.CSS(`#docs-select-font-combo`)), |
| 390 | chromedp.WaitVisible(chromedp.CSS(`#docs-select-font-listbox [rst-combo-option]`)), |
| 391 | ) |
| 392 | var rows []struct { |
| 393 | Text string `json:"text"` |
| 394 | Family string `json:"family"` |
| 395 | Loaded bool `json:"loaded"` |
| 396 | Desc bool `json:"desc"` |
| 397 | Height float64 `json:"height"` |
| 398 | } |
| 399 | fr.eval(t, `[...document.querySelectorAll('#docs-select-font-listbox [rst-combo-option]')].map(li => { |
| 400 | const fam = getComputedStyle(li).fontFamily; |
| 401 | const pf = window.__docsFamily(fam); const m = pf && pf.startsWith('Docs Preview') ? [pf, pf] : null; |
| 402 | return { text: li.textContent, family: m ? m[1] : fam, |
| 403 | loaded: !!m && document.fonts.check('16px "' + m[1] + '"'), |
| 404 | desc: !!li.querySelector('[rst-combo-name], [rst-combo-desc]'), height: li.getBoundingClientRect().height }; |
| 405 | })`, &rows) |
| 406 | if len(rows) != len(fonts.Families) { |
| 407 | t.Fatalf("the menu has %d rows, the manifest %d families", len(rows), len(fonts.Families)) |
| 408 | } |
| 409 | for i, f := range fonts.Families { |
| 410 | r := rows[i] |
| 411 | if r.Text != f.Name { |
| 412 | t.Errorf("row %d reads %q, want %q", i, r.Text, f.Name) |
| 413 | } |
| 414 | if r.Family != f.PreviewCSSName() || !r.Loaded { |
| 415 | t.Errorf("%s is drawn in %q (loaded %v), want its own preview face %q", f.Name, r.Family, r.Loaded, f.PreviewCSSName()) |
| 416 | } |
| 417 | if r.Desc { |
| 418 | t.Errorf("%s's row carries a description", f.Name) |
| 419 | } |
| 420 | if math.Abs(r.Height-rows[0].Height) > 0.5 { |
| 421 | t.Errorf("%s's row is %.1fpx tall, %s's %.1fpx", f.Name, r.Height, fonts.Families[0].Name, rows[0].Height) |
| 422 | } |
| 423 | } |
| 424 | // The closed box wears the default's face too. |
| 425 | var box string |
| 426 | fr.eval(t, `getComputedStyle(document.querySelector('#docs-select-font-combo')).fontFamily`, &box) |
| 427 | if !strings.Contains(box, fonts.Default.PreviewCSSName()) { |
| 428 | t.Errorf("the closed font box is drawn in %q, not Carlito's preview", box) |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | // Picking a font loads it before applying it: with Playfair Display held |
| 433 | // for a second and a half, no run is in Playfair until it has loaded, |
| 434 | // and then the selection is. |
| 435 | func TestFontPickingAFontLoadsItBeforeApplyingIt(t *testing.T) { |
| 436 | fr := newFontRig(t) |
| 437 | sqid := fr.document(t, "Pick", "simple.bin") |
| 438 | fr.open(t, sqid) |
| 439 | fr.editable(t) |
| 440 | fr.match.Store("PlayfairDisplay-") |
| 441 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 442 | var picked bool |
| 443 | fr.eval(t, `(() => { |
| 444 | const p = document.querySelector('[docs-text] p'); |
| 445 | const r = document.createRange(); r.selectNodeContents(p); |
| 446 | const s = getSelection(); s.removeAllRanges(); s.addRange(r); |
| 447 | document.querySelector('[docs-text]').focus(); |
| 448 | return true })()`, &picked) |
| 449 | fr.rig.Run(chromedp.Sleep(200 * time.Millisecond)) |
| 450 | fr.eval(t, `(() => { const s = document.querySelector('[data-docs-select="font"]'); s.value = 'playfair'; |
| 451 | s.dispatchEvent(new Event('change', { bubbles: true })); return true })()`, &picked) |
| 452 | var early bool |
| 453 | fr.rig.Run(chromedp.Sleep(500 * time.Millisecond)) |
| 454 | fr.eval(t, `!!document.querySelector('[docs-text] .docs-font-playfair')`, &early) |
| 455 | if early { |
| 456 | t.Error("the mark was applied while Playfair Display was still loading") |
| 457 | } |
| 458 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-playfair`))) |
| 459 | p := fr.probe(t) |
| 460 | for _, v := range p.Violations { |
| 461 | t.Error(v) |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | // A collaborator's font change waits for that font to load: another |
| 466 | // person posts a paragraph in Playfair Display, which this tab has never |
| 467 | // loaded and which is held for a second and a half. It appears once, in |
| 468 | // Playfair. |
| 469 | func TestFontACollaboratorsFontChangeWaitsForTheFont(t *testing.T) { |
| 470 | fr := newFontRig(t) |
| 471 | sqid := fr.document(t, "Together", "") |
| 472 | fr.open(t, sqid) |
| 473 | // Give the stream a moment to connect. |
| 474 | fr.rig.Run(chromedp.Sleep(500 * time.Millisecond)) |
| 475 | fr.match.Store("PlayfairDisplay-") |
| 476 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 477 | |
| 478 | update, err := os.ReadFile("../../fixtures/vectors/fragment/playfair.bin") |
| 479 | if err != nil { |
| 480 | t.Fatal(err) |
| 481 | } |
| 482 | req := httptest.NewRequest(http.MethodPost, "/d/"+sqid+"/updates", bytes.NewReader(update)) |
| 483 | req.Header.Set("Content-Type", "application/octet-stream") |
| 484 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 485 | for _, c := range fr.cookies { |
| 486 | req.AddCookie(c) |
| 487 | } |
| 488 | rec := httptest.NewRecorder() |
| 489 | fr.served.ServeHTTP(rec, req) |
| 490 | if rec.Code/100 != 2 { |
| 491 | t.Fatalf("the collaborator's POST: %d %s", rec.Code, rec.Body.String()) |
| 492 | } |
| 493 | posted := time.Now() |
| 494 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-playfair`))) |
| 495 | if waited := time.Since(posted); waited < 1200*time.Millisecond { |
| 496 | t.Errorf("the change appeared %v after it was posted, sooner than its font could have loaded", waited) |
| 497 | } |
| 498 | p := fr.probe(t) |
| 499 | for _, v := range p.Violations { |
| 500 | t.Error(v) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | // The PDF breaks lines where the screen does, because both shape the |
| 505 | // same font programs (Paul's default 6). Three long paragraphs, in |
| 506 | // Carlito, Caladea and Inter, written to kern and ligate; the words on |
| 507 | // each screen line must be the words on each PDF line. |
| 508 | func TestFontThePDFsLineBreaksMatchTheScreen(t *testing.T) { |
| 509 | fr := newFontRig(t) |
| 510 | sqid := fr.document(t, "Lines", "linebreaks.bin") |
| 511 | fr.open(t, sqid) |
| 512 | var screen []string |
| 513 | fr.eval(t, `(() => { |
| 514 | const out = []; |
| 515 | for (const p of document.querySelectorAll('[docs-text] p')) { |
| 516 | const walker = document.createTreeWalker(p, NodeFilter.SHOW_TEXT); |
| 517 | let line = [], top = null; |
| 518 | for (let n = walker.nextNode(); n; n = walker.nextNode()) { |
| 519 | const re = /\S+/g; let m; |
| 520 | while ((m = re.exec(n.data))) { |
| 521 | const r = document.createRange(); r.setStart(n, m.index); r.setEnd(n, m.index + m[0].length); |
| 522 | const y = Math.round(r.getClientRects()[0].top); |
| 523 | if (top !== null && y !== top) { out.push(line.join(' ')); line = []; } |
| 524 | top = y; line.push(m[0]); |
| 525 | } |
| 526 | } |
| 527 | if (line.length) out.push(line.join(' ')); |
| 528 | } |
| 529 | return out })()`, &screen) |
| 530 | |
| 531 | structureJSON, err := fr.app.Store().JSON(context.Background(), fr.storeDoc(t, sqid)) |
| 532 | if err != nil { |
| 533 | t.Fatal(err) |
| 534 | } |
| 535 | structure, err := export.Parse("", structureJSON) |
| 536 | if err != nil { |
| 537 | t.Fatal(err) |
| 538 | } |
| 539 | var paper []string |
| 540 | for _, l := range export.Lines(structure) { |
| 541 | paper = append(paper, strings.Join(strings.Fields(l), " ")) |
| 542 | } |
| 543 | if len(screen) < 12 { |
| 544 | t.Fatalf("the screen set %d lines; the paragraphs should run to many", len(screen)) |
| 545 | } |
| 546 | if strings.Join(screen, "\n") != strings.Join(paper, "\n") { |
| 547 | n := max(len(screen), len(paper)) |
| 548 | var diff strings.Builder |
| 549 | for i := 0; i < n; i++ { |
| 550 | s, p := "", "" |
| 551 | if i < len(screen) { |
| 552 | s = screen[i] |
| 553 | } |
| 554 | if i < len(paper) { |
| 555 | p = paper[i] |
| 556 | } |
| 557 | mark := " " |
| 558 | if s != p { |
| 559 | mark = "!=" |
| 560 | } |
| 561 | fmt.Fprintf(&diff, "%s screen: %s\n paper: %s\n", mark, s, p) |
| 562 | } |
| 563 | t.Errorf("the PDF breaks lines differently from the screen:\n%s", diff.String()) |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | func (fr *fontRig) storeDoc(t *testing.T, sqid string) *docs.Document { |
| 568 | t.Helper() |
| 569 | doc, err := fr.app.Store().GetFor(context.Background(), fr.app.TestActorForPerson(t, fr.app.TestPerson(t, "fonts@example.com")), sqid) |
| 570 | if err != nil { |
| 571 | t.Fatal(err) |
| 572 | } |
| 573 | return doc |
| 574 | } |
| 575 | |
| 576 | // post is a collaborator's change: a fragment vector posted to the |
| 577 | // document's update log the way another tab posts one. |
| 578 | func (fr *fontRig) post(t *testing.T, sqid, vector string) { |
| 579 | t.Helper() |
| 580 | update, err := os.ReadFile("../../fixtures/vectors/fragment/" + vector) |
| 581 | if err != nil { |
| 582 | t.Fatal(err) |
| 583 | } |
| 584 | req := httptest.NewRequest(http.MethodPost, "/d/"+sqid+"/updates", bytes.NewReader(update)) |
| 585 | req.Header.Set("Content-Type", "application/octet-stream") |
| 586 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 587 | for _, c := range fr.cookies { |
| 588 | req.AddCookie(c) |
| 589 | } |
| 590 | rec := httptest.NewRecorder() |
| 591 | fr.served.ServeHTTP(rec, req) |
| 592 | if rec.Code/100 != 2 { |
| 593 | t.Fatalf("POST %s: %d %s", vector, rec.Code, rec.Body.String()) |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | func (fr *fontRig) noViolations(t *testing.T) probe { |
| 598 | t.Helper() |
| 599 | p := fr.probe(t) |
| 600 | for _, v := range p.Violations { |
| 601 | t.Error(v) |
| 602 | } |
| 603 | return p |
| 604 | } |
| 605 | |
| 606 | // Review finding 1. A collaborator's change can bring in a face without |
| 607 | // naming any font: code is Liberation Mono, bold is the default's bold. |
| 608 | // Each must wait for its face like a named family does. |
| 609 | func TestFontARemoteChangeWaitsForTheFacesItUses(t *testing.T) { |
| 610 | for _, c := range []struct{ vector, slow, sel string }{ |
| 611 | {"remote-code.bin", "LiberationMono-", "[docs-text] code"}, |
| 612 | {"remote-bold.bin", "Carlito-Bold.", "[docs-text] strong"}, |
| 613 | } { |
| 614 | t.Run(c.vector, func(t *testing.T) { |
| 615 | fr := newFontRig(t) |
| 616 | sqid := fr.document(t, "Remote", "simple.bin") |
| 617 | fr.match.Store(c.slow) |
| 618 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 619 | fr.open(t, sqid) |
| 620 | fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
| 621 | fr.post(t, sqid, c.vector) |
| 622 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(c.sel)), chromedp.Sleep(200*time.Millisecond)) |
| 623 | fr.noViolations(t) |
| 624 | }) |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | // Review finding 1. A paste of code, which names no font, waits for |
| 629 | // Liberation Mono; so does typing a heading through the "# " rule, which |
| 630 | // waits for the default's bold. |
| 631 | func TestFontAPasteAndAnInputRuleWaitForTheirFaces(t *testing.T) { |
| 632 | t.Run("paste", func(t *testing.T) { |
| 633 | fr := newFontRig(t) |
| 634 | sqid := fr.document(t, "Paste", "simple.bin") |
| 635 | fr.match.Store("LiberationMono-") |
| 636 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 637 | fr.open(t, sqid) |
| 638 | fr.editable(t) |
| 639 | var ok bool |
| 640 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 641 | const d = new DataTransfer(); d.setData('text/html', '<p><code>Pasted code</code></p>'); |
| 642 | return el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) })()`, &ok) |
| 643 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] code`)), chromedp.Sleep(200*time.Millisecond)) |
| 644 | fr.noViolations(t) |
| 645 | }) |
| 646 | t.Run("heading rule", func(t *testing.T) { |
| 647 | fr := newFontRig(t) |
| 648 | sqid := fr.document(t, "Rule", "simple.bin") |
| 649 | fr.match.Store("Carlito-Bold.") |
| 650 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 651 | fr.open(t, sqid) |
| 652 | // Type the moment the editor will take it: that must not be |
| 653 | // before the bold a heading is set in has arrived. |
| 654 | fr.editable(t) |
| 655 | var ok bool |
| 656 | fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p:last-child'); const r = document.createRange(); |
| 657 | r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r); |
| 658 | document.querySelector('[docs-text]').focus(); return true })()`, &ok) |
| 659 | fr.rig.Run(chromedp.KeyEvent("\r"), chromedp.SendKeys(chromedp.CSS(`[docs-text]`), "# A heading"), |
| 660 | chromedp.WaitVisible(chromedp.CSS(`[docs-text] h1`)), chromedp.Sleep(300*time.Millisecond)) |
| 661 | fr.noViolations(t) |
| 662 | }) |
| 663 | } |
| 664 | |
| 665 | // Review finding 2, under the family rule (review 4). The gate waits for |
| 666 | // all of a family's styles, so Carlito Bold eight seconds late commits |
| 667 | // Carlito to its fallback before anything is shown. Then nothing on |
| 668 | // screen ever changes face: not when a paragraph is bolded, not when the |
| 669 | // bold arrives. |
| 670 | func TestFontABoldThatCannotLoadChangesNothing(t *testing.T) { |
| 671 | fr := newFontRig(t) |
| 672 | sqid := fr.document(t, "Bold", "simple.bin") |
| 673 | fr.match.Store("Carlito-Bold.") |
| 674 | fr.slow.Store(int64(8 * time.Second)) |
| 675 | fr.open(t, sqid) |
| 676 | var fallback string |
| 677 | fr.eval(t, `document.documentElement.getAttribute('data-docs-fonts-fallback') || ''`, &fallback) |
| 678 | if !strings.Contains(fallback, "carlito") { |
| 679 | t.Fatalf("Carlito's bold missed the deadline but Carlito was not committed: %q", fallback) |
| 680 | } |
| 681 | var before, after string |
| 682 | face := `getComputedStyle(document.querySelector('[docs-text] p:last-child')).fontFamily` |
| 683 | fr.eval(t, face, &before) |
| 684 | fr.editable(t) |
| 685 | var ok bool |
| 686 | fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p'); const r = document.createRange(); r.selectNodeContents(p); |
| 687 | getSelection().removeAllRanges(); getSelection().addRange(r); document.querySelector('[docs-text]').focus(); return true })()`, &ok) |
| 688 | fr.rig.Run(chromedp.Sleep(100*time.Millisecond), chromedp.Click(chromedp.CSS(`[docs-toolbar] [data-docs-command="strong"]`)), |
| 689 | chromedp.Sleep(8*time.Second)) |
| 690 | fr.eval(t, face, &after) |
| 691 | if before != after || strings.Contains(after, "Docs Carlito") { |
| 692 | t.Errorf("an untouched paragraph changed face, or left its fallback: %s -> %s", before, after) |
| 693 | } |
| 694 | // The bolded paragraph changes by the person's own hand; every |
| 695 | // other run keeps the one face it was first shown in. |
| 696 | p := fr.noViolations(t) |
| 697 | for run, faces := range p.Seen { |
| 698 | if len(faces) != 1 && run != "First paragraph." { |
| 699 | t.Errorf("%q changed face: %v", run, faces) |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | // Review finding 3. A paged document is first shown already paginated: |
| 705 | // the page gaps when the sheet first becomes visible are the gaps a |
| 706 | // moment later. With the editor bundle held past every deadline, the |
| 707 | // sheet shows unpaginated and stays that way for the visit rather than |
| 708 | // gaining pages under the reader. |
| 709 | func TestFontTheFirstRevealIsTheFinalLayout(t *testing.T) { |
| 710 | for _, c := range []struct { |
| 711 | name string |
| 712 | delay time.Duration |
| 713 | gaps bool |
| 714 | }{ |
| 715 | {"editor in time", 0, true}, |
| 716 | {"editor late", 5 * time.Second, false}, |
| 717 | } { |
| 718 | t.Run(c.name, func(t *testing.T) { |
| 719 | fr := newFontRig(t) |
| 720 | sqid := fr.document(t, "Pages", "long.bin") |
| 721 | fr.rig.Run(command(network.SetCookie, network.SetCookieParams{Name: "docs-view", Value: "paged", URL: fr.rig.Origin + "/"})) |
| 722 | fr.editorDelay.Store(int64(c.delay)) |
| 723 | fr.rig.Run(fr.navigate("/d/"+sqid), |
| 724 | chromedp.WaitVisible(chromedp.CSS(`[docs-page]`)), chromedp.Sleep(c.delay+1500*time.Millisecond)) |
| 725 | p := fr.noViolations(t) |
| 726 | var gaps, height int |
| 727 | fr.eval(t, `document.querySelectorAll('[docs-page-gap]').length`, &gaps) |
| 728 | fr.eval(t, `Math.round(document.querySelector('[docs-page]').getBoundingClientRect().height)`, &height) |
| 729 | if p.RevealGaps == nil { |
| 730 | t.Fatal("the sheet was never seen becoming visible") |
| 731 | } |
| 732 | if *p.RevealGaps != gaps || *p.RevealHeight != height { |
| 733 | t.Errorf("first shown with %d page gaps, %dpx tall; then %d gaps, %dpx", *p.RevealGaps, *p.RevealHeight, gaps, height) |
| 734 | } |
| 735 | if c.gaps != (gaps > 0) { |
| 736 | t.Errorf("%d page gaps; want gaps %v", gaps, c.gaps) |
| 737 | } |
| 738 | }) |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | // Review finding 4. If the font gate's script never arrives, the |
| 743 | // document is still shown, in its system faces, and never changes face. |
| 744 | // If the hold script itself never arrives, nothing is held at all. |
| 745 | func TestFontAMissingScriptNeverHidesTheDocument(t *testing.T) { |
| 746 | for _, c := range []struct { |
| 747 | blocked string |
| 748 | editorDelay time.Duration |
| 749 | }{ |
| 750 | {"/static/fontsgate.", 0}, |
| 751 | // No gate and no editor either: only the hold's own fail-safe |
| 752 | // is left to show the page. |
| 753 | {"/static/fontsgate.", 12 * time.Second}, |
| 754 | {"/static/fontshold.", 0}, |
| 755 | } { |
| 756 | blocked := c.blocked |
| 757 | t.Run(fmt.Sprintf("%s editor %v", blocked, c.editorDelay), func(t *testing.T) { |
| 758 | fr := newFontRig(t) |
| 759 | sqid := fr.document(t, "Missing", "faces.bin") |
| 760 | fr.blocked.Store(blocked) |
| 761 | fr.editorDelay.Store(int64(c.editorDelay)) |
| 762 | fr.rig.Allow(http.MethodGet, blocked, http.StatusNotFound) |
| 763 | // With an editor, it shows the page itself once it has |
| 764 | // paginated, well before the hold's fail-safe; without one, |
| 765 | // the fail-safe does at six seconds. |
| 766 | wait := 7 * time.Second |
| 767 | if c.editorDelay == 0 { |
| 768 | wait = 3 * time.Second |
| 769 | } |
| 770 | fr.rig.Run(fr.navigate("/d/"+sqid), chromedp.Sleep(wait)) |
| 771 | var visible string |
| 772 | fr.eval(t, `getComputedStyle(document.querySelector('[docs-page]')).visibility`, &visible) |
| 773 | if visible != "visible" { |
| 774 | t.Fatalf("the sheet is %s with %s missing", visible, blocked) |
| 775 | } |
| 776 | p := fr.noViolations(t) |
| 777 | for run, faces := range p.Seen { |
| 778 | if len(faces) != 1 { |
| 779 | t.Errorf("%q changed face: %v", run, faces) |
| 780 | } |
| 781 | } |
| 782 | }) |
| 783 | } |
| 784 | } |
| 785 | |
| 786 | // One wait at a time (branch review 7). A pick that needs a font starts |
| 787 | // a wait with the font control inert; a second pick made meanwhile (only |
| 788 | // a script can make one) is refused and said, not queued behind the |
| 789 | // first. |
| 790 | func TestFontASecondPickDuringAWaitIsRefused(t *testing.T) { |
| 791 | fr := newFontRig(t) |
| 792 | sqid := fr.document(t, "Order", "simple.bin") |
| 793 | fr.match.Store("PlayfairDisplay-") |
| 794 | fr.slow.Store(int64(1800 * time.Millisecond)) |
| 795 | fr.open(t, sqid) |
| 796 | fr.editable(t) |
| 797 | var ok bool |
| 798 | fr.eval(t, waitLogJS, &ok) |
| 799 | fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p'); const r = document.createRange(); r.selectNodeContents(p); |
| 800 | getSelection().removeAllRanges(); getSelection().addRange(r); document.querySelector('[docs-text]').focus(); return true })()`, &ok) |
| 801 | fr.rig.Run(chromedp.Sleep(100 * time.Millisecond)) |
| 802 | fr.eval(t, `(() => { const s = document.querySelector('#docs-select-font'); |
| 803 | s.value = 'playfair'; s.dispatchEvent(new Event('change', { bubbles: true })); return true })()`, &ok) |
| 804 | if !fr.inWait(t) { |
| 805 | t.Fatal("the pick did not start a visible wait") |
| 806 | } |
| 807 | var pickerInert bool |
| 808 | fr.eval(t, `!!document.querySelector('#docs-select-font').closest('[inert]')`, &pickerInert) |
| 809 | if !pickerInert { |
| 810 | t.Error("the font control can still be used during the wait") |
| 811 | } |
| 812 | fr.eval(t, `(() => { const s = document.querySelector('#docs-select-font'); |
| 813 | s.value = 'inter'; s.dispatchEvent(new Event('change', { bubbles: true })); return true })()`, &ok) |
| 814 | fr.settled(t) |
| 815 | var html string |
| 816 | fr.eval(t, `document.querySelector('[docs-text] p').innerHTML`, &html) |
| 817 | if !strings.Contains(html, "docs-font-playfair") || strings.Contains(html, "docs-font-inter") { |
| 818 | t.Errorf("the first paragraph is %s; the first pick should be applied and the second refused", html) |
| 819 | } |
| 820 | refused := false |
| 821 | for _, e := range fr.waitLog(t) { |
| 822 | refused = refused || e.State == "refused" |
| 823 | } |
| 824 | if !refused { |
| 825 | t.Error("the second pick was not said to be refused") |
| 826 | } |
| 827 | fr.noViolations(t) |
| 828 | } |
| 829 | |
| 830 | // Review finding 6. The closed font control wears the face of the font |
| 831 | // the caret is in, not the one it last showed. |
| 832 | func TestFontTheClosedPickerFollowsTheCaret(t *testing.T) { |
| 833 | fr := newFontRig(t) |
| 834 | sqid := fr.document(t, "Caret", "fonts.bin") |
| 835 | fr.open(t, sqid) |
| 836 | fr.editable(t) |
| 837 | serif, _ := fonts.ByKey("serif") |
| 838 | var ok bool |
| 839 | fr.eval(t, `(() => { const n = document.querySelector('[docs-text] .docs-font-serif').firstChild; const r = document.createRange(); |
| 840 | r.setStart(n, 2); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); |
| 841 | document.querySelector('[docs-text]').focus(); return true })()`, &ok) |
| 842 | fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
| 843 | var got []string |
| 844 | fr.eval(t, `[document.querySelector('#docs-select-font').value, document.querySelector('#docs-select-font-combo').value, |
| 845 | getComputedStyle(document.querySelector('#docs-select-font-combo')).fontFamily]`, &got) |
| 846 | if got[0] != "serif" || got[1] != serif.Name || !strings.Contains(got[2], serif.PreviewCSSName()) { |
| 847 | t.Errorf("in a Liberation Serif run the font box is %v; want serif, %q, in %q", got, serif.Name, serif.PreviewCSSName()) |
| 848 | } |
| 849 | } |
| 850 | |
| 851 | // Review finding 7. Without JavaScript nothing is held and no web font |
| 852 | // is used: the text is in its system faces from the first paint and |
| 853 | // stays in them, so there is nothing to wait for and nothing to swap. |
| 854 | func TestFontWithoutJavaScriptTheSystemFacesAreFinal(t *testing.T) { |
| 855 | fr := newFontRig(t) |
| 856 | sqid := fr.document(t, "No script", "faces.bin") |
| 857 | fr.rig.Run(command(emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true})) |
| 858 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 859 | fr.rig.Run(fr.navigate("/d/"+sqid), chromedp.WaitReady(chromedp.CSS(`[docs-page]`))) |
| 860 | read := func() (vis, family string, loaded int) { |
| 861 | var out []any |
| 862 | fr.eval(t, `[getComputedStyle(document.querySelector('[docs-page]')).visibility, |
| 863 | getComputedStyle(document.querySelector('[docs-text] p')).fontFamily, |
| 864 | [...document.fonts].filter(f => f.family.includes('Docs ') && f.status !== 'unloaded').length]`, &out) |
| 865 | return out[0].(string), out[1].(string), int(out[2].(float64)) |
| 866 | } |
| 867 | vis, early, _ := read() |
| 868 | fr.rig.Run(chromedp.Sleep(3 * time.Second)) |
| 869 | _, late, loaded := read() |
| 870 | if vis != "visible" { |
| 871 | t.Errorf("without JavaScript the sheet is %s", vis) |
| 872 | } |
| 873 | if strings.Contains(early, "Docs ") || early != late { |
| 874 | t.Errorf("without JavaScript the text is set in %q, then %q: it must be the system faces throughout", early, late) |
| 875 | } |
| 876 | if loaded != 0 { |
| 877 | t.Errorf("%d of Docs' web fonts were put to use without JavaScript", loaded) |
| 878 | } |
| 879 | } |
| 880 | |
| 881 | // A pasted run's font-family stack lands in the family the native app |
| 882 | // would pick for it (fixtures/vectors/font-stacks.json): Georgia first is |
| 883 | // Caladea, not the Liberation Serif its later "Times New Roman" names; |
| 884 | // Calibri is Carlito, the default, so no mark; an unknown face is the |
| 885 | // default too. |
| 886 | func TestFontAPastedFontStackMapsLikeTheNativeApp(t *testing.T) { |
| 887 | fr := newFontRig(t) |
| 888 | sqid := fr.document(t, "Paste stacks", "simple.bin") |
| 889 | fr.open(t, sqid) |
| 890 | fr.editable(t) |
| 891 | var ok bool |
| 892 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 893 | const d = new DataTransfer(); |
| 894 | d.setData('text/html', '<p><span style="font-family: Georgia, "Times New Roman", serif">Georgia</span> ' + |
| 895 | '<span style="font-family: Calibri, Arial">Calibri</span> <span style="font-family: Wingdings">Unknown</span> ' + |
| 896 | '<span style="font-family: Menlo, "Courier New", monospace">Menlo</span></p>'); |
| 897 | return el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) })()`, &ok) |
| 898 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-caladea`)), chromedp.Sleep(300*time.Millisecond)) |
| 899 | var got map[string]string |
| 900 | fr.eval(t, `Object.fromEntries(['Georgia', 'Calibri', 'Unknown', 'Menlo'].map((w) => { |
| 901 | const walker = document.createTreeWalker(document.querySelector('[docs-text]'), NodeFilter.SHOW_TEXT); |
| 902 | for (let n = walker.nextNode(); n; n = walker.nextNode()) if (n.data.includes(w)) { |
| 903 | const span = n.parentElement.closest('[class^="docs-font-"]'); return [w, span ? span.className : ''] } |
| 904 | return [w, 'missing'] }))`, &got) |
| 905 | want := map[string]string{"Georgia": "docs-font-caladea", "Calibri": "", "Unknown": "", "Menlo": "docs-font-jetbrains"} |
| 906 | for w, cls := range want { |
| 907 | if got[w] != cls { |
| 908 | t.Errorf("%s pasted as %q, want %q", w, got[w], cls) |
| 909 | } |
| 910 | } |
| 911 | fr.noViolations(t) |
| 912 | } |
| 913 | |
| 914 | // An explicit font-family inside another font wins, by the same mapping: |
| 915 | // Calibri inside Inter is Carlito, the default, so no mark; an unknown |
| 916 | // face is the default too; Cambria is Caladea; a span with no |
| 917 | // font-family keeps the outer one (branch review 3, finding 2). |
| 918 | func TestFontANestedPastedFontWinsOverItsParent(t *testing.T) { |
| 919 | fr := newFontRig(t) |
| 920 | sqid := fr.document(t, "Nested", "simple.bin") |
| 921 | fr.open(t, sqid) |
| 922 | fr.editable(t) |
| 923 | var ok bool |
| 924 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 925 | const d = new DataTransfer(); |
| 926 | d.setData('text/html', '<p style="font-family: Inter">Outer <span style="font-family: Calibri">Inner1</span> ' + |
| 927 | '<span style="font-family: Wingdings">Inner2</span> <span style="font-family: Cambria">Inner3</span> <span>Inner4</span></p>'); |
| 928 | return el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })) })()`, &ok) |
| 929 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-caladea`)), chromedp.Sleep(300*time.Millisecond)) |
| 930 | var got map[string]string |
| 931 | fr.eval(t, `Object.fromEntries(['Outer', 'Inner1', 'Inner2', 'Inner3', 'Inner4'].map((w) => { |
| 932 | const walker = document.createTreeWalker(document.querySelector('[docs-text]'), NodeFilter.SHOW_TEXT); |
| 933 | for (let n = walker.nextNode(); n; n = walker.nextNode()) if (n.data.includes(w)) { |
| 934 | const span = n.parentElement.closest('[class^="docs-font-"]'); return [w, span ? span.className : ''] } |
| 935 | return [w, 'missing'] }))`, &got) |
| 936 | want := map[string]string{"Outer": "docs-font-inter", "Inner1": "", "Inner2": "", "Inner3": "docs-font-caladea", "Inner4": "docs-font-inter"} |
| 937 | for w, cls := range want { |
| 938 | if got[w] != cls { |
| 939 | t.Errorf("%s pasted as %q, want %q", w, got[w], cls) |
| 940 | } |
| 941 | } |
| 942 | |
| 943 | // And the shared nested cases (fixtures/vectors/font-stacks.json's |
| 944 | // "nested", which the native app tests too), each pasted through the |
| 945 | // real paste handler: [outer stack, inner stack or none, family]. |
| 946 | raw, err := os.ReadFile("../../fixtures/vectors/font-stacks.json") |
| 947 | if err != nil { |
| 948 | t.Fatal(err) |
| 949 | } |
| 950 | var vectors struct { |
| 951 | Nested [][3]*string `json:"nested"` |
| 952 | } |
| 953 | if err := json.Unmarshal(raw, &vectors); err != nil || len(vectors.Nested) == 0 { |
| 954 | t.Fatalf("no nested cases in font-stacks.json: %v", err) |
| 955 | } |
| 956 | for i, c := range vectors.Nested { |
| 957 | cases, _ := json.Marshal(c) |
| 958 | var cls string |
| 959 | fr.eval(t, fmt.Sprintf(`(async () => { |
| 960 | const [outer, inner] = %s, id = 'nested%d'; |
| 961 | const o = document.createElement('span'); o.style.fontFamily = outer; o.append('Out%d '); |
| 962 | const n = document.createElement('span'); if (inner !== null) n.style.fontFamily = inner; n.append(id); |
| 963 | o.append(n); |
| 964 | const el = document.querySelector('[docs-text]'); el.focus(); |
| 965 | const d = new DataTransfer(); d.setData('text/html', '<p>' + o.outerHTML + '</p>'); |
| 966 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); |
| 967 | for (let k = 0; k < 100; k++) { |
| 968 | const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); |
| 969 | for (let t = w.nextNode(); t; t = w.nextNode()) if (t.data.includes(id)) { |
| 970 | const span = t.parentElement.closest('[class^="docs-font-"]'); return span ? span.className : '' } |
| 971 | await new Promise((r) => setTimeout(r, 50)); |
| 972 | } |
| 973 | return 'missing' })()`, cases, i, i), &cls, true) |
| 974 | want := "" |
| 975 | if c[2] != nil && *c[2] != fonts.Default.Key { |
| 976 | want = "docs-font-" + *c[2] |
| 977 | } |
| 978 | if cls != want { |
| 979 | t.Errorf("nested case %d %s: the inner text pasted as %q, want %q", i, cases, cls, want) |
| 980 | } |
| 981 | } |
| 982 | } |
| 983 | |
| 984 | // The gate covers every face the document uses, whatever the document: |
| 985 | // random documents from every node and mark in the editor's schema |
| 986 | // (fixtures/generate-random-docs.mjs walks the schema itself, and fails |
| 987 | // unless every node type and mark appeared), each opened in Chromium |
| 988 | // twice: as the server rendered it (the editor bundle refused), and as |
| 989 | // the mounted editor renders it. Then a second time with every face but |
| 990 | // the default's late past the gate's deadline, so families are committed |
| 991 | // to their fallbacks. |
| 992 | // |
| 993 | // Each element and text node inside the text has a logical family, what |
| 994 | // the markup asks for (a font mark's class, code, or the default), and is |
| 995 | // checked against it, before any fallback (review on #86: comparing only |
| 996 | // what was drawn let a committed family hide wrong coverage): |
| 997 | // |
| 998 | // - the gate's families are exactly the DOM's logical families, and |
| 999 | // every face the DOM asks for (its family, weight and style, as |
| 1000 | // internal/fonts' Face resolves them) is one the gate waited for |
| 1001 | // (branch review 4: a bold Caveat run's wrapper is Caveat Regular); |
| 1002 | // - a family the gate committed is one it waited for, and is drawn only |
| 1003 | // in its declared fallback; any other is drawn in its own Docs face; |
| 1004 | // - and what is drawn, the Docs families computed, is exactly the |
| 1005 | // gate's families less those it committed. |
| 1006 | func TestFontTheGateCoversEveryFaceTheDocumentUses(t *testing.T) { |
| 1007 | dir := t.TempDir() |
| 1008 | seed := os.Getenv("DOCS_FONT_SEED") |
| 1009 | if seed == "" { |
| 1010 | seed = "20261025" |
| 1011 | } |
| 1012 | gen := exec.Command("node", "generate-random-docs.mjs", seed, "40", dir) |
| 1013 | gen.Dir = "../../fixtures" |
| 1014 | if out, err := gen.CombinedOutput(); err != nil { |
| 1015 | t.Fatalf("generate: %v %s", err, out) |
| 1016 | } |
| 1017 | // The generator writes at least 40, and more if 40 left a node or |
| 1018 | // mark of the schema out of the files as written. |
| 1019 | written, err := os.ReadDir(dir) |
| 1020 | if err != nil || len(written) < 40 { |
| 1021 | t.Fatalf("the generator wrote %d documents: %v", len(written), err) |
| 1022 | } |
| 1023 | for _, late := range []bool{false, true} { |
| 1024 | t.Run(map[bool]string{false: "in time", true: "late"}[late], func(t *testing.T) { |
| 1025 | fr := newFontRig(t) |
| 1026 | fr.rig.Allow(http.MethodGet, "/static/editor.", http.StatusNotFound) |
| 1027 | n := len(written) |
| 1028 | if late { |
| 1029 | // Every face but the default's, past the deadline: each |
| 1030 | // opening waits it out, so a sample. |
| 1031 | fr.match.Store("") |
| 1032 | fr.slow.Store(int64(3500 * time.Millisecond)) |
| 1033 | n = 6 |
| 1034 | } |
| 1035 | for i := 0; i < n; i++ { |
| 1036 | fr.checkGateCoverage(t, dir, fmt.Sprintf("%d.bin", i), late) |
| 1037 | } |
| 1038 | }) |
| 1039 | } |
| 1040 | } |
| 1041 | |
| 1042 | // logicalFamilyJS reports, for every element and text node in the text, |
| 1043 | // the family its markup asks for and what it is drawn in. |
| 1044 | const logicalFamilyJS = `(() => { |
| 1045 | const need = JSON.parse(document.querySelector('[docs-canvas]').getAttribute('data-docs-fonts-need')); |
| 1046 | const root = document.querySelector('[docs-text]'); |
| 1047 | const logical = (el) => { |
| 1048 | for (let e = el; e; e = e.parentElement) { |
| 1049 | const c = [...e.classList].find((c) => c.startsWith('docs-font-')); |
| 1050 | if (c) return c.slice('docs-font-'.length); |
| 1051 | if (e.tagName === 'CODE' || e.tagName === 'PRE') return 'code'; |
| 1052 | if (e === root) return 'default'; |
| 1053 | } |
| 1054 | return 'default'; |
| 1055 | }; |
| 1056 | const dom = []; |
| 1057 | const add = (el, where, text = false) => { |
| 1058 | const cs = getComputedStyle(el); |
| 1059 | const first = cs.fontFamily.split(',')[0].trim().replace(/^["']|["']$/g, ''); |
| 1060 | dom.push({ logical: logical(el), drawn: window.__docsFamily(cs.fontFamily) || '', first, weight: Number(cs.fontWeight), style: cs.fontStyle, where, text }); |
| 1061 | }; |
| 1062 | for (const el of [root, ...root.querySelectorAll('*')]) add(el, el.tagName + '.' + el.className); |
| 1063 | const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); |
| 1064 | for (let n = w.nextNode(); n; n = w.nextNode()) add(n.parentElement, 'text "' + n.data.slice(0, 20) + '"', true); |
| 1065 | return { need: need.filter((f) => f.key !== 'previews'), dom, fallback: document.documentElement.getAttribute('data-docs-fonts-fallback') || '' }; |
| 1066 | })()` |
| 1067 | |
| 1068 | func (fr *fontRig) checkGateCoverage(t *testing.T, dir, name string, late bool) { |
| 1069 | t.Helper() |
| 1070 | update, err := os.ReadFile(filepath.Join(dir, name)) |
| 1071 | if err != nil { |
| 1072 | t.Fatal(err) |
| 1073 | } |
| 1074 | ctx := context.Background() |
| 1075 | doc, err := fr.app.Store().Create(ctx, fr.app.TestPerson(t, "fonts@example.com"), "Random "+name) |
| 1076 | if err != nil { |
| 1077 | t.Fatal(err) |
| 1078 | } |
| 1079 | if _, err := fr.app.Store().ApplyUpdate(ctx, doc, fr.app.TestActorFor(t, doc), update); err != nil { |
| 1080 | t.Fatal(err) |
| 1081 | } |
| 1082 | for _, mounted := range []bool{false, true} { |
| 1083 | if mounted { |
| 1084 | fr.blocked.Store("") |
| 1085 | fr.open(t, doc.Sqid) |
| 1086 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text].ProseMirror`))) |
| 1087 | } else { |
| 1088 | fr.blocked.Store("/static/editor.") |
| 1089 | fr.open(t, doc.Sqid) |
| 1090 | } |
| 1091 | where := map[bool]string{false: "server-rendered", true: "editor"}[mounted] |
| 1092 | var got struct { |
| 1093 | Need []struct { |
| 1094 | Key, Family, Style string |
| 1095 | Weight int |
| 1096 | } `json:"need"` |
| 1097 | DOM []struct { |
| 1098 | Logical, Drawn, First, Style, Where string |
| 1099 | Weight int |
| 1100 | Text bool |
| 1101 | } `json:"dom"` |
| 1102 | Fallback string `json:"fallback"` |
| 1103 | } |
| 1104 | fr.eval(t, logicalFamilyJS, &got) |
| 1105 | needFamilies := map[string]bool{} |
| 1106 | needFaces := map[string]bool{} |
| 1107 | for _, f := range got.Need { |
| 1108 | needFamilies[f.Family] = true |
| 1109 | needFaces[fmt.Sprintf("%s %d %s", f.Family, f.Weight, f.Style)] = true |
| 1110 | } |
| 1111 | committed := map[string]bool{} |
| 1112 | for _, k := range strings.Fields(got.Fallback) { |
| 1113 | f, ok := fonts.ByKey(k) |
| 1114 | if !ok { |
| 1115 | t.Errorf("%s %s: committed %q, which is no family", name, where, k) |
| 1116 | continue |
| 1117 | } |
| 1118 | committed[f.CSSName()] = true |
| 1119 | if !needFamilies[f.CSSName()] { |
| 1120 | t.Errorf("%s %s: %s was committed to its fallback, but the gate never waited for it", name, where, f.CSSName()) |
| 1121 | } |
| 1122 | } |
| 1123 | logicalFamilies := map[string]bool{} |
| 1124 | drawnFamilies := map[string]bool{} |
| 1125 | for _, d := range got.DOM { |
| 1126 | fam := fonts.Default |
| 1127 | switch d.Logical { |
| 1128 | case "default": |
| 1129 | case "code": |
| 1130 | fam = fonts.Code |
| 1131 | default: |
| 1132 | f, ok := fonts.ByKey(d.Logical) |
| 1133 | if !ok { |
| 1134 | t.Errorf("%s %s: %s asks for %q, which is no family", name, where, d.Where, d.Logical) |
| 1135 | continue |
| 1136 | } |
| 1137 | fam = f |
| 1138 | } |
| 1139 | logicalFamilies[fam.CSSName()] = true |
| 1140 | face := fam.Face(d.Weight >= 600, d.Style == "italic") |
| 1141 | id := fmt.Sprintf("%s %d %s", fam.CSSName(), face.Style.Weight(), face.Style.CSSStyle()) |
| 1142 | if !needFaces[id] { |
| 1143 | t.Errorf("%s %s: %s asks for %s, which the gate did not wait for", name, where, d.Where, id) |
| 1144 | } |
| 1145 | if d.Drawn != "" { |
| 1146 | drawnFamilies[d.Drawn] = true |
| 1147 | } |
| 1148 | // What it is drawn in, for text, and for any element drawn in |
| 1149 | // a Docs face. (A wrapper with no text of its own may be in a |
| 1150 | // system face, a <pre>'s monospace: always there, never late.) |
| 1151 | if !d.Text && d.Drawn == "" { |
| 1152 | continue |
| 1153 | } |
| 1154 | if committed[fam.CSSName()] { |
| 1155 | if d.Drawn != "" || d.First != fam.Fallback[0] { |
| 1156 | t.Errorf("%s %s: %s is in committed %s, but is drawn in %q (first %q), not its fallback %q", name, where, d.Where, fam.CSSName(), d.Drawn, d.First, fam.Fallback[0]) |
| 1157 | } |
| 1158 | } else if d.Drawn != fam.CSSName() { |
| 1159 | t.Errorf("%s %s: %s asks for %s and is drawn in %q", name, where, d.Where, fam.CSSName(), d.Drawn) |
| 1160 | } |
| 1161 | } |
| 1162 | if fmt.Sprint(sortedSet(needFamilies)) != fmt.Sprint(sortedSet(logicalFamilies)) { |
| 1163 | t.Errorf("%s %s: the gate waited for %v, the DOM asks for %v", name, where, sortedSet(needFamilies), sortedSet(logicalFamilies)) |
| 1164 | } |
| 1165 | effective := map[string]bool{} |
| 1166 | for f := range needFamilies { |
| 1167 | if !committed[f] { |
| 1168 | effective[f] = true |
| 1169 | } |
| 1170 | } |
| 1171 | if fmt.Sprint(sortedSet(effective)) != fmt.Sprint(sortedSet(drawnFamilies)) { |
| 1172 | t.Errorf("%s %s: the gate's families less those committed are %v, the DOM draws %v", name, where, sortedSet(effective), sortedSet(drawnFamilies)) |
| 1173 | } |
| 1174 | if late && len(committed) == 0 && len(needFamilies) > 1 { |
| 1175 | t.Errorf("%s %s: every face but the default's was late, and nothing was committed", name, where) |
| 1176 | } |
| 1177 | } |
| 1178 | } |
| 1179 | |
| 1180 | func sortedSet(m map[string]bool) []string { |
| 1181 | out := make([]string, 0, len(m)) |
| 1182 | for k := range m { |
| 1183 | out = append(out, k) |
| 1184 | } |
| 1185 | sort.Strings(out) |
| 1186 | return out |
| 1187 | } |
| 1188 | |
| 1189 | // Every way content reaches the document goes through the one font gate |
| 1190 | // (branch review 5): each row brings in a family nobody on the page has |
| 1191 | // loaded, held slow, and no frame may show text in a face that has not |
| 1192 | // loaded. One table, so a path without a row is easy to see missing. |
| 1193 | func TestFontEveryInputPathWaitsForItsFamily(t *testing.T) { |
| 1194 | pasteHTML := func(html string) string { |
| 1195 | return `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 1196 | const d = new DataTransfer(); d.setData('text/html', ` + "`" + html + "`" + `); |
| 1197 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()` |
| 1198 | } |
| 1199 | caretAtEnd := `(() => { const p = document.querySelector('[docs-text] p:last-child'); const r = document.createRange(); |
| 1200 | r.selectNodeContents(p); r.collapse(false); getSelection().removeAllRanges(); getSelection().addRange(r); |
| 1201 | document.querySelector('[docs-text]').focus(); return true })()` |
| 1202 | rows := []struct { |
| 1203 | name, slow string |
| 1204 | steps []chromedp.Action[chromedp.Void] |
| 1205 | wait string |
| 1206 | post string // a collaborator's vector instead of browser steps |
| 1207 | }{ |
| 1208 | {name: "paste a code block", slow: "LiberationMono-", wait: `[docs-text] pre`}, |
| 1209 | {name: "paste a font", slow: "Caveat-", wait: `[docs-text] .docs-font-caveat`}, |
| 1210 | {name: "drop a font", slow: "Caveat-", wait: `[docs-text] .docs-font-caveat`}, |
| 1211 | {name: "toggle code and type", slow: "LiberationMono-", wait: `text:typed as code`}, |
| 1212 | {name: "type a list after toggling code", slow: "LiberationMono-", wait: `[docs-text] li`}, |
| 1213 | {name: "paste, undo, redo", slow: "Caveat-", wait: `[docs-text] .docs-font-caveat`}, |
| 1214 | {name: "a collaborator's code block", slow: "LiberationMono-", wait: `[docs-text] pre`, post: "remote-codeblock.bin"}, |
| 1215 | } |
| 1216 | for _, row := range rows { |
| 1217 | t.Run(row.name, func(t *testing.T) { |
| 1218 | fr := newFontRig(t) |
| 1219 | sqid := fr.document(t, "Paths", "simple.bin") |
| 1220 | fr.match.Store(row.slow) |
| 1221 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 1222 | fr.open(t, sqid) |
| 1223 | fr.editable(t) |
| 1224 | var ok bool |
| 1225 | switch row.name { |
| 1226 | case "paste a code block": |
| 1227 | // At the start of a paragraph, where a pasted <pre> becomes a |
| 1228 | // code block (at the end of one its text runs on inline). |
| 1229 | fr.eval(t, `(() => { const p = document.querySelector('[docs-text] p'); const r = document.createRange(); |
| 1230 | r.setStart(p.firstChild, 0); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); |
| 1231 | document.querySelector('[docs-text]').focus(); return true })()`, &ok) |
| 1232 | fr.eval(t, pasteHTML(`<pre>const answer = 42;\nsecond line of code</pre>`), &ok) |
| 1233 | case "paste a font", "paste, undo, redo": |
| 1234 | fr.eval(t, caretAtEnd, &ok) |
| 1235 | fr.eval(t, pasteHTML(`<p><span style="font-family: Caveat">Pasted in Caveat</span></p>`), &ok) |
| 1236 | case "drop a font": |
| 1237 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 1238 | const d = new DataTransfer(); d.setData('text/html', '<p style="font-family: Caveat">Dropped in Caveat</p>'); |
| 1239 | const r = document.querySelector('[docs-text] p').getBoundingClientRect(); |
| 1240 | el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.left + 30, clientY: r.top + 8 })); |
| 1241 | return true })()`, &ok) |
| 1242 | case "toggle code and type": |
| 1243 | fr.eval(t, caretAtEnd, &ok) |
| 1244 | // The toggle waits for code's face with the editor inert; |
| 1245 | // typing goes in once it is back. |
| 1246 | fr.rig.Run(chromedp.Click(chromedp.CSS(`[docs-toolbar] [data-docs-command="code"]`))) |
| 1247 | fr.settled(t) |
| 1248 | fr.rig.Run(chromedp.KeyEvent(" typed as code")) |
| 1249 | case "type a list after toggling code": |
| 1250 | fr.eval(t, caretAtEnd, &ok) |
| 1251 | fr.rig.Run(chromedp.KeyEvent("\r"), chromedp.Click(chromedp.CSS(`[docs-toolbar] [data-docs-command="code"]`))) |
| 1252 | fr.settled(t) |
| 1253 | fr.rig.Run(chromedp.KeyEvent("- a listed code item")) |
| 1254 | } |
| 1255 | if row.post != "" { |
| 1256 | fr.post(t, sqid, row.post) |
| 1257 | } |
| 1258 | if text, ok := strings.CutPrefix(row.wait, "text:"); ok { |
| 1259 | fr.rig.Run(chromedp.Poll[chromedp.Void](`document.querySelector('[docs-text]').textContent.includes(` + strconv.Quote(text) + `)`)) |
| 1260 | } else { |
| 1261 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(row.wait))) |
| 1262 | } |
| 1263 | // Long enough for the held family to arrive and be applied. |
| 1264 | fr.rig.Run(chromedp.Sleep(2500 * time.Millisecond)) |
| 1265 | if row.name == "paste, undo, redo" { |
| 1266 | fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(300*time.Millisecond), |
| 1267 | chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(300*time.Millisecond)) |
| 1268 | } |
| 1269 | p := fr.noViolations(t) |
| 1270 | for run, faces := range p.Seen { |
| 1271 | for f := range faces { |
| 1272 | if !strings.Contains(f, "Docs ") && !fr.committedAny(t) { |
| 1273 | t.Errorf("%q was shown in a fallback (%s) though nothing was committed", run, f) |
| 1274 | } |
| 1275 | } |
| 1276 | } |
| 1277 | }) |
| 1278 | } |
| 1279 | } |
| 1280 | |
| 1281 | func (fr *fontRig) committedAny(t *testing.T) bool { |
| 1282 | t.Helper() |
| 1283 | var fb string |
| 1284 | fr.eval(t, `document.documentElement.getAttribute('data-docs-fonts-fallback') || ''`, &fb) |
| 1285 | return fb != "" |
| 1286 | } |
| 1287 | |
| 1288 | // waitLog records, on every change, whether the editor and the bars are |
| 1289 | // inert, what the font status says and the document's text, so a check |
| 1290 | // can see the wait from the start to the end. |
| 1291 | const waitLogJS = `(() => { |
| 1292 | window.__waitLog = []; |
| 1293 | const text = document.querySelector('[docs-text]'); |
| 1294 | const status = document.querySelector('[docs-fonts-status]'); |
| 1295 | const rec = () => window.__waitLog.push({ |
| 1296 | ms: Math.round(performance.now()), |
| 1297 | inert: !!text.inert, |
| 1298 | bar: [...document.querySelectorAll('[docs-toolbar], [estilo-menubar], [docs-history], [data-estilo-toggle]')].every((el) => el.inert) && |
| 1299 | document.querySelectorAll('[docs-toolbar], [estilo-menubar], [docs-history], [data-estilo-toggle]').length === 5, |
| 1300 | state: (status && status.getAttribute('data-state')) || '', |
| 1301 | shown: !!status && getComputedStyle(status).opacity === '1', |
| 1302 | text: text.innerText.replace(/\n+/g, '|'), |
| 1303 | }); |
| 1304 | rec(); |
| 1305 | new MutationObserver(rec).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['inert', 'data-state'] }); |
| 1306 | return true; |
| 1307 | })()` |
| 1308 | |
| 1309 | type waitEntry struct { |
| 1310 | Ms int `json:"ms"` |
| 1311 | Inert bool `json:"inert"` |
| 1312 | Bar bool `json:"bar"` |
| 1313 | State string `json:"state"` |
| 1314 | Shown bool `json:"shown"` |
| 1315 | Text string `json:"text"` |
| 1316 | } |
| 1317 | |
| 1318 | func (fr *fontRig) waitLog(t *testing.T) []waitEntry { |
| 1319 | t.Helper() |
| 1320 | var raw string |
| 1321 | fr.eval(t, `JSON.stringify(window.__waitLog)`, &raw) |
| 1322 | var log []waitEntry |
| 1323 | if err := json.Unmarshal([]byte(raw), &log); err != nil { |
| 1324 | t.Fatalf("wait log: %v", err) |
| 1325 | } |
| 1326 | return log |
| 1327 | } |
| 1328 | |
| 1329 | // settled waits until no font wait is in progress. |
| 1330 | func (fr *fontRig) settled(t *testing.T) { |
| 1331 | t.Helper() |
| 1332 | fr.rig.Run(chromedp.Poll[chromedp.Void](`(() => { const s = document.querySelector('[docs-fonts-status]'); const d = document.querySelector('[docs-text]'); |
| 1333 | return !d.inert && d.getAttribute('contenteditable') === 'true' && !['loading', 'refused'].includes((s && s.getAttribute('data-state')) || '') })()`, |
| 1334 | chromedp.WithPollingTimeout(15*time.Second))) |
| 1335 | } |
| 1336 | |
| 1337 | // inWait reports whether the editor and the chrome that drives it are |
| 1338 | // inert (the toolbar, the menu bar, both undo/redo pairs and the bar's |
| 1339 | // Format toggle: spec I2) and the |
| 1340 | // status strip visibly says a font is loading, right now. |
| 1341 | func (fr *fontRig) inWait(t *testing.T) bool { |
| 1342 | t.Helper() |
| 1343 | var on bool |
| 1344 | fr.eval(t, `(() => { const s = document.querySelector('[docs-fonts-status]'); |
| 1345 | const chrome = document.querySelectorAll('[docs-toolbar], [estilo-menubar], [docs-history], [data-estilo-toggle]'); |
| 1346 | return !!document.querySelector('[docs-text]').inert && chrome.length === 5 && [...chrome].every((el) => el.inert) && |
| 1347 | !!s && ['loading', 'refused'].includes(s.getAttribute('data-state')) && |
| 1348 | getComputedStyle(s).opacity === '1' && s.querySelector('[role="status"]').textContent.trim() !== '' })()`, &on) |
| 1349 | return on |
| 1350 | } |
| 1351 | |
| 1352 | func selectInJS(which string, from, to int) string { |
| 1353 | return fmt.Sprintf(`(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 1354 | const p = el.querySelector(%q); const n = document.createTreeWalker(p, NodeFilter.SHOW_TEXT).nextNode(); |
| 1355 | const r = document.createRange(); r.setStart(n, %d < 0 ? n.length : %d); r.setEnd(n, %d < 0 ? n.length : %d); |
| 1356 | getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, which, from, from, to, to) |
| 1357 | } |
| 1358 | |
| 1359 | func pasteJS(text, font string) string { |
| 1360 | return fmt.Sprintf(`(() => { const el = document.querySelector('[docs-text]'); |
| 1361 | const d = new DataTransfer(); d.setData('text/html', '<span style="font-family: %s">%s</span>'); |
| 1362 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`, font, text) |
| 1363 | } |
| 1364 | |
| 1365 | const docTextJS = `document.querySelector('[docs-text]').innerText.replace(/\n+/g, '|')` |
| 1366 | |
| 1367 | // A wait for a font is a short modal (branch review 7). The action that |
| 1368 | // needs the font is cancelled before it changes anything; the editor, |
| 1369 | // the formatting bar and the menu bar go inert at once and the status |
| 1370 | // over the bar says a font is loading; what is done in the editor |
| 1371 | // meanwhile goes nowhere, and visibly so; once the font is in, the action |
| 1372 | // is performed once. Nothing is queued or replayed: review 7 showed a |
| 1373 | // replayed keystroke is not the keystroke (Backspace, arrows, an IME |
| 1374 | // commit), a second queued action could release the editor early and be |
| 1375 | // dropped, and a document-wide trap took another control's typing. |
| 1376 | // |
| 1377 | // Each row pastes "PASTE" in Caveat at the start of simple.bin's first |
| 1378 | // paragraph, with Caveat two seconds away, then does something during |
| 1379 | // the wait. |
| 1380 | func TestFontAWaitIsAShortModal(t *testing.T) { |
| 1381 | const plain = "First paragraph.|Second paragraph." |
| 1382 | meta := chromedp.KeyModifiers(chromedp.ModifierMeta) |
| 1383 | keys := []chromedp.Action[chromedp.Void]{chromedp.KeyEvent("ab"), chromedp.KeyEvent(kb.Backspace), chromedp.KeyEvent(kb.ArrowLeft), chromedp.KeyEvent("X")} |
| 1384 | rows := []struct { |
| 1385 | name string |
| 1386 | slow time.Duration |
| 1387 | blocked bool |
| 1388 | during func(t *testing.T, fr *fontRig) |
| 1389 | want string // the document at the end |
| 1390 | status string // what the status says at the end ("" once cleared) |
| 1391 | after func(t *testing.T, fr *fontRig) |
| 1392 | }{ |
| 1393 | {name: "keys during the wait go nowhere; after it they edit as usual", during: func(t *testing.T, fr *fontRig) { |
| 1394 | fr.rig.Run(keys...) |
| 1395 | fr.rig.Run(chromedp.KeyEvent("z", meta)) |
| 1396 | }, want: "PASTE" + plain, after: func(t *testing.T, fr *fontRig) { |
| 1397 | // Focus is back in the document, after the paste, and the same |
| 1398 | // keys now do what they always do. |
| 1399 | fr.rig.Run(keys...) |
| 1400 | fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
| 1401 | var got string |
| 1402 | fr.eval(t, docTextJS, &got) |
| 1403 | if want := "PASTEXa" + plain; got != want { |
| 1404 | t.Errorf("after the wait the keys left %q, want %q", got, want) |
| 1405 | } |
| 1406 | }}, |
| 1407 | {name: "an IME commit during the wait goes nowhere", during: func(t *testing.T, fr *fontRig) { |
| 1408 | fr.rig.Run(command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほん", SelectionStart: 3, SelectionEnd: 3}), chromedp.Sleep(100*time.Millisecond), command(input.InsertText, input.InsertTextParams{Text: "日本"})) |
| 1409 | }, want: "PASTE" + plain}, |
| 1410 | {name: "the title keeps what is typed into it", during: func(t *testing.T, fr *fontRig) { |
| 1411 | var ok bool |
| 1412 | fr.eval(t, `(() => { const i = document.querySelector('input[aria-label="Document title"]'); i.focus(); i.setSelectionRange(i.value.length, i.value.length); return document.activeElement === i })()`, &ok) |
| 1413 | if !ok { |
| 1414 | t.Fatal("could not focus the title") |
| 1415 | } |
| 1416 | fr.rig.Run(chromedp.KeyEvent("TITLE")) |
| 1417 | }, want: "PASTE" + plain, after: func(t *testing.T, fr *fontRig) { |
| 1418 | var title string |
| 1419 | var focused bool |
| 1420 | fr.eval(t, `document.querySelector('input[aria-label="Document title"]').value`, &title) |
| 1421 | fr.eval(t, `document.activeElement === document.querySelector('input[aria-label="Document title"]')`, &focused) |
| 1422 | if !strings.HasSuffix(title, "TITLE") { |
| 1423 | t.Errorf("the title is %q; what was typed into it went elsewhere", title) |
| 1424 | } |
| 1425 | if !focused { |
| 1426 | t.Error("the end of the wait took focus away from the title") |
| 1427 | } |
| 1428 | }}, |
| 1429 | {name: "a second action during the wait is refused, and said", during: func(t *testing.T, fr *fontRig) { |
| 1430 | var ok bool |
| 1431 | fr.eval(t, pasteJS("SECOND", "Inter"), &ok) |
| 1432 | fr.rig.Run(chromedp.KeyEvent("typed")) |
| 1433 | }, want: "PASTE" + plain, after: func(t *testing.T, fr *fontRig) { |
| 1434 | refused := false |
| 1435 | for _, e := range fr.waitLog(t) { |
| 1436 | refused = refused || (e.State == "refused" && e.Shown) |
| 1437 | } |
| 1438 | if !refused { |
| 1439 | t.Error("the refused action was never said to be refused") |
| 1440 | } |
| 1441 | }}, |
| 1442 | {name: "a collaborator's edit waits for the wait, and both land", during: func(t *testing.T, fr *fontRig) { |
| 1443 | fr.post(t, fr.sqid, "remote-bold.bin") |
| 1444 | fr.rig.Run(chromedp.Sleep(500 * time.Millisecond)) |
| 1445 | }, want: "PASTE" + plain + "|A collaborator's bold"}, |
| 1446 | {name: "a font that cannot load drops the action and says so", blocked: true, want: plain, status: "unavailable"}, |
| 1447 | {name: "a font past its deadline drops the action and says so", slow: 5 * time.Second, want: plain, status: "unavailable"}, |
| 1448 | } |
| 1449 | for _, row := range rows { |
| 1450 | t.Run(row.name, func(t *testing.T) { |
| 1451 | fr := newFontRig(t) |
| 1452 | fr.sqid = fr.document(t, "Modal", "simple.bin") |
| 1453 | if row.blocked { |
| 1454 | fr.blocked.Store("Caveat-") |
| 1455 | } else { |
| 1456 | fr.match.Store("Caveat-") |
| 1457 | slow := row.slow |
| 1458 | if slow == 0 { |
| 1459 | slow = 2 * time.Second |
| 1460 | } |
| 1461 | fr.slow.Store(int64(slow)) |
| 1462 | } |
| 1463 | fr.open(t, fr.sqid) |
| 1464 | fr.editable(t) |
| 1465 | var ok bool |
| 1466 | fr.eval(t, waitLogJS, &ok) |
| 1467 | fr.eval(t, selectInJS("p", 0, 0), &ok) |
| 1468 | fr.eval(t, pasteJS("PASTE", "Caveat"), &ok) |
| 1469 | // At once: the editor and both bars inert, and the status says so. |
| 1470 | if !fr.inWait(t) { |
| 1471 | t.Error("the paste did not start a visible wait: the editor, the bars or the status") |
| 1472 | } |
| 1473 | if row.during != nil { |
| 1474 | row.during(t, fr) |
| 1475 | } |
| 1476 | var during string |
| 1477 | fr.eval(t, docTextJS, &during) |
| 1478 | if fr.inWait(t) && during != plain { |
| 1479 | t.Errorf("the document changed during the wait: %q", during) |
| 1480 | } |
| 1481 | fr.settled(t) |
| 1482 | fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
| 1483 | var got, state string |
| 1484 | fr.eval(t, docTextJS, &got) |
| 1485 | fr.eval(t, `(document.querySelector('[docs-fonts-status]') || { getAttribute: () => 'none' }).getAttribute('data-state') || ''`, &state) |
| 1486 | if got != row.want { |
| 1487 | t.Errorf("the document ends %q, want %q", got, row.want) |
| 1488 | } |
| 1489 | if state != row.status { |
| 1490 | t.Errorf("the status ends %q, want %q", state, row.status) |
| 1491 | } |
| 1492 | // The editor stayed inert, the bars too, until the action had |
| 1493 | // been performed (or dropped): one wait, never released early. |
| 1494 | log := fr.waitLog(t) |
| 1495 | started := false |
| 1496 | for i, e := range log { |
| 1497 | if e.Inert { |
| 1498 | started = true |
| 1499 | if !e.Bar { |
| 1500 | t.Errorf("at %dms the editor was inert but the bars were not", e.Ms) |
| 1501 | } |
| 1502 | if e.Text != plain { |
| 1503 | t.Errorf("at %dms, during the wait, the document was %q", e.Ms, e.Text) |
| 1504 | } |
| 1505 | continue |
| 1506 | } |
| 1507 | if started && i > 0 && log[i-1].Inert && row.status == "" && !strings.HasPrefix(e.Text, "PASTE") { |
| 1508 | t.Errorf("at %dms the editor came back before the paste was performed: %q", e.Ms, e.Text) |
| 1509 | } |
| 1510 | } |
| 1511 | if !started { |
| 1512 | t.Error("the editor was never inert") |
| 1513 | } |
| 1514 | if row.status == "unavailable" { |
| 1515 | var focused bool |
| 1516 | fr.eval(t, `document.activeElement === document.querySelector('[docs-text]')`, &focused) |
| 1517 | if !focused { |
| 1518 | t.Error("after a dropped action the caret is not back in the document") |
| 1519 | } |
| 1520 | } |
| 1521 | if row.after != nil { |
| 1522 | row.after(t, fr) |
| 1523 | } |
| 1524 | fr.noViolations(t) |
| 1525 | }) |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | // Undo groups as it would have without the wait: text typed before a |
| 1530 | // held paste is one step, the paste another. |
| 1531 | func TestFontUndoAfterABlockedPasteUndoesThePaste(t *testing.T) { |
| 1532 | fr := newFontRig(t) |
| 1533 | fr.sqid = fr.document(t, "Undo", "simple.bin") |
| 1534 | fr.open(t, fr.sqid) |
| 1535 | fr.editable(t) |
| 1536 | var ok bool |
| 1537 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); el.focus(); |
| 1538 | const n = document.createTreeWalker(el.querySelector('p'), NodeFilter.SHOW_TEXT).nextNode(); const r = document.createRange(); |
| 1539 | r.setStart(n, 0); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, &ok) |
| 1540 | fr.rig.Run(chromedp.KeyEvent("abc"), chromedp.Sleep(800*time.Millisecond)) |
| 1541 | fr.match.Store("Caveat-") |
| 1542 | fr.slow.Store(int64(1500 * time.Millisecond)) |
| 1543 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); const d = new DataTransfer(); |
| 1544 | d.setData('text/html', '<span style="font-family: Caveat">PASTE</span>'); |
| 1545 | el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: d, bubbles: true, cancelable: true })); return true })()`, &ok) |
| 1546 | fr.rig.Run(chromedp.WaitVisible(chromedp.CSS(`[docs-text] .docs-font-caveat`)), chromedp.Sleep(800*time.Millisecond)) |
| 1547 | text := func() string { |
| 1548 | var s string |
| 1549 | fr.eval(t, `document.querySelector('[docs-text] p').textContent`, &s) |
| 1550 | return s |
| 1551 | } |
| 1552 | if got := text(); got != "abcPASTEFirst paragraph." { |
| 1553 | t.Fatalf("after the paste the paragraph is %q", got) |
| 1554 | } |
| 1555 | fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta)), chromedp.Sleep(400*time.Millisecond)) |
| 1556 | if got := text(); got != "abcFirst paragraph." { |
| 1557 | t.Errorf("undo left %q; it should take the paste back and only the paste", got) |
| 1558 | } |
| 1559 | fr.rig.Run(chromedp.KeyEvent("z", chromedp.KeyModifiers(chromedp.ModifierMeta|chromedp.ModifierShift)), chromedp.Sleep(400*time.Millisecond)) |
| 1560 | if got := text(); got != "abcPASTEFirst paragraph." { |
| 1561 | t.Errorf("redo left %q", got) |
| 1562 | } |
| 1563 | fr.noViolations(t) |
| 1564 | } |
| 1565 | |
| 1566 | // An IME composition in a family already loaded never blocks: the |
| 1567 | // editor stays editable throughout, and the committed text lands with |
| 1568 | // no preedit left behind. |
| 1569 | func TestFontACompositionInALoadedFamilyNeverBlocks(t *testing.T) { |
| 1570 | fr := newFontRig(t) |
| 1571 | fr.sqid = fr.document(t, "IME", "simple.bin") |
| 1572 | fr.open(t, fr.sqid) |
| 1573 | fr.editable(t) |
| 1574 | var ok bool |
| 1575 | fr.eval(t, `(() => { window.__lostEditable = false; |
| 1576 | const text = document.querySelector('[docs-text]'); |
| 1577 | new MutationObserver(() => { if (text.getAttribute('contenteditable') !== 'true' || text.inert) window.__lostEditable = true }) |
| 1578 | .observe(text, { attributes: true }); |
| 1579 | const el = document.querySelector('[docs-text]'); el.focus(); |
| 1580 | const n = document.createTreeWalker(el.querySelector('p'), NodeFilter.SHOW_TEXT).nextNode(); const r = document.createRange(); |
| 1581 | r.setStart(n, 0); r.collapse(true); getSelection().removeAllRanges(); getSelection().addRange(r); return true })()`, &ok) |
| 1582 | fr.rig.Run(command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほん", SelectionStart: 3, SelectionEnd: 3}), chromedp.Sleep(200*time.Millisecond), command(input.InsertText, input.InsertTextParams{Text: "日本"}), chromedp.Sleep(500*time.Millisecond)) |
| 1583 | var text string |
| 1584 | var lost bool |
| 1585 | fr.eval(t, `document.querySelector('[docs-text] p').textContent`, &text) |
| 1586 | fr.eval(t, `window.__lostEditable`, &lost) |
| 1587 | if text != "日本First paragraph." { |
| 1588 | t.Errorf("the composition left %q", text) |
| 1589 | } |
| 1590 | if lost { |
| 1591 | t.Error("the editor stopped being editable during a composition in a loaded family") |
| 1592 | } |
| 1593 | } |
| 1594 | |
| 1595 | // noteOverTextJS finds whichever font note is visible (the status strip, |
| 1596 | // or the notes it replaced, so the check means the same on any of them) |
| 1597 | // and reports everything it must not cover: the document's text runs and |
| 1598 | // the editor itself, any control a person can reach, and whatever has |
| 1599 | // focus. And whether its own text is all there: inside the viewport, and |
| 1600 | // not clipped by the strip. |
| 1601 | const noteOverTextJS = `(() => { |
| 1602 | const sel = '[docs-fonts-status][data-state], [docs-fonts-busy]:not([hidden]), [docs-fonts-note]:not([hidden]), [docs-fonts-unavailable]:not([hidden])'; |
| 1603 | const note = [...document.querySelectorAll(sel)].find((e) => { const cs = getComputedStyle(e); return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0'; }); |
| 1604 | const page = document.querySelector('[docs-page]').getBoundingClientRect(); |
| 1605 | if (!note) return JSON.stringify({ found: false, pageTop: page.top, pageLeft: page.left }); |
| 1606 | const n = note.getBoundingClientRect(); |
| 1607 | const over = (q) => q.width > 0 && q.height > 0 && q.right > n.left && q.left < n.right && q.bottom > n.top && q.top < n.bottom; |
| 1608 | const hits = []; |
| 1609 | const w = document.createTreeWalker(document.querySelector('[docs-text]'), NodeFilter.SHOW_TEXT); |
| 1610 | for (let t = w.nextNode(); t; t = w.nextNode()) { |
| 1611 | if (!t.data.trim()) continue; |
| 1612 | const r = document.createRange(); r.selectNodeContents(t); |
| 1613 | if ([...r.getClientRects()].some(over)) hits.push(t.data.slice(0, 24)); |
| 1614 | } |
| 1615 | const controls = []; |
| 1616 | const focusable = 'a[href], button, input, select, textarea, summary, [tabindex], [contenteditable="true"], [docs-text]'; |
| 1617 | for (const el of document.querySelectorAll(focusable)) { |
| 1618 | if (note.contains(el) || el.closest('[inert]') || el.disabled || el.closest('[hidden]')) continue; |
| 1619 | // A closed menu's items are not there to reach. |
| 1620 | const d = el.closest('details'); |
| 1621 | if (d && !d.open && !el.closest('summary')) continue; |
| 1622 | if (el.checkVisibility && !el.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue; |
| 1623 | if (over(el.getBoundingClientRect())) controls.push(el.outerHTML.slice(0, 60)); |
| 1624 | } |
| 1625 | const a = document.activeElement; |
| 1626 | const focusCovered = !!a && a !== document.body && !note.contains(a) && over(a.getBoundingClientRect()); |
| 1627 | const text = note.querySelector('[docs-fonts-status-text]') || note; |
| 1628 | const tr = text.getBoundingClientRect(); |
| 1629 | const clipped = text.scrollHeight > text.clientHeight + 1 || tr.top < n.top - 1 || tr.bottom > n.bottom + 1 || |
| 1630 | n.left < -1 || n.right > innerWidth + 1 || n.bottom > innerHeight + 1 || text.textContent.trim() === ''; |
| 1631 | const dismiss = note.querySelector('[docs-fonts-status-dismiss]'); |
| 1632 | const dr = dismiss && dismiss.getBoundingClientRect(); |
| 1633 | const dismissable = !!dr && dr.width >= 24 && dr.height >= 24 && dr.left >= 0 && dr.right <= innerWidth && getComputedStyle(dismiss).display !== 'none'; |
| 1634 | return JSON.stringify({ found: true, hits, controls, focusCovered, focus: a ? a.tagName + (a.id ? '#' + a.id : '') : '', clipped, dismissable, |
| 1635 | note: [n.left, n.top, n.right, n.bottom].map(Math.round), pageTop: page.top, pageLeft: page.left }); |
| 1636 | })()` |
| 1637 | |
| 1638 | type noteOverText struct { |
| 1639 | Found bool `json:"found"` |
| 1640 | Hits []string `json:"hits"` |
| 1641 | Controls []string `json:"controls"` |
| 1642 | FocusCovered bool `json:"focusCovered"` |
| 1643 | Focus string `json:"focus"` |
| 1644 | Clipped bool `json:"clipped"` |
| 1645 | Dismissable bool `json:"dismissable"` |
| 1646 | Note []int `json:"note"` |
| 1647 | PageTop float64 `json:"pageTop"` |
| 1648 | PageLeft float64 `json:"pageLeft"` |
| 1649 | } |
| 1650 | |
| 1651 | func (fr *fontRig) noteOverText(t *testing.T) noteOverText { |
| 1652 | t.Helper() |
| 1653 | var raw string |
| 1654 | fr.eval(t, noteOverTextJS, &raw) |
| 1655 | var got noteOverText |
| 1656 | if err := json.Unmarshal([]byte(raw), &got); err != nil { |
| 1657 | t.Fatal(err) |
| 1658 | } |
| 1659 | return got |
| 1660 | } |
| 1661 | |
| 1662 | // What the page says about its fonts covers nothing a person reads or |
| 1663 | // uses, is all there, and saying it moves nothing (branch reviews 7 and |
| 1664 | // 8): not the document's text (at 390×640 the floating notes covered |
| 1665 | // lines), not a control or the focus (over the formatting bar, the strip |
| 1666 | // covered the Style box a person tabbed to), and not clipped (at 320 px |
| 1667 | // the substitutes note lost its first and last lines). Each note is |
| 1668 | // brought about for real: a paste waiting for its font, a second action |
| 1669 | // refused during it, a font that cannot load, and a page shown with a |
| 1670 | // substitute. |
| 1671 | func TestFontTheStatusNeverCoversText(t *testing.T) { |
| 1672 | for _, size := range []struct{ w, h int64 }{{320, 900}, {390, 640}, {1280, 1000}} { |
| 1673 | for _, state := range []string{"loading", "refused", "unavailable", "substitute"} { |
| 1674 | t.Run(fmt.Sprintf("%dx%d %s", size.w, size.h, state), func(t *testing.T) { |
| 1675 | fr := newFontRig(t) |
| 1676 | fr.rig.Run(command(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideParams{Width: int64(size.w), Height: int64(size.h), DeviceScaleFactor: 1})) |
| 1677 | vector := "long.bin" |
| 1678 | switch state { |
| 1679 | case "loading", "refused": |
| 1680 | fr.match.Store("Caveat-") |
| 1681 | fr.slow.Store(int64(3 * time.Second)) |
| 1682 | case "unavailable": |
| 1683 | fr.blocked.Store("Caveat-") |
| 1684 | case "substitute": |
| 1685 | vector = "faces.bin" |
| 1686 | fr.match.Store("Carlito-") |
| 1687 | fr.slow.Store(int64(4 * time.Second)) |
| 1688 | } |
| 1689 | sqid := fr.document(t, "Status", vector) |
| 1690 | fr.open(t, sqid) |
| 1691 | before := fr.noteOverText(t) |
| 1692 | if state != "substitute" { |
| 1693 | fr.editable(t) |
| 1694 | before = fr.noteOverText(t) |
| 1695 | var ok bool |
| 1696 | fr.eval(t, selectInJS("p", 0, 0), &ok) |
| 1697 | fr.eval(t, pasteJS("PASTE", "Caveat"), &ok) |
| 1698 | if state == "refused" { |
| 1699 | fr.eval(t, pasteJS("SECOND", "Inter"), &ok) |
| 1700 | } |
| 1701 | // Long enough for the old notes' 650 ms, and for a font |
| 1702 | // that 404s to be given up on. |
| 1703 | fr.rig.Run(chromedp.Sleep(900 * time.Millisecond)) |
| 1704 | } |
| 1705 | check := func(when string) { |
| 1706 | t.Helper() |
| 1707 | got := fr.noteOverText(t) |
| 1708 | if !got.Found { |
| 1709 | t.Fatalf("%s: no %s note is shown", when, state) |
| 1710 | } |
| 1711 | if len(got.Hits) > 0 { |
| 1712 | t.Errorf("%s: the %s note at %v covers the document's text: %q", when, state, got.Note, got.Hits) |
| 1713 | } |
| 1714 | if len(got.Controls) > 0 { |
| 1715 | t.Errorf("%s: the %s note at %v covers controls: %q", when, state, got.Note, got.Controls) |
| 1716 | } |
| 1717 | if got.FocusCovered { |
| 1718 | t.Errorf("%s: the %s note at %v covers the focus, %s", when, state, got.Note, got.Focus) |
| 1719 | } |
| 1720 | if got.Clipped { |
| 1721 | t.Errorf("%s: the %s note at %v is not all visible", when, state, got.Note) |
| 1722 | } |
| 1723 | if (state == "unavailable" || state == "substitute") && !got.Dismissable { |
| 1724 | t.Errorf("%s: the %s note has no visible way to dismiss it", when, state) |
| 1725 | } |
| 1726 | if state != "substitute" && (got.PageTop != before.PageTop || got.PageLeft != before.PageLeft) { |
| 1727 | t.Errorf("%s: showing the %s note moved the page from (%v, %v) to (%v, %v)", when, state, before.PageLeft, before.PageTop, got.PageLeft, got.PageTop) |
| 1728 | } |
| 1729 | } |
| 1730 | check("shown") |
| 1731 | if state == "unavailable" { |
| 1732 | // Escape leaves the document for the formatting bar; the |
| 1733 | // control it lands on is not under the note. |
| 1734 | fr.rig.Run(chromedp.KeyEvent(kb.Escape), chromedp.Sleep(100*time.Millisecond)) |
| 1735 | check("after Escape") |
| 1736 | } |
| 1737 | if state == "substitute" || state == "unavailable" { |
| 1738 | var left string |
| 1739 | fr.eval(t, `(() => { const b = document.querySelector('[docs-fonts-status-dismiss]'); if (!b) return 'no dismiss button'; |
| 1740 | b.click(); return document.querySelector('[docs-fonts-status]').getAttribute('data-state') || '' })()`, &left) |
| 1741 | if left != "" { |
| 1742 | t.Errorf("the %s note is still there after it was dismissed (%q)", state, left) |
| 1743 | } |
| 1744 | } |
| 1745 | }) |
| 1746 | } |
| 1747 | } |
| 1748 | } |
| 1749 | |
| 1750 | // fontFacesJS lists every Docs face the page's stylesheet declares |
| 1751 | // (not the picker's previews), and the faces the gate was asked for. |
| 1752 | const fontFacesJS = `JSON.stringify((() => { |
| 1753 | const faces = []; |
| 1754 | for (const sheet of document.styleSheets) { |
| 1755 | let rules; try { rules = sheet.cssRules } catch { continue } |
| 1756 | for (const r of rules) { |
| 1757 | if (!String(r.cssText).startsWith('@font-face')) continue; |
| 1758 | const fam = r.style.getPropertyValue('font-family').replace(/["']/g, '').trim(); |
| 1759 | const m = /url\(\s*["']?([^"')]+)/.exec(r.style.getPropertyValue('src')); |
| 1760 | if (fam.startsWith('Docs ') && !fam.endsWith(' Preview') && m && !m[1].includes('/preview-')) faces.push({ family: fam, url: new URL(m[1], sheet.href).href }); |
| 1761 | } |
| 1762 | } |
| 1763 | return { faces, need: JSON.parse(document.querySelector('[docs-canvas]').getAttribute('data-docs-fonts-need') || '[]') }; |
| 1764 | })())` |
| 1765 | |
| 1766 | const shownAtJS = `(() => { |
| 1767 | new MutationObserver(() => { |
| 1768 | if (!window.__shownAt && document.documentElement && document.documentElement.getAttribute('data-docs-fonts') === 'shown') window.__shownAt = performance.now(); |
| 1769 | }).observe(document, { subtree: true, attributes: true, attributeFilter: ['data-docs-fonts'] }); |
| 1770 | })()` |
| 1771 | |
| 1772 | type resourceEntry struct { |
| 1773 | Name string `json:"name"` |
| 1774 | Start float64 `json:"start"` |
| 1775 | Transfer float64 `json:"transfer"` |
| 1776 | Encoded float64 `json:"encoded"` |
| 1777 | Initiator string `json:"initiator"` |
| 1778 | } |
| 1779 | |
| 1780 | // Once the page is shown and idle, every family the picker offers is |
| 1781 | // fetched at low priority, one face at a time, and loaded from the |
| 1782 | // cache, so that choosing, pasting or receiving a font rarely waits |
| 1783 | // (branch review 7). Nothing beyond the page's own faces is fetched |
| 1784 | // before it is shown, and nothing at all on a connection that asks to |
| 1785 | // save data. |
| 1786 | func TestFontPrefetchFollowsTheReveal(t *testing.T) { |
| 1787 | for _, saveData := range []bool{false, true} { |
| 1788 | t.Run(fmt.Sprintf("save-data %v", saveData), func(t *testing.T) { |
| 1789 | fr := newFontRig(t) |
| 1790 | sqid := fr.document(t, "Prefetch", "simple.bin") |
| 1791 | // A real visit's cache: the prefetch puts each file there, and |
| 1792 | // the face is then loaded from it. |
| 1793 | fr.rig.Run(command(network.SetCacheDisabled, network.SetCacheDisabledParams{CacheDisabled: false}), |
| 1794 | command(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: shownAtJS})) |
| 1795 | if saveData { |
| 1796 | enabled := true |
| 1797 | fr.rig.Run(command(emulation.SetDataSaverOverride, emulation.SetDataSaverOverrideParams{DataSaverEnabled: &enabled})) |
| 1798 | } |
| 1799 | var mu sync.Mutex |
| 1800 | priority := map[string]network.ResourcePriority{} |
| 1801 | harness.Listen(fr.rig, fr.rig.Context(), network.RequestWillBeSent, func(e *network.EventRequestWillBeSent) { |
| 1802 | if e.Type == network.ResourceTypeFetch && strings.HasSuffix(e.Request.URL, ".woff2") { |
| 1803 | mu.Lock() |
| 1804 | priority[e.Request.URL] = e.Request.InitialPriority |
| 1805 | mu.Unlock() |
| 1806 | } |
| 1807 | }) |
| 1808 | fr.open(t, sqid) |
| 1809 | fr.editable(t) |
| 1810 | if saveData { |
| 1811 | fr.rig.Run(chromedp.Sleep(4 * time.Second)) |
| 1812 | } else { |
| 1813 | fr.rig.Run(chromedp.Poll[chromedp.Void](`document.documentElement.getAttribute('data-docs-fonts-prefetch') === 'done'`, chromedp.WithPollingTimeout(60*time.Second))) |
| 1814 | } |
| 1815 | var raw string |
| 1816 | fr.eval(t, fontFacesJS, &raw) |
| 1817 | var decl struct { |
| 1818 | Faces []struct{ Family, URL string } `json:"faces"` |
| 1819 | Need []struct{ Family string } `json:"need"` |
| 1820 | } |
| 1821 | if err := json.Unmarshal([]byte(raw), &decl); err != nil { |
| 1822 | t.Fatal(err) |
| 1823 | } |
| 1824 | needed := map[string]bool{} |
| 1825 | for _, n := range decl.Need { |
| 1826 | needed[n.Family] = true |
| 1827 | } |
| 1828 | var shownAt float64 |
| 1829 | fr.eval(t, `window.__shownAt || 0`, &shownAt) |
| 1830 | if shownAt == 0 { |
| 1831 | t.Fatal("the page was never shown") |
| 1832 | } |
| 1833 | fr.eval(t, `JSON.stringify(performance.getEntriesByType('resource').filter((e) => e.name.endsWith('.woff2')).map((e) => ({ name: e.name, start: e.startTime, transfer: e.transferSize, encoded: e.encodedBodySize, initiator: e.initiatorType })))`, &raw) |
| 1834 | var entries []resourceEntry |
| 1835 | if err := json.Unmarshal([]byte(raw), &entries); err != nil { |
| 1836 | t.Fatal(err) |
| 1837 | } |
| 1838 | byURL := map[string][]resourceEntry{} |
| 1839 | for _, e := range entries { |
| 1840 | byURL[e.Name] = append(byURL[e.Name], e) |
| 1841 | } |
| 1842 | var bytes float64 |
| 1843 | missing := 0 |
| 1844 | for _, f := range decl.Faces { |
| 1845 | got := byURL[f.URL] |
| 1846 | for _, e := range got { |
| 1847 | if e.Start < shownAt && !needed[f.Family] { |
| 1848 | t.Errorf("%s was fetched at %.0fms, before the page was shown at %.0fms", f.URL, e.Start, shownAt) |
| 1849 | } |
| 1850 | if e.Transfer > 0 && !needed[f.Family] && f.Family != "Docs Carlito" { |
| 1851 | bytes += e.Encoded |
| 1852 | } |
| 1853 | } |
| 1854 | overNet := 0 |
| 1855 | for _, e := range got { |
| 1856 | if e.Transfer > 0 { |
| 1857 | overNet++ |
| 1858 | } |
| 1859 | } |
| 1860 | if overNet > 1 { |
| 1861 | t.Errorf("%s came over the network %d times; the prefetch should fill the cache once", f.URL, overNet) |
| 1862 | } |
| 1863 | if len(got) == 0 { |
| 1864 | missing++ |
| 1865 | if !saveData && !needed[f.Family] { |
| 1866 | t.Errorf("%s (%s) was never prefetched", f.URL, f.Family) |
| 1867 | } |
| 1868 | } else if saveData && !needed[f.Family] && f.Family != "Docs Carlito" { |
| 1869 | t.Errorf("%s was fetched on a connection that asks to save data", f.URL) |
| 1870 | } |
| 1871 | } |
| 1872 | if !saveData { |
| 1873 | mu.Lock() |
| 1874 | for url, p := range priority { |
| 1875 | if p != network.ResourcePriorityLow && p != network.ResourcePriorityVeryLow { |
| 1876 | t.Errorf("%s was prefetched at %s priority", url, p) |
| 1877 | } |
| 1878 | } |
| 1879 | n := len(priority) |
| 1880 | mu.Unlock() |
| 1881 | if n == 0 { |
| 1882 | t.Error("no face was fetched by the prefetch") |
| 1883 | } |
| 1884 | var ready bool |
| 1885 | fr.eval(t, `globalThis.docsFonts.ready('caveat') && globalThis.docsFonts.ready('playfair') && globalThis.docsFonts.loaded('jetbrains')`, &ready) |
| 1886 | if !ready { |
| 1887 | t.Error("after the prefetch the families are not ready to use") |
| 1888 | } |
| 1889 | t.Logf("%d faces declared; the prefetch fetched %.0f bytes beyond the page's own (%.2f MiB)", len(decl.Faces), bytes, bytes/1024/1024) |
| 1890 | } |
| 1891 | fr.noViolations(t) |
| 1892 | }) |
| 1893 | } |
| 1894 | } |
| 1895 | |
| 1896 | // An action that needs a family the prefetch is still fetching waits |
| 1897 | // for it like any other, and is performed once it is in. |
| 1898 | func TestFontAWaitDuringThePrefetch(t *testing.T) { |
| 1899 | fr := newFontRig(t) |
| 1900 | sqid := fr.document(t, "Prefetching", "simple.bin") |
| 1901 | // Caladea is the first family the prefetch fetches after the default. |
| 1902 | fr.match.Store("Caladea-") |
| 1903 | fr.slow.Store(int64(2 * time.Second)) |
| 1904 | fetching := make(chan struct{}, 1) |
| 1905 | harness.Listen(fr.rig, fr.rig.Context(), network.RequestWillBeSent, func(e *network.EventRequestWillBeSent) { |
| 1906 | if e.Type == network.ResourceTypeFetch && strings.Contains(e.Request.URL, "Caladea-") { |
| 1907 | select { |
| 1908 | case fetching <- struct{}{}: |
| 1909 | default: |
| 1910 | } |
| 1911 | } |
| 1912 | }) |
| 1913 | fr.open(t, sqid) |
| 1914 | fr.editable(t) |
| 1915 | select { |
| 1916 | case <-fetching: |
| 1917 | case <-time.After(20 * time.Second): |
| 1918 | t.Fatal("the prefetch never fetched Caladea") |
| 1919 | } |
| 1920 | var ok bool |
| 1921 | fr.eval(t, waitLogJS, &ok) |
| 1922 | fr.eval(t, selectInJS("p", 0, 0), &ok) |
| 1923 | fr.eval(t, pasteJS("PASTE", "Caladea"), &ok) |
| 1924 | if !fr.inWait(t) { |
| 1925 | t.Fatal("the paste did not wait for Caladea, which was still on its way") |
| 1926 | } |
| 1927 | fr.settled(t) |
| 1928 | var html, fallback string |
| 1929 | fr.eval(t, `document.querySelector('[docs-text] p').innerHTML`, &html) |
| 1930 | fr.eval(t, `document.documentElement.getAttribute('data-docs-fonts-fallback') || ''`, &fallback) |
| 1931 | if !strings.Contains(html, `docs-font-caladea`) || !strings.Contains(html, "PASTE") { |
| 1932 | t.Errorf("the paste was not performed in Caladea: %s", html) |
| 1933 | } |
| 1934 | if strings.Contains(fallback, "caladea") { |
| 1935 | t.Error("Caladea was committed to its fallback") |
| 1936 | } |
| 1937 | fr.noViolations(t) |
| 1938 | } |
| 1939 | |
| 1940 | // A wait never begins in the middle of an IME composition (branch review |
| 1941 | // 7). A composition types in the marks already on screen; if a change in |
| 1942 | // a family not yet loaded arrives during one anyway, that family is drawn |
| 1943 | // in its fallback for the visit rather than the composition being |
| 1944 | // interrupted, and never in a face that has not loaded. |
| 1945 | func TestFontACompositionNeverStartsAWait(t *testing.T) { |
| 1946 | fr := newFontRig(t) |
| 1947 | fr.sqid = fr.document(t, "IME", "simple.bin") |
| 1948 | fr.match.Store("Caveat-") |
| 1949 | fr.slow.Store(int64(3 * time.Second)) |
| 1950 | fr.open(t, fr.sqid) |
| 1951 | fr.editable(t) |
| 1952 | var ok bool |
| 1953 | fr.eval(t, waitLogJS, &ok) |
| 1954 | fr.eval(t, selectInJS("p:last-child", -1, -1), &ok) |
| 1955 | fr.rig.Run(command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: "にほん", SelectionStart: 3, SelectionEnd: 3}), chromedp.Sleep(150*time.Millisecond)) |
| 1956 | // ProseMirror ignores a paste during a composition; a drop it takes. |
| 1957 | fr.eval(t, `(() => { const el = document.querySelector('[docs-text]'); |
| 1958 | const d = new DataTransfer(); d.setData('text/html', '<p style="font-family: Caveat">DROPPED</p>'); |
| 1959 | const r = el.querySelector('p').getBoundingClientRect(); |
| 1960 | el.dispatchEvent(new DragEvent('drop', { dataTransfer: d, bubbles: true, cancelable: true, clientX: r.left + 30, clientY: r.top + 8 })); |
| 1961 | return true })()`, &ok) |
| 1962 | fr.rig.Run(chromedp.Sleep(150*time.Millisecond), command(input.InsertText, input.InsertTextParams{Text: "日本"}), chromedp.Sleep(500*time.Millisecond)) |
| 1963 | for _, e := range fr.waitLog(t) { |
| 1964 | if e.Inert { |
| 1965 | t.Errorf("at %dms a wait began during the composition", e.Ms) |
| 1966 | break |
| 1967 | } |
| 1968 | } |
| 1969 | var text, fallback string |
| 1970 | fr.eval(t, docTextJS, &text) |
| 1971 | fr.eval(t, `document.documentElement.getAttribute('data-docs-fonts-fallback') || ''`, &fallback) |
| 1972 | if !strings.Contains(text, "日本") { |
| 1973 | t.Errorf("the composition was lost: %q", text) |
| 1974 | } |
| 1975 | var caveat bool |
| 1976 | fr.eval(t, `!!document.querySelector('[docs-text] .docs-font-caveat')`, &caveat) |
| 1977 | if caveat && !strings.Contains(fallback, "caveat") { |
| 1978 | t.Errorf("text in Caveat landed during the composition without Caveat committed to its fallback (%q)", fallback) |
| 1979 | } |
| 1980 | t.Logf("text %q, Caveat run: %v, fallback %q", text, caveat, fallback) |
| 1981 | fr.noViolations(t) |
| 1982 | } |
| 1983 | |
| 1984 | // A document that is left lets go of its connections at once: its live |
| 1985 | // stream closes on pagehide, and its prefetch stops. In a browser with a |
| 1986 | // back/forward cache (full Chrome) each document left behind otherwise |
| 1987 | // kept its stream open; with HTTP/1.1's six connections to a host, the |
| 1988 | // sixth navigation waited about a minute for one, and by the time its |
| 1989 | // page ran, the font gate's deadline had passed and it committed every |
| 1990 | // family still loading (the generative gate test on main 5a951ba). |
| 1991 | func TestFontLeavingADocumentLetsGoOfItsConnections(t *testing.T) { |
| 1992 | fr := newFontRig(t) |
| 1993 | var sqids []string |
| 1994 | for i := 0; i < 8; i++ { |
| 1995 | sqids = append(sqids, fr.document(t, fmt.Sprintf("Leaving %d", i), "simple.bin")) |
| 1996 | } |
| 1997 | for i, sqid := range sqids { |
| 1998 | start := time.Now() |
| 1999 | fr.open(t, sqid) |
| 2000 | fr.editable(t) |
| 2001 | var responseEnd float64 |
| 2002 | fr.eval(t, `performance.getEntriesByType('navigation')[0].responseEnd`, &responseEnd) |
| 2003 | if took := time.Since(start); took > 5*time.Second || responseEnd > 3000 { |
| 2004 | t.Errorf("document %d took %v to open (its response ended at %.0fms): a connection was still held by a page left behind", i, took, responseEnd) |
| 2005 | } |
| 2006 | // This page's stream, and none left open by the pages before it. |
| 2007 | deadline := time.Now().Add(3 * time.Second) |
| 2008 | for fr.streams.Load() > 1 && time.Now().Before(deadline) { |
| 2009 | time.Sleep(100 * time.Millisecond) |
| 2010 | } |
| 2011 | if n := fr.streams.Load(); n > 1 { |
| 2012 | t.Errorf("after opening document %d the server is serving %d live streams; the pages left behind kept theirs", i, n) |
| 2013 | } |
| 2014 | } |
| 2015 | } |
| 2016 | |