Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
bento-sync M1: same-machine live collab over BroadcastChannel
nyblnet414316914253
diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.tsindex 57e15eac..165475f8 100644--- a/slides/src/editor/canvas.ts+++ b/slides/src/editor/canvas.ts@@ -11,6 +11,7 @@ import { renderSlide, sanitizeHtml } from '../render'import { autoformatAtCaret, clearAutoformat, markdownToHtml, undoAutoformat } from './markdown'import { PathEditor } from './patheditor'import { CommentsUI } from './comments'+import type { Peer } from '../sync/session'export class SlideCanvas {private stage: HTMLElement@@ -135,6 +136,7 @@ export class SlideCanvas {this.moveable.updateRect()if (this.zoomLabel) this.zoomLabel.textContent = `${Math.round(this.scale * 100)}%`this.comments?.refresh()+ this.drawRemote()}// --- zoom ------------------------------------------------------------------@@ -375,6 +377,67 @@ export class SlideCanvas {this.surface = nextthis.relayout()this.syncTargets()+ this.drawRemote()+ }++ // --- collaborator presence (colored outlines + name tags) -----------------++ private remotePeers: Peer[] = []+ private remoteLayer: HTMLElement | null = null++ setRemotePeers(peers: Peer[]) {+ this.remotePeers = peers+ this.drawRemote()+ }++ private drawRemote() {+ const slide = this.store.slide+ if (!slide) return+ if (!this.remoteLayer) {+ this.remoteLayer = document.createElement('div')+ this.remoteLayer.className = 'ed-remote-layer'+ this.scaleHost.appendChild(this.remoteLayer)+ }+ // layer stays last in the scaled host so outlines paint above the slide+ if (this.remoteLayer.nextSibling) this.scaleHost.appendChild(this.remoteLayer)+ this.remoteLayer.innerHTML = ''+ for (const peer of this.remotePeers) {+ if (peer.slide !== slide.id) continue+ const ids = new Set(peer.sel)+ if (peer.editing) ids.add(peer.editing)+ // the layer lives inside the scaled host — counter-scale strokes and+ // name tags so they stay readable at any zoom (same idea as+ // moveable.zoom = 1/scale)+ const inv = 1 / (this.scale || 1)+ let tagged = false+ for (const id of ids) {+ const el = slide.elements.find((e) => e.id === id)+ if (!el) continue+ const box = document.createElement('div')+ box.className = 'ed-remote-box'+ box.style.left = `${el.x}px`+ box.style.top = `${el.y}px`+ box.style.width = `${el.w}px`+ box.style.height = `${el.h}px`+ box.style.borderColor = peer.color+ box.style.borderWidth = `${2 * inv}px`+ if (el.rotation) box.style.transform = `rotate(${el.rotation}deg)`+ if (peer.editing === id) box.classList.add('ed-remote-editing')+ if (!tagged) {+ const tag = document.createElement('div')+ tag.className = 'ed-remote-tag'+ tag.style.background = peer.color+ tag.textContent = peer.editing === id ? `✏️ ${peer.name}` : peer.name+ tag.style.transform = `scale(${inv})`+ tag.style.transformOrigin = 'bottom left'+ tag.style.bottom = '100%'+ tag.style.top = 'auto'+ box.appendChild(tag)+ tagged = true+ }+ this.remoteLayer.appendChild(box)+ }+ }}/**@@ -557,6 +620,7 @@ export class SlideCanvas {inner.focus()document.getSelection()?.selectAllChildren(inner)this.syncTargets()+ this.onTextEditChange?.(node.dataset.elId)inner.addEventListener('keydown', (ev) => {ev.stopPropagation() // keep global shortcuts (Delete, arrows…) away@@ -596,10 +660,14 @@ export class SlideCanvas {inner.addEventListener('blur', () => this.commitTextEdit(), { once: true })}+ /** collaborator presence: notified when text editing starts/stops */+ onTextEditChange: ((elId: string | undefined) => void) | null = null+commitTextEdit() {const node = this.editingif (!node) returnthis.editing = null+ this.onTextEditChange?.(undefined)const inner = node.querySelector<HTMLElement>('.bento-text-inner')const id = node.dataset.elIdnode.classList.remove('bento-editing')diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex f1a3a9b3..5f9f1cd1 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -38,6 +38,8 @@ export class Editor {private clipboard: SlideElement[] = []private presenting = falseprivate updatesB!: HTMLElement+ private avatarsBox!: HTMLElement+ private session: import('../sync/session').SyncSession | null = nullprivate updateFound: string | null = nullprivate lastAutoCheck: import('../update').UpdateCheck | null = null/** side panel widths (px) — user-resizable, persisted per browser */@@ -64,6 +66,38 @@ export class Editor {this.rebuildSidebar()}+ /** wire the live-collaboration session (avatars, remote selections) */+ connectSync(session: import('../sync/session').SyncSession) {+ this.session = session+ session.onPeers(() => {+ this.renderAvatars()+ this.canvas.setRemotePeers(session.peers())+ })+ this.canvas.onTextEditChange = (elId) => session.setEditing(elId)+ this.store.on('current', () => this.canvas.setRemotePeers(session.peers()))+ }++ private renderAvatars() {+ if (!this.session) return+ this.avatarsBox.innerHTML = ''+ for (const peer of this.session.peers()) {+ const chip = document.createElement('button')+ chip.className = 'ed-avatar'+ chip.style.background = peer.color+ chip.textContent = (peer.name || '?').trim().charAt(0).toUpperCase() || '?'+ const idx = this.store.doc.slides.findIndex((s) => s.id === peer.slide)+ chip.title =+ idx >= 0+ ? t('{name} — on slide {n} (click to follow)', { name: peer.name, n: idx + 1 })+ : peer.name+ chip.addEventListener('click', () => {+ const i = this.store.doc.slides.findIndex((s) => s.id === peer.slide)+ if (i >= 0) this.store.goTo(i)+ })+ this.avatarsBox.appendChild(chip)+ }+ }+// --- DOM ----------------------------------------------------------------private build() {@@ -91,6 +125,13 @@ export class Editor {this.store.commit(() => { this.store.doc.title = title.value || 'Untitled' })document.title = `${this.store.doc.title} — Bento Slides`})+ // remote/programmatic title changes reflect live (unless being typed in)+ this.store.on('doc', () => {+ if (document.activeElement !== title && title.value !== this.store.doc.title) {+ title.value = this.store.doc.title+ document.title = `${this.store.doc.title} — Bento Slides`+ }+ })this.dirtyDot = div('ed-dirty')this.dirtyDot.title = t('Unsaved changes')@@ -137,7 +178,8 @@ export class Editor {const rightT = btn(ICONS.panelRight, '', () => this.togglePanel('right'), t('Toggle properties (])'))actions.append(undoB, redoB, pdfB, this.updatesB, leftT, rightT, presentB, saveB, saveAsB)- bar.append(logo, title, this.dirtyDot, insert, actions)+ this.avatarsBox = div('ed-avatars')+ bar.append(logo, title, this.dirtyDot, this.avatarsBox, insert, actions)// main areaconst main = div('ed-main')diff --git a/slides/src/main.ts b/slides/src/main.tsindex cfc394e5..fceffad5 100644--- a/slides/src/main.ts+++ b/slides/src/main.ts@@ -11,6 +11,7 @@ import { starterDoc } from './starterdeck'import { injectFonts } from './fonts'import { Store } from './store'import { Editor } from './editor/editor'+import { SyncSession } from './sync/session'capturePristine()@@ -26,6 +27,11 @@ if (doc.fonts?.length) injectFonts(doc)const store = new Store(doc)const editor = new Editor(document.getElementById('app')!, store)+// Live collaboration (bento-sync): same-machine tabs sync automatically over+// BroadcastChannel; the online relay transport joins via the Share UI.+const session = new SyncSession(store)+editor.connectSync(session)+// Opening a link ending in #present starts the show immediately (player mode).if (location.hash === '#present') {editor.present(true)@@ -63,6 +69,15 @@ if (location.hash === '#present') {anim,/** i18n: t/locale/setLocale/choices — setLocale('x-pseudo') audits the sweep */i18n: i18nApi,+ /** live-collaboration session: actor id, connected peers, force a diff-flush */+ sync: {+ get actor() {+ return session.actor+ },+ peers: () => session.peers(),+ flush: () => session.flush(),+ transports: () => session.transportKinds,+ },/*** AI/tooling round-trip: replace the whole document from a JSON string* (the contents of #bento-doc). Validates via parseDoc; returns false anddiff --git a/slides/src/styles.css b/slides/src/styles.cssindex 1bf55957..e4526324 100644--- a/slides/src/styles.css+++ b/slides/src/styles.css@@ -1003,3 +1003,53 @@ body.ed-col-resizing { cursor: col-resize; user-select: none; }user-select: text;max-height: 320px;}++/* --- live collaboration ----------------------------------------------- */+.ed-avatars {+ display: flex;+ align-items: center;+ gap: 4px;+ margin: 0 2px;+}+.ed-avatar {+ width: 24px;+ height: 24px;+ border-radius: 50%;+ border: 2px solid rgba(255, 255, 255, 0.75);+ color: #16273e;+ font: 700 11px/1 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ padding: 0;+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35);+}+.ed-avatar:hover {+ transform: translateY(-1px);+}+.ed-remote-layer {+ position: absolute;+ inset: 0;+ pointer-events: none;+ z-index: 40;+}+.ed-remote-box {+ position: absolute;+ border: 2px solid;+ border-radius: 2px;+ pointer-events: none;+}+.ed-remote-box.ed-remote-editing {+ border-style: dashed;+}+.ed-remote-tag {+ position: absolute;+ top: -22px;+ left: -2px;+ padding: 2px 7px;+ border-radius: 4px;+ color: #16273e;+ font: 600 11px/1.4 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ white-space: nowrap;+}diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.tsnew file mode 100644index 00000000..455ea635--- /dev/null+++ b/slides/src/sync/session.ts@@ -0,0 +1,335 @@+// bento-sync session — the bridge between the CRDT engine (crdt.ts) and the+// running editor. Owns: the differ hook on the store, transports (same-machine+// BroadcastChannel always; an online relay transport can be added), presence,+// and peer catch-up. See docs/collab-design.md.+//+// Wire protocol (one JSON frame per message; E2EE happens inside the online+// transport — this layer never knows):+// {t:'hello', a, vv, p} join/announce — receivers reply hello + missing ops+// {t:'ops', a, ops} op batch+// {t:'need', a, vv} gap catch-up request (receivers send missing ops)+// {t:'p', a, p} presence heartbeat {t:'bye', a} leave+//+// The differ is the whole integration: every local mutation already flows+// through store.commit/touch → 'doc' event → (debounced) diff against the+// session's shadow → ops out. Remote ops apply surgically by id and re-emit+// the same store events the editor already listens to. Zero editor rewrites.++import type { Store } from '../store'+import type { BentoDoc, Slide } from '../model'+import { uid } from '../model'+import { SyncState, type Op } from './crdt'++export interface PresenceInfo {+ name: string+ color: string+ /** current slide id */+ slide: string+ /** selected element ids */+ sel: string[]+ /** element id currently being text-edited (in-text presence) */+ editing?: string+}++export interface Peer extends PresenceInfo {+ actor: string+ at: number+}++interface HelloFrame { t: 'hello'; a: string; vv: Record<string, number>; p: PresenceInfo }+interface OpsFrame { t: 'ops'; a: string; ops: Op[] }+interface NeedFrame { t: 'need'; a: string; vv: Record<string, number> }+interface PresFrame { t: 'p'; a: string; p: PresenceInfo }+interface ByeFrame { t: 'bye'; a: string }+export type Frame = HelloFrame | OpsFrame | NeedFrame | PresFrame | ByeFrame++export interface Transport {+ readonly kind: string+ send(frame: Frame): void+ close(): void+}++/** Same-machine transport: every open tab/window of this document. */+class BroadcastTransport implements Transport {+ readonly kind = 'local'+ private ch: BroadcastChannel+ constructor(docId: string, onFrame: (f: Frame) => void) {+ this.ch = new BroadcastChannel(`bento-sync-${docId}`)+ this.ch.onmessage = (ev) => onFrame(ev.data as Frame)+ }+ send(frame: Frame) {+ this.ch.postMessage(frame)+ }+ close() {+ this.ch.close()+ }+}++const PEER_COLORS = ['#FF9E8A', '#8FA3BF', '#7FC8A9', '#E8C468', '#C792EA', '#6AB7D6', '#E88AB0', '#A9C77F']++const actorColor = (actor: string): string => {+ let h = 0+ for (let i = 0; i < actor.length; i++) h = (h * 31 + actor.charCodeAt(i)) >>> 0+ return PEER_COLORS[h % PEER_COLORS.length]+}++/** per-TAB actor id: two tabs on one file are two replicas */+function tabActor(): string {+ try {+ let a = sessionStorage.getItem('bento-actor')+ if (!a) {+ a = Math.random().toString(36).slice(2, 10)+ sessionStorage.setItem('bento-actor', a)+ }+ return a+ } catch {+ return Math.random().toString(36).slice(2, 10)+ }+}++const DIFF_DEBOUNCE_MS = 90+const HEARTBEAT_MS = 5000+const PEER_TTL_MS = 13000++export class SyncSession {+ readonly actor: string+ state!: SyncState+ private shadow = ''+ private docId = ''+ private log: Op[] = []+ private transports: Transport[] = []+ private peersMap = new Map<string, Peer>()+ private applying = false+ private diffTimer: number | null = null+ private heartbeat: number | null = null+ private peerListeners = new Set<() => void>()+ private editingEl: string | undefined+ /** extra transports (the online relay) get plugged in here */+ private makeExtraTransports: Array<(docId: string, onFrame: (f: Frame) => void) => Transport> = []++ constructor(private store: Store) {+ this.actor = tabActor()+ this.attach()+ store.on('doc', () => this.onLocalChange())+ store.on('current', () => this.pushPresence())+ store.on('selection', () => this.pushPresence())+ window.addEventListener('beforeunload', () => this.broadcast({ t: 'bye', a: this.actor }))+ }++ // --- lifecycle -----------------------------------------------------------++ private attach() {+ this.docId = this.store.doc.docId+ this.state = new SyncState(this.actor)+ this.state.adopt(this.store.doc)+ this.shadow = JSON.stringify(this.store.doc)+ this.log = []+ this.peersMap.clear()+ this.emitPeers()+ for (const tr of this.transports) tr.close()+ this.transports = [new BroadcastTransport(this.docId, (f) => this.onFrame(f))]+ for (const mk of this.makeExtraTransports) this.transports.push(mk(this.docId, (f) => this.onFrame(f)))+ this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })+ if (this.heartbeat) clearInterval(this.heartbeat)+ this.heartbeat = window.setInterval(() => {+ this.pushPresence()+ this.sweepPeers()+ }, HEARTBEAT_MS)+ }++ /** register a factory for an additional transport (online relay) and connect it */+ addTransport(mk: (docId: string, onFrame: (f: Frame) => void) => Transport): Transport {+ this.makeExtraTransports.push(mk)+ const tr = mk(this.docId, (f) => this.onFrame(f))+ this.transports.push(tr)+ this.broadcast({ t: 'hello', a: this.actor, vv: this.state.vv, p: this.presence() })+ return tr+ }++ removeTransport(tr: Transport) {+ tr.close()+ this.transports = this.transports.filter((x) => x !== tr)+ this.makeExtraTransports = []+ }++ get transportKinds(): string[] {+ return this.transports.map((t) => t.kind)+ }++ // --- local mutations → ops ----------------------------------------------++ private onLocalChange() {+ if (this.applying) return+ if (this.store.doc.docId !== this.docId) {+ // replaceDoc / loadDoc swapped in a different document — re-key+ this.attach()+ return+ }+ if (this.diffTimer) return+ this.diffTimer = window.setTimeout(() => {+ this.diffTimer = null+ this.flush()+ }, DIFF_DEBOUNCE_MS)+ }++ /** diff now (also called before presence-relevant transitions) */+ flush() {+ if (this.applying) return+ const before = JSON.parse(this.shadow) as BentoDoc+ const ops = this.state.diff(before, this.store.doc, { text: true })+ this.shadow = JSON.stringify(this.store.doc)+ if (!ops.length) return+ this.log.push(...ops)+ this.broadcast({ t: 'ops', a: this.actor, ops })+ }++ // --- remote frames --------------------------------------------------------++ private onFrame(f: Frame) {+ if (f.a === this.actor) return+ switch (f.t) {+ case 'hello': {+ this.touchPeer(f.a, f.p)+ // answer so the newcomer learns us + catch them up from our log+ this.send({ t: 'p', a: this.actor, p: this.presence() })+ const missing = this.state.missingFor(this.log, f.vv)+ if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })+ break+ }+ case 'ops':+ this.applyRemote(f.ops)+ break+ case 'need': {+ const missing = this.state.missingFor(this.log, f.vv)+ if (missing.length) this.send({ t: 'ops', a: this.actor, ops: missing })+ break+ }+ case 'p':+ this.touchPeer(f.a, f.p)+ break+ case 'bye':+ this.peersMap.delete(f.a)+ this.emitPeers()+ break+ }+ }++ applyRemote(ops: Op[]) {+ // make sure our own pending edits are diffed first (they pre-date the+ // remote batch locally; LWW settles the rest)+ this.flush()+ for (const op of ops) if (!this.log.some((o) => o.a === op.a && o.s === op.s)) this.log.push(op)+ this.applying = true+ try {+ const res = this.state.apply(this.store.doc, ops)+ if (res.changed) this.afterRemoteChange(res.structure)+ } finally {+ this.applying = false+ }+ if (this.state.gappedActors.length) {+ this.send({ t: 'need', a: this.actor, vv: this.state.vv })+ }+ }++ private afterRemoteChange(structure: boolean) {+ const store = this.store+ // an all-slides-deleted race leaves an empty deck — heal with a blank+ if (store.doc.slides.length === 0) {+ const blank: Slide = {+ id: uid('s'),+ background: store.doc.theme.background,+ transition: 'fade',+ elements: [],+ notes: '',+ }+ store.doc.slides.push(blank)+ // mint it as a local op so every replica converges on ONE healer's+ // slide (LWW keeps all healers' slides; harmless extra blanks)+ this.applying = false+ this.flush()+ this.applying = true+ }+ store.currentIndex = Math.min(store.currentIndex, store.doc.slides.length - 1)+ const sel = store.selection.filter((id) => store.element(id))+ const selChanged = sel.length !== store.selection.length+ store.selection = sel+ this.shadow = JSON.stringify(store.doc)+ store.doc.modified = new Date().toISOString()+ store.setDirty(true)+ store.emit('doc')+ if (structure) {+ store.emit('slides')+ store.emit('current')+ }+ if (selChanged) store.emit('selection')+ }++ // --- presence -------------------------------------------------------------++ private presence(): PresenceInfo {+ let name = 'Guest'+ try {+ name = localStorage.getItem('bento-author') || 'Guest'+ } catch {+ /* storage unavailable */+ }+ return {+ name,+ color: actorColor(this.actor),+ slide: this.store.slide?.id ?? '',+ sel: this.store.selection.slice(),+ ...(this.editingEl ? { editing: this.editingEl } : {}),+ }+ }++ /** canvas hooks this while a text element is being edited (M3 presence) */+ setEditing(elId: string | undefined) {+ if (this.editingEl === elId) return+ this.editingEl = elId+ this.pushPresence()+ }++ private pushPresence() {+ this.send({ t: 'p', a: this.actor, p: this.presence() })+ }++ private touchPeer(actor: string, p: PresenceInfo) {+ this.peersMap.set(actor, { ...p, actor, at: Date.now() })+ this.emitPeers()+ }++ private sweepPeers() {+ const cut = Date.now() - PEER_TTL_MS+ let changed = false+ for (const [a, p] of this.peersMap) {+ if (p.at < cut) {+ this.peersMap.delete(a)+ changed = true+ }+ }+ if (changed) this.emitPeers()+ }++ peers(): Peer[] {+ return [...this.peersMap.values()].sort((a, b) => (a.actor < b.actor ? -1 : 1))+ }++ onPeers(fn: () => void): () => void {+ this.peerListeners.add(fn)+ return () => this.peerListeners.delete(fn)+ }++ private emitPeers() {+ this.peerListeners.forEach((fn) => fn())+ }++ // --- plumbing -------------------------------------------------------------++ private send(frame: Frame) {+ for (const tr of this.transports) tr.send(frame)+ }++ private broadcast(frame: Frame) {+ this.send(frame)+ }+}