Regional transport forum

Ten years of public bike hire

Regional transport forum

Ten years of public bike hire

What a decade of trip data shows

City Transport Team
14 May 2026

The decade in numbers

Trips have grown every year since 2016

Steepest rises: 2018, the station opens; 2022, e-bikes arrive.

0.40.71.21.51.31.82.42.72.93.12016201720182019202020212022202320242025

Who rides

  • Commuters38 · 38%
  • Students27 · 27%
  • Visitors19 · 19%
  • Errands and leisure16 · 16%

Three numbers to remember

3.1mtrips in 2025
412bikes in service
7 minmedian trip time

Stations

Three kinds of station

Row of hire bikes at a street station in Taipei

Taipei: a long row beside the footpath

Docking stations on a cobbled square in Paris

Paris: docks on the square

Hire bikes on a pavement plaza in Milton Keynes

Milton Keynes: bays by the transport hub

Two lanes

A cyclist on a green lane in Chicago

Chicago: a green painted lane

Cyclists on a wide street in Copenhagen

Copenhagen: a lane beside the traffic

Four stations to compare

Paris

Chicago

Brisbane

Seoul

Six cities, six kinds of station

Taipei

Paris

Milton Keynes

Chicago

Brisbane

Seoul

Station pictures with no layout named

How it works

From dock to dock

1Unlock
2Ride
3Dock
4Rebalance
5Service

What every station needs

  • A dock for each bike, with a spare
  • A map and a price list
  • Lighting and a camera
  • A neighbour who agrees to it

What riders ask for

  • Bikes that are there when I arrive
  • A safe lane for the whole trip
  • A price I can work out in advance
  • A dock near the door
  • Help when something breaks

What the analysis used

  • OpenStreetMap
  • Python
  • GitHub
  • Slack

When the city rides

Pick weekday or weekend. The two peaks on a weekday are the commute.

Over to you

Break

Back at 11:15. Coffee is in the foyer.

Talk to your neighbour

Which journey in your town would you swap for a bike if the dock were at the door?

How did you get here today?

Audience pollSingle choice

How did you get here today?

  1. AWalked
  2. BHire bike
  3. COwn bike
  4. DBus or train
  5. ECar
Choose one answer.

Join link appears when the session is live

Ready to open
Cite this page

Cite this page

Lukeš, Dominik (n.d.). ten-years-of-bike-hire. TalkWeaver. https://talkweaver.app/examples/bike-hire-slides/

Where should the next ten stations go?

Audience pollBoard

Where should the next ten stations go?

Add a place and say why in a few words. One idea per card.

  1. Near homes0

  2. Near work and study0

  3. Near transport hubs0

Add up to 5 cards, 140 characters each.

Join link appears when the session is live

Ready to open

Take the survey

Tell us where the next ten stations should go.

example.org/bike-hire/survey

Thank you

Regional transport forum

Thank you

Questions and the survey are at the link

City Transport Team
14 May 2026

Presenter

Slide1 / 5

Next

Then

Notes

`; iframe.addEventListener("load", () => { if (iframe.classList.contains("preview-incoming")) { target.querySelectorAll(":scope > iframe.preview-outgoing").forEach((node) => node.remove()); iframe.classList.remove("preview-incoming"); } fitPreviewIframe(target); pointerOverlay?.refresh(); // The page's place moves when the picture's own fit runs (two frames after load) and // whenever its content is laid out again: follow it. if (staticCurrent) { try { const figure = iframe.contentDocument?.querySelector("figure.slide-embed"); if (figure && iframe.contentWindow?.ResizeObserver) new iframe.contentWindow.ResizeObserver(() => fitPaneEmbed(target)).observe(figure); iframe.contentWindow?.requestAnimationFrame(() => iframe.contentWindow.requestAnimationFrame(() => iframe.contentWindow.requestAnimationFrame(() => fitPaneEmbed(target)))); } catch { /* the picture is being replaced: its successor fits */ } } // A stepped simulation in the preview sits where the audience's does (anchorSimScroll): // the clone carries the baked data-mode-state, so the revealed count is read from it. try { const previewSlide = iframe.contentDocument?.querySelector(".slide.mode-active"); if (previewSlide && previewSlide.querySelector(".sim .sim-scroll")) { const units = Array.from(previewSlide.querySelectorAll(".sim .sim-step")); const shown = units.filter((el) => !["hidden", "fuzzy"].includes(el.getAttribute("data-mode-state"))).length; anchorSimScroll(previewSlide, units, shown); } } catch {} // The Current pane's conversation: the published scroll, and any text still typing. if (isPresenter && target === els.currentPreview) { applySimScroll(); syncSimTyping(); } // F1: on the Current preview, let the presenter select text inside the iframe to highlight. // Events don't cross the iframe boundary, so attach the capture to the iframe's document. if (isPresenter && target === els.currentPreview) { try { iframe.contentDocument?.addEventListener("mouseup", () => { if (highlightArmed) setTimeout(captureHighlightFromPreview, 0); }); } catch {} } }, { once: true }); // The picture is the pane's FIRST frame (the pointer and the highlighter read it as such). // A successor picture waits, hidden, behind the one on show until it has loaded. if (target.querySelector(":scope > iframe.preview-outgoing")) iframe.classList.add("preview-incoming"); if (staticCurrent) target.prepend(iframe); else target.appendChild(iframe); fitPreviewIframe(target); if (previewResizeObserver && target.dataset.previewObserved !== "1") { target.dataset.previewObserved = "1"; previewResizeObserver.observe(target); } } // (The old reveal-aware next-preview decision core and its DOM fact-gathering adapter are // GONE. The Next pane is now a structural fact of the beat index: it ALWAYS renders // beats[i+1] fully revealed. See nextPaneBeat/beatLabel in BEAT_HELPERS and renderPresenter // below; scripts/test-beats-preview.mjs pins the invariant.) // === F2: resizable / smaller next-slide preview ============================================ // The presenter can shrink the right-hand preview column so the CURRENT slide preview grows // and is easier to read. Four steps cycled by the ⤢ button or the "[" key. "medium" is the // baseline layout (no attribute). The choice is remembered for the SESSION in localStorage // (presentation-scoped key), restored when the presenter window opens. Persists nothing about // live presentation state — it is purely a per-presenter UI preference, so it is local to the // presenter window and never broadcast to the audience. const PREVIEW_SIZES = ["large", "medium", "small", "off"]; const previewSizeStorageKey = `html-presentations:${deckId}:preview-size`; function readStoredPreviewSize() { try { const v = localStorage.getItem(previewSizeStorageKey); return PREVIEW_SIZES.includes(v) ? v : "medium"; } catch { return "medium"; } } let previewSize = readStoredPreviewSize(); function setPreviewSize(size) { if (!PREVIEW_SIZES.includes(size)) size = "medium"; previewSize = size; if (els.presenterRoot) { // "medium" is the unstyled baseline → no attribute keeps the default CSS path. if (size === "medium") els.presenterRoot.removeAttribute("data-preview-size"); else els.presenterRoot.setAttribute("data-preview-size", size); // Cycling presets resets any custom drag-divider split back to the preset columns. els.presenterRoot.style.gridTemplateColumns = ""; try { localStorage.removeItem("html-presentations:presenter-split"); } catch { /* private mode */ } } try { localStorage.setItem(previewSizeStorageKey, size); } catch {} // The View menu's Previews row shows the current size pressed, so "off" reads as a state you // can press out of (not a dead end). els.previewSizeOptions?.querySelectorAll("[data-preview-size-option]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.previewSizeOption === size))); // The Next preview box changed size; refit the scaled stage into the new box. if (els.nextPreview) fitPreviewIframe(els.nextPreview); if (els.currentPreview) fitPreviewIframe(els.currentPreview); if (els.followingPreview) fitPreviewIframe(els.followingPreview); } function cyclePreviewSize(delta = 1) { const i = PREVIEW_SIZES.indexOf(previewSize); const next = PREVIEW_SIZES[(i + delta + PREVIEW_SIZES.length) % PREVIEW_SIZES.length]; setPreviewSize(next); } // === NOTES_PLACEMENT_START (ADR-0028 §8 and §9) — pure: scripts/test-presenter-notes-placement.mjs // extracts this block. Where the speaker notes sit in the presenter window, and how they scroll. // "bottom" (notes under the slide, Next and Then beside it) is the default; "sidebar" is the slim // side column; "top-band" (drawn A) and "camera-column" (drawn C) are the teleprompter // placements; "off" hides the notes and gives the space to the current slide. Each placement has // its rules in presenter-notes-placement.css. const NOTES_PLACEMENTS = ["off", "bottom", "sidebar", "top-band", "camera-column"]; const DEFAULT_NOTES_PLACEMENT = "bottom"; const TELEPROMPTER_PLACEMENTS = ["top-band", "camera-column"]; const NOTES_PLACEMENT_LABELS = { off: "off", bottom: "bottom", sidebar: "sidebar", "top-band": "top band", "camera-column": "camera column" }; const NOTES_SCROLL_MODES = ["hand", "auto"]; const NOTES_WPM = { min: 60, max: 220, step: 10, default: 130 }; // One setting for all talks (JSON: placement, scroll, wpm). A talk with "Just this talk" on keeps // its own copy under the override key; no override means the all-talks value. const NOTES_SETTINGS_KEY = "talkweaver:presenter:notes"; function notesOverrideKey(deckId) { return `html-presentations:${deckId}:notes-override`; } function normaliseNotesPlacement(value) { return NOTES_PLACEMENTS.includes(value) ? value : DEFAULT_NOTES_PLACEMENT; } function isTeleprompterPlacement(value) { return TELEPROMPTER_PLACEMENTS.includes(value); } function normaliseNotesWpm(value) { const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN; if (!Number.isFinite(n)) return NOTES_WPM.default; const stepped = Math.round(n / NOTES_WPM.step) * NOTES_WPM.step; return Math.min(NOTES_WPM.max, Math.max(NOTES_WPM.min, stepped)); } function stepNotesWpm(wpm, delta) { return normaliseNotesWpm(normaliseNotesWpm(wpm) + delta * NOTES_WPM.step); } function normaliseNotesSettings(value) { const v = value && typeof value === "object" ? value : {}; return { placement: normaliseNotesPlacement(v.placement), scroll: NOTES_SCROLL_MODES.includes(v.scroll) ? v.scroll : "hand", wpm: normaliseNotesWpm(v.wpm), }; } function parseNotesSettings(text) { if (typeof text !== "string" || !text) return null; try { const v = JSON.parse(text); return v && typeof v === "object" && !Array.isArray(v) ? normaliseNotesSettings(v) : null; } catch { return null; } } // The settings this talk's presenter uses: its override when "Just this talk" is on, otherwise // the all-talks value, otherwise the defaults. Blocked or missing storage reads as the defaults. function readNotesSettings(storage, overrideKey) { let override = null; let all = null; try { override = parseNotesSettings(storage?.getItem(overrideKey)); } catch { /* blocked */ } if (override) return { ...override, justThisTalk: true }; try { all = parseNotesSettings(storage?.getItem(NOTES_SETTINGS_KEY)); } catch { /* blocked */ } return { ...(all || normaliseNotesSettings(null)), justThisTalk: false }; } function readNotesPlacement(storage, overrideKey) { return readNotesSettings(storage, overrideKey).placement; } // "Just this talk" on: only the override is written. Off: the all-talks value is written and // this talk's override is removed. function writeNotesSettings(storage, overrideKey, settings, justThisTalk) { const json = JSON.stringify(normaliseNotesSettings(settings)); try { if (justThisTalk) storage?.setItem(overrideKey, json); else { storage?.setItem(NOTES_SETTINGS_KEY, json); storage?.removeItem(overrideKey); } } catch { /* private mode */ } } // Which of the two optional panels a placement shows for the current slide. The Then preview // gives way to the notes in the sidebar (where both would share one column) and in the // teleprompter placements (which never show Then). function notesPlacementPanels(placement, hasNotes) { const p = normaliseNotesPlacement(placement); if (isTeleprompterPlacement(p)) return { notes: true, then: false }; return { notes: p === "bottom" || (p === "sidebar" && hasNotes), then: p !== "sidebar" || !hasNotes, }; } // J / ⇧J in the top band, bottom and sidebar: the visible lines less one, so the last line read // stays on screen as the first line after the step. function notesBandStep(clientHeight, lineHeight) { if (!(lineHeight > 0) || !(clientHeight > 0)) return 0; const lines = Math.floor(clientHeight / lineHeight + 0.001); return Math.max(1, lines - 1) * lineHeight; } // Automatic scroll counts progress in words: the speed (words a minute) moves it on, and the // placement turns it into a scroll position (top band) or a current paragraph (camera column, // where each paragraph dwells for its words ÷ speed). function countWords(text) { return String(text || "").split(/\s+/).filter(Boolean).length; } function paragraphStarts(wordCounts) { const starts = []; let acc = 0; for (const c of wordCounts) { starts.push(acc); acc += c; } return starts; } function paragraphAtWords(starts, wordsDone) { let i = 0; for (let k = 0; k < starts.length; k++) if (wordsDone >= starts[k]) i = k; return i; } function notesDwellMs(words, wpm) { return (Math.max(0, words) / normaliseNotesWpm(wpm)) * 60000; } function advanceWords(wordsDone, dtMs, wpm, total) { return Math.min(total, wordsDone + (Math.max(0, dtMs) * normaliseNotesWpm(wpm)) / 60000); } // Bottom notes: two columns only when one column overflows, two fit, and the second column gets // at least two lines; otherwise one column (scrolling when it overflows). function bottomNotesColumns({ oneFits, twoFits, secondColumnLines }) { if (oneFits) return 1; return twoFits && secondColumnLines >= 2 ? 2 : 1; } // === NOTES_PLACEMENT_END // A presenter-window preference only: never broadcast to the audience. Presenter windows of // every talk load file:// pages in the app's default session, so they share this localStorage // origin (checked in Electron 42.4.0; see ticket 07's report) and a change in one talk reaches // the others through the storage event below. const notesStorage = (() => { try { return window.localStorage; } catch { return null; } })(); const notesOverrideStorageKey = notesOverrideKey(deckId); let notesSettings = readNotesSettings(notesStorage, notesOverrideStorageKey); let notesPlacement = notesSettings.placement; let notesScroller = null; let notesLayoutApplied = null; function applyNotesSettings(next, { persist = true, rerender = true } = {}) { const settings = { ...normaliseNotesSettings(next), justThisTalk: Boolean(next?.justThisTalk) }; const placementChanged = settings.placement !== notesLayoutApplied; notesSettings = settings; notesPlacement = settings.placement; if (persist) writeNotesSettings(notesStorage, notesOverrideStorageKey, settings, settings.justThisTalk); // The View menu's Notes item says where the notes are and how they scroll. if (els.notesPlacementNow) els.notesPlacementNow.textContent = `Now: ${NOTES_PLACEMENT_LABELS[notesPlacement]}, ${settings.scroll === "auto" ? "automatic" : "by hand"}`; syncNotesMenu(); if (placementChanged) { notesLayoutApplied = notesPlacement; if (els.presenterRoot) { els.presenterRoot.setAttribute("data-notes-placement", notesPlacement); // As with the Preview size: a new placement resets a custom drag-divider split. els.presenterRoot.style.gridTemplateColumns = ""; } // The Then preview may now be needed (bottom/off keep it beside the notes); re-render, then // refit every scaled stage into its new box. if (rerender && isPresenter) renderPresenter(); if (els.nextPreview) fitPreviewIframe(els.nextPreview); if (els.currentPreview) fitPreviewIframe(els.currentPreview); if (els.followingPreview) fitPreviewIframe(els.followingPreview); notesScroller?.reset(); } else { notesScroller?.sync(); } } function setNotesPlacement(placement, rerender = true) { applyNotesSettings({ ...notesSettings, placement: normaliseNotesPlacement(placement) }, { rerender }); } function setNotesScroll(mode) { applyNotesSettings({ ...notesSettings, scroll: mode }); } function stepNotesSpeed(delta) { applyNotesSettings({ ...notesSettings, wpm: stepNotesWpm(notesSettings.wpm, delta) }); } function setNotesJustThisTalk(on) { if (on) { applyNotesSettings({ ...notesSettings, justThisTalk: true }); return; } // Off: drop this talk's copy and follow the all-talks value again (never copy this talk's // choice over the all-talks value). try { notesStorage?.removeItem(notesOverrideStorageKey); } catch { /* private mode */ } applyNotesSettings(readNotesSettings(notesStorage, notesOverrideStorageKey), { persist: false }); } function syncNotesMenu() { const menu = els.notesMenu; if (!menu) return; menu.querySelectorAll("[data-notes-placement-option]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.notesPlacementOption === notesPlacement))); menu.querySelectorAll("[data-notes-scroll-option]").forEach((b) => b.setAttribute("aria-pressed", String(b.dataset.notesScrollOption === notesSettings.scroll))); if (els.notesJustThisTalk) els.notesJustThisTalk.checked = notesSettings.justThisTalk; if (els.notesMenuScroll) els.notesMenuScroll.hidden = !isTeleprompterPlacement(notesPlacement); if (els.notesWpm) els.notesWpm.textContent = String(notesSettings.wpm); } function toggleNotesMenu(force) { const menu = els.notesMenu; if (!menu) return; const open = force != null ? Boolean(force) : menu.hidden; if (!open && menu.contains(document.activeElement)) els.presenterMenuView?.focus(); menu.hidden = !open; // The Notes menu opens from View and hangs under it (round-2 drawing, notes-menu-*): View // shows pressed while it is open. els.presenterMenuView?.setAttribute("aria-expanded", String(open)); if (open) syncNotesMenu(); } function notesMenuOpen() { return Boolean(els.notesMenu && !els.notesMenu.hidden); } // The notes scroller: J / ⇧J steps, the automatic scroll, the "more below" cue, the camera // column's reading line and the bottom placement's column choice. reset() on every slide // arrival and placement change (notes back to the top); sync() when the scroll mode or speed // changes; step(±1) for J / ⇧J; togglePause() for a click on the notes. function createNotesScroller(panel, body, getSettings) { let blocks = []; let counts = []; let starts = []; let total = 0; let current = 0; let wordsDone = 0; let paused = false; let raf = 0; let last = 0; let lastSet = -1; const placement = () => getSettings().placement; const lineHeight = () => parseFloat(getComputedStyle(body).lineHeight) || 24; const paddingTop = () => parseFloat(getComputedStyle(body).paddingTop) || 0; const autoOn = () => { const s = getSettings(); return isTeleprompterPlacement(s.placement) && s.scroll === "auto" && total > 0; }; function collect() { blocks = [...body.querySelectorAll("aside.notes > *")]; counts = blocks.map((b) => countWords(b.textContent)); starts = paragraphStarts(counts); total = counts.reduce((a, b) => a + b, 0); if (!blocks.length) total = countWords(body.textContent); } function setScroll(top) { body.scrollTop = Math.max(0, top); lastSet = body.scrollTop; } function blockTop(b) { return b.getBoundingClientRect().top - body.getBoundingClientRect().top + body.scrollTop - paddingTop(); } function markCurrent(i) { const camera = placement() === "camera-column"; current = Math.max(0, Math.min(blocks.length - 1, i)); blocks.forEach((b, k) => { b.classList.toggle("tp-current", camera && k === current); b.classList.toggle("tp-past", camera && k < current); }); } function syncMore() { const p = placement(); const more = p !== "camera-column" && p !== "off" && body.textContent.trim() !== "" && body.scrollHeight - body.scrollTop - body.clientHeight > 2; if (more) panel.dataset.notesMore = "1"; else delete panel.dataset.notesMore; } function syncAutoState() { const label = els.presenterNotesAuto; if (autoOn()) { panel.dataset.notesAuto = paused ? "paused" : "running"; if (label) label.textContent = paused ? "Paused · click to resume" : `Auto · ${getSettings().wpm} wpm`; } else { delete panel.dataset.notesAuto; if (label) label.textContent = ""; } } // Bottom placement: measure one column, then two, and keep two only when bottomNotesColumns says. function layoutColumns() { if (placement() !== "bottom" || !body.textContent.trim()) { delete body.dataset.notesCols; return; } body.dataset.notesCols = "1"; const oneFits = body.scrollHeight <= body.clientHeight + 1; let twoFits = false; let secondColumnLines = 0; if (!oneFits) { body.dataset.notesCols = "2"; twoFits = body.scrollHeight <= body.clientHeight + 1 && body.scrollWidth <= body.clientWidth + 1; const box = body.getBoundingClientRect(); const mid = box.left + body.clientWidth / 2; const range = document.createRange(); range.selectNodeContents(body); const tops = new Set([...range.getClientRects()].filter((r) => r.width > 0 && r.left >= mid).map((r) => Math.round(r.top))); secondColumnLines = tops.size; } body.dataset.notesCols = String(bottomNotesColumns({ oneFits, twoFits, secondColumnLines })); } // Progress in words → what the reader sees. function applyWords() { if (placement() === "camera-column" && blocks.length) { const i = paragraphAtWords(starts, wordsDone); if (i !== current) { markCurrent(i); setScroll(blockTop(blocks[i])); } // A paragraph taller than the column scrolls through while it is read. const b = blocks[current]; const over = b.offsetHeight - body.clientHeight + lineHeight(); if (over > 0 && counts[current] > 0) { const frac = Math.min(1, Math.max(0, (wordsDone - starts[current]) / counts[current])); setScroll(blockTop(b) + frac * over); } } else { const max = body.scrollHeight - body.clientHeight; setScroll(Math.min(max, (wordsDone / Math.max(1, total)) * body.scrollHeight)); } syncMore(); } // What the reader sees → progress in words (after J / ⇧J or a wheel scroll). function wordsFromScroll() { if (placement() === "camera-column" && blocks.length) { const b = blocks[current]; const over = b.offsetHeight - body.clientHeight + lineHeight(); const frac = over > 0 ? Math.min(1, Math.max(0, (body.scrollTop - blockTop(b)) / over)) : 0; return starts[current] + frac * counts[current]; } return Math.min(total, (body.scrollTop / Math.max(1, body.scrollHeight)) * total); } function tick(ts) { raf = 0; if (!autoOn() || paused) { last = 0; return; } const dt = last ? Math.min(250, ts - last) : 0; last = ts; wordsDone = advanceWords(wordsDone, dt, getSettings().wpm, total); applyWords(); if (wordsDone < total) raf = requestAnimationFrame(tick); else last = 0; } function stop() { if (raf) cancelAnimationFrame(raf); raf = 0; last = 0; } function start() { if (!raf && autoOn() && !paused && wordsDone < total) { last = 0; raf = requestAnimationFrame(tick); } syncAutoState(); } body.addEventListener("scroll", () => { // A wheel or trackpad scroll moves the automatic scroll's position with it. if (Math.abs(body.scrollTop - lastSet) > 2) { lastSet = body.scrollTop; wordsDone = wordsFromScroll(); } syncMore(); }, { passive: true }); panel.addEventListener("click", (event) => { if (!autoOn() || event.target.closest?.("a, button")) return; paused = !paused; if (paused) stop(); start(); }); // The "more" cue is a button that steps the notes as J does. It never reaches the panel's // pause toggle, and a mouse press does not take focus, so Space / Enter afterwards still // change the slide; Enter / Space on a keyboard-focused cue are handled in handleKey. const moreButton = panel.querySelector(".presenter-notes-more"); if (moreButton) { moreButton.addEventListener("mousedown", (event) => event.preventDefault()); moreButton.addEventListener("click", (event) => { event.stopPropagation(); api.step(1); }); } if ("ResizeObserver" in window) new ResizeObserver(() => { layoutColumns(); syncMore(); }).observe(panel); const api = { reset() { stop(); collect(); wordsDone = 0; paused = false; layoutColumns(); markCurrent(0); setScroll(0); syncMore(); start(); }, sync() { stop(); markCurrent(current); syncMore(); start(); }, step(delta) { const p = placement(); if (p === "off" || !body.textContent.trim()) return false; if (p === "camera-column" && blocks.length) { const b = blocks[current]; const box = body.getBoundingClientRect(); const r = b.getBoundingClientRect(); const band = notesBandStep(body.clientHeight, lineHeight()); if (delta > 0 && r.bottom > box.bottom + 1) setScroll(body.scrollTop + band); // finish a tall paragraph first else if (delta < 0 && r.top < box.top + paddingTop() - 1) setScroll(Math.max(blockTop(b), body.scrollTop - band)); else { const i = Math.max(0, Math.min(blocks.length - 1, current + delta)); markCurrent(i); setScroll(blockTop(blocks[i])); } wordsDone = wordsFromScroll(); } else { setScroll(body.scrollTop + delta * notesBandStep(body.clientHeight, lineHeight())); wordsDone = wordsFromScroll(); } syncMore(); stop(); start(); return true; }, state() { return { wordsDone, total, current, paused, running: Boolean(raf), auto: autoOn() }; }, }; return api; } if (isPresenter && els.presenterNotes && els.presenterNotesBody) { notesScroller = createNotesScroller(els.presenterNotes, els.presenterNotesBody, () => notesSettings); } // Another talk's presenter (or this talk's override) changed the setting: follow it live. window.addEventListener("storage", (event) => { if (!isPresenter) return; if (event.key !== null && event.key !== NOTES_SETTINGS_KEY && event.key !== notesOverrideStorageKey) return; const next = readNotesSettings(notesStorage, notesOverrideStorageKey); const same = next.placement === notesSettings.placement && next.scroll === notesSettings.scroll && next.wpm === notesSettings.wpm && next.justThisTalk === notesSettings.justThisTalk; if (!same) applyNotesSettings(next, { persist: false }); }); // PRESENTER_POLL_VIEW_MODEL_START function presenterPollViewModel(state) { const isOpen = Boolean(state?.open); const phase = state ? (isOpen ? "open" : "closed") : "armed"; const tallies = state?.tallies && typeof state.tallies === "object" ? state.tallies : {}; const responses = Array.isArray(state?.responses) ? state.responses : []; const count = ["ranking", "rating", "categorisation"].includes(state?.pollType) ? Math.max(0, Number(state?.responseCount) || 0) : state?.pollType === "open" ? responses.length : Object.values(tallies).reduce((sum, value) => sum + Math.max(0, Number(value) || 0), 0); const heldWaiting = phase !== "armed" && state?.visibility === "held" && !state?.revealed; return { phase, count, showResults: phase === "open" || phase === "closed", // A closed poll can be re-opened (mis-click recovery) — the Worker keeps its votes. showOpen: phase === "armed" || phase === "closed", showClose: phase === "open", showReveal: heldWaiting, showHeldNote: heldWaiting, }; } // PRESENTER_POLL_VIEW_MODEL_END function extendedPollEscape(value) { return String(value ?? '').replace(/[&<>"']/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])) } function isExtendedPoll(type) { return type === 'ranking' || type === 'rating' || type === 'categorisation' } function normaliseExtendedPollFields(message) { if (!isExtendedPoll(message.pollType)) return {} if (message.pollType === 'ranking') { if (message.rankCount === undefined) return {} if (!Number.isInteger(message.rankCount) || message.rankCount < 1 || message.rankCount > message.options.length) return null return { rankCount: message.rankCount } } if (!Array.isArray(message.labels) || !message.labels.length || (message.allowSkip !== undefined && typeof message.allowSkip !== 'boolean')) return null const labels = message.labels.map(label => label && typeof label.optionId === 'string' && label.optionId.trim() && typeof label.label === 'string' && label.label.trim() ? { optionId: label.optionId, label: label.label } : null) if (labels.some(label => !label) || new Set(labels.map(label => label.optionId)).size !== labels.length) return null return { labels, ...(message.allowSkip !== undefined ? { allowSkip: message.allowSkip } : {}) } } function normaliseExtendedPollAggregates(message) { const result = {} if (message.responseCount !== undefined) { if (!Number.isSafeInteger(message.responseCount) || message.responseCount < 0) return null result.responseCount = message.responseCount } const countsFor = (raw, ids) => { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null if (Object.values(raw).some(count => !Number.isSafeInteger(count) || count < 0)) return null return Object.fromEntries(ids.map(id => [id, raw[id] || 0])) } if (message.firstPlaces !== undefined) { const firstPlaces = countsFor(message.firstPlaces, message.options.map(option => option.optionId)) if (!firstPlaces) return null result.firstPlaces = firstPlaces } if (message.categoryTallies !== undefined) { if (!message.categoryTallies || typeof message.categoryTallies !== 'object' || Array.isArray(message.categoryTallies)) return null const categories = [] for (const option of message.options) { const counts = countsFor(message.categoryTallies[option.optionId] || {}, (message.labels || []).map(label => label.optionId)) if (!counts) return null categories.push([option.optionId, counts]) } result.categoryTallies = Object.fromEntries(categories) } return result } function normaliseBallotChoice(choice) { if (typeof choice === 'string' && choice.trim()) return choice if (Array.isArray(choice) && choice.length && choice.every(id => typeof id === 'string' && id.trim())) return [...choice] if (choice && typeof choice === 'object' && !Array.isArray(choice)) { const entries = Object.entries(choice) if (entries.length && entries.every(([row, label]) => row.trim() && typeof label === 'string' && label.trim())) return Object.fromEntries(entries) } return null } function samePollChoice(left, right) { if (left && right && typeof left === 'object' && typeof right === 'object' && !Array.isArray(left) && !Array.isArray(right)) { const keys = Object.keys(left) return keys.length === Object.keys(right).length && keys.every(key => Object.hasOwn(right, key) && left[key] === right[key]) } return JSON.stringify(left) === JSON.stringify(right) } function renderExtendedPollResults(state, presenter = false) { if (!presenter && state.visibility === 'held' && !state.revealed) return '

Results are held until the speaker reveals them.

' const escape = extendedPollEscape const count = Math.max(0, Number(state.responseCount) || 0) if (state.pollType === 'ranking') { const positions = state.rankCount ?? state.options.length const sorted = state.options.map((option, index) => ({ ...option, index, points: state.tallies?.[option.optionId] || 0 })) .sort((a, b) => b.points - a.points || a.index - b.index) let previousPoints = null; let place = 0 const rows = sorted.map((option, index) => { if (option.points !== previousPoints) place = index + 1 previousPoints = option.points const joint = sorted.some(other => other.optionId !== option.optionId && other.points === option.points) const prefix = count > 0 ? `${joint ? 'Joint ' : ''}${place}. ` : '' const firsts = state.firstPlaces?.[option.optionId] || 0 const width = count ? 100 * option.points / (count * positions) : 0 return `
${prefix}${escape(option.label)}${option.points} points · ${firsts} first-place ${firsts === 1 ? 'vote' : 'votes'}
` }).join('') return `

${count} ${count === 1 ? 'ballot' : 'ballots'}

${positions === 1 ? 'First place earns 1 point.' : `Points per ballot: ${positions}, ${positions > 2 ? '… ' : ''}1, from first to last.`} Unranked choices earn 0. Equal points share a place.

${rows}
` } const rows = state.options.map(option => { const counts = state.categoryTallies?.[option.optionId] || {} const answered = (state.labels || []).reduce((sum, label) => sum + (counts[label.optionId] || 0), 0) const cells = (state.labels || []).map(label => { const votes = counts[label.optionId] || 0 const percent = answered ? Math.round(100 * votes / answered) : 0 return `
${escape(label.label)}${votes} · ${percent}%
` }).join('') return `

${escape(option.label)}

${answered} answered${state.allowSkip ? ` · ${Math.max(0, count - answered)} skipped` : ''}

${cells}
` }).join('') return `

${count} ${count === 1 ? 'ballot' : 'ballots'} · percentages use answers to each item

${rows}
` } function createExtendedBallot(mount, poll, onChange, draft) { const escape = extendedPollEscape const ranking = poll.pollType === 'ranking' const limit = poll.rankCount ?? poll.options.length const all = ranking && poll.rankCount === undefined const labels = poll.labels || [] const doc = mount.ownerDocument let ordered = ranking && Array.isArray(draft) ? [...draft] : all ? poll.options.map(option => option.optionId) : [] let answers = !ranking && draft && typeof draft === 'object' && !Array.isArray(draft) ? { ...draft } : Object.create(null) let dragged = null let ghost = null let pointer = null let announcement = '' const labelFor = id => poll.options.find(option => option.optionId === id)?.label || '' function value() { if (ranking) return ordered.length === limit ? [...ordered] : null const entries = Object.entries(answers) return entries.length > 0 && (poll.allowSkip || entries.length === poll.options.length) ? Object.fromEntries(entries) : null } function changed() { onChange(value(), ranking ? [...ordered] : { ...answers }) } function rankRow(id, index) { const label = escape(labelFor(id)); const safeId = escape(id) return `
  • ${label} ${!all ? `` : ''}
  • ` } function render(focusId, focusAction = 'handle') { if (ranking) { const available = poll.options.filter(option => !ordered.includes(option.optionId)) mount.innerHTML = `

    ${all ? 'Rank all choices.' : `Choose and rank exactly ${limit} choices.`} Drag the handles to reorder, or use the move buttons.

      ${ordered.map(rankRow).join('')}
    ${!all ? `

    Unranked choices

    ${available.map(option => `
    ${escape(option.label)}
    `).join('')}
    ` : ''}
    ${escape(announcement || `${ordered.length} of ${limit} ranked`)}
    ` } else { mount.innerHTML = `

    ${poll.allowSkip ? 'Answer any items you wish; answer at least one.' : 'Choose one answer for every item.'}

    ${poll.options.map(option => `
    ${escape(option.label)}${labels.map(label => ``).join('')}${poll.allowSkip ? `` : ''}
    `).join('')}
    ${escape(announcement)}
    ` } if (focusId) { const target = [...mount.querySelectorAll(`[data-rank-${focusAction}]`)].find(el => el.getAttribute(`data-rank-${focusAction}`) === focusId && !el.disabled) || [...mount.querySelectorAll('[data-rank-handle]')].find(el => el.getAttribute('data-rank-handle') === focusId) target?.focus() } changed() } function move(id, index, focusAction = 'handle') { const previous = ordered.indexOf(id) if (previous < 0 && ordered.length >= limit) { announcement = `Remove a choice before adding another; rank exactly ${limit}.`; render(); return } ordered = ordered.filter(item => item !== id) ordered.splice(Math.max(0, Math.min(index, ordered.length)), 0, id) announcement = `${labelFor(id)} moved to position ${ordered.indexOf(id) + 1} of ${limit}.` render(id, focusAction) } function remove(id) { ordered = ordered.filter(item => item !== id) announcement = `${labelFor(id)} is unranked. ${ordered.length} of ${limit} ranked.` render() ;[...mount.querySelectorAll('[data-rank-add]')].find(el => el.getAttribute('data-rank-add') === id)?.focus() } function click(event) { const button = event.target.closest('button') if (!button || !mount.contains(button) || button.matches(':disabled')) return if (button.hasAttribute('data-rank-up')) { const id = button.getAttribute('data-rank-up'); move(id, ordered.indexOf(id) - 1, 'up') } if (button.hasAttribute('data-rank-down')) { const id = button.getAttribute('data-rank-down'); move(id, ordered.indexOf(id) + 1, 'down') } if (button.hasAttribute('data-rank-add')) move(button.getAttribute('data-rank-add'), ordered.length) if (button.hasAttribute('data-rank-remove')) remove(button.getAttribute('data-rank-remove')) if (button.hasAttribute('data-matrix-clear')) { const id = button.getAttribute('data-matrix-clear'); delete answers[id] for (const input of mount.querySelectorAll('input[data-matrix-row]')) if (input.getAttribute('data-matrix-row') === id) input.checked = false changed() } } function change(event) { const input = event.target if (!input.hasAttribute('data-matrix-row')) return answers[input.getAttribute('data-matrix-row')] = input.value changed() } function keydown(event) { const id = event.target.getAttribute('data-rank-handle'); const index = ordered.indexOf(id) if (!id || index < 0) return const destination = { ArrowUp: index - 1, ArrowDown: index + 1, Home: 0, End: ordered.length - 1 }[event.key] if (destination === undefined) return event.preventDefault(); event.stopPropagation(); move(id, destination) } function dropAt(id, target, y) { const zone = target?.closest('[data-rank-zone]') if (!zone || !mount.contains(zone)) return if (zone.getAttribute('data-rank-zone') === 'unranked') { if (!all) remove(id); return } const row = target.closest('[data-rank-id]') if (!row) { move(id, ordered.length); return } const targetId = row.getAttribute('data-rank-id') if (targetId === id) return const remaining = ordered.filter(candidate => candidate !== id) const rect = row.getBoundingClientRect() move(id, remaining.indexOf(targetId) + (y > rect.top + rect.height / 2 ? 1 : 0)) } function dragstart(event) { const handle = event.target.closest('[data-rank-handle]') if (!handle || handle.matches(':disabled')) return dragged = handle.getAttribute('data-rank-handle') event.dataTransfer?.setData('text/plain', dragged) if (event.dataTransfer) event.dataTransfer.effectAllowed = 'move' } function dragover(event) { if (dragged) event.preventDefault() } function drop(event) { if (!dragged) return event.preventDefault(); const id = dragged; dragged = null; dropAt(id, event.target, event.clientY) } function dragend() { dragged = null } function pointerdown(event) { if (event.pointerType === 'mouse') return // Native HTML drag handles mouse input. const handle = event.target.closest('[data-rank-handle]') if (!handle || handle.matches(':disabled') || event.button > 0) return event.preventDefault() pointer = { id: handle.getAttribute('data-rank-handle'), pointerId: event.pointerId } mount.setPointerCapture?.(event.pointerId) ghost = doc.createElement('div'); ghost.className = 'poll-rank-ghost'; ghost.setAttribute('aria-hidden', 'true'); ghost.textContent = labelFor(pointer.id) doc.body.appendChild(ghost); pointermove(event) } function pointermove(event) { if (!pointer || event.pointerId !== pointer.pointerId || !ghost) return event.preventDefault(); ghost.style.left = `${event.clientX + 12}px`; ghost.style.top = `${event.clientY + 12}px` for (const row of mount.querySelectorAll('.poll-drop-target')) row.classList.remove('poll-drop-target') doc.elementFromPoint(event.clientX, event.clientY)?.closest('[data-rank-id], [data-rank-zone]')?.classList.add('poll-drop-target') const edge = 55 if (event.clientY < edge) mount.closest('#audiencePollSurface')?.scrollBy(0, -24) if (event.clientY > doc.defaultView.innerHeight - edge) mount.closest('#audiencePollSurface')?.scrollBy(0, 24) } function clearPointer() { ghost?.remove(); ghost = null for (const row of mount.querySelectorAll('.poll-drop-target')) row.classList.remove('poll-drop-target') if (pointer && mount.hasPointerCapture?.(pointer.pointerId)) mount.releasePointerCapture(pointer.pointerId) pointer = null } function pointerup(event) { if (!pointer || pointer.pointerId !== event.pointerId) return const id = pointer.id; const target = doc.elementFromPoint(event.clientX, event.clientY) clearPointer(); dropAt(id, target, event.clientY) } const listeners = { click, change, keydown, dragstart, dragover, drop, dragend, pointerdown, pointermove, pointerup, pointercancel: clearPointer } for (const [name, handler] of Object.entries(listeners)) mount.addEventListener(name, handler) render() return { value, draft: () => ranking ? [...ordered] : { ...answers }, destroy() { clearPointer(); for (const [name, handler] of Object.entries(listeners)) mount.removeEventListener(name, handler) }, } } function createQuickPollExtras(host, onChange) { host.innerHTML = `

    ` const all = host.querySelector('[data-rank-mode="all"]') const top = host.querySelector('[data-rank-mode="top"]') const count = host.querySelector('[data-quick-rank-count]') const labelsInput = host.querySelector('[data-quick-matrix-labels]') const skip = host.querySelector('[data-quick-matrix-skip]') const error = host.querySelector('[data-quick-extra-error]') const labelValues = () => labelsInput.value.split(',').map(label => label.trim()) function setType(type) { host.hidden = !['ranking', 'rating', 'categorisation'].includes(type) host.querySelector('[data-quick-guide]').textContent = type === 'ranking' ? 'Add each choice under Options. People rank all choices by default, or exactly the number you set below.' : type === 'rating' ? 'Add each item to rate under Options. Enter the scale labels below, separated by commas; each person chooses one label per item.' : 'Add each item under Options. Enter the category labels below, separated by commas; each person chooses one category per item.' host.querySelector('[data-quick-ranking]').hidden = type !== 'ranking' host.querySelector('[data-quick-matrix]').hidden = type !== 'rating' && type !== 'categorisation' host.querySelector('[data-quick-labels-title]').textContent = type === 'categorisation' ? 'Category labels' : 'Scale labels' } function valid(type, optionCount) { let message = '' if (type === 'ranking' && top.checked && (!Number.isInteger(Number(count.value)) || Number(count.value) < 1 || Number(count.value) > optionCount)) { message = `Choose a whole number from 1 to ${optionCount}.` } if (type === 'rating' || type === 'categorisation') { const labels = labelValues() if (labels.some(label => !label) || new Set(labels.map(label => label.toLowerCase())).size !== labels.length) message = 'Enter non-empty, different labels separated by commas.' } error.textContent = message; error.hidden = !message count.max = String(optionCount) return !message } function fields(type, pollId) { if (type === 'ranking') return top.checked ? { rankCount: Number(count.value) } : {} if (type === 'rating' || type === 'categorisation') { return { labels: labelValues().map((label, index) => ({ optionId: `${pollId}-label-${index + 1}`, label })), allowSkip: skip.checked } } return {} } function reset() { all.checked = true; top.checked = false; count.value = '3' labelsInput.value = 'A lot, A little, Never'; skip.checked = false; error.hidden = true setType('single') } host.addEventListener('input', onChange) host.addEventListener('change', onChange) reset() return { setType, valid, fields, reset } } const POLL_TYPE_LABELS = {"single":"Single choice","multiple":"Multiple choice","open":"Open response","ranking":"Ranking","rating":"Rating","categorisation":"Categorisation","board":"Board"}; const POLL_STATE_LABELS = {"ready":"Ready to open","open":"Accepting responses","stopped":"Responses closed"}; const POLL_JOIN_PLACEHOLDER = "Join link appears when the session is live"; const EYEBROW_QUESTION = "Audience poll"; const EYEBROW_RESULTS = "Poll results"; function pollFrameEscape(value) { return String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } function pollFrameIsMatrix(type) { return type === "rating" || type === "categorisation"; } function pollFrameInstruction(poll, options) { if (poll.type === "board") { const cards = Number(poll.board?.cardsPerPhone) || 5; const length = Number(poll.board?.cardChars) || 140; return `Add up to ${cards} card${cards === 1 ? "" : "s"}, ${length} characters each.`; } const positions = poll.rankCount ?? options.length; if (poll.type === "ranking") { return positions === options.length ? `Rank all ${positions} choices.` : `Rank your top ${positions} choices.`; } if (pollFrameIsMatrix(poll.type)) return `Choose one label for each item.${poll.allowSkip ? " You may skip items." : ""}`; if (poll.type === "single") return "Choose one answer."; if (poll.type === "multiple") return `Select up to ${poll.maxSelections ?? options.length} options.`; if (poll.maxSubmissions === null) return "Submit as many answers as you like."; const submissions = poll.maxSubmissions ?? 1; return `Submit up to ${submissions} answer${submissions === 1 ? "" : "s"} per participant.`; } function pollFrameLetter(index) { return index < 26 ? String.fromCharCode(65 + index) : String(index + 1); } function pollFrameRenderOptions(rows, results) { const items = rows.map((row, index) => { const letter = results && row.place !== undefined ? `${row.place === null ? "" : pollFrameEscape(`${row.joint ? "Joint " : ""}${row.place}.`)}` : `${pollFrameEscape(pollFrameLetter(row.index ?? index))}`; const label = `${row.continued ? 'Continued: ' : ""}${pollFrameEscape(row.label)}`; if (!results) return `
  • ${letter}${label}
  • `; const percent = Math.max(0, Math.min(100, Number(row.percent) || 0)); return `
  • ${letter}${label}${pollFrameEscape(row.countText ?? "")}
  • `; }).join(""); // A shared place ("Joint 1.") needs a wider lane than a letter; every row in the list takes it so // the lanes stay aligned. const joint = results && rows.some((row) => row.joint && row.place !== null); return `
      ${items}
    `; } function pollFrameRenderMatrix(options, labels, matrix) { const rows = options.map((option, index) => { const result = matrix?.[option.optionId]; const chips = labels.map((label) => { const cell = result?.labels?.[label.optionId]; if (!cell) return `${pollFrameEscape(label.label)}`; const percent = Math.max(0, Math.min(100, Number(cell.percent) || 0)); return `${pollFrameEscape(label.label)}${cell.count} (${percent}%)`; }).join(""); const summary = result?.summary ? `

    ${pollFrameEscape(result.summary)}

    ` : ""; return `
  • ${index + 1}${pollFrameEscape(option.label)}

    ${summary}
    ${chips}
  • `; }).join(""); return `
      ${rows}
    `; } function pollFrameRenderResponses(responses) { if (!responses.length) return `

    No responses to show yet.

    `; const long = responses.some((response) => response.large); return `
    ${responses.map((response) => `
    ${response.continued ? 'Continued' : ""}

    ${pollFrameEscape(response.text)}

    `).join("")}
    `; } function pollFrameRenderBoard(options, board, live) { const hints = board?.hints && typeof board.hints === "object" ? board.hints : {}; const columns = options.map((option) => ({ columnId: option.optionId, label: option.label, hint: typeof hints[option.optionId] === "string" ? hints[option.optionId] : "" })); if (!columns.length) { return `

    This board has no columns yet — add a list of two to four columns under the heading.

    `; } const example = typeof board?.example === "string" ? board.example.trim() : ""; const views = new Map((live && Array.isArray(live.columns) ? live.columns : []).map((view) => [view.columnId, view])); const empty = Boolean(live) && !(live.cardCount > 0); const items = columns.map((column, index) => { const view = views.get(column.columnId); const entries = Array.isArray(view?.entries) ? view.entries : []; const shown = Number.isSafeInteger(view?.count) ? view.count : 0; const waiting = Number.isSafeInteger(view?.waiting) ? view.waiting : 0; const hint = typeof column.hint === "string" && column.hint.trim() && (!live || (!entries.length && !shown)) ? `

    ${pollFrameEscape(column.hint)}

    ` : ""; const exampleCard = index === 0 && example && (!live || empty) ? `

    ${pollFrameEscape(example)}

    Example
    ` : ""; const cards = entries.map((entry) => entry.group ? `
    ${pollFrameEscape(String(entry.group))}

    ${pollFrameEscape(entry.text)}

    ${entry.count > 1 ? `×${pollFrameEscape(String(entry.count))}` : ""}
    ` : `

    ${pollFrameEscape(entry.text)}

    `).join(""); const more = waiting > 0 ? `

    + ${waiting} more on your phone

    ` : ""; return `
  • ` + `

    ${pollFrameEscape(column.label)}${shown}

    ` + `${hint}
    ${exampleCard}${cards}
    ${more}
  • `; }).join(""); return `
      ${items}
    `; } function pollFrameRenderBoardJoin(join, big) { const shortUrl = typeof join?.shortUrl === "string" ? join.shortUrl : ""; if (!shortUrl) return ""; const written = shortUrl.replace(/^https?:\/\//, "").replace(/\/$/, ""); const qr = typeof join.qrSvg === "string" && join.qrSvg.startsWith("${join.qrSvg}` : ""; const label = `Add a card: open the link or scan${pollFrameEscape(written)}`; return big ? `` : `${qr}
    ${label}
    `; } function pollFrameBoardFoot(live, join) { const written = typeof join?.shortUrl === "string" && join.shortUrl ? join.shortUrl.replace(/^https?:\/\//, "").replace(/\/$/, "") : ""; const total = Number.isSafeInteger(live.cardCount) ? live.cardCount : 0; const cards = `${total} card${total === 1 ? "" : "s"}`; if (live.frozen) { return { state: "frozen", chip: `Final board · ${cards}`, lead: `The board as the room left it.${written ? ` Slides and links: ${pollFrameEscape(written)}` : ""}` }; } if (!live.open) { return { state: "closed", chip: `Closed to new cards · ${total}`, lead: `Closed to new cards.${written ? ` Read the whole board at ${pollFrameEscape(written)}` : ""}` }; } if (!written) return { state: "open", chip: `Open · ${cards}`, lead: `${POLL_JOIN_PLACEHOLDER}` }; return { state: "open", chip: `Open · ${cards}`, lead: total > 0 ? pollFrameRenderBoardJoin(join, false) : `Cards appear here as they arrive. No names are shown.` }; } function pollFrameFitBoard(frame) { const steps = [["var(--type-floor)", 1], ["1.7cqw", 1], ["1.7cqw", 2], ["1.5cqw", 2], ["1.35cqw", 2], ["1.25cqw", 2], ["1.25cqw", 3], ["1.1cqw", 3], ["0.95cqw", 3], ["0.85cqw", 4], ["0.75cqw", 4]]; const areas = Array.from(frame.querySelectorAll(".poll-frame-board-cards")); if (!areas.length) return ""; for (const [size, perRow] of steps) { frame.style.setProperty("--poll-frame-board-fs", size); frame.style.setProperty("--poll-frame-board-per-row", String(perRow)); if (areas.every((area) => area.scrollHeight <= area.clientHeight + 1)) { frame.dataset.fitStep = `${size} x${perRow}`; return frame.dataset.fitStep; } } frame.dataset.fitStep = "overflow"; return "overflow"; } function pollFrameRenderAnswers(poll, options, labels, view, results, live, join) { if (poll.type === "board") { const columns = pollFrameRenderBoard(options, poll.board, live); if (!live || live.cardCount > 0 || !live.open || live.frozen) return columns; const bigJoin = pollFrameRenderBoardJoin(join, true); return bigJoin ? `
    ${columns}${bigJoin}
    ` : columns; } // A poll whose type needs options but carries none must SAY so on the slide. The compiler already // warns in the build log (poll-authoring.mjs); an author looking at the slide sees nothing there. if (poll.type !== "open" && !options.length) { return `

    This poll has no options yet — add a list of choices under the heading.

    `; } if (pollFrameIsMatrix(poll.type)) { if (!labels.length) { return `

    This poll has no scale labels yet — add a [scale: …] or [categories: …] line under the heading.

    `; } return pollFrameRenderMatrix(options, labels, view === "results" ? results?.matrix : null); } if (poll.type === "open") { return view === "results" ? pollFrameRenderResponses(Array.isArray(results?.responses) ? results.responses : []) : ""; } if (view === "results") { const rows = Array.isArray(results?.options) && results.options.length ? results.options : options.map((option, index) => ({ ...option, index, percent: 0, countText: "" })); return pollFrameRenderOptions(rows, true); } return pollFrameRenderOptions(options.map((option, index) => ({ ...option, index })), false); } function pollFrameRenderJoin(join) { const shortUrl = typeof join?.shortUrl === "string" ? join.shortUrl : ""; if (!shortUrl) { return ""; } const written = shortUrl.replace(/^https?:\/\//, "").replace(/\/$/, ""); const qr = typeof join.qrSvg === "string" && join.qrSvg.startsWith("${join.qrSvg}` : ""; return ``; } function renderPollFrame(poll, ctx = {}) { if (!poll || typeof poll !== "object" || !Object.hasOwn(POLL_TYPE_LABELS, poll.type)) return ""; const options = Array.isArray(poll.options) ? poll.options.filter((option) => option && typeof option.label === "string") : []; const labels = Array.isArray(poll.labels) ? poll.labels.filter((label) => label && typeof label.label === "string") : []; const question = String(poll.question ?? ctx.title ?? "").trim(); // A live board (ctx.board) has its own three states; the frame's data-poll-state follows them. const live = poll.type === "board" && ctx.board && typeof ctx.board === "object" ? ctx.board : null; const boardFoot = live ? pollFrameBoardFoot(live, ctx.join) : null; const state = boardFoot ? (boardFoot.state === "open" ? "open" : "stopped") : Object.hasOwn(POLL_STATE_LABELS, ctx.state) ? ctx.state : "ready"; const view = ctx.view === "results" && !live ? "results" : "question"; const kind = POLL_TYPE_LABELS[poll.type]; const questionHtml = question ? `

    ${pollFrameEscape(question)}

    ` : ""; const boardInstructions = poll.type === "board" && typeof poll.board?.instructions === "string" && poll.board.instructions.trim() ? `

    ${pollFrameEscape(poll.board.instructions)}

    ` : ""; const instruction = options.length || poll.type === "open" || poll.type === "board" ? pollFrameInstruction(poll, options) : ""; // A live board puts its join in the foot (or large beside an empty board), never in the body. const joinHtml = live ? "" : pollFrameRenderJoin(ctx.join); const pendingJoinHtml = joinHtml || live ? "" : `

    ${POLL_JOIN_PLACEHOLDER}

    `; const pages = Number.isSafeInteger(ctx.pages) && ctx.pages > 1 ? ctx.pages : 1; const page = Number.isSafeInteger(ctx.page) && ctx.page >= 0 ? Math.min(ctx.page, pages - 1) : 0; const footLead = boardFoot ? boardFoot.lead : view === "results" ? (ctx.results?.total ? `${pollFrameEscape(ctx.results.total)}` : "") : (instruction ? `${pollFrameEscape(instruction)}` : ""); const pageHtml = pages > 1 ? `Page ${page + 1} of ${pages}` : ""; const chipText = boardFoot ? boardFoot.chip : POLL_STATE_LABELS[state]; const boardAttr = boardFoot ? ` data-board-state="${boardFoot.state}"` : ""; return `
    ` + `

    ${view === "results" ? EYEBROW_RESULTS : EYEBROW_QUESTION}${pollFrameEscape(kind)}

    ${questionHtml}${boardInstructions}
    ` + `
    ${pollFrameRenderAnswers(poll, options, labels, view, ctx.results, live, ctx.join)}
    ${joinHtml}
    ` + `
    ${footLead}${pendingJoinHtml}${pageHtml}${pollFrameEscape(chipText)}
    ` + `
    `; } // Injected into the portable presenter runtime AFTER the poll frame renderer (poll-frame.mjs, // `pollFrameRuntimeSource`). Keep this boundary independent of presenter UI: its return values // are the only poll data allowed into paired-window messages and storage. // // Ticket 23: this module no longer owns a poll composition. It derives STATE — the safe public // snapshot, the chosen view, the result rows and their shares, the response pages — and hands it // to `renderPollFrame`, the same function the compiler used to paint the frame into the slide. // One composition; the runtime only fills the slots the frame defines. function createPollDisplay() { const escape = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0; function safeState(message) { if (!message || typeof message.pollId !== 'string' || !message.pollId || !['single', 'multiple', 'open', 'ranking', 'rating', 'categorisation', 'board'].includes(message.pollType) || !['held', 'live'].includes(message.visibility)) return null; const options = (Array.isArray(message.options) ? message.options : []) .filter((option) => option && typeof option.optionId === 'string' && typeof option.label === 'string') .map((option) => ({ optionId: option.optionId, label: option.label })); const safe = { type: 'poll.state', pollId: message.pollId, pollType: message.pollType, question: typeof message.question === 'string' ? message.question : '', options, visibility: message.visibility, open: message.open === true, revealed: message.revealed === true, ...(message.pollType === 'multiple' && Number.isSafeInteger(message.maxSelections) && message.maxSelections > 0 && message.maxSelections <= options.length ? { maxSelections: message.maxSelections } : {}), ...(message.pollType === 'open' && (message.maxSubmissions === null || (Number.isSafeInteger(message.maxSubmissions) && message.maxSubmissions > 0)) ? { maxSubmissions: message.maxSubmissions } : {}), ...(typeof message.slideId === 'string' && message.slideId ? { slideId: message.slideId } : {}), }; if (safe.pollType === 'board') { // A board is public by nature: its cards are on the screen whatever the visibility says. safe.board = safeBoardSettings(message.board); const view = message.boardView ? checkedBoardView(message.boardView) : safeBoardView(message.boardState); if (view) safe.boardView = view; return safe; } if (safe.pollType === 'ranking') { if (message.rankCount !== undefined) { if (!Number.isSafeInteger(message.rankCount) || message.rankCount < 1 || message.rankCount > options.length) return null; safe.rankCount = message.rankCount; } } else if (isMatrix(safe)) { if (!Array.isArray(message.labels) || !message.labels.length || (message.allowSkip !== undefined && typeof message.allowSkip !== 'boolean')) return null; if (message.labels.some((label) => !label || typeof label.optionId !== 'string' || !label.optionId.trim() || typeof label.label !== 'string' || !label.label.trim()) || new Set(message.labels.map((label) => label.optionId)).size !== message.labels.length) return null; safe.labels = message.labels.map((label) => ({ optionId: label.optionId, label: label.label })); if (message.allowSkip !== undefined) safe.allowSkip = message.allowSkip; } if (safe.visibility !== 'live' && !safe.revealed) return safe; if (safe.pollType === 'open') { safe.responses = (Array.isArray(message.responses) ? message.responses : []) .filter((response) => response && response.hidden !== true && typeof response.text === 'string' && typeof response.responseId === 'string') .map((response) => ({ responseId: response.responseId, text: response.text })); } else if (isMatrix(safe)) { safe.categoryTallies = Object.fromEntries(options.map((option) => [option.optionId, Object.fromEntries(safe.labels.map((label) => [label.optionId, count(message.categoryTallies?.[option.optionId]?.[label.optionId])]))])); safe.responseCount = count(message.responseCount); } else { if (safe.pollType === 'ranking') { safe.firstPlaces = Object.fromEntries(options.map((option) => [option.optionId, count(message.firstPlaces?.[option.optionId])])); safe.responseCount = count(message.responseCount); } safe.tallies = Object.fromEntries(options.map((option) => [option.optionId, count(message.tallies?.[option.optionId])])); } return safe; } // ADR-0032 (ticket 04). The board's settings the frame reads (instructions, example, hints). function safeBoardSettings(board) { const text = (value, max) => (typeof value === 'string' && value.trim() ? value.slice(0, max) : undefined); const hints = {}; if (board && typeof board.hints === 'object' && board.hints) { for (const [columnId, hint] of Object.entries(board.hints)) if (text(hint, 300)) hints[columnId] = hint.slice(0, 300); } return { ...(text(board?.instructions, 1000) ? { instructions: board.instructions.slice(0, 1000) } : {}), ...(text(board?.example, 500) ? { example: board.example.slice(0, 500) } : {}), ...(Object.keys(hints).length ? { hints } : {}), }; } // The big-screen view of a board, resolved to what the frame draws and nothing more: the worker's // `columns[].onScreen` (already limit-, release- and hide-aware; a screen renders it, never // recomputes it) with each entry's text looked up. Names, hidden cards, ids and timestamps never // pass. A group shows its wording when the presenter gave it one, otherwise the text of its first // VISIBLE card (the presenter's board still lists a hidden card in a group's cardIds), and the count // of visible cards. function safeBoardView(state) { if (!state || typeof state !== 'object' || !Array.isArray(state.columns) || !Array.isArray(state.cards)) return null; const cards = new Map(); for (const card of state.cards) { if (card && typeof card.cardId === 'string' && typeof card.text === 'string' && card.hidden !== true) cards.set(card.cardId, card.text.slice(0, 1000)); } const groups = new Map(); for (const group of Array.isArray(state.groups) ? state.groups : []) { if (!group || !Number.isSafeInteger(group.n) || !Array.isArray(group.cardIds)) continue; const visible = group.cardIds.filter((id) => cards.has(id)); // The presenter's wording for the group (board.relabel), when set, in place of its first card's text. const label = typeof group.label === 'string' && group.label.trim() ? group.label.slice(0, 1000) : null; if (visible.length) groups.set(group.n, { text: label || cards.get(visible[0]), count: visible.length }); } const columns = []; for (const column of state.columns) { if (!column || typeof column.columnId !== 'string' || !Array.isArray(column.onScreen)) return null; const entries = []; for (const entry of column.onScreen.slice(0, 1000)) { if (entry && Number.isSafeInteger(entry.group) && groups.has(entry.group)) entries.push({ group: entry.group, ...groups.get(entry.group) }); else if (entry && typeof entry.cardId === 'string' && cards.has(entry.cardId)) entries.push({ text: cards.get(entry.cardId) }); } columns.push({ columnId: column.columnId, count: count(column.cards), waiting: count(column.waiting), entries }); } return { frozen: state.frozen === true, cardCount: count(state.cardCount), columns }; } // A view this function already resolved (it travels to the audience window and back through // storage): re-checked field by field, never trusted. function checkedBoardView(view) { if (!view || typeof view !== 'object' || !Array.isArray(view.columns)) return null; const columns = []; for (const column of view.columns) { if (!column || typeof column.columnId !== 'string' || !Array.isArray(column.entries)) return null; const entries = column.entries.slice(0, 1000) .filter((entry) => entry && typeof entry.text === 'string') .map((entry) => ({ text: entry.text.slice(0, 1000), ...(Number.isSafeInteger(entry.group) && entry.group > 0 ? { group: entry.group, count: count(entry.count) } : {}), })); columns.push({ columnId: column.columnId, count: count(column.count), waiting: count(column.waiting), entries }); } return { frozen: view.frozen === true, cardCount: count(view.cardCount), columns }; } // QR SVGs are generated in main from the established encoder. Accept only its inert drawing // vocabulary and reconstruct attributes; never trust an SVG string from storage as HTML. function safeQr(svg) { if (typeof svg !== 'string' || svg.length > 250000 || !/^\s*&]*$/, 'shape-rendering': /^crispEdges$/, }; let valid = true; const tags = []; const remainder = svg.replace(/<(\/?)([A-Za-z][\w:-]*)([^<>]*)>/g, (_tag, close, name, raw) => { if (!['svg', 'g', 'rect', 'path'].includes(name)) { valid = false; return ''; } if (close) { if (raw.trim()) valid = false; tags.push(``); return ''; } const attributes = []; const rest = raw.replace(/([A-Za-z][\w:.-]*)\s*=\s*"([^"<>]*)"/g, (_attribute, key, value) => { if (!values[key]?.test(value)) valid = false; else attributes.push(`${key}="${escape(value)}"`); return ''; }).trim(); if (rest && rest !== '/') valid = false; tags.push(`<${name}${attributes.length ? ' ' + attributes.join(' ') : ''}${rest === '/' ? '/' : ''}>`); return ''; }); return valid && !remainder.trim() && /<\/svg>\s*$/.test(svg) ? tags.join('') : ''; } function safeJoin(join) { let shortUrl = ''; try { const url = new URL(join?.shortUrl); if (['https:', 'http:'].includes(url.protocol) && !url.username && !url.password) shortUrl = url.href; } catch { /* no public joining link yet */ } return { shortUrl, qrSvg: shortUrl ? safeQr(join?.qrSvg) : '' }; } function viewFor(poll, requested) { return requested === 'results' && poll?.pollType !== 'board' && (poll?.visibility === 'live' || poll?.revealed === true) ? 'results' : 'question'; } function splitText(text, limit) { const characters = Array.from(text); const parts = []; while (characters.length > limit) { let end = limit; for (let i = limit; i > limit * .65; i--) { if (/\s/.test(characters[i])) { end = i + 1; break; } } parts.push(characters.splice(0, end).join('')); } parts.push(characters.join('')); return parts; } function isMatrix(poll) { return poll?.pollType === 'rating' || poll?.pollType === 'categorisation'; } // The poll definition the frame lays out — the same shape the compiler framed at build time. function definitionOf(poll) { return { pollId: poll.pollId, type: poll.pollType, question: poll.question, options: poll.options, ...(poll.labels ? { labels: poll.labels } : {}), ...(poll.rankCount !== undefined ? { rankCount: poll.rankCount } : {}), ...(poll.allowSkip !== undefined ? { allowSkip: poll.allowSkip } : {}), ...(poll.maxSelections !== undefined ? { maxSelections: poll.maxSelections } : {}), ...(poll.maxSubmissions !== undefined ? { maxSubmissions: poll.maxSubmissions } : {}), ...(poll.pollType === 'board' ? { board: poll.board || {} } : {}), }; } // Ranking results: points, first places, places shared on equal points (author order breaks // nothing — a tie is a tie and says so), unplaced until a ballot arrives. function rankingRows(poll) { const positions = poll.rankCount ?? poll.options.length; const rows = poll.options.map((option, index) => ({ ...option, index, points: poll.tallies?.[option.optionId] || 0 })); rows.sort((a, b) => b.points - a.points || a.index - b.index); let previous; let place = 0; return rows.map((option, order) => { if (option.points !== previous) place = order + 1; previous = option.points; const joint = rows.some((other) => other.optionId !== option.optionId && other.points === option.points); const firsts = poll.firstPlaces?.[option.optionId] || 0; return { ...option, place: poll.responseCount > 0 ? place : null, joint, percent: poll.responseCount ? Math.min(100, option.points * 100 / (poll.responseCount * positions)) : 0, // Two short lines (the count column keeps the label on one line): points, then first places. countText: `${option.points} points\n${firsts} first-place ${firsts === 1 ? 'vote' : 'votes'}`, }; }); } // Choice results: counts and shares in AUTHORED order — the audience compares bars, not ranks. function choiceRows(poll) { const votes = Object.values(poll.tallies || {}).reduce((sum, n) => sum + n, 0); return poll.options.map((option, index) => { const n = poll.tallies?.[option.optionId] || 0; const percent = votes ? Math.round(n * 100 / votes) : 0; return { ...option, index, percent, countText: `${n} · ${percent}%` }; }); } // Matrix results: each item's chips share the item's own denominator (answers to THIS item), // with skipped ballots stated when skipping was allowed. function matrixResults(poll) { return Object.fromEntries(poll.options.map((option) => { const counts = poll.categoryTallies?.[option.optionId] || {}; const answered = poll.labels.reduce((sum, label) => sum + (counts[label.optionId] || 0), 0); return [option.optionId, { summary: `${answered} answered${poll.allowSkip ? ` · ${Math.max(0, poll.responseCount - answered)} skipped` : ''}`, labels: Object.fromEntries(poll.labels.map((label) => { const n = counts[label.optionId] || 0; return [label.optionId, { count: n, percent: answered ? Math.round(n * 100 / answered) : 0 }]; })), }]; })); } // Pages exist for ONE reason: open-response results are runtime content the frame cannot size // at compile time, so they page four cards at a time (long responses stand alone, split // losslessly). Options and matrix rows never page — the compiled frame shows them all and the // live frame must agree with it; the deck's autofit (the same one that fits the compiled frame) // spends leading and type down to the floor when a long list needs it. function pageInfo(message, requested, selected = 0) { const poll = safeState(message); const view = viewFor(poll, requested); const pages = []; let current = []; const add = () => { if (current.length) pages.push(current); current = []; }; if (!poll) { /* no poll: one empty page */ } else if (poll.pollType === 'open') { if (view === 'results') for (const response of poll.responses || []) { const parts = splitText(response.text, 560); if (parts.length > 1 || response.text.length > 220) { add(); parts.forEach((text, index) => pages.push([{ ...response, text, continued: index > 0, large: true }])); } else { current.push(response); if (current.length === 4) add(); } } } else { // Options and matrix rows: one page, the rows exactly as the frame lays them out (ranking // results in place order — the only reordering a poll ever does). pages.push(poll.pollType === 'ranking' && view === 'results' ? rankingRows(poll) : poll.options.map((option, index) => ({ ...option, index, ...(isMatrix(poll) ? { labels: poll.labels } : {}) }))); } add(); if (!pages.length) pages.push([]); const page = Math.min(pages.length - 1, count(selected)); return { page, pages: pages.length, items: pages[page], view }; } function totalFor(poll) { const votes = Object.values(poll.tallies || {}).reduce((sum, n) => sum + n, 0); const positions = poll.rankCount ?? poll.options.length; const scoring = positions === 1 ? '1 point for first place.' : `${positions} points for first, down to 1 for last.`; if (poll.pollType === 'ranking') return `${poll.responseCount || 0} ballots · ${scoring} Unranked: 0. Equal points share a place.`; if (isMatrix(poll)) return `${poll.responseCount || 0} ballots · % of answers to this item`; if (poll.pollType === 'open') return `${poll.responses?.length || 0} responses`; return `${votes} ${poll.pollType === 'multiple' ? 'selections · % of selections' : 'votes'}`; } // The live frame: the compiled composition with its state slots filled. function markup(message, settings = {}) { const poll = safeState(message); if (!poll) return ''; const { page, pages, items, view } = pageInfo(poll, settings.view, settings.page); const join = safeJoin(settings.join); const state = !settings.started ? 'ready' : poll.open ? 'open' : 'stopped'; const results = view !== 'results' ? undefined : { total: totalFor(poll), ...(poll.pollType === 'open' ? { responses: items } : {}), ...(poll.pollType === 'ranking' ? { options: rankingRows(poll) } : {}), ...(poll.pollType === 'single' || poll.pollType === 'multiple' ? { options: choiceRows(poll) } : {}), ...(isMatrix(poll) ? { matrix: matrixResults(poll) } : {}), }; // A board's frame takes the worker's view (the open flag and the frozen flag pick its foot); before // any board state has arrived it stays the at-rest columns. const board = poll.pollType === 'board' && poll.boardView && settings.started ? { open: poll.open, ...poll.boardView } : undefined; return renderPollFrame(definitionOf(poll), { live: true, state, view, page, pages, join: join.shortUrl ? join : undefined, results, board }); } return { safeState, safeJoin, viewFor, pageInfo, markup }; } // Local display lifecycle. Server voting/disclosure and ordinary slide navigation are inputs, // never side effects of showing, hiding or revisiting a poll. function createPollProjection(options) { const display = createPollDisplay(); const entries = new Map(); const key = `${options.storageKey}:poll-display`; let join = display.safeJoin(null); let sequence = 0; let quickPollId = null; let quickVisible = false; let lastRenderKey = ''; function definitionFor(slide) { try { const definition = JSON.parse(slide?.dataset.poll || 'null'); return definition && typeof definition.pollId === 'string' ? { ...definition, slideId: slide.dataset.id } : null; } catch { return null; } } function entryFor(slide) { const definition = definitionFor(slide); if (!definition) return null; if (entries.has(definition.pollId)) return entries.get(definition.pollId); const entry = { state: display.safeState({ ...definition, type: 'poll.state', pollType: definition.type, open: false, revealed: false }), view: 'question', page: 0, started: false, }; entries.set(definition.pollId, entry); return entry; } function snapshot() { return { version: 1, sessionId: options.sessionId, sequence, join: display.safeJoin(join), quickPollId, quickVisible, polls: Array.from(entries.values()).map((entry) => ({ state: display.safeState(entry.state), view: entry.view === 'results' ? 'results' : 'question', page: Number.isSafeInteger(entry.page) && entry.page >= 0 ? entry.page : 0, started: entry.started === true, })).filter((entry) => entry.state), }; } function applySnapshot(value, force = false) { if (!value || value.version !== 1 || value.sessionId !== options.sessionId || !Number.isSafeInteger(value.sequence) || value.sequence < sequence || (!force && value.sequence === sequence) || !Array.isArray(value.polls)) return; entries.clear(); for (const entry of value.polls) { const state = display.safeState(entry?.state); if (!state) continue; entries.set(state.pollId, { state, view: display.viewFor(state, entry.view), page: Number.isSafeInteger(entry.page) && entry.page >= 0 ? entry.page : 0, started: entry.started === true }); } sequence = value.sequence; join = display.safeJoin(value.join); quickPollId = typeof value.quickPollId === 'string' ? value.quickPollId : null; quickVisible = value.quickVisible === true; render(); } function publish() { if (!options.isPresenter || !options.isPaired) return; sequence++; const value = snapshot(); try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* pairing still works without storage */ } options.send({ type: 'talkweaver-poll-display', sessionId: options.sessionId, snapshot: value }); render(); options.changed?.(); } function receivePeer(message) { if (message?.sessionId !== options.sessionId) return; if (options.isPresenter) { if (message.type === 'talkweaver-poll-display-request') { options.send({ type: 'talkweaver-poll-display', sessionId: options.sessionId, snapshot: snapshot() }); } } else if (message.type === 'talkweaver-poll-display') applySnapshot(message.snapshot); } function update(message) { if (!options.isPresenter) return; const state = display.safeState(message); if (!state) return; const previous = entries.get(state.pollId); const newlyRevealed = previous && !previous.state.revealed && state.revealed; const view = newlyRevealed ? 'results' : previous?.view || (!state.open && state.revealed ? 'results' : 'question'); entries.set(state.pollId, { state, view: display.viewFor(state, view), page: previous?.page || 0, started: true }); publish(); } function choose(pollId, view) { const entry = entries.get(pollId); if (!options.isPresenter || !entry) return; entry.view = display.viewFor(entry.state, view); entry.page = 0; publish(); } function turnPage(pollId, delta) { const entry = entries.get(pollId); if (!options.isPresenter || !entry) return; const info = display.pageInfo(entry.state, entry.view, entry.page); entry.page = Math.max(0, Math.min(info.pages - 1, info.page + delta)); publish(); } function showQuick(pollId, visible = true) { if (!options.isPresenter) return; quickPollId = pollId; quickVisible = visible; publish(); } function markup(entry) { return entry?.state ? display.markup(entry.state, { ...entry, join }) : ''; } function quickMarkup() { const entry = quickVisible && entries.get(quickPollId); return entry?.started ? markup(entry) : ''; } // Ticket 5 compiled the poll frame (`[data-poll-frame="compiled"]`, poll-frame.mjs) into the slide; // Ticket 23 makes the live poll THAT SAME FRAME with its state filled (renderPollFrame, called by // poll-display.js). The live frame is mounted inside `.slide-content` directly after the compiled // one — same container, same type scale, same autofit — the compiled frame is hidden while the live // one is mounted and restored when the projection leaves, so a poll slide never shows both and never // goes blank. A poll slide with no compiled frame (a carousel) gets a paper host over the slide. function compiledFrame(slide) { return slide ? slide.querySelector('[data-poll-frame="compiled"]') : null; } function liveFrame(slide) { return slide ? slide.querySelector('[data-poll-frame="live"]') : null; } function unmount(slide) { liveFrame(slide)?.remove(); slide.querySelector(':scope > .poll-frame-host')?.remove(); const frame = compiledFrame(slide); if (frame) frame.hidden = false; slide.classList.remove('has-poll-display'); } function mount(slide, html) { const frame = compiledFrame(slide); const live = liveFrame(slide); if (frame) { frame.hidden = true; if (live) live.outerHTML = html; else frame.insertAdjacentHTML('afterend', html); } else { let host = slide.querySelector(':scope > .poll-frame-host'); if (!host) { host = document.createElement('div'); host.className = 'poll-frame-host'; slide.appendChild(host); } host.innerHTML = html; } slide.classList.add('has-poll-display'); } // The frame's content changed under the deck's fit pass: run it again so a long option list // spends its slack exactly as the compiled frame did (autofitActiveSlides is the template's). function refit(slide) { // A live board picks its card size first (pollFrameFitBoard, poll-frame.mjs), so the deck's own // autofit sees a frame that already fits its slide. if (slide.classList.contains('active') && typeof pollFrameFitBoard === 'function') { slide.querySelectorAll('.poll-frame[data-poll-type="board"]:not([hidden])').forEach(pollFrameFitBoard); } if (slide.classList.contains('active') && typeof autofitActiveSlides === 'function') autofitActiveSlides(); } function render() { if (!options.isPaired) return; const slide = options.getSlide(); if (!slide) return; const entry = entryFor(slide); const html = markup(entry); const popupHtml = quickMarkup(); const renderKey = `${slide.dataset.id}\0${html}\0${popupHtml}`; if (renderKey === lastRenderKey) return; lastRenderKey = renderKey; document.querySelectorAll('.slide.has-poll-display').forEach((previous) => { if (previous === slide && html) return; unmount(previous); }); if (html) { mount(slide, html); refit(slide); } let popup = document.getElementById('audienceQuickPollPopup'); if (!options.isPresenter) { if (!popup) { popup = document.createElement('div'); popup.id = 'audienceQuickPollPopup'; popup.className = 'poll-frame-popup'; popup.setAttribute('role', 'region'); popup.setAttribute('aria-label', 'Quick poll'); options.stage.appendChild(popup); } popup.hidden = !popupHtml; popup.innerHTML = popupHtml; } } // The presenter's Current/Next/Then panes clone the slide: give the clone the same live frame // (or the compiled frame back) so the presenter sees exactly the composition the audience sees. function decoratePreview(clone, isCurrent) { const html = markup(entryFor(clone)); unmount(clone); if (html) mount(clone, html); if (isCurrent && quickMarkup()) { const popup = document.createElement('div'); popup.className = 'poll-frame-popup'; popup.innerHTML = quickMarkup(); clone.appendChild(popup); } } function previewKey(slide, isCurrent) { return `${markup(entryFor(slide))}\0${isCurrent ? quickMarkup() : ''}`; } function info(pollId) { const entry = entries.get(pollId); return entry ? { ...display.pageInfo(entry.state, entry.view, entry.page), started: entry.started } : { view: 'question', page: 0, pages: 1, started: false }; } function setJoin(value) { join = display.safeJoin(value); publish(); } function clear() { entries.clear(); join = display.safeJoin(null); quickPollId = null; quickVisible = false; publish(); } if (options.isPaired) { try { const stored = JSON.parse(localStorage.getItem(key) || 'null'); if (stored) applySnapshot(stored, true); } catch { /* fresh display */ } window.addEventListener('storage', (event) => { if (options.isPresenter || event.key !== key || !event.newValue) return; try { applySnapshot(JSON.parse(event.newValue)); } catch { /* malformed storage is inert */ } }); // The template supplies both BroadcastChannel and opener/window message delivery. if (!options.isPresenter) queueMicrotask(() => options.send({ type: 'talkweaver-poll-display-request', sessionId: options.sessionId })); } return { update, choose, turnPage, showQuick, setJoin, clear, render, decoratePreview, previewKey, info, receivePeer, quick: () => ({ pollId: quickPollId, visible: quickVisible }), snapshot }; } function bpView(poll, state, sorted) { const marked = sorted instanceof Set ? sorted : new Set() const board = state && state.boardState && typeof state.boardState === 'object' ? state.boardState : null const settings = (state && state.board) || (poll && poll.board) || {} const options = Array.isArray(state && state.options) && state.options.length ? state.options : (Array.isArray(poll && poll.options) ? poll.options : []) const cards = board && Array.isArray(board.cards) ? board.cards : [] const groups = board && Array.isArray(board.groups) ? board.groups : [] const release = board && board.release ? board.release : { extra: 0, all: false, groupsOnly: false, columns: {} } const limit = board ? board.limit : (settings.limit === undefined ? 24 : settings.limit) const byId = new Map(cards.map((card) => [card.cardId, card])) const phase = !state ? 'ready' : board && board.frozen ? 'frozen' : state.open ? 'open' : 'closed' // New: visible single cards the presenter has not moved, merged, split or hidden, and not marked // sorted here. Newest first. const isNew = (card) => !card.hidden && card.group === undefined && !card.touched && !marked.has(card.cardId) const inbox = cards.filter(isNew).sort((a, b) => b.acceptedAt - a.acceptedAt || (a.cardId < b.cardId ? 1 : -1)) .map((card) => ({ kind: 'card', cardId: card.cardId, text: card.text, column: card.column, acceptedAt: card.acceptedAt, ...(card.name ? { name: card.name } : {}), ...(card.waiting ? { waiting: true } : {}) })) const inboxIds = new Set(inbox.map((entry) => entry.cardId)) const labelOf = (columnId) => (options.find((option) => option.optionId === columnId) || {}).label || columnId const screenColumns = new Map((board && Array.isArray(board.columns) ? board.columns : []).map((column) => [column.columnId, column])) const columns = options.map((option) => { const id = option.optionId const screen = screenColumns.get(id) || { onScreen: [], waiting: 0 } const groupEntries = groups.filter((group) => group.column === id).map((group) => { const members = group.cardIds.map((cardId) => byId.get(cardId)).filter(Boolean) const lead = members.find((card) => !card.hidden) || members[0] || { text: '' } // The presenter's wording (board.relabel) in place of the first card's text, as every screen shows it. const label = typeof group.label === 'string' && group.label.trim() ? group.label : '' return { kind: 'group', n: group.n, text: label || lead.text, label, leadText: lead.text, count: group.count, cardIds: group.cardIds.slice(), hidden: group.count === 0, column: id } }) const singles = cards.filter((card) => card.column === id && card.group === undefined && !inboxIds.has(card.cardId)) const single = (card) => ({ kind: 'card', cardId: card.cardId, text: card.text, column: id, acceptedAt: card.acceptedAt, ...(card.name ? { name: card.name } : {}), ...(card.fromGroup !== undefined ? { fromGroup: card.fromGroup } : {}), ...(card.waiting ? { waiting: true } : {}), ...(card.hidden ? { hidden: true } : {}) }) // The worker's own order: what the big screen shows (singles newest first), then what waits // (oldest first, the order "Show next" releases them), then hidden cards and groups. const shownOrder = new Map(screen.onScreen.filter((entry) => entry.cardId).map((entry, index) => [entry.cardId, index])) const onScreen = singles.filter((card) => !card.hidden && !card.waiting) .sort((a, b) => (shownOrder.has(a.cardId) ? shownOrder.get(a.cardId) : 1e9) - (shownOrder.has(b.cardId) ? shownOrder.get(b.cardId) : 1e9) || b.acceptedAt - a.acceptedAt) const waiting = singles.filter((card) => !card.hidden && card.waiting).sort((a, b) => a.acceptedAt - b.acceptedAt) const hidden = singles.filter((card) => card.hidden) const entries = [...groupEntries.filter((group) => !group.hidden), ...onScreen.map(single), ...waiting.map(single), ...groupEntries.filter((group) => group.hidden), ...hidden.map(single)] const count = groupEntries.reduce((sum, group) => sum + group.count, 0) + onScreen.length + waiting.length const own = release.columns && release.columns[id] return { id, label: labelOf(id), count, waiting: screen.waiting || 0, mode: own || null, entries } }) const entries = board ? board.entries : 0 const shown = board ? board.shown : 0 const waitingTotal = board ? board.waiting : 0 const released = release.all || release.groupsOnly || release.extra > 0 || Object.keys(release.columns || {}).length > 0 const strip = { limit, entries, shown, waiting: waitingTotal, released, all: !!release.all, groupsOnly: !!release.groupsOnly, // "Big screen every card · 16 · limit 24" (D1), "Big screen 24 of 40 · 16 waiting" (D7), // "Big screen every card · 40, past the limit of 24" (D12). text: waitingTotal > 0 ? `Big screen ${shown} of ${entries}` : 'Big screen every card', detail: waitingTotal > 0 ? `${waitingTotal} waiting` : limit === null ? `${shown} · no limit` : shown > limit ? `${shown}, past the limit of ${limit}` : `${shown} · limit ${limit}`, next: waitingTotal > 0 ? Math.min(12, waitingTotal) : 0, back: released && limit !== null ? limit : null, } const cardCount = board ? board.cardCount : 0 return { pollId: poll ? poll.pollId : state && state.pollId, question: (state && state.question) || (poll && poll.question) || '', phase, cardCount, newCount: inbox.length, frozen: phase === 'frozen', names: !!settings.names, cardChars: Number.isSafeInteger(settings.cardChars) && settings.cardChars > 0 ? settings.cardChars : 140, inbox, columns, strip, columnIds: options.map((option) => option.optionId), } } function bpFind(view, target) { if (!view || !target) return null for (const entry of view.inbox) if (target.cardId && entry.cardId === target.cardId) return entry for (const column of view.columns) { for (const entry of column.entries) { if (target.group !== undefined && entry.kind === 'group' && entry.n === target.group) return entry if (target.cardId && entry.kind === 'card' && entry.cardId === target.cardId) return entry } } return null } function bpDrop(source, target) { if (!source || !target) return null const same = (source.cardId && source.cardId === target.cardId) || (source.group !== undefined && source.group === target.group) if (same) return null const from = source.cardId ? { cardId: source.cardId } : { group: source.group } if (target.column) return { op: 'move', target: from, column: target.column } if (target.cardId) return { op: 'merge', source: from, target: { cardId: target.cardId } } if (target.group !== undefined) return { op: 'merge', source: from, target: { group: target.group } } return null } function bpMessage(pollId, intent) { if (!pollId || !intent) return null const target = (value) => value && typeof value.cardId === 'string' ? { cardId: value.cardId } : value && Number.isSafeInteger(value.group) ? { group: value.group } : null switch (intent.op) { case 'move': return target(intent.target) && intent.column ? { type: 'board.move', pollId, target: target(intent.target), column: intent.column } : null case 'merge': return target(intent.source) && target(intent.target) ? { type: 'board.merge', pollId, source: target(intent.source), target: target(intent.target) } : null case 'split': return Number.isSafeInteger(intent.group) ? { type: 'board.split', pollId, group: intent.group } : null case 'hide': return target(intent.target) ? { type: 'board.hide', pollId, target: target(intent.target), hidden: intent.hidden !== false } : null case 'freeze': return { type: 'board.freeze', pollId, frozen: intent.frozen !== false } case 'release': { if (intent.column) return ['all', 'groupsOnly', 'limit'].includes(intent.mode) ? { type: 'board.release', pollId, mode: intent.mode, column: intent.column } : null if (intent.mode === 'next') return { type: 'board.release', pollId, mode: 'next', count: Number.isSafeInteger(intent.count) && intent.count > 0 ? intent.count : 12 } return ['all', 'groupsOnly', 'limit'].includes(intent.mode) ? { type: 'board.release', pollId, mode: intent.mode } : null } case 'limit': return intent.limit === null || (Number.isSafeInteger(intent.limit) && intent.limit > 0) ? { type: 'board.limit', pollId, limit: intent.limit } : null case 'relabel': return Number.isSafeInteger(intent.group) && typeof intent.text === 'string' ? { type: 'board.relabel', pollId, group: intent.group, text: intent.text.trim() } : null default: return null } } function bpUndo(intent, view) { if (!intent || !view) return null const before = (target) => bpFind(view, target) switch (intent.op) { case 'hide': return { op: 'hide', target: intent.target, hidden: !(intent.hidden !== false) } case 'freeze': return { op: 'freeze', frozen: !(intent.frozen !== false) } case 'move': { const entry = before(intent.target) if (!entry) return null if (entry.kind === 'group') return { op: 'move', target: { group: entry.n }, column: entry.column } const group = view.columns.flatMap((column) => column.entries).find((item) => item.kind === 'group' && item.cardIds.includes(entry.cardId)) if (group) return { op: 'merge', source: { cardId: entry.cardId }, target: { group: group.n } } return { op: 'move', target: { cardId: entry.cardId }, column: entry.column } } case 'merge': { if (intent.source.group !== undefined) return null const source = before(intent.source) if (!source) return null // Onto a single card: the merge made a new group, whose number is known only once the worker // has made it; the undo splits the group that card is in then. if (intent.target.cardId && before(intent.target) && before(intent.target).kind === 'card') { return { op: 'split', groupOf: intent.target.cardId } } return { op: 'move', target: { cardId: source.cardId }, column: source.column } } case 'release': { if (intent.column) { const column = view.columns.find((item) => item.id === intent.column) return column && !column.mode ? { op: 'release', mode: 'limit', column: intent.column } : null } return view.strip.released ? null : { op: 'release', mode: 'limit' } } case 'limit': return view.strip.released ? null : { op: 'limit', limit: view.strip.limit } case 'relabel': { const group = before({ group: intent.group }) return group && group.kind === 'group' ? { op: 'relabel', group: intent.group, text: group.label || '' } : null } default: return null } } function bpResolve(intent, view) { if (!intent) return null if (intent.op === 'split' && intent.groupOf) { const group = view && view.columns.flatMap((column) => column.entries).find((entry) => entry.kind === 'group' && entry.cardIds.includes(intent.groupOf)) return group ? { op: 'split', group: group.n } : null } return intent } function bpToast(intent, view) { const entry = (target) => bpFind(view, target) const label = (id) => ((view && view.columns.find((column) => column.id === id)) || {}).label || id const name = (item) => item ? (item.kind === 'group' ? `${item.n} · ${item.text}` : item.text) : 'the card' switch (intent && intent.op) { case 'merge': { const target = entry(intent.target) const source = entry(intent.source) const adds = source ? (source.kind === 'group' ? source.count : 1) : 1 if (target && target.kind === 'group') return { text: `Merged into ${target.n} · ${target.text}`, detail: `now ×${target.count + adds}` } return { text: `Merged with ${target ? target.text : 'the card'}`, detail: `now ×${1 + adds}` } } case 'move': { const item = entry(intent.target) return { text: item && item.kind === 'group' ? `Group ${item.n} moved to ${label(intent.column)}` : `Moved to ${label(intent.column)}`, detail: item && item.kind === 'card' ? item.text : '' } } case 'split': { const item = entry({ group: intent.group }) return { text: `Group ${intent.group} split into its ${item ? item.cardIds.length : ''} cards.`.replace(' ', ' '), detail: `Number ${intent.group} retires` } } case 'hide': { const item = entry(intent.target) return intent.hidden !== false ? { text: item && item.kind === 'group' ? `Group ${item.n} hidden from the board` : 'Hidden from the board', detail: 'kept in the Run' } : { text: 'Back on the board', detail: name(item) } } case 'freeze': return intent.frozen !== false ? { text: 'Board frozen', detail: 'final: no new cards, no changes' } : { text: 'Board unfrozen', detail: 'sorting and new cards again' } case 'release': { if (intent.column) { const column = label(intent.column) return intent.mode === 'all' ? { text: `${column}: every card on the big screen`, detail: 'type smaller' } : intent.mode === 'groupsOnly' ? { text: `${column}: groups only on the big screen`, detail: 'its singles stay on phones' } : { text: `${column}: back to the limit`, detail: '' } } const strip = view ? view.strip : { entries: 0, waiting: 0, limit: 24 } if (intent.mode === 'next') return { text: `Showing ${Math.min(intent.count || 12, strip.waiting)} more on the big screen`, detail: 'oldest waiting first' } if (intent.mode === 'all') return { text: 'Every card on the big screen.', detail: `${strip.entries} of ${strip.entries} · type smaller` } if (intent.mode === 'groupsOnly') return { text: 'Groups only on the big screen', detail: 'singles stay on phones' } return { text: `Back to the limit${strip.limit === null ? '' : ` of ${strip.limit}`}`, detail: 'newest leave the screen' } } case 'limit': return { text: intent.limit === null ? 'No limit on the big screen' : `Big-screen limit: ${intent.limit} cards`, detail: '' } case 'relabel': return intent.text && intent.text.trim() ? { text: `Group ${intent.group} now reads: ${intent.text.trim()}`, detail: 'the cards keep theirs' } : { text: `Group ${intent.group} shows its first card again`, detail: '' } default: return { text: '', detail: '' } } } function bpRefusal(error) { const reasons = { board_frozen: 'The board is frozen. Unfreeze it to move, merge or split cards.', already_merged: 'Those cards are already together.', card_not_found: 'That card has gone from the board.', card_too_long: 'That wording is longer than a card on this board.', group_not_found: 'That group has gone from the board.', unknown_column: 'That column is not on this board.', board_not_found: 'This board is not open in the live session.', storage_failed: 'The live service could not save that. Try again.', } return reasons[error] || 'The board did not take that change. Try again.' } function bpAgo(acceptedAt, now) { const seconds = Math.max(0, Math.round((now - acceptedAt) / 1000)) if (seconds < 10) return 'just now' if (seconds < 60) return `${seconds} s` const minutes = Math.floor(seconds / 60) if (minutes < 60) return `${minutes} min` return `${Math.floor(minutes / 60)} h` } function createBoardController(options) { const send = options.send const store = options.store || null const now = options.now || (() => Date.now()) let poll = null let state = null let view = null let sorted = new Set() let last = null // { intent, undo, before } let waitingUndo = null // an undo pressed before the state it needs arrived let toast = null // { tone, text, detail, undo } let toastTimer = 0 let pick = null // { target, text } const listeners = new Set() const sortedKey = (pollId) => `tw-board-sorted:${pollId}` function loadSorted(pollId) { try { const raw = store && store.getItem(sortedKey(pollId)); return new Set(raw ? JSON.parse(raw) : []) } catch { return new Set() } } function saveSorted() { try { if (store && poll) store.setItem(sortedKey(poll.pollId), JSON.stringify([...sorted])) } catch { /* a per-window convenience only */ } } function changed() { for (const listener of listeners) { try { listener() } catch { /* one panel's failure never stops another */ } } } function rebuild() { view = poll ? bpView(poll, state, sorted) : null } function say(next, ms) { toast = next clearTimeout(toastTimer) if (next) toastTimer = setTimeout(() => { toast = null; changed() }, ms || 6000) changed() } async function dispatch(intent, { undoable = true } = {}) { if (!poll || !view) return false const message = bpMessage(poll.pollId, intent) if (!message) return false const before = view if (undoable) waitingUndo = null const undo = undoable ? bpUndo(intent, before) : null last = { intent, undo, before, message } const words = bpToast(intent, before) say({ tone: 'done', text: words.text, detail: words.detail, undo: Boolean(undo) }) let result try { result = await send(message) } catch { result = { success: false, error: 'storage_failed' } } if (!result || result.success === false || result.status === 'rejected') { if (last && last.message === message) last = null // A refused change leaves nothing to undo: an undo waiting for its state is dropped too. waitingUndo = null say({ tone: 'error', text: bpRefusal(result && result.error), detail: '', undo: false }, 8000) return false } return true } return { /** The board to show: its definition and the worker's latest presenter poll.state (or null). */ set(nextPoll, nextState) { // The board has gone (another slide, the session ended): its undo goes with it. if (!nextPoll) { poll = null; state = null; view = null; pick = null; last = null; waitingUndo = null; changed(); return } if (!poll || poll.pollId !== nextPoll.pollId) { sorted = loadSorted(nextPoll.pollId); last = null; waitingUndo = null; pick = null; toast = null } poll = nextPoll state = nextState || null // A card that has gone (withdrawn) no longer needs its sorted mark. const present = new Set((state && state.boardState && state.boardState.cards || []).map((card) => card.cardId)) if (state && state.boardState) for (const id of [...sorted]) if (!present.has(id)) sorted.delete(id) rebuild() if (pick && !bpFind(view, pick.target)) pick = null if (waitingUndo) { const intent = bpResolve(waitingUndo, view) if (intent) { waitingUndo = null; void dispatch(intent, { undoable: false }) } } changed() }, poll: () => poll, view: () => view, toast: () => toast, pick: () => pick, hasUndo: () => Boolean(last && last.undo), subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener) }, /** One gesture: one worker operation. */ apply: (intent) => dispatch(intent), /** ⌘Z: undo the last change, where one operation can. */ undo() { if (!last || !last.undo) return false const intent = bpResolve(last.undo, view) if (!intent) { // Undo pressed before the worker's answer: a merge of two singles has no group number yet. // The undo waits for the state that carries the new group (set() sends it), never lost. if (last.undo.groupOf) { waitingUndo = last.undo; last = null; say({ tone: 'done', text: 'Undoing…', detail: 'waiting for the board', undo: false }); return true } last = null say({ tone: 'error', text: 'That change cannot be undone now.', detail: '', undo: false }) return false } last = null void dispatch(intent, { undoable: false }) return true }, /** "Mark all sorted": the inbox is emptied here; nothing changes on any screen. */ markAllSorted() { if (!view) return for (const entry of view.inbox) sorted.add(entry.cardId) saveSorted(); rebuild(); changed() }, /** A rejected or confirmed board operation reported by the live bridge. */ operation(update) { if (!update || !update.message || !String(update.message.type || '').startsWith('board.')) return if (update.status === 'rejected') { if (last && last.message && JSON.stringify(last.message) === JSON.stringify(update.message)) last = null waitingUndo = null say({ tone: 'error', text: bpRefusal(update.error), detail: '', undo: false }, 8000) } }, dismissToast() { say(null) }, /** The keyboard's drag: pick up a card or group, then drop it on a card, group or column. */ pickUp(target) { const entry = bpFind(view, target) if (!entry || entry.hidden || (view && view.frozen)) return false pick = { target: entry.kind === 'group' ? { group: entry.n } : { cardId: entry.cardId }, text: entry.text, group: entry.kind === 'group' ? entry.n : null } changed() return true }, drop(target) { if (!pick) return false // As with a pointer drop: a hidden card or group is no target (the pick stays held). const onto = target && !target.column ? bpFind(view, target) : null if (target && !target.column && (!onto || onto.hidden)) return true const intent = bpDrop(pick.target, target) pick = null changed() if (intent) void dispatch(intent) return Boolean(intent) }, cancelPick() { if (!pick) return false; pick = null; changed(); return true }, now, } } function createBoardPanel(options) { const { doc, host, controller, actions } = options const icon = (name) => { const svg = options.icon(name); return svg ? doc.importNode(svg, true) : doc.createElement('span') } const keys = Object.assign({ primary: 'Q', undo: '⌘Z', pick: '⌥↵' }, options.keys || {}) let mode = options.mode || 'beside' let shown = false let menu = null // { kind, key, anchor } let drag = null let slideLabel = '' const root = host root.classList.add('bp') root.setAttribute('role', 'region') root.setAttribute('aria-label', 'Board') const el = (tag, className, text) => { const node = doc.createElement(tag) if (className) node.className = className if (text !== undefined && text !== null) node.textContent = String(text) return node } const button = (className, label, iconName, onClick, extra) => { const node = el('button', className) node.type = 'button' if (iconName) node.append(icon(iconName)) if (label) node.append(el('span', 'bp-label', label)) if (extra && extra.kbd) node.append(el('span', 'bp-kbd', extra.kbd)) if (extra && extra.tip) { node.dataset.tip = extra.tip; node.setAttribute('aria-label', extra.tip) } if (extra && extra.id) node.id = extra.id if (extra && extra.disabled) node.disabled = true // A mouse press never takes the keyboard from the slides (Space still moves to the next slide). node.addEventListener('mousedown', (event) => { if (event.button === 0) event.preventDefault() }) node.addEventListener('click', (event) => { event.stopPropagation(); onClick(event) }) return node } const targetOf = (node) => { try { return JSON.parse(node.dataset.target) } catch { return null } } const keyOf = (target) => target ? (target.cardId ? `c:${target.cardId}` : target.group !== undefined ? `g:${target.group}` : `k:${target.column}`) : '' // ── Header ───────────────────────────────────────────────────────────────────────────── function header(view) { const head = el('header', 'bp-head') const title = el('div', 'bp-title') title.append(icon('layout-grid'), el('b', '', 'Board')) const counts = el('span', 'bp-counts', `${view.cardCount} ${view.cardCount === 1 ? 'card' : 'cards'}`) if (view.newCount && !view.frozen) counts.append(doc.createTextNode(' · '), el('span', 'bp-new', `${view.newCount} new`)) title.append(counts) const chip = el('span', `bp-chip is-${view.phase}`) if (view.phase === 'closed') chip.append(icon('lock')) if (view.phase === 'frozen') chip.append(icon('snowflake')) chip.append(doc.createTextNode({ open: 'Open', closed: 'Closed', frozen: 'Frozen', ready: 'Not open yet' }[view.phase])) title.append(chip) head.append(title, el('span', 'bp-spacer')) if (view.phase === 'frozen') head.append(button('bp-btn', 'Unfreeze', 'lock-open', () => controller.apply({ op: 'freeze', frozen: false }), { id: 'boardUnfreeze' })) else if (view.phase === 'open') head.append(button('bp-btn', 'Close to new cards', 'lock', () => actions.primary(), { kbd: keys.primary, id: 'boardPrimary' })) else head.append(button('bp-btn', view.phase === 'closed' ? 'Reopen' : 'Open board', 'lock-open', () => actions.primary(), { kbd: keys.primary, id: 'boardPrimary' })) if (mode === 'beside') { head.append(button('bp-icon-btn', '', 'maximize-2', () => actions.fullScreen(true), { tip: 'Board full screen', id: 'boardFullScreen' })) head.append(button('bp-icon-btn', '', 'picture-in-picture-2', () => actions.popOut(), { tip: 'Pop out the board · its own window, for another screen', id: 'boardPopOut' })) head.append(button('bp-icon-btn', '', 'x', () => actions.close(), { tip: 'Close the board panel', id: 'boardClose' })) } else if (mode === 'full') { head.append(button('bp-btn', 'Exit full screen', 'minimize-2', () => actions.fullScreen(false), { id: 'boardExitFullScreen' })) head.append(button('bp-btn', 'Pop out', 'picture-in-picture-2', () => actions.popOut(), { id: 'boardPopOut' })) head.append(button('bp-icon-btn', '', 'x', () => actions.close(), { tip: 'Close the board panel', id: 'boardClose' })) } else { head.append(button('bp-btn', 'Put back in the presenter window', 'picture-in-picture-2', () => actions.putBack(), { id: 'boardPutBack', tip: 'Put back · the board returns beside the slide in the presenter window' })) } return head } // ── The big-screen strip and its menu ────────────────────────────────────────────────── function strip(view, stacked) { const box = el('div', stacked ? 'bp-strip is-stacked' : 'bp-strip') const words = el('span', 'bp-strip-words') words.append(icon('monitor'), doc.createTextNode(' ')) words.append(el('span', 'bp-strip-text', view.strip.text), doc.createTextNode(' · ')) words.append(el('span', view.strip.waiting ? 'bp-strip-waiting' : 'bp-strip-detail', view.strip.detail)) box.append(words) const controls = el('span', 'bp-strip-controls') if (view.strip.waiting > 0) { controls.append(button('bp-btn', `Show next ${view.strip.next}`, 'list-end', () => controller.apply({ op: 'release', mode: 'next', count: 12 }), { id: 'boardShowNext' })) controls.append(button('bp-btn', 'Show all', 'monitor-up', () => controller.apply({ op: 'release', mode: 'all' }), { id: 'boardShowAll' })) } else if (view.strip.back !== null) { controls.append(button('bp-btn', `Back to ${view.strip.back}`, 'monitor-off', () => controller.apply({ op: 'release', mode: 'limit' }), { id: 'boardBackToLimit' })) } const more = button('bp-icon-btn', '', 'chevron-down', (event) => toggleMenu({ kind: 'screen', key: 'screen' }, event.currentTarget), { tip: 'Big screen', id: 'boardScreenMenu' }) more.setAttribute('aria-haspopup', 'menu') controls.append(more) box.append(controls) return box } // ── The inbox ────────────────────────────────────────────────────────────────────────── function inbox(view, oneColumn) { const box = el('section', 'bp-inbox') const head = el('div', 'bp-inbox-head') const title = el('span', 'bp-inbox-title') title.append(icon('inbox'), el('b', '', 'New'), el('span', 'bp-num-muted', String(view.newCount)), doc.createTextNode(' · not sorted, already on screen')) head.append(title) if (view.newCount) head.append(button('bp-link', 'Mark all sorted', '', () => controller.markAllSorted(), { id: 'boardMarkSorted' })) box.append(head) if (!view.inbox.length) { box.append(el('p', 'bp-empty', view.frozen ? 'The board is frozen. Nothing new arrives.' : 'Nothing new. Cards you have not sorted arrive here, newest first.')) return box } const list = el('div', oneColumn ? 'bp-inbox-list is-one' : 'bp-inbox-list') for (const entry of view.inbox) list.append(card(view, entry, { inbox: true })) box.append(list) return box } // ── Cards and groups ─────────────────────────────────────────────────────────────────── function card(view, entry, where) { const group = entry.kind === 'group' const target = group ? { group: entry.n } : { cardId: entry.cardId } const node = el('div', 'bp-card') node.classList.toggle('is-group', group) node.classList.toggle('is-waiting', !!entry.waiting) node.classList.toggle('is-hidden', !!entry.hidden) node.classList.toggle('is-from-group', entry.fromGroup !== undefined) node.tabIndex = 0 node.setAttribute('role', 'button') node.setAttribute('aria-haspopup', 'menu') node.dataset.target = JSON.stringify(target) node.dataset.key = keyOf(target) if (!entry.hidden) node.dataset.drop = 'entry' const pick = controller.pick() if (pick && keyOf(pick.target) === keyOf(target)) node.classList.add('is-picked') const draggable = !entry.hidden && !view.frozen if (draggable) node.dataset.drag = '1' const grip = el('span', 'bp-grip') grip.append(icon('grip-vertical')) const body = el('span', 'bp-card-body') const line = el('span', 'bp-card-line') if (group) line.append(el('span', 'bp-n', String(entry.n))) line.append(el('span', 'bp-text', entry.text)) body.append(line) const meta = [] if (where && where.inbox) { const to = el('span', 'bp-meta') to.append(icon('arrow-right'), el('b', '', (view.columns.find((column) => column.id === entry.column) || {}).label || entry.column), doc.createTextNode(` · ${bpAgo(entry.acceptedAt, controller.now())}`)) meta.push(to) } if (entry.hidden) { const m = el('span', 'bp-meta is-hidden-note'); m.append(icon('eye-off'), doc.createTextNode(group ? 'Group hidden · kept in the Run' : 'Hidden · kept in the Run')); meta.push(m) } else if (entry.waiting && !(where && where.inbox)) { const m = el('span', 'bp-meta is-waiting-note'); m.append(icon('monitor-off'), doc.createTextNode('Waiting')); meta.push(m) } if (entry.fromGroup !== undefined) { const m = el('span', 'bp-meta is-from'); m.append(icon('ungroup'), doc.createTextNode(`From group ${entry.fromGroup}`)); meta.push(m) } if (view.names && entry.name) meta.push(el('span', 'bp-meta is-name', entry.name)) for (const m of meta) body.append(m) node.append(grip, body) if (group) node.append(el('span', 'bp-x', `×${entry.count}`)) const words = group ? `Group ${entry.n}, ${entry.count} cards: ${entry.text}` : entry.text node.setAttribute('aria-label', `${words}${entry.waiting ? ', waiting' : ''}${entry.hidden ? ', hidden' : ''}`) return node } function column(view, col) { const node = el('section', 'bp-col') node.dataset.drop = 'column' node.dataset.target = JSON.stringify({ column: col.id }) node.dataset.key = keyOf({ column: col.id }) const head = el('div', 'bp-col-head') const name = el('span', 'bp-col-name') name.tabIndex = 0 name.dataset.target = node.dataset.target name.dataset.dropHead = '1' name.setAttribute('aria-label', `${col.label} column, ${col.count} cards${col.waiting ? `, ${col.waiting} waiting` : ''}`) name.append(el('b', '', col.label), el('span', 'bp-num-muted', String(col.count))) if (col.waiting) name.append(el('span', 'bp-col-waiting', ` · ${col.waiting} waiting`)) if (col.mode === 'groupsOnly') name.append(el('span', 'bp-col-mode', ' · groups only')) if (col.mode === 'all') name.append(el('span', 'bp-col-mode', ' · every card')) head.append(name) const more = button('bp-icon-btn is-small', '', 'ellipsis', (event) => toggleMenu({ kind: 'column', key: col.id }, event.currentTarget), { tip: `${col.label} on the big screen` }) more.setAttribute('aria-haspopup', 'menu') more.dataset.columnMenu = col.id head.append(more) const list = el('div', 'bp-col-list') for (const entry of col.entries) list.append(card(view, entry)) node.append(head, list) return node } // ── Menus ────────────────────────────────────────────────────────────────────────────── function toggleMenu(next, anchor) { if (menu && menu.kind === next.kind && menu.key === next.key) { menu = null; render(); return } menu = { ...next, anchorKey: anchor && (anchor.dataset.key || anchor.id || anchor.dataset.columnMenu) } render() const first = root.querySelector('.bp-menu button:not(:disabled)') if (first && next.focus) first.focus() } function closeMenu() { if (!menu) return false; menu = null; render(); return true } function item(label, sub, iconName, run, extra) { const node = button(`bp-mi${extra && extra.checked ? ' is-checked' : ''}`, label, iconName, () => { menu = null; run(); render() }, extra) node.setAttribute('role', extra && extra.checked !== undefined ? 'menuitemcheckbox' : 'menuitem') if (extra && extra.checked !== undefined) node.setAttribute('aria-checked', String(!!extra.checked)) if (sub) node.append(el('span', 'bp-mi-sub', sub)) return node } function chips(label, columns, current, run) { const row = el('div', 'bp-mi-row') row.append(el('span', 'bp-mi-sec', label)) const set = el('span', 'bp-chips') for (const col of columns) set.append(button(`bp-chip-btn${col.id === current ? ' is-current' : ''}`, col.label, '', () => { menu = null; run(col.id); render() })) row.append(set) return row } function menuBody(view) { const box = el('div', 'bp-menu') box.setAttribute('role', 'menu') if (menu.kind === 'screen') { box.setAttribute('aria-label', 'Big screen') box.append(el('div', 'bp-mi-sec', 'Big screen')) box.append(item(`Show next ${view.strip.next || 12}`, 'oldest waiting first', 'list-end', () => controller.apply({ op: 'release', mode: 'next', count: 12 }), { disabled: !view.strip.waiting })) box.append(item(view.strip.waiting ? `Show all ${view.strip.waiting} waiting` : 'Show every card', 'type gets smaller', 'monitor-up', () => controller.apply({ op: 'release', mode: 'all' }), { checked: view.strip.all })) box.append(item('Groups only', 'singles stay on phones', 'group', () => controller.apply({ op: 'release', mode: view.strip.groupsOnly ? 'limit' : 'groupsOnly' }), { checked: view.strip.groupsOnly })) box.append(item(`Back to the limit${view.strip.limit === null ? '' : ` (${view.strip.limit})`}`, 'newest leave the screen', 'monitor-off', () => controller.apply({ op: 'release', mode: 'limit' }), { disabled: !view.strip.released })) const row = el('div', 'bp-mi-row') const label = el('span', 'bp-mi-sec') label.append(icon('monitor'), doc.createTextNode(` Limit: ${view.strip.limit === null ? 'all cards' : `${view.strip.limit} cards`}`)) row.append(label) const set = el('span', 'bp-chips') for (const value of [12, 24, 36, null]) { set.append(button(`bp-chip-btn${value === view.strip.limit ? ' is-current' : ''}`, value === null ? 'All' : String(value), '', () => { menu = null; if (value !== view.strip.limit) controller.apply({ op: 'limit', limit: value }); render() })) } row.append(set) box.append(row) return box } if (menu.kind === 'column') { const col = view.columns.find((item) => item.id === menu.key) if (!col) return null box.setAttribute('aria-label', `${col.label} on the big screen`) box.append(el('div', 'bp-mi-sec', `${col.label} on the big screen`)) if (col.waiting) box.append(item(`Show ${col.label}’s ${col.waiting} waiting`, '', 'list-end', () => controller.apply({ op: 'release', mode: 'all', column: col.id }))) box.append(item(`${col.label}: groups only`, 'hide its overflow', 'group', () => controller.apply({ op: 'release', mode: col.mode === 'groupsOnly' ? 'limit' : 'groupsOnly', column: col.id }), { checked: col.mode === 'groupsOnly' })) if (!col.waiting) box.append(item(`${col.label}: every card`, '', 'monitor-up', () => controller.apply({ op: 'release', mode: col.mode === 'all' ? 'limit' : 'all', column: col.id }), { checked: col.mode === 'all' })) if (col.mode) box.append(item(`${col.label}: back to the limit`, '', 'monitor-off', () => controller.apply({ op: 'release', mode: 'limit', column: col.id }))) return box } const menuAnchor = menu.anchorKey if (menu.kind === 'relabel') { // "Edit the group's wording" (D13): the words every screen shows for the group; its cards keep theirs. const group = bpFind(view, { group: Number(menu.key) }) if (!group || group.kind !== 'group' || view.frozen) return null box.setAttribute('role', 'dialog') box.setAttribute('aria-label', `Group ${group.n}: its wording`) box.append(el('div', 'bp-mi-sec', `Group ${group.n} · its wording on every screen`)) const form = el('form', 'bp-relabel') const input = el('input', 'bp-relabel-input') input.type = 'text' input.maxLength = view.cardChars // A draft survives the panel being drawn again as cards arrive while the presenter types. input.value = typeof menu.draft === 'string' ? menu.draft : group.label || group.leadText || '' input.id = 'boardRelabelInput' input.setAttribute('aria-label', `Wording for group ${group.n}`) input.dataset.relabelInput = '1' const draftOf = menu input.addEventListener('input', () => { draftOf.draft = input.value }) const row = el('div', 'bp-relabel-row') const save = button('bp-btn', 'Save', 'check', () => form.requestSubmit(), { id: 'boardRelabelSave' }) const reset = button('bp-btn', 'Use the first card’s words', 'undo-2', () => { menu = null; controller.apply({ op: 'relabel', group: group.n, text: '' }); render() }, { id: 'boardRelabelClear', disabled: !group.label }) row.append(save, reset) form.append(input, row, el('p', 'bp-note', `Up to ${view.cardChars} characters. The cards in the group keep their own words.`)) form.addEventListener('submit', (event) => { event.preventDefault() const text = input.value.trim() menu = null if (text !== (group.label || '') && !(text === group.leadText && !group.label)) controller.apply({ op: 'relabel', group: group.n, text }) render() }) box.append(form) return box } const target = menu.kind === 'group' ? { group: Number(menu.key) } : { cardId: menu.key } const entry = bpFind(view, target) if (!entry) return null if (entry.kind === 'group') { box.setAttribute('aria-label', `Group ${entry.n}`) box.append(el('div', 'bp-mi-sec', `Group ${entry.n} · ${entry.cardIds.length} cards`)) if (entry.hidden) { box.append(item('Put the group back', 'on every screen again', 'eye', () => controller.apply({ op: 'hide', target, hidden: false }))) return box } box.append(item(`Split into its ${entry.cardIds.length} cards`, 'number retires', 'ungroup', () => controller.apply({ op: 'split', group: entry.n }), { disabled: view.frozen })) box.append(item('Merge into…', `or drag onto a card · ${keys.pick}`, 'group', () => { controller.pickUp(target); focusKey(keyOf(target)) }, { disabled: view.frozen })) if (!view.frozen) box.append(chips('Move the whole group to', view.columns, entry.column, (column) => controller.apply({ op: 'move', target, column }))) box.append(item('Edit the group’s wording', 'cards keep theirs', 'pencil', () => { menu = { kind: 'relabel', key: String(entry.n), anchorKey: menuAnchor, focus: true } }, { disabled: view.frozen, id: 'boardRelabel' })) box.append(item('Hide the group', `all ${entry.cardIds.length} cards, kept in the Run`, 'eye-off', () => controller.apply({ op: 'hide', target, hidden: true }))) return box } box.setAttribute('aria-label', 'Card') if (entry.hidden) { box.append(item('Put back on the board', 'on every screen again', 'eye', () => controller.apply({ op: 'hide', target, hidden: false }))) return box } box.append(item('Merge into…', `or drag onto a card · ${keys.pick}`, 'group', () => { controller.pickUp(target); focusKey(keyOf(target)) }, { disabled: view.frozen })) if (!view.frozen) box.append(chips('Move to column', view.columns, null, (column) => controller.apply({ op: 'move', target, column }))) box.append(item('Hide from the board', 'kept in the Run', 'eye-off', () => controller.apply({ op: 'hide', target, hidden: true }), { danger: true })) return box } function placeMenu(box) { const anchor = menu.anchorKey && [...root.querySelectorAll('[data-key], [id], [data-column-menu]')] .find((node) => node.dataset.key === menu.anchorKey || node.id === menu.anchorKey || node.dataset.columnMenu === menu.anchorKey) const rootBox = root.getBoundingClientRect() const a = anchor ? anchor.getBoundingClientRect() : rootBox const width = Math.min(360, rootBox.width - 16) box.style.width = `${width}px` let left = Math.min(Math.max(8, a.right - rootBox.left - width), rootBox.width - width - 8) let top = a.bottom - rootBox.top + 4 box.style.left = `${left}px` box.style.top = `${top}px` // Keep it inside the panel: open upward when it would run off the bottom. const h = box.getBoundingClientRect().height if (top + h > rootBox.height - 8) { top = Math.max(8, a.top - rootBox.top - h - 4); box.style.top = `${top}px` } } // ── Toast and the keyboard pick ──────────────────────────────────────────────────────── function toastEl() { const toast = controller.toast() if (!toast || !toast.text) return null const box = el('div', `bp-toast is-${toast.tone}`) box.setAttribute('role', 'status') box.append(icon(toast.tone === 'error' ? 'circle-alert' : 'circle-check')) const words = el('span', 'bp-toast-words') words.append(el('b', '', toast.text)) if (toast.detail) words.append(doc.createTextNode(' '), el('span', 'bp-toast-detail', toast.detail)) box.append(words) if (toast.undo && controller.hasUndo()) box.append(button('bp-btn is-undo', 'Undo', 'undo-2', () => controller.undo(), { kbd: keys.undo, id: 'boardUndo' })) return box } function pickEl() { const pick = controller.pick() if (!pick) return null const box = el('div', 'bp-pickbar') box.setAttribute('role', 'status') box.append(icon('hand'), el('b', '', `Holding ${pick.group !== null ? `group ${pick.group}` : 'a card'}: `), el('span', 'bp-pick-text', pick.text)) box.append(el('span', 'bp-pick-help', ` · ${keys.pick} on a card or group to merge, on a column name to move · Esc puts it down`)) return box } // ── Render ───────────────────────────────────────────────────────────────────────────── function focusKey(key) { const node = key && [...root.querySelectorAll('[data-key]')].find((item) => item.dataset.key === key && item.tabIndex >= 0) if (node) node.focus({ preventScroll: false }) } // The panel's frame is kept between draws: the monitor holds an iframe, which would reload if it // were moved or rebuilt on every change of the board. let frame = null function skeleton() { if (frame && frame.mode === mode && frame.rail === (mode !== 'beside')) return frame root.replaceChildren() frame = { mode, rail: mode !== 'beside' } if (frame.rail) { frame.railEl = el('aside', 'bp-rail') const monitorWrap = el('div', 'bp-monitor-wrap') frame.monitor = el('div', 'bp-monitor preview') monitorWrap.append(frame.monitor) frame.railBody = el('div', 'bp-rail-body') frame.railEl.append(monitorWrap, frame.railBody) root.append(frame.railEl) } frame.main = el('div', 'bp-main') frame.layer = el('div', 'bp-layer') root.append(frame.main, frame.layer) return frame } function render() { if (drag) return // the board is redrawn when the drag ends const view = controller.view() root.hidden = !shown || !view root.dataset.mode = mode if (root.hidden) return const active = doc.activeElement && root.contains(doc.activeElement) ? (doc.activeElement.dataset.key || doc.activeElement.id || '') : '' const scrolls = [...root.querySelectorAll('.bp-col-list, .bp-inbox-list')].map((node) => node.scrollTop) const parts = skeleton() if (actions.place) actions.place(root, mode) root.classList.toggle('is-frozen', view.frozen) root.classList.toggle('is-picking', Boolean(controller.pick())) const main = parts.main main.replaceChildren(header(view)) if (mode === 'beside') { main.append(strip(view, false), inbox(view, false)) } else { const screen = el('div', 'bp-screen') const heading = el('div', 'bp-screen-head') heading.append(icon('presentation'), doc.createTextNode(`On the big screen now${slideLabel ? ` · ${slideLabel}` : ''}`)) screen.append(heading, strip(view, true)) const note = el('p', 'bp-note') note.append(icon('monitor-off'), doc.createTextNode('Cards past the limit wait with a dashed edge. Phones show every card at once.')) screen.append(note) parts.railBody.replaceChildren(screen, inbox(view, true)) try { actions.monitor(parts.monitor) } catch { /* the monitor is a picture of the room's screen only */ } } const cols = el('div', 'bp-cols') cols.style.setProperty('--bp-columns', String(Math.max(1, view.columns.length))) for (const col of view.columns) cols.append(column(view, col)) main.append(cols) const pickBar = pickEl() if (pickBar) main.append(pickBar) parts.layer.replaceChildren() const toast = toastEl() if (toast) { parts.layer.append(toast); placeToast(toast) } if (menu) { const box = menuBody(view) if (box) { parts.layer.append(box); placeMenu(box) if (menu.focus) { menu.focus = false; const field = box.querySelector('[data-relabel-input]'); if (field) { field.focus(); field.select() } } } else menu = null } ;[...root.querySelectorAll('.bp-col-list, .bp-inbox-list')].forEach((node, index) => { if (scrolls[index]) node.scrollTop = scrolls[index] }) if (active) { const back = [...root.querySelectorAll('[data-key], [id]')].find((node) => node.dataset.key === active || node.id === active) if (back && (back.tabIndex >= 0 || back.tagName === 'BUTTON')) { back.focus({ preventScroll: true }) if (back.tagName === 'INPUT') { const end = back.value.length; back.setSelectionRange(end, end) } } } } function placeToast(toast) { const box = mode === 'beside' && actions.toastBox ? actions.toastBox() : null if (box) { toast.style.position = 'fixed'; toast.style.left = `${box.left}px`; toast.style.top = `${box.top}px` } } // ── Drag and drop (pointer) ──────────────────────────────────────────────────────────── function dropAt(x, y) { const hit = doc.elementFromPoint(x, y) if (!hit || !root.contains(hit)) return null const entry = hit.closest('[data-drop="entry"]') if (entry) return { node: entry, target: targetOf(entry) } const col = hit.closest('[data-drop="column"]') if (col) return { node: col, target: targetOf(col) } return null } function dropWords(view, source, target) { const intent = bpDrop(source, target) if (!intent) return '' if (intent.op === 'move') return `Move to ${(view.columns.find((column) => column.id === intent.column) || {}).label || intent.column}` const into = bpFind(view, intent.target) const from = bpFind(view, source) const adds = from && from.kind === 'group' ? from.count : 1 return `Merge · ×${(into && into.kind === 'group' ? into.count : 1) + adds}` } root.addEventListener('pointerdown', (event) => { if (event.button !== 0) return const node = event.target.closest('[data-drag]') if (!node || event.target.closest('button')) return event.preventDefault() drag = { node, source: targetOf(node), x: event.clientX, y: event.clientY, moved: false, ghost: null, over: null, pill: null, pointerId: event.pointerId } try { node.setPointerCapture(event.pointerId) } catch { /* synthetic pointers */ } }) root.addEventListener('pointermove', (event) => { if (!drag) return const dx = event.clientX - drag.x, dy = event.clientY - drag.y if (!drag.moved && Math.hypot(dx, dy) < 5) return const view = controller.view() if (!drag.moved) { drag.moved = true const rect = drag.node.getBoundingClientRect() drag.ghost = drag.node.cloneNode(true) drag.ghost.classList.add('bp-ghost') drag.ghost.style.width = `${rect.width}px` drag.offset = { x: drag.x - rect.left, y: drag.y - rect.top } root.append(drag.ghost) drag.node.classList.add('is-dragging') root.classList.add('is-dragging') } const rootBox = root.getBoundingClientRect() drag.ghost.style.left = `${event.clientX - rootBox.left - drag.offset.x + 8}px` drag.ghost.style.top = `${event.clientY - rootBox.top - drag.offset.y + 6}px` const over = dropAt(event.clientX, event.clientY) const valid = over && bpDrop(drag.source, over.target) ? over : null if (drag.over && drag.over.node !== (valid && valid.node)) drag.over.node.classList.remove('is-drop-card', 'is-drop-column') if (drag.pill) { drag.pill.remove(); drag.pill = null } drag.over = valid if (valid) { valid.node.classList.add(valid.target.column ? 'is-drop-column' : 'is-drop-card') const pill = el('div', 'bp-drop-pill') pill.append(icon(valid.target.column ? 'arrow-right' : 'group'), doc.createTextNode(dropWords(view, drag.source, valid.target))) const r = valid.node.getBoundingClientRect() pill.style.left = `${Math.max(4, r.left - rootBox.left + 50)}px` pill.style.top = `${Math.max(4, r.top - rootBox.top - 16)}px` root.append(pill) drag.pill = pill } }) function endDrag(event, cancelled) { if (!drag) return const current = drag drag = null try { current.node.releasePointerCapture(current.pointerId) } catch { /* released already */ } if (current.ghost) current.ghost.remove() if (current.pill) current.pill.remove() root.classList.remove('is-dragging') current.node.classList.remove('is-dragging') if (!current.moved) { // A press without a move opens the card's menu. render() if (!cancelled) openEntryMenu(current.source, current.node.dataset.key) return } const intent = !cancelled && current.over ? bpDrop(current.source, current.over.target) : null render() if (intent) void controller.apply(intent) } root.addEventListener('pointerup', (event) => endDrag(event, false)) root.addEventListener('pointercancel', (event) => endDrag(event, true)) root.addEventListener('contextmenu', (event) => { const node = event.target.closest('.bp-card') if (!node) return event.preventDefault() openEntryMenu(targetOf(node), node.dataset.key) }) function openEntryMenu(target, key) { if (!target) return menu = target.group !== undefined ? { kind: 'group', key: String(target.group), anchorKey: key } : { kind: 'card', key: target.cardId, anchorKey: key } render() } // A press outside an open menu closes it. doc.addEventListener('pointerdown', (event) => { if (!menu) return if (event.target.closest && (event.target.closest('.bp-menu') || event.target.closest('[aria-haspopup="menu"]'))) return closeMenu() }, true) // ── Keys (registry: presenter.board-pick, presenter.board-undo, presenter.close, picker.choose) ── root.addEventListener('keydown', (event) => { if (boardPanelKey(event)) { event.preventDefault(); event.stopPropagation() } }) doc.addEventListener('keydown', (event) => { if (!shown || root.hidden) return if (boardUndoKey(event)) { event.preventDefault(); event.stopPropagation() } }, true) function boardUndoKey(event) { const typing = event.target && (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA' || event.target.isContentEditable) if (typing) return false // ⌘Z while the panel shows is the board's undo, even with nothing to undo (never the gallery's Z). if ((event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'z') { controller.undo(); return true } // In the board's own window Q still opens, closes or reopens the board, as it does beside the slide. if (mode === 'window' && (event.key === 'q' || event.key === 'Q') && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey) { actions.primary(); return true } // Esc in the board's own window: the most local thing first (menu, then the pick). if (mode === 'window' && event.key === 'Escape') return closeMenu() || controller.cancelPick() return false } function boardPanelKey(event) { const node = event.target if (event.key === 'Escape') { if (closeMenu()) return true if (controller.cancelPick()) return true if (mode === 'full') { actions.fullScreen(false); return true } return false } if (event.altKey && !event.metaKey && !event.ctrlKey && event.key === 'Enter') { const target = node && node.dataset && node.dataset.target ? targetOf(node) : null if (!target) return false const key = keyOf(target) if (controller.pick()) { controller.drop(target); focusKey(key); return true } if (target.column) return false controller.pickUp(target) focusKey(key) return true } // ↵ or Space on a focused card opens its menu; on a button they press it (and never reach the // presenter's own ↵ / Space, which move to the next slide). if ((event.key === 'Enter' || event.key === ' ') && !event.altKey && !event.metaKey && !event.ctrlKey) { if (node && node.classList && node.classList.contains('bp-card')) { openEntryMenu(targetOf(node), node.dataset.key) const first = root.querySelector('.bp-menu button:not(:disabled)') if (first) first.focus() return true } if (node && node.tagName === 'BUTTON') { event.stopPropagation(); return false } } return false } return { el: root, show(value) { shown = Boolean(value); if (!shown) menu = null; render() }, setMode(next) { mode = next; menu = null; render() }, mode: () => mode, setSlideLabel(value) { slideLabel = value || '' }, render, isOpen: () => shown && !root.hidden, } } const presenterPollStates = new Map(); const presenterPollDefinitions = new Map(); let activeQuickPollId = null; let dismissedPresenterPollId = null; // presenter hid the panel for this poll let lastPollPanelSlideId = null; // resets the dismiss when the slide changes const instantCompose = document.getElementById('presenterInstantCompose'); const instantPaste = document.getElementById('presenterInstantPaste'); const instantStrip = document.getElementById('presenterInstantStrip'); // The talk's QR code (and its link, when the talk has a published handout) sits bottom-right of // the clock and break slides on every surface in this window. Only the projector window, the // room display, plays the end-of-break chime; the presenter's own preview never does. function instantBreakQr() { const link = talkQrLink(); if (!link || !link.svg) return null; // The QR keeps the talk QR's content (the live join link while live); the written link is always the published handout, from the stamp. const handout = document.getElementById("twTalkQr")?.getAttribute("data-url") || ""; return { svg: link.svg, url: link.url, link: Boolean(handout), linkUrl: handout }; } const instantCurrent = isPresenter ? createInstantSlideSurface(els.currentPreview, { thumbnail: true, showQr: true, qr: instantBreakQr }) : null; // Only the audience (projector) window chimes: a plain presentation window open beside it must not double it. const instantChime = isAudience ? createBreakChime(window) : null; // The app's main process calls this from a user-gesture executeJavaScript so the chime's audio context starts without a click. window.__twUnlockChime = () => { instantChime?.unlock(); }; const instantProjector = !isPresenter ? createInstantSlideSurface(document.body, { qr: instantBreakQr, showQr: true, clickable: false, ...(instantChime ? { chime: instantChime } : {}) }) : null; const instantComposeThumb = createInstantSlideSurface(document.getElementById('instantComposeThumb'), { thumbnail: true, showQr: true, qr: instantBreakQr }); const instantPasteThumb = createInstantSlideSurface(document.getElementById('instantPasteThumb'), { thumbnail: true, showQr: true }); const instantSoundKey = 'html-presentations:instant-sound'; // Remembered as the last choice. Older builds stored 'on' or 'off'. let instantSound = 'chime'; try { const stored = localStorage.getItem(instantSoundKey); instantSound = instantEndSound({ endSound: stored, soundAtEnd: stored === 'off' ? false : undefined }); } catch {} // QR codes for composer links come from the app (main process), cached by address. const instantLinkQrs = new Map(); function instantLinkQr(url) { if (instantLinkQrs.has(url)) return instantLinkQrs.get(url); instantLinkQrs.set(url, ''); try { Promise.resolve(window.twLivePollBridge?.qrSvg?.(url)).then((result) => { if (result?.success && result.svg) { instantLinkQrs.set(url, result.svg); renderInstantDraft(); } }).catch(() => {}); } catch {} return ''; } let instantLinkError = ''; const instantStorageKey = `html-presentations:${deckId}:instant`; let instantActive = null; let instantDraft = null; let instantTab = 'text'; let instantClock = 'time'; let instantMinutes = 5; let instantPending = false; let instantImage = null; let instantImageError = ''; let instantImageGeneration = 0; function instantSummary(slide) { const written = slide?.link ? writtenInstantLink(slide.link) : null; return slide?.kind === 'text' ? (written ? `${slide.text} · ${written.host}${written.path}` : slide.text) : slide?.kind === 'link' ? slide.url : slide?.kind === 'image' ? `Image · ${slide.width} × ${slide.height}` : slide?.kind === 'countdown' ? `${slide.label || 'Countdown'} · ${Math.round(slide.durationMs / 60000)} minutes` : 'Current time'; } function applyInstantSlide(slide, broadcast = false) { instantActive = slide; if (isPresenter) { if (!els.currentPreview.contains(instantCurrent.element)) els.currentPreview.appendChild(instantCurrent.element); instantCurrent.show(slide); instantStrip.hidden = !slide; if (slide) { document.getElementById('presenterInstantSummary').textContent = instantSummary(slide); document.getElementById('presenterInstantSlideNumber').textContent = String(clampBeat(state.beat) + 1); els.nextPreviewLabel.textContent = `back to slide ${clampBeat(state.beat) + 1}`; previewSlide(els.nextPreview, currentSlide(), state.reveal, state.mode, beats[clampBeat(state.beat)], clampBeat(state.beat)); } else renderPresenter(); if (broadcast) { try { localStorage.setItem(instantStorageKey, JSON.stringify(slide)); } catch {} sendToPeer({ type: commandType, command: 'instant', slide }); } } else instantProjector?.show(slide); } function closeInstantPanels() { instantCompose.hidden = true; instantPaste.hidden = true; } function instantCandidate() { const shownAt = Date.now(); instantLinkError = ''; if (instantTab === 'image') return instantImage ? { ...instantImage, shownAt } : null; if (instantTab === 'clock' && instantClock === 'time') return { kind: 'time', shownAt }; // The Link field (text and countdown slides): a bare address gets https://, anything but http(s) is refused. const link = normaliseInstantLink(document.getElementById('instantLink').value); if (link.error) { instantLinkError = link.error; return null; } const linkFields = link.url ? { link: link.url, ...(instantLinkQr(link.url) ? { linkQrSvg: instantLinkQr(link.url) } : {}) } : {}; if (instantTab === 'text') { const text = document.getElementById('instantText').value.trim().slice(0, 2000); if (!text && link.url) return { kind: 'link', url: link.url, qrSvg: instantLinkQr(link.url), shownAt }; if (text && link.url) return { kind: 'text', text, ...linkFields, shownAt }; return instantSlideFromText(text, shownAt); } return { kind: 'countdown', startedAt: shownAt, durationMs: instantMinutes * 60000, label: document.getElementById('instantLabel').value.trim(), endSound: instantSound, soundAtEnd: instantSound !== 'none', ...linkFields, shownAt }; } function renderInstantDraft() { instantDraft = instantCandidate(); instantComposeThumb.show(instantDraft); document.getElementById('instantShow').disabled = !instantDraft || instantPending; document.getElementById('instantTextField').hidden = instantTab !== 'text'; const countdownTab = instantTab === 'clock' && instantClock === 'countdown'; document.getElementById('instantLinkField').hidden = instantTab !== 'text' && !countdownTab; document.getElementById('instantLinkLabel').textContent = countdownTab ? 'Link (optional; its QR code replaces the talk’s)' : 'Link (optional)'; document.getElementById('instantLinkNote').hidden = !instantLinkError; document.getElementById('instantLinkNote').textContent = instantLinkError; document.getElementById('instantImageField').hidden = instantTab !== 'image'; document.getElementById('instantImageError').hidden = !instantImageError; document.getElementById('instantImageError').textContent = instantImageError; document.getElementById('instantImageSmall').hidden = !instantImage; if (instantImage) document.getElementById('instantImageSmall').src = instantImage.dataUrl; document.getElementById('instantImageHelp').textContent = instantImage ? 'Paste (⌘V) or drop another image to replace it' : 'Paste (⌘V) or drop an image here'; document.getElementById('instantClockFields').hidden = instantTab !== 'clock'; document.getElementById('instantCountdownFields').hidden = instantTab !== 'clock' || instantClock !== 'countdown'; document.querySelectorAll('[data-instant-tab]').forEach((button) => button.setAttribute('aria-pressed', String(button.dataset.instantTab === instantTab))); document.querySelectorAll('[data-instant-clock]').forEach((button) => button.setAttribute('aria-pressed', String(button.dataset.instantClock === instantClock))); document.querySelectorAll('[data-instant-label]').forEach((button) => button.classList.toggle('on', button.dataset.instantLabel === document.getElementById('instantLabel').value.trim())); document.querySelectorAll('[data-instant-sound]').forEach((button) => button.setAttribute('aria-pressed', String(button.dataset.instantSound === instantSound))); document.querySelectorAll('[data-instant-minutes]').forEach((button) => button.classList.toggle('on', Number(button.dataset.instantMinutes) === instantMinutes)); } function openInstantCompose() { closeInstantPanels(); instantCompose.hidden = false; renderInstantDraft(); document.getElementById(instantTab === 'text' ? 'instantText' : 'instantShow').focus(); } function openInstantPaste(value) { const slide = instantSlideFromText(value); if (!slide) return; closeInstantPanels(); instantDraft = slide; document.getElementById('instantPasteKind').textContent = slide.kind === 'link' ? 'Link from the clipboard' : 'Text from the clipboard'; document.getElementById('instantPasteValue').textContent = value; document.getElementById('instantPasteShow').disabled = false; instantPasteThumb.show(slide); instantPaste.hidden = false; } async function receiveInstantImage(file, preview = false) { const generation = ++instantImageGeneration; const target = preview ? 'paste' : 'compose'; instantImageError = ''; instantImage = null; instantDraft = null; if (preview) { closeInstantPanels(); instantPaste.hidden = false; document.getElementById('instantPasteKind').textContent = 'Image from the clipboard'; document.getElementById('instantPasteValue').textContent = 'Preparing image…'; instantPasteThumb.show(null); document.getElementById('instantPasteShow').disabled = true; } else { instantTab = 'image'; renderInstantDraft(); } try { const bytes = new Uint8Array(await file.arrayBuffer()); const result = await window.twLivePollBridge?.fitImage?.(bytes); if (generation !== instantImageGeneration) return; if (!result?.success) throw new Error(result?.error || 'Could not prepare this image.'); instantImage = { kind: 'image', dataUrl: result.dataUrl, width: result.width, height: result.height }; instantDraft = { ...instantImage, shownAt: Date.now() }; if (target === 'paste') { instantPasteThumb.show(instantDraft); document.getElementById('instantPasteValue').textContent = `Screenshot · ${result.sourceWidth || result.width} × ${result.sourceHeight || result.height}`; document.getElementById('instantPasteShow').disabled = false; } else renderInstantDraft(); } catch (error) { if (generation !== instantImageGeneration) return; instantImageError = error?.message || 'Could not prepare this image.'; instantDraft = null; if (target === 'paste') { document.getElementById('instantPasteValue').textContent = instantImageError; document.getElementById('instantPasteShow').disabled = true; } else renderInstantDraft(); } } function sendInstant(action) { if (instantPending) return; instantPending = true; const bridge = window.twLivePollBridge; if (!bridge) { applyInstantSlide(action.type === 'instant.show' ? action.slide : null, true); instantPending = false; closeInstantPanels(); return; } Promise.resolve(bridge.action(action)).then((result) => { if (!result?.success) { instantPending = false; // A projector can still be used without a live session. if (result?.error === 'No live session.' || result?.error === 'Live session is not accepting controls.') applyInstantSlide(action.type === 'instant.show' ? (result.slide || action.slide) : null, true); else window.alert(result?.error || 'Could not show the instant slide.'); } }).catch(() => { instantPending = false; window.alert('Could not show the instant slide.'); }); closeInstantPanels(); } function showInstantDraft() { if (instantDraft) sendInstant({ type: 'instant.show', slide: instantDraft }); } function clearInstant() { if (instantActive) sendInstant({ type: 'instant.clear' }); } const instantPresets = document.getElementById('instantMinutePresets'); for (const minutes of [1, 2, 3, 5, 10, 15, 20]) { const button = document.createElement('button'); button.type = 'button'; button.textContent = String(minutes); button.dataset.instantMinutes = String(minutes); button.addEventListener('click', () => { instantMinutes = minutes; renderInstantDraft(); }); instantPresets.appendChild(button); } const instantLabelInput = document.getElementById('instantLabel'); const instantLabelPresets = document.getElementById('instantLabelPresets'); for (const label of ['Break', 'Discussion', 'Group work']) { const button = document.createElement('button'); button.type = 'button'; button.textContent = label; button.dataset.instantLabel = label; button.addEventListener('click', () => { instantLabelInput.value = instantLabelInput.value.trim() === label ? '' : label; renderInstantDraft(); }); instantLabelPresets.appendChild(button); } document.querySelectorAll('[data-instant-tab]').forEach((button) => button.addEventListener('click', () => { instantTab = button.dataset.instantTab; renderInstantDraft(); })); const instantDrop = document.getElementById('instantImageDrop'); instantDrop.addEventListener('dragover', (event) => { event.preventDefault(); }); instantDrop.addEventListener('drop', (event) => { event.preventDefault(); const file = Array.from(event.dataTransfer?.files || []).find((item) => item.type.startsWith('image/')); if (file) receiveInstantImage(file); }); document.querySelectorAll('[data-instant-clock]').forEach((button) => button.addEventListener('click', () => { instantClock = button.dataset.instantClock; renderInstantDraft(); })); document.querySelectorAll('[data-instant-sound]').forEach((button) => button.addEventListener('click', () => { instantSound = instantEndSound({ endSound: button.dataset.instantSound }); try { localStorage.setItem(instantSoundKey, instantSound); } catch {} renderInstantDraft(); })); document.getElementById('instantText').addEventListener('input', renderInstantDraft); document.getElementById('instantLink').addEventListener('input', renderInstantDraft); document.getElementById('instantLabel').addEventListener('input', renderInstantDraft); document.getElementById('instantShow').addEventListener('click', showInstantDraft); document.getElementById('instantPasteShow').addEventListener('click', showInstantDraft); document.getElementById('presenterInstantBack').addEventListener('click', clearInstant); for (const id of ['instantClose','instantCancel','instantPasteClose','instantPasteCancel']) document.getElementById(id).addEventListener('click', closeInstantPanels); document.getElementById('presenterInstantButton').addEventListener('click', openInstantCompose); // What the clipboard holds becomes an instant slide: an image goes to the composer's Image tab // when that is open, otherwise to the "Show this?" preview; text or a link goes to the preview. // ⌘V (the paste event) and the Live menu's "Instant slide from clipboard" both come here. function instantFromClipboardContent(image, text) { if (image && (instantTab === 'image' && !instantCompose.hidden || instantCompose.hidden)) { receiveInstantImage(image, instantCompose.hidden); return true; } if (!text?.trim()) return false; openInstantPaste(text); return true; } window.addEventListener('paste', (event) => { if (!isPresenter) return; const image = Array.from(event.clipboardData?.items || []).find((item) => item.type.startsWith('image/'))?.getAsFile(); const typing = event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement || event.target?.isContentEditable; if (instantFromClipboardContent(image, typing ? '' : event.clipboardData?.getData('text/plain'))) event.preventDefault(); }); // The menu has no paste event: it reads the clipboard through the live preload (Electron's // clipboard; the window's permission handler denies the web clipboard), or the web clipboard // where the page runs without the preload. async function instantFromClipboard() { let clip = null; try { clip = await window.twLivePollBridge?.readClipboard?.(); } catch { clip = null; } if (!clip) { try { clip = { text: await navigator.clipboard.readText(), image: null }; } catch { clip = null; } } const image = clip?.image ? new File([clip.image], 'clipboard.png', { type: 'image/png' }) : null; if (!instantFromClipboardContent(image, clip?.text || '')) flashPresenterBanner('Nothing to show: the clipboard is empty'); } try { window.twLivePollBridge?.onInstant?.((slide) => { instantPending = false; applyInstantSlide(slide, true); }); } catch {} // ── Command palette, ⌘⇧P (ADR-0031 §6, presenter redesign ticket 07) ───────────────────────── // Every presenter command, grouped, with its icon, name and key: PRESENTER_PALETTE, generated // from src/shared/presenter-palette.ts (keys from the shortcut registry). An entry runs the same // command as its control or key: it clicks the first of its `controls` that applies (so that // control's own listener runs), or sends its registry key (`code`), or calls the function below // that its key calls. Rows that do not apply now show dimmed; ↑ ↓ skip them. const PRESENTER_PALETTE_RUN = { "embed-fullscreen": { run: toggleEmbedFullScreen, enabled: () => Boolean(panePageSource()) }, "previews-larger": { run: () => cyclePreviewSize(-1) }, "previews-smaller": { run: () => cyclePreviewSize(1) }, "notes-forward": { run: () => notesScroller?.step(1) }, "notes-back": { run: () => notesScroller?.step(-1) }, // The Pen's tools (ticket 08): choosing one turns the pen on with it; W steps them while it is on. "pen-freehand": { run: () => choosePenTool("freehand") }, "pen-arrow": { run: () => choosePenTool("arrow") }, "pen-rectangle": { run: () => choosePenTool("rectangle") }, "pen-next-tool": { run: () => stepPenTool(1), enabled: () => penArmed }, "ink-undo": { run: () => undoInk(), enabled: () => inkHere() }, "ink-clear": { run: () => clearInkHere(), enabled: () => inkHere() }, "ink-clear-all": { run: () => clearAllInk(), enabled: () => (penStore?.size() || 0) > 0 }, }; const commandPalette = document.getElementById('presenterCommandPalette'); const commandScrim = document.getElementById('presenterCommandScrim'); const commandSearch = document.getElementById('presenterCommandSearch'); const commandResults = document.getElementById('presenterCommandResults'); const commandCount = document.getElementById('presenterCommandCount'); let paletteHighlight = null; const shortcutForwarded = new WeakSet(); // A control applies when it exists, is enabled, and is hidden by nothing but a closed menu or // popover it lives in (the palette runs it without opening that menu). No layout is read, so // this holds in any DOM. function paletteControlApplies(el) { if (!el || el.disabled) return false; for (let node = el; node && node !== document.body; node = node.parentElement) { if (node.hidden && !(node !== el && node.matches('.tw-menu, .notes-menu, .tw-duration-setter'))) return false; } return true; } // Menu items take their enabled state when their menu opens; bring them up to date first. function syncPaletteSources() { try { document.querySelectorAll('#presenterMenus .tw-menu').forEach((menu) => syncPresenterMenu(menu)); const more = document.getElementById('presenterMoreMenu'); if (more) syncMoreMenu(more); } catch {} } function paletteKeyEvent(code) { const parts = code.split('-'); const base = parts.pop(); const mods = new Set(parts); const shift = mods.has('Shift'); const key = base.length === 1 ? (shift ? base.toUpperCase() : base.toLowerCase()) : base; const event = new KeyboardEvent('keydown', { key, shiftKey: shift, metaKey: mods.has('Mod') || mods.has('Meta'), altKey: mods.has('Alt'), ctrlKey: mods.has('Ctrl'), bubbles: true, cancelable: true }); shortcutForwarded.add(event); return event; } // How an entry runs now, or null when it does not apply. function paletteAction(entry) { if (entry.needs && !document.querySelector(entry.needs)) return null; const own = PRESENTER_PALETTE_RUN[entry.id]; if (own) return own.enabled && !own.enabled() ? null : own.run; for (const selector of entry.controls) { const el = document.querySelector(selector); if (paletteControlApplies(el)) return () => el.click(); } if (entry.code) return () => window.dispatchEvent(paletteKeyEvent(entry.code)); return null; } function paletteKeyCaps(keys) { const holder = document.createElement('span'); holder.className = 'tw-pal-keys'; holder.setAttribute('aria-hidden', 'true'); for (const part of keys.match(/[⌥⌘⇧⌃]|[^⌥⌘⇧⌃\s]+/g) || []) { const cap = document.createElement('kbd'); cap.textContent = part; holder.appendChild(cap); } return holder; } function paletteMatches(entry, group, words) { const hay = `${entry.name} ${group} ${entry.words.join(' ')}`.toLowerCase(); return words.every((word) => hay.includes(word)); } function setPaletteHighlight(row) { if (paletteHighlight) paletteHighlight.classList.remove('hi'); paletteHighlight = row || null; if (!row) { commandSearch.removeAttribute('aria-activedescendant'); return; } row.classList.add('hi'); commandSearch.setAttribute('aria-activedescendant', row.id); row.scrollIntoView?.({ block: 'nearest' }); } function renderPresenterCommands() { syncPaletteSources(); commandResults.replaceChildren(); const words = commandSearch.value.toLowerCase().split(/\s+/).filter(Boolean); let shown = 0; for (const [group, entries] of PRESENTER_PALETTE) { const matching = entries.filter((entry) => paletteMatches(entry, group, words)); if (!matching.length) continue; // The old group names stay as search words only; each row shows its task group (onboarding 01). for (const entry of matching) { const action = paletteAction(entry); const row = document.createElement('button'); row.type = 'button'; row.className = 'tw-pal-row'; row.id = `palette-${entry.id}`; const keys = presenterShortcuts.key(entry.shortcut || `palette.${entry.id}`, entry.keys); row.setAttribute('role', 'option'); row.dataset.paletteId = entry.id; row.dataset.keys = keys; row.disabled = !action; const name = document.createElement('span'); name.className = 'tw-pal-name'; name.textContent = entry.name; const icon = twIconEl(entry.icon); const task = document.createElement('span'); task.className = 'tw-pal-task'; task.textContent = entry.task; row.append(...(icon ? [icon] : []), name, task, paletteKeyCaps(keys)); row.setAttribute('aria-label', [entry.name, entry.task, keys].filter(Boolean).join(', ')); commandResults.appendChild(row); shown += 1; } } if (!shown) { const none = document.createElement('div'); none.className = 'tw-pal-empty'; none.textContent = 'No command matches.'; commandResults.appendChild(none); } commandCount.textContent = `${shown} ${shown === 1 ? 'command' : 'commands'}`; setPaletteHighlight(commandResults.querySelector('.tw-pal-row:not(:disabled)')); } function movePaletteHighlight(step) { const rows = [...commandResults.querySelectorAll('.tw-pal-row:not(:disabled)')]; if (!rows.length) return; const at = rows.indexOf(paletteHighlight); setPaletteHighlight(rows[at < 0 ? (step > 0 ? 0 : rows.length - 1) : (at + step + rows.length) % rows.length]); } function closePresenterCommands() { commandPalette.hidden = true; if (commandScrim) commandScrim.hidden = true; if (document.activeElement === commandSearch) commandSearch.blur(); } // Run an entry: close the palette first, then run what its control or key runs. function runPaletteEntry(id) { const group = PRESENTER_PALETTE.find(([, entries]) => entries.some((entry) => entry.id === id)); const entry = group?.[1].find((item) => item.id === id); const action = entry && paletteAction(entry); closePresenterCommands(); if (action) reportGuideCommand(guideIdOfEntry(entry)); action?.(); } function togglePresenterCommands(force) { const show = force != null ? force : commandPalette.hidden; if (!show) { closePresenterCommands(); return; } topBarMenus?.close(); moreMenu?.close(); toggleNotesMenu(false); openDurationSetter(false); // The search field's icon (the icon set is the generated block, read once the page has run). const searchIcon = commandPalette.querySelector('[data-palette-icon]'); const svg = searchIcon && twIconEl(searchIcon.dataset.paletteIcon); if (svg) searchIcon.replaceWith(svg); commandPalette.hidden = false; if (commandScrim) commandScrim.hidden = false; commandSearch.value = ''; renderPresenterCommands(); commandSearch.focus(); } // Keys while the palette is open (handleKey sends them here): ↑ ↓ choose, ↵ runs, Esc closes; // everything else types into the search field. function paletteKey(event) { const key = event.key; if (event.metaKey && event.shiftKey && key === ',' && paletteHighlight) { event.preventDefault(); const entry = PRESENTER_PALETTE.flatMap(([, entries]) => entries).find(item => item.id === paletteHighlight.dataset.paletteId); presenterShortcuts.rebind(entry.shortcut || `palette.${entry.id}`, entry.name, entry.id); return; } if (key === 'Escape') { event.preventDefault(); closePresenterCommands(); return; } if (key === 'ArrowDown' || key === 'ArrowUp') { event.preventDefault(); movePaletteHighlight(key === 'ArrowDown' ? 1 : -1); return; } if (key === 'Enter') { event.preventDefault(); if (paletteHighlight) runPaletteEntry(paletteHighlight.dataset.paletteId); return; } if (key === 'Tab') { event.preventDefault(); return; } } if (commandPalette) { commandSearch.addEventListener('input', renderPresenterCommands); // A press on a row never takes focus from the search field (keys stay with the palette). commandResults.addEventListener('mousedown', (event) => { if (event.target.closest('.tw-pal-row')) event.preventDefault(); }); commandResults.addEventListener('mousemove', (event) => { const row = event.target.closest('.tw-pal-row:not(:disabled)'); if (row && row !== paletteHighlight) setPaletteHighlight(row); }); commandResults.addEventListener('click', (event) => { const row = event.target.closest('.tw-pal-row'); if (row && !row.disabled) runPaletteEntry(row.dataset.paletteId); }); commandScrim?.addEventListener('click', closePresenterCommands); } let quickPollCounter = 0; let quickPollType = "single"; let quickPollVisibility = "live"; const quickPollExtras = createQuickPollExtras(document.getElementById("quickPollExtras"), validateQuickPoll); const pendingPollActions = new Map(); let lastPollLiveStatus = null; const pollProjection = createPollProjection({ isPresenter, isPaired, sessionId, storageKey, stage, getSlide: currentSlide, send: sendToPeer, changed: () => { if (isPresenter) queueMicrotask(renderPresenter); }, }); activeQuickPollId = pollProjection.quick().pollId; function authoredPollForCurrentSlide() { const raw = currentSlide()?.dataset.poll; if (!raw) return null; try { const poll = JSON.parse(raw); return poll && typeof poll.pollId === "string" ? { ...poll, slideId: currentSlide().dataset.id } : null; } catch { return null; } } function presenterPollForDisplay() { // The panel reflects the poll relevant to where the presenter is: a slide's own // authored poll takes precedence on that slide, so "Open poll" always acts on the // poll the panel is showing. A spontaneous Quick poll shows only on slides that have // no authored poll of their own. if (activeQuickPollId && pollProjection.quick().visible && presenterPollDefinitions.has(activeQuickPollId)) { return presenterPollDefinitions.get(activeQuickPollId); } const authored = authoredPollForCurrentSlide(); if (authored) return authored; return null; } function pollDefinitionFromState(state) { return { pollId: state.pollId, type: state.pollType, question: state.question, options: Array.isArray(state.options) ? state.options : [], visibility: state.visibility, ...(state.rankCount !== undefined ? { rankCount: state.rankCount } : {}), ...(state.labels ? { labels: state.labels } : {}), ...(state.allowSkip !== undefined ? { allowSkip: state.allowSkip } : {}), ...(state.maxSelections !== undefined ? { maxSelections: state.maxSelections } : {}), ...(state.maxSubmissions !== undefined ? { maxSubmissions: state.maxSubmissions } : {}), ...(state.slideId ? { slideId: state.slideId } : {}), }; } function makeQuickPollId() { quickPollCounter += 1; const random = typeof crypto?.randomUUID === "function" ? crypto.randomUUID().replaceAll("-", "").slice(0, 8) : Math.random().toString(36).slice(2, 10); return `quick-${Date.now().toString(36)}-${quickPollCounter.toString(36)}-${random}`; } function setQuickPollSegment(attribute, value) { document.querySelectorAll(`[${attribute}]`).forEach((button) => { button.setAttribute("aria-pressed", String(button.getAttribute(attribute) === value)); }); } function addQuickPollOption(value = "") { if (!els.quickPollOptions) return; const row = document.createElement("div"); row.className = "quick-poll-option-row"; const input = document.createElement("input"); input.type = "text"; input.maxLength = 160; input.value = value; input.placeholder = "Option"; input.setAttribute("aria-label", "Poll option"); const remove = document.createElement("button"); remove.type = "button"; remove.className = "quick-poll-remove"; remove.append(twIconEl("x")); remove.setAttribute("aria-label", "Remove poll option"); input.addEventListener("input", validateQuickPoll); remove.addEventListener("click", () => { row.remove(); validateQuickPoll(); }); row.append(input, remove); els.quickPollOptions.appendChild(row); validateQuickPoll(); } function quickPollOptionLabels() { return [...(els.quickPollOptions?.querySelectorAll("input") || [])].map((input) => input.value.trim()).filter(Boolean); } function validateQuickPoll() { if (!els.quickPollOpen) return false; // The question is OPTIONAL — a bare Yes/No often needs no wording (you just asked it aloud). const optionCount = quickPollOptionLabels().length; const validOptions = quickPollType === "open" || optionCount >= (isExtendedPoll(quickPollType) ? 1 : 2); const validExtras = quickPollExtras.valid(quickPollType, optionCount); document.getElementById("quickPollSelectionsField").hidden = quickPollType !== "multiple"; document.getElementById("quickPollSubmissionsField").hidden = quickPollType !== "open"; const selections = document.getElementById("quickPollMaxSelections"); const submissions = document.getElementById("quickPollMaxSubmissions"); const unlimited = document.getElementById("quickPollUnlimited").checked; selections.max = String(quickPollOptionLabels().length); submissions.disabled = unlimited; const validSelections = quickPollType !== "multiple" || (!selections.value && !selections.validity.badInput) || (selections.validity.valid && Number.isSafeInteger(Number(selections.value))); const validSubmissions = quickPollType !== "open" || unlimited || (submissions.value && submissions.validity.valid && Number.isSafeInteger(Number(submissions.value))); els.quickPollOpen.disabled = !validOptions || !validExtras || !validSelections || !validSubmissions; return !els.quickPollOpen.disabled; } function resetQuickPollCompose() { quickPollExtras.reset(); quickPollType = "single"; quickPollVisibility = "live"; document.getElementById("quickPollMaxSelections").value = ""; document.getElementById("quickPollMaxSubmissions").value = "1"; document.getElementById("quickPollUnlimited").checked = false; if (els.quickPollQuestion) els.quickPollQuestion.value = ""; els.quickPollOptions?.replaceChildren(); addQuickPollOption(); addQuickPollOption(); setQuickPollSegment("data-quick-poll-type", quickPollType); setQuickPollSegment("data-quick-poll-visibility", quickPollVisibility); if (els.quickPollOptionsField) els.quickPollOptionsField.hidden = false; if (els.quickPollPresetsField) els.quickPollPresetsField.hidden = false; validateQuickPoll(); } function toggleQuickPollCompose(force) { if (!els.presenterQuickPollCompose) return; const opening = typeof force === "boolean" ? force : els.presenterQuickPollCompose.hidden; if (opening) { resetQuickPollCompose(); els.presenterQuickPollCompose.hidden = false; els.quickPollQuestion?.focus(); } else { els.presenterQuickPollCompose.hidden = true; // Focus leaves the closed composer; it does not land on a menu button, where Space (next // slide) would open the menu instead. if (els.presenterQuickPollCompose.contains(document.activeElement)) document.activeElement.blur(); } } function openQuickPoll() { if (!validateQuickPoll()) return; const pollId = makeQuickPollId(); const labels = quickPollOptionLabels(); const poll = { pollId, type: quickPollType, question: els.quickPollQuestion.value.trim(), options: quickPollType === "open" ? [] : labels.map((label, index) => ({ optionId: `${pollId}-option-${index + 1}`, label })), visibility: quickPollVisibility, ...quickPollExtras.fields(quickPollType, pollId), ...(quickPollType === "multiple" && document.getElementById("quickPollMaxSelections").value ? { maxSelections: Number(document.getElementById("quickPollMaxSelections").value) } : {}), ...(quickPollType === "open" && (document.getElementById("quickPollUnlimited").checked || document.getElementById("quickPollMaxSubmissions").value !== "1") ? { maxSubmissions: document.getElementById("quickPollUnlimited").checked ? null : Number(document.getElementById("quickPollMaxSubmissions").value) } : {}), }; presenterPollDefinitions.set(pollId, poll); activeQuickPollId = pollId; dismissedPresenterPollId = null; pollProjection.showQuick(pollId); emitPresenterPollAction({ type: "poll.open", poll }); toggleQuickPollCompose(false); renderPresenterPoll(); } function emitPresenterPollAction(detail) { // The preload bridge lives in an isolated world; window CustomEvents don't carry `detail` // across it. Go through the contextBridge API instead (present-live-bridge.ts). const pollId = detail.type === "poll.open" ? detail.poll.pollId : detail.pollId; if (pendingPollActions.get(pollId)?.status === "pending") return; const pending = { status: "pending", message: detail }; pendingPollActions.set(pollId, pending); renderPresenterPoll(); try { if (!window.twLivePollBridge) throw new Error("Live polling is available in TalkWeaver's presenter window."); Promise.resolve(window.twLivePollBridge.action(detail)).then((result) => { if (pendingPollActions.get(pollId) !== pending) return; if (result?.status === "pending" && result.success) { pending.operationId = result.operationId; } else if (result?.success === false || result?.status === "rejected") { pending.status = "rejected"; pending.error = result.error || "The poll action was not accepted. Try again."; } else pendingPollActions.delete(pollId); renderPresenterPoll(); }).catch(() => { if (pendingPollActions.get(pollId) !== pending) return; pending.status = "rejected"; pending.error = "Could not update the poll. Try again."; renderPresenterPoll(); }); } catch (error) { pending.status = "rejected"; pending.error = error.message; renderPresenterPoll(); } } function applyPollOperation(operation) { const message = operation?.message; if (message?.type === 'question.answer') { questionAnswerOperation(operation); return; } if (typeof message?.type === 'string' && message.type.startsWith('board.')) { boardUi?.controller.operation(operation); return; } if (message?.type === 'switches.set') { if (operation.status === 'rejected') { audienceSwitchError = operation.error === 'storage_failed' ? 'Could not update the phones. Try the switch again.' : (operation.error || 'Could not update the phones. Try the switch again.'); syncAudienceSwitchItems(); } return; } if (message?.type === 'instant.show' || message?.type === 'instant.clear') { if (operation.status === 'rejected') { instantPending = false; window.alert(operation.error || 'Could not show the instant slide.'); } return; } const pollId = message?.type === "poll.open" ? message.poll?.pollId : message?.pollId; if (pollId && operation.status === "pending" && !pendingPollActions.has(pollId)) { pendingPollActions.set(pollId, { status: "pending", operationId: operation.operationId, message }); } const pending = pendingPollActions.get(pollId); if (!pending || (pending.operationId && pending.operationId !== operation.operationId)) return; if (operation.status === "confirmed") pendingPollActions.delete(pollId); else if (operation.status === "rejected") { pending.status = "rejected"; pending.error = operation.error || "The poll action was not accepted. Try again."; } else pending.operationId = operation.operationId; renderPresenterPoll(); } // When the Poll menu's "Show Quick poll on screens" and "Show poll panel" apply. function quickPollHidden() { return Boolean(activeQuickPollId) && !pollProjection.quick().visible; } function pollPanelDismissed(poll = presenterPollForDisplay()) { return Boolean(poll) && poll.pollId === dismissedPresenterPollId; } function presenterPollPrimaryAction() { const poll = presenterPollForDisplay(); if (!poll) return; const state = presenterPollStates.get(poll.pollId); const view = presenterPollViewModel(state); if (view.showOpen) emitPresenterPollAction({ type: "poll.open", poll }); else if (view.showClose) emitPresenterPollAction({ type: "poll.close", pollId: poll.pollId }); } function presenterPollRevealAction() { const poll = presenterPollForDisplay(); const state = poll ? presenterPollStates.get(poll.pollId) : null; if (poll && presenterPollViewModel(state).showReveal) { emitPresenterPollAction({ type: "poll.reveal", pollId: poll.pollId }); } else if (poll && state && (state.revealed || state.visibility === "live")) { pollProjection.choose(poll.pollId, pollProjection.info(poll.pollId).view === "results" ? "question" : "results"); } } function renderPresenterPollResults(poll, state, count) { const host = els.presenterPollResults; if (!host) return; host.replaceChildren(); if (isExtendedPoll(poll.type)) { host.innerHTML = renderExtendedPollResults({ ...poll, ...state, pollType: poll.type }, true); return; } if (poll.type === "open") { const responses = Array.isArray(state?.responses) ? state.responses : []; if (responses.length === 0) { const empty = document.createElement("div"); empty.className = "presenter-poll-empty"; empty.textContent = "Waiting for responses…"; host.appendChild(empty); return; } const board = document.createElement("div"); board.className = "presenter-poll-board"; responses.forEach((response) => { const card = document.createElement("div"); card.className = "presenter-poll-response"; card.textContent = String(response.text || ""); card.classList.toggle("is-hidden", response.hidden === true); if (response.name) { const who = document.createElement("small"); who.textContent = String(response.name); card.appendChild(who); } const hide = document.createElement("button"); hide.type = "button"; hide.className = "presenter-poll-hide"; hide.textContent = "×"; hide.title = response.hidden ? "Restore to board" : "Hide from board"; hide.setAttribute("aria-label", response.hidden ? "Restore response to audience board" : "Hide response from audience board"); hide.addEventListener("click", () => emitPresenterPollAction({ type: "poll.hide", pollId: poll.pollId, responseId: response.responseId, hidden: !response.hidden, })); card.appendChild(hide); board.appendChild(card); }); host.appendChild(board); return; } const tallies = state?.tallies && typeof state.tallies === "object" ? state.tallies : {}; poll.options.forEach((option) => { const votes = Math.max(0, Number(tallies[option.optionId]) || 0); const percent = count > 0 ? Math.round(votes * 100 / count) : 0; const bar = document.createElement("div"); bar.className = "presenter-poll-bar"; const label = document.createElement("div"); label.className = "presenter-poll-bar-label"; const name = document.createElement("span"); name.textContent = option.label; const value = document.createElement("span"); value.className = "presenter-poll-bar-value"; value.textContent = `${percent}% · ${votes}`; const track = document.createElement("div"); track.className = "presenter-poll-track"; const fill = document.createElement("i"); fill.style.width = `${percent}%`; track.appendChild(fill); label.append(name, value); bar.append(label, track); host.appendChild(bar); }); } function renderPresenterPoll() { if (!isPresenter || !els.presenterPollPanel) return; const slideId = currentSlide()?.dataset.id || ""; if (slideId !== lastPollPanelSlideId) { lastPollPanelSlideId = slideId; dismissedPresenterPollId = null; } const poll = presenterPollForDisplay(); // Poll menu items (ticket 04): shown always, enabled only when they apply. const restoreQuick = document.getElementById("presenterQuickPollRestore"); if (restoreQuick) restoreQuick.disabled = !quickPollHidden(); const toggle = document.getElementById("presenterPollPanelToggle"); if (toggle) toggle.disabled = !pollPanelDismissed(poll); // A board has its own panel (feedback-boards ticket 05): the poll panel never shows one. renderBoard(); if (poll && poll.type === "board") { els.presenterPollPanel.hidden = true; return; } if (!poll || poll.pollId === dismissedPresenterPollId) { els.presenterPollPanel.hidden = true; return; } const state = presenterPollStates.get(poll.pollId) || null; const view = presenterPollViewModel(state); els.presenterPollPanel.hidden = false; els.presenterPollQuestion.textContent = poll.question; els.presenterPollQuestion.hidden = !poll.question; // the question is optional // Badges in sentence case (presenter redesign ticket 06): the poll type, then how results show. els.presenterPollType.textContent = isExtendedPoll(poll.type) ? poll.type.charAt(0).toUpperCase() + poll.type.slice(1) : poll.type === "open" ? `Open · ${poll.maxSubmissions === null ? "unlimited" : poll.maxSubmissions ?? 1} per participant` : poll.type === "multiple" ? `Choice · select up to ${poll.maxSelections ?? poll.options.length}` : "Single choice"; els.presenterPollVisibility.textContent = (state?.visibility || poll.visibility) === "held" ? "Results held" : "Results shown as they arrive"; els.presenterPollChip.textContent = view.phase === "armed" ? "Poll ready" : `Poll ${view.phase} · ${view.count}`; els.presenterPollCount.textContent = view.phase === "armed" ? "" : `· ${view.count} ${poll.type === "multiple" ? "selections" : poll.type === "open" ? "responses" : "votes"}`; els.presenterPollResults.hidden = !view.showResults; if (view.showResults) renderPresenterPollResults(poll, state, view.count); els.presenterPollOpen.hidden = !view.showOpen; twSetLabel(els.presenterPollOpen, view.phase === "closed" ? "Reopen responses" : "Open poll"); // keeps its icon els.presenterPollReveal.hidden = !view.showReveal; els.presenterPollClose.hidden = !view.showClose; els.presenterPollHeldNote.hidden = !view.showHeldNote; const displayInfo = pollProjection.info(poll.pollId); const publicResults = Boolean(state && (state.revealed || state.visibility === "live")); document.getElementById("presenterPollShowQuestion").hidden = !publicResults || displayInfo.view === "question"; document.getElementById("presenterPollShowResults").hidden = !publicResults || displayInfo.view === "results"; document.getElementById("presenterPollPreviousPage").hidden = displayInfo.pages < 2; document.getElementById("presenterPollNextPage").hidden = displayInfo.pages < 2; document.getElementById("presenterPollPreviousPage").disabled = displayInfo.page === 0; document.getElementById("presenterPollNextPage").disabled = displayInfo.page === displayInfo.pages - 1; document.getElementById("presenterQuickPollDismiss").hidden = poll.pollId !== activeQuickPollId || !pollProjection.quick().visible; document.getElementById("presenterPollDisplayStatus").textContent = `Audience sees: ${displayInfo.view === "results" ? "results" : "question"}${displayInfo.pages > 1 ? ` · page ${displayInfo.page + 1} of ${displayInfo.pages}` : ""}. ${view.phase === "armed" ? "Ready to open." : state.open ? "Accepting responses." : "Responses closed."} ${publicResults ? "Results are public." : "Results hidden from audience."}`; const operation = pendingPollActions.get(poll.pollId); const operationEl = document.getElementById("presenterPollOperation"); operationEl.hidden = !operation; operationEl.classList.toggle("is-error", operation?.status === "rejected"); operationEl.textContent = operation?.status === "pending" ? "Waiting for confirmation…" : operation?.error || ""; [els.presenterPollOpen, els.presenterPollClose, els.presenterPollReveal, ...els.presenterPollResults.querySelectorAll(".presenter-poll-hide")].forEach((button) => { button.disabled = operation?.status === "pending"; }); } // Poll results + live status arrive from the preload bridge via the contextBridge callbacks // (present-live-bridge.ts exposes twLivePollBridge before this script runs), NOT window events. function applyPresenterPollState(message) { if (!message || message.type !== "poll.state" || typeof message.pollId !== "string") return; presenterPollStates.set(message.pollId, message); pollProjection.update(message); if (!presenterPollDefinitions.has(message.pollId)) presenterPollDefinitions.set(message.pollId, pollDefinitionFromState(message)); if (message.pollId === dismissedPresenterPollId) return; // recorded, but don't re-open a dismissed panel if (message.pollId.startsWith("quick-") && !activeQuickPollId && message.open) { activeQuickPollId = message.pollId; pollProjection.showQuick(message.pollId); } renderPresenterPoll(); } // ADR-0031 §7: live status appears once, in the status bar (the live preload fills it); the poll // panel has no live chip of its own (presenter redesign ticket 06). A finished session clears // the polls it ran. function applyPresenterLiveStatus(status) { if (status === "ended" || status === "expired") { pollProjection.clear(); presenterPollStates.clear(); pendingPollActions.clear(); activeQuickPollId = null; renderPresenter(); } lastPollLiveStatus = status; } try { if (window.twLivePollBridge) { window.twLivePollBridge.onState(applyPresenterPollState); window.twLivePollBridge.onStatus((status) => { talkQrLiveStatus = status; applyPresenterLiveStatus(status); syncAudienceSwitchesOnStatus(status); }); window.twLivePollBridge.onJoin?.((value) => { talkQrLiveJoin = value; pollProjection.setJoin(value); }); window.twLivePollBridge.onOperation?.(applyPollOperation); } } catch {} // ── The board panel (ADR-0032 decision 4; feedback-boards ticket 05, drawn in round-2/shots D1-D24) ── // One controller per presenter window holds the board as the worker sent it and sends each change // as one worker operation (through the live bridge's boardAction). It is drawn beside the slide // (over the Next and Then previews), full screen in this window, or in the board's own window, // which this window opens and draws into with the same code. Declared with var and functions: // renderPresenterPoll can run before this block during start-up. var boardUi = null; function boardIcon(name) { try { return twIconEl(name); } catch { return null; } } function boardKeysText() { try { return { primary: PRESENTER_TIPS.pollMenuPrimary?.[1] || "Q", undo: "⌘Z", pick: "⌥↵" }; } catch { return { primary: "Q", undo: "⌘Z", pick: "⌥↵" }; } } function boardStorage() { try { return window.sessionStorage; } catch { return null; } } function ensureBoardUi() { if (boardUi || !isPresenter) return boardUi; const host = document.getElementById("presenterBoardPanel"); if (!host || typeof createBoardController !== "function") return null; const controller = createBoardController({ send: (message) => window.twLivePollBridge?.boardAction ? Promise.resolve(window.twLivePollBridge.boardAction(message)) : Promise.resolve({ success: false, status: "rejected", error: "board_not_found" }), store: boardStorage(), }); boardUi = { controller, panel: null, pollId: null, dismissed: null, mode: "beside", child: null, childPanel: null, pinned: null, lastSlide: null }; boardUi.panel = createBoardPanel({ doc: document, host, controller, icon: boardIcon, keys: boardKeysText(), mode: "beside", actions: boardActions(false) }); controller.subscribe(() => { boardUi.panel.render(); boardUi.childPanel?.render(); syncBoardChrome(); }); window.addEventListener("resize", () => { if (boardUi.panel.isOpen()) boardUi.panel.render(); }); window.addEventListener("pagehide", () => closeBoardWindow()); const chip = document.getElementById("presenterBoardCount"); if (chip) { // As the questions counter: a mouse click never leaves focus on it; Enter and Space from the keyboard. chip.addEventListener("mousedown", (event) => event.preventDefault()); chip.addEventListener("click", boardChipAction); chip.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); boardChipAction(); } }); } queueMicrotask(renderBoard); return boardUi; } function boardActions(inWindow) { return { primary: presenterBoardPrimary, fullScreen: (on) => setBoardMode(on ? "full" : "beside"), popOut: popOutBoard, putBack: () => putBackBoard(), close: inWindow ? () => putBackBoard() : () => { if (boardUi) { boardUi.dismissed = boardUi.pollId; boardUi.mode = "beside"; boardUi.panel.setMode("beside"); renderBoard(); } }, monitor: (el) => previewSlide(el, currentSlide(), state.reveal, null), place: inWindow ? null : placeBoardPanel, toastBox: inWindow ? null : () => { const box = els.currentPreview?.getBoundingClientRect(); return box && box.width > 40 ? { left: Math.round(box.left + 12), top: Math.round(box.top + 12) } : null; }, }; } // The board this window manages: the board popped out into its own window stays there while the // presenter moves on; otherwise the current slide's board. function boardPollNow() { if (!boardUi) return null; if (boardUi.mode === "window" && boardUi.pinned) return boardUi.pinned; const poll = presenterPollForDisplay(); return poll && poll.type === "board" ? poll : null; } function renderBoard() { try { const ui = ensureBoardUi(); if (!ui) return; const slideId = currentSlide()?.dataset.id || ""; if (slideId !== ui.lastSlide) { ui.lastSlide = slideId; ui.dismissed = null; } const poll = boardPollNow(); const pollState = poll ? presenterPollStates.get(poll.pollId) || null : null; if ((poll?.pollId || null) !== ui.pollId) { ui.pollId = poll?.pollId || null; if (!poll && ui.mode === "full") { ui.mode = "beside"; ui.panel.setMode("beside"); } } ui.controller.set(poll ? { ...poll, board: poll.board || pollState?.board } : null, pollState); // The columns take the board slide's section colour, as on the big screen. const boardSlide = poll ? slides.find((slide) => slide.dataset.id === (poll.slideId || pollState?.slideId)) || currentSlide() : null; const accent = boardSlide ? getComputedStyle(boardSlide).getPropertyValue("--accent").trim() : ""; for (const node of [ui.panel.el, ui.childPanel?.el]) if (node) { if (accent) node.style.setProperty("--bp-accent", accent); else node.style.removeProperty("--bp-accent"); } const label = `slide ${clampBeat(state.beat) + 1}`; ui.panel.setSlideLabel(label); ui.childPanel?.setSlideLabel(label); const show = Boolean(poll) && ui.mode !== "window" && ui.dismissed !== poll.pollId; // The layout makes room first (the slide gives the right column to the panel), then the panel // is drawn and placed over it, and placed again once the grid has settled. document.getElementById("presenterRoot")?.setAttribute("data-board", show ? ui.mode : ui.mode === "window" && poll ? "window" : ""); ui.panel.show(show); if (show) requestAnimationFrame(() => { if (ui.panel.isOpen()) placeBoardPanel(ui.panel.el, ui.mode); }); syncBoardChrome(); } catch (error) { console.warn("[board panel]", error); } } // Beside the slide: over the Next and Then column, from the top of the slide to its foot. Full // screen: everything under the top bar and above the bottom bar. function placeBoardPanel(root, mode) { const presenter = document.getElementById("presenterRoot")?.getBoundingClientRect(); const main = document.querySelector(".presenter-main")?.getBoundingClientRect(); const divider = document.getElementById("presenterDivider")?.getBoundingClientRect(); const bar = document.getElementById("presenterBottomBar")?.getBoundingClientRect(); const right = (presenter ? presenter.right : window.innerWidth) - 12; const top = main ? main.top : 60; const bottom = bar && bar.top > top + 200 ? bar.top - 14 : (main ? main.bottom : window.innerHeight - 70); let left; if (mode === "full") left = main ? main.left : 12; else if (divider && divider.width > 0 && divider.right < right - 300) left = divider.right + 14; else left = right - Math.min(600, Math.max(360, window.innerWidth * 0.42)); Object.assign(root.style, { left: `${Math.round(left)}px`, top: `${Math.round(top)}px`, width: `${Math.round(right - left)}px`, height: `${Math.round(bottom - top)}px` }); } function setBoardMode(mode) { const ui = ensureBoardUi(); if (!ui) return; if (ui.mode === "window") putBackBoard(); ui.mode = mode; ui.dismissed = null; ui.panel.setMode(mode); renderBoard(); } // Q beside the board, and its Close to new cards / Reopen button: the poll's own open and close. function presenterBoardPrimary() { const poll = boardUi?.controller.poll(); if (!poll) return; const view = presenterPollViewModel(presenterPollStates.get(poll.pollId) || null); const { board, ...definition } = poll; const authored = { ...definition, ...(board ? { board } : {}) }; if (view.showOpen) emitPresenterPollAction({ type: "poll.open", poll: authored }); else if (view.showClose) emitPresenterPollAction({ type: "poll.close", pollId: poll.pollId }); } function boardChipAction() { const ui = ensureBoardUi(); if (!ui) return; if (ui.mode === "window") { putBackBoard(); return; } ui.dismissed = ui.panel.isOpen() ? ui.pollId : null; renderBoard(); } // Pop out (D23): a window of its own for another screen, drawn by this window. TalkWeaver places // it on another display when there is one (src/main/index.ts, did-create-window). function popOutBoard() { const ui = ensureBoardUi(); const poll = ui?.controller.poll(); if (!ui || !poll) return; let child = ui.child && !ui.child.closed ? ui.child : null; if (!child) child = window.open("", "tw-board-window", "width=1440,height=900"); if (!child) { flashPresenterBanner("The board window could not open"); return; } // The board window is a blank page drawn from here; if it cannot be drawn (closed at once, // or not ours to write), it is closed and the board stays beside the slide. try { const cdoc = child.document; cdoc.open(); cdoc.write(' '); cdoc.close(); cdoc.title = `Board · ${poll.question || "Board"} · TalkWeaver`; for (const style of document.querySelectorAll("head style")) cdoc.head.appendChild(cdoc.importNode(style, true)); const host = cdoc.createElement("section"); host.id = "boardWindowPanel"; cdoc.body.appendChild(host); ui.child = child; ui.pinned = poll; ui.mode = "window"; ui.childPanel = createBoardPanel({ doc: cdoc, host, controller: ui.controller, icon: boardIcon, keys: boardKeysText(), mode: "window", actions: boardActions(true) }); ui.childPanel.setSlideLabel(`slide ${clampBeat(state.beat) + 1}`); ui.childPanel.show(true); // Closing the board window puts the board back beside the slide (D24). child.addEventListener("pagehide", () => { if (boardUi && boardUi.child === child) putBackBoard({ closed: true }); }); ui.panel.setMode("beside"); renderBoard(); } catch (error) { console.warn("[board window]", error); try { if (!child.closed) child.close(); } catch {} const ui2 = boardUi; if (ui2) { ui2.child = null; ui2.childPanel = null; ui2.pinned = null; ui2.mode = "beside"; ui2.panel.setMode("beside"); renderBoard(); } flashPresenterBanner("The board window could not open. The board stays beside the slide."); return; } try { child.focus(); } catch {} } function putBackBoard(options = {}) { const ui = boardUi; if (!ui) return; const child = ui.child; ui.child = null; ui.childPanel = null; ui.pinned = null; ui.mode = "beside"; ui.dismissed = null; if (child && !child.closed && !options.closed) { try { child.close(); } catch {} } ui.panel.setMode("beside"); renderBoard(); try { window.focus(); } catch {} } function closeBoardWindow() { const child = boardUi?.child; if (child && !child.closed) { try { child.close(); } catch {} } } // The status bar's board counter (D1, D23) and the Poll menu's Board group (D19). function syncBoardChrome() { const ui = boardUi; const view = ui?.controller.view(); const chip = document.getElementById("presenterBoardCount"); if (chip) { chip.hidden = !view; if (view) { document.getElementById("presenterBoardCards").textContent = String(view.cardCount); const inWindow = ui.mode === "window"; document.getElementById("presenterBoardNew").textContent = inWindow ? (view.strip.waiting ? `${view.strip.waiting} waiting` : "") : view.newCount && !view.frozen ? `${view.newCount} new` : ""; const where = document.getElementById("presenterBoardWhere"); where.replaceChildren(); if (inWindow) { const glyph = boardIcon("picture-in-picture-2"); if (glyph) where.append(glyph); where.append("own window"); } chip.classList.toggle("is-open", ui.panel.isOpen()); chip.setAttribute("aria-expanded", String(ui.panel.isOpen())); chip.dataset.tip = inWindow ? "Board · in its own window. Click to bring it back beside the slide." : ui.panel.isOpen() ? "Board panel · click to close it" : "Board panel · click to show it"; } } syncBoardMenu(); } function syncBoardMenu() { const view = boardUi?.controller.view(); const ids = ["pollMenuBoardRule", "pollMenuBoardSec", "pollMenuBoardClose", "pollMenuBoardFreeze", "pollMenuBoardPanel", "pollMenuBoardFull", "pollMenuBoardPopout"]; for (const id of ids) { const node = document.getElementById(id); if (node) node.hidden = !view; } if (!view) return; const sec = document.getElementById("pollMenuBoardSec"); if (sec) sec.textContent = view.question ? `Board · ${view.question}` : "Board"; // The item's words, keeping its icon and its sub-line (the dressed label holds both). const words = (id, text) => { const item = document.getElementById(id); const holder = item?.querySelector(":scope > .tw-btn-label") || item; const node = holder && [...holder.childNodes].find((child) => child.nodeType === 3); if (node) node.textContent = text; else if (holder) holder.prepend(text); }; words("pollMenuBoardClose", view.phase === "closed" ? "Reopen board to new cards" : view.phase === "ready" ? "Open board" : "Close board to new cards"); words("pollMenuBoardFreeze", view.frozen ? "Unfreeze board" : "Freeze board"); const freezeSub = document.getElementById("pollMenuBoardFreezeSub"); if (freezeSub) freezeSub.textContent = view.frozen ? "Sorting and new cards again" : "Final: no new cards, no changes"; const panelSub = document.getElementById("pollMenuBoardPanelSub"); if (panelSub) panelSub.textContent = boardUi.mode === "window" ? "Back beside the slide" : `${view.newCount} new ${view.newCount === 1 ? "card" : "cards"}`; } function boardMenuEnabled(what) { const ui = boardUi; const view = ui?.controller.view(); if (!view) return false; if (what === "close") return !view.frozen; if (what === "freeze") return view.phase !== "ready"; if (what === "panel") return ui.mode === "window" || !ui.panel.isOpen() || ui.mode === "full"; if (what === "full") return !(ui.mode === "full" && ui.panel.isOpen()); if (what === "popout") return ui.mode !== "window"; return false; } function showBoardPanel() { const ui = ensureBoardUi(); if (!ui) return; if (ui.mode === "window") { putBackBoard(); return; } ui.dismissed = null; ui.mode = "beside"; ui.panel.setMode("beside"); renderBoard(); } let lastNotesSlide = null; function renderPresenter() { if (!isPresenter) return; // The questions tray marks the question about the slide on screen, so it follows the slide // (`var`: it may run before the tray's state is declared, at start-up). if (questionsTray && questionsTray.open) renderQuestionsTray(); const slide = currentSlide(); els.presenterTitle.textContent = deckTitle; // Beat position (F3): monotonic progress even where beats revisit a slide (grid-returns). els.presenterCount.textContent = `${clampBeat(state.beat) + 1} / ${beats.length}`; const currentBeatIndex = clampBeat(state.beat); previewSlide(els.currentPreview, slide, state.reveal, state.mode, beats[currentBeatIndex], currentBeatIndex); if (instantActive) { els.currentPreview.appendChild(instantCurrent.element); instantCurrent.show(instantActive); } // Next pane: ALWAYS beats[i+1], fully revealed (999 sentinel — every unit shown, no mode // dimming, a card gallery at its arrival card). Never an intermediate step, never "this // slide again" — the pane is structurally predictable regardless of step state. The label // comes from the pure beatLabel core (same source scripts/test-beats-preview.mjs asserts). const nextBeat = nextPaneBeat(state, beats); const nextTarget = nextBeat ? previewTargetForBeat(nextBeat, 999) : null; const nextSlideEl = nextTarget ? slides[slideIndexById.get(nextTarget.slideId)] : null; previewSlide(els.nextPreview, nextSlideEl, nextTarget?.reveal ?? 999, null, nextBeat, currentBeatIndex + 1); renderInkBadge(els.nextPreview, nextSlideEl); if (els.nextPreviewLabel) els.nextPreviewLabel.textContent = beatLabel(nextBeat, beats, navTitleForSlideId); // Adaptive right column (D8): notes are rare, so when the current slide has none we // give the space to a "Then" preview (slide after next) and grow both previews; when // notes exist we surface them prominently and hide the Then preview. The collapse state // only flips when notes PRESENCE changes, so navigating note-free slides causes no churn. const note = slide.querySelector("aside.notes"); const hasNotes = Boolean(note && note.textContent.trim()); els.presenterSide?.classList.toggle("has-notes", hasNotes); // The notes are replaced only when a slide arrives (ADR-0028 §9: they jump to the top on each // slide change), not on every reveal step or poll update, so a scrolled or stepped note keeps // its place while the presenter stays on the slide. if (slide !== lastNotesSlide) { lastNotesSlide = slide; if (hasNotes) els.presenterNotesBody.replaceChildren(note.cloneNode(true)); else els.presenterNotesBody.replaceChildren(); notesScroller?.reset(); } // The camera column's empty state names the next slide. els.presenterNotesBody.dataset.nextTitle = nextSlideEl ? navTitleForSlideId(nextSlideEl.dataset.id) : "end of the talk"; // The notes placement decides whether Then shows beside the notes (bottom, off) or gives way // to them (sidebar, the former side-column behaviour). if (notesPlacementPanels(notesPlacement, hasNotes).then) { // "Then" pane: beats[i+2], fully revealed — same structural rule as the Next pane. const thenBeat = beats[clampBeat(state.beat) + 2] || null; const thenTarget = thenBeat ? previewTargetForBeat(thenBeat, 999) : null; previewSlide(els.followingPreview, thenTarget ? slides[slideIndexById.get(thenTarget.slideId)] : null, thenTarget?.reveal ?? 999, null, thenBeat, currentBeatIndex + 2); renderInkBadge(els.followingPreview, thenTarget ? slides[slideIndexById.get(thenTarget.slideId)] : null); } // The presenter drawer is driven by the shared createOverview factory; refresh it when open // so the .current marker tracks the live slide (parity with the standalone refresh in // renderAudience). if (overview.isOpen()) overview.render(); renderPresenterMedia(); renderPresenterPoll(); } function applyState(nextState) { if (!nextState) return; const updatedAt = Number(nextState.updatedAt) || 0; const seq = Number(nextState.seq) || 0; if (seq < (Number(state.seq) || 0)) return; if (seq === (Number(state.seq) || 0) && updatedAt <= lastApplied) return; lastApplied = updatedAt; const nextIndex = clampIndex(nextState.index); const slideChanged = nextIndex !== state.index; // B3: navigating to another slide or carousel card changes which embed is on screen, so any // active embed interaction is ended — its frame is about to be hidden or replaced. if (interactingFrame && (slideChanged || (Math.max(0, Number(nextState.reveal) || 0) !== state.reveal))) exitEmbedInteract(); // Leaving the slide closes any open mini-grid (it belongs to the slide's gallery). if (gridGallery && slideChanged) closeGalleryGrid(); // The lightbox belongs to a slide's image set; a slide change forces it closed so a stale // {open,index} from the previous slide can never carry over. Otherwise the published value // wins (this is shared state — late joiners see an open lightbox). const incomingLightbox = nextState.lightbox && typeof nextState.lightbox === "object" ? nextState.lightbox : { open: false, index: 0 }; // A closed lightbox keeps its published index across a slide change: goToBeat (the one // navigation sink) publishes the arrival state explicitly, and for a slide with an image // sequence entered backwards that index says "the images have been shown" (image-steps.js). const incomingIndex = Math.max(0, Number(incomingLightbox.index) || 0); const lightbox = slideChanged ? { open: false, index: incomingLightbox.open ? 0 : incomingIndex } : { open: Boolean(incomingLightbox.open), index: incomingIndex }; // Mode (reveal/focus) is taken from the incoming state VERBATIM. The "arrival" rules // (authored {data-mode} wins; manual mode sticky; step resets to 0) are applied at the // navigation source (goTo) so the published state is already authoritative — this lets a // late-joining peer mirror the presenter's exact kind+step, and keeps manual toggles intact. const mode = normalizeMode(nextState.mode); // Ticket 04: the talk's QR overlay sits over the slide it was opened from; any slide change // (overview jump, hash, peer) drops it so it can never strand over a different slide. const talkQr = slideChanged ? normaliseTalkQr(null) : normaliseTalkQr(nextState.talkQr); // Simulation disclosures (state.sim) belong to the slide they name. A state for the slide this // window now shows is kept even when the window itself changes slide (a late joiner adopting // the presenter's snapshot); one naming any other slide is dropped, so arriving at a slide // resets it to its authored default (spec 5.1). const incomingSim = normaliseSimState(nextState.sim); const sim = incomingSim && incomingSim.slideId === slides[nextIndex]?.dataset.id ? incomingSim : null; // The move that types (runtime/sim-typing.js) belongs to its slide AND its step: a step back, a // jump or any other slide drops it, so those show every part complete at once. const incomingType = normaliseSimType(nextState.simType); const simType = incomingType && incomingType.slideId === slides[nextIndex]?.dataset.id && incomingType.to === mode.step ? incomingType : null; // Beat rides the shared state so presenter and audience stay in lockstep on the SAME beat // index. A state without one (stored pre-beat session, stale peer) derives it from the // slide index — first beat of that slide — so old sessions restore cleanly. const beat = nextState.beat == null ? firstBeatForSlideIndex(nextIndex) : clampBeat(nextState.beat); state = { index: nextIndex, beat, reveal: Math.max(0, Number(nextState.reveal) || 0), fontSize: Math.max(70, Math.min(180, Number(nextState.fontSize) || 100)), lightbox, // The full-screen page belongs to its slide: any other slide's id is dropped, so leaving ends it. embedFullScreen: typeof nextState.embedFullScreen === "string" && nextState.embedFullScreen && nextState.embedFullScreen === slides[nextIndex]?.dataset.id ? nextState.embedFullScreen : null, talkQr, sim, simType, mode, seq: Math.max(seq, Number(state.seq) || 0), updatedAt: updatedAt || Date.now() }; // The preload bridge cannot read this closure directly. Publish the exact live-session // projection on the document root so main receives carousel reveal plus reveal/focus mode. document.documentElement.dataset.twLiveReveal = String(state.reveal); document.documentElement.dataset.twLiveFocus = state.mode.kind ? JSON.stringify({ kind: state.mode.kind, step: state.mode.step }) : ""; document.documentElement.dataset.twLiveLightbox = JSON.stringify(state.lightbox); document.documentElement.dataset.twLiveTalkQr = state.talkQr.open ? "1" : ""; // Presenter QoL: record this slide as shown (jumped-over gaps register as skipped via // slideStatus's maxShown rule) and refresh the overview if it is open so markers stay live. if (isPresenter) { shownSet.add(state.index); persistProgress(); if (overview?.isOpen()) overview.render(); } renderAudience(); // A slide whose emphasis steps is projected from its painted units (the card on show in a // carousel), so its entry is written once the slide is rendered. if (flatStepSlide(currentSlide())) document.documentElement.dataset.twLiveFocus = liveFocusProjection(); applySimDisclosures(); pollProjection.render(); renderPresenter(); renderLightbox(); renderTalkQr(); applyModeDimming(); applySimScroll(); syncSimTyping(); if (!state.mode.kind) hideModeBanner(); renderModeControls(); if (slideChanged || JSON.stringify(nextState.lightbox || {}) !== JSON.stringify(previousPointerLightbox || {})) { pointerOverlay?.show('gone'); if (isPresenter) broadcastPointer('gone'); } previousPointerLightbox = { ...state.lightbox }; penViewChanged(); pointerOverlay?.refresh(); // F1: highlights are per-slide. On a slide change, drop any highlight that belonged to the // slide we left so it can't bleed onto the new one; then re-apply whatever (if anything) is // recorded for the now-active slide. renderAudience already painted the slide DOM fresh. if (slideChanged && currentHighlight.slideId && currentHighlight.slideId !== currentSlide()?.dataset.id) { if (isPresenter) currentHighlight = { slideId: null, ranges: [] }; } if (!isPresenter) reapplyHighlightToLive(); if (isPresenter) updateHighlightClearBtn(); } // Read the authored stepping mode from a slide's data-mode attribute (reveal|focus). function authoredModeFor(index) { const slide = slides[index]; const m = slide?.dataset.mode; return m === "reveal" || m === "focus" ? m : null; } // {nostep}: this slide always shows everything at once — no stepping even under a sticky // presenter mode (which stays armed and reasserts on the next plain slide). function slideNoStep(index) { return Boolean(slides[index]?.hasAttribute("data-nostep")); } // Arrival mode for a slide: authored wins (that slide only), {nostep} silences everything, // otherwise the presenter's sticky manual mode reasserts. function arrivalMode(index) { const sticky = state.mode?.sticky || null; if (slideNoStep(index)) return { kind: null, step: 0, manual: false, sticky }; const authored = authoredModeFor(index); if (authored) return { kind: authored, step: 0, manual: false, sticky }; return { kind: sticky, step: 0, manual: Boolean(sticky), sticky }; } function normalizeMode(value) { if (!value || typeof value !== "object") return { kind: null, step: 0, manual: false, sticky: null }; const kind = value.kind === "reveal" || value.kind === "focus" ? value.kind : null; const sticky = value.sticky === "reveal" || value.sticky === "focus" ? value.sticky : null; // `sticky` is the PRESENTER-toggled mode: it survives authored-mode slides and {nostep} // slides and reasserts itself on every plain slide until toggled off. `kind` is what is // ACTIVE on the current slide; `manual` marks that the active kind came from sticky. return { kind, step: Math.max(0, Number(value.step) || 0), manual: Boolean(value.manual) && kind != null, sticky }; } function sendToPeer(message) { if (!isPaired) return; channel?.postMessage(message); // Only to the peer this deck established. Over http(s) the message is addressed to the deck's // own origin, so a peer window that has since gone to another site is sent nothing; from // file:// an origin cannot be named. if (peerWindow && !peerWindow.closed) peerWindow.postMessage(message, PEER_TARGET_ORIGIN); } // === E8: presenter-triggered media playback on the audience display === // The controllable media on a slide, in DOM order: lazy YouTube/embed iframes and local //