oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/fonts-gate.mjs — shows a page's slides once their families
2// are on and their layout is final (fontgate.go; Docs' fonts-gate.mjs,
3// adopted). Built into internal/slides/static/fontsgate.<hash>.js and
4// loaded as a module on every slide surface: the viewer, the projector
5// and the follow view, the editor.
6//
7// fonts-hold.js has already set <html data-slides-fonts="pending">,
8// which hides every slide. No stylesheet declares a web face, so until
9// this script adds one everything is laid out in its system faces,
10// hidden.
11//
12// 1. Load every family the server listed (the manifest's need: the
13// catalog's, and the deck's own uploaded ones its stacks lead
14// with), until the deadline. A family still missing is committed to
15// its fallback for the visit; nothing is on screen yet, so nothing
16// moves. The rest are put on (their faces join document.fonts),
17// still hidden.
18// 2. On the editor, wait for the editor's first mount — its views bound
19// to the slide, the stored viewport applied — which it reports with
20// settled(), until the layout deadline. On the presenter window, wait
21// for the pictures of the slides it opens on (Now and Next) to be
22// decoded, until the same deadline: a slow picture never puts a
23// preview up without it, and a broken one never holds the window.
24// 3. Show the slides, once. On the editor, then bring every other
25// family into the tab at idle, so that an action rarely waits.
26//
27// It leaves the session on globalThis.slidesFonts for the editor bundle
28// and for static/present.js. If the hold's fail-safe has already shown
29// the page (this script was slow), or there was no hold (its script
30// never arrived), the page is in its system faces and stays there: this
31// turns nothing on.
32
33import { createFontSession, createSystemSession, GATE_DEADLINE_MS } from './font-session.mjs'
34import { familiesOfView, familiesOfSection } from './font-families.mjs'
35import { fontStatus } from './font-status.mjs'
36import { mountViewerNav } from './viewer-nav.mjs'
37import { mountScenePages } from './scene-pages.mjs'
38
39// The editor gets this long, from navigation start, to mount before the
40// slides are shown anyway. It will still mount after that, and its first
41// mount moves nothing on a stage that is already in view
42// (editor-entry.js, shownBeforeMount).
43const LAYOUT_DEADLINE_MS = 3500
44
45// The presenter window's first pictures get as long, from navigation
46// start, before its slides are shown anyway (step 2).
47const PICTURES_DEADLINE_MS = LAYOUT_DEADLINE_MS
48
49// How long the substitutes note stays, unless dismissed.
50const SUBSTITUTE_NOTE_MS = 10000
51
52const root = document.documentElement
53const holding = root.getAttribute('data-slides-fonts') === 'pending'
54if (holding) clearTimeout(globalThis.__slidesFontsHold)
55
56let manifest = null
57try {
58 const meta = document.querySelector('meta[name="slides-fonts"]')
59 manifest = meta ? JSON.parse(meta.getAttribute('content') || 'null') : null
60} catch {
61 manifest = null
62}
63
64let settle
65const editorSettled = new Promise(resolve => { settle = resolve })
66let fontsOn
67const fontsReady = new Promise(resolve => { fontsOn = resolve })
68
69const after = ms => new Promise(resolve => setTimeout(resolve, Math.max(0, ms - performance.now())))
70
71function show (session) {
72 session.markShown()
73 if (root.getAttribute('data-slides-fonts') !== 'shown') root.setAttribute('data-slides-fonts', 'shown')
74 if (session.fallback.length) fontStatus(document.querySelector('[slides-fonts-status]')).say('substitute', SUBSTITUTE_NOTE_MS)
75}
76
77// prefetch brings every family the editor could need into the tab once
78// the slides are shown, one at a time when the page is idle. Not on a
79// connection that asks to save data or is 2G: there the wait is the
80// better cost.
81//
82// A page that is left (another page, or into the back/forward cache)
83// starts no more files until it is shown again from that cache: a
84// request from a cached page would hold one of the browser's six
85// connections to this host for nobody (Docs #86, dadf9c1).
86let away = false
87let resume = []
88addEventListener('pagehide', () => { away = true })
89addEventListener('pageshow', e => {
90 if (!e.persisted) return
91 away = false
92 const waiting = resume
93 resume = []
94 for (const r of waiting) r()
95})
96function prefetch (session) {
97 const c = navigator.connection
98 if (c && (c.saveData || /(^|-)2g$/.test(c.effectiveType || ''))) return Promise.resolve()
99 const idle = () => new Promise(resolve =>
100 typeof requestIdleCallback === 'function' ? requestIdleCallback(() => resolve(), { timeout: 5000 }) : setTimeout(resolve, 200))
101 .then(() => (away ? new Promise(resolve => resume.push(resolve)) : undefined))
102 return session.prefetch({ idle })
103}
104
105async function run (session) {
106 await session.gate(manifest.need || [], Math.max(0, GATE_DEADLINE_MS - performance.now()))
107 fontsOn()
108 const editor = document.querySelector('[slides-editor]')
109 if (editor) await Promise.race([editorSettled, after(LAYOUT_DEADLINE_MS)])
110 const presenter = document.querySelector('[presenter]')
111 if (presenter) await Promise.race([picturesOf(presenter), after(PICTURES_DEADLINE_MS)])
112 show(session)
113 if (editor) {
114 await prefetch(session)
115 root.setAttribute('data-slides-fonts-prefetch', 'done')
116 }
117}
118
119// picturesOf resolves once every picture on the presenter window's
120// slides is decoded or has failed.
121function picturesOf (presenter) {
122 const imgs = [...presenter.querySelectorAll('[presenter-panel] [slides-slide] img')]
123 return Promise.all(imgs.map(img => (typeof img.decode === 'function' ? img.decode() : Promise.resolve()).catch(() => {})))
124}
125
126function withHelpers (session) {
127 // The manifest with every uploaded family the session knows, those it
128 // learned during the visit included (font-session.mjs's learn), for
129 // reading a rendered slide.
130 const known = () => ({ ...manifest, uploaded: session.uploaded })
131 return Object.assign(session, {
132 fontsReady,
133 // The editor's half: called once it has mounted in the final faces,
134 // or failed to.
135 settled: () => settle(),
136 familiesOfView: view => (manifest ? familiesOfView(view, manifest) : []),
137 familiesOfSection: html => (manifest ? familiesOfSection(html, known()) : []),
138 // A slide the server rendered, about to go on a stage or a
139 // projector: its families are made ready first (content from
140 // elsewhere — committed, never held back, past the timeout).
141 prepareSection: html => (session.web && manifest ? session.prepare(familiesOfSection(html, known())) : Promise.resolve())
142 })
143}
144
145if (!holding || !manifest || typeof FontFace !== 'function' || !document.fonts) {
146 // No hold, or the fail-safe got there first, or nothing to load with:
147 // the system faces, and the layout already in view, are final.
148 if (holding) root.setAttribute('data-slides-fonts', 'shown')
149 const session = withHelpers(createSystemSession())
150 fontsOn()
151 globalThis.slidesFonts = session
152 mountViewerNav({ fonts: session })
153 mountScenePages()
154} else {
155 const session = withHelpers(createFontSession({ manifest, fontSet: document.fonts, FontFaceCtor: FontFace, root }))
156 globalThis.slidesFonts = session
157 // The viewer changes slides in place, never through a page load whose
158 // slide is hidden again (viewer-nav.mjs).
159 mountViewerNav({ fonts: session })
160 // Scenes run over the viewer's and the follow view's slide
161 // (scene-pages.mjs).
162 mountScenePages()
163 run(session).catch(err => {
164 // A gate that fails must not leave the slides hidden.
165 console.error('fonts:', err)
166 fontsOn()
167 show(session)
168 })
169}
170