// fixtures/viewer-nav.mjs — the viewer moves between slides in place // (Paul, 2026-10-26: "No flashing, ever!"; Astra's finding 4 on #27). // // The viewer's previous and next links, its filmstrip and the // scriptless presenting mode (?present=1) are ordinary links, and stay // so: with no script each is a page load, in the system faces, final. A // page load with the font gate, though, is a new document whose slide is // hidden until its faces are confirmed — the slide that was on screen, // then an empty stage for a frame or two, then the next. That is a gap. // // So with the script a link to another slide of the same deck does not // load a page. The page it names is fetched (or was prefetched), its // slide's families are made ready (font-session.mjs's prepareSection; // the whole deck's were waited for already, so this is normally // instant, but the deck may have changed since), its pictures decoded, // and only then is the viewer's content replaced, in one task, and the // address moved with history.pushState. Until then the current slide // stays exactly as it is: there is never a frame without a slide. Back // and Forward do the same through popstate. Anything unexpected — a // failed fetch, a page that is not this viewer — falls back to loading // the page, which is what the link would have done. // // The neighbouring pages are prefetched when the page is idle, and their // slides' families loaded (not put on), so the next slide is ready // before anyone asks for it. The page itself is fetched again when the // slide changes: a deck can change between the prefetch and the click, // and the slide shown is the deck as it is now. const ROOTS = '[slides-viewer], [slides-present]' const FRESH_MS = 30000 const PICTURE_MS = 1500 export function mountViewerNav ({ fonts, doc = document, win = window } = {}) { const root = () => doc.querySelector(ROOTS) if (!root() || !win.history || !win.history.pushState || typeof win.fetch !== 'function' || typeof win.DOMParser !== 'function') return null const cache = new Map() // href -> { at, html } let seq = 0 // A page that is left aborts what it is fetching, and fetches nothing // more until it is shown again from the back/forward cache: a request // from a cached page holds one of the browser's six connections to this // host for nobody (Docs #86, dadf9c1). let leaving = new AbortController() win.addEventListener('pagehide', () => leaving.abort()) win.addEventListener('pageshow', e => { if (!e.persisted) return leaving = new AbortController() prefetch() }) // A link this moves in place: another page of this same viewer (the // same path; only the query differs), followed by a plain click. function sameViewer (href) { let u try { u = new URL(href, win.location.href) } catch { return null } if (u.origin !== win.location.origin || u.pathname !== win.location.pathname || u.hash) return null return u.href } // page is the page at href: fetched now when the slide is about to // change (the deck may have changed since a prefetch), or from the // cache when prefetching. async function page (href, { cached = false } = {}) { const hit = cache.get(href) if (cached && hit && Date.now() - hit.at < FRESH_MS) return hit.html const res = await win.fetch(href, { credentials: 'same-origin', headers: { Accept: 'text/html' }, signal: leaving.signal }) if (!res.ok) throw new Error(`viewer: ${href}: ${res.status}`) const html = await res.text() cache.set(href, { at: Date.now(), html }) if (cache.size > 6) cache.delete(cache.keys().next().value) return html } const parse = html => new win.DOMParser().parseFromString(html, 'text/html') // learnFrom takes in the uploaded fonts the incoming page's manifest // lists (its ): a font the deck took on since // this page loaded is learned, so its slide waits for it rather than // going up in the stack's next family (final review, I6). function learnFrom (d) { if (!fonts || typeof fonts.learnUploaded !== 'function') return try { const tag = d.querySelector('meta[name="slides-fonts"]') const m = tag ? JSON.parse(tag.getAttribute('content') || 'null') : null if (m && m.uploaded) fonts.learnUploaded(m.uploaded) } catch { /* a manifest that does not parse teaches nothing */ } } // pictures resolves once every on the incoming slide has // decoded, or after PICTURE_MS: a picture still loading is not text, // and is not held for long. function pictures (next) { const imgs = [...next.querySelectorAll('img[src]')].map(img => { const i = new win.Image() i.src = img.getAttribute('src') return i.decode ? i.decode().catch(() => {}) : Promise.resolve() }) return Promise.race([Promise.all(imgs), new Promise(resolve => setTimeout(resolve, PICTURE_MS))]) } async function go (href, { push }) { const mine = ++seq let next let title try { const d = parse(await page(href)) next = d.querySelector(ROOTS) title = d.title if (!next) throw new Error('viewer: not a viewer page') learnFrom(d) const section = next.querySelector('[slides-slide]') if (section && fonts && fonts.prepareSection) await fonts.prepareSection(section.outerHTML) await pictures(next) } catch (err) { if (mine === seq && !leaving.signal.aborted) win.location.assign(href) return } if (mine !== seq) return // The one task in which the slide changes: the current one is on // screen until here, and the next is complete, in faces that have // loaded, from here. const current = root() const active = doc.activeElement const had = active && current.contains(active) ? active : null const fresh = doc.importNode(next, true) const rail = railScroll(current) current.replaceWith(fresh) keepRail(fresh, rail) if (title) doc.title = title if (push) win.history.pushState({ slidesViewer: true }, '', href) if (had) refocus(fresh, had) announce(fresh) prefetch() } // The filmstrip is a rail that scrolls inside itself from 1100px and a // row that scrolls sideways below that. The swap replaces it with the // incoming page's, which would start scrolled to the top: so where the // reader had scrolled it is carried across, and then the new current // slide is brought into view within the rail — the rail, never the // page, so nothing else moves. function railScroll (from) { const nav = from.querySelector('[slides-film-nav]') const list = from.querySelector('[slides-film]') return { nav: nav ? nav.scrollTop : 0, list: list ? list.scrollLeft : 0 } } function keepRail (fresh, was) { const nav = fresh.querySelector('[slides-film-nav]') const list = fresh.querySelector('[slides-film]') if (nav) nav.scrollTop = was.nav if (list) list.scrollLeft = was.list revealCurrent(fresh) } function revealCurrent (from) { const current = from.querySelector('[slides-film] a[aria-current="true"]') if (!current) return for (const box of [from.querySelector('[slides-film-nav]'), from.querySelector('[slides-film]')]) { if (!box || typeof box.getBoundingClientRect !== 'function') continue const b = box.getBoundingClientRect() const c = current.getBoundingClientRect() if (box.scrollHeight > box.clientHeight) { if (c.top < b.top) box.scrollTop -= b.top - c.top + 8 else if (c.bottom > b.bottom) box.scrollTop += c.bottom - b.bottom + 8 } if (box.scrollWidth > box.clientWidth) { if (c.left < b.left) box.scrollLeft -= b.left - c.left + 8 else if (c.right > b.right) box.scrollLeft += c.right - b.right + 8 } } } // refocus puts focus where a keyboard user expects it after the swap // (Astra, #27): on the same control in the new slide's page — the // link of the same rel, or the filmstrip entry of the same address — // when it is still a link there; otherwise, at the first or the last // slide where Previous or Next is no longer a link, on the slide // itself, which is made focusable for the purpose. Never on . function refocus (fresh, had) { let target = null const rel = had.getAttribute && had.getAttribute('rel') if (rel) target = fresh.querySelector(`[slides-pager] a[rel="${rel}"]`) if (!target && had.closest && had.closest('[slides-film]')) { target = [...fresh.querySelectorAll('[slides-film] a[href]')].find(a => a.getAttribute('href') === had.getAttribute('href')) || null } if (!target) { target = fresh.querySelector('[slides-slide]') if (target && !target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1') } if (target) target.focus({ preventScroll: true }) } // announce says which slide is up, politely, through the page's own // live region ([slides-announce], outside what is swapped, so it was // in the page before its text changed): "Slide 2 of 5: Revenue", in // the catalog's words, from the new root's data-announce. function announce (fresh) { const region = doc.querySelector('[slides-announce]') const said = fresh.getAttribute('data-announce') if (region && said) region.textContent = said } // prefetch fetches the pages either side and loads their slides' // families, when the page is idle. function prefetch () { const idle = fn => (typeof win.requestIdleCallback === 'function' ? win.requestIdleCallback(fn, { timeout: 2000 }) : setTimeout(fn, 300)) idle(async () => { if (leaving.signal.aborted) return for (const a of root() ? root().querySelectorAll('[slides-pager] a[rel="prev"], [slides-pager] a[rel="next"]') : []) { const href = sameViewer(a.href) if (!href) continue try { const d = parse(await page(href, { cached: true })) learnFrom(d) const section = d.querySelector('[slides-slide]') if (section && fonts && fonts.familiesOfSection && fonts.load) { await Promise.all(fonts.familiesOfSection(section.outerHTML).map(k => fonts.load(k))) } } catch { /* the click will fetch it */ } } }) } doc.addEventListener('click', e => { if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return const a = e.target.closest && e.target.closest('a[href]') if (!a || !root() || !root().contains(a) || a.target || a.hasAttribute('download')) return if (!a.closest('[slides-pager], [slides-film]')) return const href = sameViewer(a.href) if (!href) return e.preventDefault() go(href, { push: true }) }) win.addEventListener('popstate', () => { go(win.location.href, { push: false }) }) // The entry the page was loaded at can be come back to, too. win.history.replaceState({ slidesViewer: true }, '', win.location.href) // A page opened on slide 20 shows slide 20's place in the rail. if (root()) revealCurrent(root()) prefetch() return { go } }