oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/font-session.test.mjs — the font session, against a fake
2// FontFaceSet whose loads resolve by hand, so a test can hold one open
3// and watch what is (and is not) applied while it waits.
4import { test } from 'node:test'
5import assert from 'node:assert/strict'
6import { createFontSession, createSystemSession, faceURLs, keysInBytes, shorthand } from './font-session.mjs'
7import { fontStatus } from './font-status.mjs'
8
9function fakeFonts() {
10 const loads = []
11 return {
12 loads,
13 load(font) {
14 let resolve, reject
15 const p = new Promise((res, rej) => { resolve = res; reject = rej })
16 loads.push({ font, ok: () => resolve([{}]), fail: () => reject(new Error('network')), done: false })
17 return p
18 },
19 // settle resolves every load still open whose CSS mentions match.
20 settle(match, ok = true) {
21 for (const l of loads.filter((l) => !l.done && l.font.includes(match))) {
22 l.done = true
23 ;(ok ? l.ok : l.fail)()
24 }
25 },
26 open(match) {
27 return loads.filter((l) => !l.done && l.font.includes(match)).length
28 },
29 }
30}
31
32function fakeRoot() {
33 const attrs = {}
34 return { attrs, getAttribute: (n) => attrs[n] ?? null, setAttribute: (n, v) => { attrs[n] = v } }
35}
36
37function fakeTimers() {
38 const due = []
39 return { setTimer: (fn, ms) => due.push({ fn, ms }), fire: () => due.splice(0).forEach((t) => t.fn()), due }
40}
41
42const tick = async (n = 5) => { for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r)) }
43const bytes = (s) => new TextEncoder().encode(s)
44const face = (key, family, weight = 400, style = 'normal') => ({ key, family, weight, style })
45
46test('the CSS a face is loaded by', () => {
47 assert.equal(shorthand('Docs Carlito', { weight: 700, style: 'italic' }), 'italic 700 16px "Docs Carlito"')
48 assert.equal(shorthand('Docs Carlito', { weight: 400, style: 'normal' }), '400 16px "Docs Carlito"')
49})
50
51test('the gate waits for the faces the page needs, and commits what misses the deadline', async () => {
52 const fontSet = fakeFonts()
53 const root = fakeRoot()
54 const timers = fakeTimers()
55 const session = createFontSession({ fontSet, root, setTimer: timers.setTimer })
56 const need = [face('carlito', 'Docs Carlito'), face('carlito', 'Docs Carlito', 700), face('inter', 'Docs Inter')]
57 let outcome = null
58 session.gate(need, 2500).then((o) => { outcome = o })
59 await tick()
60 fontSet.settle('Docs Carlito')
61 await tick()
62 assert.equal(outcome, null, 'the gate let go with Inter still loading')
63 timers.fire()
64 await tick()
65 assert.equal(outcome, 'late')
66 assert.equal(root.attrs['data-docs-fonts-fallback'], 'inter', 'Inter must be committed: nothing is on screen yet')
67 fontSet.settle('Docs Inter')
68 await tick()
69 assert.equal(root.attrs['data-docs-fonts-fallback'], 'inter', 'a late arrival changes nothing')
70})
71
72test('the previews have their own wait and never hold the paper', async () => {
73 const fontSet = fakeFonts()
74 const session = createFontSession({ fontSet, root: fakeRoot(), setTimer: () => {} })
75 const need = [face('carlito', 'Docs Carlito'), face('previews', 'Docs Preview 01')]
76 const outcome = session.gate(need, 2500)
77 await tick()
78 fontSet.settle('Docs Carlito')
79 assert.equal(await outcome, 'ok', 'the paper waited for a preview')
80 assert.equal(session.previews, 'pending')
81 fontSet.settle('Docs Preview')
82 assert.equal(await session.previewsDone, 'web')
83})
84
85// Review finding 2: a family on screen is never committed. Carlito
86// regular is showing; its bold is slow; a command waiting for the bold
87// gives up and nothing is committed.
88test('a family on screen is never committed, whatever is late', async () => {
89 const fontSet = fakeFonts()
90 const root = fakeRoot()
91 const timers = fakeTimers()
92 const session = createFontSession({ fontSet, root, setTimer: timers.setTimer })
93 const gated = session.gate([face('carlito', 'Docs Carlito')], 2500)
94 await tick()
95 fontSet.settle('400 16px "Docs Carlito"')
96 await gated
97 session.markShown()
98 const waited = session.waitFor(['carlito'], 4000)
99 await tick()
100 timers.fire()
101 assert.equal(await waited, false, 'the command must give up')
102 assert.equal(root.attrs['data-docs-fonts-fallback'] ?? '', '', 'Carlito was committed while on screen')
103 // And a collaborator's change naming nothing waits for it rather than
104 // committing it.
105 let applied = false
106 session.prepareRemote(bytes('strong')).then(() => { applied = true })
107 await tick()
108 timers.fire()
109 await tick()
110 assert.equal(applied, false, 'the change was let through with Carlito bold still pending')
111 assert.equal(root.attrs['data-docs-fonts-fallback'] ?? '', '')
112 fontSet.settle('Docs Carlito')
113 fontSet.settle('Docs Liberation Mono')
114 await tick(10)
115 assert.ok(applied)
116})
117
118// Review finding 1: a change that names no font can still bring in a
119// face: code is Liberation Mono. It waits for it.
120test('a collaborator\'s change waits for the code face though it names no font', async () => {
121 const fontSet = fakeFonts()
122 const session = createFontSession({ fontSet, root: fakeRoot(), setTimer: () => {} })
123 let applied = false
124 const done = session.prepareRemote(bytes('\u0004code\u0000hello')).then(() => { applied = true })
125 await tick()
126 fontSet.settle('Docs Carlito')
127 await tick()
128 assert.equal(applied, false, 'applied with Liberation Mono still loading')
129 fontSet.settle('Docs Liberation Mono')
130 await done
131 assert.ok(applied)
132})
133
134test('a family a change introduces waits, and is committed if it is not on screen and late', async () => {
135 const fontSet = fakeFonts()
136 const root = fakeRoot()
137 const timers = fakeTimers()
138 const session = createFontSession({ fontSet, root, setTimer: timers.setTimer })
139 session.markShown()
140 let applied = false
141 const done = session.prepareRemote(bytes('font_caveat'), { timeout: 3000 }).then(() => { applied = true })
142 await tick()
143 fontSet.settle('Docs Carlito')
144 fontSet.settle('Docs Liberation Mono')
145 await tick()
146 assert.equal(applied, false)
147 timers.fire()
148 await done
149 assert.equal(root.attrs['data-docs-fonts-fallback'], 'caveat')
150 assert.ok(session.inUse.includes('caveat'))
151})
152
153test('the byte scan finds every family a Yjs update names', () => {
154 assert.deepEqual(keysInBytes(bytes('xx font_inter yy font_sans zz')).sort(), ['inter', 'sans'])
155 assert.deepEqual(keysInBytes(new Uint8Array([])), [])
156 assert.deepEqual(keysInBytes(bytes('font_notosans')), ['notosans'])
157})
158
159// Review finding 4: with no gate, the editor shows a held page itself
160// once it has paginated, in the system faces.
161test('without the gate, the editor shows the held page in its system faces', () => {
162 const root = fakeRoot()
163 root.setAttribute('data-docs-fonts', 'pending')
164 root.setAttribute('data-docs-previews', 'pending')
165 const session = createSystemSession(root)
166 assert.equal(session.web, false)
167 assert.ok(session.ready('inter'))
168 session.settled()
169 assert.equal(root.attrs['data-docs-fonts'], 'shown')
170 assert.equal(root.attrs['data-docs-previews'], 'system')
171 assert.equal(root.attrs['data-docs-faces'], undefined, 'the web faces were turned on')
172})
173
174// A stylesheet as the browser exposes one: @font-face rules with their
175// descriptors, and one ordinary rule.
176function fakeSheet(href, faces) {
177 const rule = (family, src, weight, style) => ({
178 cssText: '@font-face { font-family: "' + family + '"; }',
179 style: { getPropertyValue: (p) => ({ 'font-family': '"' + family + '"', src: 'url("' + src + '") format("woff2")', 'font-weight': weight, 'font-style': style })[p] || '' },
180 })
181 return { href, cssRules: [{ cssText: 'p { color: red }', style: { getPropertyValue: () => '' } }, ...faces.map((f) => rule(...f))] }
182}
183
184test('faceURLs reads every Docs face off the stylesheet, by family, weight and style', () => {
185 const urls = faceURLs([
186 fakeSheet('https://docs.example/static/fonts.css', [
187 ['Docs Inter', '/static/fonts/Inter-Regular.woff2', '400', 'normal'],
188 ['Docs Inter', '/static/fonts/Inter-BoldItalic.woff2', 'bold', 'italic'],
189 ['Onest', '/static/onest.woff2', '400', 'normal'],
190 ]),
191 { href: 'https://elsewhere.example/x.css', get cssRules() { throw new Error('cross-origin') } },
192 ])
193 assert.deepEqual([...urls], [
194 ['Docs Inter|400|normal', 'https://docs.example/static/fonts/Inter-Regular.woff2'],
195 ['Docs Inter|700|italic', 'https://docs.example/static/fonts/Inter-BoldItalic.woff2'],
196 ])
197})
198
199test('prefetch fetches each face when idle, then loads it from the cache, and never commits', async () => {
200 const fontSet = fakeFonts()
201 const root = fakeRoot()
202 const session = createFontSession({ fontSet, root })
203 const urls = new Map([
204 ['Docs Inter|400|normal', 'u/inter-r'], ['Docs Inter|700|normal', 'u/inter-b'],
205 ['Docs Inter|400|italic', 'u/inter-i'], ['Docs Inter|700|italic', 'u/inter-bi'],
206 ])
207 const fetched = []
208 let idles = 0
209 const failing = new Set(['u/inter-bi'])
210 const run = session.prefetch({
211 keys: ['inter'],
212 urls,
213 idle: async () => { idles++ },
214 fetchFn: async (u) => { fetched.push(u); return !failing.has(u) },
215 })
216 for (let i = 0; i < 4; i++) {
217 await tick(10)
218 fontSet.settle('Docs Inter')
219 }
220 await run
221 assert.deepEqual(fetched, ['u/inter-r', 'u/inter-b', 'u/inter-i', 'u/inter-bi'])
222 assert.equal(idles, 4, 'one idle wait per face')
223 // The face whose fetch failed is not loaded through the font set: an
224 // action loads it when it needs it.
225 assert.equal(fontSet.loads.length, 3)
226 assert.equal(session.ready('inter'), false)
227 assert.deepEqual(session.fallback, [])
228})
229
230test('prefetch leaves a family alone once an action is loading it, and a wait shares the load', async () => {
231 const fontSet = fakeFonts()
232 const session = createFontSession({ fontSet, root: fakeRoot() })
233 const urls = new Map([['Docs Caveat|400|normal', 'u/caveat-r'], ['Docs Caveat|700|normal', 'u/caveat-b']])
234 let finishFetch
235 const fetched = []
236 const run = session.prefetch({ keys: ['caveat'], urls, fetchFn: (u) => { fetched.push(u); return new Promise((r) => (finishFetch = r)) } })
237 await tick()
238 // An action needs Caveat while the prefetch is still fetching it.
239 let waited = null
240 session.waitFor(['caveat'], 4000).then((ok) => { waited = ok })
241 await tick()
242 assert.equal(fontSet.open('Docs Caveat'), 2, 'the action loads both faces now')
243 finishFetch(true)
244 await tick()
245 fontSet.settle('Docs Caveat')
246 await run
247 await tick()
248 assert.equal(waited, true)
249 assert.equal(fontSet.loads.length, 2, 'the prefetch did not load a face the action was loading')
250 assert.deepEqual(fetched, ['u/caveat-r'], 'nor fetch the next once the action had it')
251})
252
253test('commitFallback commits a family that is not on screen, and refuses one that is', () => {
254 const session = createFontSession({ fontSet: fakeFonts(), root: fakeRoot() })
255 session.use(['inter'])
256 session.markShown()
257 assert.equal(session.commitFallback(['caveat']), true)
258 assert.equal(session.commitFallback(['inter']), false)
259 assert.deepEqual(session.fallback, ['caveat'])
260})
261
262// A fake [docs-fonts-status]: data-* copy, a text element and a button.
263function fakeStatus() {
264 const attrs = { 'data-loading': 'Loading a font…', 'data-refused': 'Refused.', 'data-unavailable': 'Unavailable.', 'data-substitute': 'Substitutes.' }
265 const text = { textContent: '' }
266 const clicks = []
267 const button = { addEventListener: (_, fn) => clicks.push(fn) }
268 const el = {
269 getAttribute: (n) => attrs[n] ?? null,
270 setAttribute: (n, v) => { attrs[n] = v },
271 removeAttribute: (n) => { delete attrs[n] },
272 querySelector: (q) => (q === '[docs-fonts-status-text]' ? text : button),
273 }
274 return { el, text, attrs, click: () => clicks.forEach((f) => f()) }
275}
276
277test('the status strip says one thing at a time, and a timed note does not clear a later one', () => {
278 const s = fakeStatus()
279 const timers = fakeTimers()
280 const gate = fontStatus(s.el, { setTimer: timers.setTimer, clearTimer: () => {} })
281 const editor = fontStatus(s.el, { setTimer: () => {}, clearTimer: () => {} })
282 gate.say('substitute', 10000)
283 assert.equal(s.text.textContent, 'Substitutes.')
284 editor.say('loading')
285 assert.equal(editor.state, 'loading')
286 timers.fire()
287 assert.equal(s.text.textContent, 'Loading a font…', "the substitutes note's timer leaves the loading note alone")
288 editor.clear()
289 assert.equal(s.text.textContent, '')
290 assert.equal(s.attrs['data-state'], undefined)
291 editor.say('unavailable', 8000)
292 s.click()
293 assert.equal(gate.state, '', 'dismissed')
294})
295