Files
Endoleap/src/lib/canvas-curves.ts
T

30 lines
2.5 KiB
TypeScript

import {bezierChainSegments} from './canvas-core/geometry.ts';
import type { XYPosition } from "@xyflow/react";
import type { Connector } from "./canvas-geometry";
import type { EdgeData } from "./canvas-v2";
export type Cubic = [XYPosition, XYPosition, XYPosition, XYPosition];
export const plus = (a: XYPosition, b: XYPosition) => ({ x: a.x + b.x, y: a.y + b.y });
export const minus = (a: XYPosition, b: XYPosition) => ({ x: a.x - b.x, y: a.y - b.y });
const lerp = (a: XYPosition, b: XYPosition, t: number) => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });
export function curveSegments(from:Connector,to:Connector,path?:EdgeData["path"]):Cubic[]{return bezierChainSegments(from,to,path) as Cubic[];}
export function cubicPoint([a, b, c, d]: Cubic, t: number) { const ab = lerp(a, b, t), bc = lerp(b, c, t), cd = lerp(c, d, t); return lerp(lerp(ab, bc, t), lerp(bc, cd, t), t); }
export function curvePath(segments: Cubic[]) { return `M ${segments[0][0].x},${segments[0][0].y} ` + segments.map(([, b, c, d]) => `C ${b.x},${b.y} ${c.x},${c.y} ${d.x},${d.y}`).join(" "); }
/** Split the closest segment without altering its shape. */
export function insertCurveKnot(from: Connector, to: Connector, path: EdgeData["path"], point?: XYPosition) {
const segments = curveSegments(from, to, path);
let selected = Math.floor(segments.length / 2), t = .5, distance = Infinity;
if (point) segments.forEach((segment, index) => { for (let step = 1; step < 40; step++) {
const p = cubicPoint(segment, step / 40), d = Math.hypot(p.x - point.x, p.y - point.y);
if (d < distance) { distance = d; selected = index; t = step / 40; }
} });
const [a, b, c, d] = segments[selected];
const ab = lerp(a, b, t), bc = lerp(b, c, t), cd = lerp(c, d, t), abc = lerp(ab, bc, t), bcd = lerp(bc, cd, t), anchor = lerp(abc, bcd, t);
const next = structuredClone(path || { type: "bezier-chain" as const, knots: [] });
const knot = { id: crypto.randomUUID(), position: anchor, in: minus(abc, anchor), out: minus(bcd, anchor), mode: "smooth" as const };
if (selected) next.knots[selected - 1].out = minus(ab, a); else next.startControl = minus(ab, a);
if (selected < next.knots.length) next.knots[selected].in = minus(cd, d); else next.endControl = minus(cd, d);
// Splitting one side of an existing symmetric knot can make its handle lengths differ.
for (const index of [selected - 1, selected]) if (next.knots[index]?.mode === "symmetric") next.knots[index].mode = "smooth";
next.knots.splice(selected, 0, knot); return { path: next, knot };
}