// fixtures/font-session.mjs — which document faces this tab has, and the // one rule for every way text reaches the screen: it is never painted in // a face it will later leave, and a face already on screen never changes // (polish-audit/fonts/NO-FOUT.md; Paul, 2026-10-24 and again after // review: "No flashing, ever!"). // // A face is pending, loaded or failed. Loaded and failed are both final: // a face the browser could not fetch is drawn in its fallback from the // start and never swapped. Only pending is dangerous, so nothing may be // put on screen in a pending face: // // - the page: fonts-gate.mjs holds the sheet until the faces it shows // have loaded, and only then turns the web faces on at all; // - editing: the editor is not editable until every face of every // family in use (and the default's, and code's) has settled, so // typing, input rules and the formatting commands can only reach // faces that are final; // - a collaborator's change and a paste: they wait for the same set, // plus any family they introduce; // - a pick: the family loads before the mark is set, and the latest // pick wins. // // "Commit" is the escape for a family that is NOT on screen yet: past // its deadline it is shown in its fallback for the rest of the visit // (), so a late arrival has nothing to // swap into. A family already on screen is never committed; its pending // faces are waited for. That is finding 2 of the branch review: a Bold // that timed out used to commit all of Carlito, and every paragraph on // screen changed face. // // No DOM beyond what is passed in; font-session.test.mjs drives it in // Node with a fake FontFaceSet. import { FAMILIES, family, DEFAULT_FONT, CODE_FONT } from './fonts.mjs' // The gate shows the sheet at this deadline whatever has arrived, having // committed what has not. Measured from navigation start. export const GATE_DEADLINE_MS = 2500 // A family a collaborator's change or a paste introduces waits this long // before it is committed to its fallback. export const NEW_FAMILY_TIMEOUT_MS = 3000 // A formatting command waits this long for its faces, then gives up and // changes nothing. export const COMMAND_TIMEOUT_MS = 4000 // shorthand is the CSS font a FontFaceSet loads one face by. export function shorthand(cssName, { weight, style }) { return `${style === 'italic' ? 'italic ' : ''}${weight} 16px "${cssName}"` } // keysInBytes is every family a Yjs update names. Yjs writes a // formatting attribute's key as plain UTF-8, so "font_" is in the // bytes of any update that sets it. A false positive costs one download. export function keysInBytes(bytes) { if (!bytes || !bytes.length) return [] let text = '' for (let i = 0; i < bytes.length; i += 0x8000) { text += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)) } const keys = FAMILIES.filter((f) => text.includes('font_' + f.key)).map((f) => f.key) // A node or mark that names no family can still bring one in: the code // mark and the code block are the code family's. The editor fills this // in from its schema (schema.mjs), so a node added there is covered. for (const [name, key] of implicitFamilies) { if (text.includes(name) && !keys.includes(key)) keys.push(key) } return keys } // implicitFamilies is every schema node or mark name whose text is in a // family it does not name; setImplicitFamilies replaces it. const implicitFamilies = new Map([['code', CODE_FONT]]) export function setImplicitFamilies(entries) { implicitFamilies.clear() for (const [name, key] of entries) implicitFamilies.set(name, key) } // faceURLs reads every Docs face's file off the page's @font-face rules, // as "family|weight|style" -> URL, for prefetch. The stylesheet is the // one place the hashed file names are written. export function faceURLs(styleSheets) { const out = new Map() const weights = { normal: '400', bold: '700' } for (const sheet of styleSheets) { let rules try { rules = sheet.cssRules } catch { continue } for (const rule of rules || []) { if (!rule.style || !String(rule.cssText || '').startsWith('@font-face')) continue const family = rule.style.getPropertyValue('font-family').trim().replace(/^["']|["']$/g, '') const src = /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(rule.style.getPropertyValue('src')) if (!family.startsWith('Docs ') || !src) continue const w = rule.style.getPropertyValue('font-weight').trim() || '400' const st = rule.style.getPropertyValue('font-style').trim() || 'normal' out.set(family + '|' + (weights[w] || w) + '|' + st, new URL(src[1], sheet.href || location.href).href) } } return out } function delay(ms, setTimer) { return new Promise((resolve) => setTimer(() => resolve('late'), ms)) } export function createFontSession({ fontSet, root, setTimer = setTimeout } = {}) { const faces = new Map() // "key|weight|style" -> { state, promise } const committed = new Set() // inUse is every family that is, or may be, on screen: what the page // was gated on, the default, and whatever a pick, a paste or a // collaborator has brought in since. const inUse = new Set([DEFAULT_FONT]) let shown = false let previews = 'pending' function setFallbackAttr() { if (!root) return const value = [...committed].sort().join(' ') if (root.getAttribute('data-docs-fonts-fallback') !== value) root.setAttribute('data-docs-fonts-fallback', value) } // commit refuses a family that is on screen in its web face: changing // it would move text a reader is looking at. function commit(keys) { let changed = false for (const k of keys) { if (committed.has(k) || (shown && inUse.has(k) && !committed.has(k))) continue committed.add(k) changed = true } if (changed) setFallbackAttr() } // loadFace resolves to whether one face loaded. A rejection or an // empty result is a failure, which is final too. function loadFace(spec) { const id = spec.family + '|' + spec.weight + '|' + spec.style let f = faces.get(id) if (f) return f.promise f = { state: 'pending' } f.promise = Promise.resolve() .then(() => fontSet.load(shorthand(spec.family, spec))) .then((got) => (Array.isArray(got) ? got.length > 0 : !!got), () => false) .then((ok) => { f.state = ok ? 'loaded' : 'failed' return ok }) faces.set(id, f) return f.promise } // faceSpec is the face a run in key, bold and italic is drawn in: the // same fallback internal/fonts' Family.Face makes for a family with no // italic. function faceSpec(key, bold, italic) { const all = specsOf(key) const want = (b, i) => all.find((s) => (s.weight === 700) === b && (s.style === 'italic') === i) return want(bold, italic) || want(bold, false) || want(false, false) || all[0] } function specsOf(key) { const f = family(key) return f ? f.faces.map((s) => ({ family: f.cssName, ...s })) : [] } // settle loads all of a family's faces and resolves once none is // pending, to whether all of them loaded. function settle(key) { if (committed.has(key)) return Promise.resolve(false) return Promise.all(specsOf(key).map(loadFace)).then((all) => all.every(Boolean)) } function isSettled(key) { if (committed.has(key)) return true return specsOf(key).every((s) => { const f = faces.get(s.family + '|' + s.weight + '|' + s.style) return f && f.state !== 'pending' }) } const session = { // ready is whether text in this family can be painted now and stay // as it is: every face settled, or the family committed. ready: (key) => isSettled(key), loaded(key) { return !committed.has(key) && specsOf(key).every((s) => (faces.get(s.family + '|' + s.weight + '|' + s.style) || {}).state === 'loaded') }, committed: (key) => committed.has(key), get fallback() { return [...committed].sort() }, get inUse() { return [...inUse] }, use(keys) { for (const k of keys) if (family(k)) inUse.add(k) }, // required is every family any change to the document may paint // in: the families in use (the page's, and every one brought in // since) and the default. A change naming another (code's, a // font_* mark) adds it. required(extra = []) { return [...new Set([...inUse, DEFAULT_FONT, ...extra])].filter((k) => family(k)) }, markShown() { shown = true }, get shown() { return shown }, // gate waits for the faces the page shows (fontgate.go's list), until // the deadline; families still missing then are committed, which is // safe because nothing is on screen yet. Resolves 'ok' or 'late'. async gate(need, deadlineMs) { const docFaces = need.filter((f) => f.key !== 'previews') const previewFaces = need.filter((f) => f.key === 'previews') for (const f of docFaces) inUse.add(f.key) const results = new Map() const docs = Promise.all(docFaces.map((spec) => loadFace(spec).then((ok) => results.set(spec, ok)))) const prevs = Promise.all(previewFaces.map((spec) => loadFace(spec).then((ok) => results.set(spec, ok)))) const timer = delay(deadlineMs, setTimer) const outcome = await Promise.race([docs.then(() => 'ok'), timer]) const missing = new Set(docFaces.filter((s) => results.get(s) !== true).map((s) => s.key)) commit([...missing]) // The previews have their own state and their own wait, so a slow // preview never holds the paper back. session.previewsDone = Promise.race([prevs.then(() => 'ok'), timer]).then(() => { previews = previewFaces.every((s) => results.get(s) === true) ? 'web' : 'system' return previews }) return outcome === 'ok' && missing.size === 0 ? 'ok' : 'late' }, previewsDone: Promise.resolve('system'), get previews() { return previews }, set previews(v) { previews = v }, // prepare is a collaborator's change or a paste: everything it could // paint in settles first. A family it introduces that is not on // screen gets NEW_FAMILY_TIMEOUT_MS and is then committed; families // already on screen are waited for, because committing them would // change text in view. async prepare(newKeys = [], { timeout = NEW_FAMILY_TIMEOUT_MS } = {}) { const fresh = [...new Set(newKeys)].filter((k) => family(k) && !inUse.has(k)) const known = session.required().filter((k) => !fresh.includes(k)) await Promise.all([ ...known.map(settle), ...fresh.map(async (k) => { if ((await Promise.race([settle(k), delay(timeout, setTimer)])) === 'late') commit([k]) }), ]) for (const k of fresh) inUse.add(k) }, prepareRemote(bytes, opts) { return session.prepare(keysInBytes(bytes), opts) }, // waitFor resolves true once every face of every key has settled, or // false at the timeout, committing nothing. Commands use it. async waitFor(keys, timeout = COMMAND_TIMEOUT_MS) { if (keys.every(isSettled)) return true const all = Promise.all(keys.map(settle)).then(() => true) return (await Promise.race([all, delay(timeout, setTimer)])) === true }, // commitFallback draws families in their fallback for the rest of the // visit, unless one is on screen in its web face. The editor uses it // for the one change it never makes wait: an IME composition. commitFallback(keys) { commit(keys) return keys.every((k) => committed.has(k)) }, // prefetch brings every family's faces into the tab once the page is // shown and idle (branch review 7), so that a pick, a paste or a // collaborator's font is ready before anyone asks for it. One face at // a time: idle() resolves when the page is idle, fetchFn fetches a // file at low priority into the HTTP cache, and the face is then // loaded from there. It never commits anything, and a face whose // fetch fails is left alone for an action to load when it needs it. // urls maps "family|weight|style" to the file (faceURLs). async prefetch({ keys, urls, fetchFn, idle = () => Promise.resolve() }) { for (const k of keys) { for (const spec of specsOf(k)) { const id = spec.family + '|' + spec.weight + '|' + spec.style if (committed.has(k) || faces.has(id)) continue await idle() if (committed.has(k) || faces.has(id)) continue const url = urls.get(id) if (!url) continue let ok = false try { ok = await fetchFn(url) } catch { ok = false } if (ok) await loadFace(spec) } } }, // load is a pick's: all four faces, then whether all of them loaded. // A committed family is usable (it draws in its fallback, stably). async load(key) { if (committed.has(key)) return true const ok = await settle(key) if (ok) inUse.add(key) return ok }, } return session } // createSystemSession is the session for a page whose web faces are not // on (no hold, or the fail-safe showed it): everything is in its system // face for the visit, so there is nothing to load and nothing to wait // for. export function createSystemSession(root) { const yes = () => true return { web: false, ready: yes, loaded: yes, committed: () => false, fallback: [], inUse: [], use() {}, required: () => [], markShown() {}, shown: true, previews: 'system', previewsDone: Promise.resolve('system'), prepare: async () => {}, prepareRemote: async () => {}, waitFor: async () => true, load: async () => true, commitFallback: () => true, prefetch: async () => {}, fontsReady: Promise.resolve(), // Called by the editor once it has paginated. If the page is still // held (the hold ran, the gate never did), the editor shows it: in // its system faces, already paginated. settled() { if (!root || root.getAttribute('data-docs-fonts') !== 'pending') return clearTimeout(globalThis.__docsFontsHold) root.setAttribute('data-docs-fonts', 'shown') if (root.getAttribute('data-docs-previews') === 'pending') root.setAttribute('data-docs-previews', 'system') }, } }