oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/viewer-nav.mjs — the viewer moves between slides in place
2// (Paul, 2026-10-26: "No flashing, ever!"; Astra's finding 4 on #27).
3//
4// The viewer's previous and next links, its filmstrip and the
5// scriptless presenting mode (?present=1) are ordinary links, and stay
6// so: with no script each is a page load, in the system faces, final. A
7// page load with the font gate, though, is a new document whose slide is
8// hidden until its faces are confirmed — the slide that was on screen,
9// then an empty stage for a frame or two, then the next. That is a gap.
10//
11// So with the script a link to another slide of the same deck does not
12// load a page. The page it names is fetched (or was prefetched), its
13// slide's families are made ready (font-session.mjs's prepareSection;
14// the whole deck's were waited for already, so this is normally
15// instant, but the deck may have changed since), its pictures decoded,
16// and only then is the viewer's content replaced, in one task, and the
17// address moved with history.pushState. Until then the current slide
18// stays exactly as it is: there is never a frame without a slide. Back
19// and Forward do the same through popstate. Anything unexpected — a
20// failed fetch, a page that is not this viewer — falls back to loading
21// the page, which is what the link would have done.
22//
23// The neighbouring pages are prefetched when the page is idle, and their
24// slides' families loaded (not put on), so the next slide is ready
25// before anyone asks for it. The page itself is fetched again when the
26// slide changes: a deck can change between the prefetch and the click,
27// and the slide shown is the deck as it is now.
28
29const ROOTS = '[slides-viewer], [slides-present]'
30const FRESH_MS = 30000
31const PICTURE_MS = 1500
32
33export function mountViewerNav ({ fonts, doc = document, win = window } = {}) {
34 const root = () => doc.querySelector(ROOTS)
35 if (!root() || !win.history || !win.history.pushState || typeof win.fetch !== 'function' || typeof win.DOMParser !== 'function') return null
36
37 const cache = new Map() // href -> { at, html }
38 let seq = 0
39 // A page that is left aborts what it is fetching, and fetches nothing
40 // more until it is shown again from the back/forward cache: a request
41 // from a cached page holds one of the browser's six connections to this
42 // host for nobody (Docs #86, dadf9c1).
43 let leaving = new AbortController()
44 win.addEventListener('pagehide', () => leaving.abort())
45 win.addEventListener('pageshow', e => {
46 if (!e.persisted) return
47 leaving = new AbortController()
48 prefetch()
49 })
50
51 // A link this moves in place: another page of this same viewer (the
52 // same path; only the query differs), followed by a plain click.
53 function sameViewer (href) {
54 let u
55 try {
56 u = new URL(href, win.location.href)
57 } catch {
58 return null
59 }
60 if (u.origin !== win.location.origin || u.pathname !== win.location.pathname || u.hash) return null
61 return u.href
62 }
63
64 // page is the page at href: fetched now when the slide is about to
65 // change (the deck may have changed since a prefetch), or from the
66 // cache when prefetching.
67 async function page (href, { cached = false } = {}) {
68 const hit = cache.get(href)
69 if (cached && hit && Date.now() - hit.at < FRESH_MS) return hit.html
70 const res = await win.fetch(href, { credentials: 'same-origin', headers: { Accept: 'text/html' }, signal: leaving.signal })
71 if (!res.ok) throw new Error(`viewer: ${href}: ${res.status}`)
72 const html = await res.text()
73 cache.set(href, { at: Date.now(), html })
74 if (cache.size > 6) cache.delete(cache.keys().next().value)
75 return html
76 }
77
78 const parse = html => new win.DOMParser().parseFromString(html, 'text/html')
79
80 // learnFrom takes in the uploaded fonts the incoming page's manifest
81 // lists (its <meta name="slides-fonts">): a font the deck took on since
82 // this page loaded is learned, so its slide waits for it rather than
83 // going up in the stack's next family (final review, I6).
84 function learnFrom (d) {
85 if (!fonts || typeof fonts.learnUploaded !== 'function') return
86 try {
87 const tag = d.querySelector('meta[name="slides-fonts"]')
88 const m = tag ? JSON.parse(tag.getAttribute('content') || 'null') : null
89 if (m && m.uploaded) fonts.learnUploaded(m.uploaded)
90 } catch { /* a manifest that does not parse teaches nothing */ }
91 }
92
93 // pictures resolves once every <img> on the incoming slide has
94 // decoded, or after PICTURE_MS: a picture still loading is not text,
95 // and is not held for long.
96 function pictures (next) {
97 const imgs = [...next.querySelectorAll('img[src]')].map(img => {
98 const i = new win.Image()
99 i.src = img.getAttribute('src')
100 return i.decode ? i.decode().catch(() => {}) : Promise.resolve()
101 })
102 return Promise.race([Promise.all(imgs), new Promise(resolve => setTimeout(resolve, PICTURE_MS))])
103 }
104
105 async function go (href, { push }) {
106 const mine = ++seq
107 let next
108 let title
109 try {
110 const d = parse(await page(href))
111 next = d.querySelector(ROOTS)
112 title = d.title
113 if (!next) throw new Error('viewer: not a viewer page')
114 learnFrom(d)
115 const section = next.querySelector('[slides-slide]')
116 if (section && fonts && fonts.prepareSection) await fonts.prepareSection(section.outerHTML)
117 await pictures(next)
118 } catch (err) {
119 if (mine === seq && !leaving.signal.aborted) win.location.assign(href)
120 return
121 }
122 if (mine !== seq) return
123 // The one task in which the slide changes: the current one is on
124 // screen until here, and the next is complete, in faces that have
125 // loaded, from here.
126 const current = root()
127 const active = doc.activeElement
128 const had = active && current.contains(active) ? active : null
129 const fresh = doc.importNode(next, true)
130 const rail = railScroll(current)
131 current.replaceWith(fresh)
132 keepRail(fresh, rail)
133 if (title) doc.title = title
134 if (push) win.history.pushState({ slidesViewer: true }, '', href)
135 if (had) refocus(fresh, had)
136 announce(fresh)
137 prefetch()
138 }
139
140 // The filmstrip is a rail that scrolls inside itself from 1100px and a
141 // row that scrolls sideways below that. The swap replaces it with the
142 // incoming page's, which would start scrolled to the top: so where the
143 // reader had scrolled it is carried across, and then the new current
144 // slide is brought into view within the rail — the rail, never the
145 // page, so nothing else moves.
146 function railScroll (from) {
147 const nav = from.querySelector('[slides-film-nav]')
148 const list = from.querySelector('[slides-film]')
149 return { nav: nav ? nav.scrollTop : 0, list: list ? list.scrollLeft : 0 }
150 }
151
152 function keepRail (fresh, was) {
153 const nav = fresh.querySelector('[slides-film-nav]')
154 const list = fresh.querySelector('[slides-film]')
155 if (nav) nav.scrollTop = was.nav
156 if (list) list.scrollLeft = was.list
157 revealCurrent(fresh)
158 }
159
160 function revealCurrent (from) {
161 const current = from.querySelector('[slides-film] a[aria-current="true"]')
162 if (!current) return
163 for (const box of [from.querySelector('[slides-film-nav]'), from.querySelector('[slides-film]')]) {
164 if (!box || typeof box.getBoundingClientRect !== 'function') continue
165 const b = box.getBoundingClientRect()
166 const c = current.getBoundingClientRect()
167 if (box.scrollHeight > box.clientHeight) {
168 if (c.top < b.top) box.scrollTop -= b.top - c.top + 8
169 else if (c.bottom > b.bottom) box.scrollTop += c.bottom - b.bottom + 8
170 }
171 if (box.scrollWidth > box.clientWidth) {
172 if (c.left < b.left) box.scrollLeft -= b.left - c.left + 8
173 else if (c.right > b.right) box.scrollLeft += c.right - b.right + 8
174 }
175 }
176 }
177
178 // refocus puts focus where a keyboard user expects it after the swap
179 // (Astra, #27): on the same control in the new slide's page — the
180 // link of the same rel, or the filmstrip entry of the same address —
181 // when it is still a link there; otherwise, at the first or the last
182 // slide where Previous or Next is no longer a link, on the slide
183 // itself, which is made focusable for the purpose. Never on <body>.
184 function refocus (fresh, had) {
185 let target = null
186 const rel = had.getAttribute && had.getAttribute('rel')
187 if (rel) target = fresh.querySelector(`[slides-pager] a[rel="${rel}"]`)
188 if (!target && had.closest && had.closest('[slides-film]')) {
189 target = [...fresh.querySelectorAll('[slides-film] a[href]')].find(a => a.getAttribute('href') === had.getAttribute('href')) || null
190 }
191 if (!target) {
192 target = fresh.querySelector('[slides-slide]')
193 if (target && !target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1')
194 }
195 if (target) target.focus({ preventScroll: true })
196 }
197
198 // announce says which slide is up, politely, through the page's own
199 // live region ([slides-announce], outside what is swapped, so it was
200 // in the page before its text changed): "Slide 2 of 5: Revenue", in
201 // the catalog's words, from the new root's data-announce.
202 function announce (fresh) {
203 const region = doc.querySelector('[slides-announce]')
204 const said = fresh.getAttribute('data-announce')
205 if (region && said) region.textContent = said
206 }
207
208 // prefetch fetches the pages either side and loads their slides'
209 // families, when the page is idle.
210 function prefetch () {
211 const idle = fn => (typeof win.requestIdleCallback === 'function' ? win.requestIdleCallback(fn, { timeout: 2000 }) : setTimeout(fn, 300))
212 idle(async () => {
213 if (leaving.signal.aborted) return
214 for (const a of root() ? root().querySelectorAll('[slides-pager] a[rel="prev"], [slides-pager] a[rel="next"]') : []) {
215 const href = sameViewer(a.href)
216 if (!href) continue
217 try {
218 const d = parse(await page(href, { cached: true }))
219 learnFrom(d)
220 const section = d.querySelector('[slides-slide]')
221 if (section && fonts && fonts.familiesOfSection && fonts.load) {
222 await Promise.all(fonts.familiesOfSection(section.outerHTML).map(k => fonts.load(k)))
223 }
224 } catch { /* the click will fetch it */ }
225 }
226 })
227 }
228
229 doc.addEventListener('click', e => {
230 if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
231 const a = e.target.closest && e.target.closest('a[href]')
232 if (!a || !root() || !root().contains(a) || a.target || a.hasAttribute('download')) return
233 if (!a.closest('[slides-pager], [slides-film]')) return
234 const href = sameViewer(a.href)
235 if (!href) return
236 e.preventDefault()
237 go(href, { push: true })
238 })
239 win.addEventListener('popstate', () => {
240 go(win.location.href, { push: false })
241 })
242 // The entry the page was loaded at can be come back to, too.
243 win.history.replaceState({ slidesViewer: true }, '', win.location.href)
244 // A page opened on slide 20 shows slide 20's place in the rail.
245 if (root()) revealCurrent(root())
246 prefetch()
247 return { go }
248}
249