// fixtures/fonts-gate.mjs — shows a document's sheet once its faces are // ready and its layout is final (polish-audit/fonts/NO-FOUT.md §2). // // fonts-hold.js has already set , which // hides the sheet, and data-docs-previews="pending", which hides the font // control. Until this script says so, the stylesheet uses no web face at // all: everything is laid out in its system fallback, hidden. // // 1. Wait for the faces the server listed (data-docs-fonts-need), until // the deadline. A family still missing is committed to its fallback // for the visit; nothing is on screen yet, so nothing moves. // 2. Turn the web faces on (data-docs-faces="web"), still hidden. // 3. On a paged editor page, wait for the editor to paginate in those // faces. If it has not by the layout deadline, freeze the layout // (data-docs-layout="frozen": the editor will not add pages under a // reader for the rest of the visit). // 4. Show the sheet, once. Then, on an editor page, settle every face // of every family in use, which the editor waits for before it lets // anyone type. // // The picker's previews are gated separately and never hold the paper. // // If the hold's fail-safe has already shown the page (this script was // slow), or there was no hold (its script never arrived), the page is in // its system faces and stays there: this turns nothing on. import { createFontSession, createSystemSession, faceURLs, GATE_DEADLINE_MS } from './font-session.mjs' import { fontStatus } from './font-status.mjs' import { FONTS } from './fonts.mjs' // The editor gets this long, from navigation start, to paginate before // the layout is frozen. const LAYOUT_DEADLINE_MS = 3500 const root = document.documentElement const canvas = document.querySelector('[docs-canvas]') const holding = root.getAttribute('data-docs-fonts') === 'pending' if (holding) clearTimeout(globalThis.__docsFontsHold) const session = createFontSession({ fontSet: document.fonts, root }) let settle const editorSettled = new Promise((resolve) => (settle = resolve)) let fontsReady const fontsReadyPromise = new Promise((resolve) => (fontsReady = resolve)) globalThis.docsFonts = Object.assign(session, { // web is whether the web faces are on; when false everything is in its // system face for the visit and there is nothing to load or wait for. web: false, fontsReady: fontsReadyPromise, // The editor's half: called once it has paginated in the final faces, // or failed to mount. settled: () => settle(), }) const after = (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms - performance.now()))) // How long the substitutes note stays, unless dismissed. It sits over // the formatting bar, so it cannot stay for the visit. const SUBSTITUTE_NOTE_MS = 10000 function show() { session.markShown() if (session.fallback.some((k) => k !== 'previews')) { const strip = document.querySelector('[docs-fonts-status]') fontStatus(strip).say('substitute', SUBSTITUTE_NOTE_MS) makeRoom(strip) } if (root.getAttribute('data-docs-fonts') !== 'shown') root.setAttribute('data-docs-fonts', 'shown') } // makeRoom keeps the substitutes note off the text. It hangs under the // bars, over the tray, which is kept tall enough for one line of the // status; where this note wraps to more (a narrow screen, larger text), // the tray is made taller, now, while the page is still hidden, so // nothing moves once it is shown. function makeRoom(strip) { const text = document.querySelector('[docs-text]') if (!strip || !text || !canvas) return const need = Math.ceil(strip.getBoundingClientRect().bottom + 4 - text.getBoundingClientRect().top) if (need > 0) canvas.style.paddingBlockStart = parseFloat(getComputedStyle(canvas).paddingBlockStart) + need + 'px' } // prefetch brings every family the picker offers into the tab after the // page is shown, one face at a time whenever the page is idle and at low // priority, so that choosing, pasting or receiving a font rarely has to // wait (branch review 7). Not on a connection that asks to save data or // is 2G: there the wait is the better cost. About 6 MB, once; the files // are cached. function prefetch() { const c = navigator.connection if (c && (c.saveData || /(^|-)2g$/.test(c.effectiveType || ''))) return const idle = () => new Promise((resolve) => typeof requestIdleCallback === 'function' ? requestIdleCallback(() => resolve(), { timeout: 5000 }) : setTimeout(resolve, 200), ) // A page that is left stops prefetching (a fetch still in flight would // hold a connection from the back/forward cache), and starts again if // it is shown from there. const { signal } = (prefetching = new AbortController()) const fetchFn = (url) => signal.aborted ? Promise.resolve(false) : fetch(url, { priority: 'low', credentials: 'same-origin', signal }).then(async (r) => { if (!r.ok) return false await r.arrayBuffer() return true }) return session.prefetch({ keys: FONTS, urls: faceURLs(document.styleSheets), fetchFn, idle }) } let prefetching = null addEventListener('pagehide', () => prefetching && prefetching.abort()) addEventListener('pageshow', (e) => { if (e.persisted && prefetching) prefetch() }) async function run() { let need = [] try { need = JSON.parse((canvas && canvas.getAttribute('data-docs-fonts-need')) || '[]') } catch { need = [] } await session.gate(need, Math.max(0, GATE_DEADLINE_MS - performance.now())) session.web = true root.setAttribute('data-docs-faces', 'web') session.previewsDone.then((state) => root.setAttribute('data-docs-previews', state)) fontsReady() const editor = document.querySelector('[docs-editor]') if (editor && canvas && canvas.getAttribute('data-view') === 'paged') { const outcome = await Promise.race([editorSettled.then(() => 'paginated'), after(LAYOUT_DEADLINE_MS).then(() => 'late')]) if (outcome === 'late') root.setAttribute('data-docs-layout', 'frozen') } show() if (editor) { await Promise.all(session.required().map((k) => session.load(k))) await prefetch() root.setAttribute('data-docs-fonts-prefetch', 'done') } } if (!holding) { // No hold, or the fail-safe got there first: the system faces, and // the layout already in view, are final. root.setAttribute('data-docs-layout', 'frozen') globalThis.docsFonts = createSystemSession(root) } else { run().catch((err) => { // A gate that fails must not leave the sheet hidden. If the web // faces were never turned on, it shows in its system faces. console.error('fonts:', err) if (root.getAttribute('data-docs-previews') === 'pending') root.setAttribute('data-docs-previews', 'system') fontsReady() show() }) }