Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
v1.0.2: presenter view, collab keepalive, line/curve/connector suite, canvas nav, readable defaults, doc properties
nyblnet0e39d5c1d1d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46ff015c..67b3fecd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,47 @@ below opens files from every earlier version, and unknown fields are preserved.This project's versions roughly follow semantic-ish `0.MINOR.PATCH` while it ispre-1.0.+## [1.0.2] — 2026-07-20++- **Live-collab stability**: WebSocket keepalive (client ping + relay auto-pong,+ hibernation-safe) so idle connections stop getting reaped — fixes the+ frequent connect/drop churn. Client also detects a dead socket fast and+ reconnects instead of hanging. (Relay redeployed.)+- **Presenter view** overhaul: the speaker window is now a full presenter+ surface — nav bar (first/prev/next/last + counter), clickable thumbnail rail,+ all-slides grid, black-screen toggle, and keyboard control from the window+ itself. It opens from a launcher button by the present controls (or the Slide+ panel) and persists so present mode adopts it.+- **Window Management permission removed** — no prompt; the speaker window opens+ on the current display and you drag it to a second screen. Fixes the macOS+ "notes land on the wrong monitor" bug by keeping open-notes and go-fullscreen+ as two separate gestures.+- **Canvas slide navigation**: arrow keys and the scroll wheel move between+ slides when nothing is selected (arrows still nudge a selected element).+- **Readable default text**: new text boxes and tables pick a colour that reads+ on the current slide, so they're never invisible on a dark deck.+- **Lines, curves & connectors**: lines and curves now edit with direct endpoint+ / anchor handles (no more box-resize-and-rotate); double-click a curve to add+ or remove points. Draw them by dragging on the canvas. New **connectors** snap+ their ends to elements and re-route automatically when those elements move.+- **Document properties**: `doc.meta` (author/company/subject/event/keywords),+ editable in About, usable as `{{author}}` / `{{company}}` / `{{subject}}` /+ `{{event}}` field tokens in any text.+- **Entrance speed**: per-element `fx.enterDur` ("Enter secs" in the panel).+- Live-collab UI hardening: the presence avatar strip caps at a few + a "+N"+ pill, the Live panel's people list scrolls, and join/leave toasts hush in a+ crowded room — so a busy shared deck can't break the topbar.++## [1.0.1] — 2026-07-20++- Cap the live-collaboration presence UI (topbar avatars, Live panel list,+ join/leave toasts) so a crowded room can't overflow the interface.++## [1.0.0] — 2026-07-20++- First 1.0 release. MIT-licensed; feature-complete slides app (charts, tables,+ media, morph, E2EE collab, i18n) with the signed self-update channel.+## [0.9.20] — 2026-07- Audio: render the native control as-is; add an "insert media from a link"diff --git a/CLAUDE.md b/CLAUDE.mdindex 70ae960a..ca0d98a3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -33,10 +33,15 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.cross-reload-recover, by design.- `src/render.ts` — single model→DOM renderer shared by editor canvas, thumbnails, andReveal sections. Elements carry `data-el-id` (editing) and `data-flip-id` (morph).- **Dynamic fields (v0.9.12)**: text resolves `{{page}}`, `{{pages}}`, `{{title}}`,- `{{date}}`, `{{time}}` tokens at render time (`resolveFields`); page/pages take a- zero-pad width (`{{page:2}}`→"06"). `renderSlide` auto-fills `RenderOpts.fields`- via `fieldContext(doc,slide)` (page = 1-based position among NON-state slides).+ **Dynamic fields (v0.9.12, doc-props v1.0.2)**: text resolves `{{page}}`,+ `{{pages}}`, `{{title}}`, `{{date}}`, `{{time}}` plus the document-property+ tokens `{{author}}`, `{{company}}`, `{{subject}}`, `{{event}}` at render time+ (`resolveFields`); page/pages take a zero-pad width (`{{page:2}}`→"06"). The+ doc-props live in optional `doc.meta` (`{author,company,subject,event,keywords}`+ — additive, backward-compatible; old files lack it and tokens resolve empty)+ and are edited in the About dialog's "Document properties" section (title stays+ top-level). `renderSlide` auto-fills `RenderOpts.fields` via `fieldContext(doc,+ slide)` (page = 1-based position among NON-state slides).The MODEL stores the raw token; only output is resolved, so inserting/removingslides re-numbers everything. Editing gotcha: the canvas renders resolved, but`canvas.startTextEdit` swaps the token BACK to raw `el.html` while editing so@@ -252,25 +257,34 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.- **Hover content is in-slide, not states**: `showOnHover` sets + slide`hover:'reveal'` (with a default set) swap content on pointer-over. Editor previewsone set at a time. Rule of thumb: click → state slide; hover → reveal set.-- **Speaker view**: OUR OWN popup (present.ts openSpeaker, S key) — current +- next slide via renderSlide, notes, elapsed timer (click resets) + clock,- synced on slidechanged, closed on present exit. Reveal's notes plugin is- NOT used: its speaker window reloads the presentation URL in iframes,- which boots the Bento EDITOR (a whole second app instance) — never- reintroduce it. GOTCHA (fixed v0.9.7): opening the speaker popup while in- real fullscreen makes the browser leave fullscreen, whose `fullscreenchange`- would call `exit()` and END the show — `openingSpeaker` guards onFsChange and- re-enters fullscreen. Escape stays a separate exit path, so the guard can't- strand the presenter. **Dual-screen (v0.9.14)**: the Window Management- permission CANNOT be requested during present — the S keypress activation is- spent on window.open/requestFullscreen. So `src/screens.ts` holds the shared- layout and the **editor's Slide panel** ("Presenter display" section) grants- it via a dedicated click BEFORE presenting (`grantScreens`), caching the live- ScreenDetails; the editor also `refreshScreensIfGranted()` at boot. present.ts- `openSpeaker` reads `secondScreen()` synchronously and opens the notes popup- directly on that display's coords; if none is set up it drops fullscreen so- the notes aren't hidden. (The old in-present grant pill was removed.) Needs a- real two-monitor rig for final QA.+- **Speaker view (presenter view)**: OUR OWN popup (present.ts openSpeaker) —+ a PowerPoint-style presenter surface: elapsed timer (click resets) + clock,+ current + next slide (renderSlide/svSlide), notes, a **nav bar** (first/prev/+ next/last + live counter), a **black-screen** toggle (`.bento-blackout` over+ the audience overlay), a clickable **thumbnail rail** (all non-state slides,+ current highlighted + scrolled into view), and a lazy **all-slides grid**+ overlay. The popup has its OWN keydown handler (its keys fire in its own+ document) so the presenter drives the whole show from it: ←/→/space/PageUp-Dn,+ Home/End, B (black), G (grid), Esc (close grid). `updateSpeakerControls()`+ refreshes highlight/counter/button-state cheaply on every slidechange; the+ expensive current/next re-render only in `updateSpeaker`. Reveal's notes plugin+ is NOT used (it reloads the URL in an iframe → boots a whole second editor).+ **Two-window lifecycle (`src/screens.ts`)**: the speaker window OUTLIVES a+ present session. The editor opens it (its own user gesture) via the FAB beside+ the present buttons, or `editor.openSpeakerView()`; present mode ADOPTS the+ existing window (`speakerWindow()`), so "open the notes" and "go fullscreen"+ are two SEPARATE gestures and neither steals the other's activation. That is+ the whole fix for the macOS bug where a popup opened *after* fullscreen got+ trapped in the slides' exclusive fullscreen Space on the wrong monitor — open+ it FIRST, drag it to the second screen, then present (the Slide-panel notes+ hint says this, and warns on macOS via `isMacOS()`). Present closes a window it+ opened itself on exit; an ADOPTED (editor-owned) window is left open and reset+ to an idle placeholder (`speakerIdleBody`). A 1s poll (`watchSpeaker`) clears+ the ref + fires `onSpeakerWindowChange` when the popup is closed manually.+ `deckReady` gates `deck.getIndices()` reads (the window can open pre-init).+ **Window Management API was REMOVED (v1.0.2)** — no more permission prompt; the+ window opens on the current display and the presenter drags it over. `openingSpeaker`+ still guards `onFsChange` against the fullscreen bounce ending the show.- **Animation robustness**: slide exit kills tweens AND restores model frames; a2.8s wall-clock settle guarantee lands entrances on starved render loops; neverput entrance tweens on motion-path elements (transform conflict).@@ -339,9 +353,43 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.duration in Durable Objects free tier", which silently breaks ALL livecollab (the bug behind v0.9.7). The relay must be redeployed(`wrangler deploy`) for worker changes to take effect — the app shell release- does NOT touch it.+ does NOT touch it. **Keepalive (v1.0.2)**: idle WebSockets get reaped by edge/+ proxy idle timeouts, causing frequent connect/drop churn. The DO sets+ `setWebSocketAutoResponse(new WebSocketRequestResponsePair('ping','pong'))` (a+ fallback `data==='ping'` branch in `onMessage` covers older runtimes), and the+ client (`OnlineTransport`) pings every 25s + reconnects fast if a pong is+ missed. The relay change is backward-compatible (old clients never ping), so+ deploy the relay BEFORE shipping a pinging client or the client would falsely+ reconnect-storm against a non-ponging relay.Undo under collab is snapshot-based and may revert concurrent remoteedits to the same properties (documented LWW compromise).+- **Canvas slide nav (v1.0.2)**: with NOTHING selected (and not text/cell/path+ editing), arrow keys walk slides and a plain wheel over `.ed-scroll` walks+ slides (threshold 40px + 400ms cooldown so a trackpad swipe = one slide; skips+ when the slide is zoomed/pannable). When an element IS selected, arrows still+ nudge it. `store.goToLinear(±1)` skips interactive states; PageUp/Dn route+ through it too. Wheel hook is `canvas.onSlideNav`; ⌘/ctrl+wheel still zooms.+- **Readable default text (v1.0.2)**: new text/tables get a colour that reads on+ the CURRENT slide — `readableInk(slide.background)` (luminance test, dark bg →+ light ink `#F5F7FA`, else `#1E2A3A`); `editor.newTable()` also flips a dark+ slide's table borders/zebra light. Fixes invisible-on-dark-deck text.+- **Lines, curves & connectors (v1.0.2)** — `editor/lineedit.ts`. A selected+ line/curve is edited with DIRECT handles (not Moveable's box): `LineEditor`+ attaches from `canvas.syncTargets` when a single line/path shape is selected,+ hides Moveable, and shows draggable ENDPOINT handles (line) or ANCHOR handles+ (curve — double-click the body to add a point, a point to remove); dragging the+ body moves the whole thing. Geometry conversions: line ⇄ two endpoints+ (box centre ± ½w along rotation); path ⇄ anchors (pathBox normalised to+ [0,0,w,h], `d` = Catmull-Rom via patheditor's `anchorsToPath`). The overlay is+ `pointer-events:none` with only handles interactive. **Drawing**: the Shape menu's+ Line/Curved line/Connector ARM a draw tool (`canvas.armDraw`) — drag on the+ canvas to draw (a crosshair overlay captures the gesture), click to drop a+ default. **Connectors** are `line` shapes with `from`/`to: {el, side}` refs+ (model.ts `ConnectorEnd`); a connector's end that lands on an element anchors+ to it, and `editor.syncConnectors()` (on the `doc` event, mirrors+ syncLinkedCharts — derive-not-commit, re-renders) recomputes each anchored+ endpoint on the element's border toward the other end whenever anything moves.+ Dragging an endpoint by hand detaches that end. Dangling refs are dropped.- `src/editor/` — vanilla-TS editor. Moveable + Selecto handle manipulation.Interaction modifiers: Shift = keep-ratio resize / axis-locked drag / 15°rotate snap; Alt/Option = resize from CENTER (deep-select exempts@@ -425,7 +473,7 @@ One HTML file = the document + viewer + editor. See `README.md` for the vision.build:single) deflates runtime JS+CSS into base64 `bento/deflate-b64` scriptblocks + ~1KB loader (DecompressionStream → blob import; pre-2023 browsersget a plain-HTML message). Byte order: chrome → NOTICE → tooling comment →- PLAINTEXT #bento-doc → splash → payloads last. Shell ~373KB (was 1.33MB).+ PLAINTEXT #bento-doc → splash → payloads last. Shell ~478KB (was 1.33MB).SPLICE CONTRACT (old updaters are frozen code): #bento-doc stays plaintext/same id, file survives DOMParser→splice→outerHTML, no stray script-close —release.mjs runs a conformance GATE before signing every release.diff --git a/docs/agents.md b/docs/agents.mdindex c7efa9b2..65b9ef39 100644--- a/docs/agents.md+++ b/docs/agents.md@@ -167,7 +167,12 @@ each kind of content to the feature built for it:`{angle, stops:[{at:0..1, color}]}` (CSS-convention angle). Lines taketheir color from `fill` and draw horizontally across the box (rotate forvertical); `strokeStyle: solid|dashed|dotted`; tips `lineStart`/`lineEnd`- = `arrow|dot|bar`.+ = `arrow|dot|bar`. A `path` is a free vector: `d` (SVG path data) ++ `pathBox` `[x,y,w,h]` authoring viewBox, stretched into the element box;+ for a **curved line** set `fill:"transparent"` + a `stroke` + `strokeWidth`.+ A **connector** is a `line` (or `path`) with `from`/`to: {el, side}` — its ends+ follow those elements and re-route when they move (side `"auto"` picks the+ nearest border). Make sure a shape's colour contrasts with its slide background.- **image**: `src` = data URI or `"asset:<key>"` into `doc.assets`,`fit: cover|contain|fill`, `radius`. Embed images as data URIs in`doc.assets` and reference them — the file must stay self-contained.@@ -225,6 +230,16 @@ each kind of content to the feature built for it:- Fonts: `doc.fonts` (`{family, asset, weight}`) + woff2 data URIs in`doc.assets` if you need embedded faces; otherwise stick to system stacks.+## Dynamic fields (tokens in text `html`)++Put these tokens in any text element's `html`; they resolve at render time (the+model keeps the raw token, so numbering/props update automatically):+`{{page}}`, `{{pages}}` (position among non-state slides; zero-pad with+`{{page:2}}`→"06"), `{{title}}`, `{{date}}`, `{{time}}`, and the document+properties `{{author}}`, `{{company}}`, `{{subject}}`, `{{event}}`. Set the+props in an optional top-level `"meta": {author, company, subject, event,+keywords}` object — great for title slides and footers that fill from one place.+## Gotchas- Escape `<` as `\u003c` anywhere in the JSON when writing the file block.diff --git a/server/sync-worker/src/worker.js b/server/sync-worker/src/worker.jsindex 1cd45865..f762d864 100644--- a/server/sync-worker/src/worker.js+++ b/server/sync-worker/src/worker.js@@ -82,6 +82,13 @@ export class Room {constructor(state) {this.state = statethis.verifyKey = null // imported writer pubkey, cached for this wake+ // Keepalive: auto-reply "pong" to a client "ping" WITHOUT waking the DO, so+ // idle connections aren't reaped by edge/proxy idle timeouts — the usual+ // cause of "connects and drops" on hibernated WebSockets. Costs no active+ // duration; retained across hibernation. Set here so every wake re-applies it.+ try {+ state.setWebSocketAutoResponse(new WebSocketRequestResponsePair('ping', 'pong'))+ } catch { /* older runtime without auto-response — clients still reconnect */ }}/** Valid writer signature over `${i}.${d}` for a signed room? */@@ -181,6 +188,9 @@ export class Room {async onMessage(ws, data) {if (typeof data !== 'string' || data.length > MAX_FRAME) return+ // keepalive fallback: if the runtime auto-response isn't active this reaches+ // us — reply "pong" so a pinging client never mistakes a live socket for dead.+ if (data === 'ping') { try { ws.send('pong') } catch { /* gone */ } return }// rate-limit window lives on the socket attachment (survives hibernation)const meta = ws.deserializeAttachment() || { count: 0, windowStart: Date.now() }const now = Date.now()diff --git a/slides/package.json b/slides/package.jsonindex 47d27a41..5b1d3bba 100644--- a/slides/package.json+++ b/slides/package.json@@ -1,7 +1,7 @@{"name": "bento-slides","private": true,- "version": "1.0.1",+ "version": "1.0.2","license": "MIT","type": "module","scripts": {diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.tsindex 056b82c1..5a5f3888 100644--- a/slides/src/editor/canvas.ts+++ b/slides/src/editor/canvas.ts@@ -8,10 +8,15 @@ import Moveable from 'moveable'import Selecto from 'selecto'import type { Store } from '../store'import { t } from '../i18n'-import { uid, type SlideElement, type TableElement } from '../model'+import { defaultShape, readableInk, uid, type ShapeElement, type SlideElement, type TableElement } from '../model'import { renderSlide, sanitizeHtml } from '../render'import { autoformatAtCaret, clearAutoformat, markdownToHtml, undoAutoformat } from './markdown'import { PathEditor } from './patheditor'+import { LineEditor, isLineLike, setLineEndpoints, setPathAnchors } from './lineedit'+import { simplifyPoints } from './patheditor'++const SVG_NS = 'http://www.w3.org/2000/svg'+type DrawKind = 'line' | 'path' | 'connector' | 'free' | 'poly'import { CommentsUI } from './comments'import type { Peer } from '../sync/session'@@ -31,6 +36,8 @@ export class SlideCanvas {/** when editing a table cell, which cell (else null → text element edit) */private editingCell: { r: number; c: number } | null = nullprivate pathEditor!: PathEditor+ private lineEditor!: LineEditor+ private drawOverlay: HTMLElement | null = nullprivate comments!: CommentsUIconstructor(@@ -49,9 +56,27 @@ export class SlideCanvas {this.buildZoomBar()// pinch / ctrl+wheel zooms like every design toolthis.scroller.addEventListener('wheel', (ev) => {- if (!ev.ctrlKey && !ev.metaKey) return+ if (ev.ctrlKey || ev.metaKey) {+ ev.preventDefault()+ this.setZoom(this.zoom * (ev.deltaY < 0 ? 1.12 : 1 / 1.12))+ return+ }+ // plain wheel → walk slides, but only when the slide can't be panned (it+ // fits, i.e. not zoomed to overflow) and nothing is being edited. A distance+ // threshold + cooldown makes one trackpad swipe advance exactly one slide.+ if (!this.onSlideNav || this.editing || this.editingCell || this.isPathEditing) return+ const s = this.scroller+ if (s.scrollHeight > s.clientHeight + 1 || s.scrollWidth > s.clientWidth + 1) return // pannable → let it scroll+ if (Math.abs(ev.deltaY) < Math.abs(ev.deltaX)) return // horizontal intentev.preventDefault()- this.setZoom(this.zoom * (ev.deltaY < 0 ? 1.12 : 1 / 1.12))+ const now = Date.now()+ if (now < this.wheelNavCooldown) return+ this.wheelNavAccum += ev.deltaY+ if (Math.abs(this.wheelNavAccum) < 40) return+ const dir = this.wheelNavAccum > 0 ? 1 : -1+ this.wheelNavAccum = 0+ this.wheelNavCooldown = now + 400+ this.onSlideNav(dir)}, { passive: false })// Control box lives INSIDE the scaled host with rootContainer at body:@@ -88,8 +113,29 @@ export class SlideCanvas {this.wireMoveable()this.wireSelecto()+ // Pin the scroller during Moveable gestures: snap guidelines can overflow+ // the stage and grow the scroll area, which made the slide jump around+ // mid-drag. Any scroll while a gesture is live is snapped straight back.+ let gestureLock = false+ let lockL = 0+ let lockT = 0+ this.scroller.addEventListener('scroll', () => {+ if (gestureLock) {+ this.scroller.scrollLeft = lockL+ this.scroller.scrollTop = lockT+ }+ })+ const lockScroll = () => { gestureLock = true; lockL = this.scroller.scrollLeft; lockT = this.scroller.scrollTop }+ const unlockScroll = () => { gestureLock = false }+ for (const e of ['dragStart', 'resizeStart', 'rotateStart', 'dragGroupStart', 'resizeGroupStart', 'rotateGroupStart'])+ (this.moveable as unknown as { on: (e: string, f: () => void) => void }).on(e, lockScroll)+ for (const e of ['dragEnd', 'resizeEnd', 'rotateEnd', 'dragGroupEnd', 'resizeGroupEnd', 'rotateGroupEnd'])+ (this.moveable as unknown as { on: (e: string, f: () => void) => void }).on(e, unlockScroll)+this.pathEditor = new PathEditor(this.scaleHost, store, () => this.syncTargets())this.pathEditor.setScaleGetter(() => this.scale)+ this.lineEditor = new LineEditor(this.scaleHost, store)+ this.lineEditor.setScaleGetter(() => this.scale)document.addEventListener('bento:edit-path', ((ev: CustomEvent) => {this.startPathEdit(ev.detail.id)}) as EventListener)@@ -185,6 +231,9 @@ export class SlideCanvas {/** notified when the comment tool arms/disarms (topbar button state) */onCommentModeChange: ((on: boolean) => void) | null = null+ onSlideNav: ((dir: 1 | -1) => void) | null = null+ private wheelNavAccum = 0+ private wheelNavCooldown = 0private commentCleanup: (() => void) | null = nullget isCommentMode() {@@ -489,7 +538,13 @@ export class SlideCanvas {}private syncTargets() {- const targets = this.editing || this.pathEditor?.active ? [] : this.selectedNodes()+ // A single selected line/curve/connector is edited with endpoint handles+ // (LineEditor), not Moveable's box — grab an end and drag it.+ const sel = this.store.selectedElements+ const lineLike = sel.length === 1 && isLineLike(sel[0]) && !this.editing && !this.pathEditor.active+ if (lineLike) this.lineEditor.attach(sel[0].id)+ else this.lineEditor.detach()+ const targets = this.editing || this.pathEditor?.active || lineLike ? [] : this.selectedNodes()// snap against slide bounds/center and every non-selected elementconst others = this.surface? [this.surface, ...Array.from(this.surface.querySelectorAll<HTMLElement>('.bento-el'))].filter(@@ -1002,6 +1057,225 @@ export class SlideCanvas {return !!this.editing}+ get isDrawing() {+ return !!this.drawOverlay+ }++ /** Arm a draw tool: line/curve/connector drag start→end (click = default);+ * 'free' captures the pointer trail; 'poly' click-places vertices — click+ * near the first point (or double-click) to close the shape. Connector ends+ * SNAP to visible anchor points (side midpoints + centre) on the element+ * under the cursor and anchor there (auto-reroute afterwards). Esc cancels. */+ armDraw(kind: DrawKind) {+ this.cancelDraw()+ const { width, height } = this.store.doc.size+ const ov = document.createElement('div')+ ov.style.cssText = `position:absolute;left:0;top:0;width:${width}px;height:${height}px;z-index:60;cursor:crosshair`+ const svg = document.createElementNS(SVG_NS, 'svg')+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`)+ svg.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none'+ const preview = document.createElementNS(SVG_NS, 'path')+ preview.setAttribute('fill', 'none')+ preview.setAttribute('stroke', '#2f6df6')+ const dots = document.createElementNS(SVG_NS, 'g')+ svg.append(preview, dots)+ ov.appendChild(svg)+ this.scaleHost.appendChild(ov)+ this.drawOverlay = ov+ const k = () => 1 / this.scale+ const toSlide = (ev: MouseEvent) => {+ const r = this.scaleHost.getBoundingClientRect()+ return { x: (ev.clientX - r.left) / this.scale, y: (ev.clientY - r.top) / this.scale }+ }+ const setPreview = (d: string) => {+ preview.setAttribute('stroke-width', String(3 * k()))+ preview.setAttribute('stroke-dasharray', `${6 * k()} ${4 * k()}`)+ preview.setAttribute('d', d)+ }+ type Pt = { x: number; y: number }+ type Snap = { el: string; side: 'auto' | 'top' | 'right' | 'bottom' | 'left'; pt: Pt } | null+ const anchorsFor = (id: string) => {+ const e = this.store.slide.elements.find((x) => x.id === id)!+ return [+ { side: 'top' as const, pt: { x: e.x + e.w / 2, y: e.y } },+ { side: 'right' as const, pt: { x: e.x + e.w, y: e.y + e.h / 2 } },+ { side: 'bottom' as const, pt: { x: e.x + e.w / 2, y: e.y + e.h } },+ { side: 'left' as const, pt: { x: e.x, y: e.y + e.h / 2 } },+ { side: 'auto' as const, pt: { x: e.x + e.w / 2, y: e.y + e.h / 2 } },+ ]+ }+ // visible anchor points on the element under the cursor (connector tool)+ const showAnchors = (p: Pt | null) => {+ dots.innerHTML = ''+ if (kind !== 'connector' || !p) return+ const id = this.elementAt(p, 12 * Math.max(k(), 1))+ if (!id) return+ for (const a of anchorsFor(id)) {+ const c = document.createElementNS(SVG_NS, 'circle')+ c.setAttribute('cx', String(a.pt.x))+ c.setAttribute('cy', String(a.pt.y))+ c.setAttribute('r', String(5 * k()))+ c.setAttribute('fill', '#2f6df6')+ c.setAttribute('stroke', '#fff')+ c.setAttribute('stroke-width', String(1.5 * k()))+ dots.appendChild(c)+ }+ }+ const snap = (p: Pt): { a: Snap; pt: Pt } => {+ if (kind !== 'connector') return { a: null, pt: p }+ const id = this.elementAt(p, 12 * Math.max(k(), 1))+ if (!id) return { a: null, pt: p }+ let best: Snap = null+ let bd = 30 * Math.max(k(), 1)+ for (const cand of anchorsFor(id)) {+ const d = Math.hypot(p.x - cand.pt.x, p.y - cand.pt.y)+ if (d < bd) { bd = d; best = { el: id, side: cand.side, pt: cand.pt } }+ }+ return best ? { a: best, pt: best.pt } : { a: { el: id, side: 'auto', pt: p }, pt: p }+ }++ if (kind === 'poly') {+ const verts: Pt[] = []+ const redraw = (cur?: Pt) => {+ if (!verts.length) return setPreview('')+ let d = `M ${verts[0].x} ${verts[0].y}` + verts.slice(1).map((v) => ` L ${v.x} ${v.y}`).join('')+ if (cur) d += ` L ${cur.x} ${cur.y}`+ setPreview(d)+ }+ const finish = () => {+ if (verts.length >= 3) {+ const el = defaultShape('path', { fill: this.store.doc.theme.accent, stroke: 'transparent', strokeWidth: 0 }) as ShapeElement+ setPathAnchors(el, verts, { closed: true, straight: true })+ this.insert(el)+ }+ this.cancelDraw()+ }+ ov.addEventListener('mousedown', (ev: MouseEvent) => {+ ev.preventDefault()+ ev.stopPropagation()+ const p = toSlide(ev)+ if (verts.length >= 3 && Math.hypot(p.x - verts[0].x, p.y - verts[0].y) < 16 * Math.max(k(), 1)) return finish()+ verts.push(p)+ redraw(p)+ })+ ov.addEventListener('mousemove', (ev: MouseEvent) => redraw(toSlide(ev)))+ ov.addEventListener('dblclick', (ev: MouseEvent) => { ev.preventDefault(); finish() })+ return+ }++ if (kind === 'free') {+ ov.addEventListener('mousedown', (down: MouseEvent) => {+ down.preventDefault()+ down.stopPropagation()+ const raw: Pt[] = [toSlide(down)]+ const move = (e: MouseEvent) => {+ raw.push(toSlide(e))+ setPreview('M ' + raw.map((p) => `${p.x} ${p.y}`).join(' L '))+ }+ const up = () => {+ window.removeEventListener('mousemove', move)+ window.removeEventListener('mouseup', up)+ const pts = simplifyPoints(raw, 3)+ if (pts.length >= 2) {+ const el = defaultShape('path', { fill: 'transparent', stroke: readableInk(this.store.slide.background), strokeWidth: 3 }) as ShapeElement+ setPathAnchors(el, pts.length > 2 ? pts : [pts[0], { x: (pts[0].x + pts[1].x) / 2, y: (pts[0].y + pts[1].y) / 2 }, pts[1]])+ this.insert(el)+ }+ this.cancelDraw()+ }+ window.addEventListener('mousemove', move)+ window.addEventListener('mouseup', up)+ })+ return+ }++ // line / curve / connector: drag start → end+ ov.addEventListener('mousemove', (ev: MouseEvent) => {+ if (!(ev.buttons & 1)) showAnchors(toSlide(ev))+ })+ ov.addEventListener('mousedown', (down: MouseEvent) => {+ down.preventDefault()+ down.stopPropagation()+ const s0 = snap(toSlide(down))+ const start = s0.pt+ const move = (e: MouseEvent) => {+ const p = toSlide(e)+ const sn = snap(p)+ showAnchors(p)+ setPreview(kind === 'path' ? this.curveBowD(start, sn.pt) : `M ${start.x} ${start.y} L ${sn.pt.x} ${sn.pt.y}`)+ }+ const up = (e: MouseEvent) => {+ window.removeEventListener('mousemove', move)+ window.removeEventListener('mouseup', up)+ const sn = snap(toSlide(e))+ const short = Math.hypot(sn.pt.x - start.x, sn.pt.y - start.y) < 8+ const end = short ? { x: start.x + 320, y: start.y } : sn.pt+ this.createDrawn(kind, start, end, s0.a ?? undefined, short ? undefined : sn.a ?? undefined)+ this.cancelDraw()+ }+ window.addEventListener('mousemove', move)+ window.addEventListener('mouseup', up)+ })+ }++ cancelDraw() {+ this.drawOverlay?.remove()+ this.drawOverlay = null+ }++ /** SVG path 'd' for a gentle bow between two points (curve preview + default). */+ private curveBowD(a: { x: number; y: number }, b: { x: number; y: number }): string {+ const mx = (a.x + b.x) / 2+ const my = (a.y + b.y) / 2+ const dx = b.x - a.x+ const dy = b.y - a.y+ const len = Math.hypot(dx, dy) || 1+ const off = len * 0.2+ return `M ${a.x} ${a.y} Q ${mx - (dy / len) * off} ${my + (dx / len) * off} ${b.x} ${b.y}`+ }++ /** Topmost non-line element whose box contains pt (for connector anchoring).+ * `pad` forgives near-misses just outside the border. */+ private elementAt(pt: { x: number; y: number }, pad = 0): string | null {+ const els = this.store.slide.elements+ for (let i = els.length - 1; i >= 0; i--) {+ const e = els[i]+ if (e.type === 'shape' && (e.shape === 'line' || e.shape === 'path')) continue+ if (pt.x >= e.x - pad && pt.x <= e.x + e.w + pad && pt.y >= e.y - pad && pt.y <= e.y + e.h + pad) return e.id+ }+ return null+ }++ private createDrawn(+ kind: DrawKind,+ a: { x: number; y: number },+ b: { x: number; y: number },+ fromA?: { el: string; side: 'auto' | 'top' | 'right' | 'bottom' | 'left' },+ toA?: { el: string; side: 'auto' | 'top' | 'right' | 'bottom' | 'left' },+ ) {+ const ink = readableInk(this.store.slide.background)+ if (kind === 'path') {+ const el = defaultShape('path', { fill: 'transparent', stroke: ink, strokeWidth: 3 }) as ShapeElement+ const mx = (a.x + b.x) / 2+ const my = (a.y + b.y) / 2+ const dx = b.x - a.x+ const dy = b.y - a.y+ const len = Math.hypot(dx, dy) || 1+ const off = len * 0.2+ setPathAnchors(el, [a, { x: mx - (dy / len) * off, y: my + (dx / len) * off }, b])+ this.insert(el)+ return+ }+ const el = defaultShape('line', { h: 4, strokeWidth: 3, fill: ink }) as ShapeElement+ setLineEndpoints(el, a, b)+ if (kind === 'connector') {+ el.lineEnd = 'arrow'+ if (fromA) el.from = { el: fromA.el, side: fromA.side }+ if (toA) el.to = { el: toA.el, side: toA.side }+ }+ this.insert(el)+ }+/** Insert an element, select it, and (for text) drop straight into editing. */insert(el: SlideElement, startEditing = false) {// inserting while previewing a non-default hover set joins that set —diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex 916abc86..9da24105 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -8,7 +8,7 @@ import {FORMAT_VERSION,MEDIA_EMBED_BUDGET,applyChartPalette, applyLayout, builtinLayouts, defaultChart, defaultImage, defaultMedia, defaultShape, defaultTable, defaultText,- instantiateLayout, layoutElementIds, newDocId, syncLinkedChart, uid,+ instantiateLayout, isLightBg, layoutElementIds, newDocId, readableInk, syncLinkedChart, uid,type ChartElement, type ShapeKind, type Slide, type SlideElement, type TableElement,} from '../model'import { APP_VERSION, applyUpdate, applyUpdateInPlace, autoCheckEnabled, canUpdateInPlace, checkForUpdates, offlineEnabled, setAutoCheck, setOffline } from '../update'@@ -20,19 +20,24 @@ import { startPresentation } from '../present'import { hasFileHandle, isEncryptionActive, saveFile, serializeAuto, serializeFile, setEncryptionPassword, writeUpdatedFile, writeUpdatedFileAs } from '../save'import { addVersion, clearRecovery, clearVersions, docContentKey, getRecovery, listVersions, pruneOld, putRecovery, type Snapshot } from '../autosave'import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from './clipboard'-import { refreshScreensIfGranted } from '../screens'+import { openSpeakerWindow, speakerIdleBody } from '../screens'+import { borderPoint, boxCenter, lineEndpoints, setLineEndpoints, sideMidpoint } from './lineedit'import { ICONS } from '../icons'import { t, setLocale, locale, LOCALE_CHOICES } from '../i18n'import { disconnectOnline, joinFromDoc, mintCollab, onlineTransport, rotateKeys, sharingOn, startSharing, stopSharing } from '../sync/online'const i18nT = t-const SHAPE_MENU: Array<{ kind: ShapeKind; label: string; icon: string }> = [+const SHAPE_MENU: Array<{ kind: ShapeKind; label: string; icon: string; draw?: 'line' | 'path' | 'connector' | 'free' | 'poly' }> = [{ kind: 'rect', label: 'Rectangle', icon: ICONS.rect },{ kind: 'ellipse', label: 'Ellipse', icon: ICONS.ellipse },{ kind: 'triangle', label: 'Triangle', icon: ICONS.triangle },{ kind: 'arrow', label: 'Arrow', icon: ICONS.arrow },- { kind: 'line', label: 'Line', icon: ICONS.line },+ { kind: 'line', label: 'Line', icon: ICONS.line, draw: 'line' },+ { kind: 'path', label: 'Curved line', icon: ICONS.curve, draw: 'path' },+ { kind: 'line', label: 'Connector', icon: ICONS.connector, draw: 'connector' },+ { kind: 'path', label: 'Freeform', icon: ICONS.freeform, draw: 'free' },+ { kind: 'path', label: 'Polygon', icon: ICONS.polygon, draw: 'poly' },]export class Editor {@@ -70,8 +75,8 @@ export class Editor {})this.wireAutosave()this.wirePaste()- void refreshScreensIfGranted() // re-enable 2nd-screen notes if granted earlierstore.on('doc', () => this.syncLinkedCharts())+ store.on('doc', () => this.syncConnectors())document.addEventListener('bento:apply-layout', ((ev: CustomEvent) => {this.openLayoutPicker(ev.detail.anchor as HTMLElement, { kind: 'apply' })}) as EventListener)@@ -214,13 +219,13 @@ export class Editor {const insert = div('ed-group ed-insert')insert.append(- btn(ICONS.text, t('Text'), () => this.canvas.insert(defaultText({ y: 120 + Math.random() * 200 }), true),+ btn(ICONS.text, t('Text'), () => this.canvas.insert(defaultText({ color: readableInk(this.store.slide.background), y: 120 + Math.random() * 200 }), true),t('Add a text box — double-click it to edit; **bold**, *italic*, `code` and “- ” bullets format as you type')),this.shapeDropdown(),btn(ICONS.image, t('Image'), () => this.pickImage(),t('Add an image — or just paste one (⌘V) straight onto the slide')),this.mediaDropdown(),- btn(ICONS.table, t('Table'), () => this.canvas.insert(defaultTable()),+ btn(ICONS.table, t('Table'), () => this.canvas.insert(this.newTable()),t('Add a table — edit cells inline; turn it into a live chart from the panel')),btn(ICONS.chart, t('Chart'), () => this.canvas.insert(defaultChart(applyChartPalette(CHART_PRESETS.bar(), this.store.doc.theme))),t('Add a chart — edit it visually or link it to a table so it updates live')),@@ -282,7 +287,12 @@ export class Editor {tabFab.innerHTML = ICONS.windowtabFab.title = t('Present in this tab — handy for testing or sharing a window')tabFab.addEventListener('click', () => this.present(false, false))- fabs.append(fsFab, tabFab)+ const spkFab = document.createElement('button')+ spkFab.className = 'ed-fab ed-fab-small'+ spkFab.innerHTML = ICONS.presenter+ spkFab.title = t('Open the speaker view — notes, controls and thumbnails in a separate window (drag it to a second screen)')+ spkFab.addEventListener('click', () => this.openSpeakerView())+ fabs.append(fsFab, tabFab, spkFab)canvasWrap.appendChild(fabs)this.props = div('ed-props')main.append(this.sidebar, this.makeResizer('left'), canvasWrap, this.makeResizer('right'), this.props)@@ -299,6 +309,7 @@ export class Editor {this.restorePanelWidths()this.canvas = new SlideCanvas(canvasWrap, this.store)this.canvas.onCommentModeChange = (on) => commentB.classList.toggle('ed-btn-armed', on)+ this.canvas.onSlideNav = (dir) => this.store.goToLinear(dir)this.panel = new PropsPanel(this.props, this.store)if (this.store.doc.collab?.role === 'reader') this.enterReaderMode()@@ -725,8 +736,10 @@ export class Editor {for (const item of SHAPE_MENU) {const b = btn(item.icon, t(item.label), () => {wrap.classList.remove('open')- const partial = item.kind === 'line' ? { h: 4, w: 400, strokeWidth: 3 } : {}- this.canvas.insert(defaultShape(item.kind, partial))+ // line / curve / connector arm a draw tool — drag on the canvas to draw+ // (or click to drop a default); other shapes insert straight away.+ if (item.draw) { this.canvas.armDraw(item.draw); return }+ this.canvas.insert(defaultShape(item.kind))})menu.appendChild(b)}@@ -1138,8 +1151,31 @@ export class Editor {probe.src = src}+ /** A fresh table styled to read on the CURRENT slide — on a dark background the+ * default dark body text / hairline borders would be invisible, so flip them+ * light (the header keeps its own dark-bg + white text, which reads on both). */+ private newTable(): TableElement {+ const tbl = defaultTable()+ if (!isLightBg(this.store.slide.background)) {+ tbl.style.color = readableInk(this.store.slide.background)+ tbl.style.zebra = 'rgba(255,255,255,0.06)'+ tbl.style.borderColor = 'rgba(255,255,255,0.16)'+ }+ return tbl+ }+// --- present & save ------------------------------------------------------------------+ /** Open the speaker view now (a launcher twin of the Slide-panel button) so it+ * can be placed on a second screen before presenting — present mode adopts it. */+ openSpeakerView() {+ const w = openSpeakerWindow(+ `${this.store.doc.title} — ${t('Speaker view')}`,+ speakerIdleBody(this.store.doc.title, t('Notes, controls and slide thumbnails appear here when you start presenting. Drag this window to your second display.')),+ )+ if (!w) this.toast(t('Couldn’t open the speaker view — allow pop-ups for this site.'))+ }+present(fromStart = false, fullscreen = true) {if (this.presenting) returnthis.canvas.commitTextEdit()@@ -1192,7 +1228,7 @@ export class Editor {ev.preventDefault()const esc = text.trim().slice(0, 4000).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')const { width } = this.store.doc.size- const el = defaultText({ html: esc, x: Math.round(width / 2 - 300), y: 260, w: 600 })+ const el = defaultText({ html: esc, color: readableInk(this.store.slide.background), x: Math.round(width / 2 - 300), y: 260, w: 600 })this.store.commit(() => this.store.slide.elements.push(el))this.store.select([el.id])this.toast(t('Text pasted'))@@ -1246,6 +1282,36 @@ export class Editor {if (changed) this.canvas.render()}+ /** Re-route connectors (line shapes anchored to elements via from/to) when+ * anything on the slide moves. Derived, not committed — every replica computes+ * the same endpoints from the element boxes (mirrors syncLinkedCharts). */+ private syncConnectors() {+ const slide = this.store.slide+ const byId = new Map(slide.elements.map((e) => [e.id, e]))+ let changed = false+ for (const el of slide.elements) {+ if (el.type !== 'shape' || el.shape !== 'line') continue+ const c = el as import('../model').ShapeElement+ if (!c.from && !c.to) continue+ if (c.from && !byId.has(c.from.el)) { delete c.from; changed = true }+ if (c.to && !byId.has(c.to.el)) { delete c.to; changed = true }+ if (!c.from && !c.to) continue+ const [a, b] = lineEndpoints(c)+ const fromBox = c.from ? byId.get(c.from.el) : null+ const toBox = c.to ? byId.get(c.to.el) : null+ // explicit side → pin to that side's midpoint; 'auto' → nearest border+ const end = (box: SlideElement, side: 'auto' | 'top' | 'right' | 'bottom' | 'left' | undefined, toward: { x: number; y: number }) =>+ side && side !== 'auto' ? sideMidpoint(box, side) : borderPoint(box, toward)+ const na = fromBox ? end(fromBox, c.from?.side, toBox ? boxCenter(toBox) : b) : a+ const nb = toBox ? end(toBox, c.to?.side, fromBox ? boxCenter(fromBox) : a) : b+ if (Math.hypot(na.x - a.x, na.y - a.y) > 0.5 || Math.hypot(nb.x - b.x, nb.y - b.y) > 0.5) {+ setLineEndpoints(c, na, nb)+ changed = true+ }+ }+ if (changed) this.canvas.render()+ }+// --- auto-save + crash recovery -----------------------------------------------private autosaveTimer = 0@@ -1555,6 +1621,14 @@ export class Editor {}return}+ // nothing selected → arrows walk slides (Left/Up = prev, Right/Down = next);+ // when an element IS selected they nudge it (branch below). inField already+ // returned above, so this never fires mid text/cell edit.+ if (ev.key.startsWith('Arrow') && !this.store.selection.length && !this.canvas.isPathEditing) {+ ev.preventDefault()+ this.store.goToLinear(ev.key === 'ArrowLeft' || ev.key === 'ArrowUp' ? -1 : 1)+ return+ }if (ev.key.startsWith('Arrow') && this.store.selection.length) {ev.preventDefault()const step = ev.shiftKey ? 10 : 1@@ -1577,18 +1651,19 @@ export class Editor {return}if (ev.key === 'Escape') {- if (this.canvas.isPathEditing) this.canvas.stopPathEdit(true)+ if (this.canvas.isDrawing) this.canvas.cancelDraw()+ else if (this.canvas.isPathEditing) this.canvas.stopPathEdit(true)else this.store.select([])return}if (ev.key === 'PageDown') {ev.preventDefault()- this.store.goTo(this.store.currentIndex + 1)+ this.store.goToLinear(1)return}if (ev.key === 'PageUp') {ev.preventDefault()- this.store.goTo(this.store.currentIndex - 1)+ this.store.goToLinear(-1)}})}@@ -1767,6 +1842,36 @@ export class Editor {langRow.append(document.createTextNode(t('Language') + ' '), langSel)box.appendChild(langRow)+ // Document properties → fillable {{author}} {{company}} {{subject}} {{event}} fields+ const metaWrap = div('ed-about-row ed-about-meta-wrap')+ const metaTitle = document.createElement('div')+ metaTitle.className = 'ed-about-h'+ metaTitle.textContent = t('Document properties')+ metaWrap.appendChild(metaTitle)+ const metaHint = document.createElement('p')+ metaHint.className = 'ed-hint'+ metaHint.innerHTML = t('Type <b>{{author}}</b>, <b>{{company}}</b>, <b>{{subject}}</b> or <b>{{event}}</b> in any text box and it fills in from here — everywhere at once. Handy for title slides and footers.')+ metaWrap.appendChild(metaHint)+ const ensureMeta = () => (this.store.doc.meta ??= {})+ const metaField = (label: string, get: () => string, set: (v: string) => void) => {+ const row = div('ed-about-meta')+ const l = document.createElement('label')+ l.textContent = label+ const inp = document.createElement('input')+ inp.type = 'text'+ inp.value = get()+ inp.addEventListener('change', () => this.store.commit(() => set(inp.value.trim())))+ row.append(l, inp)+ metaWrap.appendChild(row)+ }+ metaField(t('Title'), () => this.store.doc.title, (v) => { this.store.doc.title = v || 'Untitled' })+ metaField(t('Author'), () => this.store.doc.meta?.author ?? '', (v) => { ensureMeta().author = v })+ metaField(t('Company'), () => this.store.doc.meta?.company ?? '', (v) => { ensureMeta().company = v })+ metaField(t('Subject'), () => this.store.doc.meta?.subject ?? '', (v) => { ensureMeta().subject = v })+ metaField(t('Event'), () => this.store.doc.meta?.event ?? '', (v) => { ensureMeta().event = v })+ metaField(t('Keywords'), () => this.store.doc.meta?.keywords ?? '', (v) => { ensureMeta().keywords = v })+ box.appendChild(metaWrap)+// AI round-trip: the document is the interchange unitconst aiRow = div('ed-about-row')const copyB = document.createElement('button')diff --git a/slides/src/editor/lineedit.ts b/slides/src/editor/lineedit.tsnew file mode 100644index 00000000..492bc771--- /dev/null+++ b/slides/src/editor/lineedit.ts@@ -0,0 +1,321 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento/Suite authors+// Direct on-canvas editing for line / curved-line / connector SHAPES — the+// intuitive alternative to resizing a box and rotating it. A selected line+// shows two draggable endpoint handles; a curve (path) shows its anchor points+// (double-click to add on the curve, double-click a point to remove); dragging+// the body moves the whole thing. Connectors (endpoints anchored to elements)+// are edited the same way but re-route automatically — see editor.syncConnectors.+//+// Model-driven: handles are positioned from the element's geometry (not its DOM+// node), so a re-render underneath us doesn't matter. Geometry conversions:+// • line ⇄ two endpoints (box centre ± half-width along rotation)+// • path ⇄ anchor points (pathBox normalised to [0,0,w,h], d = smoothed)++import type { Store } from '../store'+import type { ShapeElement } from '../model'+import { anchorsToPath, parseAnchors, samplePathAnchors } from './patheditor'++const rnd = (v: number) => Math.round(v * 100) / 100+/** Closed shapes (polygons) end with Z; straight ones have no curve commands. */+export const pathIsClosed = (d?: string) => /z\s*$/i.test(d ?? '')+export const pathIsStraight = (d?: string) => !/[csqta]/i.test(d ?? '')++const SVG_NS = 'http://www.w3.org/2000/svg'+type Pt = { x: number; y: number }++/** True for shapes this editor takes over (instead of Moveable's box). */+export function isLineLike(el: { type: string; shape?: string }): boolean {+ return el.type === 'shape' && (el.shape === 'line' || el.shape === 'path')+}++/** The two endpoints of a line shape, in slide coords. */+export function lineEndpoints(el: ShapeElement): [Pt, Pt] {+ const cx = el.x + el.w / 2+ const cy = el.y + el.h / 2+ const rad = ((el.rotation || 0) * Math.PI) / 180+ const hw = el.w / 2+ const dx = Math.cos(rad) * hw+ const dy = Math.sin(rad) * hw+ return [{ x: cx - dx, y: cy - dy }, { x: cx + dx, y: cy + dy }]+}++/** Write a line shape from two endpoints (keeps its stroke-box thickness). */+export function setLineEndpoints(el: ShapeElement, a: Pt, b: Pt): void {+ const cx = (a.x + b.x) / 2+ const cy = (a.y + b.y) / 2+ const w = Math.max(Math.hypot(b.x - a.x, b.y - a.y), 1)+ const h = el.h || 4+ el.w = w+ el.x = cx - w / 2+ el.y = cy - h / 2+ el.rotation = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI+}++type Box = { x: number; y: number; w: number; h: number }+export function boxCenter(b: Box): Pt {+ return { x: b.x + b.w / 2, y: b.y + b.h / 2 }+}+/** Where the ray from box b's centre toward `target` crosses b's border. */+export function borderPoint(b: Box, target: Pt): Pt {+ const cx = b.x + b.w / 2+ const cy = b.y + b.h / 2+ const dx = target.x - cx+ const dy = target.y - cy+ if (!dx && !dy) return { x: cx, y: cy }+ const sx = dx ? b.w / 2 / Math.abs(dx) : Infinity+ const sy = dy ? b.h / 2 / Math.abs(dy) : Infinity+ const s = Math.min(sx, sy)+ return { x: cx + dx * s, y: cy + dy * s }+}++/** Midpoint of one side of a box (connector anchor points). */+export function sideMidpoint(b: Box, side: 'top' | 'right' | 'bottom' | 'left'): Pt {+ if (side === 'top') return { x: b.x + b.w / 2, y: b.y }+ if (side === 'bottom') return { x: b.x + b.w / 2, y: b.y + b.h }+ if (side === 'left') return { x: b.x, y: b.y + b.h / 2 }+ return { x: b.x + b.w, y: b.y + b.h / 2 }+}++/** Anchor points of a path shape, in slide coords. Straight paths (polylines/+ * polygons) parse exactly; curves are sampled+reduced. */+export function pathAnchors(el: ShapeElement): Pt[] {+ const [px, py, pw, ph] = el.pathBox ?? [0, 0, el.w || 1, el.h || 1]+ const sx = el.w / (pw || 1)+ const sy = el.h / (ph || 1)+ const src = pathIsStraight(el.d) ? parseAnchors(el.d ?? '') : samplePathAnchors(el.d ?? '')+ return src.map((p) => ({ x: el.x + (p.x - px) * sx, y: el.y + (p.y - py) * sy }))+}++/** Write a path shape from anchor points (slide coords); normalises pathBox.+ * `straight` keeps segments as lines (polygons); `closed` appends Z. */+export function setPathAnchors(el: ShapeElement, pts: Pt[], opts: { closed?: boolean; straight?: boolean } = {}): void {+ if (pts.length < 2) return+ const xs = pts.map((p) => p.x)+ const ys = pts.map((p) => p.y)+ const minX = Math.min(...xs)+ const minY = Math.min(...ys)+ const w = Math.max(Math.max(...xs) - minX, 1)+ const h = Math.max(Math.max(...ys) - minY, 1)+ el.x = minX+ el.y = minY+ el.w = w+ el.h = h+ el.pathBox = [0, 0, w, h]+ const rel = pts.map((p) => ({ x: rnd(p.x - minX), y: rnd(p.y - minY) }))+ el.d = (opts.straight+ ? 'M ' + rel.map((p) => `${p.x} ${p.y}`).join(' L ')+ : anchorsToPath(rel)) + (opts.closed ? ' Z' : '')+}++export class LineEditor {+ private overlay: SVGSVGElement | null = null+ private elId = ''+ private kind: 'line' | 'path' = 'line'+ private closed = false+ private straight = false+ private pts: Pt[] = []+ private scale = () => 1++ constructor(+ private scaleHost: HTMLElement,+ private store: Store,+ ) {}++ get active() {+ return !!this.overlay+ }+ get elementId() {+ return this.elId+ }++ setScaleGetter(fn: () => number) {+ this.scale = fn+ }++ /** Show handles for a line/path shape (idempotent — re-reads geometry). */+ attach(elId: string) {+ const el = this.store.element(elId) as ShapeElement | undefined+ if (!el || !isLineLike(el)) return this.detach()+ this.elId = elId+ this.kind = el.shape === 'path' ? 'path' : 'line'+ this.closed = this.kind === 'path' && pathIsClosed(el.d)+ this.straight = this.kind === 'path' && pathIsStraight(el.d)+ this.pts = this.kind === 'line' ? lineEndpoints(el) : pathAnchors(el)+ if (!this.overlay) {+ const svg = document.createElementNS(SVG_NS, 'svg')+ svg.classList.add('ed-lineedit')+ const { width, height } = this.store.doc.size+ svg.setAttribute('viewBox', `0 0 ${width} ${height}`)+ svg.style.cssText = `position:absolute;left:0;top:0;width:${width}px;height:${height}px;overflow:visible;z-index:49;pointer-events:none`+ svg.addEventListener('dblclick', (ev) => this.onDblClick(ev))+ this.scaleHost.appendChild(svg)+ this.overlay = svg+ }+ this.draw()+ }++ detach() {+ this.overlay?.remove()+ this.overlay = null+ this.elId = ''+ }++ // --- rendering -------------------------------------------------------------++ private draw() {+ const svg = this.overlay+ if (!svg) return+ svg.innerHTML = ''+ const k = 1 / this.scale()+ const mk = (tag: string) => document.createElementNS(SVG_NS, tag)+ const d = this.kind === 'line'+ ? `M ${this.pts[0].x} ${this.pts[0].y} L ${this.pts[1].x} ${this.pts[1].y}`+ : (this.straight+ ? 'M ' + this.pts.map((p) => `${p.x} ${p.y}`).join(' L ')+ : anchorsToPath(this.pts)) + (this.closed ? ' Z' : '')++ // fat invisible hit-line to drag the whole shape (and, for curves, to insert)+ const hit = mk('path')+ hit.setAttribute('d', d)+ hit.setAttribute('fill', 'none')+ hit.setAttribute('stroke', 'transparent')+ hit.setAttribute('stroke-width', String(16 * k))+ hit.classList.add('ed-le-body')+ hit.style.cursor = 'move'+ hit.style.pointerEvents = 'stroke'+ hit.addEventListener('mousedown', (ev) => this.dragBody(ev))+ svg.appendChild(hit)++ // thin guide line so the geometry is visible while editing+ const guide = mk('path')+ guide.setAttribute('d', d)+ guide.setAttribute('fill', 'none')+ guide.setAttribute('stroke', '#5b8def')+ guide.setAttribute('stroke-width', String(1.5 * k))+ guide.style.pointerEvents = 'none'+ svg.appendChild(guide)++ this.pts.forEach((p, i) => {+ const dot = mk('circle')+ dot.setAttribute('cx', String(p.x))+ dot.setAttribute('cy', String(p.y))+ dot.setAttribute('r', String(6.5 * k))+ dot.setAttribute('fill', '#fff')+ dot.setAttribute('stroke', '#2f6df6')+ dot.setAttribute('stroke-width', String(2 * k))+ dot.classList.add('ed-le-anchor')+ dot.dataset.idx = String(i)+ dot.style.cursor = 'grab'+ dot.style.pointerEvents = 'all'+ dot.addEventListener('mousedown', (ev) => this.dragAnchor(ev, i))+ svg.appendChild(dot)+ })+ }++ // --- interaction -----------------------------------------------------------++ private toSlide(ev: MouseEvent): Pt {+ const rect = this.scaleHost.getBoundingClientRect()+ const s = this.scale()+ return { x: (ev.clientX - rect.left) / s, y: (ev.clientY - rect.top) / s }+ }++ private elNode(): HTMLElement | null {+ return this.scaleHost.querySelector<HTMLElement>(`[data-el-id="${CSS.escape(this.elId)}"]`)+ }++ private dragAnchor(down: MouseEvent, idx: number) {+ down.stopPropagation()+ down.preventDefault()+ const start = this.toSlide(down)+ const orig = { ...this.pts[idx] }+ const node = this.elNode()+ if (node) node.style.opacity = '0.4'+ let moved = false+ const move = (ev: MouseEvent) => {+ const p = this.toSlide(ev)+ moved = true+ this.pts[idx] = { x: orig.x + (p.x - start.x), y: orig.y + (p.y - start.y) }+ this.draw()+ }+ const up = () => {+ window.removeEventListener('mousemove', move)+ window.removeEventListener('mouseup', up)+ if (node) node.style.opacity = ''+ if (moved) this.commit(idx)+ }+ window.addEventListener('mousemove', move)+ window.addEventListener('mouseup', up)+ }++ private dragBody(down: MouseEvent) {+ down.stopPropagation()+ down.preventDefault()+ const start = this.toSlide(down)+ const orig = this.pts.map((p) => ({ ...p }))+ const node = this.elNode()+ if (node) node.style.opacity = '0.4'+ let moved = false+ const move = (ev: MouseEvent) => {+ const p = this.toSlide(ev)+ const dx = p.x - start.x+ const dy = p.y - start.y+ moved = true+ this.pts = orig.map((o) => ({ x: o.x + dx, y: o.y + dy }))+ this.draw()+ }+ const up = () => {+ window.removeEventListener('mousemove', move)+ window.removeEventListener('mouseup', up)+ if (node) node.style.opacity = ''+ if (moved) this.commit(null)+ }+ window.addEventListener('mousemove', move)+ window.addEventListener('mouseup', up)+ }++ private onDblClick(ev: MouseEvent) {+ if (this.kind !== 'path') return+ ev.preventDefault()+ ev.stopPropagation()+ const target = ev.target as Element+ const p = this.toSlide(ev)+ if (target.classList.contains('ed-le-anchor')) {+ const idx = Number((target as SVGElement).dataset.idx)+ if (this.pts.length > 2) {+ this.pts.splice(idx, 1)+ this.commit(null)+ }+ return+ }+ // insert into the nearest segment midpoint+ let best = 0+ let bestDist = Infinity+ for (let i = 0; i < this.pts.length - 1; i++) {+ const mx = (this.pts[i].x + this.pts[i + 1].x) / 2+ const my = (this.pts[i].y + this.pts[i + 1].y) / 2+ const dd = Math.hypot(p.x - mx, p.y - my)+ if (dd < bestDist) { bestDist = dd; best = i }+ }+ this.pts.splice(best + 1, 0, p)+ this.commit(null)+ }++ /** Push the edited geometry into the model (one undo step); a connector whose+ * dragged END lands on nothing loses that anchor (it becomes free). */+ private commit(draggedIdx: number | null) {+ const id = this.elId+ const pts = this.pts.map((p) => ({ ...p }))+ const kind = this.kind+ this.store.commit(() => {+ const el = this.store.element(id) as ShapeElement | undefined+ if (!el) return+ if (kind === 'line') setLineEndpoints(el, pts[0], pts[1])+ else setPathAnchors(el, pts, { closed: this.closed, straight: this.straight })+ // moving an endpoint by hand detaches that end of a connector+ if (draggedIdx === 0) delete el.from+ if (draggedIdx !== null && draggedIdx === pts.length - 1) delete el.to+ })+ }+}diff --git a/slides/src/editor/panels.ts b/slides/src/editor/panels.tsindex de6971a8..faefc22f 100644--- a/slides/src/editor/panels.ts+++ b/slides/src/editor/panels.ts@@ -6,7 +6,7 @@import type { Store } from '../store'import { MEDIA_EMBED_BUDGET, applyChartPalette, defaultChart, uid, type ChartElement, type LineEnding, type MediaElement, type ShapeElement, type Slide, type SlideElement, type TableElement, type TextElement, type TransitionKind } from '../model'-import { grantScreens, screensCached, secondScreen, windowManagementSupported } from '../screens'+import { isMacOS } from '../screens'import { CHART_PRESETS } from '../charts'import { FONT_CHOICES, firstFamily, injectFonts } from '../fonts'import { ICONS } from '../icons'@@ -129,43 +129,6 @@ export class PropsPanel {'A4 portrait': { w: 794, h: 1123 },}- /**- * Presenter display: grant Window Management here (a dedicated click) so a- * live show can put speaker notes on a second screen. It CANNOT be requested- * during present — the S keypress activation is spent on window.open /- * fullscreen — so this is where it belongs: in the panel, before you present.- * Rendered inline under the "Speaker notes" section (same concern), no header- * of its own.- */- private buildPresenterDisplay() {- if (!windowManagementSupported()) return- const btn = document.createElement('button')- btn.className = 'ed-btn ed-btn-block'- const status = document.createElement('p')- status.className = 'ed-hint'- const set = (label: string, msg: string, done: boolean) => {- btn.textContent = label- btn.disabled = done- btn.classList.toggle('ed-btn-primary', !done)- status.textContent = msg- }- const ready = () => set(t('✓ Second screen enabled'), t('Speaker notes will open on your second display when you press S.'), true)- const oneScreen = () => set(t('Use a second screen for notes'), t('Only one display detected — connect another, then enable it here.'), false)- if (screensCached()) { secondScreen() ? ready() : oneScreen() } else {- set(t('Use a second screen for notes'), t('Enable this once so pressing S in a show sends notes to your other display.'), false)- }- btn.addEventListener('click', async () => {- const prev = btn.textContent- btn.textContent = t('Requesting…')- const r = await grantScreens()- if (r.ok && r.screens > 1) ready()- else if (r.ok) oneScreen()- else { set(prev ?? t('Use a second screen for notes'), t('Couldn’t access displays — allow “window management” in the browser’s site permissions.'), false) }- })- const wrap = document.createElement('div')- wrap.append(btn, status)- this.host.appendChild(wrap)- }private buildSlidePanel() {const slide = this.store.slide@@ -315,10 +278,10 @@ export class PropsPanel {this.host.appendChild(notes)const notesHint = document.createElement('p')notesHint.className = 'ed-hint'- notesHint.innerHTML = t('Press <b>S</b> while presenting to open the speaker view — these notes beside the current and next slide, with a timer.')+ notesHint.innerHTML =+ t('Open the <b>speaker view</b> — the button below the slide, or <b>S</b> while presenting — for a separate window with these notes, the current and next slide, a timer, a thumbnail rail to jump anywhere, and a black-screen key. Move it to a second screen and present as usual.') ++ (isMacOS() ? ' ' + t('On macOS, open it BEFORE you go fullscreen — otherwise it lands on the slides’ screen.') : '')this.host.appendChild(notesHint)- // second-screen grant lives here too — notes go to the other display when set- this.buildPresenterDisplay()}private buildMultiPanel(els: SlideElement[]) {diff --git a/slides/src/editor/patheditor.ts b/slides/src/editor/patheditor.tsindex d728cc41..0319dcdc 100644--- a/slides/src/editor/patheditor.ts+++ b/slides/src/editor/patheditor.ts@@ -98,6 +98,11 @@ export function samplePathAnchors(d: string): Pt[] {}}+/** Reduce a raw pointer trail to editable anchors (freeform drawing). */+export function simplifyPoints(pts: Pt[], eps = 3): Pt[] {+ return rdp(pts, eps)+}+function rdp(pts: Pt[], eps: number): Pt[] {if (pts.length <= 2) return pts.slice()const a = pts[0]diff --git a/slides/src/icons.ts b/slides/src/icons.tsindex 9d853e2f..da8a2a01 100644--- a/slides/src/icons.ts+++ b/slides/src/icons.ts@@ -27,6 +27,11 @@ export const ICONS = {pdf: svg('<polyline points="6 9 6 3 18 3 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/>'),sync: svg('<path d="M21 12a9 9 0 1 1-2.64-6.36"/><polyline points="21 3 21 9 15 9"/>'),window: svg('<rect x="3" y="5" width="18" height="14" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/>'),+ presenter: svg('<rect x="3" y="4" width="18" height="14" rx="2"/><line x1="14" y1="4" x2="14" y2="18"/><line x1="16.5" y1="8" x2="18.5" y2="8"/><line x1="16.5" y1="11" x2="18.5" y2="11"/><line x1="16.5" y1="14" x2="18" y2="14"/><line x1="9" y1="21" x2="15" y2="21"/>'),+ curve: svg('<path d="M3 18 C 7 6, 17 6, 21 18"/>'),+ connector: svg('<circle cx="5" cy="19" r="2.4"/><circle cx="19" cy="5" r="2.4"/><path d="M7 17 L 17 7"/>'),+ freeform: svg('<path d="M3 17 C 6 7, 9 21, 12 12 S 18 4, 21 9"/>'),+ polygon: svg('<polygon points="12 3 21 10 17 20 7 20 3 10"/>'),share: svg('<circle cx="9" cy="8" r="3.2"/><path d="M3.5 20c.6-3.2 2.8-5 5.5-5s4.9 1.8 5.5 5"/><circle cx="17.5" cy="10.5" r="2.4"/><path d="M15.8 15.6c1.9.3 3.6 1.6 4.4 3.9"/>'),table: svg('<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="14.5" x2="21" y2="14.5"/><line x1="9" y1="4" x2="9" y2="20"/><line x1="15" y1="4" x2="15" y2="20"/>'),// shape menu entriesdiff --git a/slides/src/model.ts b/slides/src/model.tsindex acf93c27..daeb0c82 100644--- a/slides/src/model.ts+++ b/slides/src/model.ts@@ -149,6 +149,21 @@ export interface ShapeElement extends ElementBase {d?: string/** path only: [x, y, w, h] viewBox the path was authored in */pathBox?: [number, number, number, number]+ /**+ * Connector anchoring (line/path only): the start (`from`) and/or end (`to`)+ * of the shape follow another element. The geometry is DERIVED — the editor's+ * syncConnectors() recomputes the endpoint on that element's border toward the+ * other end whenever anything moves. A dangling ref (element deleted) is+ * dropped and the endpoint becomes free.+ */+ from?: ConnectorEnd+ to?: ConnectorEnd+}++/** One anchored end of a connector. `side:'auto'` picks the nearest border. */+export interface ConnectorEnd {+ el: string+ side?: 'auto' | 'top' | 'right' | 'bottom' | 'left'}export interface ImageElement extends ElementBase {@@ -318,6 +333,19 @@ export interface BentoDoc {*/docId: stringtitle: string+ /**+ * Optional document properties for template fields ({{author}}, {{company}},+ * {{subject}}, {{event}}) and general provenance. All optional → old files+ * simply lack it and every token resolves to empty. `title` stays top-level+ * (load-bearing) and remains the source of {{title}}.+ */+ meta?: {+ author?: string+ company?: string+ subject?: string+ event?: string+ keywords?: string+ }/** slide coordinate space, px */size: { width: number; height: number }theme: {@@ -405,6 +433,23 @@ export const uid = (prefix = 'el') =>export const FONT_STACK ="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"+/** True when a background reads as light (so it wants dark text on top). Accepts+ * a #rrggbb hex; for a gradient/CSS string it samples the first hex it finds and+ * falls back to "light" (the safe assumption for the model's dark default ink). */+export function isLightBg(bg: string): boolean {+ const hex = /#([0-9a-fA-F]{6})/.exec(bg || '')+ if (!hex) return true+ const n = parseInt(hex[1], 16)+ const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 > 0.55 // sRGB relative luminance+}++/** A text colour that stays legible on the given background — new text/tables use+ * this so a fresh element is never invisible on a dark deck. */+export function readableInk(bg: string): string {+ return isLightBg(bg) ? '#1E2A3A' : '#F5F7FA'+}+export function defaultText(partial: Partial<TextElement> = {}): TextElement {return {id: uid('t'),diff --git a/slides/src/present.ts b/slides/src/present.tsindex c4ae1bf8..9b1274f0 100644--- a/slides/src/present.ts+++ b/slides/src/present.ts@@ -10,7 +10,7 @@ import { anim, resetXform } from './anim'import { chartSnapshotSvg, mountChart } from './charts'import type { BentoDoc, GradientFill, ShapeElement, Slide, SlideElement } from './model'import { applyElementFrame, gradientLineCoords, renderSlide } from './render'-import { secondScreen } from './screens'+import { paintSpeaker, setSpeakerWindow, speakerIdleBody, speakerWindow } from './screens'import { t } from './i18n'const MORPH_DURATION = 0.65@@ -98,6 +98,24 @@ export function startPresentation(}const visibleIndex = (i: number) => doc.slides.slice(0, i + 1).filter((s) => !s.stateOf).lengthconst visibleTotal = doc.slides.filter((s) => !s.stateOf).length+ // real slide indices that appear in linear navigation (states are excluded) —+ // the presenter-view thumbnail rail and grid iterate this.+ const railIndices = doc.slides.map((_, i) => i).filter((i) => !isState(i))+ const goFirst = () => deck.slide(railIndices[0] ?? 0, 0)+ const goLast = () => deck.slide(railIndices[railIndices.length - 1] ?? 0, 0)++ // ——— black-screen (audience blackout; presenter keeps notes) ———+ let blacked = false+ const blackout = document.createElement('div')+ blackout.className = 'bento-blackout'+ blackout.hidden = true+ overlay.appendChild(blackout)+ const setBlack = (on: boolean) => {+ blacked = on+ blackout.hidden = !on+ updateSpeakerControls()+ }+ const toggleBlack = () => setBlack(!blacked)let exited = falseconst deck = new Reveal(revealEl, {@@ -140,6 +158,13 @@ export function startPresentation(// browsers; this guards the fullscreenchange handler so that bounce doesn't// end the show (see onFsChange).let openingSpeaker = false+ // Reveal reports valid indices only after initialize(). The speaker view can+ // be opened (from the editor) before that, so gate any deck.getIndices() read+ // and re-populate once the deck is ready.+ let deckReady = false+ // 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// 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@@ -167,8 +192,31 @@ export function startPresentation(}return frame}+ // Cheap, one-shot update of just the controls (highlight, counter, button+ // states) — called on every slidechange AND on black toggle without re-rendering+ // the (expensive) current/next slides or the thumbnail rail.+ const updateSpeakerControls = () => {+ if (!speaker || speaker.closed || !deckReady) return+ const d = speaker.document+ const cur = deck.getIndices().h+ const anchor = isState(cur) ? anchorOf(cur) : cur+ const count = d.querySelector('.sv-count')+ if (count) count.textContent = `${visibleIndex(cur)} / ${visibleTotal}`+ d.querySelectorAll<HTMLElement>('.sv-thumb').forEach((th) => {+ const on = Number(th.dataset.idx) === anchor+ th.classList.toggle('current', on)+ if (on && th.closest('.sv-rail')) th.scrollIntoView({ block: 'nearest', inline: 'center' })+ })+ const nav = (k: string) => d.querySelector<HTMLButtonElement>(`.sv-btn[data-nav="${k}"]`)+ nav('prev')?.toggleAttribute('disabled', !hasPrev())+ nav('first')?.toggleAttribute('disabled', !hasPrev())+ nav('next')?.toggleAttribute('disabled', !hasNext())+ nav('last')?.toggleAttribute('disabled', !hasNext())+ nav('black')?.classList.toggle('active', blacked)+ }const updateSpeaker = () => {if (!speaker || speaker.closed) return+ if (!deckReady) return // opened pre-init — populated on readyconst d = speaker.documentconst cur = deck.getIndices().hconst nxt = nextVisibleIndex(cur)@@ -181,8 +229,7 @@ export function startPresentation(nxtBox.appendChild(d.importNode(svSlide(nxt, 300), true))const notes = d.querySelector('.sv-notes')if (notes) notes.textContent = doc.slides[cur]?.notes || t('— no notes for this slide —')- const count = d.querySelector('.sv-count')- if (count) count.textContent = `${visibleIndex(cur)} / ${visibleTotal}`+ updateSpeakerControls()}const openSpeaker = () => {if (speaker && !speaker.closed) {@@ -193,58 +240,127 @@ export function startPresentation(// browser leave fullscreen, and without this that would end the showconst wasFullscreen = document.fullscreenElement === overlayopeningSpeaker = true- // Open DIRECTLY on the second display when we know its coordinates — the- // reliable path. (Opening centred then moveTo left the window behind the- // fullscreen slides on macOS.)- const other = secondScreen()- const features = other- ? `left=${other.availLeft},top=${other.availTop},width=${Math.min(other.availWidth, 1600)},height=${Math.min(other.availHeight, 1000)}`- : 'width=1080,height=640'- speaker = window.open('', 'bento-speaker', features)+ // ADOPT a window the editor already opened (the clean two-gesture path:+ // opened in its own gesture, never fought fullscreen for this click's+ // activation, never trapped in the fullscreen Space). Only open a fresh one —+ // on THIS display — when none was pre-opened (e.g. S pressed mid-show).+ const pre = speakerWindow()+ if (pre) {+ speaker = pre+ speakerAdopted = true+ } else {+ speaker = window.open('', 'bento-speaker', 'width=1200,height=800')+ speakerAdopted = false+ }if (!speaker) { openingSpeaker = false; console.warn('[bento-speaker] popup blocked — allow pop-ups for this site'); return }- console.info('[bento-speaker] opened on', other ? `2nd screen "${other.label}"` : 'this screen', '·', features)+ setSpeakerWindow(speaker);(window as unknown as Record<string, unknown>).__bentoSpeaker = speaker // diagnosticsconst d = speaker.documentd.title = `${doc.title} — ${t('Speaker view')}`- for (const st of document.querySelectorAll('style')) d.head.appendChild(d.importNode(st, true))+ if (!d.head.querySelector('style')) { // already styled when adopting an editor window+ for (const st of document.querySelectorAll('style')) d.head.appendChild(d.importNode(st, true))+ }d.body.className = 'bento-speaker'+ const navBtn = (k: string, glyph: string, label: string) =>+ `<button class="sv-btn" data-nav="${k}" title="${label}" aria-label="${label}">${glyph}</button>`d.body.innerHTML =- `<div class="sv-top"><div class="sv-timer" title="${t('Click to reset')}">00:00</div>` +- '<div class="sv-clock"></div><div class="sv-count"></div></div>' +- '<div class="sv-main"><div class="sv-current"></div>' +- `<div class="sv-side"><div><div class="sv-label">${t('Next')}</div><div class="sv-nextbox"></div></div>` +- `<div class="sv-notes-wrap"><div class="sv-label">${t('Notes')}</div><div class="sv-notes"></div></div></div></div>`+ `<div class="sv-top">` ++ `<div class="sv-timer" title="${t('Click to reset')}">00:00</div>` ++ `<div class="sv-clock"></div>` ++ `<div class="sv-count"></div>` ++ `<div class="sv-ctrls">` ++ navBtn('first', '⇤', t('First slide')) ++ navBtn('prev', '‹', t('Previous')) ++ navBtn('next', '›', t('Next')) ++ navBtn('last', '⇥', t('Last slide')) ++ navBtn('black', '■', t('Black screen (B)')) ++ navBtn('grid', '▦', t('All slides (G)')) ++ `</div>` ++ `</div>` ++ `<div class="sv-main">` ++ `<div class="sv-current"></div>` ++ `<div class="sv-side">` ++ `<div class="sv-next-wrap"><div class="sv-label">${t('Next')}</div><div class="sv-nextbox"></div></div>` ++ `<div class="sv-notes-wrap"><div class="sv-label">${t('Notes')}</div><div class="sv-notes"></div></div>` ++ `</div>` ++ `</div>` ++ `<div class="sv-rail"></div>` ++ `<div class="sv-grid" hidden><div class="sv-grid-inner"></div></div>`+speakerStart = performance.now()d.querySelector('.sv-timer')?.addEventListener('click', () => { speakerStart = performance.now() })clearInterval(speakerTimer)speakerTimer = window.setInterval(() => {- if (!speaker || speaker.closed) {- clearInterval(speakerTimer)- return- }+ if (!speaker || speaker.closed) { clearInterval(speakerTimer); return }const el = speaker.document.querySelector('.sv-timer')if (el) {- const t = Math.floor((performance.now() - speakerStart) / 1000)- const mm = String(Math.floor(t / 60)).padStart(2, '0')- const ss = String(t % 60).padStart(2, '0')- el.textContent = `${mm}:${ss}`+ const s = Math.floor((performance.now() - speakerStart) / 1000)+ el.textContent = `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`}const clock = speaker.document.querySelector('.sv-clock')if (clock) clock.textContent = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}, 1000)++ // a clickable thumbnail: an imported slide render inside a button, badged+ // with its slide number; clicking jumps the live show there.+ const thumb = (idx: number, w: number): HTMLElement => {+ const b = d.createElement('button')+ b.className = 'sv-thumb'+ b.dataset.idx = String(idx)+ b.appendChild(d.importNode(svSlide(idx, w), true))+ const num = d.createElement('span')+ num.className = 'sv-thumb-n'+ num.textContent = String(visibleIndex(idx))+ b.appendChild(num)+ b.addEventListener('click', () => { deck.slide(idx, 0); toggleGrid(false) })+ return b+ }++ const rail = d.querySelector('.sv-rail')!+ for (const idx of railIndices) rail.appendChild(thumb(idx, 150))++ // all-slides grid overlay — built lazily on first open (cheap for small decks,+ // but a big deck shouldn't pay for it unless the presenter asks).+ const grid = d.querySelector('.sv-grid') as HTMLElement+ const gridInner = d.querySelector('.sv-grid-inner')!+ let gridBuilt = false+ const toggleGrid = (on?: boolean) => {+ const show = on ?? grid.hasAttribute('hidden')+ if (show && !gridBuilt) { for (const idx of railIndices) gridInner.appendChild(thumb(idx, 240)); gridBuilt = true }+ grid.toggleAttribute('hidden', !show)+ if (show) updateSpeakerControls()+ }+ grid.addEventListener('click', (ev) => { if (ev.target === grid) toggleGrid(false) })++ const doNav = (k: string) => {+ if (k === 'first') goFirst()+ else if (k === 'prev') goPrev()+ else if (k === 'next') goNext()+ else if (k === 'last') goLast()+ else if (k === 'black') toggleBlack()+ else if (k === 'grid') toggleGrid()+ }+ d.querySelectorAll<HTMLButtonElement>('.sv-btn[data-nav]').forEach((b) => {+ b.addEventListener('click', () => doNav(b.dataset.nav!))+ })++ // drive the show FROM the speaker window (its keys fire in its own document)+ d.addEventListener('keydown', (ev: KeyboardEvent) => {+ const k = ev.key+ if (k === 'ArrowRight' || k === 'PageDown' || k === ' ' || k === 'n') { ev.preventDefault(); goNext() }+ else if (k === 'ArrowLeft' || k === 'PageUp' || k === 'p') { ev.preventDefault(); goPrev() }+ else if (k === 'Home') { ev.preventDefault(); goFirst() }+ else if (k === 'End') { ev.preventDefault(); goLast() }+ else if (k === 'b' || k === 'B') { ev.preventDefault(); toggleBlack() }+ else if (k === 'g' || k === 'G') { ev.preventDefault(); toggleGrid() }+ else if (k === 'Escape' && !grid.hasAttribute('hidden')) { ev.preventDefault(); toggleGrid(false) }+ })+updateSpeaker()- if (other) {- // Notes are on the second display. A popup on ANOTHER screen shouldn't- // drop this screen's fullscreen; if it did, the presenter can press F- // (the S activation is already spent on window.open, so we can't silently- // re-enter here). Nothing to do — the good path.- console.info('[bento-speaker] notes on 2nd screen; slides', document.fullscreenElement ? 'still fullscreen' : '→ press F for fullscreen')- } else if (wasFullscreen) {- // No second display set up — the notes would sit hidden behind the- // fullscreen slides, so drop fullscreen to reveal them. (To send notes to- // a second screen automatically, enable it in the editor's Slide panel- // before presenting.)- console.info('[bento-speaker] no 2nd screen — revealing notes in a window')+ if (!speakerAdopted && wasFullscreen) {+ // A fresh window on THIS display sits behind the fullscreen slides — drop+ // fullscreen so the notes are visible. (Open notes from the Slide panel and+ // drag them to a second screen to keep the slides fullscreen.)document.exitFullscreen?.().catch(() => {})}window.setTimeout(() => { openingSpeaker = false }, 500)@@ -271,6 +387,10 @@ export function startPresentation(}document.addEventListener('fullscreenchange', onFsChange)if (opts.fullscreen !== false) enterFullscreen()+ // If the editor already opened notes on the second screen, go live on that+ // existing window now — no new window.open, so fullscreen above kept this+ // click's activation and the notes were never trapped in the fullscreen Space.+ if (speakerWindow()) openSpeaker()const exit = () => {if (exited) return@@ -288,7 +408,17 @@ export function startPresentation(document.removeEventListener('keydown', onKeydown, true)document.removeEventListener('fullscreenchange', onFsChange)clearInterval(speakerTimer)- if (speaker && !speaker.closed) speaker.close()+ if (speaker && !speaker.closed) {+ if (speakerAdopted) {+ // editor-owned window — leave it open, reset to the idle placeholder so+ // it's ready for the next run instead of freezing on the last slide+ paintSpeaker(speaker, `${doc.title} — ${t('Speaker view')}`,+ speakerIdleBody(doc.title, t('Presentation ended. Start it again to bring these notes back to life.')))+ } else {+ speaker.close()+ setSpeakerWindow(null)+ }+ }onExit(last)}@@ -406,7 +536,10 @@ export function startPresentation(})deck.initialize().then(() => {+ deckReady = trueif (startIndex > 0) deck.slide(startIndex, 0)+ // 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// the measured size, and the boot viewport may still be settlingwindow.addEventListener('resize', onResize)diff --git a/slides/src/render.ts b/slides/src/render.tsindex 884de0ad..027beae6 100644--- a/slides/src/render.ts+++ b/slides/src/render.ts@@ -21,17 +21,25 @@ export interface RenderOpts {}/** Values dynamic field tokens resolve against, computed per slide. */-export interface FieldContext { page: number; pages: number; title: string; date: Date }+export interface FieldContext {+ page: number; pages: number; title: string; date: Date+ author: string; company: string; subject: string; event: string+}/** Field context for a slide: page = 1-based position among non-state slides. */export function fieldContext(doc: BentoDoc, slide: Slide): FieldContext {const idx = doc.slides.indexOf(slide)const upto = idx < 0 ? doc.slides : doc.slides.slice(0, idx + 1)+ const m = doc.meta ?? {}return {page: upto.filter((s) => !s.stateOf).length,pages: doc.slides.filter((s) => !s.stateOf).length,title: doc.title,date: new Date(),+ author: m.author ?? '',+ company: m.company ?? '',+ subject: m.subject ?? '',+ event: m.event ?? '',}}@@ -39,21 +47,26 @@ const escapeFieldText = (s: string) => s.replace(/&/g, '&').replace(/</g, '&/*** Resolve dynamic field tokens in text: {{page}}, {{pages}}, {{title}},- * {{date}}, {{time}}. page/pages take an optional zero-pad width — {{page:2}}+ * {{date}}, {{time}}, plus the document-property fields {{author}}, {{company}},+ * {{subject}}, {{event}}. page/pages take an optional zero-pad width — {{page:2}}* → "06". The MODEL stores the raw token; only rendered output is resolved, so- * inserting/removing slides re-numbers everything automatically. Groundwork for- * the wider office suite (fields/cross-references).+ * inserting/removing slides re-numbers everything and editing doc properties+ * updates every slide automatically. Groundwork for the wider office suite.*/export function resolveFields(html: string, ctx?: FieldContext): string {if (!ctx || html.indexOf('{{') < 0) return htmlconst pad = (n: number, arg?: string) => { const w = parseInt(arg ?? '', 10); return w > 0 ? String(n).padStart(w, '0') : String(n) }- return html.replace(/\{\{\s*(page|pages|title|date|time)(?::([^}]*))?\s*\}\}/gi, (_m, name: string, arg?: string) => {+ return html.replace(/\{\{\s*(page|pages|title|date|time|author|company|subject|event)(?::([^}]*))?\s*\}\}/gi, (_m, name: string, arg?: string) => {switch (name.toLowerCase()) {case 'page': return pad(ctx.page, arg)case 'pages': return pad(ctx.pages, arg)case 'title': return escapeFieldText(ctx.title)case 'date': return escapeFieldText(ctx.date.toLocaleDateString())case 'time': return escapeFieldText(ctx.date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }))+ case 'author': return escapeFieldText(ctx.author)+ case 'company': return escapeFieldText(ctx.company)+ case 'subject': return escapeFieldText(ctx.subject)+ case 'event': return escapeFieldText(ctx.event)default: return ''}})diff --git a/slides/src/screens.ts b/slides/src/screens.tsindex 545b4b3c..fcf65e3d 100644--- a/slides/src/screens.ts+++ b/slides/src/screens.ts@@ -1,51 +1,95 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento/Suite authors-// Shared Window Management state.-//-// Granting the browser's "window management" permission needs a DEDICATED user-// gesture — it can't ride the S keypress during present (that activation is-// already spent on window.open / requestFullscreen). So the editor grants it-// from the properties panel BEFORE presenting, we cache the LIVE ScreenDetails-// object here, and present mode reads the second-screen coordinates-// synchronously when the speaker view opens.--let cached: { screens: any[]; currentScreen: any } | null = null--export function windowManagementSupported(): boolean {- return typeof (window as unknown as { getScreenDetails?: unknown }).getScreenDetails === 'function'-}--export function screensCached(): boolean {- return !!cached-}--/** Call INSIDE a user gesture. Prompts once if needed, then caches the live- * details object (it auto-updates as displays change). */-export async function grantScreens(): Promise<{ ok: boolean; screens: number }> {- const gsd = (window as unknown as { getScreenDetails?: () => Promise<any> }).getScreenDetails- if (!gsd) return { ok: false, screens: 0 }- try {- cached = await gsd.call(window)- return { ok: true, screens: cached?.screens?.length ?? 1 }- } catch {- return { ok: false, screens: 0 }+// The speaker-notes window. It outlives any single present session: the editor+// opens it (its own user gesture) BEFORE presenting, and present mode adopts it.+// Opening the notes and going fullscreen are then two separate gestures, so+// neither steals the other's activation (the macOS second-screen fix). The+// window opens on the current display; the presenter drags it to a second+// screen — we deliberately do NOT request the "window management" permission.++/** macOS is the platform whose exclusive fullscreen Space traps a popup opened+ * after the slides go fullscreen — so notes must be opened first there. */+export function isMacOS(): boolean {+ const uaData = (navigator as unknown as { userAgentData?: { platform?: string } }).userAgentData+ if (uaData?.platform) return uaData.platform === 'macOS'+ return /Mac/i.test(navigator.platform || navigator.userAgent || '')+}++// --- speaker-notes window (shared editor↔present) ---------------------------++let speakerWin: Window | null = null+let speakerWatch = 0+let onSpeakerChange: (() => void) | null = null++/** Notified whenever the speaker window opens or closes — including when the+ * user closes the popup manually — so the editor panel can refresh its button. */+export function onSpeakerWindowChange(cb: (() => void) | null): void {+ onSpeakerChange = cb+}++// Poll for an externally-closed popup (there is no reliable cross-window close+// event); clear our reference and notify so the UI doesn't go stale.+function watchSpeaker(): void {+ clearInterval(speakerWatch)+ if (!speakerWin) return+ speakerWatch = window.setInterval(() => {+ if (!speakerWin || speakerWin.closed) {+ speakerWin = null+ clearInterval(speakerWatch)+ onSpeakerChange?.()+ }+ }, 1000)+}++/** The live speaker-notes window, or null if none is open. */+export function speakerWindow(): Window | null {+ return speakerWin && !speakerWin.closed ? speakerWin : null+}++/** Register (or clear) the speaker window — present mode uses this when it opens+ * its own, so the editor panel reflects the state and later opens don't dup. */+export function setSpeakerWindow(w: Window | null): void {+ speakerWin = w+ watchSpeaker()+}++/** Copy the app's <style>s and set the body of a speaker window. */+export function paintSpeaker(w: Window, title: string, bodyHtml: string): void {+ const d = w.document+ d.title = title+ if (!d.head.querySelector('style')) {+ for (const st of document.querySelectorAll('style')) d.head.appendChild(d.importNode(st, true))}+ d.body.className = 'bento-speaker'+ d.body.innerHTML = bodyHtml+}++/** A generous default popup size for the current display. */+function speakerFeatures(): string {+ const w = Math.min(1200, Math.max(800, Math.round((screen.availWidth || 1440) * 0.72)))+ const h = Math.min(820, Math.max(560, Math.round((screen.availHeight || 900) * 0.78)))+ return `width=${w},height=${h}`}-/** At load: if the permission is already granted from a prior session, cache- * the layout without a prompt so present mode Just Works. */-export async function refreshScreensIfGranted(): Promise<void> {- if (cached || !windowManagementSupported()) return- try {- const state = (await (navigator as unknown as { permissions?: { query?: (o: unknown) => Promise<{ state: string }> } })- .permissions?.query?.({ name: 'window-management' as PermissionName }))?.state- if (state === 'granted') await grantScreens()- } catch { /* query unsupported — the panel button remains the path */ }+/** Open (or focus) the speaker-notes window on the current display and paint it.+ * MUST be called inside a user gesture (window.open). The presenter drags it to+ * a second screen. Returns null if the popup was blocked. */+export function openSpeakerWindow(title: string, bodyHtml: string): Window | null {+ if (speakerWin && !speakerWin.closed) {+ speakerWin.focus()+ paintSpeaker(speakerWin, title, bodyHtml)+ return speakerWin+ }+ const w = window.open('', 'bento-speaker', speakerFeatures())+ if (!w) return null+ paintSpeaker(w, title, bodyHtml)+ speakerWin = w+ watchSpeaker()+ return w}-/** The display to put speaker notes on, or null if there isn't a usable second one. */-export function secondScreen(): any | null {- const s = cached- if (!s || !Array.isArray(s.screens) || s.screens.length < 2) return null- return s.screens.find((x) => x !== s.currentScreen) ?? s.screens.find((x) => !x.isPrimary) ?? s.screens[1]+/** The idle placeholder shown before a presentation drives the window. */+export function speakerIdleBody(title: string, message: string): string {+ const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] as string)+ return `<div class="sv-idle"><div class="sv-idle-title">${esc(title)}</div><p class="sv-idle-msg">${esc(message)}</p></div>`}diff --git a/slides/src/store.ts b/slides/src/store.tsindex f46c1b57..4fe537e7 100644--- a/slides/src/store.ts+++ b/slides/src/store.ts@@ -135,6 +135,15 @@ export class Store {this.emit('selection')}+ /** Step forward/back one slide, skipping interactive states (stateOf) the way+ * linear presentation does. dir = +1 next, -1 prev. */+ goToLinear(dir: 1 | -1) {+ const slides = this.doc.slides+ for (let i = this.currentIndex + dir; i >= 0 && i < slides.length; i += dir) {+ if (!slides[i].stateOf) { this.goTo(i); return }+ }+ }+select(ids: string[]) {this.selection = idsthis.emit('selection')diff --git a/slides/src/styles.css b/slides/src/styles.cssindex 7465c33b..2487b91c 100644--- a/slides/src/styles.css+++ b/slides/src/styles.css@@ -1167,7 +1167,26 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }color: #e9edf3;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;user-select: none;+ display: flex;+ flex-direction: column;+ height: 100vh;+ overflow: hidden;+}+/* idle placeholder shown before/after a presentation drives the notes window */+.sv-idle {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 14px;+ text-align: center;+ padding: 8vw;+ box-sizing: border-box;}+.sv-idle-title { font-size: 28px; font-weight: 700; color: #e9edf3; }+.sv-idle-msg { max-width: 30ch; margin: 0; font-size: 16px; line-height: 1.6; color: #9fb0c3; }.sv-top { display: flex; align-items: baseline; gap: 22px; padding: 14px 22px 10px; }.sv-timer {font: 700 30px/1 ui-monospace, SFMono-Regular, Menlo, monospace;@@ -1176,8 +1195,26 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }}.sv-timer:hover { color: #f7a600; }.sv-clock { font-size: 15px; color: #9fb0c3; }-.sv-count { margin-left: auto; font-size: 15px; color: #9fb0c3; }-.sv-main { display: flex; gap: 22px; padding: 0 22px 22px; align-items: flex-start; }+.sv-count { font-size: 15px; color: #9fb0c3; font-variant-numeric: tabular-nums; }+.sv-ctrls { margin-left: auto; display: flex; align-items: center; gap: 6px; }+.sv-btn {+ width: 34px;+ height: 30px;+ border-radius: 7px;+ border: 1px solid #2b333f;+ background: #1e242c;+ color: #cdd6e2;+ font-size: 15px;+ line-height: 1;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ justify-content: center;+}+.sv-btn:hover:not([disabled]) { background: #2a323c; color: #fff; }+.sv-btn[disabled] { opacity: 0.35; cursor: default; }+.sv-btn.active { background: #f7a600; border-color: #f7a600; color: #14181d; }+.sv-main { display: flex; gap: 22px; padding: 14px 22px; align-items: flex-start; flex: 1; min-height: 0; }.sv-frame {position: relative;overflow: hidden;@@ -1212,9 +1249,76 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }line-height: 1.65;color: #e9edf3;user-select: text;- max-height: 320px;}+/* --- presenter view: thumbnail rail + all-slides grid ----------------- */+.sv-rail {+ flex: none;+ display: flex;+ gap: 10px;+ padding: 12px 22px;+ overflow-x: auto;+ overflow-y: hidden;+ border-top: 1px solid #232a33;+ background: #10141a;+}+.sv-thumb {+ position: relative;+ flex: none;+ padding: 0;+ border: 2px solid transparent;+ border-radius: 8px;+ background: #000;+ cursor: pointer;+ line-height: 0;+ overflow: hidden;+}+.sv-thumb:hover { border-color: #4a5a72; }+.sv-thumb.current { border-color: #f7a600; }+.sv-thumb .sv-frame { box-shadow: none; border-radius: 0; }+.sv-thumb-n {+ position: absolute;+ left: 4px;+ bottom: 4px;+ min-width: 16px;+ padding: 1px 5px;+ border-radius: 9px;+ background: rgb(0 0 0 / 0.62);+ color: #e9edf3;+ font-size: 11px;+ font-weight: 700;+ line-height: 1.4;+ text-align: center;+}+.sv-thumb.current .sv-thumb-n { background: #f7a600; color: #14181d; }+.sv-grid {+ position: fixed;+ inset: 0;+ z-index: 10;+ background: rgb(9 12 16 / 0.94);+ overflow-y: auto;+ padding: 28px;+}+.sv-grid[hidden] { display: none; }+.sv-grid-inner {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ gap: 16px;+ justify-items: center;+}+/* line / curve / connector endpoint handles */+.ed-le-anchor { transition: r 0.08s ease; }+.ed-le-anchor:hover { fill: #eaf1ff; }++/* audience blackout — a plain black cover over the slides overlay */+.bento-blackout {+ position: absolute;+ inset: 0;+ z-index: 60;+ background: #000;+}+.bento-blackout[hidden] { display: none; }+/* --- live collaboration ----------------------------------------------- */.ed-avatars {display: flex;@@ -1363,6 +1467,20 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }white-space: normal;text-align: left;}+.ed-about-meta-wrap { flex-direction: column; align-items: stretch; gap: 5px; }+.ed-about-h { font-weight: 700; font-size: 13px; margin: 2px 0; }+.ed-about-meta { display: flex; align-items: center; gap: 8px; }+.ed-about-meta label { flex: 0 0 80px; font-size: 12px; color: var(--ink-2); }+.ed-about-meta input {+ flex: 1;+ min-width: 0;+ font: inherit;+ font-size: 13px;+ padding: 5px 8px;+ border: 1px solid var(--line);+ border-radius: 6px;+ background: #fff;+}/* collaborate popover: your-name field */.ed-share-name {diff --git a/slides/src/sync/online.ts b/slides/src/sync/online.tsindex bbd4f4e7..40d40746 100644--- a/slides/src/sync/online.ts+++ b/slides/src/sync/online.ts@@ -112,6 +112,13 @@ export class OnlineTransport implements Transport {private closed = falseprivate backoff = 800private url = ''+ // heartbeat: ping the relay (which auto-responds "pong" without waking the DO)+ // so idle connections stay alive; if a pong doesn't come back before the next+ // tick, treat the socket as dead and reconnect instead of waiting for a TCP+ // timeout that can take minutes.+ private pingTimer: ReturnType<typeof setInterval> | null = null+ private awaitingPong = false+ private static readonly PING_MS = 25_000/*** Replay bookmark — MEMORY ONLY, deliberately: it is valid only alongside* the in-memory CRDT state it was earned with. A fresh join replays from@@ -188,13 +195,17 @@ export class OnlineTransport implements Transport {this.replaySeen = new Set()this.setStatus('open')for (const text of this.queue.splice(0)) ws.send(text)+ this.startHeartbeat(ws)this.hooks.onOpen()}ws.onmessage = (ev) => {- this.onEnvelope(String(ev.data)).catch(() => {})+ const data = String(ev.data)+ if (data === 'pong') { this.awaitingPong = false; return } // keepalive reply+ this.onEnvelope(data).catch(() => {})}const drop = () => {if (this.ws !== ws) return+ this.stopHeartbeat()this.ws = nullthis.setStatus('closed')this.retry()@@ -203,6 +214,27 @@ export class OnlineTransport implements Transport {ws.onerror = drop}+ private startHeartbeat(ws: WebSocket) {+ this.stopHeartbeat()+ this.awaitingPong = false+ this.pingTimer = setInterval(() => {+ if (this.ws !== ws || ws.readyState !== WebSocket.OPEN) return+ if (this.awaitingPong) {+ // no pong since the last ping → the socket is dead (half-open); force a+ // close so onclose fires and we reconnect, rather than hanging silently.+ try { ws.close() } catch { /* already gone */ }+ return+ }+ this.awaitingPong = true+ try { ws.send('ping') } catch { /* send failed → onclose will handle it */ }+ }, OnlineTransport.PING_MS)+ }++ private stopHeartbeat() {+ if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null }+ this.awaitingPong = false+ }+private retry() {if (this.closed) returnsetTimeout(() => this.connect(), this.backoff)@@ -316,6 +348,7 @@ export class OnlineTransport implements Transport {close() {this.closed = true+ this.stopHeartbeat()this.ws?.close()this.ws = nullthis.setStatus('closed')