@flipbook-md/core 0.14.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -6,10 +6,48 @@ const previous = document.querySelector("#previous");
6
6
  const next = document.querySelector("#next");
7
7
  const playButton = document.querySelector("#play");
8
8
  const notesRoot = document.querySelector("#notes");
9
+ const upNextRoot = document.querySelector("#up-next-slide");
10
+ const slideStrip = document.querySelector("#slide-strip");
11
+ const hud = document.querySelector("nav.hud");
12
+ const gridToggle = document.querySelector("#grid-toggle");
13
+ const gridClose = document.querySelector("#grid-close");
14
+ const overviewDialog = document.querySelector("#overview-grid");
15
+ const overviewCards = document.querySelector("#overview-cards");
16
+ const notesScaleDown = document.querySelector("#notes-scale-down");
17
+ const notesScaleUp = document.querySelector("#notes-scale-up");
18
+ const timerDisplay = document.querySelector("#speaker-timer");
19
+ const timerToggle = document.querySelector("#timer-toggle");
20
+ const timerReset = document.querySelector("#timer-reset");
21
+ const wallClock = document.querySelector("#wall-clock");
22
+ const laserToggle = document.querySelector("#laser-toggle");
23
+ const laserDot = document.querySelector("#laser-dot");
24
+ const tabNotes = document.querySelector("#tab-notes");
25
+ const tabQa = document.querySelector("#tab-qa");
26
+ const qaBadge = document.querySelector("#qa-badge");
27
+ const notesScaleControls = document.querySelector("#notes-scale-controls");
28
+ const qaPanel = document.querySelector("#qa-panel");
29
+ const qaList = document.querySelector("#qa-list");
30
+ const qaEmpty = document.querySelector("#qa-empty");
31
+ const qaToggle = document.querySelector("#qa-toggle");
32
+ const qaDrawer = document.querySelector("#qa-drawer");
33
+ const qaClose = document.querySelector("#qa-close");
34
+ const qaForm = document.querySelector("#qa-form");
35
+ const qaAuthor = document.querySelector("#qa-author");
36
+ const qaInput = document.querySelector("#qa-input");
37
+ const qaStatus = document.querySelector("#qa-status");
38
+ const qaSpotlight = document.querySelector("#qa-spotlight");
39
+ const qaSpotlightText = document.querySelector("#qa-spotlight-text");
40
+ const qaSpotlightAuthor = document.querySelector("#qa-spotlight-author");
41
+
9
42
  const tabId = Math.random().toString(36).slice(2);
10
43
  let channel = null;
11
44
  try { channel = new BroadcastChannel("flipbook-md"); } catch { channel = null; }
12
45
 
46
+ const HUD_IDLE_MS = 2500;
47
+ const NOTES_SCALES = ["0.9", "1", "1.15", "1.3", "1.5"];
48
+ const PREVIEW_W = 960;
49
+ const PREVIEW_H = 540;
50
+
13
51
  let presentation;
14
52
  let current = 0;
15
53
  let playing = false;
@@ -18,9 +56,33 @@ let timer = null;
18
56
  let pendingRemote = null;
19
57
  let shown = null;
20
58
 
21
- function mountSlide() {
22
- if (slideRoot.shadowRoot) return slideRoot.shadowRoot;
23
- const shadow = slideRoot.attachShadow({ mode: "open" });
59
+ let hudHideTimer = null;
60
+ let hudHovered = false;
61
+ let overviewOpen = false;
62
+ let overviewBuilt = false;
63
+
64
+ let notesScale = "1";
65
+ let speakerElapsedMs = 0;
66
+ let speakerRunning = false;
67
+ let speakerStartedAt = 0;
68
+ let speakerInterval = null;
69
+
70
+ let laserActive = false;
71
+ let lastLaser = null;
72
+ let laserRaf = 0;
73
+ let laserPending = null;
74
+
75
+ let qaItems = [];
76
+ let qaDrawerOpen = false;
77
+ let remoteEventsEnabled = false;
78
+ let remoteQaEnabled = false;
79
+ let eventsUrl = "/api/present-events";
80
+ let qaUrl = "/api/qa";
81
+ let eventSource = null;
82
+
83
+ function mountSlide(host, { live = false } = {}) {
84
+ if (host.shadowRoot) return host.shadowRoot;
85
+ const shadow = host.attachShadow({ mode: "open" });
24
86
  const base = document.createElement("link");
25
87
  base.rel = "stylesheet";
26
88
  base.href = "/slide.css";
@@ -32,7 +94,7 @@ function mountSlide() {
32
94
  theme.href = "/presentation.css";
33
95
  const article = document.createElement("article");
34
96
  article.className = "slide-root";
35
- article.setAttribute("aria-live", "polite");
97
+ if (live) article.setAttribute("aria-live", "polite");
36
98
  shadow.append(base, templates, theme, article);
37
99
  return shadow;
38
100
  }
@@ -61,8 +123,8 @@ function restoreIndex() {
61
123
  }
62
124
  }
63
125
 
64
- function publish() {
65
- channel?.postMessage({ tab: tabId, index: current, playing: Boolean(playing && leader) });
126
+ function publish(type = "goto") {
127
+ channel?.postMessage({ tab: tabId, type, index: current, playing: Boolean(playing && leader) });
66
128
  remember();
67
129
  }
68
130
 
@@ -112,11 +174,8 @@ function animateIn(article, delta) {
112
174
  article.animate(frames, { duration: ms, easing: "ease-out" });
113
175
  }
114
176
 
115
- function render() {
116
- if (!presentation?.slides?.length) return;
117
- current = Math.max(0, Math.min(current, presentation.slides.length - 1));
118
- const slide = presentation.slides[current];
119
- const shadow = mountSlide();
177
+ function renderSlideInto(host, slide, { live = false, animateDelta = 0 } = {}) {
178
+ const shadow = mountSlide(host, { live });
120
179
  const article = shadow.querySelector(".slide-root");
121
180
  article.setAttribute("data-template", slide.template || "flow");
122
181
  setData(article, "layout", slide.layout);
@@ -125,18 +184,94 @@ function render() {
125
184
  const header = presentation.chromeHtml?.header ?? "";
126
185
  const footer = presentation.chromeHtml?.footer ?? "";
127
186
  article.innerHTML = `${header}<p class="eyebrow">${escapeHtml(presentation.title)}</p><div class="slide-body">${slide.html}</div>${footer}${slide.counterHtml ?? ""}`;
187
+ shadow.querySelectorAll("a").forEach((anchor) => {
188
+ anchor.setAttribute("target", "_blank");
189
+ anchor.setAttribute("rel", "noopener noreferrer");
190
+ });
191
+ if (animateDelta) animateIn(article, animateDelta);
192
+ }
193
+
194
+ function fitPreview(container, preview) {
195
+ if (!container || !preview) return;
196
+ const rect = container.getBoundingClientRect();
197
+ if (!rect.width || !rect.height) return;
198
+ const scale = Math.min(rect.width / PREVIEW_W, rect.height / PREVIEW_H);
199
+ const offsetX = Math.max(0, (rect.width - PREVIEW_W * scale) / 2);
200
+ const offsetY = Math.max(0, (rect.height - PREVIEW_H * scale) / 2);
201
+ preview.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
202
+ }
203
+
204
+ function renderUpNext() {
205
+ if (!upNextRoot || !presentation?.slides?.length) return;
206
+ const nextIndex = current + 1;
207
+ if (nextIndex >= presentation.slides.length) {
208
+ upNextRoot.innerHTML = `<p class="up-next-end">End of presentation</p>`;
209
+ return;
210
+ }
211
+ let preview = upNextRoot.querySelector(".up-next-preview");
212
+ if (!preview) {
213
+ upNextRoot.innerHTML = "";
214
+ preview = document.createElement("div");
215
+ preview.className = "up-next-preview";
216
+ upNextRoot.appendChild(preview);
217
+ }
218
+ renderSlideInto(preview, presentation.slides[nextIndex]);
219
+ fitPreview(upNextRoot.parentElement, preview);
220
+ }
221
+
222
+ function syncSlideStrip() {
223
+ if (!slideStrip) return;
224
+ slideStrip.querySelectorAll(".strip-item").forEach((btn) => {
225
+ const idx = Number(btn.dataset.index);
226
+ const active = idx === current;
227
+ btn.classList.toggle("is-active", active);
228
+ if (active) {
229
+ btn.setAttribute("aria-current", "true");
230
+ btn.scrollIntoView?.({ block: "nearest", inline: "nearest" });
231
+ } else {
232
+ btn.removeAttribute("aria-current");
233
+ }
234
+ });
235
+ }
236
+
237
+ function buildSlideStrip() {
238
+ if (!slideStrip || !presentation?.slides?.length) return;
239
+ const fragment = document.createDocumentFragment();
240
+ presentation.slides.forEach((slide, idx) => {
241
+ const btn = document.createElement("button");
242
+ btn.type = "button";
243
+ btn.className = "strip-item";
244
+ btn.dataset.index = String(idx);
245
+ const num = document.createElement("span");
246
+ num.className = "strip-item-num";
247
+ num.textContent = String(idx + 1);
248
+ const label = document.createElement("span");
249
+ label.className = "strip-item-title";
250
+ label.textContent = slide.title || `Slide ${idx + 1}`;
251
+ btn.append(num, label);
252
+ btn.addEventListener("click", () => go(idx));
253
+ fragment.appendChild(btn);
254
+ });
255
+ slideStrip.replaceChildren(fragment);
256
+ syncSlideStrip();
257
+ }
258
+
259
+ function render() {
260
+ if (!presentation?.slides?.length) return;
261
+ current = Math.max(0, Math.min(current, presentation.slides.length - 1));
262
+ const slide = presentation.slides[current];
263
+ const delta = shown == null ? 0 : current - shown;
264
+ renderSlideInto(slideRoot, slide, { live: true, animateDelta: delta });
128
265
  counter.textContent = `${current + 1} / ${presentation.slides.length}`;
129
266
  progress.style.width = `${((current + 1) / presentation.slides.length) * 100}%`;
130
267
  previous.disabled = current === 0;
131
268
  next.disabled = current === presentation.slides.length - 1;
132
- animateIn(article, shown == null ? 0 : current - shown);
133
269
  shown = current;
134
270
  renderNotes(slide);
271
+ renderUpNext();
135
272
  syncPlayButton();
136
- shadow.querySelectorAll("a").forEach((anchor) => {
137
- anchor.setAttribute("target", "_blank");
138
- anchor.setAttribute("rel", "noopener noreferrer");
139
- });
273
+ syncSlideStrip();
274
+ syncOverviewActive();
140
275
  }
141
276
 
142
277
  function go(index) {
@@ -154,13 +289,13 @@ function go(index) {
154
289
  }
155
290
  syncPlayButton();
156
291
  }
157
- publish();
292
+ publish("goto");
158
293
  }
159
294
 
160
- function setPlaying(next) {
295
+ function setPlaying(nextState) {
161
296
  if (!presentation?.slides?.length) return;
162
297
  clearTimer();
163
- if (next && current < presentation.slides.length - 1) {
298
+ if (nextState && current < presentation.slides.length - 1) {
164
299
  playing = true;
165
300
  leader = true;
166
301
  timer = setInterval(tick, intervalMs());
@@ -169,7 +304,7 @@ function setPlaying(next) {
169
304
  leader = false;
170
305
  }
171
306
  syncPlayButton();
172
- publish();
307
+ publish("play");
173
308
  }
174
309
 
175
310
  function tick() {
@@ -182,7 +317,7 @@ function tick() {
182
317
  leader = false;
183
318
  syncPlayButton();
184
319
  }
185
- publish();
320
+ publish("goto");
186
321
  }
187
322
 
188
323
  function applyRemote(message) {
@@ -199,40 +334,607 @@ function applyRemote(message) {
199
334
  remember();
200
335
  }
201
336
 
202
- channel?.addEventListener("message", (event) => {
203
- const message = event.data;
337
+ function handleIncomingEvent(message) {
204
338
  if (!message || message.tab === tabId) return;
205
339
  if (message.type === "hello") {
206
- if (leader) publish();
340
+ if (leader) publish("play");
341
+ if (qaItems.length && document.body.classList.contains("announcer")) {
342
+ channel?.postMessage({ tab: tabId, type: "qa-sync", items: qaItems });
343
+ }
344
+ return;
345
+ }
346
+ if (message.type === "laser") {
347
+ applyLaserEvent(message);
348
+ return;
349
+ }
350
+ if (message.type === "qa-submit" || message.type === "qa-update") {
351
+ if (message.item) upsertQaItem(message.item);
352
+ return;
353
+ }
354
+ if (message.type === "qa-sync" && Array.isArray(message.items)) {
355
+ message.items.forEach((item) => upsertQaItem(item));
207
356
  return;
208
357
  }
209
358
  applyRemote(message);
359
+ }
360
+
361
+ channel?.addEventListener("message", (event) => {
362
+ handleIncomingEvent(event.data);
210
363
  });
211
364
 
212
365
  // The tab that runs the timer tells the others to stop when it closes or reloads,
213
366
  // so they do not keep showing Pause with nothing advancing.
214
367
  window.addEventListener("pagehide", () => {
368
+ if (laserActive) setLaserActive(false);
369
+ if (eventSource) {
370
+ eventSource.close();
371
+ eventSource = null;
372
+ }
215
373
  if (!leader || !playing) return;
216
374
  clearTimer();
217
375
  playing = false;
218
376
  leader = false;
219
- publish();
377
+ publish("play");
378
+ });
379
+
380
+ /* Auto-hiding floating HUD on / */
381
+ function hudHasFocus() {
382
+ return Boolean(hud && document.activeElement && hud.contains(document.activeElement));
383
+ }
384
+
385
+ function hideHud() {
386
+ if (!hud) return;
387
+ if (overviewOpen || qaDrawerOpen || hudHovered || hudHasFocus()) return;
388
+ hud.classList.add("is-hidden");
389
+ }
390
+
391
+ function showHud() {
392
+ if (!hud) return;
393
+ hud.classList.remove("is-hidden");
394
+ if (hudHideTimer) {
395
+ clearTimeout(hudHideTimer);
396
+ hudHideTimer = null;
397
+ }
398
+ if (!overviewOpen && !qaDrawerOpen && !hudHovered && !hudHasFocus()) {
399
+ hudHideTimer = setTimeout(hideHud, HUD_IDLE_MS);
400
+ }
401
+ }
402
+
403
+ if (hud) {
404
+ document.addEventListener("pointermove", showHud, { passive: true });
405
+ document.addEventListener("pointerdown", showHud, { passive: true });
406
+ hud.addEventListener("pointerenter", () => {
407
+ hudHovered = true;
408
+ showHud();
409
+ });
410
+ hud.addEventListener("pointerleave", () => {
411
+ hudHovered = false;
412
+ showHud();
413
+ });
414
+ hud.addEventListener("focusin", showHud);
415
+ hud.addEventListener("focusout", () => {
416
+ setTimeout(showHud, 0);
417
+ });
418
+ }
419
+
420
+ /* G Slide Overview Grid on / */
421
+ function syncOverviewActive() {
422
+ if (!overviewCards) return;
423
+ overviewCards.querySelectorAll(".overview-card").forEach((card) => {
424
+ const idx = Number(card.dataset.index);
425
+ const active = idx === current;
426
+ card.classList.toggle("is-active", active);
427
+ if (active) card.setAttribute("aria-current", "true");
428
+ else card.removeAttribute("aria-current");
429
+ });
430
+ }
431
+
432
+ function fitAllOverviewThumbs() {
433
+ if (!overviewCards) return;
434
+ overviewCards.querySelectorAll(".overview-thumb").forEach((thumb) => {
435
+ const inner = thumb.querySelector(".overview-thumb-inner");
436
+ fitPreview(thumb, inner);
437
+ });
438
+ }
439
+
440
+ function buildOverviewGrid() {
441
+ if (overviewBuilt || !overviewCards || !presentation?.slides?.length) return;
442
+ overviewBuilt = true;
443
+ const fragment = document.createDocumentFragment();
444
+ presentation.slides.forEach((slide, idx) => {
445
+ const card = document.createElement("button");
446
+ card.type = "button";
447
+ card.className = "overview-card";
448
+ card.dataset.index = String(idx);
449
+
450
+ const thumb = document.createElement("div");
451
+ thumb.className = "overview-thumb";
452
+ const inner = document.createElement("div");
453
+ inner.className = "overview-thumb-inner";
454
+ renderSlideInto(inner, slide);
455
+ thumb.appendChild(inner);
456
+
457
+ const meta = document.createElement("div");
458
+ meta.className = "overview-meta";
459
+ const num = document.createElement("span");
460
+ num.className = "overview-num";
461
+ num.textContent = String(idx + 1);
462
+ const title = document.createElement("span");
463
+ title.className = "overview-title";
464
+ title.textContent = slide.title || `Slide ${idx + 1}`;
465
+ meta.append(num, title);
466
+
467
+ card.append(thumb, meta);
468
+ card.addEventListener("click", () => {
469
+ go(idx);
470
+ closeOverview();
471
+ });
472
+ fragment.appendChild(card);
473
+ });
474
+ overviewCards.replaceChildren(fragment);
475
+ syncOverviewActive();
476
+ }
477
+
478
+ function openOverview() {
479
+ if (!overviewDialog || !presentation?.slides?.length) return;
480
+ buildOverviewGrid();
481
+ overviewOpen = true;
482
+ overviewDialog.hidden = false;
483
+ gridToggle?.setAttribute("aria-expanded", "true");
484
+ if (hudHideTimer) {
485
+ clearTimeout(hudHideTimer);
486
+ hudHideTimer = null;
487
+ }
488
+ syncOverviewActive();
489
+ requestAnimationFrame(() => {
490
+ fitAllOverviewThumbs();
491
+ const activeCard = overviewCards?.querySelector(`.overview-card[data-index="${current}"]`);
492
+ activeCard?.focus();
493
+ });
494
+ }
495
+
496
+ function closeOverview() {
497
+ if (!overviewDialog || !overviewOpen) return;
498
+ overviewOpen = false;
499
+ overviewDialog.hidden = true;
500
+ gridToggle?.setAttribute("aria-expanded", "false");
501
+ gridToggle?.focus();
502
+ showHud();
503
+ }
504
+
505
+ function toggleOverview() {
506
+ if (overviewOpen) closeOverview();
507
+ else openOverview();
508
+ }
509
+
510
+ gridToggle?.addEventListener("click", toggleOverview);
511
+ gridClose?.addEventListener("click", closeOverview);
512
+
513
+ /* Notes font scale in /announcer */
514
+ function restoreNotesScale() {
515
+ try {
516
+ const saved = localStorage.getItem("flipbook-notes-scale");
517
+ if (saved && NOTES_SCALES.includes(saved)) return saved;
518
+ } catch {
519
+ // Ignore storage failures and default to 1.
520
+ }
521
+ return "1";
522
+ }
523
+
524
+ function applyNotesScale(scale) {
525
+ notesScale = NOTES_SCALES.includes(scale) ? scale : "1";
526
+ if (notesRoot) notesRoot.style.fontSize = `${notesScale}rem`;
527
+ try {
528
+ localStorage.setItem("flipbook-notes-scale", notesScale);
529
+ } catch {
530
+ // Ignore storage failures; scale remains active in memory.
531
+ }
532
+ const idx = NOTES_SCALES.indexOf(notesScale);
533
+ if (notesScaleDown) notesScaleDown.disabled = idx <= 0;
534
+ if (notesScaleUp) notesScaleUp.disabled = idx >= NOTES_SCALES.length - 1;
535
+ }
536
+
537
+ notesScaleDown?.addEventListener("click", () => {
538
+ const idx = NOTES_SCALES.indexOf(notesScale);
539
+ if (idx > 0) applyNotesScale(NOTES_SCALES[idx - 1]);
540
+ });
541
+
542
+ notesScaleUp?.addEventListener("click", () => {
543
+ const idx = NOTES_SCALES.indexOf(notesScale);
544
+ if (idx < NOTES_SCALES.length - 1) applyNotesScale(NOTES_SCALES[idx + 1]);
545
+ });
546
+
547
+ /* Speaker elapsed timer + Wall clock in /announcer */
548
+ function formatElapsed(ms) {
549
+ const totalSec = Math.max(0, Math.floor(ms / 1000));
550
+ const hours = Math.floor(totalSec / 3600);
551
+ const mins = Math.floor((totalSec % 3600) / 60);
552
+ const secs = totalSec % 60;
553
+ const mm = String(mins).padStart(2, "0");
554
+ const ss = String(secs).padStart(2, "0");
555
+ return hours > 0 ? `${hours}:${mm}:${ss}` : `${mm}:${ss}`;
556
+ }
557
+
558
+ function currentElapsedMs() {
559
+ return speakerRunning ? speakerElapsedMs + (Date.now() - speakerStartedAt) : speakerElapsedMs;
560
+ }
561
+
562
+ function updateTimerDisplay() {
563
+ if (timerDisplay) timerDisplay.textContent = formatElapsed(currentElapsedMs());
564
+ }
565
+
566
+ function syncTimerButton() {
567
+ if (!timerToggle) return;
568
+ timerToggle.textContent = speakerRunning ? "Pause" : "Start";
569
+ timerToggle.setAttribute("aria-pressed", speakerRunning ? "true" : "false");
570
+ }
571
+
572
+ timerToggle?.addEventListener("click", () => {
573
+ if (speakerRunning) {
574
+ speakerElapsedMs = currentElapsedMs();
575
+ speakerRunning = false;
576
+ if (speakerInterval) {
577
+ clearInterval(speakerInterval);
578
+ speakerInterval = null;
579
+ }
580
+ } else {
581
+ speakerStartedAt = Date.now();
582
+ speakerRunning = true;
583
+ speakerInterval = setInterval(updateTimerDisplay, 250);
584
+ }
585
+ syncTimerButton();
586
+ updateTimerDisplay();
587
+ });
588
+
589
+ timerReset?.addEventListener("click", () => {
590
+ speakerRunning = false;
591
+ speakerElapsedMs = 0;
592
+ if (speakerInterval) {
593
+ clearInterval(speakerInterval);
594
+ speakerInterval = null;
595
+ }
596
+ syncTimerButton();
597
+ updateTimerDisplay();
598
+ });
599
+
600
+ function updateWallClock() {
601
+ if (!wallClock) return;
602
+ try {
603
+ wallClock.textContent = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
604
+ } catch {
605
+ wallClock.textContent = "";
606
+ }
607
+ }
608
+
609
+ if (wallClock) {
610
+ updateWallClock();
611
+ setInterval(updateWallClock, 1000);
612
+ }
613
+
614
+ if (upNextRoot?.parentElement && typeof ResizeObserver !== "undefined") {
615
+ const ro = new ResizeObserver(() => {
616
+ fitPreview(upNextRoot.parentElement, upNextRoot.querySelector(".up-next-preview"));
617
+ });
618
+ ro.observe(upNextRoot.parentElement);
619
+ }
620
+
621
+ window.addEventListener("resize", () => {
622
+ if (overviewOpen) fitAllOverviewThumbs();
623
+ if (lastLaser?.active) positionLaserDot(lastLaser.x, lastLaser.y);
220
624
  });
221
625
 
626
+ /* Synced laser pointer (/announcer -> /) */
627
+ function emitPresentEvent(payload) {
628
+ channel?.postMessage(payload);
629
+ if (!remoteEventsEnabled) return;
630
+ fetch(eventsUrl, {
631
+ method: "POST",
632
+ headers: { "Content-Type": "application/json" },
633
+ body: JSON.stringify(payload)
634
+ }).catch(() => {});
635
+ }
636
+
637
+ function positionLaserDot(x, y) {
638
+ if (!laserDot || !slideRoot) return;
639
+ const rect = slideRoot.getBoundingClientRect();
640
+ if (!rect.width || !rect.height) return;
641
+ const cx = Math.max(0, Math.min(1, x));
642
+ const cy = Math.max(0, Math.min(1, y));
643
+ laserDot.style.left = `${rect.left + cx * rect.width}px`;
644
+ laserDot.style.top = `${rect.top + cy * rect.height}px`;
645
+ }
646
+
647
+ function applyLaserEvent(message) {
648
+ if (!laserDot) return;
649
+ if (!message.active || !Number.isFinite(message.x) || !Number.isFinite(message.y)) {
650
+ lastLaser = null;
651
+ laserDot.hidden = true;
652
+ return;
653
+ }
654
+ lastLaser = { active: true, x: message.x, y: message.y };
655
+ positionLaserDot(message.x, message.y);
656
+ laserDot.hidden = false;
657
+ }
658
+
659
+ function setLaserActive(nextState) {
660
+ laserActive = Boolean(nextState);
661
+ if (laserToggle) laserToggle.setAttribute("aria-pressed", laserActive ? "true" : "false");
662
+ slideRoot?.classList.toggle("is-laser-active", laserActive);
663
+ if (!laserActive) {
664
+ laserPending = null;
665
+ if (laserRaf) {
666
+ cancelAnimationFrame(laserRaf);
667
+ laserRaf = 0;
668
+ }
669
+ emitPresentEvent({ tab: tabId, type: "laser", active: false });
670
+ }
671
+ }
672
+
673
+ function sendLaserPointer(event) {
674
+ if (!laserActive || !slideRoot) return;
675
+ const rect = slideRoot.getBoundingClientRect();
676
+ if (!rect.width || !rect.height) return;
677
+ const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
678
+ const y = Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height));
679
+ laserPending = { tab: tabId, type: "laser", active: true, x, y };
680
+ if (!laserRaf) {
681
+ laserRaf = requestAnimationFrame(() => {
682
+ laserRaf = 0;
683
+ if (laserPending && laserActive) {
684
+ emitPresentEvent(laserPending);
685
+ laserPending = null;
686
+ }
687
+ });
688
+ }
689
+ }
690
+
691
+ if (laserToggle && slideRoot) {
692
+ laserToggle.addEventListener("click", () => setLaserActive(!laserActive));
693
+ slideRoot.addEventListener("pointermove", sendLaserPointer);
694
+ slideRoot.addEventListener("pointerdown", sendLaserPointer);
695
+ slideRoot.addEventListener("pointerleave", () => {
696
+ if (laserActive) emitPresentEvent({ tab: tabId, type: "laser", active: false });
697
+ });
698
+ slideRoot.addEventListener("pointercancel", () => {
699
+ if (laserActive) emitPresentEvent({ tab: tabId, type: "laser", active: false });
700
+ });
701
+ }
702
+
703
+ /* Live audience Q&A (/ <-> /announcer) */
704
+ function setSidebarTab(tab) {
705
+ if (!tabNotes || !tabQa || !notesRoot || !qaPanel) return;
706
+ const isQa = tab === "qa";
707
+ tabNotes.setAttribute("aria-selected", isQa ? "false" : "true");
708
+ tabQa.setAttribute("aria-selected", isQa ? "true" : "false");
709
+ notesRoot.hidden = isQa;
710
+ if (notesScaleControls) notesScaleControls.hidden = isQa;
711
+ qaPanel.hidden = !isQa;
712
+ }
713
+
714
+ tabNotes?.addEventListener("click", () => setSidebarTab("notes"));
715
+ tabQa?.addEventListener("click", () => setSidebarTab("qa"));
716
+
717
+ function renderQaSpotlight() {
718
+ if (!qaSpotlight || !qaSpotlightText || !qaSpotlightAuthor) return;
719
+ const highlighted = qaItems.find((item) => item.status === "highlighted");
720
+ if (!highlighted) {
721
+ qaSpotlight.hidden = true;
722
+ qaSpotlightText.textContent = "";
723
+ qaSpotlightAuthor.textContent = "";
724
+ return;
725
+ }
726
+ qaSpotlightText.textContent = highlighted.text;
727
+ qaSpotlightAuthor.textContent = highlighted.author ? `— ${highlighted.author}` : "";
728
+ qaSpotlight.hidden = false;
729
+ }
730
+
731
+ function renderQaList() {
732
+ if (!qaList || !qaEmpty) return;
733
+ const visible = qaItems.filter((item) => item.status !== "dismissed");
734
+ const openCount = visible.filter((item) => item.status !== "answered").length;
735
+ if (qaBadge) {
736
+ qaBadge.textContent = String(openCount);
737
+ qaBadge.hidden = openCount === 0;
738
+ }
739
+ qaEmpty.hidden = visible.length > 0;
740
+ const fragment = document.createDocumentFragment();
741
+ visible.forEach((item) => {
742
+ const card = document.createElement("article");
743
+ card.className = "qa-item";
744
+ if (item.status === "highlighted") card.classList.add("is-highlighted");
745
+ if (item.status === "answered") card.classList.add("is-answered");
746
+ card.dataset.qaId = item.id;
747
+
748
+ const meta = document.createElement("div");
749
+ meta.className = "qa-item-meta";
750
+ const author = document.createElement("span");
751
+ author.className = "qa-item-author";
752
+ author.textContent = item.author || "Audience";
753
+ const status = document.createElement("span");
754
+ status.className = "qa-item-status";
755
+ status.textContent = item.status === "open" ? "" : item.status;
756
+ meta.append(author, status);
757
+
758
+ const text = document.createElement("p");
759
+ text.className = "qa-item-text";
760
+ text.textContent = item.text;
761
+
762
+ const actions = document.createElement("div");
763
+ actions.className = "qa-item-actions";
764
+
765
+ const highlightBtn = document.createElement("button");
766
+ highlightBtn.type = "button";
767
+ highlightBtn.className = "qa-action-btn";
768
+ highlightBtn.dataset.action = "highlight";
769
+ highlightBtn.setAttribute("aria-pressed", item.status === "highlighted" ? "true" : "false");
770
+ highlightBtn.textContent = item.status === "highlighted" ? "Unhighlight" : "Highlight";
771
+ highlightBtn.addEventListener("click", () => updateQaStatus(item.id, item.status === "highlighted" ? "open" : "highlighted"));
772
+
773
+ const answerBtn = document.createElement("button");
774
+ answerBtn.type = "button";
775
+ answerBtn.className = "qa-action-btn";
776
+ answerBtn.dataset.action = "answer";
777
+ answerBtn.textContent = "Answer";
778
+ answerBtn.addEventListener("click", () => updateQaStatus(item.id, "answered"));
779
+
780
+ const dismissBtn = document.createElement("button");
781
+ dismissBtn.type = "button";
782
+ dismissBtn.className = "qa-action-btn";
783
+ dismissBtn.dataset.action = "dismiss";
784
+ dismissBtn.textContent = "Dismiss";
785
+ dismissBtn.addEventListener("click", () => updateQaStatus(item.id, "dismissed"));
786
+
787
+ actions.append(highlightBtn, answerBtn, dismissBtn);
788
+ card.append(meta, text, actions);
789
+ fragment.appendChild(card);
790
+ });
791
+ qaList.replaceChildren(fragment);
792
+ }
793
+
794
+ function upsertQaItem(incoming) {
795
+ if (!incoming || typeof incoming.id !== "string" || typeof incoming.text !== "string") return;
796
+ if (incoming.status === "highlighted") {
797
+ qaItems.forEach((existing) => {
798
+ if (existing.id !== incoming.id && existing.status === "highlighted") existing.status = "open";
799
+ });
800
+ }
801
+ const idx = qaItems.findIndex((item) => item.id === incoming.id);
802
+ if (idx >= 0) qaItems[idx] = { ...qaItems[idx], ...incoming };
803
+ else qaItems.unshift({ ...incoming });
804
+ renderQaList();
805
+ renderQaSpotlight();
806
+ }
807
+
808
+ function emitQaEvent(type, item) {
809
+ channel?.postMessage({ tab: tabId, type, item });
810
+ if (!remoteQaEnabled) return;
811
+ fetch(qaUrl, {
812
+ method: "POST",
813
+ headers: { "Content-Type": "application/json" },
814
+ body: JSON.stringify({ action: type, item })
815
+ }).catch(() => {});
816
+ }
817
+
818
+ function updateQaStatus(id, nextStatus) {
819
+ const item = qaItems.find((entry) => entry.id === id);
820
+ if (!item) return;
821
+ if (nextStatus === "highlighted") {
822
+ qaItems.forEach((entry) => {
823
+ if (entry.id !== id && entry.status === "highlighted") entry.status = "open";
824
+ });
825
+ }
826
+ item.status = nextStatus;
827
+ renderQaList();
828
+ renderQaSpotlight();
829
+ emitQaEvent("qa-update", { ...item });
830
+ }
831
+
832
+ function openQaDrawer() {
833
+ if (!qaDrawer) return;
834
+ qaDrawerOpen = true;
835
+ qaDrawer.hidden = false;
836
+ qaToggle?.setAttribute("aria-expanded", "true");
837
+ if (qaStatus) qaStatus.textContent = "";
838
+ if (hudHideTimer) {
839
+ clearTimeout(hudHideTimer);
840
+ hudHideTimer = null;
841
+ }
842
+ qaInput?.focus();
843
+ }
844
+
845
+ function closeQaDrawer() {
846
+ if (!qaDrawer || !qaDrawerOpen) return;
847
+ qaDrawerOpen = false;
848
+ qaDrawer.hidden = true;
849
+ qaToggle?.setAttribute("aria-expanded", "false");
850
+ qaToggle?.focus();
851
+ showHud();
852
+ }
853
+
854
+ function toggleQaDrawer() {
855
+ if (qaDrawerOpen) closeQaDrawer();
856
+ else openQaDrawer();
857
+ }
858
+
859
+ qaToggle?.addEventListener("click", toggleQaDrawer);
860
+ qaClose?.addEventListener("click", closeQaDrawer);
861
+
862
+ qaForm?.addEventListener("submit", (event) => {
863
+ event.preventDefault();
864
+ const text = qaInput?.value.trim() || "";
865
+ if (!text) return;
866
+ const author = qaAuthor?.value.trim() || "Audience";
867
+ const item = {
868
+ id: `qa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
869
+ author,
870
+ text,
871
+ status: "open",
872
+ createdAt: Date.now()
873
+ };
874
+ upsertQaItem(item);
875
+ emitQaEvent("qa-submit", item);
876
+ if (qaInput) qaInput.value = "";
877
+ if (qaStatus) qaStatus.textContent = "Question sent!";
878
+ });
879
+
880
+ function connectRemoteStream() {
881
+ if (!remoteEventsEnabled || typeof EventSource === "undefined" || eventSource) return;
882
+ try {
883
+ eventSource = new EventSource(eventsUrl);
884
+ eventSource.onmessage = (event) => {
885
+ try {
886
+ handleIncomingEvent(JSON.parse(event.data));
887
+ } catch {
888
+ // Ignore malformed SSE payloads.
889
+ }
890
+ };
891
+ } catch {
892
+ eventSource = null;
893
+ }
894
+ }
895
+
896
+ async function initRemoteBridge() {
897
+ if (presentation?.eventsUrl) eventsUrl = presentation.eventsUrl;
898
+ if (presentation?.qaUrl) qaUrl = presentation.qaUrl;
899
+ if (presentation?.capabilities?.events) remoteEventsEnabled = true;
900
+ if (presentation?.capabilities?.qa) remoteQaEnabled = true;
901
+ if (presentation?.capabilities?.remote !== false) {
902
+ try {
903
+ const res = await fetch(qaUrl);
904
+ if (res.ok) {
905
+ remoteQaEnabled = true;
906
+ if (presentation?.capabilities?.events !== false) remoteEventsEnabled = true;
907
+ const data = await res.json();
908
+ if (Array.isArray(data?.items)) {
909
+ data.items.forEach((item) => upsertQaItem(item));
910
+ }
911
+ }
912
+ } catch {
913
+ // Local BroadcastChannel-only mode.
914
+ }
915
+ }
916
+ connectRemoteStream();
917
+ }
918
+
222
919
  async function boot() {
920
+ if (notesRoot) applyNotesScale(restoreNotesScale());
921
+ if (timerDisplay) updateTimerDisplay();
223
922
  try {
224
923
  const response = await fetch("/api/presentation");
225
924
  if (!response.ok) throw new Error(`Server returned ${response.status}`);
226
925
  presentation = await response.json();
227
- document.title = `${presentation.title} · Flipbook MD`;
228
- titleRoot.textContent = presentation.title;
926
+ document.title = document.body.classList.contains("announcer")
927
+ ? `${presentation.title} · Presenter · Flipbook MD`
928
+ : `${presentation.title} · Flipbook MD`;
929
+ if (titleRoot) titleRoot.textContent = presentation.title;
930
+ buildSlideStrip();
229
931
  // ?slide=N (1-based) or the server's startSlide opens on that slide and tells the announcer.
230
932
  const requested = Number(new URLSearchParams(location.search).get("slide") ?? presentation.startSlide ?? NaN);
231
933
  if (Number.isInteger(requested) && requested >= 1) {
232
934
  pendingRemote = null;
233
935
  current = requested - 1;
234
936
  render();
235
- publish();
937
+ publish("goto");
236
938
  } else if (pendingRemote) {
237
939
  const message = pendingRemote;
238
940
  pendingRemote = null;
@@ -242,6 +944,8 @@ async function boot() {
242
944
  render();
243
945
  }
244
946
  channel?.postMessage({ tab: tabId, type: "hello" });
947
+ initRemoteBridge();
948
+ showHud();
245
949
  } catch (error) {
246
950
  slideRoot.innerHTML = `<p class="loading">Could not load this presentation: ${escapeHtml(error.message)}</p>`;
247
951
  }
@@ -257,11 +961,55 @@ function toggleFullscreen() {
257
961
  else document.exitFullscreen?.();
258
962
  }
259
963
 
964
+ function moveOverviewFocus(delta) {
965
+ const cards = Array.from(overviewCards?.querySelectorAll(".overview-card") ?? []);
966
+ if (!cards.length) return;
967
+ const activeIdx = cards.indexOf(document.activeElement);
968
+ const base = activeIdx >= 0 ? activeIdx : current;
969
+ const nextIdx = Math.max(0, Math.min(cards.length - 1, base + delta));
970
+ cards[nextIdx]?.focus();
971
+ }
972
+
260
973
  document.addEventListener("keydown", (event) => {
974
+ if (qaDrawerOpen && event.key === "Escape") {
975
+ event.preventDefault();
976
+ event.stopPropagation();
977
+ closeQaDrawer();
978
+ return;
979
+ }
261
980
  if (["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement?.tagName)) return;
262
981
  if (!presentation?.slides?.length) return;
263
982
  if (event.metaKey || event.ctrlKey || event.altKey) return;
264
- if (event.key === "ArrowRight" || event.key === " ") {
983
+
984
+ if (overviewOpen) {
985
+ if (event.key === "Escape") {
986
+ event.preventDefault();
987
+ event.stopPropagation();
988
+ closeOverview();
989
+ } else if (event.key.toLowerCase() === "g") {
990
+ event.preventDefault();
991
+ closeOverview();
992
+ } else if (event.key === "ArrowRight" || event.key === "ArrowDown") {
993
+ event.preventDefault();
994
+ moveOverviewFocus(1);
995
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
996
+ event.preventDefault();
997
+ moveOverviewFocus(-1);
998
+ } else if (event.key === "Home") {
999
+ event.preventDefault();
1000
+ moveOverviewFocus(-presentation.slides.length);
1001
+ } else if (event.key === "End") {
1002
+ event.preventDefault();
1003
+ moveOverviewFocus(presentation.slides.length);
1004
+ }
1005
+ return;
1006
+ }
1007
+
1008
+ if (event.key === "ArrowRight") {
1009
+ event.preventDefault();
1010
+ go(current + 1);
1011
+ } else if (event.key === " ") {
1012
+ if (document.activeElement?.closest("button, a")) return;
265
1013
  event.preventDefault();
266
1014
  go(current + 1);
267
1015
  } else if (event.key === "ArrowLeft") {
@@ -278,6 +1026,15 @@ document.addEventListener("keydown", (event) => {
278
1026
  setPlaying(!playing);
279
1027
  } else if (event.key.toLowerCase() === "f") {
280
1028
  toggleFullscreen();
1029
+ } else if (event.key.toLowerCase() === "g" && overviewDialog) {
1030
+ event.preventDefault();
1031
+ toggleOverview();
1032
+ } else if (event.key.toLowerCase() === "l" && laserToggle) {
1033
+ event.preventDefault();
1034
+ setLaserActive(!laserActive);
1035
+ } else if (event.key.toLowerCase() === "q" && qaToggle) {
1036
+ event.preventDefault();
1037
+ toggleQaDrawer();
281
1038
  }
282
1039
  });
283
1040