// talk-driver.mjs — where a presenting window is, and how it moves // (spec §6). Shared by the presenter window and the slide window; each // says how to draw a position (draw) and what to show for the network // (onStatus) and the loading (onProgress). // // A press moves the window at once, from the talk it holds // (talk-store.mjs, moves.mjs's advance), then goes to the server through // the link (talk-link.mjs). The server's positions come back through the // link, which says when the window should take one. A slide the window // has not got ready leaves the slide on screen where it is until it is, // then swaps in one task; presses made meanwhile keep counting from // where they would have landed. // // A newer version of the deck is learned from any answer's deckSeq, from // a check of /talk every 30 seconds while online, and when the window // gets focus back (the speaker fixed a slide in the editor); it is // loaded quietly and taken at the next change of slide, by the rule the // server uses (settleNear, with the slide's place in the version the // window held), so the window and the server land on the same slide. import { advance, settle, settleNear, talkOrder } from './moves.mjs' import { createLink, differs } from './talk-link.mjs' import { loadTalk } from './talk-store.mjs' import { indexOf } from './talk-draw.mjs' // How often a window that is online asks whether the deck changed. const CHECK_MS = 30000 // How long a slide change heard from the server waits to learn whether // the deck changed, before going ahead with the version it holds. const CHECK_ON_CHANGE_MS = 1500 // How long a talk that did not load waits before it is asked for again. const RELOAD_MS = 3000 const fullIndex = (view, id) => talkOrder(view, 'full').indexOf(indexOf(view, id)) const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) /** The session's stream, as the link hears it. Closed while the page is away (AGENTS.md: leaving a page lets go of its streams). */ export function eventStream (href) { return h => { let es = null let left = false const open = () => { if (es || left) return es = new EventSource(href) es.onopen = () => h.open() es.onerror = () => { h.error() // A stream refused outright is not retried by the browser. if (es && es.readyState === EventSource.CLOSED) { es = null setTimeout(open, RELOAD_MS) } } es.addEventListener('slide', e => { let d try { d = JSON.parse(e.data) } catch { return } if (d.ended) { location.reload(); return } // A position: an empty slideId is the empty talk, a position // like any other. Without the key it is not one. if (typeof d.slideId !== 'string') return const p = { slide: d.slideId, step: Number(d.step) || 0, mode: d.mode, black: !!d.blackout, seq: Number(d.seq) || 0 } if ('timerAt' in d) p.timerAt = d.timerAt h.position(p) }) } addEventListener('pagehide', () => { left = true if (es) { es.close(); es = null } }) addEventListener('pageshow', e => { const back = left && e.persisted left = false if (back) setTimeout(open, 0) }) open() return () => { left = true; if (es) es.close() } } } /** A press posted as the command form posts it, asking for the position as JSON. */ export function commandPost (action, token) { return fields => { const body = new URLSearchParams(fields) if (token) body.set('t', token) return fetch(action, { method: 'POST', body, credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' } }).then(r => { // The talk ended: the page as it loads says so. if (r.status === 410) location.reload() if (!r.ok) throw new Error('press: ' + r.status) return r.json() }) } } /** * draw(to, from, {fresh, store}) draws a position; to.slide is "" for * an empty talk (every slide parked or gone), which draws the empty * state. onTimer(ms) is the talk's timer as the server has it, Unix ms * or null, from every position heard, whether or not the window moves; * onLoad(store, pos) the talk once held, at the position the server drew. */ export function createDriver ({ root, talkHref, streamHref, action, token, draw, onLoad = () => {}, onStatus = () => {}, onProgress = () => {}, onPressed = () => {}, onTimer = () => {} }) { let store = null let link = null let pos = null // what is drawn let target = null // where presses have taken the window, while that slide gets ready let drawnSeq = 0 // the version pos was drawn from let ticket = 0 // the newest move, so an older one still waiting gives way const early = [] // moves and jumps made before the talk was in memory function show (to) { const from = pos const fresh = drawnSeq !== store.deckSeq pos = to target = null drawnSeq = store.deckSeq draw(to, from, { fresh, store }) } // go moves the window to `to` as soon as its slide is ready. function go (to) { const mine = ++ticket target = to if (!to.slide || store.has(to.slide) || (to.slide === pos.slide && drawnSeq === store.deckSeq)) { show(to) return } store.ready(to.slide).then(ok => { if (ok && mine === ticket) show(to) }) } // refresh asks for a newer version; the root says one is held // (data-deck-pending) until it is taken. function refresh () { return store.refresh().then(got => { if (store.pending) root.setAttribute('data-deck-pending', String(store.pending)) return got }) } // take is a newer version, if one is held, at a change of slide. function take (from) { const near = fullIndex(store.view, from.slide) store.adopt() root.removeAttribute('data-deck-pending') return settleNear(store.view, from, near) } /** A press made in this window. */ function move (m) { if (!store) { early.push(m); return } if (m.op === 'timer-reset') { link.press(m, null); return } const from = target || pos let to = advance(store.view, from, m) const next = store.pendingView if (next) { const there = advance(next, settleNear(next, from, fullIndex(store.view, from.slide)), m) if (to.slide !== from.slide || there.slide !== from.slide) { const settled = take(from) to = advance(store.view, settled, m) } } onPressed(m, from, to) link.press(m, to) go(to) } /** A jump to the slide numbered n in the talk being given (what the counter says). */ function jump (n) { if (!store) { early.push({ jump: n }); return } const from = target || pos const i = talkOrder(store.view, from.mode)[n - 1] if (i !== undefined) move({ op: 'goto', slide: store.view.slides[i].id }) } /** * The server says the talk is at p, and the link says take it. A * change of slide first asks, briefly, whether the deck changed, so * the slide goes up as the deck has it now; a slide this window has * never heard of waits for the version that has it. */ async function heard (p) { const mine = ++ticket const from = target || pos const known = () => !p.slide || !!store.slide(p.slide) || (!!store.pendingView && indexOf(store.pendingView, p.slide) >= 0) if (!p.slide) { // The talk is empty: the version that says so is the one to hold. await refresh() if (mine !== ticket) return if (store.pendingView) take(from) go({ slide: '', step: 0, mode: p.mode === 'full' ? 'full' : 'core', black: !!p.black }) return } if (p.slide !== from.slide && link.status() === 'online') { await Promise.race([refresh(), delay(CHECK_ON_CHANGE_MS)]) } if (!known()) await refresh() if (mine !== ticket || !known()) return const next = store.pendingView if (next && indexOf(next, p.slide) >= 0 && (p.slide !== from.slide || !store.slide(p.slide))) take(from) go(settle(store.view, p)) } function check () { if (store && link && link.status() === 'online') { refresh() store.retry() } } async function start () { const initial = { number: Number(root.getAttribute('data-slide')) || 0, step: Number(root.getAttribute('data-step')) || 0, mode: root.getAttribute('data-mode') === 'full' ? 'full' : 'core', black: root.getAttribute('data-blackout') === 'true' } for (;;) { try { store = await loadTalk({ href: talkHref, onProgress, from: Math.max(0, initial.number - 1) }) break } catch { onStatus('offline') await delay(RELOAD_MS) } } const here = store.slides.find(s => s.number === initial.number) pos = { slide: here ? here.id : '', step: initial.step, mode: initial.mode, black: initial.black } drawnSeq = store.deckSeq onLoad(store, pos) // the talk is held; what is on screen is the server's link = createLink({ post: commandPost(action, token), stream: eventStream(streamHref), onPosition: heard, onStatus: s => { onStatus(s); if (s === 'online') store.retry() }, onDeckSeq: n => { if (n > store.deckSeq && n > store.pending) refresh() }, onTimer }) link.resume(pos) onStatus(link.status()) // What was pressed while the talk loaded, in the order it was. for (const a of early.splice(0)) { if (a.jump) jump(a.jump) else move(a) } setInterval(check, CHECK_MS) addEventListener('focus', check) } start() return { move, jump, /** Resets the talk's timer; nothing moves. */ timerReset () { move({ op: 'timer-reset' }) }, get store () { return store }, get position () { return target || pos }, differs } } // The command forms' ops, as moves. const FORM_MOVES = { next: 'next', prev: 'back', first: 'first', last: 'last', blackout: 'black', mode: 'mode' } /** * Takes over the page's command forms (posted to action): each becomes * a press of the driver, so the window moves at once. Without this the * forms post and redirect, as they do with scripts off. Ending the * talk, and anything else, still posts. */ export function bindForms (root, action, driver, done = () => {}) { const path = new URL(action, location.href).pathname root.addEventListener('submit', e => { const form = e.target if (!form || (form.method || '').toLowerCase() !== 'post') return if (new URL(form.action, location.href).pathname !== path) return const op = form.elements.op && form.elements.op.value if (op === 'timer-reset') { e.preventDefault() driver.timerReset() } else if (op === 'goto' && form.elements.slide) { // A form's goto names the slide by its number in the full talk. const n = Number(form.elements.slide.value) const s = driver.store && driver.store.slides.find(x => x.number === n) if (!s) return e.preventDefault() driver.move({ op: 'goto', slide: s.id }) } else if (FORM_MOVES[op]) { e.preventDefault() driver.move({ op: FORM_MOVES[op] }) } else { return } done(op) }) }