Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

feat(slides): Live broadcast (#293)

Niemesce9f923ab995
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c57af6e5..90dd1864 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1247,6 +1247,24 @@ jobs:
# image gone from a file with nothing on screen to say so.
run: node scripts/test-slides-assets.ts
+ - name: Audience projection rig
+ # Live broadcast: the handout, the join snapshot and every streamed op
+ # go through slides/src/audience.ts, which keeps back speaker notes
+ # and review comments and nothing else. Runs the negative control
+ # first — with the boundary emptied the rig must go red, or it is
+ # checking nothing.
+ run: |
+ if node scripts/test-audience-projection.ts --mutate > /dev/null 2>&1; then
+ echo 'negative control passed with the boundary removed'; exit 1; fi
+ node scripts/test-audience-projection.ts
+
+ - name: Broadcast follow-mode rig
+ # The audience side's decisions (slides/src/follow.ts): nav by slide
+ # ID with the index only as fallback — an insert mid-talk moves nobody;
+ # follow is the viewer's, lock is the presenter's and wins; laser
+ # samples rate-limited at the source with pen-up always sent.
+ run: node scripts/test-broadcast-follow.ts
+
- name: slides store rig
# The editor's undo/redo, selection and whole-deck replacement, at the
# store level rather than through the DOM. Bundled first for the same
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 190e0907..f5c7ee79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,19 @@ pre-1.0.
## [Unreleased]
+- **Live broadcast.** *Audience copy…* in the Share menu writes a hand-out
+ for a live show: whoever opens it lands straight in the presentation, and
+ while you are **Live** (a toggle in the speaker view, off every time you
+ present) their slide follows yours — transitions, morphs, black screen and
+ laser included — and the deck itself updates as you edit mid-talk. The copy
+ never carries your speaker notes or comments, in the file or on the wire.
+ **Lock** holds the audience on your slide; otherwise they can browse and
+ snap back. When you end the show the copy is a plain deck of what was
+ shown, and it receives nothing between shows: it holds a per-show key, not
+ the room key. *Issue new tickets…* makes every copy handed out so far stop
+ working. Built on the same end-to-end-encrypted collaboration room as
+ everything else — no second channel.
+
## [1.0.19] — 2026-09-04
- **Bento Slides works on a phone.** Eight changes land together, because
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index f53d070d..fd177faa 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -3621,6 +3621,53 @@ payload 72KB → 79KB). Most of it is the finding messages, which are the
product: a code with no explanation is not actionable. Anyone tempted to shrink
this should shorten prose, not drop checks.
+## 2026-08-08 — Live broadcast control channel
+
+**Decision.** The presenter of a deck can broadcast to copies of it over the
+existing relay: a "Save broadcast copy…" Share-menu export embeds
+`collab.broadcast = {room, relay}` and boots the copy into a locked
+present-follow viewer; the presenter's speaker view arms a broadcast per show
+(off by default) and sends signed control frames over a dedicated
+BroadcastSocket. Frame types: `{ctl:'nav',n,g}` (presenter-visible slide
+number, 1-based with interactive states excluded), `{ctl:'laser',p,g}` /
+`{ctl:'laser',off:1,g}` (slide-fraction stroke points, hold-to-draw, ~30fps
+client throttle) and `{ctl:'black',on:1|0,g}` (persisted as `lastBlack` and
+replayed to late joiners, unlike laser which is transient). Signatures over
+literal texts (`nav.${n}`, `laser.${p}`, `laser.off`, `black.on`/`black.off`)
+with the presenter's key; the relay fans a signature-less copy (clients trust
+its verification, like ops) and sends `{ctl:'presence',n}` viewer counts on
+connect/close. The relay keeps the generic per-socket rate limiter (RATE_BURST
+400/10s — enough for a full laser stroke with nav headroom) and the storage is
+two small values (`lastNav`/`lastBlack`) replayed ahead of any live frame, so
+a late joiner always lands on the newest slide. Relay changes are
+backward-compatible: old copies ignore unknown ctl frames. Details:
+docs/broadcast-design.md, server/sync-worker/src/worker.js,
+slides/src/present.ts, slides/src/main.ts.
+
+## 2026-08-10 — Broadcast rooms derived from the presenter's signing key; hosted client
+
+**Decision.** One room system for ALL broadcasts: the room is derived from the
+PRESENTER's signing key — the key this copy signs control frames with: the
+owner key (owner deck), the per-copy invite key (a shared editor copy — each
+invitee's room is unique to their copy), the shared writer key (legacy), or a
+device-local broadcast key (no-collab decks). `room = b64url(sha256(signerPub))
+[0:10]`, re-hashed until it doesn't start with 'w' (a 'w' name would be
+mistaken for a signed collab room by the relay); the relay connect token is
+derived from the room name (`tok = b64url(sha256(room))[0:18]`). Presenter and
+viewers compute the same values, so the shareable link is
+`<hostClient>?room=<name>` (no tok) and the copy embeds `broadcast:{room,relay}`
+(no tok). The relay TOFUs the presenter's `?w=` signer key per non-`w` room
+(like the tok) and verifies nav/laser/black against it; signed rooms keep the
+owner-key commitment. The collab-socket reuse path is removed; earlier
+`?b=` re-pointing and `?room=&tok=` URL formats were dropped during
+development (no backward compatibility). The hosted variant: a broadcast copy
+hosted once on the presenter's server (`doc.meta.hostClient`, set in the
+About dialog's Document properties — no prompt), re-pointed at any presenter
+via `?room=`, and joining the deck's collab room as a live reader replica so
+content updates in real time. The URL carries only the nav capability; the
+file carries the deck key (same trust as the read-only copy). Key rotation
+breaks the pinned signer key until the deck is duplicated (new docId) —
+accepted. Design: docs/broadcast-design.md, docs/hosted-broadcast-design.md.
## dash: a workbook holds two kinds of sheet — spreadsheets and datasets
2026-08-11. Settles a tension that was shipping as a visual lie.
@@ -6442,3 +6489,57 @@ Deploy: after #452's relay (deployed 2026-09-13 as `62a12ffa`, from
`ivr=audience` or `s:'aud'`, and `v`/`bc` on `ready` are ignored by clients
that do not read them. The client half (slides) feature-detects and lands
separately. Design note: private until the client ships, then promoted.
+
+## 2026-09-13 — Broadcast: the client half is a projection, a ticket, and two toggles
+
+The relay half is the entry above. This is what the slides client decided,
+built on the same day against it, with the reasoning that should not be
+re-derived.
+
+**The audience receives a PROJECTION, and one module builds all three
+surfaces.** `slides/src/audience.ts` builds the handout ("Audience copy…"),
+the join snapshot the relay serves (`projectDoc`), and filters every op the
+presenter streams (`projectOp`). Speaker notes and review comments are kept
+back — no export path stripped either before, so the first draft would have
+sent a presenter's notes to the room in the file, in the snapshot, and LIVE
+as they typed. Hidden slides stay: reachable by link, part of the deck. The
+rule that made the module honest, found by driving the real CRDT rather than
+hand-built ops: **every place the doc projection strips, the op projection
+must strip the op carrying the same content** — `doc.layouts` syncs as one
+document-level register, not as slide nodes, and "Save slide as layout"
+mid-show would have streamed a layout's notes while the handout was clean.
+`scripts/test-audience-projection.ts` diffs eight real editor edits through
+the engine and searches the projected wire for a sentinel, content-agnostic,
+so a register nobody knows about yet is caught; CI runs its negative control
+first.
+
+**An audience copy is `role: 'audience'`, not `'reader'`.** Every check that
+reads `collab.role` would otherwise do reader things — join the room path,
+boot the locked editor, skip autosave — and the audience boot path is the
+show. It holds the SHOW key as `collab.key`, the owner-signed audience invite,
+no room key, no private halves, blobs inlined (blob keys derive from
+`collab.key`, so a show-key copy could never open room-key blobs). The ticket
+(invite + show key) lives in the presenter's `collab.audience`, minted once
+and reused for every show; "Issue new tickets" re-mints it and revokes the old
+invite at the relay — defence in depth behind the cryptographic cut.
+
+**The join snapshot is built from a FRESH sync state**, never the save-time
+one: `stash` carries dead-window values including deleted slides' notes, and
+the text history carries every keystroke. The client hands the session the
+projected document only; the session builds the state.
+
+**Navigation is by slide ID; the visible index is only a fallback.** The
+design this replaced navigated by index, and an insert mid-talk moved every
+viewer to the wrong slide, silently. **Follow is the viewer's toggle; Lock is
+the presenter's and wins** — it forces follow on and makes the toggle inert.
+Lock is a UX constraint, not a security one: the viewer holds the whole deck,
+and the button says so in those words rather than implying otherwise. **Live
+is off on every show**; presenting locally never broadcasts by itself. Laser
+samples leave at ≤ 20 fps with pen-up always sent (`slides/src/follow.ts`,
+`scripts/test-broadcast-follow.ts`).
+
+**What was deleted with the old shape:** the separate broadcast socket, its
+derived rooms and trust-on-first-use pinning, `doc.broadcast`, the hosting
+URL, the hosted client, and the relay integration check that tested them.
+The contributor's relay verb logic, follow UI and off-by-default rule are the
+surviving core; the PR stays theirs.
diff --git a/docs/broadcast-design.md b/docs/broadcast-design.md
new file mode 100644
index 00000000..6bba5be2
--- /dev/null
+++ b/docs/broadcast-design.md
@@ -0,0 +1,96 @@
+# Live broadcast — design
+
+Status: shipped shape (2026-09-13). Supersedes the 2026-08-10 design that
+stood here (a separate control channel with derived rooms and a hosted
+client) — see `DECISIONS.md`, "Broadcast is a special case of collaboration".
+Companion to `collab-design.md`; the relay half is documented there and in the
+relay's own rig (`scripts/test-relay-broadcast.ts`).
+
+## What it is
+
+The presenter of a `.bento.html` deck hands out an **audience copy**. Whoever
+opens it lands straight in the show; while the presenter is live their slide
+follows the presenter's — transitions, morphs, black screen and laser included
+— and the deck itself updates as the presenter edits mid-talk. When the show
+ends, the audience copy is a plain, working deck of what was shown. Between
+shows it receives nothing, by construction.
+
+## The idea: an audience member is a collaborator with a ticket
+
+Bento already has live collaboration: an end-to-end-encrypted room on a blind
+relay, a CRDT, owner-signed invites, reader and writer roles, revocation.
+Broadcast reuses all of it instead of building a second channel. The one new
+thing is the **ticket**:
+
+- an owner-signed invite with role `audience` (same chain as "Invite to edit"),
+ which is what the relay admits on — receive-only;
+- a per-show **show key**, separate from the room's read key. An audience
+ copy carries the show key **as** its `collab.key`; it never holds the room
+ key.
+
+While live, the presenter's client encrypts every outgoing op twice — under
+the room key for collaborators (as always) and under the show key for the
+audience — and the relay fans the second stream to audience sockets without
+ever persisting it beyond the show. Nothing is encrypted under the show key
+between shows, so an audience file decrypts nothing further no matter who
+holds it or what the relay does. Both halves of the ticket live in the
+presenter's own file (`collab.audience`) and are reused for every show;
+**Issue new tickets** re-mints them, which kills every outstanding copy.
+
+## What the audience receives is a projection
+
+Everything the audience gets — the handout, the join snapshot the relay
+serves to late joiners, and every op streamed mid-show — is built by one
+module, `slides/src/audience.ts`, so the three cannot disagree:
+
+- **Speaker notes and review comments are kept back.** On every slide,
+ interactive state and custom layout; in the file, in the snapshot, and on
+ the wire — a notes edit mid-show never leaves the presenter's machine
+ (`projectOp`), or the next keystroke would repair a stripped snapshot.
+- **Hidden slides stay.** They are reachable by link and are part of the deck.
+ A presenter who wants a slide out of the handout deletes it.
+- **Blobs are inlined.** Blob keys derive from `collab.key`, so a show-key copy
+ could never open room-key blobs.
+- No room key, no private halves, no writer invite; `role: 'audience'` so no
+ reader path ever runs on it.
+
+`scripts/test-audience-projection.ts` drives the real CRDT through every edit
+that can carry a hidden field and searches the projected wire for a sentinel;
+CI runs its negative control first.
+
+## The show, as the presenter sees it
+
+- **Live** is a toggle in the speaker view, **off on every show**. Presenting
+ locally never broadcasts by itself.
+- Three verbs ride the room, signed like ops: `nav` (slide **id** first, the
+ visible index only as a fallback, so an insert mid-talk costs nothing),
+ `black`, and `laser` (≤ 20 fps at the source; the viewer's dot glides
+ between samples). Any writer in the room may drive — a co-presenter is an
+ ordinary "Invite to edit".
+- **Lock** holds the audience on the presenter's slide. It is a UX constraint,
+ not a security one — the audience already holds the deck — and the button
+ says so: *Lock keeps the audience on your slide. It does not hide the rest
+ of the deck, which they already have.*
+- The relay serves late joiners itself from the presenter's last checkpoint;
+ the presenter's machine does no per-joiner work.
+- The audience count is coarse; audience sockets receive no presence.
+
+## The show, as the audience sees it
+
+- The file opens into the show and waits for the presenter.
+- **Follow** is the viewer's toggle: un-follow to re-read a slide, snap back.
+ Under lock the toggle is disabled and says why.
+- Presenter gone: after a 60 s grace the show ends; the copy keeps the deck as
+ last delivered. Presenter not live yet: "waiting", with reconnection.
+ Tickets re-issued: the copy says it is no longer valid.
+
+## What this replaced, and why
+
+The earlier design ran a separate broadcast socket with its own rooms derived
+from the presenter's key, trust-on-first-use pinning, and navigation by index.
+Measured against the relay it ran on the same Durable Object with the same
+fan-out, so the separate channel bought no scale; its one real property —
+no durable secret in the audience file — is kept by the show key. Folding
+broadcast into collaboration deleted the second transport, the pinning, the
+derived rooms and a document field, and added mid-show edits, co-presenters,
+revocation and the follow toggle, none of which the old shape could offer.
diff --git a/scripts/build-broadcast-example.mjs b/scripts/build-broadcast-example.mjs
new file mode 100644
index 00000000..6ec264ce
--- /dev/null
+++ b/scripts/build-broadcast-example.mjs
@@ -0,0 +1,359 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Build the live-broadcast example fixtures:
+// 1. Owner deck (owner.bento.html) — real v2 collab room, owner creds in-file.
+// 2. Broadcast copy (copy.bento.html) — snapshot follow mode (no collab creds).
+// 3. Hosted copy (hosted.bento.html) — broadcast creds + live reader replica.
+//
+// node scripts/build-broadcast-example.mjs [--relay wss://host]
+//
+// Output: working/broadcast-demo/
+
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { webcrypto as crypto } from 'node:crypto'
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)))
+const shell = readFileSync(join(root, 'slides/dist-single/Bento_Slides.bento.html'), 'utf8')
+
+const DEFAULT_RELAY = 'wss://sync.bento.page'
+const relay = parseRelay(process.argv.slice(2))
+
+// ═══════════════════════════════════════════════════════════════════════
+// base64url (byte-identical to slides/src/sync/online.ts)
+// ═══════════════════════════════════════════════════════════════════════
+const b64u = {
+ enc(bytes) {
+ let s = ''
+ for (const b of bytes) s += String.fromCharCode(b)
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+ },
+ dec(s) {
+ const b = atob(s.replace(/-/g, '+').replace(/_/g, '/'))
+ const out = new Uint8Array(b.length)
+ for (let i = 0; i < b.length; i++) out[i] = b.charCodeAt(i)
+ return out
+ },
+}
+
+function parseRelay(args) {
+ const i = args.indexOf('--relay')
+ if (i !== -1 && args[i + 1]) return args[i + 1].replace(/\/+$/, '')
+ return DEFAULT_RELAY
+}
+
+function uuid() {
+ const bytes = new Uint8Array(16)
+ crypto.getRandomValues(bytes)
+ bytes[6] = (bytes[6] & 0x0f) | 0x40
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0'))
+ return `${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`
+}
+
+async function mintCollab() {
+ const kp = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
+ const pub = b64u.enc(new Uint8Array(await crypto.subtle.exportKey('raw', kp.publicKey)))
+ const priv = b64u.enc(new Uint8Array(await crypto.subtle.exportKey('pkcs8', kp.privateKey)))
+ const commit = new Uint8Array(await crypto.subtle.digest('SHA-256', b64u.dec(pub)))
+ const roomName = 'w' + b64u.enc(commit)
+ const room = `${relay}/d/${roomName}`
+ const keyBytes = new Uint8Array(32)
+ crypto.getRandomValues(keyBytes)
+ const key = b64u.enc(keyBytes)
+ const tokDigest = new Uint8Array(await crypto.subtle.digest('SHA-256', keyBytes))
+ const tok = b64u.enc(tokDigest.slice(0, 18))
+ return { room, roomName, key, tok, owner: pub, ownerPriv: priv }
+}
+
+// Broadcast room derived from the presenter's signing key (byte-identical to
+// slides/src/sync/online.ts broadcastRoom): 10-char b64url of sha256(seed),
+// re-hashed until it doesn't start with 'w' (a 'w' name would be mistaken for
+// a signed collab room by the relay).
+async function broadcastRoom(seed) {
+ let name = ''
+ do {
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed)))
+ name = b64u.enc(d).slice(0, 10)
+ seed = name
+ } while (name[0] === 'w')
+ return name
+}
+
+// ═══════════════════════════════════════════════════════════════════════
+// tiny SVG asset (geometric bento mark), embedded as a data URI
+// ═══════════════════════════════════════════════════════════════════════
+const svgMarkup =
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 240" width="320" height="240">` +
+ `<rect width="320" height="240" rx="16" fill="#F2F0EA"/>` +
+ `<rect x="24" y="24" width="128" height="96" rx="8" fill="#FF9E8A"/>` +
+ `<rect x="168" y="24" width="128" height="96" rx="8" fill="#5E7699"/>` +
+ `<rect x="24" y="132" width="272" height="84" rx="8" fill="#16273E"/>` +
+ `</svg>`
+const bentoImage = 'data:image/svg+xml;base64,' + btoa(svgMarkup)
+
+// ═══════════════════════════════════════════════════════════════════════
+// deck builders
+// ═══════════════════════════════════════════════════════════════════════
+const INK = '#0D1B2E'
+const PAPER = '#F2F0EA'
+const PEACH = '#FF9E8A'
+const STEEL = '#5E7699'
+const BODY = "'Instrument Sans', system-ui, sans-serif"
+const DISPLAY = "'Fraunces', Georgia, serif"
+
+let uid = 0
+const id = (p) => `${p}-${(++uid).toString(36)}`
+
+const text = (o) => ({
+ id: o.id ?? id('t'),
+ type: 'text',
+ x: o.x,
+ y: o.y,
+ w: o.w,
+ h: o.h,
+ rotation: o.rotation ?? 0,
+ opacity: o.opacity ?? 1,
+ html: o.html,
+ fontSize: o.fontSize ?? 24,
+ fontFamily: o.fontFamily ?? BODY,
+ fontWeight: o.fontWeight ?? 400,
+ color: o.color ?? INK,
+ align: o.align ?? 'left',
+ valign: o.valign ?? 'top',
+ lineHeight: o.lineHeight ?? 1.3,
+ ...(o.fx ? { fx: o.fx } : {}),
+})
+
+const shape = (kind, o) => ({
+ id: o.id ?? id('s'),
+ type: 'shape',
+ shape: kind,
+ x: o.x,
+ y: o.y,
+ w: o.w,
+ h: o.h,
+ rotation: o.rotation ?? 0,
+ opacity: o.opacity ?? 1,
+ fill: o.fill ?? '#000',
+ stroke: o.stroke ?? 'none',
+ strokeWidth: o.strokeWidth ?? 0,
+ radius: o.radius ?? 0,
+ ...(o.fx ? { fx: o.fx } : {}),
+})
+
+const chart = (o) => ({
+ id: o.id ?? id('c'),
+ type: 'chart',
+ x: o.x,
+ y: o.y,
+ w: o.w,
+ h: o.h,
+ rotation: 0,
+ opacity: 1,
+ preset: o.preset ?? 'bar',
+ option: o.option,
+ ...(o.fx ? { fx: o.fx } : {}),
+})
+
+const slide = (o) => ({
+ id: o.id ?? id('sl'),
+ background: o.background,
+ transition: o.transition ?? 'fade',
+ notes: o.notes ?? '',
+ elements: o.elements,
+})
+
+function buildDoc(docId, collab) {
+ const sTitle = slide({
+ id: 'bc-title',
+ background: INK,
+ transition: 'none',
+ notes: 'Broadcast demo cover. A simple title slide on the ink background.',
+ elements: [
+ text({
+ x: 96, y: 240, w: 1088, h: 120,
+ html: 'Bento Broadcast Demo',
+ fontSize: 84, fontWeight: 900, fontFamily: DISPLAY, color: PAPER, lineHeight: 1.05,
+ }),
+ text({
+ x: 96, y: 380, w: 900, h: 40,
+ html: 'A tiny deck that follows the presenter live.',
+ fontSize: 24, color: 'rgba(242,240,234,0.75)',
+ }),
+ shape('rect', { x: 96, y: 430, w: 160, h: 6, fill: PEACH }),
+ ],
+ })
+
+ const sBullets = slide({
+ id: 'bc-bullets',
+ background: PAPER,
+ transition: 'fade',
+ notes: 'Bullet slide showing the broadcast value proposition.',
+ elements: [
+ text({ x: 96, y: 84, w: 900, h: 60, html: 'What broadcast does', fontSize: 52, fontWeight: 900, fontFamily: DISPLAY, color: INK }),
+ shape('rect', { x: 96, y: 150, w: 1088, h: 2, fill: 'rgba(13,27,46,0.15)' }),
+ ...[
+ ['No accounts', 'Viewers open a file, not a login page.'],
+ ['Same renderer', 'The copy runs the real Bento presenter — morphs included.'],
+ ['Number-only nav', 'The relay sees only a slide index, never content.'],
+ ].flatMap(([head, body], i) => [
+ shape('ellipse', { x: 116, y: 210 + i * 130, w: 20, h: 20, fill: PEACH }),
+ text({ x: 156, y: 196 + i * 130, w: 800, h: 44, html: `<b>${head}</b>`, fontSize: 28, fontWeight: 800, color: INK }),
+ text({ x: 156, y: 244 + i * 130, w: 800, h: 36, html: body, fontSize: 20, color: 'rgba(13,27,46,0.72)' }),
+ ]),
+ ],
+ })
+
+ const sImage = slide({
+ id: 'bc-image',
+ background: PAPER,
+ transition: 'fade',
+ notes: 'Image slide: a small inline SVG data URI used as a self-contained asset.',
+ elements: [
+ text({ x: 96, y: 84, w: 900, h: 60, html: 'Self-contained assets', fontSize: 52, fontWeight: 900, fontFamily: DISPLAY, color: INK }),
+ shape('rect', { x: 96, y: 150, w: 1088, h: 2, fill: 'rgba(13,27,46,0.15)' }),
+ text({ x: 96, y: 200, w: 560, h: 200, html: 'This image is embedded as a data URI in the doc JSON — no external host, no broken link when the copy travels.', fontSize: 22, color: 'rgba(13,27,46,0.72)', lineHeight: 1.5 }),
+ { id: id('im'), type: 'image', x: 720, y: 180, w: 480, h: 360, rotation: 0, opacity: 1, src: bentoImage, fit: 'contain', radius: 16 },
+ ],
+ })
+
+ const sMorphA = slide({
+ id: 'bc-morph-a',
+ background: PAPER,
+ transition: 'fade',
+ notes: 'Morph beat part 1: the amber block and title are about to rearrange.',
+ elements: [
+ text({ id: 'bc-m-title', x: 96, y: 84, w: 900, h: 60, html: 'Morph transition', fontSize: 52, fontWeight: 900, fontFamily: DISPLAY, color: INK }),
+ shape('rect', { id: 'bc-m-bar', x: 96, y: 160, w: 320, h: 24, fill: PEACH }),
+ text({ x: 96, y: 230, w: 600, h: 160, html: 'The next slide shares these element ids.<br>Bento tweens position, size and color automatically.', fontSize: 24, color: 'rgba(13,27,46,0.72)', lineHeight: 1.5 }),
+ shape('rect', { id: 'bc-m-box', x: 96, y: 430, w: 200, h: 200, fill: STEEL, radius: 12 }),
+ ],
+ })
+
+ const sMorphB = slide({
+ id: 'bc-morph-b',
+ background: INK,
+ transition: 'morph',
+ notes: 'Morph beat part 2: same ids, new frames. The amber bar becomes a column, the box slides right and changes colour.',
+ elements: [
+ text({ id: 'bc-m-title', x: 96, y: 60, w: 500, h: 44, html: 'Morph transition', fontSize: 32, fontWeight: 900, fontFamily: DISPLAY, color: 'rgba(242,240,234,0.7)' }),
+ shape('rect', { id: 'bc-m-bar', x: 96, y: 120, w: 16, h: 520, fill: PEACH }),
+ text({ x: 150, y: 120, w: 500, h: 160, html: 'Same ids.<br>New frames.<br>Instant motion.', fontSize: 48, fontWeight: 800, color: PAPER, lineHeight: 1.2 }),
+ shape('rect', { id: 'bc-m-box', x: 780, y: 260, w: 360, h: 360, fill: PEACH, radius: 180 }),
+ ],
+ })
+
+ const sChart = slide({
+ id: 'bc-chart',
+ background: PAPER,
+ transition: 'fade',
+ notes: 'Chart slide: a simple bar chart using the ECharts-shaped option JSON that charts-lite understands.',
+ elements: [
+ text({ x: 96, y: 84, w: 900, h: 60, html: 'Charts work too', fontSize: 52, fontWeight: 900, fontFamily: DISPLAY, color: INK }),
+ shape('rect', { x: 96, y: 150, w: 1088, h: 2, fill: 'rgba(13,27,46,0.15)' }),
+ chart({
+ x: 96, y: 200, w: 1088, h: 420,
+ preset: 'bar',
+ option: {
+ grid: { left: 48, right: 16, top: 24, bottom: 48 },
+ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
+ yAxis: { type: 'value' },
+ color: [PEACH, STEEL],
+ tooltip: { trigger: 'axis' },
+ legend: { bottom: 0, textStyle: { color: '#6B7280' } },
+ series: [
+ { type: 'bar', name: 'Views', data: [42, 68, 54, 86, 73], itemStyle: { borderRadius: [6, 6, 0, 0] } },
+ { type: 'bar', name: 'Edits', data: [28, 35, 42, 51, 64], itemStyle: { borderRadius: [6, 6, 0, 0] } },
+ ],
+ },
+ fx: { enter: 'fade-up' },
+ }),
+ ],
+ })
+
+ return {
+ format: 'bento/slides',
+ version: 1,
+ docId,
+ title: 'Bento Broadcast Demo',
+ size: { width: 1280, height: 720 },
+ theme: { background: PAPER, color: INK, accent: PEACH, fontFamily: BODY },
+ modified: new Date().toISOString(),
+ slides: [sTitle, sBullets, sImage, sMorphA, sMorphB, sChart],
+ collab,
+ }
+}
+
+function spliceDoc(shell, doc) {
+ const json = JSON.stringify(doc).replace(/</g, '\\u003c')
+ const blockRe = /<script type="application\/bento\+json" id="bento-doc">[\s\S]*?<\/script>/
+ const out = shell.replace(blockRe, `<script type="application/bento+json" id="bento-doc">\n${json}\n</scr` + 'ipt>')
+ if (!out.includes(json)) throw new Error('splice failed — #bento-doc block not found or replacement missed')
+ return out
+}
+
+// ═══════════════════════════════════════════════════════════════════════
+// build + write
+// ═══════════════════════════════════════════════════════════════════════
+const creds = await mintCollab()
+const bcastRoom = await broadcastRoom(creds.owner)
+const ownerDocId = uuid()
+const copyDocId = uuid()
+const hostedDocId = uuid()
+
+const ownerCollab = {
+ room: creds.room,
+ key: creds.key,
+ on: true,
+ v: 2,
+ owner: creds.owner,
+ ownerPriv: creds.ownerPriv,
+ role: 'writer',
+}
+
+const broadcastCopyCollab = {
+ on: false,
+ broadcast: {
+ room: bcastRoom,
+ relay,
+ },
+}
+
+const hostedCopyCollab = {
+ ...ownerCollab,
+ role: 'reader',
+ on: true,
+ sync: undefined,
+ broadcast: {
+ room: bcastRoom,
+ relay,
+ },
+}
+delete hostedCopyCollab.writerPriv
+delete hostedCopyCollab.ownerPriv
+delete hostedCopyCollab.invite
+
+const ownerDoc = buildDoc(ownerDocId, ownerCollab)
+const copyDoc = buildDoc(copyDocId, broadcastCopyCollab)
+const hostedDoc = buildDoc(hostedDocId, hostedCopyCollab)
+
+const outDir = join(root, 'working/broadcast-demo')
+mkdirSync(outDir, { recursive: true })
+
+const ownerOut = spliceDoc(shell, ownerDoc)
+const copyOut = spliceDoc(shell, copyDoc)
+const hostedOut = spliceDoc(shell, hostedDoc)
+
+writeFileSync(join(outDir, 'owner.bento.html'), ownerOut)
+writeFileSync(join(outDir, 'copy.bento.html'), copyOut)
+writeFileSync(join(outDir, 'hosted.bento.html'), hostedOut)
+
+console.log(`owner.bento.html — ${Math.round(ownerOut.length / 1024)} KB`)
+console.log(`copy.bento.html — ${Math.round(copyOut.length / 1024)} KB`)
+console.log(`hosted.bento.html — ${Math.round(hostedOut.length / 1024)} KB`)
+console.log(`relay: ${relay}`)
+console.log(`collab room: ${creds.roomName}`)
+console.log(`broadcast room: ${bcastRoom}`)
diff --git a/scripts/test-audience-projection.ts b/scripts/test-audience-projection.ts
new file mode 100644
index 00000000..d2f703d8
--- /dev/null
+++ b/scripts/test-audience-projection.ts
@@ -0,0 +1,204 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The audience projection rig (live broadcast).
+//
+// node scripts/test-audience-projection.ts
+// node scripts/test-audience-projection.ts --mutate (must FAIL: the negative control)
+//
+// WHAT THIS PROVES. Everything a broadcast audience receives — the handout
+// file, the join snapshot the relay serves, every op streamed mid-show — goes
+// through slides/src/audience.ts, and that module keeps back exactly two
+// things: speaker notes and review comments. Security's finding on the design
+// (2026-09-12) was that no export path stripped either, so as first written
+// the audience would have received the presenter's notes in the handout, in
+// the snapshot, and LIVE as they were typed. This rig pins all three surfaces:
+//
+// projectDoc — no notes text and no `comments` key on any slide, state or
+// layout; hidden slides KEPT (reachable by link, part of the
+// deck — the judgement is recorded, not implied); `blobs`
+// dropped and bytes inline; collab.key IS the show key and is
+// NOT the room key; the invite is the audience one; no private
+// halves; readonly/template cleared.
+// projectOp — a slide-level `set notes` / `set comments` never leaves the
+// presenter (null); a slide `ins` arrives with its node
+// projected; element ops and everything else pass unchanged.
+// This is the one that keeps a stripped snapshot from being
+// repaired by the next keystroke in the notes panel.
+// carriesHidden — the predicate test-export-secrets uses on an audience
+// copy answers the same way as the assertions above.
+//
+// NEGATIVE CONTROL. `--mutate` empties AUDIENCE_HIDDEN before running (the
+// module reads it at call time), and the run must go red. A projection rig
+// that stays green with the boundary removed is checking nothing.
+
+import { AUDIENCE_HIDDEN, projectDoc, projectOp, carriesHidden } from '../slides/src/audience.ts'
+import { SyncState } from '../slides/src/sync/crdt.ts'
+import type { BentoDoc, Slide } from '../slides/src/model.ts'
+import type { Op } from '../kernel/src/sync/crdt.ts'
+
+const MUTATE = process.argv.includes('--mutate')
+if (MUTATE) (AUDIENCE_HIDDEN as unknown as string[]).length = 0
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const PNG = 'data:image/png;base64,iVBORw0KGgo='
+const slide = (o: Partial<Slide> & { id: string }): Slide =>
+ ({ background: '#fff', transition: 'fade', elements: [], notes: '', ...o } as Slide)
+const comment = { id: 'c1', author: 'A', text: 'fix the number', at: '2026-09-13T00:00:00Z' }
+
+const ROOM_KEY = 'ROOMKEY-b64u-not-for-the-audience'
+const SHOW_KEY = 'SHOWKEY-b64u-per-show'
+const ticket = {
+ invite: { pub: 'AUDPUB', priv: 'AUDPRIV', role: 'audience' as const, sig: 'OWNERSIG' },
+ key: SHOW_KEY,
+}
+
+const presenter: BentoDoc = {
+ format: 'bento/slides', version: 1, docId: 'd1', title: 'Talk',
+ size: { width: 1280, height: 720 },
+ theme: { background: '#fff', color: '#000', accent: '#f00', fontFamily: 'sans' },
+ slides: [
+ slide({ id: 's1', notes: 'remember to breathe', comments: [comment] }),
+ slide({ id: 's2', notes: 'skip if short on time', elements: [{ id: 'img', type: 'image', x: 0, y: 0, w: 10, h: 10, src: 'asset:big' } as never] }),
+ slide({ id: 's2b', stateOf: 's2', notes: 'state notes', comments: [comment] }),
+ slide({ id: 's3', hidden: true, notes: 'backup numbers' } as Partial<Slide> & { id: string }),
+ ],
+ layouts: [slide({ id: 'lay', name: 'Custom', notes: 'layout notes', comments: [comment] })],
+ assets: { big: PNG, small: PNG },
+ blobs: { big: { key: 'blobkey', mime: 'image/png', size: 9 }, gone: { key: 'k2', mime: 'image/png', size: 9 } },
+ readonly: true,
+ template: true,
+ collab: {
+ room: 'wROOM', key: ROOM_KEY, on: true, v: 2, owner: 'OWNERPUB',
+ ownerPriv: 'OWNERPRIV', writerPub: 'WPUB', writerPriv: 'WPRIV',
+ invite: { pub: 'WINV', priv: 'WINVPRIV', role: 'writer', sig: 'S' },
+ audience: ticket,
+ },
+} as unknown as BentoDoc
+
+const before = JSON.stringify(presenter)
+
+console.log('projectDoc — the handout and the join snapshot\n')
+const { doc: aud, missingAssets } = projectDoc(presenter, ticket)
+ok(JSON.stringify(presenter) === before, 'the presenter document is untouched')
+for (const s of aud.slides) {
+ ok(s.notes === '', `slide ${s.id}: notes are empty`)
+ ok(!('comments' in s), `slide ${s.id}: no comments key`)
+}
+ok(aud.layouts!.every((l) => l.notes === '' && !('comments' in l)), 'custom layouts are projected too')
+ok(aud.slides.some((s) => s.id === 's2b' && s.stateOf === 's2'), 'the interactive state slide is kept')
+ok(aud.slides.some((s) => s.id === 's3' && (s as { hidden?: boolean }).hidden === true), 'the HIDDEN slide is kept (reachable by link; part of the deck)')
+ok(aud.blobs === undefined, 'blobs are dropped (a show-key copy cannot open room-key blobs)')
+ok(aud.assets?.big === PNG, 'the offloaded asset is still inline')
+ok(missingAssets.length === 1 && missingAssets[0] === 'gone', 'a blob with no inline bytes is reported, not silently lost')
+ok(aud.readonly === undefined && aud.template === undefined, 'readonly/template are cleared')
+const c = aud.collab!
+ok(c.room === 'wROOM', 'same room')
+ok(c.key === SHOW_KEY, 'collab.key IS the show key')
+ok(c.key !== ROOM_KEY && JSON.stringify(aud).indexOf(ROOM_KEY) === -1, 'the room key appears nowhere in the audience copy')
+ok((c.role as string) === 'audience', 'role is the distinct, client-visible \'audience\' (never \'reader\': every reader check would join the room path)')
+ok(c.invite?.role === 'audience' && c.invite.pub === 'AUDPUB', 'the invite is the audience one')
+ok(c.ownerPriv === undefined && c.writerPriv === undefined, 'no private halves')
+ok((c as { audience?: unknown }).audience === undefined, 'the presenter\'s ticket store does not travel')
+ok(c.owner === 'OWNERPUB' && c.writerPub === 'WPUB', 'public keys travel (the relay verifies the chain against them)')
+ok(carriesHidden(aud).length === 0, `carriesHidden(audience copy) is empty (${carriesHidden(aud).join(', ') || 'nothing'})`)
+ok(carriesHidden(presenter).length >= 6, `carriesHidden(presenter) names what would leak: ${carriesHidden(presenter).length} items`)
+
+console.log('\nprojectOp — the live stream\n')
+const base = { a: 'actor', s: 1, l: 1 }
+const setNotes: Op = { ...base, op: 'set', sl: 's1', k: 'notes', v: 'new notes' }
+const setComments: Op = { ...base, op: 'set', sl: 's1', k: 'comments', v: [comment] }
+const setBg: Op = { ...base, op: 'set', sl: 's1', k: 'background', v: '#000' }
+const setEl: Op = { ...base, op: 'set', sl: 's1', el: 's1e1', k: 'x', v: 5 }
+const docSet: Op = { ...base, op: 'set', k: 'title', v: 'New title' }
+const insSlide: Op = { ...base, op: 'ins', kind: 'slide', id: 's9', ord: 'm', node: slide({ id: 's9', notes: 'secret', comments: [comment] }) }
+const insEl: Op = { ...base, op: 'ins', kind: 'element', id: 's1e2', sl: 's1', ord: 'm', node: { id: 'e2', type: 'text', x: 0, y: 0, w: 1, h: 1, html: 'hi' } as never }
+const del: Op = { ...base, op: 'del', kind: 'slide', id: 's1' }
+const txt: Op = { ...base, op: 'txt', el: 's1e1', sd: [1, 'actor'], ins: [{ at: '^', toks: ['x'] }] }
+
+ok(projectOp(setNotes) === null, 'a notes edit never leaves the presenter')
+ok(projectOp(setComments) === null, 'a comment never leaves the presenter')
+ok(projectOp(setBg) === setBg, 'a slide background edit passes unchanged')
+ok(projectOp(setEl) === setEl, 'an element edit passes unchanged')
+ok(projectOp(docSet) === docSet, 'a document-level edit passes unchanged')
+const projectedIns = projectOp(insSlide)
+ok(projectedIns !== null && projectedIns.op === 'ins' && projectedIns.kind === 'slide', 'an inserted slide still arrives')
+ok(projectedIns !== null && (projectedIns as typeof insSlide).node.notes === '' && !('comments' in (projectedIns as typeof insSlide).node),
+ '…with its notes and comments stripped')
+ok((insSlide.node as Slide).notes === 'secret', '…and the presenter\'s own op object is untouched')
+ok(projectOp(insEl) === insEl, 'an inserted element passes unchanged')
+ok(projectOp(del) === del && projectOp(txt) === txt, 'deletes and text deltas pass unchanged')
+
+// The property the lead asked for by name: a batch that carries a notes op
+// loses exactly that op, and the survivors are byte-identical.
+const batch = [setBg, setNotes, setEl, setComments, docSet]
+const streamed = batch.map(projectOp).filter((o): o is Op => o !== null)
+ok(streamed.length === 3 && streamed.every((o) => (o as { k?: string }).k !== 'notes' && (o as { k?: string }).k !== 'comments'),
+ 'a mixed batch streams without its notes/comments ops and with nothing else changed')
+
+// ---------------------------------------------------------------------------
+// Engine-driven: ask the CRDT which op shapes each hidden-carrying edit
+// actually produces, rather than trusting hand-built ops. Content-agnostic —
+// a SENTINEL string is planted in every hidden field the edit touches and the
+// projected wire must never contain it, while a VISIBLE marker planted in a
+// public field must arrive (so an empty stream cannot pass). This is what
+// caught `layouts`: the engine diffs doc.layouts as ONE whole-value register,
+// which no slide-scoped rule saw (security, 2026-09-13).
+console.log('\nengine-driven — every hidden-carrying edit the editor can make\n')
+const SENTINEL = 'ZZ-HIDDEN-SENTINEL-ZZ'
+const VISIBLE = 'ZZ-VISIBLE-MARKER-ZZ'
+function baseDoc(): BentoDoc {
+ return {
+ format: 'bento/slides', version: 1, docId: 'd', title: 't',
+ size: { width: 1280, height: 720 },
+ theme: { background: '#fff', color: '#000', accent: '#f00', fontFamily: 'sans' },
+ slides: [
+ slide({ id: 'p1', elements: [{ id: 'e1', type: 'text', x: 0, y: 0, w: 10, h: 10, html: 'hello' } as never] }),
+ slide({ id: 'p2' }),
+ ],
+ layouts: [slide({ id: 'l1', name: 'L' })],
+ assets: {},
+ } as unknown as BentoDoc
+}
+function driven(name: string, edit: (d: BentoDoc) => void, expectVisible = true) {
+ const before = baseDoc()
+ const engine = new SyncState('presenter')
+ engine.adopt(before)
+ const after: BentoDoc = JSON.parse(JSON.stringify(before))
+ edit(after)
+ const ops = engine.diff(before, after, { text: true })
+ ok(ops.length > 0, `${name}: the engine minted ${ops.length} op(s)`)
+ const wire = JSON.stringify(ops.map(projectOp).filter((o) => o !== null))
+ ok(!wire.includes(SENTINEL), `${name}: the sentinel never reaches the wire`)
+ if (expectVisible) ok(wire.includes(VISIBLE), `${name}: the visible edit in the same batch DOES arrive`)
+ ok(JSON.stringify(ops).includes(SENTINEL), `${name}: (control) the unprojected ops did carry the sentinel`)
+}
+driven('edit speaker notes', (d) => { d.slides[0].notes = SENTINEL; d.slides[0].background = VISIBLE })
+driven('add a comment with a reply', (d) => {
+ d.slides[0].comments = [{ ...comment, text: SENTINEL, replies: [{ id: 'r', author: 'B', text: SENTINEL, at: comment.at }] }]
+ d.slides[0].background = VISIBLE
+})
+driven('duplicate a slide that has notes', (d) => {
+ d.slides.push(slide({ id: 'p3', notes: SENTINEL, comments: [{ ...comment, text: SENTINEL }], background: VISIBLE }))
+})
+driven('new interactive state from a slide with notes', (d) => {
+ d.slides.splice(1, 0, slide({ id: 'p1b', stateOf: 'p1', notes: SENTINEL, background: VISIBLE }))
+})
+driven('save slide as layout (doc-level register)', (d) => {
+ d.layouts!.push(slide({ id: 'l2', name: VISIBLE, notes: SENTINEL, comments: [{ ...comment, text: SENTINEL }] }))
+})
+driven('edit an existing layout\'s notes', (d) => { d.layouts![0].notes = SENTINEL; d.layouts![0].name = VISIBLE })
+driven('sync a state from its parent (content + notes together)', (d) => {
+ d.slides.push(slide({ id: 'p1c', stateOf: 'p1', notes: SENTINEL, elements: [{ id: 'e1', type: 'text', x: 0, y: 0, w: 10, h: 10, html: VISIBLE } as never] }))
+})
+driven('replace the whole layouts list', (d) => { d.layouts = [slide({ id: 'l9', name: VISIBLE, notes: SENTINEL })] })
+
+console.log(`\n${checks - failures}/${checks} checks passed${MUTATE ? ' (MUTATED — this run must be red)' : ''}`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-broadcast-follow.ts b/scripts/test-broadcast-follow.ts
new file mode 100644
index 00000000..d8734c2e
--- /dev/null
+++ b/scripts/test-broadcast-follow.ts
@@ -0,0 +1,91 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Follow mode rig (live broadcast, audience side).
+//
+// node scripts/test-broadcast-follow.ts
+//
+// WHAT THIS PROVES. The audience overlay's decisions — which slide a
+// presenter's nav names, whether the viewer follows or browses, what the
+// presenter's lock does, when a laser sample is due — live in
+// slides/src/follow.ts, pure, so they can be driven here without a DOM.
+// Three properties matter and each has bitten a design before:
+//
+// 1. Navigation is by slide ID, index only as a fallback. The design this
+// replaced navigated by index; inserting a slide mid-talk sent every
+// viewer to the wrong slide, silently. Here an insert BEFORE the current
+// slide changes nothing for the viewer.
+// 2. Lock is the presenter's, follow is the viewer's, and lock wins: it
+// forces follow on and makes the toggle inert — but it never hides a
+// slide (the viewer holds the deck), so unlocking restores browsing
+// without any state to repair.
+// 3. Laser samples are rate-limited at the SOURCE (≤ 20 fps) and pen-up
+// always goes, or a viewer's dot could stick on after the presenter
+// stopped pointing.
+
+import { FollowState, laserDue, resolveNav } from '../slides/src/follow.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const slides = [
+ { id: 'a' }, { id: 'b' }, { id: 'b1', stateOf: 'b' }, { id: 'c' }, { id: 'd' },
+]
+
+console.log('resolveNav — ID first, visible index as fallback\n')
+ok(resolveNav(slides, { id: 'c', i: 1 }) === 3, 'the ID wins over a contradicting index')
+ok(resolveNav(slides, { i: 3 }) === 3, 'visible index 3 → slide c (the state is uncounted)')
+ok(resolveNav(slides, { i: 2 }) === 1, 'visible index 2 → slide b')
+ok(resolveNav(slides, { id: 'zz', i: 4 }) === 4, 'an unknown ID falls back to the index')
+ok(resolveNav(slides, { id: 'zz' }) === -1, 'an unknown ID with no index resolves to nothing')
+ok(resolveNav(slides, { i: 99 }) === -1 && resolveNav(slides, { i: 0 }) === -1, 'out-of-range and zero indices resolve to nothing')
+
+console.log('\ninsert mid-talk — the viewer does not move\n')
+{
+ const f = new FollowState(true)
+ ok(f.nav(slides, { id: 'c', i: 3 }) === 3, 'presenter on c: viewer jumps to index 3')
+ const inserted = [{ id: 'new' }, ...slides] // a slide inserted at the front
+ ok(f.nav(inserted, { id: 'c', i: 4 }) === 4, 'after the insert, c is index 4 and the viewer follows the ID there')
+ ok(resolveNav(inserted, { i: 3 }) === 2, '(control) the OLD index alone would have landed on b — the bug the ID removes')
+}
+
+console.log('\nfollow ⇄ browse\n')
+{
+ const f = new FollowState(true)
+ f.nav(slides, { id: 'b' })
+ ok(f.label() === 'following', 'starts following')
+ ok(f.toggle() === null && f.label() === 'browsing', 'toggle → browsing, no jump')
+ ok(f.nav(slides, { id: 'd' }) === null, 'while browsing a nav is remembered but not applied')
+ ok(f.presenterIndex === 4, '…remembered as the presenter\'s slide')
+ ok(f.toggle() === 4 && f.label() === 'following', 'toggle back → following, snaps to the presenter\'s slide')
+}
+
+console.log('\nlock — the presenter\'s, and it wins\n')
+{
+ const f = new FollowState(true)
+ f.toggle() // browsing
+ ok(f.nav(slides, { id: 'c', lock: true }) === 3, 'a locked nav forces follow on and applies')
+ ok(f.label() === 'locked', 'the chip reads locked')
+ ok(f.toggle() === null && f.following === true, 'the toggle is inert under lock')
+ ok(f.nav(slides, { id: 'd', lock: false }) === 4, 'an unlocked nav still applies (follow stayed on)')
+ ok(f.label() === 'following', '…and the chip reads following, not locked')
+ ok(f.toggle() === null && f.label() === 'browsing', 'browsing is available again the moment lock lifts')
+ f.applyLock(true)
+ ok(f.following && f.locked, 'lock via black also forces follow')
+ f.applyLock(false)
+ ok(!f.locked && f.following, 'unlock keeps whatever follow state lock forced — nothing to repair')
+}
+
+console.log('\nlaser rate limit at the source\n')
+ok(laserDue('0.5,0.5', 100, 0), 'first sample goes')
+ok(!laserDue('0.5,0.5', 130, 100), 'a sample 30 ms later is dropped (≤ 20 fps)')
+ok(laserDue('0.5,0.5', 150, 100), 'a sample 50 ms later goes')
+ok(laserDue(null, 101, 100), 'pen-up ALWAYS goes, whatever the clock says')
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-export-secrets.ts b/scripts/test-export-secrets.ts
index bbb0cdcb..0a7e988f 100644
--- a/scripts/test-export-secrets.ts
+++ b/scripts/test-export-secrets.ts
@@ -154,13 +154,20 @@ const collabBlock = (() => {
return src.slice(open, i + 1)
})()
-const collabFields = [...collabBlock.matchAll(/^ {4}([A-Za-z_$][\w$]*)\??:/gm)].map((m) => m[1])
-// Private key material: anything ending in -Priv, plus the delegation keypair.
+const fieldDecls = [...collabBlock.matchAll(/^ {4}([A-Za-z_$][\w$]*)\??:/gm)]
+const collabFields = fieldDecls.map((m) => m[1])
+// Private key material: anything ending in -Priv, the delegation keypair, and
+// ANY field whose declared type carries a `priv` key inside it — the audience
+// ticket store (`audience: { invite: { priv … }, key }`) is an object, matched
+// neither -Priv nor 'invite', and rode into every keepRoom copy until security
+// found it (2026-09-13): a reader could mint audience tickets the presenter
+// never issued. Discovery by SHAPE so the next nested keypair is caught too.
// `key` and `room` are the read capability — a copy that must follow the live
// session keeps them, so they are only covered by the drop-the-block default.
-const privateFields = collabFields.filter((f) => /Priv$/.test(f) || f === 'invite')
+const typeOf = (i: number) => collabBlock.slice(fieldDecls[i].index!, fieldDecls[i + 1]?.index ?? collabBlock.length)
+const privateFields = collabFields.filter((f, i) => /Priv$/.test(f) || f === 'invite' || /\bpriv\??:/.test(typeOf(i)))
-ok(collabFields.includes('key') && privateFields.length >= 3,
+ok(collabFields.includes('key') && privateFields.length >= 4 && privateFields.includes('audience'),
`model.ts declares ${collabFields.length} collab fields, ${privateFields.length} of them private (${privateFields.join(', ')})`)
const stripper = body('stripCollabSecrets')
@@ -186,6 +193,35 @@ for (const name of EXPORTS) {
ok(!/writeText\(JSON\.stringify\(this\.store\.doc\)/.test(body('copyDocJson')),
'copyDocJson() copies a stripped CLONE, never the live document')
+// The audience copy (live broadcast) is the one export that does NOT go
+// through stripCollabSecrets: it is built by the audience PROJECTION, which
+// replaces the collab block outright (show key as collab.key, audience
+// invite, no private halves) and also strips speaker notes and comments — the
+// two fields no other export strips. It is invisible to the catch-all below
+// (projectDoc clones internally), so it is pinned here by shape AND by running
+// the projection on a deck that carries everything it must lose.
+{
+ const aud = body('saveAudienceCopy')
+ ok(/\bprojectDoc\(this\.store\.doc,/.test(aud), 'saveAudienceCopy() builds the copy with projectDoc(this.store.doc, …)')
+ ok(!/serializeAuto\(this\.store\.doc\)|writeUpdatedFileAs\([^)]*this\.store\.doc/.test(mask(aud)),
+ 'saveAudienceCopy() never hands the LIVE document to the sink')
+ const { projectDoc, carriesHidden } = await import('../slides/src/audience.ts')
+ const ROOM = 'ROOM-KEY-MUST-NOT-TRAVEL', PRIV = 'OWNER-PRIV-MUST-NOT-TRAVEL', NOTE = 'NOTES-MUST-NOT-TRAVEL'
+ const deck = {
+ format: 'bento/slides', version: 1, docId: 'd', title: 't', size: { width: 1, height: 1 },
+ theme: { background: '#fff', color: '#000', accent: '#f00', fontFamily: 'x' },
+ slides: [{ id: 's', background: '#fff', transition: 'fade', elements: [], notes: NOTE,
+ comments: [{ id: 'c', author: 'a', text: NOTE, at: 'now' }] }],
+ collab: { room: 'w1', key: ROOM, on: true, v: 2, owner: 'O', ownerPriv: PRIV, writerPriv: PRIV,
+ invite: { pub: 'I', priv: PRIV, role: 'writer', sig: 'S' } },
+ }
+ const out = JSON.stringify(projectDoc(deck as never, { invite: { pub: 'A', priv: 'AP', role: 'audience', sig: 'S' }, key: 'SHOW' }).doc)
+ ok(!out.includes(ROOM), 'an audience copy carries no room key')
+ ok(!out.includes(PRIV), 'an audience copy carries no private half')
+ ok(!out.includes(NOTE), 'an audience copy carries no speaker notes and no comments')
+ ok(carriesHidden(JSON.parse(out)).length === 0, 'carriesHidden() agrees: nothing hidden travels')
+}
+
// The catch-all: any method that clones the document and then hands it to an
// outbound sink is an export, named in the list above or not. saveAsNewDeck is
// the one clone that legitimately keeps a session — it mints a brand new one.
diff --git a/slides/src/audience.ts b/slides/src/audience.ts
new file mode 100644
index 00000000..a72a8985
--- /dev/null
+++ b/slides/src/audience.ts
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * The audience projection — what a live-broadcast audience is allowed to see.
+ *
+ * An audience member is a collaborator holding a TICKET: an owner-signed
+ * `audience` invite plus a per-show SHOW KEY that is separate from the room's
+ * read key. Everything the audience receives — the handout file, the join
+ * snapshot the relay serves, and every op the presenter streams mid-show — is
+ * built by THIS module, so the three can never disagree about what was kept
+ * back. (docs/DECISIONS.md, the broadcast entry.)
+ *
+ * What is kept back: `Slide.notes` (speaker notes) and `Slide.comments`
+ * (review threads, documented editor-only). Nothing else. Hidden slides STAY —
+ * they are reachable by link and are part of the deck; a presenter who wants
+ * a slide out of the handout deletes it. The rest of the deck is the deck: an
+ * audience copy is a working file, not a stream.
+ *
+ * Three enforcement points, one boundary:
+ * 1. `projectDoc` — the handout ("Save audience copy…") AND the `audsnap`
+ * the relay serves to late joiners. Same function, so a
+ * handout can never carry what the snapshot strips or
+ * the other way round.
+ * 2. `projectOp` — every op the presenter's client encrypts under the show
+ * key mid-show. Without this, a stripped snapshot is
+ * REPAIRED by the next notes edit arriving as a plain
+ * property set — the projection would hold for exactly
+ * as long as nobody typed in the notes panel.
+ * 3. the rig — scripts/test-audience-projection.ts, negative-controlled:
+ * with AUDIENCE_HIDDEN emptied it must fail.
+ *
+ * The kernel session applies `projectOp` to the aud stream and calls
+ * `projectDoc` for snapshots; it is handed these functions and never learns
+ * the field names — the boundary is slides' and lives here only.
+ */
+import type { BentoDoc, Slide } from './model'
+import type { Op } from '../../kernel/src/sync/crdt'
+
+/** Slide-level fields an audience never receives. Comments are slide-level
+ * only in the format; elements carry neither field. */
+export const AUDIENCE_HIDDEN: readonly (keyof Slide)[] = ['notes', 'comments']
+
+/**
+ * Document-level keys whose VALUE is a list of slide-shaped objects. The CRDT
+ * diffs these as one whole-value register (`set k=layouts v=[...]`), not as
+ * slide nodes, so a projection that only looked at slide-scoped ops let
+ * "Save slide as layout" mid-show stream the layout's notes and comments —
+ * found by security driving the real engine (2026-09-13). The rule this
+ * encodes: every place `projectDoc` projects, `projectOp` must project the op
+ * that carries the same content.
+ */
+export const AUDIENCE_SLIDE_LISTS: readonly string[] = ['layouts']
+
+/** The ticket half that lives in the audience file's `collab`. */
+export type AudienceTicket = {
+ /** owner-signed invite with role 'audience' — the relay admits on the chain */
+ invite: { pub: string; priv: string; role: 'audience'; exp?: number; sig: string }
+ /** the per-show symmetric key (b64url raw AES-GCM key), NOT the room key */
+ key: string
+}
+
+/** Driven by AUDIENCE_HIDDEN at call time — the rig empties that list as
+ * its negative control, and BOTH surfaces (doc and op) must go red. `notes`
+ * is a required string in the format, so it is blanked; anything optional
+ * is deleted. */
+function projectSlide(slide: Slide): Slide {
+ const out = { ...slide } as Record<string, unknown>
+ for (const k of AUDIENCE_HIDDEN) {
+ if (k === 'notes') out.notes = ''
+ else delete out[k]
+ }
+ return out as unknown as Slide
+}
+
+/**
+ * The audience document. Deep-copies; the presenter's doc is untouched.
+ *
+ * - every slide (interactive states included) and every custom layout goes
+ * through `projectSlide`
+ * - `collab` becomes the ticket: same room, `key` = the SHOW key, the
+ * audience invite, role 'reader' (the client's read-only boot path), and no
+ * private halves — `ownerPriv`, `writerPriv` and any writer invite are gone
+ * - `blobs` is dropped: blob keys derive from `collab.key`, so a show-key copy
+ * could never open room-key blobs; the bytes are already inline in `assets`
+ * on the presenter (a referenced asset that is NOT in `assets` cannot be
+ * inlined and is reported so the caller can warn)
+ * - `readonly` and `template` are cleared: this file boots into the show by
+ * being an audience copy, not by being a player or a template
+ */
+export function projectDoc(doc: BentoDoc, ticket: AudienceTicket): { doc: BentoDoc; missingAssets: string[] } {
+ const src = doc.collab
+ if (!src) throw new Error('projectDoc: the presenter deck has no collab block')
+ const copy: BentoDoc = JSON.parse(JSON.stringify(doc))
+ copy.slides = copy.slides.map(projectSlide)
+ for (const k of AUDIENCE_SLIDE_LISTS) {
+ const list = (copy as unknown as Record<string, unknown>)[k]
+ if (Array.isArray(list)) (copy as unknown as Record<string, unknown>)[k] = list.map((x) => projectSlide(x as Slide))
+ }
+ const missingAssets: string[] = []
+ if (copy.blobs) {
+ for (const k of Object.keys(copy.blobs)) if (!copy.assets?.[k]) missingAssets.push(k)
+ delete copy.blobs
+ }
+ delete copy.readonly
+ delete copy.template
+ copy.collab = {
+ room: src.room,
+ key: ticket.key,
+ on: true,
+ // A distinct, client-visible role (security, 2026-09-13): every existing
+ // check that reads collab.role would otherwise do READER things — join the
+ // room on the room path, boot the locked editor, skip autosave — and the
+ // audience boot path is the show, not the editor.
+ role: 'audience',
+ ...(src.v !== undefined ? { v: src.v } : {}),
+ ...(src.owner !== undefined ? { owner: src.owner } : {}),
+ ...(src.writerPub !== undefined ? { writerPub: src.writerPub } : {}),
+ invite: ticket.invite,
+ }
+ return { doc: copy, missingAssets }
+}
+
+/**
+ * The op the audience may see, or null.
+ *
+ * - a `set` of a hidden key on a slide node → null (the audience never learns
+ * the notes changed, let alone what to)
+ * - a doc-level `set` of a slide-shaped list (`layouts`) → the same op with
+ * every entry projected
+ * - an `ins` of a slide → the same op with the inserted node projected (the
+ * slide must still arrive — minus its notes and comments)
+ * - everything else → unchanged. Element ops carry no hidden field; slide
+ * deletes/orders reveal nothing; doc-level sets have no hidden keys.
+ */
+export function projectOp(op: Op): Op | null {
+ if (op.op === 'set' && op.sl !== undefined && op.el === undefined
+ && (AUDIENCE_HIDDEN as readonly string[]).includes(op.k)) return null
+ // a doc-level whole-value register carrying slide-shaped objects (layouts)
+ if (op.op === 'set' && op.sl === undefined && op.el === undefined
+ && AUDIENCE_SLIDE_LISTS.includes(op.k) && Array.isArray(op.v)) {
+ return { ...op, v: (op.v as Slide[]).map(projectSlide) }
+ }
+ if (op.op === 'ins' && op.kind === 'slide') return { ...op, node: projectSlide(op.node as Slide) }
+ return op
+}
+
+/** True when a document still carries anything the projection removes —
+ * the assertion the export-secrets rig makes about an audience copy. */
+export function carriesHidden(doc: BentoDoc): string[] {
+ const hits: string[] = []
+ const all = [...doc.slides, ...(doc.layouts ?? [])]
+ const c = doc.collab
+ if (c && c.role !== 'audience') hits.push(`collab.role(${c.role})`)
+ for (const s of all) {
+ if (s.notes) hits.push(`${s.id}.notes`)
+ if ((s as { comments?: unknown }).comments !== undefined) hits.push(`${s.id}.comments`)
+ }
+ if (doc.blobs) hits.push('blobs')
+ if (c?.ownerPriv) hits.push('collab.ownerPriv')
+ if (c?.writerPriv) hits.push('collab.writerPriv')
+ if (c?.invite && c.invite.role !== 'audience') hits.push(`collab.invite(${c.invite.role})`)
+ return hits
+}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index fc79f952..11f350ed 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -35,7 +35,8 @@ import { t, setLocale, locale, localeChoices, LOCALE_CHOICES, applyDirection, is
import { availablePacks, fetchPack, markFileSaved, packCoverage, packsInFile, stageForFile, unstageFromFile } from '../packs'
import { injectFonts } from '../fonts'
import { appConfig } from '../../../kernel/src/app.ts'
-import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'
+import { disconnectOnline, joinFromDoc, mintCollab, mintInvite, mintRoomKey, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'
+import { projectDoc, projectOp, type AudienceTicket } from '../audience'
import { lsGet, lsJson, lsSet } from '../../../kernel/src/storage.ts'
const i18nT = t
@@ -962,6 +963,72 @@ export class Editor {
}
}
+ /**
+ * The audience TICKET for live broadcast — minted once per deck, reused for
+ * every show, replaced only by "Issue new tickets". An audience member is a
+ * collaborator whose `collab.key` is the SHOW key, not the room key: the
+ * presenter double-encrypts while live and the relay never persists that
+ * stream, so between shows the ticket decrypts nothing (docs/DECISIONS.md,
+ * the broadcast entry). Owner-only: the invite is owner-signed.
+ */
+ private async audienceTicket(): Promise<AudienceTicket | null> {
+ const c = this.store.doc.collab
+ if (!(c?.room && c.key && c.v === 2 && c.ownerPriv)) return null
+ if (c.audience) return c.audience
+ const invite = await mintInvite(c.ownerPriv, 'audience')
+ const ticket: AudienceTicket = { invite: { ...invite, role: 'audience' }, key: mintRoomKey() }
+ this.store.commit(() => { this.store.doc.collab!.audience = ticket })
+ return ticket
+ }
+
+ /** A live broadcast hand-out: opens straight into the show and follows the
+ * presenter while they are live. Built by the audience PROJECTION
+ * (src/audience.ts) — the same function that builds the join snapshot the
+ * relay serves — so it never carries speaker notes, comments, the room key
+ * or any private half; blobs are inlined because a show-key copy cannot
+ * open room-key blobs. Between shows it is a plain, working deck. */
+ private async saveAudienceCopy() {
+ await this.goLive()
+ const ticket = await this.audienceTicket()
+ if (!ticket) {
+ this.toast(t('Only the deck owner can issue audience tickets'))
+ return
+ }
+ this.canvas.commitTextEdit()
+ const { doc: copy, missingAssets } = projectDoc(this.store.doc, ticket)
+ copy.docId = this.store.doc.docId // same document: the audience follows THIS deck
+ if (missingAssets.length) this.toast(t('Some offloaded images are not on this machine yet and will be missing from the copy'))
+ try {
+ // serializeAuto, like every other copy written for a person: an active
+ // password reaches the file. A viewer of an encrypted deck needs the
+ // password, which is what encrypting the deck meant.
+ const ok = await writeUpdatedFileAs(await serializeAuto(copy), copy, { suffix: 'audience', keepHandle: false })
+ if (ok) this.toast(t('Audience copy saved — it opens into the show and follows you while you are live'))
+ } catch {
+ this.toast(t('Saving failed'))
+ }
+ }
+
+ /** Re-mint the audience ticket. Every audience copy handed out so far is
+ * dead from this moment — cryptographically (a new show key; nothing is
+ * ever encrypted under the old one again) and at the door (the old invite
+ * is revoked at the relay). A recurring class's handouts included: say so. */
+ private async issueNewTickets() {
+ const c = this.store.doc.collab
+ if (!(c?.v === 2 && c.ownerPriv && c.owner)) {
+ this.toast(t('Only the deck owner can issue audience tickets'))
+ return
+ }
+ const old = c.audience
+ if (!old) { this.toast(t('No audience tickets have been issued for this deck')); return }
+ if (!confirm(t('Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.'))) return
+ const tr = onlineTransport()
+ if (tr) await tr.revokeKey(old.invite.pub, c.owner, c.ownerPriv) // defence in depth behind the key change
+ this.store.commit(() => { delete this.store.doc.collab!.audience })
+ const fresh = await this.audienceTicket()
+ if (fresh) this.toast(t('New tickets issued — save a new audience copy to hand out'))
+ }
+
/** A live viewer: follows the shared session read-only. Keeps the room + read
* key + writer PUBKEY (so the relay knows the room's writer) but drops the
* writer PRIVATE key — the relay then rejects any op it tries to send. */
@@ -1348,6 +1415,12 @@ export class Editor {
t('A live viewer: follows every edit as it happens but can never change the deck — the relay enforces it.'))
action(ICONS.slideshow, t('Present-only file…'), false, () => void this.savePresentationPackage(),
t('A sealed hand-out that opens straight into the show — no editor, no live connection.'))
+ action(ICONS.broadcast, t('Audience copy…'), false, () => void this.saveAudienceCopy(),
+ t('A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.'))
+ if (this.store.doc.collab?.audience) {
+ action(ICONS.broadcast, t('Issue new tickets…'), false, () => void this.issueNewTickets(),
+ t('Replaces the audience tickets: every audience copy saved so far stops working.'))
+ }
action(ICONS.template, t('Template…'), false, () => void this.saveAsTemplate(),
t('A reusable starter: everyone who opens it gets their own fresh, independent deck.'))
} else {
@@ -1382,6 +1455,9 @@ export class Editor {
* "share" is one action for users — no separate start-a-session step. */
private async goLive() {
if (!this.session || offlineEnabled()) return
+ // An audience copy holds the SHOW key, not the room key, and must never
+ // mint or join a session of its own — its only path is the show (main.ts).
+ if (this.store.doc.collab?.role === 'audience') return
this.session.enableSharing()
await startSharing(this.session, this.store)
this.wireOnlineStatus()
@@ -2095,7 +2171,41 @@ export class Editor {
this.presenting = false
this.store.goTo(last)
this.canvas.render()
- }, { fullscreen })
+ }, { fullscreen, broadcast: this.presenterBroadcast() })
+ }
+
+ /**
+ * The show's broadcast surface, presenter side. The speaker view's Live
+ * toggle calls start(): make sure we are sharing (a proven writer), mint or
+ * reuse the audience ticket, and hand the session the show key plus the two
+ * projection functions — projectOp for every op it streams from now on,
+ * projectDoc for the audsnap it seals (and re-seals on checkpoint). The
+ * session does the rest; the show only sends verbs. Absent when there is no
+ * session at all (offline shell), so the toggle is inert rather than broken.
+ */
+ private presenterBroadcast(): import('../present').PresentBroadcast | undefined {
+ const session = this.session
+ if (!session) return undefined
+ return {
+ onShow: (fn) => session.onShow(fn),
+ presenter: {
+ start: async () => {
+ await this.goLive()
+ const ticket = await this.audienceTicket()
+ if (!ticket) throw new Error('only the deck owner can broadcast')
+ await session.startShow({
+ showKey: ticket.key,
+ projectOp,
+ // the PROJECTED document only — the session builds a fresh
+ // adopt-shaped state itself (a saved state's internals carry
+ // deleted slides' notes and the whole text history)
+ snapshot: () => ({ doc: projectDoc(this.store.doc, ticket).doc }),
+ })
+ },
+ stop: () => session.endShow(),
+ verbs: () => session.show,
+ },
+ }
}
// --- paste: external objects + cross-deck elements/slides ---------------------
@@ -3481,6 +3591,11 @@ function stripCollabSecrets(doc: import('../model').BentoDoc, opts: { keepRoom?:
delete doc.collab.writerPriv // the muzzle — no write capability travels
delete doc.collab.ownerPriv // v2: neither the owner key…
delete doc.collab.invite // …nor any invite (delegation) material
+ // …nor the audience ticket store: presenter-only. It holds the show key
+ // (worthless to a reader, who sees everything anyway) AND the audience
+ // invite's private half, which would let a reader mint audience tickets the
+ // presenter never issued. Stripped like the other private halves.
+ delete doc.collab.audience
}
/** Deep-clone an element with a fresh id (same-slide duplicates must not share ids). */
diff --git a/slides/src/follow.ts b/slides/src/follow.ts
new file mode 100644
index 00000000..7f72fd8c
--- /dev/null
+++ b/slides/src/follow.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * Follow mode — the pure half of the audience side of a live broadcast.
+ *
+ * present.ts owns the DOM; this owns the decisions, so a rig can drive them in
+ * node: which slide a presenter's `nav` names, whether the viewer is following
+ * or browsing, what the presenter's lock does to that, and when a laser sample
+ * is due. docs/broadcast-design.md.
+ */
+
+/** What a presenter's nav carries: slide ID first, visible index as fallback. */
+export type NavPayload = { id?: string; i?: number; lock?: boolean }
+
+/**
+ * Resolve a nav to a slide index, or -1. The ID wins — an insert or reorder
+ * mid-talk changes every index and no ID. The visible index (1-based, states
+ * uncounted, exactly what the presenter's counter shows) is only for a copy
+ * that somehow lacks the slide.
+ */
+export function resolveNav(slides: ReadonlyArray<{ id: string; stateOf?: string }>, p: NavPayload): number {
+ if (p.id) {
+ const byId = slides.findIndex((s) => s.id === p.id)
+ if (byId >= 0) return byId
+ }
+ if (typeof p.i === 'number' && p.i > 0) {
+ let n = 0
+ for (let i = 0; i < slides.length; i++) {
+ if (slides[i].stateOf) continue
+ n++
+ if (n === p.i) return i
+ }
+ }
+ return -1
+}
+
+/**
+ * The viewer's follow toggle and the presenter's lock, as one small machine.
+ *
+ * - following: the overlay tracks the presenter's slide
+ * - locked: the presenter has held the audience; following is forced on and
+ * the toggle is inert. Lock is a UX constraint, not a security one — the
+ * viewer holds the whole deck — so nothing here hides anything.
+ * - presenterIndex: the last slide the presenter named, so snapping back to
+ * follow lands there without waiting for the next nav
+ */
+export class FollowState {
+ following: boolean
+ locked = false
+ presenterIndex: number | null = null
+ constructor(following = true) { this.following = following }
+
+ /** The viewer clicked the chip. Returns the index to jump to, or null. */
+ toggle(): number | null {
+ if (this.locked) return null
+ this.following = !this.following
+ return this.following ? this.presenterIndex : null
+ }
+
+ /** A nav arrived. Returns the index to jump to, or null (browsing / unknown). */
+ nav(slides: ReadonlyArray<{ id: string; stateOf?: string }>, p: NavPayload): number | null {
+ this.applyLock(p.lock)
+ const idx = resolveNav(slides, p)
+ if (idx < 0) return null
+ this.presenterIndex = idx
+ return this.following ? idx : null
+ }
+
+ /** The lock flag rides on nav and black. Locking forces follow on. */
+ applyLock(lock: boolean | undefined) {
+ this.locked = !!lock
+ if (this.locked) this.following = true
+ }
+
+ /** What the chip should say — one of three states, never a fourth. */
+ label(): 'locked' | 'following' | 'browsing' {
+ return this.locked ? 'locked' : this.following ? 'following' : 'browsing'
+ }
+}
+
+/** Laser samples leave at most every `minMs`; pen-up (null) always goes. */
+export function laserDue(p: string | null, now: number, last: number, minMs = 50): boolean {
+ return p === null || now - last >= minMs
+}
diff --git a/slides/src/i18n/de.ts b/slides/src/i18n/de.ts
index b7050938..ce079ac3 100644
--- a/slides/src/i18n/de.ts
+++ b/slides/src/i18n/de.ts
@@ -757,6 +757,10 @@ export const de: Catalog = {
"Zoom in and out": "Vergrößern und verkleinern",
"Space-drag": "Leertaste + ziehen",
"Pan as well, if your mouse has a middle button": "Verschiebt ebenfalls, wenn die Maus eine mittlere Taste hat",
+ "N viewers": "N Zuschauer",
+ "Broadcast refused in offline mode": "Übertragung im Offline-Modus abgelehnt",
+ "Broadcast ended": "Übertragung beendet",
+ "Broadcast failed": "Übertragung fehlgeschlagen",
"Hide slide": "Folie ausblenden",
"Number hidden slides": "Ausgeblendete Folien nummerieren",
"Hidden — skipped while presenting and left out of PDF export": "Ausgeblendet — wird beim Präsentieren übersprungen und nicht als PDF exportiert",
@@ -774,4 +778,29 @@ export const de: Catalog = {
"Theme": "Design",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "Markenfarben für das gesamte Deck. Alles, was eine Designfarbe verwendet, folgt Ihren Änderungen hier.",
"Accent {n}": "Akzent {n}",
+ "Audience copy…": "Publikumskopie…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "Ein Handout für eine Live-Vorführung: öffnet direkt die Präsentation und folgt Ihren Folien, solange Sie live sind. Enthält nie Ihre Sprechernotizen oder Kommentare.",
+ "Issue new tickets…": "Neue Tickets ausgeben…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "Ersetzt die Publikumstickets: jede bisher gespeicherte Publikumskopie funktioniert nicht mehr.",
+ "Only the deck owner can issue audience tickets": "Nur die Besitzerin oder der Besitzer des Decks kann Publikumstickets ausgeben",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "Einige ausgelagerte Bilder sind noch nicht auf diesem Rechner und fehlen in der Kopie",
+ "Audience copy saved — it opens into the show and follows you while you are live": "Publikumskopie gespeichert — sie öffnet direkt die Vorführung und folgt Ihnen, solange Sie live sind",
+ "No audience tickets have been issued for this deck": "Für dieses Deck wurden keine Publikumstickets ausgegeben",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "Neue Tickets ausgeben? Jede bisher gespeicherte Publikumskopie funktioniert nicht mehr — auch die für eine wiederkehrende Veranstaltung verteilten.",
+ "New tickets issued — save a new audience copy to hand out": "Neue Tickets ausgegeben — speichern Sie eine neue Publikumskopie zum Verteilen",
+ "Go live — audience copies follow your slides": "Live gehen — Publikumskopien folgen Ihren Folien",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "Sperren hält das Publikum auf Ihrer Folie. Es verbirgt nicht den Rest des Decks, den es bereits hat.",
+ "Live — audience copies now follow you": "Live — Publikumskopien folgen Ihnen jetzt",
+ "Audience locked to your slide": "Publikum auf Ihre Folie gesperrt",
+ "Audience may browse the deck": "Das Publikum kann im Deck blättern",
+ "Following the presenter (locked)": "Folgt der Vortragenden (gesperrt)",
+ "Following the presenter": "Folgt der Vortragenden",
+ "Browsing — click to follow": "Blättern — klicken, um zu folgen",
+ "The presenter has locked the audience to their slide": "Die vortragende Person hat das Publikum auf ihre Folie gesperrt",
+ "Click to browse the deck on your own": "Klicken, um selbst im Deck zu blättern",
+ "Click to snap back to the presenter": "Klicken, um zur vortragenden Person zurückzuspringen",
+ "Waiting for the presenter…": "Warten auf die vortragende Person…",
+ "The show has ended — this copy stays a working deck": "Die Vorführung ist beendet — diese Kopie bleibt ein nutzbares Deck",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "Ihre Publikumskopie ist nicht mehr gültig — bitten Sie um eine neue",
+ "You left the show — reopen this file to rejoin": "Sie haben die Vorführung verlassen — öffnen Sie die Datei erneut, um wieder beizutreten",
}
diff --git a/slides/src/i18n/es.ts b/slides/src/i18n/es.ts
index d0510886..17889dc3 100644
--- a/slides/src/i18n/es.ts
+++ b/slides/src/i18n/es.ts
@@ -757,6 +757,10 @@ export const es: Catalog = {
"Zoom in and out": "Acercar y alejar",
"Space-drag": "Espacio + arrastrar",
"Pan as well, if your mouse has a middle button": "También desplaza, si tu ratón tiene botón central",
+ "N viewers": "N espectadores",
+ "Broadcast refused in offline mode": "Transmisión rechazada en modo sin conexión",
+ "Broadcast ended": "Transmisión finalizada",
+ "Broadcast failed": "Transmisión fallida",
"Hide slide": "Ocultar diapositiva",
"Number hidden slides": "Numerar diapositivas ocultas",
"Hidden — skipped while presenting and left out of PDF export": "Oculta: se omite al presentar y no se incluye en la exportación a PDF",
@@ -774,4 +778,29 @@ export const es: Catalog = {
"Theme": "Tema",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "Colores de marca de toda la presentación. Todo lo que use un color del tema se actualiza al cambiarlo aquí.",
"Accent {n}": "Acento {n}",
+ "Audience copy…": "Copia para el público…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "Un material para una sesión en directo: se abre en la presentación y sigue tus diapositivas mientras estás en directo. Nunca incluye tus notas del orador ni comentarios.",
+ "Issue new tickets…": "Emitir nuevas entradas…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "Sustituye las entradas del público: todas las copias guardadas hasta ahora dejan de funcionar.",
+ "Only the deck owner can issue audience tickets": "Solo el propietario de la presentación puede emitir entradas para el público",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "Algunas imágenes externalizadas aún no están en este equipo y faltarán en la copia",
+ "Audience copy saved — it opens into the show and follows you while you are live": "Copia para el público guardada — se abre en la sesión y te sigue mientras estás en directo",
+ "No audience tickets have been issued for this deck": "No se han emitido entradas para el público de esta presentación",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "¿Emitir nuevas entradas? Todas las copias para el público guardadas hasta ahora dejarán de funcionar, incluidas las repartidas para una sesión periódica.",
+ "New tickets issued — save a new audience copy to hand out": "Nuevas entradas emitidas — guarda una nueva copia para el público y repártela",
+ "Go live — audience copies follow your slides": "Emitir en directo — las copias del público siguen tus diapositivas",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "Bloquear mantiene al público en tu diapositiva. No oculta el resto de la presentación, que ya tienen.",
+ "Live — audience copies now follow you": "En directo — las copias del público ahora te siguen",
+ "Audience locked to your slide": "Público bloqueado en tu diapositiva",
+ "Audience may browse the deck": "El público puede explorar la presentación",
+ "Following the presenter (locked)": "Siguiendo al presentador (bloqueado)",
+ "Following the presenter": "Siguiendo al presentador",
+ "Browsing — click to follow": "Explorando — haz clic para seguir",
+ "The presenter has locked the audience to their slide": "El presentador ha bloqueado al público en su diapositiva",
+ "Click to browse the deck on your own": "Haz clic para explorar la presentación por tu cuenta",
+ "Click to snap back to the presenter": "Haz clic para volver con el presentador",
+ "Waiting for the presenter…": "Esperando al presentador…",
+ "The show has ended — this copy stays a working deck": "La sesión ha terminado — esta copia sigue siendo una presentación útil",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "Tu copia para el público ya no es válida — pide una nueva al presentador",
+ "You left the show — reopen this file to rejoin": "Has salido de la sesión — vuelve a abrir este archivo para volver a unirte",
}
diff --git a/slides/src/i18n/fr.ts b/slides/src/i18n/fr.ts
index cca67693..d2f0b3f8 100644
--- a/slides/src/i18n/fr.ts
+++ b/slides/src/i18n/fr.ts
@@ -757,6 +757,10 @@ export const fr: Catalog = {
"Zoom in and out": "Zoomer et dézoomer",
"Space-drag": "Espace + glisser",
"Pan as well, if your mouse has a middle button": "Déplace aussi, si votre souris a un bouton du milieu",
+ "N viewers": "N spectateurs",
+ "Broadcast refused in offline mode": "Diffusion refusée en mode hors ligne",
+ "Broadcast ended": "Diffusion terminée",
+ "Broadcast failed": "Échec de la diffusion",
"Hide slide": "Masquer la diapositive",
"Number hidden slides": "Numéroter les diapositives masquées",
"Hidden — skipped while presenting and left out of PDF export": "Masquée — ignorée pendant la présentation et absente de l’export PDF",
@@ -774,4 +778,29 @@ export const fr: Catalog = {
"Theme": "Thème",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "Couleurs de marque pour tout le diaporama. Tout élément utilisant une couleur du thème suit vos modifications ici.",
"Accent {n}": "Accent {n}",
+ "Audience copy…": "Copie pour le public…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "Un document pour une séance en direct : s’ouvre sur la présentation et suit vos diapositives tant que vous êtes en direct. Ne contient jamais vos notes ni vos commentaires.",
+ "Issue new tickets…": "Émettre de nouveaux billets…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "Remplace les billets du public : toutes les copies enregistrées jusqu’ici cessent de fonctionner.",
+ "Only the deck owner can issue audience tickets": "Seul le propriétaire de la présentation peut émettre des billets pour le public",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "Certaines images externalisées ne sont pas encore sur cette machine et manqueront dans la copie",
+ "Audience copy saved — it opens into the show and follows you while you are live": "Copie pour le public enregistrée — elle s’ouvre sur la séance et vous suit tant que vous êtes en direct",
+ "No audience tickets have been issued for this deck": "Aucun billet pour le public n’a été émis pour cette présentation",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "Émettre de nouveaux billets ? Toutes les copies pour le public enregistrées jusqu’ici cesseront de fonctionner, y compris celles distribuées pour une séance récurrente.",
+ "New tickets issued — save a new audience copy to hand out": "Nouveaux billets émis — enregistrez une nouvelle copie pour le public à distribuer",
+ "Go live — audience copies follow your slides": "Passer en direct — les copies du public suivent vos diapositives",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "Verrouiller garde le public sur votre diapositive. Cela ne masque pas le reste de la présentation, qu’il possède déjà.",
+ "Live — audience copies now follow you": "En direct — les copies du public vous suivent maintenant",
+ "Audience locked to your slide": "Public verrouillé sur votre diapositive",
+ "Audience may browse the deck": "Le public peut parcourir la présentation",
+ "Following the presenter (locked)": "Suit le présentateur (verrouillé)",
+ "Following the presenter": "Suit le présentateur",
+ "Browsing — click to follow": "Navigation libre — cliquez pour suivre",
+ "The presenter has locked the audience to their slide": "Le présentateur a verrouillé le public sur sa diapositive",
+ "Click to browse the deck on your own": "Cliquez pour parcourir la présentation par vous-même",
+ "Click to snap back to the presenter": "Cliquez pour revenir au présentateur",
+ "Waiting for the presenter…": "En attente du présentateur…",
+ "The show has ended — this copy stays a working deck": "La séance est terminée — cette copie reste une présentation utilisable",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "Votre copie pour le public n’est plus valide — demandez-en une nouvelle au présentateur",
+ "You left the show — reopen this file to rejoin": "Vous avez quitté la séance — rouvrez ce fichier pour la rejoindre",
}
diff --git a/slides/src/i18n/it.ts b/slides/src/i18n/it.ts
index da11ec85..4da96aa3 100644
--- a/slides/src/i18n/it.ts
+++ b/slides/src/i18n/it.ts
@@ -757,6 +757,10 @@ export const it: Catalog = {
"Zoom in and out": "Ingrandisci e riduci",
"Space-drag": "Spazio + trascina",
"Pan as well, if your mouse has a middle button": "Sposta anche, se il mouse ha il tasto centrale",
+ "N viewers": "N spettatori",
+ "Broadcast refused in offline mode": "Trasmissione rifiutata in modalità offline",
+ "Broadcast ended": "Trasmissione terminata",
+ "Broadcast failed": "Trasmissione non riuscita",
"Hide slide": "Nascondi diapositiva",
"Number hidden slides": "Numera le diapositive nascoste",
"Hidden — skipped while presenting and left out of PDF export": "Nascosta — saltata durante la presentazione ed esclusa dall’esportazione PDF",
@@ -774,4 +778,29 @@ export const it: Catalog = {
"Theme": "Tema",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "Colori del brand per tutta la presentazione. Tutto ciò che usa un colore del tema segue le modifiche fatte qui.",
"Accent {n}": "Accento {n}",
+ "Audience copy…": "Copia per il pubblico…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "Un materiale per una sessione dal vivo: si apre sulla presentazione e segue le tue diapositive mentre sei in diretta. Non contiene mai le note del relatore né i commenti.",
+ "Issue new tickets…": "Emetti nuovi biglietti…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "Sostituisce i biglietti del pubblico: ogni copia per il pubblico salvata finora smette di funzionare.",
+ "Only the deck owner can issue audience tickets": "Solo il proprietario della presentazione può emettere biglietti per il pubblico",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "Alcune immagini esternalizzate non sono ancora su questo computer e mancheranno nella copia",
+ "Audience copy saved — it opens into the show and follows you while you are live": "Copia per il pubblico salvata — si apre sulla sessione e ti segue mentre sei in diretta",
+ "No audience tickets have been issued for this deck": "Non sono stati emessi biglietti per il pubblico per questa presentazione",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "Emettere nuovi biglietti? Ogni copia per il pubblico salvata finora smetterà di funzionare, comprese quelle distribuite per una sessione ricorrente.",
+ "New tickets issued — save a new audience copy to hand out": "Nuovi biglietti emessi — salva una nuova copia per il pubblico da distribuire",
+ "Go live — audience copies follow your slides": "Vai in diretta — le copie del pubblico seguono le tue diapositive",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "Blocca tiene il pubblico sulla tua diapositiva. Non nasconde il resto della presentazione, che hanno già.",
+ "Live — audience copies now follow you": "In diretta — le copie del pubblico ora ti seguono",
+ "Audience locked to your slide": "Pubblico bloccato sulla tua diapositiva",
+ "Audience may browse the deck": "Il pubblico può sfogliare la presentazione",
+ "Following the presenter (locked)": "Segue il relatore (bloccato)",
+ "Following the presenter": "Segue il relatore",
+ "Browsing — click to follow": "Navigazione libera — clicca per seguire",
+ "The presenter has locked the audience to their slide": "Il relatore ha bloccato il pubblico sulla sua diapositiva",
+ "Click to browse the deck on your own": "Clicca per sfogliare la presentazione per conto tuo",
+ "Click to snap back to the presenter": "Clicca per tornare al relatore",
+ "Waiting for the presenter…": "In attesa del relatore…",
+ "The show has ended — this copy stays a working deck": "La sessione è terminata — questa copia resta una presentazione utilizzabile",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "La tua copia per il pubblico non è più valida — chiedine una nuova al relatore",
+ "You left the show — reopen this file to rejoin": "Hai lasciato la sessione — riapri questo file per rientrare",
}
diff --git a/slides/src/i18n/ja.ts b/slides/src/i18n/ja.ts
index e2793ced..a6e76794 100644
--- a/slides/src/i18n/ja.ts
+++ b/slides/src/i18n/ja.ts
@@ -757,6 +757,10 @@ export const ja: Catalog = {
"Zoom in and out": "拡大・縮小",
"Space-drag": "スペース+ドラッグ",
"Pan as well, if your mouse has a middle button": "中ボタンのあるマウスでも移動できます",
+ "N viewers": "N人の視聴者",
+ "Broadcast refused in offline mode": "オフラインモードでは配信できません",
+ "Broadcast ended": "配信が終了しました",
+ "Broadcast failed": "配信に失敗しました",
"Hide slide": "スライドを非表示",
"Number hidden slides": "非表示スライドに番号を付ける",
"Hidden — skipped while presenting and left out of PDF export": "非表示 — 発表中はスキップされ、PDF 書き出しにも含まれません",
@@ -774,4 +778,29 @@ export const ja: Catalog = {
"Theme": "テーマ",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "デッキ全体のブランドカラー。テーマカラーを使用している要素は、ここでの変更に追従します。",
"Accent {n}": "アクセント {n}",
+ "Audience copy…": "観客用コピー…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "ライブ配信用の配布ファイルです。開くとすぐにプレゼンテーションが始まり、配信中はあなたのスライドに追従します。発表者ノートやコメントは決して含まれません。",
+ "Issue new tickets…": "新しいチケットを発行…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "観客チケットを差し替えます。これまでに保存した観客用コピーはすべて使えなくなります。",
+ "Only the deck owner can issue audience tickets": "観客チケットを発行できるのはデッキの所有者だけです",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "外部保存された画像の一部がまだこのマシンにないため、コピーには含まれません",
+ "Audience copy saved — it opens into the show and follows you while you are live": "観客用コピーを保存しました — 開くとすぐにショーが始まり、配信中はあなたに追従します",
+ "No audience tickets have been issued for this deck": "このデッキには観客チケットが発行されていません",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "新しいチケットを発行しますか? これまでに保存した観客用コピーは、定期セッション用に配布したものも含めてすべて使えなくなります。",
+ "New tickets issued — save a new audience copy to hand out": "新しいチケットを発行しました — 配布用に新しい観客用コピーを保存してください",
+ "Go live — audience copies follow your slides": "配信開始 — 観客用コピーがあなたのスライドに追従します",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "ロックすると観客はあなたのスライドに固定されます。デッキの残りの部分は隠れません — 観客はすでに持っています。",
+ "Live — audience copies now follow you": "配信中 — 観客用コピーがあなたに追従しています",
+ "Audience locked to your slide": "観客をあなたのスライドに固定しました",
+ "Audience may browse the deck": "観客はデッキを自由に閲覧できます",
+ "Following the presenter (locked)": "発表者に追従中(固定)",
+ "Following the presenter": "発表者に追従中",
+ "Browsing — click to follow": "自由閲覧中 — クリックで追従",
+ "The presenter has locked the audience to their slide": "発表者が観客を自分のスライドに固定しています",
+ "Click to browse the deck on your own": "クリックするとデッキを自由に閲覧できます",
+ "Click to snap back to the presenter": "クリックすると発表者の位置に戻ります",
+ "Waiting for the presenter…": "発表者を待っています…",
+ "The show has ended — this copy stays a working deck": "ショーは終了しました — このコピーは引き続きデッキとして使えます",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "この観客用コピーは無効になりました — 発表者に新しいものを依頼してください",
+ "You left the show — reopen this file to rejoin": "ショーから退出しました — 再参加するにはこのファイルを開き直してください",
}
diff --git a/slides/src/i18n/packed.ts b/slides/src/i18n/packed.ts
index 21539d0a..c73b4ff7 100644
--- a/slides/src/i18n/packed.ts
+++ b/slides/src/i18n/packed.ts
@@ -763,6 +763,10 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Zoom in and out": ["拡大・縮小","放大与缩小","放大與縮小","Acercar y alejar","Zoomer et dézoomer","Vergrößern und verkleinern","Ingrandisci e riduci","Ampliar e reduzir"],
"Space-drag": ["スペース+ドラッグ","空格键+拖动","空白鍵+拖曳","Espacio + arrastrar","Espace + glisser","Leertaste + ziehen","Spazio + trascina","Espaço + arrastar"],
"Pan as well, if your mouse has a middle button": ["中ボタンのあるマウスでも移動できます","如果鼠标有中键,也可以平移","如果滑鼠有中鍵,也可以平移","También desplaza, si tu ratón tiene botón central","Déplace aussi, si votre souris a un bouton du milieu","Verschiebt ebenfalls, wenn die Maus eine mittlere Taste hat","Sposta anche, se il mouse ha il tasto centrale","Também desloca, se o rato tiver botão do meio"],
+ "N viewers": ["N人の視聴者","N 位观众","N 位觀眾","N espectadores","N spectateurs","N Zuschauer","N spettatori","N espectadores"],
+ "Broadcast refused in offline mode": ["オフラインモードでは配信できません","离线模式下无法广播","離線模式下無法廣播","Transmisión rechazada en modo sin conexión","Diffusion refusée en mode hors ligne","Übertragung im Offline-Modus abgelehnt","Trasmissione rifiutata in modalità offline","Transmissão recusada no modo offline"],
+ "Broadcast ended": ["配信が終了しました","广播已结束","廣播已結束","Transmisión finalizada","Diffusion terminée","Übertragung beendet","Trasmissione terminata","Transmissão encerrada"],
+ "Broadcast failed": ["配信に失敗しました","广播失败","廣播失敗","Transmisión fallida","Échec de la diffusion","Übertragung fehlgeschlagen","Trasmissione non riuscita","Falha na transmissão"],
"Hide slide": ["スライドを非表示","隐藏幻灯片","隱藏投影片","Ocultar diapositiva","Masquer la diapositive","Folie ausblenden","Nascondi diapositiva","Ocultar diapositivo"],
"Number hidden slides": ["非表示スライドに番号を付ける","为隐藏幻灯片编号","為隱藏投影片編號","Numerar diapositivas ocultas","Numéroter les diapositives masquées","Ausgeblendete Folien nummerieren","Numera le diapositive nascoste","Numerar diapositivos ocultos"],
"Hidden — skipped while presenting and left out of PDF export": ["非表示 — 発表中はスキップされ、PDF 書き出しにも含まれません","已隐藏 — 放映时跳过,且不包含在 PDF 导出中","已隱藏 — 放映時略過,且不包含在 PDF 匯出中","Oculta: se omite al presentar y no se incluye en la exportación a PDF","Masquée — ignorée pendant la présentation et absente de l’export PDF","Ausgeblendet — wird beim Präsentieren übersprungen und nicht als PDF exportiert","Nascosta — saltata durante la presentazione ed esclusa dall’esportazione PDF","Oculto — ignorado ao apresentar e excluído da exportação para PDF"],
@@ -780,4 +784,29 @@ export const PACKED: Record<string, ReadonlyArray<string | 0>> = {
"Theme": ["テーマ","主题","主題","Tema","Thème","Design","Tema","Tema"],
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": ["デッキ全体のブランドカラー。テーマカラーを使用している要素は、ここでの変更に追従します。","整份文稿的品牌配色。使用主题颜色的元素会随此处的更改而更新。","整份簡報的品牌配色。使用主題顏色的元素會隨此處的變更而更新。","Colores de marca de toda la presentación. Todo lo que use un color del tema se actualiza al cambiarlo aquí.","Couleurs de marque pour tout le diaporama. Tout élément utilisant une couleur du thème suit vos modifications ici.","Markenfarben für das gesamte Deck. Alles, was eine Designfarbe verwendet, folgt Ihren Änderungen hier.","Colori del brand per tutta la presentazione. Tutto ciò che usa un colore del tema segue le modifiche fatte qui.","Cores da marca para toda a apresentação. Tudo o que usa uma cor do tema acompanha as alterações feitas aqui."],
"Accent {n}": ["アクセント {n}","强调色 {n}","強調色 {n}","Acento {n}","Accent {n}","Akzent {n}","Accento {n}","Destaque {n}"],
+ "Audience copy…": ["観客用コピー…","观众副本…","觀眾副本…","Copia para el público…","Copie pour le public…","Publikumskopie…","Copia per il pubblico…","Cópia para o público…"],
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": ["ライブ配信用の配布ファイルです。開くとすぐにプレゼンテーションが始まり、配信中はあなたのスライドに追従します。発表者ノートやコメントは決して含まれません。","用于直播的分发文件:打开即进入演示,在你直播期间跟随你的幻灯片。绝不包含你的演讲者备注或批注。","用於直播的分發檔案:開啟即進入簡報,在你直播期間跟隨你的投影片。絕不包含你的講者備註或註解。","Un material para una sesión en directo: se abre en la presentación y sigue tus diapositivas mientras estás en directo. Nunca incluye tus notas del orador ni comentarios.","Un document pour une séance en direct : s’ouvre sur la présentation et suit vos diapositives tant que vous êtes en direct. Ne contient jamais vos notes ni vos commentaires.","Ein Handout für eine Live-Vorführung: öffnet direkt die Präsentation und folgt Ihren Folien, solange Sie live sind. Enthält nie Ihre Sprechernotizen oder Kommentare.","Un materiale per una sessione dal vivo: si apre sulla presentazione e segue le tue diapositive mentre sei in diretta. Non contiene mai le note del relatore né i commenti.","Um material para uma sessão ao vivo: abre na apresentação e segue os seus slides enquanto está ao vivo. Nunca inclui as suas notas do orador nem comentários."],
+ "Issue new tickets…": ["新しいチケットを発行…","签发新票据…","簽發新票券…","Emitir nuevas entradas…","Émettre de nouveaux billets…","Neue Tickets ausgeben…","Emetti nuovi biglietti…","Emitir novos bilhetes…"],
+ "Replaces the audience tickets: every audience copy saved so far stops working.": ["観客チケットを差し替えます。これまでに保存した観客用コピーはすべて使えなくなります。","更换观众票据:此前保存的所有观众副本都将失效。","更換觀眾票券:此前儲存的所有觀眾副本都將失效。","Sustituye las entradas del público: todas las copias guardadas hasta ahora dejan de funcionar.","Remplace les billets du public : toutes les copies enregistrées jusqu’ici cessent de fonctionner.","Ersetzt die Publikumstickets: jede bisher gespeicherte Publikumskopie funktioniert nicht mehr.","Sostituisce i biglietti del pubblico: ogni copia per il pubblico salvata finora smette di funzionare.","Substitui os bilhetes do público: todas as cópias guardadas até agora deixam de funcionar."],
+ "Only the deck owner can issue audience tickets": ["観客チケットを発行できるのはデッキの所有者だけです","只有演示文稿的所有者才能签发观众票据","只有簡報的擁有者才能簽發觀眾票券","Solo el propietario de la presentación puede emitir entradas para el público","Seul le propriétaire de la présentation peut émettre des billets pour le public","Nur die Besitzerin oder der Besitzer des Decks kann Publikumstickets ausgeben","Solo il proprietario della presentazione può emettere biglietti per il pubblico","Só o proprietário da apresentação pode emitir bilhetes para o público"],
+ "Some offloaded images are not on this machine yet and will be missing from the copy": ["外部保存された画像の一部がまだこのマシンにないため、コピーには含まれません","部分外置存储的图片尚未在本机,副本中将缺少它们","部分外置儲存的圖片尚未在本機,副本中將缺少它們","Algunas imágenes externalizadas aún no están en este equipo y faltarán en la copia","Certaines images externalisées ne sont pas encore sur cette machine et manqueront dans la copie","Einige ausgelagerte Bilder sind noch nicht auf diesem Rechner und fehlen in der Kopie","Alcune immagini esternalizzate non sono ancora su questo computer e mancheranno nella copia","Algumas imagens externalizadas ainda não estão nesta máquina e faltarão na cópia"],
+ "Audience copy saved — it opens into the show and follows you while you are live": ["観客用コピーを保存しました — 開くとすぐにショーが始まり、配信中はあなたに追従します","观众副本已保存 — 打开即进入演示,直播期间跟随你","觀眾副本已儲存 — 開啟即進入簡報,直播期間跟隨你","Copia para el público guardada — se abre en la sesión y te sigue mientras estás en directo","Copie pour le public enregistrée — elle s’ouvre sur la séance et vous suit tant que vous êtes en direct","Publikumskopie gespeichert — sie öffnet direkt die Vorführung und folgt Ihnen, solange Sie live sind","Copia per il pubblico salvata — si apre sulla sessione e ti segue mentre sei in diretta","Cópia para o público guardada — abre na sessão e segue-o enquanto está ao vivo"],
+ "No audience tickets have been issued for this deck": ["このデッキには観客チケットが発行されていません","此演示文稿尚未签发观众票据","此簡報尚未簽發觀眾票券","No se han emitido entradas para el público de esta presentación","Aucun billet pour le public n’a été émis pour cette présentation","Für dieses Deck wurden keine Publikumstickets ausgegeben","Non sono stati emessi biglietti per il pubblico per questa presentazione","Não foram emitidos bilhetes para o público desta apresentação"],
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": ["新しいチケットを発行しますか? これまでに保存した観客用コピーは、定期セッション用に配布したものも含めてすべて使えなくなります。","签发新票据?此前保存的所有观众副本都将失效,包括为定期活动分发的副本。","簽發新票券?此前儲存的所有觀眾副本都將失效,包括為定期活動分發的副本。","¿Emitir nuevas entradas? Todas las copias para el público guardadas hasta ahora dejarán de funcionar, incluidas las repartidas para una sesión periódica.","Émettre de nouveaux billets ? Toutes les copies pour le public enregistrées jusqu’ici cesseront de fonctionner, y compris celles distribuées pour une séance récurrente.","Neue Tickets ausgeben? Jede bisher gespeicherte Publikumskopie funktioniert nicht mehr — auch die für eine wiederkehrende Veranstaltung verteilten.","Emettere nuovi biglietti? Ogni copia per il pubblico salvata finora smetterà di funzionare, comprese quelle distribuite per una sessione ricorrente.","Emitir novos bilhetes? Todas as cópias para o público guardadas até agora deixarão de funcionar, incluindo as distribuídas para uma sessão recorrente."],
+ "New tickets issued — save a new audience copy to hand out": ["新しいチケットを発行しました — 配布用に新しい観客用コピーを保存してください","已签发新票据 — 请保存新的观众副本用于分发","已簽發新票券 — 請儲存新的觀眾副本用於分發","Nuevas entradas emitidas — guarda una nueva copia para el público y repártela","Nouveaux billets émis — enregistrez une nouvelle copie pour le public à distribuer","Neue Tickets ausgegeben — speichern Sie eine neue Publikumskopie zum Verteilen","Nuovi biglietti emessi — salva una nuova copia per il pubblico da distribuire","Novos bilhetes emitidos — guarde uma nova cópia para o público para distribuir"],
+ "Go live — audience copies follow your slides": ["配信開始 — 観客用コピーがあなたのスライドに追従します","开始直播 — 观众副本将跟随你的幻灯片","開始直播 — 觀眾副本將跟隨你的投影片","Emitir en directo — las copias del público siguen tus diapositivas","Passer en direct — les copies du public suivent vos diapositives","Live gehen — Publikumskopien folgen Ihren Folien","Vai in diretta — le copie del pubblico seguono le tue diapositive","Entrar ao vivo — as cópias do público seguem os seus slides"],
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": ["ロックすると観客はあなたのスライドに固定されます。デッキの残りの部分は隠れません — 観客はすでに持っています。","锁定会让观众停留在你的幻灯片上。它不会隐藏演示文稿的其余部分 — 观众已经拥有它们。","鎖定會讓觀眾停留在你的投影片上。它不會隱藏簡報的其餘部分 — 觀眾已經擁有它們。","Bloquear mantiene al público en tu diapositiva. No oculta el resto de la presentación, que ya tienen.","Verrouiller garde le public sur votre diapositive. Cela ne masque pas le reste de la présentation, qu’il possède déjà.","Sperren hält das Publikum auf Ihrer Folie. Es verbirgt nicht den Rest des Decks, den es bereits hat.","Blocca tiene il pubblico sulla tua diapositiva. Non nasconde il resto della presentazione, che hanno già.","Bloquear mantém o público no seu slide. Não esconde o resto da apresentação, que já têm."],
+ "Live — audience copies now follow you": ["配信中 — 観客用コピーがあなたに追従しています","直播中 — 观众副本正在跟随你","直播中 — 觀眾副本正在跟隨你","En directo — las copias del público ahora te siguen","En direct — les copies du public vous suivent maintenant","Live — Publikumskopien folgen Ihnen jetzt","In diretta — le copie del pubblico ora ti seguono","Ao vivo — as cópias do público seguem-no agora"],
+ "Audience locked to your slide": ["観客をあなたのスライドに固定しました","已将观众锁定在你的幻灯片","已將觀眾鎖定在你的投影片","Público bloqueado en tu diapositiva","Public verrouillé sur votre diapositive","Publikum auf Ihre Folie gesperrt","Pubblico bloccato sulla tua diapositiva","Público bloqueado no seu slide"],
+ "Audience may browse the deck": ["観客はデッキを自由に閲覧できます","观众可自由浏览演示文稿","觀眾可自由瀏覽簡報","El público puede explorar la presentación","Le public peut parcourir la présentation","Das Publikum kann im Deck blättern","Il pubblico può sfogliare la presentazione","O público pode percorrer a apresentação"],
+ "Following the presenter (locked)": ["発表者に追従中(固定)","跟随演讲者(已锁定)","跟隨講者(已鎖定)","Siguiendo al presentador (bloqueado)","Suit le présentateur (verrouillé)","Folgt der Vortragenden (gesperrt)","Segue il relatore (bloccato)","A seguir o apresentador (bloqueado)"],
+ "Following the presenter": ["発表者に追従中","跟随演讲者","跟隨講者","Siguiendo al presentador","Suit le présentateur","Folgt der Vortragenden","Segue il relatore","A seguir o apresentador"],
+ "Browsing — click to follow": ["自由閲覧中 — クリックで追従","自由浏览中 — 点击以跟随","自由瀏覽中 — 點擊以跟隨","Explorando — haz clic para seguir","Navigation libre — cliquez pour suivre","Blättern — klicken, um zu folgen","Navigazione libera — clicca per seguire","A navegar — clique para seguir"],
+ "The presenter has locked the audience to their slide": ["発表者が観客を自分のスライドに固定しています","演讲者已将观众锁定在其幻灯片上","講者已將觀眾鎖定在其投影片上","El presentador ha bloqueado al público en su diapositiva","Le présentateur a verrouillé le public sur sa diapositive","Die vortragende Person hat das Publikum auf ihre Folie gesperrt","Il relatore ha bloccato il pubblico sulla sua diapositiva","O apresentador bloqueou o público no seu slide"],
+ "Click to browse the deck on your own": ["クリックするとデッキを自由に閲覧できます","点击可自行浏览演示文稿","點擊可自行瀏覽簡報","Haz clic para explorar la presentación por tu cuenta","Cliquez pour parcourir la présentation par vous-même","Klicken, um selbst im Deck zu blättern","Clicca per sfogliare la presentazione per conto tuo","Clique para percorrer a apresentação por conta própria"],
+ "Click to snap back to the presenter": ["クリックすると発表者の位置に戻ります","点击回到演讲者所在位置","點擊回到講者所在位置","Haz clic para volver con el presentador","Cliquez pour revenir au présentateur","Klicken, um zur vortragenden Person zurückzuspringen","Clicca per tornare al relatore","Clique para voltar ao apresentador"],
+ "Waiting for the presenter…": ["発表者を待っています…","正在等待演讲者…","正在等待講者…","Esperando al presentador…","En attente du présentateur…","Warten auf die vortragende Person…","In attesa del relatore…","À espera do apresentador…"],
+ "The show has ended — this copy stays a working deck": ["ショーは終了しました — このコピーは引き続きデッキとして使えます","演示已结束 — 此副本仍是可用的演示文稿","簡報已結束 — 此副本仍是可用的簡報","La sesión ha terminado — esta copia sigue siendo una presentación útil","La séance est terminée — cette copie reste une présentation utilisable","Die Vorführung ist beendet — diese Kopie bleibt ein nutzbares Deck","La sessione è terminata — questa copia resta una presentazione utilizzabile","A sessão terminou — esta cópia continua a ser uma apresentação utilizável"],
+ "Your audience copy is no longer valid — ask the presenter for a new one": ["この観客用コピーは無効になりました — 発表者に新しいものを依頼してください","你的观众副本已失效 — 请向演讲者索取新的副本","你的觀眾副本已失效 — 請向講者索取新的副本","Tu copia para el público ya no es válida — pide una nueva al presentador","Votre copie pour le public n’est plus valide — demandez-en une nouvelle au présentateur","Ihre Publikumskopie ist nicht mehr gültig — bitten Sie um eine neue","La tua copia per il pubblico non è più valida — chiedine una nuova al relatore","A sua cópia para o público já não é válida — peça uma nova ao apresentador"],
+ "You left the show — reopen this file to rejoin": ["ショーから退出しました — 再参加するにはこのファイルを開き直してください","你已退出演示 — 重新打开此文件即可重新加入","你已退出簡報 — 重新開啟此檔案即可重新加入","Has salido de la sesión — vuelve a abrir este archivo para volver a unirte","Vous avez quitté la séance — rouvrez ce fichier pour la rejoindre","Sie haben die Vorführung verlassen — öffnen Sie die Datei erneut, um wieder beizutreten","Hai lasciato la sessione — riapri questo file per rientrare","Saiu da sessão — volte a abrir este ficheiro para regressar"],
}
diff --git a/slides/src/i18n/pt.ts b/slides/src/i18n/pt.ts
index faac4759..ecc76187 100644
--- a/slides/src/i18n/pt.ts
+++ b/slides/src/i18n/pt.ts
@@ -755,6 +755,10 @@ export const pt: Catalog = {
"Zoom in and out": "Ampliar e reduzir",
"Space-drag": "Espaço + arrastar",
"Pan as well, if your mouse has a middle button": "Também desloca, se o rato tiver botão do meio",
+ "N viewers": "N espectadores",
+ "Broadcast refused in offline mode": "Transmissão recusada no modo offline",
+ "Broadcast ended": "Transmissão encerrada",
+ "Broadcast failed": "Falha na transmissão",
"Hide slide": "Ocultar diapositivo",
"Number hidden slides": "Numerar diapositivos ocultos",
"Hidden — skipped while presenting and left out of PDF export": "Oculto — ignorado ao apresentar e excluído da exportação para PDF",
@@ -772,4 +776,29 @@ export const pt: Catalog = {
"Theme": "Tema",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "Cores da marca para toda a apresentação. Tudo o que usa uma cor do tema acompanha as alterações feitas aqui.",
"Accent {n}": "Destaque {n}",
+ "Audience copy…": "Cópia para o público…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "Um material para uma sessão ao vivo: abre na apresentação e segue os seus slides enquanto está ao vivo. Nunca inclui as suas notas do orador nem comentários.",
+ "Issue new tickets…": "Emitir novos bilhetes…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "Substitui os bilhetes do público: todas as cópias guardadas até agora deixam de funcionar.",
+ "Only the deck owner can issue audience tickets": "Só o proprietário da apresentação pode emitir bilhetes para o público",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "Algumas imagens externalizadas ainda não estão nesta máquina e faltarão na cópia",
+ "Audience copy saved — it opens into the show and follows you while you are live": "Cópia para o público guardada — abre na sessão e segue-o enquanto está ao vivo",
+ "No audience tickets have been issued for this deck": "Não foram emitidos bilhetes para o público desta apresentação",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "Emitir novos bilhetes? Todas as cópias para o público guardadas até agora deixarão de funcionar, incluindo as distribuídas para uma sessão recorrente.",
+ "New tickets issued — save a new audience copy to hand out": "Novos bilhetes emitidos — guarde uma nova cópia para o público para distribuir",
+ "Go live — audience copies follow your slides": "Entrar ao vivo — as cópias do público seguem os seus slides",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "Bloquear mantém o público no seu slide. Não esconde o resto da apresentação, que já têm.",
+ "Live — audience copies now follow you": "Ao vivo — as cópias do público seguem-no agora",
+ "Audience locked to your slide": "Público bloqueado no seu slide",
+ "Audience may browse the deck": "O público pode percorrer a apresentação",
+ "Following the presenter (locked)": "A seguir o apresentador (bloqueado)",
+ "Following the presenter": "A seguir o apresentador",
+ "Browsing — click to follow": "A navegar — clique para seguir",
+ "The presenter has locked the audience to their slide": "O apresentador bloqueou o público no seu slide",
+ "Click to browse the deck on your own": "Clique para percorrer a apresentação por conta própria",
+ "Click to snap back to the presenter": "Clique para voltar ao apresentador",
+ "Waiting for the presenter…": "À espera do apresentador…",
+ "The show has ended — this copy stays a working deck": "A sessão terminou — esta cópia continua a ser uma apresentação utilizável",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "A sua cópia para o público já não é válida — peça uma nova ao apresentador",
+ "You left the show — reopen this file to rejoin": "Saiu da sessão — volte a abrir este ficheiro para regressar",
}
diff --git a/slides/src/i18n/zh-Hans.ts b/slides/src/i18n/zh-Hans.ts
index 8c93423a..4d6c289b 100644
--- a/slides/src/i18n/zh-Hans.ts
+++ b/slides/src/i18n/zh-Hans.ts
@@ -757,6 +757,10 @@ export const zhHans: Catalog = {
"Zoom in and out": "放大与缩小",
"Space-drag": "空格键+拖动",
"Pan as well, if your mouse has a middle button": "如果鼠标有中键,也可以平移",
+ "N viewers": "N 位观众",
+ "Broadcast refused in offline mode": "离线模式下无法广播",
+ "Broadcast ended": "广播已结束",
+ "Broadcast failed": "广播失败",
"Hide slide": "隐藏幻灯片",
"Number hidden slides": "为隐藏幻灯片编号",
"Hidden — skipped while presenting and left out of PDF export": "已隐藏 — 放映时跳过,且不包含在 PDF 导出中",
@@ -774,4 +778,29 @@ export const zhHans: Catalog = {
"Theme": "主题",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "整份文稿的品牌配色。使用主题颜色的元素会随此处的更改而更新。",
"Accent {n}": "强调色 {n}",
+ "Audience copy…": "观众副本…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "用于直播的分发文件:打开即进入演示,在你直播期间跟随你的幻灯片。绝不包含你的演讲者备注或批注。",
+ "Issue new tickets…": "签发新票据…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "更换观众票据:此前保存的所有观众副本都将失效。",
+ "Only the deck owner can issue audience tickets": "只有演示文稿的所有者才能签发观众票据",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "部分外置存储的图片尚未在本机,副本中将缺少它们",
+ "Audience copy saved — it opens into the show and follows you while you are live": "观众副本已保存 — 打开即进入演示,直播期间跟随你",
+ "No audience tickets have been issued for this deck": "此演示文稿尚未签发观众票据",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "签发新票据?此前保存的所有观众副本都将失效,包括为定期活动分发的副本。",
+ "New tickets issued — save a new audience copy to hand out": "已签发新票据 — 请保存新的观众副本用于分发",
+ "Go live — audience copies follow your slides": "开始直播 — 观众副本将跟随你的幻灯片",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "锁定会让观众停留在你的幻灯片上。它不会隐藏演示文稿的其余部分 — 观众已经拥有它们。",
+ "Live — audience copies now follow you": "直播中 — 观众副本正在跟随你",
+ "Audience locked to your slide": "已将观众锁定在你的幻灯片",
+ "Audience may browse the deck": "观众可自由浏览演示文稿",
+ "Following the presenter (locked)": "跟随演讲者(已锁定)",
+ "Following the presenter": "跟随演讲者",
+ "Browsing — click to follow": "自由浏览中 — 点击以跟随",
+ "The presenter has locked the audience to their slide": "演讲者已将观众锁定在其幻灯片上",
+ "Click to browse the deck on your own": "点击可自行浏览演示文稿",
+ "Click to snap back to the presenter": "点击回到演讲者所在位置",
+ "Waiting for the presenter…": "正在等待演讲者…",
+ "The show has ended — this copy stays a working deck": "演示已结束 — 此副本仍是可用的演示文稿",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "你的观众副本已失效 — 请向演讲者索取新的副本",
+ "You left the show — reopen this file to rejoin": "你已退出演示 — 重新打开此文件即可重新加入",
}
diff --git a/slides/src/i18n/zh-Hant.ts b/slides/src/i18n/zh-Hant.ts
index cfe0c062..83f456ff 100644
--- a/slides/src/i18n/zh-Hant.ts
+++ b/slides/src/i18n/zh-Hant.ts
@@ -757,6 +757,10 @@ export const zhHant: Catalog = {
"Zoom in and out": "放大與縮小",
"Space-drag": "空白鍵+拖曳",
"Pan as well, if your mouse has a middle button": "如果滑鼠有中鍵,也可以平移",
+ "N viewers": "N 位觀眾",
+ "Broadcast refused in offline mode": "離線模式下無法廣播",
+ "Broadcast ended": "廣播已結束",
+ "Broadcast failed": "廣播失敗",
"Hide slide": "隱藏投影片",
"Number hidden slides": "為隱藏投影片編號",
"Hidden — skipped while presenting and left out of PDF export": "已隱藏 — 放映時略過,且不包含在 PDF 匯出中",
@@ -774,4 +778,29 @@ export const zhHant: Catalog = {
"Theme": "主題",
"Deck-wide brand colours. Anything using a theme colour follows when you change it here.": "整份簡報的品牌配色。使用主題顏色的元素會隨此處的變更而更新。",
"Accent {n}": "強調色 {n}",
+ "Audience copy…": "觀眾副本…",
+ "A hand-out for a live show: opens into the presentation and follows your slides while you are live. Never carries your speaker notes or comments.": "用於直播的分發檔案:開啟即進入簡報,在你直播期間跟隨你的投影片。絕不包含你的講者備註或註解。",
+ "Issue new tickets…": "簽發新票券…",
+ "Replaces the audience tickets: every audience copy saved so far stops working.": "更換觀眾票券:此前儲存的所有觀眾副本都將失效。",
+ "Only the deck owner can issue audience tickets": "只有簡報的擁有者才能簽發觀眾票券",
+ "Some offloaded images are not on this machine yet and will be missing from the copy": "部分外置儲存的圖片尚未在本機,副本中將缺少它們",
+ "Audience copy saved — it opens into the show and follows you while you are live": "觀眾副本已儲存 — 開啟即進入簡報,直播期間跟隨你",
+ "No audience tickets have been issued for this deck": "此簡報尚未簽發觀眾票券",
+ "Issue new tickets? Every audience copy saved so far will stop working, including ones you handed out for a recurring session.": "簽發新票券?此前儲存的所有觀眾副本都將失效,包括為定期活動分發的副本。",
+ "New tickets issued — save a new audience copy to hand out": "已簽發新票券 — 請儲存新的觀眾副本用於分發",
+ "Go live — audience copies follow your slides": "開始直播 — 觀眾副本將跟隨你的投影片",
+ "Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.": "鎖定會讓觀眾停留在你的投影片上。它不會隱藏簡報的其餘部分 — 觀眾已經擁有它們。",
+ "Live — audience copies now follow you": "直播中 — 觀眾副本正在跟隨你",
+ "Audience locked to your slide": "已將觀眾鎖定在你的投影片",
+ "Audience may browse the deck": "觀眾可自由瀏覽簡報",
+ "Following the presenter (locked)": "跟隨講者(已鎖定)",
+ "Following the presenter": "跟隨講者",
+ "Browsing — click to follow": "自由瀏覽中 — 點擊以跟隨",
+ "The presenter has locked the audience to their slide": "講者已將觀眾鎖定在其投影片上",
+ "Click to browse the deck on your own": "點擊可自行瀏覽簡報",
+ "Click to snap back to the presenter": "點擊回到講者所在位置",
+ "Waiting for the presenter…": "正在等待講者…",
+ "The show has ended — this copy stays a working deck": "簡報已結束 — 此副本仍是可用的簡報",
+ "Your audience copy is no longer valid — ask the presenter for a new one": "你的觀眾副本已失效 — 請向講者索取新的副本",
+ "You left the show — reopen this file to rejoin": "你已退出簡報 — 重新開啟此檔案即可重新加入",
}
diff --git a/slides/src/icons.ts b/slides/src/icons.ts
index a7c9fe1d..4524694c 100644
--- a/slides/src/icons.ts
+++ b/slides/src/icons.ts
@@ -38,7 +38,9 @@ export const ICONS = {
lock: svg('<rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11 V8 a4 4 0 0 1 8 0 v3"/>'),
key: svg('<circle cx="8" cy="16" r="4"/><path d="M11 13 L20 4"/><path d="M15 9 l3 3"/>'),
live: svg('<circle cx="12" cy="12" r="2.2" fill="currentColor" stroke="none"/><path d="M7.5 16.5 a6.4 6.4 0 0 1 0-9"/><path d="M16.5 7.5 a6.4 6.4 0 0 1 0 9"/><path d="M5 19 a10 10 0 0 1 0-14"/><path d="M19 5 a10 10 0 0 1 0 14"/>'),
+ broadcast: svg('<path d="M12 20V4"/><path d="M4.5 8.5a11 11 0 0 1 15 0"/><path d="M7.5 12.5a7 7 0 0 1 9 0"/><circle cx="12" cy="20" r="2" fill="currentColor" stroke="none"/>'),
stop: svg('<rect x="7" y="7" width="10" height="10" rx="1.5"/>'),
+ laser: svg('<circle cx="12" cy="12" r="2.4" fill="currentColor" stroke="none"/><path d="M12 6V2.5"/><path d="M12 21.5V18"/><path d="M6 12H2.5"/><path d="M21.5 12H18"/><path d="m8.2 8.2-4-4"/><path d="m15.8 15.8 4 4"/><path d="m15.8 8.2 4-4"/><path d="m8.2 15.8-4 4"/>'),
globe: svg('<circle cx="12" cy="12" r="9"/><path d="M3 12 h18"/><ellipse cx="12" cy="12" rx="4.2" ry="9"/>'),
code: svg('<polyline points="8 6 4 12 8 18"/><polyline points="16 6 20 12 16 18"/>'),
history: svg('<circle cx="12" cy="12" r="8.5"/><polyline points="12 7 12 12 15.5 14"/>'),
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 2f4a4109..9cddb949 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -27,7 +27,7 @@ import { Store } from './store'
import { Editor } from './editor/editor'
import { startPresentation } from './present'
import { SyncSession } from './sync/session'
-import { onlineTransport, startSharing, stopSharing } from './sync/online'
+import { onlineTransport, startSharing, stopSharing, disconnectOnline, joinFromDoc } from './sync/online'
// Tell the kernel who this app is — must precede any kernel module use
// (window title suffix, save-picker label, update manifest + its `app` check).
@@ -133,10 +133,78 @@ function bootWith(doc: BentoDoc, docIsFresh = false) {
// re-derives through the editor's `doc` hook; nothing else would visit a
// player file at all.
resolveThemeRefs(doc)
- if (doc.readonly) playerMode(doc)
+ if (doc.collab?.role === 'audience') audienceMode(doc)
+ else if (doc.readonly) playerMode(doc)
else editorMode(doc, docIsFresh)
}
+/**
+ * An AUDIENCE copy boots straight into the show and follows the presenter
+ * while they are live. It is a collaborator holding a ticket: `collab.key` is
+ * the per-show key, the invite is the owner-signed audience one, and the
+ * session's transport connects receive-only on that role — it never mints or
+ * joins a session of its own, never sends a frame. The projected deck (no
+ * notes, no comments) streams in through the ordinary reader path, so the
+ * slides update live as the presenter edits; the three verbs (nav, black,
+ * laser) reach the overlay through the session's show events. Between shows
+ * the file is a plain, working deck — leaving the show lands on a card, never
+ * the editor. (docs/DECISIONS.md, the broadcast entry.)
+ */
+function audienceMode(doc: BentoDoc) {
+ document.title = `${doc.title} — ${appConfig().appName}`
+ if (doc.fonts?.length) injectFonts(doc)
+ document.getElementById('bento-splash')?.remove()
+
+ const store = new Store(doc)
+ const session = new SyncSession(store)
+ joinFromDoc(session, store)
+
+ let exited = false
+ let unsubscribeDoc: (() => void) | null = null
+ const exitCard = () => {
+ if (exited) return
+ exited = true
+ disconnectOnline(session)
+ unsubscribeDoc?.()
+ const card = document.createElement('div')
+ card.className = 'ed-player'
+ card.innerHTML =
+ `<div class="ed-playercard"><h1>${doc.title.replace(/</g, '&lt;')}</h1>` +
+ `<p>${t('You left the show — reopen this file to rejoin')}</p></div>`
+ document.body.appendChild(card)
+ }
+
+ const show = startPresentation(doc, 0, exitCard, {
+ broadcast: { audience: true, onShow: (fn) => session.onShow(fn) },
+ onDocChange: ({ slidesEl, deck, buildSection }) => {
+ const applyDoc = () => {
+ const cur = deck.getIndices().h
+ const curId = doc.slides[cur]?.id
+ if (doc.slides.length !== slidesEl.children.length) {
+ // structural change: rebuild the section list and re-settle on the
+ // same slide BY ID (an insert before it must not move the audience)
+ slidesEl.replaceChildren(...doc.slides.map(buildSection))
+ deck.sync()
+ const back = doc.slides.findIndex((sl) => sl.id === curId)
+ show.goTo(back >= 0 ? back : Math.min(cur, doc.slides.length - 1))
+ } else {
+ // content change: re-render the current slide in place (no fx replay —
+ // the slide is already shown; entrance fx run on slidechange only).
+ // The CONTENTS of a fresh section, not the section itself: a
+ // <section> nested inside a <section> is a vertical slide to Reveal,
+ // and the next arrow would descend into it instead of advancing.
+ const section = slidesEl.children[cur] as HTMLElement | undefined
+ const slide = doc.slides[cur]
+ if (section && slide) section.replaceChildren(...buildSection(slide, cur).childNodes)
+ }
+ }
+ unsubscribeDoc = store.on('doc', applyDoc)
+ },
+ })
+
+ ;(window as any).bento = { format: doc.format, doc }
+}
+
/**
* Read-only files are PLAYER files: they open straight into the show and
* never expose the editor. Leaving the presentation lands on a minimal card.
@@ -238,7 +306,8 @@ if (location.hash === '#present') {
transports: () => session.transportKinds,
/** start an online session (mints doc.collab, connects the relay) */
share: () => {
- void startSharing(session, store)
+ // same guard as editor.goLive(): an audience copy never mints a session
+ if (store.doc.collab?.role !== 'audience') void startSharing(session, store)
return store.doc.collab
},
unshare: () => stopSharing(session, store),
diff --git a/slides/src/model.ts b/slides/src/model.ts
index 09b2b2bc..bd25c4e3 100644
--- a/slides/src/model.ts
+++ b/slides/src/model.ts
@@ -558,7 +558,7 @@ export interface BentoDoc {
writerPub?: string
writerPriv?: string
/** 'reader' = this copy is a live viewer: receives updates, never sends. */
- role?: 'writer' | 'reader'
+ role?: 'writer' | 'reader' | 'audience'
/**
* Fine-grained access (v1.0.3+, `v: 2`): per-person keys. The room id
* commits to the OWNER's pubkey. A member copy carries an INVITE — an
@@ -573,12 +573,28 @@ export interface BentoDoc {
invite?: {
pub: string
priv: string
+ /** 'audience' (live broadcast) admits a receive-only socket for the
+ * duration of a show; it travels only in audience copies, whose `key`
+ * is the show key rather than the room key (see src/audience.ts). */
role: 'writer' | 'commenter' | 'audience'
/** unix ms expiry; 0/absent = no expiry */
exp?: number
/** owner's signature over `inv.${pub}.${role}.${exp||0}` */
sig: string
}
+ /**
+ * Live broadcast tickets (PRESENTER's copy only; additive, old shells
+ * preserve it). Minted once by "Save audience copy…" and reused for every
+ * show until "Issue new tickets" re-mints both halves, which kills every
+ * outstanding audience copy: `invite` is the owner-signed audience
+ * invite the relay admits on, `key` the per-show symmetric key the
+ * presenter double-encrypts under while live. Never in an audience copy
+ * (that copy carries the invite and has `key` AS its collab.key).
+ */
+ audience?: {
+ invite: { pub: string; priv: string; role: 'audience'; exp?: number; sig: string }
+ key: string
+ }
}
/**
* Template file (.dotx-style): every OPEN instantiates a fresh document —
diff --git a/slides/src/present.ts b/slides/src/present.ts
index 6fc91d19..7a70b937 100644
--- a/slides/src/present.ts
+++ b/slides/src/present.ts
@@ -12,8 +12,12 @@ import type { BentoDoc, GradientFill, ShapeElement, Slide, SlideElement } from '
import { morphKey, paginates, inLinearFlow } from './model'
import { applyElementFrame, gradientLineCoords, renderSlide } from './render'
import { paintSpeaker, setSpeakerWindow, speakerIdleBody, speakerWindow } from './screens'
+import { ICONS } from './icons'
import { t } from './i18n'
import { lsGet, lsSet } from '../../kernel/src/storage.ts'
+import type { ShowEvent, ShowVerbs } from '../../kernel/src/sync/session.ts'
+import { FollowState, laserDue } from './follow'
+import { offlineEnabled } from './update'
const MORPH_DURATION_DEFAULT = 0.65
/** Set per-deck by doc.present.morphSeconds; clamped to something sane. */
@@ -22,13 +26,55 @@ const MORPH_EASE = 'power2.inOut'
export interface PresentSession {
exit(): void
+ /** Absolute slide navigation: jump the show to a 0-based slide index. */
+ goTo(index: number): void
+ /** Show or hide the audience blackout (audience copy side). */
+ setBlack(on: boolean): void
+ /** Position the remote laser dot from the presenter (null = hide). */
+ setRemoteLaser(p: string | null): void
+}
+
+/**
+ * Live broadcast, as the show sees it. Broadcast is a special case of live
+ * collaboration (docs/DECISIONS.md): the presenter's session streams a
+ * PROJECTED copy of the deck plus three signed verbs to audience copies over
+ * the room they already share. present.ts owns only what is visible — the
+ * Live/Lock toggles, the audience count, follow mode, the cards — and hands
+ * every wire concern to the session through this surface. Payloads are
+ * slides' own objects, sealed by the transport:
+ * nav { id, i, lock } slide ID first (an insert mid-talk costs nothing),
+ * visible index as the fallback, and the lock flag
+ * black { on, lock }
+ * laser 'fx,fy' | null fractions of the slide box; ≤ 20 fps at the source
+ */
+export interface PresentBroadcast {
+ /** presenter side — absent on an audience copy */
+ presenter?: {
+ start(): Promise<void>
+ stop(): Promise<void>
+ verbs(): ShowVerbs | null
+ }
+ /** both sides: verbs (audience), count/checkpoint (presenter), closed */
+ onShow(fn: (e: ShowEvent) => void): () => void
+ /** true on an audience copy: follow the presenter, show the follow chip */
+ audience?: boolean
}
export function startPresentation(
doc: BentoDoc,
startIndex: number,
onExit: (lastIndex: number) => void,
- opts: { fullscreen?: boolean } = {},
+ opts: {
+ fullscreen?: boolean
+ /** hosted-client live sync: invoked once at init with the pieces needed to
+ * re-render the deck on remote doc changes (slidesEl, deck, buildSection) */
+ onDocChange?: (ctx: {
+ slidesEl: HTMLElement
+ deck: Reveal.Api
+ buildSection: (s: BentoDoc['slides'][number], i: number) => HTMLElement
+ }) => void
+ broadcast?: PresentBroadcast
+ } = {},
): PresentSession {
MORPH_DURATION = Math.min(6, Math.max(0.1, doc.present?.morphSeconds ?? MORPH_DURATION_DEFAULT))
@@ -46,7 +92,10 @@ export function startPresentation(
revealEl.appendChild(slidesEl)
overlay.appendChild(revealEl)
- doc.slides.forEach((slide, i) => {
+ // Extracted from the forEach so the broadcast viewer can rebuild one
+ // section when the presenter's document changes underneath it. The index
+ // is the loop's: `morphNext` looks one slide ahead.
+ const buildSection = (slide: BentoDoc['slides'][number], i: number) => {
const section = document.createElement('section')
// Morph slides swap instantly; the Flip animation supplies the motion.
//
@@ -77,8 +126,9 @@ export function startPresentation(
aside.textContent = slide.notes
section.appendChild(aside)
}
- slidesEl.appendChild(section)
- })
+ return section
+ }
+ doc.slides.forEach((slide, i) => slidesEl.appendChild(buildSection(slide, i)))
document.body.appendChild(overlay)
@@ -159,9 +209,13 @@ export function startPresentation(
laserTrail.append(laserTrailHalo, laserTrailCore)
const laserDot = document.createElement('div')
laserDot.className = 'bento-laser-dot'
- laserLayer.append(laserTrail, laserDot)
+ const remoteLaserDot = document.createElement('div')
+ remoteLaserDot.className = 'bento-laser-dot bento-remote'
+ laserLayer.append(laserTrail, laserDot, remoteLaserDot)
- const LASER_TRAIL_LIFETIME = 275
+ // ~0.8s fade, in the direction of Excalidraw's 1s laser decay — short enough
+ // to stay responsive, long enough that the tail reads as a sweep, not a smear.
+ const LASER_TRAIL_LIFETIME = 800
const LASER_TRAIL_SAMPLE_MS = 5
const LASER_TRAIL_SEGMENTS = Math.ceil(LASER_TRAIL_LIFETIME / LASER_TRAIL_SAMPLE_MS) + 1
const laserTrailHaloSegments: SVGPathElement[] = []
@@ -201,12 +255,15 @@ export function startPresentation(
() => ({ x: 0, y: 0, time: 0 }),
)
let laserEnabled = false
+ let laserDrawing = false
let laserFrame = 0
let laserTrailFrame = 0
let laserTrailStart = 0
let laserTrailLength = 0
let laserTrailVisibleSegments = 0
let laserPoint: { x: number; y: number } | null = null
+ let laserSentThisStroke = false
+ let lastLaserSend = 0
const hideLaserDot = () => {
laserDot.classList.remove('visible')
@@ -347,18 +404,24 @@ export function startPresentation(
}
const resetLaserPointer = () => {
+ if (laserDrawing && laserSentThisStroke) {
+ laserDrawing = false
+ sendLaserPoint(null)
+ }
+ laserDrawing = false
hideLaserDot()
clearLaserTrail()
if (laserFrame) cancelAnimationFrame(laserFrame)
laserFrame = 0
laserPoint = null
overlay.classList.remove('laser-over-slide')
+ laserSentThisStroke = false
}
const paintLaser = (now: number) => {
laserFrame = 0
const point = laserPoint
- if (!laserEnabled || blacked || !deckReady || !point) {
+ if (!laserEnabled || blacked || !deckReady || !point || !laserDrawing) {
resetLaserPointer()
return
}
@@ -379,6 +442,17 @@ export function startPresentation(
overlay.classList.remove('laser-over-slide')
return
}
+ const sendAt = performance.now()
+ // ~30fps on the wire — Excalidraw's CURSOR_SYNC_TIMEOUT=33ms. The relay
+ // burst (400/10s) fits a continuous stroke with nav headroom; the copy
+ // still sub-frame-smooths with a short CSS tween.
+ if (sendAt - lastLaserSend >= 33) {
+ const fx = Math.max(0, Math.min(1, (point.x - rect.left) / rect.width))
+ const fy = Math.max(0, Math.min(1, (point.y - rect.top) / rect.height))
+ sendLaserPoint(`${fx.toFixed(4)},${fy.toFixed(4)}`)
+ lastLaserSend = sendAt
+ laserSentThisStroke = true
+ }
const host = overlay.getBoundingClientRect()
const x = point.x - host.left
const y = point.y - host.top
@@ -394,11 +468,85 @@ export function startPresentation(
}
const scheduleLaser = (ev: PointerEvent) => {
- if (!laserEnabled || ev.pointerType === 'touch' || !ev.isPrimary) return
+ if (!laserEnabled || !laserDrawing || ev.pointerType === 'touch' || !ev.isPrimary) return
laserPoint = { x: ev.clientX, y: ev.clientY }
if (!laserFrame) laserFrame = requestAnimationFrame(paintLaser)
}
+ // ——— remote (broadcast) laser trail ———
+ // The channel carries dot points at ~30fps (33ms throttle); the LOCAL trail is sampled at
+ // 5ms/1.5px and is never sent. Excalidraw's collab laser is the model here:
+ // the trail head is glued to the pointer's CURRENT position and the whole
+ // stroke redraws every frame — never pre-baked ahead of it. Feeding the
+ // received points subdivided along the tween path injected the ENTIRE
+ // 100ms segment at arrival while the dot still crawled after it, so the
+ // trail visibly ran AHEAD of the pointer. Instead, sample the dot's
+ // RENDERED position every frame (the CSS tween glides it; offsetLeft/Top
+ // are already in trail coordinate space) and feed that — head glued to the
+ // dot at every instant, same fade, same taper, no wire change.
+ let remoteTrailFrame = 0
+ const sampleRemoteTrail = (now: number) => {
+ remoteTrailFrame = 0
+ if (laserDrawing || reduceMotion || blacked || !remoteLaserDot.classList.contains('visible')) return
+ addLaserTrailPoint(remoteLaserDot.offsetLeft, remoteLaserDot.offsetTop, now)
+ if (laserTrailLength > 1) {
+ if (laserTrailFrame) cancelAnimationFrame(laserTrailFrame)
+ renderLaserTrail(now)
+ }
+ remoteTrailFrame = requestAnimationFrame(sampleRemoteTrail)
+ }
+ const clearRemoteLaser = () => {
+ if (remoteTrailFrame) cancelAnimationFrame(remoteTrailFrame)
+ remoteTrailFrame = 0
+ remoteLaserDot.classList.remove('visible')
+ clearLaserTrail()
+ }
+
+ const setRemoteLaser = (p: string | null) => {
+ if (!p || blacked) {
+ clearRemoteLaser()
+ return
+ }
+ // The laser layer only enters the DOM when the laser was armed locally —
+ // on a broadcast copy nobody ever arms it, so mount it on first remote
+ // frame or the dot would be positioned on a detached element.
+ buildLaser()
+ const section = deck.getCurrentSlide() as HTMLElement | null
+ const surface = section?.querySelector<HTMLElement>('.bento-slide')
+ if (!surface) {
+ clearRemoteLaser()
+ return
+ }
+ const rect = surface.getBoundingClientRect()
+ const parts = p.split(',')
+ const fx = parseFloat(parts[0] ?? 'NaN')
+ const fy = parseFloat(parts[1] ?? 'NaN')
+ if (!Number.isFinite(fx) || !Number.isFinite(fy)) {
+ clearRemoteLaser()
+ return
+ }
+ const host = overlay.getBoundingClientRect()
+ const x = rect.left + Math.max(0, Math.min(1, fx)) * rect.width - host.left
+ const y = rect.top + Math.max(0, Math.min(1, fy)) * rect.height - host.top
+ if (remoteLaserDot.classList.contains('visible')) {
+ // Mid-stroke: let the short tween glide the dot to the new frame.
+ remoteLaserDot.style.left = `${x}px`
+ remoteLaserDot.style.top = `${y}px`
+ } else {
+ // A new stroke after a release: the dot is hidden at its OLD spot and the
+ // CSS left/top tween would fly it across the gap — the trail sampler
+ // traces that ghost glide into a line from the last position. Snap it to
+ // the new position first (tween off), then re-enable for the stream.
+ remoteLaserDot.style.transition = 'none'
+ remoteLaserDot.style.left = `${x}px`
+ remoteLaserDot.style.top = `${y}px`
+ void remoteLaserDot.offsetWidth // reflow so the snap lands before re-enabling
+ remoteLaserDot.style.transition = ''
+ remoteLaserDot.classList.add('visible')
+ }
+ if (!remoteTrailFrame) remoteTrailFrame = requestAnimationFrame(sampleRemoteTrail)
+ }
+
const setLaserEnabled = (on: boolean, feedback = true) => {
if (laserEnabled === on) return
if (on) buildLaser()
@@ -411,14 +559,47 @@ export function startPresentation(
const toggleLaser = () => setLaserEnabled(!laserEnabled)
overlay.addEventListener('pointermove', scheduleLaser, true)
+ overlay.addEventListener('pointerdown', (ev: PointerEvent) => {
+ if (!laserEnabled || ev.pointerType === 'touch' || !ev.isPrimary || !deckReady) return
+ const section = deck.getCurrentSlide() as HTMLElement | null
+ const surface = section?.querySelector<HTMLElement>('.bento-slide')
+ if (!surface) return
+ const rect = surface.getBoundingClientRect()
+ if (
+ ev.clientX < rect.left || ev.clientX > rect.right ||
+ ev.clientY < rect.top || ev.clientY > rect.bottom
+ ) return
+ laserDrawing = true
+ laserSentThisStroke = false
+ laserPoint = { x: ev.clientX, y: ev.clientY }
+ if (!laserFrame) laserFrame = requestAnimationFrame(paintLaser)
+ const fx = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width))
+ const fy = Math.max(0, Math.min(1, (ev.clientY - rect.top) / rect.height))
+ sendLaserPoint(`${fx.toFixed(4)},${fy.toFixed(4)}`)
+ lastLaserSend = performance.now()
+ laserSentThisStroke = true
+ }, true)
+ overlay.addEventListener('pointerup', () => {
+ if (!laserDrawing) return
+ laserDrawing = false
+ // resetLaserPointer's own off-send guard needs laserDrawing still true, so
+ // the off frame fires HERE — before the stroke is cleared.
+ if (laserSentThisStroke) sendLaserPoint(null)
+ resetLaserPointer()
+ })
overlay.addEventListener('pointerleave', resetLaserPointer)
const onWindowBlur = () => resetLaserPointer()
window.addEventListener('blur', onWindowBlur)
const setBlack = (on: boolean) => {
blacked = on
- if (on) resetLaserPointer()
+ if (on) {
+ resetLaserPointer()
+ sendLaserPoint(null)
+ setRemoteLaser(null)
+ }
blackout.hidden = !on
+ sendBlackPoint(on)
updateSpeakerControls()
}
const toggleBlack = () => setBlack(!blacked)
@@ -515,9 +696,40 @@ export function startPresentation(
// be opened (from the editor) before that, so gate any deck.getIndices() read
// and re-populate once the deck is ready.
let deckReady = false
+ // Broadcast follow-mode may receive a nav frame before Reveal finishes init;
+ // park it here and apply as soon as the deck is ready.
+ let pendingIndex: number | null = null
// true when we adopted a speaker window the EDITOR opened — we drive it but
// must not close it on exit (it lives beyond this present session).
let speakerAdopted = false
+ // ——— live broadcast ———
+ const bc = opts.broadcast
+ let showOn = false // presenter: live
+ let showLock = false // presenter: the audience is held on my slide
+ let showCount = 0 // presenter: audience sockets, coarse
+ const follow = new FollowState(!!bc?.audience) // audience: follow ⇄ browse, lock
+ let followChip: HTMLButtonElement | null = null
+
+ // Laser frames leave at ≤ 20 fps; the viewer's dot glides between samples
+ // (CSS tween, see setRemoteLaser) so the trail stays smooth. Nav and black
+ // are rare and never throttled. `null` (pen up) always goes (follow.ts).
+ let lastLaserSent = 0
+ const sendLaserPoint = (p: string | null) => {
+ if (!showOn) return
+ const now = performance.now()
+ if (!laserDue(p, now, lastLaserSent)) return
+ lastLaserSent = now
+ bc?.presenter?.verbs()?.laser(p)
+ }
+ const sendBlackPoint = (on: boolean) => {
+ if (!showOn) return
+ bc?.presenter?.verbs()?.black({ on, lock: showLock })
+ }
+ const sendNav = (idx: number) => {
+ if (!showOn) return
+ bc?.presenter?.verbs()?.nav({ id: doc.slides[idx]?.id, i: visibleIndex(idx), lock: showLock })
+ }
+
// Second-screen placement is set up in the EDITOR (properties panel) before
// presenting — that's where the Window Management permission is granted via a
// dedicated gesture, and the layout is cached in ../screens. Here we just read
@@ -569,6 +781,23 @@ export function startPresentation(
nav('laser')?.classList.toggle('active', laserEnabled)
nav('laser')?.setAttribute('aria-pressed', String(laserEnabled))
nav('reduce')?.classList.toggle('active', reduceMotion)
+ const liveBtn = nav('live')
+ if (liveBtn) {
+ liveBtn.classList.toggle('active', showOn)
+ liveBtn.setAttribute('aria-pressed', String(showOn))
+ }
+ const lockBtn = nav('lock')
+ if (lockBtn) {
+ lockBtn.classList.toggle('active', showLock)
+ lockBtn.setAttribute('aria-pressed', String(showLock))
+ lockBtn.toggleAttribute('disabled', !showOn)
+ }
+ const badge = d.querySelector<HTMLElement>('.sv-bcast')
+ if (badge) {
+ badge.hidden = !showOn
+ badge.textContent = showOn ? String(showCount) : ''
+ badge.title = t('N viewers').replace('N', String(showCount))
+ }
}
// A brief centred pill so a keypress (M) gives visible confirmation — the
@@ -583,6 +812,54 @@ export function startPresentation(
toastTimer = window.setTimeout(() => el!.classList.remove('show'), 1400)
}
+ const stopShow = async () => {
+ if (!showOn) return
+ sendLaserPoint(null)
+ sendBlackPoint(false)
+ showOn = false
+ showLock = false
+ showCount = 0
+ updateSpeakerControls()
+ try { await bc?.presenter?.stop() } catch (err) { console.error('[bento-broadcast] end failed', err) }
+ }
+
+ // OFF on every show. Presenting locally must never silently broadcast; the
+ // presenter goes live on purpose, from the speaker view, every time.
+ const toggleShow = async () => {
+ if (!bc?.presenter) return
+ if (showOn) {
+ await stopShow()
+ flashPresentMsg(t('Broadcast ended'))
+ return
+ }
+ if (offlineEnabled()) {
+ flashPresentMsg(t('Broadcast refused in offline mode'))
+ return
+ }
+ try {
+ await bc.presenter.start()
+ showOn = true
+ updateSpeakerControls()
+ sendNav(deck.getIndices().h)
+ if (blacked) sendBlackPoint(true)
+ flashPresentMsg(t('Live — audience copies now follow you'))
+ } catch (err) {
+ console.error('[bento-broadcast] go live failed', err)
+ flashPresentMsg(t('Broadcast failed'))
+ }
+ }
+
+ // Lock is a UX constraint, not a security one — the audience already holds
+ // the whole deck (their copy IS the deck). It disables their follow toggle;
+ // it hides nothing. The button's title says so, in those words.
+ const toggleLock = () => {
+ if (!showOn) return
+ showLock = !showLock
+ updateSpeakerControls()
+ sendNav(deck.getIndices().h) // the lock flag rides on nav
+ flashPresentMsg(showLock ? t('Audience locked to your slide') : t('Audience may browse the deck'))
+ }
+
const setReduceMotion = (on: boolean, persist = true) => {
reduceMotion = on
if (persist) lsSet('bento-reduce-motion', on ? 'on' : 'off')
@@ -674,10 +951,13 @@ export function startPresentation(
navBtn('next', '›', t('Next')) +
navBtn('last', '⇥', t('Last slide')) +
navBtn('black', '■', t('Black screen (B)')) +
- navBtn('laser', '🟒', t('Laser pointer (L)'), true) +
+ navBtn('laser', ICONS.laser, t('Laser pointer (L)'), true) +
navBtn('grid', '▦', t('All slides (G)')) +
navBtn('reduce', '⏸', t('Reduce motion (M)')) +
+ navBtn('live', ICONS.broadcast, t('Go live — audience copies follow your slides')) +
+ navBtn('lock', '🔒', t('Lock keeps the audience on your slide. It does not hide the rest of the deck, which they already have.')) +
`</div>` +
+ `<span class="sv-bcast" hidden title="${t('N viewers')}"></span>` +
`</div>` +
`<div class="sv-main">` +
`<div class="sv-current"></div>` +
@@ -689,6 +969,18 @@ export function startPresentation(
`<div class="sv-rail"></div>` +
`<div class="sv-grid" hidden><div class="sv-grid-inner"></div></div>`
+ const bcastStyle = d.createElement('style')
+ bcastStyle.textContent =
+ // a display property on the rule would override the UA's [hidden]{display:none},
+ // so the [hidden] variant must restate it explicitly
+ `.sv-bcast { display:inline-block; min-width:1.6em; text-align:center; background:rgba(255,255,255,0.15); border-radius:999px; padding:0.15em 0.5em; margin-left:0.5em; font-size:0.85em; line-height:1; }` +
+ `.sv-bcast[hidden] { display:none; }`
+ // the popup head persists across openSpeaker calls — never append a second copy
+ if (!d.head.querySelector('style[data-bento-bcast]')) {
+ bcastStyle.dataset.bentoBcast = '1'
+ d.head.appendChild(bcastStyle)
+ }
+
speakerStart = performance.now()
d.querySelector('.sv-timer')?.addEventListener('click', () => { speakerStart = performance.now() })
clearInterval(speakerTimer)
@@ -743,6 +1035,8 @@ export function startPresentation(
else if (k === 'laser') toggleLaser()
else if (k === 'grid') toggleGrid()
else if (k === 'reduce') toggleReduceMotion()
+ else if (k === 'live') void toggleShow()
+ else if (k === 'lock') toggleLock()
}
d.querySelectorAll<HTMLButtonElement>('.sv-btn[data-nav]').forEach((b) => {
b.addEventListener('click', () => doNav(b.dataset.nav!))
@@ -833,6 +1127,8 @@ export function startPresentation(
const exit = () => {
if (exited) return
exited = true
+ void stopShow() // a broadcast never outlives its show
+ unShow?.()
// measurements are keyed by slide INDEX, so they'd be wrong for the next
// show if the deck was edited in between — never carry them across
symCache.clear()
@@ -904,6 +1200,12 @@ export function startPresentation(
if (!ev.repeat) toggleLaser()
return
}
+ if (ev.key === 'b' || ev.key === 'B') {
+ ev.preventDefault()
+ ev.stopPropagation()
+ toggleBlack()
+ return
+ }
const key = ev.key || ({ 32: ' ', 37: 'ArrowLeft', 39: 'ArrowRight', 33: 'PageUp', 34: 'PageDown' } as Record<number, string>)[ev.keyCode]
if (key === 'ArrowRight' || key === 'PageDown' || key === ' ') {
ev.preventDefault()
@@ -996,6 +1298,7 @@ export function startPresentation(
// symbol-morph on the way out. symbolOffsets normalises by the element's
// own box, so measuring mid-morph is safe.
cacheSlideSymbols(doc, to, toIdx)
+ sendNav(toIdx)
updateSpeaker()
}) as any)
@@ -1011,9 +1314,80 @@ export function startPresentation(
}
})
+ const goTo = (index: number) => {
+ if (deckReady) deck.slide(index, 0)
+ else pendingIndex = index
+ }
+
+ // ——— the audience side: follow the presenter ———
+ // The decisions live in follow.ts (rig-driven); this is the DOM around them.
+ const updateFollowChip = () => {
+ if (!followChip) return
+ const state = follow.label()
+ followChip.classList.toggle('following', follow.following)
+ followChip.toggleAttribute('disabled', follow.locked)
+ followChip.textContent = state === 'locked'
+ ? t('Following the presenter (locked)')
+ : state === 'following' ? t('Following the presenter') : t('Browsing — click to follow')
+ followChip.title = state === 'locked'
+ ? t('The presenter has locked the audience to their slide')
+ : state === 'following' ? t('Click to browse the deck on your own') : t('Click to snap back to the presenter')
+ }
+ const showCard = (text: string, sticky = false) => {
+ let el = overlay.querySelector<HTMLElement>('.bento-show-card')
+ if (!el) { el = document.createElement('div'); el.className = 'bento-show-card'; overlay.appendChild(el) }
+ el.textContent = text
+ el.hidden = false
+ if (!sticky) window.setTimeout(() => { if (el) el.hidden = true }, 4000)
+ }
+ if (bc?.audience) {
+ followChip = document.createElement('button')
+ followChip.className = 'bento-follow-chip'
+ followChip.addEventListener('click', () => {
+ const jump = follow.toggle()
+ updateFollowChip()
+ if (jump !== null) goTo(jump)
+ })
+ overlay.appendChild(followChip)
+ updateFollowChip()
+ showCard(t('Waiting for the presenter…'), true)
+ }
+ let unShow: (() => void) | undefined
+ if (bc) {
+ unShow = bc.onShow((e) => {
+ if (e.t === 'count') { showCount = e.n; updateSpeakerControls(); return }
+ if (e.t === 'checkpoint') return // the session re-sends the audsnap itself
+ if (e.t === 'closed') {
+ if (!bc.audience) return
+ if (e.code === 4001) { follow.applyLock(false); updateFollowChip(); showCard(t('The show has ended — this copy stays a working deck')) }
+ else if (e.code === 4002) showCard(t('Waiting for the presenter…'), true)
+ else if (e.code === 1008) showCard(t('Your audience copy is no longer valid — ask the presenter for a new one'), true)
+ return
+ }
+ if (!bc.audience) return
+ const p = (e.payload ?? {}) as { id?: string; i?: number; on?: boolean; lock?: boolean }
+ if (e.kind === 'nav') {
+ overlay.querySelector<HTMLElement>('.bento-show-card')?.setAttribute('hidden', '')
+ const jump = follow.nav(doc.slides, p)
+ updateFollowChip()
+ if (jump !== null) goTo(jump)
+ } else if (e.kind === 'black') {
+ follow.applyLock(p.lock)
+ updateFollowChip()
+ setBlack(!!p.on)
+ } else if (e.kind === 'laser') {
+ setRemoteLaser(typeof e.payload === 'string' ? e.payload : null)
+ }
+ })
+ }
+
deck.initialize().then(() => {
deckReady = true
if (startIndex > 0) deck.slide(startIndex, 0)
+ if (pendingIndex !== null) {
+ deck.slide(pendingIndex, 0)
+ pendingIndex = null
+ }
// if the speaker view was opened before init (macOS reorder), fill it now
updateSpeaker()
// late layout: fonts/images that finish loading after init can change
@@ -1035,9 +1409,12 @@ export function startPresentation(
mountLiveCharts(doc.slides[startIndex], first)
startMediaIn(first)
}
+ if (opts?.onDocChange) {
+ opts.onDocChange({ slidesEl, deck, buildSection })
+ }
})
- return { exit }
+ return { exit, goTo, setBlack, setRemoteLaser }
}
// --- media playback -----------------------------------------------------------
diff --git a/slides/src/styles.css b/slides/src/styles.css
index b77280e6..2228bc69 100644
--- a/slides/src/styles.css
+++ b/slides/src/styles.css
@@ -864,6 +864,12 @@ a.ed-btn { text-decoration: none; } /* the update block's "What's new" link is
}
.bento-present-overlay.laser-over-slide .bento-slide,
.bento-present-overlay.laser-over-slide .bento-slide * { cursor: none !important; }
+/* While the laser is armed, dragging on the slide must never select text. */
+.bento-present-overlay.laser-enabled .bento-slide,
+.bento-present-overlay.laser-enabled .bento-slide * {
+ user-select: none;
+ -webkit-user-select: none;
+}
.bento-laser-trail {
position: absolute;
inset: 0;
@@ -896,6 +902,17 @@ a.ed-btn { text-decoration: none; } /* the update block's "What's new" link is
transition: opacity 0.08s linear;
}
.bento-laser-dot.visible { opacity: 1; }
+.bento-laser-dot.bento-remote {
+ /* Frames arrive at ~30fps; a short linear tween (longer than one frame
+ interval so it always settles, short enough to add no lag) smooths the
+ last step — Excalidraw steps at 33ms with no tween at all, this is
+ strictly smoother. The LOCAL dot keeps its opacity-only transition: at
+ 60fps a position tween would smear it behind the hand. */
+ transition:
+ left 0.045s linear,
+ top 0.045s linear,
+ opacity 0.08s linear;
+}
.bento-present-overlay.reduce-motion .bento-laser-trail { display: none; }
.bento-present-overlay.reduce-motion .bento-laser-dot { transition: none; }
/* Reduced motion (M / speaker toggle / OS prefers-reduced-motion): JS fx are
@@ -1686,6 +1703,43 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }
}
.bento-present-toast.show { opacity: 1; }
+/* --- live broadcast, audience side ------------------------------------- */
+/* Follow chip: the viewer's toggle (browse ⇄ follow); disabled under lock. */
+.bento-follow-chip {
+ position: absolute;
+ top: 14px;
+ right: 14px;
+ z-index: 61;
+ border: 1px solid rgb(255 255 255 / 0.25);
+ background: rgb(20 30 45 / 0.82);
+ color: #fff;
+ font: 500 13px/1.2 system-ui, sans-serif;
+ padding: 7px 12px;
+ border-radius: 999px;
+ cursor: pointer;
+ opacity: 0.85;
+}
+.bento-follow-chip:hover { opacity: 1; }
+.bento-follow-chip.following { border-color: var(--bento-accent, #f7a600); }
+.bento-follow-chip[disabled] { cursor: default; opacity: 0.7; }
+/* Status card: waiting for the presenter / the show has ended / ticket dead. */
+.bento-show-card {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ z-index: 61;
+ background: rgb(20 30 45 / 0.9);
+ color: #fff;
+ font: 500 16px/1.4 system-ui, sans-serif;
+ padding: 16px 24px;
+ border-radius: 12px;
+ max-width: 70vw;
+ text-align: center;
+ pointer-events: none;
+}
+.bento-show-card[hidden] { display: none; }
+
/* --- live collaboration ----------------------------------------------- */
.ed-avatars {
display: flex;