${clone.outerHTML}
`;
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 `
⠿
${index + 1} ${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)} = limit ? 'disabled' : ''} aria-label="Rank ${escape(option.label)}">Rank
`).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 => `${escape(label.label)} `).join('')}${poll.allowSkip ? `Clear answer ` : ''}`).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 = `
Ranking
Rank all
Rank your top
Scale labels
Labels, separated by commas
Allow skipped items
`
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 ``
+ ``
+ `${pollFrameRenderAnswers(poll, options, labels, view, ctx.results, live, ctx.join)}
${joinHtml}
`
+ ``
+ ` `;
}
// 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(`${name}>`);
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
// elements. Used both to build the presenter control row (label/selector) and, on
// the audience, to resolve a command's target index to a real element.
function slideMedia(slide) {
if (!slide) return [];
return Array.from(slide.querySelectorAll("figure.slide-embed iframe, video, .lightbox-video-placeholder, .slide-audio > audio")).map((node) => {
// Ticket 04: an audio chip is controlled like a video, from the same Play/Pause row, M key and selector.
if (node.tagName === "AUDIO") {
const chip = node.closest(".slide-audio");
return { el: node, chip, isVideo: false, isAudio: true, label: chip?.querySelector(".slide-audio-title")?.textContent?.trim() || "Audio" };
}
// Ticket 24: a video enlarged in the lightbox is represented in its slide by a placeholder.
const el = node.classList.contains("lightbox-video-placeholder") ? lightboxVideo?.el : node;
if (!el) return null;
const isVideo = el.tagName === "VIDEO";
let label = isVideo
? (el.getAttribute("title") || el.closest("figure")?.querySelector("figcaption")?.textContent?.trim() || "Video")
: (el.getAttribute("title") || "Embedded video");
// A bare URL title reads as noise on the control row — show a friendly source name.
if (/^https?:\/\//i.test(label)) {
if (/youtu/.test(label)) label = "YouTube video";
else if (/vimeo/.test(label)) label = "Vimeo video";
else { try { label = new URL(label).hostname.replace(/^www\./, "") + " embed"; } catch {} }
}
return { el, isVideo, label };
}).filter(Boolean);
}
// Transient media command channel. NOT part of replayed state: media commands never touch
// localStorage or the published state, so a late-joining audience (which only reads the
// stored state) can never auto-play from a stale command. Each command carries a nonce so a
// window that receives it on more than one path (BroadcastChannel AND postMessage) runs it
// once. The presenter reads the live slide's media; the target is its DOM index.
function sendMediaCommand(action) {
if (!isPresenter) return;
const media = slideMedia(currentSlide());
if (media.length === 0) return;
let target = Number(els.presenterMediaSelect.value);
if (!Number.isInteger(target) || target < 0 || target >= media.length) target = 0;
const nonce = createSessionId();
sendMediaCommandToPeer({ action, target, nonce });
// The presenter's own previews strip media src, so there is nothing to play locally — the
// command is for the audience window only.
}
function sendMediaCommandToPeer(mediaCommand) {
sendToPeer({ type: commandType, command: "media", mediaCommand, index: state.index });
}
// Ticket 24: presenter → audience "Video: Fullscreen". Same transient command channel as media
// play/pause (never replayed state); the target is the index into the slide's videos.
function sendVideoCommandToPeer(videoCommand) {
sendToPeer({ type: commandType, command: "video", videoCommand, index: state.index });
}
// Presenter side of the audio chip: the projector reports each chip's state and whole-second
// time; the presenter keeps the latest per slide and chip, paints it into the current-slide
// preview (live, inside the preview iframe) and into any rebuilt preview clone. No sound here.
const audioPreviewStates = new Map();
function paintAudioStates(root, slideIndex) {
if (!root || slideIndex < 0) return;
root.querySelectorAll(".slide-audio").forEach((chip, chipIndex) => {
const known = audioPreviewStates.get(slideIndex + ":" + chipIndex);
if (known) setAudioChipState(chip, known.chipState, known.seconds);
});
}
function applyAudioState(message) {
if (!isPresenter || !message || !Number.isInteger(message.slideIndex) || !Number.isInteger(message.chipIndex)) return;
audioPreviewStates.set(message.slideIndex + ":" + message.chipIndex, { chipState: message.chipState, seconds: message.seconds });
if (message.slideIndex !== state.index) return;
try {
const doc = els.currentPreview?.querySelector("iframe")?.contentDocument;
setAudioChipState(doc?.querySelectorAll(".slide-audio")[message.chipIndex], message.chipState, message.seconds);
} catch { /* the preview is mid-rebuild: the next paint reads the stored state */ }
}
let lastVideoNonce = "";
function executeVideoCommand(message) {
if (!isAudience) return;
const vc = message?.videoCommand;
if (!vc || vc.action !== "fullscreen") return;
if (vc.nonce && vc.nonce === lastVideoNonce) return;
lastVideoNonce = vc.nonce || "";
if (Number.isInteger(message.index) && message.index !== state.index) return;
const videos = slideVideos(currentSlide());
const entry = videos[Number.isInteger(vc.target) ? vc.target : 0] || videos[0];
if (!entry) return;
requestVideoFullscreen(entry.el);
}
let lastMediaNonce = "";
function executeMediaCommand(message) {
if (!isAudience) return;
const mc = message?.mediaCommand;
if (!mc || (mc.action !== "play" && mc.action !== "pause")) return;
// De-dup: ignore a command already applied (arrived on a second path).
if (mc.nonce && mc.nonce === lastMediaNonce) return;
lastMediaNonce = mc.nonce || "";
// Only act on media of the slide the presenter is on; if the audience has drifted, ignore.
if (Number.isInteger(message.index) && message.index !== state.index) return;
const media = slideMedia(currentSlide());
const targetIndex = Number.isInteger(mc.target) ? mc.target : 0;
const item = media[targetIndex];
if (!item) return;
if (item.isAudio) {
if (mc.action === "play") audioChips.play(item.chip);
else audioChips.pause(item.chip);
} else if (item.isVideo) {
if (mc.action === "play") {
const result = item.el.play?.();
if (result && typeof result.catch === "function") {
// A dummy/undecodable source rejects the play() promise — that is expected and not a
// failure of the control path; swallow it so the audience console stays clean.
result.catch(() => {});
}
} else {
item.el.pause?.();
}
} else {
// YouTube IFrame API: post a command message to the embed. Requires enablejsapi=1 on the
// embed URL (baked in by the generator). Works once the iframe has loaded; if it has not
// (lazy data-src not yet promoted), promote it first.
const frame = item.el;
if (!frame.src && frame.dataset.src) frame.src = embedSrcFor(frame);
const func = mc.action === "play" ? "playVideo" : "pauseVideo";
try {
frame.contentWindow?.postMessage(JSON.stringify({ event: "command", func, args: [] }), "*");
} catch {
// contentWindow may be briefly unavailable; ignore — the next command will retry.
}
}
}
// Presenter control row: shown when the current slide carries controllable media OR images.
function renderPresenterMedia() {
if (!isPresenter || !els.presenterMedia) return;
const media = slideMedia(currentSlide());
// G5: the Gallery button rides the same control row, shown when the slide has images.
if (els.presenterVideoFullscreen) els.presenterVideoFullscreen.hidden = slideVideos().length === 0;
if (els.presenterGallery) {
const images = slideImages();
els.presenterGallery.hidden = images.length === 0;
if (els.presenterGalleryBtn) {
twSetLabel(els.presenterGalleryBtn, state.lightbox?.open ? "Close gallery" : "Gallery");
els.presenterGalleryBtn.dataset.tip = state.lightbox?.open ? "Close image gallery" : "Image gallery";
}
}
if (media.length === 0) {
// Media row still needs to be visible if there are images for the Gallery button.
els.presenterMedia.hidden = !els.presenterGallery || els.presenterGallery.hidden;
els.presenterMediaSelect.hidden = true;
els.presenterMediaLabel.textContent = "";
els.presenterMediaPlay.hidden = true;
els.presenterMediaPause.hidden = true;
return;
}
els.presenterMediaPlay.hidden = false;
els.presenterMediaPause.hidden = false;
els.presenterMedia.hidden = false;
if (media.length > 1) {
els.presenterMediaSelect.hidden = false;
const previousValue = els.presenterMediaSelect.value;
els.presenterMediaSelect.replaceChildren();
media.forEach((item, index) => {
const option = document.createElement("option");
option.value = String(index);
option.textContent = `${index + 1}. ${item.label}`;
els.presenterMediaSelect.appendChild(option);
});
els.presenterMediaSelect.value = (previousValue && Number(previousValue) < media.length) ? previousValue : "0";
els.presenterMediaLabel.textContent = "Media:";
} else {
els.presenterMediaSelect.hidden = true;
els.presenterMediaSelect.value = "0";
els.presenterMediaLabel.textContent = media[0].label;
}
}
// === F1: live highlight sync (presenter → audience) ========================================
// The presenter highlights text on the CURRENT slide; the same highlight appears on the
// AUDIENCE slide, broadcast over the existing session-scoped command channel (the same path as
// the media commands — NOT replayed state, so it never touches localStorage and a late-joining
// audience can't auto-restore a stale highlight). Each broadcast carries the full current set
// for the slide, so "apply" and "clear" are the same operation with a longer/empty list.
//
// Robust addressing: a highlight is one or more ranges, each {block, start, end} where `block`
// is the index of a text-bearing block element in a stable per-slide order, and start/end are
// character offsets into that block's textContent. Because presenter and audience render the
// SAME slide DOM, the same (block,start,end) re-resolves on the audience. Applying walks the
// block's text nodes and wraps the [start,end) slice in , so nested markup
// ( etc.) is preserved (each crossed text node gets its own adjacent mark). If a block
// index or offset can't be resolved (DOM differs), that range is skipped silently — no crash.
// The stable, ordered set of highlightable text blocks on a slide. Leaf-ish text containers
// only (so offsets are unambiguous): headings, paragraphs, list items, quotes, captions,
// statements, trace turns, table cells. Notes are never highlightable (audience can't see them).
const HIGHLIGHT_BLOCK_SELECTOR = "h1,h2,h3,h4,p,li,blockquote,figcaption,.statement,.fl-text,.card-comment,th,td,.tl-text,.smartart-node > .smartart-label";
function highlightableBlocks(slide) {
if (!slide) return [];
return Array.from(slide.querySelectorAll(HIGHLIGHT_BLOCK_SELECTOR))
.filter((el) => !el.closest("aside.notes"));
}
// The ordered text nodes inside a block (ignoring those already inside a previous mark is not
// needed: we always clear first, then apply). Used to map char offsets ↔ DOM positions.
function blockTextNodes(block) {
const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT, null);
const nodes = [];
let node;
while ((node = walker.nextNode())) nodes.push(node);
return nodes;
}
// Serialise the current window's text selection (a Selection or Range) against `slide` into the
// {block,start,end} range form. Returns null if the selection is empty or outside any block.
// `root` is the document the selection lives in (the live slide's document on audience, or the
// preview iframe's document on the presenter).
function serializeSelectionWithin(slide, range) {
if (!slide || !range || range.collapsed) return null;
const blocks = highlightableBlocks(slide);
// Find the block that fully contains the selection (or the closest common ancestor block).
const common = range.commonAncestorContainer;
const commonEl = common.nodeType === 1 ? common : common.parentElement;
const block = commonEl && commonEl.closest(HIGHLIGHT_BLOCK_SELECTOR);
if (!block) return null;
const blockIndex = blocks.indexOf(block);
if (blockIndex < 0) return null;
// Char offset of a (node, offset) point within the block's textContent.
const charOffsetOf = (node, offset) => {
let acc = 0;
const nodes = blockTextNodes(block);
for (const tn of nodes) {
if (tn === node) return acc + offset;
acc += tn.nodeValue.length;
}
// Point is at an element boundary: count text up to it.
const pre = document.createRange();
pre.selectNodeContents(block);
try { pre.setEnd(node, offset); } catch { return acc; }
return pre.toString().length;
};
let start = charOffsetOf(range.startContainer, range.startOffset);
let end = charOffsetOf(range.endContainer, range.endOffset);
if (end < start) [start, end] = [end, start];
if (end <= start) return null;
return { block: blockIndex, start, end };
}
// Pure comparator for two range-sets, used to skip redundant re-broadcasts and in tests.
function highlightRangesEqual(a, b) {
const A = Array.isArray(a) ? a : [];
const B = Array.isArray(b) ? b : [];
if (A.length !== B.length) return false;
for (let i = 0; i < A.length; i++) {
if (A[i].block !== B[i].block || A[i].start !== B[i].start || A[i].end !== B[i].end) return false;
}
return true;
}
// Remove every highlight mark from a root, restoring the original text (merging split nodes).
function clearHighlights(root) {
if (!root) return;
root.querySelectorAll("mark.hl-mark").forEach((mark) => {
const parent = mark.parentNode;
if (!parent) return;
while (mark.firstChild) parent.insertBefore(mark.firstChild, mark);
parent.removeChild(mark);
parent.normalize();
});
}
// PURE: given the lengths of a block's text nodes in order and a [start,end) char range over
// their concatenation, return the per-node slices to wrap: {nodeIndex, from, to} (node-local
// offsets). This is the offset arithmetic that crosses nested markup, isolated so it can be
// unit-tested without a DOM.
function computeRangeEdits(textNodeLengths, start, end) {
const edits = [];
if (!(end > start)) return edits;
let acc = 0;
for (let idx = 0; idx < textNodeLengths.length; idx++) {
const len = textNodeLengths[idx];
const nodeStart = acc;
const nodeEnd = acc + len;
acc = nodeEnd;
const from = Math.max(start, nodeStart);
const to = Math.min(end, nodeEnd);
if (to <= from) continue;
edits.push({ nodeIndex: idx, from: from - nodeStart, to: to - nodeStart });
}
return edits;
}
// Wrap [start,end) of a block's text in , crossing nested markup safely by
// wrapping each overlapping text node's slice. No-op if offsets fall outside the text.
function applyRangeToBlock(block, start, end) {
if (!block || end <= start) return;
const nodes = blockTextNodes(block);
const edits = computeRangeEdits(nodes.map((tn) => tn.nodeValue.length), start, end)
.map((e) => ({ node: nodes[e.nodeIndex], from: e.from, to: e.to }));
// Apply edits (computed against the original nodes before any wrapping).
for (const { node, from, to } of edits) {
const range = document.createRange();
try {
range.setStart(node, from);
range.setEnd(node, to);
const mark = document.createElement("mark");
mark.className = "hl-mark";
range.surroundContents(mark);
} catch {
// surroundContents throws if the range partially selects a non-text node; skip silently.
}
}
}
// Apply a full highlight payload to a root: clear first, then re-apply each resolvable range.
// Skips ranges whose block index is out of bounds. Resilient: never throws on a bad payload.
function applyHighlightPayload(root, payload) {
if (!root) return;
clearHighlights(root);
const ranges = payload && Array.isArray(payload.ranges) ? payload.ranges : [];
if (ranges.length === 0) return;
const blocks = highlightableBlocks(root);
for (const r of ranges) {
const block = blocks[r.block];
if (!block) continue;
const start = Math.max(0, Number(r.start) || 0);
const end = Math.max(0, Number(r.end) || 0);
applyRangeToBlock(block, start, end);
}
}
// Per-slide highlight set, kept in memory on BOTH windows (never persisted). Re-applied on
// slide change so highlights stick to their slide; cleared when leaving it.
let currentHighlight = { slideId: null, ranges: [] };
function broadcastHighlight() {
if (!isPaired) return;
sendToPeer({
type: commandType,
command: "highlight",
highlight: { slideId: currentHighlight.slideId, ranges: currentHighlight.ranges },
nonce: createSessionId()
});
}
// Audience side: apply an incoming highlight command to the LIVE slide (if it is the addressed
// slide). A highlight for another slide is stored so it lands when that slide becomes active.
let lastHighlightNonce = "";
function executeHighlightCommand(message) {
const hl = message?.highlight;
if (!hl) return;
if (message.nonce && message.nonce === lastHighlightNonce) return; // de-dup multi-path delivery
lastHighlightNonce = message.nonce || "";
currentHighlight = { slideId: hl.slideId || null, ranges: Array.isArray(hl.ranges) ? hl.ranges : [] };
reapplyHighlightToLive();
}
// Apply currentHighlight to whichever live surface this window owns:
// - audience / standalone: the live active slide
// - presenter: nothing live (the deck is hidden); the marks ride the Current preview clone,
// which previewSlide() rebuilds — so the presenter re-bakes them in renderPresenter.
function reapplyHighlightToLive() {
const slide = currentSlide();
if (!slide) return;
if (isPresenter) { renderPresenter(); return; }
clearHighlights(slide);
if (currentHighlight.slideId === slide.dataset.id) {
applyHighlightPayload(slide, currentHighlight);
}
}
// === Presenter highlight authoring ===
// Highlight mode is "armed" by the Highlight button or the `h` key. While armed, the Current
// preview iframe is selectable; selecting text inside it serialises against the iframe's slide
// clone (identical to the audience DOM) and broadcasts the new set. Disarm with `h`/Escape.
function refreshPresenterShortcuts() {
for (const [id, registryId] of Object.entries(PRESENTER_CONTROL_COMMANDS)) {
const el = document.getElementById(id);
if (!el) continue;
const fallback = PRESENTER_TIPS[id]?.[1] ?? PRESENTER_COMMAND_KEYS.find(item => item.id === registryId)?.keys ?? '';
const key = presenterShortcuts.key(registryId, fallback);
el.dataset.key = key;
const cap = el.querySelector('.tw-mi-key');
if (cap && cap.textContent !== key) cap.textContent = key;
}
}
let presenterShortcuts;
let previousPointerLightbox = null;
let pointerArmed = false, pointerPending = 'gone', pointerFrame = 0, pointerLiveAt = 0, pointerLiveTimer = 0;
let pointerHeartbeat = null;
// The Pen's state (ticket 08). `var`: applyState and the capture sync may run before the Pen's
// block below at start-up; penReady holds every Pen render until the generated block has run.
var penArmed = false, penReady = false, penStore = null, penGesture = null, penDraft = null, penPieces = [];
const pointerOverlaySurfaces = [...document.querySelectorAll(
'#presenterCommandPalette, #twShortcuts, #presenterQuickPollCompose, #presenterInstantCompose, #presenterInstantPaste, '
+ '#presenterQuestionsTray, #twDurationSetter, #liveGoPanel, #presenterRoot .tw-menu, #notesMenu'
)];
function presenterOverlayOpen() {
return pointerOverlaySurfaces.some(el => !el.hidden)
// The image lightbox is itself a Pointer surface, rather than presenter chrome.
// A full-screen board covers the slide; beside it the slide stays pointable (board-panel.js sets data-mode).
|| (() => { const board = document.getElementById('presenterBoardPanel'); return !!board && !board.hidden && board.dataset.mode === 'full'; })()
|| [...document.querySelectorAll('[role="dialog"], [aria-modal="true"], .tw-shortcut-rebind, .twrec-picker, .twrec-close-modal')].some(el => el !== els.lightbox && !el.closest('[hidden]') && getComputedStyle(el).display !== 'none')
|| [...document.querySelectorAll('#presenterRoot [role="menu"]')].some(el => !el.hidden);
}
function syncPointerCapture() {
const open = presenterOverlayOpen();
const capture = pointerArmed && !open;
pointerOverlay?.arm(capture);
// The Pen takes presses the same way, and lets go while presenter chrome covers the slide.
if (penArmed && open) penGesture?.cancel();
pointerOverlay?.armPen(penArmed && !open, penArmed ? penCursorNow() : '');
if (!capture) {
pointerOverlay?.show('gone');
if (pointerPending !== 'gone') broadcastPointer('gone');
}
}
const pointerSurface = () => {
const image = state.lightbox?.open && !els.lightboxImg.hidden ? els.lightboxImg : null;
const target = image || (isPresenter ? els.currentPreview?.querySelector('iframe') : document.querySelector('.stage'));
if (!target) return null;
const canvasScale = image ? Math.min(innerWidth / 1280, innerHeight / 720) : target.getBoundingClientRect().width / 1280;
const rect = target.getBoundingClientRect();
// Clip capture to the Current pane without changing its verified coordinate mapping.
const captureRect = isPresenter && !image ? els.currentPreview.getBoundingClientRect() : null;
return { element: target, rect, captureRect, canvasScale,
space: image ? 'image' : 'slide', image: image ? Math.max(0, Number(state.lightbox?.index) || 0) : undefined, slideId: currentSlide()?.dataset.id };
};
const pointerOverlay = !isReplay && !document.body.hasAttribute('data-tw-preview') && (isPresenter || isAudience) ? createPointerOverlay({ document, surface: pointerSurface, onMove: broadcastPointer, staleMs: isAudience ? 2000 : 0, drawInk: penDraw }) : null;
// A replay draws the recorded ink only (ticket 08), on an overlay made when ink first arrives;
// it never shows the pointer and never takes presses. The replay does not zoom: ink drawn on a
// zoomed image is drawn over that image where it sits on the slide, in the image's own units.
let replayInkOverlay = null, replayInkImage = null;
// Where the picture itself is drawn inside its element (pen-ink.js penPictureRect: object-fit and
// object-position, so a framed picture pinned left-top is drawn from its left-top corner).
function replayPictureRect(el) {
const box = el.getBoundingClientRect();
const natural = el.tagName === "IMG" ? [el.naturalWidth, el.naturalHeight] : null;
if (!natural) return box;
const style = getComputedStyle(el);
return penPictureRect(box, natural, style.objectFit, style.objectPosition);
}
function replayInkSurface() {
if (replayInkImage === null) return pointerSurface();
const slide = currentSlide();
const entry = slideImages(slide)[replayInkImage];
const stage = document.querySelector(".stage");
// Any zoomable picture (a figure's image, an image-grid cell, a QR code); never a video.
if (!entry?.el || entry.kind === "video" || !stage) return null;
const rect = replayPictureRect(entry.el);
// Clipped to the element's box: a cropped (cover) picture's ink stops where the picture does.
return { element: entry.el, rect, captureRect: entry.el.getBoundingClientRect(), canvasScale: stage.getBoundingClientRect().width / 1280,
space: "image", image: replayInkImage, slideId: slide?.dataset.id };
}
function showReplayInk(strokes, slideId, image = null) {
replayInkImage = Number.isSafeInteger(image) && image >= 0 ? image : null;
const layer = replayInkImage === null ? { space: "slide" } : { space: "image", image: replayInkImage };
const view = Array.isArray(strokes) && strokes.length ? penInkView({ slideId, ...layer, strokes, draft: null }) : null;
if (!view && !replayInkOverlay) return;
replayInkOverlay ??= createPointerOverlay({ document, surface: replayInkSurface, drawInk: penDraw });
replayInkOverlay.ink(view);
}
function broadcastPointer(value) {
pointerPending = value;
if (value === 'gone') { flushPointer(); writeLivePointer(); return; }
if (!pointerFrame) pointerFrame = requestAnimationFrame(flushPointer);
if (!pointerLiveTimer) pointerLiveTimer = setTimeout(writeLivePointer,
Math.max(0, Math.ceil(1000 / 15) - (Date.now() - pointerLiveAt)));
}
function flushPointer() {
cancelAnimationFrame(pointerFrame); pointerFrame = 0;
if (isPaired) sendToPeer({ type: commandType, command: 'pointer', pointer: pointerPending });
}
function writeLivePointer() {
clearTimeout(pointerLiveTimer); pointerLiveTimer = 0;
// The preload owns IPC; only this path has the venue's 15 Hz limit.
document.documentElement.dataset.twLivePointer = JSON.stringify(pointerPending);
pointerLiveAt = Date.now();
document.documentElement.dataset.twLivePointerTick = String(pointerLiveAt);
}
function setPointerArmed(on) {
if (!isPresenter) return;
pointerArmed = Boolean(on);
if (pointerArmed && penArmed) setPenArmed(false);
watchMarkSuspension();
if (pointerArmed) { setHighlightArmed(false); releaseEmbedEngagement(); }
syncPointerCapture();
clearInterval(pointerHeartbeat);
pointerHeartbeat = pointerArmed ? setInterval(() => {
if (pointerPending !== 'gone' && !presenterOverlayOpen() && Date.now() - pointerLiveAt >= 950) { flushPointer(); writeLivePointer(); }
}, 1000) : null;
document.getElementById('presenterPointer')?.setAttribute('aria-pressed', String(pointerArmed));
const chip = document.getElementById('presenterPointerChip'); if (chip) chip.hidden = !pointerArmed;
if (!pointerArmed) { pointerOverlay?.show('gone'); broadcastPointer('gone'); }
}
function togglePointer() { setPointerArmed(!pointerArmed); }
// Existing open/close paths write these attributes; one predicate suspends capture on all surfaces.
// The pen's own options (popover, strip) are not presenter chrome over the slide.
const pointerSuspension = new MutationObserver(records => {
if (records.some(record => !record.target.closest?.('.tw-live-overlay, #presenterPenPop, #presenterPenStrip, #presenterInkStatus'))) syncPointerCapture();
});
function watchMarkSuspension() {
pointerSuspension.disconnect();
if (pointerArmed || penArmed) pointerSuspension.observe(document.body, { childList: true, subtree: true,
attributes: true, attributeFilter: ['hidden', 'role', 'aria-modal', 'class', 'style', 'data-mode'] });
}
function clearLivePointer() {
if (!isPresenter) return;
clearInterval(pointerHeartbeat);
pointerSuspension.disconnect();
pointerOverlay?.arm(false);
pointerOverlay?.show('gone');
broadcastPointer('gone');
}
document.getElementById('moreRefresh')?.addEventListener('click', clearLivePointer, true);
window.addEventListener('pagehide', () => { clearLivePointer(); pointerOverlay?.destroy(); }, { once: true });
window.addEventListener('beforeunload', () => {
clearLivePointer();
pointerSuspension.disconnect();
pointerOverlay?.destroy();
}, { once: true });
// ── The Pen (ticket 08; ADR-0037; drawn in docs/design/2026-10-06-pointer-and-pen/, P2) ──
// Freehand, Arrow and Rectangle on the current slide, or on a zoomed image (its own layer, shown
// only when that image is zoomed again). Ink is kept per layer in this window's memory for the
// talk (penStore, compiler/assets/runtime/pen-ink.js) until cleared, and is gone when the window
// closes: it is never part of the published state, localStorage, the talk file or the vault.
// The projector gets the current layer as `command: "ink"` (each animation frame at most) and
// asks for it with `ink-ready` when it opens or reloads; the venue screen gets it through the
// live bridge from the root's data-tw-live-ink (15 a second at most, a keep-alive every 10 s) and
// the worker, which checks it again and sends it to venue screens only.
const PEN_TOOL_NAMES = { freehand: 'Freehand', arrow: 'Arrow', rectangle: 'Rectangle' };
const PEN_INK_NAMES = { red: 'Red', yellow: 'Yellow', green: 'Green', blue: 'Blue' };
const PEN_TOOL_GLYPHS = { arrow: 'move-up-right', rectangle: 'square' };
const penSettings = { tool: 'freehand', ink: 'red', width: 'thin' };
let penFrame = 0, penLiveTimer = 0, penLiveAt = 0, penHeartbeat = 0, penLastLayer = '';
if (isPresenter) penStore = createPenStore();
function penLayer() {
const slideId = currentSlide()?.dataset.id;
if (!slideId) return null;
const image = Boolean(state.lightbox?.open && els.lightboxImg && !els.lightboxImg.hidden);
return { slideId, space: image ? 'image' : 'slide', image: image ? Math.max(0, Number(state.lightbox?.index) || 0) : undefined };
}
const penKeyOf = (layer) => penLayerKey(layer.slideId, layer.space, layer.image);
function penView(withDraft = true) {
const layer = penLayer();
if (!layer || !penStore) return null;
return { slideId: layer.slideId, space: layer.space, ...(layer.space === 'image' ? { image: layer.image } : {}),
// The finished pieces of a long line still being drawn show with it; Esc drops them with it.
strokes: withDraft ? penStore.strokes(penKeyOf(layer)).concat(penPieces) : penStore.strokes(penKeyOf(layer)), draft: withDraft ? penDraft : null };
}
function inkHere() { const layer = penLayer(); return Boolean(layer && penStore?.has(penKeyOf(layer))); }
function penCursorNow() {
const scale = pointerSurface()?.canvasScale || 1;
return penCursor(penSettings.tool, penSettings.ink, PEN_WIDTHS[penSettings.width] * scale);
}
// Draw the current layer here and send it on; the last change always goes.
function pushInk() {
if (!isPresenter || !penReady) return;
pointerOverlay?.ink(penView());
if (!penFrame) penFrame = requestAnimationFrame(flushInkPeer);
if (!penLiveTimer) penLiveTimer = setTimeout(writeLiveInk, Math.max(0, Math.ceil(1000 / 15) - (Date.now() - penLiveAt)));
renderPenControls();
}
function flushInkPeer() {
cancelAnimationFrame(penFrame); penFrame = 0;
const view = penView();
if (isPaired && view) sendToPeer({ type: commandType, command: 'ink', ink: view });
}
function writeLiveInk() {
clearTimeout(penLiveTimer); penLiveTimer = 0;
const view = penView();
if (!view) return;
// The preload owns IPC (present-live-bridge.ts); the recorder reads the same slot for replay.
document.documentElement.dataset.twLiveInk = JSON.stringify(view);
penLiveAt = Date.now();
}
// A slide change or a zoom: the drag in progress is dropped and the new layer's ink is shown.
function penViewChanged() {
if (!isPresenter || !penReady) return;
const layer = penLayer();
const key = layer ? penKeyOf(layer) : '';
if (key === penLastLayer) return;
penLastLayer = key;
penGesture?.cancel();
penDraft = null; penPieces = [];
pushInk();
}
function setPenArmed(on) {
if (!isPresenter) return;
on = Boolean(on);
if (on && pointerArmed) setPointerArmed(false);
if (on && highlightArmed) setHighlightArmed(false);
if (on) releaseEmbedEngagement();
if (!on) { penGesture?.cancel(); penDraft = null; penPieces = []; }
penArmed = on;
watchMarkSuspension();
syncPointerCapture();
pushInk();
renderPenControls();
}
function togglePen() { setPenArmed(!penArmed); }
function setPenTool(tool) {
if (!PEN_TOOLS.includes(tool)) return;
penGesture?.cancel();
penSettings.tool = tool;
syncPointerCapture(); renderPenControls();
}
function stepPenTool(step) {
const at = PEN_TOOLS.indexOf(penSettings.tool);
setPenTool(PEN_TOOLS[(at + step + PEN_TOOLS.length) % PEN_TOOLS.length]);
}
function choosePenTool(tool) { setPenTool(tool); if (!penArmed) setPenArmed(true); }
function setPenInk(ink) { if (!Object.hasOwn(PEN_INKS, ink)) return; penSettings.ink = ink; syncPointerCapture(); renderPenControls(); }
function setPenWidth(width) { if (!Object.hasOwn(PEN_WIDTHS, width)) return; penSettings.width = width; syncPointerCapture(); renderPenControls(); }
function undoInk() { const layer = penLayer(); if (layer && penStore?.undo(penKeyOf(layer))) { pushInk(); refreshInkMarks(); } }
function clearInkHere() {
penGesture?.cancel();
const layer = penLayer();
if (layer && penStore?.clear(penKeyOf(layer))) { pushInk(); refreshInkMarks(); }
}
function clearAllInk() { penGesture?.cancel(); if (penStore?.clearAll()) { pushInk(); refreshInkMarks(); } }
// The projector has just opened or reloaded: it gets the current layer at once.
function answerInkReady() { if (isPresenter && penReady) flushInkPeer(); }
// Projector (and replay): ink from the presenter, checked field by field before it is drawn.
function receiveInk(raw) {
if (!isAudience) return;
// A malformed message is dropped; it never throws out of the message handler.
try {
const view = penInkView(raw);
if (view) pointerOverlay?.ink(view);
} catch {}
}
// A small mark on the Next and Then previews and in the outline for a slide that has a drawing.
function inkMarkNode() {
const mark = document.createElement('span');
mark.className = 'tw-ink-mark';
mark.setAttribute('role', 'img');
mark.setAttribute('aria-label', 'This slide has a drawing');
const icon = twIconEl('pen-tool');
if (icon) mark.append(icon);
return mark;
}
function renderInkBadge(target, slide) {
if (!target || !isPresenter) return;
target.dataset.inkSlide = slide?.dataset.id || '';
if (!penReady) return;
target.querySelector(':scope > .tw-ink-mark')?.remove();
if (slide && penStore?.slideHas(slide.dataset.id)) target.append(inkMarkNode());
}
function refreshInkMarks() {
if (!isPresenter || !penReady) return;
for (const target of [els.nextPreview, els.followingPreview]) {
if (!target) continue;
const id = target.dataset.inkSlide;
const shown = Boolean(target.querySelector(':scope > .tw-ink-mark'));
const has = Boolean(id && penStore.slideHas(id));
if (shown && !has) target.querySelector(':scope > .tw-ink-mark').remove();
if (!shown && has) target.append(inkMarkNode());
}
if (overview?.isOpen()) overview.render();
}
function placePenPop(pop) {
const anchor = document.getElementById('presenterPen');
if (!anchor || pop.hidden) return;
const r = anchor.getBoundingClientRect();
pop.style.left = Math.round(Math.max(8, Math.min(innerWidth - pop.offsetWidth - 8, r.right - pop.offsetWidth))) + 'px';
pop.style.top = Math.round(Math.max(8, r.top - 6 - pop.offsetHeight)) + 'px';
}
function renderPenControls() {
if (!isPresenter || !penReady) return;
const tool = penSettings.tool, ink = penSettings.ink, width = penSettings.width;
const button = document.getElementById('presenterPen');
if (button) {
button.setAttribute('aria-pressed', String(penArmed));
button.setAttribute('aria-expanded', String(penArmed));
let dot = button.querySelector(':scope > .tw-pen-dot');
if (!dot) { dot = document.createElement('span'); dot.className = 'tw-pen-dot'; dot.setAttribute('aria-hidden', 'true'); button.append(dot); }
dot.hidden = !penArmed;
dot.style.background = PEN_INKS[ink];
let glyph = button.querySelector(':scope > .tw-pen-glyph');
if (!glyph) { glyph = document.createElement('span'); glyph.className = 'tw-pen-glyph'; glyph.setAttribute('aria-hidden', 'true'); button.append(glyph); }
const glyphName = penArmed ? PEN_TOOL_GLYPHS[tool] || '' : '';
if (glyph.dataset.glyph !== glyphName) { glyph.dataset.glyph = glyphName; glyph.replaceChildren(...[glyphName && twIconEl(glyphName)].filter(Boolean)); }
glyph.hidden = !glyphName;
}
const chip = document.getElementById('presenterPenChip');
if (chip) chip.hidden = !penArmed;
const zoomed = penLayer()?.space === 'image';
const pop = document.getElementById('presenterPenPop');
const strip = document.getElementById('presenterPenStrip');
if (strip) strip.hidden = !penArmed || !zoomed;
if (pop) { pop.hidden = !penArmed || zoomed; placePenPop(pop); }
const stateEl = document.getElementById('presenterPenState');
if (stateEl) stateEl.textContent = `${PEN_INK_NAMES[ink]} · ${PEN_TOOL_NAMES[tool]}`;
const penKey = document.getElementById('presenterPenKey');
if (penKey) penKey.textContent = presenterShortcuts?.key('presenter.pen', 'D') ?? 'D';
const toolKey = document.getElementById('presenterPenToolKey');
if (toolKey) toolKey.textContent = (presenterShortcuts?.key('presenter.pen-tool', 'W') ?? 'W').split(' / ')[0];
for (const b of document.querySelectorAll('#presenterRoot [data-pen-tool]')) b.setAttribute('aria-pressed', String(b.dataset.penTool === tool));
for (const b of document.querySelectorAll('#presenterRoot [data-pen-ink]')) {
b.setAttribute('aria-pressed', String(b.dataset.penInk === ink));
b.style.setProperty('--ink', PEN_INKS[b.dataset.penInk] || 'transparent');
}
for (const b of document.querySelectorAll('#presenterRoot [data-pen-width]')) b.setAttribute('aria-pressed', String(b.dataset.penWidth === width));
const has = inkHere();
for (const id of ['penUndo', 'penStripUndo', 'penClear', 'penStripClear']) { const b = document.getElementById(id); if (b) b.disabled = !has; }
// With no tool on, a slide with a drawing offers one quiet "Clear drawing" in the status bar.
const status = document.getElementById('presenterInkStatus');
if (status) status.hidden = penArmed || pointerArmed || highlightArmed || !has;
}
if (isPresenter && pointerOverlay) {
penGesture = createPenGesture({ root: pointerOverlay.root, surface: pointerSurface,
settings: () => (penArmed ? penSettings : null),
onDraft: (stroke, pieces) => { penDraft = stroke; penPieces = pieces || []; pushInk(); },
fits: (key, strokes, points) => penStore.fits(key, strokes, points),
onCommit: (strokes, key) => {
const before = penStore.slideHas(key.split('\u0000')[0]);
// One gesture, one undo unit: a long line's pieces go in (and come out) together.
penStore.add(key, strokes);
pushInk();
if (!before) refreshInkMarks();
} });
penHeartbeat = setInterval(() => {
if (inkHere()) document.documentElement.dataset.twLiveInkTick = String(Date.now());
}, 10000);
window.addEventListener('resize', () => { const pop = document.getElementById('presenterPenPop'); if (pop) placePenPop(pop); });
// Closing (or reloading) the presenter ends the talk's drawings on the projector too.
window.addEventListener('pagehide', () => {
clearInterval(penHeartbeat);
const view = penView(false);
if (view && isPaired) sendToPeer({ type: commandType, command: 'ink', ink: { ...view, strokes: [], draft: null } });
penStore?.clearAll();
penGesture?.destroy();
}, { once: true });
}
let highlightArmed = false;
function setHighlightArmed(on) {
if (!isPresenter) return;
if (on && pointerArmed) setPointerArmed(false);
if (on && penArmed) setPenArmed(false);
highlightArmed = Boolean(on);
els.presenterRoot?.classList.toggle("highlight-armed", highlightArmed);
renderModeControls();
}
// The modes' steady indicators (ADR-0031 §4, presenter redesign ticket 05): Focus and Highlight
// show pressed in the bottom bar, Reveal shows checked in More, and while Reveal, Focus or
// Highlight is on a chip in the status bar names it, with × to leave (the function Esc runs)
// and, for Highlight, Clear. A mode counts as on while it is armed, also on a slide where it is
// dormant ({nostep}). The chip names come from the generated block (MODE_CHIP), which is
// defined further down; modeChipReady holds rendering until the chips are dressed.
let modeChipReady = false;
function armedMode() {
const kind = state.mode?.kind || state.mode?.sticky || null;
return kind === "reveal" || kind === "focus" ? kind : null;
}
function slideHasHighlights() {
return currentHighlight.slideId === (currentSlide()?.dataset.id || null) && currentHighlight.ranges.length > 0;
}
function renderModeControls() {
if (!isPresenter || !modeChipReady) return;
const mode = armedMode();
els.presenterFocus?.setAttribute("aria-pressed", String(mode === "focus"));
els.presenterHighlight?.setAttribute("aria-pressed", String(highlightArmed));
els.presenterReveal?.setAttribute("aria-checked", String(mode === "reveal"));
const chip = els.presenterModeChip;
if (chip) {
chip.hidden = !mode;
chip.dataset.mode = mode || "";
if (mode && chip.dataset.shown !== mode) {
const names = MODE_CHIP[mode];
chip.dataset.shown = mode;
els.presenterModeMark.replaceChildren(...[twIconEl(names.icon)].filter(Boolean));
els.presenterModeWord.textContent = names.word;
els.presenterModeExit.dataset.tip = names.exit;
els.presenterModeExit.setAttribute("aria-label", names.exit);
}
}
if (els.presenterHighlightChip) els.presenterHighlightChip.hidden = !highlightArmed;
if (els.presenterHighlightChipClear) els.presenterHighlightChipClear.disabled = !slideHasHighlights();
}
function toggleHighlightArmed() { setHighlightArmed(!highlightArmed); }
// Read a selection made inside the Current preview iframe and broadcast it. The iframe is
// same-origin (srcdoc), so its document/selection are accessible. The clone inside it carries
// the same slide markup, so offsets transfer verbatim to the audience.
function captureHighlightFromPreview() {
if (!isPresenter) return;
const iframe = els.currentPreview?.querySelector("iframe");
const doc = iframe?.contentDocument;
const sel = iframe?.contentWindow?.getSelection?.();
if (!doc || !sel || sel.rangeCount === 0 || sel.isCollapsed) return;
const slideClone = doc.querySelector(".slide");
if (!slideClone) return;
const range = serializeSelectionWithin(slideClone, sel.getRangeAt(0));
if (!range) return;
const slideId = currentSlide()?.dataset.id || null;
// Accumulate ranges for the current slide (multiple highlights allowed); replace if same slide.
if (currentHighlight.slideId !== slideId) currentHighlight = { slideId, ranges: [] };
currentHighlight.ranges = [...currentHighlight.ranges, range];
sel.removeAllRanges();
reapplyHighlightToLive(); // re-bake marks into the presenter preview
broadcastHighlight(); // push to the audience
updateHighlightClearBtn();
}
function clearCurrentSlideHighlights() {
const slideId = currentSlide()?.dataset.id || null;
currentHighlight = { slideId, ranges: [] };
reapplyHighlightToLive();
broadcastHighlight();
updateHighlightClearBtn();
}
function updateHighlightClearBtn() {
// Clear highlights sits in More (ticket 05): it shows disabled while there is nothing to clear.
if (els.presenterHighlightClear) els.presenterHighlightClear.disabled = !slideHasHighlights();
renderModeControls();
}
function publish(patch) {
const nextState = { ...state, ...patch, seq: (Number(state.seq) || 0) + 1, updatedAt: Date.now() };
if (isPaired) {
localStorage.setItem(storageKey, JSON.stringify(nextState));
sendToPeer({ type: messageType, state: nextState });
}
applyState(nextState);
}
function goTo(index, reveal = 0) {
// Slide-addressed navigation (hash, overview jumps, Home/End, skip, resume, replay)
// resolves to the slide's FIRST beat; arrival rules live in goToBeat. The reveal
// pass-through exists for the replay path's fragment restore only.
goToBeat(firstBeatForSlideIndex(index), { reveal });
}
function applyReplayState(message) {
try {
if (!isReplay || !message || message.type !== "tw-replay-state") return;
const slideId = String(message.slideId || "");
if (!slideId) return;
const index = slides.findIndex((slide) => slide.dataset.id === slideId);
if (index < 0) return;
const slide = slides[index];
const hiddenCount = Math.max(0, Number(message.hiddenCount) || 0);
const reveal = Math.max(0, fragments(slide).length - hiddenCount);
goTo(index, reveal);
const live = currentSlide();
if (!live) return;
const ranges = Array.isArray(message.highlights) ? message.highlights : [];
currentHighlight = { slideId, ranges };
applyHighlightPayload(live, { slideId, ranges });
// Ticket 08: the Pen's strokes on this slide at this moment of the recording (checked first).
showReplayInk(message.ink, slideId, message.inkSpace === "image" ? message.inkImage : null);
} catch {
// Replay is driven by an external monitor. Bad messages must never break the presentation.
}
}
// next/previous are the ONE stepping grammar (stepForward/stepBackward): intra-beat steps
// (reveal/focus units + block-carousel cards) are consumed first, then the beat index moves.
// ← is press-for-press symmetric with → — crossing backwards arrives at the previous beat's
// FULL state (goToBeat atEnd), never at step 0 of an authored-mode slide.
function next() {
stepForward();
}
function previous() {
stepBackward();
}
// The ONE advance/retreat entry point shared by the keyboard AND every "Next"/"Previous"
// button (standalone control bar + presenter control bar) — a single grammar whether or not
// a mode is on (the same advanceTarget/retreatTarget accounting the tests pin down), so the
// advance action and the Next pane stay in lockstep regardless of how the presenter
// triggers it.
function advance(delta) {
stepMode(delta);
}
// H2 — readable section/subsection labels for the overview. A section-title slide
// (data-role) carries the section's display title in its nav-title; likewise a
// subsection-title slide. Build id → title maps once so group headers read as words, not
// slugs, and so subsections nest under their parent section as indented sub-headers.
const sectionTitleById = new Map();
const subsectionTitleById = new Map();
slides.forEach((slide) => {
const role = slide.dataset.role;
if (role === "section-title" && slide.dataset.section) {
sectionTitleById.set(slide.dataset.section, slide.dataset.navLabel || slide.dataset.navTitle || slide.dataset.section);
} else if (role === "subsection-title" && slide.dataset.subsection) {
subsectionTitleById.set(slide.dataset.subsection, slide.dataset.navLabel || slide.dataset.navTitle || slide.dataset.subsection);
}
});
// The shared overview runtime (rankSlides / deriveSlideStatus / createOverview) is injected here
// at build time in place of the placeholder line below — SINGLE SOURCE OF TRUTH with the handout.
// The placeholder MUST live on its OWN line (no other line may carry the token), or a non-global
// .replace() would inject it into a // comment (dead code).
// Shared overview runtime. Inlined verbatim (no export) into the presenter template AND the handout
// (buildShareHtml) — see 01-cli-utils.overviewRuntimeSource. Pure helpers (rankSlides,
// deriveSlideStatus) are also loaded by scripts/test-overview.mjs. createOverview (Task 5) touches
// `document` only inside its body, so the test's `new Function(...)` load parses but never executes
// it — no DOM required at load.
// Rank slides for search. Titles first: prefix (4) > substring (3) > section/subsection (2) >
// body (1) > notes (0.5). Empty query -> all indices in original order.
function rankSlides(query, slideData) {
const q = (query || "").trim().toLowerCase();
if (!q) return slideData.map((s) => s.index);
const scored = [];
for (const s of slideData) {
const title = (s.title || "").toLowerCase();
let score = 0;
if (title.startsWith(q)) score = 4;
else if (title.includes(q)) score = 3;
for (const sub of Array.isArray(s.subs) ? s.subs : []) {
const subTitle = (sub.title || "").toLowerCase();
if (subTitle.startsWith(q)) score = Math.max(score, 4);
else if (subTitle.includes(q)) score = Math.max(score, 3);
}
if (score < 2 && ((s.section || "").toLowerCase().includes(q) || (s.subsection || "").toLowerCase().includes(q))) score = 2;
if (score < 1 && (s.body || "").toLowerCase().includes(q)) score = 1;
if (score < 0.5 && (s.notes || "").toLowerCase().includes(q)) score = 0.5;
if (score > 0) scored.push({ index: s.index, score });
}
scored.sort((a, b) => b.score - a.score || a.index - b.index);
return scored.map((x) => x.index);
}
function preferredOverviewRow(query, slideData, rankedParents) {
const q = (query || "").trim().toLowerCase();
const parent = rankedParents.length ? { index: rankedParents[0] } : null;
if (!q) return parent;
const childMatches = [];
for (const index of rankedParents) {
const slide = slideData[index];
for (const child of Array.isArray(slide?.subs) ? slide.subs : []) {
if ((child.title || "").toLowerCase().includes(q)) {
childMatches.push({ index, subIndex: Number(child.subIndex) || 0 });
}
}
}
return childMatches.length === 1 ? childMatches[0] : parent;
}
function clampOverviewHighlight(highlight, rowCount) {
if (rowCount <= 0) return 0;
return Math.max(0, Math.min(rowCount - 1, Number(highlight) || 0));
}
// Shown/skipped derivation (presenter only). shown/skippedExplicit are Sets of slide index;
// maxShown is the highest shown index. A gap before maxShown reads as "skipped (jumped)".
function deriveSlideStatus(index, ctx) {
if (ctx.shown.has(index)) return { status: "shown" };
if (ctx.skippedExplicit.has(index)) return { status: "skipped", reason: "explicit" };
if (index < ctx.maxShown) return { status: "skipped", reason: "jumped" };
return { status: "unseen" };
}
// Single overview UI used by BOTH the presenter drawer and the handout. Collapsed = grouped,
// clickable, searchable list; expanded = scaled-thumbnail grid. Keyboard: type to filter, Up/Down
// move a highlight, Enter jumps to the highlight (or the top-ranked result) and closes, Esc closes.
// Shown/skipped markers render only when host.isPresenter and host.getStatus returns a status.
// host.statusIcon(status), when given, draws a marker (the presenter's lucide icons, ticket 08);
// without it, or when it returns nothing, the marker is the text glyph.
function createOverview(host) {
let expanded = false;
let highlight = 0; // index into the current visible order
let renderedCurrentIndex = null;
let visibleOrder = []; // { index, subIndex? } rows currently shown, in display order
const statusGlyph = { shown: "●", skipped: "⊘", unseen: "○" };
function build(filter, preferQueryTarget = false, followCurrent = false) {
if (host.beforeBuild) host.beforeBuild();
const list = host.listEl;
list.replaceChildren();
list.classList.toggle("tw-overview-grid", expanded);
const skippedOnly = host.isPresenter && Boolean(host.skippedOnlyEl?.checked);
const rankedParents = rankSlides(filter || "", host.slideData)
.filter((index) => !skippedOnly || host.getStatus(index)?.status === "skipped");
visibleOrder = [];
const bySection = filter && filter.trim(); // when searching, skip section grouping (flat ranked list)
const cur = host.getCurrentIndex();
renderedCurrentIndex = cur;
let curSection = null, curSub = null;
rankedParents.forEach((index) => {
const s = host.slideData[index];
if (!bySection) {
if (s.section !== curSection) {
curSection = s.section; curSub = null;
const head = document.createElement("button");
head.type = "button"; head.className = "section-head";
head.textContent = host.sectionTitleById.get(curSection) || `Section ${curSection || ""}`.trim();
head.addEventListener("click", () => jump(index));
list.appendChild(head);
}
if ((s.subsection || "") !== curSub) {
curSub = s.subsection || "";
if (curSub) {
const sub = document.createElement("button");
sub.type = "button"; sub.className = "subsection-head";
sub.textContent = host.subsectionTitleById.get(curSub) || curSub;
sub.addEventListener("click", () => jump(index));
list.appendChild(sub);
}
}
}
const btn = document.createElement("button");
const pos = visibleOrder.length;
visibleOrder.push({ index });
btn.type = "button";
btn.className = "slide-link";
btn.dataset.pos = String(pos);
if (index === cur) btn.classList.add("current");
const status = host.isPresenter ? host.getStatus(index) : null;
if (status) { btn.classList.add(`tw-${status.status}`); if (status.reason) btn.title = `skipped (${status.reason})`; }
const title = `${index + 1}. ${s.title || "(untitled)"}`;
if (expanded) {
const thumb = document.createElement("div");
thumb.className = "tw-thumb";
// A slide is position:absolute;inset:0;display:none until .active. Render the clone inside a
// fixed deck-sized inner (the clone fills it via inset:0), force it visible+active, then
// scale the inner down to the column width (see scaleThumbs). Iframes/videos would reload
// per thumbnail (cost + network) — swap them for a light placeholder.
const inner = document.createElement("div");
inner.className = "tw-thumb-inner";
const clone = s.el.cloneNode(true);
clone.classList.add("active");
clone.removeAttribute("aria-hidden");
clone.querySelectorAll("audio").forEach((m) => m.remove());
clone.querySelectorAll("iframe, video").forEach((m) => {
const ph = document.createElement("div");
ph.className = "tw-thumb-embed";
m.replaceWith(ph);
});
inner.appendChild(clone);
thumb.appendChild(inner);
btn.appendChild(thumb);
}
const label = document.createElement("span");
label.className = "slide-link-title";
if (status) {
const markerEl = document.createElement("span");
markerEl.className = "tw-status";
markerEl.setAttribute("aria-hidden", "true");
const icon = host.statusIcon ? host.statusIcon(status.status) : null;
if (icon) markerEl.appendChild(icon);
else markerEl.textContent = statusGlyph[status.status];
label.appendChild(markerEl);
}
const titleEl = document.createElement("span");
titleEl.textContent = title;
label.appendChild(titleEl);
// The handout draws one small mark per kind a person kept on this slide (host.slideMarks(index) → a node or null).
const marks = host.slideMarks ? host.slideMarks(index) : null;
if (marks) label.appendChild(marks);
btn.appendChild(label);
btn.addEventListener("click", () => jump(index));
list.appendChild(btn);
// Expanded thumbnails stay parent-only: sub-slides are navigation rows, not duplicate
// thumbnail canvases of the same compiled parent slide.
if (!expanded) {
for (const child of Array.isArray(s.subs) ? s.subs : []) {
const childPos = visibleOrder.length;
const subIndex = Number(child.subIndex) || 0;
visibleOrder.push({ index, subIndex });
const childBtn = document.createElement("button");
childBtn.type = "button";
childBtn.className = "slide-link slide-sublink";
childBtn.dataset.pos = String(childPos);
const childLabel = document.createElement("span");
childLabel.className = "slide-link-title";
childLabel.textContent = `${index + 1}.${subIndex + 1} ${child.title || "(untitled)"}`;
childBtn.appendChild(childLabel);
childBtn.addEventListener("click", () => jump(index, subIndex));
list.appendChild(childBtn);
}
}
});
if (host.isPresenter && followCurrent && !bySection && !skippedOnly) {
const currentPos = visibleOrder.findIndex((row) => row.index === cur && row.subIndex === undefined);
highlight = currentPos >= 0 ? currentPos : 0;
} else if (preferQueryTarget) {
const preferred = preferredOverviewRow(filter, host.slideData, rankedParents);
const preferredPos = preferred ? visibleOrder.findIndex((row) => row.index === preferred.index
&& row.subIndex === preferred.subIndex) : -1;
highlight = preferredPos >= 0 ? preferredPos : 0;
}
highlight = clampOverviewHighlight(highlight, visibleOrder.length);
list.querySelectorAll(".slide-link[data-pos]").forEach((row) => {
row.classList.toggle("tw-highlight", Number(row.dataset.pos) === highlight);
});
if (skippedOnly && !visibleOrder.length) {
const empty = document.createElement("p");
empty.className = "tw-overview-empty";
empty.setAttribute("role", "status");
empty.textContent = bySection ? "No skipped slides match your search" : "No skipped slides";
list.appendChild(empty);
}
if (host.isPresenter && followCurrent && !bySection && !skippedOnly) revealHighlight();
// Scale each thumbnail's fixed 1280x720 inner down to its (responsive) column width — done after
// layout so clientWidth is real (the drawer is open by the time rAF fires).
if (expanded && typeof requestAnimationFrame === "function") {
requestAnimationFrame(() => {
list.querySelectorAll(".tw-thumb-inner").forEach((inner) => {
const w = inner.parentElement && inner.parentElement.clientWidth;
if (w) inner.style.transform = "scale(" + (w / 1280) + ")";
});
});
}
}
// Wait for the open drawer and thumbnail layout; scroll only its selected row, without
// moving keyboard focus away from search. Same-slide refreshes must not undo browsing.
function revealHighlight() {
requestAnimationFrame(() => {
if (isOpen()) host.listEl.querySelector(".tw-highlight")?.scrollIntoView({ block: "nearest", inline: "nearest" });
});
}
function jump(index, subIndex) { host.onJump(index, subIndex); close(); }
// Closing must RELEASE focus back to the deck. The drawer hides via a CSS transform (not
// display:none), so a focused search input / slide-link button inside it keeps focus — and the
// deck's key handler bails on `event.target instanceof HTMLInputElement`, so every nav key would
// be swallowed after an Enter/click jump. Blur whatever is focused inside the drawer on close.
function releaseFocus() {
const active = document.activeElement;
if (active && host.drawerEl && host.drawerEl.contains(active) && typeof active.blur === "function") active.blur();
}
function moveHighlight(delta) {
if (!visibleOrder.length) return;
highlight = (highlight + delta + visibleOrder.length) % visibleOrder.length;
build(host.searchEl ? host.searchEl.value : "");
host.listEl.querySelector(".tw-highlight")?.scrollIntoView({ block: "nearest" });
}
function onKey(e) {
if (e.key === "ArrowDown") { e.preventDefault(); moveHighlight(1); }
else if (e.key === "ArrowUp") { e.preventDefault(); moveHighlight(-1); }
else if (e.key === "Enter") {
e.preventDefault();
const target = visibleOrder[highlight] || visibleOrder[0];
if (target) jump(target.index, target.subIndex);
}
else if (e.key === "Escape") { e.preventDefault(); close(); }
}
function toggleExpand() { expanded = !expanded; build(host.searchEl ? host.searchEl.value : ""); revealHighlight(); }
function open() {
highlight = 0;
host.drawerEl.classList.add("open");
build(host.searchEl ? host.searchEl.value : "", false, true);
host.searchEl?.focus({ preventScroll: true });
}
function close() { releaseFocus(); host.drawerEl.classList.remove("open"); }
function isOpen() { return host.drawerEl.classList.contains("open"); }
function toggle() { isOpen() ? close() : open(); }
// Filtering changes the navigation order, so begin at the first matching result. Returning
// to the full outline resumes following; a skipped-only list normally excludes the current slide.
host.skippedOnlyEl?.addEventListener("change", () => {
highlight = 0;
build(host.searchEl ? host.searchEl.value : "", true, !host.skippedOnlyEl.checked);
revealHighlight();
});
host.searchEl?.addEventListener("input", () => { build(host.searchEl.value, true, !host.searchEl.value.trim()); });
host.searchEl?.addEventListener("keydown", onKey);
// Esc closes the drawer from whichever control inside it has focus, and that Esc is spent: it must
// not also reach the deck's key handler (which would end a page full screen in the same press).
host.drawerEl?.addEventListener("keydown", (e) => { if (e.key === "Escape" && isOpen()) { close(); e.stopPropagation(); } });
// render() with no argument re-reads the live search value — so callers on slide change need not
// know which drawer (standalone/presenter) is mounted.
return { render: (f) => build(f !== undefined ? f : (host.searchEl ? host.searchEl.value : ""), false, host.getCurrentIndex() !== renderedCurrentIndex), open, close, toggle, isOpen, toggleExpand };
}
const overviewSlideData = slides.map((el, index) => ({
index,
title: el.dataset.navLabel || el.dataset.navTitle || el.querySelector("h1,h2")?.textContent || "",
section: el.dataset.section || "",
subsection: el.dataset.subsection || "",
body: el.textContent || "",
notes: el.querySelector("aside.notes")?.textContent || "",
subs: Array.from(el.querySelectorAll(".carousel-subslide")).map((c) => ({ title: c.dataset.subTitle || "", subIndex: Number(c.dataset.subIndex) || 0, body: c.textContent || "" })),
el,
}));
// ONE overview instance per window. In presenter mode it mounts on the presenter's own
// (already presenter-styled, dark) drawer so we retire the bespoke presenter outline renderer
// without un-hiding the standalone .drawer (which is CSS-hidden in presenter mode). The
// standalone/handout drawer is used otherwise.
const overview = createOverview({
slideData: overviewSlideData,
listEl: isPresenter ? els.presenterOutline : els.overviewList,
searchEl: isPresenter ? els.presenterSearch : els.overviewSearch,
skippedOnlyEl: isPresenter ? document.getElementById("presenterSkippedOnly") : null,
drawerEl: isPresenter ? els.presenterOutlineDrawer : els.overviewDrawer,
isPresenter,
getCurrentIndex: () => state.index,
getStatus: (i) => slideStatus(i), // defined in Phase C; until then returns null
// The presenter's marks are lucide icons (OUTLINE_STATUS_ICONS, generated); the generated
// block runs later in this script, so an early call falls back to the overview's glyph.
statusIcon: isPresenter ? (status) => { try { return twIconEl(OUTLINE_STATUS_ICONS[status]); } catch { return null; } } : undefined,
onJump: (i, subIndex) => jumpTo(i, subIndex),
// A slide carrying a drawing (ticket 08) shows the pen mark in the outline.
slideMarks: isPresenter ? (i) => (penReady && penStore?.slideHas(overviewSlideData[i]?.el?.dataset.id) ? inkMarkNode() : null) : undefined,
sectionTitleById, subsectionTitleById,
});
els.overviewExpand?.addEventListener("click", () => overview.toggleExpand());
els.presenterOutlineExpand?.addEventListener("click", () => overview.toggleExpand());
document.getElementById("presenterOutlineClose")?.addEventListener("click", () => overview.close());
function openPresenter() {
const targetSessionId = createSessionId();
const initialState = { ...state, seq: 0, updatedAt: Date.now() };
localStorage.setItem(storageKeyFor(targetSessionId), JSON.stringify(initialState));
const presenterUrl = new URL(location.href);
presenterUrl.searchParams.set("presenter", "1");
presenterUrl.searchParams.delete("audience");
presenterUrl.searchParams.set("session", targetSessionId);
presenterUrl.hash = hashIdForBeat(beats[clampBeat(state.beat)], currentSlide().dataset.id || "");
window.open(presenterUrl.toString(), `html-presenter-${targetSessionId}`, "popup=yes,width=1200,height=800,left=60,top=60");
}
// Chromeless audience (2026-06-10): pages cannot create app-mode windows, so the LOCAL
// SERVER launches one (Chrome --app, no address bar). Pairing rides BroadcastChannel/
// localStorage (no window ref needed). On file:// there is no server — fall back to the
// regular popup.
function openAudienceChromeless() {
if (!isPaired) return;
if (location.protocol === "file:") { openAudience(); return; }
// sendBeacon, deliberately not the fetch API: the portable full HTML must carry no runtime
// network calls of that kind (audit-enforced); a fire-and-forget beacon is all this needs.
const params = new URLSearchParams({ session: sessionId, slide: currentSlide().dataset.id || "" });
const queued = navigator.sendBeacon(`/launch-audience?${params.toString()}`);
if (!queued) { openAudience(); return; }
sendToPeer({ type: messageType, state });
if (currentHighlight.ranges.length) setTimeout(broadcastHighlight, 1200);
}
function openAudience() {
if (!isPaired) return;
const url = new URL(location.href);
url.searchParams.set("audience", "1");
url.searchParams.delete("presenter");
url.searchParams.set("session", sessionId);
url.hash = hashIdForBeat(beats[clampBeat(state.beat)], currentSlide().dataset.id || "");
peerWindow = window.open(url.toString(), `html-audience-${sessionId}`, "popup=yes,width=1280,height=800,left=80,top=80");
sendToPeer({ type: messageType, state });
// F1: replay any active highlight to the freshly opened audience window once it has loaded.
if (currentHighlight.ranges.length) setTimeout(broadcastHighlight, 400);
}
function syncFromHash() {
const id = location.hash.replace("#", "");
if (!id) return;
const beatIndex = beatIndexForHash(id, beats);
if (beatIndex >= 0) {
state.beat = beatIndex;
state.index = slideIndexForBeat(beatIndex);
state.reveal = revealForRuntimeBeat(beats[beatIndex], 0);
return;
}
const index = slides.findIndex((slide) => slide.dataset.id === id);
// Deep links (#id) resolve to the node's FIRST beat (a grid section opens on its grid beat).
if (index >= 0) { state.index = index; state.beat = firstBeatForSlideIndex(index); }
}
function restoreStoredState() {
if (!isPaired) return false;
const stored = localStorage.getItem(storageKey);
if (!stored) return false;
try {
applyState(JSON.parse(stored));
return true;
} catch {
return false;
}
}
function updateFullscreenState() {
document.body.classList.toggle("fullscreen-active", Boolean(document.fullscreenElement));
}
function requestAudienceFullscreen() {
document.documentElement.requestFullscreen?.();
}
// The card a number key (1-9) jumps to on a grid slide (ADR-0007), or null off a grid slide or
// past its last card. More's "Card on a grid slide" item goes to card 1 through the same lookup.
function gridCardTarget(n) {
const gb = beats[clampBeat(state.beat)];
if (!gb || (gb.kind !== "grid" && gb.kind !== "grid-return")) return null;
const target = childIdsForSection("grid", gb.slideId)[n - 1];
return target && slideIndexById.has(target) ? target : null;
}
// The element that got the focus from the keyboard (Tab), or null. Read when the focus arrives:
// at that moment :focus-visible tells a Tab from a click; by the time a key is pressed on a
// clicked button the browser reports it as focus-visible too.
let keyboardFocusedControl = null;
document.addEventListener("focusin", (event) => {
keyboardFocusedControl = event.target instanceof Element && event.target.matches(":focus-visible") ? event.target : null;
}, true);
// A pointer press anywhere in the deck (also on the control that has the focus: clicking it
// raises no new focusin) and Escape end that: from then on Enter and Space step the talk again.
window.addEventListener("pointerdown", (event) => { if (event.isTrusted) keyboardFocusedControl = null; }, true);
window.addEventListener("keydown", (event) => { if (event.isTrusted && event.key === "Escape") keyboardFocusedControl = null; }, true);
// Enter or Space on such a control: the control's own activation, not a deck key (so it is no
// entry of the shortcut registry: the deck binds nothing here, it stands aside).
function isActivationOfKeyboardFocusedControl(event) {
const activates = ["Enter", " ", "Spacebar"].includes(event.key) || event.code === "Space";
return activates && !event.metaKey && !event.ctrlKey && !event.altKey
&& event.target === keyboardFocusedControl && event.target.matches('button, a[href], [role="button"], summary');
}
function handleKey(event) {
if (isReplay) { event.preventDefault(); return; }
if (isPresenter && event.metaKey && event.shiftKey && !event.altKey && event.key.toLowerCase() === 'p') { event.preventDefault(); togglePresenterCommands(); return; }
if (isPresenter && !commandPalette.hidden) { paletteKey(event); return; }
if (isPresenter && event.key === "Escape" && notesMenuOpen()) { event.preventDefault(); toggleNotesMenu(false); return; }
if (isPresenter && event.key === "Escape" && questionsTray.open && instantCompose.hidden && instantPaste.hidden && !(els.presenterQuickPollCompose && !els.presenterQuickPollCompose.hidden)) { event.preventDefault(); event.stopPropagation(); openQuestionsTray(false); return; }
if (isPresenter && event.metaKey && event.altKey && !event.shiftKey && event.key.toLowerCase() === 'i') { event.preventDefault(); openInstantCompose(); return; }
if (isPresenter && (!instantCompose.hidden || !instantPaste.hidden)) {
if (event.key === 'Escape') { event.preventDefault(); closeInstantPanels(); return; }
if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); showInstantDraft(); return; }
}
if (isPresenter && instantActive && event.key === 'ArrowRight') { event.preventDefault(); clearInstant(); return; }
if (isPresenter && event.key === "Escape" && els.presenterQuickPollCompose && !els.presenterQuickPollCompose.hidden) {
event.preventDefault(); event.stopPropagation(); toggleQuickPollCompose(false); return;
}
// ↵ opens the Quick poll, as its Open poll button shows (a button keeps its own ↵).
if (isPresenter && event.key === "Enter" && !event.shiftKey && els.presenterQuickPollCompose && !els.presenterQuickPollCompose.hidden && !(event.target instanceof HTMLButtonElement)) {
event.preventDefault(); event.stopPropagation(); openQuickPoll(); return;
}
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement || event.target instanceof HTMLSelectElement) return;
// A control of the deck's own chrome that the person reached with the KEYBOARD (Tab) keeps
// Enter and Space: they activate it and are not navigation. That is how a keyboard user gets
// into a page (the Current pane's cover, the Interact chip). A control that only has the focus
// because it was clicked is not one (keyboardFocusedControl), so after a click on a bar button
// the same keys (a clicker sends them) do what they did before.
if (isActivationOfKeyboardFocusedControl(event)) return;
if (isPresenter && event.key === "F5") { event.preventDefault(); openAudienceChromeless(); return; }
if (isPresenter && event.key === "?") { event.preventDefault(); toggleShortcuts(); return; }
if (isPresenter && event.key === "Escape" && els.twShortcuts && !els.twShortcuts.hidden) { event.preventDefault(); toggleShortcuts(false); return; }
if (isPresenter && event.key === 'Escape' && pointerArmed) { event.preventDefault(); setPointerArmed(false); return; }
if (isPresenter && event.key.toLowerCase() === 'i' && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey) { event.preventDefault(); togglePointer(); return; }
// The Pen (ticket 08): Esc abandons a drag in progress, else turns the pen off; D, W / ⇧W, X / ⇧X;
// ⌘Z undoes the last stroke while the pen is on (the board panel, while it shows, keeps ⌘Z).
if (isPresenter && event.key === 'Escape' && penArmed) { event.preventDefault(); if (!penGesture?.cancel()) setPenArmed(false); return; }
if (isPresenter && event.key.toLowerCase() === 'd' && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey) { event.preventDefault(); togglePen(); return; }
if (isPresenter && penArmed && event.key.toLowerCase() === 'w' && !event.metaKey && !event.ctrlKey && !event.altKey) { event.preventDefault(); stepPenTool(event.shiftKey ? -1 : 1); return; }
if (isPresenter && event.key.toLowerCase() === 'x' && !event.metaKey && !event.ctrlKey && !event.altKey) { event.preventDefault(); if (event.shiftKey) clearAllInk(); else clearInkHere(); return; }
if (isPresenter && penArmed && (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'z') { event.preventDefault(); undoInk(); return; }
const key = event.key;
const code = event.code;
// A focused simulation disclosure (.sim-toggle) keeps Enter and Space: the button's own click
// opens or closes its part; the deck neither steps nor advances (spec invariant 4). Audience and
// plain deck windows only: the presenter's own deck is hidden, so no toggle there takes focus.
if (!isPresenter && (key === "Enter" || key === " " || code === "Space") && event.target?.closest?.(".sim-toggle:not(.sim-static *)")) return;
if (isPresenter && (key === "k" || key === "K") && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey) {
event.preventDefault(); toggleQuickPollCompose(); return;
}
// A opens (or closes) the questions tray while a session is up (registry: presenter.questions).
if (isPresenter && (key === "a" || key === "A") && !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey && !event.repeat) {
if (questionsTrayAvailable() || questionsTray.open) { event.preventDefault(); openQuestionsTray(!questionsTray.open); }
return;
}
if (isPresenter && (key === "q" || key === "Q") && !event.metaKey && !event.ctrlKey && !event.altKey) {
event.preventDefault();
if (event.shiftKey) presenterPollRevealAction();
else presenterPollPrimaryAction();
return;
}
// C pins / unpins the control bar (ADR-0005 chrome policy), in the audience and plain deck
// windows. Not in the presenter: presenter mode hides that bar, so C does nothing there and is
// not listed (presenter redesign ticket 07).
if (!isPresenter && (key === "c" || key === "C") && !event.metaKey && !event.ctrlKey && !event.altKey) {
event.preventDefault();
const pinned = document.body.classList.toggle("chrome-pinned");
if (pinned) document.body.classList.remove("chrome-idle");
else armChromeIdle();
return;
}
const nextKeys = new Set(["ArrowRight", "ArrowDown", " ", "Spacebar", "PageDown", "Enter", "MediaTrackNext"]);
const nextCodes = new Set(["ArrowRight", "ArrowDown", "Space", "PageDown", "Enter", "NumpadEnter", "MediaTrackNext"]);
const previousKeys = new Set(["ArrowLeft", "ArrowUp", "PageUp", "Backspace", "MediaTrackPrevious"]);
const previousCodes = new Set(["ArrowLeft", "ArrowUp", "PageUp", "Backspace", "MediaTrackPrevious"]);
const isNextKey = nextKeys.has(key) || nextCodes.has(code);
const isPreviousKey = previousKeys.has(key) || previousCodes.has(code);
// Ticket 04: while the talk's QR overlay is up, Esc (any window) or U (presenter) returns to
// the slide it left; slide navigation is swallowed so the return lands on that same slide.
if (state.talkQr?.open) {
if (key === "Escape" || (isPresenter && isTalkQrKey(event))) { event.preventDefault(); closeTalkQr(); return; }
if (isNextKey || isPreviousKey || key === "Home" || key === "End") { event.preventDefault(); return; }
}
if (isPresenter && isTalkQrKey(event)) { event.preventDefault(); toggleTalkQr(); return; }
// While the full-screen QR overlay is open (refinement 6), the deck is suspended — Esc / Enter /
// Space close it and every other key is swallowed so nav does not fire behind it.
if (qrFsEl) {
if (key === "Escape" || key === "Enter" || key === " " || code === "Space") { event.preventDefault(); closeQrFullscreen(); }
return;
}
// When a corner QR button has focus, Enter / Space expand it full-screen instead of advancing
// the deck (the button's activation key must not double as "next slide").
if (!isPresenter && (key === "Enter" || key === " " || code === "Space")) {
const qrBtn = event.target && event.target.closest && event.target.closest(".slide-qr .qr-code");
if (qrBtn) { event.preventDefault(); openQrFullscreen(qrBtn); return; }
}
// While a lightbox is OPEN on this window, the deck is suspended — arrows browse images,
// Esc / z close. Every window (presenter, audience, standalone) renders the overlay and
// publishes the index/close, so the pair stays in lockstep.
if (lightboxActiveHere()) {
// On a slide with an image sequence the arrows are Next / Back of that sequence (still
// images only, then the slide again); elsewhere they browse every zoomable, as before.
const inSequence = imageStops().length > 0;
if (isNextKey) { event.preventDefault(); if (inSequence) stepForward(); else stepLightbox(1); return; }
if (isPreviousKey) { event.preventDefault(); if (inSequence) stepBackward(); else stepLightbox(-1); return; }
if (key === "Escape" || key === "z" || key === "Z") { event.preventDefault(); closeLightbox(); return; }
// Ticket 24: V asks for element full screen on the enlarged video (or jumps to the slide's video).
if ((key === "v" || key === "V") && slideVideos().length > 0) { event.preventDefault(); videoFullscreenCommand(); return; }
if (key === "Home") { event.preventDefault(); publish({ lightbox: { open: true, index: 0 } }); return; }
if (key === "End") { event.preventDefault(); publish({ lightbox: { open: true, index: slideImages().length - 1 } }); return; }
return; // swallow everything else while the gallery is open
}
// B3 embed interaction (all roles). Esc exits an active interaction first (most local action).
// `e` toggles interaction with the current slide's covered embed. A focused cross-origin embed
// can't deliver keys here, so `e` only toggles ON from the deck; the Return button / Esc /
// click-background handle exit once the embed has focus.
// Esc with the page full screen and NOT in use puts the slide back; a page in use takes Esc
// first (it ends the engagement), so a second Esc is the one that restores the slide.
// The presenter's open outline drawer takes Esc before this (its dismissal sits further down).
if (key === "Escape" && embedFullScreenOn() && !embedInUse() && !(isPresenter && overview.isOpen())) { event.preventDefault(); publish({ embedFullScreen: null }); return; }
if (key === "Escape" && interactingFrame) { event.preventDefault(); exitEmbedInteract(); return; }
if ((key === "e" || key === "E") && !event.metaKey && !event.ctrlKey && !event.altKey && event.isTrusted) {
event.preventDefault(); toggleEmbedInteract(); return;
}
// Card Table (ADR-0007): number keys 1-9 while on a grid beat jump straight to that child.
// All roles (goToBeat publishes to the shared state so a paired audience stays in lockstep).
if (/^[1-9]$/.test(key) && !event.metaKey && !event.ctrlKey && !event.altKey) {
const target = gridCardTarget(Number(key));
if (target) { event.preventDefault(); goToContainerChild(target); return; }
}
// AUDIENCE mirrors modes via shared state — f stays FULLSCREEN here and there are no mode
// toggles (the presenter/standalone owns R/F). But when a mode IS on, the audience's arrows
// must drive the SAME stepping grammar (it publishes to the shared state the presenter reads)
// rather than blindly advancing the slide, so a stray audience keypress can't desync.
if (isAudience) {
if (state.mode?.kind && (isNextKey || isPreviousKey)) { event.preventDefault(); stepMode(isNextKey ? 1 : -1); return; }
if (isNextKey) { event.preventDefault(); next(); }
else if (isPreviousKey) { event.preventDefault(); previous(); }
else if (key === "Home") { event.preventDefault(); goTo(0, 0); }
else if (key === "End") { event.preventDefault(); goTo(total - 1, 0); }
else if (key === "f" || key === "F") { event.preventDefault(); requestAudienceFullscreen(); }
else if (key === "z" || key === "Z") { if (slideImages().length > 0) { event.preventDefault(); openLightbox(0); }
else if (panePageSource()) { event.preventDefault(); toggleEmbedFullScreen(); } }
else if (key === "v" || key === "V") { if (slideVideos().length > 0) { event.preventDefault(); videoFullscreenCommand(); } }
return;
}
// R / F toggle the optional stepping modes (standalone + presenter). Mutually exclusive:
// pressing the active mode's key turns it off; the other key switches to it. These work
// regardless of current mode, so they always provide an escape hatch.
// Outline drawer Esc beats mode-exit Esc — closing the overlay is the more local action.
if (isPresenter && key === "Escape" && overview.isOpen()) { event.preventDefault(); overview.close(); return; }
// J / ⇧J scroll the speaker notes (ADR-0028 §9; presenter.notes-scroll). Arrows stay slide
// navigation. Works in every placement that shows notes, also while automatic scroll runs.
if (isPresenter && (key === "j" || key === "J") && !event.metaKey && !event.ctrlKey && !event.altKey) {
event.preventDefault(); notesScroller?.step(event.shiftKey ? -1 : 1); return;
}
// Enter / Space on the keyboard-focused "more" cue activate it (J), not the next slide.
if (isPresenter && (key === "Enter" || key === " " || code === "Space") && event.target?.closest?.(".presenter-notes-more")) {
event.preventDefault(); notesScroller?.step(1); return;
}
if (key === "r" || key === "R") { event.preventDefault(); toggleMode("reveal"); return; }
if ((key === "f" || key === "F")) { event.preventDefault(); toggleMode("focus"); return; }
// While a mode is ON, → is the primary step key and drives the ONE stepping grammar
// everywhere — it walks the slide's units (the active card's on a block-content carousel),
// then advances to the next BEAT (see stepMode). N/P remain as aliases for → / ←. Esc
// exits the mode.
if (state.mode?.kind) {
if (key === "Escape") { event.preventDefault(); exitMode(); return; }
// N is a step alias outside the presenter only; the presenter lists → for stepping (ticket 07).
if (!isPresenter && (key === "n" || key === "N")) { event.preventDefault(); stepMode(1); return; }
// P is NOT a step alias — it must always control the top timer (Start/Pause/Resume), even
// while a mode is active. Step back with ← instead.
if (isNextKey) { event.preventDefault(); stepMode(1); return; }
if (isPreviousKey) { event.preventDefault(); stepMode(-1); return; }
if (key === "Home") { event.preventDefault(); goTo(0, 0); return; }
if (key === "End") { event.preventDefault(); goTo(total - 1, 0); return; }
// Other keys fall through to the normal handlers below.
}
if (isNextKey) { event.preventDefault(); next(); }
else if (isPreviousKey) { event.preventDefault(); previous(); }
else if (key === "Home") { event.preventDefault(); goTo(0, 0); }
else if (key === "End") { event.preventDefault(); goTo(total - 1, 0); }
else if (isPresenter && key === "+") { event.preventDefault(); publish({ fontSize: state.fontSize + 10 }); }
else if (isPresenter && key === "-") { event.preventDefault(); publish({ fontSize: state.fontSize - 10 }); }
else if (isPresenter && (key === "o" || key === "O")) { event.preventDefault(); overview.toggle(); }
else if (isPresenter && key === "[") {
// F2: cycle the preview size (large → medium → small → off → large …); "]" cycles back.
event.preventDefault(); cyclePreviewSize(1);
}
else if (isPresenter && key === "]") { event.preventDefault(); cyclePreviewSize(-1); }
else if (isPresenter && (key === "t" || key === "T")) {
// Open the duration setter for the top clock (presenter QoL).
event.preventDefault(); openDurationSetter();
}
else if (isPresenter && (key === "p" || key === "P")) {
// Start / pause / resume the top clock (presenter QoL).
event.preventDefault(); startOrToggleTimer();
}
else if (isPresenter && (key === "h" || key === "H")) {
// F1: arm/disarm highlight authoring. While armed, select text in the Current preview.
event.preventDefault(); toggleHighlightArmed();
}
else if (isPresenter && (key === "m" || key === "M")) {
// E8: play the current slide's media on the audience display (no-op when none).
if (slideMedia(currentSlide()).length > 0) { event.preventDefault(); sendMediaCommand("play"); }
}
else if (isPresenter && (key === "z" || key === "Z") && !event.metaKey && !event.ctrlKey) {
// G5 (⌘Z is not Z: it is the board panel's undo, never the gallery): presenter renders the lightbox locally AND drives the shared lightbox on the audience.
if (slideImages().length > 0) { event.preventDefault(); toggleLightbox(); }
else if (panePageSource()) { event.preventDefault(); toggleEmbedFullScreen(); }
}
else if (isPresenter && (key === "v" || key === "V")) {
// Ticket 24: Video: Fullscreen — shared lightbox on the video + full-screen command to the audience.
if (slideVideos().length > 0) { event.preventDefault(); videoFullscreenCommand(); }
}
else if (isPresenter && (key === "s" || key === "S")) {
// Task 8: skip-next — jump past the next slide, marking it explicitly skipped.
event.preventDefault(); skipNext();
}
else if (isPresenter && (key === "b" || key === "B")) {
// Return: pop back to where the last >1-slide overview jump came from (R is taken by Reveal).
if (jumpOrigin != null) { event.preventDefault(); returnToOrigin(); }
}
else if (isPresenter && key === "Escape") {
// NOTE (Task 5 escalation): the old presenter card mini-grid ("G") is removed. Folding it into
// the shared overview is BLOCKED — the presenter uses its own outline drawer (already on "O"),
// and the shared overview drawer is CSS-hidden in presenter mode. Deciding how the presenter
// reaches the shared overview needs the plan author. Until then the presenter keeps its
// outline drawer on "O" and "G" is unbound (no-op). See .superpowers/sdd/task-5-report.md.
if (highlightArmed) { event.preventDefault(); setHighlightArmed(false); }
}
else if (isPresenter) return;
else if (key === "o" || key === "O") { event.preventDefault(); overview.toggle(); }
else if (key === "n" || key === "N") { event.preventDefault(); els.notesDrawer.classList.toggle("open"); }
else if (key === "p" || key === "P") { event.preventDefault(); window.print(); }
// r/f are handled above (mode toggles); fullscreen stays on the ⛶ button.
else if (key === "g" || key === "G") {
// Mini-grid overview of the active slide's gallery (standalone only).
const gallery = gridGallery || activeGallery();
if (gallery) { event.preventDefault(); toggleGalleryGrid(gallery); }
}
else if (key === "z" || key === "Z") {
// G5: open the fullscreen image gallery for the current slide (standalone).
if (slideImages().length > 0) { event.preventDefault(); openLightbox(0); }
else if (panePageSource()) { event.preventDefault(); toggleEmbedFullScreen(); }
}
else if (key === "v" || key === "V") {
// Ticket 24: Video: Fullscreen (standalone) — lightbox on the video, then element full screen.
if (slideVideos().length > 0) { event.preventDefault(); videoFullscreenCommand(); }
}
else if (key === "+") { event.preventDefault(); publish({ fontSize: state.fontSize + 10 }); }
else if (key === "-") { event.preventDefault(); publish({ fontSize: state.fontSize - 10 }); }
else if (key === "Escape") {
if (gridGallery) closeGalleryGrid();
overview.close();
els.notesDrawer.classList.remove("open");
}
}
els.prevBtn.addEventListener("click", () => advance(-1));
els.nextBtn.addEventListener("click", () => advance(1));
els.overviewBtn.addEventListener("click", () => overview.open());
els.closeOverview.addEventListener("click", () => overview.close());
els.notesBtn.addEventListener("click", () => els.notesDrawer.classList.toggle("open"));
// License popup (2026-06-13): footer button opens it; × / Esc / backdrop close it. Present
// only when the build unhid the button (deck carries a license).
if (els.licenseBtn && els.licenseModal) {
const setLicense = (open) => { els.licenseModal.hidden = !open; };
els.licenseBtn.addEventListener("click", () => setLicense(els.licenseModal.hidden));
els.licenseClose?.addEventListener("click", () => setLicense(false));
els.licenseModal.addEventListener("click", (e) => { if (e.target === els.licenseModal) setLicense(false); });
// Esc closes (capture phase so it beats the deck's key handler) — only while the modal is open.
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && !els.licenseModal.hidden) { e.stopPropagation(); setLicense(false); }
}, true);
}
els.closeNotes.addEventListener("click", () => els.notesDrawer.classList.remove("open"));
els.printBtn.addEventListener("click", () => window.print());
els.fullscreenBtn.addEventListener("click", requestAudienceFullscreen);
document.addEventListener("fullscreenchange", updateFullscreenState);
els.presenterBtn.addEventListener("click", openPresenter);
els.presenterPrev.addEventListener("click", () => advance(-1));
els.presenterNext.addEventListener("click", () => advance(1));
els.presenterPollOpen?.addEventListener("click", presenterPollPrimaryAction);
els.presenterPollClose?.addEventListener("click", presenterPollPrimaryAction);
els.presenterPollReveal?.addEventListener("click", presenterPollRevealAction);
document.getElementById("presenterPollShowQuestion")?.addEventListener("click", () => {
const poll = presenterPollForDisplay(); if (poll) pollProjection.choose(poll.pollId, "question");
});
document.getElementById("presenterPollShowResults")?.addEventListener("click", () => {
const poll = presenterPollForDisplay(); if (poll) pollProjection.choose(poll.pollId, "results");
});
document.getElementById("presenterPollPreviousPage")?.addEventListener("click", () => {
const poll = presenterPollForDisplay(); if (poll) pollProjection.turnPage(poll.pollId, -1);
});
document.getElementById("presenterPollNextPage")?.addEventListener("click", () => {
const poll = presenterPollForDisplay(); if (poll) pollProjection.turnPage(poll.pollId, 1);
});
document.getElementById("presenterQuickPollDismiss")?.addEventListener("click", () => {
pollProjection.showQuick(activeQuickPollId, false); dismissedPresenterPollId = null; renderPresenter();
});
document.getElementById("presenterQuickPollRestore")?.addEventListener("click", () => {
dismissedPresenterPollId = null; pollProjection.showQuick(activeQuickPollId, true); renderPresenter();
});
document.getElementById("presenterPollPanelToggle")?.addEventListener("click", () => {
dismissedPresenterPollId = null; renderPresenterPoll();
});
els.presenterPollDismiss?.addEventListener("click", () => {
const poll = presenterPollForDisplay();
if (poll) {
dismissedPresenterPollId = poll.pollId;
}
renderPresenterPoll();
});
els.presenterQuickPollButton?.addEventListener("click", () => toggleQuickPollCompose());
els.quickPollClose?.addEventListener("click", () => toggleQuickPollCompose(false));
els.quickPollCancel?.addEventListener("click", () => toggleQuickPollCompose(false));
els.quickPollOpen?.addEventListener("click", openQuickPoll);
els.quickPollQuestion?.addEventListener("input", validateQuickPoll);
["quickPollMaxSelections", "quickPollMaxSubmissions", "quickPollUnlimited"].forEach((id) => {
document.getElementById(id)?.addEventListener("input", validateQuickPoll);
});
els.quickPollAddOption?.addEventListener("click", () => addQuickPollOption());
document.querySelectorAll("[data-quick-poll-type]").forEach((button) => button.addEventListener("click", () => {
quickPollType = button.getAttribute("data-quick-poll-type") || "single";
setQuickPollSegment("data-quick-poll-type", quickPollType);
quickPollExtras.setType(quickPollType);
// Open polls take free text — no option rows. Presets are all mutually-exclusive scales,
// so they only make sense for Single choice.
if (els.quickPollOptionsField) els.quickPollOptionsField.hidden = quickPollType === "open";
if (els.quickPollPresetsField) els.quickPollPresetsField.hidden = quickPollType !== "single";
validateQuickPoll();
}));
// Presets fill the option rows in one tap — the common scales for a spontaneous poll.
document.querySelectorAll("[data-quick-poll-preset]").forEach((button) => button.addEventListener("click", () => {
const labels = (button.getAttribute("data-quick-poll-preset") || "").split("|").filter(Boolean);
if (!labels.length || !els.quickPollOptions) return;
els.quickPollOptions.replaceChildren();
labels.forEach((label) => addQuickPollOption(label));
validateQuickPoll();
}));
document.querySelectorAll("[data-quick-poll-visibility]").forEach((button) => button.addEventListener("click", () => {
quickPollVisibility = button.getAttribute("data-quick-poll-visibility") || "live";
setQuickPollSegment("data-quick-poll-visibility", quickPollVisibility);
validateQuickPoll();
}));
els.presenterReveal.addEventListener("click", () => toggleMode("reveal"));
els.presenterFocus?.addEventListener("click", () => toggleMode("focus"));
// Preview size and the Notes menu are set from the View menu (ticket 04; PRESENTER_MENU_COMMANDS).
els.notesMenu?.addEventListener("click", (event) => {
const option = event.target.closest?.("[data-notes-placement-option]");
if (option) { setNotesPlacement(option.dataset.notesPlacementOption); return; }
const scroll = event.target.closest?.("[data-notes-scroll-option]");
if (scroll) { setNotesScroll(scroll.dataset.notesScrollOption); return; }
if (event.target.closest?.("#notesWpmSlower")) stepNotesSpeed(-1);
else if (event.target.closest?.("#notesWpmFaster")) stepNotesSpeed(1);
});
els.notesJustThisTalk?.addEventListener("change", () => setNotesJustThisTalk(els.notesJustThisTalk.checked));
// A press anywhere outside the Notes menu and the View menu it opens from closes it.
document.addEventListener("pointerdown", (event) => {
if (notesMenuOpen() && !event.target.closest?.(".notes-menu-anchor")) toggleNotesMenu(false);
}, true);
document.getElementById('presenterPointer')?.addEventListener('click', togglePointer);
document.getElementById('presenterPointerExit')?.addEventListener('click', () => setPointerArmed(false));
document.getElementById('presenterPen')?.addEventListener('click', togglePen);
document.getElementById('presenterPenExit')?.addEventListener('click', () => setPenArmed(false));
document.getElementById('penStripOff')?.addEventListener('click', () => setPenArmed(false));
document.getElementById('presenterInkClear')?.addEventListener('click', clearInkHere);
for (const id of ['penUndo', 'penStripUndo']) document.getElementById(id)?.addEventListener('click', undoInk);
for (const id of ['penClear', 'penStripClear']) document.getElementById(id)?.addEventListener('click', clearInkHere);
document.querySelectorAll('#presenterRoot [data-pen-tool]').forEach((b) => b.addEventListener('click', () => setPenTool(b.dataset.penTool)));
document.querySelectorAll('#presenterRoot [data-pen-ink]').forEach((b) => b.addEventListener('click', () => setPenInk(b.dataset.penInk)));
document.querySelectorAll('#presenterRoot [data-pen-width]').forEach((b) => b.addEventListener('click', () => setPenWidth(b.dataset.penWidth)));
els.presenterHighlight?.addEventListener("click", toggleHighlightArmed);
els.presenterHighlightClear?.addEventListener("click", clearCurrentSlideHighlights);
// Bottom bar and mode chips (ticket 05): each runs the function its key runs — K, ⌥⌘I, Esc.
els.navQuickPoll?.addEventListener("click", () => toggleQuickPollCompose());
els.navInstant?.addEventListener("click", () => openInstantCompose());
els.presenterModeExit?.addEventListener("click", () => exitMode());
els.presenterHighlightExit?.addEventListener("click", () => setHighlightArmed(false));
els.presenterHighlightChipClear?.addEventListener("click", clearCurrentSlideHighlights);
// Quick poll and Instant slide show pressed while their composer is open.
if (isPresenter) {
for (const [tool, panel] of [[els.navQuickPoll, els.presenterQuickPollCompose], [els.navInstant, document.getElementById("presenterInstantCompose")]]) {
if (!tool || !panel) continue;
const sync = () => tool.setAttribute("aria-expanded", String(!panel.hidden));
new MutationObserver(sync).observe(panel, { attributes: true, attributeFilter: ["hidden"] });
sync();
}
}
// The selection-capture listener is attached to each Current-preview iframe's document on load
// (see previewSlide), because mouse events do not cross the iframe boundary.
els.fontDown.addEventListener("click", () => publish({ fontSize: state.fontSize - 10 }));
els.fontUp.addEventListener("click", () => publish({ fontSize: state.fontSize + 10 }));
// The presenter outline drawer is the shared createOverview instance (constructed above): O
// toggles it, its own search/keyboard/click handlers jump-and-close. No bespoke wiring here.
// Drag divider: resize current-preview vs side column; persisted across sessions. The
// preview-size cycle ([ key / ⤢ button) clears the custom split back to its presets.
(function initPresenterDivider() {
const divider = els.presenterDivider;
const root = divider ? divider.parentElement : null;
if (!divider || !root) return;
const KEY = "html-presentations:presenter-split";
const apply = (fraction) => {
const f = Math.min(0.88, Math.max(0.35, fraction));
root.style.gridTemplateColumns = `minmax(0, ${f}fr) 8px minmax(220px, ${(1 - f)}fr)`;
};
try { const saved = parseFloat(localStorage.getItem(KEY)); if (saved) apply(saved); } catch { /* private mode */ }
let dragging = false;
divider.addEventListener("pointerdown", (event) => {
dragging = true;
divider.classList.add("dragging");
divider.setPointerCapture(event.pointerId);
});
divider.addEventListener("pointermove", (event) => {
if (!dragging) return;
const rect = root.getBoundingClientRect();
apply((event.clientX - rect.left) / rect.width);
});
divider.addEventListener("pointerup", (event) => {
dragging = false;
divider.classList.remove("dragging");
divider.releasePointerCapture(event.pointerId);
const rect = root.getBoundingClientRect();
try { localStorage.setItem(KEY, String(Math.min(0.88, Math.max(0.35, (event.clientX - rect.left) / rect.width)))); } catch { /* private mode */ }
});
})();
els.presenterFirst.addEventListener("click", () => goTo(0, 0));
els.presenterLast.addEventListener("click", () => goTo(slides.length - 1, 0));
els.presenterAudienceApp.addEventListener("click", openAudienceChromeless);
els.presenterMediaPlay.addEventListener("click", () => sendMediaCommand("play"));
els.presenterMediaPause.addEventListener("click", () => sendMediaCommand("pause"));
// G5: presenter Gallery button drives the shared lightbox; lightbox controls (non-presenter).
els.presenterGalleryBtn?.addEventListener("click", () => { if (slideImages().length > 0) toggleLightbox(); });
els.presenterVideoFullscreen?.addEventListener("click", () => { if (slideVideos().length > 0) videoFullscreenCommand(); });
els.lightboxPrev?.addEventListener("click", () => stepLightbox(-1));
els.lightboxNext?.addEventListener("click", () => stepLightbox(1));
els.lightboxClose?.addEventListener("click", closeLightbox);
// Click the dark backdrop (not the image or a control) to close.
els.lightbox?.addEventListener("click", (event) => {
if (event.target === els.lightboxImg || event.target.closest(".lightbox-video") || event.target.closest(".lightbox-nav") || event.target.closest(".lightbox-close")) return;
closeLightbox();
});
// Click any still image on a slide to open the gallery at that image (standalone/audience).
stage.addEventListener("click", (event) => {
// Card Table (ADR-0007): a click on a child card jumps to that child's first beat. Works on
// the live deck (standalone/audience); the presenter drives its clone previews via keys.
const ctCard = event.target.closest && event.target.closest(".ct-card");
if (ctCard && ctCard.dataset.ctChild) { event.preventDefault(); goToContainerChild(ctCard.dataset.ctChild); return; }
if (isPresenter) return;
// QR overhaul (refinement 6): a corner QR button expands the code full-screen.
const qrBtn = event.target.closest(".slide-qr .qr-code");
if (qrBtn) { event.preventDefault(); openQrFullscreen(qrBtn); return; }
// Ticket 24: the video figure's enlarge affordance opens the lightbox on THAT video.
const enlarge = event.target.closest("figure.slide-video .video-enlarge");
if (enlarge) {
const video = enlarge.closest("figure.slide-video")?.querySelector("video");
const idx = slideImages().findIndex((entry) => entry.kind === "video" && entry.el === video);
event.preventDefault();
if (idx >= 0) openLightbox(idx);
return;
}
const img = event.target.closest("figure.slide-figure img") || event.target.closest(".image-grid .ig-media img");
if (!img) return;
const images = slideImages();
const idx = images.findIndex((entry) => entry.src === (img.currentSrc || img.src || img.getAttribute("src")));
if (images.length > 0) { event.preventDefault(); openLightbox(idx < 0 ? 0 : idx); }
});
// #presenterSearch input + keydown are wired by createOverview (its host.searchEl is #presenterSearch
// in presenter mode) — type-to-filter, Up/Down highlight, Enter jump-and-close, Esc close.
if (isReplay) {
window.addEventListener("click", (event) => {
event.preventDefault();
event.stopImmediatePropagation();
}, true);
// The replay is driven by the page that frames it (Studio), and by nothing inside it.
window.addEventListener("message", (event) => { if (event.source === window.parent) applyReplayState(event.data); });
}
// A key the presenter acted on (handleKey prevented its default) is reported to the Guide (ticket 10).
window.addEventListener("keydown", (event) => {
const acted = event.defaultPrevented;
handleKey(event);
if (isPresenter && !acted && event.defaultPrevented && !shortcutForwarded.has(event)) reportGuideCommand(guideKeyCommand(event));
});
// ADR-0005 chrome policy: the control bar auto-hides after ~2s of mouse stillness and reappears
// on any mouse movement. C pins it visible (handled in handleKey). Presenter mode hides the deck
// entirely, so this only governs the standalone/handout deck.
let chromeIdleTimer = 0;
function armChromeIdle() {
document.body.classList.remove("chrome-idle");
clearTimeout(chromeIdleTimer);
chromeIdleTimer = setTimeout(() => {
if (!document.body.classList.contains("chrome-pinned")) document.body.classList.add("chrome-idle");
}, 2000);
}
window.addEventListener("mousemove", armChromeIdle, { passive: true });
window.addEventListener("mousedown", armChromeIdle, { passive: true });
armChromeIdle();
let resizeTimer = 0;
window.addEventListener("resize", () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(autofitActiveSlides, 100);
});
// Test hook: lets a headless harness run the same title-fit + autofit pass the deck runs on
// slide change / resize, so an overflow sweep measures the real (fitted) layout. Inert in
// normal use — nothing calls it unless a verifier does.
window.__autofitForTest = autofitActiveSlides;
// Test hooks: the pure beat-navigation decision core (BEAT_HELPERS), callable headlessly so
// the advance grammar and Next-pane labels can be asserted without a live presenter/audience
// pair (scripts/test-beats-preview.mjs also extracts the marker block verbatim).
window.__advanceTargetForTest = advanceTarget;
window.__beatLabelForTest = beatLabel;
// Test hooks: the pure container-mode state core (CONTAINER_HELPERS), for the e2e/diagnose
// harness (scripts/test-container-render.mjs also extracts the marker block verbatim).
window.__containerRenderPlanForTest = containerRenderPlan;
window.__childIdsForSectionForTest = childIdsForSection;
// Canvas regression capture activates slides directly; expose only the normal lazy Mermaid path.
window.__initMermaidsForCanvasTest = initMermaids;
// Test hook: the highlight apply/clear/serialise primitives, so a headless DOM round-trip can
// verify a presenter selection re-resolves to the same audience marks. Inert in normal use.
window.__highlightForTest = {
highlightableBlocks, applyHighlightPayload, clearHighlights, serializeSelectionWithin,
setCurrentHighlight: (h) => { currentHighlight = h; }
};
// Print shows every slide at full height (flowing naturally), so strip any inline
// autofit zoom before printing and restore it afterwards.
window.addEventListener("beforeprint", () => {
document.querySelectorAll(".slide-content").forEach((node) => { node.style.zoom = ""; });
// A stepped simulation's scroll position (anchorSimScroll) must not reach paper: print shows
// every part, anchored like the static handout. applyModeDimming puts it back afterwards.
document.querySelectorAll(".sim .sim-scroll").forEach((node) => { if (node.scrollTop !== 0) node.scrollTop = 0; });
});
window.addEventListener("afterprint", autofitActiveSlides);
window.addEventListener("afterprint", () => applyModeDimming());
window.addEventListener("hashchange", () => {
const id = location.hash.replace("#", "");
if (!id) return;
const beatIndex = beatIndexForHash(id, beats);
if (beatIndex >= 0) {
if (beatIndex !== state.beat) goToBeat(beatIndex);
return;
}
const index = slides.findIndex((slide) => slide.dataset.id === id);
if (index >= 0 && index !== state.index) goTo(index, 0);
});
if (isReplay) {
try { window.parent?.postMessage({ type: "tw-replay-ready" }, "*"); } catch {}
}
if (isPaired) {
channel?.addEventListener("message", (event) => {
pollProjection.receivePeer(event.data);
if (event.data?.type === messageType) applyState(event.data.state);
if (event.data?.type === commandType && event.data.command === "print") window.print();
if (event.data?.type === commandType && event.data.command === "media") executeMediaCommand(event.data);
if (event.data?.type === commandType && event.data.command === "video") executeVideoCommand(event.data);
if (event.data?.type === commandType && event.data.command === "audio-state") applyAudioState(event.data);
if (event.data?.type === commandType && event.data.command === "highlight") executeHighlightCommand(event.data);
if (isAudience && event.data?.type === commandType && event.data.command === "pointer" && validPointer(event.data.pointer)) pointerOverlay?.show(event.data.pointer);
if (isAudience && event.data?.type === commandType && event.data.command === "ink") receiveInk(event.data.ink);
if (isPresenter && event.data?.type === commandType && event.data.command === "ink-ready") answerInkReady();
if (event.data?.type === commandType && event.data.command === "embed") executeEmbedCommand(event.data);
if (event.data?.type === commandType && event.data.command === "embed-ready") answerEmbedReady(event.data);
if (event.data?.type === commandType && event.data.command === 'instant') applyInstantSlide(event.data.slide);
});
window.addEventListener("message", (event) => {
// Only the peer this deck established (acceptsPeerMessage). The peer is never taken from a message.
if (!acceptsPeerMessage(event)) return;
pollProjection.receivePeer(event.data);
if (event.data?.type === messageType) applyState(event.data.state);
if (event.data?.type === commandType && event.data.command === "print") window.print();
if (event.data?.type === commandType && event.data.command === "media") executeMediaCommand(event.data);
if (event.data?.type === commandType && event.data.command === "video") executeVideoCommand(event.data);
if (event.data?.type === commandType && event.data.command === "audio-state") applyAudioState(event.data);
if (event.data?.type === commandType && event.data.command === "highlight") executeHighlightCommand(event.data);
if (isAudience && event.data?.type === commandType && event.data.command === "pointer" && validPointer(event.data.pointer)) pointerOverlay?.show(event.data.pointer);
if (isAudience && event.data?.type === commandType && event.data.command === "ink") receiveInk(event.data.ink);
if (isPresenter && event.data?.type === commandType && event.data.command === "ink-ready") answerInkReady();
if (event.data?.type === commandType && event.data.command === "embed") executeEmbedCommand(event.data);
if (event.data?.type === commandType && event.data.command === "embed-ready") answerEmbedReady(event.data);
if (event.data?.type === commandType && event.data.command === 'instant') applyInstantSlide(event.data.slide);
});
window.addEventListener("storage", (event) => {
if (event.key === instantStorageKey) { try { applyInstantSlide(JSON.parse(event.newValue)); } catch {} return; }
if (event.key !== storageKey || !event.newValue) return;
try { applyState(JSON.parse(event.newValue)); } catch {}
});
setInterval(() => {
const stored = localStorage.getItem(storageKey);
if (!stored) return;
try { applyState(JSON.parse(stored)); } catch {}
}, 300);
if (isAudience) { try { applyInstantSlide(JSON.parse(localStorage.getItem(instantStorageKey))); } catch {} }
// A projector that opens or reloads asks the presenter for the drawing on screen (ticket 08).
if (isAudience) sendToPeer({ type: commandType, command: "ink-ready" });
}
// === Presenter timer family (2026-06-30, presenter QoL) ===
// ONE top clock with explicit Start / Pause / Resume + a duration setter, driven by the pure
// timer core (fmtClock / bigTimerState). The core is injected verbatim at build time from
// compiler/assets/runtime/timer.js — the SAME source scripts/test-timers.mjs unit-tests. The
// placeholder below (on its own line, exactly once) is replaced by 07-assembly.buildDeckHtmlFromModel.
// Pure presenter timer core. Inlined into the presenter template at build time (no export
// keyword — see 01-cli-utils.timerRuntimeSource) and loaded verbatim by scripts/test-timers.mjs.
// timer = { targetSeconds, elapsedMs, runningSince }: elapsedMs is frozen accumulated run time,
// runningSince is the wall-clock ms the current run began (null when idle/paused). This shape lets
// pause/resume and mid-talk reload accumulate correctly from one persisted object.
function fmtClock(totalSeconds) {
const t = Math.max(0, Math.round(totalSeconds));
return `${String(Math.floor(t / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}`;
}
function bigTimerState(nowMs, timer, thresholds, firedMilestones) {
const targetSeconds = Number(timer?.targetSeconds || 0);
const elapsedMs = Number(timer?.elapsedMs || 0);
const runningSince = timer?.runningSince || null;
const status = runningSince ? "running" : (elapsedMs > 0 ? "paused" : "idle");
const elapsed = elapsedMs + (runningSince ? nowMs - runningSince : 0);
const seconds = Math.round(targetSeconds - elapsed / 1000); // remaining; negative once overrunning
const warnAt = Number(thresholds?.warnAtSeconds ?? 300);
const urgentAt = Number(thresholds?.urgentAtSeconds ?? 60);
let level = "";
if (status !== "idle") {
level = seconds <= 0 ? "over" : seconds <= urgentAt ? "urgent" : seconds <= warnAt ? "warn" : "";
}
// Most-urgent-first so a clock jump (window slept) announces what matters NOW; a milestone above
// the talk's own length never fires (a 2-minute talk has no "5 minutes"). Announce only while running.
let milestone = null;
if (status === "running") {
for (const m of [0, urgentAt, warnAt]) {
if (seconds <= m && targetSeconds > m && !firedMilestones.has(m)) { milestone = m; break; }
}
}
return { status, mode: status === "idle" ? "idle" : "countdown", seconds, level, milestone };
}
function instantSlideFromText(value, shownAt = Date.now()) {
const text = String(value || '').trim();
if (!text) return null;
try {
const url = new URL(text);
if ((url.protocol === 'http:' || url.protocol === 'https:') && text.length <= 2048)
return { kind: 'link', url: text, qrSvg: '', shownAt };
} catch {}
return { kind: 'text', text: text.slice(0, 2000), shownAt };
}
function writtenInstantLink(url) {
const written = String(url || '').replace(/^[a-z][a-z0-9+.-]*:\/\//i, '').replace(/^www\./i, '').replace(/\/+$/, '');
const slash = written.search(/[/?#]/);
const parts = slash >= 0 ? { host: written.slice(0, slash), path: written.slice(slash) } : { host: written, path: '' };
// The host as the browser will resolve it: lower case, and punycode when it holds non-ASCII letters, so the written link cannot mislead.
try { parts.host = new URL('https://' + parts.host).host; } catch {}
return parts;
}
function normaliseInstantLink(input) {
const raw = String(input == null ? '' : input).trim();
if (!raw) return { empty: true };
const refuse = { error: 'Only web links (http or https) can be shown.' };
if (/[\s\u0000-\u001f\u007f]/.test(raw) || raw.length > 2048) return { error: 'That does not look like a web link.' };
let url = raw;
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
if (!/^https?:\/\//i.test(raw)) return refuse;
} else if (/^[a-z][a-z0-9+.-]*:/i.test(raw) && !/^[^/:?#]+:\d+([/?#]|$)/.test(raw)) return refuse;
else url = 'https://' + raw.replace(/^\/\//, '');
try {
const parsed = new URL(url);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return refuse;
if (parsed.username || parsed.password) return { error: 'Links with a username or password in them cannot be shown.' };
if (!parsed.hostname || (parsed.hostname.indexOf('.') < 0 && parsed.hostname.charAt(0) !== '[')) return { error: 'That does not look like a web link.' };
// The canonical form (percent-encodes < > " and path backticks); what is still unsafe in it is refused.
url = parsed.href;
if (url.length > 2048 || /[<>"`\u0000-\u001f\u007f]/.test(url)) return { error: 'That link has characters that cannot be shown.' };
} catch { return { error: 'That does not look like a web link.' }; }
const shown = writtenInstantLink(url);
return { url, written: shown.host + shown.path };
}
function instantEndSound(slide) {
const value = slide && slide.endSound;
if (value === 'none' || value === 'chime' || value === 'alarm') return value;
return slide && slide.soundAtEnd === false ? 'none' : 'chime';
}
function nextBreakEnd(prev, slide, remainingMs, plays) {
const key = slide.startedAt + ':' + slide.durationMs;
const state = prev && prev.key === key ? prev : { key, armed: false, fired: false };
if (remainingMs > 0) return { state: state.armed ? state : { key, armed: true, fired: state.fired }, play: false, sound: null };
if (state.armed && !state.fired) {
const choice = instantEndSound(slide);
const play = Boolean(plays) && choice !== 'none';
return { state: { key, armed: true, fired: true }, play, sound: play ? choice : null };
}
return { state, play: false, sound: null };
}
function createBreakChime(win) {
const Context = win && (win.AudioContext || win.webkitAudioContext);
let context = null;
const events = ['pointerdown', 'keydown', 'click', 'touchstart'];
function ensure() {
if (!context && Context) { try { context = new Context(); } catch { context = null; } }
return context;
}
function resume() {
const ctx = ensure();
if (ctx && ctx.state === 'suspended') { try { const result = ctx.resume(); if (result && result.catch) result.catch(() => {}); } catch {} }
return ctx;
}
function onGesture() {
const ctx = resume();
if (ctx && ctx.state !== 'suspended') events.forEach((name) => win.document.removeEventListener(name, onGesture, true));
}
if (Context && win.document) events.forEach((name) => win.document.addEventListener(name, onGesture, true));
function play(sound) {
try {
const ctx = resume();
if (!ctx || ctx.state !== 'running') return false;
const start = ctx.currentTime + 0.05;
const alarm = sound === 'alarm';
const notes = alarm
? [0, 1.6].flatMap((group) => [880, 1108.73, 1318.51].map((frequency, i) => [frequency, group + i * 0.4, 0.28]))
: [[659.25, 0, 1.4], [880, 0.32, 1.4]];
notes.forEach(([frequency, offset, length]) => {
const oscillator = ctx.createOscillator();
const gain = ctx.createGain();
oscillator.type = alarm ? 'square' : 'sine';
oscillator.frequency.value = frequency;
gain.gain.setValueAtTime(0.0001, start + offset);
gain.gain.exponentialRampToValueAtTime(alarm ? 0.2 : 0.28, start + offset + 0.02);
if (alarm) gain.gain.setValueAtTime(0.2, start + offset + length - 0.04);
gain.gain.exponentialRampToValueAtTime(0.0001, start + offset + length);
oscillator.connect(gain);
gain.connect(ctx.destination);
oscillator.start(start + offset);
oscillator.stop(start + offset + length + 0.1);
});
return true;
} catch { return false; }
}
return { play, unlock: resume };
}
function createInstantSlideSurface(mount, options = {}) {
const document = mount.ownerDocument;
const surface = document.createElement('div');
surface.className = 'instant-slide-surface' + (options.thumbnail ? ' instant-slide-thumb' : '');
surface.hidden = true;
mount.appendChild(surface);
let slide = null;
let timer = null;
let breakEnd = null;
const now = options.now || Date.now;
function add(tag, className, text, parent = surface) {
const node = document.createElement(tag);
node.className = className;
if (text != null) node.textContent = text;
parent.appendChild(node);
return node;
}
function updateClock() {
if (!slide) return;
if (slide.kind === 'time') {
const digits = surface.querySelector('.instant-slide-digits');
if (digits) digits.textContent = new Date(now()).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
if (slide.kind === 'countdown') {
const remaining = Math.max(0, slide.startedAt + slide.durationMs - now());
const seconds = Math.ceil(remaining / 1000);
const digits = surface.querySelector('.instant-slide-digits');
if (digits) digits.textContent = String(Math.floor(seconds / 60)).padStart(2, '0') + ':' + String(seconds % 60).padStart(2, '0');
const bar = surface.querySelector('.instant-slide-bar i');
if (bar) bar.style.width = (100 * remaining / slide.durationMs) + '%';
const done = surface.querySelector('.instant-slide-timeup');
if (done) done.hidden = remaining > 0;
const decision = nextBreakEnd(breakEnd, slide, remaining, Boolean(options.chime));
breakEnd = decision.state;
if (decision.play) { try { options.chime.play(decision.sound); } catch {} }
}
}
// A written link: an anchor on surfaces people can tap, plain text elsewhere (thumbnails, projector, venue). `options.clickable === false` turns anchors off.
function addWrittenLink(parent, url, className) {
const written = writtenInstantLink(url);
const box = add('div', className, null, parent);
const holder = options.clickable === false || options.thumbnail ? box : add('a', '', null, box);
if (holder !== box) { holder.href = url; holder.target = '_blank'; holder.rel = 'noopener noreferrer'; }
holder.appendChild(document.createTextNode(written.host));
if (written.path) add('strong', '', written.path, holder);
return box;
}
// A QR code in a box of class `boxClass`. Drawn only on surfaces that opt in with `options.showQr`
// (projector, presenter preview, venue screen); phones never get one.
function addQr(parent, boxClass, svg, alt) {
if (!options.showQr || !svg) return;
const image = add('img', '', null, add('div', boxClass, null, parent));
image.alt = alt;
image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
}
// The talk's QR code, and its link when the talk has a published handout, bottom-right of the
// clock, break and text slides that carry no link of their own. `options.qr()` supplies { svg, url, link } where the page has one;
// phones pass none and never show a QR.
function addCornerQr() {
// A countdown that carries its own link shows that link's QR here instead of the talk's.
if (slide.kind === 'countdown' && slide.link) {
const corner = add('div', 'instant-slide-corner');
addQr(corner, 'instant-slide-corner-qr', slide.linkQrSvg, 'QR code for this link');
addWrittenLink(corner, slide.link, 'instant-slide-corner-link');
return;
}
let qr = null;
try { qr = options.qr ? options.qr() : null; } catch { qr = null; }
if (!qr || !qr.svg || !options.showQr) return;
const corner = add('div', 'instant-slide-corner');
addQr(corner, 'instant-slide-corner-qr', qr.svg, 'QR code for this talk');
// The written link is the published handout (qr.linkUrl), which can differ from what the QR encodes (the live join link).
const linkUrl = qr.linkUrl || qr.url;
if (qr.link && linkUrl) addWrittenLink(corner, linkUrl, 'instant-slide-corner-link');
}
function show(next) {
if (timer != null) clearInterval(timer);
timer = null;
slide = next;
if (!slide) breakEnd = null;
surface.replaceChildren();
surface.hidden = !slide;
if (!slide) return;
const content = add('div', 'instant-slide-content');
if (slide.kind === 'text') {
add('p', 'instant-slide-text', slide.text, content);
if (slide.link) {
addWrittenLink(content, slide.link, 'instant-slide-link');
addQr(content, 'instant-slide-qr', slide.linkQrSvg, 'QR code for this link');
} else addCornerQr();
}
else if (slide.kind === 'image') {
const image = add('img', 'instant-slide-image', null, content);
image.src = slide.dataUrl;
image.alt = 'Image shown by the presenter';
}
else if (slide.kind === 'link') {
add('div', 'instant-slide-kicker', 'Link', content);
addWrittenLink(content, slide.url, 'instant-slide-link');
addQr(content, 'instant-slide-qr', slide.qrSvg, 'QR code for this link');
} else {
const label = slide.kind === 'countdown' ? String(slide.label || '').trim() : '';
if (label) add('div', 'instant-slide-kicker', label, content);
if (slide.kind === 'countdown') add('div', 'instant-slide-timeup', "Time’s up", content);
add('div', 'instant-slide-digits', '', content);
if (slide.kind === 'countdown') {
const bar = add('div', 'instant-slide-bar', null, content);
add('i', '', null, bar);
const meta = add('div', 'instant-slide-bar-meta', null, content);
add('span', '', '0:00', meta);
add('span', '', String(Math.round(slide.durationMs / 60000)) + ':00', meta);
}
addCornerQr();
updateClock();
timer = setInterval(updateClock, slide.kind === 'time' ? 1000 : 100);
}
}
return { show, element: surface, destroy() { if (timer != null) clearInterval(timer); surface.remove(); } };
}
function formatAudioClock(seconds) {
const whole = Math.max(0, Math.floor(Number(seconds) || 0));
return Math.floor(whole / 60) + ':' + String(whole % 60).padStart(2, '0');
}
function setAudioChipState(chip, state, seconds) {
if (!chip || !chip.dataset) return false;
const next = state === 'playing' || state === 'finished' ? state : 'ready';
const text = formatAudioClock(next === 'ready' ? 0 : seconds);
const time = chip.querySelector('.slide-audio-time');
const timeChanged = Boolean(time) && time.textContent !== text;
const stateChanged = chip.dataset.audioState !== next;
if (stateChanged) chip.dataset.audioState = next;
if (timeChanged) time.textContent = text;
return stateChanged || timeChanged;
}
function createAudioChipController(options) {
const onChange = (options && options.onChange) || function () {};
const audioOf = (chip) => chip.querySelector('audio');
function apply(chip, state, seconds) {
if (setAudioChipState(chip, state, seconds)) onChange(chip, chip.dataset.audioState, seconds);
}
function bind(chip) {
const audio = audioOf(chip);
if (!audio || chip.dataset.audioBound) return audio;
chip.dataset.audioBound = '1';
audio.addEventListener('playing', () => apply(chip, 'playing', audio.currentTime));
audio.addEventListener('timeupdate', () => { if (!audio.paused) apply(chip, 'playing', audio.currentTime); });
// A clip that ran to its end pauses first and then fires `ended`: only a real pause is "ready".
// finish() below pauses a clip the step has moved past: that chip is already `finished`.
audio.addEventListener('pause', () => { if (!audio.ended && chip.dataset.audioState !== 'finished') apply(chip, 'ready', 0); });
audio.addEventListener('ended', () => apply(chip, 'finished', audio.currentTime));
return audio;
}
function play(chip) {
const audio = bind(chip);
if (!audio) return Promise.resolve(false);
if (chip.dataset.audioState === 'finished') { try { audio.currentTime = 0; } catch (e) { /* not seekable yet */ } }
// Resolves true once playback has begun. A blocked autoplay, or an undecodable or missing
// source, rejects: the chip stays as it was (ready) and the promise resolves false.
let result;
try { result = audio.play(); } catch (e) { return Promise.resolve(false); }
return Promise.resolve(result).then(() => true, () => false);
}
function pause(chip) {
const audio = audioOf(chip);
if (audio) audio.pause();
}
function stop(chip) {
const audio = audioOf(chip);
if (audio) {
audio.pause();
try { audio.currentTime = 0; } catch (e) { /* not seekable yet */ }
}
delete chip.dataset.audioAutoplayed;
apply(chip, 'ready', 0);
}
// "Play as a step" (ticket 05): the step has moved past the file. It stops where it is and the
// chip shows `finished`, as it does after a clip that ran to its end.
function finish(chip) {
const audio = audioOf(chip);
const at = audio ? audio.currentTime : 0;
if (audio && !audio.paused) audio.pause();
apply(chip, 'finished', at);
}
return {
play, pause, stop, finish,
/** The slide became the live one: bind its chips and start the {autoplay} ones, once.
* `canAutoplay` is false on every surface but the live projector / plain deck display. */
enter(slide, canAutoplay) {
slide.querySelectorAll('.slide-audio').forEach((chip) => {
bind(chip);
if (canAutoplay && chip.hasAttribute('data-audio-autoplay') && !chip.dataset.audioAutoplayed) {
// The marker stops a re-render restarting a clip that is starting or has played; a
// rejected start clears it, so the next render of the live slide tries again.
chip.dataset.audioAutoplayed = '1';
play(chip).then((started) => { if (!started) delete chip.dataset.audioAutoplayed; });
}
});
},
/** The slide is no longer live: every chip stops, rewinds to 0 and returns to ready, whatever its state. */
leave(slide) {
slide.querySelectorAll('.slide-audio').forEach((chip) => {
// Whatever its state: a paused clip (state ready, position kept) is rewound too, so coming
// back starts from the top. Chips never touched are skipped: leave runs on every render.
const audio = audioOf(chip);
const touched = chip.dataset.audioState !== 'ready' || chip.dataset.audioAutoplayed || (audio && (!audio.paused || audio.currentTime > 0));
if (touched) stop(chip);
});
}
};
}
function pointerPoint(clientX, clientY, rect, space = 'slide') {
if (!rect || rect.width <= 0 || rect.height <= 0 || !Number.isFinite(clientX) || !Number.isFinite(clientY)) return null;
const x = (clientX - rect.left) / rect.width, y = (clientY - rect.top) / rect.height;
if (x < 0 || x > 1 || y < 0 || y > 1) return null;
return { x: x * (space === 'image' ? 1 : 1280), y: y * (space === 'image' ? 1 : 720), space };
}
function pointerPixels(point, rect) {
return { x: rect.left + point.x / (point.space === 'image' ? 1 : 1280) * rect.width,
y: rect.top + point.y / (point.space === 'image' ? 1 : 720) * rect.height };
}
function validPointer(value) {
if (value === 'gone') return true;
if (!value || !['slide', 'image'].includes(value.space) || typeof value.slideId !== 'string'
|| !value.slideId.trim() || value.slideId.length > 100) return false;
return typeof value.x === 'number' && Number.isFinite(value.x) && value.x >= 0 && value.x <= (value.space === 'image' ? 1 : 1280)
&& typeof value.y === 'number' && Number.isFinite(value.y) && value.y >= 0 && value.y <= (value.space === 'image' ? 1 : 720);
}
function createPointerOverlay({ document, surface, onMove = undefined, staleMs = 0, drawInk = undefined }) {
const win = document.defaultView;
const ns = 'http://www.w3.org/2000/svg';
const node = (tag, attrs) => {
const el = document.createElementNS(ns, tag);
for (const [key, value] of Object.entries(attrs || {})) el.setAttribute(key, value);
return el;
};
const root = node('svg', {
class: 'tw-live-overlay', 'aria-hidden': 'true', viewBox: '0 0 1280 720', preserveAspectRatio: 'none'
});
root.style.cssText = 'position:fixed;z-index:10000;pointer-events:none;overflow:hidden;';
const strokes = node('g', { 'data-overlay-layer': 'strokes' });
const ring = node('g', { 'data-overlay-layer': 'pointer', class: 'tw-pointer-ring' });
for (const [width, colour] of [[11, '#0006'], [8, '#fff'], [4, '#ff3b30']]) {
ring.append(node('circle', { r: 21, fill: 'none', stroke: colour, 'stroke-width': width }));
}
root.append(strokes, ring);
document.body.append(root);
const style = document.createElement('style');
style.textContent = '@media print{.tw-live-overlay{display:none!important}}';
document.head.append(style);
/** @type {import('../../../worker/protocol.ts').PointerMessage['pointer']} */
let point = 'gone';
let armed = false, timer, frame, observed;
let penArmed = false, penCursorCss = '', inkView = null, inkVersion = 0, inkDrawn = '';
// Ink is redrawn only when the view or the surface's geometry changed: observers elsewhere in
// the deck call refresh() on DOM changes, and an unconditional redraw would feed them forever.
const drawInkOnce = (view, rect, canvasScale) => {
if (!drawInk) return;
const signature = view ? [inkVersion, rect.left, rect.top, rect.width, rect.height, canvasScale].join(',') : '';
if (signature === inkDrawn) return;
inkDrawn = signature;
drawInk(strokes, view, { rect, canvasScale });
};
const inkShown = (s) => Boolean(inkView && s && inkView.slideId === s.slideId && inkView.space === s.space
&& (s.space !== 'image' || inkView.image === (s.image ?? 0)) && (inkView.strokes.length || inkView.draft));
function refresh() {
const s = surface();
const rect = s?.rect;
if ((armed || penArmed || point !== 'gone' || inkView) && s?.element && s.element !== observed) {
watch.disconnect();
watch.observe(document.body);
observed = s.element;
watch.observe(observed);
if (observed.parentElement) watch.observe(observed.parentElement);
}
const visible = point !== 'gone' && point.slideId === s?.slideId && point.space === s?.space;
const usable = rect && rect.width > 0 && rect.height > 0;
const ink = usable && inkShown(s);
root.style.display = usable && (armed || penArmed || visible || ink) ? '' : 'none';
root.style.pointerEvents = (armed || penArmed) && usable ? 'all' : 'none';
root.style.cursor = armed && usable ? 'none' : penArmed && usable ? penCursorCss : '';
ring.style.display = visible ? '' : 'none';
if (!usable) { drawInkOnce(null); return; }
Object.assign(root.style, {
left: rect.left + 'px', top: rect.top + 'px', width: rect.width + 'px', height: rect.height + 'px'
});
const clip = s.captureRect;
const edges = clip ? [clip.top - rect.top, rect.left + rect.width - clip.right,
rect.top + rect.height - clip.bottom, clip.left - rect.left].map(value => Math.max(0, value) + 'px') : null;
root.style.clipPath = edges ? `inset(${edges.join(' ')})` : 'none';
drawInkOnce(ink ? inkView : null, rect, s.canvasScale ?? rect.width / 1280);
if (point !== 'gone') {
const pixelScale = s.canvasScale ?? rect.width / 1280;
const x = point.x * (point.space === 'image' ? 1280 : 1);
const y = point.y * (point.space === 'image' ? 720 : 1);
// Position uses the image rect; size always uses the slide canvas, independently on both axes.
ring.setAttribute('transform', `translate(${x} ${y}) scale(${pixelScale * 1280 / rect.width} ${pixelScale * 720 / rect.height})`);
}
}
function show(next) {
if (!validPointer(next)) return;
point = next;
if (next === 'gone' && !armed && !penArmed && !inkView) { watch.disconnect(); observed = null; }
clearTimeout(timer);
if (staleMs && next !== 'gone') timer = setTimeout(() => show('gone'), staleMs);
refresh();
}
function move(event) {
if (!armed) return;
const s = surface();
const p = s && pointerPoint(event.clientX, event.clientY, s.rect, s.space);
const next = p ? { ...p, slideId: s.slideId } : 'gone';
show(next);
onMove?.(next);
}
root.addEventListener('pointermove', move);
root.addEventListener('pointerleave', () => {
if (armed) { show('gone'); onMove?.('gone'); }
});
root.addEventListener('pointerdown', event => {
if (armed) { event.preventDefault(); event.stopPropagation(); }
});
win.addEventListener('resize', refresh);
const watch = new win.ResizeObserver(() => {
win.cancelAnimationFrame(frame);
frame = win.requestAnimationFrame(refresh);
});
document.addEventListener('load', refresh, true);
refresh();
return {
show, refresh, strokes, root,
/** The Pen's view of one layer ({ slideId, space, image?, strokes, draft }), or null. */
ink(view) { inkView = view || null; inkVersion++; refresh(); },
/** Pen capture: the overlay takes presses over the slide and shows the pen's cursor. */
armPen(on, cursor = '') {
penArmed = Boolean(on); penCursorCss = cursor;
if (!penArmed && !armed) { watch.disconnect(); observed = null; win.cancelAnimationFrame(frame); }
refresh();
},
arm(on) {
armed = Boolean(on);
if (!armed && !penArmed) { watch.disconnect(); observed = null; win.cancelAnimationFrame(frame); }
refresh();
},
destroy() {
clearTimeout(timer);
win.cancelAnimationFrame(frame);
watch.disconnect();
win.removeEventListener('resize', refresh);
document.removeEventListener('load', refresh, true);
root.remove();
style.remove();
}
};
}
function normalisePresenterChord(chord) {
if (typeof chord !== 'string') return null;
const match = /^([⌃⌥⌘⇧]*)(.+)$/.exec(chord);
if (!match || new Set(match[1]).size !== match[1].length || match[1].length === 4) return null;
let mods = match[1], key = match[2];
const names = ['Space', 'Tab', 'Enter', 'Escape', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown',
'Backspace', 'Delete', 'Home', 'End', 'PageUp', 'PageDown', 'MediaTrackNext', 'MediaTrackPrevious'];
const named = names.find(name => name.toUpperCase() === key.toUpperCase());
const shifted = '~!@#$%^&*()_+{}|:"<>?';
const bases = '`1234567890-=[]\\;\',./';
if (named) key = named;
else if (/^F([1-9]|1\d|2[0-4])$/i.test(key)) key = key.toUpperCase();
else if (key.length === 1 && /^[a-z0-9`\-=\[\]\\;',./]$/i.test(key)) key = key.toUpperCase();
else if (key.length === 1 && shifted.includes(key)) {
key = bases[shifted.indexOf(key)];
if (!mods.includes('⇧')) mods += '⇧';
} else return null;
return ['⌃', '⌥', '⌘', '⇧'].filter(mod => mods.includes(mod)).join('') + key;
}
function presenterChord(event) {
let key = event.key;
if (['Meta', 'Control', 'Alt', 'Shift'].includes(key)) return null;
// macOS Option produces composed characters or Dead; bind the physical key instead.
const punctuation = { Backquote: '`', Minus: '-', Equal: '=', BracketLeft: '[', BracketRight: ']',
Backslash: '\\', Semicolon: ';', Quote: "'", Comma: ',', Period: '.', Slash: '/' };
if (event.altKey && /^Key[A-Z]$/.test(event.code || '')) key = event.code.slice(3);
else if (event.altKey && /^Digit\d$/.test(event.code || '')) key = event.code.slice(5);
else if (punctuation[event.code]) key = punctuation[event.code];
return normalisePresenterChord((event.ctrlKey ? '⌃' : '') + (event.altKey ? '⌥' : '') + (event.metaKey ? '⌘' : '')
+ (event.shiftKey ? '⇧' : '') + (key === ' ' ? 'Space' : key || ''));
}
function presenterCodeChord(code) {
if (code === '-') return '-';
const parts = code.split('-');
let key = parts.pop();
if (key === 'BracketLeft') key = '[';
if (key === 'BracketRight') key = ']';
return normalisePresenterChord((parts.includes('Ctrl') ? '⌃' : '') + (parts.includes('Alt') ? '⌥' : '')
+ (parts.includes('Mod') || parts.includes('Meta') ? '⌘' : '')
+ (parts.includes('Shift') ? '⇧' : '') + key);
}
function createPresenterShortcuts({ document, storage, commands, onChange }) {
const store = 'talkweaver:presenter:shortcuts';
const overrides = Object.create(null);
const extra = {
'⌘K': 'Contextual actions', '⌘P': 'Inspector', '⌘F': 'Find', '⌘⇧F': 'Search', '⌘,': 'Settings',
'⌘/': 'Keyboard shortcuts', '⌘⇧P': 'All commands', '⌘⇧K': 'Navigation', '⌘⇧,': 'Rebind command',
'-': 'Slide text smaller', '=': 'Slide text larger', '?': 'Keyboard shortcuts', '⇧?': 'Keyboard shortcuts'
};
for (let i = 0; i <= 9; i++) extra[String(i)] = 'Card on a grid slide';
const navigationKeys = ['Space', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End',
'Enter', 'Tab', 'Escape', 'Backspace', 'Delete'];
function taken(chord, id) {
const normal = normalisePresenterChord(chord);
if (!normal) return 'a reserved or invalid key';
chord = normal;
const own = commands.find(command => command.id === id);
const ownDefault = own?.codes.some(code => presenterCodeChord(code) === chord);
const key = chord.replace(/^[⌃⌥⌘⇧]+/, '');
if (['Tab', 'Escape', 'Enter'].includes(key)
|| ((chord.includes('⌘') || chord.includes('⌃')) && !ownDefault)
|| (chord.includes('⌥') && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Backspace'].includes(key))) {
return 'a reserved key';
}
if (!ownDefault) {
for (const [code, label] of Object.entries(extra)) {
if (normalisePresenterChord(code) === chord) return label;
}
}
for (const command of commands) {
if (command.id === id) continue;
if (command.codes.some(code => presenterCodeChord(code) === chord) || overrides[command.id]?.chord === chord) {
return command.label;
}
}
// Navigation and editing keys stay the deck's, with or without Shift: the deck's key handler
// matches on the key alone, so Shift+Right and Shift+Space already navigate. Name the holder of the plain key if any.
if (navigationKeys.includes(key) && !ownDefault) {
if (chord.includes('⇧')) {
const plain = chord.replace('⇧', '');
for (const [code, label] of Object.entries(extra)) if (normalisePresenterChord(code) === plain) return label;
for (const command of commands) {
if (command.id !== id && command.codes.some(code => presenterCodeChord(code) === plain)) return command.label;
}
}
return 'a reserved key';
}
return null;
}
function persist() { try { storage.setItem(store, JSON.stringify(overrides)); } catch {} }
try {
const saved = JSON.parse(storage.getItem(store) || '{}');
for (const command of commands) {
const value = saved[command.id];
if (value && !taken(value.chord, command.id)) overrides[command.id] = {
chord: normalisePresenterChord(value.chord), entryId: command.id.startsWith('palette.') ? command.id.slice(8)
: typeof value.entryId === 'string' ? value.entryId : undefined
};
}
const old = storage.getItem('talkweaver:presenter:pointer-shortcut');
if (old && !overrides['presenter.pointer'] && !taken(old, 'presenter.pointer')) {
overrides['presenter.pointer'] = { chord: normalisePresenterChord(old), entryId: 'pointer' };
persist();
storage.removeItem('talkweaver:presenter:pointer-shortcut');
}
} catch {}
persist();
let dialog;
let previousFocus, focusFrame;
function recoverFocus() {
if (!dialog) return;
document.defaultView.cancelAnimationFrame(focusFrame);
focusFrame = document.defaultView.requestAnimationFrame(() => dialog?.focus());
}
function focusInside(event) {
if (dialog && !dialog.contains(event.target)) dialog.focus();
}
function record(event) {
if (!dialog) return;
event.preventDefault();
event.stopImmediatePropagation();
if (event.key === 'Escape') { close(); return; }
dialog.record(event);
}
function close() {
document?.removeEventListener('keydown', record, true);
document?.removeEventListener('focusin', focusInside, true);
document?.defaultView.removeEventListener('pagehide', close);
document?.defaultView.removeEventListener('blur', recoverFocus);
document?.defaultView.cancelAnimationFrame(focusFrame);
dialog?.remove(); dialog = null;
previousFocus?.focus?.();
}
function rebind(id, label, entryId) {
close();
dialog = document.createElement('dialog');
dialog.className = 'tw-shortcut-rebind';
dialog.setAttribute('aria-modal', 'true');
dialog.id = 'presenterRebind';
dialog.setAttribute('role', 'dialog');
dialog.setAttribute('aria-label', `Rebind ${label}`);
dialog.tabIndex = -1;
const prompt = document.createElement('p');
prompt.textContent = `Press a new key for ${label}. Esc cancels.`;
const status = document.createElement('p');
status.setAttribute('role', 'status');
const reset = document.createElement('button');
reset.textContent = 'Reset to default';
reset.type = 'button';
const cancel = document.createElement('button');
cancel.textContent = 'Cancel';
cancel.type = 'button';
function save(next) {
if (next) overrides[id] = { chord: next, entryId };
else delete overrides[id];
persist();
close();
onChange();
}
reset.addEventListener('click', () => save(null));
cancel.addEventListener('click', close);
dialog.append(prompt, status, reset, cancel);
previousFocus = document.activeElement;
document.body.append(dialog);
if (typeof dialog.showModal === 'function') dialog.showModal();
else dialog.setAttribute('open', '');
dialog.focus();
dialog.record = event => {
const next = presenterChord(event);
if (!next) { status.textContent = 'That key is reserved. Choose another.'; return; }
const owner = taken(next, id);
if (owner) { status.textContent = `That key is already used by ${owner}. Choose another.`; return; }
save(next);
};
document.addEventListener('keydown', record, true);
document.addEventListener('focusin', focusInside, true);
document.defaultView.addEventListener('blur', recoverFocus);
document.defaultView.addEventListener('pagehide', close, { once: true });
}
return {
key(id, fallback = '') {
const chord = overrides[id]?.chord;
if (!chord) return fallback;
const defaults = commands.find(command => command.id === id)?.keys ?? fallback;
return chord !== defaults ? [chord, defaults].filter(Boolean).join(' / ') : defaults;
},
taken, rebind,
match(event) {
if (event.target?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable=false])')) return null;
const chord = presenterChord(event);
for (const [id, value] of Object.entries(overrides)) {
if (value.chord === chord) return { id, entryId: value.entryId };
}
return null;
}
};
}
function imageStepStops(enabled, entries) {
if (!enabled || !Array.isArray(entries)) return [];
const stops = [];
entries.forEach(function (entry, index) {
if (entry && entry.kind !== 'video' && !entry.isQr) stops.push(index);
});
if (stops.length === 1 && entries[stops[0]].fullBleed) return [];
return stops;
}
function imageStepRest(stops, where) {
const after = where === 'after' && Array.isArray(stops) && stops.length > 0;
return { open: false, index: after ? stops[stops.length - 1] + 1 : 0 };
}
function imageStepForward(input) {
const stops = (input && input.stops) || [];
if (stops.length === 0) return null;
const lightbox = (input && input.lightbox) || {};
const index = Math.max(0, Number(lightbox.index) || 0);
if (lightbox.open) {
const next = stops.find(function (stop) { return stop > index; });
return next === undefined ? imageStepRest(stops, 'after') : { open: true, index: next };
}
if (index > 0) return null;
if ((Number(input.stepsRemaining) || 0) > 0) return null;
return { open: true, index: stops[0] };
}
function imageStepBackward(input) {
const stops = (input && input.stops) || [];
if (stops.length === 0) return null;
const lightbox = (input && input.lightbox) || {};
const index = Math.max(0, Number(lightbox.index) || 0);
if (lightbox.open) {
let previous;
stops.forEach(function (stop) { if (stop < index) previous = stop; });
return previous === undefined ? imageStepRest(stops, 'before') : { open: true, index: previous };
}
if (index > 0) return { open: true, index: stops[stops.length - 1] };
return null;
}
const EMPH_STEP_SELECTOR = "[data-emph-step]";
const MEDIA_STEP_SELECTOR = "[data-play-on-next]";
function emphasisSteppedMode(mode) {
return mode === 'reveal' || mode === 'focus';
}
function stepUnitIsBlock(unit) {
if (!unit) return true;
if (unit.kind === 'emphasis') return false;
return !(unit.kind === 'media' && unit.parent != null);
}
function emphasisStepMax(units, mode) {
const list = Array.isArray(units) ? units : [];
let blocks = 0;
let inline = 0;
list.forEach(function (unit) {
if (stepUnitIsBlock(unit)) blocks += 1;
if (unit && (unit.kind === 'emphasis' || unit.kind === 'media')) inline += 1;
});
if (!emphasisSteppedMode(mode)) return inline;
return list.length + (blocks > 1 ? 1 : 0);
}
function emphasisStepStates(units, mode, step) {
const list = Array.isArray(units) ? units : [];
const max = emphasisStepMax(list, mode);
const at = Math.max(0, Math.min(max, Number(step) || 0));
if (!emphasisSteppedMode(mode)) {
let seen = 0;
return list.map(function (unit) {
if (unit && unit.kind === 'media') seen += 1;
if (!unit || unit.kind !== 'emphasis') return null;
seen += 1;
return seen <= at ? 'on' : 'off';
});
}
const full = at >= max && at >= list.length;
const waiting = mode === 'focus' ? 'fuzzy' : 'hidden';
let current = -1;
list.forEach(function (unit, i) { if (i < at && stepUnitIsBlock(unit)) current = i; });
return list.map(function (unit, i) {
if (unit && unit.kind === 'emphasis') {
// A span inside a block that has not appeared stays off, wherever the list puts it.
const parentShown = unit.parent == null || unit.parent < at;
return i < at && parentShown ? 'on' : 'off';
}
if (!stepUnitIsBlock(unit)) return null;
if (full) return 'full';
if (i >= at) return waiting;
return i === current ? 'current' : 'soft';
});
}
function mediaStepStates(units, mode, step, movedOn) {
const list = Array.isArray(units) ? units : [];
// A step past the last: the slide was entered backwards and is finished (mediaStepDone).
if (!movedOn && (Number(step) || 0) > emphasisStepMax(list, mode)) movedOn = true;
if (movedOn) return list.map(function (unit) { return unit && unit.kind === 'media' ? 'played' : null; });
const at = Math.max(0, Math.min(emphasisStepMax(list, mode), Number(step) || 0));
const stepped = emphasisSteppedMode(mode);
let seen = 0;
return list.map(function (unit, i) {
const counts = stepped || (unit && (unit.kind === 'emphasis' || unit.kind === 'media'));
if (counts) seen += 1;
if (!unit || unit.kind !== 'media') return null;
return seen === at ? 'playing' : seen < at ? 'played' : 'waiting';
});
}
function mediaStepPlaying(units, mode, step, movedOn) {
return mediaStepStates(units, mode, step, movedOn).indexOf('playing');
}
function mediaStepDone(units, mode) {
const max = emphasisStepMax(units, mode);
return mediaStepPlaying(units, mode, max) >= 0 ? max + 1 : max;
}
function mediaStepQuiet(units, mode, step) {
let at = Math.max(0, Math.min(emphasisStepMax(units, mode), Number(step) || 0));
while (at > 0 && mediaStepPlaying(units, mode, at) >= 0) at -= 1;
return at;
}
function emphasisWireFocus(units, mode, step) {
// Finished after a backwards arrival: one past the no-mode range, whatever the mode.
if ((Number(step) || 0) > emphasisStepMax(units, mode) && mediaStepDone(units, mode) > emphasisStepMax(units, mode)) {
return { kind: 'reveal', step: emphasisStepMax(units, 'reveal') + 1 + emphasisStepMax(units, null) + 1 };
}
const at = Math.max(0, Math.min(emphasisStepMax(units, mode), Number(step) || 0));
if (emphasisSteppedMode(mode)) return { kind: mode, step: at };
return { kind: 'reveal', step: emphasisStepMax(units, 'reveal') + 1 + at };
}
function emphasisFromWire(units, focus) {
if (!focus || !emphasisSteppedMode(focus.kind)) return null;
const step = Math.max(0, Number(focus.step) || 0);
const top = emphasisStepMax(units, focus.kind);
if (step > top) return { mode: null, step: Math.min(mediaStepDone(units, null), step - top - 1) };
return { mode: focus.kind, step: step };
}
function mediaStepHolder(file, listed) {
let node = file.parentElement;
while (node) {
if (listed.has(node) && !node.hasAttribute('data-emph-step') && !node.hasAttribute('data-play-on-next')) return node;
node = node.parentElement;
}
return null;
}
function mediaStepFile(el, listed) {
if (el.hasAttribute('data-emph-step')) return null;
if (el.hasAttribute('data-play-on-next')) return el;
const inside = el.querySelectorAll('[data-play-on-next]');
for (let i = 0; i < inside.length; i += 1) {
if (!listed.has(inside[i]) && mediaStepHolder(inside[i], listed) === el) return inside[i];
}
return null;
}
function emphasisStepElements(scope, blockSelector, isVisible) {
if (!scope) return [];
const selector = (blockSelector ? blockSelector + ',' : '') + EMPH_STEP_SELECTOR + ',' + MEDIA_STEP_SELECTOR;
const found = Array.from(scope.querySelectorAll(selector)).filter(function (el) {
return typeof isVisible === 'function' ? isVisible(el) : true;
});
const listed = new Set(found);
const taken = new Set();
return found.filter(function (el) {
if (!el.hasAttribute('data-play-on-next')) return true;
const holder = mediaStepHolder(el, listed);
if (!holder || taken.has(holder)) return true;
taken.add(holder);
listed.delete(el);
return false;
});
}
function emphasisStepUnits(els) {
const listed = new Set(els);
const blockAt = new Map();
function holderOf(el) {
let node = el.parentElement;
while (node && !blockAt.has(node)) node = node.parentElement;
return node ? blockAt.get(node) : null;
}
return els.map(function (el, i) {
if (el.hasAttribute('data-emph-step')) return { kind: 'emphasis', parent: holderOf(el) };
const parent = el.hasAttribute('data-play-on-next') ? holderOf(el) : null;
blockAt.set(el, i);
return { kind: mediaStepFile(el, listed) ? 'media' : 'block', parent: parent };
});
}
function mediaStepFiles(els) {
const listed = new Set(els);
return els.map(function (el) { return mediaStepFile(el, listed); });
}
function paintEmphasisStates(root, els, states) {
const live = new Set();
els.forEach(function (el, i) {
if (!el.hasAttribute('data-emph-step')) return;
live.add(el);
const want = states[i] === 'off' ? 'off' : 'on';
if (el.getAttribute('data-emph-state') !== want) el.setAttribute('data-emph-state', want);
});
if (!root) return;
root.querySelectorAll('[data-emph-state]').forEach(function (el) {
if (!live.has(el)) el.removeAttribute('data-emph-state');
});
}
function stampEmphasisPlainWeight(root, styleOf) {
if (!root || typeof styleOf !== 'function') return;
root.querySelectorAll('strong[data-emph-step]').forEach(function (el) {
if (!el.parentElement || el.style.getPropertyValue('--emph-plain-weight')) return;
const weight = styleOf(el.parentElement).fontWeight;
if (weight) el.style.setProperty('--emph-plain-weight', String(weight));
});
}
function simTypingCharsPerSecond() {
return 40 * 4;
}
function simTypedChars(elapsedMs, cps) {
const rate = Number(cps) > 0 ? Number(cps) : simTypingCharsPerSecond();
const elapsed = Number(elapsedMs);
if (!Number.isFinite(elapsed) || elapsed <= 0) return 0;
return Math.floor((elapsed * rate) / 1000);
}
function simTypingStates(lengths, chars) {
const typed = Math.max(0, Math.floor(Number(chars) || 0));
const out = [];
let start = 0;
for (const raw of lengths || []) {
const length = Math.max(0, Math.floor(Number(raw) || 0));
const end = start + length;
if (typed < start) out.push({ state: 'wait', shown: 0 });
else if (typed >= end) out.push({ state: 'done', shown: length });
else out.push({ state: 'typing', shown: typed - start });
start = end;
}
return out;
}
function normaliseSimType(value) {
if (!value || typeof value !== 'object' || typeof value.slideId !== 'string' || !value.slideId) return null;
const from = Math.floor(Number(value.from));
const to = Math.floor(Number(value.to));
const at = Number(value.at);
if (!Number.isFinite(from) || from < -1 || !Number.isFinite(to) || to < 0 || !Number.isFinite(at)) return null;
return { slideId: value.slideId, from, to, at, done: Boolean(value.done) };
}
function simTypingUnits(slide, move) {
const root = slide && slide.querySelector ? slide.querySelector('.sim:not(.sim-static)') : null;
if (!root || !move) return [];
const terminal = root.classList.contains('sim-terminal');
const stream = root.getAttribute('data-stream') === 'on';
if (!terminal && !stream) return [];
const steps = Array.from(root.querySelectorAll('.sim-step'));
const shown = move.stepped ? steps.slice(0, Math.max(0, Math.min(steps.length, move.to))) : steps;
let units = shown.slice(Math.max(0, move.from));
units = units.sort((a, b) => (a === b ? 0 : a.compareDocumentPosition(b) & 4 ? -1 : 1));
const TEXT = 4;
return units.map((el) => {
const nodes = [];
const walker = el.ownerDocument.createTreeWalker(el, TEXT);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const parent = node.parentElement;
if (!parent || !node.data) continue;
if (parent.closest('.sim-toggle, [aria-hidden="true"], .sim-typing-rest, .is-closed .sim-body')) continue;
if (!terminal && !parent.closest('.sim-answer-text > p, .sim-reasoning-text')) continue;
nodes.push(node);
}
return { el, nodes, length: nodes.reduce((sum, node) => sum + node.data.length, 0) };
});
}
function createSimTyping(options) {
const now = options.now;
const frame = options.frame;
const cancelFrame = options.cancelFrame || function () {};
const cps = options.cps || simTypingCharsPerSecond();
let job = null;
let handle = 0;
function keyOf(slide, move) {
return move ? [move.slideId, move.from, move.to, move.at, move.stepped ? 1 : 0].join(':') : '';
}
function showNode(record, count) {
const full = record.full;
let k = Math.max(0, Math.min(full.length, count));
// Never split a surrogate pair.
if (k > 0 && k < full.length) {
const code = full.charCodeAt(k - 1);
if (code >= 0xd800 && code <= 0xdbff) k += 1;
}
if (record.node.data !== full.slice(0, k)) record.node.data = full.slice(0, k);
if (k >= full.length) {
if (record.rest) { record.rest.remove(); record.rest = null; }
return;
}
if (!record.rest) {
record.rest = record.node.ownerDocument.createElement('span');
record.rest.className = 'sim-typing-rest';
record.node.after(record.rest);
}
if (record.rest.textContent !== full.slice(k)) record.rest.textContent = full.slice(k);
}
function showUnit(unit, state, shown) {
unit.el.classList.toggle('sim-typing-wait', state === 'wait');
unit.el.classList.toggle('sim-typing', state === 'typing');
let left = state === 'typing' ? shown : Infinity;
for (const record of unit.records) {
showNode(record, left);
left = Math.max(0, left - record.full.length);
}
}
function restore() {
if (handle) { cancelFrame(handle); handle = 0; }
if (!job) return;
for (const unit of job.units) showUnit(unit, 'done', 0);
job = null;
}
function paint() {
handle = 0;
if (!job) return;
const chars = simTypedChars(now() - job.at, cps);
if (chars >= job.total) { restore(); return; }
const states = simTypingStates(job.units.map((unit) => unit.length), chars);
job.units.forEach((unit, i) => showUnit(unit, states[i].state, states[i].shown));
handle = frame(paint);
}
function lengthOf(slide, move) {
if (job && job.slide === slide && job.key === keyOf(slide, move)) return job.total;
return simTypingUnits(slide, move).reduce((sum, unit) => sum + unit.length, 0);
}
return {
sync(slide, move) {
if (!slide || !move || move.done) { restore(); return; }
const key = keyOf(slide, move);
if (job && job.slide === slide && job.key === key) { if (!handle) paint(); return; }
restore();
const units = simTypingUnits(slide, move).map((unit) => ({
el: unit.el,
length: unit.length,
records: unit.nodes.map((node) => ({ node, full: node.data, rest: null }))
}));
const total = units.reduce((sum, unit) => sum + unit.length, 0);
if (!total) return;
job = { slide, key, at: move.at, units, total };
paint();
},
busy(slide, move) {
if (!slide || !move || move.done) return false;
return simTypedChars(now() - move.at, cps) < lengthOf(slide, move);
},
stop: restore
};
}
function createMediaStepController(options) {
const canPlay = (options && options.canPlay) || function () { return true; };
const audioChips = (options && options.audioChips) || null;
const playerOf = (options && options.playerOf) || function (file) { return file.querySelector('video, audio'); };
let live = null; // the slide whose files carry a state now
function isChip(file) { return file.classList.contains('slide-audio'); }
function attempt(player) {
try { return Promise.resolve(player.play()); } catch (error) { return Promise.reject(error); }
}
function clearTap(file) {
const tap = file.querySelector(':scope > .media-step-tap');
if (tap) tap.remove();
if (file.dataset.mediaStepMuted) {
const player = playerOf(file);
if (player) player.muted = false;
delete file.dataset.mediaStepMuted;
}
}
function showTap(file, label) {
if (file.querySelector(':scope > .media-step-tap')) return;
const tap = document.createElement('button');
tap.type = 'button';
tap.className = 'media-step-tap';
tap.textContent = label;
tap.addEventListener('click', function (event) { event.stopPropagation(); tapped(file); });
// Space and Enter press the focused control (the browser turns them into its click). The deck
// reads both as Next, so they stop here; every other key (arrows, Esc) goes on to the deck.
const ownKey = function (event) { if (event.key === ' ' || event.key === 'Enter') event.stopPropagation(); };
tap.addEventListener('keydown', ownKey);
tap.addEventListener('keyup', ownKey);
file.appendChild(tap);
}
// The tap is the gesture the browser asked for: sound on for a video, the first start for a chip.
function tapped(file) {
const player = playerOf(file);
if (!player) return;
clearTap(file);
file.dataset.mediaStepStarted = '1';
attempt(player).catch(function () { delete file.dataset.mediaStepStarted; });
}
function start(file) {
const player = playerOf(file);
if (!player) return;
file.dataset.mediaStepStarted = '1';
if (!player.paused && !player.ended) return;
try { if (player.currentTime > 0) player.currentTime = 0; } catch (error) { /* not seekable yet */ }
attempt(player).catch(function (error) {
if (file.dataset.mediaStep !== 'playing') return; // the step moved on while the start was pending
const refused = Boolean(error) && error.name === 'NotAllowedError';
if (refused && !isChip(file) && !player.muted) {
player.muted = true;
file.dataset.mediaStepMuted = '1';
attempt(player).then(function () {
if (file.dataset.mediaStep === 'playing') showTap(file, 'Tap for sound');
}, function () {
player.muted = false;
delete file.dataset.mediaStepMuted;
delete file.dataset.mediaStepStarted;
});
return;
}
delete file.dataset.mediaStepStarted;
if (refused && isChip(file)) showTap(file, 'Tap to play');
});
}
function pass(file) {
delete file.dataset.mediaStepStarted;
clearTap(file);
const player = playerOf(file);
if (isChip(file) && audioChips) { audioChips.finish(file); return; }
if (!player) return;
if (!player.paused) { player.pause(); return; }
// Never started here: show the last frame, now or once the length is known. No load() and no
// play(): the element fetches its own metadata.
if (player.currentTime > 0 || isChip(file)) return;
const toEnd = function () {
if (file.dataset.mediaStep !== 'played' || !isFinite(player.duration) || player.duration <= 0) return;
try { player.currentTime = player.duration; } catch (error) { /* not seekable yet */ }
};
if (isFinite(player.duration) && player.duration > 0) toEnd();
else player.addEventListener('loadedmetadata', toEnd, { once: true });
}
function rewind(file) {
delete file.dataset.mediaStepStarted;
clearTap(file);
const player = playerOf(file);
if (isChip(file) && audioChips) { audioChips.stop(file); return; }
if (!player) return;
if (!player.paused) player.pause();
try { if (player.currentTime > 0) player.currentTime = 0; } catch (error) { /* not seekable yet */ }
}
function set(file, next) {
const was = file.dataset.mediaStep || 'waiting';
if (next === 'playing') {
file.dataset.mediaStep = 'playing';
if (!file.dataset.mediaStepStarted) start(file);
return;
}
file.dataset.mediaStep = next;
if (next !== was) { if (next === 'played') pass(file); else rewind(file); }
}
function release(slide) {
slide.querySelectorAll('[data-media-step]').forEach(function (file) {
// Whatever its step: a file played by hand before its step is still 'waiting', and it too
// goes back to its start, so the slide returns on the first frame.
const player = playerOf(file);
const touched = Boolean(player) && (!player.paused || player.currentTime > 0);
if (file.dataset.mediaStep !== 'waiting' || touched) rewind(file);
file.removeAttribute('data-media-step');
});
}
return {
/**
* slide is the one on show; files[i] is a {play-on-next} file on it and states[i] its state
* at the step ('waiting' | 'playing' | 'played'; a null entry in either is skipped).
* Every other file on the slide is 'waiting', and the files of the slide shown before are
* stopped and rewound.
*/
apply(slide, files, states) {
if (!canPlay()) return;
if (live && live !== slide) { release(live); live = null; }
if (!slide) return;
const all = slide.querySelectorAll('[data-play-on-next]');
if (all.length === 0) return;
live = slide;
const want = new Map();
(files || []).forEach(function (file, i) { if (file && states[i]) want.set(file, states[i]); });
// The chips' own events paint their state (runtime/audio-chip.js); nothing autoplays here.
if (audioChips && slide.querySelector('.slide-audio[data-play-on-next]')) audioChips.enter(slide, false);
all.forEach(function (file) { set(file, want.get(file) || 'waiting'); });
}
};
}
function paintMediaStepMarks(files, states, icon) {
(files || []).forEach(function (file, i) {
const state = file ? states[i] : null;
if (!state) return;
file.setAttribute('data-media-step', state);
const label = state === 'waiting' ? 'plays on Next' : state === 'playing' && !file.classList.contains('slide-audio') ? 'playing' : '';
if (!label) return;
const mark = document.createElement('span');
mark.className = 'media-step-mark';
const glyph = typeof icon === 'function' ? icon(state) : null;
if (glyph) mark.appendChild(glyph);
const text = document.createElement('span');
text.textContent = label;
mark.appendChild(text);
file.appendChild(mark);
});
}
function embedLimits() {
if (embedLimits.cache) return embedLimits.cache;
// A page may ask the deck to STEP, never to jump: no Home, no End (they stay the page's own keys).
const navKeys = ['ArrowRight', 'ArrowLeft', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', ' '];
embedLimits.cache = Object.freeze({
tag: 'embed',
version: 1,
tokenBytes: 16, // design 5.3: 16 bytes from crypto.getRandomValues
tokenLength: 32, // those bytes as lower-case hex
valueMax: 4096, // design 5.2: input / change value
keyMax: 32, // design 5.2: keydown key
codeMax: 32, // design 5.2: keydown code
idMax: 128, // design 5.2: element id
tagMax: 32, // chosen: longest tag name carried
pathMax: 64, // design 5.2: entries in a path
pathIndexMax: 65535, // design 5.2: largest path entry
fractionSlack: 1e-6, // chosen: rounding tolerance outside 0..1 before a fraction is refused
ratePerSecond: 60, // design 5.5
rateBurst: 120, // design 5.5
dropLimit: 2000, // design 5.5: drops within the window that stop mirroring
dropWindowMs: 10000, // design 5.5
scrollCoalesceMs: 50, // design 5.5: newest position per element per window
scrollPendingMax: 32, // chosen: distinct scrolling elements held per frame per window
scrollReplaceAllowance: 64, // chosen: superseded scroll messages per window before they count as drops
keyRateMax: 5, // design 5.5 (lowered from 20 after review): fewer than this many key messages in the window
keyRateWindowMs: 1000, // design 5.5
helloMax: 8, // chosen: `ready` messages answered per activation
navKeys: Object.freeze(navKeys), // design 5.5: the stepping keys
forwardKeys: Object.freeze(navKeys.concat(['Escape'])), // design 5.6
eventKinds: Object.freeze(['click', 'input', 'change', 'keydown', 'scroll']),
roles: Object.freeze(['capture', 'replay', 'none'])
});
return embedLimits.cache;
}
function embedKindFields(kind) {
switch (kind) {
case 'ready': return [];
case 'hello': return ['t', 'role'];
case 'key': return ['t', 'key'];
case 'click': return ['t', 'el'];
case 'input': return ['t', 'el', 'value', 'checked'];
case 'change': return ['t', 'el', 'value', 'checked'];
case 'keydown': return ['t', 'el', 'key', 'code'];
case 'scroll': return ['t', 'el', 'fx', 'fy'];
default: return null;
}
}
function embedPlainFields(value, allowed) {
if (value === null || typeof value !== 'object') return null;
const proto = Object.getPrototypeOf(value);
if (proto !== Object.prototype && proto !== null) return null;
const keys = Reflect.ownKeys(value);
if (keys.length > allowed.length) return null;
const out = Object.create(null);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
if (typeof key !== 'string' || allowed.indexOf(key) < 0) return null;
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return null;
out[key] = descriptor.value;
}
return out;
}
function embedIsToken(value) {
if (typeof value !== 'string' || value.length !== embedLimits().tokenLength) return false;
for (let i = 0; i < value.length; i += 1) {
const c = value.charCodeAt(i);
if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) return false;
}
return true;
}
function embedTokenFromBytes(bytes) {
const limits = embedLimits();
if (!bytes || typeof bytes.length !== 'number' || bytes.length !== limits.tokenBytes) throw new Error('embed: token needs ' + limits.tokenBytes + ' random bytes');
let out = '';
for (let i = 0; i < bytes.length; i += 1) {
const byte = bytes[i];
if (typeof byte !== 'number' || byte < 0 || byte > 255 || Math.floor(byte) !== byte) throw new Error('embed: token bytes must be bytes');
out += (byte < 16 ? '0' : '') + byte.toString(16);
}
return out;
}
function embedIsText(value, max, allowEmpty) {
return typeof value === 'string' && value.length <= max && (allowEmpty === true || value.length > 0);
}
function embedIsTagName(value) {
if (!embedIsText(value, embedLimits().tagMax, false)) return false;
for (let i = 0; i < value.length; i += 1) {
const c = value.charCodeAt(i);
const ok = (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 45 || c === 95 || c === 46 || c === 58;
if (!ok) return false;
}
return true;
}
function embedIsIdText(value) {
if (!embedIsText(value, embedLimits().idMax, false)) return false;
for (let i = 0; i < value.length; i += 1) {
const c = value.charCodeAt(i);
if (c < 32 || c === 127) return false;
}
return true;
}
function embedReadFraction(value) {
if (typeof value !== 'number' || value !== value || value === Infinity || value === -Infinity) return null;
const slack = embedLimits().fractionSlack;
if (value < -slack || value > 1 + slack) return null;
return value < 0 ? 0 : value > 1 ? 1 : value;
}
function embedReadPath(value) {
const limits = embedLimits();
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) return null;
const lengthDescriptor = Object.getOwnPropertyDescriptor(value, 'length');
const length = lengthDescriptor ? lengthDescriptor.value : -1;
if (typeof length !== 'number' || length < 0 || length > limits.pathMax) return null;
if (Reflect.ownKeys(value).length !== length + 1) return null; // a hole, or a key that is not an index
const out = [];
for (let i = 0; i < length; i += 1) {
const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, 'value')) return null;
const entry = descriptor.value;
if (typeof entry !== 'number' || entry < 0 || entry > limits.pathIndexMax || Math.floor(entry) !== entry) return null;
out.push(entry);
}
return out;
}
function embedReadAddress(value, kind) {
const fields = embedPlainFields(value, ['path', 'tag', 'id', 'px', 'py']);
if (!fields) return null;
const path = embedReadPath(fields.path);
if (!path) return null;
const hasId = 'id' in fields;
const hasPoint = 'px' in fields || 'py' in fields;
if (fields.tag === '') {
// The document itself: scroll only, and nothing else in the address.
if (kind !== 'scroll' || path.length !== 0 || hasId || hasPoint) return null;
return { path: path, tag: '' };
}
if (!embedIsTagName(fields.tag)) return null;
if (hasId && !embedIsIdText(fields.id)) return null;
if (!hasPoint) return hasId ? { path: path, tag: fields.tag, id: fields.id } : { path: path, tag: fields.tag };
if (kind !== 'click') return null;
const px = embedReadFraction(fields.px);
const py = embedReadFraction(fields.py);
if (px === null || py === null) return null;
return hasId ? { path: path, tag: fields.tag, id: fields.id, px: px, py: py } : { path: path, tag: fields.tag, px: px, py: py };
}
function embedReadMessage(message) {
const limits = embedLimits();
if (message === null || typeof message !== 'object') return null;
const head = embedPlainFields(message, ['tw', 'v', 'k', 't', 'role', 'key', 'el', 'value', 'checked', 'code', 'fx', 'fy']);
if (!head || head.tw !== limits.tag || head.v !== limits.version || typeof head.k !== 'string') return null;
const kind = head.k;
const names = embedKindFields(kind);
if (!names) return null;
const fields = embedPlainFields(message, ['tw', 'v', 'k'].concat(names));
if (!fields) return null;
if (kind === 'ready') return { tw: limits.tag, v: limits.version, k: 'ready' };
if (!embedIsToken(fields.t)) return null;
const token = fields.t;
if (kind === 'hello') {
if (typeof fields.role !== 'string' || limits.roles.indexOf(fields.role) < 0) return null;
return { tw: limits.tag, v: limits.version, t: token, k: 'hello', role: fields.role };
}
if (kind === 'key') {
if (typeof fields.key !== 'string' || limits.forwardKeys.indexOf(fields.key) < 0) return null;
return { tw: limits.tag, v: limits.version, t: token, k: 'key', key: fields.key };
}
const el = embedReadAddress(fields.el, kind);
if (!el) return null;
if (kind === 'click') return { tw: limits.tag, v: limits.version, t: token, k: 'click', el: el };
if (kind === 'input' || kind === 'change') {
const hasValue = 'value' in fields;
const hasChecked = 'checked' in fields;
if (hasValue === hasChecked) return null; // exactly one of the two
if (hasChecked) {
if (typeof fields.checked !== 'boolean') return null;
return { tw: limits.tag, v: limits.version, t: token, k: kind, el: el, checked: fields.checked };
}
if (!embedIsText(fields.value, limits.valueMax, true)) return null;
return { tw: limits.tag, v: limits.version, t: token, k: kind, el: el, value: fields.value };
}
if (kind === 'keydown') {
if (!embedIsText(fields.key, limits.keyMax, false) || !embedIsText(fields.code, limits.codeMax, true)) return null;
return { tw: limits.tag, v: limits.version, t: token, k: 'keydown', el: el, key: fields.key, code: fields.code };
}
if (kind === 'scroll') {
const fx = embedReadFraction(fields.fx);
const fy = embedReadFraction(fields.fy);
if (fx === null || fy === null) return null;
return { tw: limits.tag, v: limits.version, t: token, k: 'scroll', el: el, fx: fx, fy: fy };
}
return null;
}
function embedValidateMessage(message) {
try {
const out = embedReadMessage(message);
if (!out) return null;
if (typeof structuredClone === 'function') structuredClone(message);
return out;
} catch (error) {
return null;
}
}
function embedBuildMessage(kind, token, fields) {
const limits = embedLimits();
const names = embedKindFields(kind);
if (!names) return null;
const message = { tw: limits.tag, v: limits.version, k: kind };
for (let i = 0; i < names.length; i += 1) {
const name = names[i];
if (name === 't') message.t = token;
else if (fields && fields[name] !== undefined) message[name] = fields[name];
}
return embedValidateMessage(message);
}
function embedEventDescription(message) {
if (!message || embedLimits().eventKinds.indexOf(message.k) < 0) return null;
switch (message.k) {
case 'click': return { k: 'click', el: message.el };
case 'keydown': return { k: 'keydown', el: message.el, key: message.key, code: message.code };
case 'scroll': return { k: 'scroll', el: message.el, fx: message.fx, fy: message.fy };
default:
return message.checked !== undefined ? { k: message.k, el: message.el, checked: message.checked } : { k: message.k, el: message.el, value: message.value };
}
}
function embedMessageFromDescription(token, description) {
try {
const fields = embedPlainFields(description, ['k', 'el', 'value', 'checked', 'key', 'code', 'fx', 'fy']);
if (!fields || typeof fields.k !== 'string' || embedLimits().eventKinds.indexOf(fields.k) < 0) return null;
if (typeof structuredClone === 'function') structuredClone(description);
return embedBuildMessage(fields.k, token, fields);
} catch (error) {
return null;
}
}
function embedAcceptsFromFrame(role, kind) {
if (kind === 'ready' || kind === 'key') return true;
return role === 'capture' && embedLimits().eventKinds.indexOf(kind) >= 0;
}
function embedSendsToFrame(role, kind) {
if (kind === 'hello') return true;
return role === 'replay' && embedLimits().eventKinds.indexOf(kind) >= 0;
}
function embedRoleForWindow(windowKind) {
return windowKind === 'presenter' ? 'capture' : windowKind === 'projector' ? 'replay' : 'none';
}
function embedKeyDecision(key, engaged, frameHasFocus, userActive, recentCount) {
const limits = embedLimits();
if (typeof key !== 'string' || limits.forwardKeys.indexOf(key) < 0) return false;
if (frameHasFocus !== true) return false;
if (typeof recentCount !== 'number' || !(recentCount < limits.keyRateMax)) return false;
if (key === 'Escape') return true;
return engaged === true && userActive === true;
}
function embedCreateLimiter(now) {
const limits = embedLimits();
return { tokens: limits.rateBurst, at: now, dropSlots: [], dropSlotAt: [], stopped: false };
}
function embedLimiterDrop(limiter, now) {
const limits = embedLimits();
if (limiter.stopped) return false;
const slotMs = 1000;
const slotCount = Math.ceil(limits.dropWindowMs / slotMs) + 1; // the window, plus the slot in progress
const slot = Math.floor(now / slotMs);
const index = ((slot % slotCount) + slotCount) % slotCount;
if (limiter.dropSlotAt[index] !== slot) { limiter.dropSlotAt[index] = slot; limiter.dropSlots[index] = 0; }
limiter.dropSlots[index] += 1;
let total = 0;
for (let i = 0; i < slotCount; i += 1) {
const at = limiter.dropSlotAt[i];
if (typeof at === 'number' && slot - at >= 0 && slot - at < slotCount) total += limiter.dropSlots[i];
}
if (total < limits.dropLimit) return false;
limiter.stopped = true;
return true;
}
function embedLimiterTake(limiter, now) {
const limits = embedLimits();
if (limiter.stopped) return false;
const elapsed = now > limiter.at ? now - limiter.at : 0;
limiter.tokens = Math.min(limits.rateBurst, limiter.tokens + (elapsed * limits.ratePerSecond) / 1000);
if (now > limiter.at) limiter.at = now;
if (limiter.tokens >= 1) { limiter.tokens -= 1; return true; }
embedLimiterDrop(limiter, now);
return false;
}
function embedElementTag(element) {
if (!element) return '';
if (typeof element.localName === 'string') return element.localName;
return typeof element.tagName === 'string' ? element.tagName.toLowerCase() : '';
}
function embedElementsWithId(doc, id) {
if (!embedIsIdText(id) || !doc || typeof doc.querySelectorAll !== 'function') return [];
return doc.querySelectorAll('[id="' + id.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]');
}
function embedDescribeElement(doc, element, point) {
const limits = embedLimits();
if (!doc || !element || element.nodeType !== 1) return null;
const tag = embedElementTag(element);
if (!embedIsTagName(tag)) return null;
const root = doc.documentElement;
let path = [];
let node = element;
let inBounds = true;
while (node !== root) {
const parent = node.parentElement;
if (!parent || path.length >= limits.pathMax) { inBounds = false; break; }
const index = Array.prototype.indexOf.call(parent.children, node);
if (index < 0 || index > limits.pathIndexMax) { inBounds = false; break; }
path.unshift(index);
node = parent;
}
let id = '';
if (typeof element.id === 'string' && element.id) {
const same = embedElementsWithId(doc, element.id);
if (same.length === 1 && same[0] === element) id = element.id;
}
if (!inBounds) {
if (!id) return null;
path = [];
}
const out = { path: path, tag: tag };
if (id) out.id = id;
if (point) {
const px = embedReadFraction(Math.min(1, Math.max(0, Number(point.x))));
const py = embedReadFraction(Math.min(1, Math.max(0, Number(point.y))));
if (px !== null && py !== null) { out.px = px; out.py = py; }
}
return out;
}
function embedResolveElement(doc, address) {
if (!doc || !address || !doc.documentElement) return null;
const root = doc.documentElement;
if (address.tag === '') return address.path.length === 0 ? (doc.scrollingElement || root) : null;
if (address.id !== undefined) {
const same = embedElementsWithId(doc, address.id);
if (same.length === 1 && embedElementTag(same[0]) === address.tag) return same[0];
}
let node = root;
for (let i = 0; i < address.path.length && node; i += 1) {
const children = node.children;
node = children && address.path[i] < children.length ? children[address.path[i]] : null;
}
if (node && embedElementTag(node) === address.tag) return node;
if (typeof address.px === 'number' && typeof address.py === 'number' && typeof doc.elementFromPoint === 'function') {
const view = doc.defaultView;
const width = view && typeof view.innerWidth === 'number' ? view.innerWidth : root.clientWidth;
const height = view && typeof view.innerHeight === 'number' ? view.innerHeight : root.clientHeight;
return doc.elementFromPoint(address.px * width, address.py * height) || null;
}
return null;
}
function embedScrollFractions(element) {
const rangeX = (element.scrollWidth || 0) - (element.clientWidth || 0);
const rangeY = (element.scrollHeight || 0) - (element.clientHeight || 0);
const fx = rangeX > 0 ? (element.scrollLeft || 0) / rangeX : 0;
const fy = rangeY > 0 ? (element.scrollTop || 0) / rangeY : 0;
return { fx: fx < 0 ? 0 : fx > 1 ? 1 : fx, fy: fy < 0 ? 0 : fy > 1 ? 1 : fy };
}
function embedApplyScroll(element, fx, fy) {
const rangeX = (element.scrollWidth || 0) - (element.clientWidth || 0);
const rangeY = (element.scrollHeight || 0) - (element.clientHeight || 0);
const left = rangeX > 0 ? fx * rangeX : 0;
const top = rangeY > 0 ? fy * rangeY : 0;
// At once, whatever the page's own scroll-behavior: the copy is sent every position on the way,
// and a smooth scroll restarted for each one would lag behind (and stand still in a hidden window).
if (typeof element.scrollTo === 'function') {
try { element.scrollTo({ left: left, top: top, behavior: 'instant' }); return; } catch (error) { /* an older engine: set the properties */ }
}
element.scrollLeft = left;
element.scrollTop = top;
}
function embedInputType(element) {
if (embedElementTag(element) !== 'input') return '';
const type = typeof element.type === 'string' && element.type ? element.type : 'text';
return type.toLowerCase();
}
function embedIsSensitiveField(element) {
if (!element || element.nodeType !== 1) return false;
if (embedInputType(element) === 'password') return true;
const attribute = typeof element.getAttribute === 'function' ? element.getAttribute('autocomplete') : null;
if (typeof attribute !== 'string') return false;
const tokens = attribute.toLowerCase().split(/\s+/);
for (let i = 0; i < tokens.length; i += 1) {
const token = tokens[i];
if (token === 'one-time-code' || token === 'current-password' || token === 'new-password' || token.indexOf('cc-') === 0) return true;
}
return false;
}
function embedIsTextField(element) {
if (!element || element.nodeType !== 1) return false;
if (element.isContentEditable === true) return true;
const tag = embedElementTag(element);
if (tag === 'textarea') return true;
if (tag !== 'input') return false;
const notTyped = ['checkbox', 'radio', 'button', 'submit', 'reset', 'range', 'color', 'file', 'image', 'hidden'];
return notTyped.indexOf(embedInputType(element)) < 0;
}
function embedKeepsKeys(element) {
return embedIsTextField(element) || embedElementTag(element) === 'select';
}
function embedFieldState(element) {
if (!element || element.nodeType !== 1) return null;
const tag = embedElementTag(element);
if (tag === 'input') {
const type = embedInputType(element);
if (type === 'checkbox' || type === 'radio') return { checked: element.checked === true };
if (type === 'file' || type === 'button' || type === 'submit' || type === 'reset' || type === 'image' || type === 'hidden') return null;
return typeof element.value === 'string' ? { value: element.value } : null;
}
if (tag === 'textarea' || tag === 'select') return typeof element.value === 'string' ? { value: element.value } : null;
return null;
}
function embedCreateChannel(options) {
const settings = options || {};
const limits = embedLimits();
const host = settings.window || (typeof window !== 'undefined' ? window : null);
const now = settings.now || function () { return host && host.performance ? host.performance.now() : Date.now(); };
const randomBytes = settings.randomBytes || function (count) { return host.crypto.getRandomValues(new Uint8Array(count)); };
// No userActivation API (an old browser): keys are never honoured there. Refusing is the safe side.
const isUserActive = settings.isUserActive || function () { return Boolean(host && host.navigator && host.navigator.userActivation && host.navigator.userActivation.isActive); };
const activeElement = settings.activeElement || function () { return host && host.document ? host.document.activeElement : null; };
const setTimer = settings.setTimer || function (fn, ms) { return host.setTimeout(fn, ms); };
const clearTimer = settings.clearTimer || function (handle) { host.clearTimeout(handle); };
const warn = settings.warn || function (text) { if (typeof console !== 'undefined') console.warn(text); };
const records = new Map(); // the frame's contentWindow → its record
function identity(record) { return { slide: record.slide, index: record.index, frame: record.frame }; }
function call(fn, record, value) {
if (typeof fn !== 'function') return;
try { fn(identity(record), value); } catch (error) { /* a consumer's error is not the frame's business */ }
}
function isCurrent(record) { return records.get(record.window) === record; }
function clearScroll(record) {
if (record.scrollTimer !== null) { clearTimer(record.scrollTimer); record.scrollTimer = null; }
record.scroll.clear();
}
// Every count goes through these two, so the moment a frame is cut off is seen exactly once.
function noteStop(record, wasStopped) {
if (wasStopped || !record.limiter.stopped) return;
clearScroll(record);
warn('TalkWeaver: an embedded page sent too many messages; copying it to the other screen is off until its slide is left.');
}
function drop(record, at) {
const wasStopped = record.limiter.stopped;
embedLimiterDrop(record.limiter, at);
noteStop(record, wasStopped);
}
function take(record, at) {
const wasStopped = record.limiter.stopped;
const allowed = embedLimiterTake(record.limiter, at);
noteStop(record, wasStopped);
return allowed;
}
function flushScroll(record) {
record.scrollTimer = null;
if (!isCurrent(record) || record.limiter.stopped) { record.scroll.clear(); return; }
const at = now();
const pending = Array.from(record.scroll.values());
record.scroll.clear();
record.scrollReplaced = 0;
record.scrollFlushedAt = at;
for (let i = 0; i < pending.length && !record.limiter.stopped; i += 1) {
if (take(record, at)) call(settings.onEvent, record, embedEventDescription(pending[i]));
}
}
function queueScroll(record, message, at) {
const key = message.el.path.join('.') + '|' + message.el.tag + '|' + (message.el.id === undefined ? '' : message.el.id);
if (record.scroll.has(key)) {
record.scrollReplaced += 1;
if (record.scrollReplaced > limits.scrollReplaceAllowance) {
drop(record, at);
if (record.limiter.stopped) return;
}
} else if (record.scroll.size >= limits.scrollPendingMax) {
drop(record, at);
return;
}
record.scroll.set(key, message);
if (record.scrollTimer !== null) return;
const wait = record.scrollFlushedAt + limits.scrollCoalesceMs - at;
if (wait <= 0) flushScroll(record);
else record.scrollTimer = setTimer(function () { flushScroll(record); }, wait);
}
function handleKey(record, message, at) {
const times = record.keyTimes;
while (times.length > 0 && at - times[0] >= limits.keyRateWindowMs) times.shift();
const recent = times.length;
times.push(at);
if (times.length > limits.keyRateMax) times.shift();
if (!embedKeyDecision(message.key, record.engaged === true, activeElement() === record.frame, isUserActive() === true, recent)) return;
call(settings.onKey, record, message.key);
}
/** The deck window's one `message` listener for embedded frames. */
function handleMessage(event) {
if (!event) return;
const source = event.source;
if (!source) return;
const record = records.get(source);
if (!record) return; // not a live embedded frame of this window
const data = event.data;
if (data === null || typeof data !== 'object') return; // a string (a video player's command) is not ours
const at = now();
const message = embedValidateMessage(data);
if (!message) { drop(record, at); return; }
if (message.k === 'ready') {
if (record.hellos >= limits.helloMax) { drop(record, at); return; }
record.hellos += 1;
const hello = embedBuildMessage('hello', record.token, { role: record.role });
// The target cannot be an origin: a sandboxed frame's origin is opaque.
try { record.window.postMessage(hello, '*'); } catch (error) { return; }
record.ready = true;
call(settings.onReady, record, undefined);
return;
}
if (message.t !== record.token || !embedAcceptsFromFrame(record.role, message.k)) { drop(record, at); return; }
if (message.k === 'key') { handleKey(record, message, at); return; }
if (record.limiter.stopped) return;
if (message.k === 'scroll') { queueScroll(record, message, at); return; }
if (take(record, at)) call(settings.onEvent, record, embedEventDescription(message));
}
function find(frame) {
let found = null;
records.forEach(function (record) { if (record.frame === frame) found = record; });
return found;
}
/**
* Start an activation of `frame`: a new token, a new limiter, a new record. Call it before the
* frame is given its document, so the agent's `ready` finds the record. `identity.role` is
* "capture", "replay" or "none" (anything else is "none"). False when the frame has no window
* (it is not in a document) or no token could be made; nothing is recorded then.
*/
function activate(frame, frameIdentity) {
deactivate(frame);
const target = frame ? frame.contentWindow : null;
if (!target) return false;
let token;
try { token = embedTokenFromBytes(randomBytes(limits.tokenBytes)); } catch (error) { return false; }
const given = frameIdentity || {};
const at = now();
records.set(target, {
frame: frame,
window: target,
slide: given.slide,
index: given.index,
role: limits.roles.indexOf(given.role) >= 0 ? given.role : 'none',
token: token,
limiter: embedCreateLimiter(at),
ready: false,
engaged: false,
hellos: 0,
keyTimes: [],
scroll: new Map(),
scrollTimer: null,
scrollFlushedAt: -Infinity,
scrollReplaced: 0
});
return true;
}
/** End the frame's activation. Messages still on their way from it are ignored. */
function deactivate(frame) {
const record = find(frame);
if (!record) return false;
clearScroll(record);
records.delete(record.window);
return true;
}
function deactivateAll() {
Array.from(records.values()).forEach(function (record) { clearScroll(record); });
records.clear();
}
/**
* Send an event description (as `onEvent` produced it in the other window) to the frame's agent.
* Only for a frame activated with role "replay" whose agent has announced itself. The
* description is validated again here. True when a message was posted.
*/
function deliver(frame, description) {
const record = find(frame);
if (!record || record.role !== 'replay' || !record.ready) return false;
const message = embedMessageFromDescription(record.token, description);
if (!message) return false;
try { record.window.postMessage(message, '*'); } catch (error) { return false; }
return true;
}
/**
* The deck has just observed a trusted press that the person aimed at this frame (Interact with
* E or the chip, a click on the presenter's Current pane). Only the deck calls this; no message
* from a frame can. From now until `disengage`, or until the frame is deactivated, a stepping
* key the frame forwards may be honoured.
*/
function engage(frame) {
const record = find(frame);
if (!record) return false;
record.engaged = true;
return true;
}
/** The person has left the page (Escape, a press elsewhere in the deck). */
function disengage(frame) {
const record = find(frame);
if (record) record.engaged = false;
}
function disengageAll() {
records.forEach(function (record) { record.engaged = false; });
}
/** For the deck and for tests: null when the frame is not live. Never includes the token. */
function status(frame) {
const record = find(frame);
return record ? { slide: record.slide, index: record.index, role: record.role, ready: record.ready, stopped: record.limiter.stopped, engaged: record.engaged } : null;
}
function dispose() {
deactivateAll();
if (host && settings.listen !== false && typeof host.removeEventListener === 'function') host.removeEventListener('message', handleMessage);
}
if (host && settings.listen !== false && typeof host.addEventListener === 'function') host.addEventListener('message', handleMessage);
return { activate: activate, deactivate: deactivate, deactivateAll: deactivateAll, deliver: deliver, engage: engage, disengage: disengage, disengageAll: disengageAll, status: status, handleMessage: handleMessage, dispose: dispose };
}
function embedCreateFocusGuard(options) {
const settings = options || {};
const host = settings.window || window;
const doc = host.document;
const channel = settings.channel;
const livePresent = settings.livePresent || function () { return false; };
const inUse = settings.inUse || function () { return null; };
const watchMs = settings.watchMs || 200;
const restoreMs = settings.restoreMs || 400;
const grabLimit = settings.grabLimit || 10;
const grabWindowMs = settings.grabWindowMs || 2000;
const grabGapMs = settings.grabGapMs || 20;
const pressGraceMs = 100;
const now = function () { return host.performance.now(); };
// The person's own presses in this document. `pressing` is true for the rest of the turn in
// which one arrived: a focus change in that turn is theirs. `pressCount` lets a deferred
// give-back see that a press came after it was scheduled.
let pressCount = 0;
let pressing = false;
let pressedAt = -Infinity;
// What this window can know of a press INSIDE a frame (it receives no event for one): the frame
// the pointer is over (boundary events arrive here), and, for a frame of this window's own
// origin, a trusted pointerdown heard inside it. `permitted` is the frame the person was found
// to have put the focus on, for as long as it keeps it. `pressedIn` allows ONE arrival of the
// focus on its frame and is then spent; unspent, it ends with the person's next press anywhere
// in this document, with a press inside another frame, and with the visit to the slide. It is
// kept with the DOCUMENT it was heard in ({ frame, inner, at }): a frame whose document has been
// replaced since (a pane rebuilt between the press and the focus) is not the frame that was
// pressed. A press inside the frame that already holds the focus by leave makes no record (it
// has nothing to allow), and whenever a frame's leave ends, for whatever reason, a press still
// recorded for that frame ends with it (withdraw): nothing is left over to allow a later return.
let hovered = null;
let pressedIn = null;
let permitted = null;
function withdraw(frame) {
if (pressedIn && pressedIn.frame === frame) pressedIn = null;
if (permitted === frame) permitted = null;
}
const wired = new WeakSet();
// The text field that last lost the focus without a press: { el, at, presses }.
let lost = null;
let timer = null;
// This visit: its key, the take-backs counted in it, the embed indexes stopped in it.
let visitKey = null;
let grabTimes = [];
const stopped = new Set();
// Every LOCAL PAGE's frame (one with a record in the channel) that this guard has been handed or
// has taken the focus from. A page goes on running for a moment after its frame is emptied
// (until the empty document replaces it), and its timers can take the focus in that moment: the
// rule holds for such a frame too, record or no record. No other frame is ever put here: a
// video or a copy of a slide is asked about again each time the focus arrives on it (`guarded`).
const known = new WeakSet();
function remember(frame) { if (channel && channel.status(frame)) known.add(frame); }
function isTextField(el) {
if (!el || el.nodeType !== 1) return false;
if (el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable) return true;
return el.tagName === 'INPUT' && !/^(button|checkbox|radio|range|color|file|image|reset|submit)$/i.test(el.type);
}
function isShown(el) {
if (!el.isConnected) return false;
if (typeof el.checkVisibility === 'function') return el.checkVisibility({ visibilityProperty: true });
return el.getClientRects().length > 0;
}
// One more grab on this slide. True when the slide's pages are now over the budget.
function overBudget() {
const at = now();
if (grabTimes.length > 0 && at - grabTimes[grabTimes.length - 1] < grabGapMs) return false;
grabTimes = grabTimes.filter(function (time) { return at - time < grabWindowMs; });
grabTimes.push(at);
return grabTimes.length > grabLimit;
}
// A take-back has just been made from `frame`, in a window that had the focus: count it, and
// over the budget stop every page of the slide that is not in use.
function countGrab(frame) {
if (typeof settings.pages !== 'function' || inUse() || !overBudget()) return;
grabTimes = [];
let indexes = [];
try { indexes = settings.pages() || []; } catch (error) { /* the host's affair */ }
indexes.forEach(function (index) { stopped.add(index); });
try { if (typeof settings.onStopped === 'function') settings.onStopped(); } catch (error) { /* the host's affair */ }
// This may be running inside a page's own focus() call, which puts the focus back on the frame
// as it returns: take it off the emptied frame when that call is over. (What a page does until
// it has unloaded is caught as for any frame this guard knows.)
const letGo = function () { takeBack(frame); };
host.queueMicrotask(letGo);
host.setTimeout(letGo, 0);
}
/** The host lays out its pages for the slide `key`. True when that is a new visit (the record and the count are cleared). */
function visit(key) {
if (key === visitKey) return false;
visitKey = key;
pressedIn = null;
permitted = null;
grabTimes = [];
stopped.clear();
return true;
}
function isStopped(index) { return stopped.has(index); }
/** The person chose this page: it is no longer stopped. */
function resume(index) { stopped.delete(index); }
// After the turn the press arrived in. Ahead of timers where the browser can say so: a page's
// own overdue timer must not run while the press still counts.
function afterThisTurn(fn) {
if (host.scheduler && typeof host.scheduler.postTask === 'function') {
host.scheduler.postTask(fn, { priority: 'user-blocking' }).catch(function () { /* aborted with the page */ });
} else host.setTimeout(fn, 0);
}
function onPress(event) {
if (!event.isTrusted) return;
if (event.type === 'keydown' && event.key !== 'Tab' && event.key !== 'Escape' && event.key !== 'Enter') return;
pressCount += 1;
pressing = true;
pressedAt = now();
lost = null;
// A press in this document (one inside a frame is not heard here): whatever a press inside a
// frame still allowed is over, and so is a frame's leave to hold the focus once it has lost it.
pressedIn = null;
if (permitted && doc.activeElement !== permitted) withdraw(permitted);
const mine = pressCount;
afterThisTurn(function () { if (pressCount === mine) pressing = false; });
}
/**
* Move the focus from `frame`, when it holds it, to the window's own document. Also the unload
* step: a frame removed or emptied while it holds the focus leaves the document with no focus at
* all (document.hasFocus() false), and the browser then reports nothing when the next page takes
* it. True when the frame held the focus.
*/
function release(frame) {
if (!frame) return false;
remember(frame);
// The frame is going (unloaded, emptied, removed): no press in it and no leave outlives that.
withdraw(frame);
return takeBack(frame);
}
// The same without the record: the rule's own take-back, from any frame.
function takeBack(frame) {
if (!frame || doc.activeElement !== frame) return false;
// Only a window that has the focus asks for it: a window behind another application must not
// come to the front because a page focused itself.
const windowFocused = doc.hasFocus();
const field = lost;
lost = null;
try { frame.blur(); } catch (error) { /* ignore */ }
if (windowFocused) { try { host.focus(); } catch (error) { /* ignore */ } }
if (field && now() - field.at <= restoreMs) {
// Not here: this may be running inside the page's own focus() call (the window's `blur` is
// raised from within it), and a focus set there is undone when that call completes: the
// field would look focused while the keys went to the page. As soon as the page's script
// has returned (a microtask), and once more a task later. Each time, everything is asked again.
const giveBack = function () {
if (field.given || field.presses !== pressCount || pressing || inUse()) return;
// The focus is on the document, or on a frame the rule would take it from anyway (a page
// can go on to a second frame in the same script): the field takes it. On anything else
// (another field, a button, a frame that may hold it) it stays where it is.
const active = doc.activeElement;
if (active && active !== doc.body && active !== frame && !mayNotHoldFocus(active)) return;
if (!isShown(field.el)) return;
field.given = true;
try { field.el.focus({ preventScroll: true }); } catch (error) { /* ignore */ }
};
host.queueMicrotask(giveBack);
host.setTimeout(giveBack, 0);
}
return true;
}
// Whether the rule takes the focus from this element: a page's frame that is not engaged; a
// frame with no record that this guard has known as a page's (a page a moment ago), or one the host says
// nobody can have put the focus on by hand (`guarded`: an unloaded page, a frame of a slide that
// is not shown, a preview): a page can put the focus on ANY frame of the window. Anything else
// (a video the person clicked, the remote site in use) is left alone.
function mayNotHoldFocus(el) {
if (!channel || !el || el.tagName !== 'IFRAME') return false;
const status = channel.status(el);
if (status) return !status.engaged;
return known.has(el) || (typeof settings.guarded === 'function' && Boolean(settings.guarded(el)));
}
// A frame of this window's own origin: hear the person's presses inside it.
function wire(frame) {
try {
const inner = frame.contentDocument;
if (!inner || wired.has(inner)) return;
wired.add(inner);
frame.contentWindow.addEventListener('pointerdown', function (event) {
if (!event.isTrusted) return;
// Inside the frame that holds the focus by leave: nothing to record. A leave that names a
// frame the focus is no longer on (this one, or another) is over, with anything recorded for it.
if (permitted === frame && doc.activeElement === frame) return;
if (permitted) withdraw(permitted);
pressedIn = { frame: frame, inner: inner, at: now() };
}, true);
} catch (error) { /* another origin: nothing can be heard there */ }
}
/**
* Did the PERSON put the focus on this frame? For the host's `guarded`, about a frame that takes
* presses (a video, a copy of a slide the person selects text in). A frame of this window's own
* origin: only when a trusted pointerdown was heard inside it just before. A frame of another
* origin: nothing can be heard, so when the pointer is over it (which a press needs; a script
* that focuses a frame the pointer happens to rest on is not told apart). Once found so, the
* frame may keep the focus until the focus goes elsewhere. Asking SPENDS the press heard inside
* the frame: it allows this one arrival of the focus, never a later one (a script that puts the
* focus back on the frame after the person has gone elsewhere finds nothing to go by).
*/
function pressedOn(frame) {
const press = pressedIn && pressedIn.frame === frame ? pressedIn : null;
if (press) pressedIn = null;
if (permitted === frame) return true;
let inner = null;
try { inner = frame.contentDocument; } catch (error) { inner = null; }
const yes = inner ? Boolean(press && press.inner === inner && frame.isConnected && now() - press.at < 1000) : hovered === frame;
if (yes) permitted = frame;
return yes;
}
/** The rule, now. True when the focus was taken back from a frame. */
function check() {
const el = doc.activeElement;
if (permitted && el !== permitted) withdraw(permitted);
if (!mayNotHoldFocus(el)) return false;
const windowFocused = doc.hasFocus();
// A press of the person's own in this window, in this turn or just before: the focus is on its
// way somewhere because of it (the end of an engagement is checked before the press has moved
// the focus off the page). The focus is still taken back; it is not a grab by a page.
const byThePerson = pressing || now() - pressedAt < pressGraceMs;
remember(el);
if (!takeBack(el)) return false;
// The budget (the field the focus was taken from is given it back as after any other grab).
if (windowFocused && !byThePerson) countGrab(el);
return true;
}
/** Check now, and keep checking while any page is live in this window. The interval ends itself. */
function watch() {
check();
if (timer !== null || !channel) return;
timer = host.setInterval(function () {
if (!livePresent()) { host.clearInterval(timer); timer = null; return; }
check();
}, watchMs);
}
if (channel) {
host.addEventListener('blur', function () { check(); host.queueMicrotask(check); host.setTimeout(check, 0); });
host.addEventListener('focus', function () { check(); });
doc.addEventListener('visibilitychange', function () { check(); });
// Focus arriving on an element of this document: the rule first; any other arrival means the
// person (or the window's own code) has put the focus somewhere, and no field is owed anything.
doc.addEventListener('focusin', function () { if (!check()) lost = null; }, true);
doc.addEventListener('focusout', function (event) {
lost = !pressing && isTextField(event.target) ? { el: event.target, at: now(), presses: pressCount, given: false } : null;
}, true);
// Where the pointer is, as far as frames go; and a listener inside a frame of our own origin
// the moment the pointer reaches it (before any press there).
doc.addEventListener('pointerover', function (event) {
const target = event.target;
hovered = target && target.tagName === 'IFRAME' ? target : null;
if (hovered) wire(hovered);
}, true);
doc.documentElement.addEventListener('pointerleave', function () { hovered = null; });
// A touch moves the focus when the finger lifts, a mouse when the button goes down.
['pointerdown', 'pointerup', 'mousedown', 'click', 'keydown'].forEach(function (type) { host.addEventListener(type, onPress, true); });
}
return { check: check, watch: watch, release: release, visit: visit, isStopped: isStopped, resume: resume, pressedOn: pressedOn };
}
// Persisted shape { targetSeconds, elapsedMs, runningSince } survives a mid-talk rebuild reload
// (sessionStorage, deck-scoped). The clock does NOT auto-run on open — the presenter presses
// Start (or P). Thresholds ride the deck (frontmatter defaults: warn 5 min, urgent 1 min).
const timerStorageKey = `html-presentations:${deckId}:timer`;
// Resume-on-reopen: localStorage survives a window CLOSE (sessionStorage does not). A sessionStorage
// sentinel distinguishes a same-window RELOAD (silent restore, as before) from a fresh window / reopen.
const resumeKey = `html-presentations:${deckId}:resume`;
const sessionSentinelKey = `html-presentations:${deckId}:session`;
const RESUME_WINDOW_MS = 4 * 60 * 60 * 1000; // a talk + breaks; older saved state = a different run, ignored
const wasReload = isPresenter && sessionStorage.getItem(sessionSentinelKey) === "1";
if (isPresenter) { try { sessionStorage.setItem(sessionSentinelKey, "1"); } catch {} }
const MILESTONE_TEXT = (warnAt, urgentAt) => ({ [warnAt]: `${Math.round(warnAt / 60)} minutes left`, [urgentAt]: `${Math.round(urgentAt / 60)} minute${urgentAt === 60 ? "" : "s"} left`, 0: "Time's up" });
const deckEl = document.querySelector("main.deck");
const thresholds = {
warnAtSeconds: Math.round(Number(deckEl?.dataset.warnAt || 5) * 60),
urgentAtSeconds: Math.round(Number(deckEl?.dataset.urgentAt || 1) * 60),
};
const frontmatterDuration = Number(deckEl?.dataset.talkDuration || 0); // seconds, may be 0
let timer = { targetSeconds: frontmatterDuration || 0, elapsedMs: 0, runningSince: null, reminders: [5, 1] };
let timerFired = new Set();
let remindersFired = new Set();
if (isPresenter) {
try {
const stored = JSON.parse(sessionStorage.getItem(timerStorageKey) || "null");
if (stored && typeof stored.targetSeconds === "number") timer = stored;
} catch {}
}
if (!Array.isArray(timer.reminders)) timer.reminders = [5, 1]; // default: 5-min + 1-min "before end" reminders
const persistTimer = () => { try { sessionStorage.setItem(timerStorageKey, JSON.stringify(timer)); } catch {} persistResume(); };
// === Presenter shown/skipped tracking (2026-07-01, presenter QoL) ===
// Session-scoped record of which slides the presenter has actually shown vs skipped, so the
// overview can mark progress. Presenter-only; the audience/handout window never tracks this.
const progressKey = `html-presentations:${deckId}:progress`;
let shownSet = new Set();
let skippedExplicitSet = new Set();
if (isPresenter) {
try {
const p = JSON.parse(sessionStorage.getItem(progressKey) || "null");
if (p) { shownSet = new Set(p.shown || []); skippedExplicitSet = new Set(p.skipped || []); }
} catch {}
}
const persistProgress = () => { try { sessionStorage.setItem(progressKey, JSON.stringify({ shown: [...shownSet], skipped: [...skippedExplicitSet] })); } catch {} persistResume(); };
// Resume snapshot (localStorage, per deck) — index + timer + progress + a timestamp for recency.
function persistResume() {
if (!isPresenter) return;
try {
localStorage.setItem(resumeKey, JSON.stringify({
index: state.index,
timer,
progress: { shown: [...shownSet], skipped: [...skippedExplicitSet] },
updatedAt: Date.now(),
}));
} catch {}
}
// === Skip-next control (Task 8, presenter QoL; beat-aware since Task 5 fixes) ===
// Skips the NEXT beat's slide: marks that slide explicitly skipped — but never a slide the
// presenter has already shown (a grid-return's section, an already-presented grid child) —
// and jumps to the first beat AFTER that slide's beats (past a grid section's whole grid
// sequence). Marking happens BEFORE the jump so an open overview re-renders with the marker
// in place. No-op when nothing follows the skipped slide's beats.
function skipNext() {
const nextBeatIndex = clampBeat(state.beat) + 1;
if (nextBeatIndex >= beats.length) return; // nothing after -> no-op
const skipId = beats[nextBeatIndex].slideId;
let land = beats.length;
for (let k = beats.length - 1; k >= nextBeatIndex; k -= 1) {
if (beats[k].slideId === skipId) { land = k + 1; break; }
}
if (land >= beats.length) return; // skipping would run off the deck -> no-op
const skipSlideIndex = slideIndexById.get(skipId);
if (isPresenter && skipSlideIndex != null && !shownSet.has(skipSlideIndex)) {
skippedExplicitSet.add(skipSlideIndex);
persistProgress();
}
goToBeat(land);
}
els.skipNextBtn?.addEventListener("click", skipNext);
// ── Return (single-level): an overview jump of MORE than 1 slide remembers where it came FROM;
// "Return" / B pops back there once, then clears. Ephemeral (in-memory, not persisted). Only
// overview jumps arm it — plain arrows and Skip-next do not. The overview's onJump routes here.
let jumpOrigin = null;
function updateReturnBtn() { if (els.returnBtn) els.returnBtn.hidden = !(isPresenter && jumpOrigin != null); }
function jumpTo(index, subIndex) {
if (isPresenter) { jumpOrigin = Math.abs(index - state.index) > 1 ? state.index : null; updateReturnBtn(); }
if (subIndex == null) { goTo(index, 0); return; }
const parentId = slides[index]?.dataset.id;
const childBeatIndex = carouselChildBeatIndex(beats, parentId, subIndex);
if (childBeatIndex >= 0) { goToBeat(childBeatIndex); return; }
// Block-content carousels have no authored child headings/beats; retain their direct reveal.
goToBeat(firstBeatForSlideIndex(index), { reveal: Number(subIndex) || 0 });
}
function returnToOrigin() {
if (jumpOrigin == null) return;
const target = jumpOrigin;
jumpOrigin = null; updateReturnBtn();
goTo(target, 0);
}
els.returnBtn?.addEventListener("click", returnToOrigin);
els.outlineBtn?.addEventListener("click", () => overview.toggle());
// ── Presenter chrome: lucide icons, "Name Shortcut" on hover, the "?" sheet (presenter only) ──
// ADR-0031 §6, presenter redesign ticket 01. Every control's name, icon and key comes from the
// generated block below (src/shared/presenter-controls.ts + src/shared/shortcut-registry.ts via
// scripts/build-shortcut-help.mjs); nothing here names a control, a key or a glyph by hand.
// Controls a preload injects (recording, edit pencil) carry the same data-tip / data-key and are
// shown by the same delegated tooltip.
/*SHORTCUT_HELP*/
const PRESENTER_COMMAND_KEYS = [{"id":"presenter.next","label":"Next","codes":["ArrowRight","Space","ArrowDown","PageDown","Enter","MediaTrackNext"],"keys":"→ Space ↓ PgDn ↵"},{"id":"presenter.previous","label":"Previous","codes":["ArrowLeft","ArrowUp","PageUp","Backspace","MediaTrackPrevious"],"keys":"← ↑ PgUp Backspace"},{"id":"presenter.first","label":"First slide","codes":["Home"],"keys":"Home"},{"id":"presenter.last","label":"Last slide","codes":["End"],"keys":"End"},{"id":"presenter.grid-child","label":"Jump to grid child","codes":["Digit1-Digit9"],"keys":"1–9"},{"id":"presenter.skip","label":"Skip next slide","codes":["s"],"keys":"S"},{"id":"presenter.return","label":"Return from jump","codes":["b"],"keys":"B"},{"id":"presenter.overview","label":"Outline","codes":["o"],"keys":"O"},{"id":"presenter.timer","label":"Start or pause timer","codes":["p"],"keys":"P"},{"id":"presenter.duration","label":"Set duration","codes":["t"],"keys":"T"},{"id":"presenter.record","label":"Start, or stop and save, recording","codes":["Shift-r"],"keys":"⇧R"},{"id":"presenter.record-pause","label":"Pause or resume recording","codes":["Shift-p"],"keys":"⇧P"},{"id":"presenter.save-run-as","label":"Save run as…","codes":["l"],"keys":"L"},{"id":"presenter.save-run","label":"Save this run as a delivery","codes":["Enter"],"keys":"↵"},{"id":"presenter.reveal","label":"Reveal mode","codes":["r"],"keys":"R"},{"id":"presenter.focus","label":"Focus mode","codes":["f"],"keys":"F"},{"id":"presenter.rebind","label":"Rebind the highlighted command","codes":["Mod-Shift-,"],"keys":"⌘⇧,"},{"id":"presenter.pointer","label":"Pointer","codes":["i"],"keys":"I"},{"id":"presenter.pen","label":"Pen","codes":["d"],"keys":"D"},{"id":"presenter.pen-tool","label":"Next or previous pen tool","codes":["w","Shift-w"],"keys":"W / ⇧W"},{"id":"presenter.ink-undo","label":"Undo last stroke","codes":["Mod-z"],"keys":"⌘Z"},{"id":"presenter.ink-clear","label":"Clear drawing on this slide","codes":["x"],"keys":"X"},{"id":"presenter.ink-clear-all","label":"Clear all drawings","codes":["Shift-x"],"keys":"⇧X"},{"id":"presenter.highlight","label":"Highlight","codes":["h"],"keys":"H"},{"id":"presenter.preview-size","label":"Resize previews","codes":["BracketLeft","BracketRight"],"keys":"[ / ]"},{"id":"presenter.notes-scroll","label":"Scroll notes forward or back","codes":["j","Shift-j"],"keys":"J / ⇧J"},{"id":"presenter.media","label":"Play audience media","codes":["m"],"keys":"M"},{"id":"presenter.gallery","label":"Gallery or lightbox","codes":["z"],"keys":"Z"},{"id":"presenter.embed-fullscreen","label":"Embedded page: full screen","codes":["z"],"keys":"Z"},{"id":"presenter.video-fullscreen","label":"Video: Fullscreen","codes":["v"],"keys":"V"},{"id":"presenter.embed","label":"Interact with embed","codes":["e"],"keys":"E"},{"id":"presenter.font-larger","label":"Increase text size","codes":["+"],"keys":"+"},{"id":"presenter.font-smaller","label":"Decrease text size","codes":["-"],"keys":"−"},{"id":"presenter.audience","label":"Launch audience","codes":["F5"],"keys":"F5"},{"id":"presenter.live","label":"Go or end live","codes":["g"],"keys":"G"},{"id":"presenter.poll-primary","label":"Open or close current poll","codes":["q"],"keys":"Q"},{"id":"presenter.poll-reveal","label":"Reveal held poll results","codes":["Shift-q"],"keys":"⇧ Q"},{"id":"presenter.questions","label":"Open the questions tray","codes":["a"],"keys":"A"},{"id":"presenter.poll-compose","label":"Compose a Quick poll","codes":["k"],"keys":"K"},{"id":"presenter.instant-compose","label":"Compose an instant slide","codes":["Mod-Alt-i"],"keys":"⌥⌘I"},{"id":"presenter.instant-paste","label":"Preview clipboard as an instant slide","codes":["Mod-v"],"keys":"⌘V"},{"id":"presenter.instant-return","label":"Back to slide while instant slide is shown","codes":["ArrowRight"],"keys":"→"},{"id":"presenter.talk-qr","label":"Show the talk's QR code","codes":["u"],"keys":"U"},{"id":"presenter.board-pick","label":"Pick up or drop a board card","codes":["Alt-Enter"],"keys":"⌥↵"},{"id":"presenter.board-undo","label":"Undo the last board change","codes":["Mod-z"],"keys":"⌘Z"},{"id":"presenter.edit","label":"Edit this slide in TalkWeaver","codes":["Mod-e"],"keys":"⌘E"},{"id":"presenter.refresh","label":"Refresh with latest edits","codes":["Mod-r","Shift-F5"],"keys":"⌘R / ⇧F5"},{"id":"presenter.command-palette","label":"Command palette","codes":["Mod-Shift-p"],"keys":"⌘⇧P"},{"id":"presenter.help","label":"Show shortcuts","codes":["?"],"keys":"?"},{"id":"presenter.close","label":"Close overlay or mode","codes":["Escape"],"keys":"Esc"},{"id":"palette.reset-timer","label":"Reset timer","codes":[],"keys":""},{"id":"palette.join-link","label":"Show join link and venue screen","codes":[],"keys":""},{"id":"palette.copy-venue-link","label":"Copy venue-screen link","codes":[],"keys":""},{"id":"palette.allow-questions","label":"Allow slide questions","codes":[],"keys":""},{"id":"palette.allow-reactions","label":"Allow slide reactions","codes":[],"keys":""},{"id":"palette.poll-panel","label":"Show poll panel","codes":[],"keys":""},{"id":"palette.quick-poll-restore","label":"Show Quick poll on screens","codes":[],"keys":""},{"id":"palette.quick-poll-dismiss","label":"Dismiss Quick poll","codes":[],"keys":""},{"id":"palette.board-freeze","label":"Freeze or unfreeze the board","codes":[],"keys":""},{"id":"palette.board-panel","label":"Show board panel","codes":[],"keys":""},{"id":"palette.board-full","label":"Board full screen","codes":[],"keys":""},{"id":"palette.board-popout","label":"Pop out the board","codes":[],"keys":""},{"id":"palette.notes-off","label":"Notes: off","codes":[],"keys":""},{"id":"palette.notes-bottom","label":"Notes: bottom","codes":[],"keys":""},{"id":"palette.notes-sidebar","label":"Notes: sidebar","codes":[],"keys":""},{"id":"palette.notes-top-band","label":"Notes: top band","codes":[],"keys":""},{"id":"palette.notes-camera-column","label":"Notes: camera column","codes":[],"keys":""},{"id":"palette.notes-scroll-hand","label":"Notes scroll by hand","codes":[],"keys":""},{"id":"palette.notes-scroll-auto","label":"Notes scroll automatically","codes":[],"keys":""},{"id":"palette.notes-faster","label":"Notes scroll faster","codes":[],"keys":""},{"id":"palette.notes-slower","label":"Notes scroll slower","codes":[],"keys":""},{"id":"palette.pen-freehand","label":"Pen tool: Freehand","codes":[],"keys":""},{"id":"palette.pen-arrow","label":"Pen tool: Arrow","codes":[],"keys":""},{"id":"palette.pen-rectangle","label":"Pen tool: Rectangle","codes":[],"keys":""},{"id":"palette.highlight-clear","label":"Clear highlights","codes":[],"keys":""},{"id":"palette.guide","label":"Guide: Present chapter","codes":[],"keys":""}];
const PRESENTER_CONTROL_COMMANDS = {"twClockBtn":"presenter.timer","twStartTimerBtn":"presenter.timer","twDurationBtn":"presenter.duration","presenterGoLive":"presenter.live","presenterEndLive":"presenter.live","liveGoButton":"presenter.live","presenterAudienceApp":"presenter.audience","liveTalkQr":"presenter.talk-qr","presenterInstantButton":"presenter.instant-compose","liveInstantPaste":"presenter.instant-paste","liveInstantBack":"presenter.instant-return","presenterQuickPollButton":"presenter.poll-compose","pollMenuPrimary":"presenter.poll-primary","pollMenuReveal":"presenter.poll-reveal","pollMenuBoardClose":"presenter.poll-primary","pollMenuQuestions":"presenter.questions","viewOutline":"presenter.overview","viewFontDown":"presenter.font-smaller","viewFontUp":"presenter.font-larger","viewReveal":"presenter.reveal","viewFocus":"presenter.focus","viewHighlight":"presenter.highlight","viewShortcuts":"presenter.help","viewCommands":"presenter.command-palette","presenterInstantBack":"presenter.instant-return","presenterPollOpen":"presenter.poll-primary","presenterPollClose":"presenter.poll-primary","presenterPollReveal":"presenter.poll-reveal","presenterNotesMore":"presenter.notes-scroll","presenterOutlineClose":"presenter.overview","outlineBtn":"presenter.overview","presenterPrev":"presenter.previous","presenterNext":"presenter.next","skipNextBtn":"presenter.skip","returnBtn":"presenter.return","presenterMediaPlay":"presenter.media","presenterVideoFullscreen":"presenter.video-fullscreen","presenterGalleryBtn":"presenter.gallery","presenterEmbedFullscreen":"presenter.embed-fullscreen","navQuickPoll":"presenter.poll-compose","navInstant":"presenter.instant-compose","presenterFocus":"presenter.focus","presenterPointer":"presenter.pointer","viewPointer":"presenter.pointer","morePointer":"presenter.pointer","presenterPointerExit":"presenter.close","presenterPen":"presenter.pen","viewPen":"presenter.pen","morePen":"presenter.pen","presenterPenExit":"presenter.close","presenterInkClear":"presenter.ink-clear","viewInkClear":"presenter.ink-clear","moreInkClear":"presenter.ink-clear","viewInkClearAll":"presenter.ink-clear-all","moreInkClearAll":"presenter.ink-clear-all","penUndo":"presenter.ink-undo","penClear":"presenter.ink-clear","penStripUndo":"presenter.ink-undo","penStripClear":"presenter.ink-clear","penStripOff":"presenter.close","presenterHighlight":"presenter.highlight","presenterFirst":"presenter.first","presenterLast":"presenter.last","moreReturn":"presenter.return","moreGridCard":"presenter.grid-child","presenterReveal":"presenter.reveal","moreEmbed":"presenter.embed","fontDown":"presenter.font-smaller","fontUp":"presenter.font-larger","moreRefresh":"presenter.refresh","presenterModeExit":"presenter.close","presenterHighlightExit":"presenter.close","twrec-primary":"presenter.record","twrec-change-kind":"presenter.save-run-as","twrec-pause":"presenter.record-pause","twrec-resume":"presenter.record-pause","twrec-stop":"presenter.record","twrec-toast-yes":"presenter.record-pause","twrec-save-delivery":"presenter.save-run","twrec-save-as":"presenter.save-run-as","twrec-start-record":"presenter.record","twrec-saved-change":"presenter.save-run-as","twedit-btn":"presenter.edit"};
const PRESENTER_TIPS = {"twClockBtn":["Start timer","P"],"twStartTimerBtn":["Start timer","P"],"twDurationBtn":["Talk length and reset","T"],"twResetBtn":["Reset timer",""],"twDurationMinus":["Talk length 5 minutes shorter",""],"twDurationPlus":["Talk length 5 minutes longer",""],"presenterGoLive":["Go live","G"],"presenterEndLive":["End live session","G"],"presenterMenuLive":["Live menu",""],"presenterMenuPoll":["Poll menu",""],"presenterMenuView":["View menu",""],"liveGoButton":["Go live","G"],"presenterAudienceApp":["Open audience window","F5"],"liveShowJoin":["Show join link and venue screen",""],"liveCopyVenueLink":["Copy venue-screen link",""],"liveAllowQuestions":["Allow slide questions",""],"liveAllowReactions":["Allow slide reactions",""],"liveTalkQr":["Show talk QR code","U"],"presenterInstantButton":["Compose instant slide","⌥⌘I"],"liveInstantPaste":["Instant slide from clipboard","⌘V"],"liveInstantBack":["Back to slide","→"],"presenterQuickPollButton":["Compose Quick poll","K"],"presenterQuickPollRestore":["Show Quick poll on screens",""],"pollMenuPrimary":["Open or close current poll","Q"],"pollMenuReveal":["Reveal results","⇧ Q"],"presenterPollPanelToggle":["Show poll panel",""],"pollMenuBoardClose":["Close board to new cards","Q"],"pollMenuBoardFreeze":["Freeze board",""],"pollMenuBoardPanel":["Show board panel",""],"pollMenuBoardFull":["Board full screen",""],"pollMenuBoardPopout":["Pop out the board",""],"pollMenuQuestions":["Open questions","A"],"notesPlacementBtn":["Notes placement and scrolling",""],"viewOutline":["Outline","O"],"viewFontDown":["Slide text smaller","−"],"viewFontUp":["Slide text larger","+"],"viewReveal":["Reveal mode","R"],"viewFocus":["Focus mode","F"],"viewHighlight":["Highlight text","H"],"viewHighlightClear":["Clear highlights",""],"viewShortcuts":["Keyboard shortcuts","?"],"viewCommands":["All commands","⌘⇧P"],"notesWpmSlower":["Notes scroll slower",""],"notesWpmFaster":["Notes scroll faster",""],"liveGoPanelClose":["Hide the join link",""],"liveVenueCopy":["Copy venue-screen link",""],"presenterInstantBack":["Back to slide","→"],"instantClose":["Close instant slide",""],"instantPasteClose":["Cancel clipboard preview",""],"quickPollClose":["Close Quick poll",""],"presenterPollDismiss":["Hide the poll panel",""],"presenterPollOpen":["Open poll","Q"],"presenterPollClose":["Stop accepting responses","Q"],"presenterPollReveal":["Reveal results","⇧ Q"],"presenterPollShowQuestion":["Show the question on screens",""],"presenterPollShowResults":["Show the results on screens",""],"presenterPollPreviousPage":["Previous page of the poll",""],"presenterPollNextPage":["Next page of the poll",""],"presenterQuickPollDismiss":["Dismiss Quick poll",""],"presenterNotesMore":["Step notes forward","J / ⇧J"],"presenterOutlineExpand":["Show previews in the outline",""],"presenterOutlineClose":["Close outline","O"],"outlineBtn":["Outline","O"],"presenterPrev":["Previous","← ↑ PgUp Backspace"],"presenterNext":["Next","→ Space ↓ PgDn ↵"],"skipNextBtn":["Skip next slide","S"],"returnBtn":["Return to where you jumped from","B"],"presenterMediaPlay":["Play media","M"],"presenterMediaPause":["Pause media",""],"presenterVideoFullscreen":["Video full screen","V"],"presenterGalleryBtn":["Image gallery","Z"],"presenterEmbedFullscreen":["Embedded page: full screen","Z"],"navQuickPoll":["Compose Quick poll","K"],"navInstant":["Compose instant slide","⌥⌘I"],"presenterFocus":["Focus mode","F"],"presenterPointer":["Pointer: show your mouse on every screen","I"],"viewPointer":["Pointer","I"],"morePointer":["Pointer","I"],"presenterPointerExit":["Turn off pointer","Esc"],"presenterPen":["Pen: draw on the slide on every screen","D"],"viewPen":["Pen","D"],"morePen":["Pen","D"],"presenterPenExit":["Turn off pen","Esc"],"presenterInkClear":["Clear the drawing on this slide","X"],"viewInkClear":["Clear drawing on this slide","X"],"moreInkClear":["Clear drawing on this slide","X"],"viewInkClearAll":["Clear all drawings","⇧X"],"moreInkClearAll":["Clear all drawings","⇧X"],"penToolFreehand":["Freehand: draw with the mouse",""],"penToolArrow":["Arrow: press on the point, drag to the tail",""],"penToolRectangle":["Rectangle: drag from one corner to the opposite",""],"penInkRed":["Red ink",""],"penInkYellow":["Yellow ink",""],"penInkGreen":["Green ink",""],"penInkBlue":["Blue ink",""],"penWidthThin":["Thin line",""],"penWidthThick":["Thick line",""],"penUndo":["Undo last stroke","⌘Z"],"penClear":["Clear this slide","X"],"penStripFreehand":["Freehand: draw with the mouse",""],"penStripArrow":["Arrow: press on the point, drag to the tail",""],"penStripRectangle":["Rectangle: drag from one corner to the opposite",""],"penStripInkRed":["Red ink",""],"penStripInkYellow":["Yellow ink",""],"penStripInkGreen":["Green ink",""],"penStripInkBlue":["Blue ink",""],"penStripWidthThin":["Thin line",""],"penStripWidthThick":["Thick line",""],"penStripUndo":["Undo last stroke","⌘Z"],"penStripClear":["Clear this slide","X"],"penStripOff":["Pen off","Esc"],"presenterHighlight":["Highlight text","H"],"presenterMore":["More",""],"presenterFirst":["First slide","Home"],"presenterLast":["Last slide","End"],"moreReturn":["Return to where you jumped from","B"],"moreGridCard":["Card on a grid slide","1–9"],"presenterReveal":["Reveal mode","R"],"presenterHighlightClear":["Clear highlights",""],"moreEmbed":["Interact with embedded page","E"],"fontDown":["Slide text smaller","−"],"fontUp":["Slide text larger","+"],"moreRefresh":["Refresh with latest edits","⌘R / ⇧F5"],"presenterModeExit":["Turn off focus mode","Esc"],"presenterHighlightExit":["Turn off highlighting","Esc"],"presenterHighlightChipClear":["Clear highlights on this slide",""]};
const PRESENTER_ICON_OF = {"twStartTimerBtn":["timer",0,0],"twDurationBtn":["chevron-down",0,1],"twResetBtn":["timer-reset",0,0],"twDurationMinus":["minus",0,1],"twDurationPlus":["plus",0,1],"presenterGoLive":["radio",0,0],"presenterEndLive":["radio-off",0,0],"presenterMenuLive":["radio",0,0],"presenterMenuPoll":["vote",0,0],"presenterMenuView":["panels-top-left",0,0],"liveGoButton":["radio",0,0],"presenterAudienceApp":["monitor-up",0,0],"liveShowJoin":["scan-qr-code",0,0],"liveCopyVenueLink":["link",0,0],"liveAllowQuestions":["message-circle-question-mark",0,0],"liveAllowReactions":["smile-plus",0,0],"liveTalkQr":["qr-code",0,0],"presenterInstantButton":["zap",0,0],"liveInstantPaste":["clipboard",0,0],"liveInstantBack":["undo-2",0,0],"presenterQuickPollButton":["vote",0,0],"presenterQuickPollRestore":["monitor-play",0,0],"pollMenuPrimary":["lock-open",0,0],"pollMenuReveal":["eye",0,0],"presenterPollPanelToggle":["chart-bar",0,0],"pollMenuBoardClose":["lock",0,0],"pollMenuBoardFreeze":["snowflake",0,0],"pollMenuBoardPanel":["layout-grid",0,0],"pollMenuBoardFull":["maximize-2",0,0],"pollMenuBoardPopout":["picture-in-picture-2",0,0],"pollMenuQuestions":["message-circle-question-mark",0,0],"notesPlacementBtn":["notebook-text",0,0],"viewOutline":["list-tree",0,0],"viewFontDown":["a-arrow-down",0,0],"viewFontUp":["a-arrow-up",0,0],"viewReveal":["layers",0,0],"viewFocus":["focus",0,0],"viewHighlight":["highlighter",0,0],"viewHighlightClear":["eraser",0,0],"viewShortcuts":["keyboard",0,0],"viewCommands":["command",0,0],"notesWpmSlower":["minus",0,1],"notesWpmFaster":["plus",0,1],"liveGoPanelClose":["x",0,1],"liveVenueCopy":["copy",0,0],"presenterInstantBack":["undo-2",0,0],"instantClose":["x",0,1],"instantPasteClose":["x",0,1],"quickPollClose":["x",0,1],"presenterPollDismiss":["x",0,1],"presenterPollOpen":["lock-open",0,0],"presenterPollClose":["lock",0,0],"presenterPollReveal":["eye",0,0],"presenterPollShowQuestion":["message-square-text",0,0],"presenterPollShowResults":["chart-bar",0,0],"presenterPollPreviousPage":["chevron-left",0,0],"presenterPollNextPage":["chevron-right",0,0],"presenterQuickPollDismiss":["x",0,0],"presenterNotesMore":["chevrons-down",1,0],"presenterOutlineExpand":["layout-grid",0,0],"presenterOutlineClose":["x",0,1],"outlineBtn":["list-tree",0,0],"presenterPrev":["arrow-left",0,0],"presenterNext":["arrow-right",1,0],"skipNextBtn":["skip-forward",0,1],"returnBtn":["undo-2",0,0],"presenterMediaPlay":["play",0,0],"presenterMediaPause":["pause",0,0],"presenterVideoFullscreen":["fullscreen",0,0],"presenterGalleryBtn":["images",0,0],"presenterEmbedFullscreen":["maximize-2",0,1],"navQuickPoll":["vote",0,0],"navInstant":["zap",0,0],"presenterFocus":["focus",0,0],"presenterPointer":["mouse-pointer-2",0,0],"viewPointer":["mouse-pointer-2",0,0],"morePointer":["mouse-pointer-2",0,0],"presenterPointerExit":["x",0,1],"presenterPen":["pen-tool",0,0],"viewPen":["pen-tool",0,0],"morePen":["pen-tool",0,0],"presenterPenExit":["x",0,1],"presenterInkClear":["eraser",0,0],"viewInkClear":["eraser",0,0],"moreInkClear":["eraser",0,0],"viewInkClearAll":["eraser",0,0],"moreInkClearAll":["eraser",0,0],"penToolFreehand":["pen-line",0,0],"penToolArrow":["move-up-right",0,0],"penToolRectangle":["square",0,0],"penUndo":["undo-2",0,0],"penClear":["eraser",0,0],"penStripFreehand":["pen-line",0,0],"penStripArrow":["move-up-right",0,0],"penStripRectangle":["square",0,0],"penStripUndo":["undo-2",0,0],"penStripClear":["eraser",0,0],"penStripOff":["x",0,0],"presenterHighlight":["highlighter",0,0],"presenterMore":["ellipsis",0,1],"presenterFirst":["chevron-first",0,0],"presenterLast":["chevron-last",0,0],"moreReturn":["undo-2",0,0],"moreGridCard":["layout-grid",0,0],"presenterReveal":["layers",0,0],"presenterHighlightClear":["eraser",0,0],"moreEmbed":["mouse-pointer-click",0,0],"fontDown":["a-arrow-down",0,0],"fontUp":["a-arrow-up",0,0],"moreRefresh":["refresh-cw",0,0],"presenterModeExit":["x",0,1],"presenterHighlightExit":["x",0,1],"presenterHighlightChipClear":["eraser",0,0]};
const TIMER_BUTTON = {"names":{"idle":"Start timer","running":"Pause timer","paused":"Resume timer"}};
const MODE_CHIP = {"reveal":{"icon":"layers","word":"Reveal mode","exit":"Turn off reveal mode"},"focus":{"icon":"focus","word":"Focus mode","exit":"Turn off focus mode"},"highlight":{"icon":"highlighter","word":"Highlight on","exit":"Turn off highlighting"}};
const OUTLINE_STATUS_ICONS = {"shown":"circle","skipped":"circle-slash","unseen":"circle-dashed"};
const PRESENTER_ICONS = {"a-arrow-down":" ","a-arrow-up":" ","alarm-clock":" ","arrow-left":" ","arrow-right":" ","bookmark":" ","chart-bar":" ","check":" ","chevron-down":" ","chevron-first":" ","chevron-last":" ","chevron-left":" ","chevron-right":" ","chevrons-down":" ","chevrons-up":" ","circle":" ","circle-alert":" ","circle-check":" ","circle-dashed":" ","circle-dot":" ","circle-pause":" ","circle-play":" ","circle-slash":" ","clipboard":" ","clock":" ","command":" ","copy":" ","ellipsis":" ","eraser":" ","eye":" ","eye-off":" ","flag":" ","focus":" ","frown":" ","fullscreen":" ","gallery-vertical-end":" ","graduation-cap":" ","grip-vertical":" ","group":" ","hand":" ","highlighter":" ","image":" ","images":" ","inbox":" ","keyboard":" ","layers":" ","layout-grid":" ","lightbulb":" ","link":" ","list-end":" ","list-tree":" ","loader-circle":" ","lock":" ","lock-open":" ","maximize-2":" ","message-circle-more":" ","message-circle-question-mark":" ","message-square-text":" ","minimize-2":" ","minus":" ","monitor":" ","monitor-check":" ","monitor-off":" ","monitor-play":" ","monitor-up":" ","monitor-x":" ","mouse-pointer-2":" ","mouse-pointer-click":" ","move-up-right":" ","notebook-text":" ","panel-bottom":" ","panel-right":" ","panel-top":" ","panels-top-left":" ","pause":" ","pen-line":" ","pen-tool":" ","pencil":" ","picture-in-picture-2":" ","play":" ","plus":" ","presentation":" ","qr-code":" ","radio":" ","radio-off":" ","refresh-cw":" ","scan-qr-code":" ","search":" ","skip-forward":" ","smile-plus":" ","snail":" ","snowflake":" ","square":" ","tags":" ","thumbs-down":" ","thumbs-up":" ","timer":" ","timer-reset":" ","trash-2":" ","type":" ","undo-2":" ","ungroup":" ","user-round":" ","vote":" ","webcam":" ","wifi-off":" ","x":" ","zap":" "};
const SHORTCUTS_LIST = [["Navigation",[["→ Space ↓ PgDn ↵","Next",null,"presenter.next"],["← ↑ PgUp Backspace","Previous",null,"presenter.previous"],["Home","First slide",null,"presenter.first"],["End","Last slide",null,"presenter.last"],["1–9","Jump to grid child",null,"presenter.grid-child"],["S","Skip next slide",null,"presenter.skip"],["B","Return from jump",null,"presenter.return"]]],["Overview & timer",[["O","Outline",null,"presenter.overview"],["P","Start or pause timer",null,"presenter.timer"],["T","Set duration",null,"presenter.duration"]]],["Recording",[["⇧R","Start, or stop and save, recording","#twrec-module","presenter.record"],["⇧P","Pause or resume recording","#twrec-module","presenter.record-pause"],["L","Save run as…","#twrec-module","presenter.save-run-as"],["↵","Save this run as a delivery","#twrec-module","presenter.save-run"]]],["Modes & display",[["R","Reveal mode",null,"presenter.reveal"],["F","Focus mode",null,"presenter.focus"],["I","Pointer",null,"presenter.pointer"],["D","Pen",null,"presenter.pen"],["W / ⇧W","Next or previous pen tool",null,"presenter.pen-tool"],["⌘Z","Undo last stroke",null,"presenter.ink-undo"],["X","Clear drawing on this slide",null,"presenter.ink-clear"],["⇧X","Clear all drawings",null,"presenter.ink-clear-all"],["H","Highlight",null,"presenter.highlight"],["[ / ]","Resize previews",null,"presenter.preview-size"],["J / ⇧J","Scroll notes forward or back",null,"presenter.notes-scroll"],["M","Play audience media",null,"presenter.media"],["Z","Gallery or lightbox",null,"presenter.gallery"],["Z","Embedded page: full screen",null,"presenter.embed-fullscreen"],["V","Video: Fullscreen",null,"presenter.video-fullscreen"],["E","Interact with embed",null,"presenter.embed"],["+","Increase text size",null,"presenter.font-larger"],["−","Decrease text size",null,"presenter.font-smaller"]]],["Help",[["⌘⇧,","Rebind the highlighted command",null,"presenter.rebind"],["⌘⇧P","Command palette",null,"presenter.command-palette"],["?","Show shortcuts",null,"presenter.help"],["Esc","Close overlay or mode",null,"presenter.close"]]],["Audience",[["F5","Launch audience",null,"presenter.audience"],["G","Go or end live","[data-tw-live-bridge]","presenter.live"],["Q","Open or close current poll","[data-tw-live-bridge]","presenter.poll-primary"],["⇧ Q","Reveal held poll results","[data-tw-live-bridge]","presenter.poll-reveal"],["A","Open the questions tray","[data-tw-live-bridge]","presenter.questions"],["K","Compose a Quick poll","[data-tw-live-bridge]","presenter.poll-compose"],["⌥⌘I","Compose an instant slide",null,"presenter.instant-compose"],["⌘V","Preview clipboard as an instant slide",null,"presenter.instant-paste"],["→","Back to slide while instant slide is shown",null,"presenter.instant-return"],["U","Show the talk's QR code",null,"presenter.talk-qr"]]],["Board",[["⌥↵","Pick up or drop a board card",null,"presenter.board-pick"],["⌘Z","Undo the last board change",null,"presenter.board-undo"]]],["Editor",[["⌘E","Edit this slide in TalkWeaver","#twedit-btn","presenter.edit"],["⌘R / ⇧F5","Refresh with latest edits","#twedit-btn","presenter.refresh"]]]];
const AUDIENCE_REACTION_NAMES = {"puzzled":["frown","Puzzled by this","Puzzled by this"],"helped":["lightbulb","Helped me understand","Helped me understand"],"bookmark":["bookmark","Bookmark","Bookmark: I need to return to this"],"agree":["thumbs-up","Agree","Agree"],"disagree":["thumbs-down","Disagree","Disagree"],"yes":["check","Yes","Yes"],"no":["x","No","No"],"more":["message-circle-more","Tell me more","Tell me more"],"slower":["snail","Slower, please","Slower, please"]};
const PRESENTER_PALETTE = [["Slides",[{"id":"next","shortcut":"presenter.next","name":"Next","icon":"arrow-right","keys":"→","controls":["#presenterNext"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"previous","shortcut":"presenter.previous","name":"Previous","icon":"arrow-left","keys":"←","controls":["#presenterPrev"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"skip","shortcut":"presenter.skip","name":"Skip next slide","icon":"skip-forward","keys":"S","controls":["#skipNextBtn"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"return","shortcut":"presenter.return","name":"Return to where you jumped from","icon":"undo-2","keys":"B","controls":["#returnBtn","#moreReturn"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"first","shortcut":"presenter.first","name":"First slide","icon":"chevron-first","keys":"Home","controls":["#presenterFirst"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"last","shortcut":"presenter.last","name":"Last slide","icon":"chevron-last","keys":"End","controls":["#presenterLast"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"outline","shortcut":"presenter.overview","name":"Outline","icon":"list-tree","keys":"O","controls":["#outlineBtn","#viewOutline"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"grid-card","shortcut":"presenter.grid-child","name":"Go to card on a grid slide","icon":"layout-grid","keys":"1–9","controls":["#moreGridCard"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"embed","shortcut":"presenter.embed","name":"Interact with embedded page","icon":"mouse-pointer-click","keys":"E","controls":["#moreEmbed"],"code":null,"needs":null,"words":[],"task":"Present"}]],["Timer",[{"id":"timer","shortcut":"presenter.timer","name":"Start, pause or resume timer","icon":"timer","keys":"P","controls":["#twClockBtn","#twStartTimerBtn"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"duration","shortcut":"presenter.duration","name":"Talk length and reminders…","icon":"alarm-clock","keys":"T","controls":["#twDurationBtn"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"reset-timer","shortcut":null,"name":"Reset timer","icon":"timer-reset","keys":"","controls":["#twResetBtn"],"code":null,"needs":null,"words":[],"task":"Present"}]],["Recording",[{"id":"record-start","shortcut":"presenter.record","name":"Start recording","icon":"circle-dot","keys":"⇧R","controls":["#twrec-primary"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"record-pause","shortcut":"presenter.record-pause","name":"Pause or resume recording","icon":"circle-pause","keys":"⇧P","controls":["#twrec-pause","#twrec-resume"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"record-stop","shortcut":"presenter.record","name":"Stop and save recording","icon":"square","keys":"⇧R","controls":["#twrec-stop"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"save-run-as","shortcut":"presenter.save-run-as","name":"Save run as…","icon":"tags","keys":"L","controls":["#twrec-change-kind"],"code":"l","needs":"#twrec-module","words":["run kind","history","change"],"task":"Present"}]],["Live",[{"id":"live","shortcut":"presenter.live","name":"Go live or end live session","icon":"radio","keys":"G","controls":["#liveGoButton","#presenterEndLive","#presenterGoLive"],"code":null,"needs":"[data-tw-live-bridge]","words":[],"task":"Present"},{"id":"audience","shortcut":"presenter.audience","name":"Open audience window","icon":"monitor-up","keys":"F5","controls":["#presenterAudienceApp"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"join-link","shortcut":null,"name":"Show join link and venue screen","icon":"scan-qr-code","keys":"","controls":["#liveShowJoin"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"copy-venue-link","shortcut":null,"name":"Copy venue-screen link","icon":"link","keys":"","controls":["#liveCopyVenueLink"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"allow-questions","shortcut":null,"name":"Allow slide questions","icon":"message-circle-question-mark","keys":"","controls":["#liveAllowQuestions"],"code":null,"needs":"[data-tw-live-bridge]","words":["pause","phones","audience"],"task":"Present"},{"id":"allow-reactions","shortcut":null,"name":"Allow slide reactions","icon":"smile-plus","keys":"","controls":["#liveAllowReactions"],"code":null,"needs":"[data-tw-live-bridge]","words":["pause","phones","audience"],"task":"Present"},{"id":"talk-qr","shortcut":"presenter.talk-qr","name":"Show talk QR code","icon":"qr-code","keys":"U","controls":["#liveTalkQr"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"instant-compose","shortcut":"presenter.instant-compose","name":"Compose instant slide…","icon":"zap","keys":"⌥⌘I","controls":["#presenterInstantButton","#navInstant"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"instant-paste","shortcut":"presenter.instant-paste","name":"Instant slide from clipboard","icon":"clipboard","keys":"⌘V","controls":["#liveInstantPaste"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"instant-back","shortcut":"presenter.instant-return","name":"Back to slide","icon":"undo-2","keys":"→","controls":["#liveInstantBack","#presenterInstantBack"],"code":null,"needs":null,"words":[],"task":"Present"}]],["Poll and questions",[{"id":"quick-poll","shortcut":"presenter.poll-compose","name":"Compose Quick poll…","icon":"vote","keys":"K","controls":["#presenterQuickPollButton","#navQuickPoll"],"code":null,"needs":"[data-tw-live-bridge]","words":[],"task":"Present"},{"id":"poll-primary","shortcut":"presenter.poll-primary","name":"Open or close current poll","icon":"lock-open","keys":"Q","controls":["#pollMenuPrimary","#presenterPollOpen","#presenterPollClose"],"code":null,"needs":"[data-tw-live-bridge]","words":[],"task":"Present"},{"id":"poll-reveal","shortcut":"presenter.poll-reveal","name":"Reveal results","icon":"eye","keys":"⇧ Q","controls":["#pollMenuReveal","#presenterPollReveal"],"code":null,"needs":"[data-tw-live-bridge]","words":[],"task":"Present"},{"id":"poll-panel","shortcut":null,"name":"Show poll panel","icon":"chart-bar","keys":"","controls":["#presenterPollPanelToggle"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"quick-poll-restore","shortcut":null,"name":"Show Quick poll on screens","icon":"monitor-play","keys":"","controls":["#presenterQuickPollRestore"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"quick-poll-dismiss","shortcut":null,"name":"Dismiss Quick poll","icon":"x","keys":"","controls":["#presenterQuickPollDismiss"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"board-close","shortcut":"presenter.poll-primary","name":"Close board to new cards or reopen it","icon":"lock","keys":"Q","controls":["#pollMenuBoardClose"],"code":null,"needs":"[data-tw-live-bridge]","words":["board","cards"],"task":"Present"},{"id":"board-freeze","shortcut":null,"name":"Freeze or unfreeze the board","icon":"snowflake","keys":"","controls":["#pollMenuBoardFreeze"],"code":null,"needs":"[data-tw-live-bridge]","words":["board","final"],"task":"Present"},{"id":"board-panel","shortcut":null,"name":"Show board panel","icon":"layout-grid","keys":"","controls":["#pollMenuBoardPanel"],"code":null,"needs":null,"words":["board","inbox"],"task":"Present"},{"id":"board-full","shortcut":null,"name":"Board full screen","icon":"maximize-2","keys":"","controls":["#pollMenuBoardFull"],"code":null,"needs":null,"words":["board"],"task":"Present"},{"id":"board-popout","shortcut":null,"name":"Pop out the board","icon":"picture-in-picture-2","keys":"","controls":["#pollMenuBoardPopout"],"code":null,"needs":null,"words":["board","window","screen"],"task":"Present"},{"id":"questions","shortcut":"presenter.questions","name":"Open questions","icon":"message-circle-question-mark","keys":"A","controls":["#pollMenuQuestions"],"code":null,"needs":"[data-tw-live-bridge]","words":[],"task":"Present"}]],["View",[{"id":"previews-larger","shortcut":"presenter.preview-size","name":"Larger previews","icon":"gallery-vertical-end","keys":"]","controls":[],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"previews-smaller","shortcut":"presenter.preview-size","name":"Smaller previews","icon":"gallery-vertical-end","keys":"[","controls":[],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"notes-off","shortcut":null,"name":"Notes: off","icon":"eye-off","keys":"","controls":["[data-notes-placement-option=\"off\"]"],"code":null,"needs":null,"words":["placement"],"task":"Present"},{"id":"notes-bottom","shortcut":null,"name":"Notes: bottom","icon":"panel-bottom","keys":"","controls":["[data-notes-placement-option=\"bottom\"]"],"code":null,"needs":null,"words":["placement"],"task":"Present"},{"id":"notes-sidebar","shortcut":null,"name":"Notes: sidebar","icon":"panel-right","keys":"","controls":["[data-notes-placement-option=\"sidebar\"]"],"code":null,"needs":null,"words":["placement"],"task":"Present"},{"id":"notes-top-band","shortcut":null,"name":"Notes: top band","icon":"panel-top","keys":"","controls":["[data-notes-placement-option=\"top-band\"]"],"code":null,"needs":null,"words":["placement","teleprompter"],"task":"Present"},{"id":"notes-camera-column","shortcut":null,"name":"Notes: camera column","icon":"webcam","keys":"","controls":["[data-notes-placement-option=\"camera-column\"]"],"code":null,"needs":null,"words":["placement","teleprompter"],"task":"Present"},{"id":"notes-scroll-hand","shortcut":null,"name":"Notes scroll by hand","icon":"hand","keys":"","controls":["[data-notes-scroll-option=\"hand\"]"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"notes-scroll-auto","shortcut":null,"name":"Notes scroll automatically","icon":"play","keys":"","controls":["[data-notes-scroll-option=\"auto\"]"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"notes-forward","shortcut":"presenter.notes-scroll","name":"Step notes forward","icon":"chevrons-down","keys":"J","controls":[],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"notes-back","shortcut":"presenter.notes-scroll","name":"Step notes back","icon":"chevrons-up","keys":"⇧J","controls":[],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"notes-faster","shortcut":null,"name":"Notes scroll faster","icon":"plus","keys":"","controls":["#notesWpmFaster"],"code":null,"needs":null,"words":["speed"],"task":"Present"},{"id":"notes-slower","shortcut":null,"name":"Notes scroll slower","icon":"minus","keys":"","controls":["#notesWpmSlower"],"code":null,"needs":null,"words":["speed"],"task":"Present"}]],["Slide on every screen",[{"id":"reveal","shortcut":"presenter.reveal","name":"Reveal mode","icon":"layers","keys":"R","controls":["#viewReveal","#presenterReveal"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"focus","shortcut":"presenter.focus","name":"Focus mode","icon":"focus","keys":"F","controls":["#presenterFocus","#viewFocus"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"pointer","shortcut":"presenter.pointer","name":"Pointer","icon":"mouse-pointer-2","keys":"I","controls":["#presenterPointer","#viewPointer","#morePointer"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"pen","shortcut":"presenter.pen","name":"Pen","icon":"pen-tool","keys":"D","controls":["#presenterPen","#viewPen","#morePen"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"pen-freehand","shortcut":null,"name":"Pen tool: Freehand","icon":"pen-line","keys":"","controls":["#penToolFreehand","#penStripFreehand"],"code":null,"needs":null,"words":["draw"],"task":"Present"},{"id":"pen-arrow","shortcut":null,"name":"Pen tool: Arrow","icon":"move-up-right","keys":"","controls":["#penToolArrow","#penStripArrow"],"code":null,"needs":null,"words":["draw"],"task":"Present"},{"id":"pen-rectangle","shortcut":null,"name":"Pen tool: Rectangle","icon":"square","keys":"","controls":["#penToolRectangle","#penStripRectangle"],"code":null,"needs":null,"words":["draw","box"],"task":"Present"},{"id":"pen-next-tool","shortcut":"presenter.pen-tool","name":"Pen: next tool","icon":"pen-tool","keys":"W","controls":[],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"ink-undo","shortcut":"presenter.ink-undo","name":"Undo last stroke","icon":"undo-2","keys":"⌘Z","controls":["#penUndo","#penStripUndo"],"code":null,"needs":null,"words":["pen","drawing"],"task":"Present"},{"id":"ink-clear","shortcut":"presenter.ink-clear","name":"Clear drawing on this slide","icon":"eraser","keys":"X","controls":["#presenterInkClear","#viewInkClear","#moreInkClear"],"code":null,"needs":null,"words":["pen"],"task":"Present"},{"id":"ink-clear-all","shortcut":"presenter.ink-clear-all","name":"Clear all drawings","icon":"eraser","keys":"⇧X","controls":["#viewInkClearAll","#moreInkClearAll"],"code":null,"needs":null,"words":["pen"],"task":"Present"},{"id":"highlight","shortcut":"presenter.highlight","name":"Highlight text","icon":"highlighter","keys":"H","controls":["#presenterHighlight","#viewHighlight"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"highlight-clear","shortcut":null,"name":"Clear highlights","icon":"eraser","keys":"","controls":["#presenterHighlightClear","#viewHighlightClear","#presenterHighlightChipClear"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"font-smaller","shortcut":"presenter.font-smaller","name":"Slide text smaller","icon":"a-arrow-down","keys":"−","controls":["#fontDown","#viewFontDown"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"font-larger","shortcut":"presenter.font-larger","name":"Slide text larger","icon":"a-arrow-up","keys":"+","controls":["#fontUp","#viewFontUp"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"media","shortcut":"presenter.media","name":"Play or pause media","icon":"play","keys":"M","controls":["#presenterMediaPlay","#presenterMediaPause"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"video-fullscreen","shortcut":"presenter.video-fullscreen","name":"Video full screen","icon":"fullscreen","keys":"V","controls":["#presenterVideoFullscreen"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"embed-fullscreen","shortcut":"presenter.embed-fullscreen","name":"Embedded page: full screen","icon":"maximize-2","keys":"Z","controls":["#presenterEmbedFullscreen"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"gallery","shortcut":"presenter.gallery","name":"Image gallery","icon":"images","keys":"Z","controls":["#presenterGalleryBtn"],"code":null,"needs":null,"words":[],"task":"Present"}]],["Editor and help",[{"id":"edit","shortcut":"presenter.edit","name":"Edit this slide in TalkWeaver","icon":"pencil","keys":"⌘E","controls":["#twedit-btn"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"refresh","shortcut":"presenter.refresh","name":"Refresh with latest edits","icon":"refresh-cw","keys":"⌘R / ⇧F5","controls":["#moreRefresh"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"shortcuts","shortcut":"presenter.help","name":"Keyboard shortcuts","icon":"keyboard","keys":"?","controls":["#viewShortcuts"],"code":null,"needs":null,"words":[],"task":"Present"},{"id":"guide","shortcut":null,"name":"Guide: Present chapter","icon":"graduation-cap","keys":"","controls":["#twguide-chip"],"code":null,"needs":"#twguide-chip","words":["learn","onboarding","chapter","tried"],"task":"Present"}]]];
/*END_SHORTCUT_HELP*/
// ── The Guide's tick reports (onboarding 0.38.1 ticket 10) ──────────────────────────────────
// When a presenter command runs, by its key, a rebound key, the palette, a button or a menu item,
// the presenter says so once per page with a DOM event: the TalkWeaver bridge preload forwards it
// to main, which ticks the Guide's Present chapter (src/preload/present-edit-bridge.ts). A deck
// opened on its own has no listener. Nothing here changes what a command does; after the first
// report of an id, a press costs one Set lookup.
const guideReported = new Set();
function reportGuideCommand(id) {
if (!isPresenter || isReplay || typeof id !== "string" || !id || guideReported.has(id)) return;
guideReported.add(id);
try { window.dispatchEvent(new CustomEvent("tw-guide-command-ran", { detail: id })); } catch { /* never fails a command */ }
}
// A palette entry's command: its key's registry id, or the entry itself when it has no key.
const guideIdOfEntry = (entry) => entry.shortcut || `presenter-palette.${entry.id}`;
const guideIdOfOverride = (id) => (id.startsWith("palette.") ? `presenter-palette.${id.slice(8)}` : id);
let guideChords = null;
// The command a default key ran, read after handleKey acted on it (it prevented the default).
// Keys that mean two commands are told apart by the state handleKey read.
function guideKeyCommand(event) {
if (/^[1-9]$/.test(event.key) && !event.metaKey && !event.ctrlKey && !event.altKey) return "presenter.grid-child";
const chord = presenterChord(event);
if (!chord) return null;
if (!guideChords) {
guideChords = new Map();
for (const command of PRESENTER_COMMAND_KEYS) {
for (const code of command.codes) { const c = presenterCodeChord(code); if (c && !guideChords.has(c)) guideChords.set(c, command.id); }
}
}
const id = guideChords.get(chord) ?? null;
if (id === "presenter.next" && chord === "ArrowRight" && instantActive) return "presenter.instant-return";
if (id === "presenter.gallery" && !slideImages().length) return "presenter.embed-fullscreen";
if (id === "presenter.ink-undo" && !penArmed) return "presenter.board-undo";
return id;
}
// A press on a control: its registry id (PRESENTER_CONTROL_COMMANDS), else the key-less palette
// entry whose control it is (Reset timer, the notes placements, the pen tools, Clear highlights).
let guideKeylessControls = null;
function guideControlCommand(target) {
const control = target?.closest?.("button, [role=menuitem], [role=menuitemcheckbox]");
if (!control) return null;
if (control.id && PRESENTER_CONTROL_COMMANDS[control.id]) return PRESENTER_CONTROL_COMMANDS[control.id];
if (!guideKeylessControls) guideKeylessControls = PRESENTER_PALETTE.flatMap(([, entries]) => entries).filter((entry) => !entry.shortcut && entry.controls.length);
const entry = guideKeylessControls.find((item) => item.controls.some((selector) => control.matches(selector)));
return entry ? guideIdOfEntry(entry) : null;
}
function initialisePresenterShortcuts() {
presenterShortcuts = createPresenterShortcuts({ document, storage: localStorage,
commands: PRESENTER_COMMAND_KEYS,
onChange: () => {
refreshPresenterShortcuts();
renderPresenterCommands();
if (els.twShortcuts && !els.twShortcuts.hidden) renderShortcuts();
}
});
refreshPresenterShortcuts();
// Preloads mount their controls later; their tooltip keys use the same overrides.
const shortcutControls = new MutationObserver(() => {
// jsdom closes a window without pagehide; do not refresh controls after its document is gone.
if (!document?.documentElement?.isConnected) { shortcutControls.disconnect(); return; }
refreshPresenterShortcuts();
});
shortcutControls.observe(els.presenterRoot, { childList: true, subtree: true });
window.addEventListener('pagehide', () => shortcutControls.disconnect(), { once: true });
window.addEventListener('beforeunload', () => shortcutControls.disconnect(), { once: true });
// A press on a presenter control (bar, menus, status bar, the preloads' buttons) reports its command.
document.addEventListener("click", (event) => reportGuideCommand(guideControlCommand(event.target)), true);
// Capture before preloads and the legacy handler, so overrides work for every registry command.
window.addEventListener('keydown', event => {
if (shortcutForwarded.has(event) || event.target?.closest?.('.tw-shortcut-rebind')) return;
const typing = event.target?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable=false])');
if (!commandPalette.hidden || typing) return;
const match = presenterShortcuts.match(event);
if (match) {
event.preventDefault();
event.stopImmediatePropagation();
const entry = PRESENTER_PALETTE.flatMap(([, entries]) => entries).find(item => item.id === match.entryId);
syncPaletteSources();
reportGuideCommand(guideIdOfOverride(match.id));
const action = entry && paletteAction(entry);
if (action) action();
else {
const command = PRESENTER_COMMAND_KEYS.find(item => item.id === match.id);
if (command?.codes[0]) {
const replay = paletteKeyEvent(command.codes[0]);
shortcutForwarded.add(replay);
window.dispatchEvent(replay);
}
}
}
}, true);
}
// A control's visible label, set without dropping its icon (label setters run before and after
// the icons are applied, so both shapes are handled).
function twSetLabel(el, text) {
if (!el) return;
const label = el.querySelector(":scope > .tw-btn-label");
if (label) label.textContent = text; else el.textContent = text;
}
function twIconEl(name) {
const t = document.createElement("template");
t.innerHTML = PRESENTER_ICONS[name] || "";
return t.content.firstElementChild;
}
function twDressControl(el, id) {
const tip = PRESENTER_TIPS[id];
// A name already set by state (the timer button, a preload's live button) wins over the default.
if (tip) { if (!el.dataset.tip) el.dataset.tip = tip[0]; el.dataset.key = presenterShortcuts?.key(PRESENTER_CONTROL_COMMANDS[id], tip[1]) ?? tip[1]; }
el.removeAttribute("title");
const spec = PRESENTER_ICON_OF[id];
if (spec && !el.querySelector(":scope > svg.tw-ico")) {
const [icon, after, iconOnly] = spec;
const label = document.createElement("span");
label.className = "tw-btn-label";
while (el.firstChild) label.appendChild(el.firstChild);
if (iconOnly) label.hidden = true;
const svg = twIconEl(icon);
if (after) el.append(label, svg); else el.append(svg, label);
}
if (tip && !el.getAttribute("aria-label") && !el.textContent.trim()) el.setAttribute("aria-label", tip[0]);
}
function renderShortcuts() {
const body = els.twShortcutsBody;
if (!body) return;
body.replaceChildren();
for (const [section, all] of SHORTCUTS_LIST) {
// A row whose key a preload provides (recording, the editor keys) shows only when it has
// mounted: the sheet lists only keys that work in this window.
const rows = all.filter(([, , needs]) => !needs || document.querySelector(needs));
if (!rows.length) continue;
const h = document.createElement("div"); h.className = "tw-shortcuts-section"; h.textContent = section; body.appendChild(h);
for (const [keys, label, , registryId] of rows) {
const row = document.createElement("div"); row.className = "tw-shortcuts-row";
const k = document.createElement("kbd"); k.className = "tw-shortcuts-keys"; k.textContent = presenterShortcuts.key(registryId, keys);
const l = document.createElement("span"); l.textContent = label;
row.append(k, l); body.appendChild(row);
}
}
}
function toggleShortcuts(force) {
const el = els.twShortcuts; if (!el) return;
const show = force != null ? force : el.hidden;
if (show) renderShortcuts();
el.hidden = !show;
}
if (isPresenter) {
// Strip the slow, wordy native titles; the delegated tooltip below shows name and key.
document.querySelectorAll("#presenterRoot button[title]").forEach((b) => b.removeAttribute("title"));
for (const id in PRESENTER_TIPS) { const el = document.getElementById(id); if (el) twDressControl(el, id); }
// Status marks that are not controls (the go-live panel's "You are live"), and the composers'
// titles, type tabs and own buttons (labelled by their words in context, so no tooltip).
document.querySelectorAll("#presenterRoot [data-icon]").forEach((el) => {
if (el.querySelector(":scope > svg.tw-ico")) return;
const label = document.createElement("span"); label.className = "tw-btn-label";
while (el.firstChild) label.appendChild(el.firstChild);
const svg = twIconEl(el.dataset.icon);
el.append(...(svg ? [svg] : []), label);
});
const tip = document.createElement("div");
tip.className = "tw-tip"; tip.setAttribute("aria-hidden", "true"); tip.hidden = true;
const tipName = document.createElement("span"); tipName.className = "tw-tip-name";
const tipKey = document.createElement("span"); tipKey.className = "tw-tip-key";
tip.append(tipName, tipKey);
document.body.appendChild(tip);
let tipOwner = null;
const hideTip = () => { tip.hidden = true; tipOwner = null; };
const showTip = (el) => {
el.removeAttribute("title"); // a preload's control may still carry one; never two tooltips
tipName.textContent = el.dataset.tip;
tipKey.textContent = el.dataset.key || "";
tipKey.hidden = !el.dataset.key;
tip.hidden = false;
const r = el.getBoundingClientRect();
const below = r.top < 120; // top-bar tooltips open below the bar (ADR-0031 drawing)
tip.classList.toggle("below", below);
const w = tip.offsetWidth;
tip.style.left = Math.round(Math.max(8 + w / 2, Math.min(innerWidth - 8 - w / 2, r.left + r.width / 2))) + "px";
tip.style.top = Math.round(below ? r.bottom + 8 : r.top - 8) + "px";
};
// Delegated on the document, so controls a preload adds later get the same tooltip. mouseover
// (not CSS :hover): a control that appears under a stationary cursor, such as Return after a
// jump, shows no tooltip until the pointer actually moves onto it.
document.addEventListener("mouseover", (e) => {
let el = e.target instanceof Element ? e.target.closest("[data-tip]") : null;
// Menu items are labelled by their own text; a menu button's name is not needed over its
// open menu.
if (el && (el.closest(".tw-menu, .notes-menu") || el.getAttribute("aria-expanded") === "true")) el = null;
if (el === tipOwner) return;
if (!el || !el.dataset.tip) { hideTip(); return; }
tipOwner = el; showTip(el);
});
document.addEventListener("mouseout", (e) => { if (!e.relatedTarget) hideTip(); });
document.addEventListener("mousedown", hideTip, true);
els.twShortcuts?.addEventListener("click", (e) => { if (e.target === els.twShortcuts) toggleShortcuts(false); });
}
// ── From phones · this talk (ADR-0027 amendment, 2026-09-29; reactions ticket 05) ─────────────
// Two switches in the Poll menu: "Allow slide questions" and "Allow slide reactions", on by
// default. The choice is a presenter-window preference kept per talk, like the notes override
// (same storage, key by the talk), so it survives closing and reopening the window. It reaches
// the worker as switches.set when the session goes live and on every change while one is up; the
// worker tells every following phone. While one is off the status bar keeps what it holds, dimmed,
// with a pause mark.
const AUDIENCE_SWITCHES_KEY = `html-presentations:${deckId}:audience-switches`;
const audienceSwitches = (() => {
try {
const saved = JSON.parse(notesStorage?.getItem(AUDIENCE_SWITCHES_KEY) || "null");
return { questionsAllowed: saved?.questionsAllowed !== false, reactionsAllowed: saved?.reactionsAllowed !== false };
} catch { return { questionsAllowed: true, reactionsAllowed: true }; }
})();
let audienceSwitchError = "";
let audienceSwitchesSynced = false;
const AUDIENCE_SWITCH_ITEMS = [
["liveAllowQuestions", "questionsAllowed", "Phones show Ask"],
["liveAllowReactions", "reactionsAllowed", "Phones show reactions"],
];
function audienceSessionUp(status) { return ["connecting", "live", "paused-reconnecting"].includes(status); }
function sendAudienceSwitches(patch) {
if (!isPresenter || !audienceSessionUp(talkQrLiveStatus)) return;
try {
Promise.resolve(window.twLivePollBridge?.setSwitches?.(patch)).then((result) => {
if (result?.success === false || result?.status === "rejected") { audienceSwitchError = result.error || "Could not update the phones. Try the switch again."; syncAudienceSwitchItems(); }
}).catch(() => {});
} catch {}
}
// The live status feeds this: a session that has just come up gets both switches once, whatever
// they are (the worker starts with both on), and a finished session forgets it was told.
function syncAudienceSwitchesOnStatus(status) {
if (status === "live" && !audienceSwitchesSynced) { audienceSwitchesSynced = true; sendAudienceSwitches({ ...audienceSwitches }); }
else if (!audienceSessionUp(status) && status !== "ending") audienceSwitchesSynced = false;
}
function setAudienceSwitch(name, allowed) {
if (audienceSwitches[name] === allowed) return;
audienceSwitches[name] = allowed;
audienceSwitchError = "";
try { notesStorage?.setItem(AUDIENCE_SWITCHES_KEY, JSON.stringify(audienceSwitches)); } catch { /* private mode: kept for this window */ }
syncAudienceSwitchItems();
renderAudienceSwitchMarks();
sendAudienceSwitches({ [name]: allowed });
}
function syncAudienceSwitchItems() {
for (const [id, key, on] of AUDIENCE_SWITCH_ITEMS) {
const item = document.getElementById(id);
if (!item) continue;
item.setAttribute("aria-checked", String(audienceSwitches[key]));
const sub = document.getElementById(id + "Sub");
if (sub) { sub.textContent = audienceSwitchError || (audienceSwitches[key] ? on : "Off. Paused on every phone"); sub.classList.toggle("is-error", Boolean(audienceSwitchError)); }
}
}
const AUDIENCE_CHIP_TIPS = {
presenterReactions: ["reactionsAllowed", "Reactions to this slide", "Reactions paused. Counts so far kept. Turn on in the Poll menu."],
presenterQuestions: ["questionsAllowed", "Questions", "Questions paused. The ones already in are kept. Turn on in the Poll menu."],
};
function renderAudienceSwitchMarks() {
for (const id in AUDIENCE_CHIP_TIPS) {
const el = document.getElementById(id);
if (!el) continue;
const [key, on, off] = AUDIENCE_CHIP_TIPS[id];
const paused = !audienceSwitches[key];
el.dataset.paused = String(paused);
// A custom-label chip names its labels in the tooltip (ticket 04, D11) while it is on.
el.dataset.tip = paused ? off : (el.dataset.tipOn || on);
let mark = el.querySelector(":scope > .tw-pause-mark");
if (paused && !mark) {
mark = document.createElement("span"); mark.className = "tw-pause-mark"; mark.setAttribute("aria-hidden", "true");
const icon = twIconEl("pause"); if (icon) { icon.classList.add("tw-ico"); mark.appendChild(icon); }
el.appendChild(mark);
}
if (mark) mark.hidden = !paused;
}
}
// ── Top-bar menus: Live, Poll, View (ADR-0031 §2, presenter redesign ticket 04) ──────────────
// PRESENTER_MENU_COMMANDS is the command registry the menu items call: per item id, `run` (the
// same function its key calls) and `enabled` (when the item applies; otherwise it shows
// disabled). Items that kept the id of the top-bar button they replace have no `run`: the
// button's own click listener (which F5, a preload or another caller also reaches) runs the
// command, so pressing the item and the old button are the same event. The live preload owns
// Go live, Show join link and Copy venue-screen link, and sets their names and states.
const PRESENTER_MENU_COMMANDS = {
liveAllowQuestions: { run: () => setAudienceSwitch("questionsAllowed", !audienceSwitches.questionsAllowed), checked: () => audienceSwitches.questionsAllowed, stayOpen: true },
liveAllowReactions: { run: () => setAudienceSwitch("reactionsAllowed", !audienceSwitches.reactionsAllowed), checked: () => audienceSwitches.reactionsAllowed, stayOpen: true },
liveTalkQr: { run: toggleTalkQr },
liveInstantPaste: { run: () => { void instantFromClipboard(); } },
liveInstantBack: { run: clearInstant, enabled: () => Boolean(instantActive) },
presenterQuickPollRestore: { enabled: () => quickPollHidden() },
pollMenuPrimary: { run: presenterPollPrimaryAction, enabled: () => Boolean(presenterPollForDisplay()) },
pollMenuReveal: { run: presenterPollRevealAction, enabled: () => Boolean(presenterPollForDisplay()) },
presenterPollPanelToggle: { enabled: () => pollPanelDismissed() },
// The questions tray (key A): the item shows the count and applies while a session is up.
pollMenuQuestions: { run: () => openQuestionsTray(!questionsTray.open), enabled: () => questionsTrayAvailable() },
pollMenuBoardClose: { run: presenterBoardPrimary, enabled: () => boardMenuEnabled("close") },
pollMenuBoardFreeze: { run: () => { const view = boardUi?.controller.view(); if (view) boardUi.controller.apply({ op: "freeze", frozen: !view.frozen }); }, enabled: () => boardMenuEnabled("freeze") },
pollMenuBoardPanel: { run: showBoardPanel, enabled: () => boardMenuEnabled("panel") },
pollMenuBoardFull: { run: () => setBoardMode("full"), enabled: () => boardMenuEnabled("full") },
pollMenuBoardPopout: { run: popOutBoard, enabled: () => boardMenuEnabled("popout") },
notesPlacementBtn: { run: () => toggleNotesMenu(true), keepFocus: true },
viewOutline: { run: () => overview.toggle() },
viewFontDown: { run: () => publish({ fontSize: state.fontSize - 10 }), stayOpen: true },
viewFontUp: { run: () => publish({ fontSize: state.fontSize + 10 }), stayOpen: true },
viewReveal: { run: () => toggleMode("reveal"), checked: () => state.mode?.kind === "reveal" },
viewFocus: { run: () => toggleMode("focus"), checked: () => state.mode?.kind === "focus" },
viewPointer: { run: togglePointer, checked: () => pointerArmed },
viewPen: { run: togglePen, checked: () => penArmed },
viewInkClear: { run: clearInkHere, enabled: inkHere },
viewInkClearAll: { run: clearAllInk, enabled: () => (penStore?.size() || 0) > 0 },
viewHighlight: { run: toggleHighlightArmed, checked: () => highlightArmed },
viewHighlightClear: { run: clearCurrentSlideHighlights, enabled: () => currentHighlight.slideId === (currentSlide()?.dataset.id || null) && currentHighlight.ranges.length > 0 },
viewShortcuts: { run: () => toggleShortcuts() },
viewCommands: { run: () => togglePresenterCommands() },
};
// The questions count, as the audience counts report it (live status: talkQrLiveStatus, from
// the live bridge).
let menuQuestions = null;
function syncPresenterMenu(menu) {
for (const item of menu.querySelectorAll("button[id]")) {
const command = PRESENTER_MENU_COMMANDS[item.id];
if (command?.enabled) item.disabled = !command.enabled();
if (command?.checked) item.setAttribute("aria-checked", String(Boolean(command.checked())));
}
syncAudienceSwitchItems();
syncBoardMenu();
const sub = document.getElementById("pollMenuQuestionsSub");
if (sub) sub.textContent = ["live", "paused-reconnecting"].includes(talkQrLiveStatus) ? `${menuQuestions ?? 0} waiting` : "While live";
}
// The menus: open and close, keyboard, and running an item. One open at a time; opening one
// closes the Notes menu and the clock popover. Mouse presses never move focus onto a menu button
// or item (Space would then open the menu instead of moving to the next slide); from the
// keyboard, Enter, Space or ↓ on a menu button opens its menu on the first item, ↑ ↓ Home End
// move, ← → go to the next menu, Enter or Space runs the item, Esc and Tab close.
function createTopBarMenus(root, { commands, sync, beforeOpen }) {
const buttons = [...root.querySelectorAll(".tw-menu-btn")];
const menuOf = (button) => document.getElementById(button.getAttribute("aria-controls"));
let open = null;
let viaKeyboard = false;
// ↑ ↓ move by rows: an item, or a row with a segmented control (Previews, Slide text), which
// takes focus on its pressed (or first) button; ← → move within that control.
const rows = (menu) => [...menu.querySelectorAll(".tw-mi, .tw-menu-row")].filter((row) => row.getClientRects().length > 0 && !(row.matches(".tw-mi") && row.disabled));
const rowTarget = (row) => (row?.matches(".tw-mi") ? row : row?.querySelector("button[aria-pressed=\"true\"]") || row?.querySelector("button"));
const focusRow = (menu, index) => { const list = rows(menu); if (list.length) rowTarget(list[(index + list.length) % list.length])?.focus(); };
function close({ focusButton = false } = {}) {
if (!open) return;
const button = open;
const menu = menuOf(button);
menu.hidden = true;
button.setAttribute("aria-expanded", "false");
open = null;
if (focusButton) button.focus();
else if (menu.contains(document.activeElement)) document.activeElement.blur();
}
function show(button, { keyboard = false, focus = "first" } = {}) {
if (open === button) return;
close();
beforeOpen?.();
const menu = menuOf(button);
sync(menu);
menu.hidden = false;
button.setAttribute("aria-expanded", "true");
open = button;
viaKeyboard = keyboard;
if (keyboard) focusRow(menu, focus === "last" ? -1 : 0);
}
function toggle(button, keyboard) {
if (open === button) { close({ focusButton: keyboard }); return; }
// The Notes menu hangs under View: while it is open, View closes it.
if (button === els.presenterMenuView && notesMenuOpen()) { toggleNotesMenu(false); return; }
show(button, { keyboard });
}
function runItem(item) {
const command = commands[item.id];
const keyboard = viaKeyboard;
if (!command?.stayOpen) close({ focusButton: keyboard && !command?.keepFocus });
// Items without `run` are the top-bar buttons they replaced; their own listener has run.
command?.run?.();
if (command?.stayOpen) sync(menuOf(open || buttons[0]));
if (command?.keepFocus && keyboard) els.notesMenu?.querySelector("button[aria-pressed=\"true\"], button")?.focus();
}
for (const button of buttons) {
button.addEventListener("mousedown", (event) => event.preventDefault());
button.addEventListener("click", (event) => toggle(button, event.detail === 0));
const menu = menuOf(button);
menu.addEventListener("mousedown", (event) => { if (event.target.closest("button")) event.preventDefault(); });
// Whether the item was disabled is read BEFORE its own click listener runs (capture): an item
// whose handler disables itself while it works (Go live → "Going live…") must still run
// here and close the menu, or the open menu covers what the item just showed.
let itemWasDisabled = false;
menu.addEventListener("click", (event) => { itemWasDisabled = !!event.target.closest("button")?.disabled; }, true);
menu.addEventListener("click", (event) => {
const item = event.target.closest("button");
if (!item || itemWasDisabled || !menu.contains(item)) return;
if (item.matches("[data-preview-size-option]")) { setPreviewSize(item.dataset.previewSizeOption); return; }
runItem(item);
});
}
// Keys, before the presenter's own key handler (arrows and Space must not move the slide
// while a menu has focus).
window.addEventListener("keydown", (event) => {
const onButton = buttons.includes(event.target);
if (!open && !onButton) return;
const key = event.key;
const stop = () => { event.preventDefault(); event.stopImmediatePropagation(); };
if (!open) {
if (key === "Enter" || key === " " || key === "ArrowDown") { stop(); show(event.target, { keyboard: true }); }
else if (key === "ArrowUp") { stop(); show(event.target, { keyboard: true, focus: "last" }); }
return;
}
const menu = menuOf(open);
const active = menu.contains(document.activeElement) ? document.activeElement : null;
const at = rows(menu).indexOf(active?.closest(".tw-mi, .tw-menu-row"));
if (key === "Escape") { stop(); close({ focusButton: viaKeyboard || event.target === open }); return; }
if (key === "Tab") { close(); return; }
if (key === "ArrowDown" || key === "ArrowUp") {
stop(); viaKeyboard = true;
focusRow(menu, at < 0 ? (key === "ArrowDown" ? 0 : -1) : at + (key === "ArrowDown" ? 1 : -1));
return;
}
if (key === "Home" || key === "End") { stop(); viaKeyboard = true; focusRow(menu, key === "Home" ? 0 : -1); return; }
if (key === "ArrowLeft" || key === "ArrowRight") {
stop(); viaKeyboard = true;
const sibling = active?.closest(".tw-seg") ? (key === "ArrowRight" ? active.nextElementSibling : active.previousElementSibling) : null;
if (sibling) { sibling.focus(); return; }
const next = buttons[(buttons.indexOf(open) + (key === "ArrowRight" ? 1 : -1) + buttons.length) % buttons.length];
show(next, { keyboard: true });
return;
}
if ((key === "Enter" || key === " ") && active?.matches("button")) { stop(); viaKeyboard = true; active.click(); return; }
if (key === "Enter" || key === " ") { stop(); return; }
}, true);
// A press outside the open menu and its button closes it.
document.addEventListener("pointerdown", (event) => {
if (open && !menuOf(open).contains(event.target) && !open.contains(event.target)) close();
}, true);
return { open: (id) => { const b = buttons.find((x) => x.id === id); if (b) show(b); }, close, isOpen: () => open?.id || null };
}
let topBarMenus = null;
if (isPresenter && els.presenterMenus) {
// Each item's shortcut, right-aligned, from the registry (the generated block); the menu
// buttons' chevron.
for (const item of els.presenterMenus.querySelectorAll(".tw-mi, .tw-seg-btn")) {
// A switch item shows its switch where a shortcut would be.
if (item.classList.contains("tw-mi-switch")) { const sw = document.createElement("span"); sw.className = "tw-sw"; sw.setAttribute("aria-hidden", "true"); item.appendChild(sw); continue; }
const keys = PRESENTER_TIPS[item.id]?.[1] || "";
const kbd = document.createElement("span"); kbd.className = "kbd tw-mi-key"; kbd.textContent = keys; kbd.setAttribute("aria-hidden", "true");
item.appendChild(kbd);
}
for (const button of els.presenterMenus.querySelectorAll(".tw-menu-btn")) {
const chev = twIconEl("chevron-down");
if (chev) { chev.classList.add("tw-menu-chev"); chev.classList.remove("tw-btn-ico"); button.appendChild(chev); }
}
for (const option of els.notesMenu?.querySelectorAll("[data-notes-placement-option]") || []) {
const tick = twIconEl("check");
if (tick) { tick.classList.add("notes-menu-tick"); tick.classList.remove("tw-btn-ico"); option.appendChild(tick); }
}
for (const id of ["viewReveal", "viewFocus", "viewHighlight"]) document.getElementById(id)?.setAttribute("role", "menuitemcheckbox");
topBarMenus = createTopBarMenus(els.presenterMenus, {
commands: PRESENTER_MENU_COMMANDS,
sync: syncPresenterMenu,
beforeOpen: () => { toggleNotesMenu(false); openDurationSetter(false); moreMenu?.close(); },
});
}
// ── Bottom bar: the "…" More menu and the mode chips (ADR-0031 §4, presenter redesign ticket 05) ──
// More opens upward from the bottom bar and works like the top-bar menus (the same
// createTopBarMenus: click or keyboard to open, Esc or a press outside to close). Its items keep
// the ids of the bottom-bar buttons they replaced (First, Last, Reveal, Clear highlights, Slide
// text smaller / larger), whose own listeners run the command; the others run through
// PRESENTER_MORE_COMMANDS, each the function its key runs. Refresh with latest edits stays
// hidden unless the edit bridge (TalkWeaver) shows and wires it.
const PRESENTER_MORE_COMMANDS = {
morePointer: { run: togglePointer, checked: () => pointerArmed },
morePen: { run: togglePen, checked: () => penArmed },
moreInkClear: { run: clearInkHere, enabled: inkHere },
moreInkClearAll: { run: clearAllInk, enabled: () => (penStore?.size() || 0) > 0 },
moreReturn: { run: () => returnToOrigin(), enabled: () => jumpOrigin != null },
moreGridCard: { run: () => { const target = gridCardTarget(1); if (target) goToContainerChild(target); }, enabled: () => Boolean(gridCardTarget(1)) },
presenterReveal: { checked: () => armedMode() === "reveal" },
presenterHighlightClear: { enabled: () => slideHasHighlights() },
moreEmbed: { run: () => toggleEmbedInteract(), enabled: () => Boolean(interactingFrame || activeInteractFrame()) },
fontDown: { stayOpen: true },
fontUp: { stayOpen: true },
};
function syncMoreMenu(menu) {
for (const item of menu.querySelectorAll("button[id]")) {
const command = PRESENTER_MORE_COMMANDS[item.id];
if (command?.enabled) item.disabled = !command.enabled();
if (command?.checked) item.setAttribute("aria-checked", String(Boolean(command.checked())));
}
}
let moreMenu = null;
if (isPresenter && els.presenterBottomBar && els.presenterMoreMenu) {
for (const item of els.presenterMoreMenu.querySelectorAll(".tw-mi")) {
const kbd = document.createElement("span"); kbd.className = "kbd tw-mi-key"; kbd.textContent = PRESENTER_TIPS[item.id]?.[1] || ""; kbd.setAttribute("aria-hidden", "true");
item.appendChild(kbd);
}
moreMenu = createTopBarMenus(els.presenterBottomBar, {
commands: PRESENTER_MORE_COMMANDS,
sync: syncMoreMenu,
beforeOpen: () => { topBarMenus?.close(); toggleNotesMenu(false); openDurationSetter(false); },
});
// The Highlight chip's mark and words are fixed; the Reveal / Focus chip's follow the mode.
els.presenterHighlightMark?.replaceChildren(...[twIconEl(MODE_CHIP.highlight.icon)].filter(Boolean));
if (els.presenterHighlightWord) els.presenterHighlightWord.textContent = MODE_CHIP.highlight.word;
if (els.presenterHighlightExit) { els.presenterHighlightExit.dataset.tip = MODE_CHIP.highlight.exit; els.presenterHighlightExit.setAttribute("aria-label", MODE_CHIP.highlight.exit); }
initialisePresenterShortcuts();
modeChipReady = true;
penReady = true;
penViewChanged();
renderPenControls();
renderModeControls();
updateHighlightClearBtn();
}
function startOrToggleTimer() {
if (!timer.targetSeconds) { openDurationSetter(true); return; } // nothing to run yet
if (timer.runningSince) { // running -> pause
timer.elapsedMs += Date.now() - timer.runningSince;
timer.runningSince = null;
} else { // idle or paused -> run
timer.runningSince = Date.now();
}
persistTimer(); renderClock();
}
function applyDuration(minutes, close) {
// Reset the run + milestone/reminder firing, but PRESERVE chosen reminders (independent of length).
timer = { targetSeconds: Math.round(minutes * 60), elapsedMs: 0, runningSince: null, reminders: timer.reminders || [] };
timerFired = new Set();
remindersFired = new Set();
persistTimer();
const input = document.getElementById("twDurationInput");
if (input) input.value = String(Math.round(timer.targetSeconds / 60) || "");
syncSetterButtons();
if (close) openDurationSetter(false);
renderClock();
}
function toggleReminder(minutes) {
if (!Array.isArray(timer.reminders)) timer.reminders = [];
const i = timer.reminders.indexOf(minutes);
if (i >= 0) timer.reminders.splice(i, 1); else timer.reminders.push(minutes);
remindersFired.delete(minutes);
persistTimer(); syncSetterButtons();
}
function syncSetterButtons() {
const el = els.twDurationSetter;
if (!el) return;
const curMin = Math.round((timer.targetSeconds || 0) / 60);
el.querySelectorAll(".tw-duration-presets button").forEach((b) => b.classList.toggle("on", Number(b.dataset.minutes) === curMin));
el.querySelectorAll(".tw-reminder").forEach((b) => {
const on = (timer.reminders || []).includes(Number(b.dataset.remind));
b.classList.toggle("on", on);
b.setAttribute("aria-pressed", String(on));
});
}
function openDurationSetter(force) {
const el = els.twDurationSetter;
if (!el) return;
el.hidden = force != null ? !force : !el.hidden;
els.twDurationBtn?.setAttribute("aria-expanded", String(!el.hidden));
if (!el.hidden) {
const i = document.getElementById("twDurationInput");
if (i) { i.value = String(Math.round((timer.targetSeconds || 0) / 60) || ""); i.focus(); }
syncSetterButtons();
}
}
function renderClock() {
if (!isPresenter || !els.twClock) return;
const s = bigTimerState(Date.now(), timer, thresholds, timerFired);
if (s.milestone != null) {
for (const m of [0, thresholds.urgentAtSeconds, thresholds.warnAtSeconds]) if (m >= s.milestone) timerFired.add(m);
showPresenterBanner(MILESTONE_TEXT(thresholds.warnAtSeconds, thresholds.urgentAtSeconds)[s.milestone]);
}
// Presenter-set reminders ("N minutes before end"): fire once as the countdown crosses each mark.
if (s.status === "running") {
for (const rm of (timer.reminders || [])) {
if (s.seconds <= rm * 60 && !remindersFired.has(rm)) { remindersFired.add(rm); showPresenterBanner(`${rm} minute${rm === 1 ? "" : "s"} left`); }
}
}
els.twClock.textContent = s.seconds < 0 ? `+${fmtClock(-s.seconds)}` : fmtClock(s.seconds);
els.twClock.dataset.status = s.status;
els.twClock.dataset.level = s.level;
// The line under the clock (collapse step c1 drops it; the popover carries the length).
const target = fmtClock(timer.targetSeconds || 0);
if (els.twClockSub) els.twClockSub.textContent = s.status === "idle" ? "talk length" : s.seconds < 0 ? `over ${target}` : `left of ${target}`;
// The clock itself is the pause/resume button (ADR-0031 §2): its name follows the timer state.
if (els.twClockBtn) {
els.twClockBtn.dataset.tip = TIMER_BUTTON.names[s.status];
els.twClockBtn.setAttribute("aria-label", `${TIMER_BUTTON.names[s.status]} (${els.twClock.textContent} ${els.twClockSub?.textContent || ""})`.replace(" )", ")"));
els.twClockBtn.dataset.status = s.status;
}
// Start timer before the talk, Resume timer while paused; gone while the clock runs.
if (els.twStartTimerBtn) {
const hide = s.status === "running";
if (els.twStartTimerBtn.hidden !== hide) els.twStartTimerBtn.hidden = hide;
const name = TIMER_BUTTON.names[s.status === "paused" ? "paused" : "idle"];
if (els.twStartTimerBtn.dataset.tip !== name) {
twSetLabel(els.twStartTimerBtn, name);
els.twStartTimerBtn.dataset.tip = name;
els.twStartTimerBtn.classList.toggle("tw-resume-timer", s.status === "paused");
}
}
}
setInterval(() => { tickSectionTimer(); if (!isPresenter) return; renderClock(); tickReminders(); }, 500);
els.twClockBtn?.addEventListener("click", startOrToggleTimer);
els.twStartTimerBtn?.addEventListener("click", startOrToggleTimer);
// Reset the clock back to zero (idle at the same target); reminders + target are kept.
function resetTimer() {
timer = { targetSeconds: timer.targetSeconds, elapsedMs: 0, runningSince: null, reminders: timer.reminders || [5, 1] };
timerFired = new Set(); remindersFired = new Set();
persistTimer(); renderClock();
}
els.twResetBtn?.addEventListener("click", resetTimer);
els.twDurationBtn?.addEventListener("click", () => openDurationSetter());
els.twDurationSetter?.addEventListener("click", (e) => {
const btn = e.target.closest("button");
if (!btn) return;
if (btn.dataset.minutes != null) { applyDuration(Number(btn.dataset.minutes), true); return; }
if (btn.dataset.remind != null) { toggleReminder(Number(btn.dataset.remind)); return; }
if (btn.id === "twDurationMinus" || btn.id === "twDurationPlus") {
const input = document.getElementById("twDurationInput");
const cur = Number(input && input.value) || Math.round((timer.targetSeconds || 0) / 60) || 0;
applyDuration(Math.max(1, cur + (btn.id === "twDurationPlus" ? 5 : -5)), false);
}
});
document.getElementById("twDurationInput")?.addEventListener("keydown", (e) => {
if (e.key === "Escape") { openDurationSetter(false); return; }
if (e.key === "Enter") { const v = Number(e.target.value); if (v > 0) applyDuration(v, true); }
});
// The clock popover closes on Esc and on a press outside it and its chevron.
document.addEventListener("pointerdown", (event) => {
if (els.twDurationSetter && !els.twDurationSetter.hidden && !event.target.closest?.("#twDurationSetter, #twDurationBtn")) openDurationSetter(false);
}, true);
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && els.twDurationSetter && !els.twDurationSetter.hidden) { event.preventDefault(); event.stopImmediatePropagation(); openDurationSetter(false); }
}, true);
// Keys named in the popover's text come from the shortcut registry (the generated block).
document.querySelectorAll("#presenterTopBar [data-key-of]").forEach((el) => { el.textContent = PRESENTER_TIPS[el.dataset.keyOf]?.[1] || ""; });
if (isPresenter) renderClock();
// ── Status bar: reactions, questions and the collapse ladder (presenter redesign ticket 02) ──
// Reactions (ADR-0027 §4) and the questions counter (ADR-0004 §4) render only when a feature
// supplies counts for the current slide, through window.twLivePollBridge.onAudience(callback)
// with callback({ reactions: { puzzled, helped, bookmark } | null, questions: number | null }).
// The preload's live bridge feeds it the counts for the slide on screen (present-live-bridge.ts,
// audienceCountsView); the status-bar test also feeds a fixture through the same call.
// Ticket 04: the chip shows the slide's own set, read from the compiled slide's data-reactions
// (registered ids and custom: ids, [] for off; no attribute is the standard three). Named
// reactions carry their icon and a count; custom labels are counts only, "2 · 14 · 1", with the
// labels in the tooltip (D11); a slide with reactions off hides the chip and keeps the counter (D4).
const STANDARD_REACTION_SET = ["puzzled", "helped", "bookmark"];
const STANDARD_REACTION_ELS = { puzzled: "presenterReactPuzzled", helped: "presenterReactHelped", bookmark: "presenterReactBookmark" };
const countOf = (value) => Math.max(0, Math.floor(Number(value) || 0));
const customLabel = (id) => (id.startsWith("custom:") ? id.slice(7).trim() : "");
// The chip's accessible names: the bookmark count reads "Bookmarked", as the chip always said.
const reactionName = (id) => (id === "bookmark" ? "Bookmarked" : customLabel(id) || (AUDIENCE_REACTION_NAMES[id] || [])[2] || id);
function slideReactionSet(slideId) {
const index = slideId ? slideIndexById.get(slideId) : undefined;
const slide = index !== undefined ? slides[index] : currentSlide();
const raw = slide && slide.dataset ? slide.dataset.reactions : undefined;
if (raw == null) return STANDARD_REACTION_SET;
let list;
try { list = JSON.parse(raw); } catch { return STANDARD_REACTION_SET; }
if (!Array.isArray(list)) return STANDARD_REACTION_SET;
const set = [];
for (const value of list) {
const id = String(value);
if (set.includes(id) || !(AUDIENCE_REACTION_NAMES[id] || customLabel(id))) continue;
set.push(id);
if (set.length === 4) break;
}
return set;
}
let chipSetKey = STANDARD_REACTION_SET.join("\n");
function buildReactionChip(set) {
const chip = els.presenterReactions;
chip.querySelectorAll(":scope > [data-rx], :scope > .tw-rx-sep").forEach((el) => el.remove());
const mark = chip.querySelector(":scope > .tw-pause-mark");
set.forEach((id, index) => {
const custom = Boolean(customLabel(id));
if (custom && index > 0) {
const sep = document.createElement("span"); sep.className = "tw-rx-sep"; sep.setAttribute("aria-hidden", "true"); sep.textContent = "·";
chip.insertBefore(sep, mark);
}
const span = document.createElement("span");
span.dataset.rx = id;
if (STANDARD_REACTION_ELS[id]) span.id = STANDARD_REACTION_ELS[id];
if (!custom) { const icon = twIconEl(AUDIENCE_REACTION_NAMES[id][0]); if (icon) span.appendChild(icon); }
const label = document.createElement("span"); label.className = "tw-btn-label"; label.textContent = "0";
span.appendChild(label);
chip.insertBefore(span, mark);
});
chipSetKey = set.join("\n");
}
function renderAudienceCounts(counts) {
if (!isPresenter) return;
const reactions = counts && counts.reactions;
if (els.presenterReactions) {
const set = reactions ? slideReactionSet(counts.slideId) : STANDARD_REACTION_SET;
els.presenterReactions.hidden = !reactions || set.length === 0;
if (reactions && set.length) {
if (set.join("\n") !== chipSetKey) buildReactionChip(set);
for (const el of els.presenterReactions.querySelectorAll(":scope > [data-rx]")) {
const id = el.dataset.rx;
twSetLabel(el, String(countOf(reactions[id])));
el.setAttribute("aria-label", `${reactionName(id)}: ${countOf(reactions[id])}`);
}
// Custom labels are numbers on the chip; the tooltip names them in the chip's order (D11).
if (set.some((id) => customLabel(id))) els.presenterReactions.dataset.tipOn = set.map((id) => `${customLabel(id) || (AUDIENCE_REACTION_NAMES[id] || [])[1] || id} ${countOf(reactions[id])}`).join(" · ");
else delete els.presenterReactions.dataset.tipOn;
renderAudienceSwitchMarks();
}
}
const questions = counts ? counts.questions : null;
if (els.presenterQuestions) {
const has = questions != null && Number.isFinite(Number(questions));
els.presenterQuestions.hidden = !has;
menuQuestions = has ? countOf(questions) : null;
if (has) {
twSetLabel(els.presenterQuestions, String(countOf(questions)));
els.presenterQuestions.setAttribute("aria-label", `Questions waiting: ${countOf(questions)}`);
}
}
}
try { if (isPresenter) window.twLivePollBridge?.onAudience?.(renderAudienceCounts); } catch {}
if (isPresenter) { syncAudienceSwitchItems(); renderAudienceSwitchMarks(); }
// ── Questions tray (ADR-0027 amendment; ticket "Anyone can ask the speaker") ────────────────
// A drawer over the Next and Then previews. The live bridge hands it every question the worker holds
// (twLivePollBridge.onQuestions); it lists the waiting ones newest first with their slide, time and
// name, marks the one about the slide on screen, folds the answered into "Answered · n", and asks the
// worker to mark one answered through twLivePollBridge.answerQuestion (the worker's next state is what
// it then shows). Question text and names come from the audience: only textContent touches them.
var questionsTray = { list: [], live: false, open: false, answeredOpen: false, marking: new Map(), error: "", timer: 0, errorTimer: 0 };
const trayEl = () => document.getElementById("presenterQuestionsTray");
function questionsTrayAvailable() { return isPresenter && questionsTray.live && Boolean(window.twLivePollBridge?.answerQuestion); }
function trayAgo(ms) {
const seconds = Math.max(0, Math.round((Date.now() - ms) / 1000));
if (seconds < 45) return "just now";
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes} min ago`;
return `${Math.round(minutes / 60)} h ago`;
}
function trayItem(question, answered) {
// A pre-work question with no slide of its own (slideId "") comes up on whichever slide is on screen.
const anySlide = question.fromPrework === true && !question.slideId;
const slideIndex = anySlide ? undefined : slideIndexById.get(question.slideId);
const item = document.createElement("article");
item.className = "qt-item" + (answered ? " is-answered" : "") + (!answered && (anySlide || question.slideId === currentSlide()?.dataset.id) ? " is-current" : "");
if (question.fromPrework === true) item.dataset.fromPrework = "1";
item.dataset.questionId = question.questionId;
const meta = document.createElement("div"); meta.className = "qt-meta";
const slide = document.createElement("span"); slide.className = "qt-slide"; slide.textContent = anySlide ? "Any slide" : slideIndex === undefined ? "Slide" : `Slide ${slideIndex + 1}`;
const title = document.createElement("span"); title.className = "qt-stitle"; title.textContent = slideIndex === undefined ? "" : navTitleForSlideId(question.slideId);
meta.append(slide, title);
if (question.fromPrework === true) { const from = document.createElement("span"); from.className = "qt-here qt-pw"; from.textContent = "From pre-work"; meta.appendChild(from); }
if (item.classList.contains("is-current")) { const here = document.createElement("span"); here.className = "qt-here"; here.textContent = "This slide"; meta.appendChild(here); }
const text = document.createElement("p"); text.className = "qt-text"; text.textContent = question.text;
const foot = document.createElement("div"); foot.className = "qt-foot";
const who = document.createElement("span"); who.className = "qt-who" + (question.name ? "" : " anon");
const whoName = document.createElement("span"); const shownName = Array.from(question.name || "");
whoName.textContent = shownName.length ? (shownName.length > 20 ? shownName.slice(0, 20).join("") + "…" : question.name) : "No name";
if (shownName.length > 20) whoName.title = question.name;
who.append(twIconEl("user-round"), whoName);
const time = document.createElement("span"); time.className = "qt-time";
const at = new Date(question.acceptedAt);
const clock = document.createElement("span"); clock.textContent = at.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", hour12: false });
const ago = document.createElement("span"); ago.className = "qt-ago"; ago.dataset.at = String(question.acceptedAt); ago.textContent = ` · ${trayAgo(question.acceptedAt)}`;
time.append(twIconEl("clock"), clock, ago);
const done = document.createElement("button"); done.type = "button"; done.className = "qt-done";
done.dataset.questionId = question.questionId; done.dataset.answered = answered ? "false" : "true";
done.disabled = questionsTray.marking.has(question.questionId);
done.append(twIconEl(answered ? "undo-2" : "check"), document.createTextNode(answered ? "Not answered" : "Mark answered"));
foot.append(who, time, done);
item.append(meta, text, foot);
return item;
}
function renderQuestionsTray() {
const tray = trayEl();
if (!tray || !isPresenter) return;
const counter = els.presenterQuestions;
counter?.classList.toggle("qt-open", questionsTray.open);
counter?.setAttribute("aria-expanded", String(questionsTray.open));
if (!questionsTray.open) { tray.hidden = true; return; }
const waiting = questionsTray.list.filter((question) => !question.answered).sort((a, b) => b.acceptedAt - a.acceptedAt);
const answered = questionsTray.list.filter((question) => question.answered).sort((a, b) => b.acceptedAt - a.acceptedAt);
const scroll = tray.querySelector(".qt-list")?.scrollTop || 0;
tray.replaceChildren();
const head = document.createElement("header"); head.className = "qt-head";
const title = document.createElement("span"); title.className = "qt-title"; title.append(twIconEl("message-circle-question-mark"), document.createTextNode("Questions"));
const count = document.createElement("span"); count.className = "qt-count"; count.textContent = waiting.length ? `${waiting.length} waiting` : "none yet";
const spacer = document.createElement("span"); spacer.className = "qt-spacer";
const hint = document.createElement("span"); hint.className = "qt-keyhint"; hint.append(document.createTextNode("Close "), Object.assign(document.createElement("span"), { className: "qt-kbd", textContent: "Esc" }));
const close = document.createElement("button"); close.type = "button"; close.className = "qt-x"; close.dataset.qtClose = "1"; close.setAttribute("aria-label", "Close questions"); close.dataset.tip = "Close questions"; close.dataset.key = "Esc"; close.appendChild(twIconEl("x"));
head.append(title, count, spacer, hint, close);
const list = document.createElement("div"); list.className = "qt-list";
if (waiting.length) for (const question of waiting) list.appendChild(trayItem(question, false));
else {
const empty = document.createElement("div"); empty.className = "qt-empty";
empty.append(twIconEl(answered.length ? "circle-check" : "inbox"), document.createTextNode(answered.length ? "All questions answered." : "No questions yet. They arrive here, and nowhere else."));
list.appendChild(empty);
}
tray.append(head, list);
if (answered.length) {
const fold = document.createElement("button"); fold.type = "button"; fold.className = "qt-answered"; fold.dataset.qtFold = "1";
fold.setAttribute("aria-expanded", String(questionsTray.answeredOpen));
fold.append(twIconEl("chevron-right"), document.createTextNode(`Answered · ${answered.length}`));
tray.appendChild(fold);
if (questionsTray.answeredOpen) {
const folded = document.createElement("div"); folded.className = "qt-answered-list";
for (const question of answered) folded.appendChild(trayItem(question, true));
tray.appendChild(folded);
}
}
// The Next preview is under the tray, so its title is said here (the notes column already knows it).
const nextTitle = document.getElementById("presenterNotesBody")?.dataset.nextTitle;
if (nextTitle) {
const next = document.createElement("div"); next.className = "qt-nextline";
const word = document.createElement("b"); word.textContent = "Next";
const name = document.createElement("span"); name.textContent = nextTitle;
next.append(twIconEl("arrow-right"), word, name);
tray.appendChild(next);
}
const error = document.createElement("div"); error.className = "qt-error"; error.setAttribute("role", "alert"); error.hidden = !questionsTray.error; error.textContent = questionsTray.error;
tray.appendChild(error);
tray.hidden = false;
placeQuestionsTray();
const newList = tray.querySelector(".qt-list"); if (newList) newList.scrollTop = scroll;
}
// Over the Next and Then panels (their union); with previews off, docked to the right of the stage.
function placeQuestionsTray() {
const tray = trayEl();
if (!tray || tray.hidden) return;
const panels = [els.nextPreview?.closest(".presenter-panel"), document.getElementById("presenterFollowing")].filter(Boolean)
.map((panel) => panel.getBoundingClientRect()).filter((rect) => rect.width > 40 && rect.height > 40);
let box;
if (panels.length) {
const left = Math.min(...panels.map((rect) => rect.left)), top = Math.min(...panels.map((rect) => rect.top));
box = { left, top, width: Math.max(...panels.map((rect) => rect.right)) - left, height: Math.max(...panels.map((rect) => rect.bottom)) - top };
} else {
const main = document.querySelector(".presenter-main")?.getBoundingClientRect();
const top = main ? main.top : 60;
box = { left: window.innerWidth - 394, top, width: 380, height: Math.max(240, window.innerHeight - top - 90) };
}
if (box.width < 300) box = { ...box, left: Math.max(8, box.left + box.width - 340), width: 340 };
Object.assign(tray.style, { left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px` });
}
function openQuestionsTray(open) {
if (open && !questionsTrayAvailable()) return;
questionsTray.open = Boolean(open);
window.clearInterval(questionsTray.timer); questionsTray.timer = 0;
if (questionsTray.open) {
questionsTray.error = "";
// "3 min ago" is kept true while the tray is open.
questionsTray.timer = window.setInterval(() => { for (const el of document.querySelectorAll("#presenterQuestionsTray .qt-ago")) el.textContent = ` · ${trayAgo(Number(el.dataset.at))}`; }, 20000);
}
renderQuestionsTray();
}
function trayError(message) {
questionsTray.error = message;
window.clearTimeout(questionsTray.errorTimer);
questionsTray.errorTimer = window.setTimeout(() => { questionsTray.error = ""; renderQuestionsTray(); }, 6000);
renderQuestionsTray();
}
function markQuestion(questionId, answered) {
if (!questionId || questionsTray.marking.has(questionId)) return;
questionsTray.marking.set(questionId, answered);
renderQuestionsTray();
Promise.resolve(window.twLivePollBridge?.answerQuestion?.(questionId, answered)).then((result) => {
if (result?.success === false || result?.status === "rejected") { questionsTray.marking.delete(questionId); trayError(result.error || "Could not mark the question answered. Try again."); }
}).catch(() => { questionsTray.marking.delete(questionId); trayError("Could not mark the question answered. Try again."); });
}
// The worker refused the mark (or it was confirmed): the button comes back, and a refusal is said.
function questionAnswerOperation(operation) {
const questionId = operation?.message?.questionId;
if (operation.status === "confirmed" || operation.status === "rejected") {
questionsTray.marking.delete(questionId);
if (operation.status === "rejected") trayError(operation.error || "The speaker view could not mark that question answered. Try again.");
else renderQuestionsTray();
}
}
function applyQuestionsView(view) {
if (!isPresenter) return;
// A mark waits for the worker: it is over once the question is in the state that was asked for (or gone).
for (const [id, target] of [...questionsTray.marking]) {
const now = (view?.questions || []).find((question) => question.questionId === id);
if (!now || now.answered === target) questionsTray.marking.delete(id);
}
questionsTray.list = Array.isArray(view?.questions) ? view.questions : [];
questionsTray.live = Boolean(view?.live);
if (!questionsTray.live && questionsTray.open) { openQuestionsTray(false); return; }
renderQuestionsTray();
}
try {
if (isPresenter) {
window.twLivePollBridge?.onQuestions?.(applyQuestionsView);
const tray = trayEl();
// Mouse presses never take focus into the tray (an arrow or Space then still moves the slides);
// from the keyboard a button in it keeps its own Enter and Space, and Esc closes it.
tray?.addEventListener("mousedown", (event) => { if (event.target.closest?.("button")) event.preventDefault(); });
tray?.addEventListener("click", (event) => {
const button = event.target.closest?.("button");
if (!button) return;
if (button.dataset.qtClose) openQuestionsTray(false);
else if (button.dataset.qtFold) { questionsTray.answeredOpen = !questionsTray.answeredOpen; renderQuestionsTray(); }
else if (button.classList.contains("qt-done")) markQuestion(button.dataset.questionId, button.dataset.answered === "true");
});
tray?.addEventListener("keydown", (event) => {
if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); openQuestionsTray(false); return; }
if ((event.key === "Enter" || event.key === " ") && event.target.closest?.("button")) event.stopPropagation();
});
const counter = els.presenterQuestions;
if (counter) {
if (PRESENTER_TIPS.pollMenuQuestions) counter.dataset.key = PRESENTER_TIPS.pollMenuQuestions[1];
// A mouse click never leaves focus on the counter (Space would then toggle the tray instead of moving
// the slide); Enter and Space toggle it only when it was reached from the keyboard, as with the menu buttons.
counter.addEventListener("mousedown", (event) => event.preventDefault());
counter.addEventListener("click", () => openQuestionsTray(!questionsTray.open));
counter.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); event.stopPropagation(); openQuestionsTray(!questionsTray.open); } });
}
window.addEventListener("resize", placeQuestionsTray);
new MutationObserver(placeQuestionsTray).observe(document.getElementById("presenterRoot") || document.body, { attributes: true, attributeFilter: ["data-notes-placement", "data-preview-size", "class"] });
}
} catch {}
// What gives way when the top bar runs short (surfaces-drawn.md, "What gives way"): the title
// shrinks first (to 120px, with an ellipsis, by its CSS); then the steps c1-c10 are added one
// at a time until the three groups sit side by side with room between them. The CSS for each
// step is in compiler/assets/styles/presenter-status-bar.css. Re-run when the window resizes or
// what the bar shows changes (a status item appearing, a longer label, a new recording state);
// a cheap signature of the bar's items skips the re-run when nothing that affects width moved.
const TOPBAR_STEPS = ["c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10"];
function topBarGroups(bar) {
return [bar.querySelector(".tw-topbar-left"), bar.querySelector(".tw-status"), bar.querySelector(".presenter-header-actions")];
}
// The horizontal extent of a group's laid-out children (popovers and menus, positioned
// absolutely, do not count), or null when nothing in it is shown.
function barExtent(group) {
if (!group || getComputedStyle(group).display === "none") return null;
const rects = [...group.children].filter((child) => {
const cs = getComputedStyle(child);
return cs.display !== "none" && cs.position !== "absolute" && cs.position !== "fixed";
}).map((child) => child.getBoundingClientRect()).filter((r) => r.width > 0);
if (!rects.length) return null;
return { left: Math.min(...rects.map((r) => r.left)), right: Math.max(...rects.map((r) => r.right)) };
}
function topBarFits(bar) {
const [left, status, right] = topBarGroups(bar);
const box = bar.getBoundingClientRect();
const extents = [left, status, right].map(barExtent).filter(Boolean);
const leftBox = left.getBoundingClientRect();
const leftExtent = barExtent(left);
if (leftExtent && leftExtent.right > leftBox.right + 0.5) return false; // the left group overflows its box
for (let i = 1; i < extents.length; i++) if (extents[i - 1].right > extents[i].left - 8) return false;
return extents.every((e) => e.left >= box.left - 0.5 && e.right <= box.right + 0.5);
}
function fitTopBar() {
const bar = els.presenterTopBar;
if (!isPresenter || !bar) return;
bar.classList.remove(...TOPBAR_STEPS);
for (const step of TOPBAR_STEPS) { if (topBarFits(bar)) break; bar.classList.add(step); }
bar.dataset.collapse = TOPBAR_STEPS.filter((step) => bar.classList.contains(step)).join(" ");
bar.dataset.fits = String(topBarFits(bar));
}
let topBarKey = "";
let topBarFrame = 0;
function topBarSignature(bar) {
const parts = [String(bar.clientWidth)];
for (const group of topBarGroups(bar)) {
if (!group) continue;
for (const item of group.querySelectorAll(":scope > *, :scope > * > *, :scope > * > * > *")) {
if (item.closest(".tw-duration-setter, .notes-menu, .tw-menu")) continue;
parts.push(item.hidden ? "-" : String((item.textContent || "").length));
}
}
return parts.join(",");
}
function scheduleFitTopBar(force) {
if (!isPresenter || !els.presenterTopBar || topBarFrame) return;
topBarFrame = requestAnimationFrame(() => {
topBarFrame = 0;
const key = topBarSignature(els.presenterTopBar);
if (!force && key === topBarKey) return;
topBarKey = key;
fitTopBar();
});
}
if (isPresenter && els.presenterTopBar) {
new ResizeObserver(() => scheduleFitTopBar()).observe(els.presenterTopBar);
new MutationObserver(() => scheduleFitTopBar()).observe(els.presenterTopBar, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["hidden", "data-rec", "data-tone"] });
document.fonts?.ready?.then(() => scheduleFitTopBar(true));
fitTopBar();
topBarKey = topBarSignature(els.presenterTopBar);
}
// What gives way when the bottom bar runs short (surfaces-drawn.md, "Bottom bar"): by default
// the centre group (Previous, Next, Skip next) is centred on the window; then, one step at a
// time until the three groups sit side by side at least 12px apart inside the bar, n1 centres
// it between the side groups instead, n2 makes Focus and the marking tools icon-only, n3 Quick poll and
// Instant slide. The CSS for each step is in compiler/assets/styles/presenter-bottom-bar.css.
// Re-run when the window resizes or what the bar shows changes (Return, media or gallery
// controls, the edit pencil arriving).
const BOTTOMBAR_STEPS = ["n1", "n2", "n3"];
function bottomBarFits(bar) {
const box = bar.getBoundingClientRect();
const extents = [...bar.children].map(barExtent).filter(Boolean);
for (let i = 1; i < extents.length; i++) if (extents[i - 1].right > extents[i].left - 12) return false;
return extents.every((e) => e.left >= box.left - 0.5 && e.right <= box.right + 0.5);
}
function fitBottomBar() {
const bar = els.presenterBottomBar;
if (!isPresenter || !bar) return;
bar.classList.remove(...BOTTOMBAR_STEPS);
for (const step of BOTTOMBAR_STEPS) { if (bottomBarFits(bar)) break; bar.classList.add(step); }
bar.dataset.collapse = BOTTOMBAR_STEPS.filter((step) => bar.classList.contains(step)).join(" ");
bar.dataset.fits = String(bottomBarFits(bar));
}
let bottomBarFrame = 0;
function scheduleFitBottomBar() {
if (!isPresenter || !els.presenterBottomBar || bottomBarFrame) return;
bottomBarFrame = requestAnimationFrame(() => { bottomBarFrame = 0; fitBottomBar(); });
}
if (isPresenter && els.presenterBottomBar) {
new ResizeObserver(() => scheduleFitBottomBar()).observe(els.presenterBottomBar);
new MutationObserver((records) => {
// Opening More, or a pressed state changing, does not change the bar's width.
if (records.some((r) => !r.target.closest?.(".tw-menu"))) scheduleFitBottomBar();
}).observe(els.presenterBottomBar, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["hidden"] });
document.fonts?.ready?.then(() => scheduleFitBottomBar());
fitBottomBar();
}
// ── Resume-on-reopen (presenter): offer to jump back to where you were if this deck was being
// presented recently and this is a fresh window (not a same-window reload). Timer keeps running
// (wall-clock runningSince), with a "reset the timer" option. Stale (> RESUME_WINDOW_MS) = a
// different run — cleared, never offered. Milestone/reminder banners already crossed don't re-fire.
function seedFiredFromRemaining() {
const elapsed = timer.elapsedMs + (timer.runningSince ? Date.now() - timer.runningSince : 0);
const rem = Math.round(timer.targetSeconds - elapsed / 1000);
timerFired = new Set(); remindersFired = new Set();
for (const m of [0, thresholds.urgentAtSeconds, thresholds.warnAtSeconds]) if (rem <= m) timerFired.add(m);
for (const rm of (timer.reminders || [])) if (rem <= rm * 60) remindersFired.add(rm);
}
let pendingResume = null;
function maybeOfferResume() {
if (!isPresenter || wasReload) return; // a same-window reload already restored via sessionStorage
let saved = null;
try { saved = JSON.parse(localStorage.getItem(resumeKey) || "null"); } catch {}
if (!saved) return;
if (Date.now() - (saved.updatedAt || 0) > RESUME_WINDOW_MS) { try { localStorage.removeItem(resumeKey); } catch {} return; }
if (!(saved.index > 0)) return; // nothing meaningful to resume to
pendingResume = saved;
if (els.twResumeSlide) els.twResumeSlide.textContent = String(saved.index + 1);
if (els.twResume) els.twResume.hidden = false;
}
els.twResumeYes?.addEventListener("click", () => {
const saved = pendingResume;
if (els.twResume) els.twResume.hidden = true;
if (!saved) return;
shownSet = new Set(saved.progress?.shown || []);
skippedExplicitSet = new Set(saved.progress?.skipped || []);
persistProgress();
if (els.twResumeReset && els.twResumeReset.checked) {
timer = { targetSeconds: (saved.timer && saved.timer.targetSeconds) || 0, elapsedMs: 0, runningSince: null, reminders: (saved.timer && saved.timer.reminders) || [] };
} else {
timer = saved.timer || timer;
if (!Array.isArray(timer.reminders)) timer.reminders = [];
}
seedFiredFromRemaining();
persistTimer();
goTo(saved.index, 0);
renderClock();
});
els.twResumeNo?.addEventListener("click", () => {
if (els.twResume) els.twResume.hidden = true;
pendingResume = null;
try { localStorage.removeItem(resumeKey); } catch {}
});
if (isPresenter) maybeOfferResume();
// Section timer: {timer=10min} on a section stamps data-section-timer on its slides. Arms
// when the presenter ENTERS the section, persists across its slides, resets on re-entry,
// clears on leaving. Presenter sees a chip beside the clock; {timer-audience} also floats
// a countdown on the LIVE deck windows (never share exports — this element is runtime-made).
let sectionTimerId = null;
let sectionTimerEndAt = 0;
let sectionTimerShow = "presenter";
function syncSectionTimer() {
const slide = currentSlide();
const seconds = Math.floor(Number(slide?.dataset.sectionTimer || 0));
const sectionId = seconds > 0 ? (slide.dataset.section || "") : null;
if (sectionId === sectionTimerId) return;
sectionTimerId = sectionId;
document.querySelectorAll(".section-timer-float").forEach((el) => el.remove());
if (!sectionId) { sectionTimerEndAt = 0; updateSectionChip(null); return; }
sectionTimerEndAt = Date.now() + seconds * 1000;
sectionTimerShow = slide.dataset.sectionTimerShow === "audience" ? "audience" : "presenter";
if (sectionTimerShow === "audience" && !isPresenter) {
const float = document.createElement("div");
float.className = "section-timer-float";
float.setAttribute("aria-hidden", "true");
document.body.appendChild(float);
}
}
function updateSectionChip(text, critical) {
const chip = els.sectionTimer;
if (!chip) return;
if (chip.hidden !== (text == null)) chip.hidden = text == null;
if (text != null && els.sectionTimerTime && els.sectionTimerTime.textContent !== text) els.sectionTimerTime.textContent = text;
chip.classList.toggle("talk-crit", Boolean(critical));
}
function tickSectionTimer() {
if (!sectionTimerEndAt) return;
const left = Math.round((sectionTimerEndAt - Date.now()) / 1000);
const critical = left <= 60;
if (isPresenter) updateSectionChip(left >= 0 ? fmtClock(left) : "00:00", critical);
const float = document.querySelector(".section-timer-float");
if (float) {
float.textContent = fmtClock(Math.max(0, left));
float.classList.toggle("countdown-final", left > 0 && left <= 10);
if (left <= 0 && !float.classList.contains("countdown-done")) float.classList.add("countdown-done");
}
}
// Presenter reminders: {remind="Lunch" remind-at=13:00} (wall clock today) or
// {remind="Stretch" remind-in=45min} (from presenter start). Collected from ALL slides at
// load; each fires once with a flashing banner in the PRESENTER window only; click
// dismisses. An absolute time already in the past at load never fires.
const reminders = [];
if (isPresenter) {
const startOfDay = new Date();
startOfDay.setHours(0, 0, 0, 0);
document.querySelectorAll(".slide[data-remind]").forEach((slide) => {
const text = slide.dataset.remind;
if (slide.dataset.remindAt != null) {
const fireAt = startOfDay.getTime() + Number(slide.dataset.remindAt) * 60000;
if (fireAt > Date.now()) reminders.push({ text, fireAt });
} else if (slide.dataset.remindIn != null) {
reminders.push({ text, fireAt: timerStart + Number(slide.dataset.remindIn) * 1000 });
}
});
// {timetable} (2026-06-13): each timed row arms a wall-clock reminder ("HH:MM · Event"), so a
// day schedule paces the presenter — when the clock reaches a session's time it flashes, and
// if you are still on an earlier slide you can see you are running behind.
document.querySelectorAll(".timetable[data-tt-schedule]").forEach((table) => {
let schedule = [];
try { schedule = JSON.parse(table.dataset.ttSchedule || "[]"); } catch {}
for (const row of schedule) {
const fireAt = startOfDay.getTime() + Number(row.m) * 60000;
if (Number.isFinite(fireAt) && fireAt > Date.now()) reminders.push({ text: row.label, fireAt });
}
});
}
// One flashing banner device shared by authored reminders AND countdown milestones.
function showPresenterBanner(text) {
const banner = document.createElement("div");
banner.className = "presenter-reminder";
banner.setAttribute("role", "alert");
const label = document.createElement("span");
label.textContent = text;
const hint = document.createElement("small");
hint.textContent = "click to dismiss";
banner.append(label, hint);
banner.addEventListener("click", () => banner.remove());
document.body.appendChild(banner);
}
function tickReminders() {
const now = Date.now();
for (const reminder of reminders) {
if (reminder.fired || reminder.fireAt > now) continue;
reminder.fired = true;
showPresenterBanner(reminder.text);
}
}
// F2: apply the remembered preview size as soon as the presenter window opens.
if (isPresenter) setPreviewSize(previewSize);
if (isPresenter) applyNotesSettings(notesSettings, { persist: false, rerender: false });
syncFromHash();
// On a cold start, honour the start slide's authored {mode=…} so reveal/focus is active on
// arrival. (A restored paired session replays its own mode from storage instead.)
if (!restoreStoredState()) {
const authored = authoredModeFor(state.index);
if (authored) state.mode = { kind: authored, step: 0 };
applyState(state);
}
})();