oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/font-session.mjs — which of the deck's font families this tab
2// has, and the one rule every path to a slide goes through: slide text
3// is never painted in a face it will later leave (Paul, 2026-10-26: "No
4// flashing, ever!"). Docs' font-session.mjs is the model; Slides has
5// three families and no stylesheet that declares them, which makes the
6// rule simpler to keep.
7//
8// No stylesheet declares a web face (fontgate.go). A family exists for
9// the page only once this session has loaded all four of its faces and
10// added them to document.fonts, together. Until then every stack that
11// names it falls through to the system faces after it. So:
12//
13// - a face that is loading is never drawn: it is not in the set;
14// - a family is never half on: its four faces join the set in one go,
15// so a bold run can never be drawn in a fallback bold beside a web
16// regular;
17// - a family that is committed to its fallback never joins the set,
18// so when its files arrive late nothing can swap into them.
19//
20// A family is idle, loading, loaded, failed or committed. Loaded,
21// failed and committed are final. Text may be drawn in a family that is
22// loaded (and then it is added) or committed (and then it stays in its
23// system face); "ready" means one of the two. Failed is final but not
24// ready: a person's own action that needs a failed family is refused,
25// because applying it in a substitute would be a lie about what they
26// chose. Only content from elsewhere (the page itself, a collaborator,
27// the projector's next slide) commits a family that will not load.
28//
29// "Commit" is only ever for a family that is not on screen in its web
30// face; one that is never changes.
31//
32// No DOM beyond what is passed in: font-session.test.mjs drives it in
33// Node with a fake FontFace and FontFaceSet.
34
35import { FAMILY_KEYS, uploadedFamily } from './font-families.mjs'
36
37export { createSystemSession } from './font-system-session.mjs'
38
39// The gate shows the slides at this deadline whatever has arrived,
40// having committed what has not. Measured from navigation start, and
41// under the three seconds a browser holds font-display: block, so even
42// a browser that ignored all of this would not have swapped yet.
43export const GATE_DEADLINE_MS = 2500
44
45// Content from elsewhere — a collaborator's change, a slide the server
46// rendered, the projector's next slide — waits this long for a family
47// that is not on screen, then commits it to its fallback. It is never
48// held back for longer, and never dropped.
49export const NEW_FAMILY_TIMEOUT_MS = 3000
50
51// A person's own action waits this long for its family, then is
52// refused and changes nothing.
53export const ACTION_TIMEOUT_MS = 4000
54
55function delay (ms, setTimer) {
56 return new Promise(resolve => setTimer(() => resolve('late'), ms))
57}
58
59/**
60 * The session for a page whose gate is running. manifest is the
61 * server's (<meta name="slides-fonts">, fontgate.go); fontSet is
62 * document.fonts; FontFaceCtor is window.FontFace; root is <html>, on
63 * which the committed families are written as data-slides-fonts-fallback
64 * for the tests and for anyone reading the page.
65 */
66export function createFontSession ({ manifest, fontSet, FontFaceCtor, root = null, setTimer = setTimeout } = {}) {
67 const families = new Map() // version (vkey) -> { state, faces, promise, added }
68 const inUse = new Set()
69 let shown = false
70
71 // The deck's own fonts, keyed "u:" + css (fontgate.go's
72 // manifest.uploaded), and any a change brings in during the visit
73 // (learn). They follow every rule the catalog's three do.
74 const uploaded = { ...(manifest && manifest.uploaded) }
75 const isUploaded = key => typeof key === 'string' && key.startsWith('u:')
76 const familyOf = key => (isUploaded(key) ? uploaded[key] : manifest && manifest.families && manifest.families[key])
77 const known = key => !!familyOf(key)
78 const allKeys = () => [...FAMILY_KEYS.filter(known), ...Object.keys(uploaded)]
79
80 // An uploaded family is known by its name AND its set of faces: a
81 // family that gains a bold face is, to this tab, a new family under an
82 // old name (final review, I4). Its state lives under its version, the
83 // key and the set together, so the set on the page is never taken for
84 // one that has not loaded, and a set loaded once (undo, redo) is
85 // ready again at once.
86 const facesOf = fam => fam.faces.map(f => [f.url, f.weight, f.style, f.format].join(' ')).join('\n')
87 const vkey = key => (isUploaded(key) && uploaded[key] ? key + '\n' + facesOf(uploaded[key]) : key)
88 const stateOf = key => families.get(vkey(key))
89 const committedKeys = () => allKeys().filter(k => stateOf(k) && stateOf(k).state === 'committed')
90 const entry = key => {
91 const v = vkey(key)
92 let e = families.get(v)
93 if (!e) {
94 e = { state: 'idle', faces: [], promise: null, added: false }
95 families.set(v, e)
96 }
97 return e
98 }
99
100 function writeFallback () {
101 if (!root) return
102 const value = committedKeys().join(' ')
103 if ((root.getAttribute('data-slides-fonts-fallback') || '') !== value) root.setAttribute('data-slides-fonts-fallback', value)
104 }
105
106 // load starts (once) the four faces of a family and resolves to
107 // whether all four loaded. It adds nothing to the page: use() does.
108 // The name goes in as it is, never quoted: FontFace takes its family
109 // literally, so quotes would become part of the name and no stack
110 // would match it. Each face carries its own format (a catalog face is
111 // woff2) and weight, which for a variable face is its range
112 // ("100 900").
113 function load (key) {
114 if (!known(key)) return Promise.resolve(false)
115 const e = entry(key)
116 if (e.state === 'committed') return Promise.resolve(false)
117 if (e.promise) return e.promise
118 const fam = familyOf(key)
119 e.state = 'loading'
120 e.promise = Promise.resolve()
121 .then(() => {
122 e.faces = fam.faces.map(f => new FontFaceCtor(fam.css, `url("${f.url}") format("${f.format || 'woff2'}")`, {
123 weight: String(f.weight),
124 style: f.style,
125 display: 'block'
126 }))
127 return Promise.all(e.faces.map(face => face.load().then(() => true, () => false)))
128 })
129 .then(all => all.every(Boolean), () => false)
130 .then(ok => {
131 if (e.state === 'loading') e.state = ok ? 'loaded' : 'failed'
132 return e.state === 'loaded'
133 })
134 return e.promise
135 }
136
137 const isReady = key => {
138 if (!known(key)) return true
139 const s = stateOf(key) ? stateOf(key).state : 'idle'
140 return s === 'loaded' || s === 'committed'
141 }
142
143 // onPage is another set of the uploaded family key that is on the
144 // page, if one is.
145 const onPage = key => {
146 if (!isUploaded(key)) return null
147 for (const [v, e] of families) if (e.added && v.startsWith(key + '\n') && v !== vkey(key)) return e
148 return null
149 }
150
151 // commit draws a family in its fallback for the rest of the visit,
152 // unless it is already on screen in its web face. A new set of an
153 // uploaded family committed while an older set is on the page leaves
154 // that set where it is: the page does not move.
155 function commit (keys) {
156 for (const k of keys) {
157 if (!known(k)) continue
158 const e = entry(k)
159 if (e.added || e.state === 'committed') continue
160 e.state = 'committed'
161 }
162 writeFallback()
163 }
164
165 // use puts families on screen: a loaded one's faces join the set, all
166 // four at once, and a committed one stays in its system face. Callers
167 // only use families that are ready. An uploaded family's loaded set
168 // goes on in place of any other set of it on the page, in the same
169 // task, so the text in it never has a frame without its faces.
170 function use (keys) {
171 for (const k of keys) {
172 if (!known(k)) continue
173 const e = entry(k)
174 if (e.state === 'loaded' && !e.added) {
175 const old = onPage(k)
176 if (old) {
177 for (const face of old.faces) if (typeof fontSet.delete === 'function') fontSet.delete(face)
178 old.added = false
179 }
180 for (const face of e.faces) fontSet.add(face)
181 e.added = true
182 }
183 if (e.state === 'loaded' || e.state === 'committed') inUse.add(k)
184 }
185 }
186
187 function adopt (fam) {
188 const key = 'u:' + fam.css
189 if (!uploaded[key] || facesOf(uploaded[key]) !== facesOf(fam)) uploaded[key] = fam
190 }
191
192 const session = {
193 web: true,
194 get manifest () { return manifest },
195 ready: isReady,
196 loaded: key => known(key) && !!stateOf(key) && stateOf(key).state === 'loaded',
197 committed: key => known(key) && !!stateOf(key) && stateOf(key).state === 'committed',
198 failed: key => known(key) && !!stateOf(key) && stateOf(key).state === 'failed',
199 state: key => (stateOf(key) ? stateOf(key).state : 'idle'),
200 get inUse () { return [...inUse] },
201 get fallback () { return committedKeys() },
202 // Every family this page can load: the catalog's, then the deck's own.
203 get keys () { return allKeys() },
204 get uploaded () { return uploaded },
205 // learn takes in the families of a deck's meta.fontFiles (a pick, a
206 // collaborator's: editor-fonts.mjs), fetched under base. A family
207 // whose set of faces is new to this tab is that set from now on, not
208 // ready until it loads; a set it has had before keeps its state.
209 learn (fontFiles, base) {
210 for (const f of Array.isArray(fontFiles) ? fontFiles : []) {
211 const fam = uploadedFamily(f, base)
212 if (fam) adopt(fam)
213 }
214 },
215 // learnUploaded is learn for families already in the manifest's
216 // shape (manifest.uploaded: another page's, a talk's), by key.
217 learnUploaded (families) {
218 for (const fam of Object.values(families || {})) if (fam && typeof fam.css === 'string' && Array.isArray(fam.faces)) adopt(fam)
219 },
220 use,
221 load,
222 markShown () { shown = true },
223 get shown () { return shown },
224
225 // gate is the page's first wait: every family the page needs, until
226 // the deadline. A family still not loaded then is committed, which
227 // is safe because nothing is on screen yet; the rest are put on.
228 // Resolves to the families committed.
229 async gate (need, deadlineMs) {
230 const keys = need.filter(known)
231 const all = Promise.all(keys.map(load))
232 await Promise.race([all, delay(deadlineMs, setTimer)])
233 const late = keys.filter(k => !session.loaded(k))
234 commit(late)
235 use(keys)
236 return late
237 },
238
239 // waitFor is a person's own action: it resolves true once every key
240 // has loaded (or was committed before), false if one failed or the
241 // timeout came first. It commits nothing and puts nothing on.
242 async waitFor (keys, timeout = ACTION_TIMEOUT_MS) {
243 const want = keys.filter(known)
244 if (want.every(isReady)) return true
245 const all = Promise.all(want.map(k => (isReady(k) ? true : load(k))))
246 await Promise.race([all, delay(timeout, setTimer)])
247 return want.every(isReady)
248 },
249
250 // prepare is content from elsewhere: every family it needs is made
251 // ready. One already on screen is ready by construction; one that is
252 // not gets the timeout and is then committed. It never rejects and
253 // it always puts the families on, so the content can be shown.
254 async prepare (keys, { timeout = NEW_FAMILY_TIMEOUT_MS } = {}) {
255 const want = [...new Set(keys)].filter(known)
256 const cold = want.filter(k => !isReady(k))
257 if (cold.length) {
258 await Promise.race([Promise.all(cold.map(load)), delay(timeout, setTimer)])
259 commit(cold.filter(k => !session.loaded(k)))
260 }
261 use(want)
262 },
263
264 // commitFallback is for the one change that never waits: an IME
265 // composition. Families not on screen are committed and put on.
266 commitFallback (keys) {
267 commit(keys.filter(k => !isReady(k)))
268 use(keys)
269 },
270
271 // prefetch loads every family not loaded yet, one at a time when the
272 // page is idle, so that an action rarely has to wait. idle() resolves
273 // when the page is idle. It commits nothing and puts nothing on.
274 async prefetch ({ idle = () => Promise.resolve() } = {}) {
275 for (const k of allKeys()) {
276 if (!known(k) || stateOf(k)) continue
277 await idle()
278 if (stateOf(k)) continue
279 await load(k)
280 }
281 }
282 }
283 return session
284}
285