oficina / slides Public

Presenter: arrange the window, and pair a phone from its menu

Arrange this window (presenter-arrange.mjs) makes the three panels
movable on their 12x12 grid by pointer and by keyboard (arrows move a
focused panel a cell, Shift+arrows resize it), clamped inside the grid,
at least 2x2 and never overlapping. Done saves the cookie through the
notes' one writer, keeping the notes' part; Reset saves the default;
Esc leaves without saving. While arranging only PageUp and PageDown
press. The placing stylesheet says what presenter_window.go's says, so
the next first paint is the arrangement on screen. Below 720x560 the
panels stack and Arrange is not offered.

POST /p/{session}/pair, for the signed-in presenter only, replaces the
remote token and answers present_pair.html (code, address, QR, from the
partial the old presenter view now shares) with no-store; 404 for
anyone else, 410 for an ended talk. The test helpers pair through it,
and pairThroughRow is gone. slides.present.pair.body takes the approved
sentence.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 3dd8d43df74fcb0159c46b10278560d98be9ffec parent fc6da8d
22 files changed, +1,430 −100
  • fixtures/presenter-arrange.mjs +261 −0
  • fixtures/presenter-arrange.test.mjs +132 −0
  • fixtures/presenter-notes.mjs +9 −2
  • fixtures/presenter-window.mjs +17 −1
  • internal/slides/app.go +3 −0
  • internal/slides/credits/assets.json +1 −1
  • internal/slides/locales/en.toml +5 −2
  • internal/slides/presentation.go +99 −18
  • internal/slides/presenter_window.go +14 −4
  • internal/slides/render.go +4 −1
  • internal/slides/static/presenter.1e8d4e112c3a7a78.js +4 −0
  • internal/slides/static/presenter.c27ac07e6032f790.js +0 −2
  • internal/slides/static/presenter.css +94 −2
  • internal/slides/templates/present_notes.html +7 −31
  • internal/slides/templates/present_pair.html +16 −0
  • internal/slides/templates/present_pairing.html +38 −0
  • internal/slides/templates/presenter.html +9 −1
  • internal/slidestest/browser_present_test.go +11 −8
  • internal/slidestest/present_pair_test.go +168 −0
  • internal/slidestest/present_position_test.go +1 −1
  • internal/slidestest/present_test.go +27 −26
  • internal/slidestest/presenter_arrange_browser_test.go +510 −0
diff --git a/fixtures/presenter-arrange.mjs b/fixtures/presenter-arrange.mjs
new file mode 100644
index 0000000..17a6497
--- /dev/null
+++ b/fixtures/presenter-arrange.mjs
@@ -0,0 +1,261 @@
+// presenter-arrange.mjs — arranging the presenter window (spec §5.4,
+// mockup #parrange).
+//
+// The three panels (now, next, notes) sit on a 12×12 grid. Arrange this
+// window, in the ⋯ menu, outlines them: a panel dragged moves, its
+// corner dragged resizes it, and a focused panel moves a cell with an
+// arrow key and resizes with Shift and an arrow, so none of it needs a
+// pointer (WCAG 2.5.7). Every change snaps to the grid, stays inside
+// it, keeps each panel at least 2×2 and never lets two overlap
+// (clampPanels). Done saves the arrangement in the window's cookie
+// (presenter-notes.mjs writes it, notes and all); Reset puts the
+// default back and saves that; Esc leaves without saving.
+//
+// The panels are placed by a stylesheet that says what the server's
+// does (presenter_window.go's css), so the arrangement on screen while
+// arranging is the one the next first paint draws. Below 720×560 the
+// panels stack, the arrangement is ignored, and there is nothing to
+// arrange.
+//
+// No words here: the bar's are the page's. Tested in
+// presenter-arrange.test.mjs.
+import { DEFAULT_PANELS } from './presenter-notes.mjs'
+
+export { DEFAULT_PANELS }
+export const GRID = 12
+export const MIN_CELLS = 2
+const NAMES = ['now', 'next', 'notes']
+const WIDE = '(min-width: 720px) and (min-height: 560px)'
+
+function overlaps (a, b) {
+ return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
+}
+
+function inGrid (p) {
+ return p.x >= 0 && p.y >= 0 && p.w >= MIN_CELLS && p.h >= MIN_CELLS && p.x + p.w <= GRID && p.y + p.h <= GRID
+}
+
+/** "x,y,w,h;x,y,w,h;x,y,w,h" read as three panels, or null for anything
+ * the server would not believe either (off the grid, under 2×2,
+ * overlapping). */
+export function parsePanels (raw) {
+ const rects = String(raw ?? '').split(';')
+ if (rects.length !== NAMES.length) return null
+ const out = []
+ for (const rect of rects) {
+ const n = rect.split(',')
+ if (n.length !== 4 || !n.every(v => /^[0-9]{1,2}$/.test(v))) return null
+ const [x, y, w, h] = n.map(Number)
+ const p = { x, y, w, h }
+ if (!inGrid(p)) return null
+ out.push(p)
+ }
+ for (let i = 0; i < out.length; i++) {
+ for (let j = i + 1; j < out.length; j++) if (overlaps(out[i], out[j])) return null
+ }
+ return out
+}
+
+/** The panels as the cookie keeps them. */
+export function formatPanels (panels) {
+ return panels.map(p => [p.x, p.y, p.w, p.h].join(',')).join(';')
+}
+
+function cells (n) {
+ const v = Math.round(Number(n) || 0)
+ return Math.max(-GRID, Math.min(GRID, v))
+}
+
+// walk moves panels[i] a cell at a time along each [key, delta] in
+// turn, each stopping at the first cell that would leave the grid,
+// shrink it under 2×2 or overlap another panel.
+function walk (panels, i, steps) {
+ const out = panels.map(p => ({ ...p }))
+ for (const [key, delta] of steps) {
+ const dir = Math.sign(delta)
+ for (let k = 0; k < Math.abs(delta); k++) {
+ const next = { ...out[i], [key]: out[i][key] + dir }
+ if (!inGrid(next) || out.some((q, j) => j !== i && overlaps(next, q))) break
+ out[i] = next
+ }
+ }
+ return out
+}
+
+/**
+ * panels with panels[moved] changed by change, {dx, dy} to move it or
+ * {dw, dh} to resize it from its far corner, in grid cells. A change is
+ * taken as far as it can go and no further: the result is always on
+ * the grid, inside it, at least 2×2 and free of overlaps. Of the two
+ * ways to take a change (across then down, or down then across), the
+ * one that ends nearer what was asked for. Pure: panels is not changed.
+ */
+export function clampPanels (panels, moved, change = {}) {
+ if (!panels[moved]) return panels.map(p => ({ ...p }))
+ const [a, b] = [['x', cells(change.dx)], ['y', cells(change.dy)]]
+ const [c, d] = [['w', cells(change.dw)], ['h', cells(change.dh)]]
+ const want = { ...panels[moved] }
+ for (const [key, delta] of [a, b, c, d]) want[key] += delta
+ const miss = out => ['x', 'y', 'w', 'h'].reduce((sum, k) => sum + Math.abs(out[moved][k] - want[k]), 0)
+ const first = walk(panels, moved, [a, b, c, d])
+ const second = walk(panels, moved, [b, a, d, c])
+ return miss(second) < miss(first) ? second : first
+}
+
+/** What an arrow key does to the focused panel: moves it a cell, or
+ * with Shift resizes it a cell; null for any other key. */
+export function keyChange (key, shift) {
+ const along = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }[key]
+ if (!along) return null
+ const [x, y] = along
+ if (shift) return x ? { dw: x } : { dh: y }
+ return x ? { dx: x } : { dy: y }
+}
+
+/** The stylesheet that places panels: presenter_window.go's css, less
+ * the notes' size, which the notes keep themselves. The default window
+ * leaves Next room for half of Now and draws it at half; an arranged
+ * one lets Next fill its own panel. */
+export function arrangeCSS (panels) {
+ const lines = [`@media ${WIDE} {`]
+ panels.forEach((p, i) => {
+ lines.push(` [presenter-panel="${NAMES[i]}"] { grid-area: ${p.y + 1} / ${p.x + 1} / span ${p.h} / span ${p.w}; }`)
+ })
+ const [now, next] = panels
+ let room = `${now.w} / ${GRID} * 100cqw - 32px, (${now.h} / ${GRID} * 100cqh - 16px) * 16 / 9`
+ const plain = formatPanels(panels) === DEFAULT_PANELS
+ if (plain) room += `, (${next.h} / ${GRID} * 100cqh - 50px) * 2 * 16 / 9`
+ lines.push(` [presenter-panel] { --p-now: min(${room}); }`)
+ lines.push(` [presenter-panel="next"] [presenter-frame] { inline-size: min(100cqw, 100cqh * 16 / 9${plain ? ', var(--p-now) / 2' : ''}); }`)
+ lines.push('}')
+ return lines.join('\n') + '\n'
+}
+
+/**
+ * Arranging, in the window root. panels is the arrangement the page was
+ * drawn with (the cookie's, or the default); save(panels) keeps one.
+ * Returns start (the menu's Arrange), isOn, and key, the keydown
+ * handler while arranging: the window gives it every key but the
+ * clicker's.
+ */
+export function mountArrange ({ root, panels: initial, save }) {
+ const doc = root.ownerDocument
+ const win = doc.defaultView
+ const bar = root.querySelector('[presenter-arrange-bar]')
+ const box = root.querySelector('[presenter-panels]')
+ const els = NAMES.map(n => root.querySelector(`[presenter-panel="${n}"]`))
+ const wide = win.matchMedia(WIDE)
+ let panels = parsePanels(initial) || parsePanels(DEFAULT_PANELS)
+ let saved = panels // what Esc goes back to
+ let on = false
+ let style = null
+ let drag = null
+
+ // A right-to-left window's grid runs the other way across.
+ const across = () => (win.getComputedStyle(root).direction === 'rtl' ? -1 : 1)
+
+ function set (next) {
+ panels = next
+ if (!style) {
+ style = doc.createElement('style')
+ style.setAttribute('presenter-arranged', '')
+ doc.head.append(style)
+ }
+ style.textContent = arrangeCSS(panels)
+ }
+
+ function leave () {
+ on = false
+ drag = null
+ root.removeAttribute('data-arranging')
+ bar.hidden = true
+ for (const el of els) {
+ el.removeAttribute('tabindex')
+ el.querySelector(':scope > [presenter-arrange-handle]')?.remove()
+ }
+ root.querySelector('[presenter-more]')?.focus()
+ }
+
+ function start () {
+ if (on || !bar || !box || els.some(el => !el) || !wide.matches) return
+ on = true
+ saved = panels
+ root.setAttribute('data-arranging', '')
+ bar.hidden = false
+ for (const el of els) {
+ el.tabIndex = 0
+ const handle = doc.createElement('span')
+ handle.setAttribute('presenter-arrange-handle', '')
+ handle.setAttribute('aria-hidden', 'true')
+ el.append(handle)
+ }
+ els[0].focus()
+ }
+
+ function cancel () {
+ set(saved)
+ leave()
+ }
+
+ bar?.querySelector('[presenter-arrange-done]')?.addEventListener('click', () => {
+ save(formatPanels(panels))
+ saved = panels
+ leave()
+ })
+ bar?.querySelector('[presenter-arrange-reset]')?.addEventListener('click', () => {
+ set(parsePanels(DEFAULT_PANELS))
+ save(DEFAULT_PANELS)
+ saved = panels
+ })
+ // Narrowed below the grid while arranging: the panels stack, and
+ // there is nothing left to arrange.
+ wide.addEventListener?.('change', () => { if (on && !wide.matches) cancel() })
+
+ els.forEach((el, i) => {
+ if (!el) return
+ el.addEventListener('pointerdown', e => {
+ if (!on || e.button !== 0) return
+ e.preventDefault()
+ el.focus({ preventScroll: true })
+ el.setPointerCapture?.(e.pointerId)
+ const r = box.getBoundingClientRect()
+ drag = {
+ i,
+ id: e.pointerId,
+ resize: !!e.target.closest?.('[presenter-arrange-handle]'),
+ x: e.clientX,
+ y: e.clientY,
+ w: r.width / GRID,
+ h: r.height / GRID,
+ from: panels
+ }
+ })
+ el.addEventListener('pointermove', e => {
+ if (!drag || drag.i !== i || drag.id !== e.pointerId) return
+ const dx = Math.round(across() * (e.clientX - drag.x) / drag.w)
+ const dy = Math.round((e.clientY - drag.y) / drag.h)
+ set(clampPanels(drag.from, i, drag.resize ? { dw: dx, dh: dy } : { dx, dy }))
+ })
+ const end = e => { if (drag && drag.id === e.pointerId) drag = null }
+ el.addEventListener('pointerup', end)
+ el.addEventListener('pointercancel', end)
+ })
+
+ function key (e) {
+ if (e.metaKey || e.ctrlKey || e.altKey) return
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ cancel()
+ return
+ }
+ const i = els.indexOf(doc.activeElement)
+ const change = i >= 0 && keyChange(e.key, e.shiftKey)
+ if (!change) return
+ e.preventDefault()
+ if (change.dx) change.dx *= across()
+ if (change.dw) change.dw *= across()
+ set(clampPanels(panels, i, change))
+ }
+
+ return { start, key, isOn: () => on }
+}
diff --git a/fixtures/presenter-arrange.test.mjs b/fixtures/presenter-arrange.test.mjs
new file mode 100644
index 0000000..8627efd
--- /dev/null
+++ b/fixtures/presenter-arrange.test.mjs
@@ -0,0 +1,132 @@
+// presenter-arrange.mjs: the panels on their 12×12 grid, as a person
+// moves and resizes them, the keys that do it, and the stylesheet that
+// places them (the server's own, presenter_window.go's css).
+import test from 'node:test'
+import assert from 'node:assert/strict'
+import { clampPanels, parsePanels, formatPanels, keyChange, arrangeCSS, DEFAULT_PANELS } from './presenter-arrange.mjs'
+
+const defaults = parsePanels(DEFAULT_PANELS)
+// Room to move: Now 4×4 at the top left, Next 4×4 below it, the notes
+// 4×12 on the right, and the middle of the grid empty.
+const roomy = parsePanels('0,0,4,4;0,4,4,4;8,0,4,12')
+
+function valid (panels) {
+ for (const p of panels) {
+ assert.ok(p.w >= 2 && p.h >= 2, 'at least 2×2: ' + JSON.stringify(p))
+ assert.ok(p.x >= 0 && p.y >= 0 && p.x + p.w <= 12 && p.y + p.h <= 12, 'inside the grid: ' + JSON.stringify(p))
+ }
+ for (let i = 0; i < panels.length; i++) {
+ for (let j = i + 1; j < panels.length; j++) {
+ const a = panels[i]
+ const b = panels[j]
+ assert.ok(!(a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h),
+ 'no overlap: ' + JSON.stringify([a, b]))
+ }
+ }
+}
+
+test('the cookie\'s panels read and write back the same', () => {
+ assert.deepEqual(defaults, [{ x: 0, y: 0, w: 7, h: 8 }, { x: 0, y: 8, w: 7, h: 4 }, { x: 7, y: 0, w: 5, h: 12 }])
+ assert.equal(formatPanels(defaults), DEFAULT_PANELS)
+ assert.equal(DEFAULT_PANELS, '0,0,7,8;0,8,7,4;7,0,5,12')
+ for (const bad of ['', 'x', '0,0,7,8;0,8,7,4', '0,0,7,8;0,8,7,4;7,0,5,13', '0,0,1,8;0,8,7,4;7,0,5,12',
+ '0,0,7,8;0,7,7,4;7,0,5,12', '0,0,7,8;0,8,7,4;7,0,5,12;1,1,2,2', '-1,0,7,8;0,8,7,4;7,0,5,12', '0,0,7.5,8;0,8,7,4;7,0,5,12']) {
+ assert.equal(parsePanels(bad), null, bad)
+ }
+})
+
+test('a panel moves by whole cells into free room', () => {
+ const out = clampPanels(roomy, 0, { dx: 4, dy: 1 })
+ assert.deepEqual(out[0], { x: 4, y: 1, w: 4, h: 4 })
+ assert.deepEqual(out[1], roomy[1])
+ assert.deepEqual(out[2], roomy[2])
+ valid(out)
+ assert.deepEqual(roomy[0], { x: 0, y: 0, w: 4, h: 4 }, 'the panels given are not changed')
+})
+
+test('a move stops at the edge of the grid', () => {
+ const out = clampPanels(roomy, 0, { dx: -5, dy: -3 })
+ assert.deepEqual(out[0], { x: 0, y: 0, w: 4, h: 4 })
+ const down = clampPanels(parsePanels('0,0,4,4;4,8,4,4;8,0,4,4'), 0, { dy: 40 })
+ assert.deepEqual(down[0], { x: 0, y: 8, w: 4, h: 4 })
+ valid(down)
+})
+
+test('a move goes round a panel in its way when it can', () => {
+ // Down then across is blocked by Next; across then down is not.
+ assert.deepEqual(clampPanels(roomy, 0, { dx: 4, dy: 2 })[0], { x: 4, y: 2, w: 4, h: 4 })
+ // Across then down is blocked by the notes; down then across is not.
+ const tall = parsePanels('0,0,4,4;4,0,4,4;8,0,4,4')
+ assert.deepEqual(clampPanels(tall, 1, { dx: 4, dy: 4 })[1], { x: 8, y: 4, w: 4, h: 4 })
+})
+
+test('a move stops at the panel in its way, never over it', () => {
+ // Now moving right runs into the notes at column 8.
+ const out = clampPanels(roomy, 0, { dx: 7 })
+ assert.deepEqual(out[0], { x: 4, y: 0, w: 4, h: 4 })
+ valid(out)
+ // Next moving up runs into Now.
+ const up = clampPanels(roomy, 1, { dy: -3 })
+ assert.deepEqual(up[1], roomy[1])
+ // The default window is full: nothing moves until something shrinks.
+ for (let i = 0; i < 3; i++) {
+ for (const change of [{ dx: 1 }, { dx: -1 }, { dy: 1 }, { dy: -1 }]) {
+ const moved = clampPanels(defaults, i, change)
+ assert.deepEqual(moved, defaults, `panel ${i} ${JSON.stringify(change)}`)
+ }
+ }
+})
+
+test('a resize keeps at least 2×2, inside the grid, clear of the others', () => {
+ assert.deepEqual(clampPanels(roomy, 0, { dw: -9, dh: -9 })[0], { x: 0, y: 0, w: 2, h: 2 })
+ assert.deepEqual(clampPanels(roomy, 2, { dw: 5 })[2], { x: 8, y: 0, w: 4, h: 12 })
+ // Now grows right to the notes and down to Next, no further.
+ const grown = clampPanels(roomy, 0, { dw: 9, dh: 9 })
+ assert.deepEqual(grown[0], { x: 0, y: 0, w: 8, h: 4 })
+ valid(grown)
+ const shrunk = clampPanels(defaults, 0, { dw: -2, dh: -3 })
+ assert.deepEqual(shrunk[0], { x: 0, y: 0, w: 5, h: 5 })
+ valid(shrunk)
+})
+
+test('every change from every arrangement stays a valid window', () => {
+ const starts = [defaults, roomy, parsePanels('5,5,2,2;0,0,2,2;10,10,2,2')]
+ const changes = []
+ for (const d of [-13, -3, -1, 0, 1, 2, 13]) {
+ changes.push({ dx: d }, { dy: d }, { dw: d }, { dh: d }, { dx: d, dy: -d }, { dw: d, dh: d })
+ }
+ for (const start of starts) {
+ for (let i = 0; i < 3; i++) {
+ for (const change of changes) valid(clampPanels(start, i, change))
+ }
+ }
+})
+
+test('arrow keys move a panel a cell; with Shift they resize it', () => {
+ assert.deepEqual(keyChange('ArrowLeft', false), { dx: -1 })
+ assert.deepEqual(keyChange('ArrowRight', false), { dx: 1 })
+ assert.deepEqual(keyChange('ArrowUp', false), { dy: -1 })
+ assert.deepEqual(keyChange('ArrowDown', false), { dy: 1 })
+ assert.deepEqual(keyChange('ArrowLeft', true), { dw: -1 })
+ assert.deepEqual(keyChange('ArrowRight', true), { dw: 1 })
+ assert.deepEqual(keyChange('ArrowUp', true), { dh: -1 })
+ assert.deepEqual(keyChange('ArrowDown', true), { dh: 1 })
+ assert.equal(keyChange('PageDown', false), null)
+ assert.equal(keyChange('b', false), null)
+})
+
+test('the stylesheet places the panels as the server does', () => {
+ const css = arrangeCSS(roomy)
+ assert.match(css, /^@media \(min-width: 720px\) and \(min-height: 560px\) \{/)
+ assert.ok(css.includes('[presenter-panel="now"] { grid-area: 1 / 1 / span 4 / span 4; }'))
+ assert.ok(css.includes('[presenter-panel="next"] { grid-area: 5 / 1 / span 4 / span 4; }'))
+ assert.ok(css.includes('[presenter-panel="notes"] { grid-area: 1 / 9 / span 12 / span 4; }'))
+ assert.ok(css.includes('[presenter-panel] { --p-now: min(4 / 12 * 100cqw - 32px, (4 / 12 * 100cqh - 16px) * 16 / 9); }'))
+ // Arranged, Next fills its own panel.
+ assert.ok(css.includes('[presenter-panel="next"] [presenter-frame] { inline-size: min(100cqw, 100cqh * 16 / 9); }'))
+
+ // The default leaves Next room for half of Now, and Next is half.
+ const def = arrangeCSS(defaults)
+ assert.ok(def.includes('[presenter-panel] { --p-now: min(7 / 12 * 100cqw - 32px, (8 / 12 * 100cqh - 16px) * 16 / 9, (4 / 12 * 100cqh - 50px) * 2 * 16 / 9); }'))
+ assert.ok(def.includes('[presenter-panel="next"] [presenter-frame] { inline-size: min(100cqw, 100cqh * 16 / 9, var(--p-now) / 2); }'))
+})
diff --git a/fixtures/presenter-notes.mjs b/fixtures/presenter-notes.mjs
index 5c93574..4ccbeb1 100644
--- a/fixtures/presenter-notes.mjs
+++ b/fixtures/presenter-notes.mjs
@@ -8,7 +8,8 @@
// view, and fades at the edge that has more. Scroll uses the chosen
// size. Smaller and larger move the size 2px between 16 and 48 and
// leave the mode alone. Every change is saved (the cookie
-// slides-presenter, read by the server, so the first paint matches).
+// slides-presenter, read by the server, so the first paint matches),
+// and so is the window's arrangement, through setPanels.
//
// The words come from the page (data-text-nonotes); nothing here is
// English. Tested in presenter-notes.test.mjs.
@@ -182,5 +183,11 @@ export function mountNotes ({ root, prefs, savePrefs = writePrefs }) {
// The server drew the first paint; this sizes and places it.
layout()
- return { show }
+ // Arranging saves the panels through here (presenter-arrange.mjs), so
+ // the cookie has one writer and keeps the notes' part.
+ function setPanels (panels) {
+ change({ panels })
+ }
+
+ return { show, setPanels }
}
diff --git a/fixtures/presenter-window.mjs b/fixtures/presenter-window.mjs
index 95ff792..625c262 100644
--- a/fixtures/presenter-window.mjs
+++ b/fixtures/presenter-window.mjs
@@ -16,6 +16,7 @@ import { createDriver, bindForms } from './talk-driver.mjs'
import { createKeys } from './presenter-keys.mjs'
import { mountPicker } from './presenter-picker.mjs'
import { mountNotes, readPrefs, DEFAULT_SIZE, DEFAULT_PANELS } from './presenter-notes.mjs'
+import { mountArrange } from './presenter-arrange.mjs'
import { install, reveal, fill, talkPlace, indexOf, restart, createPreview } from './talk-draw.mjs'
const MOVING = new Set(['next', 'back', 'first', 'last', 'goto'])
@@ -198,6 +199,11 @@ export function mountPresenterWindow (root) {
}
const menu = $('[presenter-more-menu]')
+ // Pairing opens in a window of its own (target slides-pair), so this
+ // one keeps its talk; the menu closes behind it.
+ root.addEventListener('submit', e => {
+ if (menu && e.target.getAttribute('target') === 'slides-pair') menu.open = false
+ })
bindForms(root, T.command, {
move: m => driver.move(m),
timerReset: resetTimer,
@@ -231,7 +237,17 @@ export function mountPresenterWindow (root) {
// P opens the presenter window, which this is.
}
})
- document.addEventListener('keydown', onKey)
+ // Arranging the panels (presenter-arrange.mjs), from the menu. While
+ // it is on, the clicker's keys still press; every other key is its.
+ const arrange = mountArrange({ root, panels: saved.panels || DEFAULT_PANELS, save: notes.setPanels })
+ $('[presenter-arrange]')?.addEventListener('click', () => {
+ if (menu) menu.open = false
+ arrange.start()
+ })
+ document.addEventListener('keydown', e => {
+ if (arrange.isOn() && e.key !== 'PageUp' && e.key !== 'PageDown') arrange.key(e)
+ else onKey(e)
+ })
tick(elapsed, $('[data-clock]'))
}
diff --git a/internal/slides/app.go b/internal/slides/app.go
index 1b1038e..c501337 100644
--- a/internal/slides/app.go
+++ b/internal/slides/app.go
@@ -157,6 +157,9 @@ func New(d *db.DB, cfg Config) (*http.ServeMux, *app, error) {
r.Get("/p/{session}/assets/{ref}", a.presentAsset)
r.Get("/p/{session}/slides/{file}", a.presentSlideThumb)
r.Post("/p/{session}/command", a.presentCommand)
+ // Pairing a phone from the presenter window's menu: the signed-in
+ // presenter only, so it is a capability screen by its cookie.
+ r.Post("/p/{session}/pair", a.presentPair)
// The phone's way in: a scanned QR carries the code and the key,
// a typed code gets a form asking for the key.
r.Get("/r/{code}", a.remotePair)
diff --git a/internal/slides/credits/assets.json b/internal/slides/credits/assets.json
index 736e742..926b1ad 100644
--- a/internal/slides/credits/assets.json
+++ b/internal/slides/credits/assets.json
@@ -69,7 +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.c27ac07e6032f790.js": "c27ac07e6032f79097a5d7a710135dfa58d871f8bd8e2810ecacf2ea5760a047",
+ "internal/slides/static/presenter.1e8d4e112c3a7a78.js": "1e8d4e112c3a7a788fa2b3105d1dde1251f515da241bf28e8ecf8a916d207916",
"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 e330601..cb119a3 100644
--- a/internal/slides/locales/en.toml
+++ b/internal/slides/locales/en.toml
@@ -695,6 +695,9 @@ slides.present.menu.core = "Switch to the short version"
slides.present.menu.arrange = "Arrange this window…"
slides.present.menu.back = "Back to the deck"
slides.present.menu.end = "End presenting"
+slides.present.arrange.hint = "Drag a panel to move it; drag its corner to resize it."
+slides.present.arrange.reset = "Reset to the default"
+slides.present.arrange.done = "Done"
slides.present.next.step = "Next step"
slides.present.next.slide = "Next slide"
slides.present.next.end = "End of the talk"
@@ -724,9 +727,9 @@ slides.present.over.body = "The talk it was showing has ended. Ask whoever prese
# Pairing a phone. Shown once, at the moment of pairing, because only
# a fingerprint of the key is stored — the share link's bargain, and
-# the reason the body says what pressing Present again does.
+# the reason the body says what pairing again from the menu does.
slides.present.pair.title = "Use your phone as the remote"
-slides.present.pair.body = "Scan this, or open the address and type the code and key. It is shown once: press Present again to pair a different phone, which retires this one."
+slides.present.pair.body = "Scan this, or open the address and type the code and key. It is shown once. Pairing another phone from the menu retires this one."
slides.present.pair.code = "Pairing code"
slides.present.pair.url = "Remote address"
slides.present.pair.qr = "QR code for the remote, pairing code {code}"
diff --git a/internal/slides/presentation.go b/internal/slides/presentation.go
index 49b0053..a4f03a1 100644
--- a/internal/slides/presentation.go
+++ b/internal/slides/presentation.go
@@ -573,14 +573,7 @@ type presenterPage struct {
// The pairing block, rendered once: only for the presenter's own
// session, and only on the one request that carries the token.
- Pair bool
- PairTitle string
- PairBody string
- CodeLabel string
- Code string
- URLLabel string
- RemoteURL string
- QR template.HTML
+ Pair *pairing
Controls *controls
StageHref string
StageLabel string
@@ -942,24 +935,112 @@ func (a *app) presenterNotes(w http.ResponseWriter, r *http.Request) {
// Coming back to the page without it — from a bookmark, from the
// browser's history — shows the talk and no capability.
if holder && presenter {
- remoteURL := a.cfg.Origin + "/r/" + p.Code + "?t=" + token
- qr, err := qrSVG(remoteURL, rastrillo.Tf(r, "slides.present.pair.qr", "code", p.Code))
+ pair, err := a.pairingFor(r, p, token)
if err != nil {
a.fail(w, r, "render the pairing QR", err)
return
}
- page.Pair = true
- page.PairTitle = rastrillo.T(r, "slides.present.pair.title")
- page.PairBody = rastrillo.T(r, "slides.present.pair.body")
- page.CodeLabel = rastrillo.T(r, "slides.present.pair.code")
- page.Code = p.Code
- page.URLLabel = rastrillo.T(r, "slides.present.pair.url")
- page.RemoteURL = remoteURL
- page.QR = qr
+ page.Pair = &pair
}
render(w, "present_notes", page)
}
+// pairing is what pairs a phone: the code, the remote's address with
+// the token in it, and the QR that carries both
+// (templates/present_pairing.html).
+type pairing struct {
+ Title string
+ Body string
+ CodeLabel string
+ Code string
+ URLLabel string
+ RemoteURL string
+ QR template.HTML
+}
+
+// pairingFor is p's pairing with token, in the request's language.
+func (a *app) pairingFor(r *http.Request, p Presentation, token string) (pairing, error) {
+ remoteURL := a.cfg.Origin + "/r/" + p.Code + "?t=" + token
+ qr, err := qrSVG(remoteURL, rastrillo.Tf(r, "slides.present.pair.qr", "code", p.Code))
+ if err != nil {
+ return pairing{}, err
+ }
+ return pairing{
+ Title: rastrillo.T(r, "slides.present.pair.title"),
+ Body: rastrillo.T(r, "slides.present.pair.body"),
+ CodeLabel: rastrillo.T(r, "slides.present.pair.code"),
+ Code: p.Code,
+ URLLabel: rastrillo.T(r, "slides.present.pair.url"),
+ RemoteURL: remoteURL,
+ QR: qr,
+ }, nil
+}
+
+// --- POST /p/{session}/pair ---
+
+// presentPairPage is the pairing page the window's menu opens.
+type presentPairPage struct {
+ shell
+ Title string
+ Body string
+ Pair pairing
+}
+
+// presentPair pairs a phone (spec §6 "Who may drive"): a new remote
+// token replaces the old one, which drives and reads nothing from then
+// on, and the answer shows the new one, once.
+//
+// Only the presenter, signed in, may pair: never the token, which is
+// the phone's and would otherwise let a phone pass itself on, and never
+// the session sqid, which is on the projector. Anybody else gets the
+// 404 every capability screen gives; a talk that is over is a 410.
+// csrf.Protect (app.go) keeps another site from pairing through the
+// presenter's browser, and no-store keeps the token out of every cache.
+func (a *app) presentPair(w http.ResponseWriter, r *http.Request) {
+ p, ok := a.presentationFor(w, r)
+ if !ok {
+ return
+ }
+ if p.Actor == "" || a.presenterActor(r) != p.Actor {
+ a.notFound(w, r)
+ return
+ }
+ token, err := newRemoteToken()
+ if err != nil {
+ a.fail(w, r, "mint a remote token", err)
+ return
+ }
+ // ended_at in the WHERE, as every write here has: pairing that
+ // races End presenting loses rather than arming a finished talk.
+ res := a.db.G.WithContext(r.Context()).Model(&Presentation{}).
+ Where("id = ? AND ended_at IS NULL", p.ID).
+ Update("remote_token_hash", hashRemoteToken(token))
+ switch {
+ case res.Error != nil:
+ a.fail(w, r, "pair a phone", res.Error)
+ return
+ case res.RowsAffected == 0:
+ a.gone(w, r)
+ return
+ }
+ pair, err := a.pairingFor(r, p, token)
+ if err != nil {
+ a.fail(w, r, "render the pairing QR", err)
+ return
+ }
+ d, ok := a.deckOf(w, r, p)
+ if !ok {
+ return
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ render(w, "present_pair", presentPairPage{
+ shell: presentShellFor(r, pair.Title, d.Title),
+ Title: pair.Title,
+ Body: pair.Body,
+ Pair: pair,
+ })
+}
+
// clockWords is a wall clock a presenter can read at a glance. UTC and
// said so: the server has no idea what time zone the room is in, and a
// clock that is quietly an hour out is worse than one that names its
diff --git a/internal/slides/presenter_window.go b/internal/slides/presenter_window.go
index 27b2848..08a7777 100644
--- a/internal/slides/presenter_window.go
+++ b/internal/slides/presenter_window.go
@@ -34,7 +34,8 @@ import (
// presenterPrefsCookie holds how a person likes the window: the notes
// fitted or scrolling, their text size, and where the three panels sit.
-// It is read here; the window's script writes it (Tasks 11 and 13), as
+// It is read here; the window's script writes it (presenter-notes.mjs's
+// writePrefs, for the notes and for arranging), as
// "fit.24.0,0,7,8;0,8,7,4;7,0,5,12" percent-encoded, because a cookie
// value cannot hold a ";". Path /p, a year, SameSite=Lax.
const presenterPrefsCookie = "slides-presenter"
@@ -247,6 +248,10 @@ type presenterWindowPage struct {
MoreLabel string
Menu presenterMenu
+ // The bar arranging shows (fixtures/presenter-arrange.mjs): what to
+ // do, and its two buttons.
+ ArrangeHint, ArrangeReset, ArrangeDone string
+
Now template.HTML
NextLabel string
Next template.HTML
@@ -305,9 +310,10 @@ func presenterWordsFor(r *http.Request) presenterWords {
}
}
-// 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.
+// presenterMenu is the ⋯ menu's six rows (§5.6). Pair posts to
+// /p/{session}/pair (presentation.go's presentPair) into a window of its
+// own, so this one keeps its talk; Arrange is a button that needs the
+// window's script.
type presenterMenu struct {
PairAction string
PairLabel string
@@ -406,6 +412,10 @@ func (a *app) presenterWindow(w http.ResponseWriter, r *http.Request, p Presenta
Clock: clockWords(now),
ClockLabel: rastrillo.T(r, "slides.present.clock"),
MoreLabel: rastrillo.T(r, "slides.present.more"),
+
+ ArrangeHint: rastrillo.T(r, "slides.present.arrange.hint"),
+ ArrangeReset: rastrillo.T(r, "slides.present.arrange.reset"),
+ ArrangeDone: rastrillo.T(r, "slides.present.arrange.done"),
Menu: presenterMenu{
PairAction: "/p/" + p.Sqid + "/pair",
PairLabel: rastrillo.T(r, "slides.present.menu.pair"),
diff --git a/internal/slides/render.go b/internal/slides/render.go
index cafad90..e18f12e 100644
--- a/internal/slides/render.go
+++ b/internal/slides/render.go
@@ -122,7 +122,10 @@ var pageFiles = map[string][]string{
// and the presenter view cannot drift on what a button is called or
// where it posts.
"present": {"templates/present_controls.html"},
- "present_notes": {"templates/present_controls.html"},
+ "present_notes": {"templates/present_controls.html", "templates/present_pairing.html"},
+ // Pairing a phone, from the presenter window's menu; its QR and
+ // code are the old presenter view's (present_pairing.html).
+ "present_pair": {"templates/present_pairing.html"},
// The presenter window and its scriptless picker (presenter_window.go).
"presenter": nil,
"presenter_pick": nil,
diff --git a/internal/slides/static/presenter.1e8d4e112c3a7a78.js b/internal/slides/static/presenter.1e8d4e112c3a7a78.js
new file mode 100644
index 0000000..fe44020
--- /dev/null
+++ b/internal/slides/static/presenter.1e8d4e112c3a7a78.js
@@ -0,0 +1,4 @@
+var be=/^[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]*$/,xe=e=>(Array.isArray(e)?e:[]).map(t=>t&&typeof t.t=="string"?t.t:"").join("");function ye(e){let t=[];return(Array.isArray(e)?e:[]).forEach((n,r)=>{be.test(xe(n))||t.push(r)}),t}var ie=e=>typeof e.step=="number"&&e.step>0?e.step:0;function oe(e){let t=e.props&&e.props.children;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ge(e){let t=new Map;for(let r of e)t.set(r.id,r);let n=new Map;for(let r of e)if(r.type==="columns")for(let s of oe(r))t.has(s)&&s!==r.id&&!n.has(s)&&n.set(s,r.id);return{byID:t,parent:n}}function Ye(e,t){let n=ie(t),r=new Set([t.id]);for(let s=e.parent.get(t.id);s!==void 0&&!r.has(s);s=e.parent.get(s))r.add(s),n=Math.max(n,ie(e.byID.get(s)));return n}function ae(e,t,n){switch(t.type){case"list":return ye(t.text).length>0;case"heading":case"text":case"quote":return!be.test((Array.isArray(t.text)?t.text:[]).map(xe).join(`
+`));case"columns":n.add(t.id);for(let r of oe(t)){let s=e.byID.get(r);if(s&&!n.has(r)&&ae(e,s,n))return!0}return!1}return!0}function we(e,t,n){let r=Ye(e,t);if(t.type!=="columns")return r;n.add(t.id);let s=1/0;for(let l of oe(t)){let a=e.byID.get(l);!a||n.has(l)||!ae(e,a,new Set)||(s=Math.min(s,we(e,a,n)))}return s>r&&s!==1/0?s:r}function ke(e){let t=Array.isArray(e&&e.blocks)?e.blocks:[],n=Ge(t),r=[],s=[];for(let a of t){if(ie(a)===0||!ae(n,a,new Set))continue;let u={id:a.id,value:we(n,a,new Set),items:null};a.type==="list"&&a.items==="each"&&(u.items=ye(a.text)),r.push(u),s.includes(u.value)||s.push(u.value)}s.sort((a,u)=>a-u);let l=[];for(let a of s){let u=1;for(let f of r)f.value===a&&f.items&&f.items.length>u&&(u=f.items.length);for(let f=0;f<u;f++){let o=[];for(let p of r)p.value===a&&(p.items?f<p.items.length&&o.push({block:p.id,item:p.items[f]}):f===0&&o.push({block:p.id,item:-1}));l.push(o)}}return l}var G=e=>Array.isArray(e&&e.slides)?e.slides:[],ce=(e,t)=>e.findIndex(n=>n.id===t),le=e=>ke(e).length,B=(e,t,n=0)=>({slide:e.id,step:n,mode:t,black:!1}),ue=e=>({slide:"",step:0,mode:e,black:!1}),Se=(e,t)=>Math.min(Math.max(e,0),t);function F(e,t){let n=[];return G(e).forEach((r,s)=>{r.talk==="parked"||r.talk==="full"&&t!=="full"||n.push(s)}),n}function Y(e,t,n){let r=G(e),s=F(e,t.mode);switch(n.op){case"black":return{...t,black:!t.black};case"mode":return{...t,mode:t.mode==="full"?"core":"full"};case"goto":{let l=n.slide?ce(r,n.slide):-1;return l<0||r[l].talk==="parked"?t:B(r[l],r[l].talk==="full"?"full":t.mode)}case"first":case"last":return s.length?B(r[n.op==="first"?s[0]:s[s.length-1]],t.mode):ue(t.mode);case"next":case"back":return Je(e,t,n.op==="next",s)}return t}function Je(e,t,n,r){let s=G(e);if(!r.length)return ue(t.mode);let l=ce(s,t.slide);if(l<0)return{...de(e,t),black:!1};let a=le(s[l]),u=Se(t.step,a);if(n&&u<a)return{...t,step:u+1,black:!1};if(!n&&u>0)return{...t,step:u-1,black:!1};if(n){let f=r.find(o=>o>l);if(f!==void 0)return B(s[f],t.mode)}else{let f=r.findLast(o=>o<l);if(f!==void 0)return B(s[f],t.mode,le(s[f]))}return{...t,step:u,black:!1}}function de(e,t){return J(e,t,-1)}function J(e,t,n){let r=G(e),s=F(e,t.mode);if(!s.length)return ue(t.mode);let l=f=>({...B(r[f],t.mode),black:t.black}),a=s[s.length-1];if(t.slide==="")return l(s[0]);let u=ce(r,t.slide);if(u<0&&n>=0){let f=F(e,"full").slice(n).find(o=>s.includes(o));return l(f??a)}return u<0?l(a):r[u].talk==="parked"?l(s.find(f=>f>u)??a):{...t,step:Se(t.step,le(r[u]))}}var Qe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function et(){let e=new Uint8Array(22);globalThis.crypto.getRandomValues(e);let t="";for(let n of e)t+=Qe[n&63];return t}var tt={back:"prev",black:"blackout"};function nt(e){let t={op:tt[e.op]||e.op};return e.slide&&(t.slide=String(e.slide)),t}function fe(e,t){return!e||!t?e!==t:e.slide!==t.slide||(e.step||0)!==(t.step||0)||e.mode!==t.mode||!!e.black!=!!t.black}var rt=(e,t)=>{let n=setTimeout(t,e);return()=>clearTimeout(n)};function Ae({post:e,stream:t,now:n=()=>Date.now(),after:r=rt,onPosition:s=()=>{},onStatus:l=()=>{},onDeckSeq:a=()=>{},makeID:u=et}){let f=!0,o=[],p=null,c=!1,x=null,d=null,m=0,w=null,k=null,M=u(),E=0,q=S=>({id:u(),n:++E,fields:S});function b(){return f?"online":"offline"}function A(S){let _=f;f=S==="online",_!==f&&l(b())}function L(S){!S||typeof S.seq!="number"||(typeof S.deckSeq=="number"&&a(S.deckSeq),(!d||S.seq>d.seq)&&(d=S))}function P(){!f||p||o.length||!d||d.seq<=m||(m=d.seq,fe(d,x)&&(x={slide:d.slide,step:d.step||0,mode:d.mode,black:!!d.black},s({...x,seq:d.seq})))}function N(){if(!f||p||!o.length)return;let S=o[0],_=n(),h={item:S};p=h;let v=r(3e3,()=>{p===h&&i()});Promise.resolve().then(()=>e({...S.fields,press:S.id,link:M,n:String(S.n)})).then(T=>{if(p===h){if(v(),n()-_>3e3){i();return}p=null,o.shift(),L(T),o.length?N():P()}},()=>{p===h&&(v(),i())})}function i(){(p||o.length)&&(c=!0),p=null,o=[],A("offline"),y()}function y(){w||f||!c||(w=r(2e3,()=>{w=null,!(f||!c)&&g()}))}function g(){if(w&&(w(),w=null),A("online"),c&&x){c=!1,o=[q({op:"resume",at_slide:x.slide,at_step:String(x.step||0),at_mode:x.mode,at_black:x.black?"true":"false"})],N();return}P()}function I(){k&&(k(),k=null)}return t({open(){I(),f||g()},error(){!f||k||(k=r(5e3,()=>{k=null,f&&i()}))},position(S){I(),L(S),f?P():g()}}),{press(S,_){if(_&&(x={..._}),!f){c=!0,y();return}o.push(q(nt(S))),N()},resume(S){x=S?{...S}:null},status:b}}function st(e){let t=[];for(let n=1;n<=e;n++)t.push({id:"press"+n,type:"image",step:n});return t}function it(e,t){let n=Array.isArray(e.slides)?e.slides:[];return{deckSeq:Number(e.deckSeq)||0,arrive:e.arrive||"appear",etag:t,slides:n,byID:new Map(n.map(r=>[r.id,r])),view:{slides:n.map(r=>({id:r.id,talk:r.full?"full":"",blocks:st(Number(r.presses)||0)}))},ready:new Set,failed:new Set,waiters:new Map}}var ot=[];function at(e){let t=new Image;return t.decoding="async",t.src=e,ot.push(t),t.decode()}async function ve({href:e,fonts:t=()=>globalThis.slidesFonts,onProgress:n=()=>{},from:r=0,fetchImpl:s=(...a)=>globalThis.fetch(...a),picture:l=at}){let a=typeof t=="function"?t:()=>t;async function u(d){let m={Accept:"application/json"};d&&(m["If-None-Match"]=d);let w=await s(e,{credentials:"same-origin",cache:"no-store",headers:m});if(w.status===304)return null;if(!w.ok)throw new Error("talk: "+w.status);return it(await w.json(),w.headers.get("ETag"))}async function f(d,m){try{let w=a();await Promise.all([w&&w.prepareSection?w.prepareSection(m.html):null,...(Array.isArray(m.assets)?m.assets:[]).map(l)]),d.ready.add(m.id),d.failed.delete(m.id);let k=d.waiters.get(m.id)||[];d.waiters.delete(m.id);for(let M of k)M(!0)}catch{d.failed.add(m.id)}}async function o(d,m,w){let k=d.slides.length,M=[];for(let b=0;b<k;b++)M.push(d.slides[(m+b)%k]);let E=b=>w&&n({done:d.ready.size,total:k,failed:d.failed.size,finished:b}),q=0;E(!1),await Promise.all(Array.from({length:Math.min(4,k)},async()=>{for(;q<k;){let b=M[q++];d.ready.has(b.id)||(await f(d,b),E(!1))}})),E(!0)}let p=await u(null),c=null,x=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 c?c.deckSeq:0},get pendingView(){return c?c.view:null},slide(d){return p.byID.get(d)||null},has(d){return p.ready.has(d)},ready(d){if(p.ready.has(d))return Promise.resolve(!0);if(!p.byID.has(d))return Promise.resolve(!1);let m=p;return new Promise(w=>{m.waiters.has(d)||m.waiters.set(d,[]),m.waiters.get(d).push(w)})},refresh(){if(x)return x;let d=c||p;return x=u(d.etag).then(async m=>!m||m.deckSeq<=d.deckSeq?!1:(c=m,await o(m,0,!1),!0)).catch(()=>!1).finally(()=>{x=null}),x},adopt(){if(!c)return null;let d=p.view;for(let m of c.slides){let w=p.byID.get(m.id);w&&p.ready.has(m.id)&&w.html===m.html&&c.ready.add(m.id)}return p=c,c=null,o(p,0,!1),d},retry(){for(let d of[p,c])d&&d.failed.size&&o(d,0,d===p)}}}function lt(e,t){for(let n of e.querySelectorAll("[data-press]"))n.removeAttribute("data-arriving"),Number(n.getAttribute("data-press"))>t?n.setAttribute("data-waiting",""):n.removeAttribute("data-waiting")}function X(e,t,n){let r=document.createElement("template");r.innerHTML=t,lt(r.content,n),e.replaceChildren(r.content)}function Ee(e){e.target===e.currentTarget&&(e.currentTarget.removeAttribute("data-arriving"),e.currentTarget.removeEventListener("animationend",Ee))}function Q(e,t){for(let n of e.querySelectorAll("[data-arriving]"))n.removeAttribute("data-arriving");for(let n of e.querySelectorAll("[data-press]"))Number(n.getAttribute("data-press"))>t?n.setAttribute("data-waiting",""):n.hasAttribute("data-waiting")&&(n.removeAttribute("data-waiting"),n.setAttribute("data-arriving",""),n.addEventListener("animationend",Ee))}function O(e,t){return String(e||"").replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):n)}function ee(e,t,n){let r=F(e,t);if(!r.length)return{n:n+1,total:e.slides.length};let s=1;return r.forEach((l,a)=>{l<=n&&(s=a+1)}),{n:s,total:r.length}}function $(e,t){return e.slides.findIndex(n=>n.id===t)}function pe(e,t){e&&e.setAttribute(t,e.getAttribute(t)==="a"?"b":"a")}function Me(e){let t=0;return function(r,s,l,a){let u=++t,f=r.deckSeq,o=()=>{if(u!==t||r.deckSeq!==f||s!==null&&!r.has(s))return;let p=s===null?null:r.slide(s);s!==null&&!p||e({html:p?p.html:null,step:l,words:a,seq:f})};s===null||r.has(s)?o():r.ready(s).then(p=>{p&&o()})}}var ct=3e4,ut=1500,Ie=3e3,Pe=(e,t)=>F(e,"full").indexOf($(e,t)),Te=e=>new Promise(t=>setTimeout(t,e));function dt(e){return t=>{let n=null,r=!1,s=()=>{n||r||(n=new EventSource(e),n.onopen=()=>t.open(),n.onerror=()=>{t.error(),n&&n.readyState===EventSource.CLOSED&&(n=null,setTimeout(s,Ie))},n.addEventListener("slide",l=>{let a;try{a=JSON.parse(l.data)}catch{return}if(a.ended){location.reload();return}a.slideId&&t.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",l=>{let a=r&&l.persisted;r=!1,a&&setTimeout(s,0)}),s(),()=>{r=!0,n&&n.close()}}}function ft(e,t){return n=>{let r=new URLSearchParams(n);return t&&r.set("t",t),fetch(e,{method:"POST",body:r,credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(s=>{if(s.status===410&&location.reload(),!s.ok)throw new Error("press: "+s.status);return s.json()})}}function te({root:e,talkHref:t,streamHref:n,action:r,token:s,draw:l,onStatus:a=()=>{},onProgress:u=()=>{},onPressed:f=()=>{}}){let o=null,p=null,c=null,x=null,d=0,m=0,w=[];function k(i){let y=c,g=d!==o.deckSeq;c=i,x=null,d=o.deckSeq,l(i,y,{fresh:g,store:o})}function M(i){let y=++m;if(x=i,!i.slide||o.has(i.slide)||i.slide===c.slide&&d===o.deckSeq){k(i);return}o.ready(i.slide).then(g=>{g&&y===m&&k(i)})}function E(){return o.refresh().then(i=>(o.pending&&e.setAttribute("data-deck-pending",String(o.pending)),i))}function q(i){let y=Pe(o.view,i.slide);return o.adopt(),e.removeAttribute("data-deck-pending"),J(o.view,i,y)}function b(i){if(!o){w.push(i);return}if(i.op==="timer-reset"){p.press(i,null);return}let y=x||c,g=Y(o.view,y,i),I=o.pendingView;if(I){let S=Y(I,J(I,y,Pe(o.view,y.slide)),i);if(g.slide!==y.slide||S.slide!==y.slide){let _=q(y);g=Y(o.view,_,i)}}f(i,y,g),p.press(i,g),M(g)}function A(i){if(!o){w.push({jump:i});return}let y=x||c,g=F(o.view,y.mode)[i-1];g!==void 0&&b({op:"goto",slide:o.view.slides[g].id})}async function L(i){let y=++m,g=x||c,I=()=>!i.slide||!!o.slide(i.slide)||!!o.pendingView&&$(o.pendingView,i.slide)>=0;if(i.slide!==g.slide&&p.status()==="online"&&await Promise.race([E(),Te(ut)]),I()||await E(),y!==m||!I())return;let S=o.pendingView;S&&$(S,i.slide)>=0&&(i.slide!==g.slide||!o.slide(i.slide))&&q(g),M(de(o.view,i))}function P(){o&&p&&p.status()==="online"&&(E(),o.retry())}async function N(){let i={number:Number(e.getAttribute("data-slide"))||0,step:Number(e.getAttribute("data-step"))||0,mode:e.getAttribute("data-mode")==="full"?"full":"core",black:e.getAttribute("data-blackout")==="true"};for(;;)try{o=await ve({href:t,onProgress:u,from:Math.max(0,i.number-1)});break}catch{a("offline"),await Te(Ie)}let y=o.slides.find(g=>g.number===i.number);c={slide:y?y.id:"",step:i.step,mode:i.mode,black:i.black},d=o.deckSeq,p=Ae({post:ft(r,s),stream:dt(n),onPosition:L,onStatus:g=>{a(g),g==="online"&&o.retry()},onDeckSeq:g=>{g>o.deckSeq&&g>o.pending&&E()}}),p.resume(c),a(p.status());for(let g of w.splice(0))g.jump?A(g.jump):b(g);setInterval(P,ct),addEventListener("focus",P)}return N(),{move:b,jump:A,timerReset(){b({op:"timer-reset"})},get store(){return o},get position(){return x||c},differs:fe}}var qe={next:"next",prev:"back",first:"first",last:"last",blackout:"black",mode:"mode"};function ne(e,t,n,r=()=>{}){let s=new URL(t,location.href).pathname;e.addEventListener("submit",l=>{let a=l.target;if(!a||(a.method||"").toLowerCase()!=="post"||new URL(a.action,location.href).pathname!==s)return;let u=a.elements.op&&a.elements.op.value;if(u==="timer-reset")l.preventDefault(),n.timerReset();else if(u==="goto"&&a.elements.slide){let f=Number(a.elements.slide.value),o=n.store&&n.store.slides.find(p=>p.number===f);if(!o)return;l.preventDefault(),n.move({op:"goto",slide:o.id})}else if(qe[u])l.preventDefault(),n.move({op:qe[u]});else return;r(u)})}var me={ArrowRight:"next"," ":"next",PageDown:"next",ArrowLeft:"back",PageUp:"back",Home:"first",End:"last",b:"black",B:"black",".":"black",o:"mode",O:"mode"},pt=new Set(["PageDown","PageUp"]);function mt(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=String(e.tagName||"").toUpperCase();return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function re({act:e}){let t="";return function(r){if(r.metaKey||r.ctrlKey||r.altKey)return;let s=r.key;if(s==="Escape"){t="",e({escape:!0});return}if(mt(r.target)&&!pt.has(s))return;if(r.repeat){s in me&&r.preventDefault();return}if(/^[0-9]$/.test(s)){t=(t+s).slice(-4),r.preventDefault();return}if(s==="Enter"){if(!t)return;let a=Number(t);t="",r.preventDefault(),a>0&&e({jump:a});return}t="";let l=null;s in me?l={move:{op:me[s]}}:s==="p"||s==="P"?l={open:"presenter"}:(s==="r"||s==="R")&&(l={timer:"reset"}),l&&(r.preventDefault(),e(l))}}var ht=e=>String(e||"").toLowerCase().split(/\s+/).filter(Boolean);function gt(e,t){let n=String(t||"").trim();if(!n)return e.slice();if(/^\d+$/.test(n)){let s=e.filter(a=>String(a.number)===n),l=e.filter(a=>String(a.number)!==n&&String(a.number).startsWith(n));return s.concat(l)}let r=ht(n);return e.filter(s=>{let l=String(s.title||"").toLowerCase();return r.every(a=>l.includes(a))})}function bt(e,t,n,r){return t==="ArrowRight"?Math.min(e+1,r-1):t==="ArrowLeft"?Math.max(e-1,0):t==="ArrowDown"?Math.min(e+n,r-1):t==="ArrowUp"?e-n<0?-1:e-n:e}function R(e,t,n){let r=document.createElement(e);return t&&r.setAttribute(t,""),n!==void 0&&(r.textContent=n),r}function Le({root:e,talk:t,position:n,go:r}){let s=e.dataset,l=e.querySelector("[presenter-pos]"),a=l.parentElement;l.setAttribute("role","button"),l.setAttribute("aria-haspopup","dialog"),l.setAttribute("aria-expanded","false");let u=R("div","presenter-picker");u.id="presenter-picker",u.hidden=!0,u.setAttribute("role","dialog"),u.setAttribute("aria-label",s.textPickTitle),l.setAttribute("aria-controls",u.id);let f=R("label","presenter-picker-field"),o=R("input");o.type="text",o.autocomplete="off",o.placeholder=s.textPickField,o.setAttribute("aria-label",s.textPickField);let p=R("span","presenter-picker-count");f.append(o,p);let c=R("div","presenter-picker-grid"),x=R("p","presenter-picker-none");x.setAttribute("role","status"),p.setAttribute("role","status"),u.append(f,x,c),a.append(u);let d=new Map,m=new IntersectionObserver(i=>{for(let y of i){if(!y.isIntersecting)continue;let g=y.target.querySelector("img");g&&!g.getAttribute("src")&&(g.src=g.getAttribute("data-src")),m.unobserve(y.target)}},{root:c,rootMargin:"0px 0px 80px 0px"});function w(i){let y=d.get(i.id);if(y)return y;y=R("button","presenter-pick-item"),y.type="button",y.setAttribute("data-id",i.id);let g=R("img");g.alt="",g.width=1920,g.height=1080,g.loading="lazy",g.setAttribute("data-src",i.thumb||"");let I=R("span");return I.append(R("b","",String(i.number)),i.title||""),i.full&&I.append(" ",R("em","","\xB7 "+s.textPickFull)),y.append(g,I),y.addEventListener("click",()=>L(i)),m.observe(y),d.set(i.id,y),y}let k=[];function M(){let i=t.slides||[],y=gt(i,o.value);k=y;let g=(n()||{}).number;p.textContent=o.value.trim()?O(s.textPickMatches,{n:y.length,total:i.length}):O(s.textPickCount,{total:i.length}),x.textContent=y.length?"":s.textPickNone,c.hidden=y.length===0,c.replaceChildren(...y.map(I=>{let S=w(I);return I.number===g?S.setAttribute("aria-current","true"):S.removeAttribute("aria-current"),S}))}function E(){let i=c.querySelector("[aria-current]");i?c.scrollTop=Math.max(0,i.offsetTop-(c.clientHeight-i.offsetHeight)/2):c.scrollTop=0}function q(){return!u.hidden}function b(){o.value="",u.hidden=!1,l.setAttribute("aria-expanded","true"),M(),E(),o.focus({preventScroll:!0})}function A(i=!0){q()&&(u.hidden=!0,l.setAttribute("aria-expanded","false"),i&&l.focus({preventScroll:!0}))}function L(i){A(),r(i)}l.addEventListener("keydown",i=>{i.key!==" "||i.metaKey||i.ctrlKey||i.altKey||(i.preventDefault(),i.stopPropagation(),i.repeat||P())});function P(){q()?A():b()}l.addEventListener("click",i=>{i.preventDefault(),P()}),o.addEventListener("input",()=>{M(),c.scrollTop=0}),u.addEventListener("keydown",i=>{i.key==="PageDown"||i.key==="PageUp"||(i.stopPropagation(),i.key==="Escape"?(i.preventDefault(),A()):i.key==="Enter"&&i.target===o?(i.preventDefault(),k.length&&L(k[0])):i.key.startsWith("Arrow")&&(i.target===o?i.key==="ArrowDown":c.contains(i.target))&&N(i))});function N(i){let y=[...c.children];if(!y.length)return;i.preventDefault();let g;if(i.target===o)g=0;else{let I=y.indexOf(i.target),S=y.filter(_=>_.offsetTop===y[0].offsetTop).length||1;g=bt(I,i.key,S,y.length)}g<0?o.focus():y[g].focus()}return document.addEventListener("pointerdown",i=>{q()&&!u.contains(i.target)&&!l.contains(i.target)&&A(!1)}),{open:b,close:A,isOpen:q}}var Ne="slides-presenter",U="0,0,7,8;0,8,7,4;7,0,5,12";function xt(e,t){let n=Array.isArray(e)?e.length:Number(e)||0;return Math.max(0,Math.min(Math.floor(Number(t))||0,n-1))}function Ce(e,t){let n=Math.round(Number(e)/2)*2;return Math.max(16,Math.min(48,(Number.isFinite(n)?n:24)+(t<0?-2:2)))}function yt(e,t){let n=Math.max(16,Math.min(48,Math.round(e)));for(;n>16&&t(n);)n--;return n}function wt(e){let t=String(e??"").split(".");if(t.length!==3||t[0]!=="fit"&&t[0]!=="scroll")return null;let n=Number(t[1]);return!Number.isInteger(n)||n<16||n>48||n%2?null:{notes:t[0],size:n,panels:t[2]}}function kt(e){return encodeURIComponent(`${e.notes}.${e.size}.${e.panels||U}`)}function De(e=globalThis.document){try{for(let t of String(e?.cookie||"").split(";")){let n=t.indexOf("=");if(n>0&&t.slice(0,n).trim()===Ne)return wt(decodeURIComponent(t.slice(n+1).trim()))}}catch{}return null}function St(e,t=globalThis.document,n=globalThis.location){let r=n?.protocol==="https:"?"; Secure":"";try{t&&(t.cookie=`${Ne}=${kt(e)}; Path=/p; Max-Age=31536000; SameSite=Lax${r}`)}catch{}}function At(e,t,n){let r=e>1,s=e+t<n-1;return r&&s?"both":r?"top":s?"bottom":""}function vt(e,t,n,r){return e>=n&&t<=n+r?null:Math.max(0,e)}function _e({root:e,prefs:t,savePrefs:n=St}){let r=e.querySelector("[presenter-notes]"),s=m=>e.querySelector("[presenter-notes-"+m+"]"),l={fit:s("fit"),scroll:s("scroll"),smaller:s("smaller"),larger:s("larger")},a=null,u={notes:t.notes==="scroll"?"scroll":"fit",size:t.size||24,panels:t.panels||U};function f(){r.setAttribute("data-fade",At(r.scrollTop,r.clientHeight,r.scrollHeight))}function o(){let m=r.querySelector('[data-part="now"]');if(!m)return;let w=r.getBoundingClientRect().top-r.scrollTop,k=m.getBoundingClientRect().top-w,M=vt(k-12,k+m.offsetHeight,r.scrollTop,r.clientHeight);M!==null&&(r.scrollTop=M)}function p(){r.setAttribute("data-notes-mode",u.notes);let m=u.size;u.notes==="fit"&&(m=yt(u.size,k=>(r.style.fontSize=k+"px",r.scrollHeight>r.clientHeight))),r.style.fontSize=m+"px";let w=r.scrollHeight>r.clientHeight;r.setAttribute("data-notes-scrolls",w?"true":"false"),w?o():r.scrollTop=0,f(),l.fit?.setAttribute("aria-pressed",u.notes==="fit"?"true":"false"),l.scroll?.setAttribute("aria-pressed",u.notes==="scroll"?"true":"false")}function c(m){Object.assign(u,m),n({notes:u.notes,size:u.size,panels:u.panels}),p()}if(l.fit?.addEventListener("click",()=>c({notes:"fit"})),l.scroll?.addEventListener("click",()=>c({notes:"scroll"})),l.smaller?.addEventListener("click",()=>c({size:Ce(u.size,-1)})),l.larger?.addEventListener("click",()=>c({size:Ce(u.size,1)})),r.addEventListener("scroll",f),typeof ResizeObserver=="function"){let m="";new ResizeObserver(()=>{let w=r.clientWidth+"x"+r.clientHeight;w!==m&&(m=w,p())}).observe(r)}function x(m,w){let k=Array.isArray(m)?m:[],M=JSON.stringify(k);if(M!==a&&(r.scrollTop=0),a=M,k.length){let E=xt(k,w);r.replaceChildren(...k.map((q,b)=>{let A=document.createElement("section");return A.setAttribute("presenter-part",""),k.length>1&&A.setAttribute("data-part",b<E?"past":b>E?"later":"now"),A.innerHTML=q,A}))}else{let E=document.createElement("p");E.setAttribute("presenter-nonotes",""),E.textContent=e.dataset.textNonotes||"",r.replaceChildren(E)}p()}p();function d(m){c({panels:m})}return{show:x,setPanels:d}}var j=12,Oe=2,ge=["now","next","notes"],Fe="(min-width: 720px) and (min-height: 560px)";function Ue(e,t){return e.x<t.x+t.w&&t.x<e.x+e.w&&e.y<t.y+t.h&&t.y<e.y+e.h}function $e(e){return e.x>=0&&e.y>=0&&e.w>=Oe&&e.h>=Oe&&e.x+e.w<=j&&e.y+e.h<=j}function he(e){let t=String(e??"").split(";");if(t.length!==ge.length)return null;let n=[];for(let r of t){let s=r.split(",");if(s.length!==4||!s.every(p=>/^[0-9]{1,2}$/.test(p)))return null;let[l,a,u,f]=s.map(Number),o={x:l,y:a,w:u,h:f};if(!$e(o))return null;n.push(o)}for(let r=0;r<n.length;r++)for(let s=r+1;s<n.length;s++)if(Ue(n[r],n[s]))return null;return n}function je(e){return e.map(t=>[t.x,t.y,t.w,t.h].join(",")).join(";")}function se(e){let t=Math.round(Number(e)||0);return Math.max(-j,Math.min(j,t))}function Re(e,t,n){let r=e.map(s=>({...s}));for(let[s,l]of n){let a=Math.sign(l);for(let u=0;u<Math.abs(l);u++){let f={...r[t],[s]:r[t][s]+a};if(!$e(f)||r.some((o,p)=>p!==t&&Ue(f,o)))break;r[t]=f}}return r}function ze(e,t,n={}){if(!e[t])return e.map(c=>({...c}));let[r,s]=[["x",se(n.dx)],["y",se(n.dy)]],[l,a]=[["w",se(n.dw)],["h",se(n.dh)]],u={...e[t]};for(let[c,x]of[r,s,l,a])u[c]+=x;let f=c=>["x","y","w","h"].reduce((x,d)=>x+Math.abs(c[t][d]-u[d]),0),o=Re(e,t,[r,s,l,a]),p=Re(e,t,[s,r,a,l]);return f(p)<f(o)?p:o}function Et(e,t){let n={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]}[e];if(!n)return null;let[r,s]=n;return t?r?{dw:r}:{dh:s}:r?{dx:r}:{dy:s}}function Mt(e){let t=[`@media ${Fe} {`];e.forEach((a,u)=>{t.push(` [presenter-panel="${ge[u]}"] { grid-area: ${a.y+1} / ${a.x+1} / span ${a.h} / span ${a.w}; }`)});let[n,r]=e,s=`${n.w} / ${j} * 100cqw - 32px, (${n.h} / ${j} * 100cqh - 16px) * 16 / 9`,l=je(e)===U;return l&&(s+=`, (${r.h} / ${j} * 100cqh - 50px) * 2 * 16 / 9`),t.push(` [presenter-panel] { --p-now: min(${s}); }`),t.push(` [presenter-panel="next"] [presenter-frame] { inline-size: min(100cqw, 100cqh * 16 / 9${l?", var(--p-now) / 2":""}); }`),t.push("}"),t.join(`
+`)+`
+`}function He({root:e,panels:t,save:n}){let r=e.ownerDocument,s=r.defaultView,l=e.querySelector("[presenter-arrange-bar]"),a=e.querySelector("[presenter-panels]"),u=ge.map(b=>e.querySelector(`[presenter-panel="${b}"]`)),f=s.matchMedia(Fe),o=he(t)||he(U),p=o,c=!1,x=null,d=null,m=()=>s.getComputedStyle(e).direction==="rtl"?-1:1;function w(b){o=b,x||(x=r.createElement("style"),x.setAttribute("presenter-arranged",""),r.head.append(x)),x.textContent=Mt(o)}function k(){c=!1,d=null,e.removeAttribute("data-arranging"),l.hidden=!0;for(let b of u)b.removeAttribute("tabindex"),b.querySelector(":scope > [presenter-arrange-handle]")?.remove();e.querySelector("[presenter-more]")?.focus()}function M(){if(!(c||!l||!a||u.some(b=>!b)||!f.matches)){c=!0,p=o,e.setAttribute("data-arranging",""),l.hidden=!1;for(let b of u){b.tabIndex=0;let A=r.createElement("span");A.setAttribute("presenter-arrange-handle",""),A.setAttribute("aria-hidden","true"),b.append(A)}u[0].focus()}}function E(){w(p),k()}l?.querySelector("[presenter-arrange-done]")?.addEventListener("click",()=>{n(je(o)),p=o,k()}),l?.querySelector("[presenter-arrange-reset]")?.addEventListener("click",()=>{w(he(U)),n(U),p=o}),f.addEventListener?.("change",()=>{c&&!f.matches&&E()}),u.forEach((b,A)=>{if(!b)return;b.addEventListener("pointerdown",P=>{if(!c||P.button!==0)return;P.preventDefault(),b.focus({preventScroll:!0}),b.setPointerCapture?.(P.pointerId);let N=a.getBoundingClientRect();d={i:A,id:P.pointerId,resize:!!P.target.closest?.("[presenter-arrange-handle]"),x:P.clientX,y:P.clientY,w:N.width/j,h:N.height/j,from:o}}),b.addEventListener("pointermove",P=>{if(!d||d.i!==A||d.id!==P.pointerId)return;let N=Math.round(m()*(P.clientX-d.x)/d.w),i=Math.round((P.clientY-d.y)/d.h);w(ze(d.from,A,d.resize?{dw:N,dh:i}:{dx:N,dy:i}))});let L=P=>{d&&d.id===P.pointerId&&(d=null)};b.addEventListener("pointerup",L),b.addEventListener("pointercancel",L)});function q(b){if(b.metaKey||b.ctrlKey||b.altKey)return;if(b.key==="Escape"){b.preventDefault(),E();return}let A=u.indexOf(r.activeElement),L=A>=0&&Et(b.key,b.shiftKey);L&&(b.preventDefault(),L.dx&&(L.dx*=m()),L.dw&&(L.dw*=m()),w(ze(o,A,L)))}return{start:M,key:q,isOn:()=>c}}var Tt=new Set(["next","back","first","last","goto"]);function V(e,t,n){let r=document.createElement(e);return t&&r.setAttribute(t,""),n!==void 0&&(r.textContent=n),r}function Ke(e){let t=e.dataset,n=h=>e.querySelector(h),r=n("[presenter-head]"),s=n("[presenter-pos]"),l=n("[presenter-status]"),a=n("[presenter-elapsed]");window.name="slides-presenter";function u(h,v){let T=n("["+h+"]");return T||(T=V("span",h),T.hidden=!0,v.after(T)),T}let f=u("presenter-stepcount",s);if(!f.firstChild){f.setAttribute("role","status");let h=V("span","presenter-track");h.setAttribute("aria-hidden","true"),f.append(h,V("span","presenter-steptext"))}let o=u("presenter-mode",f),p=u("presenter-black",o);function c(h,v,T){let C=T.view,D=s.querySelector("[presenter-count]");D&&(D.textContent=O(t.textProgress,ee(C,v.mode,$(C,v.slide))));let z=Number(h.presses)||0;if(f.hidden=z===0,z){let W=f.querySelector("[presenter-track]");for(;W.children.length<z;)W.append(V("i"));for(;W.children.length>z;)W.lastChild.remove();[...W.children].forEach((Be,Xe)=>Be.toggleAttribute("data-done",Xe<v.step)),f.querySelector("[presenter-steptext]").textContent=O(t.textStep,{n:v.step,total:z})}let H=T.slides.some(W=>W.full);o.hidden=!H,H&&(o.textContent=v.mode==="full"?t.textModeFull:t.textModeCore),p.hidden=!v.black,p.textContent=t.textBlack;let Z=e.querySelector('[presenter-menu] form input[name="op"][value="mode"]'),K=Z&&Z.form.querySelector("button");K&&(K.textContent=v.mode==="full"?t.textMenuCore:t.textMenuFull)}function x(h,v){let T=V("div","presenter-frame");if(h===null)return T.setAttribute("data-end",""),T;let C=V("div","presenter-scale");return X(C,h,v),T.append(C),T}let d="",m=Me(({html:h,step:v,words:T,seq:C})=>{n("[presenter-next-label] span").textContent=T;let D=C+":"+v+":"+h;D!==d&&(d=D,n('[presenter-panel="next"] [presenter-fit]').replaceChildren(x(h,v)))});function w(h,v,T){let C=T.view,D=$(C,v.slide),z=Number(h.presses)||0,H=F(C,v.mode).find(Z=>Z>D);v.step<z?m(T,h.id,v.step+1,t.textNextStep):H!==void 0?m(T,C.slides[H].id,0,t.textNextSlide):m(T,null,0,t.textNextEnd)}let k=n("[presenter-notes]"),M=De()||{},E=_e({root:e,prefs:{notes:M.notes||k.getAttribute("data-notes-mode"),size:M.size||Math.round(parseFloat(getComputedStyle(k).fontSize)/2)*2||24,panels:M.panels||U}});function q(h,v,{fresh:T,store:C}){let D=C.slide(h.slide);if(!D)return;let z=n('[presenter-panel="now"] [presenter-frame]'),H=z.querySelector("[presenter-scale]"),Z=!T&&v&&v.slide===h.slide;Z?v.step!==h.step&&Q(H,h.step):X(H,D.html,h.step),z.toggleAttribute("data-black",!!h.black),c(D,h,C),w(D,h,C),(!Z||v.step!==h.step)&&E.show(Array.isArray(D.notes)?D.notes:[],h.step),e.setAttribute("data-slide",String(D.number)),e.setAttribute("data-step",String(h.step)),e.setAttribute("data-mode",h.mode),e.setAttribute("data-blackout",h.black?"true":"false"),e.setAttribute("data-deck-seq",String(C.deckSeq));let K=new URL(location.href);(K.searchParams.has("slide")||K.searchParams.has("step"))&&(K.searchParams.delete("slide"),K.searchParams.delete("step"),history.replaceState(history.state,"",K.href))}let b="",A=!1;function L(){l&&(l.textContent=A?t.textOffline:b)}function P(){return a&&a.getAttribute("data-timer-since")}function N(h){pe(f,"data-flash"),pe(s,"data-pulse"),Tt.has(h.op)&&a&&!P()&&a.setAttribute("data-timer-since",String(Math.floor(Date.now()/1e3)))}let i=te({root:e,talkHref:t.talk,streamHref:t.stream,action:t.command,token:e.getAttribute("data-remote-token")||"",draw:q,onPressed:N,onStatus:h=>{A=h==="offline",L()},onProgress:h=>{e.setAttribute("data-loaded",h.finished&&!h.failed?"all":String(h.done)),b=h.finished?h.failed?O(t.textLoadingFailed,{n:h.failed}):"":O(t.textLoading,{n:h.done,total:h.total}),L()}});function y(){i.timerReset(),a&&(a.removeAttribute("data-timer-since"),a.textContent="0:00")}let g=n("[presenter-more-menu]");e.addEventListener("submit",h=>{g&&h.target.getAttribute("target")==="slides-pair"&&(g.open=!1)}),ne(e,t.command,{move:h=>i.move(h),timerReset:y,get store(){return i.store}},()=>{g&&(g.open=!1)});let I=Le({root:e,talk:{get slides(){return i.store?i.store.slides:[]}},position:()=>({number:Number(e.getAttribute("data-slide"))}),go:h=>i.move({op:"goto",slide:h.id})}),S=re({act(h){if(h.move)i.move(h.move);else if(h.jump)i.jump(h.jump);else if(h.timer)y();else if(h.escape){if(I.isOpen()){I.close();return}g&&g.open&&(g.open=!1);let v=document.activeElement;v&&v!==document.body&&v.blur&&v.blur()}}}),_=He({root:e,panels:M.panels||U,save:E.setPanels});n("[presenter-arrange]")?.addEventListener("click",()=>{g&&(g.open=!1),_.start()}),document.addEventListener("keydown",h=>{_.isOn()&&h.key!=="PageUp"&&h.key!=="PageDown"?_.key(h):S(h)}),qt(a,n("[data-clock]"))}function qt(e,t){let n=l=>(l<10?"0":"")+l;function r(){let l=e&&e.getAttribute("data-timer-since");if(!l)return;let a=Math.max(0,Math.floor(Date.now()/1e3-Number(l))),u=Math.floor(a/3600),f=Math.floor(a/60)%60;e.textContent=u?u+":"+n(f)+":"+n(a%60):f+":"+n(a%60)}function s(){t&&(t.textContent=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))}r(),s(),setInterval(r,1e3),setInterval(s,15e3)}function Ze(e){let t=e.dataset,n=e.querySelector("[slides-stage]"),r=e.querySelector("[slides-blackout]"),s=e.querySelector("[slides-waiting]"),l=e.querySelector("[slides-announce]");if(!n)return;function a(c){let x=e.querySelector("[slides-counter]");if(!x)return;let d=x.lastChild;d&&d.nodeType===Node.TEXT_NODE?d.textContent=" "+c:x.append(" "+c)}function u(c,x,{fresh:d,store:m}){let w=m.slide(c.slide);if(!w)return;let k=m.view;if(!d&&x&&x.slide===c.slide)x.step!==c.step&&Q(n,c.step);else{X(n,w.html,c.step);let A=O(t.textAnnounce,{n:w.number,total:m.slides.length,title:w.title});e.setAttribute("data-announce",A),l&&l.textContent!==A&&(l.textContent=A)}let E=ee(k,c.mode,$(k,c.slide));a(O(t.textProgress,E));let q=e.querySelector("[slides-progress]");q&&(q.setAttribute("value",String(E.n)),q.setAttribute("max",String(E.total))),e.setAttribute("data-slide",String(w.number)),e.setAttribute("data-step",String(c.step)),e.setAttribute("data-mode",c.mode),e.setAttribute("data-blackout",c.black?"true":"false"),e.setAttribute("data-deck-seq",String(m.deckSeq)),r&&(r.hidden=!c.black);let b=new URL(location.href);(b.searchParams.has("slide")||b.searchParams.has("step"))&&(b.searchParams.delete("slide"),b.searchParams.delete("step"),history.replaceState(history.state,"",b.href))}let f=te({root:e,talkHref:t.talk,streamHref:t.stream,action:t.command,token:e.getAttribute("data-remote-token")||"",draw:u,onProgress:c=>e.setAttribute("data-loaded",c.finished&&!c.failed?"all":String(c.done)),onStatus:c=>{s&&(s.textContent=t.textWaiting,s.hidden=c!=="offline")}});ne(e,t.command,f);let o=re({act(c){if(c.move)f.move(c.move);else if(c.jump)f.jump(c.jump);else if(c.timer)f.timerReset();else if(c.open&&t.presenter)window.open(t.presenter,"slides-presenter");else if(c.escape){document.fullscreenElement&&document.exitFullscreen();let x=document.activeElement;x&&x!==document.body&&x.blur&&x.blur()}}});document.addEventListener("keydown",o);let p=null;e.addEventListener("touchstart",c=>{p=c.changedTouches[0].clientX},{passive:!0}),e.addEventListener("touchend",c=>{if(p===null)return;let x=c.changedTouches[0].clientX-p;p=null,Math.abs(x)>=60&&f.move({op:x<0?"next":"back"})},{passive:!0})}var We=document.querySelector("[presenter][data-talk]"),Ve=document.querySelector("[slides-surface][data-talk]");We?Ke(We):Ve&&Ze(Ve);
diff --git a/internal/slides/static/presenter.c27ac07e6032f790.js b/internal/slides/static/presenter.c27ac07e6032f790.js
deleted file mode 100644
index 1453504..0000000
--- a/internal/slides/static/presenter.c27ac07e6032f790.js
+++ /dev/null
@@ -1,2 +0,0 @@
-var fe=/^[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]*$/,pe=e=>(Array.isArray(e)?e:[]).map(t=>t&&typeof t.t=="string"?t.t:"").join("");function me(e){let t=[];return(Array.isArray(e)?e:[]).forEach((n,r)=>{fe.test(pe(n))||t.push(r)}),t}var ne=e=>typeof e.step=="number"&&e.step>0?e.step:0;function re(e){let t=e.props&&e.props.children;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Re(e){let t=new Map;for(let r of e)t.set(r.id,r);let n=new Map;for(let r of e)if(r.type==="columns")for(let s of re(r))t.has(s)&&s!==r.id&&!n.has(s)&&n.set(s,r.id);return{byID:t,parent:n}}function ze(e,t){let n=ne(t),r=new Set([t.id]);for(let s=e.parent.get(t.id);s!==void 0&&!r.has(s);s=e.parent.get(s))r.add(s),n=Math.max(n,ne(e.byID.get(s)));return n}function se(e,t,n){switch(t.type){case"list":return me(t.text).length>0;case"heading":case"text":case"quote":return!fe.test((Array.isArray(t.text)?t.text:[]).map(pe).join(`
-`));case"columns":n.add(t.id);for(let r of re(t)){let s=e.byID.get(r);if(s&&!n.has(r)&&se(e,s,n))return!0}return!1}return!0}function he(e,t,n){let r=ze(e,t);if(t.type!=="columns")return r;n.add(t.id);let s=1/0;for(let c of re(t)){let l=e.byID.get(c);!l||n.has(c)||!se(e,l,new Set)||(s=Math.min(s,he(e,l,n)))}return s>r&&s!==1/0?s:r}function ge(e){let t=Array.isArray(e&&e.blocks)?e.blocks:[],n=Re(t),r=[],s=[];for(let l of t){if(ne(l)===0||!se(n,l,new Set))continue;let d={id:l.id,value:he(n,l,new Set),items:null};l.type==="list"&&l.items==="each"&&(d.items=me(l.text)),r.push(d),s.includes(d.value)||s.push(d.value)}s.sort((l,d)=>l-d);let c=[];for(let l of s){let d=1;for(let f of r)f.value===l&&f.items&&f.items.length>d&&(d=f.items.length);for(let f=0;f<d;f++){let o=[];for(let p of r)p.value===l&&(p.items?f<p.items.length&&o.push({block:p.id,item:p.items[f]}):f===0&&o.push({block:p.id,item:-1}));c.push(o)}}return c}var B=e=>Array.isArray(e&&e.slides)?e.slides:[],oe=(e,t)=>e.findIndex(n=>n.id===t),ie=e=>ge(e).length,W=(e,t,n=0)=>({slide:e.id,step:n,mode:t,black:!1}),le=e=>({slide:"",step:0,mode:e,black:!1}),be=(e,t)=>Math.min(Math.max(e,0),t);function R(e,t){let n=[];return B(e).forEach((r,s)=>{r.talk==="parked"||r.talk==="full"&&t!=="full"||n.push(s)}),n}function X(e,t,n){let r=B(e),s=R(e,t.mode);switch(n.op){case"black":return{...t,black:!t.black};case"mode":return{...t,mode:t.mode==="full"?"core":"full"};case"goto":{let c=n.slide?oe(r,n.slide):-1;return c<0||r[c].talk==="parked"?t:W(r[c],r[c].talk==="full"?"full":t.mode)}case"first":case"last":return s.length?W(r[n.op==="first"?s[0]:s[s.length-1]],t.mode):le(t.mode);case"next":case"back":return Fe(e,t,n.op==="next",s)}return t}function Fe(e,t,n,r){let s=B(e);if(!r.length)return le(t.mode);let c=oe(s,t.slide);if(c<0)return{...ae(e,t),black:!1};let l=ie(s[c]),d=be(t.step,l);if(n&&d<l)return{...t,step:d+1,black:!1};if(!n&&d>0)return{...t,step:d-1,black:!1};if(n){let f=r.find(o=>o>c);if(f!==void 0)return W(s[f],t.mode)}else{let f=r.findLast(o=>o<c);if(f!==void 0)return W(s[f],t.mode,ie(s[f]))}return{...t,step:d,black:!1}}function ae(e,t){return $(e,t,-1)}function $(e,t,n){let r=B(e),s=R(e,t.mode);if(!s.length)return le(t.mode);let c=f=>({...W(r[f],t.mode),black:t.black}),l=s[s.length-1];if(t.slide==="")return c(s[0]);let d=oe(r,t.slide);if(d<0&&n>=0){let f=R(e,"full").slice(n).find(o=>s.includes(o));return c(f??l)}return d<0?c(l):r[d].talk==="parked"?c(s.find(f=>f>d)??l):{...t,step:be(t.step,ie(r[d]))}}var He="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function Ue(){let e=new Uint8Array(22);globalThis.crypto.getRandomValues(e);let t="";for(let n of e)t+=He[n&63];return t}var je={back:"prev",black:"blackout"};function Ze(e){let t={op:je[e.op]||e.op};return e.slide&&(t.slide=String(e.slide)),t}function ce(e,t){return!e||!t?e!==t:e.slide!==t.slide||(e.step||0)!==(t.step||0)||e.mode!==t.mode||!!e.black!=!!t.black}var Ke=(e,t)=>{let n=setTimeout(t,e);return()=>clearTimeout(n)};function ke({post:e,stream:t,now:n=()=>Date.now(),after:r=Ke,onPosition:s=()=>{},onStatus:c=()=>{},onDeckSeq:l=()=>{},makeID:d=Ue}){let f=!0,o=[],p=null,u=!1,x=null,a=null,h=0,k=null,y=null,E=d(),P=0,M=S=>({id:d(),n:++P,fields:S});function A(){return f?"online":"offline"}function I(S){let m=f;f=S==="online",m!==f&&c(A())}function D(S){!S||typeof S.seq!="number"||(typeof S.deckSeq=="number"&&l(S.deckSeq),(!a||S.seq>a.seq)&&(a=S))}function L(){!f||p||o.length||!a||a.seq<=h||(h=a.seq,ce(a,x)&&(x={slide:a.slide,step:a.step||0,mode:a.mode,black:!!a.black},s({...x,seq:a.seq})))}function z(){if(!f||p||!o.length)return;let S=o[0],m=n(),w={item:S};p=w;let v=r(3e3,()=>{p===w&&i()});Promise.resolve().then(()=>e({...S.fields,press:S.id,link:E,n:String(S.n)})).then(q=>{if(p===w){if(v(),n()-m>3e3){i();return}p=null,o.shift(),D(q),o.length?z():L()}},()=>{p===w&&(v(),i())})}function i(){(p||o.length)&&(u=!0),p=null,o=[],I("offline"),b()}function b(){k||f||!u||(k=r(2e3,()=>{k=null,!(f||!u)&&g()}))}function g(){if(k&&(k(),k=null),I("online"),u&&x){u=!1,o=[M({op:"resume",at_slide:x.slide,at_step:String(x.step||0),at_mode:x.mode,at_black:x.black?"true":"false"})],z();return}L()}function T(){y&&(y(),y=null)}return t({open(){T(),f||g()},error(){!f||y||(y=r(5e3,()=>{y=null,f&&i()}))},position(S){T(),D(S),f?L():g()}}),{press(S,m){if(m&&(x={...m}),!f){u=!0,b();return}o.push(M(Ze(S))),z()},resume(S){x=S?{...S}:null},status:A}}function We(e){let t=[];for(let n=1;n<=e;n++)t.push({id:"press"+n,type:"image",step:n});return t}function Ve(e,t){let n=Array.isArray(e.slides)?e.slides:[];return{deckSeq:Number(e.deckSeq)||0,arrive:e.arrive||"appear",etag:t,slides:n,byID:new Map(n.map(r=>[r.id,r])),view:{slides:n.map(r=>({id:r.id,talk:r.full?"full":"",blocks:We(Number(r.presses)||0)}))},ready:new Set,failed:new Set,waiters:new Map}}var Be=[];function Xe(e){let t=new Image;return t.decoding="async",t.src=e,Be.push(t),t.decode()}async function xe({href:e,fonts:t=()=>globalThis.slidesFonts,onProgress:n=()=>{},from:r=0,fetchImpl:s=(...l)=>globalThis.fetch(...l),picture:c=Xe}){let l=typeof t=="function"?t:()=>t;async function d(a){let h={Accept:"application/json"};a&&(h["If-None-Match"]=a);let k=await s(e,{credentials:"same-origin",cache:"no-store",headers:h});if(k.status===304)return null;if(!k.ok)throw new Error("talk: "+k.status);return Ve(await k.json(),k.headers.get("ETag"))}async function f(a,h){try{let k=l();await Promise.all([k&&k.prepareSection?k.prepareSection(h.html):null,...(Array.isArray(h.assets)?h.assets:[]).map(c)]),a.ready.add(h.id),a.failed.delete(h.id);let y=a.waiters.get(h.id)||[];a.waiters.delete(h.id);for(let E of y)E(!0)}catch{a.failed.add(h.id)}}async function o(a,h,k){let y=a.slides.length,E=[];for(let A=0;A<y;A++)E.push(a.slides[(h+A)%y]);let P=A=>k&&n({done:a.ready.size,total:y,failed:a.failed.size,finished:A}),M=0;P(!1),await Promise.all(Array.from({length:Math.min(4,y)},async()=>{for(;M<y;){let A=E[M++];a.ready.has(A.id)||(await f(a,A),P(!1))}})),P(!0)}let p=await d(null),u=null,x=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 u?u.deckSeq:0},get pendingView(){return u?u.view:null},slide(a){return p.byID.get(a)||null},has(a){return p.ready.has(a)},ready(a){if(p.ready.has(a))return Promise.resolve(!0);if(!p.byID.has(a))return Promise.resolve(!1);let h=p;return new Promise(k=>{h.waiters.has(a)||h.waiters.set(a,[]),h.waiters.get(a).push(k)})},refresh(){if(x)return x;let a=u||p;return x=d(a.etag).then(async h=>!h||h.deckSeq<=a.deckSeq?!1:(u=h,await o(h,0,!1),!0)).catch(()=>!1).finally(()=>{x=null}),x},adopt(){if(!u)return null;let a=p.view;for(let h of u.slides){let k=p.byID.get(h.id);k&&p.ready.has(h.id)&&k.html===h.html&&u.ready.add(h.id)}return p=u,u=null,o(p,0,!1),a},retry(){for(let a of[p,u])a&&a.failed.size&&o(a,0,a===p)}}}function $e(e,t){for(let n of e.querySelectorAll("[data-press]"))n.removeAttribute("data-arriving"),Number(n.getAttribute("data-press"))>t?n.setAttribute("data-waiting",""):n.removeAttribute("data-waiting")}function V(e,t,n){let r=document.createElement("template");r.innerHTML=t,$e(r.content,n),e.replaceChildren(r.content)}function Se(e){e.target===e.currentTarget&&(e.currentTarget.removeAttribute("data-arriving"),e.currentTarget.removeEventListener("animationend",Se))}function G(e,t){for(let n of e.querySelectorAll("[data-arriving]"))n.removeAttribute("data-arriving");for(let n of e.querySelectorAll("[data-press]"))Number(n.getAttribute("data-press"))>t?n.setAttribute("data-waiting",""):n.hasAttribute("data-waiting")&&(n.removeAttribute("data-waiting"),n.setAttribute("data-arriving",""),n.addEventListener("animationend",Se))}function N(e,t){return String(e||"").replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):n)}function J(e,t,n){let r=R(e,t);if(!r.length)return{n:n+1,total:e.slides.length};let s=1;return r.forEach((c,l)=>{c<=n&&(s=l+1)}),{n:s,total:r.length}}function F(e,t){return e.slides.findIndex(n=>n.id===t)}function ue(e,t){e&&e.setAttribute(t,e.getAttribute(t)==="a"?"b":"a")}function we(e){let t=0;return function(r,s,c,l){let d=++t,f=r.deckSeq,o=()=>{if(d!==t||r.deckSeq!==f||s!==null&&!r.has(s))return;let p=s===null?null:r.slide(s);s!==null&&!p||e({html:p?p.html:null,step:c,words:l,seq:f})};s===null||r.has(s)?o():r.ready(s).then(p=>{p&&o()})}}var Ge=3e4,Je=1500,Ee=3e3,ye=(e,t)=>R(e,"full").indexOf(F(e,t)),Ae=e=>new Promise(t=>setTimeout(t,e));function Ye(e){return t=>{let n=null,r=!1,s=()=>{n||r||(n=new EventSource(e),n.onopen=()=>t.open(),n.onerror=()=>{t.error(),n&&n.readyState===EventSource.CLOSED&&(n=null,setTimeout(s,Ee))},n.addEventListener("slide",c=>{let l;try{l=JSON.parse(c.data)}catch{return}if(l.ended){location.reload();return}l.slideId&&t.position({slide:l.slideId,step:Number(l.step)||0,mode:l.mode,black:!!l.blackout,seq:Number(l.seq)||0})}))};return addEventListener("pagehide",()=>{r=!0,n&&(n.close(),n=null)}),addEventListener("pageshow",c=>{let l=r&&c.persisted;r=!1,l&&setTimeout(s,0)}),s(),()=>{r=!0,n&&n.close()}}}function Qe(e,t){return n=>{let r=new URLSearchParams(n);return t&&r.set("t",t),fetch(e,{method:"POST",body:r,credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}).then(s=>{if(s.status===410&&location.reload(),!s.ok)throw new Error("press: "+s.status);return s.json()})}}function Y({root:e,talkHref:t,streamHref:n,action:r,token:s,draw:c,onStatus:l=()=>{},onProgress:d=()=>{},onPressed:f=()=>{}}){let o=null,p=null,u=null,x=null,a=0,h=0,k=[];function y(i){let b=u,g=a!==o.deckSeq;u=i,x=null,a=o.deckSeq,c(i,b,{fresh:g,store:o})}function E(i){let b=++h;if(x=i,!i.slide||o.has(i.slide)||i.slide===u.slide&&a===o.deckSeq){y(i);return}o.ready(i.slide).then(g=>{g&&b===h&&y(i)})}function P(){return o.refresh().then(i=>(o.pending&&e.setAttribute("data-deck-pending",String(o.pending)),i))}function M(i){let b=ye(o.view,i.slide);return o.adopt(),e.removeAttribute("data-deck-pending"),$(o.view,i,b)}function A(i){if(!o){k.push(i);return}if(i.op==="timer-reset"){p.press(i,null);return}let b=x||u,g=X(o.view,b,i),T=o.pendingView;if(T){let S=X(T,$(T,b,ye(o.view,b.slide)),i);if(g.slide!==b.slide||S.slide!==b.slide){let m=M(b);g=X(o.view,m,i)}}f(i,b,g),p.press(i,g),E(g)}function I(i){if(!o){k.push({jump:i});return}let b=x||u,g=R(o.view,b.mode)[i-1];g!==void 0&&A({op:"goto",slide:o.view.slides[g].id})}async function D(i){let b=++h,g=x||u,T=()=>!i.slide||!!o.slide(i.slide)||!!o.pendingView&&F(o.pendingView,i.slide)>=0;if(i.slide!==g.slide&&p.status()==="online"&&await Promise.race([P(),Ae(Je)]),T()||await P(),b!==h||!T())return;let S=o.pendingView;S&&F(S,i.slide)>=0&&(i.slide!==g.slide||!o.slide(i.slide))&&M(g),E(ae(o.view,i))}function L(){o&&p&&p.status()==="online"&&(P(),o.retry())}async function z(){let i={number:Number(e.getAttribute("data-slide"))||0,step:Number(e.getAttribute("data-step"))||0,mode:e.getAttribute("data-mode")==="full"?"full":"core",black:e.getAttribute("data-blackout")==="true"};for(;;)try{o=await xe({href:t,onProgress:d,from:Math.max(0,i.number-1)});break}catch{l("offline"),await Ae(Ee)}let b=o.slides.find(g=>g.number===i.number);u={slide:b?b.id:"",step:i.step,mode:i.mode,black:i.black},a=o.deckSeq,p=ke({post:Qe(r,s),stream:Ye(n),onPosition:D,onStatus:g=>{l(g),g==="online"&&o.retry()},onDeckSeq:g=>{g>o.deckSeq&&g>o.pending&&P()}}),p.resume(u),l(p.status());for(let g of k.splice(0))g.jump?I(g.jump):A(g);setInterval(L,Ge),addEventListener("focus",L)}return z(),{move:A,jump:I,timerReset(){A({op:"timer-reset"})},get store(){return o},get position(){return x||u},differs:ce}}var ve={next:"next",prev:"back",first:"first",last:"last",blackout:"black",mode:"mode"};function Q(e,t,n,r=()=>{}){let s=new URL(t,location.href).pathname;e.addEventListener("submit",c=>{let l=c.target;if(!l||(l.method||"").toLowerCase()!=="post"||new URL(l.action,location.href).pathname!==s)return;let d=l.elements.op&&l.elements.op.value;if(d==="timer-reset")c.preventDefault(),n.timerReset();else if(d==="goto"&&l.elements.slide){let f=Number(l.elements.slide.value),o=n.store&&n.store.slides.find(p=>p.number===f);if(!o)return;c.preventDefault(),n.move({op:"goto",slide:o.id})}else if(ve[d])c.preventDefault(),n.move({op:ve[d]});else return;r(d)})}var de={ArrowRight:"next"," ":"next",PageDown:"next",ArrowLeft:"back",PageUp:"back",Home:"first",End:"last",b:"black",B:"black",".":"black",o:"mode",O:"mode"},et=new Set(["PageDown","PageUp"]);function tt(e){if(!e)return!1;if(e.isContentEditable)return!0;let t=String(e.tagName||"").toUpperCase();return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function ee({act:e}){let t="";return function(r){if(r.metaKey||r.ctrlKey||r.altKey)return;let s=r.key;if(s==="Escape"){t="",e({escape:!0});return}if(tt(r.target)&&!et.has(s))return;if(r.repeat){s in de&&r.preventDefault();return}if(/^[0-9]$/.test(s)){t=(t+s).slice(-4),r.preventDefault();return}if(s==="Enter"){if(!t)return;let l=Number(t);t="",r.preventDefault(),l>0&&e({jump:l});return}t="";let c=null;s in de?c={move:{op:de[s]}}:s==="p"||s==="P"?c={open:"presenter"}:(s==="r"||s==="R")&&(c={timer:"reset"}),c&&(r.preventDefault(),e(c))}}var nt=e=>String(e||"").toLowerCase().split(/\s+/).filter(Boolean);function rt(e,t){let n=String(t||"").trim();if(!n)return e.slice();if(/^\d+$/.test(n)){let s=e.filter(l=>String(l.number)===n),c=e.filter(l=>String(l.number)!==n&&String(l.number).startsWith(n));return s.concat(c)}let r=nt(n);return e.filter(s=>{let c=String(s.title||"").toLowerCase();return r.every(l=>c.includes(l))})}function st(e,t,n,r){return t==="ArrowRight"?Math.min(e+1,r-1):t==="ArrowLeft"?Math.max(e-1,0):t==="ArrowDown"?Math.min(e+n,r-1):t==="ArrowUp"?e-n<0?-1:e-n:e}function _(e,t,n){let r=document.createElement(e);return t&&r.setAttribute(t,""),n!==void 0&&(r.textContent=n),r}function Me({root:e,talk:t,position:n,go:r}){let s=e.dataset,c=e.querySelector("[presenter-pos]"),l=c.parentElement;c.setAttribute("role","button"),c.setAttribute("aria-haspopup","dialog"),c.setAttribute("aria-expanded","false");let d=_("div","presenter-picker");d.id="presenter-picker",d.hidden=!0,d.setAttribute("role","dialog"),d.setAttribute("aria-label",s.textPickTitle),c.setAttribute("aria-controls",d.id);let f=_("label","presenter-picker-field"),o=_("input");o.type="text",o.autocomplete="off",o.placeholder=s.textPickField,o.setAttribute("aria-label",s.textPickField);let p=_("span","presenter-picker-count");f.append(o,p);let u=_("div","presenter-picker-grid"),x=_("p","presenter-picker-none");x.setAttribute("role","status"),p.setAttribute("role","status"),d.append(f,x,u),l.append(d);let a=new Map,h=new IntersectionObserver(i=>{for(let b of i){if(!b.isIntersecting)continue;let g=b.target.querySelector("img");g&&!g.getAttribute("src")&&(g.src=g.getAttribute("data-src")),h.unobserve(b.target)}},{root:u,rootMargin:"0px 0px 80px 0px"});function k(i){let b=a.get(i.id);if(b)return b;b=_("button","presenter-pick-item"),b.type="button",b.setAttribute("data-id",i.id);let g=_("img");g.alt="",g.width=1920,g.height=1080,g.loading="lazy",g.setAttribute("data-src",i.thumb||"");let T=_("span");return T.append(_("b","",String(i.number)),i.title||""),i.full&&T.append(" ",_("em","","\xB7 "+s.textPickFull)),b.append(g,T),b.addEventListener("click",()=>D(i)),h.observe(b),a.set(i.id,b),b}let y=[];function E(){let i=t.slides||[],b=rt(i,o.value);y=b;let g=(n()||{}).number;p.textContent=o.value.trim()?N(s.textPickMatches,{n:b.length,total:i.length}):N(s.textPickCount,{total:i.length}),x.textContent=b.length?"":s.textPickNone,u.hidden=b.length===0,u.replaceChildren(...b.map(T=>{let S=k(T);return T.number===g?S.setAttribute("aria-current","true"):S.removeAttribute("aria-current"),S}))}function P(){let i=u.querySelector("[aria-current]");i?u.scrollTop=Math.max(0,i.offsetTop-(u.clientHeight-i.offsetHeight)/2):u.scrollTop=0}function M(){return!d.hidden}function A(){o.value="",d.hidden=!1,c.setAttribute("aria-expanded","true"),E(),P(),o.focus({preventScroll:!0})}function I(i=!0){M()&&(d.hidden=!0,c.setAttribute("aria-expanded","false"),i&&c.focus({preventScroll:!0}))}function D(i){I(),r(i)}c.addEventListener("keydown",i=>{i.key!==" "||i.metaKey||i.ctrlKey||i.altKey||(i.preventDefault(),i.stopPropagation(),i.repeat||L())});function L(){M()?I():A()}c.addEventListener("click",i=>{i.preventDefault(),L()}),o.addEventListener("input",()=>{E(),u.scrollTop=0}),d.addEventListener("keydown",i=>{i.key==="PageDown"||i.key==="PageUp"||(i.stopPropagation(),i.key==="Escape"?(i.preventDefault(),I()):i.key==="Enter"&&i.target===o?(i.preventDefault(),y.length&&D(y[0])):i.key.startsWith("Arrow")&&(i.target===o?i.key==="ArrowDown":u.contains(i.target))&&z(i))});function z(i){let b=[...u.children];if(!b.length)return;i.preventDefault();let g;if(i.target===o)g=0;else{let T=b.indexOf(i.target),S=b.filter(m=>m.offsetTop===b[0].offsetTop).length||1;g=st(T,i.key,S,b.length)}g<0?o.focus():b[g].focus()}return document.addEventListener("pointerdown",i=>{M()&&!d.contains(i.target)&&!c.contains(i.target)&&I(!1)}),{open:A,close:I,isOpen:M}}var Pe="slides-presenter",te="0,0,7,8;0,8,7,4;7,0,5,12";function it(e,t){let n=Array.isArray(e)?e.length:Number(e)||0;return Math.max(0,Math.min(Math.floor(Number(t))||0,n-1))}function Te(e,t){let n=Math.round(Number(e)/2)*2;return Math.max(16,Math.min(48,(Number.isFinite(n)?n:24)+(t<0?-2:2)))}function ot(e,t){let n=Math.max(16,Math.min(48,Math.round(e)));for(;n>16&&t(n);)n--;return n}function lt(e){let t=String(e??"").split(".");if(t.length!==3||t[0]!=="fit"&&t[0]!=="scroll")return null;let n=Number(t[1]);return!Number.isInteger(n)||n<16||n>48||n%2?null:{notes:t[0],size:n,panels:t[2]}}function at(e){return encodeURIComponent(`${e.notes}.${e.size}.${e.panels||te}`)}function Ie(e=globalThis.document){try{for(let t of String(e?.cookie||"").split(";")){let n=t.indexOf("=");if(n>0&&t.slice(0,n).trim()===Pe)return lt(decodeURIComponent(t.slice(n+1).trim()))}}catch{}return null}function ct(e,t=globalThis.document,n=globalThis.location){let r=n?.protocol==="https:"?"; Secure":"";try{t&&(t.cookie=`${Pe}=${at(e)}; Path=/p; Max-Age=31536000; SameSite=Lax${r}`)}catch{}}function ut(e,t,n){let r=e>1,s=e+t<n-1;return r&&s?"both":r?"top":s?"bottom":""}function dt(e,t,n,r){return e>=n&&t<=n+r?null:Math.max(0,e)}function qe({root:e,prefs:t,savePrefs:n=ct}){let r=e.querySelector("[presenter-notes]"),s=a=>e.querySelector("[presenter-notes-"+a+"]"),c={fit:s("fit"),scroll:s("scroll"),smaller:s("smaller"),larger:s("larger")},l=null,d={notes:t.notes==="scroll"?"scroll":"fit",size:t.size||24,panels:t.panels||te};function f(){r.setAttribute("data-fade",ut(r.scrollTop,r.clientHeight,r.scrollHeight))}function o(){let a=r.querySelector('[data-part="now"]');if(!a)return;let h=r.getBoundingClientRect().top-r.scrollTop,k=a.getBoundingClientRect().top-h,y=dt(k-12,k+a.offsetHeight,r.scrollTop,r.clientHeight);y!==null&&(r.scrollTop=y)}function p(){r.setAttribute("data-notes-mode",d.notes);let a=d.size;d.notes==="fit"&&(a=ot(d.size,k=>(r.style.fontSize=k+"px",r.scrollHeight>r.clientHeight))),r.style.fontSize=a+"px";let h=r.scrollHeight>r.clientHeight;r.setAttribute("data-notes-scrolls",h?"true":"false"),h?o():r.scrollTop=0,f(),c.fit?.setAttribute("aria-pressed",d.notes==="fit"?"true":"false"),c.scroll?.setAttribute("aria-pressed",d.notes==="scroll"?"true":"false")}function u(a){Object.assign(d,a),n({notes:d.notes,size:d.size,panels:d.panels}),p()}if(c.fit?.addEventListener("click",()=>u({notes:"fit"})),c.scroll?.addEventListener("click",()=>u({notes:"scroll"})),c.smaller?.addEventListener("click",()=>u({size:Te(d.size,-1)})),c.larger?.addEventListener("click",()=>u({size:Te(d.size,1)})),r.addEventListener("scroll",f),typeof ResizeObserver=="function"){let a="";new ResizeObserver(()=>{let h=r.clientWidth+"x"+r.clientHeight;h!==a&&(a=h,p())}).observe(r)}function x(a,h){let k=Array.isArray(a)?a:[],y=JSON.stringify(k);if(y!==l&&(r.scrollTop=0),l=y,k.length){let E=it(k,h);r.replaceChildren(...k.map((P,M)=>{let A=document.createElement("section");return A.setAttribute("presenter-part",""),k.length>1&&A.setAttribute("data-part",M<E?"past":M>E?"later":"now"),A.innerHTML=P,A}))}else{let E=document.createElement("p");E.setAttribute("presenter-nonotes",""),E.textContent=e.dataset.textNonotes||"",r.replaceChildren(E)}p()}return p(),{show:x}}var pt=new Set(["next","back","first","last","goto"]);function K(e,t,n){let r=document.createElement(e);return t&&r.setAttribute(t,""),n!==void 0&&(r.textContent=n),r}function Ce(e){let t=e.dataset,n=m=>e.querySelector(m),r=n("[presenter-head]"),s=n("[presenter-pos]"),c=n("[presenter-status]"),l=n("[presenter-elapsed]");window.name="slides-presenter";function d(m,w){let v=n("["+m+"]");return v||(v=K("span",m),v.hidden=!0,w.after(v)),v}let f=d("presenter-stepcount",s);if(!f.firstChild){f.setAttribute("role","status");let m=K("span","presenter-track");m.setAttribute("aria-hidden","true"),f.append(m,K("span","presenter-steptext"))}let o=d("presenter-mode",f),p=d("presenter-black",o);function u(m,w,v){let q=v.view,C=s.querySelector("[presenter-count]");C&&(C.textContent=N(t.textProgress,J(q,w.mode,F(q,w.slide))));let O=Number(m.presses)||0;if(f.hidden=O===0,O){let Z=f.querySelector("[presenter-track]");for(;Z.children.length<O;)Z.append(K("i"));for(;Z.children.length>O;)Z.lastChild.remove();[...Z.children].forEach((De,Oe)=>De.toggleAttribute("data-done",Oe<w.step)),f.querySelector("[presenter-steptext]").textContent=N(t.textStep,{n:w.step,total:O})}let H=v.slides.some(Z=>Z.full);o.hidden=!H,H&&(o.textContent=w.mode==="full"?t.textModeFull:t.textModeCore),p.hidden=!w.black,p.textContent=t.textBlack;let j=e.querySelector('[presenter-menu] form input[name="op"][value="mode"]'),U=j&&j.form.querySelector("button");U&&(U.textContent=w.mode==="full"?t.textMenuCore:t.textMenuFull)}function x(m,w){let v=K("div","presenter-frame");if(m===null)return v.setAttribute("data-end",""),v;let q=K("div","presenter-scale");return V(q,m,w),v.append(q),v}let a="",h=we(({html:m,step:w,words:v,seq:q})=>{n("[presenter-next-label] span").textContent=v;let C=q+":"+w+":"+m;C!==a&&(a=C,n('[presenter-panel="next"] [presenter-fit]').replaceChildren(x(m,w)))});function k(m,w,v){let q=v.view,C=F(q,w.slide),O=Number(m.presses)||0,H=R(q,w.mode).find(j=>j>C);w.step<O?h(v,m.id,w.step+1,t.textNextStep):H!==void 0?h(v,q.slides[H].id,0,t.textNextSlide):h(v,null,0,t.textNextEnd)}let y=n("[presenter-notes]"),E=Ie()||{},P=qe({root:e,prefs:{notes:E.notes||y.getAttribute("data-notes-mode"),size:E.size||Math.round(parseFloat(getComputedStyle(y).fontSize)/2)*2||24,panels:E.panels||te}});function M(m,w,{fresh:v,store:q}){let C=q.slide(m.slide);if(!C)return;let O=n('[presenter-panel="now"] [presenter-frame]'),H=O.querySelector("[presenter-scale]"),j=!v&&w&&w.slide===m.slide;j?w.step!==m.step&&G(H,m.step):V(H,C.html,m.step),O.toggleAttribute("data-black",!!m.black),u(C,m,q),k(C,m,q),(!j||w.step!==m.step)&&P.show(Array.isArray(C.notes)?C.notes:[],m.step),e.setAttribute("data-slide",String(C.number)),e.setAttribute("data-step",String(m.step)),e.setAttribute("data-mode",m.mode),e.setAttribute("data-blackout",m.black?"true":"false"),e.setAttribute("data-deck-seq",String(q.deckSeq));let U=new URL(location.href);(U.searchParams.has("slide")||U.searchParams.has("step"))&&(U.searchParams.delete("slide"),U.searchParams.delete("step"),history.replaceState(history.state,"",U.href))}let A="",I=!1;function D(){c&&(c.textContent=I?t.textOffline:A)}function L(){return l&&l.getAttribute("data-timer-since")}function z(m){ue(f,"data-flash"),ue(s,"data-pulse"),pt.has(m.op)&&l&&!L()&&l.setAttribute("data-timer-since",String(Math.floor(Date.now()/1e3)))}let i=Y({root:e,talkHref:t.talk,streamHref:t.stream,action:t.command,token:e.getAttribute("data-remote-token")||"",draw:M,onPressed:z,onStatus:m=>{I=m==="offline",D()},onProgress:m=>{e.setAttribute("data-loaded",m.finished&&!m.failed?"all":String(m.done)),A=m.finished?m.failed?N(t.textLoadingFailed,{n:m.failed}):"":N(t.textLoading,{n:m.done,total:m.total}),D()}});function b(){i.timerReset(),l&&(l.removeAttribute("data-timer-since"),l.textContent="0:00")}let g=n("[presenter-more-menu]");Q(e,t.command,{move:m=>i.move(m),timerReset:b,get store(){return i.store}},()=>{g&&(g.open=!1)});let T=Me({root:e,talk:{get slides(){return i.store?i.store.slides:[]}},position:()=>({number:Number(e.getAttribute("data-slide"))}),go:m=>i.move({op:"goto",slide:m.id})}),S=ee({act(m){if(m.move)i.move(m.move);else if(m.jump)i.jump(m.jump);else if(m.timer)b();else if(m.escape){if(T.isOpen()){T.close();return}g&&g.open&&(g.open=!1);let w=document.activeElement;w&&w!==document.body&&w.blur&&w.blur()}}});document.addEventListener("keydown",S),mt(l,n("[data-clock]"))}function mt(e,t){let n=c=>(c<10?"0":"")+c;function r(){let c=e&&e.getAttribute("data-timer-since");if(!c)return;let l=Math.max(0,Math.floor(Date.now()/1e3-Number(c))),d=Math.floor(l/3600),f=Math.floor(l/60)%60;e.textContent=d?d+":"+n(f)+":"+n(l%60):f+":"+n(l%60)}function s(){t&&(t.textContent=new Date().toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))}r(),s(),setInterval(r,1e3),setInterval(s,15e3)}function Le(e){let t=e.dataset,n=e.querySelector("[slides-stage]"),r=e.querySelector("[slides-blackout]"),s=e.querySelector("[slides-waiting]"),c=e.querySelector("[slides-announce]");if(!n)return;function l(u){let x=e.querySelector("[slides-counter]");if(!x)return;let a=x.lastChild;a&&a.nodeType===Node.TEXT_NODE?a.textContent=" "+u:x.append(" "+u)}function d(u,x,{fresh:a,store:h}){let k=h.slide(u.slide);if(!k)return;let y=h.view;if(!a&&x&&x.slide===u.slide)x.step!==u.step&&G(n,u.step);else{V(n,k.html,u.step);let I=N(t.textAnnounce,{n:k.number,total:h.slides.length,title:k.title});e.setAttribute("data-announce",I),c&&c.textContent!==I&&(c.textContent=I)}let P=J(y,u.mode,F(y,u.slide));l(N(t.textProgress,P));let M=e.querySelector("[slides-progress]");M&&(M.setAttribute("value",String(P.n)),M.setAttribute("max",String(P.total))),e.setAttribute("data-slide",String(k.number)),e.setAttribute("data-step",String(u.step)),e.setAttribute("data-mode",u.mode),e.setAttribute("data-blackout",u.black?"true":"false"),e.setAttribute("data-deck-seq",String(h.deckSeq)),r&&(r.hidden=!u.black);let A=new URL(location.href);(A.searchParams.has("slide")||A.searchParams.has("step"))&&(A.searchParams.delete("slide"),A.searchParams.delete("step"),history.replaceState(history.state,"",A.href))}let f=Y({root:e,talkHref:t.talk,streamHref:t.stream,action:t.command,token:e.getAttribute("data-remote-token")||"",draw:d,onProgress:u=>e.setAttribute("data-loaded",u.finished&&!u.failed?"all":String(u.done)),onStatus:u=>{s&&(s.textContent=t.textWaiting,s.hidden=u!=="offline")}});Q(e,t.command,f);let o=ee({act(u){if(u.move)f.move(u.move);else if(u.jump)f.jump(u.jump);else if(u.timer)f.timerReset();else if(u.open&&t.presenter)window.open(t.presenter,"slides-presenter");else if(u.escape){document.fullscreenElement&&document.exitFullscreen();let x=document.activeElement;x&&x!==document.body&&x.blur&&x.blur()}}});document.addEventListener("keydown",o);let p=null;e.addEventListener("touchstart",u=>{p=u.changedTouches[0].clientX},{passive:!0}),e.addEventListener("touchend",u=>{if(p===null)return;let x=u.changedTouches[0].clientX-p;p=null,Math.abs(x)>=60&&f.move({op:x<0?"next":"back"})},{passive:!0})}var Ne=document.querySelector("[presenter][data-talk]"),_e=document.querySelector("[slides-surface][data-talk]");Ne?Ce(Ne):_e&&Le(_e);
diff --git a/internal/slides/static/presenter.css b/internal/slides/static/presenter.css
index e8d2b66..2e585f4 100644
--- a/internal/slides/static/presenter.css
+++ b/internal/slides/static/presenter.css
@@ -114,11 +114,21 @@ body {
stroke-width: 1.75;
}
-/* The window: the header, then what is left for the panels. */
+/* The window: the header, the arranging bar while it shows, then what
+ is left for the panels. */
[presenter] {
display: grid;
grid-template-columns: minmax(0, 1fr);
- grid-template-rows: auto minmax(0, 1fr);
+ grid-template-rows: auto auto minmax(0, 1fr);
+}
+
+[presenter-head] {
+ grid-row: 1;
+}
+
+[presenter-panels],
+[presenter-empty] {
+ grid-row: 3;
}
/* ---- the header ---- */
@@ -378,6 +388,88 @@ body {
margin: 4px 0;
}
+/* ---- arranging (fixtures/presenter-arrange.mjs) ----
+ Mockup #parrange: a bar under the header saying what to do, with
+ Reset and Done. Each panel is outlined, moves under the pointer or
+ the arrow keys, and resizes from the handle in its corner (or Shift
+ and the arrows). What the panels hold takes no pointer while they
+ are being arranged. */
+[presenter-arrange-bar] {
+ grid-row: 2;
+ min-inline-size: 0;
+ margin-block-end: 16px;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ align-items: center;
+ padding: 10px 16px;
+ border-radius: 10px;
+ background: var(--p-raised);
+ color: var(--p-ink-2);
+ font-size: 17px;
+}
+
+[presenter-arrange-bar] span {
+ margin-inline-end: auto;
+}
+
+[presenter-arrange-bar] button {
+ min-block-size: 36px;
+ padding: 6px 16px;
+ border-radius: 8px;
+ border: 1px solid var(--p-border);
+ color: var(--p-ink);
+}
+
+[presenter-arrange-bar] button:hover {
+ background: var(--p-panel);
+}
+
+[presenter][data-arranging] [presenter-panel] {
+ outline: 2px dashed var(--p-accent);
+ outline-offset: -4px;
+ cursor: move;
+ touch-action: none;
+ user-select: none;
+}
+
+[presenter][data-arranging] [presenter-panel]:focus-visible {
+ outline-style: solid;
+ outline-width: 3px;
+ background: rgb(255 180 84 / 0.06);
+}
+
+[presenter][data-arranging] [presenter-panel] > :not([presenter-arrange-handle]) {
+ pointer-events: none;
+}
+
+[presenter][data-arranging] [presenter-tools] {
+ visibility: hidden;
+}
+
+[presenter-arrange-handle] {
+ position: absolute;
+ z-index: 2;
+ inset-block-end: 6px;
+ inset-inline-end: 6px;
+ inline-size: 24px;
+ block-size: 24px;
+ border-block-end: 3px solid var(--p-accent);
+ border-inline-end: 3px solid var(--p-accent);
+ border-end-end-radius: 4px;
+ cursor: nwse-resize;
+ touch-action: none;
+}
+
+/* The panels stack below 720×560 and the arrangement is ignored there,
+ so there is nothing to arrange. */
+@media (max-width: 719.98px), (max-height: 559.98px) {
+ [presenter-arrange],
+ [presenter-arrange-bar] {
+ display: none !important;
+ }
+}
+
/* ---- the panels ---- */
/* --p-now is the width the slide on screen is drawn at, worked out on
every panel from the panels' own box (a container), so the slide
diff --git a/internal/slides/templates/present_notes.html b/internal/slides/templates/present_notes.html
index 1b68958..96176f0 100644
--- a/internal/slides/templates/present_notes.html
+++ b/internal/slides/templates/present_notes.html
@@ -70,20 +70,10 @@
flex-wrap: wrap;
gap: var(--rst-sp-2);
}
- [slides-code] {
- font-size: var(--rst-fs-lg);
- letter-spacing: 0.25em;
- margin: 0;
- }
- [slides-pair] {
- display: flex;
- flex-wrap: wrap;
- gap: var(--rst-sp-4);
- }
- [slides-pair-fields] {
- flex: 1 1 18rem;
- }
-</style>{{end}}
+</style>
+{{- if .Pair}}
+{{template "present-pairing-style"}}
+{{- end}}{{end}}
{{define "content"}}
{{template "page-header" dict "Title" .Title "Sub" .DeckTitle}}
@@ -128,24 +118,10 @@
{{if .Notes}}{{.Notes}}{{else}}<p>{{.NoNotes}}</p>{{end}}
</div>
-{{if .Pair}}
+{{with .Pair}}
<div rst-box>
- {{template "callout" dict "Tone" "info" "Title" .PairTitle "Body" .PairBody}}
- <div slides-pair>
- {{.QR}}
- <div slides-pair-fields>
- <p slides-code>{{.Code}}</p>
- {{/* Hand-written for one attribute, share.html's reason: readonly
- is not in field-text's contract, and the field is here to be
- selected and copied. */}}
- <div rst-field>
- <label rst-field-label for="remote-url">{{.URLLabel}}</label>
- <input rst-input id="remote-url" name="remote-url" type="text"
- value="{{.RemoteURL}}" readonly aria-describedby="remote-url-hint">
- <small rst-field-hint id="remote-url-hint">{{.CodeLabel}} {{.Code}}</small>
- </div>
- </div>
- </div>
+ {{template "callout" dict "Tone" "info" "Title" .Title "Body" .Body}}
+ {{template "present-pairing" .}}
</div>
{{end}}
diff --git a/internal/slides/templates/present_pair.html b/internal/slides/templates/present_pair.html
new file mode 100644
index 0000000..ea1b205
--- /dev/null
+++ b/internal/slides/templates/present_pair.html
@@ -0,0 +1,16 @@
+{{/* present_pair — POST /p/{session}/pair: pairing a phone, from the
+ presenter window's ⋯ menu (spec §5.6, §6 "Who may drive").
+
+ The menu's form posts here into a window of its own
+ (target="slides-pair"), so the presenter window keeps its talk.
+ Each post makes a new remote token and retires the old one; this
+ page is the one time the new one is shown, since only a fingerprint
+ of it is stored, and the answer is never cached. */}}
+{{define "page-head"}}<link rel="stylesheet" href="{{asset "static/slides.css"}}">
+{{template "present-pairing-style"}}{{end}}
+{{define "content"}}
+{{template "page-header" dict "Title" .Title "Sub" .Body}}
+<div rst-box>
+ {{template "present-pairing" .Pair}}
+</div>
+{{end}}
diff --git a/internal/slides/templates/present_pairing.html b/internal/slides/templates/present_pairing.html
new file mode 100644
index 0000000..8eda3c6
--- /dev/null
+++ b/internal/slides/templates/present_pairing.html
@@ -0,0 +1,38 @@
+{{/* present-pairing — the QR, the code and the remote's address, shared
+ by the pairing page (present_pair.html, what the presenter window's
+ ⋯ menu opens) and the old presenter view (present_notes.html, kept
+ by the sessions begun before positions), so the two cannot drift on
+ how a phone is paired.
+
+ The data is presentation.go's pairing. present-pairing-style is
+ the block's own rules, for each page's <head>. */}}
+{{define "present-pairing-style"}}<style>
+ [slides-code] {
+ font-size: var(--rst-fs-lg);
+ letter-spacing: 0.25em;
+ margin: 0;
+ }
+ [slides-pair] {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--rst-sp-4);
+ }
+ [slides-pair-fields] {
+ flex: 1 1 18rem;
+ }
+</style>{{end}}
+{{define "present-pairing"}}<div slides-pair>
+ {{.QR}}
+ <div slides-pair-fields>
+ <p slides-code>{{.Code}}</p>
+ {{/* Hand-written for one attribute, share.html's reason: readonly
+ is not in field-text's contract, and the field is here to be
+ selected and copied. */}}
+ <div rst-field>
+ <label rst-field-label for="remote-url">{{.URLLabel}}</label>
+ <input rst-input id="remote-url" name="remote-url" type="text"
+ value="{{.RemoteURL}}" readonly aria-describedby="remote-url-hint">
+ <small rst-field-hint id="remote-url-hint">{{.CodeLabel}} {{.Code}}</small>
+ </div>
+ </div>
+</div>{{end}}
diff --git a/internal/slides/templates/presenter.html b/internal/slides/templates/presenter.html
index 119f322..fbb8b56 100644
--- a/internal/slides/templates/presenter.html
+++ b/internal/slides/templates/presenter.html
@@ -17,7 +17,11 @@
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. */}}
+ keeps static/present.js for the clock and to follow the session.
+
+ Arrange this window (fixtures/presenter-arrange.mjs) shows the bar
+ under the header and makes the panels movable on their grid; it
+ needs the script, and the bar stays hidden without it. */}}
{{define "page-head"}}<link rel="stylesheet" href="{{asset "static/slides.css"}}">
<link rel="stylesheet" href="{{asset "static/presenter.css"}}">
<style>{{.ArrangeCSS}}</style>
@@ -106,6 +110,10 @@
{{template "empty-state" dict "Title" .EmptyTitle "Body" .EmptyBody}}
</div>
{{else}}
+<div presenter-arrange-bar hidden><span>{{.ArrangeHint}}</span>
+ <button type="button" presenter-arrange-reset>{{.ArrangeReset}}</button>
+ <button type="button" presenter-arrange-done>{{.ArrangeDone}}</button>
+</div>
<div presenter-panels>
<div presenter-panel="now">
<div presenter-fit>
diff --git a/internal/slidestest/browser_present_test.go b/internal/slidestest/browser_present_test.go
index a7e0fee..d521716 100644
--- a/internal/slidestest/browser_present_test.go
+++ b/internal/slidestest/browser_present_test.go
@@ -19,6 +19,7 @@ import (
"amadan.net/rastrillo/rastrillo/harness"
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
+ "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/kb"
)
@@ -36,7 +37,7 @@ func TestBrowserProjectorFitsTheViewport(t *testing.T) {
t.Fatalf("the deck list links no deck: %q", deck)
}
- session, token := browserPresent(t, rig, served, deck)
+ session, token := browserPresent(t, rig, deck)
for _, viewport := range []struct{ width, height int }{{1920, 1080}, {1280, 720}} {
t.Run(fmt.Sprintf("%dx%d", viewport.width, viewport.height), func(t *testing.T) {
@@ -77,12 +78,12 @@ func TestBrowserProjectorFitsTheViewport(t *testing.T) {
var sessionLocation = regexp.MustCompile(`^/p/[23456789abcdefghjkmnpqrstuvwxyz]{10}$`)
// browserPresent presses Present on the deck the browser is signed in
-// to, waits for the slide it lands on, and pairs a phone through the
-// row (pairThroughRow). It returns the session's path, /p/{session},
-// and the remote token.
-func browserPresent(t *testing.T, rig *harness.Rig, served *testApp, deck string) (string, string) {
+// to, waits for the slide it lands on, and pairs a phone as the
+// presenter's browser does (POST /p/{session}/pair, signed in). It
+// returns the session's path, /p/{session}, and the remote token.
+func browserPresent(t *testing.T, rig *harness.Rig, deck string) (string, string) {
t.Helper()
- var path string
+ var path, paired string
rig.Run(
chromedp.Navigate(rig.Origin+deck+"?slide=1"),
chromedp.Click(`form[action$="/present"] button`, chromedp.ByQuery),
@@ -92,7 +93,9 @@ func browserPresent(t *testing.T, rig *harness.Rig, served *testApp, deck string
if !sessionLocation.MatchString(path) {
t.Fatalf("Present landed on %q, want /p/{session}", path)
}
- return path, pairThroughRow(t, served, path[len("/p/"):])
+ rig.Run(chromedp.Evaluate(`fetch(location.pathname + '/pair', { method: 'POST' }).then(r => r.text())`, &paired,
+ func(p *runtime.EvaluateParams) *runtime.EvaluateParams { return p.WithAwaitPromise(true) }))
+ return path, tokenOn(t, paired)
}
// TestBrowserPresentingScreensHoldStill: the presenter view and the
@@ -120,7 +123,7 @@ func TestBrowserPresentingScreensHoldStill(t *testing.T) {
t.Fatalf("the deck list links no deck: %q", deck)
}
- session, token := browserPresent(t, rig, served, deck)
+ session, token := browserPresent(t, rig, deck)
rig.Run(chromedp.Navigate(rig.Origin + session + "/notes?t=" + token))
// holdsStill waits for the page to settle and the stream to have
diff --git a/internal/slidestest/present_pair_test.go b/internal/slidestest/present_pair_test.go
new file mode 100644
index 0000000..fe40a33
--- /dev/null
+++ b/internal/slidestest/present_pair_test.go
@@ -0,0 +1,168 @@
+package slidestest
+
+// Pairing a phone from the presenter window's ⋯ menu (Task 13, spec §6
+// "Who may drive"): POST /p/{session}/pair, for the signed-in presenter
+// alone, makes a new remote token, retires the old one, and answers
+// with the code, the remote's address and its QR. Ending the talk ends
+// the phone and the follow link with it.
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+)
+
+// TestPairingReplacesTheOldToken: pairing answers with a fresh token,
+// shown once and never cached, and the phone holding the old one
+// drives and reads nothing from then on.
+func TestPairingReplacesTheOldToken(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ session, old := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
+ press(t, a, session, old, op(t, "next"), nil)
+
+ rec := post(t, a, "/p/"+session+"/pair", nil, cookies...)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("POST /p/%s/pair: status %d, want 200\n%s", session, rec.Code, rec.Body)
+ }
+ if cc := rec.Header().Get("Cache-Control"); !strings.Contains(cc, "no-store") {
+ t.Errorf("the pairing page is cacheable: Cache-Control %q", cc)
+ }
+ page := rec.Body.String()
+ fresh := tokenOn(t, page)
+ if fresh == old {
+ t.Fatalf("pairing kept the old token")
+ }
+ code := sessionCode(t, a, session)
+ remoteURL := testOrigin + "/r/" + code + "?t=" + fresh
+ if !strings.Contains(page, `value="`+remoteURL+`"`) {
+ t.Errorf("the pairing page does not show the remote address %q:\n%s", remoteURL, page)
+ }
+ if codeOn(t, page) != code {
+ t.Errorf("the pairing page shows code %q, want %q", codeOn(t, page), code)
+ }
+ if !strings.Contains(page, "slides-qr") || !strings.Contains(page, code+`"`) {
+ t.Errorf("the pairing page carries no QR naming the code:\n%s", page)
+ }
+ if !strings.Contains(page, "Pairing another phone from the menu retires this one.") {
+ t.Errorf("the pairing page does not say what pairing again does:\n%s", page)
+ }
+
+ // The old phone is retired: it neither drives nor reads.
+ if rec := pressRequest(t, a, session, old, op(t, "next"), nil); rec.Code != http.StatusNotFound {
+ t.Errorf("a press with the retired token: status %d, want 404", rec.Code)
+ }
+ mustGet(t, a, "/p/"+session+"/remote?t="+url.QueryEscape(old), http.StatusNotFound, nil)
+ if rec := get(t, a, "/r/"+code+"?t="+url.QueryEscape(old)); rec.Code == http.StatusSeeOther {
+ t.Errorf("the retired token still pairs through /r/%s", code)
+ }
+
+ // The new one does both.
+ press(t, a, session, fresh, op(t, "next"), nil)
+ mustGet(t, a, "/p/"+session+"/remote?t="+url.QueryEscape(fresh), http.StatusOK, nil)
+ mustGet(t, a, "/r/"+code+"?t="+url.QueryEscape(fresh), http.StatusSeeOther, nil)
+ if _, step, _ := rowPosition(t, a, session); step != 2 {
+ t.Errorf("the talk is at step %d, want 2", step)
+ }
+
+ // And the presenter's own window never needed a token at all.
+ press(t, a, session, "", op(t, "next"), cookies)
+}
+
+// TestOnlyThePresenterMayPair: nobody but the signed-in presenter may
+// make a token: not a stranger, not the phone (a token is not a
+// presenter), not someone else signed in, not another site through the
+// presenter's browser. Each refusal leaves the paired phone paired.
+func TestOnlyThePresenterMayPair(t *testing.T) {
+ a := newSharedApp(t)
+ mine := signedIn(t, a, allowedAddress)
+ theirs := signedIn(t, a, otherAddress)
+ session, token := startPresenting(t, a, stepsDeck(t, a, mine), mine)
+ target := "/p/" + session + "/pair"
+
+ if rec := post(t, a, target, nil); rec.Code != http.StatusNotFound {
+ t.Errorf("pairing by nobody: status %d, want 404", rec.Code)
+ }
+ if rec := post(t, a, target, url.Values{"t": {token}}); rec.Code != http.StatusNotFound {
+ t.Errorf("pairing with the remote token: status %d, want 404", rec.Code)
+ }
+ if rec := post(t, a, target, nil, theirs...); rec.Code != http.StatusNotFound {
+ t.Errorf("pairing by somebody else signed in: status %d, want 404", rec.Code)
+ }
+ if rec := post(t, a, "/p/2222222222/pair", nil, mine...); rec.Code != http.StatusNotFound {
+ t.Errorf("pairing a session that never was: status %d, want 404", rec.Code)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, target, nil)
+ req.Header.Set("Origin", "https://elsewhere.example")
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ for _, c := range mine {
+ req.AddCookie(c)
+ }
+ cross := httptest.NewRecorder()
+ a.ServeHTTP(cross, req)
+ if cross.Code != http.StatusForbidden {
+ t.Errorf("a cross-site pairing with the presenter's cookie: status %d, want 403", cross.Code)
+ }
+
+ // Nothing refused retired the phone.
+ press(t, a, session, token, op(t, "next"), nil)
+
+ // A talk that is over pairs nothing: it is gone.
+ command(t, a, session, "end", token, "", nil)
+ if rec := post(t, a, target, nil, mine...); rec.Code != http.StatusGone {
+ t.Errorf("pairing an ended talk: status %d, want 410", rec.Code)
+ }
+}
+
+// endForm is the window's End presenting form: its op and press id.
+var endForm = regexp.MustCompile(`<input type="hidden" name="op" value="end">\s*<input type="hidden" name="press" value="([^"]+)">`)
+
+// TestEndingTheTalkEndsThePhone: End presenting in the window's menu,
+// posted as the window posts it (by the presenter's cookie, no token),
+// ends the talk, and the paired phone and the follow link end with it.
+func TestEndingTheTalkEndsThePhone(t *testing.T) {
+ a := newApp(t)
+ cookies := signedIn(t, a, allowedAddress)
+ deck := stepsDeck(t, a, cookies)
+ share := "/s/" + mintShareLink(t, a, deck, cookies)
+ session, token := startPresenting(t, a, deck, cookies)
+ mustGet(t, a, "/p/"+session+"/remote?t="+url.QueryEscape(token), http.StatusOK, nil)
+ mustGet(t, a, share+"?follow=1", http.StatusOK, nil)
+
+ window := mustGet(t, a, "/p/"+session+"/notes", http.StatusOK, cookies).Body.String()
+ m := endForm.FindStringSubmatch(window)
+ if m == nil {
+ t.Fatalf("the window has no End presenting form:\n%s", window)
+ }
+ form := url.Values{"op": {"end"}, "press": {m[1]}}
+ req := httptest.NewRequest(http.MethodPost, "/p/"+session+"/command", strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", testOrigin)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ req.Header.Set("Referer", testOrigin+"/p/"+session+"/notes")
+ for _, c := range cookies {
+ req.AddCookie(c)
+ }
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, req)
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("End presenting: status %d, want 303\n%s", rec.Code, rec.Body)
+ }
+
+ if rec := getHTML(t, a, "/p/"+session+"/remote?t="+url.QueryEscape(token)); rec.Code != http.StatusGone {
+ t.Errorf("the phone after the talk ended: status %d, want 410", rec.Code)
+ }
+ if rec := command(t, a, session, "next", token, "", nil); rec.Code != http.StatusGone {
+ t.Errorf("a press from the phone after the talk ended: status %d, want 410", rec.Code)
+ }
+ if rec := get(t, a, share+"?follow=1"); rec.Code != http.StatusSeeOther {
+ t.Errorf("following an ended talk: status %d, want 303 back to the deck", rec.Code)
+ }
+ if strings.Contains(mustGet(t, a, share, http.StatusOK, nil).Body.String(), "Follow the presenter") {
+ t.Errorf("the follow offer outlives the talk")
+ }
+}
diff --git a/internal/slidestest/present_position_test.go b/internal/slidestest/present_position_test.go
index 76ac5f9..4803bb9 100644
--- a/internal/slidestest/present_position_test.go
+++ b/internal/slidestest/present_position_test.go
@@ -359,7 +359,7 @@ func TestARevokedTokenDrivesNothing(t *testing.T) {
cookies := signedIn(t, a, allowedAddress)
session, old := startPresenting(t, a, stepsDeck(t, a, cookies), cookies)
press(t, a, session, old, op(t, "next"), nil)
- pairThroughRow(t, a, session)
+ pairPhone(t, a, session, cookies)
_, _, before := rowPosition(t, a, session)
if rec := pressRequest(t, a, session, old, op(t, "next"), nil); rec.Code != http.StatusNotFound {
diff --git a/internal/slidestest/present_test.go b/internal/slidestest/present_test.go
index be285c5..5491859 100644
--- a/internal/slidestest/present_test.go
+++ b/internal/slidestest/present_test.go
@@ -3,10 +3,6 @@ package slidestest
import (
"bufio"
"context"
- "crypto/rand"
- "crypto/sha256"
- "encoding/base64"
- "encoding/hex"
"net/http"
"net/http/httptest"
"net/url"
@@ -68,7 +64,8 @@ func preDeploy(t *testing.T, a *testApp, session string) {
}
// startPresenting presses Present on a deck and returns the session's
-// sqid and a freshly paired remote token (pairThroughRow).
+// sqid and a freshly paired remote token: the presenter pairs a phone
+// from the window's menu (pairPhone).
func startPresenting(t *testing.T, a *testApp, deckPath string, cookies []*http.Cookie) (string, string) {
t.Helper()
rec := post(t, a, deckPath+"/present", nil, cookies...)
@@ -80,30 +77,34 @@ func startPresenting(t *testing.T, a *testApp, deckPath string, cookies []*http.
if m == nil {
t.Fatalf("POST %s/present: Location = %q, want /p/{session}", deckPath, loc)
}
- return m[1], pairThroughRow(t, a, m[1])
+ return m[1], pairPhone(t, a, m[1], cookies)
}
-// pairThroughRow pairs a phone with a session the interim way: it mints
-// a remote token and writes the token's hash straight onto the row, as
-// Present used to, and returns the token. Replacing the session's token
-// is also how a test revokes the old one.
-//
-// It is the suite's one way to get a remote token until
-// POST /p/{session}/pair exists (Task 13), which replaces this body.
-func pairThroughRow(t *testing.T, a *testApp, session string) string {
+// pairPhone pairs a phone as the presenter does, from the window's ⋯
+// menu: POST /p/{session}/pair, signed in, and the token read off the
+// page it answers. Pairing again is also how a test retires the old
+// token.
+func pairPhone(t *testing.T, a *testApp, session string, cookies []*http.Cookie) string {
t.Helper()
- raw := make([]byte, 32)
- if _, err := rand.Read(raw); err != nil {
- t.Fatalf("mint a remote token: %v", err)
- }
- token := base64.RawURLEncoding.EncodeToString(raw)
- sum := sha256.Sum256([]byte(token))
- res := a.db.G.Exec("UPDATE presentations SET remote_token_hash = ? WHERE sqid = ?",
- hex.EncodeToString(sum[:]), session)
- if res.Error != nil || res.RowsAffected != 1 {
- t.Fatalf("pair a phone with %s: %v (%d rows)", session, res.Error, res.RowsAffected)
- }
- return token
+ rec := post(t, a, "/p/"+session+"/pair", nil, cookies...)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("POST /p/%s/pair: status %d, want 200\n%s", session, rec.Code, rec.Body)
+ }
+ return tokenOn(t, rec.Body.String())
+}
+
+// remoteToken finds the token in the remote's address on a pairing
+// page: /r/{code}?t={token}, the token base64url.
+var remoteToken = regexp.MustCompile(`/r/[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}\?t=([A-Za-z0-9_-]{43})"`)
+
+// tokenOn reads the remote token off a pairing page.
+func tokenOn(t *testing.T, page string) string {
+ t.Helper()
+ m := remoteToken.FindStringSubmatch(page)
+ if m == nil {
+ t.Fatalf("no remote address on the pairing page:\n%s", page)
+ }
+ return m[1]
}
// command posts one remote command as the phone does: a form, with the
diff --git a/internal/slidestest/presenter_arrange_browser_test.go b/internal/slidestest/presenter_arrange_browser_test.go
new file mode 100644
index 0000000..0576d47
--- /dev/null
+++ b/internal/slidestest/presenter_arrange_browser_test.go
@@ -0,0 +1,510 @@
+//go:build browser
+
+// Arranging the presenter window, its ⋯ menu, and pairing a phone from
+// it (Task 13, spec §5.4, §5.6 and §6 "Who may drive"). The panels move
+// and resize on the 12×12 grid by pointer and by keyboard, never leave
+// the window, never overlap, and are remembered in the cookie the
+// server draws the first paint from.
+package slidestest
+
+import (
+ "context"
+ "fmt"
+ "math"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/cdproto/input"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ "github.com/chromedp/chromedp/kb"
+)
+
+// arrangeRig is a talk on stepsDeck, with the browser signed in as its
+// presenter: the window is theirs by the cookie, no token in it.
+type arrangeRig struct {
+ rig *harness.Rig
+ app *testApp
+ cookies []*http.Cookie
+ session, token string
+ window string
+}
+
+func newArrangeRig(t *testing.T) *arrangeRig {
+ t.Helper()
+ rig, app := newRigApp(t, nil)
+ cookies := signedIn(t, app, allowedAddress)
+ var set []chromedp.Action
+ for _, c := range cookies {
+ set = append(set, network.SetCookie(c.Name, c.Value).WithURL(rig.Origin+"/").
+ WithHTTPOnly(c.HttpOnly).WithSecure(c.Secure).WithSameSite(network.CookieSameSiteLax))
+ }
+ set = append(set, emulation.SetDeviceMetricsOverride(1280, 720, 1, false))
+ rig.Run(set...)
+ session, token := startPresenting(t, app, stepsDeck(t, app, cookies), cookies)
+ return &arrangeRig{rig: rig, app: app, cookies: cookies, session: session, token: token,
+ window: rig.Origin + "/p/" + session + "/notes"}
+}
+
+// prefs sets the window's cookie as its script writes it.
+func (ar *arrangeRig) prefs(value string) {
+ ar.rig.Run(network.SetCookie("slides-presenter", url.QueryEscape(value)).
+ WithURL(ar.rig.Origin + "/p/").WithPath("/p").WithSameSite(network.CookieSameSiteLax))
+}
+
+// open loads the window and waits for its script to have the talk.
+func (ar *arrangeRig) open(t *testing.T) {
+ t.Helper()
+ ar.rig.Run(chromedp.Navigate(ar.window),
+ waitFor(`document.querySelector('[presenter]')?.getAttribute('data-loaded') === 'all'`))
+}
+
+// arrange opens the ⋯ menu and chooses Arrange this window.
+func (ar *arrangeRig) arrange(t *testing.T) {
+ t.Helper()
+ ar.rig.Run(
+ chromedp.Click(`[presenter-more]`, chromedp.ByQuery),
+ waitFor(`document.querySelector('[presenter-more-menu]').open`),
+ chromedp.Click(`[presenter-arrange]`, chromedp.ByQuery),
+ waitFor(`document.querySelector('[presenter]').hasAttribute('data-arranging') && !document.querySelector('[presenter-arrange-bar]').hidden`))
+}
+
+// keys presses key n times, with Shift when shift is true.
+func keys(key string, n int, shift bool) chromedp.Action {
+ return chromedp.ActionFunc(func(ctx context.Context) error {
+ for range n {
+ var opts []chromedp.KeyOption
+ if shift {
+ opts = append(opts, chromedp.KeyModifiers(input.ModifierShift))
+ }
+ if err := chromedp.KeyEvent(key, opts...).Do(ctx); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
+// focus puts the keyboard on a panel.
+func focusPanel(name string) chromedp.Action {
+ return chromedp.Evaluate(`document.querySelector('[presenter-panel="`+name+`"]').focus()`, nil)
+}
+
+// cookieValue is the window's cookie, decoded, or "".
+const cookieValueJS = `(() => { const m = document.cookie.split('; ').find(c => c.startsWith('slides-presenter='));
+ return m ? decodeURIComponent(m.slice('slides-presenter='.length)) : '' })()`
+
+type panelRect struct{ L, T, R, B float64 }
+
+func (r panelRect) String() string { return fmt.Sprintf("(%.1f,%.1f)-(%.1f,%.1f)", r.L, r.T, r.R, r.B) }
+
+func near(a, b panelRect) bool {
+ return math.Abs(a.L-b.L) <= 0.5 && math.Abs(a.T-b.T) <= 0.5 && math.Abs(a.R-b.R) <= 0.5 && math.Abs(a.B-b.B) <= 0.5
+}
+
+// panelRects is each panel and each frame, by name.
+const panelRectsJS = `(() => { const out = {};
+ for (const n of ['now', 'next', 'notes']) {
+ const r = document.querySelector('[presenter-panel="' + n + '"]').getBoundingClientRect();
+ out[n] = { L: r.left, T: r.top, R: r.right, B: r.bottom };
+ const f = document.querySelector('[presenter-panel="' + n + '"] [presenter-frame]');
+ if (f) { const q = f.getBoundingClientRect(); out[n + '-frame'] = { L: q.left, T: q.top, R: q.right, B: q.bottom } }
+ const fit = document.querySelector('[presenter-panel="' + n + '"] [presenter-fit]');
+ if (fit) { const q = fit.getBoundingClientRect(); out[n + '-fit'] = { L: q.left, T: q.top, R: q.right, B: q.bottom } }
+ }
+ return out })()`
+
+func (ar *arrangeRig) rects(t *testing.T) map[string]panelRect {
+ t.Helper()
+ var out map[string]panelRect
+ ar.rig.Run(chromedp.Evaluate(panelRectsJS, &out))
+ return out
+}
+
+// inside fails for a document that scrolls or a box outside the window.
+func inside(t *testing.T, ar *arrangeRig, what string) {
+ t.Helper()
+ var g presenterGeometry
+ ar.rig.Run(chromedp.Evaluate(presenterGeometryJS, &g))
+ var bar presenterBox
+ ar.rig.Run(chromedp.Evaluate(`(() => { const b = document.querySelector('[presenter-arrange-bar]'); if (!b || b.hidden) return { name: '' };
+ const r = b.getBoundingClientRect(); return { name: 'bar', l: r.left, t: r.top, r: r.right, b: r.bottom } })()`, &bar))
+ if bar.Name != "" {
+ g.Boxes = append(g.Boxes, bar)
+ }
+ if g.SH != g.VH || g.SW != g.VW || g.BSH > g.VH || g.BSW > g.VW || g.ScrollY != 0 {
+ t.Errorf("%s: the document is %.0f×%.0f (body %.0f×%.0f, scrolled %.0f) in a %.0f×%.0f window",
+ what, g.SW, g.SH, g.BSW, g.BSH, g.ScrollY, g.VW, g.VH)
+ }
+ if len(g.Boxes) < 6 {
+ t.Fatalf("%s: %d boxes measured, want the header, three panels and two frames", what, len(g.Boxes))
+ }
+ for _, b := range g.Boxes {
+ if b.L < 0 || b.T < 0 || b.R > g.VW || b.B > g.VH || b.R <= b.L || b.B <= b.T {
+ t.Errorf("%s: %s at (%.0f,%.0f)-(%.0f,%.0f) is not inside the %.0f×%.0f window",
+ what, b.Name, b.L, b.T, b.R, b.B, g.VW, g.VH)
+ }
+ }
+}
+
+// overlapping is two panels sharing any area, beyond a rounding.
+func overlapping(a, b panelRect) bool {
+ return a.L < b.R-1 && b.L < a.R-1 && a.T < b.B-1 && b.T < a.B-1
+}
+
+// TestArrangedPanelsStayInsideTheWindow: however the panels are
+// arranged, at each of the ten window sizes nothing leaves the window
+// and the document never scrolls; the panels never overlap; Next fills
+// its own panel. Below 720×560 the arrangement is ignored and the
+// panels stack, and Arrange is not offered there. While arranging,
+// with the bar showing, the window still holds.
+func TestArrangedPanelsStayInsideTheWindow(t *testing.T) {
+ ar := newArrangeRig(t)
+ arrangements := []string{
+ "fit.24.0,0,4,4;0,4,4,4;8,0,4,12",
+ "fit.24.10,10,2,2;0,0,2,2;5,5,2,2",
+ "scroll.48.0,0,12,6;0,6,6,6;6,6,6,6",
+ }
+ for _, size := range presenterSizes {
+ stacked := size.w < 720 || size.h < 560
+ t.Run(fmt.Sprintf("%dx%d", size.w, size.h), func(t *testing.T) {
+ ar.rig.Run(emulation.SetDeviceMetricsOverride(size.w, size.h, 1, false))
+ for _, prefs := range arrangements {
+ ar.prefs(prefs)
+ ar.open(t)
+ inside(t, ar, prefs)
+ r := ar.rects(t)
+ if stacked {
+ if !(r["now"].B <= r["next"].T+1 && r["next"].B <= r["notes"].T+1) {
+ t.Errorf("%s: stacked panels are not now, next, notes: %v %v %v", prefs, r["now"], r["next"], r["notes"])
+ }
+ continue
+ }
+ for _, pair := range [][2]string{{"now", "next"}, {"now", "notes"}, {"next", "notes"}} {
+ if overlapping(r[pair[0]], r[pair[1]]) {
+ t.Errorf("%s: %s %v and %s %v overlap", prefs, pair[0], r[pair[0]], pair[1], r[pair[1]])
+ }
+ }
+ fit, frame := r["next-fit"], r["next-frame"]
+ want := math.Min(fit.R-fit.L, (fit.B-fit.T)*16/9)
+ if got := frame.R - frame.L; math.Abs(got-want) > 1 {
+ t.Errorf("%s: Next is %.1fpx wide in a panel with room for %.1fpx: an arranged Next fills its panel", prefs, got, want)
+ }
+ }
+
+ // Arranging, with the bar over the panels.
+ ar.prefs(arrangements[0])
+ ar.open(t)
+ var shown bool
+ ar.rig.Run(chromedp.Evaluate(`getComputedStyle(document.querySelector('[presenter-arrange]')).display !== 'none'`, &shown))
+ if stacked {
+ if shown {
+ t.Errorf("Arrange is offered where the panels stack and the arrangement is ignored")
+ }
+ return
+ }
+ if !shown {
+ t.Fatalf("Arrange is not offered at %dx%d", size.w, size.h)
+ }
+ ar.arrange(t)
+ inside(t, ar, "arranging")
+ ar.rig.Run(keys(kb.Escape, 1, false),
+ waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`))
+ })
+ }
+}
+
+// TestArrangeByKeyboardAndPointer: a focused panel moves a cell with an
+// arrow key and resizes with Shift and an arrow, so arranging is not
+// mouse-only; dragging a panel moves it and dragging its corner resizes
+// it, snapped to the grid. Done writes the cookie, keeping the notes'
+// part. While arranging, only the clicker's keys move the talk.
+func TestArrangeByKeyboardAndPointer(t *testing.T) {
+ ar := newArrangeRig(t)
+ ar.prefs("scroll.30.0,0,7,8;0,8,7,4;7,0,5,12")
+ ar.open(t)
+ ar.arrange(t)
+
+ var focused string
+ ar.rig.Run(chromedp.Evaluate(`document.activeElement.getAttribute('presenter-panel') || ''`, &focused))
+ if focused != "now" {
+ t.Errorf("arranging puts the focus on %q, want the first panel, now", focused)
+ }
+ // Now 7×8 to 5×5; Next up three cells into the room that leaves.
+ ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 2, true), keys(kb.ArrowUp, 3, true),
+ focusPanel("next"), keys(kb.ArrowUp, 3, false))
+
+ // While arranging, B blacks nothing and the arrows move no slide;
+ // the clicker's PageDown still presses.
+ _, step, _ := rowPosition(t, ar.app, ar.session)
+ ar.rig.Run(keys("b", 1, false), keys(kb.ArrowRight, 1, false), keys(kb.ArrowLeft, 1, false))
+ time.Sleep(300 * time.Millisecond)
+ if _, now, _ := rowPosition(t, ar.app, ar.session); now != step {
+ t.Errorf("a key while arranging moved the talk from step %d to %d", step, now)
+ }
+ var black string
+ ar.rig.Run(chromedp.Evaluate(`document.querySelector('[presenter]').getAttribute('data-blackout')`, &black))
+ if black != "false" {
+ t.Errorf("B while arranging blacked the screen")
+ }
+ ar.rig.Run(keys(kb.PageDown, 1, false), waitFor(`document.querySelector('[presenter]').getAttribute('data-step') === '`+fmt.Sprint(step+1)+`'`))
+
+ // The pointer: the notes' corner dragged two cells left narrows
+ // them, and Now dragged a little over a cell right snaps to one.
+ var cell struct{ W, H float64 }
+ ar.rig.Run(chromedp.Evaluate(`(() => { const r = document.querySelector('[presenter-panels]').getBoundingClientRect(); return { W: r.width / 12, H: r.height / 12 } })()`, &cell))
+ drag := func(sel string, dx, dy float64) chromedp.Action {
+ return chromedp.ActionFunc(func(ctx context.Context) error {
+ var at struct{ X, Y float64 }
+ if err := chromedp.Evaluate(`(() => { const r = document.querySelector('`+sel+`').getBoundingClientRect(); return { X: r.left + r.width / 2, Y: r.top + r.height / 2 } })()`, &at).Do(ctx); err != nil {
+ return err
+ }
+ if err := input.DispatchMouseEvent(input.MousePressed, at.X, at.Y).WithButton(input.Left).WithButtons(1).WithClickCount(1).Do(ctx); err != nil {
+ return err
+ }
+ for i := 1; i <= 8; i++ {
+ f := float64(i) / 8
+ if err := input.DispatchMouseEvent(input.MouseMoved, at.X+dx*f, at.Y+dy*f).WithButton(input.Left).WithButtons(1).Do(ctx); err != nil {
+ return err
+ }
+ }
+ return input.DispatchMouseEvent(input.MouseReleased, at.X+dx, at.Y+dy).WithButton(input.Left).WithButtons(0).WithClickCount(1).Do(ctx)
+ })
+ }
+ ar.rig.Run(drag(`[presenter-panel="notes"] [presenter-arrange-handle]`, -2*cell.W, 0))
+ ar.rig.Run(drag(`[presenter-panel="now"]`, 1.2*cell.W, 0))
+
+ ar.rig.Run(chromedp.Click(`[presenter-arrange-done]`, chromedp.ByQuery),
+ waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`))
+ var saved string
+ ar.rig.Run(chromedp.Evaluate(cookieValueJS, &saved))
+ if want := "scroll.30.1,0,5,5;0,5,7,4;7,0,3,12"; saved != want {
+ t.Errorf("Done saved %q, want %q", saved, want)
+ }
+}
+
+// TestArrangeEscapeLeavesWithoutSaving: Esc puts the panels back where
+// arranging found them and writes nothing.
+func TestArrangeEscapeLeavesWithoutSaving(t *testing.T) {
+ ar := newArrangeRig(t)
+ ar.open(t)
+ before := ar.rects(t)
+ ar.arrange(t)
+ ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 3, true))
+ if near(ar.rects(t)["now"], before["now"]) {
+ t.Fatalf("Shift+ArrowLeft did not narrow Now")
+ }
+ ar.rig.Run(keys(kb.Escape, 1, false), waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`))
+ after := ar.rects(t)
+ for _, n := range []string{"now", "next", "notes"} {
+ if !near(before[n], after[n]) {
+ t.Errorf("after Esc %s is at %v, was %v", n, after[n], before[n])
+ }
+ }
+ var saved string
+ ar.rig.Run(chromedp.Evaluate(cookieValueJS, &saved))
+ if saved != "" {
+ t.Errorf("Esc wrote the cookie: %q", saved)
+ }
+}
+
+// TestArrangeResetReturnsTheDefault: Reset puts the panels where a
+// window with no cookie has them, Next half of Now again, and writes it,
+// keeping the notes' choice.
+func TestArrangeResetReturnsTheDefault(t *testing.T) {
+ ar := newArrangeRig(t)
+ ar.open(t)
+ def := ar.rects(t)
+
+ ar.prefs("scroll.30.0,0,4,4;0,4,4,4;8,0,4,12")
+ ar.open(t)
+ if near(ar.rects(t)["now"], def["now"]) {
+ t.Fatalf("the arranged window looks like the default")
+ }
+ ar.arrange(t)
+ ar.rig.Run(chromedp.Click(`[presenter-arrange-reset]`, chromedp.ByQuery))
+ var saved string
+ ar.rig.Run(chromedp.Evaluate(cookieValueJS, &saved))
+ if want := "scroll.30.0,0,7,8;0,8,7,4;7,0,5,12"; saved != want {
+ t.Errorf("Reset saved %q, want %q", saved, want)
+ }
+ ar.rig.Run(chromedp.Click(`[presenter-arrange-done]`, chromedp.ByQuery),
+ waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`))
+ check := func(when string) {
+ got := ar.rects(t)
+ for _, n := range []string{"now", "next", "notes", "now-frame", "next-frame"} {
+ if !near(got[n], def[n]) {
+ t.Errorf("%s: %s is at %v, the default window has it at %v", when, n, got[n], def[n])
+ }
+ }
+ }
+ check("after Reset")
+ ar.open(t)
+ check("reloaded after Reset")
+}
+
+// TestArrangementIsFinalAtFirstPaint: the window the server draws from
+// the cookie, before any script, is the window the arranging left on
+// screen, frames and all.
+func TestArrangementIsFinalAtFirstPaint(t *testing.T) {
+ ar := newArrangeRig(t)
+ ar.open(t)
+ ar.arrange(t)
+ ar.rig.Run(focusPanel("now"), keys(kb.ArrowLeft, 2, true), keys(kb.ArrowUp, 3, true),
+ focusPanel("next"), keys(kb.ArrowUp, 3, false), keys(kb.ArrowDown, 1, true),
+ chromedp.Click(`[presenter-arrange-done]`, chromedp.ByQuery),
+ waitFor(`!document.querySelector('[presenter]').hasAttribute('data-arranging')`))
+ live := ar.rects(t)
+
+ ar.rig.Run(emulation.SetScriptExecutionDisabled(true), chromedp.Navigate(ar.window),
+ chromedp.WaitReady(`[presenter-panel="notes"]`, chromedp.ByQuery))
+ painted := ar.rects(t)
+ ar.rig.Run(emulation.SetScriptExecutionDisabled(false))
+ for _, n := range []string{"now", "next", "notes", "now-frame", "next-frame"} {
+ if !near(live[n], painted[n]) {
+ t.Errorf("%s is at %v as arranged and at %v as first painted", n, live[n], painted[n])
+ }
+ }
+}
+
+// TestTheMenuHasItsSixRows: the ⋯ menu's rows, in the spec's order,
+// each doing what it says: Pair posts to /pair in a window of its own,
+// the slide window opens in its own, Arrange shows the bar in the
+// approved words.
+func TestTheMenuHasItsSixRows(t *testing.T) {
+ ar := newArrangeRig(t)
+ ar.rig.Run(emulation.SetDeviceMetricsOverride(1440, 900, 1, false))
+ ar.open(t)
+ var rows []struct {
+ Label, Tag, Href, Action, Target, Method, Op string
+ Shown bool
+ }
+ ar.rig.Run(chromedp.Click(`[presenter-more]`, chromedp.ByQuery),
+ waitFor(`document.querySelector('[presenter-more-menu]').open`),
+ chromedp.Evaluate(`[...document.querySelectorAll('[presenter-menu] button, [presenter-menu] a')].map(e => {
+ const f = e.closest('form'); const r = e.getBoundingClientRect();
+ return { Label: e.textContent.trim(), Tag: e.tagName.toLowerCase(), Href: e.getAttribute('href') || '',
+ Action: f ? f.getAttribute('action') : '', Target: (f || e).getAttribute('target') || '',
+ Method: f ? f.getAttribute('method') : '', Op: f && f.elements.op ? f.elements.op.value : '',
+ Shown: r.width > 0 && r.height > 0 } })`, &rows))
+ want := []string{"Pair a phone as a remote…", "Open the slide window", "Switch to the full version",
+ "Arrange this window…", "Back to the deck", "End presenting"}
+ if len(rows) != len(want) {
+ t.Fatalf("the menu has %d rows, want %d: %+v", len(rows), len(want), rows)
+ }
+ for i, w := range want {
+ if rows[i].Label != w || !rows[i].Shown {
+ t.Errorf("row %d is %q (shown %v), want %q", i+1, rows[i].Label, rows[i].Shown, w)
+ }
+ }
+ session := "/p/" + ar.session
+ if r := rows[0]; r.Action != session+"/pair" || r.Method != "post" || r.Target != "slides-pair" {
+ t.Errorf("Pair is %+v, want a POST to %s/pair in the window slides-pair", r, session)
+ }
+ if r := rows[1]; r.Href != session || r.Target != "slides-window" {
+ t.Errorf("the slide window row is %+v, want %s in the window slides-window", r, session)
+ }
+ if r := rows[2]; r.Action != session+"/command" || r.Op != "mode" {
+ t.Errorf("the mode row is %+v, want the mode press", r)
+ }
+ if r := rows[3]; r.Tag != "button" {
+ t.Errorf("Arrange is a %s, want a button", r.Tag)
+ }
+ if r := rows[4]; !strings.HasSuffix(r.Href, "/edit") {
+ t.Errorf("Back to the deck goes to %q, want the editor", r.Href)
+ }
+ if r := rows[5]; r.Action != session+"/command" || r.Op != "end" {
+ t.Errorf("End presenting is %+v, want the end press", r)
+ }
+
+ ar.rig.Run(chromedp.Click(`[presenter-arrange]`, chromedp.ByQuery),
+ waitFor(`document.querySelector('[presenter]').hasAttribute('data-arranging')`))
+ var bar struct {
+ Text, Reset, Done string
+ MenuOpen bool
+ }
+ ar.rig.Run(chromedp.Evaluate(`(() => { const b = document.querySelector('[presenter-arrange-bar]');
+ return { Text: b.querySelector('span').textContent, Reset: b.querySelector('[presenter-arrange-reset]').textContent,
+ Done: b.querySelector('[presenter-arrange-done]').textContent, MenuOpen: document.querySelector('[presenter-more-menu]').open } })()`, &bar))
+ if bar.Text != "Drag a panel to move it; drag its corner to resize it." || bar.Reset != "Reset to the default" || bar.Done != "Done" {
+ t.Errorf("the arranging bar says %+v", bar)
+ }
+ if bar.MenuOpen {
+ t.Errorf("the menu stays open while arranging")
+ }
+}
+
+// TestPairingLeavesTheWindowItsTalk: Pair opens the pairing page in a
+// window of its own, with the code, the address and the QR; the
+// presenter window stays where it was and keeps driving, the old phone
+// is retired, and the new one moves the window.
+func TestPairingLeavesTheWindowItsTalk(t *testing.T) {
+ ar := newArrangeRig(t)
+ ar.open(t)
+ ar.rig.Run(keys(kb.ArrowRight, 1, false),
+ waitFor(`document.querySelector('[presenter]').getAttribute('data-step') === '1'`))
+
+ opened := chromedp.WaitNewTarget(ar.rig.Context(), func(info *target.Info) bool {
+ return strings.HasSuffix(info.URL, "/p/"+ar.session+"/pair")
+ })
+ ar.rig.Run(chromedp.Click(`[presenter-more]`, chromedp.ByQuery),
+ waitFor(`document.querySelector('[presenter-more-menu]').open`),
+ chromedp.Click(`[presenter-menu] form[action$="/pair"] button`, chromedp.ByQuery))
+ var id target.ID
+ select {
+ case id = <-opened:
+ case <-time.After(20 * time.Second):
+ t.Fatal("Pair opened no window of its own")
+ }
+ pairCtx, cancel := chromedp.NewContext(ar.rig.Context(), chromedp.WithTargetID(id))
+ defer cancel()
+ var page, code string
+ if err := chromedp.Run(pairCtx, waitFor(`document.querySelector('[slides-qr]')`),
+ chromedp.Evaluate(`document.documentElement.outerHTML`, &page),
+ chromedp.Evaluate(`document.querySelector('[slides-code]').textContent`, &code)); err != nil {
+ t.Fatalf("read the pairing window: %v", err)
+ }
+ fresh := tokenOn(t, page)
+ if code != sessionCode(t, ar.app, ar.session) {
+ t.Errorf("the pairing window shows code %q, not the session's", code)
+ }
+
+ var where struct {
+ Path, Name string
+ Step string
+ MenuOpen bool
+ }
+ ar.rig.Run(chromedp.Evaluate(`({ Path: location.pathname, Name: window.name, Step: document.querySelector('[presenter]').getAttribute('data-step'),
+ MenuOpen: document.querySelector('[presenter-more-menu]').open })`, &where))
+ if where.Path != "/p/"+ar.session+"/notes" || where.Step != "1" {
+ t.Errorf("pairing moved the window: %+v", where)
+ }
+ if where.MenuOpen {
+ t.Errorf("the menu stays open after pairing")
+ }
+
+ if rec := pressRequest(t, ar.app, ar.session, ar.token, op(t, "next"), nil); rec.Code != http.StatusNotFound {
+ t.Errorf("the retired phone still presses: status %d", rec.Code)
+ }
+ // The window still drives, by its presenter being signed in.
+ ar.rig.Run(keys(kb.ArrowRight, 1, false))
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ if _, step, _ := rowPosition(t, ar.app, ar.session); step == 2 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("the window's press after pairing never reached the talk")
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ // And the new phone moves the window.
+ press(t, ar.app, ar.session, fresh, op(t, "next"), nil)
+ ar.rig.Run(waitFor(`document.querySelector('[presenter]').getAttribute('data-step') === '3'`))
+}