oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// talk-driver.mjs — where a presenting window is, and how it moves
2// (spec §6). Shared by the presenter window and the slide window; each
3// says how to draw a position (draw) and what to show for the network
4// (onStatus) and the loading (onProgress).
5//
6// A press moves the window at once, from the talk it holds
7// (talk-store.mjs, moves.mjs's advance), then goes to the server through
8// the link (talk-link.mjs). The server's positions come back through the
9// link, which says when the window should take one. A slide the window
10// has not got ready leaves the slide on screen where it is until it is,
11// then swaps in one task; presses made meanwhile keep counting from
12// where they would have landed.
13//
14// A newer version of the deck is learned from any answer's deckSeq, from
15// a check of /talk every 30 seconds while online, and when the window
16// gets focus back (the speaker fixed a slide in the editor); it is
17// loaded quietly and taken at the next change of slide, by the rule the
18// server uses (settleNear, with the slide's place in the version the
19// window held), so the window and the server land on the same slide.
20import { advance, settle, settleNear, talkOrder } from './moves.mjs'
21import { createLink, differs } from './talk-link.mjs'
22import { loadTalk } from './talk-store.mjs'
23import { indexOf } from './talk-draw.mjs'
24
25// How often a window that is online asks whether the deck changed.
26const CHECK_MS = 30000
27// How long a slide change heard from the server waits to learn whether
28// the deck changed, before going ahead with the version it holds.
29const CHECK_ON_CHANGE_MS = 1500
30// How long a talk that did not load waits before it is asked for again.
31const RELOAD_MS = 3000
32
33const fullIndex = (view, id) => talkOrder(view, 'full').indexOf(indexOf(view, id))
34const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
35
36/** 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). */
37export function eventStream (href) {
38 return h => {
39 let es = null
40 let left = false
41 const open = () => {
42 if (es || left) return
43 es = new EventSource(href)
44 es.onopen = () => h.open()
45 es.onerror = () => {
46 h.error()
47 // A stream refused outright is not retried by the browser.
48 if (es && es.readyState === EventSource.CLOSED) {
49 es = null
50 setTimeout(open, RELOAD_MS)
51 }
52 }
53 es.addEventListener('slide', e => {
54 let d
55 try { d = JSON.parse(e.data) } catch { return }
56 if (d.ended) { location.reload(); return }
57 // A position: an empty slideId is the empty talk, a position
58 // like any other. Without the key it is not one.
59 if (typeof d.slideId !== 'string') return
60 const p = { slide: d.slideId, step: Number(d.step) || 0, mode: d.mode, black: !!d.blackout, seq: Number(d.seq) || 0 }
61 if ('timerAt' in d) p.timerAt = d.timerAt
62 h.position(p)
63 })
64 }
65 addEventListener('pagehide', () => {
66 left = true
67 if (es) { es.close(); es = null }
68 })
69 addEventListener('pageshow', e => {
70 const back = left && e.persisted
71 left = false
72 if (back) setTimeout(open, 0)
73 })
74 open()
75 return () => { left = true; if (es) es.close() }
76 }
77}
78
79/** A press posted as the command form posts it, asking for the position as JSON. */
80export function commandPost (action, token) {
81 return fields => {
82 const body = new URLSearchParams(fields)
83 if (token) body.set('t', token)
84 return fetch(action, {
85 method: 'POST',
86 body,
87 credentials: 'same-origin',
88 headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }
89 }).then(r => {
90 // The talk ended: the page as it loads says so.
91 if (r.status === 410) location.reload()
92 if (!r.ok) throw new Error('press: ' + r.status)
93 return r.json()
94 })
95 }
96}
97
98/**
99 * draw(to, from, {fresh, store}) draws a position; to.slide is "" for
100 * an empty talk (every slide parked or gone), which draws the empty
101 * state. onTimer(ms) is the talk's timer as the server has it, Unix ms
102 * or null, from every position heard, whether or not the window moves;
103 * onLoad(store, pos) the talk once held, at the position the server drew.
104 */
105export function createDriver ({ root, talkHref, streamHref, action, token, draw, onLoad = () => {}, onStatus = () => {}, onProgress = () => {}, onPressed = () => {}, onTimer = () => {} }) {
106 let store = null
107 let link = null
108 let pos = null // what is drawn
109 let target = null // where presses have taken the window, while that slide gets ready
110 let drawnSeq = 0 // the version pos was drawn from
111 let ticket = 0 // the newest move, so an older one still waiting gives way
112 const early = [] // moves and jumps made before the talk was in memory
113
114 function show (to) {
115 const from = pos
116 const fresh = drawnSeq !== store.deckSeq
117 pos = to
118 target = null
119 drawnSeq = store.deckSeq
120 draw(to, from, { fresh, store })
121 }
122
123 // go moves the window to `to` as soon as its slide is ready.
124 function go (to) {
125 const mine = ++ticket
126 target = to
127 if (!to.slide || store.has(to.slide) || (to.slide === pos.slide && drawnSeq === store.deckSeq)) {
128 show(to)
129 return
130 }
131 store.ready(to.slide).then(ok => { if (ok && mine === ticket) show(to) })
132 }
133
134 // refresh asks for a newer version; the root says one is held
135 // (data-deck-pending) until it is taken.
136 function refresh () {
137 return store.refresh().then(got => {
138 if (store.pending) root.setAttribute('data-deck-pending', String(store.pending))
139 return got
140 })
141 }
142
143 // take is a newer version, if one is held, at a change of slide.
144 function take (from) {
145 const near = fullIndex(store.view, from.slide)
146 store.adopt()
147 root.removeAttribute('data-deck-pending')
148 return settleNear(store.view, from, near)
149 }
150
151 /** A press made in this window. */
152 function move (m) {
153 if (!store) { early.push(m); return }
154 if (m.op === 'timer-reset') { link.press(m, null); return }
155 const from = target || pos
156 let to = advance(store.view, from, m)
157 const next = store.pendingView
158 if (next) {
159 const there = advance(next, settleNear(next, from, fullIndex(store.view, from.slide)), m)
160 if (to.slide !== from.slide || there.slide !== from.slide) {
161 const settled = take(from)
162 to = advance(store.view, settled, m)
163 }
164 }
165 onPressed(m, from, to)
166 link.press(m, to)
167 go(to)
168 }
169
170 /** A jump to the slide numbered n in the talk being given (what the counter says). */
171 function jump (n) {
172 if (!store) { early.push({ jump: n }); return }
173 const from = target || pos
174 const i = talkOrder(store.view, from.mode)[n - 1]
175 if (i !== undefined) move({ op: 'goto', slide: store.view.slides[i].id })
176 }
177
178 /**
179 * The server says the talk is at p, and the link says take it. A
180 * change of slide first asks, briefly, whether the deck changed, so
181 * the slide goes up as the deck has it now; a slide this window has
182 * never heard of waits for the version that has it.
183 */
184 async function heard (p) {
185 const mine = ++ticket
186 const from = target || pos
187 const known = () => !p.slide || !!store.slide(p.slide) || (!!store.pendingView && indexOf(store.pendingView, p.slide) >= 0)
188 if (!p.slide) {
189 // The talk is empty: the version that says so is the one to hold.
190 await refresh()
191 if (mine !== ticket) return
192 if (store.pendingView) take(from)
193 go({ slide: '', step: 0, mode: p.mode === 'full' ? 'full' : 'core', black: !!p.black })
194 return
195 }
196 if (p.slide !== from.slide && link.status() === 'online') {
197 await Promise.race([refresh(), delay(CHECK_ON_CHANGE_MS)])
198 }
199 if (!known()) await refresh()
200 if (mine !== ticket || !known()) return
201 const next = store.pendingView
202 if (next && indexOf(next, p.slide) >= 0 && (p.slide !== from.slide || !store.slide(p.slide))) take(from)
203 go(settle(store.view, p))
204 }
205
206 function check () {
207 if (store && link && link.status() === 'online') {
208 refresh()
209 store.retry()
210 }
211 }
212
213 async function start () {
214 const initial = {
215 number: Number(root.getAttribute('data-slide')) || 0,
216 step: Number(root.getAttribute('data-step')) || 0,
217 mode: root.getAttribute('data-mode') === 'full' ? 'full' : 'core',
218 black: root.getAttribute('data-blackout') === 'true'
219 }
220 for (;;) {
221 try {
222 store = await loadTalk({ href: talkHref, onProgress, from: Math.max(0, initial.number - 1) })
223 break
224 } catch {
225 onStatus('offline')
226 await delay(RELOAD_MS)
227 }
228 }
229 const here = store.slides.find(s => s.number === initial.number)
230 pos = { slide: here ? here.id : '', step: initial.step, mode: initial.mode, black: initial.black }
231 drawnSeq = store.deckSeq
232 onLoad(store, pos) // the talk is held; what is on screen is the server's
233 link = createLink({
234 post: commandPost(action, token),
235 stream: eventStream(streamHref),
236 onPosition: heard,
237 onStatus: s => { onStatus(s); if (s === 'online') store.retry() },
238 onDeckSeq: n => { if (n > store.deckSeq && n > store.pending) refresh() },
239 onTimer
240 })
241 link.resume(pos)
242 onStatus(link.status())
243 // What was pressed while the talk loaded, in the order it was.
244 for (const a of early.splice(0)) {
245 if (a.jump) jump(a.jump)
246 else move(a)
247 }
248 setInterval(check, CHECK_MS)
249 addEventListener('focus', check)
250 }
251
252 start()
253
254 return {
255 move,
256 jump,
257 /** Resets the talk's timer; nothing moves. */
258 timerReset () { move({ op: 'timer-reset' }) },
259 get store () { return store },
260 get position () { return target || pos },
261 differs
262 }
263}
264
265// The command forms' ops, as moves.
266const FORM_MOVES = { next: 'next', prev: 'back', first: 'first', last: 'last', blackout: 'black', mode: 'mode' }
267
268/**
269 * Takes over the page's command forms (posted to action): each becomes
270 * a press of the driver, so the window moves at once. Without this the
271 * forms post and redirect, as they do with scripts off. Ending the
272 * talk, and anything else, still posts.
273 */
274export function bindForms (root, action, driver, done = () => {}) {
275 const path = new URL(action, location.href).pathname
276 root.addEventListener('submit', e => {
277 const form = e.target
278 if (!form || (form.method || '').toLowerCase() !== 'post') return
279 if (new URL(form.action, location.href).pathname !== path) return
280 const op = form.elements.op && form.elements.op.value
281 if (op === 'timer-reset') {
282 e.preventDefault()
283 driver.timerReset()
284 } else if (op === 'goto' && form.elements.slide) {
285 // A form's goto names the slide by its number in the full talk.
286 const n = Number(form.elements.slide.value)
287 const s = driver.store && driver.store.slides.find(x => x.number === n)
288 if (!s) return
289 e.preventDefault()
290 driver.move({ op: 'goto', slide: s.id })
291 } else if (FORM_MOVES[op]) {
292 e.preventDefault()
293 driver.move({ op: FORM_MOVES[op] })
294 } else {
295 return
296 }
297 done(op)
298 })
299}
300