Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
kernel: shared connector geometry (diagram-engine lift 3) (#619)
nyblneta90f18335baf
diff --git a/kernel/src/geom.ts b/kernel/src/geom.tsindex 3bffaf95..51db05b6 100644--- a/kernel/src/geom.ts+++ b/kernel/src/geom.ts@@ -305,3 +305,54 @@ export function sideMidpoint(b: Box, side: 'top' | 'right' | 'bottom' | 'left'):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 }}++// --- connectors -------------------------------------------------------------+// A connector is a line/path whose ends anchor to elements (model: from/to+// {el, side}). These are the pure routing + snapping primitives; the editor owns+// the derive-not-commit pass (syncConnectors), the draw tool and the handles.++/** A connector end's side: a named border midpoint, or 'auto' = ride the border+ * toward the other end (and, as a snap anchor, the box centre). */+export type ConnectorSide = 'auto' | 'top' | 'right' | 'bottom' | 'left'++/** Where a connector end sits on an anchored box: an explicit side pins to that+ * side's midpoint; 'auto' (or undefined) rides the border toward `toward` — the+ * other end's point. */+export function connectorEndpoint(b: Box, side: ConnectorSide | undefined, toward: Pt): Pt {+ return side && side !== 'auto' ? sideMidpoint(b, side) : borderPoint(b, toward)+}++/** The snap anchors a box offers a connector: the four side midpoints, then the+ * centre as 'auto'. Order is stable so nearest-anchor ties resolve the same way+ * everywhere. */+export function boxAnchors(b: Box): Array<{ side: ConnectorSide; pt: Pt }> {+ return [+ { side: 'top', pt: sideMidpoint(b, 'top') },+ { side: 'right', pt: sideMidpoint(b, 'right') },+ { side: 'bottom', pt: sideMidpoint(b, 'bottom') },+ { side: 'left', pt: sideMidpoint(b, 'left') },+ { side: 'auto', pt: boxCenter(b) },+ ]+}++/** The nearest anchor to `p` strictly within `tol` (euclidean), or null. First+ * anchor wins a tie, matching the draw tool's scan order. */+export function nearestAnchor(+ anchors: ReadonlyArray<{ side: ConnectorSide; pt: Pt }>,+ p: Pt,+ tol: number,+): { side: ConnectorSide; pt: Pt } | null {+ let best: { side: ConnectorSide; pt: Pt } | null = null+ let bd = tol+ for (const a of anchors) {+ const d = Math.hypot(p.x - a.pt.x, p.y - a.pt.y)+ if (d < bd) { bd = d; best = a }+ }+ return best+}++/** Is `p` inside `b` grown by `pad` on every side (inclusive)? */+export function boxContains(b: Box, p: Pt, pad = 0): boolean {+ return p.x >= b.x - pad && p.x <= b.x + b.w + pad+ && p.y >= b.y - pad && p.y <= b.y + b.h + pad+}diff --git a/scripts/test-slides-connectors.ts b/scripts/test-slides-connectors.tsindex 6d2a63c4..b418b444 100644--- a/scripts/test-slides-connectors.ts+++ b/scripts/test-slides-connectors.ts@@ -24,7 +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 { borderPoint, lineEndpoints, setLineEndpoints } from '../kernel/src/geom.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 = 0let checks = 0@@ -208,5 +208,85 @@ 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')+console.log('\nconnector routing + snapping moved to the kernel (byte-identical)\n')+// The diagram-engine lift (step 3) moved the connector SEMANTICS — border/side+// routing, the box anchor set, nearest-anchor snapping and the padded hit-test —+// into kernel/src/geom.ts, and slides' editor.ts/canvas.ts now call them. Pin the+// relocation to the exact inline code it replaced: reference implementations are+// verbatim what synced/anchorsFor/snap/elementAt computed before, and the kernel+// helpers must agree byte-for-byte across side, auto and free-end cases.+{+ type Side = ConnectorSide+ const SIDES: Array<Side | undefined> = [undefined, 'auto', 'top', 'right', 'bottom', 'left']+ // OLD inline code, verbatim:+ const oldEnd = (box: Box, side: Side | undefined, toward: GPt): GPt =>+ side && side !== 'auto' ? sideMidpoint(box, side) : borderPoint(box, toward)+ const oldAnchors = (e: Box) => [+ { 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 } },+ ]+ type Snap = { el: string; side: Side; pt: GPt } | null+ const oldSnap = (anchors: ReturnType<typeof oldAnchors>, p: GPt, tol: number): Snap => {+ let best: Snap = null+ let bd = tol+ for (const cand of anchors) {+ const d = Math.hypot(p.x - cand.pt.x, p.y - cand.pt.y)+ if (d < bd) { bd = d; best = { el: 'x', side: cand.side, pt: cand.pt } }+ }+ return best+ }+ const oldContains = (e: Box, pt: GPt, pad: number) =>+ pt.x >= e.x - pad && pt.x <= e.x + e.w + pad && pt.y >= e.y - pad && pt.y <= e.y + e.h + pad++ const eq = (a: GPt, b: GPt) => a.x === b.x && a.y === b.y+ // deterministic LCG so a failure reproduces+ let seed = 0x2f6df6+ const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff+ const box = (): Box => ({ x: rnd() * 2000 - 500, y: rnd() * 2000 - 500, w: 1 + rnd() * 600, h: 1 + rnd() * 400 })+ const pt = (): GPt => ({ x: rnd() * 2000 - 500, y: rnd() * 2000 - 500 })++ let endOk = true, anchorOk = true, snapOk = true, containsOk = true, scenarioOk = true+ for (let i = 0; i < 4000; i++) {+ const b = box(), toward = pt(), side = SIDES[Math.floor(rnd() * SIDES.length)]+ if (!eq(connectorEndpoint(b, side, toward), oldEnd(b, side, toward))) endOk = false+ const a1 = boxAnchors(b), a0 = oldAnchors(b)+ if (JSON.stringify(a1) !== JSON.stringify(a0)) anchorOk = false+ const p = pt(), tol = rnd() * 60+ const n1 = nearestAnchor(a1, p, tol), n0 = oldSnap(a0, p, tol)+ if (JSON.stringify(n1 && { side: n1.side, pt: n1.pt }) !== JSON.stringify(n0 && { side: n0.side, pt: n0.pt })) snapOk = false+ const pad = rnd() * 30+ if (boxContains(b, p, pad) !== oldContains(b, p, pad)) containsOk = false+ }+ ok(endOk, 'connectorEndpoint == the old inline end() across side / auto / free-end (4000 cases)')+ ok(anchorOk, 'boxAnchors == the old anchorsFor list, same order (4000 boxes)')+ ok(snapOk, 'nearestAnchor == the old snap selection, same tie-order (4000 points)')+ ok(containsOk, 'boxContains == the old elementAt predicate (4000 points × pads)')++ // full connector scenarios: two boxes, each kind of anchoring, na/nb both ways+ for (let i = 0; i < 2000; i++) {+ const fb = box(), tb = box()+ const [la, lb] = lineEndpoints({ x: Math.min(fb.x, tb.x), y: fb.y, w: 200, h: 4, rotation: 0 })+ for (const fs of SIDES) for (const ts of SIDES) {+ const na1 = connectorEndpoint(fb, fs, boxCenter(tb))+ const nb1 = connectorEndpoint(tb, ts, boxCenter(fb))+ const na0 = oldEnd(fb, fs, boxCenter(tb))+ const nb0 = oldEnd(tb, ts, boxCenter(fb))+ if (!eq(na1, na0) || !eq(nb1, nb0)) scenarioOk = false+ }+ // free end: one side anchored, the other rides toward the loose endpoint+ if (!eq(connectorEndpoint(fb, undefined, lb), oldEnd(fb, undefined, lb))) scenarioOk = false+ if (!eq(connectorEndpoint(tb, 'auto', la), oldEnd(tb, 'auto', la))) scenarioOk = false+ }+ ok(scenarioOk, 'two-box connectors route identically for every from/to side pair + a free end (2000 × 38)')++ // 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(/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')+}+console.log(`\n${checks - failures}/${checks} checks passed`)process.exit(failures ? 1 : 0)diff --git a/slides/src/editor/canvas.ts b/slides/src/editor/canvas.tsindex e6c40b47..a9a675d6 100644--- a/slides/src/editor/canvas.ts+++ b/slides/src/editor/canvas.ts@@ -15,7 +15,7 @@ import { bulletsToLists } from './bullets'import { clipboardToHtml } from './paste'import { execFormat, hideFormatBar, syncFormatBar } from './richtext'import { PathEditor } from './patheditor'-import { LineEditor, isLineLike, setLineEndpoints, setPathAnchors } from './lineedit'+import { LineEditor, isLineLike, setLineEndpoints, setPathAnchors, boxAnchors, nearestAnchor, boxContains } from './lineedit'import { CropEditor } from './cropedit'import { BezierEditor, isCurve } from './beziereditor'import { simplifyPoints } from './patheditor'@@ -1717,16 +1717,8 @@ export class SlideCanvas {}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 } },- ]- }+ const anchorsFor = (id: string) =>+ boxAnchors(this.store.slide.elements.find((x) => x.id === id)!)// visible anchor points on the element under the cursor (connector tool)const showAnchors = (p: Pt | null) => {dots.innerHTML = ''@@ -1748,13 +1740,10 @@ export class SlideCanvas {if (kind !== 'connector' && kind !== 'curve-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 }+ const near = nearestAnchor(anchorsFor(id), p, 30 * Math.max(k(), 1))+ return near+ ? { a: { el: id, side: near.side, pt: near.pt }, pt: near.pt }+ : { a: { el: id, side: 'auto', pt: p }, pt: p }}if (kind === 'poly') {@@ -1864,7 +1853,7 @@ export class SlideCanvas {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+ if (boxContains(e, pt, pad)) return e.id}return null}diff --git a/slides/src/editor/editor.ts b/slides/src/editor/editor.tsindex ef65ce55..8280ea51 100644--- a/slides/src/editor/editor.ts+++ b/slides/src/editor/editor.ts@@ -30,7 +30,7 @@ import { noteSavedFromWeb } from './returngate'import { addVersion, clearRecovery, clearVersions, docContentKey, getRecovery, listVersions, pruneOld, putRecovery, type Snapshot } from '../autosave'import { insertElements, insertSlides, parseClip, serializeElements, serializeSlides } from './clipboard'import { openSpeakerWindow, speakerIdleBody } from '../screens'-import { borderPoint, boxCenter, lineEndpoints, pathEndpoints, setLineEndpoints, setPathEndpoints, sideMidpoint } from './lineedit'+import { boxCenter, connectorEndpoint, lineEndpoints, pathEndpoints, setLineEndpoints, setPathEndpoints } from './lineedit'import { ICONS } from '../icons'import { t, setLocale, locale, localeChoices, LOCALE_CHOICES, applyDirection, isRtl } from '../i18n'import { stepOf } from '../steps'@@ -2540,11 +2540,10 @@ export class Editor {const [a, b] = isPath ? pathEnds! : lineEndpoints(c)const fromBox = c.from ? byId.get(c.from.el) : nullconst 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+ // 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) : bif (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)diff --git a/slides/src/editor/lineedit.ts b/slides/src/editor/lineedit.tsindex 25454f61..43998051 100644--- a/slides/src/editor/lineedit.ts+++ b/slides/src/editor/lineedit.ts@@ -24,7 +24,7 @@ import { movePathEnds, pathEnds } from '../tips'import {isLineLike, lineEndpoints, pathIsClosed, pathIsStraight, setLineEndpoints, type Pt,} from '../../../kernel/src/geom.ts'-export { boxCenter, borderPoint, sideMidpoint } from '../../../kernel/src/geom.ts'+export { boxCenter, borderPoint, sideMidpoint, boxAnchors, connectorEndpoint, nearestAnchor, boxContains, type ConnectorSide } from '../../../kernel/src/geom.ts'export { isLineLike, lineEndpoints, pathIsClosed, pathIsStraight, setLineEndpoints }const rnd = (v: number) => Math.round(v * 100) / 100