Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: shared shape rendering + tip catalogue → shape.ts / tips.ts (#616)

nyblnet202a53f04e45
diff --git a/kernel/src/shape.ts b/kernel/src/shape.ts
new file mode 100644
index 00000000..559a4fd0
--- /dev/null
+++ b/kernel/src/shape.ts
@@ -0,0 +1,282 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// SHARED SHAPE RENDERING — model → <svg> for rect / ellipse / triangle / arrow /
+// line / arbitrary path, with gradients, line-tip markers (the kernel tip
+// catalogue) and dash styles. Lifted out of slides (render.ts) so bento/spaces
+// diagrams render shapes through ONE engine. Step 2 of the diagram-engine move;
+// slides re-exports these from render.ts so its imports — and the pixels — are
+// unchanged.
+//
+// This builds DOM nodes (document.createElementNS), as the kernel UI primitives
+// already do, but reads NO layout and imports nothing from an app: the element
+// argument is a STRUCTURAL ShapeSpec (the fields the renderer reads), which a
+// slides ShapeElement satisfies, so the kernel depends on no app type. Geometry
+// math is in kernel/src/geom.ts; the tip catalogue + path-tip math in
+// kernel/src/tips.ts.
+
+import { shortenPathEnds, tipInsetPx, tipSpec, type TipKind } from './tips.ts'
+
+const SVG_NS = 'http://www.w3.org/2000/svg'
+
+/** A linear gradient fill (CSS angle convention: 0deg = bottom→top). */
+export interface GradientSpec {
+ angle: number
+ stops: Array<{ at: number; color: string }>
+}
+
+/** The shape fields the renderer reads — a slides ShapeElement satisfies this.
+ * `shape` is the closed kind set (not `string`) so the render switch stays
+ * exhaustive, as it was in render.ts. */
+export interface ShapeSpec {
+ shape: 'rect' | 'ellipse' | 'triangle' | 'arrow' | 'line' | 'path'
+ w: number
+ h: number
+ fill: string
+ stroke: string
+ strokeWidth: number
+ /** corner radius, rect only */
+ radius?: number
+ /** when set, wins over `fill` */
+ fillGradient?: GradientSpec
+ /** legacy numeric dash length (px) */
+ strokeDash?: number
+ /** stroke pattern; wins over strokeDash */
+ strokeStyle?: 'solid' | 'dashed' | 'dotted'
+ /** line/path only: tip decorations */
+ lineStart?: TipKind
+ lineEnd?: TipKind
+ /** arrow only: 2 = a head at both ends */
+ heads?: number
+ /** path only: SVG path data in the coordinate space given by pathBox */
+ d?: string
+ /** path only: [x, y, w, h] viewBox the path was authored in */
+ pathBox?: [number, number, number, number]
+}
+
+// Module-global id counters: svg url(#…) references resolve DOCUMENT-WIDE (the
+// same gradient/marker ids appear on the canvas, in sidebar thumbnails and in
+// the present overlay), so each minted id must be unique across them. One app
+// runs per page, so a shared counter here is still unique.
+let gradSeq = 0
+
+/** Gradient line endpoints (objectBoundingBox units) for a CSS-convention
+ * angle: 0deg points up, 90deg points right. Shared with morph tweening. */
+export function gradientLineCoords(angle: number) {
+ const rad = ((angle ?? 180) * Math.PI) / 180
+ const dx = Math.sin(rad) / 2
+ const dy = -Math.cos(rad) / 2
+ return { x1: 0.5 - dx, y1: 0.5 - dy, x2: 0.5 + dx, y2: 0.5 + dy }
+}
+
+/** CSS linear-gradient() from a GradientFill. CSS angle convention matches the
+ * model (0deg = bottom->top, 90deg = left->right), so pass angle straight. */
+export function cssLinearGradient(g: GradientSpec): string {
+ const stops = g.stops
+ .map((s) => `${s.color} ${Math.round(Math.min(Math.max(s.at, 0), 1) * 100)}%`)
+ .join(', ')
+ return `linear-gradient(${g.angle}deg, ${stops})`
+}
+
+/** Materialize a GradientFill as a <defs> gradient; returns its url() ref. */
+function gradientRef(svg: SVGSVGElement, g: GradientSpec): string {
+ const id = `bento-grad-${gradSeq++}`
+ const defs = document.createElementNS(SVG_NS, 'defs')
+ const lin = document.createElementNS(SVG_NS, 'linearGradient')
+ lin.setAttribute('id', id)
+ const { x1, y1, x2, y2 } = gradientLineCoords(g.angle)
+ lin.setAttribute('x1', String(x1))
+ lin.setAttribute('y1', String(y1))
+ lin.setAttribute('x2', String(x2))
+ lin.setAttribute('y2', String(y2))
+ for (const s of g.stops) {
+ const stop = document.createElementNS(SVG_NS, 'stop')
+ stop.setAttribute('offset', String(Math.min(Math.max(s.at, 0), 1)))
+ stop.setAttribute('stop-color', s.color)
+ lin.appendChild(stop)
+ }
+ defs.appendChild(lin)
+ svg.appendChild(defs)
+ return `url(#${id})`
+}
+
+/** stroke-dasharray for the element's line style (undefined = solid). */
+function dashArray(el: ShapeSpec, w: number): string | undefined {
+ if (el.strokeStyle === 'dashed') return `${Math.max(w * 2.4, 7)} ${Math.max(w * 1.8, 5)}`
+ if (el.strokeStyle === 'dotted') return `0.1 ${Math.max(w * 2.2, 5)}`
+ if (el.strokeStyle === 'solid') return undefined
+ if (el.strokeDash) return `${el.strokeDash} ${el.strokeDash}` // legacy numeric dash
+ return undefined
+}
+
+let markSeq = 0
+
+/** A line-tip marker in <defs>; sized in strokeWidth units, colored like the
+ * line. Geometry comes from tips.ts — one catalogue for every tip. A hollow
+ * tip is an outline in the line colour with an open interior. */
+function markerRef(svg: SVGSVGElement, kind: TipKind, color: string, start: boolean): string | null {
+ const spec = tipSpec(kind)
+ if (!spec) return null
+ const id = `bento-mark-${markSeq++}`
+ const marker = document.createElementNS(SVG_NS, 'marker')
+ marker.setAttribute('id', id)
+ marker.setAttribute('viewBox', '0 0 8 8')
+ marker.setAttribute('refX', String(spec.refX))
+ marker.setAttribute('refY', '4')
+ marker.setAttribute('orient', start ? 'auto-start-reverse' : 'auto')
+ marker.setAttribute('markerWidth', String(spec.size))
+ marker.setAttribute('markerHeight', String(spec.size))
+ const g = spec.geom
+ let tip: SVGElement
+ if (g.tag === 'path') {
+ tip = document.createElementNS(SVG_NS, 'path')
+ tip.setAttribute('d', g.d)
+ } else if (g.tag === 'circle') {
+ tip = document.createElementNS(SVG_NS, 'circle')
+ tip.setAttribute('cx', String(g.cx))
+ tip.setAttribute('cy', String(g.cy))
+ tip.setAttribute('r', String(g.r))
+ } else {
+ tip = document.createElementNS(SVG_NS, 'rect')
+ tip.setAttribute('x', String(g.x))
+ tip.setAttribute('y', String(g.y))
+ tip.setAttribute('width', String(g.w))
+ tip.setAttribute('height', String(g.h))
+ }
+ if (spec.hollow) {
+ tip.setAttribute('fill', 'none')
+ tip.setAttribute('stroke', color)
+ tip.setAttribute('stroke-width', '1.1')
+ tip.setAttribute('stroke-linejoin', 'round')
+ } else {
+ tip.setAttribute('fill', color)
+ }
+ marker.appendChild(tip)
+ let defs = svg.querySelector('defs')
+ if (!defs) {
+ defs = document.createElementNS(SVG_NS, 'defs')
+ svg.appendChild(defs)
+ }
+ defs.appendChild(marker)
+ return `url(#${id})`
+}
+
+export function shapeSvg(el: ShapeSpec): SVGSVGElement {
+ const svg = document.createElementNS(SVG_NS, 'svg')
+ const { w, h } = el
+ const sw = el.strokeWidth
+ const inset = sw / 2
+ svg.setAttribute('viewBox', `0 0 ${Math.max(w, 1)} ${Math.max(h, 1)}`)
+ svg.setAttribute('preserveAspectRatio', 'none')
+ svg.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;overflow:visible'
+
+ let node: SVGElement
+ switch (el.shape) {
+ case 'path': {
+ // arbitrary vector data, stretched from its authored viewBox into the box
+ if (el.pathBox) svg.setAttribute('viewBox', el.pathBox.join(' '))
+ node = document.createElementNS(SVG_NS, 'path')
+ let d = el.d ?? ''
+ // Tips on a curve (#302): SVG orients a marker along the path's own end
+ // tangent, so the head points the way the curve arrives. The endpoint is
+ // pulled back along that tangent by the tip's inset (tips.ts) so the
+ // point lands on the model's endpoint and a hollow head has no stroke
+ // inside it. Insets are in slide px; the path is in pathBox units, so
+ // divide by the box→slide scale (uniform for anything the editor draws —
+ // a connector is renormalised on every re-route).
+ if ((el.lineStart || el.lineEnd) && sw > 0 && !/z\s*$/i.test(d)) {
+ const [, , pw, ph] = el.pathBox ?? [0, 0, w, h]
+ const k = ((w / (pw || 1)) + (h / (ph || 1))) / 2 || 1
+ d = shortenPathEnds(d, tipInsetPx(el.lineStart, sw) / k, tipInsetPx(el.lineEnd, sw) / k)
+ const color = el.stroke && el.stroke !== 'transparent' ? el.stroke : el.fill
+ const mStart = el.lineStart ? markerRef(svg, el.lineStart, color, true) : null
+ const mEnd = el.lineEnd ? markerRef(svg, el.lineEnd, color, false) : null
+ if (mStart) node.setAttribute('marker-start', mStart)
+ if (mEnd) node.setAttribute('marker-end', mEnd)
+ if (tipSpec(el.lineStart)?.hollow || tipSpec(el.lineEnd)?.hollow) node.setAttribute('stroke-linecap', 'butt')
+ }
+ node.setAttribute('d', d)
+ if (sw > 0) node.setAttribute('vector-effect', 'non-scaling-stroke')
+ break
+ }
+ case 'rect': {
+ node = document.createElementNS(SVG_NS, 'rect')
+ node.setAttribute('x', String(inset))
+ node.setAttribute('y', String(inset))
+ node.setAttribute('width', String(Math.max(w - sw, 0)))
+ node.setAttribute('height', String(Math.max(h - sw, 0)))
+ if (el.radius) node.setAttribute('rx', String(el.radius))
+ break
+ }
+ case 'ellipse': {
+ node = document.createElementNS(SVG_NS, 'ellipse')
+ node.setAttribute('cx', String(w / 2))
+ node.setAttribute('cy', String(h / 2))
+ node.setAttribute('rx', String(Math.max(w / 2 - inset, 0)))
+ node.setAttribute('ry', String(Math.max(h / 2 - inset, 0)))
+ break
+ }
+ case 'triangle': {
+ node = document.createElementNS(SVG_NS, 'polygon')
+ node.setAttribute('points', `${w / 2},${inset} ${w - inset},${h - inset} ${inset},${h - inset}`)
+ break
+ }
+ case 'arrow': {
+ // right-pointing arrow: shaft + head, proportional to the box
+ node = document.createElementNS(SVG_NS, 'polygon')
+ const shaftH = h * 0.44
+ const y0 = (h - shaftH) / 2
+ if (el.heads === 2) {
+ // a head at BOTH ends (#304): the same head, mirrored, symmetric about
+ // the box centre. Still `shape: 'arrow'` — a shell that predates
+ // `heads` draws the single arrow. Morph: the polygon's points are not
+ // tweened (no shape geometry is); a one-head ↔ two-head morph tweens
+ // the box and fill and the point list snaps at the swap.
+ const headW = Math.min(w * 0.3, h)
+ node.setAttribute(
+ 'points',
+ `0,${h / 2} ${headW},0 ${headW},${y0} ${w - headW},${y0} ${w - headW},0 ${w},${h / 2} ${w - headW},${h} ${w - headW},${y0 + shaftH} ${headW},${y0 + shaftH} ${headW},${h}`,
+ )
+ break
+ }
+ const headW = Math.min(w * 0.38, h)
+ node.setAttribute(
+ 'points',
+ `0,${y0} ${w - headW},${y0} ${w - headW},0 ${w},${h / 2} ${w - headW},${h} ${w - headW},${y0 + shaftH} 0,${y0 + shaftH}`,
+ )
+ break
+ }
+ case 'line': {
+ node = document.createElementNS(SVG_NS, 'line')
+ const lw = Math.max(sw, 2)
+ // inset the endpoints so the tip's point lands on the box edge (tips.ts:
+ // the three original kinds keep their 2.6 — every old deck unchanged)
+ node.setAttribute('x1', String(tipInsetPx(el.lineStart, lw)))
+ node.setAttribute('y1', String(h / 2))
+ node.setAttribute('x2', String(w - tipInsetPx(el.lineEnd, lw)))
+ node.setAttribute('y2', String(h / 2))
+ node.setAttribute('stroke', el.fill)
+ node.setAttribute('stroke-width', String(lw))
+ const hollow = tipSpec(el.lineStart)?.hollow || tipSpec(el.lineEnd)?.hollow
+ node.setAttribute('stroke-linecap', el.strokeStyle === 'dashed' || hollow ? 'butt' : 'round')
+ const lineDash = dashArray(el, lw)
+ if (lineDash) node.setAttribute('stroke-dasharray', lineDash)
+ const mStart = el.lineStart ? markerRef(svg, el.lineStart, el.fill, true) : null
+ const mEnd = el.lineEnd ? markerRef(svg, el.lineEnd, el.fill, false) : null
+ if (mStart) node.setAttribute('marker-start', mStart)
+ if (mEnd) node.setAttribute('marker-end', mEnd)
+ svg.appendChild(node)
+ return svg
+ }
+ }
+ node.setAttribute('fill', el.fillGradient?.stops.length ? gradientRef(svg, el.fillGradient) : el.fill)
+ if (el.stroke && el.stroke !== 'transparent' && sw > 0) {
+ node.setAttribute('stroke', el.stroke)
+ node.setAttribute('stroke-width', String(sw))
+ const dash = dashArray(el, sw)
+ if (dash) node.setAttribute('stroke-dasharray', dash)
+ if (el.strokeStyle === 'dotted') node.setAttribute('stroke-linecap', 'round')
+ }
+ svg.appendChild(node)
+ return svg
+}
diff --git a/kernel/src/tips.ts b/kernel/src/tips.ts
new file mode 100644
index 00000000..8472a37c
--- /dev/null
+++ b/kernel/src/tips.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * Line tips — the ONE catalogue behind `lineStart`/`lineEnd` (discussion
+ * #303): the model's allowed values, the shape gate, the panel's options and
+ * the renderer's marker geometry all read this list, so a tip cannot exist in
+ * one place and not another. Moved into the kernel with the diagram-engine lift
+ * so bento/spaces diagram connectors share the same catalogue and arrowheads;
+ * slides re-exports it from its old path (slides/src/tips.ts).
+ *
+ * Geometry lives in an 8×8 marker frame, the line arriving from the left and
+ * the tip pointing +x. `size` is the marker's width in STROKE units (SVG
+ * `markerUnits="strokeWidth"`), `refX` the frame x that sits on the line's
+ * end, `tipX` where the point is. A hollow tip needs the line to STOP at the
+ * head's back edge — otherwise the stroke shows through the hollow — so the
+ * renderer insets the endpoint by `inset` stroke units, which for the new
+ * kinds is exactly the distance from the line end to the point. The three
+ * original kinds keep their historic numbers (2.6 inset, refX inside the
+ * head) so every existing deck renders byte-identically.
+ *
+ * DEGRADE, stated plainly: in 1.1.0 and older the renderer matches only
+ * 'arrow' and 'dot' and draws a BAR for anything else — so a deck carrying
+ * one of the seven newer tips shows a bar at that end in those shells, not a
+ * plain end. Nothing throws; the deck opens.
+ *
+ * Also here, because a curved connector needs it (#302): the END TANGENT of
+ * a cubic path, so a tip on a curve points along the curve and the endpoint
+ * is inset along it, not along the chord.
+ */
+
+import { parseBezier, serializeBezier, type BezNode, type Pt } from './geom.ts'
+
+export type TipKind = 'none' | 'arrow' | 'dot' | 'bar' | 'arrow-open' | 'triangle' | 'triangle-open' | 'diamond' | 'diamond-open' | 'square' | 'circle-open'
+
+export interface TipSpec {
+ kind: TipKind
+ /** panel label, English key for t() */
+ label: string
+ /** marker width in stroke units */
+ size: number
+ refX: number
+ tipX: number
+ /** 'path' | 'circle' | 'rect' + geometry in the 8×8 frame */
+ geom: { tag: 'path'; d: string } | { tag: 'circle'; cx: number; cy: number; r: number } | { tag: 'rect'; x: number; y: number; w: number; h: number }
+ /** drawn as an outline in the line's colour, interior left open */
+ hollow?: boolean
+ /** endpoint inset in stroke units; legacy kinds pin 2.6 */
+ inset: number
+}
+
+const geometric = (tipX: number, refX: number, size: number) => Math.round(((tipX - refX) * size / 8) * 100) / 100
+
+export const TIPS: ReadonlyArray<TipSpec> = [
+ { kind: 'none', label: 'none', size: 0, refX: 0, tipX: 0, geom: { tag: 'path', d: '' }, inset: 0 },
+ // the original three — numbers unchanged since 1.0.2
+ { kind: 'arrow', label: 'Arrow', size: 5.5, refX: 6.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0 0.4 L 7.6 4 L 0 7.6 Z' }, inset: 2.6 },
+ { kind: 'dot', label: 'Dot', size: 5.5, refX: 4, tipX: 6.6, geom: { tag: 'circle', cx: 4, cy: 4, r: 2.6 }, inset: 2.6 },
+ { kind: 'bar', label: 'Bar', size: 5.5, refX: 4, tipX: 4.8, geom: { tag: 'rect', x: 3.2, y: 0.4, w: 1.6, h: 7.2 }, inset: 2.6 },
+ // #303
+ { kind: 'arrow-open', label: 'Open arrow', size: 5.5, refX: 7.2, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 0.4 L 7.6 4 L 0.4 7.6' }, hollow: true, inset: geometric(7.6, 7.2, 5.5) },
+ { kind: 'triangle', label: 'Triangle', size: 7.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 0.4 L 7.6 4 L 0.4 7.6 Z' }, inset: geometric(7.6, 0.4, 7.5) },
+ { kind: 'triangle-open', label: 'Hollow triangle', size: 7.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 0.4 L 7.6 4 L 0.4 7.6 Z' }, hollow: true, inset: geometric(7.6, 0.4, 7.5) },
+ { kind: 'diamond', label: 'Diamond', size: 6.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 4 L 4 0.8 L 7.6 4 L 4 7.2 Z' }, inset: geometric(7.6, 0.4, 6.5) },
+ { kind: 'diamond-open', label: 'Hollow diamond', size: 6.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 4 L 4 0.8 L 7.6 4 L 4 7.2 Z' }, hollow: true, inset: geometric(7.6, 0.4, 6.5) },
+ { kind: 'square', label: 'Square', size: 5.5, refX: 1.2, tipX: 7.6, geom: { tag: 'rect', x: 1.2, y: 0.8, w: 6.4, h: 6.4 }, inset: geometric(7.6, 1.2, 5.5) },
+ { kind: 'circle-open', label: 'Hollow circle', size: 5.5, refX: 0.8, tipX: 7.2, geom: { tag: 'circle', cx: 4, cy: 4, r: 3.2 }, hollow: true, inset: geometric(7.2, 0.8, 5.5) },
+]
+
+export const TIP_KINDS: ReadonlyArray<TipKind> = TIPS.map((t) => t.kind)
+
+export const tipSpec = (kind: string | undefined): TipSpec | undefined =>
+ kind && kind !== 'none' ? TIPS.find((t) => t.kind === kind) : undefined
+
+/** Endpoint inset for a tip, in px, given the drawn stroke width. */
+export const tipInsetPx = (kind: string | undefined, strokePx: number): number => (tipSpec(kind)?.inset ?? 0) * strokePx
+
+/** Unit tangent at a path's start or end: from the end node's own handle,
+ * else the neighbour's handle, else the chord — so a degenerate (zero
+ * length) handle never yields a zero vector. `null` for fewer than 2 nodes. */
+export function endTangent(nodes: ReadonlyArray<BezNode>, atEnd: boolean): Pt | null {
+ if (nodes.length < 2) return null
+ const a = atEnd ? nodes[nodes.length - 2] : nodes[1]
+ const b = atEnd ? nodes[nodes.length - 1] : nodes[0]
+ // direction pointing OUT of the path at that end
+ const candidates: Array<[Pt, Pt]> = atEnd
+ ? [[b.in ?? b.p, b.p], [a.out ?? a.p, b.p], [a.p, b.p]]
+ : [[b.out ?? b.p, b.p], [a.in ?? a.p, b.p], [a.p, b.p]]
+ for (const [from, to] of candidates) {
+ const dx = to.x - from.x
+ const dy = to.y - from.y
+ const len = Math.hypot(dx, dy)
+ if (len > 1e-6) return { x: dx / len, y: dy / len }
+ }
+ return null
+}
+
+/** The path `d` with each tipped end pulled back along its tangent by the
+ * given amounts (path units), so a marker's point lands where the model's
+ * endpoint is and a hollow head has no stroke inside it. Interior nodes are
+ * untouched; the end node's handle moves with it so the curve keeps its
+ * arrival direction. */
+export function shortenPathEnds(d: string, startBy: number, endBy: number): string {
+ if (!(startBy > 0) && !(endBy > 0)) return d
+ const { nodes, closed } = parseBezier(d)
+ if (closed || nodes.length < 2) return d
+ const pull = (i: number, by: number, atEnd: boolean) => {
+ const t = endTangent(nodes, atEnd)
+ if (!t || !(by > 0)) return
+ const n = nodes[i]
+ const dx = -t.x * by
+ const dy = -t.y * by
+ const h = atEnd ? n.in : n.out
+ nodes[i] = { ...n, p: { x: n.p.x + dx, y: n.p.y + dy }, ...(h ? (atEnd ? { in: { x: h.x + dx, y: h.y + dy } } : { out: { x: h.x + dx, y: h.y + dy } }) : {}) }
+ }
+ pull(0, startBy, false)
+ pull(nodes.length - 1, endBy, true)
+ return serializeBezier(nodes, false)
+}
+
+/**
+ * Move a path's first and/or last on-curve point (path units) for connector
+ * re-routing (#302). The moved node's handle is recomputed the auto way —
+ * one sixth of the way toward its neighbour, the Catmull-Rom end rule the
+ * curve editor uses for untouched nodes — so the curve leaves the new anchor
+ * smoothly; the neighbour's facing handle is recomputed only if it was auto
+ * itself (matched the rule before the move), so a hand-shaped interior point
+ * keeps its tangents. Every other node is returned byte-identical.
+ */
+export function movePathEnds(d: string, start: Pt | null, end: Pt | null): string {
+ const { nodes, closed } = parseBezier(d)
+ if (closed || nodes.length < 2 || (!start && !end)) return d
+ const sixth = (from: Pt, to: Pt): Pt => ({ x: from.x + (to.x - from.x) / 6, y: from.y + (to.y - from.y) / 6 })
+ const near = (a: Pt | undefined, b: Pt) => !!a && Math.abs(a.x - b.x) < 0.02 && Math.abs(a.y - b.y) < 0.02
+ const catmullIn = (i: number): Pt => {
+ // Catmull-Rom incoming handle at node i (P(i) - (P(i+1) - P(i-1)) / 6)
+ const P = (k: number) => nodes[Math.max(0, Math.min(nodes.length - 1, k))].p
+ return { x: P(i).x - (P(i + 1).x - P(i - 1).x) / 6, y: P(i).y - (P(i + 1).y - P(i - 1).y) / 6 }
+ }
+ const catmullOut = (i: number): Pt => {
+ const P = (k: number) => nodes[Math.max(0, Math.min(nodes.length - 1, k))].p
+ return { x: P(i).x + (P(i + 1).x - P(i - 1).x) / 6, y: P(i).y + (P(i + 1).y - P(i - 1).y) / 6 }
+ }
+ if (start) {
+ const nb = nodes[1]
+ const nbWasAuto = near(nb.in, catmullIn(1))
+ nodes[0] = { p: start, out: sixth(start, nb.p) }
+ if (nbWasAuto) nodes[1] = { ...nb, in: catmullIn(1) }
+ }
+ if (end) {
+ const last = nodes.length - 1
+ const nb = nodes[last - 1]
+ const nbWasAuto = near(nb.out, catmullOut(last - 1))
+ nodes[last] = { p: end, in: sixth(end, nb.p) }
+ if (nbWasAuto) nodes[last - 1] = { ...nb, out: catmullOut(last - 1) }
+ }
+ return serializeBezier(nodes, false)
+}
+
+/** First and last on-curve points of a path (path units). */
+export function pathEnds(d: string): [Pt, Pt] | null {
+ const { nodes } = parseBezier(d)
+ if (nodes.length < 2) return null
+ return [nodes[0].p, nodes[nodes.length - 1].p]
+}
diff --git a/scripts/test-slides-connectors.ts b/scripts/test-slides-connectors.ts
index 6e4b4692..6d2a63c4 100644
--- a/scripts/test-slides-connectors.ts
+++ b/scripts/test-slides-connectors.ts
@@ -51,7 +51,11 @@ const editor = read('slides/src/editor/editor.ts')
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')
-ok(/const spec = tipSpec\(kind\)/.test(render) && !/'M 0 0\.4 L 7\.6 4 L 0 7\.6 Z'/.test(render), 'the renderer builds markers from the catalogue, not from its own geometry')
+// shapeSvg + markerRef moved to the kernel (kernel/src/shape.ts) with step 2 of
+// the diagram-engine lift; the tip catalogue to kernel/src/tips.ts. Source pins
+// that checked the moved code follow it there.
+const shape = read('kernel/src/shape.ts')
+ok(/const spec = tipSpec\(kind\)/.test(shape) && !/'M 0 0\.4 L 7\.6 4 L 0 7\.6 Z'/.test(shape), 'the shape renderer builds markers from the catalogue, not from its own geometry')
ok(new Set(TIP_KINDS).size === TIP_KINDS.length, 'no duplicate kinds')
ok(TIPS.every((s) => s.label.length > 0), 'every tip has a panel label')
@@ -70,7 +74,7 @@ ok(close(tipInsetPx('triangle-open', 3), tipSpec('triangle-open')!.inset * 3), '
ok(tipInsetPx(undefined, 3) === 0 && tipInsetPx('none', 3) === 0, 'no tip → no inset')
console.log('\nthe double arrow\n')
-ok(/if \(el\.heads === 2\) \{/.test(render.slice(render.indexOf("case 'arrow': {"), render.indexOf("case 'line': {"))), 'render.ts draws the two-headed polygon inside the ARROW branch')
+ok(/if \(el\.heads === 2\) \{/.test(shape.slice(shape.indexOf("case 'arrow': {"), shape.indexOf("case 'line': {"))), 'shape.ts draws the two-headed polygon inside the ARROW branch')
ok(/heads: num\(2, 2\)/.test(gate), 'the gate admits heads: 2 on a shape')
ok(/heads\?: 2/.test(model), 'the model has heads?: 2 on ShapeElement')
ok(!/arrow2/.test(model) && !/arrow2/.test(gate) && !/'arrow2'/.test(render), 'no new shape kind anywhere — arrow2 is gone')
@@ -127,7 +131,7 @@ for (const s of TIPS) {
if (['none', 'arrow', 'dot', 'bar'].includes(s.kind)) continue
ok(frozenMarker(s.kind) === 'bar', `${s.kind}: 1.1.0 draws a BAR at that end (not a plain end) — no throw`)
}
-ok(/in 1\.1\.0 and older the renderer matches only\n \* 'arrow' and 'dot' and draws a BAR/.test(read('slides/src/tips.ts')), 'tips.ts states the degrade')
+ok(/in 1\.1\.0 and older the renderer matches only\n \* 'arrow' and 'dot' and draws a BAR/.test(read('kernel/src/tips.ts')), 'tips.ts states the degrade')
ok(/those shells draw a bar where a\n new tip should be; a double arrow shows there as a single one/.test(read('CHANGELOG.md')), 'the changelog states the same degrade, no softer')
console.log('\nend tangent\n')
@@ -184,9 +188,21 @@ console.log('\nthe legacy straight connector\n')
ok(el.w === 100 && el.x === 0 && el.y === -2 && el.rotation === 0, 'setLineEndpoints rebuilds the box from two endpoints')
const bp = borderPoint({ x: 0, y: 0, w: 100, h: 100 }, { x: 200, y: 50 })
ok(bp.x === 100 && bp.y === 50, 'borderPoint lands on the border along the ray to the target')
+ // rotated + diagonal cases (slides review on #592 asked for coverage beyond rotation 0)
+ const vert = lineEndpoints({ x: 0, y: 0, w: 100, h: 4, rotation: 90 })
+ const approx = (a: number, b: number) => Math.abs(a - b) < 1e-6
+ ok(approx(vert[0].x, 50) && approx(vert[0].y, -48) && approx(vert[1].x, 50) && approx(vert[1].y, 52),
+ 'lineEndpoints at 90° gives a vertical pair about the box centre')
+ // deno-lint-ignore no-explicit-any
+ const rot: any = { h: 4 }
+ setLineEndpoints(rot, { x: 50, y: 0 }, { x: 50, y: 100 })
+ ok(rot.w === 100 && approx(rot.rotation, 90) && approx(rot.x, 0) && approx(rot.y, 48),
+ 'setLineEndpoints encodes a vertical drag as rotation 90')
+ const diag = borderPoint({ x: 0, y: 0, w: 100, h: 100 }, { x: 200, y: 200 })
+ ok(diag.x === 100 && diag.y === 100, 'borderPoint on a diagonal ray lands on the corner')
}
// 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(render) && /tipInsetPx\(el\.lineStart, lw\)/.test(render), 'a line insets by the catalogue — 2.6 for the original three (asserted above)')
+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')
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')
diff --git a/slides/src/render.ts b/slides/src/render.ts
index fa1586ea..3a00475a 100644
--- a/slides/src/render.ts
+++ b/slides/src/render.ts
@@ -4,13 +4,12 @@
// editor canvas, sidebar thumbnails, and Reveal.js sections.
import { offlineEnabled, isRemoteUrl, remoteSrcBlocked } from '../../kernel/src/net.ts'
-import type { BentoDoc, EmbedElement, ShapeElement, Slide, SlideElement, SvgElement, TableElement } from './model'
+import type { BentoDoc, EmbedElement, Slide, SlideElement, SvgElement, TableElement } from './model'
import { morphKey, paginates, isWebUrl } from './model'
import { chartSnapshotSvg } from './charts'
import { renderMath as mathsLite, mathError } from './maths/index.ts'
import { resolveMathHtml } from './maths/delimiters.ts'
import { renderCodeInto } from './code'
-import { tipSpec, tipInsetPx, shortenPathEnds } from './tips'
import { formatDate } from './datefmt'
import { cropImgStyle, isIdentityCrop } from './crop'
@@ -251,231 +250,12 @@ export function applyElementFrame(node: HTMLElement, el: SlideElement) {
}
}
-// Gradient ids must be unique per rendered instance: the same element renders
-// on the canvas, in sidebar thumbnails and in the present overlay, and svg
-// url(#…) references resolve document-wide.
-let gradSeq = 0
-
-/** Gradient line endpoints (objectBoundingBox units) for a CSS-convention
- * angle: 0deg points up, 90deg points right. Shared with morph tweening. */
-export function gradientLineCoords(angle: number) {
- const rad = ((angle ?? 180) * Math.PI) / 180
- const dx = Math.sin(rad) / 2
- const dy = -Math.cos(rad) / 2
- return { x1: 0.5 - dx, y1: 0.5 - dy, x2: 0.5 + dx, y2: 0.5 + dy }
-}
-
-/** CSS linear-gradient() from a GradientFill. CSS angle convention matches the
- * model (0deg = bottom->top, 90deg = left->right), so pass angle straight. */
-export function cssLinearGradient(g: NonNullable<ShapeElement['fillGradient']>): string {
- const stops = g.stops
- .map((s) => `${s.color} ${Math.round(Math.min(Math.max(s.at, 0), 1) * 100)}%`)
- .join(', ')
- return `linear-gradient(${g.angle}deg, ${stops})`
-}
-
-/** Materialize a GradientFill as a <defs> gradient; returns its url() ref. */
-function gradientRef(svg: SVGSVGElement, g: NonNullable<ShapeElement['fillGradient']>): string {
- const id = `bento-grad-${gradSeq++}`
- const defs = document.createElementNS(SVG_NS, 'defs')
- const lin = document.createElementNS(SVG_NS, 'linearGradient')
- lin.setAttribute('id', id)
- const { x1, y1, x2, y2 } = gradientLineCoords(g.angle)
- lin.setAttribute('x1', String(x1))
- lin.setAttribute('y1', String(y1))
- lin.setAttribute('x2', String(x2))
- lin.setAttribute('y2', String(y2))
- for (const s of g.stops) {
- const stop = document.createElementNS(SVG_NS, 'stop')
- stop.setAttribute('offset', String(Math.min(Math.max(s.at, 0), 1)))
- stop.setAttribute('stop-color', s.color)
- lin.appendChild(stop)
- }
- defs.appendChild(lin)
- svg.appendChild(defs)
- return `url(#${id})`
-}
-
-/** stroke-dasharray for the element's line style (undefined = solid). */
-function dashArray(el: ShapeElement, w: number): string | undefined {
- if (el.strokeStyle === 'dashed') return `${Math.max(w * 2.4, 7)} ${Math.max(w * 1.8, 5)}`
- if (el.strokeStyle === 'dotted') return `0.1 ${Math.max(w * 2.2, 5)}`
- if (el.strokeStyle === 'solid') return undefined
- if (el.strokeDash) return `${el.strokeDash} ${el.strokeDash}` // legacy numeric dash
- return undefined
-}
-
-let markSeq = 0
-
-/** A line-tip marker in <defs>; sized in strokeWidth units, colored like the
- * line. Geometry comes from tips.ts — one catalogue for every tip. A hollow
- * tip is an outline in the line colour with an open interior. */
-function markerRef(svg: SVGSVGElement, kind: NonNullable<ShapeElement['lineStart']>, color: string, start: boolean): string | null {
- const spec = tipSpec(kind)
- if (!spec) return null
- const id = `bento-mark-${markSeq++}`
- const marker = document.createElementNS(SVG_NS, 'marker')
- marker.setAttribute('id', id)
- marker.setAttribute('viewBox', '0 0 8 8')
- marker.setAttribute('refX', String(spec.refX))
- marker.setAttribute('refY', '4')
- marker.setAttribute('orient', start ? 'auto-start-reverse' : 'auto')
- marker.setAttribute('markerWidth', String(spec.size))
- marker.setAttribute('markerHeight', String(spec.size))
- const g = spec.geom
- let tip: SVGElement
- if (g.tag === 'path') {
- tip = document.createElementNS(SVG_NS, 'path')
- tip.setAttribute('d', g.d)
- } else if (g.tag === 'circle') {
- tip = document.createElementNS(SVG_NS, 'circle')
- tip.setAttribute('cx', String(g.cx))
- tip.setAttribute('cy', String(g.cy))
- tip.setAttribute('r', String(g.r))
- } else {
- tip = document.createElementNS(SVG_NS, 'rect')
- tip.setAttribute('x', String(g.x))
- tip.setAttribute('y', String(g.y))
- tip.setAttribute('width', String(g.w))
- tip.setAttribute('height', String(g.h))
- }
- if (spec.hollow) {
- tip.setAttribute('fill', 'none')
- tip.setAttribute('stroke', color)
- tip.setAttribute('stroke-width', '1.1')
- tip.setAttribute('stroke-linejoin', 'round')
- } else {
- tip.setAttribute('fill', color)
- }
- marker.appendChild(tip)
- let defs = svg.querySelector('defs')
- if (!defs) {
- defs = document.createElementNS(SVG_NS, 'defs')
- svg.appendChild(defs)
- }
- defs.appendChild(marker)
- return `url(#${id})`
-}
-
-export function shapeSvg(el: ShapeElement): SVGSVGElement {
- const svg = document.createElementNS(SVG_NS, 'svg')
- const { w, h } = el
- const sw = el.strokeWidth
- const inset = sw / 2
- svg.setAttribute('viewBox', `0 0 ${Math.max(w, 1)} ${Math.max(h, 1)}`)
- svg.setAttribute('preserveAspectRatio', 'none')
- svg.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;overflow:visible'
-
- let node: SVGElement
- switch (el.shape) {
- case 'path': {
- // arbitrary vector data, stretched from its authored viewBox into the box
- if (el.pathBox) svg.setAttribute('viewBox', el.pathBox.join(' '))
- node = document.createElementNS(SVG_NS, 'path')
- let d = el.d ?? ''
- // Tips on a curve (#302): SVG orients a marker along the path's own end
- // tangent, so the head points the way the curve arrives. The endpoint is
- // pulled back along that tangent by the tip's inset (tips.ts) so the
- // point lands on the model's endpoint and a hollow head has no stroke
- // inside it. Insets are in slide px; the path is in pathBox units, so
- // divide by the box→slide scale (uniform for anything the editor draws —
- // a connector is renormalised on every re-route).
- if ((el.lineStart || el.lineEnd) && sw > 0 && !/z\s*$/i.test(d)) {
- const [, , pw, ph] = el.pathBox ?? [0, 0, w, h]
- const k = ((w / (pw || 1)) + (h / (ph || 1))) / 2 || 1
- d = shortenPathEnds(d, tipInsetPx(el.lineStart, sw) / k, tipInsetPx(el.lineEnd, sw) / k)
- const color = el.stroke && el.stroke !== 'transparent' ? el.stroke : el.fill
- const mStart = el.lineStart ? markerRef(svg, el.lineStart, color, true) : null
- const mEnd = el.lineEnd ? markerRef(svg, el.lineEnd, color, false) : null
- if (mStart) node.setAttribute('marker-start', mStart)
- if (mEnd) node.setAttribute('marker-end', mEnd)
- if (tipSpec(el.lineStart)?.hollow || tipSpec(el.lineEnd)?.hollow) node.setAttribute('stroke-linecap', 'butt')
- }
- node.setAttribute('d', d)
- if (sw > 0) node.setAttribute('vector-effect', 'non-scaling-stroke')
- break
- }
- case 'rect': {
- node = document.createElementNS(SVG_NS, 'rect')
- node.setAttribute('x', String(inset))
- node.setAttribute('y', String(inset))
- node.setAttribute('width', String(Math.max(w - sw, 0)))
- node.setAttribute('height', String(Math.max(h - sw, 0)))
- if (el.radius) node.setAttribute('rx', String(el.radius))
- break
- }
- case 'ellipse': {
- node = document.createElementNS(SVG_NS, 'ellipse')
- node.setAttribute('cx', String(w / 2))
- node.setAttribute('cy', String(h / 2))
- node.setAttribute('rx', String(Math.max(w / 2 - inset, 0)))
- node.setAttribute('ry', String(Math.max(h / 2 - inset, 0)))
- break
- }
- case 'triangle': {
- node = document.createElementNS(SVG_NS, 'polygon')
- node.setAttribute('points', `${w / 2},${inset} ${w - inset},${h - inset} ${inset},${h - inset}`)
- break
- }
- case 'arrow': {
- // right-pointing arrow: shaft + head, proportional to the box
- node = document.createElementNS(SVG_NS, 'polygon')
- const shaftH = h * 0.44
- const y0 = (h - shaftH) / 2
- if (el.heads === 2) {
- // a head at BOTH ends (#304): the same head, mirrored, symmetric about
- // the box centre. Still `shape: 'arrow'` — a shell that predates
- // `heads` draws the single arrow. Morph: the polygon's points are not
- // tweened (no shape geometry is); a one-head ↔ two-head morph tweens
- // the box and fill and the point list snaps at the swap.
- const headW = Math.min(w * 0.3, h)
- node.setAttribute(
- 'points',
- `0,${h / 2} ${headW},0 ${headW},${y0} ${w - headW},${y0} ${w - headW},0 ${w},${h / 2} ${w - headW},${h} ${w - headW},${y0 + shaftH} ${headW},${y0 + shaftH} ${headW},${h}`,
- )
- break
- }
- const headW = Math.min(w * 0.38, h)
- node.setAttribute(
- 'points',
- `0,${y0} ${w - headW},${y0} ${w - headW},0 ${w},${h / 2} ${w - headW},${h} ${w - headW},${y0 + shaftH} 0,${y0 + shaftH}`,
- )
- break
- }
- case 'line': {
- node = document.createElementNS(SVG_NS, 'line')
- const lw = Math.max(sw, 2)
- // inset the endpoints so the tip's point lands on the box edge (tips.ts:
- // the three original kinds keep their 2.6 — every old deck unchanged)
- node.setAttribute('x1', String(tipInsetPx(el.lineStart, lw)))
- node.setAttribute('y1', String(h / 2))
- node.setAttribute('x2', String(w - tipInsetPx(el.lineEnd, lw)))
- node.setAttribute('y2', String(h / 2))
- node.setAttribute('stroke', el.fill)
- node.setAttribute('stroke-width', String(lw))
- const hollow = tipSpec(el.lineStart)?.hollow || tipSpec(el.lineEnd)?.hollow
- node.setAttribute('stroke-linecap', el.strokeStyle === 'dashed' || hollow ? 'butt' : 'round')
- const lineDash = dashArray(el, lw)
- if (lineDash) node.setAttribute('stroke-dasharray', lineDash)
- const mStart = el.lineStart ? markerRef(svg, el.lineStart, el.fill, true) : null
- const mEnd = el.lineEnd ? markerRef(svg, el.lineEnd, el.fill, false) : null
- if (mStart) node.setAttribute('marker-start', mStart)
- if (mEnd) node.setAttribute('marker-end', mEnd)
- svg.appendChild(node)
- return svg
- }
- }
- node.setAttribute('fill', el.fillGradient?.stops.length ? gradientRef(svg, el.fillGradient) : el.fill)
- if (el.stroke && el.stroke !== 'transparent' && sw > 0) {
- node.setAttribute('stroke', el.stroke)
- node.setAttribute('stroke-width', String(sw))
- const dash = dashArray(el, sw)
- if (dash) node.setAttribute('stroke-dasharray', dash)
- if (el.strokeStyle === 'dotted') node.setAttribute('stroke-linecap', 'round')
- }
- svg.appendChild(node)
- return svg
-}
+// The shape renderer moved to the kernel (kernel/src/shape.ts) so bento/spaces
+// diagrams render shapes through one engine. Re-exported here so render.ts stays
+// the import site (present.ts imports gradientLineCoords; renderElement below uses
+// shapeSvg and cssLinearGradient) and the pixels are unchanged.
+import { cssLinearGradient, shapeSvg } from '../../kernel/src/shape.ts'
+export { cssLinearGradient, gradientLineCoords, shapeSvg } from '../../kernel/src/shape.ts'
// --- math ($…$ → MathML) -----------------------------------------------------
diff --git a/slides/src/tips.ts b/slides/src/tips.ts
index 4d6e4c09..f678048e 100644
--- a/slides/src/tips.ts
+++ b/slides/src/tips.ts
@@ -1,162 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
-/**
- * Line tips — the ONE catalogue behind `lineStart`/`lineEnd` (discussion
- * #303): the model's allowed values, the shape gate, the panel's options and
- * the renderer's marker geometry all read this list, so a tip cannot exist in
- * one place and not another.
- *
- * Geometry lives in an 8×8 marker frame, the line arriving from the left and
- * the tip pointing +x. `size` is the marker's width in STROKE units (SVG
- * `markerUnits="strokeWidth"`), `refX` the frame x that sits on the line's
- * end, `tipX` where the point is. A hollow tip needs the line to STOP at the
- * head's back edge — otherwise the stroke shows through the hollow — so the
- * renderer insets the endpoint by `inset` stroke units, which for the new
- * kinds is exactly the distance from the line end to the point. The three
- * original kinds keep their historic numbers (2.6 inset, refX inside the
- * head) so every existing deck renders byte-identically.
- *
- * DEGRADE, stated plainly: in 1.1.0 and older the renderer matches only
- * 'arrow' and 'dot' and draws a BAR for anything else — so a deck carrying
- * one of the seven newer tips shows a bar at that end in those shells, not a
- * plain end. Nothing throws; the deck opens.
- *
- * Also here, because a curved connector needs it (#302): the END TANGENT of
- * a cubic path, so a tip on a curve points along the curve and the endpoint
- * is inset along it, not along the chord.
- */
-
-import { parseBezier, serializeBezier, type BezNode, type Pt } from './editor/bezier'
-
-export type TipKind = 'none' | 'arrow' | 'dot' | 'bar' | 'arrow-open' | 'triangle' | 'triangle-open' | 'diamond' | 'diamond-open' | 'square' | 'circle-open'
-
-export interface TipSpec {
- kind: TipKind
- /** panel label, English key for t() */
- label: string
- /** marker width in stroke units */
- size: number
- refX: number
- tipX: number
- /** 'path' | 'circle' | 'rect' + geometry in the 8×8 frame */
- geom: { tag: 'path'; d: string } | { tag: 'circle'; cx: number; cy: number; r: number } | { tag: 'rect'; x: number; y: number; w: number; h: number }
- /** drawn as an outline in the line's colour, interior left open */
- hollow?: boolean
- /** endpoint inset in stroke units; legacy kinds pin 2.6 */
- inset: number
-}
-
-const geometric = (tipX: number, refX: number, size: number) => Math.round(((tipX - refX) * size / 8) * 100) / 100
-
-export const TIPS: ReadonlyArray<TipSpec> = [
- { kind: 'none', label: 'none', size: 0, refX: 0, tipX: 0, geom: { tag: 'path', d: '' }, inset: 0 },
- // the original three — numbers unchanged since 1.0.2
- { kind: 'arrow', label: 'Arrow', size: 5.5, refX: 6.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0 0.4 L 7.6 4 L 0 7.6 Z' }, inset: 2.6 },
- { kind: 'dot', label: 'Dot', size: 5.5, refX: 4, tipX: 6.6, geom: { tag: 'circle', cx: 4, cy: 4, r: 2.6 }, inset: 2.6 },
- { kind: 'bar', label: 'Bar', size: 5.5, refX: 4, tipX: 4.8, geom: { tag: 'rect', x: 3.2, y: 0.4, w: 1.6, h: 7.2 }, inset: 2.6 },
- // #303
- { kind: 'arrow-open', label: 'Open arrow', size: 5.5, refX: 7.2, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 0.4 L 7.6 4 L 0.4 7.6' }, hollow: true, inset: geometric(7.6, 7.2, 5.5) },
- { kind: 'triangle', label: 'Triangle', size: 7.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 0.4 L 7.6 4 L 0.4 7.6 Z' }, inset: geometric(7.6, 0.4, 7.5) },
- { kind: 'triangle-open', label: 'Hollow triangle', size: 7.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 0.4 L 7.6 4 L 0.4 7.6 Z' }, hollow: true, inset: geometric(7.6, 0.4, 7.5) },
- { kind: 'diamond', label: 'Diamond', size: 6.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 4 L 4 0.8 L 7.6 4 L 4 7.2 Z' }, inset: geometric(7.6, 0.4, 6.5) },
- { kind: 'diamond-open', label: 'Hollow diamond', size: 6.5, refX: 0.4, tipX: 7.6, geom: { tag: 'path', d: 'M 0.4 4 L 4 0.8 L 7.6 4 L 4 7.2 Z' }, hollow: true, inset: geometric(7.6, 0.4, 6.5) },
- { kind: 'square', label: 'Square', size: 5.5, refX: 1.2, tipX: 7.6, geom: { tag: 'rect', x: 1.2, y: 0.8, w: 6.4, h: 6.4 }, inset: geometric(7.6, 1.2, 5.5) },
- { kind: 'circle-open', label: 'Hollow circle', size: 5.5, refX: 0.8, tipX: 7.2, geom: { tag: 'circle', cx: 4, cy: 4, r: 3.2 }, hollow: true, inset: geometric(7.2, 0.8, 5.5) },
-]
-
-export const TIP_KINDS: ReadonlyArray<TipKind> = TIPS.map((t) => t.kind)
-
-export const tipSpec = (kind: string | undefined): TipSpec | undefined =>
- kind && kind !== 'none' ? TIPS.find((t) => t.kind === kind) : undefined
-
-/** Endpoint inset for a tip, in px, given the drawn stroke width. */
-export const tipInsetPx = (kind: string | undefined, strokePx: number): number => (tipSpec(kind)?.inset ?? 0) * strokePx
-
-/** Unit tangent at a path's start or end: from the end node's own handle,
- * else the neighbour's handle, else the chord — so a degenerate (zero
- * length) handle never yields a zero vector. `null` for fewer than 2 nodes. */
-export function endTangent(nodes: ReadonlyArray<BezNode>, atEnd: boolean): Pt | null {
- if (nodes.length < 2) return null
- const a = atEnd ? nodes[nodes.length - 2] : nodes[1]
- const b = atEnd ? nodes[nodes.length - 1] : nodes[0]
- // direction pointing OUT of the path at that end
- const candidates: Array<[Pt, Pt]> = atEnd
- ? [[b.in ?? b.p, b.p], [a.out ?? a.p, b.p], [a.p, b.p]]
- : [[b.out ?? b.p, b.p], [a.in ?? a.p, b.p], [a.p, b.p]]
- for (const [from, to] of candidates) {
- const dx = to.x - from.x
- const dy = to.y - from.y
- const len = Math.hypot(dx, dy)
- if (len > 1e-6) return { x: dx / len, y: dy / len }
- }
- return null
-}
-
-/** The path `d` with each tipped end pulled back along its tangent by the
- * given amounts (path units), so a marker's point lands where the model's
- * endpoint is and a hollow head has no stroke inside it. Interior nodes are
- * untouched; the end node's handle moves with it so the curve keeps its
- * arrival direction. */
-export function shortenPathEnds(d: string, startBy: number, endBy: number): string {
- if (!(startBy > 0) && !(endBy > 0)) return d
- const { nodes, closed } = parseBezier(d)
- if (closed || nodes.length < 2) return d
- const pull = (i: number, by: number, atEnd: boolean) => {
- const t = endTangent(nodes, atEnd)
- if (!t || !(by > 0)) return
- const n = nodes[i]
- const dx = -t.x * by
- const dy = -t.y * by
- const h = atEnd ? n.in : n.out
- nodes[i] = { ...n, p: { x: n.p.x + dx, y: n.p.y + dy }, ...(h ? (atEnd ? { in: { x: h.x + dx, y: h.y + dy } } : { out: { x: h.x + dx, y: h.y + dy } }) : {}) }
- }
- pull(0, startBy, false)
- pull(nodes.length - 1, endBy, true)
- return serializeBezier(nodes, false)
-}
-
-/**
- * Move a path's first and/or last on-curve point (path units) for connector
- * re-routing (#302). The moved node's handle is recomputed the auto way —
- * one sixth of the way toward its neighbour, the Catmull-Rom end rule the
- * curve editor uses for untouched nodes — so the curve leaves the new anchor
- * smoothly; the neighbour's facing handle is recomputed only if it was auto
- * itself (matched the rule before the move), so a hand-shaped interior point
- * keeps its tangents. Every other node is returned byte-identical.
- */
-export function movePathEnds(d: string, start: Pt | null, end: Pt | null): string {
- const { nodes, closed } = parseBezier(d)
- if (closed || nodes.length < 2 || (!start && !end)) return d
- const sixth = (from: Pt, to: Pt): Pt => ({ x: from.x + (to.x - from.x) / 6, y: from.y + (to.y - from.y) / 6 })
- const near = (a: Pt | undefined, b: Pt) => !!a && Math.abs(a.x - b.x) < 0.02 && Math.abs(a.y - b.y) < 0.02
- const catmullIn = (i: number): Pt => {
- // Catmull-Rom incoming handle at node i (P(i) - (P(i+1) - P(i-1)) / 6)
- const P = (k: number) => nodes[Math.max(0, Math.min(nodes.length - 1, k))].p
- return { x: P(i).x - (P(i + 1).x - P(i - 1).x) / 6, y: P(i).y - (P(i + 1).y - P(i - 1).y) / 6 }
- }
- const catmullOut = (i: number): Pt => {
- const P = (k: number) => nodes[Math.max(0, Math.min(nodes.length - 1, k))].p
- return { x: P(i).x + (P(i + 1).x - P(i - 1).x) / 6, y: P(i).y + (P(i + 1).y - P(i - 1).y) / 6 }
- }
- if (start) {
- const nb = nodes[1]
- const nbWasAuto = near(nb.in, catmullIn(1))
- nodes[0] = { p: start, out: sixth(start, nb.p) }
- if (nbWasAuto) nodes[1] = { ...nb, in: catmullIn(1) }
- }
- if (end) {
- const last = nodes.length - 1
- const nb = nodes[last - 1]
- const nbWasAuto = near(nb.out, catmullOut(last - 1))
- nodes[last] = { p: end, in: sixth(end, nb.p) }
- if (nbWasAuto) nodes[last - 1] = { ...nb, out: catmullOut(last - 1) }
- }
- return serializeBezier(nodes, false)
-}
-
-/** First and last on-curve points of a path (path units). */
-export function pathEnds(d: string): [Pt, Pt] | null {
- const { nodes } = parseBezier(d)
- if (nodes.length < 2) return null
- return [nodes[0].p, nodes[nodes.length - 1].p]
-}
+// The line-tip catalogue moved to the kernel (kernel/src/tips.ts) with the
+// diagram-engine lift so bento/spaces diagram connectors share it. Re-exported
+// here so every existing `./tips` / `../tips` import — and the rendered tips —
+// are unchanged.
+export * from '../../kernel/src/tips.ts'