Presenter: a press moves the window at once, even with no network
The presenter window and the slide window of a session with a position (for whoever may drive it) load a new bundle, presenter.<hash>.js (fixtures/presenter-entry.mjs). Each holds the whole talk in memory (talk-store.mjs: /talk, families on, pictures decoded), moves at once on a press from moves.mjs's advance, and tells the server afterwards through talk-link.mjs: one press on the wire at a time, each with its own id; the server's positions are taken only once no press waits; a send that fails or takes over 3 s is offline, and the window that pressed resumes the server at its own position on reconnecting, while one that pressed nothing takes the server's. A slide not ready yet leaves the current one on screen. A newer deck, learned from answers' deckSeq, a 30 s check or focus, is taken at the next change of slide through settleNear. The keys of spec 5.5 (presenter-keys.mjs), repeats ignored, PageUp and PageDown from fields, a number then Enter, P opening slides-presenter. The step count flashes and the position pulses on every press, the last press of the talk included. Loading, offline and waiting words come from the catalog as data-text-* attributes. The signed-in presenter's slide window now has the press buttons. The follow link, watchers, the remote and sessions begun before positions keep present.js; its ordering and fallback tests now run on such a session, and the presenter window is expected not to reload.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
25 files changed,
+2,480
−36
fixtures/build-bundles.mjs+4 −1fixtures/presenter-entry.mjs+13 −0fixtures/presenter-keys.mjs+88 −0fixtures/presenter-keys.test.mjs+108 −0fixtures/presenter-window.mjs+250 −0fixtures/slide-window.mjs+112 −0fixtures/talk-draw.mjs+81 −0fixtures/talk-driver.mjs+274 −0fixtures/talk-link.mjs+224 −0fixtures/talk-link.test.mjs+197 −0fixtures/talk-store.mjs+179 −0internal/slides/assets_embed.go+6 −1internal/slides/credits/assets.json+1 −0internal/slides/locales/en.toml+9 −0internal/slides/presentation.go+39 −5internal/slides/presenter_window.go+47 −3internal/slides/static/presenter.bbc8971ba87c2dd3.js+2 −0internal/slides/static/presenter.css+61 −0internal/slides/templates/present.html+29 −4internal/slides/templates/presenter.html+24 −7internal/slidestest/browser_present_test.go+13 −10internal/slidestest/fonts_browser_test.go+34 −5internal/slidestest/presenter_moves_browser_test.go+587 −0internal/slidestest/presenter_moves_test.go+86 −0internal/slidestest/races_browser_test.go+12 −0
diff --git a/fixtures/build-bundles.mjs b/fixtures/build-bundles.mjs| index 0548d73..44a6593 100644 |
| --- a/fixtures/build-bundles.mjs |
| +++ b/fixtures/build-bundles.mjs |
| @@ -35,7 +35,10 @@ const bundles = [ |
| // (fonts-gate.mjs, internal/slides/fontgate.go). |
| { name: 'fontsgate', entry: 'fonts-gate.mjs' }, |
| // The hold: a classic, blocking script in <head>, so an IIFE. |
| - { name: 'fontshold', entry: 'fonts-hold.js', format: 'iife' } |
| + { name: 'fontshold', entry: 'fonts-hold.js', format: 'iife' }, |
| + // The presenter window and the slide window, moving at once |
| + // (presenter-entry.mjs, internal/slides/presenter_window.go). |
| + { name: 'presenter', entry: 'presenter-entry.mjs' } |
| ] |
| for (const { name, entry, format = 'esm' } of bundles) { |
diff --git a/fixtures/presenter-entry.mjs b/fixtures/presenter-entry.mjs| new file mode 100644 |
| index 0000000..4f93e6c |
| --- /dev/null |
| +++ b/fixtures/presenter-entry.mjs |
| @@ -0,0 +1,13 @@ |
| +// presenter-entry.mjs — the presenting windows' bundle |
| +// (internal/slides/static/presenter.<hash>.js), wiring and nothing |
| +// else. The presenter window (templates/presenter.html) and the slide |
| +// window of a session with a position (templates/present.html, for |
| +// whoever may drive it) both load it; each page's root says which it is |
| +// and where its talk is (data-talk). |
| +import { mountPresenterWindow } from './presenter-window.mjs' |
| +import { mountSlideWindow } from './slide-window.mjs' |
| + |
| +const presenter = document.querySelector('[presenter][data-talk]') |
| +const surface = document.querySelector('[slides-surface][data-talk]') |
| +if (presenter) mountPresenterWindow(presenter) |
| +else if (surface) mountSlideWindow(surface) |
diff --git a/fixtures/presenter-keys.mjs b/fixtures/presenter-keys.mjs| new file mode 100644 |
| index 0000000..f855fba |
| --- /dev/null |
| +++ b/fixtures/presenter-keys.mjs |
| @@ -0,0 +1,88 @@ |
| +// presenter-keys.mjs — the keys of spec §5.5, shared by the presenter |
| +// window and the slide window. |
| +// |
| +// → Space PageDown, clicker next press |
| +// ← PageUp, clicker back one press |
| +// Home, End first and last slide of the talk |
| +// a number, then Enter go to that slide |
| +// B or . black screen |
| +// O core or full |
| +// P open the presenter window |
| +// R reset the timer |
| +// Esc close what is open; leave a field |
| +// |
| +// A key held down is one press: its repeats are ignored. PageUp and |
| +// PageDown move the talk even from inside a field, because a clicker |
| +// sends them; every other key typed into a field is the field's. |
| +// |
| +// createKeys({act}) returns the keydown handler. act receives one of |
| +// {move: {op}}, {jump: n}, {open: 'presenter'}, {timer: 'reset'} or |
| +// {escape: true}; the window decides what each does. |
| + |
| +const MOVES = { |
| + ArrowRight: 'next', |
| + ' ': 'next', |
| + PageDown: 'next', |
| + ArrowLeft: 'back', |
| + PageUp: 'back', |
| + Home: 'first', |
| + End: 'last', |
| + b: 'black', |
| + B: 'black', |
| + '.': 'black', |
| + o: 'mode', |
| + O: 'mode' |
| +} |
| + |
| +// The keys a clicker sends, which work wherever focus is. |
| +const CLICKER = new Set(['PageDown', 'PageUp']) |
| + |
| +/** Whether the event was typed into something that takes text. */ |
| +export function inField (target) { |
| + if (!target) return false |
| + if (target.isContentEditable) return true |
| + const tag = String(target.tagName || '').toUpperCase() |
| + return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' |
| +} |
| + |
| +export function createKeys ({ act }) { |
| + // The digits typed so far, waiting for Enter. |
| + let number = '' |
| + |
| + return function onKey (e) { |
| + if (e.metaKey || e.ctrlKey || e.altKey) return |
| + const k = e.key |
| + if (k === 'Escape') { |
| + number = '' |
| + act({ escape: true }) |
| + return |
| + } |
| + if (inField(e.target) && !CLICKER.has(k)) return |
| + // One press per press of the key, however long it is held. |
| + if (e.repeat) { |
| + if (k in MOVES) e.preventDefault() |
| + return |
| + } |
| + if (/^[0-9]$/.test(k)) { |
| + number = (number + k).slice(-4) |
| + e.preventDefault() |
| + return |
| + } |
| + if (k === 'Enter') { |
| + if (!number) return |
| + const n = Number(number) |
| + number = '' |
| + e.preventDefault() |
| + if (n > 0) act({ jump: n }) |
| + return |
| + } |
| + number = '' |
| + let action = null |
| + if (k in MOVES) action = { move: { op: MOVES[k] } } |
| + else if (k === 'p' || k === 'P') action = { open: 'presenter' } |
| + else if (k === 'r' || k === 'R') action = { timer: 'reset' } |
| + if (!action) return |
| + e.preventDefault() |
| + act(action) |
| + } |
| +} |
diff --git a/fixtures/presenter-keys.test.mjs b/fixtures/presenter-keys.test.mjs| new file mode 100644 |
| index 0000000..8b76fb2 |
| --- /dev/null |
| +++ b/fixtures/presenter-keys.test.mjs |
| @@ -0,0 +1,108 @@ |
| +// fixtures/presenter-keys.test.mjs — the keys of spec §5.5 |
| +// (presenter-keys.mjs), on plain objects standing in for key events. |
| +import { test } from 'node:test' |
| +import assert from 'node:assert/strict' |
| +import { createKeys } from './presenter-keys.mjs' |
| + |
| +function key (k, extra = {}) { |
| + return { |
| + key: k, |
| + repeat: false, |
| + target: { tagName: 'BODY', isContentEditable: false }, |
| + prevented: false, |
| + preventDefault () { this.prevented = true }, |
| + ...extra |
| + } |
| +} |
| +const inField = (k, tag = 'INPUT') => key(k, { target: { tagName: tag, isContentEditable: false } }) |
| + |
| +function keys () { |
| + const acts = [] |
| + const handle = createKeys({ act: a => acts.push(a) }) |
| + return { acts, handle } |
| +} |
| + |
| +test('the table: each key does its one thing', () => { |
| + const { acts, handle } = keys() |
| + const table = [ |
| + ['ArrowRight', { move: { op: 'next' } }], |
| + [' ', { move: { op: 'next' } }], |
| + ['PageDown', { move: { op: 'next' } }], |
| + ['ArrowLeft', { move: { op: 'back' } }], |
| + ['PageUp', { move: { op: 'back' } }], |
| + ['Home', { move: { op: 'first' } }], |
| + ['End', { move: { op: 'last' } }], |
| + ['b', { move: { op: 'black' } }], |
| + ['B', { move: { op: 'black' } }], |
| + ['.', { move: { op: 'black' } }], |
| + ['o', { move: { op: 'mode' } }], |
| + ['O', { move: { op: 'mode' } }], |
| + ['p', { open: 'presenter' }], |
| + ['P', { open: 'presenter' }], |
| + ['r', { timer: 'reset' }], |
| + ['R', { timer: 'reset' }], |
| + ['Escape', { escape: true }] |
| + ] |
| + for (const [k, want] of table) { |
| + acts.length = 0 |
| + const e = key(k) |
| + handle(e) |
| + assert.deepEqual(acts, [want], k) |
| + assert.equal(e.prevented, k !== 'Escape', `${k} prevented`) |
| + } |
| +}) |
| + |
| +test('a held key is not a second press', () => { |
| + const { acts, handle } = keys() |
| + handle(key('ArrowRight')) |
| + handle(key('ArrowRight', { repeat: true })) |
| + handle(key('PageDown', { repeat: true })) |
| + assert.equal(acts.length, 1) |
| +}) |
| + |
| +test('a clicker works from inside a field, and nothing else does', () => { |
| + const { acts, handle } = keys() |
| + handle(inField('PageDown')) |
| + handle(inField('PageUp', 'TEXTAREA')) |
| + handle(inField('ArrowRight')) |
| + handle(inField(' ')) |
| + handle(inField('b', 'SELECT')) |
| + handle(key('p', { target: { tagName: 'DIV', isContentEditable: true } })) |
| + assert.deepEqual(acts, [{ move: { op: 'next' } }, { move: { op: 'back' } }]) |
| + handle(inField('Escape')) |
| + assert.deepEqual(acts.at(-1), { escape: true }) |
| +}) |
| + |
| +test('a number then Enter jumps', () => { |
| + const { acts, handle } = keys() |
| + handle(key('1')) |
| + handle(key('2')) |
| + assert.deepEqual(acts, [], 'digits alone do nothing') |
| + const enter = key('Enter') |
| + handle(enter) |
| + assert.deepEqual(acts, [{ jump: 12 }]) |
| + assert.ok(enter.prevented) |
| + // Enter with no number is left to whatever has focus. |
| + const bare = key('Enter') |
| + handle(bare) |
| + assert.equal(acts.length, 1) |
| + assert.ok(!bare.prevented) |
| + // Another key forgets the number. |
| + handle(key('3')) |
| + handle(key('ArrowRight')) |
| + handle(key('Enter')) |
| + assert.deepEqual(acts.slice(1), [{ move: { op: 'next' } }]) |
| + // Escape forgets it too. |
| + handle(key('4')) |
| + handle(key('Escape')) |
| + handle(key('Enter')) |
| + assert.deepEqual(acts.slice(2), [{ escape: true }]) |
| +}) |
| + |
| +test('modifier keys are the browser\'s', () => { |
| + const { acts, handle } = keys() |
| + handle(key('ArrowRight', { metaKey: true })) |
| + handle(key('r', { ctrlKey: true })) |
| + handle(key('p', { altKey: true })) |
| + assert.deepEqual(acts, []) |
| +}) |
diff --git a/fixtures/presenter-window.mjs b/fixtures/presenter-window.mjs| new file mode 100644 |
| index 0000000..79edb99 |
| --- /dev/null |
| +++ b/fixtures/presenter-window.mjs |
| @@ -0,0 +1,250 @@ |
| +// presenter-window.mjs — the presenter window (templates/presenter.html, |
| +// spec §5), moving at once. |
| +// |
| +// The server draws the window, and with scripts off its forms post and |
| +// redirect. This takes over: the window holds the talk |
| +// (talk-driver.mjs), a press redraws Now, Next, the notes and the header |
| +// from it in one task, and the server is told afterwards. Every word |
| +// comes from the page (data-text-* on the root, rendered from the |
| +// catalog); nothing here is English. |
| +// |
| +// Every press is answered in the header: the step count flashes, and |
| +// the position pulses, even when the press changes nothing (next at the |
| +// end of the talk). |
| +import { talkOrder } from './moves.mjs' |
| +import { createDriver, bindForms } from './talk-driver.mjs' |
| +import { createKeys } from './presenter-keys.mjs' |
| +import { install, reveal, fill, talkPlace, indexOf, restart } from './talk-draw.mjs' |
| + |
| +const MOVING = new Set(['next', 'back', 'first', 'last', 'goto']) |
| + |
| +function el (tag, attr, text) { |
| + const e = document.createElement(tag) |
| + if (attr) e.setAttribute(attr, '') |
| + if (text !== undefined) e.textContent = text |
| + return e |
| +} |
| + |
| +export function mountPresenterWindow (root) { |
| + const T = root.dataset |
| + const $ = sel => root.querySelector(sel) |
| + const head = $('[presenter-head]') |
| + const pos = $('[presenter-pos]') |
| + const status = $('[presenter-status]') |
| + const elapsed = $('[presenter-elapsed]') |
| + window.name = 'slides-presenter' |
| + |
| + // The header's parts that come and go with the slide, made once and |
| + // hidden when there is nothing to say. |
| + function part (attr, after) { |
| + let e = $('[' + attr + ']') |
| + if (!e) { |
| + e = el('span', attr) |
| + e.hidden = true |
| + after.after(e) |
| + } |
| + return e |
| + } |
| + const stepcount = part('presenter-stepcount', pos) |
| + if (!stepcount.firstChild) { |
| + stepcount.setAttribute('role', 'status') |
| + const track = el('span', 'presenter-track') |
| + track.setAttribute('aria-hidden', 'true') |
| + stepcount.append(track, el('span', 'presenter-steptext')) |
| + } |
| + const mode = part('presenter-mode', stepcount) |
| + const black = part('presenter-black', mode) |
| + |
| + function drawHead (s, to, store) { |
| + const view = store.view |
| + const count = pos.querySelector('[presenter-count]') |
| + if (count) count.textContent = fill(T.textProgress, talkPlace(view, to.mode, indexOf(view, to.slide))) |
| + const n = Number(s.presses) || 0 |
| + stepcount.hidden = n === 0 |
| + if (n) { |
| + const track = stepcount.querySelector('[presenter-track]') |
| + while (track.children.length < n) track.append(el('i')) |
| + while (track.children.length > n) track.lastChild.remove() |
| + ;[...track.children].forEach((i, k) => i.toggleAttribute('data-done', k < to.step)) |
| + stepcount.querySelector('[presenter-steptext]').textContent = fill(T.textStep, { n: to.step, total: n }) |
| + } |
| + const both = store.slides.some(x => x.full) |
| + mode.hidden = !both |
| + if (both) mode.textContent = to.mode === 'full' ? T.textModeFull : T.textModeCore |
| + black.hidden = !to.black |
| + black.textContent = T.textBlack |
| + const menuMode = root.querySelector('[presenter-menu] form input[name="op"][value="mode"]') |
| + const label = menuMode && menuMode.form.querySelector('button') |
| + if (label) label.textContent = to.mode === 'full' ? T.textMenuCore : T.textMenuFull |
| + } |
| + |
| + // frame is a fresh presenter-frame holding html at step, or the end. |
| + function frame (html, step) { |
| + const f = el('div', 'presenter-frame') |
| + if (html === null) { |
| + f.setAttribute('data-end', '') |
| + return f |
| + } |
| + const scale = el('div', 'presenter-scale') |
| + install(scale, html, step) |
| + f.append(scale) |
| + return f |
| + } |
| + |
| + // What Next shows, so a press that leaves it the same redraws nothing. |
| + let nextDrawn = '' |
| + |
| + function drawNext (s, to, store) { |
| + const view = store.view |
| + const index = indexOf(view, to.slide) |
| + const label = $('[presenter-next-label] span') |
| + const fit = $('[presenter-panel="next"] [presenter-fit]') |
| + const n = Number(s.presses) || 0 |
| + const after = talkOrder(view, to.mode).find(i => i > index) |
| + let html = null |
| + let step = 0 |
| + let words = T.textNextEnd |
| + if (to.step < n) { |
| + words = T.textNextStep |
| + html = s.html |
| + step = to.step + 1 |
| + } else if (after !== undefined) { |
| + words = T.textNextSlide |
| + html = store.slide(view.slides[after].id).html |
| + } |
| + label.textContent = words |
| + const drawn = store.deckSeq + ':' + step + ':' + html |
| + if (drawn === nextDrawn) return |
| + nextDrawn = drawn |
| + fit.replaceChildren(frame(html, step)) |
| + } |
| + |
| + function drawNotes (s, to) { |
| + const notes = $('[presenter-notes]') |
| + const parts = Array.isArray(s.notes) ? s.notes : [] |
| + if (!parts.length) { |
| + notes.replaceChildren(el('p', 'presenter-nonotes', T.textNonotes)) |
| + return |
| + } |
| + const bright = Math.min(Math.max(to.step, 0), parts.length - 1) |
| + notes.replaceChildren(...parts.map((html, i) => { |
| + const section = el('section', 'presenter-part') |
| + if (parts.length > 1) section.setAttribute('data-part', i < bright ? 'past' : i > bright ? 'later' : 'now') |
| + section.innerHTML = html |
| + return section |
| + })) |
| + } |
| + |
| + function draw (to, from, { fresh, store }) { |
| + const s = store.slide(to.slide) |
| + if (!s) return |
| + const now = $('[presenter-panel="now"] [presenter-frame]') |
| + const scale = now.querySelector('[presenter-scale]') |
| + const same = !fresh && from && from.slide === to.slide |
| + if (!same) install(scale, s.html, to.step) |
| + else if (from.step !== to.step) reveal(scale, to.step) |
| + now.toggleAttribute('data-black', !!to.black) |
| + drawHead(s, to, store) |
| + drawNext(s, to, store) |
| + if (!same || from.step !== to.step) drawNotes(s, to) |
| + root.setAttribute('data-slide', String(s.number)) |
| + root.setAttribute('data-step', String(to.step)) |
| + root.setAttribute('data-mode', to.mode) |
| + root.setAttribute('data-blackout', to.black ? 'true' : 'false') |
| + root.setAttribute('data-deck-seq', String(store.deckSeq)) |
| + // The address says where the window was drawn when it loaded; a |
| + // reload should draw where the talk is. |
| + const u = new URL(location.href) |
| + if (u.searchParams.has('slide') || u.searchParams.has('step')) { |
| + u.searchParams.delete('slide') |
| + u.searchParams.delete('step') |
| + history.replaceState(history.state, '', u.href) |
| + } |
| + } |
| + |
| + // What the header says beside the talk: how far the loading has got, |
| + // or that this window is on its own. |
| + let progress = '' |
| + let offline = false |
| + function say () { |
| + if (status) status.textContent = offline ? T.textOffline : progress |
| + } |
| + |
| + // The timer starts at the talk's first press (the server's timer_at), |
| + // and a reset waits for the next. |
| + function since () { return elapsed && elapsed.getAttribute('data-timer-since') } |
| + function pressed (m) { |
| + restart(stepcount, 'data-flash') |
| + restart(pos, 'data-pulse') |
| + if (MOVING.has(m.op) && elapsed && !since()) elapsed.setAttribute('data-timer-since', String(Math.floor(Date.now() / 1000))) |
| + } |
| + |
| + const driver = createDriver({ |
| + root, |
| + talkHref: T.talk, |
| + streamHref: T.stream, |
| + action: T.command, |
| + token: root.getAttribute('data-remote-token') || '', |
| + draw, |
| + onPressed: pressed, |
| + onStatus: s => { offline = s === 'offline'; say() }, |
| + onProgress: p => { |
| + root.setAttribute('data-loaded', p.finished && !p.failed ? 'all' : String(p.done)) |
| + progress = !p.finished ? fill(T.textLoading, { n: p.done, total: p.total }) |
| + : p.failed ? fill(T.textLoadingFailed, { n: p.failed }) : '' |
| + say() |
| + } |
| + }) |
| + |
| + function resetTimer () { |
| + driver.timerReset() |
| + if (!elapsed) return |
| + elapsed.removeAttribute('data-timer-since') |
| + elapsed.textContent = '0:00' |
| + } |
| + |
| + const menu = $('[presenter-more-menu]') |
| + bindForms(root, T.command, { |
| + move: m => driver.move(m), |
| + timerReset: resetTimer, |
| + get store () { return driver.store } |
| + }, () => { if (menu) menu.open = false }) |
| + |
| + const onKey = createKeys({ |
| + act (a) { |
| + if (a.move) driver.move(a.move) |
| + else if (a.jump) driver.jump(a.jump) |
| + else if (a.timer) resetTimer() |
| + else if (a.escape) { |
| + if (menu && menu.open) menu.open = false |
| + const f = document.activeElement |
| + if (f && f !== document.body && f.blur) f.blur() |
| + } |
| + // P opens the presenter window, which this is. |
| + } |
| + }) |
| + document.addEventListener('keydown', onKey) |
| + |
| + tick(elapsed, $('[data-clock]')) |
| +} |
| + |
| +// tick keeps the clock and the timer going: the clock in the room's |
| +// own time, the timer in numbers only. |
| +function tick (timer, clock) { |
| + const two = n => (n < 10 ? '0' : '') + n |
| + function timerNow () { |
| + const at = timer && timer.getAttribute('data-timer-since') |
| + if (!at) return |
| + const s = Math.max(0, Math.floor(Date.now() / 1000 - Number(at))) |
| + const h = Math.floor(s / 3600) |
| + const m = Math.floor(s / 60) % 60 |
| + timer.textContent = h ? h + ':' + two(m) + ':' + two(s % 60) : m + ':' + two(s % 60) |
| + } |
| + function clockNow () { |
| + if (clock) clock.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) |
| + } |
| + timerNow() |
| + clockNow() |
| + setInterval(timerNow, 1000) |
| + setInterval(clockNow, 15000) |
| +} |
diff --git a/fixtures/slide-window.mjs b/fixtures/slide-window.mjs| new file mode 100644 |
| index 0000000..9d9d394 |
| --- /dev/null |
| +++ b/fixtures/slide-window.mjs |
| @@ -0,0 +1,112 @@ |
| +// slide-window.mjs — the slide window (templates/present.html, GET |
| +// /p/{session}) of a session with a position, for whoever may drive it: |
| +// the projector, moving at once. |
| +// |
| +// The server draws the slide, and with scripts off the bar's forms post |
| +// and redirect. This holds the talk (talk-driver.mjs), takes the same |
| +// keys as the presenter window, and swaps the slide in one task from |
| +// memory: a step in place, the slide whole, never a blank stage. When |
| +// the network is gone and this window is not the one pressing, it holds |
| +// still and says it is waiting. Every word comes from the page |
| +// (data-text-* on the surface). |
| +// |
| +// The follow link, the remote and sessions begun before positions keep |
| +// static/present.js. |
| +import { createDriver, bindForms } from './talk-driver.mjs' |
| +import { createKeys } from './presenter-keys.mjs' |
| +import { install, reveal, fill, talkPlace, indexOf } from './talk-draw.mjs' |
| + |
| +export function mountSlideWindow (root) { |
| + const T = root.dataset |
| + const stage = root.querySelector('[slides-stage]') |
| + const note = root.querySelector('[slides-blackout]') |
| + const waiting = root.querySelector('[slides-waiting]') |
| + const region = root.querySelector('[slides-announce]') |
| + if (!stage) return |
| + |
| + // counterText is the counter's own words: the line after the label |
| + // only a screen reader hears. |
| + function counterText (text) { |
| + const counter = root.querySelector('[slides-counter]') |
| + if (!counter) return |
| + const last = counter.lastChild |
| + if (last && last.nodeType === Node.TEXT_NODE) last.textContent = ' ' + text |
| + else counter.append(' ' + text) |
| + } |
| + |
| + function draw (to, from, { fresh, store }) { |
| + const s = store.slide(to.slide) |
| + if (!s) return |
| + const view = store.view |
| + const same = !fresh && from && from.slide === to.slide |
| + if (!same) { |
| + install(stage, s.html, to.step) |
| + const said = fill(T.textAnnounce, { n: s.number, total: store.slides.length, title: s.title }) |
| + root.setAttribute('data-announce', said) |
| + if (region && region.textContent !== said) region.textContent = said |
| + } else if (from.step !== to.step) { |
| + reveal(stage, to.step) |
| + } |
| + const place = talkPlace(view, to.mode, indexOf(view, to.slide)) |
| + counterText(fill(T.textProgress, place)) |
| + const bar = root.querySelector('[slides-progress]') |
| + if (bar) { |
| + bar.setAttribute('value', String(place.n)) |
| + bar.setAttribute('max', String(place.total)) |
| + } |
| + root.setAttribute('data-slide', String(s.number)) |
| + root.setAttribute('data-step', String(to.step)) |
| + root.setAttribute('data-mode', to.mode) |
| + root.setAttribute('data-blackout', to.black ? 'true' : 'false') |
| + root.setAttribute('data-deck-seq', String(store.deckSeq)) |
| + if (note) note.hidden = !to.black |
| + const u = new URL(location.href) |
| + if (u.searchParams.has('slide') || u.searchParams.has('step')) { |
| + u.searchParams.delete('slide') |
| + u.searchParams.delete('step') |
| + history.replaceState(history.state, '', u.href) |
| + } |
| + } |
| + |
| + const driver = createDriver({ |
| + root, |
| + talkHref: T.talk, |
| + streamHref: T.stream, |
| + action: T.command, |
| + token: root.getAttribute('data-remote-token') || '', |
| + draw, |
| + onProgress: p => root.setAttribute('data-loaded', p.finished && !p.failed ? 'all' : String(p.done)), |
| + onStatus: s => { |
| + if (!waiting) return |
| + waiting.textContent = T.textWaiting |
| + waiting.hidden = s !== 'offline' |
| + } |
| + }) |
| + |
| + bindForms(root, T.command, driver) |
| + |
| + const onKey = createKeys({ |
| + act (a) { |
| + if (a.move) driver.move(a.move) |
| + else if (a.jump) driver.jump(a.jump) |
| + else if (a.timer) driver.timerReset() |
| + else if (a.open && T.presenter) window.open(T.presenter, 'slides-presenter') |
| + else if (a.escape) { |
| + if (document.fullscreenElement) document.exitFullscreen() |
| + const f = document.activeElement |
| + if (f && f !== document.body && f.blur) f.blur() |
| + } |
| + } |
| + }) |
| + document.addEventListener('keydown', onKey) |
| + |
| + // A swipe on a touch screen is a press too. |
| + let startX = null |
| + root.addEventListener('touchstart', e => { startX = e.changedTouches[0].clientX }, { passive: true }) |
| + root.addEventListener('touchend', e => { |
| + if (startX === null) return |
| + const dx = e.changedTouches[0].clientX - startX |
| + startX = null |
| + if (Math.abs(dx) >= 60) driver.move({ op: dx < 0 ? 'next' : 'back' }) |
| + }, { passive: true }) |
| +} |
diff --git a/fixtures/talk-draw.mjs b/fixtures/talk-draw.mjs| new file mode 100644 |
| index 0000000..145d7a6 |
| --- /dev/null |
| +++ b/fixtures/talk-draw.mjs |
| @@ -0,0 +1,81 @@ |
| +// talk-draw.mjs — what both presenting windows draw a slide with, from |
| +// the talk they hold (talk-store.mjs): a slide at a step, a step |
| +// applied in place, the counter's place in the talk, and the catalog's |
| +// sentences filled in. |
| +// |
| +// A slide comes from the server rendered at press 0, every box that |
| +// arrives on a press marked data-press (render.go). At step k a box |
| +// whose press is after k is data-waiting, and keeps its space |
| +// (slides.css). Moving to another step of the slide on screen is done in |
| +// place: what has just arrived is marked data-arriving until its effect |
| +// ends (slides.css draws it, and leaves it out under reduced motion); |
| +// back marks nothing. The same as static/present.js does for the follow |
| +// link and the remote. |
| +import { talkOrder } from './moves.mjs' |
| + |
| +/** Marks what is still to come at step, without animating anything. */ |
| +export function waitAt (container, step) { |
| + for (const el of container.querySelectorAll('[data-press]')) { |
| + el.removeAttribute('data-arriving') |
| + if (Number(el.getAttribute('data-press')) > step) el.setAttribute('data-waiting', '') |
| + else el.removeAttribute('data-waiting') |
| + } |
| +} |
| + |
| +/** Draws a slide's html in container at step, in one go. */ |
| +export function install (container, html, step) { |
| + const t = document.createElement('template') |
| + t.innerHTML = html |
| + waitAt(t.content, step) |
| + container.replaceChildren(t.content) |
| +} |
| + |
| +function arrived (e) { |
| + if (e.target !== e.currentTarget) return |
| + e.currentTarget.removeAttribute('data-arriving') |
| + e.currentTarget.removeEventListener('animationend', arrived) |
| +} |
| + |
| +/** Moves the slide in container to step in place; only what arrives is marked arriving. */ |
| +export function reveal (container, step) { |
| + for (const el of container.querySelectorAll('[data-arriving]')) el.removeAttribute('data-arriving') |
| + for (const el of container.querySelectorAll('[data-press]')) { |
| + if (Number(el.getAttribute('data-press')) > step) { |
| + el.setAttribute('data-waiting', '') |
| + } else if (el.hasAttribute('data-waiting')) { |
| + el.removeAttribute('data-waiting') |
| + el.setAttribute('data-arriving', '') |
| + el.addEventListener('animationend', arrived) |
| + } |
| + } |
| +} |
| + |
| +/** A catalog sentence with its {name}s filled in. */ |
| +export function fill (pattern, values) { |
| + return String(pattern || '').replace(/\{(\w+)\}/g, (m, k) => (k in values ? String(values[k]) : m)) |
| +} |
| + |
| +/** |
| + * The counter's "n / total" for the slide at index of view: its place |
| + * in the talk being given, in mode. A slide outside that talk (a |
| + * full-only slide shown in the short version) takes the place of the |
| + * slide before it (presenting_position.go's talkPlace). |
| + */ |
| +export function talkPlace (view, mode, index) { |
| + const order = talkOrder(view, mode) |
| + if (!order.length) return { n: index + 1, total: view.slides.length } |
| + let n = 1 |
| + order.forEach((i, k) => { if (i <= index) n = k + 1 }) |
| + return { n, total: order.length } |
| +} |
| + |
| +/** The index of the slide with id in view, or -1. */ |
| +export function indexOf (view, id) { |
| + return view.slides.findIndex(s => s.id === id) |
| +} |
| + |
| +/** Restarts a CSS animation by flipping the attribute it hangs on between two values. */ |
| +export function restart (el, name) { |
| + if (!el) return |
| + el.setAttribute(name, el.getAttribute(name) === 'a' ? 'b' : 'a') |
| +} |
diff --git a/fixtures/talk-driver.mjs b/fixtures/talk-driver.mjs| new file mode 100644 |
| index 0000000..0a36c34 |
| --- /dev/null |
| +++ b/fixtures/talk-driver.mjs |
| @@ -0,0 +1,274 @@ |
| +// 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 } |
| + if (!d.slideId) return |
| + h.position({ slide: d.slideId, step: Number(d.step) || 0, mode: d.mode, black: !!d.blackout, seq: Number(d.seq) || 0 }) |
| + }) |
| + } |
| + 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() |
| + }) |
| + } |
| +} |
| + |
| +export function createDriver ({ root, talkHref, streamHref, action, token, draw, onStatus = () => {}, onProgress = () => {}, onPressed = () => {} }) { |
| + 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 = [] |
| + |
| + 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) 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 !== 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 |
| + 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() } |
| + }) |
| + link.resume(pos) |
| + onStatus(link.status()) |
| + for (const m of early.splice(0)) move(m) |
| + 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) |
| + }) |
| +} |
diff --git a/fixtures/talk-link.mjs b/fixtures/talk-link.mjs| new file mode 100644 |
| index 0000000..e4a5228 |
| --- /dev/null |
| +++ b/fixtures/talk-link.mjs |
| @@ -0,0 +1,224 @@ |
| +// talk-link.mjs — a window's link to the server while it presents |
| +// (spec §6, "Moving through the talk"). Shared by the presenter window |
| +// and the slide window. |
| +// |
| +// The window moves at once, from what it holds, and then tells the |
| +// link. The link tells the server, and decides which of the server's |
| +// positions the window should take: |
| +// |
| +// - Presses go to the server one at a time, in order, each with its own |
| +// id, so a press sent twice counts once (presenting_position.go). |
| +// - While a press is unanswered, the server's positions (its answers |
| +// and the stream's events) are recorded but not applied. When the |
| +// queue empties, the newest is applied if its seq is higher than the |
| +// last applied and it differs from where the window stands. |
| +// - A send that fails or takes over 3 seconds marks the link offline. |
| +// Unanswered presses are dropped: the position they reached is kept, |
| +// and the server is told it on reconnecting. |
| +// - On reconnecting, a window that pressed while offline (or lost a |
| +// press) sends resume with where it stands; one that did not takes |
| +// the server's position. |
| +// |
| +// post(fields) sends one press and resolves with the server's answer, |
| +// {slide, step, mode, black, seq, deckSeq}. stream({open, error, |
| +// position}) starts hearing the server's positions in the same shape |
| +// and returns a function that stops. now() is the time in ms, and |
| +// after(ms, fn) a timer that returns its cancel: both are injected so |
| +// a test can run on a fake clock. |
| + |
| +// How long a press may wait for its answer before the link is offline. |
| +export const ANSWER_TIMEOUT_MS = 3000 |
| + |
| +// How often an offline link that owes the server a resume tries again, |
| +// when the stream has not already said the network is back. |
| +export const RETRY_MS = 2000 |
| + |
| +// How long the stream may be gone before the link is offline. The |
| +// server ends every stream after five minutes and the browser opens it |
| +// again three seconds later; that is not a split, and a room should not |
| +// see the slide window say it is waiting each time. |
| +export const STREAM_GRACE_MS = 5000 |
| + |
| +const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' |
| + |
| +/** A press id: 22 characters from the alphabet the server accepts, from crypto.getRandomValues. */ |
| +export function pressID () { |
| + const bytes = new Uint8Array(22) |
| + globalThis.crypto.getRandomValues(bytes) |
| + let out = '' |
| + // 64 letters divide 256 evenly, so each is equally likely. |
| + for (const b of bytes) out += ALPHABET[b & 63] |
| + return out |
| +} |
| + |
| +// The ops moves.mjs names, as the command form names them. |
| +const WIRE = { back: 'prev', black: 'blackout' } |
| + |
| +/** The form fields for a move: {op, slide} in moves.mjs's words. */ |
| +export function pressFields (move) { |
| + const fields = { op: WIRE[move.op] || move.op } |
| + if (move.slide) fields.slide = String(move.slide) |
| + return fields |
| +} |
| + |
| +/** Whether two positions differ in anything the window draws. */ |
| +export function differs (a, b) { |
| + if (!a || !b) return a !== b |
| + return a.slide !== b.slide || (a.step || 0) !== (b.step || 0) || a.mode !== b.mode || !!a.black !== !!b.black |
| +} |
| + |
| +const defaultAfter = (ms, fn) => { |
| + const id = setTimeout(fn, ms) |
| + return () => clearTimeout(id) |
| +} |
| + |
| +export function createLink ({ |
| + post, |
| + stream, |
| + now = () => Date.now(), |
| + after = defaultAfter, |
| + onPosition = () => {}, |
| + onStatus = () => {}, |
| + onDeckSeq = () => {}, |
| + makeID = pressID |
| +}) { |
| + let online = true |
| + let queue = [] // presses not yet answered: [{fields}] |
| + let sending = null // the press on the wire, while it is |
| + let owed = false // the server has not heard where this window went |
| + let standing = null // where the window stands |
| + let newest = null // the newest position the server has said |
| + let applied = 0 // the seq of the last position taken or matched |
| + let retry = null |
| + let gap = null // the stream's grace, while it is gone |
| + |
| + function status () { return online ? 'online' : 'offline' } |
| + |
| + function say (s) { |
| + const was = online |
| + online = s === 'online' |
| + if (was !== online) onStatus(status()) |
| + } |
| + |
| + // hear is every position the server says, from any source. |
| + function hear (pos) { |
| + if (!pos || typeof pos.seq !== 'number') return |
| + if (typeof pos.deckSeq === 'number') onDeckSeq(pos.deckSeq) |
| + if (!newest || pos.seq > newest.seq) newest = pos |
| + } |
| + |
| + // take applies the newest position once nothing is waiting. |
| + function take () { |
| + if (!online || sending || queue.length || !newest || newest.seq <= applied) return |
| + applied = newest.seq |
| + if (!differs(newest, standing)) return |
| + standing = { slide: newest.slide, step: newest.step || 0, mode: newest.mode, black: !!newest.black } |
| + onPosition({ ...standing, seq: newest.seq }) |
| + } |
| + |
| + function pump () { |
| + if (!online || sending || !queue.length) return |
| + const item = queue[0] |
| + const sentAt = now() |
| + // mine is this send; once the link has given up on it (lost), what |
| + // comes back for it is nobody's. |
| + const mine = { item } |
| + sending = mine |
| + const cancel = after(ANSWER_TIMEOUT_MS, () => { if (sending === mine) lost() }) |
| + Promise.resolve() |
| + .then(() => post({ ...item.fields, press: item.id })) |
| + .then(answer => { |
| + if (sending !== mine) return |
| + cancel() |
| + // An answer that took too long is as good as lost: the window |
| + // may have been throttled and the timer late. |
| + if (now() - sentAt > ANSWER_TIMEOUT_MS) { lost(); return } |
| + sending = null |
| + queue.shift() |
| + hear(answer) |
| + if (queue.length) pump() |
| + else take() |
| + }, () => { |
| + if (sending !== mine) return |
| + cancel() |
| + lost() |
| + }) |
| + } |
| + |
| + // lost is the network gone: every unanswered press is dropped, and |
| + // the window's position is owed to the server instead. |
| + function lost () { |
| + if (sending || queue.length) owed = true |
| + sending = null |
| + queue = [] |
| + say('offline') |
| + schedule() |
| + } |
| + |
| + // schedule tries the resume again while offline and owing one. |
| + function schedule () { |
| + if (retry || online || !owed) return |
| + retry = after(RETRY_MS, () => { |
| + retry = null |
| + if (online || !owed) return |
| + reconnect() |
| + }) |
| + } |
| + |
| + // reconnect is the network back: the resume if one is owed, which |
| + // is a press like any other (it may fail, and the link is offline |
| + // again); otherwise the server's newest position is taken. |
| + function reconnect () { |
| + if (retry) { retry(); retry = null } |
| + say('online') |
| + if (owed && standing) { |
| + owed = false |
| + queue = [{ |
| + id: makeID(), |
| + fields: { op: 'resume', at_slide: standing.slide, at_step: String(standing.step || 0), at_mode: standing.mode } |
| + }] |
| + pump() |
| + return |
| + } |
| + take() |
| + } |
| + |
| + function heardFrom () { |
| + if (gap) { gap(); gap = null } |
| + } |
| + |
| + stream({ |
| + open () { |
| + heardFrom() |
| + if (!online) reconnect() |
| + }, |
| + error () { |
| + // The stream opens again by itself. Gone for longer than its |
| + // grace, nothing is reaching this window: offline. |
| + if (!online || gap) return |
| + gap = after(STREAM_GRACE_MS, () => { gap = null; if (online) lost() }) |
| + }, |
| + position (pos) { |
| + heardFrom() |
| + hear(pos) |
| + // Hearing anything means the network is back. |
| + if (!online) reconnect() |
| + else take() |
| + } |
| + }) |
| + |
| + return { |
| + /** The window has moved by move to landedAt; tell the server. */ |
| + press (move, landedAt) { |
| + if (landedAt) standing = { ...landedAt } |
| + if (!online) { owed = true; schedule(); return } |
| + queue.push({ id: makeID(), fields: pressFields(move) }) |
| + pump() |
| + }, |
| + /** The window stands at position without a press (it started there, or a newer deck settled it). */ |
| + resume (position) { |
| + standing = position ? { ...position } : null |
| + }, |
| + status |
| + } |
| +} |
diff --git a/fixtures/talk-link.test.mjs b/fixtures/talk-link.test.mjs| new file mode 100644 |
| index 0000000..fbfe64d |
| --- /dev/null |
| +++ b/fixtures/talk-link.test.mjs |
| @@ -0,0 +1,197 @@ |
| +// fixtures/talk-link.test.mjs — the link between a window and the |
| +// server (talk-link.mjs), on a fake clock and a fake network: what is |
| +// sent, in what order, and which of the server's positions the window |
| +// is asked to take. |
| +import { test } from 'node:test' |
| +import assert from 'node:assert/strict' |
| +import { createLink, pressID } from './talk-link.mjs' |
| + |
| +// fakeNet is the network: every post waits until the test answers or |
| +// fails it, and the stream's handlers are the test's to call. |
| +function fakeNet () { |
| + const posts = [] |
| + const net = { |
| + posts, |
| + handlers: null, |
| + post (fields) { |
| + return new Promise((resolve, reject) => posts.push({ fields, resolve, reject })) |
| + }, |
| + stream (handlers) { |
| + net.handlers = handlers |
| + return () => { net.handlers = null } |
| + } |
| + } |
| + return net |
| +} |
| + |
| +// fakeClock is time that moves only when the test says so. |
| +function fakeClock () { |
| + let t = 0 |
| + let timers = [] |
| + return { |
| + now: () => t, |
| + after (ms, fn) { |
| + const timer = { at: t + ms, fn } |
| + timers.push(timer) |
| + return () => { timers = timers.filter(x => x !== timer) } |
| + }, |
| + advance (ms) { |
| + t += ms |
| + const due = timers.filter(x => x.at <= t) |
| + timers = timers.filter(x => x.at > t) |
| + for (const x of due) x.fn() |
| + } |
| + } |
| +} |
| + |
| +const settle = () => new Promise(resolve => setImmediate(resolve)) |
| +const at = (slide, step, seq) => ({ slide, step, mode: 'core', black: false, seq, deckSeq: 1 }) |
| + |
| +function rig (start = at('a', 0, 1)) { |
| + const net = fakeNet() |
| + const clock = fakeClock() |
| + const moved = [] |
| + const statuses = [] |
| + const link = createLink({ |
| + post: net.post, |
| + stream: net.stream, |
| + now: clock.now, |
| + after: clock.after, |
| + onPosition: pos => moved.push(pos), |
| + onStatus: s => statuses.push(s) |
| + }) |
| + link.resume(start) |
| + net.handlers.open() |
| + net.handlers.position(start) |
| + return { net, clock, link, moved, statuses } |
| +} |
| + |
| +test('a press is sent once and in order', async () => { |
| + const { net, link } = rig() |
| + link.press({ op: 'next' }, at('a', 1)) |
| + link.press({ op: 'next' }, at('a', 2)) |
| + link.press({ op: 'back' }, at('a', 1)) |
| + link.press({ op: 'goto', slide: 'c' }, at('c', 0)) |
| + await settle() |
| + assert.equal(net.posts.length, 1, 'one press on the wire at a time') |
| + const ids = new Set() |
| + const ops = [] |
| + for (let i = 0; i < 4; i++) { |
| + const p = net.posts[i] |
| + assert.ok(p, `press ${i + 1} was sent`) |
| + ops.push(p.fields.op + (p.fields.slide ? ':' + p.fields.slide : '')) |
| + assert.match(p.fields.press, /^[A-Za-z0-9_-]{22}$/) |
| + ids.add(p.fields.press) |
| + p.resolve(at('x', 0, 2 + i)) |
| + await settle() |
| + } |
| + assert.deepEqual(ops, ['next', 'next', 'prev', 'goto:c']) |
| + assert.equal(ids.size, 4, 'each press has its own id') |
| + assert.equal(net.posts.length, 4, 'nothing sent twice') |
| +}) |
| + |
| +test('a late answer does not move a window with presses waiting', async () => { |
| + const { net, link, moved } = rig() |
| + link.press({ op: 'next' }, at('a', 1)) |
| + link.press({ op: 'next' }, at('a', 2)) |
| + await settle() |
| + // The phone pressed meanwhile: heard, not taken. |
| + net.handlers.position(at('b', 0, 2)) |
| + net.posts[0].resolve(at('b', 0, 3)) |
| + await settle() |
| + assert.deepEqual(moved, [], 'nothing applied while a press waits') |
| + net.posts[1].resolve(at('b', 1, 4)) |
| + await settle() |
| + assert.deepEqual(moved.map(p => [p.slide, p.step]), [['b', 1]], 'the newest, once the queue is empty') |
| + // An older event arriving late changes nothing. |
| + net.handlers.position(at('a', 2, 3)) |
| + await settle() |
| + assert.equal(moved.length, 1) |
| + // Its own answer, where the window already stands, moves nothing. |
| + link.press({ op: 'next' }, at('b', 2)) |
| + await settle() |
| + net.posts[2].resolve(at('b', 2, 5)) |
| + await settle() |
| + assert.equal(moved.length, 1) |
| + net.handlers.position(at('c', 0, 6)) |
| + await settle() |
| + assert.deepEqual(moved.map(p => p.slide), ['b', 'c']) |
| +}) |
| + |
| +test('offline presses end in one resume', async () => { |
| + const { net, clock, link, statuses } = rig() |
| + link.press({ op: 'next' }, at('a', 1)) |
| + link.press({ op: 'next' }, at('a', 2)) |
| + await settle() |
| + // No answer in three seconds: offline, and the waiting press dropped. |
| + clock.advance(3001) |
| + await settle() |
| + assert.equal(link.status(), 'offline') |
| + assert.equal(statuses.at(-1), 'offline') |
| + link.press({ op: 'next' }, at('b', 0)) |
| + link.press({ op: 'next' }, at('c', 0)) |
| + await settle() |
| + assert.equal(net.posts.length, 1, 'nothing sent while offline') |
| + // The late answer to the dropped press changes nothing. |
| + net.posts[0].resolve(at('a', 1, 2)) |
| + net.handlers.error() |
| + await settle() |
| + net.handlers.open() |
| + await settle() |
| + assert.equal(link.status(), 'online') |
| + assert.equal(net.posts.length, 2, 'one resume') |
| + assert.deepEqual( |
| + { op: net.posts[1].fields.op, slide: net.posts[1].fields.at_slide, step: net.posts[1].fields.at_step, mode: net.posts[1].fields.at_mode }, |
| + { op: 'resume', slide: 'c', step: '0', mode: 'core' }) |
| + net.handlers.position(at('z', 0, 9)) // the phone's press, made while cut |
| + net.posts[1].resolve(at('c', 0, 10)) |
| + await settle() |
| + net.handlers.open() |
| + await settle() |
| + assert.equal(net.posts.length, 2, 'still one resume') |
| +}) |
| + |
| +test('a failed send is offline at once', async () => { |
| + const { net, link } = rig() |
| + link.press({ op: 'next' }, at('a', 1)) |
| + await settle() |
| + net.posts[0].reject(new Error('offline')) |
| + await settle() |
| + assert.equal(link.status(), 'offline') |
| +}) |
| + |
| +test('a stream that comes back by itself is not a split', async () => { |
| + const { net, clock, link, statuses } = rig() |
| + net.handlers.error() |
| + clock.advance(3000) |
| + net.handlers.open() |
| + clock.advance(5000) |
| + await settle() |
| + assert.equal(link.status(), 'online') |
| + assert.deepEqual(statuses, []) |
| +}) |
| + |
| +test('a window that pressed nothing takes the server\'s position', async () => { |
| + const { net, clock, link, moved, statuses } = rig() |
| + net.handlers.error() |
| + clock.advance(5001) |
| + await settle() |
| + assert.equal(link.status(), 'offline') |
| + net.handlers.open() |
| + net.handlers.position(at('d', 1, 7)) |
| + await settle() |
| + assert.equal(link.status(), 'online') |
| + assert.deepEqual(statuses, ['offline', 'online']) |
| + assert.equal(net.posts.length, 0, 'no resume') |
| + assert.deepEqual(moved.map(p => [p.slide, p.step]), [['d', 1]]) |
| +}) |
| + |
| +test('a press id is 22 characters of the allowed alphabet', () => { |
| + const seen = new Set() |
| + for (let i = 0; i < 200; i++) { |
| + const id = pressID() |
| + assert.match(id, /^[A-Za-z0-9_-]{22}$/) |
| + seen.add(id) |
| + } |
| + assert.equal(seen.size, 200) |
| +}) |
diff --git a/fixtures/talk-store.mjs b/fixtures/talk-store.mjs| new file mode 100644 |
| index 0000000..5b3524f |
| --- /dev/null |
| +++ b/fixtures/talk-store.mjs |
| @@ -0,0 +1,179 @@ |
| +// talk-store.mjs — the whole talk, in memory (spec §6, "Getting |
| +// ready"; S17). Shared by the presenter window and the slide window. |
| +// |
| +// GET /p/{session}/talk (presenting_talk.go) is every slide of the full |
| +// talk, rendered at press 0, with the pictures it shows and, for whoever |
| +// may drive, its notes. A slide is ready once its families are on (the |
| +// font gate's prepareSection) and its pictures are decoded, so a press |
| +// that lands on it needs no network. Until it is ready the window keeps |
| +// what it shows (has, ready). |
| +// |
| +// The talk lives in memory only. A newer version of the deck (refresh) |
| +// is loaded beside the one in use, quietly, and taken when the window |
| +// says so (adopt), which it does at its next change of slide. |
| +// |
| +// view is the version in moves.mjs's shape, so talkOrder, advance and |
| +// settleNear answer for the talk as the window holds it: each slide's |
| +// talk ('full' or in the talk; parked slides never reach a reader) and |
| +// one box per press, which is all presses() needs to count them. |
| + |
| +// How many slides get ready at once. |
| +const AT_ONCE = 4 |
| + |
| +/** A slide's presses as boxes presses() counts: n boxes on steps 1 to n. */ |
| +function pressBoxes (n) { |
| + const out = [] |
| + for (let k = 1; k <= n; k++) out.push({ id: 'press' + k, type: 'image', step: k }) |
| + return out |
| +} |
| + |
| +function version (payload, etag) { |
| + const slides = Array.isArray(payload.slides) ? payload.slides : [] |
| + return { |
| + deckSeq: Number(payload.deckSeq) || 0, |
| + arrive: payload.arrive || 'appear', |
| + etag, |
| + slides, |
| + byID: new Map(slides.map(s => [s.id, s])), |
| + view: { slides: slides.map(s => ({ id: s.id, talk: s.full ? 'full' : '', blocks: pressBoxes(Number(s.presses) || 0) })) }, |
| + ready: new Set(), |
| + failed: new Set(), |
| + waiters: new Map() |
| + } |
| +} |
| + |
| +// The pictures decoded, held so the browser keeps them for the talk. |
| +const held = [] |
| + |
| +/** A picture fetched and decoded, so drawing it later waits for nothing. */ |
| +export function decodePicture (url) { |
| + const img = new Image() |
| + img.decoding = 'async' |
| + img.src = url |
| + held.push(img) |
| + return img.decode() |
| +} |
| + |
| +export async function loadTalk ({ |
| + href, |
| + fonts = () => globalThis.slidesFonts, |
| + onProgress = () => {}, |
| + from = 0, |
| + fetchImpl = (...args) => globalThis.fetch(...args), |
| + picture = decodePicture |
| +}) { |
| + const fontsOf = typeof fonts === 'function' ? fonts : () => fonts |
| + |
| + async function fetchTalk (etag) { |
| + const headers = { Accept: 'application/json' } |
| + if (etag) headers['If-None-Match'] = etag |
| + const r = await fetchImpl(href, { credentials: 'same-origin', cache: 'no-store', headers }) |
| + if (r.status === 304) return null |
| + if (!r.ok) throw new Error('talk: ' + r.status) |
| + return version(await r.json(), r.headers.get('ETag')) |
| + } |
| + |
| + // prepare makes one slide ready: its families on, its pictures |
| + // decoded. A slide that fails is tried again by retry(). |
| + async function prepare (v, s) { |
| + try { |
| + const f = fontsOf() |
| + await Promise.all([ |
| + f && f.prepareSection ? f.prepareSection(s.html) : null, |
| + ...(Array.isArray(s.assets) ? s.assets : []).map(picture) |
| + ]) |
| + v.ready.add(s.id) |
| + v.failed.delete(s.id) |
| + const waiting = v.waiters.get(s.id) || [] |
| + v.waiters.delete(s.id) |
| + for (const resolve of waiting) resolve(true) |
| + } catch { |
| + v.failed.add(s.id) |
| + } |
| + } |
| + |
| + // prepareAll gets every slide of v ready, a few at a time, starting |
| + // at index start (the slide on screen), saying how far it has got. |
| + async function prepareAll (v, start, report) { |
| + const n = v.slides.length |
| + const order = [] |
| + for (let i = 0; i < n; i++) order.push(v.slides[(start + i) % n]) |
| + const say = finished => report && onProgress({ done: v.ready.size, total: n, failed: v.failed.size, finished }) |
| + let next = 0 |
| + say(false) |
| + await Promise.all(Array.from({ length: Math.min(AT_ONCE, n) }, async () => { |
| + while (next < n) { |
| + const s = order[next++] |
| + if (v.ready.has(s.id)) continue |
| + await prepare(v, s) |
| + say(false) |
| + } |
| + })) |
| + say(true) |
| + } |
| + |
| + let current = await fetchTalk(null) |
| + let pending = null |
| + let loading = null |
| + prepareAll(current, Math.max(0, Math.min(from, current.slides.length - 1)), true) |
| + |
| + return { |
| + get deckSeq () { return current.deckSeq }, |
| + get arrive () { return current.arrive }, |
| + get view () { return current.view }, |
| + get slides () { return current.slides }, |
| + /** The deckSeq of a newer version held and not yet taken, or 0. */ |
| + get pending () { return pending ? pending.deckSeq : 0 }, |
| + /** That newer version's view, or null. */ |
| + get pendingView () { return pending ? pending.view : null }, |
| + slide (id) { return current.byID.get(id) || null }, |
| + has (id) { return current.ready.has(id) }, |
| + /** Resolves true once the slide is ready, false if this version has no such slide. */ |
| + ready (id) { |
| + if (current.ready.has(id)) return Promise.resolve(true) |
| + if (!current.byID.has(id)) return Promise.resolve(false) |
| + const v = current |
| + return new Promise(resolve => { |
| + if (!v.waiters.has(id)) v.waiters.set(id, []) |
| + v.waiters.get(id).push(resolve) |
| + }) |
| + }, |
| + /** |
| + * Asks the server for a newer version and, if there is one, holds |
| + * it beside this one (pending, from the moment it arrives) and gets |
| + * it ready. Resolves true once a newer version is held and every |
| + * slide of it has been tried. |
| + */ |
| + refresh () { |
| + if (loading) return loading |
| + const have = pending || current |
| + loading = fetchTalk(have.etag).then(async v => { |
| + if (!v || v.deckSeq <= have.deckSeq) return false |
| + pending = v |
| + await prepareAll(v, 0, false) |
| + return true |
| + }).catch(() => false).finally(() => { loading = null }) |
| + return loading |
| + }, |
| + /** Takes the newer version, if one is held, and returns the view it replaced (or null). */ |
| + adopt () { |
| + if (!pending) return null |
| + const before = current.view |
| + // A slide both versions draw the same is ready in the new one. |
| + for (const s of pending.slides) { |
| + const old = current.byID.get(s.id) |
| + if (old && current.ready.has(s.id) && old.html === s.html) pending.ready.add(s.id) |
| + } |
| + current = pending |
| + pending = null |
| + prepareAll(current, 0, false) |
| + return before |
| + }, |
| + /** Tries again the slides that did not get ready. */ |
| + retry () { |
| + for (const v of [current, pending]) { |
| + if (v && v.failed.size) prepareAll(v, 0, v === current) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/slides/assets_embed.go b/internal/slides/assets_embed.go| index 3c1970f..69ca9cb 100644 |
| --- a/internal/slides/assets_embed.go |
| +++ b/internal/slides/assets_embed.go |
| @@ -26,7 +26,7 @@ import ( |
| // tag 404s, which is the same silent-failure shape the exactly-one rule |
| // below exists to prevent. The editor, and the font gate's two |
| // (fontgate.go): the hold, a classic script for <head>, and the gate. |
| -var bundleKinds = []string{"editor", "fontsgate", "fontshold"} |
| +var bundleKinds = []string{"editor", "fontsgate", "fontshold", "presenter"} |
| // bundleNames maps each committed bundle's kind to its filename under |
| // static/ — "editor" to "editor.f13f5e0ce6fa7467.js" — resolved once, |
| @@ -98,3 +98,8 @@ func bundlePath(kind string) string { |
| // editorBundlePath is the editor's bundle — templates/editor.html's |
| // <script type="module"> tag. |
| func editorBundlePath() string { return bundlePath("editor") } |
| + |
| +// presenterBundlePath is the presenting windows' bundle: the presenter |
| +// window and the slide window of a session with a position, moving at |
| +// once (fixtures/presenter-entry.mjs). |
| +func presenterBundlePath() string { return bundlePath("presenter") } |
diff --git a/internal/slides/credits/assets.json b/internal/slides/credits/assets.json| index eedf8e8..27f65da 100644 |
| --- a/internal/slides/credits/assets.json |
| +++ b/internal/slides/credits/assets.json |
| @@ -69,6 +69,7 @@ |
| "internal/slides/static/fontsgate.971e476eab8b8588.js": "971e476eab8b8588be520ac38eb823ab19beb2567db734555a7edc40d58567b2", |
| "internal/slides/static/fontshold.876f3d8d396da42f.js": "876f3d8d396da42f81954539f30b7200edfcde719d2920504707822f176a36ab", |
| "internal/slides/static/present.js": "a5a6802d7f40986c3692a16029f554d50ec6a14e0168a362697ce1313f964de4", |
| + "internal/slides/static/presenter.bbc8971ba87c2dd3.js": "bbc8971ba87c2dd382f6ffef197191b618a8b1597e8d016235073a522ae62120", |
| "internal/slides/static/rastrillo.js": "13a8ca6fa9ac25833f6485ab50a521dff7bd811372025dc5141b96522b60098b", |
| "internal/slides/static/select.js": "e231bad4b964464addfacd52d2260d4bdc0a02938fc033a25fdd9cbeb3671be1", |
| "internal/slides/static/shell.js": "bdc4d635fb8f14ef7089f7f692290baea645b13543be36328e7667fe8aed2caf", |
diff --git a/internal/slides/locales/en.toml b/internal/slides/locales/en.toml| index 9c6f6b2..35d8e10 100644 |
| --- a/internal/slides/locales/en.toml |
| +++ b/internal/slides/locales/en.toml |
| @@ -703,6 +703,15 @@ slides.present.notes.larger = "Larger notes" |
| slides.present.empty.title = "Nothing to present" |
| slides.present.empty.body = "Every slide in this deck is parked, or there are none yet. Unpark a slide in the editor to present it." |
| +# Moving through the talk (spec §6). The presenter window says how far |
| +# getting the talk into memory has got, and then nothing; that it moves |
| +# on its own while the network is gone; and the slide window, which is |
| +# not the one pressing, says it is waiting. |
| +slides.present.loading = "Getting the talk ready: {n} of {total}" |
| +slides.present.loading.failed = "{n} slides did not load. They will show when the network allows." |
| +slides.present.offline = "Offline. This window still moves." |
| +slides.present.waiting = "Waiting for the network" |
| + |
| # A session that is over — ended, or past its twelve hours. A 410, and |
| # worded as one: the talk finished, which is a different thing from an |
| # address that was never real. |
diff --git a/internal/slides/presentation.go b/internal/slides/presentation.go| index 51a1131..49b0053 100644 |
| --- a/internal/slides/presentation.go |
| +++ b/internal/slides/presentation.go |
| @@ -510,6 +510,20 @@ type surfacePage struct { |
| NotesHref string |
| NotesLabel string |
| + // Bundle is set on the slide window of a session with a position, |
| + // for whoever may drive it: the presenter bundle |
| + // (fixtures/slide-window.mjs) moves it at once, from the talk it |
| + // holds in memory (TalkHref), instead of static/present.js. Its |
| + // sentences come down unfilled: the counter, what the live region |
| + // says, and that the window is waiting for the network. P opens the |
| + // presenter window (PresenterHref). |
| + Bundle string |
| + TalkHref string |
| + PresenterHref string |
| + ProgressWords string |
| + AnnounceWords string |
| + WaitingWords string |
| + |
| // Refresh is the follow view's scriptless heartbeat: a meta |
| // refresh, so an audience with no JavaScript still moves with the |
| // presenter. Off on the presenter's own surface, where a refresh |
| @@ -780,22 +794,42 @@ func (a *app) renderSurface(w http.ResponseWriter, r *http.Request, d Deck, p Pr |
| page.Refresh = true |
| page.BackHref = opt.backHref |
| page.BackLabel = opt.backLabel |
| - case remoteTokenOK(p, opt.token): |
| + case remoteTokenOK(p, opt.token) || (p.Positional && a.mayDrive(r, p, "")): |
| // Whoever holds the remote drives the session from here too: |
| // the pager posts commands, so the projector's own next button |
| - // moves the talk rather than only this browser. |
| - page.Token = opt.token |
| + // moves the talk rather than only this browser. On a session |
| + // with a position so does the presenter, signed in (S19): the |
| + // slide window they open from the presenter window drives. |
| + token := "" |
| + if remoteTokenOK(p, opt.token) { |
| + token = opt.token |
| + } |
| + page.Token = token |
| back, next := pressLabels(r, p) |
| page.Controls = &controls{ |
| Action: "/p/" + p.Sqid + "/command", |
| - Token: opt.token, |
| + Token: token, |
| Buttons: withPressIDs([]commandButton{ |
| {Op: "prev", Label: back}, |
| {Op: "next", Label: next}, |
| }), |
| } |
| - page.NotesHref = "/p/" + p.Sqid + "/notes?t=" + url.QueryEscape(opt.token) |
| + page.NotesHref = "/p/" + p.Sqid + "/notes" |
| + if token != "" { |
| + page.NotesHref += "?t=" + url.QueryEscape(token) |
| + } |
| page.NotesLabel = rastrillo.T(r, "slides.present.notes.title") |
| + if p.Positional { |
| + page.Bundle = presenterBundlePath() |
| + page.TalkHref = "/p/" + p.Sqid + "/talk" |
| + if token != "" { |
| + page.TalkHref += "?t=" + url.QueryEscape(token) |
| + } |
| + page.PresenterHref = page.NotesHref |
| + page.ProgressWords = rastrillo.T(r, "slides.present.progress") |
| + page.AnnounceWords = rastrillo.T(r, "slides.slide.announce") |
| + page.WaitingWords = rastrillo.T(r, "slides.present.waiting") |
| + } |
| default: |
| // A watcher may page through the deck on their own screen |
| // without moving anybody else's: ordinary links, no session |
diff --git a/internal/slides/presenter_window.go b/internal/slides/presenter_window.go| index 3bf0fbc..a041c31 100644 |
| --- a/internal/slides/presenter_window.go |
| +++ b/internal/slides/presenter_window.go |
| @@ -205,10 +205,18 @@ type presenterWindowPage struct { |
| ArrangeCSS template.CSS |
| Action string |
| - // What the page's root says, for static/present.js: the session, |
| + // What the window's script needs (fixtures/presenter-window.mjs): |
| + // its bundle, the talk it holds in memory, the session's stream, and |
| + // every sentence it draws, from the catalog. |
| + Bundle string |
| + TalkHref string |
| + StreamHref string |
| + Words presenterWords |
| + |
| + // What the page's root says, for the window's script: the session, |
| // the slide drawn (its number in the full talk), the step, the mode |
| - // and whether the room sees black, so it reloads when an event says |
| - // otherwise; the token when this window was opened with one. |
| + // and whether the room sees black, which is where it starts from; |
| + // the token when this window was opened with one. |
| Session string |
| Token string |
| Slide int |
| @@ -257,6 +265,37 @@ type presenterWindowPage struct { |
| EmptyBody string |
| } |
| +// presenterWords are the catalog's sentences the window's script draws |
| +// as the talk moves, unfilled: it puts in the numbers itself. |
| +type presenterWords struct { |
| + Progress, Step string |
| + NextStep, NextSlide, NextEnd string |
| + ModeCore, ModeFull, Black string |
| + MenuFull, MenuCore, NoNotes string |
| + Loading, LoadingFailed string |
| + Offline string |
| +} |
| + |
| +// presenterWordsFor is the window's sentences in the request's language. |
| +func presenterWordsFor(r *http.Request) presenterWords { |
| + return presenterWords{ |
| + Progress: rastrillo.T(r, "slides.present.progress"), |
| + Step: rastrillo.T(r, "slides.present.step.count"), |
| + NextStep: rastrillo.T(r, "slides.present.next.step"), |
| + NextSlide: rastrillo.T(r, "slides.present.next.slide"), |
| + NextEnd: rastrillo.T(r, "slides.present.next.end"), |
| + ModeCore: rastrillo.T(r, "slides.present.mode.core"), |
| + ModeFull: rastrillo.T(r, "slides.present.mode.full"), |
| + Black: rastrillo.T(r, "slides.present.black"), |
| + MenuFull: rastrillo.T(r, "slides.present.menu.full"), |
| + MenuCore: rastrillo.T(r, "slides.present.menu.core"), |
| + NoNotes: rastrillo.T(r, "slides.notes.none"), |
| + Loading: rastrillo.T(r, "slides.present.loading"), |
| + LoadingFailed: rastrillo.T(r, "slides.present.loading.failed"), |
| + Offline: rastrillo.T(r, "slides.present.offline"), |
| + } |
| +} |
| + |
| // presenterMenu is the ⋯ menu's six rows (§5.6). Pairing and arranging |
| // arrive in Task 13: the pair form posts to a route that comes then, |
| // and Arrange is a button that needs the window's script. |
| @@ -343,6 +382,10 @@ func (a *app) presenterWindow(w http.ResponseWriter, r *http.Request, p Presenta |
| shell: presentShellFor(r, rastrillo.T(r, "slides.present.notes.title"), view.Meta.Title), |
| ArrangeCSS: prefs.css(), |
| Action: "/p/" + p.Sqid + "/command", |
| + Bundle: presenterBundlePath(), |
| + TalkHref: "/p/" + p.Sqid + "/talk", |
| + StreamHref: "/p/" + p.Sqid + "/stream", |
| + Words: presenterWordsFor(r), |
| Session: p.Sqid, |
| Token: token, |
| Mode: string(mode), |
| @@ -378,6 +421,7 @@ func (a *app) presenterWindow(w http.ResponseWriter, r *http.Request, p Presenta |
| } |
| if token != "" { |
| page.Menu.WindowHref += "?t=" + url.QueryEscape(token) |
| + page.TalkHref += "?t=" + url.QueryEscape(token) |
| } |
| if mode == deck.ModeFull { |
| page.Menu.ModeLabel = rastrillo.T(r, "slides.present.menu.core") |
diff --git a/internal/slides/static/presenter.bbc8971ba87c2dd3.js b/internal/slides/static/presenter.bbc8971ba87c2dd3.js| new file mode 100644 |
| index 0000000..6a58252 |
| --- /dev/null |
| +++ b/internal/slides/static/presenter.bbc8971ba87c2dd3.js |
| @@ -0,0 +1,2 @@ |
| +var ce=/^[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]*$/,ue=t=>(Array.isArray(t)?t:[]).map(e=>e&&typeof e.t=="string"?e.t:"").join("");function de(t){let e=[];return(Array.isArray(t)?t:[]).forEach((n,r)=>{ce.test(ue(n))||e.push(r)}),e}var Q=t=>typeof t.step=="number"&&t.step>0?t.step:0;function Z(t){let e=t.props&&t.props.children;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Me(t){let e=new Map;for(let r of t)e.set(r.id,r);let n=new Map;for(let r of t)if(r.type==="columns")for(let i of Z(r))e.has(i)&&i!==r.id&&!n.has(i)&&n.set(i,r.id);return{byID:e,parent:n}}function Te(t,e){let n=Q(e),r=new Set([e.id]);for(let i=t.parent.get(e.id);i!==void 0&&!r.has(i);i=t.parent.get(i))r.add(i),n=Math.max(n,Q(t.byID.get(i)));return n}function ee(t,e,n){switch(e.type){case"list":return de(e.text).length>0;case"heading":case"text":case"quote":return!ce.test((Array.isArray(e.text)?e.text:[]).map(ue).join(` |
| +`));case"columns":n.add(e.id);for(let r of Z(e)){let i=t.byID.get(r);if(i&&!n.has(r)&&ee(t,i,n))return!0}return!1}return!0}function fe(t,e,n){let r=Te(t,e);if(e.type!=="columns")return r;n.add(e.id);let i=1/0;for(let f of Z(e)){let a=t.byID.get(f);!a||n.has(f)||!ee(t,a,new Set)||(i=Math.min(i,fe(t,a,n)))}return i>r&&i!==1/0?i:r}function pe(t){let e=Array.isArray(t&&t.blocks)?t.blocks:[],n=Me(e),r=[],i=[];for(let a of e){if(Q(a)===0||!ee(n,a,new Set))continue;let h={id:a.id,value:fe(n,a,new Set),items:null};a.type==="list"&&a.items==="each"&&(h.items=de(a.text)),r.push(h),i.includes(h.value)||i.push(h.value)}i.sort((a,h)=>a-h);let f=[];for(let a of i){let h=1;for(let d of r)d.value===a&&d.items&&d.items.length>h&&(h=d.items.length);for(let d=0;d<h;d++){let o=[];for(let p of r)p.value===a&&(p.items?d<p.items.length&&o.push({block:p.id,item:p.items[d]}):d===0&&o.push({block:p.id,item:-1}));f.push(o)}}return f}var W=t=>Array.isArray(t&&t.slides)?t.slides:[],ne=(t,e)=>t.findIndex(n=>n.id===e),te=t=>pe(t).length,H=(t,e,n=0)=>({slide:t.id,step:n,mode:e,black:!1}),re=t=>({slide:"",step:0,mode:t,black:!1}),me=(t,e)=>Math.min(Math.max(t,0),e);function R(t,e){let n=[];return W(t).forEach((r,i)=>{r.talk==="parked"||r.talk==="full"&&e!=="full"||n.push(i)}),n}function B(t,e,n){let r=W(t),i=R(t,e.mode);switch(n.op){case"black":return{...e,black:!e.black};case"mode":return{...e,mode:e.mode==="full"?"core":"full"};case"goto":{let f=n.slide?ne(r,n.slide):-1;return f<0||r[f].talk==="parked"?e:H(r[f],r[f].talk==="full"?"full":e.mode)}case"first":case"last":return i.length?H(r[n.op==="first"?i[0]:i[i.length-1]],e.mode):re(e.mode);case"next":case"back":return Ce(t,e,n.op==="next",i)}return e}function Ce(t,e,n,r){let i=W(t);if(!r.length)return re(e.mode);let f=ne(i,e.slide);if(f<0)return{...se(t,e),black:!1};let a=te(i[f]),h=me(e.step,a);if(n&&h<a)return{...e,step:h+1,black:!1};if(!n&&h>0)return{...e,step:h-1,black:!1};if(n){let d=r.find(o=>o>f);if(d!==void 0)return H(i[d],e.mode)}else{let d=r.findLast(o=>o<f);if(d!==void 0)return H(i[d],e.mode,te(i[d]))}return{...e,step:h,black:!1}}function se(t,e){return X(t,e,-1)}function X(t,e,n){let r=W(t),i=R(t,e.mode);if(!i.length)return re(e.mode);let f=d=>({...H(r[d],e.mode),black:e.black}),a=i[i.length-1];if(e.slide==="")return f(i[0]);let h=ne(r,e.slide);if(h<0&&n>=0){let d=R(t,"full").slice(n).find(o=>i.includes(o));return f(d??a)}return h<0?f(a):r[h].talk==="parked"?f(i.find(d=>d>h)??a):{...e,step:me(e.step,te(r[h]))}}var Ne="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Pe(){let t=new Uint8Array(22);globalThis.crypto.getRandomValues(t);let e="";for(let n of t)e+=Ne[n&63];return e}var Le={back:"prev",black:"blackout"};function De(t){let e={op:Le[t.op]||t.op};return t.slide&&(e.slide=String(t.slide)),e}function ie(t,e){return!t||!e?t!==e:t.slide!==e.slide||(t.step||0)!==(e.step||0)||t.mode!==e.mode||!!t.black!=!!e.black}var Oe=(t,e)=>{let n=setTimeout(e,t);return()=>clearTimeout(n)};function he({post:t,stream:e,now:n=()=>Date.now(),after:r=Oe,onPosition:i=()=>{},onStatus:f=()=>{},onDeckSeq:a=()=>{},makeID:h=Pe}){let d=!0,o=[],p=null,l=!1,b=null,c=null,g=0,k=null,S=null;function q(){return d?"online":"offline"}function A(s){let u=d;d=s==="online",u!==d&&f(q())}function E(s){!s||typeof s.seq!="number"||(typeof s.deckSeq=="number"&&a(s.deckSeq),(!c||s.seq>c.seq)&&(c=s))}function x(){!d||p||o.length||!c||c.seq<=g||(g=c.seq,ie(c,b)&&(b={slide:c.slide,step:c.step||0,mode:c.mode,black:!!c.black},i({...b,seq:c.seq})))}function N(){if(!d||p||!o.length)return;let s=o[0],u=n(),w={item:s};p=w;let y=r(3e3,()=>{p===w&&M()});Promise.resolve().then(()=>t({...s.fields,press:s.id})).then(v=>{if(p===w){if(y(),n()-u>3e3){M();return}p=null,o.shift(),E(v),o.length?N():x()}},()=>{p===w&&(y(),M())})}function M(){(p||o.length)&&(l=!0),p=null,o=[],A("offline"),_()}function _(){k||d||!l||(k=r(2e3,()=>{k=null,!(d||!l)&&P()}))}function P(){if(k&&(k(),k=null),A("online"),l&&b){l=!1,o=[{id:h(),fields:{op:"resume",at_slide:b.slide,at_step:String(b.step||0),at_mode:b.mode}}],N();return}x()}function m(){S&&(S(),S=null)}return e({open(){m(),d||P()},error(){!d||S||(S=r(5e3,()=>{S=null,d&&M()}))},position(s){m(),E(s),d?x():P()}}),{press(s,u){if(u&&(b={...u}),!d){l=!0,_();return}o.push({id:h(),fields:De(s)}),N()},resume(s){b=s?{...s}:null},status:q}}function Re(t){let e=[];for(let n=1;n<=t;n++)e.push({id:"press"+n,type:"image",step:n});return e}function Ie(t,e){let n=Array.isArray(t.slides)?t.slides:[];return{deckSeq:Number(t.deckSeq)||0,arrive:t.arrive||"appear",etag:e,slides:n,byID:new Map(n.map(r=>[r.id,r])),view:{slides:n.map(r=>({id:r.id,talk:r.full?"full":"",blocks:Re(Number(r.presses)||0)}))},ready:new Set,failed:new Set,waiters:new Map}}var _e=[];function je(t){let e=new Image;return e.decoding="async",e.src=t,_e.push(e),e.decode()}async function ge({href:t,fonts:e=()=>globalThis.slidesFonts,onProgress:n=()=>{},from:r=0,fetchImpl:i=(...a)=>globalThis.fetch(...a),picture:f=je}){let a=typeof e=="function"?e:()=>e;async function h(c){let g={Accept:"application/json"};c&&(g["If-None-Match"]=c);let k=await i(t,{credentials:"same-origin",cache:"no-store",headers:g});if(k.status===304)return null;if(!k.ok)throw new Error("talk: "+k.status);return Ie(await k.json(),k.headers.get("ETag"))}async function d(c,g){try{let k=a();await Promise.all([k&&k.prepareSection?k.prepareSection(g.html):null,...(Array.isArray(g.assets)?g.assets:[]).map(f)]),c.ready.add(g.id),c.failed.delete(g.id);let S=c.waiters.get(g.id)||[];c.waiters.delete(g.id);for(let q of S)q(!0)}catch{c.failed.add(g.id)}}async function o(c,g,k){let S=c.slides.length,q=[];for(let x=0;x<S;x++)q.push(c.slides[(g+x)%S]);let A=x=>k&&n({done:c.ready.size,total:S,failed:c.failed.size,finished:x}),E=0;A(!1),await Promise.all(Array.from({length:Math.min(4,S)},async()=>{for(;E<S;){let x=q[E++];c.ready.has(x.id)||(await d(c,x),A(!1))}})),A(!0)}let p=await h(null),l=null,b=null;return o(p,Math.max(0,Math.min(r,p.slides.length-1)),!0),{get deckSeq(){return p.deckSeq},get arrive(){return p.arrive},get view(){return p.view},get slides(){return p.slides},get pending(){return l?l.deckSeq:0},get pendingView(){return l?l.view:null},slide(c){return p.byID.get(c)||null},has(c){return p.ready.has(c)},ready(c){if(p.ready.has(c))return Promise.resolve(!0);if(!p.byID.has(c))return Promise.resolve(!1);let g=p;return new Promise(k=>{g.waiters.has(c)||g.waiters.set(c,[]),g.waiters.get(c).push(k)})},refresh(){if(b)return b;let c=l||p;return b=h(c.etag).then(async g=>!g||g.deckSeq<=c.deckSeq?!1:(l=g,await o(g,0,!1),!0)).catch(()=>!1).finally(()=>{b=null}),b},adopt(){if(!l)return null;let c=p.view;for(let g of l.slides){let k=p.byID.get(g.id);k&&p.ready.has(g.id)&&k.html===g.html&&l.ready.add(g.id)}return p=l,l=null,o(p,0,!1),c},retry(){for(let c of[p,l])c&&c.failed.size&&o(c,0,c===p)}}}function Ke(t,e){for(let n of t.querySelectorAll("[data-press]"))n.removeAttribute("data-arriving"),Number(n.getAttribute("data-press"))>e?n.setAttribute("data-waiting",""):n.removeAttribute("data-waiting")}function V(t,e,n){let r=document.createElement("template");r.innerHTML=e,Ke(r.content,n),t.replaceChildren(r.content)}function be(t){t.target===t.currentTarget&&(t.currentTarget.removeAttribute("data-arriving"),t.currentTarget.removeEventListener("animationend",be))}function G(t,e){for(let n of t.querySelectorAll("[data-arriving]"))n.removeAttribute("data-arriving");for(let n of t.querySelectorAll("[data-press]"))Number(n.getAttribute("data-press"))>e?n.setAttribute("data-waiting",""):n.hasAttribute("data-waiting")&&(n.removeAttribute("data-waiting"),n.setAttribute("data-arriving",""),n.addEventListener("animationend",be))}function j(t,e){return String(t||"").replace(/\{(\w+)\}/g,(n,r)=>r in e?String(e[r]):n)}function z(t,e,n){let r=R(t,e);if(!r.length)return{n:n+1,total:t.slides.length};let i=1;return r.forEach((f,a)=>{f<=n&&(i=a+1)}),{n:i,total:r.length}}function I(t,e){return t.slides.findIndex(n=>n.id===e)}function ae(t,e){t&&t.setAttribute(e,t.getAttribute(e)==="a"?"b":"a")}var Ue=3e4,Fe=1500,xe=3e3,ke=(t,e)=>R(t,"full").indexOf(I(t,e)),we=t=>new Promise(e=>setTimeout(e,t));function He(t){return e=>{let n=null,r=!1,i=()=>{n||r||(n=new EventSource(t),n.onopen=()=>e.open(),n.onerror=()=>{e.error(),n&&n.readyState===EventSource.CLOSED&&(n=null,setTimeout(i,xe))},n.addEventListener("slide",f=>{let a;try{a=JSON.parse(f.data)}catch{return}if(a.ended){location.reload();return}a.slideId&&e.position({slide:a.slideId,step:Number(a.step)||0,mode:a.mode,black:!!a.blackout,seq:Number(a.seq)||0})}))};return addEventListener("pagehide",()=>{r=!0,n&&(n.close(),n=null)}),addEventListener("pageshow",f=>{let a=r&&f.persisted;r=!1,a&&setTimeout(i,0)}),i(),()=>{r=!0,n&&n.close()}}}function Ve(t,e){return n=>{let r=new URLSearchParams(n);return e&&r.set("t",e),fetch(t,{method:"POST",body:r,credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(i=>{if(i.status===410&&location.reload(),!i.ok)throw new Error("press: "+i.status);return i.json()})}}function Y({root:t,talkHref:e,streamHref:n,action:r,token:i,draw:f,onStatus:a=()=>{},onProgress:h=()=>{},onPressed:d=()=>{}}){let o=null,p=null,l=null,b=null,c=0,g=0,k=[];function S(m){let s=l,u=c!==o.deckSeq;l=m,b=null,c=o.deckSeq,f(m,s,{fresh:u,store:o})}function q(m){let s=++g;if(b=m,!m.slide||o.has(m.slide)||m.slide===l.slide&&c===o.deckSeq){S(m);return}o.ready(m.slide).then(u=>{u&&s===g&&S(m)})}function A(){return o.refresh().then(m=>(o.pending&&t.setAttribute("data-deck-pending",String(o.pending)),m))}function E(m){let s=ke(o.view,m.slide);return o.adopt(),t.removeAttribute("data-deck-pending"),X(o.view,m,s)}function x(m){if(!o){k.push(m);return}if(m.op==="timer-reset"){p.press(m,null);return}let s=b||l,u=B(o.view,s,m),w=o.pendingView;if(w){let y=B(w,X(w,s,ke(o.view,s.slide)),m);if(u.slide!==s.slide||y.slide!==s.slide){let v=E(s);u=B(o.view,v,m)}}d(m,s,u),p.press(m,u),q(u)}function N(m){if(!o)return;let s=b||l,u=R(o.view,s.mode)[m-1];u!==void 0&&x({op:"goto",slide:o.view.slides[u].id})}async function M(m){let s=++g,u=b||l,w=()=>!m.slide||!!o.slide(m.slide)||!!o.pendingView&&I(o.pendingView,m.slide)>=0;if(m.slide!==u.slide&&p.status()==="online"&&await Promise.race([A(),we(Fe)]),w()||await A(),s!==g||!w())return;let y=o.pendingView;y&&I(y,m.slide)>=0&&(m.slide!==u.slide||!o.slide(m.slide))&&E(u),q(se(o.view,m))}function _(){o&&p&&p.status()==="online"&&(A(),o.retry())}async function P(){let m={number:Number(t.getAttribute("data-slide"))||0,step:Number(t.getAttribute("data-step"))||0,mode:t.getAttribute("data-mode")==="full"?"full":"core",black:t.getAttribute("data-blackout")==="true"};for(;;)try{o=await ge({href:e,onProgress:h,from:Math.max(0,m.number-1)});break}catch{a("offline"),await we(xe)}let s=o.slides.find(u=>u.number===m.number);l={slide:s?s.id:"",step:m.step,mode:m.mode,black:m.black},c=o.deckSeq,p=he({post:Ve(r,i),stream:He(n),onPosition:M,onStatus:u=>{a(u),u==="online"&&o.retry()},onDeckSeq:u=>{u>o.deckSeq&&u>o.pending&&A()}}),p.resume(l),a(p.status());for(let u of k.splice(0))x(u);setInterval(_,Ue),addEventListener("focus",_)}return P(),{move:x,jump:N,timerReset(){x({op:"timer-reset"})},get store(){return o},get position(){return b||l},differs:ie}}var ye={next:"next",prev:"back",first:"first",last:"last",blackout:"black",mode:"mode"};function $(t,e,n,r=()=>{}){let i=new URL(e,location.href).pathname;t.addEventListener("submit",f=>{let a=f.target;if(!a||(a.method||"").toLowerCase()!=="post"||new URL(a.action,location.href).pathname!==i)return;let h=a.elements.op&&a.elements.op.value;if(h==="timer-reset")f.preventDefault(),n.timerReset();else if(h==="goto"&&a.elements.slide){let d=Number(a.elements.slide.value),o=n.store&&n.store.slides.find(p=>p.number===d);if(!o)return;f.preventDefault(),n.move({op:"goto",slide:o.id})}else if(ye[h])f.preventDefault(),n.move({op:ye[h]});else return;r(h)})}var oe={ArrowRight:"next"," ":"next",PageDown:"next",ArrowLeft:"back",PageUp:"back",Home:"first",End:"last",b:"black",B:"black",".":"black",o:"mode",O:"mode"},We=new Set(["PageDown","PageUp"]);function Be(t){if(!t)return!1;if(t.isContentEditable)return!0;let e=String(t.tagName||"").toUpperCase();return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function J({act:t}){let e="";return function(r){if(r.metaKey||r.ctrlKey||r.altKey)return;let i=r.key;if(i==="Escape"){e="",t({escape:!0});return}if(Be(r.target)&&!We.has(i))return;if(r.repeat){i in oe&&r.preventDefault();return}if(/^[0-9]$/.test(i)){e=(e+i).slice(-4),r.preventDefault();return}if(i==="Enter"){if(!e)return;let a=Number(e);e="",r.preventDefault(),a>0&&t({jump:a});return}e="";let f=null;i in oe?f={move:{op:oe[i]}}:i==="p"||i==="P"?f={open:"presenter"}:(i==="r"||i==="R")&&(f={timer:"reset"}),f&&(r.preventDefault(),t(f))}}var Xe=new Set(["next","back","first","last","goto"]);function K(t,e,n){let r=document.createElement(t);return e&&r.setAttribute(e,""),n!==void 0&&(r.textContent=n),r}function Se(t){let e=t.dataset,n=s=>t.querySelector(s),r=n("[presenter-head]"),i=n("[presenter-pos]"),f=n("[presenter-status]"),a=n("[presenter-elapsed]");window.name="slides-presenter";function h(s,u){let w=n("["+s+"]");return w||(w=K("span",s),w.hidden=!0,u.after(w)),w}let d=h("presenter-stepcount",i);if(!d.firstChild){d.setAttribute("role","status");let s=K("span","presenter-track");s.setAttribute("aria-hidden","true"),d.append(s,K("span","presenter-steptext"))}let o=h("presenter-mode",d),p=h("presenter-black",o);function l(s,u,w){let y=w.view,v=i.querySelector("[presenter-count]");v&&(v.textContent=j(e.textProgress,z(y,u.mode,I(y,u.slide))));let T=Number(s.presses)||0;if(d.hidden=T===0,T){let C=d.querySelector("[presenter-track]");for(;C.children.length<T;)C.append(K("i"));for(;C.children.length>T;)C.lastChild.remove();[...C.children].forEach((U,F)=>U.toggleAttribute("data-done",F<u.step)),d.querySelector("[presenter-steptext]").textContent=j(e.textStep,{n:u.step,total:T})}let O=w.slides.some(C=>C.full);o.hidden=!O,O&&(o.textContent=u.mode==="full"?e.textModeFull:e.textModeCore),p.hidden=!u.black,p.textContent=e.textBlack;let L=t.querySelector('[presenter-menu] form input[name="op"][value="mode"]'),D=L&&L.form.querySelector("button");D&&(D.textContent=u.mode==="full"?e.textMenuCore:e.textMenuFull)}function b(s,u){let w=K("div","presenter-frame");if(s===null)return w.setAttribute("data-end",""),w;let y=K("div","presenter-scale");return V(y,s,u),w.append(y),w}let c="";function g(s,u,w){let y=w.view,v=I(y,u.slide),T=n("[presenter-next-label] span"),O=n('[presenter-panel="next"] [presenter-fit]'),L=Number(s.presses)||0,D=R(y,u.mode).find(qe=>qe>v),C=null,U=0,F=e.textNextEnd;u.step<L?(F=e.textNextStep,C=s.html,U=u.step+1):D!==void 0&&(F=e.textNextSlide,C=w.slide(y.slides[D].id).html),T.textContent=F;let le=w.deckSeq+":"+U+":"+C;le!==c&&(c=le,O.replaceChildren(b(C,U)))}function k(s,u){let w=n("[presenter-notes]"),y=Array.isArray(s.notes)?s.notes:[];if(!y.length){w.replaceChildren(K("p","presenter-nonotes",e.textNonotes));return}let v=Math.min(Math.max(u.step,0),y.length-1);w.replaceChildren(...y.map((T,O)=>{let L=K("section","presenter-part");return y.length>1&&L.setAttribute("data-part",O<v?"past":O>v?"later":"now"),L.innerHTML=T,L}))}function S(s,u,{fresh:w,store:y}){let v=y.slide(s.slide);if(!v)return;let T=n('[presenter-panel="now"] [presenter-frame]'),O=T.querySelector("[presenter-scale]"),L=!w&&u&&u.slide===s.slide;L?u.step!==s.step&&G(O,s.step):V(O,v.html,s.step),T.toggleAttribute("data-black",!!s.black),l(v,s,y),g(v,s,y),(!L||u.step!==s.step)&&k(v,s),t.setAttribute("data-slide",String(v.number)),t.setAttribute("data-step",String(s.step)),t.setAttribute("data-mode",s.mode),t.setAttribute("data-blackout",s.black?"true":"false"),t.setAttribute("data-deck-seq",String(y.deckSeq));let D=new URL(location.href);(D.searchParams.has("slide")||D.searchParams.has("step"))&&(D.searchParams.delete("slide"),D.searchParams.delete("step"),history.replaceState(history.state,"",D.href))}let q="",A=!1;function E(){f&&(f.textContent=A?e.textOffline:q)}function x(){return a&&a.getAttribute("data-timer-since")}function N(s){ae(d,"data-flash"),ae(i,"data-pulse"),Xe.has(s.op)&&a&&!x()&&a.setAttribute("data-timer-since",String(Math.floor(Date.now()/1e3)))}let M=Y({root:t,talkHref:e.talk,streamHref:e.stream,action:e.command,token:t.getAttribute("data-remote-token")||"",draw:S,onPressed:N,onStatus:s=>{A=s==="offline",E()},onProgress:s=>{t.setAttribute("data-loaded",s.finished&&!s.failed?"all":String(s.done)),q=s.finished?s.failed?j(e.textLoadingFailed,{n:s.failed}):"":j(e.textLoading,{n:s.done,total:s.total}),E()}});function _(){M.timerReset(),a&&(a.removeAttribute("data-timer-since"),a.textContent="0:00")}let P=n("[presenter-more-menu]");$(t,e.command,{move:s=>M.move(s),timerReset:_,get store(){return M.store}},()=>{P&&(P.open=!1)});let m=J({act(s){if(s.move)M.move(s.move);else if(s.jump)M.jump(s.jump);else if(s.timer)_();else if(s.escape){P&&P.open&&(P.open=!1);let u=document.activeElement;u&&u!==document.body&&u.blur&&u.blur()}}});document.addEventListener("keydown",m),Ge(a,n("[data-clock]"))}function Ge(t,e){let n=f=>(f<10?"0":"")+f;function r(){let f=t&&t.getAttribute("data-timer-since");if(!f)return;let a=Math.max(0,Math.floor(Date.now()/1e3-Number(f))),h=Math.floor(a/3600),d=Math.floor(a/60)%60;t.textContent=h?h+":"+n(d)+":"+n(a%60):d+":"+n(a%60)}function i(){e&&(e.textContent=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))}r(),i(),setInterval(r,1e3),setInterval(i,15e3)}function Ae(t){let e=t.dataset,n=t.querySelector("[slides-stage]"),r=t.querySelector("[slides-blackout]"),i=t.querySelector("[slides-waiting]"),f=t.querySelector("[slides-announce]");if(!n)return;function a(l){let b=t.querySelector("[slides-counter]");if(!b)return;let c=b.lastChild;c&&c.nodeType===Node.TEXT_NODE?c.textContent=" "+l:b.append(" "+l)}function h(l,b,{fresh:c,store:g}){let k=g.slide(l.slide);if(!k)return;let S=g.view;if(!c&&b&&b.slide===l.slide)b.step!==l.step&&G(n,l.step);else{V(n,k.html,l.step);let N=j(e.textAnnounce,{n:k.number,total:g.slides.length,title:k.title});t.setAttribute("data-announce",N),f&&f.textContent!==N&&(f.textContent=N)}let A=z(S,l.mode,I(S,l.slide));a(j(e.textProgress,A));let E=t.querySelector("[slides-progress]");E&&(E.setAttribute("value",String(A.n)),E.setAttribute("max",String(A.total))),t.setAttribute("data-slide",String(k.number)),t.setAttribute("data-step",String(l.step)),t.setAttribute("data-mode",l.mode),t.setAttribute("data-blackout",l.black?"true":"false"),t.setAttribute("data-deck-seq",String(g.deckSeq)),r&&(r.hidden=!l.black);let x=new URL(location.href);(x.searchParams.has("slide")||x.searchParams.has("step"))&&(x.searchParams.delete("slide"),x.searchParams.delete("step"),history.replaceState(history.state,"",x.href))}let d=Y({root:t,talkHref:e.talk,streamHref:e.stream,action:e.command,token:t.getAttribute("data-remote-token")||"",draw:h,onProgress:l=>t.setAttribute("data-loaded",l.finished&&!l.failed?"all":String(l.done)),onStatus:l=>{i&&(i.textContent=e.textWaiting,i.hidden=l!=="offline")}});$(t,e.command,d);let o=J({act(l){if(l.move)d.move(l.move);else if(l.jump)d.jump(l.jump);else if(l.timer)d.timerReset();else if(l.open&&e.presenter)window.open(e.presenter,"slides-presenter");else if(l.escape){document.fullscreenElement&&document.exitFullscreen();let b=document.activeElement;b&&b!==document.body&&b.blur&&b.blur()}}});document.addEventListener("keydown",o);let p=null;t.addEventListener("touchstart",l=>{p=l.changedTouches[0].clientX},{passive:!0}),t.addEventListener("touchend",l=>{if(p===null)return;let b=l.changedTouches[0].clientX-p;p=null,Math.abs(b)>=60&&d.move({op:b<0?"next":"back"})},{passive:!0})}var ve=document.querySelector("[presenter][data-talk]"),Ee=document.querySelector("[slides-surface][data-talk]");ve?Se(ve):Ee&&Ae(Ee); |
diff --git a/internal/slides/static/presenter.css b/internal/slides/static/presenter.css| index 1bb73ad..557d616 100644 |
| --- a/internal/slides/static/presenter.css |
| +++ b/internal/slides/static/presenter.css |
| @@ -208,6 +208,67 @@ body { |
| letter-spacing: 0.14em; |
| } |
| +/* What the window's script shows and hides as the talk moves |
| + (fixtures/presenter-window.mjs): the step count on a slide with no |
| + steps, the mode, BLACK. */ |
| +[presenter] [hidden] { |
| + display: none !important; |
| +} |
| + |
| +/* A press is always answered here: the step count flashes and the |
| + position pulses, restarted on every press, even one that moves |
| + nothing at the end of the talk. The script flips the attribute |
| + between two copies of one animation, which restarts it. Colour |
| + only, so it stays under reduced motion. */ |
| +[presenter-stepcount][data-flash="a"] { |
| + animation: presenter-flash-a 0.5s var(--p-ease); |
| +} |
| + |
| +[presenter-stepcount][data-flash="b"] { |
| + animation: presenter-flash-b 0.5s var(--p-ease); |
| +} |
| + |
| +[presenter-pos][data-pulse="a"] { |
| + animation: presenter-pulse-a 0.5s var(--p-ease); |
| +} |
| + |
| +[presenter-pos][data-pulse="b"] { |
| + animation: presenter-pulse-b 0.5s var(--p-ease); |
| +} |
| + |
| +@keyframes presenter-flash-a { |
| + from { background: rgb(255 180 84 / 0.28); } |
| + to { background: var(--p-raised); } |
| +} |
| + |
| +@keyframes presenter-flash-b { |
| + from { background: rgb(255 180 84 / 0.28); } |
| + to { background: var(--p-raised); } |
| +} |
| + |
| +@keyframes presenter-pulse-a { |
| + from { background: rgb(255 180 84 / 0.28); } |
| + to { background: transparent; } |
| +} |
| + |
| +@keyframes presenter-pulse-b { |
| + from { background: rgb(255 180 84 / 0.28); } |
| + to { background: transparent; } |
| +} |
| + |
| +/* How far getting the talk ready has got, or that this window moves on |
| + its own while the network is gone. Quiet, and empty once there is |
| + nothing to say. */ |
| +[presenter-status] { |
| + min-inline-size: 0; |
| + font: 15px/1.3 var(--p-sans); |
| + color: var(--p-muted); |
| +} |
| + |
| +[presenter-status]:empty { |
| + display: none; |
| +} |
| + |
| /* Back and Next: the scriptless presses, quiet beside the timer. */ |
| [presenter-presses] { |
| display: inline-flex; |
diff --git a/internal/slides/templates/present.html b/internal/slides/templates/present.html| index 6f37ba1..a14cf0e 100644 |
| --- a/internal/slides/templates/present.html |
| +++ b/internal/slides/templates/present.html |
| @@ -14,7 +14,12 @@ |
| A session with a position draws its slide at a step (data-step): |
| the session's, or the ?slide=N&step=k a scriptless press redirects |
| to. present.js applies a step change in place, from the data-press |
| - each arriving box carries. */}} |
| + each arriving box carries. |
| + |
| + The slide window of such a session, for whoever may drive it, |
| + loads the presenter bundle instead (fixtures/slide-window.mjs): it |
| + holds the whole talk (data-talk) and moves at once, from memory, on |
| + every press, and says it is waiting while the network is gone. */}} |
| {{define "page-head"}}<link rel="stylesheet" href="{{asset "static/slides.css"}}"> |
| {{if .Refresh}}{{/* The scriptless heartbeat: an audience with no |
| JavaScript still moves with the presenter, five seconds behind. |
| @@ -25,8 +30,9 @@ |
| seconds would blink the follower's slide the same way (and hold it |
| hidden while the font gate ran again). */}} |
| <noscript><meta http-equiv="refresh" content="5"></noscript>{{end}} |
| -<script defer src="{{asset "static/present.js"}}"></script> |
| -<style> |
| +{{if .Bundle}}<script type="module" src="{{.Bundle}}"></script> |
| +{{else}}<script defer src="{{asset "static/present.js"}}"></script> |
| +{{end}}<style> |
| /* The projector is a bounded black stage, never a document that can |
| push its remote controls underneath the fold. The controls live on |
| the stage so the slide can use every pixel behind them. */ |
| @@ -96,6 +102,20 @@ |
| [slides-surface][data-blackout="true"] [slides-stage] { |
| visibility: hidden; |
| } |
| + /* The slide window holding still while the network is gone: small, |
| + in a corner, over the slide. */ |
| + [slides-waiting] { |
| + background: color-mix(in srgb, #000 72%, transparent); |
| + border-radius: var(--rst-radius-sm); |
| + color: #fff; |
| + font-size: var(--rst-fs-sm); |
| + inset-block-start: var(--rst-sp-3); |
| + inset-inline-end: var(--rst-sp-3); |
| + margin: 0; |
| + padding: var(--rst-sp-1) var(--rst-sp-2); |
| + position: absolute; |
| + z-index: 2; |
| + } |
| [slides-blackout] { |
| align-self: center; |
| color: #fff; |
| @@ -121,13 +141,18 @@ |
| data-blackout="{{if .Blackout}}true{{else}}false{{end}}" |
| {{- with .Announce}} data-announce="{{.}}"{{end}} |
| {{- if .Token}} data-remote-token="{{.Token}}"{{end}} |
| - {{- if .NotesHref}} data-notes="{{.NotesHref}}"{{end}}> |
| + {{- if .NotesHref}} data-notes="{{.NotesHref}}"{{end}} |
| + {{- if .Bundle}} data-talk="{{.TalkHref}}" data-command="{{.Controls.Action}}" data-presenter="{{.PresenterHref}}" |
| + data-text-progress="{{.ProgressWords}}" data-text-announce="{{.AnnounceWords}}" data-text-waiting="{{.WaitingWords}}"{{end}}> |
| {{/* Said politely when the slide changes in place (static/present.js); |
| in the page from the start so the change is heard. */}} |
| <p slides-announce class="rst-sr-only" role="status" aria-live="polite" aria-atomic="true"></p> |
| {{if .HasSlide}} |
| <div slides-stage>{{.Slide}}</div> |
| <p slides-blackout{{if not .Blackout}} hidden{{end}}>{{.BlackoutLabel}}</p> |
| + {{- if .Bundle}} |
| + <p slides-waiting role="status" hidden></p> |
| + {{- end}} |
| <div slides-bar> |
| {{if .Controls}}{{template "present-controls" .Controls}}{{end}} |
| {{if .PrevHref}}<a rst-btn href="{{.PrevHref}}" rel="prev">{{.PrevLabel}}</a>{{end}} |
diff --git a/internal/slides/templates/presenter.html b/internal/slides/templates/presenter.html| index ed8f496..91854f0 100644 |
| --- a/internal/slides/templates/presenter.html |
| +++ b/internal/slides/templates/presenter.html |
| @@ -12,14 +12,20 @@ |
| With scripts off every control is a form that posts a press and |
| redirects back to ?slide=N&step=k, which draws that state; the |
| - position is a link to the picker (?pick=1). With them, present.js |
| - reloads the page when the talk moves elsewhere and ticks the clock |
| - and the timer. Task 10's bundle replaces that with a window that |
| - moves at once. */}} |
| + position is a link to the picker (?pick=1). With them, the |
| + presenter bundle (fixtures/presenter-window.mjs) holds the whole |
| + talk (data-talk) and moves the window at once, from memory, on every |
| + press; it ticks the clock and the timer, and draws every sentence |
| + from the data-text-* below. An empty talk has nothing to move, and |
| + keeps static/present.js for the clock and to follow the session. */}} |
| {{define "page-head"}}<link rel="stylesheet" href="{{asset "static/slides.css"}}"> |
| <link rel="stylesheet" href="{{asset "static/presenter.css"}}"> |
| <style>{{.ArrangeCSS}}</style> |
| -<script defer src="{{asset "static/present.js"}}"></script>{{end}} |
| +{{- if .Empty}} |
| +<script defer src="{{asset "static/present.js"}}"></script> |
| +{{- else}} |
| +<script type="module" src="{{.Bundle}}"></script> |
| +{{- end}}{{end}} |
| {{define "presenter-fields"}}<input type="hidden" name="op" value="{{.Op}}"> |
| {{- with .Slide}}<input type="hidden" name="slide" value="{{.}}">{{end}} |
| {{- with .Token}}<input type="hidden" name="t" value="{{.}}">{{end}} |
| @@ -27,10 +33,20 @@ |
| {{define "main"}}<main id="main" presenter data-session="{{.Session}}" |
| {{- if not .Empty}} data-slide="{{.Slide}}" data-step="{{.Step}}" data-mode="{{.Mode}}"{{end}} |
| data-blackout="{{if .Blackout}}true{{else}}false{{end}}" |
| - {{- with .Token}} data-remote-token="{{.}}"{{end}}> |
| + {{- with .Token}} data-remote-token="{{.}}"{{end}} |
| + {{- if not .Empty}} |
| + data-talk="{{.TalkHref}}" data-stream="{{.StreamHref}}" data-command="{{.Action}}" |
| + {{- with .Words}} |
| + data-text-progress="{{.Progress}}" data-text-step="{{.Step}}" |
| + data-text-next-step="{{.NextStep}}" data-text-next-slide="{{.NextSlide}}" data-text-next-end="{{.NextEnd}}" |
| + data-text-mode-core="{{.ModeCore}}" data-text-mode-full="{{.ModeFull}}" data-text-black="{{.Black}}" |
| + data-text-menu-full="{{.MenuFull}}" data-text-menu-core="{{.MenuCore}}" data-text-nonotes="{{.NoNotes}}" |
| + data-text-loading="{{.Loading}}" data-text-loading-failed="{{.LoadingFailed}}" data-text-offline="{{.Offline}}" |
| + {{- end}} |
| + {{- end}}> |
| <div presenter-head> |
| {{- if not .Empty}} |
| - <a presenter-pos slides-counter href="{{.PickHref}}" title="{{.PickLabel}}">{{.Counter}}{{icon "chevron-down"}}</a> |
| + <a presenter-pos slides-counter href="{{.PickHref}}" title="{{.PickLabel}}"><span presenter-count>{{.Counter}}</span>{{icon "chevron-down"}}</a> |
| {{- if .StepCount}} |
| <span presenter-stepcount role="status"><span presenter-track aria-hidden="true"> |
| {{- range .Track}}<i{{if .}} data-done{{end}}></i>{{end -}} |
| @@ -42,6 +58,7 @@ |
| {{- if .Blackout}} |
| <span presenter-black>{{.BlackLabel}}</span> |
| {{- end}} |
| + <span presenter-status role="status"></span> |
| <span presenter-presses> |
| <form method="post" action="{{.Action}}" data-busy="false"> |
| {{template "presenter-fields" .Back}} |
diff --git a/internal/slidestest/browser_present_test.go b/internal/slidestest/browser_present_test.go| index 1fec644..a7e0fee 100644 |
| --- a/internal/slidestest/browser_present_test.go |
| +++ b/internal/slidestest/browser_present_test.go |
| @@ -97,9 +97,11 @@ func browserPresent(t *testing.T, rig *harness.Rig, served *testApp, deck string |
| // TestBrowserPresentingScreensHoldStill: the presenter view and the |
| // phone remote each load once and then stay put while nothing |
| -// changes, and each reloads exactly once when the slide does move — |
| -// which is how those two pages follow a talk (present.js reloads them |
| -// rather than re-rendering two slides and the notes itself). |
| +// changes. When the slide moves the remote reloads exactly once, which |
| +// is how it follows a talk (present.js reloads it rather than |
| +// re-rendering the slide itself); the presenter window of a session |
| +// with a position moves in place, from the talk it holds, and never |
| +// reloads (fixtures/presenter-window.mjs). |
| func TestBrowserPresentingScreensHoldStill(t *testing.T) { |
| rig, served := newRigApp(t, nil) |
| browserSignIn(t, rig, served.mailer) |
| @@ -145,9 +147,10 @@ func TestBrowserPresentingScreensHoldStill(t *testing.T) { |
| t.Errorf("the %s's script root says data-slide=%q; the counter shows slide %q", name, marked, counter) |
| } |
| } |
| - // movesOnce presses the right arrow — present.js posts `next` — and |
| - // the page must reload onto the new slide once, and only once. |
| - movesOnce := func(name, counter string) { |
| + // movesOnce presses the right arrow — the page posts `next` — and |
| + // the page must show the new slide having loaded exactly loads |
| + // times. |
| + movesOnce := func(name, counter string, want int64) { |
| t.Helper() |
| before := loads.Load() |
| rig.Run( |
| @@ -155,17 +158,17 @@ func TestBrowserPresentingScreensHoldStill(t *testing.T) { |
| waitFor(`document.querySelector('[slides-counter]')?.textContent.trim().startsWith('`+counter+` /')`), |
| chromedp.Sleep(3*time.Second), |
| ) |
| - if n := loads.Load() - before; n != 1 { |
| - t.Errorf("the %s loaded %d times after one slide change, want exactly 1", name, n) |
| + if n := loads.Load() - before; n != want { |
| + t.Errorf("the %s loaded %d times after one slide change, want exactly %d", name, n, want) |
| } |
| } |
| holdsStill("presenter view") |
| rig.Screen("body", "presenter view") |
| - movesOnce("presenter view", "2") |
| + movesOnce("presenter view", "2", 0) |
| rig.Run(chromedp.Navigate(rig.Origin + session + "/remote?t=" + token)) |
| holdsStill("remote") |
| rig.Screen("body", "remote") |
| - movesOnce("remote", "3") |
| + movesOnce("remote", "3", 1) |
| } |
diff --git a/internal/slidestest/fonts_browser_test.go b/internal/slidestest/fonts_browser_test.go| index 0ad1192..68b7a83 100644 |
| --- a/internal/slidestest/fonts_browser_test.go |
| +++ b/internal/slidestest/fonts_browser_test.go |
| @@ -44,6 +44,7 @@ import ( |
| "time" |
| "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/blobs" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/harness" |
| "github.com/chromedp/cdproto/emulation" |
| @@ -71,12 +72,23 @@ type fontRig struct { |
| match atomic.Value |
| blocked atomic.Value |
| editorDelay atomic.Int64 |
| + // wrap, when set, answers every request in place of the rig's own |
| + // handling, which it is handed as next: a check can hold a request, |
| + // or cut a stream, on the way out. |
| + wrap atomic.Pointer[func(w http.ResponseWriter, r *http.Request, next http.Handler)] |
| mu sync.Mutex |
| fontHits map[string]int |
| } |
| func newFontRig(t *testing.T) *fontRig { |
| + t.Helper() |
| + return newFontRigWith(t, nil) |
| +} |
| + |
| +// newFontRigWith is newFontRig with an object store, so a deck can hold |
| +// pictures. |
| +func newFontRigWith(t *testing.T, store blobs.Store) *fontRig { |
| t.Helper() |
| fr := &fontRig{fontHits: map[string]int{}} |
| fr.match.Store("") |
| @@ -94,6 +106,7 @@ func newFontRig(t *testing.T) *fontRig { |
| InstanceKey: testInstanceKey, |
| Mailer: mailer, |
| AllowedAddresses: []string{allowedAddress}, |
| + Blobs: store, |
| Logger: logger, |
| }) |
| if err != nil { |
| @@ -107,7 +120,15 @@ func newFontRig(t *testing.T) *fontRig { |
| } |
| t.Cleanup(func() { _ = closeFn() }) |
| fr.app = &testApp{Handler: served, mailer: mailer, db: d, mux: mux, app: a} |
| - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + var rest http.Handler |
| + outer := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if wrap := fr.wrap.Load(); wrap != nil { |
| + (*wrap)(w, r, rest) |
| + return |
| + } |
| + rest.ServeHTTP(w, r) |
| + }) |
| + rest = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| if b := fr.blocked.Load().(string); b != "" && strings.Contains(r.URL.Path, b) { |
| http.NotFound(w, r) |
| return |
| @@ -127,6 +148,7 @@ func newFontRig(t *testing.T) *fontRig { |
| } |
| served.ServeHTTP(w, r) |
| }) |
| + return outer |
| }) |
| fr.cookies = signedIn(t, fr.app, allowedAddress) |
| fr.token = mintAgent(t, fr.app, fr.cookies, "fonts") |
| @@ -1734,16 +1756,23 @@ func TestFontTheNextSlideWaitsForItsFamilyBehindTheCurrentOne(t *testing.T) { |
| // The projector pages in place too: the presenter's own Next and |
| // Previous on the projector (command forms) and a watcher's links on the |
| // follow-free projector page. Never a reload, never a frame without a |
| -// slide. |
| +// slide. A watcher is somebody who may not drive: no token, and not the |
| +// presenter signed in, who drives from their own slide window. |
| func TestFontTheProjectorPagesInPlace(t *testing.T) { |
| fr := newFontRig(t) |
| sqid := fr.deck(t, "Talk", paperDeck) |
| session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies) |
| - for _, c := range []struct{ name, path, next, prev string }{ |
| - {"the presenter's buttons", "/p/" + session + "?t=" + token, `[slides-bar] form input[value="next"]`, `[slides-bar] form input[value="prev"]`}, |
| - {"a watcher's links", "/p/" + session, `[slides-bar] a[rel="next"]`, `[slides-bar] a[rel="prev"]`}, |
| + for _, c := range []struct { |
| + name, path, next, prev string |
| + watcher bool |
| + }{ |
| + {"the presenter's buttons", "/p/" + session + "?t=" + token, `[slides-bar] form input[value="next"]`, `[slides-bar] form input[value="prev"]`, false}, |
| + {"a watcher's links", "/p/" + session, `[slides-bar] a[rel="next"]`, `[slides-bar] a[rel="prev"]`, true}, |
| } { |
| t.Run(c.name, func(t *testing.T) { |
| + if c.watcher { |
| + fr.rig.Run(network.ClearBrowserCookies()) |
| + } |
| fr.rig.Run(chromedp.Evaluate(`window.__leaving = true`, nil), fr.navigate(c.path)) |
| fr.until(t, `!window.__leaving && !!document.querySelector('[slides-slide]') && document.documentElement.getAttribute('data-slides-fonts') === 'shown'`) |
| fr.rig.Run(chromedp.Sleep(300 * time.Millisecond)) |
diff --git a/internal/slidestest/presenter_moves_browser_test.go b/internal/slidestest/presenter_moves_browser_test.go| new file mode 100644 |
| index 0000000..182d421 |
| --- /dev/null |
| +++ b/internal/slidestest/presenter_moves_browser_test.go |
| @@ -0,0 +1,587 @@ |
| +//go:build browser |
| + |
| +// The presenter window and the slide window move at once (Task 10, |
| +// spec §6): a press redraws the window from the talk it holds in |
| +// memory, then goes to the server; a press is never lost or repeated, |
| +// never unanswered, and needs no network. |
| +package slidestest |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/blobs" |
| + "github.com/chromedp/cdproto/input" |
| + "github.com/chromedp/cdproto/network" |
| + "github.com/chromedp/chromedp" |
| + "github.com/chromedp/chromedp/kb" |
| +) |
| + |
| +// movesTalk is a session on a deck of four slides in the talk: "steps" |
| +// (four presses), "plain", "picture" (an image) and "last". |
| +type movesTalk struct { |
| + fr *fontRig |
| + sqid string |
| + session, token string |
| + |
| + // hold, when set, sees each request first and may hold it. |
| + hold atomic.Pointer[func(r *http.Request)] |
| + |
| + // Chromium's offline emulation stops new requests but leaves a |
| + // stream already open delivering, so a cut network also ends every |
| + // open stream here, and refuses new ones until it is healed. |
| + mu sync.Mutex |
| + off bool |
| + streams map[*http.Request]context.CancelFunc |
| +} |
| + |
| +func newMovesTalk(t *testing.T) *movesTalk { |
| + t.Helper() |
| + store, err := blobs.Dir(t.TempDir()) |
| + if err != nil { |
| + t.Fatalf("blobs.Dir: %v", err) |
| + } |
| + fr := newFontRigWith(t, store) |
| + mt := &movesTalk{fr: fr, streams: map[*http.Request]context.CancelFunc{}} |
| + wrap := func(w http.ResponseWriter, r *http.Request, next http.Handler) { |
| + if hold := mt.hold.Load(); hold != nil { |
| + (*hold)(r) |
| + } |
| + if !strings.HasSuffix(r.URL.Path, "/stream") { |
| + next.ServeHTTP(w, r) |
| + return |
| + } |
| + mt.mu.Lock() |
| + if mt.off { |
| + mt.mu.Unlock() |
| + http.Error(w, "cut", http.StatusServiceUnavailable) |
| + return |
| + } |
| + ctx, cancel := context.WithCancel(r.Context()) |
| + mt.streams[r] = cancel |
| + mt.mu.Unlock() |
| + defer func() { |
| + mt.mu.Lock() |
| + delete(mt.streams, r) |
| + mt.mu.Unlock() |
| + cancel() |
| + }() |
| + next.ServeHTTP(w, r.WithContext(ctx)) |
| + } |
| + fr.wrap.Store(&wrap) |
| + mt.sqid = fr.deck(t, "Moves", `[]`) |
| + record := upload(t, fr.app, "/d/"+mt.sqid, fr.cookies, "chart.png", "image/png", onePixelPNG, "A chart") |
| + registerInDeck(t, fr.app, fr.token, mt.sqid, record) |
| + ops := []string{ |
| + `{"op":"add_slide","id":"steps","layout":"flow","template":"title-body"}`, |
| + `{"op":"add_block","slide":"steps","id":"stepshead","type":"heading","region":"heading","props":{"level":1},"markdown":"Steps"}`, |
| + } |
| + for i, word := range []string{"one", "two", "three", "four"} { |
| + id := quote("b" + strconv.Itoa(i+1)) |
| + ops = append(ops, |
| + `{"op":"add_block","slide":"steps","id":`+id+`,"type":"text","region":"body","markdown":`+quote(word)+`}`, |
| + `{"op":"set_block","slide":"steps","id":`+id+`,"step":`+strconv.Itoa(i+1)+`}`) |
| + } |
| + ops = append(ops, |
| + `{"op":"add_slide","id":"plain","layout":"flow","template":"title-body"}`, |
| + `{"op":"add_block","slide":"plain","id":"plainhead","type":"heading","region":"heading","props":{"level":1},"markdown":"Plain"}`, |
| + `{"op":"add_slide","id":"picture","layout":"flow","template":"image-full"}`, |
| + fmt.Sprintf(`{"op":"add_block","slide":"picture","id":"pictureimg","type":"image","region":"media","props":{"asset":%q}}`, record["id"]), |
| + `{"op":"add_slide","id":"last","layout":"flow","template":"title-body"}`, |
| + `{"op":"add_block","slide":"last","id":"lasthead","type":"heading","region":"heading","props":{"level":1},"markdown":"Last"}`) |
| + fr.ops(t, mt.sqid, "["+strings.Join(ops, ",")+"]") |
| + mt.session, mt.token = startPresenting(t, fr.app, "/d/"+mt.sqid, fr.cookies) |
| + return mt |
| +} |
| + |
| +func (mt *movesTalk) presenter() string { |
| + return "/p/" + mt.session + "/notes?t=" + url.QueryEscape(mt.token) |
| +} |
| + |
| +func (mt *movesTalk) slideWindow() string { |
| + return "/p/" + mt.session + "?t=" + url.QueryEscape(mt.token) |
| +} |
| + |
| +// phone presses as the paired phone does. |
| +func (mt *movesTalk) phone(t *testing.T, name string) pressAnswer { |
| + t.Helper() |
| + return press(t, mt.fr.app, mt.session, mt.token, op(t, name), nil) |
| +} |
| + |
| +func (mt *movesTalk) gotoSlide(t *testing.T, n int) { |
| + t.Helper() |
| + press(t, mt.fr.app, mt.session, mt.token, url.Values{"op": {"goto"}, "slide": {strconv.Itoa(n)}, "press": {newPressID(t)}}, nil) |
| +} |
| + |
| +// row is where the server says the talk is. |
| +func (mt *movesTalk) row(t *testing.T) (string, int, int64) { |
| + t.Helper() |
| + return rowPosition(t, mt.fr.app, mt.session) |
| +} |
| + |
| +// waitRow waits until the server's position is slide at step. |
| +func (mt *movesTalk) waitRow(t *testing.T, slide string, step int) { |
| + t.Helper() |
| + deadline := time.Now().Add(15 * time.Second) |
| + for { |
| + id, k, _ := mt.row(t) |
| + if id == slide && k == step { |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the server is at %s step %d, want %s step %d", id, k, slide, step) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| +} |
| + |
| +// root is the window's root on either page. |
| +const rootJS = `(document.querySelector('[presenter]') || document.querySelector('[slides-surface]'))` |
| + |
| +// open loads path in ctx and waits until the window holds the whole talk. |
| +func open(t *testing.T, ctx context.Context, origin, path string) { |
| + t.Helper() |
| + run(t, ctx, chromedp.Navigate(origin+path), waitFor(rootJS+`?.getAttribute('data-loaded') === 'all'`)) |
| +} |
| + |
| +func run(t *testing.T, ctx context.Context, actions ...chromedp.Action) { |
| + t.Helper() |
| + if err := chromedp.Run(ctx, actions...); err != nil { |
| + t.Fatalf("drive: %v", err) |
| + } |
| +} |
| + |
| +// windowState is what a window's root says it shows. |
| +type windowState struct { |
| + Slide, Step, Mode, Black string |
| + Steps, Pos, Flash, Pulse string |
| + Now string |
| +} |
| + |
| +const windowStateJS = `(() => { const r = ` + rootJS + `; |
| + const sc = document.querySelector('[presenter-stepcount]'); |
| + const pos = document.querySelector('[presenter-pos]'); |
| + const now = document.querySelector('[presenter-panel="now"] [slides-slide]') || document.querySelector('[slides-stage] [slides-slide]'); |
| + return { Slide: r.dataset.slide, Step: r.dataset.step, Mode: r.dataset.mode, Black: r.dataset.blackout, |
| + Steps: sc && sc.checkVisibility() ? sc.innerText : '', Pos: pos ? pos.innerText : '', |
| + Flash: sc ? sc.getAttribute('data-flash') || '' : '', Pulse: pos ? pos.getAttribute('data-pulse') || '' : '', |
| + Now: now ? now.innerText : '' }; })()` |
| + |
| +func state(t *testing.T, ctx context.Context) windowState { |
| + t.Helper() |
| + var s windowState |
| + run(t, ctx, chromedp.Evaluate(windowStateJS, &s)) |
| + return s |
| +} |
| + |
| +func key(k string) chromedp.Action { return chromedp.KeyEvent(k) } |
| + |
| +// TestPresenterStepCountChangesOnEveryPress: through a slide with steps |
| +// the step count's words change on every press, at once; on slides |
| +// without steps it is not drawn and the position changes instead. |
| +func TestPresenterStepCountChangesOnEveryPress(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + before := state(t, ctx) |
| + if before.Steps == "" { |
| + t.Fatalf("the step count is not drawn on a slide with steps: %+v", before) |
| + } |
| + for k := 1; k <= 4; k++ { |
| + run(t, ctx, key(kb.ArrowRight)) |
| + got := state(t, ctx) |
| + if got.Step != strconv.Itoa(k) || got.Steps == before.Steps || got.Steps == "" { |
| + t.Fatalf("press %d: step %q, step count %q (was %q); want step %d and new words, at once", k, got.Step, got.Steps, before.Steps, k) |
| + } |
| + if got.Flash == before.Flash { |
| + t.Errorf("press %d: the step count's flash did not restart", k) |
| + } |
| + before = got |
| + } |
| + for _, want := range []string{"2", "3", "4"} { |
| + run(t, ctx, key(kb.ArrowRight)) |
| + got := state(t, ctx) |
| + if got.Slide != want || got.Pos == before.Pos || got.Steps != "" { |
| + t.Fatalf("onto slide %s: data-slide %q, position %q (was %q), step count %q; want the position to change and no step count", |
| + want, got.Slide, got.Pos, before.Pos, got.Steps) |
| + } |
| + before = got |
| + } |
| + mt.waitRow(t, "last", 0) |
| +} |
| + |
| +// TestTheLastPressOfTheTalkStillAnswers: next on the last step of the |
| +// last slide moves nothing, and still answers: the position pulses |
| +// again, the step count's flash restarts, and the server hears it. |
| +func TestTheLastPressOfTheTalkStillAnswers(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + run(t, ctx, key(kb.End)) |
| + mt.waitRow(t, "last", 0) |
| + before := state(t, ctx) |
| + _, _, seq := mt.row(t) |
| + for range 2 { |
| + var running bool |
| + run(t, ctx, key(kb.ArrowRight), |
| + chromedp.Evaluate(`document.querySelector('[presenter-pos]').getAnimations().some(a => a.playState === 'running')`, &running)) |
| + got := state(t, ctx) |
| + if got.Slide != before.Slide || got.Step != before.Step { |
| + t.Fatalf("next at the end moved the window: %+v, was %+v", got, before) |
| + } |
| + if got.Pulse == before.Pulse || got.Flash == before.Flash || !running { |
| + t.Errorf("next at the end did not answer: pulse %q (was %q), flash %q (was %q), animating %v", |
| + got.Pulse, before.Pulse, got.Flash, before.Flash, running) |
| + } |
| + before = got |
| + } |
| + deadline := time.Now().Add(10 * time.Second) |
| + for { |
| + _, _, now := mt.row(t) |
| + if now >= seq+2 { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the server heard %d of the two presses at the end", now-seq) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| +} |
| + |
| +// TestPresenterFastPressesNeverJumpBack: with every press's answer |
| +// slow, three quick presses move the window three steps at once, it |
| +// never shows an earlier step on any frame while the answers come in, |
| +// and the server counts three. |
| +func TestPresenterFastPressesNeverJumpBack(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + slow := func(r *http.Request) { |
| + if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/command") { |
| + time.Sleep(600 * time.Millisecond) |
| + } |
| + } |
| + mt.hold.Store(&slow) |
| + run(t, ctx, chromedp.Evaluate(`(() => { window.__steps = []; const r = `+rootJS+`; |
| + const sample = () => { window.__steps.push(Number(r.dataset.step)); requestAnimationFrame(sample) }; sample(); return true })()`, nil)) |
| + run(t, ctx, key(kb.ArrowRight), key(kb.ArrowRight), key(kb.ArrowRight)) |
| + if got := state(t, ctx); got.Step != "3" { |
| + t.Fatalf("three quick presses: the window is at step %s, want 3 at once", got.Step) |
| + } |
| + mt.waitRow(t, "steps", 3) |
| + run(t, ctx, chromedp.Sleep(1500*time.Millisecond)) |
| + var steps []int |
| + run(t, ctx, chromedp.Evaluate(`window.__steps`, &steps)) |
| + for i := 1; i < len(steps); i++ { |
| + if steps[i] < steps[i-1] { |
| + t.Fatalf("the step went back from %d to %d on frame %d of %d: %v", steps[i-1], steps[i], i, len(steps), steps) |
| + } |
| + } |
| + if len(steps) == 0 || steps[len(steps)-1] != 3 { |
| + t.Errorf("the window ended at %v, want step 3", steps) |
| + } |
| + if _, step, _ := mt.row(t); step != 3 { |
| + t.Errorf("the server counted %d presses, want 3", step) |
| + } |
| +} |
| + |
| +// TestPresenterIgnoresKeyRepeat: a key held down is one press. |
| +func TestPresenterIgnoresKeyRepeat(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + down := func(repeat bool) chromedp.Action { |
| + return input.DispatchKeyEvent(input.KeyDown).WithKey("ArrowRight").WithCode("ArrowRight"). |
| + WithWindowsVirtualKeyCode(39).WithNativeVirtualKeyCode(39).WithAutoRepeat(repeat) |
| + } |
| + run(t, ctx, down(false), down(true), down(true), down(true), |
| + input.DispatchKeyEvent(input.KeyUp).WithKey("ArrowRight").WithCode("ArrowRight").WithWindowsVirtualKeyCode(39).WithNativeVirtualKeyCode(39)) |
| + if got := state(t, ctx); got.Step != "1" { |
| + t.Fatalf("a held key moved the window to step %s, want 1", got.Step) |
| + } |
| + mt.waitRow(t, "steps", 1) |
| + run(t, ctx, chromedp.Sleep(time.Second)) |
| + if _, step, _ := mt.row(t); step != 1 { |
| + t.Errorf("a held key moved the talk to step %d, want 1", step) |
| + } |
| +} |
| + |
| +// TestPresenterClickerWorksFromAField: with a field focused, the |
| +// clicker's PageDown and PageUp still move the talk, and every other |
| +// key is typed into the field. |
| +func TestPresenterClickerWorksFromAField(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + run(t, ctx, |
| + chromedp.Evaluate(`(() => { const f = document.createElement('input'); f.id = 'field'; document.querySelector('[presenter-head]').append(f); return true })()`, nil), |
| + chromedp.Focus(`#field`, chromedp.ByQuery), |
| + key(kb.PageDown)) |
| + if got := state(t, ctx); got.Step != "1" { |
| + t.Fatalf("PageDown from a field: step %s, want 1", got.Step) |
| + } |
| + var value string |
| + run(t, ctx, key("b"), key(kb.ArrowRight), chromedp.Value(`#field`, &value, chromedp.ByQuery)) |
| + if got := state(t, ctx); got.Step != "1" || got.Black != "false" || value != "b" { |
| + t.Errorf("typing in a field moved the talk: step %s, black %s, the field holds %q", got.Step, got.Black, value) |
| + } |
| + run(t, ctx, key(kb.PageUp)) |
| + if got := state(t, ctx); got.Step != "0" { |
| + t.Errorf("PageUp from a field: step %s, want 0", got.Step) |
| + } |
| + mt.waitRow(t, "steps", 0) |
| +} |
| + |
| +// TestTwoWindowsAndAPhoneStayTogether: a press in either window or on |
| +// the phone moves all three; the laptop and the phone pressing at once |
| +// both count. |
| +func TestTwoWindowsAndAPhoneStayTogether(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + presenter := mt.fr.rig.Context() |
| + slides, cancel := chromedp.NewContext(presenter) |
| + defer cancel() |
| + open(t, presenter, mt.fr.rig.Origin, mt.presenter()) |
| + open(t, slides, mt.fr.rig.Origin, mt.slideWindow()) |
| + both := func(slide, step string) { |
| + t.Helper() |
| + want := rootJS + `.dataset.slide === '` + slide + `' && ` + rootJS + `.dataset.step === '` + step + `'` |
| + run(t, presenter, waitFor(want)) |
| + run(t, slides, waitFor(want)) |
| + } |
| + |
| + run(t, presenter, key(kb.ArrowRight)) |
| + both("1", "1") |
| + run(t, slides, key(kb.ArrowRight)) |
| + both("1", "2") |
| + mt.phone(t, "next") |
| + both("1", "3") |
| + |
| + var wg sync.WaitGroup |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + rec := pressRequest(t, mt.fr.app, mt.session, mt.token, op(t, "next"), nil) |
| + if rec.Code != http.StatusOK { |
| + t.Errorf("the phone's press: %d", rec.Code) |
| + } |
| + }() |
| + run(t, presenter, key(kb.ArrowRight)) |
| + wg.Wait() |
| + mt.waitRow(t, "plain", 0) |
| + both("2", "0") |
| +} |
| + |
| +// cut takes the pages in ctxs off the network, or puts them back. |
| +func (mt *movesTalk) cut(t *testing.T, off bool, ctxs ...context.Context) { |
| + t.Helper() |
| + for _, ctx := range ctxs { |
| + run(t, ctx, network.EmulateNetworkConditions(off, 0, -1, -1)) |
| + } |
| + mt.mu.Lock() |
| + mt.off = off |
| + if off { |
| + for _, cancel := range mt.streams { |
| + cancel() |
| + } |
| + } |
| + mt.mu.Unlock() |
| +} |
| + |
| +// TestADroppedNetworkKeepsThePressingWindowMoving: with the network cut |
| +// the presenter window still moves across slides, a picture included, |
| +// and says so; the slide window holds still and says it is waiting; when |
| +// the network returns the server takes the presenter window's position |
| +// over a phone press made meanwhile, and the slide window follows. |
| +func TestADroppedNetworkKeepsThePressingWindowMoving(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + mt.gotoSlide(t, 2) |
| + presenter := mt.fr.rig.Context() |
| + slides, cancel := chromedp.NewContext(presenter) |
| + defer cancel() |
| + open(t, presenter, mt.fr.rig.Origin, mt.presenter()) |
| + open(t, slides, mt.fr.rig.Origin, mt.slideWindow()) |
| + run(t, presenter, waitFor(rootJS+`.dataset.slide === '2'`)) |
| + run(t, slides, waitFor(rootJS+`.dataset.slide === '2'`)) |
| + |
| + mt.cut(t, true, presenter, slides) |
| + // The cut is real: a phone press made now reaches neither window. |
| + mt.phone(t, "prev") |
| + run(t, presenter, chromedp.Sleep(2*time.Second)) |
| + for name, ctx := range map[string]context.Context{"presenter window": presenter, "slide window": slides} { |
| + if got := state(t, ctx); got.Slide != "2" { |
| + t.Fatalf("the %s heard the phone through a cut network: on slide %s step %s", name, got.Slide, got.Step) |
| + } |
| + } |
| + |
| + picture := `(() => { const img = document.querySelector('[presenter-panel="now"] img'); return !!img && img.complete && img.naturalWidth > 0 })()` |
| + var drawn bool |
| + run(t, presenter, key(kb.ArrowRight), chromedp.Evaluate(picture, &drawn)) |
| + if got := state(t, presenter); got.Slide != "3" || !drawn { |
| + t.Fatalf("offline, next onto the picture: slide %s, picture drawn %v", got.Slide, drawn) |
| + } |
| + run(t, presenter, key(kb.ArrowRight)) |
| + if got := state(t, presenter); got.Slide != "4" || !strings.Contains(got.Now, "Last") { |
| + t.Fatalf("offline, next onto the last slide: slide %s, Now %q", got.Slide, got.Now) |
| + } |
| + run(t, presenter, waitFor(`document.querySelector('[presenter-status]').innerText === 'Offline. This window still moves.'`)) |
| + run(t, slides, waitFor(`document.querySelector('[slides-waiting]')?.checkVisibility() && document.querySelector('[slides-waiting]').innerText === 'Waiting for the network'`)) |
| + if got := state(t, slides); got.Slide != "2" { |
| + t.Errorf("the slide window moved while cut off: slide %s", got.Slide) |
| + } |
| + |
| + mt.cut(t, false, presenter, slides) |
| + mt.waitRow(t, "last", 0) |
| + run(t, slides, waitFor(rootJS+`.dataset.slide === '4'`), waitFor(`!document.querySelector('[slides-waiting]').checkVisibility()`)) |
| + run(t, presenter, waitFor(`document.querySelector('[presenter-status]').innerText === ''`)) |
| + if got := state(t, presenter); got.Slide != "4" { |
| + t.Errorf("the presenter window left its own position on reconnecting: slide %s", got.Slide) |
| + } |
| +} |
| + |
| +// TestAWindowThatPressedNothingTakesTheServersPosition: a window cut off |
| +// that pressed nothing takes where the phone took the talk meanwhile, |
| +// and tells the server nothing. |
| +func TestAWindowThatPressedNothingTakesTheServersPosition(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + mt.cut(t, true, ctx) |
| + mt.phone(t, "next") |
| + mt.phone(t, "next") |
| + run(t, ctx, chromedp.Sleep(2*time.Second)) |
| + if got := state(t, ctx); got.Step != "0" { |
| + t.Fatalf("the window heard the phone through a cut network: step %s", got.Step) |
| + } |
| + run(t, ctx, waitFor(`document.querySelector('[presenter-status]').innerText === 'Offline. This window still moves.'`)) |
| + _, _, seq := mt.row(t) |
| + mt.cut(t, false, ctx) |
| + run(t, ctx, waitFor(rootJS+`.dataset.step === '2'`), waitFor(`document.querySelector('[presenter-status]').innerText === ''`)) |
| + run(t, ctx, chromedp.Sleep(time.Second)) |
| + if id, step, now := mt.row(t); id != "steps" || step != 2 || now != seq { |
| + t.Errorf("the server is at %s step %d (seq %d, was %d); the window that pressed nothing changed it", id, step, now, seq) |
| + } |
| +} |
| + |
| +// TestPresenterTakesAnEditAtTheNextSlide: a deck changed during the |
| +// talk is loaded quietly and taken at the window's next change of |
| +// slide, landing where the server lands: the current slide deleted, |
| +// parked, or left with fewer steps. |
| +func TestPresenterTakesAnEditAtTheNextSlide(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + start func(mt *movesTalk, t *testing.T) |
| + edit string |
| + key string |
| + slide string // where the window and the server land |
| + step int |
| + shows string |
| + }{ |
| + {name: "the current slide deleted", start: func(mt *movesTalk, t *testing.T) { mt.gotoSlide(t, 2) }, |
| + edit: `[{"op":"remove_slide","id":"plain"}]`, key: kb.ArrowLeft, slide: "steps", step: 4, shows: "four"}, |
| + {name: "the current slide parked", start: func(mt *movesTalk, t *testing.T) { mt.gotoSlide(t, 2) }, |
| + edit: `[{"op":"set_slide","id":"plain","talk":"parked"}]`, key: kb.ArrowLeft, slide: "steps", step: 4, shows: "four"}, |
| + {name: "the current slide losing steps", start: func(mt *movesTalk, t *testing.T) { |
| + mt.phone(t, "next") |
| + mt.phone(t, "next") |
| + mt.phone(t, "next") |
| + }, edit: `[{"op":"set_block","slide":"steps","id":"b4","step":null}]`, key: kb.ArrowRight, slide: "plain", step: 0, shows: "Plain"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + ctx := mt.fr.rig.Context() |
| + c.start(mt, t) |
| + open(t, ctx, mt.fr.rig.Origin, mt.presenter()) |
| + before := state(t, ctx) |
| + mt.fr.ops(t, mt.sqid, c.edit) |
| + // The speaker comes back from the editor. |
| + run(t, ctx, chromedp.Evaluate(`window.dispatchEvent(new Event('focus'))`, nil), |
| + waitFor(rootJS+`.hasAttribute('data-deck-pending')`)) |
| + if got := state(t, ctx); got.Now != before.Now || got.Slide != before.Slide { |
| + t.Fatalf("the window took the edit before the slide changed: Now %q (was %q)", got.Now, before.Now) |
| + } |
| + run(t, ctx, key(c.key)) |
| + got := state(t, ctx) |
| + mt.waitRow(t, c.slide, c.step) |
| + if got.Step != strconv.Itoa(c.step) || !strings.Contains(got.Now, c.shows) { |
| + t.Errorf("after the press the window is at step %s showing %q; the server is at %s step %d (%s)", |
| + got.Step, got.Now, c.slide, c.step, c.shows) |
| + } |
| + var pending bool |
| + run(t, ctx, chromedp.Evaluate(rootJS+`.hasAttribute('data-deck-pending')`, &pending)) |
| + if pending { |
| + t.Error("the newer version is still waiting after a change of slide") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// frameLogJS records, on every frame, the slide on the presenter's Now: |
| +// its heading, and whether its picture is drawn. |
| +const frameLogJS = `(() => { window.__frames = []; |
| + const log = () => { const now = document.querySelectorAll('[presenter-panel="now"] [slides-slide]'); |
| + const img = now[0] && now[0].querySelector('img'); |
| + window.__frames.push({ n: now.length, text: now[0] ? now[0].innerText : '', img: !!img, ok: !!img && img.complete && img.naturalWidth > 0 }); |
| + requestAnimationFrame(log) }; |
| + log(); return true })()` |
| + |
| +// TestPressBeforeTheTalkLoadsKeepsTheSlideOnScreen: a press made while |
| +// the talk and the next slide's picture are still on their way leaves |
| +// the slide on screen, never a blank, until the next is complete, which |
| +// arrives whole. |
| +func TestPressBeforeTheTalkLoadsKeepsTheSlideOnScreen(t *testing.T) { |
| + mt := newMovesTalk(t) |
| + mt.gotoSlide(t, 2) |
| + ctx := mt.fr.rig.Context() |
| + hold := func(r *http.Request) { |
| + switch { |
| + case strings.HasSuffix(r.URL.Path, "/talk"): |
| + time.Sleep(1500 * time.Millisecond) |
| + case strings.Contains(r.URL.Path, "/assets/"): |
| + time.Sleep(3 * time.Second) |
| + } |
| + } |
| + mt.hold.Store(&hold) |
| + run(t, ctx, mt.fr.navigate(mt.presenter())) |
| + mt.fr.shown(t) |
| + run(t, ctx, chromedp.Evaluate(frameLogJS, nil), key(kb.ArrowRight)) |
| + var loaded string |
| + run(t, ctx, chromedp.Evaluate(rootJS+`.getAttribute('data-loaded') || ''`, &loaded)) |
| + if loaded == "all" { |
| + t.Fatal("the talk was loaded before the press; the check needs it not to be") |
| + } |
| + run(t, ctx, waitFor(rootJS+`.dataset.slide === '3'`), chromedp.Sleep(300*time.Millisecond)) |
| + var frames []struct { |
| + N int |
| + Text string |
| + Img, OK bool |
| + } |
| + run(t, ctx, chromedp.Evaluate(`window.__frames`, &frames)) |
| + seenPicture := false |
| + for i, f := range frames { |
| + if f.N != 1 { |
| + t.Fatalf("frame %d of %d had %d slides on Now: never a blank", i, len(frames), f.N) |
| + } |
| + if f.Img && !f.OK { |
| + t.Fatalf("frame %d: the picture slide was up before its picture", i) |
| + } |
| + if f.Img { |
| + seenPicture = true |
| + } else if seenPicture { |
| + t.Fatalf("frame %d: back off the picture slide to %q", i, f.Text) |
| + } else if !strings.Contains(f.Text, "Plain") { |
| + t.Fatalf("frame %d: before the picture Now showed %q, want the slide it was on", i, f.Text) |
| + } |
| + } |
| + if !seenPicture { |
| + t.Errorf("the picture slide never came up in %d frames", len(frames)) |
| + } |
| + mt.waitRow(t, "picture", 0) |
| +} |
diff --git a/internal/slidestest/presenter_moves_test.go b/internal/slidestest/presenter_moves_test.go| new file mode 100644 |
| index 0000000..706e32e |
| --- /dev/null |
| +++ b/internal/slidestest/presenter_moves_test.go |
| @@ -0,0 +1,86 @@ |
| +package slidestest |
| + |
| +import ( |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +var ( |
| + presenterBundle = regexp.MustCompile(`<script type="module" src="/static/presenter\.[0-9a-f]{16}(\.[0-9a-f]{16})?\.js"></script>`) |
| + presentScript = regexp.MustCompile(`src="/static/present\.([0-9a-f]{16}\.)?js"`) |
| +) |
| + |
| +// TestTheWindowsThatDriveHoldTheTalk: the presenter window and the |
| +// slide window of a session with a position, for whoever may drive it, |
| +// load the presenter bundle with the talk's address and every sentence |
| +// it draws from the catalog (Task 10). The follow link, a watcher, and a |
| +// session begun before positions keep static/present.js. |
| +func TestTheWindowsThatDriveHoldTheTalk(t *testing.T) { |
| + a := newApp(t) |
| + cookies := signedIn(t, a, allowedAddress) |
| + deck := stepsDeck(t, a, cookies) |
| + session, token := startPresenting(t, a, deck, cookies) |
| + talk := `data-talk="/p/` + session + `/talk` |
| + |
| + window := mustGet(t, a, "/p/"+session+"/notes?t="+url.QueryEscape(token), http.StatusOK, nil).Body.String() |
| + for _, want := range []string{ |
| + talk + `?t=`, |
| + `data-stream="/p/` + session + `/stream"`, |
| + `data-command="/p/` + session + `/command"`, |
| + `data-text-loading="Getting the talk ready: {n} of {total}"`, |
| + `data-text-loading-failed="{n} slides did not load. They will show when the network allows."`, |
| + `data-text-offline="Offline. This window still moves."`, |
| + `data-text-step="step {n} of {total}"`, |
| + `<span presenter-status role="status"></span>`, |
| + } { |
| + if !strings.Contains(window, want) { |
| + t.Errorf("the presenter window lacks %s", want) |
| + } |
| + } |
| + if !presenterBundle.MatchString(window) || presentScript.MatchString(window) { |
| + t.Error("the presenter window does not load the presenter bundle in place of present.js") |
| + } |
| + |
| + for _, c := range []struct { |
| + name string |
| + path string |
| + cookies []*http.Cookie |
| + bundle bool |
| + }{ |
| + {"the slide window with the token", "/p/" + session + "?t=" + url.QueryEscape(token), nil, true}, |
| + {"the slide window of the presenter signed in", "/p/" + session, cookies, true}, |
| + {"a watcher", "/p/" + session, nil, false}, |
| + } { |
| + page := mustGet(t, a, c.path, http.StatusOK, c.cookies).Body.String() |
| + if got := presenterBundle.MatchString(page); got != c.bundle { |
| + t.Errorf("%s: loads the presenter bundle %v, want %v", c.name, got, c.bundle) |
| + } |
| + if got := presentScript.MatchString(page); got == c.bundle { |
| + t.Errorf("%s: loads present.js %v", c.name, got) |
| + } |
| + if !c.bundle { |
| + if strings.Contains(page, "data-talk=") || strings.Contains(page, `slides-op="next"`) { |
| + t.Errorf("%s: may not drive, and holds the talk or a Next button", c.name) |
| + } |
| + continue |
| + } |
| + for _, want := range []string{talk, `data-text-waiting="Waiting for the network"`, `slides-op="next"`, `<p slides-waiting role="status" hidden></p>`} { |
| + if !strings.Contains(page, want) { |
| + t.Errorf("%s: lacks %s", c.name, want) |
| + } |
| + } |
| + } |
| + |
| + share := mintShareLink(t, a, deck, cookies) |
| + if follow := mustGet(t, a, "/s/"+share+"?follow=1", http.StatusOK, nil).Body.String(); presenterBundle.MatchString(follow) { |
| + t.Error("the follow link loads the presenter bundle; it keeps present.js") |
| + } |
| + |
| + preDeploy(t, a, session) |
| + if old := mustGet(t, a, "/p/"+session+"?t="+url.QueryEscape(token), http.StatusOK, nil).Body.String(); presenterBundle.MatchString(old) { |
| + t.Error("a session begun before positions loads the presenter bundle; it keeps present.js") |
| + } |
| +} |
diff --git a/internal/slidestest/races_browser_test.go b/internal/slidestest/races_browser_test.go| index 1313cfa..fac1d85 100644 |
| --- a/internal/slidestest/races_browser_test.go |
| +++ b/internal/slidestest/races_browser_test.go |
| @@ -212,6 +212,11 @@ func TestANewSlideGoesUpAfterARetriedSave(t *testing.T) { |
| // arrived late (Astra's finding 2 on #27). Each case holds an answer back, |
| // lets the session move on through the stream, then releases it: nothing |
| // changes — not the slide, not the counter, not the blackout. |
| +// |
| +// This is static/present.js's ordering, which a session begun before |
| +// positions keeps (preDeploy). A session with a position moves its slide |
| +// window from memory instead, and its link orders presses and answers |
| +// (fixtures/talk-link.mjs, TestPresenterFastPressesNeverJumpBack). |
| func TestTheProjectorIgnoresAStaleAnswer(t *testing.T) { |
| three := strings.TrimSuffix(paperDeck, "]") + `,{"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},{"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]` |
| // holdJS holds the body of the next response whose URL matches. |
| @@ -263,6 +268,7 @@ func TestTheProjectorIgnoresAStaleAnswer(t *testing.T) { |
| fr := newFontRig(t) |
| sqid := fr.deck(t, "ordering", three) |
| session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies) |
| + preDeploy(t, fr.app, session) |
| path := "/p/" + session |
| if c.page == "token" { |
| path += "?t=" + token |
| @@ -302,11 +308,17 @@ func TestTheProjectorIgnoresAStaleAnswer(t *testing.T) { |
| // (Claude Fable on #27: the fallback was form.submit(), a second POST of |
| // "next"). The server applies the Next and the answer is lost; the page |
| // falls back to loading itself, and the session is on slide 2, not 3. |
| +// |
| +// static/present.js's fallback, on a session begun before positions |
| +// (preDeploy). A session with a position keeps moving with no answer at |
| +// all and tells the server where it went when it can |
| +// (TestADroppedNetworkKeepsThePressingWindowMoving). |
| func TestAFailedCommandAnswerIsNotSentAgain(t *testing.T) { |
| three := strings.TrimSuffix(paperDeck, "]") + `,{"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},{"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]` |
| fr := newFontRig(t) |
| sqid := fr.deck(t, "fallback", three) |
| session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies) |
| + preDeploy(t, fr.app, session) |
| // The stream is kept quiet, so the failed answer is still the newest |
| // thing this page has heard: with it, the stream's own event would |
| // move the page on and the fallback would never run. |