| 1 | // present.js — the live half of presenting: a keyboard, a swipe, and |
| 2 | // a stream that keeps every screen on the same slide. |
| 3 | // |
| 4 | // An ENHANCEMENT and nothing else. Every page that loads it — the |
| 5 | // fullscreen surface, the presenter view, the phone remote, the |
| 6 | // audience's follow view — is complete without it: the buttons are |
| 7 | // forms, the pager is links, the follow view has a meta refresh. |
| 8 | // |
| 9 | // It sends exactly what those forms send (op, t, slide and a press id, |
| 10 | // POSTed to /p/{session}/command), so there is one protocol rather than |
| 11 | // two, and only on a page rendered for whoever drives: the token arrives |
| 12 | // as data-remote-token, the signed-in presenter's page says data-drives |
| 13 | // (their cookie is the credential), and a page with neither cannot send. |
| 14 | // |
| 15 | // Every URL it reads comes down as an attribute (codex 5). The |
| 16 | // audience's follow view is served from a share link and stays there — |
| 17 | // its stream and its slide fragments are /s/{token} URLs, so revoking |
| 18 | // the link stops it — and it carries no session sqid at all, which is |
| 19 | // why nothing in here builds a /p/… address out of one. |
| 20 | (function () { |
| 21 | var root = document.querySelector('[data-session], [data-stream]'); |
| 22 | if (!root) return; |
| 23 | // Empty on a page that holds no session capability of its own. |
| 24 | var session = root.getAttribute('data-session') || ''; |
| 25 | var token = root.getAttribute('data-remote-token') || ''; |
| 26 | // The presenter view and the remote are always the session's own, so |
| 27 | // they may fall back to its address; the surface says which it is. |
| 28 | var streamHref = root.getAttribute('data-stream') || |
| 29 | (session ? '/p/' + session + '/stream' : ''); |
| 30 | // {n} is where the slide number goes. Absent on the pages that have |
| 31 | // no stage to swap — they reload instead. |
| 32 | var fragmentHref = root.getAttribute('data-fragment') || ''; |
| 33 | var stage = document.querySelector('[slides-stage]'); |
| 34 | var note = document.querySelector('[slides-blackout]'); |
| 35 | if (!streamHref) return; |
| 36 | |
| 37 | // A press id: 16 random bytes, base64url (22 characters). A session |
| 38 | // with a position requires one with every press, so a press sent |
| 39 | // twice counts once; one begun before positions ignores it. Each |
| 40 | // press gets its own. |
| 41 | function pressID() { |
| 42 | var bytes = new Uint8Array(16); |
| 43 | crypto.getRandomValues(bytes); |
| 44 | var raw = ''; |
| 45 | for (var i = 0; i < bytes.length; i++) raw += String.fromCharCode(bytes[i]); |
| 46 | return btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); |
| 47 | } |
| 48 | |
| 49 | // A page drives with the remote token, or, rendered for the |
| 50 | // presenter signed in, by their cookie (data-drives) with none. |
| 51 | var drives = !!token || root.hasAttribute('data-drives'); |
| 52 | function command(op, slide) { |
| 53 | if (!drives || !session) return; |
| 54 | var body = new URLSearchParams({ op: op, press: pressID() }); |
| 55 | if (token) body.set('t', token); |
| 56 | if (slide) body.set('slide', slide); |
| 57 | fetch('/p/' + session + '/command', { |
| 58 | method: 'POST', |
| 59 | body: body, |
| 60 | credentials: 'same-origin', |
| 61 | headers: { 'Content-Type': 'application/x-www-form-urlencoded' } |
| 62 | }).catch(function () {}); |
| 63 | } |
| 64 | |
| 65 | document.addEventListener('keydown', function (e) { |
| 66 | if (e.metaKey || e.ctrlKey || e.altKey) return; |
| 67 | var tag = e.target && e.target.tagName; |
| 68 | if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return; |
| 69 | switch (e.key) { |
| 70 | case 'ArrowRight': case ' ': case 'PageDown': |
| 71 | command('next'); |
| 72 | break; |
| 73 | case 'ArrowLeft': case 'PageUp': |
| 74 | command('prev'); |
| 75 | break; |
| 76 | case 'b': case 'B': |
| 77 | command('blackout'); |
| 78 | break; |
| 79 | case 'n': case 'N': |
| 80 | var notes = root.getAttribute('data-notes'); |
| 81 | if (notes) window.open(notes, 'slides-notes'); |
| 82 | break; |
| 83 | case 'Escape': |
| 84 | if (document.fullscreenElement) document.exitFullscreen(); |
| 85 | return; |
| 86 | default: return; |
| 87 | } |
| 88 | e.preventDefault(); |
| 89 | }); |
| 90 | |
| 91 | var startX = null; |
| 92 | root.addEventListener('touchstart', function (e) { |
| 93 | startX = e.changedTouches[0].clientX; |
| 94 | }, { passive: true }); |
| 95 | root.addEventListener('touchend', function (e) { |
| 96 | if (startX === null) return; |
| 97 | var dx = e.changedTouches[0].clientX - startX; |
| 98 | startX = null; |
| 99 | // Enough to be a swipe rather than a tap that moved. |
| 100 | if (Math.abs(dx) < 60) return; |
| 101 | command(dx < 0 ? 'next' : 'prev'); |
| 102 | }, { passive: true }); |
| 103 | |
| 104 | // What is on the screen, and what a fetch is trying to put there. |
| 105 | // TWO facts, not one (codex 13). They were one — the data-slide |
| 106 | // attribute, written the moment an event arrived — and that is a |
| 107 | // projector left permanently behind: with the record already saying |
| 108 | // 3, a late response for 2 overwrote the stage and the event that |
| 109 | // would have corrected it was suppressed as a slide the page was |
| 110 | // already on. |
| 111 | // |
| 112 | // So: displayed only ever moves after an install succeeds, requested |
| 113 | // rolls back to displayed when a fetch fails, and every response |
| 114 | // carries the id of the request that asked for it — anything but the |
| 115 | // newest is dropped on the floor, however late it turns up. |
| 116 | var displayed = Number(root.getAttribute('data-slide')) || 0; |
| 117 | var requested = displayed; |
| 118 | var newest = 0; |
| 119 | // A session with a position also says the slide's id |
| 120 | // (data-slide-id), and the slide is known by that: after a reorder |
| 121 | // the number on the stage can be another slide's. |
| 122 | var displayedID = root.getAttribute('data-slide-id'); |
| 123 | |
| 124 | // Steps, on a session with a position. Its surface says which step |
| 125 | // the slide is drawn at (data-step), and each box or list item that |
| 126 | // arrives on a press carries data-press, with data-waiting while its |
| 127 | // press has not come. Moving to another step of the same slide is done |
| 128 | // here, in place: data-waiting follows the step, and data-arriving |
| 129 | // goes on what has just arrived and nothing else, until its effect |
| 130 | // ends or the next step comes (slides.css draws the effect, and leaves |
| 131 | // it out under reduced motion). Back within a slide animates nothing. |
| 132 | // A page without data-step (a session begun before positions) has |
| 133 | // null for its step and none of this applies. |
| 134 | function shownStep() { |
| 135 | var step = root.getAttribute('data-step'); |
| 136 | return step === null ? null : Number(step) || 0; |
| 137 | } |
| 138 | var requestedStep = shownStep(); |
| 139 | // unstepped is a stage's markup without what a step changes: two |
| 140 | // drawings of one slide at different steps are the same once it is |
| 141 | // taken out, and installed is that of the slide on the stage. A scene |
| 142 | // block's data-scene-live, and a scene frame run inside its block, are |
| 143 | // the frame layer's (fixtures/scene-pages.mjs), never the server's, and |
| 144 | // are taken out too; so are a clip's video and its data-clip-live |
| 145 | // (fixtures/clip.mjs). |
| 146 | function unstepped(html) { |
| 147 | var t = document.createElement('template'); |
| 148 | t.innerHTML = html; |
| 149 | var frames = t.content.querySelectorAll('[slides-scene-frame], [slides-clip-video]'); |
| 150 | for (var f = 0; f < frames.length; f++) frames[f].remove(); |
| 151 | var marked = t.content.querySelectorAll('[data-waiting], [data-arriving], [data-scene-live], [data-clip-live]'); |
| 152 | for (var i = 0; i < marked.length; i++) { |
| 153 | marked[i].removeAttribute('data-waiting'); |
| 154 | marked[i].removeAttribute('data-arriving'); |
| 155 | marked[i].removeAttribute('data-scene-live'); |
| 156 | marked[i].removeAttribute('data-clip-live'); |
| 157 | } |
| 158 | return t.innerHTML; |
| 159 | } |
| 160 | var installed = stage ? unstepped(stage.innerHTML) : ''; |
| 161 | function reveal(step) { |
| 162 | var settled = stage.querySelectorAll('[data-arriving]'); |
| 163 | for (var i = 0; i < settled.length; i++) settled[i].removeAttribute('data-arriving'); |
| 164 | var marked = stage.querySelectorAll('[data-press]'); |
| 165 | for (var j = 0; j < marked.length; j++) { |
| 166 | var el = marked[j]; |
| 167 | if (Number(el.getAttribute('data-press')) > step) { |
| 168 | el.setAttribute('data-waiting', ''); |
| 169 | } else if (el.hasAttribute('data-waiting')) { |
| 170 | el.removeAttribute('data-waiting'); |
| 171 | el.setAttribute('data-arriving', ''); |
| 172 | el.addEventListener('animationend', arrived); |
| 173 | } |
| 174 | } |
| 175 | root.setAttribute('data-step', String(step)); |
| 176 | requestedStep = step; |
| 177 | } |
| 178 | function arrived(e) { |
| 179 | if (e.target !== e.currentTarget) return; |
| 180 | e.currentTarget.removeAttribute('data-arriving'); |
| 181 | e.currentTarget.removeEventListener('animationend', arrived); |
| 182 | } |
| 183 | |
| 184 | // pageFor is this same surface's page for a slide: same capability, |
| 185 | // same token, ?slide=n, and &step=k on a session with a position. Its |
| 186 | // stage and its bar (counter, progress, the pager or the presenter's |
| 187 | // buttons) are what the slide looks like here. |
| 188 | function pageFor(slide, step) { |
| 189 | var u = new URL(location.href); |
| 190 | u.searchParams.set('slide', String(slide)); |
| 191 | if (step === null) u.searchParams.delete('step'); |
| 192 | else u.searchParams.set('step', String(step)); |
| 193 | return u.href; |
| 194 | } |
| 195 | |
| 196 | // again fetches the page even for the slide and step already asked |
| 197 | // for: the talk's mode changed, and with it the counter and the bar. |
| 198 | function show(slide, step, again) { |
| 199 | // Slide numbers on the wire are 1-based; anything else is not an |
| 200 | // event this page understands and is left alone rather than fetched. |
| 201 | if (!(slide > 0) || (!again && slide === requested && step === requestedStep)) return; |
| 202 | requested = slide; |
| 203 | requestedStep = step; |
| 204 | var mine = ++newest; |
| 205 | // The stage and the bar together, from this surface's own page for |
| 206 | // the slide, so the counter and the pager move with the slide (a |
| 207 | // fragment moved the stage alone). The blackout is the stream's: the |
| 208 | // page for an explicit slide is never blacked out. |
| 209 | fetchPage(pageFor(slide, step)) |
| 210 | .then(function (html) { return swapFrom(html, null, false, mine, true); }) |
| 211 | .catch(function () { |
| 212 | // Only this request's own failure rolls the record back, and |
| 213 | // only while it is still the newest: otherwise the next event |
| 214 | // for this slide would be suppressed as one already asked for. |
| 215 | if (mine === newest && requested === slide && requestedStep === step) { |
| 216 | requested = displayed; |
| 217 | requestedStep = shownStep(); |
| 218 | } |
| 219 | }); |
| 220 | } |
| 221 | |
| 222 | // Paging on the projector and the follow view changes the slide in |
| 223 | // place, never through a page load (Paul, 2026-10-26: "No flashing, |
| 224 | // ever!"; Astra's finding 4 on #27). A page load shows the bar first |
| 225 | // and the slide only once the font gate has confirmed its faces — an |
| 226 | // empty stage between two slides. With the script, a watcher's own |
| 227 | // previous and next links fetch the page they name and swap its stage |
| 228 | // and its bar in one task once its families are ready, moving the |
| 229 | // address with pushState; the remote's command forms post as they |
| 230 | // would and swap from the page the post answers with. The current |
| 231 | // slide stays on screen until the next is complete. Without the |
| 232 | // script both are what they always were. Anything unexpected falls |
| 233 | // back to the ordinary navigation. |
| 234 | // |
| 235 | // One ordering for everything that can change what this page shows: a |
| 236 | // streamed slide (show), a page a link, a form or Back asked for |
| 237 | // (page), and the stream's own whole-state events. Each |
| 238 | // request takes its number from newest when it STARTS, a stream event |
| 239 | // takes one too, and a response is applied only while its number is |
| 240 | // still the newest. So an old response — a Next form answered late, |
| 241 | // after the stream has already moved the room on — changes nothing: |
| 242 | // not the slide, not the bar, not the blackout (Astra, #27: it rolled |
| 243 | // the projector back to slide 2 while the session was on 3). An old |
| 244 | // failure does nothing either; only the newest request's failure falls |
| 245 | // back to an ordinary navigation. |
| 246 | var bar = document.querySelector('[slides-bar]'); |
| 247 | // The bar is out of sight while presenting (the same behaviour as |
| 248 | // fixtures/quiet-bar.mjs, which a classic script cannot import): a |
| 249 | // moving pointer or focus in it shows it; two seconds of stillness, or |
| 250 | // the talk moving (slide, step, blackout), hide it. Focus inside holds it. |
| 251 | if (stage && root.hasAttribute('slides-surface') && bar) { |
| 252 | var quietTimer; |
| 253 | var focused = function () { return root.querySelector('[slides-bar]:focus-within'); }; |
| 254 | var quiet = function () { clearTimeout(quietTimer); root.setAttribute('data-quiet', ''); }; |
| 255 | var rest = function () { |
| 256 | clearTimeout(quietTimer); |
| 257 | quietTimer = setTimeout(function () { |
| 258 | if (!focused() && !root.querySelector('[slides-bar]:hover')) quiet(); |
| 259 | }, 2000); |
| 260 | }; |
| 261 | var unquiet = function () { root.removeAttribute('data-quiet'); rest(); }; |
| 262 | var inBar = function (e) { if (e.target.closest && e.target.closest('[slides-bar]')) unquiet(); }; |
| 263 | quiet(); |
| 264 | root.addEventListener('pointermove', unquiet); |
| 265 | root.addEventListener('pointerleave', function () { if (!root.hasAttribute('data-quiet')) rest(); }); |
| 266 | root.addEventListener('focusin', inBar); |
| 267 | root.addEventListener('focusout', inBar); |
| 268 | new MutationObserver(function (records) { |
| 269 | if (focused()) return; |
| 270 | for (var i = 0; i < records.length; i++) { |
| 271 | if (records[i].target.getAttribute(records[i].attributeName) !== records[i].oldValue) return quiet(); |
| 272 | } |
| 273 | }).observe(root, { attributes: true, attributeOldValue: true, attributeFilter: ['data-slide', 'data-step', 'data-blackout'] }); |
| 274 | } |
| 275 | function page(href, init, push, fallback) { |
| 276 | var mine = ++newest; |
| 277 | fetchPage(href, init) |
| 278 | .then(function (html) { return swapFrom(html, href, push, mine); }) |
| 279 | .catch(function () { if (mine === newest) fallback(); }); |
| 280 | } |
| 281 | function swapFrom(html, href, push, mine, keepBlackout) { |
| 282 | if (mine !== newest) return; |
| 283 | var doc = new DOMParser().parseFromString(html, 'text/html'); |
| 284 | var nextStage = doc.querySelector('[slides-stage]'); |
| 285 | var nextBar = doc.querySelector('[slides-bar]'); |
| 286 | var nextRoot = doc.querySelector('[slides-surface]'); |
| 287 | if (!nextStage || !nextRoot) throw new Error('present: not a surface page'); |
| 288 | var fonts = window.slidesFonts; |
| 289 | // The incoming page's uploaded fonts (its <meta name="slides-fonts">) |
| 290 | // are learned first: a font the deck took on since this page loaded |
| 291 | // is waited for, not fallen back from (final review, I6). |
| 292 | if (fonts && typeof fonts.learnUploaded === 'function') { |
| 293 | try { |
| 294 | var manifestTag = doc.querySelector('meta[name="slides-fonts"]'); |
| 295 | var incoming = manifestTag ? JSON.parse(manifestTag.getAttribute('content') || 'null') : null; |
| 296 | if (incoming && incoming.uploaded) fonts.learnUploaded(incoming.uploaded); |
| 297 | } catch (e) { /* a manifest that does not parse teaches nothing */ } |
| 298 | } |
| 299 | var ready = fonts && fonts.prepareSection ? fonts.prepareSection(nextStage.innerHTML) : Promise.resolve(); |
| 300 | return ready.then(function () { |
| 301 | if (mine !== newest) return; |
| 302 | // Where focus was, so it can be put back on the same control once |
| 303 | // the bar is new (Astra, #27: it fell to <body>). |
| 304 | var active = document.activeElement; |
| 305 | var hadOp = null; |
| 306 | var hadRel = null; |
| 307 | if (active && bar && bar.contains(active)) { |
| 308 | var form = active.form || (active.closest && active.closest('form')); |
| 309 | var op = form && form.querySelector('input[name="op"]'); |
| 310 | hadOp = op ? op.value : null; |
| 311 | hadRel = active.getAttribute && active.getAttribute('rel'); |
| 312 | } |
| 313 | // The same slide at another step changes in place; anything else |
| 314 | // is swapped whole, as a slide always was. |
| 315 | var nextStep = nextRoot.getAttribute('data-step'); |
| 316 | var drawn = unstepped(nextStage.innerHTML); |
| 317 | if (nextStep !== null && shownStep() !== null && drawn === installed) { |
| 318 | if ((Number(nextStep) || 0) !== shownStep()) reveal(Number(nextStep) || 0); |
| 319 | } else { |
| 320 | stage.innerHTML = nextStage.innerHTML; |
| 321 | installed = drawn; |
| 322 | if (nextStep === null) root.removeAttribute('data-step'); |
| 323 | else root.setAttribute('data-step', nextStep); |
| 324 | } |
| 325 | // The mode the counter and the bar were drawn for. |
| 326 | var nextMode = nextRoot.getAttribute('data-mode'); |
| 327 | if (nextMode === null) root.removeAttribute('data-mode'); |
| 328 | else root.setAttribute('data-mode', nextMode); |
| 329 | if (bar && nextBar) { |
| 330 | var fresh = document.importNode(nextBar, true); |
| 331 | bar.replaceWith(fresh); |
| 332 | bar = fresh; |
| 333 | } |
| 334 | if (hadOp || hadRel) { |
| 335 | var target = null; |
| 336 | if (hadOp) { |
| 337 | var input = bar.querySelector('form input[name="op"][value="' + hadOp + '"]'); |
| 338 | target = input && input.form && input.form.querySelector('button, [type="submit"]'); |
| 339 | } |
| 340 | if (!target && hadRel) target = bar.querySelector('a[rel="' + hadRel + '"]'); |
| 341 | if (!target) { |
| 342 | target = stage.querySelector('[slides-slide]'); |
| 343 | if (target && !target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1'); |
| 344 | } |
| 345 | if (target) target.focus({ preventScroll: true }); |
| 346 | } |
| 347 | // Which slide is up, said politely ("Slide 3 of 12: Revenue"). |
| 348 | var said = nextRoot.getAttribute('data-announce'); |
| 349 | if (said) { |
| 350 | root.setAttribute('data-announce', said); |
| 351 | var region = root.querySelector('[slides-announce]'); |
| 352 | if (region && region.textContent !== said) region.textContent = said; |
| 353 | } |
| 354 | var slide = Number(nextRoot.getAttribute('data-slide')) || displayed; |
| 355 | displayed = requested = slide; |
| 356 | displayedID = nextRoot.getAttribute('data-slide-id'); |
| 357 | if (displayedID === null) root.removeAttribute('data-slide-id'); |
| 358 | else root.setAttribute('data-slide-id', displayedID); |
| 359 | requestedStep = shownStep(); |
| 360 | root.setAttribute('data-slide', String(slide)); |
| 361 | if (!keepBlackout) { |
| 362 | root.setAttribute('data-blackout', nextRoot.getAttribute('data-blackout') || 'false'); |
| 363 | if (note) note.hidden = nextRoot.getAttribute('data-blackout') !== 'true'; |
| 364 | } |
| 365 | if (push) history.pushState({ slidesSurface: true }, '', href); |
| 366 | }); |
| 367 | } |
| 368 | function fetchPage(href, init) { |
| 369 | return fetch(href, init || { credentials: 'same-origin', headers: { Accept: 'text/html' } }) |
| 370 | .then(function (r) { if (!r.ok) throw new Error('present: ' + r.status); return r.text(); }); |
| 371 | } |
| 372 | if (stage && fragmentHref && window.history && history.pushState && window.DOMParser) { |
| 373 | root.addEventListener('click', function (e) { |
| 374 | if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; |
| 375 | var a = e.target.closest && e.target.closest('[slides-bar] a[rel="prev"], [slides-bar] a[rel="next"]'); |
| 376 | if (!a) return; |
| 377 | var u = new URL(a.href, location.href); |
| 378 | if (u.origin !== location.origin || u.pathname !== location.pathname) return; |
| 379 | e.preventDefault(); |
| 380 | page(u.href, null, true, function () { location.assign(u.href); }); |
| 381 | }); |
| 382 | root.addEventListener('submit', function (e) { |
| 383 | var form = e.target; |
| 384 | if (!form.closest || !form.closest('[slides-bar]') || (form.method || '').toLowerCase() !== 'post') return; |
| 385 | e.preventDefault(); |
| 386 | var fd = new FormData(form); |
| 387 | if (e.submitter && e.submitter.name) fd.append(e.submitter.name, e.submitter.value); |
| 388 | // The form's press id was rendered once with the page, and this |
| 389 | // page is not reloaded between presses: each submit is a new one. |
| 390 | if (fd.has('press')) fd.set('press', pressID()); |
| 391 | var body = new URLSearchParams(fd); |
| 392 | page(form.action, { |
| 393 | method: 'POST', |
| 394 | body: body, |
| 395 | credentials: 'same-origin', |
| 396 | headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'text/html' } |
| 397 | }, false, function () { |
| 398 | // Load this page again, never post again: the server may already |
| 399 | // have applied the command whose answer failed, and a second post |
| 400 | // would move the room twice (Claude Fable, #27). The page as it |
| 401 | // loads shows where the session is. |
| 402 | location.reload(); |
| 403 | }); |
| 404 | }); |
| 405 | window.addEventListener('popstate', function () { |
| 406 | page(location.href, null, false, function () { location.reload(); }); |
| 407 | }); |
| 408 | history.replaceState({ slidesSurface: true }, '', location.href); |
| 409 | } |
| 410 | |
| 411 | // The pages with no stage to swap — the presenter view and the |
| 412 | // remote — follow by reloading: they show two slides, the notes and |
| 413 | // the blackout state, and re-rendering all that in here would be a |
| 414 | // second renderer to keep in step with the Go one. Their root says |
| 415 | // what they were rendered with (data-slide, data-blackout), and they |
| 416 | // reload only when an event says something else. |
| 417 | // |
| 418 | // And at most once for any one state. A page that has just reloaded |
| 419 | // for slide 3 and still says something else — a root missing its |
| 420 | // data-slide, or a session pointing past a deck that has since got |
| 421 | // shorter, which the server clamps — would otherwise reload again on |
| 422 | // the stream's first event, and again after that, forever: the |
| 423 | // presenter view once did exactly that about fifty times a second |
| 424 | // (polish audit B3). The record is taken off at load, so it only |
| 425 | // ever guards the load straight after the reload that wrote it. |
| 426 | // |
| 427 | // A page that says its step (the remote, on a session with a |
| 428 | // position, data-step) reloads for a step as for a slide, and one that |
| 429 | // says its mode (data-mode) for a change of mode: its counter and the |
| 430 | // slide it shows coming next count through the talk being given. |
| 431 | var renderedBlackout = root.getAttribute('data-blackout') === 'true'; |
| 432 | var renderedID = root.getAttribute('data-slide-id'); |
| 433 | var renderedStep = root.getAttribute('data-step'); |
| 434 | var renderedMode = root.getAttribute('data-mode'); |
| 435 | var reloadKey = 'slides-present-reload:' + window.location.pathname; |
| 436 | var reloadedFor = null; |
| 437 | try { |
| 438 | reloadedFor = window.sessionStorage.getItem(reloadKey); |
| 439 | window.sessionStorage.removeItem(reloadKey); |
| 440 | } catch (err) { /* no storage: see follow */ } |
| 441 | |
| 442 | function follow(state, step, mode) { |
| 443 | var slide = Number(state.slide); |
| 444 | if (!(slide > 0)) return; |
| 445 | var blackout = !!state.blackout; |
| 446 | if (renderedStep === null) step = null; |
| 447 | if (renderedMode === null) mode = null; |
| 448 | var id = state.slideId && renderedID !== null ? String(state.slideId) : null; |
| 449 | if (slide === displayed && blackout === renderedBlackout && |
| 450 | (id === null || id === renderedID) && |
| 451 | (step === null || String(step) === renderedStep) && |
| 452 | (mode === null || mode === renderedMode)) return; |
| 453 | var want = String(slide) + (id === null ? '' : '#' + id) + (step === null ? '' : '.' + step) + |
| 454 | (mode === null ? '' : '@' + mode) + (blackout ? ':blackout' : ''); |
| 455 | if (want === reloadedFor) return; |
| 456 | try { |
| 457 | window.sessionStorage.setItem(reloadKey, want); |
| 458 | } catch (err) { |
| 459 | // Nowhere to remember that this reload happened, so only reload |
| 460 | // a page that at least knows which slide it is on. |
| 461 | if (!displayed) return; |
| 462 | } |
| 463 | reloadedFor = want; |
| 464 | // A page that names its state (?slide=N&step=k, where a scriptless |
| 465 | // press lands it) would only draw that state again: it goes to where |
| 466 | // the session is instead. |
| 467 | var here = new URL(window.location.href); |
| 468 | if (here.searchParams.has('slide') || here.searchParams.has('step')) { |
| 469 | here.searchParams.delete('slide'); |
| 470 | here.searchParams.delete('step'); |
| 471 | window.location.replace(here.href); |
| 472 | return; |
| 473 | } |
| 474 | window.location.reload(); |
| 475 | } |
| 476 | |
| 477 | // apply is the whole of what an event does. The state is complete — |
| 478 | // never a delta — so applying one is exactly right rather than |
| 479 | // approximately, and a page that missed some is right again on the |
| 480 | // next one. |
| 481 | // |
| 482 | // A session with a position names its slide by id and numbers its |
| 483 | // events (seq): one older than an event already applied is late and |
| 484 | // changes nothing, and its step is applied in place when the slide is |
| 485 | // the one on the stage. |
| 486 | var appliedSeq = 0; |
| 487 | function apply(state) { |
| 488 | if (state.ended) { window.location.reload(); return; } |
| 489 | var seq = Number(state.seq) || 0; |
| 490 | if (seq) { |
| 491 | if (seq < appliedSeq) return; |
| 492 | appliedSeq = seq; |
| 493 | } |
| 494 | var step = state.slideId ? Number(state.step) || 0 : null; |
| 495 | var mode = state.slideId && state.mode ? String(state.mode) : null; |
| 496 | if (!stage || !fragmentHref) { follow(state, step, mode); return; } |
| 497 | // The stream's state is newer than any request still out: none of |
| 498 | // them may be applied after it. The slide it names is fetched afresh |
| 499 | // unless it is the one already shown. |
| 500 | newest++; |
| 501 | requested = displayed; |
| 502 | requestedStep = shownStep(); |
| 503 | root.setAttribute('data-blackout', state.blackout ? 'true' : 'false'); |
| 504 | if (note) note.hidden = !state.blackout; |
| 505 | var slide = Number(state.slide); |
| 506 | // The same number may be another slide since a reorder: the id |
| 507 | // says, where both sides have one. |
| 508 | var other = !!state.slideId && displayedID !== null && state.slideId !== displayedID; |
| 509 | if (step !== null && requestedStep !== null && slide === displayed && !other) { |
| 510 | if (step !== requestedStep) reveal(step); |
| 511 | // Another mode on the same slide: the stage stays as it is, and |
| 512 | // the counter and the bar, which count through the talk being |
| 513 | // given, come afresh from the server (swapFrom keeps the slide). |
| 514 | var drawnMode = root.getAttribute('data-mode'); |
| 515 | if (mode !== null && drawnMode !== null && mode !== drawnMode) show(slide, step, true); |
| 516 | return; |
| 517 | } |
| 518 | show(slide, step, other); |
| 519 | } |
| 520 | |
| 521 | // The stream is the page's only while the page is: leaving it (another |
| 522 | // page, or into the back/forward cache, which Chrome and WebKit keep |
| 523 | // left pages in) closes it at once, and a page shown again from that |
| 524 | // cache opens a new one on the next task — WebKit fails a stream opened |
| 525 | // inside pageshow — whose first event, whole state, catches it up |
| 526 | // (Docs #86, dadf9c1: each cached page held its stream, one of the |
| 527 | // browser's six HTTP/1.1 connections to this host, and after five the |
| 528 | // next page stalled). The listeners are here, before the stream is |
| 529 | // opened, so a page left before anything else ran opens none. |
| 530 | var events = null; |
| 531 | var left = false; |
| 532 | function openStream() { |
| 533 | if (events || left) return; |
| 534 | events = new EventSource(streamHref); |
| 535 | events.addEventListener('slide', function (e) { |
| 536 | try { apply(JSON.parse(e.data)); } catch (err) { /* not ours */ } |
| 537 | }); |
| 538 | } |
| 539 | window.addEventListener('pagehide', function () { |
| 540 | left = true; |
| 541 | if (events) { events.close(); events = null; } |
| 542 | }); |
| 543 | window.addEventListener('pageshow', function (e) { |
| 544 | var back = left && e.persisted; |
| 545 | left = false; |
| 546 | if (back) setTimeout(openStream, 0); |
| 547 | }); |
| 548 | openStream(); |
| 549 | |
| 550 | // The clock and elapsed line are server-rendered in UTC — the server |
| 551 | // has no idea what time zone the room is in. Here they become local |
| 552 | // and tick, in the catalog's own words: the pattern comes down as an |
| 553 | // attribute rather than being written in this file. |
| 554 | var clock = document.querySelector('[data-clock]'); |
| 555 | var elapsed = document.querySelector('[data-elapsed-since]'); |
| 556 | function tick() { |
| 557 | if (clock) clock.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); |
| 558 | if (!elapsed) return; |
| 559 | var mins = Math.floor((Date.now() / 1000 - Number(elapsed.getAttribute('data-elapsed-since'))) / 60); |
| 560 | var pattern = elapsed.getAttribute('data-elapsed-template'); |
| 561 | if (pattern) elapsed.textContent = pattern.replace('{n}', String(mins)); |
| 562 | } |
| 563 | if (clock || elapsed) { |
| 564 | tick(); |
| 565 | setInterval(tick, 15000); |
| 566 | } |
| 567 | |
| 568 | // The presenter window's timer: minutes and seconds since the talk's |
| 569 | // first press, and hours once there are any. Numbers only, so there is |
| 570 | // no sentence to keep out of this file. Absent until the first press. |
| 571 | var timer = document.querySelector('[data-timer-since]'); |
| 572 | function two(n) { return (n < 10 ? '0' : '') + n; } |
| 573 | function tickTimer() { |
| 574 | var s = Math.max(0, Math.floor(Date.now() / 1000 - Number(timer.getAttribute('data-timer-since')))); |
| 575 | var h = Math.floor(s / 3600), m = Math.floor(s / 60) % 60; |
| 576 | timer.textContent = h ? h + ':' + two(m) + ':' + two(s % 60) : m + ':' + two(s % 60); |
| 577 | } |
| 578 | if (timer) { |
| 579 | tickTimer(); |
| 580 | setInterval(tickTimer, 1000); |
| 581 | } |
| 582 | })(); |
| 583 | |