@mmon-co/ncept-bb 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ ADOPT_SESSION,
7
+ BEGIN_SESSION,
8
+ OPEN_SESSION,
9
+ type AdoptSession,
10
+ type BeginSession,
11
+ type OpenSession,
12
+ } from "@mmon-co/ncept-pi/events";
13
+ import { entrySchema } from "./entries";
14
+
15
+ function isHandoff(value: unknown): value is OpenSession {
16
+ return (
17
+ !!value &&
18
+ typeof value === "object" &&
19
+ "session" in value &&
20
+ typeof value.session === "string" &&
21
+ "mode" in value &&
22
+ typeof value.mode === "string" &&
23
+ "aside" in value &&
24
+ typeof value.aside === "boolean" &&
25
+ "claim" in value &&
26
+ typeof value.claim === "function"
27
+ );
28
+ }
29
+
30
+ export default function nceptBb(pi: ExtensionAPI) {
31
+ if (!process.env.BB_THREAD_ID) return;
32
+
33
+ async function command(args: string[]) {
34
+ const result = await pi.exec(process.env.BB_CLI || "bb", ["concept", ...args]);
35
+ if (result.code !== 0) throw new Error(result.stderr || result.stdout || "bb concept failed");
36
+ return JSON.parse(result.stdout);
37
+ }
38
+
39
+ pi.registerCommand("ncept-kickoff", {
40
+ description: "Begin a tutor-led Session from host context",
41
+ handler: async (instruction) => {
42
+ pi.sendMessage(
43
+ {
44
+ customType: "ncept.opening",
45
+ content: "Tutor-led Session opening (host context, not learner speech). " + instruction,
46
+ display: false,
47
+ },
48
+ { triggerTurn: true },
49
+ );
50
+ },
51
+ });
52
+
53
+ let refusal: string | undefined;
54
+ let associated: string | undefined;
55
+ async function associate(ctx: ExtensionContext) {
56
+ const entry = ctx.sessionManager
57
+ .getBranch()
58
+ .findLast((item) => item.type === "custom" && item.customType === "ncept.session");
59
+ const data = entry?.type === "custom" ? entry.data : undefined;
60
+ const session =
61
+ data && typeof data === "object" && "id" in data && typeof data.id === "string" ? data.id : undefined;
62
+ if (!session || session === associated) return;
63
+ await command(["associate", "--session", session]);
64
+ associated = session;
65
+ }
66
+
67
+ // session_start errors are reported by pi but do not stop the first prompt.
68
+ // Consume input before ncept-pi can prepare an ordinary empty Session instead.
69
+ pi.on("input", (_event, ctx) => {
70
+ if (!refusal) return;
71
+ // bb reports an exited pi process, including stderr, as a failed turn.
72
+ // A handled prompt alone leaves its bridge waiting for agent_end.
73
+ console.error(refusal);
74
+ ctx.shutdown();
75
+ return { action: "handled" };
76
+ });
77
+
78
+ pi.on("before_agent_start", async (_event, ctx) => {
79
+ await associate(ctx);
80
+ });
81
+ pi.on("session_start", async (_event, ctx) => {
82
+ const rejected = ctx.sessionManager
83
+ .getBranch()
84
+ .findLast((entry) => entry.type === "custom" && entry.customType === "ncept.entry-refused");
85
+ refusal = rejected?.type === "custom" && typeof rejected.data === "string" ? rejected.data : undefined;
86
+ if (refusal) return;
87
+ const stored = ctx.sessionManager
88
+ .getBranch()
89
+ .some((entry) => entry.type === "custom" && entry.customType === "ncept.session");
90
+ if (!stored && process.env.NCEPT_BB_ENTRY) {
91
+ try {
92
+ const intent = entrySchema.parse(JSON.parse(process.env.NCEPT_BB_ENTRY));
93
+ let begin: (() => ReturnType<Parameters<BeginSession["claim"]>[0]>) | undefined;
94
+ pi.events.emit(BEGIN_SESSION, {
95
+ intent,
96
+ claim: (open) => {
97
+ begin = open;
98
+ },
99
+ } satisfies BeginSession);
100
+ if (!begin) throw new Error("The tutoring extension did not accept the Session entry");
101
+ await begin();
102
+ } catch (error) {
103
+ refusal = "Could not start this learning Session: " + (error instanceof Error ? error.message : String(error));
104
+ pi.appendEntry("ncept.entry-refused", refusal);
105
+ return;
106
+ }
107
+ await associate(ctx);
108
+ return;
109
+ }
110
+ const session = process.env.NCEPT_BB_SESSION;
111
+ // A restarted pi process must keep the existing conversation and carry.
112
+ if (!session || stored) {
113
+ await associate(ctx);
114
+ return;
115
+ }
116
+ const carry = process.env.NCEPT_BB_CARRY_REF
117
+ ? (await command(["carry", "--thread", process.env.NCEPT_BB_CARRY_REF])).carry
118
+ : process.env.NCEPT_BB_CARRY;
119
+ pi.events.emit(ADOPT_SESSION, { session, ...(carry ? { carry } : {}) } satisfies AdoptSession);
120
+ await associate(ctx);
121
+ });
122
+
123
+ pi.events.on(OPEN_SESSION, (data) => {
124
+ if (!isHandoff(data)) return;
125
+ const handoff = data;
126
+ handoff.claim(async () => {
127
+ const directory = await mkdtemp(join(tmpdir(), "ncept-bb-"));
128
+ try {
129
+ const path = join(directory, "handoff.json");
130
+ await writeFile(
131
+ path,
132
+ JSON.stringify({
133
+ session: handoff.session,
134
+ mode: handoff.mode,
135
+ kickoff: handoff.kickoff,
136
+ learnerKickoff: handoff.learnerKickoff,
137
+ carry: handoff.carry,
138
+ aside: handoff.aside,
139
+ }),
140
+ { mode: 0o600 },
141
+ );
142
+ const result = await command(["spawn", "--request-file", path]);
143
+ return "Continue in @thread:" + result.threadId;
144
+ } finally {
145
+ await rm(directory, { recursive: true, force: true });
146
+ }
147
+ });
148
+ });
149
+ }
@@ -0,0 +1,302 @@
1
+ import { graphlib, layout } from "@dagrejs/dagre";
2
+ import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY } from "d3-force";
3
+
4
+ export type Position = { readonly id: string; readonly x: number; readonly y: number };
5
+
6
+ /** Settled D3-force positions over the whole universe: stable across Queries. */
7
+ export function settleGraph(universe: {
8
+ /** `label` is read only when `labelsBeside`. */
9
+ readonly nodes: readonly { readonly id: string; readonly label?: string }[];
10
+ readonly edges: readonly { readonly from: string; readonly to: string }[];
11
+ readonly direction?: "up";
12
+ /** Names sit to the right of the marks (the skill tree), so the free layout keeps each Node's name clear of the
13
+ * others' marks and names, not just its mark. */
14
+ readonly labelsBeside?: boolean;
15
+ /** Free (force) unless drawn as the spine's tree, layered or radial. */
16
+ readonly arrangement?: "layered" | "radial";
17
+ }): readonly Position[] {
18
+ if (universe.arrangement === "layered") return layeredTree(universe);
19
+ if (universe.arrangement === "radial") return radialTree(universe);
20
+ const up = universe.direction === "up";
21
+ // Upward landscapes use input order for horizontal lanes. Co-located seeds
22
+ // and a shared x target let collision jitter choose each branch’s side.
23
+ const particles = universe.nodes.map((node, index) => ({
24
+ id: node.id,
25
+ x: up ? (index - (universe.nodes.length - 1) / 2) * 80 : 0,
26
+ y: 0,
27
+ }));
28
+ const lanes = new Map(particles.map((node) => [node.id, node.x]));
29
+ // Mission progression places each Node above every prerequisite reachable from a root
30
+ // (longest path, bounded by one pass per Node); cycles without a root stay a settled cluster.
31
+ const levels = new Map<string, number>();
32
+ if (up) {
33
+ const targets = new Set(universe.edges.map((edge) => edge.to));
34
+ for (const node of universe.nodes) if (!targets.has(node.id)) levels.set(node.id, 0);
35
+ for (let pass = 0; pass < universe.nodes.length; pass++)
36
+ for (const edge of universe.edges) {
37
+ const from = levels.get(edge.from);
38
+ if (from !== undefined && from + 1 > (levels.get(edge.to) ?? -1)) levels.set(edge.to, from + 1);
39
+ }
40
+ }
41
+ forceSimulation(particles)
42
+ .force(
43
+ "links",
44
+ forceLink<(typeof particles)[number], { source: string; target: string }>(
45
+ universe.edges.map(({ from, to }) => ({ source: from, target: to })),
46
+ )
47
+ .id((node) => node.id)
48
+ .distance(up ? 200 : 142)
49
+ .strength(up ? 0.3 : 0.45),
50
+ )
51
+ // Upward levels spread sideways so labels beside the marks keep a landscape, not a column.
52
+ // The upward constants were fitted to the drawn Mission graphs (docs/design/pages/mission.html and
53
+ // mission-phone.html): the Mission's own path climbs the middle, other Missions' branches to either side.
54
+ .force("charge", forceManyBody().strength(up ? -200 : -210))
55
+ // The default document labels hang below marks; Mission labels sit beside them.
56
+ .force(
57
+ "collision",
58
+ universe.labelsBeside
59
+ ? rectangleCollision(universe.nodes.map((node) => nameBox(node.label ?? "")))
60
+ : forceCollide(up ? 80 : 100).iterations(3),
61
+ )
62
+ .force(
63
+ "x",
64
+ up
65
+ ? forceX<(typeof particles)[number]>((node) => lanes.get(node.id) ?? 0).strength(0.5)
66
+ : forceX().strength(0.045),
67
+ )
68
+ .force(
69
+ "y",
70
+ up
71
+ ? forceY<(typeof particles)[number]>((node) => -(levels.get(node.id) ?? 0) * 50).strength(0.3)
72
+ : forceY().strength(0.055),
73
+ )
74
+ .stop()
75
+ .tick(300);
76
+ if (universe.labelsBeside) {
77
+ const bodies = bodiesOf(
78
+ particles,
79
+ universe.nodes.map((node) => nameBox(node.label ?? "")),
80
+ );
81
+ // The simulation's forces can still leave overlaps; sweeps of the same push end only when none remain.
82
+ for (let sweep = 0; sweep < 200 && separate(bodies, 1); sweep++);
83
+ }
84
+ return particles;
85
+ }
86
+
87
+ /** What a Node needs clear in the skill tree, as the distance to the next Node's mark: its mark (44px with its
88
+ * ring), its name 52px to the right (Courier 20px/1.2 wrapped at 200px, as styled in hub.css), and a gap. */
89
+ type Box = { readonly width: number; readonly height: number };
90
+ const NAME_ADVANCE = 12;
91
+ const NAME_LINE = 24;
92
+ const NAME_MAX = 200;
93
+ const NAME_GAP = { x: 20, y: 14 };
94
+
95
+ function nameBox(label: string): Box {
96
+ const advance = (word: string) => {
97
+ let sum = 0;
98
+ for (const char of word) sum += (char.codePointAt(0) ?? 0) >= 0x2e80 ? 2 * NAME_ADVANCE : NAME_ADVANCE;
99
+ return sum;
100
+ };
101
+ let lines = 1;
102
+ let line = 0;
103
+ let widest = 0;
104
+ for (const word of label.split(/\s+/).filter(Boolean)) {
105
+ const width = advance(word);
106
+ if (line && line + NAME_ADVANCE + width > NAME_MAX) {
107
+ lines++;
108
+ line = 0;
109
+ }
110
+ line += (line ? NAME_ADVANCE : 0) + width;
111
+ // A word wider than the name's column breaks across lines.
112
+ while (line > NAME_MAX) {
113
+ lines++;
114
+ widest = NAME_MAX;
115
+ line -= NAME_MAX;
116
+ }
117
+ widest = Math.max(widest, line);
118
+ }
119
+ // A wrapped name fills its column.
120
+ return {
121
+ width: 62 + (lines > 1 ? NAME_MAX : widest) + NAME_GAP.x,
122
+ height: Math.max(48, lines * NAME_LINE + 6) + NAME_GAP.y,
123
+ };
124
+ }
125
+
126
+ /** A Node's settling point and the box it keeps clear, reaching right and down from the point. */
127
+ type Body = { readonly point: { x: number; y: number }; readonly box: Box };
128
+ const bodiesOf = (points: readonly { x: number; y: number }[], boxes: readonly Box[]): Body[] =>
129
+ points.map((point, index) => ({ point, box: boxes[index] ?? { width: 0, height: 0 } }));
130
+
131
+ /** Pushes overlapping boxes apart along the axis of least overlap; returns whether any overlapped. */
132
+ function separate(bodies: readonly Body[], share: number): boolean {
133
+ let moved = false;
134
+ bodies.forEach((one, index) => {
135
+ for (const other of bodies.slice(index + 1)) {
136
+ const [a, b] = [one.point, other.point];
137
+ const overlapX = (a.x <= b.x ? one : other).box.width - Math.abs(a.x - b.x);
138
+ const overlapY = (a.y <= b.y ? one : other).box.height - Math.abs(a.y - b.y);
139
+ if (overlapX <= 0 || overlapY <= 0) continue;
140
+ moved = true;
141
+ const axis = overlapY <= overlapX ? "y" : "x";
142
+ const push = ((axis === "y" ? overlapY : overlapX) / 2) * share + 0.5;
143
+ const sign = a[axis] <= b[axis] ? 1 : -1;
144
+ a[axis] -= sign * push;
145
+ b[axis] += sign * push;
146
+ }
147
+ });
148
+ return moved;
149
+ }
150
+
151
+ /** A d3-force body per Node shaped like its mark and name, so the name keeps clear of the marks to its right. */
152
+ function rectangleCollision(boxes: readonly Box[]) {
153
+ let bodies: Body[] = [];
154
+ const force = () => {
155
+ separate(bodies, 0.5);
156
+ };
157
+ force.initialize = (nodes: { x: number; y: number }[]) => {
158
+ bodies = bodiesOf(nodes, boxes);
159
+ };
160
+ return force;
161
+ }
162
+
163
+ type Universe = Parameters<typeof settleGraph>[0];
164
+
165
+ /** The spine as Dagre's layered tree, prerequisites first, left to right. Labels hang beside the marks, so ranks sit
166
+ * wide apart and Nodes in a rank close together. */
167
+ function layeredTree(universe: Universe): readonly Position[] {
168
+ const primary = spine(universe);
169
+ const graph = new graphlib.Graph();
170
+ graph.setGraph({ rankdir: "LR", nodesep: 46, ranksep: 190 });
171
+ graph.setDefaultEdgeLabel(() => ({}));
172
+ for (const node of universe.nodes) graph.setNode(node.id, { width: 42, height: 42 });
173
+ for (const edge of universe.edges) if (primary.get(edge.to) === edge.from) graph.setEdge(edge.from, edge.to);
174
+ layout(graph);
175
+ return universe.nodes.map((node) => {
176
+ const { x, y } = graph.node(node.id);
177
+ return { id: node.id, x, y };
178
+ });
179
+ }
180
+
181
+ /** The progression spine: each Node's primary prerequisite, the one deepest along the longest path from the
182
+ * foundations. At most one per Node, so the spine is a forest rooted at the foundations; every other Edge is a
183
+ * cross-link. */
184
+ export function spine(universe: Pick<Universe, "nodes" | "edges">): ReadonlyMap<string, string> {
185
+ const into = new Map<string, string[]>();
186
+ for (const edge of universe.edges) into.set(edge.to, [...(into.get(edge.to) ?? []), edge.from]);
187
+ const depth = new Map<string, number>();
188
+ const deep = (id: string, seen: ReadonlySet<string> = new Set()): number => {
189
+ const known = depth.get(id);
190
+ if (known !== undefined) return known;
191
+ if (seen.has(id)) return 0;
192
+ const next = new Set([...seen, id]);
193
+ const value = Math.max(-1, ...(into.get(id) ?? []).map((from) => deep(from, next))) + 1;
194
+ depth.set(id, value);
195
+ return value;
196
+ };
197
+ const primary = new Map<string, string>();
198
+ for (const node of universe.nodes) {
199
+ const parents = into.get(node.id) ?? [];
200
+ const best = parents.reduce<string | undefined>(
201
+ (chosen, from) => (chosen === undefined || deep(from) > deep(chosen) ? from : chosen),
202
+ undefined,
203
+ );
204
+ if (best !== undefined && deep(best) < deep(node.id)) primary.set(node.id, best);
205
+ }
206
+ return primary;
207
+ }
208
+
209
+ /** What a Node needs clear in the Map: its mark and its name beside it, two lines at most. */
210
+ const LABEL_WIDTH = 212;
211
+ const LABEL_HEIGHT = 46;
212
+
213
+ /** The spine as a radial tree: the foundations round the centre, each Node a ring further out than its primary
214
+ * prerequisite, each subtree a wedge as wide as its leaves, so separate Missions become separate sectors. */
215
+ function radialTree(universe: Universe): readonly Position[] {
216
+ const primary = spine(universe);
217
+ const children = new Map<string, string[]>();
218
+ for (const node of universe.nodes) {
219
+ const parent = primary.get(node.id);
220
+ if (parent !== undefined) children.set(parent, [...(children.get(parent) ?? []), node.id]);
221
+ }
222
+ const leaves = new Map<string, number>();
223
+ const count = (id: string): number => {
224
+ const value = (children.get(id) ?? []).reduce((sum, child) => sum + count(child), 0) || 1;
225
+ leaves.set(id, value);
226
+ return value;
227
+ };
228
+ // Foundations of one connected graph sit side by side, so each unrelated Mission or Patch takes one sector, with
229
+ // a leaf's width of empty sector between them.
230
+ const group = new Map(universe.nodes.map((node) => [node.id, node.id]));
231
+ const find = (id: string): string => {
232
+ const parent = group.get(id) ?? id;
233
+ return parent === id ? id : find(parent);
234
+ };
235
+ for (const edge of universe.edges) group.set(find(edge.from), find(edge.to));
236
+ const order = new Map(universe.nodes.map((node, index) => [node.id, index]));
237
+ const componentOrder = new Map<string, number>();
238
+ for (const node of universe.nodes)
239
+ if (!componentOrder.has(find(node.id))) componentOrder.set(find(node.id), componentOrder.size);
240
+ const roots = universe.nodes
241
+ .filter((node) => !primary.has(node.id))
242
+ .map((node) => node.id)
243
+ .sort(
244
+ (a, b) =>
245
+ (componentOrder.get(find(a)) ?? 0) - (componentOrder.get(find(b)) ?? 0) ||
246
+ (order.get(a) ?? 0) - (order.get(b) ?? 0),
247
+ );
248
+ const components = componentOrder.size;
249
+ const total = roots.reduce((sum, root) => sum + count(root), 0) + (components > 1 ? components : 0);
250
+ const depthOf = (id: string): number =>
251
+ (children.get(id) ?? []).reduce((most, child) => Math.max(most, 1 + depthOf(child)), 0);
252
+ const deepest = Math.max(0, ...roots.map(depthOf));
253
+ const single = roots.length === 1;
254
+ // Rings sit further apart than a mark and its name are wide, so no name reaches the next ring however the two
255
+ // angles line up; and wide enough that the outermost leaves and the innermost foundations each sit a name apart.
256
+ const ring = Math.max(
257
+ LABEL_WIDTH + 30,
258
+ (total * 110) / (2 * Math.PI * (deepest + (single ? 0 : 1))),
259
+ (roots.length * 130) / (2 * Math.PI),
260
+ );
261
+ const polar: { id: string; angle: number; radius: number }[] = [];
262
+ const place = (id: string, from: number, to: number, depth: number) => {
263
+ polar.push({ id, angle: (from + to) / 2, radius: (depth + (single ? 0 : 1)) * ring });
264
+ let start = from;
265
+ for (const child of children.get(id) ?? []) {
266
+ const end = start + ((to - from) * (leaves.get(child) ?? 1)) / (leaves.get(id) ?? 1);
267
+ place(child, start, end, depth + 1);
268
+ start = end;
269
+ }
270
+ };
271
+ let start = 0;
272
+ roots.forEach((root, index) => {
273
+ const previous = index ? roots.at(index - 1) : undefined;
274
+ if (components > 1 && previous !== undefined && find(previous) !== find(root)) start += (2 * Math.PI) / total;
275
+ const end = start + (2 * Math.PI * (leaves.get(root) ?? 1)) / total;
276
+ place(root, start, end, 0);
277
+ start = end;
278
+ });
279
+ // A foundation whose dependents all chose other primary prerequisites is a one-Node tree with a thin wedge: on
280
+ // each ring, push crowded neighbours on round the circle until their names clear each other.
281
+ const at = (radius: number, angle: number) => ({
282
+ x: radius * Math.cos(angle - Math.PI / 2),
283
+ y: radius * Math.sin(angle - Math.PI / 2),
284
+ });
285
+ for (const radius of new Set(polar.map((point) => point.radius))) {
286
+ if (!radius) continue;
287
+ const onRing = polar.filter((point) => point.radius === radius).sort((a, b) => a.angle - b.angle);
288
+ // A second sweep lets the first neighbour clear the last one round the circle.
289
+ for (let sweep = 0; sweep < 2 && onRing.length > 1; sweep++)
290
+ onRing.forEach((point, index) => {
291
+ const previous = onRing.at(index - 1);
292
+ if (!previous || (sweep === 0 && index === 0)) return;
293
+ const before = at(radius, previous.angle - (index ? 0 : 2 * Math.PI));
294
+ for (let step = 0; step < 400; step++) {
295
+ const here = at(radius, point.angle);
296
+ if (Math.abs(here.x - before.x) >= LABEL_WIDTH || Math.abs(here.y - before.y) >= LABEL_HEIGHT) break;
297
+ point.angle += 4 / radius;
298
+ }
299
+ });
300
+ }
301
+ return polar.map(({ id, angle, radius }) => ({ id, ...at(radius, angle) }));
302
+ }
package/src/graph.ts ADDED
@@ -0,0 +1,57 @@
1
+ type Point = { x: number; y: number };
2
+
3
+ /** Every graph's Edge, the one recipe both the app's React Flow Edge and drawings outside it (the Hub's share
4
+ * previews) draw: a slight bow between mark centers (a quadratic whose control sits off the midpoint, left of travel,
5
+ * by 12% of the length up to 24px, so Edges sharing a mark fan apart), clipped to the marks' rims, tapering from a
6
+ * hairline at the source into the target like a comet trail. Undefined when the marks coincide. */
7
+ export function edgeCurve(from: Point, to: Point, radius: number) {
8
+ const dx = to.x - from.x;
9
+ const dy = to.y - from.y;
10
+ const distance = Math.hypot(dx, dy);
11
+ if (!distance) return undefined;
12
+ const bend = Math.min(24, distance * 0.12);
13
+ const control = { x: (from.x + to.x) / 2 - (dy / distance) * bend, y: (from.y + to.y) / 2 + (dx / distance) * bend };
14
+ const at = (t: number): Point => ({
15
+ x: (1 - t) ** 2 * from.x + 2 * (1 - t) * t * control.x + t ** 2 * to.x,
16
+ y: (1 - t) ** 2 * from.y + 2 * (1 - t) * t * control.y + t ** 2 * to.y,
17
+ });
18
+ const start = Math.min(0.45, radius / distance);
19
+ return {
20
+ control,
21
+ at,
22
+ /** Where the trail leaves the source's rim and meets the target's, along the curve. */
23
+ start,
24
+ end: 1 - start,
25
+ /** The trail's width at \`share\` of the way from source rim to target rim: 1 to 6.5. */
26
+ width: (share: number) => 1 + 5.5 * share,
27
+ };
28
+ }
29
+
30
+ /** How many times its drawn width a trail holds on screen when its graph is shown at \`zoom\`: zoomed out to fit a
31
+ * large graph, up to 2.5×, so the taper still reads as a tree's limbs. */
32
+ export function edgeHold(zoom: number): number {
33
+ return Math.min(2.5, Math.max(1, 1 / zoom));
34
+ }
35
+
36
+ /** The Edge's trail as one filled outline, for drawings that can't stroke segment by segment. \`scale\` thins it (a
37
+ * cross-link off the spine draws at 0.8). Empty when the marks coincide or overlap. */
38
+ export function taperPath(from: Point, to: Point, radius: number, scale = 1): string {
39
+ const curve = edgeCurve(from, to, radius);
40
+ if (!curve || Math.hypot(to.x - from.x, to.y - from.y) <= 2 * radius) return "";
41
+ const steps = 16;
42
+ const left: string[] = [];
43
+ const right: string[] = [];
44
+ const f = (x: number) => x.toFixed(2);
45
+ for (let i = 0; i <= steps; i++) {
46
+ const t = curve.start + ((curve.end - curve.start) * i) / steps;
47
+ const p = curve.at(t);
48
+ // The quadratic's tangent, for the normal the outline steps out along.
49
+ const tx = 2 * (1 - t) * (curve.control.x - from.x) + 2 * t * (to.x - curve.control.x);
50
+ const ty = 2 * (1 - t) * (curve.control.y - from.y) + 2 * t * (to.y - curve.control.y);
51
+ const length = Math.hypot(tx, ty) || 1;
52
+ const half = (curve.width(i / steps) * scale) / 2;
53
+ left.push(f(p.x - (ty / length) * half) + "," + f(p.y + (tx / length) * half));
54
+ right.push(f(p.x + (ty / length) * half) + "," + f(p.y - (tx / length) * half));
55
+ }
56
+ return "M" + left.join(" L") + " L" + right.reverse().join(" L") + " Z";
57
+ }