Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides fix: preserve editor state when deleting slides (#262)

Jamie (James) Londoneb7053f6b5bc
diff --git a/scripts/test-slide-store.ts b/scripts/test-slide-store.ts
new file mode 100644
index 00000000..0697c223
--- /dev/null
+++ b/scripts/test-slide-store.ts
@@ -0,0 +1,168 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// Slide-list/view-state regression rig. Runs without a DOM.
+
+import { emptySlide, newDoc, defaultText } from '../slides/src/model.ts'
+import { Store } from '../slides/src/store.ts'
+
+let checks = 0
+let failures = 0
+
+function ok(condition: boolean, message: string) {
+ checks++
+ if (condition) console.log(` ok ${message}`)
+ else {
+ failures++
+ console.error(` FAIL ${message}`)
+ }
+}
+
+function makeStore(ids: string[]): Store {
+ const doc = newDoc()
+ doc.slides = ids.map((id) => emptySlide({ id, name: id }))
+ return new Store(doc)
+}
+
+function observeDoc(store: Store) {
+ let observed: string[] = []
+ store.on('doc', () => { observed.push(store.slide.id) })
+ return () => observed
+}
+
+console.log('\nslide view reconciliation')
+
+{
+ const store = makeStore(['a', 'b', 'c', 'd'])
+ store.currentIndex = 3
+ store.slide.elements.push(defaultText({ id: 'selected' }))
+ store.selection = ['selected']
+ const observed = observeDoc(store)
+ store.commit(() => { store.doc.slides.splice(0, 1) }, 'slides')
+ ok(store.slide.id === 'd' && store.currentIndex === 2, 'deleting before the current slide preserves it by id')
+ ok(store.selection[0] === 'selected', 'selection survives when the current slide survives')
+ ok(observed().join() === 'd', 'doc listeners only observe a valid reconciled slide')
+}
+
+{
+ const store = makeStore(['a', 'b', 'c', 'd'])
+ store.currentIndex = 1
+ store.slide.elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.doc.slides[2].elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.selection = ['shared-morph-id']
+ store.hoverPreview = 'details'
+ let currentEvents = 0
+ let selectionEvents = 0
+ store.on('current', () => { currentEvents++ })
+ store.on('selection', () => { selectionEvents++ })
+ store.commit(() => { store.doc.slides.splice(1, 1) }, 'slides')
+ ok(store.slide.id === 'c' && store.currentIndex === 1, 'deleting the current slide selects its next neighbour')
+ ok(store.selection.length === 0 && store.hoverPreview == null, 'switching slides clears transient view state even when element ids repeat')
+ ok(currentEvents === 1 && selectionEvents === 1, 'the reconciled slide switch emits current and selection once')
+}
+
+{
+ const store = makeStore(['a', 'b', 'c', 'd'])
+ store.currentIndex = 3
+ store.commit(() => { store.doc.slides.pop() }, 'slides')
+ ok(store.slide.id === 'c' && store.currentIndex === 2, 'deleting the last current slide selects the previous neighbour')
+}
+
+{
+ const store = makeStore(['parent', 'state-1', 'state-2', 'next', 'tail'])
+ store.currentIndex = 2
+ const doomed = new Set(['parent', 'state-1', 'state-2'])
+ store.commit(() => { store.doc.slides = store.doc.slides.filter((slide) => !doomed.has(slide.id)) }, 'slides')
+ ok(store.slide.id === 'next' && store.currentIndex === 0, 'a deleted state selects the next survivor across a cascade')
+}
+
+{
+ const store = makeStore(['parent', 'state-1', 'state-2', 'current', 'tail'])
+ store.currentIndex = 3
+ const doomed = new Set(['parent', 'state-1', 'state-2'])
+ store.commit(() => { store.doc.slides = store.doc.slides.filter((slide) => !doomed.has(slide.id)) }, 'slides')
+ ok(store.slide.id === 'current' && store.currentIndex === 0, 'a surviving current slide follows its id across a cascade')
+}
+
+{
+ const store = makeStore(['a', 'b', 'c'])
+ store.currentIndex = 1
+ store.commit(() => {
+ const [current] = store.doc.slides.splice(1, 1)
+ store.doc.slides.push(current)
+ }, 'slides')
+ ok(store.slide.id === 'b' && store.currentIndex === 2, 'reordering preserves the current slide by id')
+}
+
+{
+ const store = makeStore(['a', 'b', 'c'])
+ store.currentIndex = 2
+ store.slide.elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.doc.slides[0].elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.selection = ['shared-morph-id']
+ store.hoverPreview = 'details'
+ const movedId = store.doc.slides[0].id
+ store.goTo(store.doc.slides.findIndex((slide) => slide.id === movedId))
+ store.commit(() => {
+ const [moved] = store.doc.slides.splice(0, 1)
+ store.doc.slides.splice(1, 0, moved)
+ }, 'slides')
+ ok(store.slide.id === 'a', 'drag navigation selects the moved slide')
+ ok(store.selection.length === 0 && store.hoverPreview == null, 'drag navigation clears transient state from the previous slide')
+}
+
+console.log('\nhistory reconciliation')
+
+{
+ const store = makeStore(['a', 'b', 'c', 'd'])
+ store.currentIndex = 3
+ store.slide.elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.doc.slides[2].elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.selection = ['shared-morph-id']
+ store.commit(() => { store.doc.slides.splice(0, 1) }, 'slides')
+ store.undo()
+ ok(store.slide.id === 'd' && store.currentIndex === 3, 'undo restores the pre-edit slide by id rather than by shifted index')
+ ok(store.selection[0] === 'shared-morph-id', 'undo keeps selection only on the same surviving slide')
+ store.redo()
+ ok(store.slide.id === 'd' && store.currentIndex === 2, 'redo restores the post-edit slide by id')
+}
+
+{
+ const store = makeStore(['a', 'b', 'c'])
+ store.currentIndex = 1
+ store.selection = ['shared-morph-id']
+ store.commit(() => { store.doc.slides.splice(1, 1) }, 'slides')
+ store.undo()
+ ok(store.slide.id === 'b' && store.selection.length === 0, 'undoing current-slide deletion restores that slide without carrying another slide selection onto it')
+}
+
+console.log('\nexternal mutation reconciliation')
+
+{
+ const store = makeStore(['a', 'b', 'c', 'd'])
+ store.currentIndex = 2
+ store.slide.elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.doc.slides[3].elements.push(defaultText({ id: 'shared-morph-id' }))
+ store.selection = ['shared-morph-id']
+ const view = store.captureView()
+ store.doc.slides.splice(0, 1) // remote CRDT changes bypass commit()
+ const change = store.reconcileView(view)
+ ok(store.slide.id === 'c' && store.currentIndex === 1, 'external deletion before current preserves the current slide by id')
+ ok(store.selection[0] === 'shared-morph-id' && !change.currentChanged, 'external reconciliation does not transfer selection to a repeated id on another slide')
+}
+
+{
+ const store = makeStore(['a', 'b'])
+ store.currentIndex = 1
+ store.selection = ['selected']
+ let currentEvents = 0
+ let selectionEvents = 0
+ store.on('current', () => { currentEvents++ })
+ store.on('selection', () => { selectionEvents++ })
+ store.commit(() => { store.doc.slides = [emptySlide({ id: 'blank' })] }, 'slides')
+ ok(store.slide.id === 'blank' && store.currentIndex === 0, 'whole-deck replacement lands on its valid blank slide')
+ ok(currentEvents === 1 && selectionEvents === 1, 'whole-deck replacement emits current and selection exactly once')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.ts
index 8eb13930..a5a1c4b0 100644
--- a/slides/src/editor/canvas.ts
+++ b/slides/src/editor/canvas.ts
@@ -34,6 +34,11 @@ export class SlideCanvas {
private zoom = 1
private zoomLabel: HTMLElement | null = null
private editing: HTMLElement | null = null
+ /** Slide identity captured when an inline edit begins. Element ids may be
+ * shared across duplicated slides, so resolving through store.slide at
+ * commit time can write into the wrong slide after navigation or a remote
+ * deletion. */
+ private editingSlideId: string | null = null
/** startTextEdit swapped the rendered form for raw source (a field or a
* formula), so commit must re-render even if the text is unchanged. */
private editingShowedRaw = false
@@ -575,6 +580,10 @@ export class SlideCanvas {
}
render() {
+ // A slide switch is a hard boundary for an inline edit. Commit against
+ // the slide where editing began (or discard if that slide was remotely
+ // deleted) before replacing the canvas DOM.
+ if (this.editing && this.editingSlideId !== this.store.slide?.id) this.commitTextEdit()
// Don't repaint out from under an in-progress inline edit. A remote collab
// op landing must NOT tear down the text/cell node you're typing in — that
// steals focus and resets the caret (the #1 rough edge reported at launch).
@@ -1059,6 +1068,7 @@ export class SlideCanvas {
this.editingShowedRaw = true
}
this.editing = node
+ this.editingSlideId = this.store.slide.id
node.classList.add('bento-editing')
inner.contentEditable = 'true'
inner.focus()
@@ -1111,7 +1121,9 @@ export class SlideCanvas {
const node = this.editing
if (!node) return
if (this.editingCell) { this.commitCellEdit(node); return }
+ const slideId = this.editingSlideId
this.editing = null
+ this.editingSlideId = null
this.onTextEditChange?.(undefined)
const inner = node.querySelector<HTMLElement>('.bento-text-inner')
const id = node.dataset.elId
@@ -1121,7 +1133,9 @@ export class SlideCanvas {
// drop the zero-width caret spacers autoformat leaves behind
const html = sanitizeHtml(inner.innerHTML.replace(/\u200B/g, '').replace(/\\([*_~`-])/g, '$1'))
const grownH = Math.max(parseFloat(node.style.height) || 0, inner.scrollHeight)
- const el = this.store.element(id)
+ const el = this.store.doc.slides
+ .find((slide) => slide.id === slideId)
+ ?.elements.find((element) => element.id === id)
if (el && el.type === 'text' && (el.html !== html || grownH > el.h)) {
this.store.commit(() => {
el.html = html
@@ -1170,6 +1184,7 @@ export class SlideCanvas {
const inner = td.querySelector<HTMLElement>('.bento-cell-inner')
if (!node || !inner) return
this.editing = node
+ this.editingSlideId = this.store.slide.id
this.editingCell = { r, c }
node.classList.add('bento-editing')
inner.contentEditable = 'true'
@@ -1202,7 +1217,9 @@ export class SlideCanvas {
private commitCellEdit(node: HTMLElement) {
const cell = this.editingCell!
const id = node.dataset.elId
+ const slideId = this.editingSlideId
this.editing = null
+ this.editingSlideId = null
this.editingCell = null
this.onTextEditChange?.(undefined)
node.classList.remove('bento-editing')
@@ -1211,10 +1228,12 @@ export class SlideCanvas {
if (!inner || !id) return
inner.contentEditable = 'false'
const html = sanitizeHtml(inner.innerHTML.replace(/\u200B/g, '').replace(/\\([*_~`-])/g, '$1'))
- const el = this.store.element(id)
+ const el = this.store.doc.slides
+ .find((slide) => slide.id === slideId)
+ ?.elements.find((element) => element.id === id)
if (el && el.type === 'table' && el.rows[cell.r]?.cells[cell.c] && el.rows[cell.r].cells[cell.c].html !== html) {
this.store.commit(() => {
- const tb = this.store.element(id) as TableElement
+ const tb = el as TableElement
if (tb.rows[cell.r]?.cells[cell.c]) tb.rows[cell.r].cells[cell.c].html = html
})
} else {
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 8a5792f7..0cdf061e 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -792,12 +792,9 @@ export class Editor {
const blank = builtinLayouts().find((l) => l.id === 'layout-blank')
if (!blank) return
this.canvas.commitTextEdit() // a live text edit would commit ONTO the new slide
- this.store.select([])
this.store.commit(() => {
this.store.doc.slides = [instantiateLayout(blank)]
}, 'slides')
- this.store.goTo(0)
- this.store.emit('current')
}
/** A sealed hand-out: present-only player file, no editor, no live session. */
@@ -1653,6 +1650,14 @@ export class Editor {
}
private wireThumbDrag(item: HTMLElement, index: number) {
+ // Select on press, before the browser starts native dragging. Waiting for
+ // click/dragstart leaves Moveable's previous canvas target live while the
+ // pointer crosses the workspace.
+ item.addEventListener('mousedown', (ev) => {
+ if (ev.button !== 0 || (ev.target instanceof Element && ev.target.closest('.ed-thumb-tools'))) return
+ ev.stopPropagation() // keep the canvas Moveable gesture controller out
+ this.store.goTo(index)
+ })
item.addEventListener('dragstart', (ev) => {
ev.dataTransfer!.setData('text/bento-slide', String(index))
ev.dataTransfer!.effectAllowed = 'move'
@@ -1671,8 +1676,6 @@ export class Editor {
const [moved] = this.store.doc.slides.splice(from, 1)
this.store.doc.slides.splice(index, 0, moved)
}, 'slides')
- this.store.currentIndex = index
- this.store.emit('current')
})
}
@@ -1758,8 +1761,6 @@ export class Editor {
}
}
}, 'slides')
- this.store.goTo(Math.min(i, this.store.doc.slides.length - 1))
- this.store.emit('current')
}
/**
diff --git a/slides/src/store.ts b/slides/src/store.ts
index fb415754..70721b82 100644
--- a/slides/src/store.ts
+++ b/slides/src/store.ts
@@ -12,6 +12,17 @@ export type StoreEvent =
type Listener = () => void
+export type ViewSnapshot = {
+ slideIds: string[]
+ currentIndex: number
+ currentId?: string
+}
+
+type HistoryEntry = {
+ doc: string
+ view: ViewSnapshot
+}
+
const MAX_UNDO = 100
/** Central state: document, current slide, selection, undo/redo, dirty flag. */
@@ -23,8 +34,8 @@ export class Store {
/** editor-only: which showOnHover set the canvas previews (never saved) */
hoverPreview: string | null = null
- private undoStack: string[] = []
- private redoStack: string[] = []
+ private undoStack: HistoryEntry[] = []
+ private redoStack: HistoryEntry[] = []
private listeners = new Map<StoreEvent, Set<Listener>>()
/** read-only viewer: block user edits (commit) while remote ops — which
@@ -80,7 +91,7 @@ export class Store {
/** Snapshot current doc state onto the undo stack. Call BEFORE a mutation. */
checkpoint() {
- this.undoStack.push(JSON.stringify(this.doc))
+ this.undoStack.push({ doc: JSON.stringify(this.doc), view: this.captureView() })
if (this.undoStack.length > MAX_UNDO) this.undoStack.shift()
this.redoStack.length = 0
}
@@ -88,9 +99,56 @@ export class Store {
/** checkpoint() + mutate + notify, in one call. */
commit(mutate: () => void, event: StoreEvent = 'doc') {
if (this.readOnly) return // live viewer — user edits are inert
+ const view = this.captureView()
this.checkpoint()
mutate()
+ const { currentChanged, selectionChanged } = this.reconcileView(view)
this.touch(event)
+ if (currentChanged) this.emit('current')
+ if (selectionChanged) this.emit('selection')
+ }
+
+ /**
+ * A slide-list mutation and the view that points into it are one state
+ * transition. Keep the same slide by id when it survives; otherwise choose
+ * the next surviving neighbour (or the previous one at the end). This runs
+ * before touch(), so no redraw listener can observe an invalid slide index.
+ */
+ captureView(): ViewSnapshot {
+ return {
+ slideIds: this.doc.slides.map((slide) => slide.id),
+ currentIndex: this.currentIndex,
+ currentId: this.doc.slides[this.currentIndex]?.id,
+ }
+ }
+
+ reconcileView(
+ before: ViewSnapshot,
+ preferred: ViewSnapshot = before,
+ ): { currentChanged: boolean; selectionChanged: boolean } {
+ const slides = this.doc.slides
+ const byId = new Map(slides.map((slide, index) => [slide.id, index]))
+
+ let nextIndex = preferred.currentId == null ? undefined : byId.get(preferred.currentId)
+ if (nextIndex == null) {
+ const neighbourId = preferred.slideIds.slice(preferred.currentIndex + 1).find((id) => byId.has(id))
+ ?? preferred.slideIds.slice(0, preferred.currentIndex).reverse().find((id) => byId.has(id))
+ nextIndex = neighbourId == null
+ ? Math.max(0, Math.min(preferred.currentIndex, slides.length - 1))
+ : byId.get(neighbourId)!
+ }
+
+ this.currentIndex = nextIndex
+ const currentChanged = slides[nextIndex]?.id !== before.currentId
+ const selection = currentChanged
+ ? []
+ : this.selection.filter((id) => slides[nextIndex]?.elements.some((element) => element.id === id))
+ const selectionChanged = currentChanged
+ || selection.length !== this.selection.length
+ || selection.some((id, index) => id !== this.selection[index])
+ this.selection = selection
+ if (currentChanged) this.hoverPreview = null
+ return { currentChanged, selectionChanged }
}
/** Mark dirty and notify after an in-place mutation (no checkpoint). */
@@ -104,13 +162,13 @@ export class Store {
undo() { this.restore(this.undoStack, this.redoStack) }
redo() { this.restore(this.redoStack, this.undoStack) }
- private restore(from: string[], to: string[]) {
- const snapshot = from.pop()
- if (!snapshot) return
- to.push(JSON.stringify(this.doc))
- this.doc = JSON.parse(snapshot)
- this.currentIndex = Math.min(this.currentIndex, this.doc.slides.length - 1)
- this.selection = this.selection.filter((id) => this.element(id))
+ private restore(from: HistoryEntry[], to: HistoryEntry[]) {
+ const entry = from.pop()
+ if (!entry) return
+ const before = this.captureView()
+ to.push({ doc: JSON.stringify(this.doc), view: before })
+ this.doc = JSON.parse(entry.doc)
+ this.reconcileView(before, entry.view)
this.setDirty(true)
this.emit('doc')
this.emit('slides')
diff --git a/slides/src/sync/session.ts b/slides/src/sync/session.ts
index aa59ebe4..3687d648 100644
--- a/slides/src/sync/session.ts
+++ b/slides/src/sync/session.ts
@@ -17,7 +17,7 @@
// 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 { Store, ViewSnapshot } from '../store'
import type { BentoDoc, Slide } from '../model'
import { uid } from '../model'
import { SyncState, SYNC_V, BLOB_INLINE_MAX, type Op } from './crdt'
@@ -470,10 +470,11 @@ export class SyncSession {
// 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)
+ const view = this.store.captureView()
this.applying = true
try {
const res = this.state.apply(this.store.doc, ops)
- if (res.changed) this.afterRemoteChange(res.structure)
+ if (res.changed) this.afterRemoteChange(res.structure, view)
} finally {
this.applying = false
}
@@ -482,7 +483,7 @@ export class SyncSession {
}
}
- private afterRemoteChange(structure: boolean) {
+ private afterRemoteChange(structure: boolean, view: ViewSnapshot) {
void this.resolveBlobs()
const store = this.store
// an all-slides-deleted race leaves an empty deck — heal with a blank
@@ -501,19 +502,16 @@ export class SyncSession {
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
+ const { currentChanged, selectionChanged } = store.reconcileView(view)
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')
+ if (currentChanged) store.emit('current')
+ if (selectionChanged) store.emit('selection')
}
// --- presence -------------------------------------------------------------
@@ -646,10 +644,11 @@ export class SyncSession {
applySnapshot(rdoc: BentoDoc, rstate: import('./crdt').SyncStateJSON) {
if (!rstate || rstate.v !== SYNC_V) return // pre-v2 room snapshot — unusable
this.flush()
+ const view = this.store.captureView()
this.applying = true
try {
const res = this.state.mergeSnapshot(this.store.doc, rdoc, rstate)
- if (res.changed) this.afterRemoteChange(true)
+ if (res.changed) this.afterRemoteChange(true, view)
} finally {
this.applying = false
}