// fixtures/font-session.test.mjs — the font session, against a fake // FontFaceSet whose loads resolve by hand, so a test can hold one open // and watch what is (and is not) applied while it waits. import { test } from 'node:test' import assert from 'node:assert/strict' import { createFontSession, createSystemSession, faceURLs, keysInBytes, shorthand } from './font-session.mjs' import { fontStatus } from './font-status.mjs' function fakeFonts() { const loads = [] return { loads, load(font) { let resolve, reject const p = new Promise((res, rej) => { resolve = res; reject = rej }) loads.push({ font, ok: () => resolve([{}]), fail: () => reject(new Error('network')), done: false }) return p }, // settle resolves every load still open whose CSS mentions match. settle(match, ok = true) { for (const l of loads.filter((l) => !l.done && l.font.includes(match))) { l.done = true ;(ok ? l.ok : l.fail)() } }, open(match) { return loads.filter((l) => !l.done && l.font.includes(match)).length }, } } function fakeRoot() { const attrs = {} return { attrs, getAttribute: (n) => attrs[n] ?? null, setAttribute: (n, v) => { attrs[n] = v } } } function fakeTimers() { const due = [] return { setTimer: (fn, ms) => due.push({ fn, ms }), fire: () => due.splice(0).forEach((t) => t.fn()), due } } const tick = async (n = 5) => { for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r)) } const bytes = (s) => new TextEncoder().encode(s) const face = (key, family, weight = 400, style = 'normal') => ({ key, family, weight, style }) test('the CSS a face is loaded by', () => { assert.equal(shorthand('Docs Carlito', { weight: 700, style: 'italic' }), 'italic 700 16px "Docs Carlito"') assert.equal(shorthand('Docs Carlito', { weight: 400, style: 'normal' }), '400 16px "Docs Carlito"') }) test('the gate waits for the faces the page needs, and commits what misses the deadline', async () => { const fontSet = fakeFonts() const root = fakeRoot() const timers = fakeTimers() const session = createFontSession({ fontSet, root, setTimer: timers.setTimer }) const need = [face('carlito', 'Docs Carlito'), face('carlito', 'Docs Carlito', 700), face('inter', 'Docs Inter')] let outcome = null session.gate(need, 2500).then((o) => { outcome = o }) await tick() fontSet.settle('Docs Carlito') await tick() assert.equal(outcome, null, 'the gate let go with Inter still loading') timers.fire() await tick() assert.equal(outcome, 'late') assert.equal(root.attrs['data-docs-fonts-fallback'], 'inter', 'Inter must be committed: nothing is on screen yet') fontSet.settle('Docs Inter') await tick() assert.equal(root.attrs['data-docs-fonts-fallback'], 'inter', 'a late arrival changes nothing') }) test('the previews have their own wait and never hold the paper', async () => { const fontSet = fakeFonts() const session = createFontSession({ fontSet, root: fakeRoot(), setTimer: () => {} }) const need = [face('carlito', 'Docs Carlito'), face('previews', 'Docs Preview 01')] const outcome = session.gate(need, 2500) await tick() fontSet.settle('Docs Carlito') assert.equal(await outcome, 'ok', 'the paper waited for a preview') assert.equal(session.previews, 'pending') fontSet.settle('Docs Preview') assert.equal(await session.previewsDone, 'web') }) // Review finding 2: a family on screen is never committed. Carlito // regular is showing; its bold is slow; a command waiting for the bold // gives up and nothing is committed. test('a family on screen is never committed, whatever is late', async () => { const fontSet = fakeFonts() const root = fakeRoot() const timers = fakeTimers() const session = createFontSession({ fontSet, root, setTimer: timers.setTimer }) const gated = session.gate([face('carlito', 'Docs Carlito')], 2500) await tick() fontSet.settle('400 16px "Docs Carlito"') await gated session.markShown() const waited = session.waitFor(['carlito'], 4000) await tick() timers.fire() assert.equal(await waited, false, 'the command must give up') assert.equal(root.attrs['data-docs-fonts-fallback'] ?? '', '', 'Carlito was committed while on screen') // And a collaborator's change naming nothing waits for it rather than // committing it. let applied = false session.prepareRemote(bytes('strong')).then(() => { applied = true }) await tick() timers.fire() await tick() assert.equal(applied, false, 'the change was let through with Carlito bold still pending') assert.equal(root.attrs['data-docs-fonts-fallback'] ?? '', '') fontSet.settle('Docs Carlito') fontSet.settle('Docs Liberation Mono') await tick(10) assert.ok(applied) }) // Review finding 1: a change that names no font can still bring in a // face: code is Liberation Mono. It waits for it. test('a collaborator\'s change waits for the code face though it names no font', async () => { const fontSet = fakeFonts() const session = createFontSession({ fontSet, root: fakeRoot(), setTimer: () => {} }) let applied = false const done = session.prepareRemote(bytes('\u0004code\u0000hello')).then(() => { applied = true }) await tick() fontSet.settle('Docs Carlito') await tick() assert.equal(applied, false, 'applied with Liberation Mono still loading') fontSet.settle('Docs Liberation Mono') await done assert.ok(applied) }) test('a family a change introduces waits, and is committed if it is not on screen and late', async () => { const fontSet = fakeFonts() const root = fakeRoot() const timers = fakeTimers() const session = createFontSession({ fontSet, root, setTimer: timers.setTimer }) session.markShown() let applied = false const done = session.prepareRemote(bytes('font_caveat'), { timeout: 3000 }).then(() => { applied = true }) await tick() fontSet.settle('Docs Carlito') fontSet.settle('Docs Liberation Mono') await tick() assert.equal(applied, false) timers.fire() await done assert.equal(root.attrs['data-docs-fonts-fallback'], 'caveat') assert.ok(session.inUse.includes('caveat')) }) test('the byte scan finds every family a Yjs update names', () => { assert.deepEqual(keysInBytes(bytes('xx font_inter yy font_sans zz')).sort(), ['inter', 'sans']) assert.deepEqual(keysInBytes(new Uint8Array([])), []) assert.deepEqual(keysInBytes(bytes('font_notosans')), ['notosans']) }) // Review finding 4: with no gate, the editor shows a held page itself // once it has paginated, in the system faces. test('without the gate, the editor shows the held page in its system faces', () => { const root = fakeRoot() root.setAttribute('data-docs-fonts', 'pending') root.setAttribute('data-docs-previews', 'pending') const session = createSystemSession(root) assert.equal(session.web, false) assert.ok(session.ready('inter')) session.settled() assert.equal(root.attrs['data-docs-fonts'], 'shown') assert.equal(root.attrs['data-docs-previews'], 'system') assert.equal(root.attrs['data-docs-faces'], undefined, 'the web faces were turned on') }) // A stylesheet as the browser exposes one: @font-face rules with their // descriptors, and one ordinary rule. function fakeSheet(href, faces) { const rule = (family, src, weight, style) => ({ cssText: '@font-face { font-family: "' + family + '"; }', style: { getPropertyValue: (p) => ({ 'font-family': '"' + family + '"', src: 'url("' + src + '") format("woff2")', 'font-weight': weight, 'font-style': style })[p] || '' }, }) return { href, cssRules: [{ cssText: 'p { color: red }', style: { getPropertyValue: () => '' } }, ...faces.map((f) => rule(...f))] } } test('faceURLs reads every Docs face off the stylesheet, by family, weight and style', () => { const urls = faceURLs([ fakeSheet('https://docs.example/static/fonts.css', [ ['Docs Inter', '/static/fonts/Inter-Regular.woff2', '400', 'normal'], ['Docs Inter', '/static/fonts/Inter-BoldItalic.woff2', 'bold', 'italic'], ['Onest', '/static/onest.woff2', '400', 'normal'], ]), { href: 'https://elsewhere.example/x.css', get cssRules() { throw new Error('cross-origin') } }, ]) assert.deepEqual([...urls], [ ['Docs Inter|400|normal', 'https://docs.example/static/fonts/Inter-Regular.woff2'], ['Docs Inter|700|italic', 'https://docs.example/static/fonts/Inter-BoldItalic.woff2'], ]) }) test('prefetch fetches each face when idle, then loads it from the cache, and never commits', async () => { const fontSet = fakeFonts() const root = fakeRoot() const session = createFontSession({ fontSet, root }) const urls = new Map([ ['Docs Inter|400|normal', 'u/inter-r'], ['Docs Inter|700|normal', 'u/inter-b'], ['Docs Inter|400|italic', 'u/inter-i'], ['Docs Inter|700|italic', 'u/inter-bi'], ]) const fetched = [] let idles = 0 const failing = new Set(['u/inter-bi']) const run = session.prefetch({ keys: ['inter'], urls, idle: async () => { idles++ }, fetchFn: async (u) => { fetched.push(u); return !failing.has(u) }, }) for (let i = 0; i < 4; i++) { await tick(10) fontSet.settle('Docs Inter') } await run assert.deepEqual(fetched, ['u/inter-r', 'u/inter-b', 'u/inter-i', 'u/inter-bi']) assert.equal(idles, 4, 'one idle wait per face') // The face whose fetch failed is not loaded through the font set: an // action loads it when it needs it. assert.equal(fontSet.loads.length, 3) assert.equal(session.ready('inter'), false) assert.deepEqual(session.fallback, []) }) test('prefetch leaves a family alone once an action is loading it, and a wait shares the load', async () => { const fontSet = fakeFonts() const session = createFontSession({ fontSet, root: fakeRoot() }) const urls = new Map([['Docs Caveat|400|normal', 'u/caveat-r'], ['Docs Caveat|700|normal', 'u/caveat-b']]) let finishFetch const fetched = [] const run = session.prefetch({ keys: ['caveat'], urls, fetchFn: (u) => { fetched.push(u); return new Promise((r) => (finishFetch = r)) } }) await tick() // An action needs Caveat while the prefetch is still fetching it. let waited = null session.waitFor(['caveat'], 4000).then((ok) => { waited = ok }) await tick() assert.equal(fontSet.open('Docs Caveat'), 2, 'the action loads both faces now') finishFetch(true) await tick() fontSet.settle('Docs Caveat') await run await tick() assert.equal(waited, true) assert.equal(fontSet.loads.length, 2, 'the prefetch did not load a face the action was loading') assert.deepEqual(fetched, ['u/caveat-r'], 'nor fetch the next once the action had it') }) test('commitFallback commits a family that is not on screen, and refuses one that is', () => { const session = createFontSession({ fontSet: fakeFonts(), root: fakeRoot() }) session.use(['inter']) session.markShown() assert.equal(session.commitFallback(['caveat']), true) assert.equal(session.commitFallback(['inter']), false) assert.deepEqual(session.fallback, ['caveat']) }) // A fake [docs-fonts-status]: data-* copy, a text element and a button. function fakeStatus() { const attrs = { 'data-loading': 'Loading a font…', 'data-refused': 'Refused.', 'data-unavailable': 'Unavailable.', 'data-substitute': 'Substitutes.' } const text = { textContent: '' } const clicks = [] const button = { addEventListener: (_, fn) => clicks.push(fn) } const el = { getAttribute: (n) => attrs[n] ?? null, setAttribute: (n, v) => { attrs[n] = v }, removeAttribute: (n) => { delete attrs[n] }, querySelector: (q) => (q === '[docs-fonts-status-text]' ? text : button), } return { el, text, attrs, click: () => clicks.forEach((f) => f()) } } test('the status strip says one thing at a time, and a timed note does not clear a later one', () => { const s = fakeStatus() const timers = fakeTimers() const gate = fontStatus(s.el, { setTimer: timers.setTimer, clearTimer: () => {} }) const editor = fontStatus(s.el, { setTimer: () => {}, clearTimer: () => {} }) gate.say('substitute', 10000) assert.equal(s.text.textContent, 'Substitutes.') editor.say('loading') assert.equal(editor.state, 'loading') timers.fire() assert.equal(s.text.textContent, 'Loading a font…', "the substitutes note's timer leaves the loading note alone") editor.clear() assert.equal(s.text.textContent, '') assert.equal(s.attrs['data-state'], undefined) editor.say('unavailable', 8000) s.click() assert.equal(gate.state, '', 'dismissed') })