Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

slides: route connectors on every slide, at boot and on every doc change (#493) (#693)

nyblnet8af2c0612e0f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index edc91abf..4277677c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2394,6 +2394,11 @@ jobs:
# restores; paste moves it to the pointer in one undo step, across
# slides, without two elements sharing an id on one slide.
run: node scripts/test-slides-ghost-cut-browser.mjs
+ - name: Connectors route on every slide in Chromium
+ # #493: a deck saved or loaded with stale connector endpoints opens with
+ # every slide's connectors on their elements' borders (thumbnail too),
+ # without dirtying the deck or making an undo step.
+ run: node scripts/test-slides-connectors-browser.mjs
- name: Caret at the start of a line in Chromium
# #547: with the caret at a text box's left edge, nothing paints over
# it — the editing ring is an outline held off the box, Moveable's
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a284edd..98c00204 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,14 @@ pre-1.0.
## [Unreleased]
+- **Connectors in decks written outside the editor now attach.** A deck made
+ by hand or by an AI agent can name the two elements a connector joins
+ without giving it the right endpoints. Until now only the slide on screen was
+ ever re-routed, and only after an edit, so a connector on any other slide sat
+ wherever the file put it — in the thumbnails, the slideshow and the PDF. Every
+ slide's connectors now land on their elements' borders as the deck opens, or
+ is replaced from JSON. Doing so is not an edit: the deck is not marked unsaved
+ and there is nothing to undo. (#493)
- **A table with rounded corners no longer hides rows.** When a rounded
table's rows needed more height than its box, the rows past the bottom were
cut off with nothing to say so. They now show, as they always did for a table
diff --git a/scripts/test-slides-connectors-browser.mjs b/scripts/test-slides-connectors-browser.mjs
new file mode 100644
index 00000000..591b07db
--- /dev/null
+++ b/scripts/test-slides-connectors-browser.mjs
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// #493 — connectors in a deck authored outside the editor route on every slide.
+//
+// npm run build:single --prefix slides && node scripts/test-slides-connectors-browser.mjs
+//
+// WHAT THIS PROVES, in the packaged document. A deck written by hand or by an
+// agent names a connector's from/to elements but carries stale or placeholder
+// endpoints. Before #493 only the slide on screen was ever routed, and only on
+// an edit — so slide 2's connector stayed wherever the author left it, in the
+// thumbnail, the show and the PDF. Now:
+// 1. a deck SAVED that way (the file's own #bento-doc) opens with slide 2's
+// connector already on its two elements' borders, while slide 1 is shown;
+// 2. slide 2's thumbnail draws it there;
+// 3. that routing is not an edit — the deck is not dirty, and ⌘Z does not
+// bring the stale endpoints back;
+// 4. a deck put in with window.bento.loadDoc (Replace from JSON) routes the
+// same way, on every slide.
+import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+
+let checks = 0
+let failures = 0
+function ok(cond, msg) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`)
+}
+const shellPath = new URL('../slides/dist-single/Bento_Slides.bento.html', import.meta.url)
+const OPEN = '<script type="application/bento+json" id="bento-doc">'
+
+// a line's two endpoints from its box (kernel geom lineEndpoints)
+const ends = (el) => {
+ const cx = el.x + el.w / 2, cy = el.y + el.h / 2, t = ((el.rotation || 0) * Math.PI) / 180
+ const dx = (Math.cos(t) * el.w) / 2, dy = (Math.sin(t) * el.w) / 2
+ return [{ x: cx - dx, y: cy - dy }, { x: cx + dx, y: cy + dy }]
+}
+const routed = (el) => {
+ if (!el) return false
+ const [a, b] = ends(el)
+ return Math.abs(a.x - 300) < 1.5 && Math.abs(a.y - 350) < 1.5 && Math.abs(b.x - 800) < 1.5 && Math.abs(b.y - 350) < 1.5
+}
+const box = (id, x) => ({ id, type: 'shape', shape: 'rect', x, y: 300, w: 200, h: 100, rotation: 0, opacity: 1, fill: '#5E7699' })
+const conn = { id: 'conn', type: 'shape', shape: 'line', x: 20, y: 20, w: 40, h: 2, rotation: 0, opacity: 1, fill: '#1E2A3A', strokeWidth: 3, from: { el: 'A' }, to: { el: 'B' } }
+const staleDeck = (base) => {
+ const d = JSON.parse(JSON.stringify(base))
+ d.slides = [
+ { id: 's1', background: '#ffffff', elements: [box('A', 100)] },
+ { id: 's2', background: '#ffffff', elements: [box('A', 100), box('B', 800), JSON.parse(JSON.stringify(conn))] },
+ ]
+ return d
+}
+
+const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })
+try {
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } })
+ await ctx.route(/^https?:/, (r) => r.abort())
+ const p = await ctx.newPage()
+ const errors = []
+ p.on('pageerror', (e) => errors.push(e.message))
+ await p.goto(shellPath.href)
+ await p.waitForFunction(() => window.bento?.doc)
+ const base = await p.evaluate(() => JSON.parse(JSON.stringify(window.bento.doc)))
+
+ console.log('\na deck saved with stale connector endpoints\n')
+ const shell = readFileSync(shellPath, 'utf8')
+ const i = shell.indexOf(OPEN) + OPEN.length, j = shell.indexOf('</' + 'script>', i)
+ const json = JSON.stringify(staleDeck(base)).replace(/</g, '\\u003c')
+ const dir = mkdtempSync(join(tmpdir(), 'bento-493-'))
+ const file = join(dir, 'stale-connectors.bento.html')
+ writeFileSync(file, shell.slice(0, i) + json + shell.slice(j))
+ await p.goto('file://' + file)
+ await p.waitForFunction(() => window.bento?.doc && document.querySelector('.ed-sidebar .ed-thumb[data-index="1"]'))
+ await p.waitForTimeout(600)
+ const s = await p.evaluate(() => ({
+ conn: window.bento.doc.slides[1].elements.find((e) => e.id === 'conn'),
+ current: document.querySelector('.ed-stage-scale [data-el-id="A"]') && !document.querySelector('.ed-stage-scale [data-el-id="B"]'),
+ dirty: !!document.querySelector('.ed-dirty.on'),
+ }))
+ ok(s.current, 'slide 1 is the one on screen')
+ ok(routed(s.conn), `slide 2's connector opens on A's and B's borders (${ends(s.conn).map((q) => `${Math.round(q.x)},${Math.round(q.y)}`).join(' → ')})`)
+ const thumb = await p.evaluate(() => {
+ const t = document.querySelector('.ed-sidebar .ed-thumb[data-index="1"] [data-el-id="conn"]')
+ return t ? { left: parseFloat(t.style.left), width: parseFloat(t.style.width) } : null
+ })
+ const want = s.conn
+ ok(!!thumb && Math.abs(thumb.left - want.x) < 0.5 && Math.abs(thumb.width - want.w) < 0.5, `slide 2's thumbnail draws it there (left ${thumb?.left}, width ${thumb?.width})`)
+ ok(!s.dirty, 'opening it is not an edit — the deck is not dirty')
+ await p.evaluate(() => window.bento.undo())
+ await p.waitForTimeout(200)
+ const afterUndo = await p.evaluate(() => window.bento.doc.slides[1].elements.find((e) => e.id === 'conn'))
+ ok(routed(afterUndo), '⌘Z does not bring the stale endpoints back (routing made no undo step)')
+
+ console.log('\na deck put in with loadDoc\n')
+ await p.goto(shellPath.href)
+ await p.waitForFunction(() => window.bento?.doc)
+ await p.evaluate((d) => window.bento.loadDoc(JSON.stringify(d)), staleDeck(base))
+ await p.waitForTimeout(400)
+ const viaLoad = await p.evaluate(() => window.bento.doc.slides[1].elements.find((e) => e.id === 'conn'))
+ ok(routed(viaLoad), 'slide 2 — not the slide on screen — is routed after loadDoc')
+
+ ok(errors.length === 0, `no page errors${errors.length ? ': ' + errors.join('; ') : ''}`)
+} finally { await browser.close() }
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-slides-connectors.ts b/scripts/test-slides-connectors.ts
index b418b444..d70910ef 100644
--- a/scripts/test-slides-connectors.ts
+++ b/scripts/test-slides-connectors.ts
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { TIPS, TIP_KINDS, tipSpec, tipInsetPx, endTangent, shortenPathEnds, movePathEnds, pathEnds } from '../slides/src/tips.ts'
import { parseBezier } from '../slides/src/editor/bezier.ts'
+import { routeConnectors, routeAllConnectors } from '../slides/src/connectors.ts'
import { borderPoint, lineEndpoints, setLineEndpoints, boxCenter, sideMidpoint, connectorEndpoint, boxAnchors, nearestAnchor, boxContains, type ConnectorSide, type Box, type Pt as GPt } from '../kernel/src/geom.ts'
let failures = 0
@@ -48,6 +49,7 @@ const gate = read('slides/src/untrusted.ts')
ok(/lineStart: oneOf\(\.\.\.TIP_KINDS\), lineEnd: oneOf\(\.\.\.TIP_KINDS\)/.test(gate), 'the shape gate admits exactly the catalogue')
const panels = read('slides/src/editor/panels.ts')
const editor = read('slides/src/editor/editor.ts')
+const lineedit = read('slides/src/connectors.ts') // the routing moved here (#493)
ok(/TIPS\.map\(\(tip\) => \[tip\.kind, t\(tip\.label\)\]\)/.test(panels), 'the panel lists the catalogue — model words as values, translated labels for display')
ok(/el\.shape === 'line' \|\| \(el\.shape === 'path' && !\/z\\s\*\$\/i\.test/.test(panels), 'tips are offered on lines and OPEN paths, never on a polygon')
const render = read('slides/src/render.ts')
@@ -203,7 +205,7 @@ console.log('\nthe legacy straight connector\n')
}
// and the marker numbers an old deck was drawn with
ok(/inset the endpoints so the tip's point lands on the box edge/.test(shape) && /tipInsetPx\(el\.lineStart, lw\)/.test(shape), 'a line insets by the catalogue — 2.6 for the original three (asserted above)')
-ok(/el\.shape !== 'line' && el\.shape !== 'path'/.test(editor) && /if \(isPath\) setPathEndpoints\(c, na, nb\)\n\s+else setLineEndpoints\(c, na, nb\)/.test(editor), 'syncConnectors routes lines through setLineEndpoints and paths through setPathEndpoints')
+ok(/el\.shape !== 'line' && el\.shape !== 'path'/.test(lineedit) && /if \(isPath\) setPathEndpoints\(c, na, nb\)\n\s+else setLineEndpoints\(c, na, nb\)/.test(lineedit), 'routeConnectors routes lines through setLineEndpoints and paths through setPathEndpoints')
const canvas = read('slides/src/editor/canvas.ts')
ok(/kind === 'curve-connector'/.test(canvas) && /el\.lineEnd = 'arrow'\n\s+if \(fromA\) el\.from/.test(canvas), 'the Curved connector tool draws a path with a tip and anchors like Connector')
ok(/label: 'Curved connector'/.test(editor) && /label: 'Double arrow'/.test(editor), 'both new shapes are in the Shape menu')
@@ -284,9 +286,46 @@ console.log('\nconnector routing + snapping moved to the kernel (byte-identical)
// slides imports the kernel helpers through ./lineedit (the one import site)
ok(/export \{ boxCenter, borderPoint, sideMidpoint, boxAnchors, connectorEndpoint, nearestAnchor, boxContains/.test(read('slides/src/editor/lineedit.ts')), 'lineedit re-exports the connector geom — ./lineedit stays the import site')
- ok(/connectorEndpoint\(fromBox, c\.from\?\.side/.test(editor) && !/const end = \(box/.test(editor), 'editor.ts syncConnectors calls connectorEndpoint, inline end() gone')
+ ok(/connectorEndpoint\(fromBox, c\.from\?\.side/.test(lineedit) && !/const end = \(box/.test(editor), 'routeConnectors (connectors.ts) calls connectorEndpoint, inline end() gone')
ok(/boxAnchors\(this\.store\.slide\.elements\.find/.test(canvas) && /nearestAnchor\(anchorsFor\(id\)/.test(canvas) && /boxContains\(e, pt, pad\)/.test(canvas), 'canvas.ts uses boxAnchors / nearestAnchor / boxContains, inline dups gone')
}
+// #493 — a deck authored OUTSIDE the editor (by hand, or an agent) names a
+// connector's from/to elements with stale or placeholder endpoints. Every
+// slide is routed at boot (main.ts bootWith) and on every 'doc' event
+// (editor.syncConnectors), not just the slide on screen.
+console.log('\n#493: every slide routes, from the model alone\n')
+{
+ const box = (id: string, x: number) => ({ id, type: 'shape', shape: 'rect', x, y: 300, w: 200, h: 100, rotation: 0, opacity: 1 })
+ const conn = (id: string, extra: Record<string, unknown> = {}) => ({ id, type: 'shape', shape: 'line', x: 5, y: 5, w: 10, h: 2, rotation: 0, opacity: 1, from: { el: 'A' }, to: { el: 'B' }, ...extra })
+ const deck: any = {
+ slides: [
+ { id: 's1', elements: [box('A', 100)] },
+ { id: 's2', elements: [box('A', 100), box('B', 800), conn('c')] },
+ { id: 's3', elements: [box('A', 100), conn('gone', { to: { el: 'nobody' } })] },
+ ],
+ layouts: [{ id: 'L', elements: [box('A', 100), box('B', 800), conn('lc')] }],
+ }
+ const ends = (el: any) => lineEndpoints(el)
+ ok(routeAllConnectors(deck) === true, 'routing a deck with stale endpoints reports a change')
+ const [a, b] = ends(deck.slides[1].elements[2])
+ ok(Math.abs(a.x - 300) < 1 && Math.abs(a.y - 350) < 1 && Math.abs(b.x - 800) < 1 && Math.abs(b.y - 350) < 1,
+ `slide 2 (not the first) lands on the two borders (${Math.round(a.x)},${Math.round(a.y)} → ${Math.round(b.x)},${Math.round(b.y)})`)
+ const [la, lb] = ends(deck.layouts[0].elements[2])
+ ok(Math.abs(la.x - 300) < 1 && Math.abs(lb.x - 800) < 1, 'a layout\'s connector is routed too')
+ const gone = deck.slides[2].elements[1]
+ ok(gone.to === undefined && gone.from?.el === 'A', 'a ref to an element that is not on the slide is dropped; the live one is kept')
+ const snap = JSON.stringify(deck)
+ ok(routeAllConnectors(deck) === false && JSON.stringify(deck) === snap, 'routing again changes nothing (idempotent — safe on every doc event)')
+ const one: any = { id: 'x', elements: [box('A', 100), box('B', 800), conn('c2')] }
+ ok(routeConnectors(one) === true, 'routeConnectors routes a single slide')
+ // the two entry points
+ const main = read('slides/src/main.ts')
+ const boot = main.slice(main.indexOf('function bootWith('), main.indexOf('function bootWith(') + 1200)
+ ok(/routeAllConnectors\(doc\)[\s\S]*audienceMode\(doc\)[\s\S]*playerMode\(doc\)[\s\S]*editorMode\(doc/.test(boot), 'boot routes the whole deck before editor, player or audience render anything')
+ const sync = editor.slice(editor.indexOf(' private syncConnectors() {'), editor.indexOf(' private syncConnectors() {') + 300)
+ ok(/routeAllConnectors\(this\.store\.doc\)/.test(sync) && !/this\.store\.slide/.test(sync), 'the editor re-routes the whole deck on a doc event, not only the slide on screen')
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
process.exit(failures ? 1 : 0)
diff --git a/slides/src/connectors.ts b/slides/src/connectors.ts
new file mode 100644
index 00000000..dad620eb
--- /dev/null
+++ b/slides/src/connectors.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Connector routing — pure model work, no DOM, so the boot path (main.ts) and
+// the rigs can run it without the editor (#493). The editor re-routes through
+// it on every 'doc' event; lineedit.ts re-exports the path-endpoint helpers so
+// its import sites are unchanged.
+
+import type { ShapeElement, Slide } from './model'
+import { movePathEnds, pathEnds } from './tips'
+import { boxCenter, connectorEndpoint, lineEndpoints, setLineEndpoints, type Pt } from '../../kernel/src/geom.ts'
+
+const rnd = (v: number) => Math.round(v * 100) / 100
+
+/** First and last on-curve points of an open path shape, in slide coords —
+ * exact (parsed, not sampled), for connector re-routing. */
+export function pathEndpoints(el: ShapeElement): [Pt, Pt] | null {
+ const ends = pathEnds(el.d ?? '')
+ if (!ends) return null
+ 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 out = (p: Pt): Pt => ({ x: el.x + (p.x - px) * sx, y: el.y + (p.y - py) * sy })
+ return [out(ends[0]), out(ends[1])]
+}
+
+/** Move an open path's ends to new slide-coord points (connector re-route,
+ * #302): interior anchors keep their positions exactly; the box and pathBox
+ * are renormalised to the on-curve points, the way setPathAnchors does. */
+export function setPathEndpoints(el: ShapeElement, a: Pt, b: Pt): void {
+ 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)
+ // slide → current path units
+ const toPath = (p: Pt): Pt => ({ x: px + (p.x - el.x) / sx, y: py + (p.y - el.y) / sy })
+ const moved = movePathEnds(el.d ?? '', toPath(a), toPath(b))
+ // renormalise: pathBox [0,0,w,h] over the on-curve points, at scale 1
+ const nodes = parseBezierPoints(moved)
+ if (!nodes.length) return
+ const abs = nodes.map((p) => ({ x: el.x + (p.x - px) * sx, y: el.y + (p.y - py) * sy }))
+ const minX = Math.min(...abs.map((p) => p.x))
+ const minY = Math.min(...abs.map((p) => p.y))
+ const w = Math.max(Math.max(...abs.map((p) => p.x)) - minX, 1)
+ const h = Math.max(Math.max(...abs.map((p) => p.y)) - minY, 1)
+ // re-express every coordinate (points AND handles) in the new box
+ const re = moved.replace(/-?\d*\.?\d+(?:e-?\d+)?/g, (() => {
+ let i = 0
+ return (tok: string) => {
+ const v = Number(tok)
+ const isX = i++ % 2 === 0
+ const s = isX ? rnd(el.x + (v - px) * sx - minX) : rnd(el.y + (v - py) * sy - minY)
+ return String(s)
+ }
+ })())
+ el.x = minX
+ el.y = minY
+ el.w = w
+ el.h = h
+ el.pathBox = [0, 0, w, h]
+ el.d = re
+}
+
+/**
+ * Route one slide's connectors — line and open-path shapes anchored to
+ * elements by from/to — onto their elements' borders, in place. Returns true
+ * if anything moved (or a dangling ref was dropped).
+ *
+ * DERIVED, never committed: every replica computes the same endpoints from the
+ * element boxes, so it is never an edit, never dirties the deck and never makes
+ * an undo step. A line moves its two endpoints; a curve (#302) moves its
+ * first/last anchor and keeps every interior point (tips.movePathEnds).
+ * Pure model work — no DOM — so the boot path routes a whole deck with it
+ * before anything renders (#493: a file authored outside the editor arrives
+ * with refs but stale endpoints, and nothing else would ever route it).
+ */
+export function routeConnectors(slide: Slide): boolean {
+ 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' && el.shape !== 'path')) continue
+ const c = el as 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 isPath = c.shape === 'path'
+ const pathEnds = isPath ? pathEndpoints(c) : null
+ if (isPath && !pathEnds) continue
+ const [a, b] = isPath ? pathEnds! : 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' → ride the border
+ // toward the other end (kernel geom: connectorEndpoint)
+ const na = fromBox ? connectorEndpoint(fromBox, c.from?.side, toBox ? boxCenter(toBox) : b) : a
+ const nb = toBox ? connectorEndpoint(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) {
+ if (isPath) setPathEndpoints(c, na, nb)
+ else setLineEndpoints(c, na, nb)
+ changed = true
+ }
+ }
+ return changed
+}
+
+/** Route every slide's connectors (and every layout's) — see routeConnectors. */
+export function routeAllConnectors(doc: { slides: Slide[]; layouts?: Slide[] }): boolean {
+ let changed = false
+ for (const s of [...doc.slides, ...(doc.layouts ?? [])]) if (routeConnectors(s)) changed = true
+ return changed
+}
+
+/** On-curve points of an M/C path string (path units). */
+function parseBezierPoints(d: string): Pt[] {
+ const out: Pt[] = []
+ const re = /([MC])\s*((?:-?\d*\.?\d+(?:e-?\d+)?[\s,]*)+)/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(d))) {
+ const nums = m[2].trim().split(/[\s,]+/).map(Number)
+ if (m[1] === 'M') out.push({ x: nums[0], y: nums[1] })
+ else out.push({ x: nums[4], y: nums[5] })
+ }
+ return out
+}
diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.ts
index 3f24d36a..06d99fe6 100644
--- a/slides/src/editor/editor.ts
+++ b/slides/src/editor/editor.ts
@@ -33,7 +33,7 @@ import { addVersion, clearRecovery, clearVersions, docContentKey, getRecovery, l
import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from './clipboard'
import { estimatedFrames, fencedElements, splitFences } from './codefence'
import { openSpeakerWindow, speakerIdleBody } from '../screens'
-import { boxCenter, connectorEndpoint, lineEndpoints, pathEndpoints, setLineEndpoints, setPathEndpoints } from './lineedit'
+import { routeAllConnectors } from '../connectors'
import { ICONS } from '../icons'
import { t, setLocale, locale, localeChoices, LOCALE_CHOICES, applyDirection, isRtl } from '../i18n'
import { stepOf } from '../steps'
@@ -2609,38 +2609,14 @@ export class Editor {
}
/** Re-route connectors (line and open-path 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). A line moves its two endpoints; a curve (#302) moves
- * its first/last anchor and keeps every interior point (tips.movePathEnds). */
+ * from/to) when anything moves — on EVERY slide, not just the one on screen:
+ * a deck replaced by JSON, a remote op on another slide, or an undo can
+ * leave any slide's connectors stale, and the thumbnails, the show and print
+ * all read the model. Derived, not committed — every replica computes the
+ * same endpoints from the element boxes (mirrors syncLinkedCharts); see
+ * connectors.ts routeConnectors. Boot routes the whole deck once (main.ts). */
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' && el.shape !== 'path')) 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 isPath = c.shape === 'path'
- const pathEnds = isPath ? pathEndpoints(c) : null
- if (isPath && !pathEnds) continue
- const [a, b] = isPath ? pathEnds! : 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' → ride the border
- // toward the other end (kernel geom: connectorEndpoint)
- const na = fromBox ? connectorEndpoint(fromBox, c.from?.side, toBox ? boxCenter(toBox) : b) : a
- const nb = toBox ? connectorEndpoint(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) {
- if (isPath) setPathEndpoints(c, na, nb)
- else setLineEndpoints(c, na, nb)
- changed = true
- }
- }
- if (changed) this.canvas.render()
+ if (routeAllConnectors(this.store.doc)) this.canvas.render()
}
// --- auto-save + crash recovery -----------------------------------------------
diff --git a/slides/src/editor/lineedit.ts b/slides/src/editor/lineedit.ts
index 43998051..24e5b4d5 100644
--- a/slides/src/editor/lineedit.ts
+++ b/slides/src/editor/lineedit.ts
@@ -15,7 +15,6 @@
import type { Store } from '../store'
import type { ShapeElement } from '../model'
import { anchorsToPath, parseAnchors, samplePathAnchors } from './patheditor'
-import { movePathEnds, pathEnds } from '../tips'
// The pure line/box/anchor geometry moved to the kernel (kernel/src/geom.ts) so
// bento/spaces diagrams share it. Re-exported here so `./lineedit` stays the
// import site for editor.ts / canvas.ts and behaviour is unchanged. What remains
@@ -24,6 +23,8 @@ import { movePathEnds, pathEnds } from '../tips'
import {
isLineLike, lineEndpoints, pathIsClosed, pathIsStraight, setLineEndpoints, type Pt,
} from '../../../kernel/src/geom.ts'
+// pure connector routing lives in ../connectors (DOM-free, used at boot)
+export { pathEndpoints, setPathEndpoints, routeConnectors, routeAllConnectors } from '../connectors'
export { boxCenter, borderPoint, sideMidpoint, boxAnchors, connectorEndpoint, nearestAnchor, boxContains, type ConnectorSide } from '../../../kernel/src/geom.ts'
export { isLineLike, lineEndpoints, pathIsClosed, pathIsStraight, setLineEndpoints }
@@ -61,67 +62,6 @@ export function setPathAnchors(el: ShapeElement, pts: Pt[], opts: { closed?: boo
: anchorsToPath(rel)) + (opts.closed ? ' Z' : '')
}
-/** First and last on-curve points of an open path shape, in slide coords —
- * exact (parsed, not sampled), for connector re-routing. */
-export function pathEndpoints(el: ShapeElement): [Pt, Pt] | null {
- const ends = pathEnds(el.d ?? '')
- if (!ends) return null
- 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 out = (p: Pt): Pt => ({ x: el.x + (p.x - px) * sx, y: el.y + (p.y - py) * sy })
- return [out(ends[0]), out(ends[1])]
-}
-
-/** Move an open path's ends to new slide-coord points (connector re-route,
- * #302): interior anchors keep their positions exactly; the box and pathBox
- * are renormalised to the on-curve points, the way setPathAnchors does. */
-export function setPathEndpoints(el: ShapeElement, a: Pt, b: Pt): void {
- 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)
- // slide → current path units
- const toPath = (p: Pt): Pt => ({ x: px + (p.x - el.x) / sx, y: py + (p.y - el.y) / sy })
- const moved = movePathEnds(el.d ?? '', toPath(a), toPath(b))
- // renormalise: pathBox [0,0,w,h] over the on-curve points, at scale 1
- const nodes = parseBezierPoints(moved)
- if (!nodes.length) return
- const abs = nodes.map((p) => ({ x: el.x + (p.x - px) * sx, y: el.y + (p.y - py) * sy }))
- const minX = Math.min(...abs.map((p) => p.x))
- const minY = Math.min(...abs.map((p) => p.y))
- const w = Math.max(Math.max(...abs.map((p) => p.x)) - minX, 1)
- const h = Math.max(Math.max(...abs.map((p) => p.y)) - minY, 1)
- // re-express every coordinate (points AND handles) in the new box
- const re = moved.replace(/-?\d*\.?\d+(?:e-?\d+)?/g, (() => {
- let i = 0
- return (tok: string) => {
- const v = Number(tok)
- const isX = i++ % 2 === 0
- const s = isX ? rnd(el.x + (v - px) * sx - minX) : rnd(el.y + (v - py) * sy - minY)
- return String(s)
- }
- })())
- el.x = minX
- el.y = minY
- el.w = w
- el.h = h
- el.pathBox = [0, 0, w, h]
- el.d = re
-}
-
-/** On-curve points of an M/C path string (path units). */
-function parseBezierPoints(d: string): Pt[] {
- const out: Pt[] = []
- const re = /([MC])\s*((?:-?\d*\.?\d+(?:e-?\d+)?[\s,]*)+)/g
- let m: RegExpExecArray | null
- while ((m = re.exec(d))) {
- const nums = m[2].trim().split(/[\s,]+/).map(Number)
- if (m[1] === 'M') out.push({ x: nums[0], y: nums[1] })
- else out.push({ x: nums[4], y: nums[5] })
- }
- return out
-}
-
export class LineEditor {
private overlay: SVGSVGElement | null = null
private elId = ''
diff --git a/slides/src/main.ts b/slides/src/main.ts
index 3938522c..7d971f7c 100644
--- a/slides/src/main.ts
+++ b/slides/src/main.ts
@@ -30,6 +30,7 @@ function reportGuard(dropped: Dropped[]) {
import { validateDoc, type ValidateOpts } from './validate'
import { buildSchema } from './schema'
import { resolveThemeRefs } from './palette'
+import { routeAllConnectors } from './connectors'
import { measureText, measureElement, type TextMeasureSpec } from './measure'
import { starterDoc } from './starterdeck'
import { injectFonts } from './fonts'
@@ -147,6 +148,12 @@ function bootWith(doc: BentoDoc, docIsFresh = false) {
// re-derives through the editor's `doc` hook; nothing else would visit a
// player file at all.
resolveThemeRefs(doc)
+ // Same reason, connectors (#493): a hand- or agent-written deck can name a
+ // connector's from/to elements with endpoints that are stale or placeholder.
+ // The editor re-routes on edits, but nothing routed a slide nobody touched,
+ // and a player or audience file never meets the editor at all. Derived, not
+ // an edit: it does not dirty the deck or make an undo step.
+ routeAllConnectors(doc)
if (doc.collab?.role === 'audience') audienceMode(doc)
else if (doc.readonly) playerMode(doc)
else editorMode(doc, docIsFresh)