| 1 | // fixtures/font-session.mjs — which document faces this tab has, and the |
| 2 | // one rule for every way text reaches the screen: it is never painted in |
| 3 | // a face it will later leave, and a face already on screen never changes |
| 4 | // (polish-audit/fonts/NO-FOUT.md; Paul, 2026-10-24 and again after |
| 5 | // review: "No flashing, ever!"). |
| 6 | // |
| 7 | // A face is pending, loaded or failed. Loaded and failed are both final: |
| 8 | // a face the browser could not fetch is drawn in its fallback from the |
| 9 | // start and never swapped. Only pending is dangerous, so nothing may be |
| 10 | // put on screen in a pending face: |
| 11 | // |
| 12 | // - the page: fonts-gate.mjs holds the sheet until the faces it shows |
| 13 | // have loaded, and only then turns the web faces on at all; |
| 14 | // - editing: the editor is not editable until every face of every |
| 15 | // family in use (and the default's, and code's) has settled, so |
| 16 | // typing, input rules and the formatting commands can only reach |
| 17 | // faces that are final; |
| 18 | // - a collaborator's change and a paste: they wait for the same set, |
| 19 | // plus any family they introduce; |
| 20 | // - a pick: the family loads before the mark is set, and the latest |
| 21 | // pick wins. |
| 22 | // |
| 23 | // "Commit" is the escape for a family that is NOT on screen yet: past |
| 24 | // its deadline it is shown in its fallback for the rest of the visit |
| 25 | // (<html data-docs-fonts-fallback>), so a late arrival has nothing to |
| 26 | // swap into. A family already on screen is never committed; its pending |
| 27 | // faces are waited for. That is finding 2 of the branch review: a Bold |
| 28 | // that timed out used to commit all of Carlito, and every paragraph on |
| 29 | // screen changed face. |
| 30 | // |
| 31 | // No DOM beyond what is passed in; font-session.test.mjs drives it in |
| 32 | // Node with a fake FontFaceSet. |
| 33 | |
| 34 | import { FAMILIES, family, DEFAULT_FONT, CODE_FONT } from './fonts.mjs' |
| 35 | |
| 36 | // The gate shows the sheet at this deadline whatever has arrived, having |
| 37 | // committed what has not. Measured from navigation start. |
| 38 | export const GATE_DEADLINE_MS = 2500 |
| 39 | |
| 40 | // A family a collaborator's change or a paste introduces waits this long |
| 41 | // before it is committed to its fallback. |
| 42 | export const NEW_FAMILY_TIMEOUT_MS = 3000 |
| 43 | |
| 44 | // A formatting command waits this long for its faces, then gives up and |
| 45 | // changes nothing. |
| 46 | export const COMMAND_TIMEOUT_MS = 4000 |
| 47 | |
| 48 | // shorthand is the CSS font a FontFaceSet loads one face by. |
| 49 | export function shorthand(cssName, { weight, style }) { |
| 50 | return `${style === 'italic' ? 'italic ' : ''}${weight} 16px "${cssName}"` |
| 51 | } |
| 52 | |
| 53 | // keysInBytes is every family a Yjs update names. Yjs writes a |
| 54 | // formatting attribute's key as plain UTF-8, so "font_<key>" is in the |
| 55 | // bytes of any update that sets it. A false positive costs one download. |
| 56 | export function keysInBytes(bytes) { |
| 57 | if (!bytes || !bytes.length) return [] |
| 58 | let text = '' |
| 59 | for (let i = 0; i < bytes.length; i += 0x8000) { |
| 60 | text += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)) |
| 61 | } |
| 62 | const keys = FAMILIES.filter((f) => text.includes('font_' + f.key)).map((f) => f.key) |
| 63 | // A node or mark that names no family can still bring one in: the code |
| 64 | // mark and the code block are the code family's. The editor fills this |
| 65 | // in from its schema (schema.mjs), so a node added there is covered. |
| 66 | for (const [name, key] of implicitFamilies) { |
| 67 | if (text.includes(name) && !keys.includes(key)) keys.push(key) |
| 68 | } |
| 69 | return keys |
| 70 | } |
| 71 | |
| 72 | // implicitFamilies is every schema node or mark name whose text is in a |
| 73 | // family it does not name; setImplicitFamilies replaces it. |
| 74 | const implicitFamilies = new Map([['code', CODE_FONT]]) |
| 75 | export function setImplicitFamilies(entries) { |
| 76 | implicitFamilies.clear() |
| 77 | for (const [name, key] of entries) implicitFamilies.set(name, key) |
| 78 | } |
| 79 | |
| 80 | // faceURLs reads every Docs face's file off the page's @font-face rules, |
| 81 | // as "family|weight|style" -> URL, for prefetch. The stylesheet is the |
| 82 | // one place the hashed file names are written. |
| 83 | export function faceURLs(styleSheets) { |
| 84 | const out = new Map() |
| 85 | const weights = { normal: '400', bold: '700' } |
| 86 | for (const sheet of styleSheets) { |
| 87 | let rules |
| 88 | try { |
| 89 | rules = sheet.cssRules |
| 90 | } catch { |
| 91 | continue |
| 92 | } |
| 93 | for (const rule of rules || []) { |
| 94 | if (!rule.style || !String(rule.cssText || '').startsWith('@font-face')) continue |
| 95 | const family = rule.style.getPropertyValue('font-family').trim().replace(/^["']|["']$/g, '') |
| 96 | const src = /url\(\s*["']?([^"')]+)["']?\s*\)/.exec(rule.style.getPropertyValue('src')) |
| 97 | if (!family.startsWith('Docs ') || !src) continue |
| 98 | const w = rule.style.getPropertyValue('font-weight').trim() || '400' |
| 99 | const st = rule.style.getPropertyValue('font-style').trim() || 'normal' |
| 100 | out.set(family + '|' + (weights[w] || w) + '|' + st, new URL(src[1], sheet.href || location.href).href) |
| 101 | } |
| 102 | } |
| 103 | return out |
| 104 | } |
| 105 | |
| 106 | function delay(ms, setTimer) { |
| 107 | return new Promise((resolve) => setTimer(() => resolve('late'), ms)) |
| 108 | } |
| 109 | |
| 110 | export function createFontSession({ fontSet, root, setTimer = setTimeout } = {}) { |
| 111 | const faces = new Map() // "key|weight|style" -> { state, promise } |
| 112 | const committed = new Set() |
| 113 | // inUse is every family that is, or may be, on screen: what the page |
| 114 | // was gated on, the default, and whatever a pick, a paste or a |
| 115 | // collaborator has brought in since. |
| 116 | const inUse = new Set([DEFAULT_FONT]) |
| 117 | let shown = false |
| 118 | let previews = 'pending' |
| 119 | |
| 120 | function setFallbackAttr() { |
| 121 | if (!root) return |
| 122 | const value = [...committed].sort().join(' ') |
| 123 | if (root.getAttribute('data-docs-fonts-fallback') !== value) root.setAttribute('data-docs-fonts-fallback', value) |
| 124 | } |
| 125 | |
| 126 | // commit refuses a family that is on screen in its web face: changing |
| 127 | // it would move text a reader is looking at. |
| 128 | function commit(keys) { |
| 129 | let changed = false |
| 130 | for (const k of keys) { |
| 131 | if (committed.has(k) || (shown && inUse.has(k) && !committed.has(k))) continue |
| 132 | committed.add(k) |
| 133 | changed = true |
| 134 | } |
| 135 | if (changed) setFallbackAttr() |
| 136 | } |
| 137 | |
| 138 | // loadFace resolves to whether one face loaded. A rejection or an |
| 139 | // empty result is a failure, which is final too. |
| 140 | function loadFace(spec) { |
| 141 | const id = spec.family + '|' + spec.weight + '|' + spec.style |
| 142 | let f = faces.get(id) |
| 143 | if (f) return f.promise |
| 144 | f = { state: 'pending' } |
| 145 | f.promise = Promise.resolve() |
| 146 | .then(() => fontSet.load(shorthand(spec.family, spec))) |
| 147 | .then((got) => (Array.isArray(got) ? got.length > 0 : !!got), () => false) |
| 148 | .then((ok) => { |
| 149 | f.state = ok ? 'loaded' : 'failed' |
| 150 | return ok |
| 151 | }) |
| 152 | faces.set(id, f) |
| 153 | return f.promise |
| 154 | } |
| 155 | |
| 156 | // faceSpec is the face a run in key, bold and italic is drawn in: the |
| 157 | // same fallback internal/fonts' Family.Face makes for a family with no |
| 158 | // italic. |
| 159 | function faceSpec(key, bold, italic) { |
| 160 | const all = specsOf(key) |
| 161 | const want = (b, i) => all.find((s) => (s.weight === 700) === b && (s.style === 'italic') === i) |
| 162 | return want(bold, italic) || want(bold, false) || want(false, false) || all[0] |
| 163 | } |
| 164 | |
| 165 | function specsOf(key) { |
| 166 | const f = family(key) |
| 167 | return f ? f.faces.map((s) => ({ family: f.cssName, ...s })) : [] |
| 168 | } |
| 169 | |
| 170 | // settle loads all of a family's faces and resolves once none is |
| 171 | // pending, to whether all of them loaded. |
| 172 | function settle(key) { |
| 173 | if (committed.has(key)) return Promise.resolve(false) |
| 174 | return Promise.all(specsOf(key).map(loadFace)).then((all) => all.every(Boolean)) |
| 175 | } |
| 176 | |
| 177 | function isSettled(key) { |
| 178 | if (committed.has(key)) return true |
| 179 | return specsOf(key).every((s) => { |
| 180 | const f = faces.get(s.family + '|' + s.weight + '|' + s.style) |
| 181 | return f && f.state !== 'pending' |
| 182 | }) |
| 183 | } |
| 184 | |
| 185 | const session = { |
| 186 | // ready is whether text in this family can be painted now and stay |
| 187 | // as it is: every face settled, or the family committed. |
| 188 | ready: (key) => isSettled(key), |
| 189 | loaded(key) { |
| 190 | return !committed.has(key) && specsOf(key).every((s) => (faces.get(s.family + '|' + s.weight + '|' + s.style) || {}).state === 'loaded') |
| 191 | }, |
| 192 | committed: (key) => committed.has(key), |
| 193 | get fallback() { |
| 194 | return [...committed].sort() |
| 195 | }, |
| 196 | get inUse() { |
| 197 | return [...inUse] |
| 198 | }, |
| 199 | use(keys) { |
| 200 | for (const k of keys) if (family(k)) inUse.add(k) |
| 201 | }, |
| 202 | // required is every family any change to the document may paint |
| 203 | // in: the families in use (the page's, and every one brought in |
| 204 | // since) and the default. A change naming another (code's, a |
| 205 | // font_* mark) adds it. |
| 206 | required(extra = []) { |
| 207 | return [...new Set([...inUse, DEFAULT_FONT, ...extra])].filter((k) => family(k)) |
| 208 | }, |
| 209 | markShown() { |
| 210 | shown = true |
| 211 | }, |
| 212 | get shown() { |
| 213 | return shown |
| 214 | }, |
| 215 | |
| 216 | // gate waits for the faces the page shows (fontgate.go's list), until |
| 217 | // the deadline; families still missing then are committed, which is |
| 218 | // safe because nothing is on screen yet. Resolves 'ok' or 'late'. |
| 219 | async gate(need, deadlineMs) { |
| 220 | const docFaces = need.filter((f) => f.key !== 'previews') |
| 221 | const previewFaces = need.filter((f) => f.key === 'previews') |
| 222 | for (const f of docFaces) inUse.add(f.key) |
| 223 | const results = new Map() |
| 224 | const docs = Promise.all(docFaces.map((spec) => loadFace(spec).then((ok) => results.set(spec, ok)))) |
| 225 | const prevs = Promise.all(previewFaces.map((spec) => loadFace(spec).then((ok) => results.set(spec, ok)))) |
| 226 | const timer = delay(deadlineMs, setTimer) |
| 227 | const outcome = await Promise.race([docs.then(() => 'ok'), timer]) |
| 228 | const missing = new Set(docFaces.filter((s) => results.get(s) !== true).map((s) => s.key)) |
| 229 | commit([...missing]) |
| 230 | // The previews have their own state and their own wait, so a slow |
| 231 | // preview never holds the paper back. |
| 232 | session.previewsDone = Promise.race([prevs.then(() => 'ok'), timer]).then(() => { |
| 233 | previews = previewFaces.every((s) => results.get(s) === true) ? 'web' : 'system' |
| 234 | return previews |
| 235 | }) |
| 236 | return outcome === 'ok' && missing.size === 0 ? 'ok' : 'late' |
| 237 | }, |
| 238 | previewsDone: Promise.resolve('system'), |
| 239 | get previews() { |
| 240 | return previews |
| 241 | }, |
| 242 | set previews(v) { |
| 243 | previews = v |
| 244 | }, |
| 245 | |
| 246 | // prepare is a collaborator's change or a paste: everything it could |
| 247 | // paint in settles first. A family it introduces that is not on |
| 248 | // screen gets NEW_FAMILY_TIMEOUT_MS and is then committed; families |
| 249 | // already on screen are waited for, because committing them would |
| 250 | // change text in view. |
| 251 | async prepare(newKeys = [], { timeout = NEW_FAMILY_TIMEOUT_MS } = {}) { |
| 252 | const fresh = [...new Set(newKeys)].filter((k) => family(k) && !inUse.has(k)) |
| 253 | const known = session.required().filter((k) => !fresh.includes(k)) |
| 254 | await Promise.all([ |
| 255 | ...known.map(settle), |
| 256 | ...fresh.map(async (k) => { |
| 257 | if ((await Promise.race([settle(k), delay(timeout, setTimer)])) === 'late') commit([k]) |
| 258 | }), |
| 259 | ]) |
| 260 | for (const k of fresh) inUse.add(k) |
| 261 | }, |
| 262 | prepareRemote(bytes, opts) { |
| 263 | return session.prepare(keysInBytes(bytes), opts) |
| 264 | }, |
| 265 | |
| 266 | // waitFor resolves true once every face of every key has settled, or |
| 267 | // false at the timeout, committing nothing. Commands use it. |
| 268 | async waitFor(keys, timeout = COMMAND_TIMEOUT_MS) { |
| 269 | if (keys.every(isSettled)) return true |
| 270 | const all = Promise.all(keys.map(settle)).then(() => true) |
| 271 | return (await Promise.race([all, delay(timeout, setTimer)])) === true |
| 272 | }, |
| 273 | |
| 274 | // commitFallback draws families in their fallback for the rest of the |
| 275 | // visit, unless one is on screen in its web face. The editor uses it |
| 276 | // for the one change it never makes wait: an IME composition. |
| 277 | commitFallback(keys) { |
| 278 | commit(keys) |
| 279 | return keys.every((k) => committed.has(k)) |
| 280 | }, |
| 281 | |
| 282 | // prefetch brings every family's faces into the tab once the page is |
| 283 | // shown and idle (branch review 7), so that a pick, a paste or a |
| 284 | // collaborator's font is ready before anyone asks for it. One face at |
| 285 | // a time: idle() resolves when the page is idle, fetchFn fetches a |
| 286 | // file at low priority into the HTTP cache, and the face is then |
| 287 | // loaded from there. It never commits anything, and a face whose |
| 288 | // fetch fails is left alone for an action to load when it needs it. |
| 289 | // urls maps "family|weight|style" to the file (faceURLs). |
| 290 | async prefetch({ keys, urls, fetchFn, idle = () => Promise.resolve() }) { |
| 291 | for (const k of keys) { |
| 292 | for (const spec of specsOf(k)) { |
| 293 | const id = spec.family + '|' + spec.weight + '|' + spec.style |
| 294 | if (committed.has(k) || faces.has(id)) continue |
| 295 | await idle() |
| 296 | if (committed.has(k) || faces.has(id)) continue |
| 297 | const url = urls.get(id) |
| 298 | if (!url) continue |
| 299 | let ok = false |
| 300 | try { |
| 301 | ok = await fetchFn(url) |
| 302 | } catch { |
| 303 | ok = false |
| 304 | } |
| 305 | if (ok) await loadFace(spec) |
| 306 | } |
| 307 | } |
| 308 | }, |
| 309 | |
| 310 | // load is a pick's: all four faces, then whether all of them loaded. |
| 311 | // A committed family is usable (it draws in its fallback, stably). |
| 312 | async load(key) { |
| 313 | if (committed.has(key)) return true |
| 314 | const ok = await settle(key) |
| 315 | if (ok) inUse.add(key) |
| 316 | return ok |
| 317 | }, |
| 318 | } |
| 319 | return session |
| 320 | } |
| 321 | |
| 322 | // createSystemSession is the session for a page whose web faces are not |
| 323 | // on (no hold, or the fail-safe showed it): everything is in its system |
| 324 | // face for the visit, so there is nothing to load and nothing to wait |
| 325 | // for. |
| 326 | export function createSystemSession(root) { |
| 327 | const yes = () => true |
| 328 | return { |
| 329 | web: false, |
| 330 | ready: yes, |
| 331 | loaded: yes, |
| 332 | committed: () => false, |
| 333 | fallback: [], |
| 334 | inUse: [], |
| 335 | use() {}, |
| 336 | required: () => [], |
| 337 | markShown() {}, |
| 338 | shown: true, |
| 339 | previews: 'system', |
| 340 | previewsDone: Promise.resolve('system'), |
| 341 | prepare: async () => {}, |
| 342 | prepareRemote: async () => {}, |
| 343 | waitFor: async () => true, |
| 344 | load: async () => true, |
| 345 | commitFallback: () => true, |
| 346 | prefetch: async () => {}, |
| 347 | fontsReady: Promise.resolve(), |
| 348 | // Called by the editor once it has paginated. If the page is still |
| 349 | // held (the hold ran, the gate never did), the editor shows it: in |
| 350 | // its system faces, already paginated. |
| 351 | settled() { |
| 352 | if (!root || root.getAttribute('data-docs-fonts') !== 'pending') return |
| 353 | clearTimeout(globalThis.__docsFontsHold) |
| 354 | root.setAttribute('data-docs-fonts', 'shown') |
| 355 | if (root.getAttribute('data-docs-previews') === 'pending') root.setAttribute('data-docs-previews', 'system') |
| 356 | }, |
| 357 | } |
| 358 | } |
| 359 | |